code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
var $M = require("@effectful/debugger"),
$x = $M.context,
$ret = $M.ret,
$unhandled = $M.unhandled,
$brk = $M.brk,
$lset = $M.lset,
$mcall = $M.mcall,
$m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", {
__webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__
}, null),
$s$1 = [{
e: [1, "1:9-1:10"]
}, null, 0],
$s$2 = [{}, $s$1, 1],
$m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 2, "1:0-4:0", 32, function ($, $l, $p) {
for (;;) switch ($.state = $.goto) {
case 0:
$lset($l, 1, $m$1($));
$.goto = 2;
continue;
case 1:
$.goto = 2;
return $unhandled($.error);
case 2:
return $ret($.result);
default:
throw new Error("Invalid state");
}
}, null, null, 0, [[0, "1:0-3:1", $s$1], [16, "4:0-4:0", $s$1], [16, "4:0-4:0", $s$1]]),
$m$1 = $M.fun("m$1", "e", null, $m$0, [], 0, 2, "1:0-3:1", 0, function ($, $l, $p) {
for (;;) switch ($.state = $.goto) {
case 0:
$.goto = 1;
$brk();
$.state = 1;
case 1:
$.goto = 2;
$p = ($x.call = eff)(1);
$.state = 2;
case 2:
$l[1] = $p;
$.goto = 3;
$p = ($x.call = eff)(2);
$.state = 3;
case 3:
$.goto = 4;
$mcall("log", console, $l[1] + $p);
$.state = 4;
case 4:
$.goto = 6;
$brk();
continue;
case 5:
$.goto = 6;
return $unhandled($.error);
case 6:
return $ret($.result);
default:
throw new Error("Invalid state");
}
}, null, null, 1, [[4, "2:2-2:31", $s$2], [2, "2:14-2:20", $s$2], [2, "2:23-2:29", $s$2], [2, "2:2-2:30", $s$2], [36, "3:1-3:1", $s$2], [16, "3:1-3:1", $s$2], [16, "3:1-3:1", $s$2]]);
$M.moduleExports(); | awto/effectfuljs | packages/core/test/samples/simple/expr/test04-out-ds.js | JavaScript | mit | 1,801 |
'use strict';
module.exports = require('./is-implemented')() ?
Array.prototype.concat : require('./shim');
| runningfun/angular_project | node_modules/bower/node_modules/inquirer/node_modules/cli-color/node_modules/es5-ext/array/#/concat/index.js | JavaScript | mit | 112 |
import React from "react";
import { Link } from "@curi/react-dom";
import {
TitledPlainSection,
HashSection,
Paragraph,
CodeBlock,
Note,
IJS
} from "../../components/guide/common";
let meta = {
title: "Apollo Integration"
};
let setupMeta = {
title: "Setup",
hash: "setup"
};
let looseMeta = {
title: "Loose Pairing",
hash: "loose-pairing"
};
let prefetchMeta = {
title: "Prefetching",
hash: "prefetch"
};
let tightMeta = {
title: "Tight Pairing",
hash: "tight-pairing",
children: [prefetchMeta]
};
let contents = [setupMeta, looseMeta, tightMeta];
function ApolloGuide() {
return (
<React.Fragment>
<TitledPlainSection title={meta.title}>
<Paragraph>
<a href="https://apollographql.com">Apollo</a> is a great solution for
managing an application's data using{" "}
<a href="http://graphql.org">GraphQL</a>.
</Paragraph>
<Paragraph>
There are a few different implementation strategies for integrating
Apollo and Curi based on how tightly you want them to be paired.
</Paragraph>
<Note>
<Paragraph>
This guide only covers integration between Curi and Apollo. If you
are not already familiar with how to use Apollo, you will want to
learn that first.
</Paragraph>
<Paragraph>
Also, this guide will only be referencing Apollo's React
implementation, but the principles are the same no matter how you
render your application.
</Paragraph>
</Note>
</TitledPlainSection>
<HashSection meta={setupMeta} tag="h2">
<Paragraph>
Apollo's React package provides an <IJS>ApolloProvider</IJS> component
for accessing your Apollo client throughout the application. The{" "}
<IJS>Router</IJS> (or whatever you name the root Curi component)
should be a descendant of the <IJS>ApolloProvider</IJS> because we
don't need to re-render the <IJS>ApolloProvider</IJS> for every new
response.
</Paragraph>
<CodeBlock lang="jsx">
{`import { ApolloProvider } from "react-apollo";
import { createRouterComponent } from "@curi/react-dom";
let Router = createRouterComponent(router);
ReactDOM.render((
<ApolloProvider client={client}>
<Router>
<App />
</Router>
</ApolloProvider>
), holder);`}
</CodeBlock>
</HashSection>
<HashSection meta={looseMeta} tag="h2">
<Paragraph>
Apollo and Curi don't actually have to know about each other. Curi can
create a response without doing any data fetching and let Apollo
handle that with its <IJS>Query</IJS> component.
</Paragraph>
<CodeBlock>
{`// routes.js
import Noun from "./pages/Noun";
// nothing Apollo related in here
let routes = prepareRoutes([
{
name: 'Noun',
path: 'noun/:word',
respond: () => {
return {
body: Noun
};
}
}
]);`}
</CodeBlock>
<Paragraph>
Any location data that a query needs can be taken from the response
object. The best way to access this is to read the current{" "}
<IJS>response</IJS> from the context. This can either be done in the
component or the response can be passed down from the root app.
</Paragraph>
<CodeBlock lang="jsx">
{`import { useResponse } from "@curi/react-dom";
function App() {
let { response } = useResponse();
let { body:Body } = response;
return <Body response={response} />;
}`}
</CodeBlock>
<Paragraph>
Because we pass the <IJS>response</IJS> to the route's <IJS>body</IJS>{" "}
component, we can pass a <IJS>Query</IJS> the response's location
params using <IJS>props.response.params</IJS>.
</Paragraph>
<CodeBlock lang="jsx">
{`// pages/Nouns.js
import { Query } from "react-apollo";
let GET_NOUN = gql\`
query noun(\$word: String!) {
noun(word: $word) {
word,
type,
definition
}
}
\`;
// use the "word" param from the response props
// to query the correct data
let Noun = ({ response }) => (
<Query
query={GET_NOUN}
variables={{ word: response.params.word }}
>
{({ loading, error, data }) => {
if (loading) {
return <Loading />;
}
// ...
return (
<article>
<h1>{data.noun.word}</h1>
<Paragraph>{data.noun.definition}</Paragraph>
</article>
)
}}
</Query>
);`}
</CodeBlock>
</HashSection>
<HashSection meta={tightMeta} tag="h2">
<Paragraph>
You can use your Apollo client instance to call queries in a route's{" "}
<IJS>resolve</IJS> function. <IJS>resolve</IJS> is expected to return
a Promise, which is exactly what <IJS>client.query</IJS> returns.
Tightly pairing Curi and Apollo is mostly center around using{" "}
<IJS>resolve</IJS> to return a <IJS>client.query</IJS> call. This will
delay navigation until after a route's GraphQL data has been loaded by
Apollo.
</Paragraph>
<Paragraph>
The <IJS>external</IJS> option can be used when creating the router to
make the Apollo client accessible from routes.
</Paragraph>
<CodeBlock>
{`import client from "./apollo";
let router = createRouter(browser, routes, {
external: { client }
});`}
</CodeBlock>
<CodeBlock>
{`import { EXAMPLE_QUERY } from "./queries";
let routes = prepareRoutes([
{
name: "Example",
path: "example/:id",
resolve({ params }, external) {
return external.client.query({
query: EXAMPLE_QUERY,
variables: { id: params.id }
});
}
}
]);`}
</CodeBlock>
<Paragraph>There are two strategies for doing this.</Paragraph>
<Paragraph>
The first approach is to avoid the <IJS>Query</IJS> altogether.
Instead, you can use a route's <IJS>response</IJS> property to attach
the data fetched by Apollo directly to a response through its{" "}
<IJS>data</IJS> property.
</Paragraph>
<Paragraph>
While we know at this point that the query has executed, we should
also check <IJS>error</IJS> in the <IJS>respond</IJS> function to
ensure that the query was executed successfully.
</Paragraph>
<CodeBlock>
{`// routes.js
import GET_VERB from "./queries";
import Verb from "./pages/Verb";
export default [
{
name: "Verb",
path: "verb/:word",
resolve({ params }, external) {
return external.client.query({
query: GET_VERB,
variables: { word: params.word }
});
},
respond({ error, resolved }) {
if (error) {
// handle failed queries
}
return {
body: Verb,
data: resolved.verb.data
}
}
}
];`}
</CodeBlock>
<Paragraph>
When rendering, you can access the query data through the{" "}
<IJS>response</IJS>'s <IJS>data</IJS> property.
</Paragraph>
<CodeBlock lang="jsx">
{`// pages/Verb.js
let Verb = ({ response }) => (
<article>
<h1>{response.data.verb.word}</h1>
<Paragraph>
{response.data.verb.definition}
</Paragraph>
</article>
)`}
</CodeBlock>
<Paragraph>
The second approach is to use the <IJS>resolve</IJS> function as a way
to cache the data, but also use <IJS>Query</IJS>. With this approach,
we do not have to attach the query data to the response; we are
relying on the fact that Apollo will execute and cache the results
prior to navigation.
</Paragraph>
<CodeBlock>
{`// routes.js
import { GET_VERB } from "./queries";
export default [
{
name: "Verb",
path: "verb/:word",
resolve({ params, external }) {
// load the data so it is cached by
// your Apollo client
return external.client.query({
query: GET_VERB,
variables: { word: params.word }
});
}
}
];`}
</CodeBlock>
<Paragraph>
The route's component will render a <IJS>Query</IJS> to also call the
query. Because the query has already been executed, Apollo will grab
the data from its cache instead of re-sending a request to your
server.
</Paragraph>
<CodeBlock lang="jsx">
{`// pages/Verb.js
import { GET_VERB } from "../queries";
let Verb = ({ response }) => (
<Query
query={GET_VERB}
variables={{ word: response.params.word }}
>
{({ loading, error, data }) => {
// ...
return (
<article>
<h1>{data.verb.word}</h1>
<Paragraph>
{data.verb.definition}
</Paragraph>
</article>
);
}}
</Query>
)`}
</CodeBlock>
<HashSection meta={prefetchMeta} tag="h3">
<Paragraph>
One additional benefit of adding queries to routes using{" "}
<IJS>resolve</IJS> is that you can prefetch data for a route.
</Paragraph>
<Paragraph>
The{" "}
<Link
name="Package"
params={{ package: "interactions", version: "v2" }}
hash="prefetch"
>
<IJS>prefetch</IJS>
</Link>{" "}
interaction lets you programmatically fetch the data for a route
prior to navigating to a location.
</Paragraph>
<CodeBlock>
{`// index.js
import { prefetch } from "@curi/router";
let routes = prepareRoutes([
{
name: "Example",
path: "example/:id",
resolve({ params }, external) {
return external.client.query({
query: GET_EXAMPLES,
variables: { id: params.id }
});
}
}
]);
let router = createRouter(browser, routes);
// this will call the GET_EXAMPLES query
// and Apollo will cache the results
let exampleRoute = router.route("Example");
prefetch(exampleRoute, { params: { id: 2 }});`}
</CodeBlock>
</HashSection>
</HashSection>
</React.Fragment>
);
}
export { ApolloGuide as component, contents };
| pshrmn/curi | website/src/pages/Guides/apollo.js | JavaScript | mit | 10,462 |
/**
* before : before(el, newEl)
* Inserts a new element `newEl` just before `el`.
*
* var before = require('dom101/before');
* var newNode = document.createElement('div');
* var button = document.querySelector('#submit');
*
* before(button, newNode);
*/
function before (el, newEl) {
if (typeof newEl === 'string') {
return el.insertAdjacentHTML('beforebegin', newEl)
} else {
return el.parentNode.insertBefore(newEl, el)
}
}
module.exports = before
| rstacruz/dom101 | before.js | JavaScript | mit | 492 |
import React, { PropTypes } from 'react';
import Page from './Page';
import ProjectListItem from './ProjectListItem';
import AspectContainer from './AspectContainer';
import BannerImage from './BannerImage';
import styles from './Projects.css';
const Projects = ({ projects }) => (
<Page
Hero={() =>
<AspectContainer>
<BannerImage url="https://placebear.com/900/1200" />
</AspectContainer>
}
title="Projects"
>
<div className={styles.projects}>
{projects.map(project => <ProjectListItem key={project.id} {...project} />)}
</div>
</Page>
);
Projects.propTypes = {
projects: PropTypes.arrayOf(PropTypes.object),
};
export default Projects;
| neffbirkley/o | thomaswooster/src/components/Projects.js | JavaScript | mit | 697 |
(function($) {
var FourthWallConfiguration = function() {
this.token = localStorage.getItem('token');
this.gitlab_host = localStorage.getItem('gitlab_host');
}
FourthWallConfiguration.prototype.save = function() {
localStorage.setItem('token', this.token);
localStorage.setItem('gitlab_host', this.gitlab_host);
$(this).trigger('updated');
}
var FourthWallConfigurationForm = function(form, config) {
this.form = form;
this.statusField = $('#form-status', form)
this.config = config;
this.form.submit(this.onSubmit.bind(this));
};
FourthWallConfigurationForm.prototype.updateStatus = function(string) {
this.statusField.text(string).show();
};
FourthWallConfigurationForm.prototype.onSubmit = function(e) {
var values = this.form.serializeArray();
for( var i in values ) {
this.config[values[i].name] = values[i].value;
}
this.config.save();
this.updateStatus('Data saved!');
return false;
}
var FourthWallConfigurationDisplay = function(element) {
this.configurationList = element;
};
FourthWallConfigurationDisplay.prototype.display = function(config) {
var tokenValue = $('<li>').text('Token: ' + config.token);
var hostnameValue = $('<li>').text('Hostname: ' + config.gitlab_host);
this.configurationList.empty();
this.configurationList.append(tokenValue);
this.configurationList.append(hostnameValue);
};
$(document).ready(function() {
var form = $('#fourth-wall-config');
var savedValues = $('#saved-values');
var config = new FourthWallConfiguration();
var form = new FourthWallConfigurationForm(form, config);
var configDisplay = new FourthWallConfigurationDisplay(savedValues);
configDisplay.display(config);
$(config).on('updated', function() {
configDisplay.display(config);
});
});
})(jQuery);
| dxw/fourth-wall-for-gitlab | javascript/config-form.js | JavaScript | mit | 1,883 |
"use strict";
ace.define("ace/snippets/golang", ["require", "exports", "module"], function (require, exports, module) {
"use strict";
exports.snippetText = undefined;
exports.scope = "golang";
}); | IonicaBizau/arc-assembler | clients/ace-builds/src-noconflict/snippets/golang.js | JavaScript | mit | 204 |
export default {
A: [[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[4,4]],
B: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4]],
C: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
D: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4]],
E: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
F: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[0,3],[0,4]],
G: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
H: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[4,4]],
I: [[0,0],[1,0],[2,0],[3,0],[4,0],[2,1],[2,2],[2,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
J: [[4,0],[4,1],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
K: [[0,0],[4,0],[0,1],[3,1],[0,2],[1,2],[2,2],[0,3],[3,3],[0,4],[4,4]],
L: [[0,0],[0,1],[0,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
M: [[0,0],[4,0],[0,1],[1,1],[3,1],[4,1],[0,2],[2,2],[4,2],[0,3],[4,3],[0,4],[4,4]],
N: [[0,0],[4,0],[0,1],[1,1],[4,1],[0,2],[2,2],[4,2],[0,3],[3,3],[4,3],[0,4],[4,4]],
O: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
P: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[0,4]],
Q: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[3,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
R: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[3,3],[0,4],[4,4]],
S: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
T: [[0,0],[1,0],[2,0],[3,0],[4,0],[2,1],[2,2],[2,3],[2,4]],
U: [[0,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
V: [[0,0],[4,0],[0,1],[4,1],[0,2],[4,2],[1,3],[3,3],[2,4]],
W: [[0,0],[4,0],[0,1],[4,1],[0,2],[2,2],[4,2],[0,3],[1,3],[3,3],[4,3],[0,4],[4,4]],
X: [[0,0],[4,0],[1,1],[3,1],[2,2],[1,3],[3,3],[0,4],[4,4]],
Y: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[2,3],[2,4]],
Z: [[0,0],[1,0],[2,0],[3,0],[4,0],[3,1],[2,2],[1,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
Å: [[2,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[1,3],[2,3],[3,3],[4,3],[0,4],[4,4]],
Ä: [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[1,3],[2,3],[3,3],[4,3],[0,4],[4,4]],
Ö: [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
0: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
1: [[1,0],[2,0],[3,0],[3,1],[3,2],[3,3],[3,4]],
2: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
3: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
4: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[4,4]],
5: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
6: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
7: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[4,2],[4,3],[4,4]],
8: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
9: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
'\@': [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[2,2],[3,2],[4,2],[0,3],[2,3],[4,3],[0,4],[2,4],[3,4],[4,4]],
'\#': [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[1,2],[3,2],[0,3],[1,3],[2,3],[3,3],[4,3],[1,4],[3,4]],
'\?': [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[2,2],[3,2],[4,2],[2,4]],
'\%': [[0,0],[1,0],[4,0],[0,1],[1,1],[3,1],[2,2],[1,3],[3,3],[4,3],[0,4],[3,4],[4,4]],
'\/': [[4,0],[3,1],[2,2],[1,3],[0,4]],
'\+': [[2,0],[2,1],[0,2],[1,2],[2,2],[3,2],[4,2],[2,3],[2,4]],
'\-': [[1,2],[2,2],[3,2]],
'\_': [[0,4],[1,4],[2,4],[3,4],[4,4]],
'\=': [[0,1],[1,1],[2,1],[3,1],[4,1],[0,3],[1,3],[2,3],[3,3],[4,3]],
'\*': [[0,1],[2,1],[4,1],[1,2],[2,2],[3,2],[0,3],[2,3],[4,3]],
'\'': [[2,0],[2,1]],
'\"': [[1,0],[3,0],[1,1],[3,1]],
'\(': [[2,0],[1,1],[1,2],[1,3],[2,4]],
'\)': [[2,0],[3,1],[3,2],[3,3],[2,4]],
'\.': [[2,4]],
'\,': [[3,3],[2,3]],
'\;': [[2,1],[2,3],[2,4]],
'\:': [[2,1],[2,4]],
'\!': [[2,0],[2,1],[2,2],[2,4]],
'\{': [[2,0],[3,0],[2,1],[1,2],[2,2],[2,3],[2,4],[3,4]],
'\}': [[1,0],[2,0],[2,1],[2,2],[3,2],[2,3],[1,4],[2,4]],
'\]': [[1,0],[2,0],[2,1],[2,2],[2,3],[1,4],[2,4]],
'\[': [[2,0],[3,0],[2,1],[2,2],[2,3],[2,4],[3,4]],
'\^': [[2,0],[1,1],[3,1]],
'\<': [[3,0],[2,1],[1,2],[2,3],[3,4]],
'\>': [[1,0],[2,1],[3,2],[2,3],[1,4]]
} | Aapzu/aapzu.xyz | config/characters.js | JavaScript | mit | 4,761 |
export default {
modules: require('glob!./glob.txt'),
options: {
name: 'Comment',
},
info: true,
utils: {},
};
| sb-Milky-Way/Comment | .storybook/params.js | JavaScript | mit | 125 |
#!/usr/bin/env node
process.env.FORCE_COLOR = true;
const program = require('commander');
const package = require('../package.json');
/**
* CLI Commands
*
*/
program
.version((package.name) + '@' + (package.version));
/**
* Command for creating and seeding
*/
program
.command('create [dataObject]', 'Generate seed data').alias('c')
.command('teardown', 'Tear down seed data').alias('t')
.parse(process.argv);
| generationtux/cufflink | src/cufflink.js | JavaScript | mit | 434 |
var hb = require('handlebars')
, fs = require('vinyl-fs')
, map = require('vinyl-map')
module.exports = function (opts, cb) {
if (!opts || typeof opts === 'function') throw new Error('opts is required')
if (!opts.origin) throw new Error('opts.origin is required')
if (!opts.target) throw new Error('opts.target is required')
if (!opts.context) throw new Error('opts.context is required')
var render = map(function (code, filename) {
var t = hb.compile(code.toString())
return t(opts.context)
})
fs.src([opts.origin+'/**'])
.pipe(render)
.pipe(fs.dest(opts.target))
.on('error', cb)
.on('end', cb)
}
| Techwraith/hbs-dir | index.js | JavaScript | mit | 642 |
var request = require('request');
var url = require('url');
var authenticate = require('./oauthentication');
var Request = function(obj){
this.obj = obj;
};
Request.prototype.mailboxes = function(method, specific_url, params, callback){
/*
* @params:
* @ param : if user wants to call specific mailbox e.g. : /
* @ callback: function to pass the following parameters to:
* @error
* @response
* @body
*/
makeRequest(this, method, 'https://api.slice.com/api/v1/mailboxes', specific_url, params, callback);
};
Request.prototype.users = function(method, specific_url, params, callback){
makeRequest(this, method, 'https://api.slice.com/api/v1/users', specific_url, params, callback);
};
Request.prototype.orders = function(method, specific_url, params, callback){
makeRequest(this, method, 'https://api.slice.com/api/v1/orders', specific_url, params, callback);
};
Request.prototype.items = function(method, specific_url, params, callback){
makeRequest(this, method, 'https://api.slice.com/api/v1/items', specific_url, params, callback);
};
Request.prototype.shipments = function(method, specific_url, params, callback){
makeRequest(this, method, 'https://api.slice.com/api/v1/shipments', specific_url, params, callback);
};
Request.prototype.recalls = function(method, specific_url, params, callback){
makeRequest(this, method, 'https://api.slice.com/api/v1/recalls', specific_url, params, callback);
};
Request.prototype.emails = function(method, specific_url, params, callback){
makeRequest(this, method, 'https://api.slice.com/api/v1/emails', specific_url, params, callback);
};
Request.prototype.merchants = function(method, specific_url, params, callback){
makeRequest(this, method, 'https://api.slice.com/api/v1/merchants', specific_url, params, callback);
};
Request.prototype.actions = function(method, specific_url, params, callback){
makeRequest(this, method, 'https://api.slice.com/api/v1/actions/update', specific_url, params, callback);
};
Request.prototype.setAccessToken = function(access_token){
this.access_token = access_token;
}
var makeRequest = function(obj, method, url, specific_url, params, callback){
this.params = params || '';
this.param_url = compileRequest(this.params);
this.method = method || 'GET'; // defaults to 'GET'
this.specific_url = specific_url || '';
request({
uri : url+this.specific_url+this.params,
headers : {
'Authorization' : 'Bearer ' + obj.access_token
},
method : this.method,
timeout : 1000,
followRedirect : true,
maxRedirects : 4,
}, function(error, response, body){
if(error){
throw error;
}
callback(error, response, body);
});
};
var compileRequest = function(params){
var param_url = '?';
for(var key in params){
param_url += key + '=' + params[key] + '&';
}
return param_url.substring(0, param_url.length-1);
};
module.exports = Request;
module.exports.users = Request.users;
module.exports.mailboxes = Request.mailboxes;
module.exports.orders = Request.orders;
module.exports.items = Request.items;
module.exports.shipments = Request.shipments;
module.exports.recalls = Request.recalls;
module.exports.emails = Request.emails;
module.exports.merchants = Request.merchants;
module.exports.actions = Request.actions;
| slicedev/slice-node | lib/requests.js | JavaScript | mit | 3,323 |
(function () {
'use strict';
angular.module('atacamaApp').directive('atacamaIndicator', indicatorDirective);
function indicatorDirective() {
return {
templateUrl: 'app/components/widgets/indicator/indicator.html',
link: linkFunc,
controller: 'IndicatorWidgetController',
controllerAs: 'vm',
bindToController: true // because the scope is isolated
};
}
function linkFunc(scope, element, attrs) {
//set to null by default so images will not try to load until the data is returned
scope.selectedLocation = null;
scope.isLoaded = false;
scope.hasError = false;
// scope.offsetParent = element.offsetParent();
}
})();
| the-james-burton/atacama | src/app/components/widgets/indicator/indicator.directive.js | JavaScript | mit | 689 |
define(['tantaman/web/css_manip/CssManip'],
function(CassManip) {
var el = CassManip.getStyleElem({
id: 'customBackgrounds',
create: true
});
/**
* This is essentially a view class that
* render the stylesheet of background classes whenever
* new background classes are created.
*
* @param {EditorModel} editorModel
*/
function CustomBgStylesheet(editorModel) {
this.model = editorModel;
editorModel.on('change:customBackgrounds', this.render, this);
}
CustomBgStylesheet.prototype = {
/**
* render the stylesheet. Should never
* need to be called explicitly.
*/
render: function(m, customBgs) {
if (!customBgs) return;
el.innerHTML =
JST['strut.presentation_generator/CustomBgStylesheet'](customBgs.get('bgs'));
},
/**
* Unregister from the model so this component
* can be cleaned up.
*/
dispose: function() {
this.model.off(null, null, this);
}
}
return CustomBgStylesheet;
}); | shirshendu/kine_type | public/editor/bundles/app/strut.editor/CustomBgStylesheet.js | JavaScript | mit | 957 |
var dp = jQuery;
dp.noConflict();
dp(document).ready(function() {
//SMOOTH SCROLL
dp('a[href^="#"]').bind('click.smoothscroll', function(e) {
e.preventDefault();
dp('html,body').animate({
scrollTop: dp(this.hash).offset().top
}, 1200);
});
//SUPER SLIDES
// dp('#home-slide').superslides({
// animation: 'fade', // You can choose either fade or slide
// play: 6000
// });
//ANIMAZE
dp('.animaze').bind('inview', function(event, visible) {
if (visible) {
dp(this).stop().animate({
opacity: 1,
top: '0px'
}, 500);
}
/* REMOVE THIS if you want to repeat the animation after the element not in view
else {
$(this).stop().animate({ opacity: 0 });
$(this).removeAttr('style');
}*/
});
dp('.animaze').stop().animate({
opacity: 0
});
//SERVICES
dp("#dp-service").sudoSlider({
customLink: 'a.servicesLink',
responsive: true,
speed: 350,
prevNext: false,
useCSS: true,
effect: "fadeOutIn",
continuous: true,
updateBefore: true
});
//TEXT ROTATOR
dp(".rotatez").textrotator({
animation: "fade",
separator: ",",
speed: 1700
});
//PORTFOLIO
dp('.portfolioContainer').mixitup({
filterSelector: '.portfolioFilter a',
targetSelector: '.portfolio-item',
effects: ['fade', 'scale']
});
//QUOTE SLIDE
dp("#quote-slider").sudoSlider({
customLink: 'a.quoteLink',
speed: 425,
prevNext: true,
responsive: true,
prevHtml: '<a href="#" class="quote-left-indicator"><i class="icon-arrow-left"></i></a>',
nextHtml: '<a href="#" class="quote-right-indicator"><i class="icon-arrow-right"></i></a>',
useCSS: true,
continuous: true,
effect: "fadeOutIn",
updateBefore: true
});
//MAGNIFIC POPUP
dp('.popup').magnificPopup({
type: 'image'
});
//PARALLAX
dp('.parallaxize').parallax("50%", 0.3);
// CONTACT SLIDER
dp("#contact-slider").sudoSlider({
customLink: 'a.contactLink',
speed: 750,
responsive: true,
prevNext: false,
useCSS: false,
continuous: false,
updateBefore: true,
effect: "fadeOutIn"
});
//Map
dp('#map').gmap3({
map: {
options: {
maxZoom: 15
}
},
marker: {
address: "Haltern am See, Weseler Str. 151", // PUT YOUR ADDRESS HERE
options: {
icon: new google.maps.MarkerImage(
"http://cdn.webiconset.com/map-icons/images/pin6.png",
new google.maps.Size(42, 69, "px", "px")
)
}
}
},
"autofit");
});
dp(window).load(function() {
dp("#lazyload").fadeOut();
});
| mromrell/quotadeck-frontend | public/partials/js/main.js | JavaScript | mit | 3,100 |
/*
* aem-sling-contrib
* https://github.com/dherges/aem-sling-contrib
*
* Copyright (c) 2016 David Herges
* Licensed under the MIT license.
*/
define([
"./core",
"./var/slice",
"./callbacks"
], function( jQuery, slice ) {
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// Add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// If we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
return jQuery;
});
| dherges/aem-sling-contrib | content/bootstrap/src/main/content/jcr_root/etc/clientlibs/bootstrap/vendor/jquery/src/deferred.js | JavaScript | mit | 4,564 |
var http = require("http");
var url = require("url");
function start(route, handle)
{
function onRequest(request, response)
{
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started");
}
exports.start = start;
| ombt/ombt | jssrc/nodebeginner/server/ver4/server.js | JavaScript | mit | 421 |
const colors = require('colors/safe');
const shouldSilenceWarnings = (...messages) =>
[].some((msgRegex) => messages.some((msg) => msgRegex.test(msg)));
const shouldNotThrowWarnings = (...messages) =>
[].some((msgRegex) => messages.some((msg) => msgRegex.test(msg)));
const logOrThrow = (log, method, messages) => {
const warning = `console.${method} calls not allowed in tests`;
if (process.env.CI) {
if (shouldSilenceWarnings(messages)) return;
log(warning, '\n', ...messages);
// NOTE: That some warnings should be logged allowing us to refactor graceully
// without having to introduce a breaking change.
if (shouldNotThrowWarnings(messages)) return;
throw new Error(...messages);
} else {
log(colors.bgYellow.black(' WARN '), warning, '\n', ...messages);
}
};
// eslint-disable-next-line no-console
const logMessage = console.log;
global.console.log = (...messages) => {
logOrThrow(logMessage, 'log', messages);
};
// eslint-disable-next-line no-console
const logInfo = console.info;
global.console.info = (...messages) => {
logOrThrow(logInfo, 'info', messages);
};
// eslint-disable-next-line no-console
const logWarning = console.warn;
global.console.warn = (...messages) => {
logOrThrow(logWarning, 'warn', messages);
};
// eslint-disable-next-line no-console
const logError = console.error;
global.console.error = (...messages) => {
logOrThrow(logError, 'error', messages);
};
| tdeekens/flopflip | throwing-console-patch.js | JavaScript | mit | 1,445 |
import Helper, { helper as buildHelper } from '@ember/component/helper';
import { inlineSvg } from 'ember-inline-svg/helpers/inline-svg';
import SVGs from '../svgs';
import Ember from 'ember';
let helper;
if (Helper && buildHelper) {
helper = buildHelper(function ([path], options) {
return inlineSvg(SVGs, path, options);
});
} else {
helper = Ember.Handlebars.makeBoundHelper(function (path, options) {
return inlineSvg(SVGs, path, options.hash || {});
});
}
export default helper;
| minutebase/ember-inline-svg | app/helpers/inline-svg.js | JavaScript | mit | 502 |
'use strict';
var path = require('path');
var Stream = require('readable-stream');
var BufferStreams = require('bufferstreams');
var ttf2woff2 = require('ttf2woff2');
var PluginError = require('plugin-error');
var replaceExtension = require('replace-ext');
var PLUGIN_NAME = 'gulp-ttf2woff2';
// File level transform function
function ttf2woff2Transform() {
// Return a callback function handling the buffered content
return function ttf2woff2TransformCb(err, buf, cb) {
// Handle any error
if(err) {
return cb(new PluginError(PLUGIN_NAME, err, { showStack: true }));
}
// Use the buffered content
try {
buf = ttf2woff2(buf);
return cb(null, buf);
} catch(err2) {
return cb(new PluginError(PLUGIN_NAME, err2, { showStack: true }));
}
};
}
// Plugin function
function ttf2woff2Gulp(options) {
var stream = new Stream.Transform({ objectMode: true });
options = options || {};
options.ignoreExt = options.ignoreExt || false;
options.clone = options.clone || false;
stream._transform = function ttf2woff2GulpTransform(file, unused, done) {
var cntStream;
var newFile;
// When null just pass through
if(file.isNull()) {
stream.push(file); done();
return;
}
// If the ext doesn't match, pass it through
if((!options.ignoreExt) && '.ttf' !== path.extname(file.path)) {
stream.push(file); done();
return;
}
// Fix for the vinyl clone method...
// https://github.com/wearefractal/vinyl/pull/9
if(options.clone) {
if(file.isBuffer()) {
stream.push(file.clone());
} else {
cntStream = file.contents;
file.contents = null;
newFile = file.clone();
file.contents = cntStream.pipe(new Stream.PassThrough());
newFile.contents = cntStream.pipe(new Stream.PassThrough());
stream.push(newFile);
}
}
file.path = replaceExtension(file.path, '.woff2');
// Buffers
if(file.isBuffer()) {
try {
file.contents = ttf2woff2(file.contents);
} catch(err) {
stream.emit('error', new PluginError(PLUGIN_NAME, err, {
showStack: true,
}));
}
// Streams
} else {
file.contents = file.contents.pipe(new BufferStreams(ttf2woff2Transform()));
}
stream.push(file);
done();
};
return stream;
}
// Export the file level transform function for other plugins usage
ttf2woff2Gulp.fileTransform = ttf2woff2Transform;
// Export the plugin main function
module.exports = ttf2woff2Gulp;
| nfroidure/gulp-ttf2woff2 | src/index.js | JavaScript | mit | 2,569 |
//# sourceMappingURL=WeatherData.js.map
| MatthewNichols/WeatherDemo | Scripts/WeatherApp/Model/WeatherData.js | JavaScript | mit | 43 |
function commentPage() {
// Open popup
$("#comment-popup").dialog({
width : 800,
height : 400,
modal : true,
appendTo: "#mainForm",
open : function(event, ui) {
$('input[id$="comment-comment"]').focus();
},
close : function(event, ui) {
cancelComment();
}
});
}
/**
* Clean comment form
*/
function cancelComment() {
$('textarea[id$="comment-comment"]').val('');
}
function saveComment(event) {
if (event.status == 'complete') {
cancelComment();
$('#comment-popup').dialog('close');
}
}
| Micht69/shoplist | WebContent/static/scripts/comment.js | JavaScript | mit | 556 |
document.addEventListener("DOMContentLoaded", function() {
"use_strict";
// Store game in global variable
const CASUDOKU = {};
CASUDOKU.game = (function() {
// Controls the state of the game
// Game UI
let uiStats = document.getElementById("gameStats"),
uiComplete = document.getElementById("gameComplete"),
uiNewGame = document.getElementById("gameNew"),
gamePadKeys = document.querySelectorAll("#gameKeypad li a");
// GameKeypad Events
for (let i = gamePadKeys.length - 1; i >= 0; i--) {
let key = gamePadKeys[i];
key.onclick = function(e) {
e.preventDefault();
// Parse keycode value
let number = parseInt(e.currentTarget.innerText, 10);
if (!number) {
CASUDOKU.board.update_cell(0);
} else {
CASUDOKU.board.update_cell(number);
}
}
}
uiNewGame.onclick = function(e) {
e.preventDefault();
CASUDOKU.game.start();
}
start = function() {
CASUDOKU.timer.start();
CASUDOKU.board.new_puzzle();
uiComplete.style.display = "none";
uiStats.style.display = "block";
};
over = function() {
CASUDOKU.timer.stop();
uiComplete.style.display = "block";
uiStats.style.display = "none";
};
// Public api
return {
start: start,
over: over
};
}());
CASUDOKU.timer = (function() {
let timeout,
seconds = 0,
minutes = 0,
secCounter = document.querySelectorAll(".secCounter"),
minCounter = document.querySelectorAll(".minCounter");
start = function() {
if (seconds === 0 && minutes === 0) {
timer();
} else {
stop();
seconds = 0;
minutes = 0;
setText(minCounter, 0);
timer();
}
};
stop = function() {
clearTimeout(timeout);
};
setText = function(element, time) {
element.forEach(function(val) {
val.innerText = time;
});
};
timer = function() {
timeout = setTimeout(timer, 1000);
if (seconds === 59) {
setText(minCounter, ++minutes);
seconds = 0;
}
setText(secCounter, seconds++);
};
// Public api
return {
start: start,
stop: stop
};
}());
CASUDOKU.board = (function() {
// Stores the cells that make up the Sudoku board
let grid = [],
// Canvas settings
canvas = document.getElementById("gameCanvas"),
context = canvas.getContext("2d"),
canvasWidth = canvas.offsetWidth,
canvasHeight = canvas.offsetHeight,
// Board Settings
numRows = 9, numCols = 9,
regionWidth = canvasWidth / 3,
regionHeight = canvasHeight / 3,
// Cell Settings
cellWidth = canvasWidth / numCols,
cellHeight = canvasHeight / numRows,
numCells = numRows * numCols,
selectedCellIndex = 0,
//Key Codes
keycode = {
arrowLeft: 37,
arrowUp: 38,
arrowRight: 39,
arrowDown: 40,
zero: 48,
nine: 57
};
// End let
// Keyboard & Mouse Events
canvas.addEventListener("click", function (e) {
// Calculate position of mouse click and update selected cell
let xAxis,
yAxis,
canvasOffset = getOffset(),
cellIndex,
resultsX = [],
resultsY = [];
function getOffset() {
return {
left: canvas.getBoundingClientRect().left + window.scrollX,
top: canvas.getBoundingClientRect().top + window.scrollY
};
}
if (e.pageX !== undefined && e.pageY !== undefined) {
xAxis = e.pageX;
yAxis = e.pageY;
} else {
xAxis = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
yAxis = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
xAxis -= canvasOffset.left;
yAxis -= canvasOffset.top;
xAxis = Math.min(xAxis, canvasWidth);
yAxis = Math.min(yAxis, canvasHeight);
xAxis = Math.floor(xAxis/cellWidth);
yAxis = Math.floor(yAxis/cellHeight);
// Matches clicked coordinates to a cell
for (let i = 0; i < numCells; i+= 1) {
if (grid[i].col === xAxis && grid[i].row === yAxis) {
selectedCellIndex = i;
refresh_board();
}
}
});
window.addEventListener("keypress", function (e) {
if (e.which >= keycode.zero && e.which <= keycode.nine) {
// Subtract 48 to get actual number
update_cell(e.which - 48);
}
});
window.addEventListener("keydown", function (e) {
// Arrow Key events for changing the selected cell
let pressed = e.which,
col = grid[selectedCellIndex].col,
row = grid[selectedCellIndex].row;
if (pressed >= keycode.arrowLeft && pressed <= keycode.arrowDown) {
if (col < (numCols - 1) && pressed == keycode.arrowRight) {
selectedCellIndex++;
refresh_board();
}
if (col > 0 && pressed == keycode.arrowLeft) {
selectedCellIndex--;
refresh_board();
}
if (row < (numRows - 1) && pressed == keycode.arrowDown) {
selectedCellIndex += numCols;
refresh_board();
}
if (row > 0 && pressed == keycode.arrowUp) {
selectedCellIndex -= numCols;
refresh_board();
}
}
});
new_puzzle = function() {
let workerSudokuSolver = new Worker("js/sudoku-solver.js"),
clues = 24,
puzzle;
workerSudokuSolver.postMessage(clues);
workerSudokuSolver.onmessage = function(e) {
puzzle = e.data;
make_grid(puzzle);
};
};
make_grid = function(puzzle) {
// Makes a grid array filled with cell instances. Each cell stores
// one puzzle value
let colCounter = 0,
rowCounter = 0;
class Cell {
constructor() {
// set fixed puzzle values
this.isDefault = true;
this.value = 0;
// Store position on the canvas
this.x = 0;
this.y = 0;
this.col = 0;
this.row = 0;
}
};
for (let i = 0; i < puzzle.length; i++) {
grid[i] = new Cell();
grid[i].value = puzzle[i];
if (puzzle[i] === 0) {
grid[i].isDefault = false;
}
// Set cell column and row
grid[i].col = colCounter;
grid[i].row = rowCounter;
colCounter++;
// change row
if ((i + 1) % 9 === 0) {
rowCounter++;
colCounter = 0;
}
}
refresh_board();
};
refresh_board = function () {
let workerSudokuValidator = new Worker("js/sudoku-validator.js");
workerSudokuValidator.postMessage(grid);
workerSudokuValidator.onmessage = function(e) {
let correct = e.data;
if (correct) {
CASUDOKU.game.over();
}
draw();
};
};
draw = function () {
// renders the canvas
let regionPosX = 0, regionPosY = 0,
cellPosX = 0, cellPosY = 0,
textPosX = cellWidth * 0.4, textPosY = cellHeight * 0.65;
// board outline
context.clearRect(0, 0, canvasWidth, canvasHeight);
context.strokeRect(0 , 0, canvasWidth, canvasHeight);
context.globalCompositeOperation = "destination-over";
context.lineWidth = 10;
// regions
for (let x = 0; x < numRows; x++) {
context.strokeRect(regionPosX, regionPosY, regionWidth, regionHeight);
regionPosX += regionWidth;
if (regionPosX == canvasWidth){
regionPosY += regionHeight;
regionPosX = 0;
}
}
// Start to draw the Grid
context.beginPath();
// vertical lines
for (let z = 0; z <= canvasWidth; z += cellWidth) {
context.moveTo(0.5 + z, 0);
context.lineTo(0.5 + z, canvasWidth);
}
// horizontal lines
for (let y = 0; y <= canvasHeight; y += cellHeight) {
context.moveTo(0, 0.5 + y);
context.lineTo(canvasHeight, 0.5 + y);
}
// cell outline
context.lineWidth = 2;
context.strokeStyle = "black";
context.stroke();
for (let i = 0; i < numCells; i++) {
grid[i].x = cellPosX;
grid[i].y = cellPosY;
// Cell values
if (grid[i].isDefault) {
context.font = "bold 1.6em Droid Sans, sans-serif";
context.fillStyle = "black";
context.fillText(grid[i].value, textPosX, textPosY);
}
if (grid[i].value !== 0 && !grid[i].isDefault) {
context.font = "1.4em Droid Sans, sans-serif";
context.fillStyle = "grey";
context.fillText(grid[i].value, textPosX, textPosY);
}
// Cell background colour
if (i == selectedCellIndex) {
context.fillStyle = "#00B4FF";
}
else {
context.fillStyle = "#EEEEEE";
}
// Cell background
context.fillRect(cellPosX, cellPosY, cellWidth, cellHeight);
cellPosX += cellWidth;
textPosX += cellWidth;
// Change row
if ((i + 1) % numRows === 0) {
cellPosX = 0;
cellPosY += cellHeight;
textPosY += cellHeight;
textPosX = cellWidth * 0.4;
}
}
};
update_cell = function (value) {
if (!grid[selectedCellIndex].isDefault) {
grid[selectedCellIndex].value = value;
refresh_board();
}
};
// Public api
return {
new_puzzle: new_puzzle,
update_cell: update_cell
};
}());
CASUDOKU.game.start();
});
| davidhenry/CaSudoku | js/game.js | JavaScript | mit | 8,726 |
webpackJsonp([2],{
/***/ 16:
/***/ function(module, exports, __webpack_require__) {
/// <reference path="../../typings/tsd.d.ts" />
var ListController = __webpack_require__(17);
// webpack will load the html. Nifty, eh?
__webpack_require__(9);
// webpack will load this scss too!
__webpack_require__(18);
module.exports = angular.module('List', [])
.controller('ListController', ['$scope', ListController]);
//# sourceMappingURL=index.js.map
/***/ },
/***/ 17:
/***/ function(module, exports) {
var ListController = (function () {
function ListController() {
this.apps = [
{ name: 'Gmail' },
{ name: 'Facebook' },
{ name: 'Twitter' },
{ name: 'LinkedIn' }
];
this.title = 'Applications';
}
return ListController;
})();
module.exports = ListController;
//# sourceMappingURL=list.controller.js.map
/***/ },
/***/ 18:
/***/ function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(19);
if(typeof content === 'string') content = [[module.id, content, '']];
// add the styles to the DOM
var update = __webpack_require__(15)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!./../../../../node_modules/css-loader/index.js!./../../../../node_modules/autoprefixer-loader/index.js!./../../../../node_modules/sass-loader/index.js!./list.scss", function() {
var newContent = require("!!./../../../../node_modules/css-loader/index.js!./../../../../node_modules/autoprefixer-loader/index.js!./../../../../node_modules/sass-loader/index.js!./list.scss");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ },
/***/ 19:
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(14)();
// imports
// module
exports.push([module.id, ".list-item {\n color: blue; }\n", ""]);
// exports
/***/ }
}); | jaganathanb/Typescript-Angular-Gulp-Webpack-Dynamic-module-loading- | dist/2.module.js | JavaScript | mit | 2,324 |
djsex.css = {
/*
* http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
*/
create: function(stylesheet) {
var head = document.getElementsByTagName('head')[0],
style = document.createElement('style'),
rules = document.createTextNode(stylesheet);
style.type = 'text/css';
if(style.styleSheet)
style.styleSheet.cssText = rules.nodeValue;
else style.appendChild(rules);
head.appendChild(style);
},
appendClass: function (el, classname) {
if(el.className) {
var classes = el.className.split(" ");
var alreadyclassed = false;
classes.forEach(function(thisclassname) {
if(classname == thisclassname)
alreadyclassed=true;
});
if(!alreadyclassed)
classes.push(classname);
el.className = classes.join(" ")
} else {
el.className=classname;
}
},
deleteClass: function (el, classname) {
if(el.className) {
var classes = el.className.split(" ");
for(i=0; i<=classes.length; i++) {
if((classes[i]) && (classes[i]==classname))
classes.splice(i,1);
}
el.className = classes.join(" ");
}
},
};
| WatersideDevelopment/Fullscreen-Ajax-Image-Loader | js/djsex/CSS.js | JavaScript | mit | 1,396 |
/**
* The Furnace namespace
*
* @module furnace
* @class Furnace
* @static
*/
import Validation from 'furnace/packages/furnace-validation';
import I18n from 'furnace/packages/furnace-i18n';
import Forms from 'furnace/packages/furnace-forms';
export default {
/**
*
* @property Forms
* @type Furnace.Forms
*/
Forms : Forms,
/**
* @property I18n
* @type Furnace.I18n
*/
I18n : I18n,
/**
* @property Validation
* @type Furnace.Validation
*/
Validation: Validation
};
| ember-furnace/ember-cli-furnace | addon/index.js | JavaScript | mit | 503 |
import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import { customPropTypes, getElementType, getUnhandledProps, useKeyOnly } from '../../lib'
/**
* A placeholder can contain an image.
*/
function PlaceholderImage(props) {
const { className, square, rectangular } = props
const classes = cx(
useKeyOnly(square, 'square'),
useKeyOnly(rectangular, 'rectangular'),
'image',
className,
)
const rest = getUnhandledProps(PlaceholderImage, props)
const ElementType = getElementType(PlaceholderImage, props)
return <ElementType {...rest} className={classes} />
}
PlaceholderImage.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Additional classes. */
className: PropTypes.string,
/** An image can modify size correctly with responsive styles. */
square: customPropTypes.every([customPropTypes.disallow(['rectangular']), PropTypes.bool]),
/** An image can modify size correctly with responsive styles. */
rectangular: customPropTypes.every([customPropTypes.disallow(['square']), PropTypes.bool]),
}
export default PlaceholderImage
| Semantic-Org/Semantic-UI-React | src/elements/Placeholder/PlaceholderImage.js | JavaScript | mit | 1,162 |
(function (angular) {
"use strict";
var appFooter = angular.module('myApp.footer', []);
appFooter.controller("footerCtrl", ['$scope', function ($scope) {
}]);
myApp.directive("siteFooter",function(){
return {
restrict: 'A',
templateUrl:'app/components/footer/footer.html'
};
});
} (angular)); | kevinczhang/kevinczhang.github.io | src/app/components/footer/footer.js | JavaScript | mit | 376 |
export default function formatList(xs, { ifEmpty = 'нет', joint = ', ' } = {}) {
return (!xs || xs.length === 0) ? ifEmpty : xs.join(joint)
}
| whitescape/react-admin-components | src/ui/format/list.js | JavaScript | mit | 147 |
import React from 'react';
const EditHero = props => {
if (props.selectedHero) {
return (
<div>
<div className="editfields">
<div>
<label>id: </label>
{props.addingHero
? <input
type="number"
name="id"
placeholder="id"
value={props.selectedHero.id}
onChange={props.onChange}
/>
: <label className="value">
{props.selectedHero.id}
</label>}
</div>
<div>
<label>name: </label>
<input
name="name"
value={props.selectedHero.name}
placeholder="name"
onChange={props.onChange}
/>
</div>
<div>
<label>saying: </label>
<input
name="saying"
value={props.selectedHero.saying}
placeholder="saying"
onChange={props.onChange}
/>
</div>
</div>
<button onClick={props.onCancel}>Cancel</button>
<button onClick={props.onSave}>Save</button>
</div>
);
} else {
return <div />;
}
};
export default EditHero;
| Ryan-ZL-Lin/react-cosmosdb | src/components/EditHero.js | JavaScript | mit | 1,289 |
/**
* Module dependencies.
*/
var express = require('express')
var MemoryStore = express.session.MemoryStore
var mongoStore = require('connect-mongo')(express)
var path = require('path')
var fs = require('fs')
var _ = require('underscore')
var mongoose = require('mongoose')
var passport = require('passport')
var http = require('http')
var socketio = require('socket.io')
var passportSocketIo = require('passport.socketio')
// Load configurations
var env = process.env.NODE_ENV || 'development'
var config = require('./config/config')[env]
// Bootstrap db connection
mongoose.connect(config.db)
// Bootstrap models
var modelsDir = path.join(__dirname, '/app/models')
fs.readdirSync(modelsDir).forEach(function (file) {
if (~file.indexOf('.js')) require(modelsDir + '/' + file)
})
// Bootstrap passport config
require('./config/passport')(passport, config)
var app = express()
var store = new mongoStore({ url : config.db, collection : 'sessions' });
//var store = new MemoryStore()
// express settings
require('./config/express')(app, config, passport, store)
// Bootstrap routes
require('./config/routes')(app, passport)
var server = http.createServer(app)
var sio = socketio.listen(server)
var clients = {}
var socketsOfClients = {}
sio.configure(function () {
sio.set('authorization', passportSocketIo.authorize({
cookieParser: express.cookieParser, //or connect.cookieParser
key: 'express.sid', //the cookie where express (or connect) stores the session id.
secret: 'dirty', //the session secret to parse the cookie
store: store, //the session store that express uses
fail: function (data, accept) { // *optional* callbacks on success or fail
accept(null, false) // second parameter takes boolean on whether or not to allow handshake
},
success: function (data, accept) {
accept(null, true)
}
}))
})
// upon connection, start a periodic task that emits (every 1s) the current timestamp
sio.sockets.on('connection', function (socket) {
var username = socket.handshake.user.username;
clients[username] = socket.id
socketsOfClients[socket.id] = username
userNameAvailable(socket.id, username)
userJoined(username)
socket.on('data', function (data) {
socket.broadcast.emit('data', { 'drawing' : data })
})
socket.on('message', function (data) {
var now = new Date();
sio.sockets.emit('message', {
'source': socketsOfClients[socket.id],
'time': now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds(),
'message': data.message
})
})
socket.on('disconnect', function() {
var username = socketsOfClients[socket.id]
delete socketsOfClients[socket.id]
delete clients[username];
// relay this message to all the clients
userLeft(username)
})
})
// Start the application by listening on port <>
var port = process.env.PORT || 3000
server.listen(port, function(){
console.log('Express server listening on port ' + port)
});
function userNameAvailable(socketId, username) {
setTimeout(function(){
sio.sockets.sockets[socketId].emit('user welcome', {
"currentUsers": JSON.stringify(Object.keys(clients))
});
}, 500);
}
function userJoined(username) {
Object.keys(socketsOfClients).forEach(function(socketId) {
sio.sockets.sockets[socketId].emit('user joined', {
"username": username
});
});
}
function userLeft(username) {
sio.sockets.emit('user left', {
"username": username
});
}
// expose app
exports = module.exports = app;
| rtorino/shiny-octo-ironman | app.js | JavaScript | mit | 3,595 |
'use strict';
var redis = require('redis')
, xtend = require('xtend')
, hyperquest = require('hyperquest')
;
module.exports = FetchAndCache;
/**
* Creates a fetchncache instance.
*
* #### redis opts
*
* - **opts.redis.host** *{number=}* host at which redis is listening, defaults to `127.0.0.1`
* - **opts.redis.port** *{string=}* port at which redis is listening, defaults to `6379`
*
* #### service opts
*
* - **opts.service.url** *{string=}* url at which to reach the service
*
* @name fetchncache
* @function
* @param {Object=} opts
* @param {Object=} opts.redis redis options passed straight to [redis](https://github.com/mranney/node_redis) (@see above)
* @param {Object=} opts.service options specifying how to reach the service that provides the data (@see above)
* @param {number=} opts.expire the default number of seconds after which to expire a resource from the redis cache (defaults to 15mins)
* @return {Object} fetchncache instance
*/
function FetchAndCache(opts) {
if (!(this instanceof FetchAndCache)) return new FetchAndCache(opts);
opts = opts || {};
var redisOpts = xtend({ port: 6379, host: '127.0.0.1' }, opts.redis)
, serviceOpts = xtend({ url: 'http://127.0.0.1' }, opts.service)
this._defaultExpire = opts.expire || 15 * 60 // 15min
this._serviceOpts = serviceOpts;
this._markCached = opts.markCached !== false;
this._client = redis.createClient(redisOpts.port, redisOpts.host, redisOpts)
}
var proto = FetchAndCache.prototype;
/**
* Fetches the resource, probing the redis cache first and falling back to the service.
* If a transform function is provided (@see opts), that is applied to the result before returning or caching it.
* When fetched from the service it is added to the redis cached according to the provided options.
*
* @name fetcncache::fetch
* @function
* @param {string} uri path to the resource, i.e. `/reource1?q=1234`
* @param {Object=} opts configure caching and transformation behavior for this particular resource
* @param {number=} opts.expire overrides default expire for this particular resource
* @param {function=} opts.transform specify the transform function to be applied, default: `function (res} { return res }`
* @param {function} cb called back with an error or the transformed resource
*/
proto.fetch = function (uri, opts, cb) {
var self = this;
if (!self._client) return cb(new Error('fetchncache was stopped and can no longer be used to fetch data'));
if (typeof opts === 'function') {
cb = opts;
opts = null;
}
opts = xtend({ expire: self._defaultExpire, transform: function (x) { return x } }, opts);
self._client.get(uri, function (err, res) {
if (err) return cb(err);
if (res) return cb(null, res, true);
self._get(uri, function (err, res) {
if (err) return cb(err);
self._cache(uri, res, opts, cb);
})
});
}
/**
* Stops the redis client in order to allow exiting the application.
* At this point this fetchncache instance becomes unusable and throws errors on any attempts to use it.
*
* @name fetchncache::stop
* @function
* @param {boolean=} force will make it more aggressive about ending the underlying redis client (default: false)
*/
proto.stop = function (force) {
if (!this._client) throw new Error('fetchncache was stopped previously and cannot be stopped again');
if (force) this._client.end(); else this._client.unref();
this._client = null;
}
/**
* Clears the entire redis cache, so use with care.
* Mainly useful for testing or to ensure that all resources get refreshed.
*
* @name fetchncache::clearCache
* @function
* @return {Object} fetchncache instance
*/
proto.clearCache = function () {
if (!this._client) throw new Error('fetchncache was stopped previously and cannot be cleared');
this._client.flushdb();
return this;
}
proto._get = function (uri, cb) {
var body = '';
var url = this._serviceOpts.url + uri;
console.log('url', url);
hyperquest
.get(url)
.on('error', cb)
.on('data', function (d) { body += d.toString() })
.on('end', function () { cb(null, body) })
}
proto._cache = function (uri, res, opts, cb) {
var self = this;
var val;
try {
val = opts.transform(res);
} catch (e) {
return cb(e);
}
// assuming that value is now a string we use set to add it
self._client.set(uri, val, function (err) {
if (err) return cb(err);
self._client.expire(uri, opts.expire, function (err) {
if (err) return cb(err);
cb(null, val);
})
});
}
| thlorenz/fetchncache | index.js | JavaScript | mit | 4,638 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let _ = require('lodash');
let async = require('async');
const pip_services3_commons_node_1 = require("pip-services3-commons-node");
const pip_services3_facade_node_1 = require("pip-services3-facade-node");
class RolesOperationsV1 extends pip_services3_facade_node_1.FacadeOperations {
constructor() {
super();
this._dependencyResolver.put('roles', new pip_services3_commons_node_1.Descriptor('pip-services-roles', 'client', '*', '*', '1.0'));
}
setReferences(references) {
super.setReferences(references);
this._rolesClient = this._dependencyResolver.getOneRequired('roles');
}
getUserRolesOperation() {
return (req, res) => {
this.getUserRoles(req, res);
};
}
grantUserRolesOperation() {
return (req, res) => {
this.grantUserRoles(req, res);
};
}
revokeUserRolesOperation() {
return (req, res) => {
this.revokeUserRoles(req, res);
};
}
getUserRoles(req, res) {
let userId = req.route.params.user_id;
this._rolesClient.getRolesById(null, userId, this.sendResult(req, res));
}
grantUserRoles(req, res) {
let userId = req.route.params.user_id;
let roles = req.body;
this._rolesClient.grantRoles(null, userId, roles, this.sendResult(req, res));
}
revokeUserRoles(req, res) {
let userId = req.route.params.user_id;
let roles = req.body;
this._rolesClient.revokeRoles(null, userId, roles, this.sendResult(req, res));
}
}
exports.RolesOperationsV1 = RolesOperationsV1;
//# sourceMappingURL=RolesOperationsV1.js.map | pip-services-users/pip-facade-users-node | obj/src/operations/version1/RolesOperationsV1.js | JavaScript | mit | 1,730 |
var config = require('../lib/config')();
var Changeset = require('./Changeset');
var queries = require('./queries');
var helpers = require('../helpers');
require('../validators');
var validate = require('validate.js');
var errors = require('../errors');
var pgPromise = helpers.pgPromise;
var promisifyQuery = helpers.promisifyQuery;
var changesets = {};
module.exports = changesets;
var pgURL = config.PostgresURL;
changesets.search = function(params) {
var parseError = validateParams(params);
if (parseError) {
return Promise.reject(new errors.ParseError(parseError));
}
var searchQuery = queries.getSearchQuery(params);
var countQuery = queries.getCountQuery(params);
console.log('searchQ', searchQuery);
console.log('countQ', countQuery);
return pgPromise(pgURL)
.then(function (pg) {
var query = promisifyQuery(pg.client);
var searchProm = query(searchQuery.text, searchQuery.values);
var countProm = query(countQuery.text, countQuery.values);
return Promise.all([searchProm, countProm])
.then(function (r) {
pg.done();
return r;
})
.catch(function (e) {
pg.done();
return Promise.reject(e);
});
})
.then(processSearchResults);
};
changesets.get = function(id) {
if (!validate.isNumber(parseInt(id, 10))) {
return Promise.reject(new errors.ParseError('Changeset id must be a number'));
}
var changesetQuery = queries.getChangesetQuery(id);
var changesetCommentsQuery = queries.getChangesetCommentsQuery(id);
return pgPromise(pgURL)
.then(function (pg) {
var query = promisifyQuery(pg.client);
var changesetProm = query(changesetQuery.text, changesetQuery.values);
var changesetCommentsProm = query(changesetCommentsQuery.text, changesetCommentsQuery.values);
return Promise.all([changesetProm, changesetCommentsProm])
.then(function (results) {
pg.done();
return results;
})
.catch(function (e) {
pg.done();
return Promise.reject(e);
});
})
.then(function (results) {
var changesetResult = results[0];
if (changesetResult.rows.length === 0) {
return Promise.reject(new errors.NotFoundError('Changeset not found'));
}
var changeset = new Changeset(results[0].rows[0], results[1].rows);
return changeset.getGeoJSON();
});
};
function processSearchResults(results) {
var searchResult = results[0];
var countResult = results[1];
var changesetsArray = searchResult.rows.map(function (row) {
var changeset = new Changeset(row);
return changeset.getGeoJSON();
});
var count;
if (countResult.rows.length > 0) {
count = countResult.rows[0].count;
} else {
count = 0;
}
var featureCollection = {
'type': 'FeatureCollection',
'features': changesetsArray,
'total': count
};
return featureCollection;
}
function validateParams(params) {
var constraints = {
'from': {
'presence': false,
'datetime': true
},
'to': {
'presence': false,
'datetime': true
},
'bbox': {
'presence': false,
'bbox': true
}
};
var errs = validate(params, constraints);
if (errs) {
var errMsg = Object.keys(errs).map(function(key) {
return errs[key][0];
}).join(', ');
return errMsg;
}
return null;
} | mapbox/osm-comments-api | changesets/index.js | JavaScript | mit | 3,841 |
'use strict';
const assert = require('assert');
const HttpResponse = require('./http-response');
describe('HttpResponse', () => {
const mockResponse = {
version: '1.0',
status: '200 OK'
};
it('should create an instance', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse instanceof HttpResponse);
});
describe('isProtocolVersion()', () => {
it('should determine if protocol version matches', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse.isProtocolVersion('1.0'));
});
it('should return false if versions do not match', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.isProtocolVersion('2.0'), false);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.isProtocolVersion, /Specify a protocol `version`/);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.isProtocolVersion(false), /The protocol `version` must be a string/);
});
});
describe('getProtocolVersion()', () => {
it('should get the protocol version', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getProtocolVersion(), '1.0');
});
});
describe('setProtocolVersion()', () => {
it('should set the protocol version', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getProtocolVersion(), '1.0');
httpResponse.setProtocolVersion('2.0');
assert.equal(httpResponse.getProtocolVersion(), '2.0');
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.setProtocolVersion, /Specify a protocol `version`/);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setProtocolVersion(Boolean), /The protocol `version` must be a string/);
});
});
describe('isStatus()', () => {
it('should determine if status matches', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse.isStatus('200 OK'));
});
it('should return false if status do not match', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.isStatus('400 Bad Request'), false);
});
it('should throw an error if no status specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.isStatus, /Specify a `status`/);
});
it('should throw an error if specified status is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.isStatus({}), /The `status` must be a string/);
});
});
describe('getStatus()', () => {
it('should return the status', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
});
});
describe('getStatusCode()', () => {
it('should return status code', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatusCode(), '200');
});
});
describe('getStatusText()', () => {
it('should return status text', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatusText(), 'OK');
});
});
describe('setStatus()', () => {
it('should set the status', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
httpResponse.setStatus(400, 'Bad Request');
assert.equal(httpResponse.getStatus(), '400 Bad Request');
});
it('should throw an error if no code specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(void 0, 'Bad Request'), /Specify a status `code`/);
});
it('should throw an error if the code is not an integer', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() =>
httpResponse.setStatus('200', 'Bad Request'), /The status `code` must be an integer/);
});
it('should throw an error if no text specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(400, void 0), /Specify a status `text`/);
});
it('should throw an error if specified text is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(400, true), /The status `text` must be a string/);
});
});
describe('hasHeader()', () => {
it('should determine if header has been set', () => {
const _mockResponse = Object.assign({headers: {'Content-Type': 'test'}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.ok(httpResponse.hasHeader('Content-Type'));
});
it('should return false if header has not been set', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.hasHeader('Content-Type'), false);
});
it('should throw an error if no header `name` specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.hasHeader, /Specify a header `name`/);
});
it('should throw an error if specified header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.hasHeader({}), /The header `name` must be a string/);
});
});
describe('getHeader()', () => {
it('should return the header with the specified `name`', () => {
const _mockResponse = Object.assign({headers: {'Content-Type': ['test']}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.equal(httpResponse.getHeader('Content-Type'), 'test');
});
it('should return the default value if specified header does not exist', () => {
const _mockResponse = Object.assign({headers: {}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
const defaultValue = 'text/plain';
assert.equal(httpResponse.getHeader('Content-Type', defaultValue), defaultValue);
});
it('should throw an error if no header `name` specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.getHeader, /Specify a header `name`/);
});
it('should throw an error if specified header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.getHeader({}), /The header `name` must be a string/);
});
});
describe('getHeaders()', () => {
it('should return all headers', () => {
const headers = {'Content-Type': ['test']};
const _mockResponse = Object.assign({headers}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.deepEqual(httpResponse.getHeaders(), {'Content-Type': 'test'});
});
it('should return an empty set of headers when none are set', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.deepEqual(httpResponse.getHeaders(), {});
});
});
describe('setHeader()', () => {
it('should set a header in the httpResponse', () => {
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setHeader('Content-Type', 'test');
assert.ok(httpResponse.hasHeader('Content-Type'));
assert.equal(httpResponse.getHeader('Content-Type'), 'test');
});
it('should throw an error if a header `name` is not defined', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.setHeader(void 0, 'test'), /Specify a header `name`/);
});
it('should throw an error if a header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setHeader(false, 'test'), /The header `name` must be a string/);
});
it('should throw an error if a header `value` is not defined', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setHeader('Content-Type', void 0), /Specify a header `value`/);
});
it('should throw an error if a header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.setHeader('Content-Type', []),
/The header `value` must be a string/);
});
it('should register a new header as an array with 1 value', () => {
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setHeader('X-Test', 'test');
assert.ok(httpResponse.hasHeader('X-Test'));
assert.deepEqual(httpResponse.getHeaderArray('X-Test'), ['test']);
});
});
describe('hasBody()', () => {
it('should determine if the httpResponse has a `body`', () => {
const _mockResponse = Object.assign({body: ' '}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.ok(httpResponse.hasBody());
});
it('should return false if the esponse do not have a `body`', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.hasBody(), false);
});
});
describe('getBody()', () => {
it('should return the content of the httpResponse `body`', () => {
const body = ' ';
const _mockResponse = Object.assign({body}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.equal(httpResponse.getBody(), body);
});
});
describe('setBody()', () => {
it('should set the content of the httpResponse `body`', () => {
const body = ' ';
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setBody(body);
assert.equal(httpResponse.getBody(), body);
});
});
});
| orestes/katana-sdk-node | sdk/http-response.test.js | JavaScript | mit | 10,676 |
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_sql_failoverdatabases"); | DataFire/Integrations | integrations/generated/azure_sql_failoverdatabases/index.js | JavaScript | mit | 181 |
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, node: true, nomen: true,
indent: 4, maxerr: 50 */
/*global expect, describe, it, beforeEach, afterEach */
"use strict";
var ExtensionsDomain = require("../ExtensionManagerDomain"),
fs = require("fs-extra"),
async = require("async"),
path = require("path");
var testFilesDirectory = path.join(path.dirname(module.filename),
"..", // node
"..", // extensibility
"..", // src
"..", // brackets
"test",
"spec",
"extension-test-files"),
installParent = path.join(path.dirname(module.filename), "extensions"),
installDirectory = path.join(installParent, "good"),
disabledDirectory = path.join(installParent, "disabled");
var basicValidExtension = path.join(testFilesDirectory, "basic-valid-extension.zip"),
basicValidExtension2 = path.join(testFilesDirectory, "basic-valid-extension-2.0.zip"),
missingMain = path.join(testFilesDirectory, "missing-main.zip"),
oneLevelDown = path.join(testFilesDirectory, "one-level-extension-master.zip"),
incompatibleVersion = path.join(testFilesDirectory, "incompatible-version.zip"),
invalidZip = path.join(testFilesDirectory, "invalid-zip-file.zip"),
missingPackageJSON = path.join(testFilesDirectory, "missing-package-json.zip");
describe("Package Installation", function () {
var standardOptions = {
disabledDirectory: disabledDirectory,
apiVersion: "0.22.0"
};
beforeEach(function (done) {
fs.mkdirs(installDirectory, function (err) {
fs.mkdirs(disabledDirectory, function (err) {
done();
});
});
});
afterEach(function (done) {
fs.remove(installParent, function (err) {
done();
});
});
function checkPaths(pathsToCheck, callback) {
var existsCalls = [];
pathsToCheck.forEach(function (path) {
existsCalls.push(function (callback) {
fs.exists(path, async.apply(callback, null));
});
});
async.parallel(existsCalls, function (err, results) {
expect(err).toBeNull();
results.forEach(function (result, num) {
expect(result ? "" : pathsToCheck[num] + " does not exist").toEqual("");
});
callback();
});
}
it("should validate the package", function (done) {
ExtensionsDomain._cmdInstall(missingMain, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
var errors = result.errors;
expect(errors.length).toEqual(1);
done();
});
});
it("should work fine if all is well", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
var extensionDirectory = path.join(installDirectory, "basic-valid-extension");
expect(err).toBeNull();
var errors = result.errors;
expect(errors.length).toEqual(0);
expect(result.metadata.name).toEqual("basic-valid-extension");
expect(result.name).toEqual("basic-valid-extension");
expect(result.installedTo).toEqual(extensionDirectory);
var pathsToCheck = [
path.join(extensionDirectory, "package.json"),
path.join(extensionDirectory, "main.js")
];
checkPaths(pathsToCheck, done);
});
});
// This is mildly redundant. the validation check should catch this.
// But, I wanted to be sure that the install function doesn't try to
// do anything with the file before validation.
it("should fail for missing package", function (done) {
ExtensionsDomain._cmdInstall(path.join(testFilesDirectory, "NOT A PACKAGE"),
installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
var errors = result.errors;
expect(errors.length).toEqual(1);
expect(errors[0][0]).toEqual("NOT_FOUND_ERR");
done();
});
});
it("should install to the disabled directory if it's already installed", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toBeNull();
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toEqual("ALREADY_INSTALLED");
var extensionDirectory = path.join(disabledDirectory, "basic-valid-extension");
var pathsToCheck = [
path.join(extensionDirectory, "package.json"),
path.join(extensionDirectory, "main.js")
];
checkPaths(pathsToCheck, done);
});
});
});
it("should yield an error if there's no disabled directory set", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, { apiVersion: "0.22.0" }, function (err, result) {
expect(err.message).toEqual("MISSING_REQUIRED_OPTIONS");
done();
});
});
it("should yield an error if there's no apiVersion set", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, { disabledDirectory: disabledDirectory }, function (err, result) {
expect(err.message).toEqual("MISSING_REQUIRED_OPTIONS");
done();
});
});
it("should overwrite the disabled directory copy if there's already one", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toBeNull();
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toEqual("ALREADY_INSTALLED");
ExtensionsDomain._cmdInstall(basicValidExtension2, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toEqual("ALREADY_INSTALLED");
var extensionDirectory = path.join(disabledDirectory, "basic-valid-extension");
fs.readJson(path.join(extensionDirectory, "package.json"), function (err, packageObj) {
expect(err).toBeNull();
expect(packageObj.version).toEqual("2.0.0");
done();
});
});
});
});
});
it("should derive the name from the zip if there's no package.json", function (done) {
ExtensionsDomain._cmdInstall(missingPackageJSON, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toBeNull();
var extensionDirectory = path.join(installDirectory, "missing-package-json");
var pathsToCheck = [
path.join(extensionDirectory, "main.js")
];
checkPaths(pathsToCheck, done);
});
});
it("should install with the common prefix removed", function (done) {
ExtensionsDomain._cmdInstall(oneLevelDown, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
var extensionDirectory = path.join(installDirectory, "one-level-extension");
var pathsToCheck = [
path.join(extensionDirectory, "main.js"),
path.join(extensionDirectory, "package.json"),
path.join(extensionDirectory, "lib", "foo.js")
];
checkPaths(pathsToCheck, done);
});
});
it("should disable extensions that are not compatible with the current Brackets API", function (done) {
ExtensionsDomain._cmdInstall(incompatibleVersion, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toEqual("API_NOT_COMPATIBLE");
var extensionDirectory = path.join(disabledDirectory, "incompatible-version");
var pathsToCheck = [
path.join(extensionDirectory, "main.js"),
path.join(extensionDirectory, "package.json")
];
checkPaths(pathsToCheck, done);
});
});
it("should not have trouble with invalid zip files", function (done) {
ExtensionsDomain._cmdInstall(invalidZip, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.errors.length).toEqual(1);
done();
});
});
}); | L0g1k/quickfire-old | src/extensibility/node/spec/Installation.spec.js | JavaScript | mit | 10,734 |
(function () {
"use strict";
require('futures/forEachAsync');
var fs = require('fs'),
crypto = require('crypto'),
path = require('path'),
exec = require('child_process').exec,
mime = require('mime'),
FileStat = require('filestat'),
dbaccess = require('../dbaccess'),
utils = require('../utils'),
hashAlgo = "md5";
function readFile(filePath, callback) {
var readStream, hash = crypto.createHash(hashAlgo);
readStream = fs.createReadStream(filePath);
readStream.on('data', function (data) {
hash.update(data);
});
readStream.on('error', function (err) {
console.log("Read Error: " + err.toString());
readStream.destroy();
fs.unlink(filePath);
callback(err);
});
readStream.on('end', function () {
callback(null, hash.digest("hex"));
});
}
function saveToFs(md5, filePath, callback) {
var newPath = utils.hashToPath(md5);
path.exists(newPath, function (exists) {
if (exists) {
fs.move(filePath, newPath, function (err) {
callback(err, newPath);
});
return;
}
exec('mkdir -p ' + newPath, function (err, stdout, stderr) {
var tError;
if (err || stderr) {
console.log("Err: " + (err ? err : "none"));
console.log("stderr: " + (stderr ? stderr : "none"));
tError = {error: err, stderr: stderr, stdout: stdout};
return callback(tError, newPath);
}
console.log("stdout: " + (stdout ? stdout : "none"));
fs.move(filePath, newPath, function (moveErr) {
callback(moveErr, newPath);
});
});
});
}
function addKeysToFileStats(fieldNames, stats) {
var fileStats = [];
stats.forEach(function (item) {
var fileStat = new FileStat();
item.forEach(function (fieldValue, i) {
fileStat[fieldNames[i]] = fieldValue;
});
if (fileStat.path) {
fileStat.type = mime.lookup(fileStat.path);
}
fileStats.push(fileStat);
});
return fileStats;
}
function importFile(fileStat, tmpFile, username, callback) {
var oldPath;
oldPath = tmpFile.path;
readFile(oldPath, function (err, md5) {
if (err) {
fileStat.err = err;
callback(err, fileStat);
return;
}
// if we have an md5sum and they don't match, abandon ship
if (fileStat.md5 && fileStat.md5 !== md5) {
callback("MD5 sums don't match");
return;
}
fileStat.md5 = md5;
fileStat.genTmd5(function (error, tmd5) {
if (!error) {
fileStat.tmd5 = tmd5;
saveToFs(fileStat.md5, oldPath, function (fserr) {
if (fserr) {
// ignoring possible unlink error
fs.unlink(oldPath);
fileStat.err = "File did not save";
} else {
dbaccess.put(fileStat, username);
}
callback(fserr, fileStat);
});
}
});
});
}
function handleUpload(req, res, next) {
if (!req.form) {
return next();
}
req.form.complete(function (err, fields, files) {
var fileStats, bFirst;
fields.statsHeader = JSON.parse(fields.statsHeader);
fields.stats = JSON.parse(fields.stats);
fileStats = addKeysToFileStats(fields.statsHeader, fields.stats);
dbaccess.createViews(req.remoteUser, fileStats);
res.writeHead(200, {'Content-Type': 'application/json'});
// response as array
res.write("[");
bFirst = true;
function handleFileStat(next, fileStat) {
// this callback is synchronous
fileStat.checkMd5(function (qmd5Error, qmd5) {
function finishReq(err) {
console.log(fileStat);
fileStat.err = err;
// we only want to add a comma after the first one
if (!bFirst) {
res.write(",");
}
bFirst = false;
res.write(JSON.stringify(fileStat));
return next();
}
if (qmd5Error) {
return finishReq(qmd5Error);
}
importFile(fileStat, files[qmd5], req.remoteUser, finishReq);
});
}
fileStats.forEachAsync(handleFileStat).then(function () {
// end response array
res.end("]");
});
});
}
module.exports = handleUpload;
}());
| beatgammit/node-filesync | server/lib/routes/upload.js | JavaScript | mit | 3,981 |
/*"use strict";
var expect = require("expect.js"),
ShellController = require("../lib/shell-controller"),
testView = require("./test-shell-view");
describe("ShellController", function() {
var ctrl;
it("is defined", function() {
expect(ShellController).to.be.an("function");
});
describe("constructor", function() {
before(function() {
ctrl = new ShellController(testView);
});
it("create an object", function() {
expect(ctrl).to.be.an("object");
});
});
describe("on command event", function() {
before(function(done) {
ctrl.events.on("commandExecuted", done);
testView.invokeCommand("ls test/files --color");
});
after(function() {
testView.reset();
});
it("write commands output to view", function() {
var expected =
" <span style=\'color:rgba(170,170,170,255)\'>1.txt<br> 2.txt<br><br><br></span>";
expect(testView.content).to.be.equal(expected);
});
});
describe("findCommandRunner", function() {
var runner;
before(function(done) {
ctrl.findCommandRunner("ls test/files", function(cmdRunner) {
runner = cmdRunner;
done();
});
});
it("return a command runner", function() {
expect(runner.run).to.be.a("function");
});
});
});*/ | parroit/shell-js | test/shell-controller_test.js | JavaScript | mit | 1,229 |
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Database
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/mydb');
var index = require('./routes/index');
var buyer = require('./routes/buyer');
var seller = require('./routes/seller');
var products = require('./routes/products');
var app = express();
const ObjectID = mongo.ObjectID;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
req.ObjectID = ObjectID;
next();
});
app.use('/', index);
app.use('/buyer', buyer);
app.use('/seller', seller);
app.use('/products', products);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error.html', err);
});
module.exports = app;
| imRishabhGupta/smart-kart | app.js | JavaScript | mit | 1,740 |
/**
* @author yomboprime https://github.com/yomboprime
*
* GPUComputationRenderer, based on SimulationRenderer by zz85
*
* The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
* for each compute element (texel)
*
* Each variable has a fragment shader that defines the computation made to obtain the variable in question.
* You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader
* (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency.
*
* The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used
* as inputs to render the textures of the next frame.
*
* The render targets of the variables can be used as input textures for your visualization shaders.
*
* Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers.
* a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity...
*
* The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example:
* #DEFINE resolution vec2( 1024.0, 1024.0 )
*
* -------------
*
* Basic use:
*
* // Initialization...
*
* // Create computation renderer
* var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer );
*
* // Create initial state float textures
* var pos0 = gpuCompute.createTexture();
* var vel0 = gpuCompute.createTexture();
* // and fill in here the texture data...
*
* // Add texture variables
* var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 );
* var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 );
*
* // Add variable dependencies
* gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] );
* gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] );
*
* // Add custom uniforms
* velVar.material.uniforms.time = { value: 0.0 };
*
* // Check for completeness
* var error = gpuCompute.init();
* if ( error !== null ) {
* console.error( error );
* }
*
*
* // In each frame...
*
* // Compute!
* gpuCompute.compute();
*
* // Update texture uniforms in your visualization materials with the gpu renderer output
* myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture;
*
* // Do your rendering
* renderer.render( myScene, myCamera );
*
* -------------
*
* Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures)
* Note that the shaders can have multiple input textures.
*
* var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } );
* var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } );
*
* var inputTexture = gpuCompute.createTexture();
*
* // Fill in here inputTexture...
*
* myFilter1.uniforms.theTexture.value = inputTexture;
*
* var myRenderTarget = gpuCompute.createRenderTarget();
* myFilter2.uniforms.theTexture.value = myRenderTarget.texture;
*
* var outputRenderTarget = gpuCompute.createRenderTarget();
*
* // Now use the output texture where you want:
* myMaterial.uniforms.map.value = outputRenderTarget.texture;
*
* // And compute each frame, before rendering to screen:
* gpuCompute.doRenderTarget( myFilter1, myRenderTarget );
* gpuCompute.doRenderTarget( myFilter2, outputRenderTarget );
*
*
*
* @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
* @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
* @param {WebGLRenderer} renderer The renderer
*/
import {
Camera,
ClampToEdgeWrapping,
DataTexture,
FloatType,
HalfFloatType,
Mesh,
NearestFilter,
PlaneBufferGeometry,
RGBAFormat,
Scene,
ShaderMaterial,
WebGLRenderTarget
} from "./three.module.js";
var GPUComputationRenderer = function ( sizeX, sizeY, renderer ) {
this.variables = [];
this.currentTextureIndex = 0;
var scene = new Scene();
var camera = new Camera();
camera.position.z = 1;
var passThruUniforms = {
passThruTexture: { value: null }
};
var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );
var mesh = new Mesh( new PlaneBufferGeometry( 2, 2 ), passThruShader );
scene.add( mesh );
this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) {
var material = this.createShaderMaterial( computeFragmentShader );
var variable = {
name: variableName,
initialValueTexture: initialValueTexture,
material: material,
dependencies: null,
renderTargets: [],
wrapS: null,
wrapT: null,
minFilter: NearestFilter,
magFilter: NearestFilter
};
this.variables.push( variable );
return variable;
};
this.setVariableDependencies = function ( variable, dependencies ) {
variable.dependencies = dependencies;
};
this.init = function () {
if ( ! renderer.extensions.get( "OES_texture_float" ) &&
! renderer.capabilities.isWebGL2 ) {
return "No OES_texture_float support for float textures.";
}
if ( renderer.capabilities.maxVertexTextures === 0 ) {
return "No support for vertex shader textures.";
}
for ( var i = 0; i < this.variables.length; i ++ ) {
var variable = this.variables[ i ];
// Creates rendertargets and initialize them with input texture
variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );
// Adds dependencies uniforms to the ShaderMaterial
var material = variable.material;
var uniforms = material.uniforms;
if ( variable.dependencies !== null ) {
for ( var d = 0; d < variable.dependencies.length; d ++ ) {
var depVar = variable.dependencies[ d ];
if ( depVar.name !== variable.name ) {
// Checks if variable exists
var found = false;
for ( var j = 0; j < this.variables.length; j ++ ) {
if ( depVar.name === this.variables[ j ].name ) {
found = true;
break;
}
}
if ( ! found ) {
return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
}
}
uniforms[ depVar.name ] = { value: null };
material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
}
}
}
this.currentTextureIndex = 0;
return null;
};
this.compute = function () {
var currentTextureIndex = this.currentTextureIndex;
var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
for ( var i = 0, il = this.variables.length; i < il; i ++ ) {
var variable = this.variables[ i ];
// Sets texture dependencies uniforms
if ( variable.dependencies !== null ) {
var uniforms = variable.material.uniforms;
for ( var d = 0, dl = variable.dependencies.length; d < dl; d ++ ) {
var depVar = variable.dependencies[ d ];
uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;
}
}
// Performs the computation for this variable
this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );
}
this.currentTextureIndex = nextTextureIndex;
};
this.getCurrentRenderTarget = function ( variable ) {
return variable.renderTargets[ this.currentTextureIndex ];
};
this.getAlternateRenderTarget = function ( variable ) {
return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
};
function addResolutionDefine( materialShader ) {
materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )";
}
this.addResolutionDefine = addResolutionDefine;
// The following functions can be used to compute things manually
function createShaderMaterial( computeFragmentShader, uniforms ) {
uniforms = uniforms || {};
var material = new ShaderMaterial( {
uniforms: uniforms,
vertexShader: getPassThroughVertexShader(),
fragmentShader: computeFragmentShader
} );
addResolutionDefine( material );
return material;
}
this.createShaderMaterial = createShaderMaterial;
this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
sizeXTexture = sizeXTexture || sizeX;
sizeYTexture = sizeYTexture || sizeY;
wrapS = wrapS || ClampToEdgeWrapping;
wrapT = wrapT || ClampToEdgeWrapping;
minFilter = minFilter || NearestFilter;
magFilter = magFilter || NearestFilter;
var renderTarget = new WebGLRenderTarget( sizeXTexture, sizeYTexture, {
wrapS: wrapS,
wrapT: wrapT,
minFilter: minFilter,
magFilter: magFilter,
format: RGBAFormat,
type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? HalfFloatType : FloatType,
stencilBuffer: false,
depthBuffer: false
} );
return renderTarget;
};
this.createTexture = function () {
var a = new Float32Array( sizeX * sizeY * 4 );
var texture = new DataTexture( a, sizeX, sizeY, RGBAFormat, FloatType );
texture.needsUpdate = true;
return texture;
};
this.renderTexture = function ( input, output ) {
// Takes a texture, and render out in rendertarget
// input = Texture
// output = RenderTarget
passThruUniforms.passThruTexture.value = input;
this.doRenderTarget( passThruShader, output );
passThruUniforms.passThruTexture.value = null;
};
this.doRenderTarget = function ( material, output ) {
var currentRenderTarget = renderer.getRenderTarget();
mesh.material = material;
renderer.setRenderTarget( output );
renderer.render( scene, camera );
mesh.material = passThruShader;
renderer.setRenderTarget( currentRenderTarget );
};
// Shaders
function getPassThroughVertexShader() {
return "void main() {\n" +
"\n" +
" gl_Position = vec4( position, 1.0 );\n" +
"\n" +
"}\n";
}
function getPassThroughFragmentShader() {
return "uniform sampler2D passThruTexture;\n" +
"\n" +
"void main() {\n" +
"\n" +
" vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
"\n" +
" gl_FragColor = texture2D( passThruTexture, uv );\n" +
"\n" +
"}\n";
}
};
export { GPUComputationRenderer };
| ChenJiaH/chenjiah.github.io | js/GPUComputationRenderer.js | JavaScript | mit | 10,733 |
/*jshint node:true*/
/*global test, suite, setup, teardown*/
'use strict';
var assert = require('assert');
var tika = require('../');
suite('document tests', function() {
test('detect txt content-type', function(done) {
tika.type('test/data/file.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(typeof contentType, 'string');
assert.equal(contentType, 'text/plain');
done();
});
});
test('detect txt content-type and charset', function(done) {
tika.typeAndCharset('test/data/file.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(typeof contentType, 'string');
assert.equal(contentType, 'text/plain; charset=ISO-8859-1');
done();
});
});
test('extract from txt', function(done) {
tika.text('test/data/file.txt', function(err, text) {
assert.ifError(err);
assert.equal(typeof text, 'string');
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('extract meta from txt', function(done) {
tika.meta('test/data/file.txt', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.equal(typeof meta.resourceName[0], 'string');
assert.deepEqual(meta.resourceName, ['file.txt']);
assert.deepEqual(meta['Content-Type'], ['text/plain; charset=ISO-8859-1']);
assert.deepEqual(meta['Content-Encoding'], ['ISO-8859-1']);
done();
});
});
test('extract meta and text from txt', function(done) {
tika.extract('test/data/file.txt', function(err, text, meta) {
assert.ifError(err);
assert.equal(typeof text, 'string');
assert.equal(text, 'Just some text.\n\n');
assert.ok(meta);
assert.equal(typeof meta.resourceName[0], 'string');
assert.deepEqual(meta.resourceName, ['file.txt']);
assert.deepEqual(meta['Content-Type'], ['text/plain; charset=ISO-8859-1']);
assert.deepEqual(meta['Content-Encoding'], ['ISO-8859-1']);
done();
});
});
test('extract from extensionless txt', function(done) {
tika.text('test/data/extensionless/txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('extract from doc', function(done) {
tika.text('test/data/file.doc', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from doc', function(done) {
tika.meta('test/data/file.doc', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.doc']);
assert.deepEqual(meta['Content-Type'], ['application/msword']);
assert.deepEqual(meta['dcterms:created'], ['2013-12-06T21:15:26Z']);
done();
});
});
test('extract from extensionless doc', function(done) {
tika.text('test/data/extensionless/doc', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract from docx', function(done) {
tika.text('test/data/file.docx', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from docx', function(done) {
tika.meta('test/data/file.docx', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.docx']);
assert.deepEqual(meta['Content-Type'], ['application/vnd.openxmlformats-officedocument.wordprocessingml.document']);
assert.deepEqual(meta['Application-Name'], ['LibreOffice/4.1.3.2$MacOSX_x86 LibreOffice_project/70feb7d99726f064edab4605a8ab840c50ec57a']);
done();
});
});
test('extract from extensionless docx', function(done) {
tika.text('test/data/extensionless/docx', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from extensionless docx', function(done) {
tika.meta('test/data/extensionless/docx', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['docx']);
assert.deepEqual(meta['Content-Type'], ['application/vnd.openxmlformats-officedocument.wordprocessingml.document']);
assert.deepEqual(meta['Application-Name'], ['LibreOffice/4.1.3.2$MacOSX_x86 LibreOffice_project/70feb7d99726f064edab4605a8ab840c50ec57a']);
done();
});
});
test('extract from pdf', function(done) {
tika.text('test/data/file.pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('detect content-type of pdf', function(done) {
tika.type('test/data/file.pdf', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/pdf');
done();
});
});
test('extract meta from pdf', function(done) {
tika.meta('test/data/file.pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
test('extract from extensionless pdf', function(done) {
tika.text('test/data/extensionless/pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('extract meta from extensionless pdf', function(done) {
tika.meta('test/data/extensionless/pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
test('extract from protected pdf', function(done) {
tika.text('test/data/protected/file.pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('extract meta from protected pdf', function(done) {
tika.meta('test/data/protected/file.pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
});
suite('partial document extraction tests', function() {
test('extract from long txt', function(done) {
tika.text('test/data/big/file.txt', { maxLength: 10 }, function(err, text) {
assert.ifError(err);
assert.equal(text.length, 10);
assert.equal(text, 'Lorem ipsu');
done();
});
});
test('extract from pdf', function(done) {
tika.text('test/data/file.pdf', { maxLength: 10 }, function(err, text) {
assert.ifError(err);
assert.equal(text.length, 10);
assert.equal(text.trim(), 'Just some');
done();
});
});
});
suite('obscure document tests', function() {
test('extract from Word 2003 XML', function(done) {
tika.text('test/data/obscure/word2003.xml', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Just some text.'));
assert.ok(-1 === text.indexOf('<?xml'));
done();
});
});
});
suite('structured data tests', function() {
test('extract from plain XML', function(done) {
tika.text('test/data/structured/plain.xml', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Just some text.'));
assert.ok(-1 === text.indexOf('<?xml'));
done();
});
});
});
suite('image tests', function() {
test('extract from png', function(done) {
tika.text('test/data/file.png', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract from extensionless png', function(done) {
tika.text('test/data/extensionless/png', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract from gif', function(done) {
tika.text('test/data/file.gif', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract meta from gif', function(done) {
tika.meta('test/data/file.gif', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.gif']);
assert.deepEqual(meta['Content-Type'], ['image/gif']);
assert.deepEqual(meta['Dimension ImageOrientation'], ['Normal']);
done();
});
});
test('extract from extensionless gif', function(done) {
tika.text('test/data/extensionless/gif', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract meta from extensionless gif', function(done) {
tika.meta('test/data/extensionless/gif', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['gif']);
assert.deepEqual(meta['Content-Type'], ['image/gif']);
assert.deepEqual(meta['Dimension ImageOrientation'], ['Normal']);
done();
});
});
});
suite('non-utf8 encoded document tests', function() {
test('extract Windows Latin 1 text', function(done) {
tika.text('test/data/nonutf8/windows-latin1.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Algún pequeño trozo de texto.\n\n');
done();
});
});
test('detect Windows Latin 1 text charset', function(done) {
tika.charset('test/data/nonutf8/windows-latin1.txt', function(err, charset) {
assert.ifError(err);
assert.equal(typeof charset, 'string');
assert.equal(charset, 'ISO-8859-1');
done();
});
});
test('detect Windows Latin 1 text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/windows-latin1.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=ISO-8859-1');
done();
});
});
test('extract UTF-16 English-language text', function(done) {
tika.text('test/data/nonutf8/utf16-english.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('detect UTF-16 English-language text charset', function(done) {
tika.charset('test/data/nonutf8/utf16-english.txt', function(err, charset) {
assert.ifError(err);
assert.equal(charset, 'UTF-16LE');
done();
});
});
test('detect UTF-16 English-language text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/utf16-english.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=UTF-16LE');
done();
});
});
test('extract UTF-16 Chinese (Simplified) text', function(done) {
tika.text('test/data/nonutf8/utf16-chinese.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, '\u53ea\u662f\u4e00\u4e9b\u6587\u5b57\u3002\n\n');
done();
});
});
test('detect UTF-16 Chinese (Simplified) text charset', function(done) {
tika.charset('test/data/nonutf8/utf16-chinese.txt', function(err, charset) {
assert.ifError(err);
assert.equal(charset, 'UTF-16LE');
done();
});
});
test('detect UTF-16 Chinese (Simplified) text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/utf16-chinese.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=UTF-16LE');
done();
});
});
});
suite('archive tests', function() {
test('extract from compressed archive', function(done) {
tika.text('test/data/archive/files.zip', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'file1.txt\nSome text 1.\n\n\n\n\nfile2.txt\nSome text 2.\n\n\n\n\nfile3.txt\nSome text 3.');
done();
});
});
test('extract from compressed zlib archive', function(done) {
tika.text('test/data/archive/files.zlib', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'files\nSome text 1.\nSome text 2.\nSome text 3.');
done();
});
});
test('detect compressed archive content-type', function(done) {
tika.type('test/data/archive/files.zip', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/zip');
done();
});
});
test('extract from twice compressed archive', function(done) {
tika.text('test/data/archive/files-files.zip', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'file4.txt\nSome text 4.\n\n\n\n\nfile5.txt\nSome text 5.\n\n\n\n\nfile6.txt\nSome text 6.\n\n\n\n\nfiles.zip\n\n\nfile1.txt\n\nSome text 1.\n\n\n\n\n\n\n\nfile2.txt\n\nSome text 2.\n\n\n\n\n\n\n\nfile3.txt\n\nSome text 3.');
done();
});
});
});
suite('encrypted doc tests', function() {
test('detect encrypted pdf content-type', function(done) {
tika.type('test/data/encrypted/file.pdf', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/pdf');
done();
});
});
test('detect encrypted doc content-type', function(done) {
tika.type('test/data/encrypted/file.doc', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/msword');
done();
});
});
test('specify password to decrypt document', function(done) {
tika.text('test/data/encrypted/file.pdf', {
password: 'password'
}, function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
});
suite('error handling tests', function() {
test('extract from encrypted doc', function(done) {
tika.text('test/data/encrypted/file.doc', function(err, text) {
assert.ok(err);
assert.ok(-1 !== err.toString().indexOf('EncryptedDocumentException: Cannot process encrypted word file'));
done();
});
});
test('extract from encrypted pdf', function(done) {
tika.text('test/data/encrypted/file.pdf', function(err, text) {
assert.ok(err);
assert.ok(-1 !== err.toString().indexOf('Unable to process: document is encrypted'));
done();
});
});
});
suite('http extraction tests', function() {
test('extract from pdf over http', function(done) {
tika.text('http://www.ohchr.org/EN/UDHR/Documents/UDHR_Translations/eng.pdf', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Universal Declaration of Human Rights'));
done();
});
});
});
suite('ftp extraction tests', function() {
test('extract from text file over ftp', function(done) {
tika.text('ftp://ftp.ed.ac.uk/INSTRUCTIONS-FOR-USING-THIS-SERVICE', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('This service is managed by Information Services'));
done();
});
});
});
suite('language detection tests', function() {
test('detect English text', function(done) {
tika.language('This just some text in English.', function(err, language, reasonablyCertain) {
assert.ifError(err);
assert.equal(typeof language, 'string');
assert.equal(typeof reasonablyCertain, 'boolean');
assert.equal(language, 'en');
done();
});
});
});
| ICIJ/node-tika | test/tika.js | JavaScript | mit | 14,883 |
/**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import './index.scss'
import React, { Component } from 'react'
// import { Grid, Col, Row } from 'react-bootstrap';
export default class IndexPage extends Component {
render() {
return (
<div className="top-page">
<div>
<img
className="top-image"
src="/cover2.jpg"
width="100%"
alt="cover image"
/>
</div>
<div className="top-page--footer">
The source code of this website is available
<a
href="https://github.com/odoruinu/odoruinu.net-pug"
target="_blank"
rel="noopener noreferrer"
>
here on GitHub
</a>
.
</div>
</div>
)
}
}
| odoruinu/odoruinu.net-pug | pages/index.js | JavaScript | mit | 908 |
import {extend} from 'lodash';
export default class User {
/**
* The User class
* @class
* @param {Object} user
* @return {Object} A User
*/
constructor(user) {
extend(this, user);
console.log(this);
}
}
| mpaarating/sports-thing-web | client/app/users/models/user.js | JavaScript | mit | 236 |
exports._buildExclamationKeyObject = function (tuples) {
var valueMap = {};
tuples.forEach(function (tuple) {
valueMap['!' + tuple.value0] = tuple.value1;
});
return valueMap;
};
var templatePattern = /\$\{([^}]+)\}/g;
exports._getTemplateVars = function (str) {
return (str.match(templatePattern) || []).map(function (str) {
return str.substring(2, str.length - 1);
});
};
| LiamGoodacre/purescript-template-strings | src/Data/TemplateString/TemplateString.js | JavaScript | mit | 397 |
/**
* @overview
* API handler action creator
* Takes a key-value -pair representing the event to handle as key and its respective
* handler function as the value.
*
* Event-to-URL mapping is done in {@link ApiEventPaths}.
*
* @since 0.2.0
* @version 0.3.0
*/
import { Seq, Map } from 'immutable';
import { createAction } from 'redux-actions';
import { Internal } from '../records';
import { ApiEventPaths } from '../constants';
import * as apiHandlerFns from '../actions/kcsapi';
/**
* Ensure that the action handlers are mapped into {@link ApiHandler} records.
* @type {Immutable.Iterable<any, any>}
* @since 0.2.0
*/
export const handlers = Seq.Keyed(ApiEventPaths)
.flatMap((path, event) =>
Map.of(event, new Internal.ApiHandler({ path, event, handler: apiHandlerFns[event] })));
/**
* A non-`Seq` version of the @see findEventSeq function.
* @param {string} findPath
* @returns {string}
* @since 0.2.0
* @version 0.3.0
*/
export const findEvent = (findPath) => {
const pathRegex = new RegExp(`^${findPath}$`);
return ApiEventPaths.findKey((path) => pathRegex.test(path));
};
/**
* Create a `Seq` of action handlers that is in a usable form for the Redux application.
* @type {Immutable.Iterable<any, any>}
* @since 0.2.0
*/
export const actionHandlers = Seq.Keyed(handlers)
.flatMap((handlerRecord, event) =>
Map.of(event, createAction(event, handlerRecord.handler)));
| rensouhou/dockyard-app | app/actions/api-actions.js | JavaScript | mit | 1,532 |
// xParentN 2, Copyright 2005-2007 Olivier Spinelli
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xParentN(e, n)
{
while (e && n--) e = e.parentNode;
return e;
}
| sambaker/awe-core | test/x/lib/xparentn.js | JavaScript | mit | 230 |
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Navigator,
ScrollView,
ListView,
} from 'react-native'
import NavigationBar from 'react-native-navbar';
var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?';
class GroupDetails extends Component {
constructor(props, context) {
super(props, context);
this.state = {
loggedIn: true,
loaded: false,
rando: "a",
};
this.fetchData();
}
backOnePage () {
this.props.navigator.pop();
}
renderRide (ride) {
return (
<View>
<Text style={styles.title}>{ride.title}</Text>
</View>
);
}
componentDidMount () {
this.fetchData();
}
toQueryString(obj) {
return obj ? Object.keys(obj).sort().map(function (key) {
var val = obj[key];
if (Array.isArray(val)) {
return val.sort().map(function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
}).join('&');
}
return encodeURIComponent(key) + '=' + encodeURIComponent(val);
}).join('&') : '';
}
fetchData() {
console.log(this.props.group_info.pk);
fetch(REQUEST_URL + this.toQueryString({"group": this.props.group_info.pk}))
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
this.setState({
group_info: responseData,
loaded: true,
});
})
.done();
}
render () {
if (!this.state.loaded) {
return (<View>
<Text>Loading!</Text>
</View>);
}
else if (this.state.loggedIn) {
console.log(this.props.group_info.fields);
console.log(this.state);
console.log(this.state.group_info[0]);
const backButton = {
title: "Back",
handler: () => this.backOnePage(),
};
return (
<ScrollView>
<NavigationBar
style={{ backgroundColor: "white", }}
leftButton={backButton}
statusBar={{ tintColor: "white", }}
/>
<Text style={styles.headTitle}>
Group Name: {this.state.group_info.name}
</Text>
<Text style={styles.headerOtherText}>Group Leader: {this.state.group_info.admin}</Text>
<Text style={styles.headerOtherText}>{this.state.group_info.users} people in this group.</Text>
</ScrollView>
);
} else {
this.props.navigator.push({id: "LoginPage", name:"Index"})
}
}
}
var styles = StyleSheet.create({
headerOtherText : {
color: 'black',
fontSize: 15 ,
fontWeight: 'normal',
fontFamily: 'Helvetica Neue',
alignSelf: "center",
},
headTitle: {
color: 'black',
fontSize: 30 ,
fontWeight: 'normal',
fontFamily: 'Helvetica Neue',
alignSelf: "center",
},
header: {
marginTop: 20,
flex: 1,
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
},
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ff7f50',
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
backgroundColor: '#0000ff',
paddingBottom: 200,
},
});
module.exports = GroupDetails;
| adnanhemani/RideApp | App/GroupDetails.js | JavaScript | mit | 3,798 |
process.stderr.write('Test'); | patrick-steele-idem/child-process-promise | test/fixtures/stderr.js | JavaScript | mit | 29 |
(function () {
'use strict';
angular
.module('app')
.service('UploadUserLogoService', UploadUserLogoService);
function UploadUserLogoService($http, $log, TokenService, UserService, $rootScope) {
this.uploadImage = uploadImage;
////
/**
* Upload Image
* @description For correct uploading we must send FormData object
* With 'transformRequest: angular.identity' prevents Angular to do anything on our data (like serializing it).
* By setting ‘Content-Type’: undefined, the browser sets the Content-Type to multipart/form-data for us
* and fills in the correct boundary.
* Manually setting ‘Content-Type’: multipart/form-data will fail to fill in the boundary parameter of the request
* All this for correct request typing and uploading
* @param formdata
* @param callback
*/
function uploadImage(formdata, callback) {
let userToken = TokenService.get();
let request = {
method: 'POST',
url: '/api/user/avatar',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Autorization': userToken
},
data: formdata
};
let goodResponse = function successCallback(response) {
let res = response.data;
if (res.success) {
let currentUser = UserService.get();
currentUser.avatarUrl = res.data.avatarUrl;
UserService.save(currentUser);
}
if (callback && typeof callback === 'function') {
callback(res);
}
};
let badResponse = function errorCallback(response) {
$log.debug('Bad, some problems ', response);
if (callback && typeof callback === 'function') {
callback(response);
}
};
$http(request).then(goodResponse, badResponse);
}
}
})(); | royalrangers-ck/rr-web-app | app/utils/upload.user.logo/upload.user.logo.service.js | JavaScript | mit | 2,187 |
angular.module('tips.tips').controller('TipsController', ['$scope', '$routeParams', '$location', 'Global', 'Tips', function ($scope, $routeParams, $location, Global, Tips) {
$scope.global = Global;
$scope.createTip = function () {
var tips = new Tips({
text: this.text,
likes: this.likes,
category: this.category
});
tips.$save(function (response) {
$location.path("/");
});
this.title = "";
};
$scope.showTip = function () {
Tips.query(function (tips) {
$scope.tips = tips;
tips.linkEdit = 'tips/edit/';
// show tips size
function Settings (minLikes, maxLikes) {
var that = this;
that.size = {
min: 26,
max: 300
};
that.maxLikes = maxLikes;
that.minLikes = tips[0].likes;
that.valueOfdivision = (function(){
return (that.size.max - that.size.min)/that.maxLikes
})()
}
function startIsotope(){
var el = $('#isotope-container');
el.isotope({
itemSelector: '.isotope-element',
layoutMode: 'fitRows',
sortBy: 'number',
sortAscending: true,
});
return el;
}
var maxLikes = 0;
var minLikes = 0;
for (var i = 0; i < tips.length; i++) {
if(maxLikes <= tips[i].likes)maxLikes = tips[i].likes;
if(minLikes >= tips[i].likes)minLikes = tips[i].likes;
};
tips.settingsView = new Settings(minLikes, maxLikes);
$scope.$watch('tips', function () {
$scope.$evalAsync(function () {
var isotope = startIsotope();
});
})
});
};
$scope.updateTip = function (tip) {
var tip = new Tips(tip);
tip.$update(tip, function(){
console.log("update updateTip: ", tip._id);
}, function(){
console.warn("error updateTip:", tip._id);
});
};
$scope.getTip = function () {
Tips.query(function (tip) {
$scope.tip = tip;
console.log(tip);
});
};
$scope.editTip = function(tip){
console.log("edit tip");
};
}]) | Arsey/tips-of-the-day | public/js/controllers/tips.js | JavaScript | mit | 2,505 |
import apiConfig from './MovieDBConfig';
import TmdbApi from 'moviedb-api';
var api = new TmdbApi({
consume: false,
apiKey: apiConfig.apiKey
});
const makeAndList = (list) => {
return list.map(item => item.value).join();
};
export const getGenres = (input='', callback) => {
api.request('/genre/movie/list', 'GET')
.then(res => {
return res.genres.map(item => {
return {label: item.name, value: item.id};
})
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const getKeywords = (input='', callback) => {
api.request('/search/keyword', 'GET', {query: input})
.then(res => {
return res.results.map(item => {
return {label: item.name, value: item.id};
});
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const getActors = (input='', callback) => {
api.request('/search/person', 'GET', {query: input})
.then(res => {
return res.results.map(item => {
return {label: item.name, value: item.id};
});
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const discover = (genres=null, keywords=null, actors, minYear, maxYear, page=1) => {
let g = genres ? makeAndList(genres) : null;
let k = keywords ? makeAndList(keywords) : null;
let a = actors ? makeAndList(actors) : null;
return api.request('/discover/movie', 'GET', {
with_genres: g,
with_keywords: k,
with_cast: a,
"release_date.gte": minYear,
"release_date.lte": maxYear,
page
})
.then(res => res)
};
export const getVideos = (id, language='en') => {
return api.request(`/movie/${id}/videos`, 'GET', {language})
};
export const getMovieKeywords = (id, language='en') => {
return api.request(`/movie/${id}/keywords`, 'GET', {language})
};
export const discoverWithVideo = (genres=null, keywords=null, actors, minYear, maxYear) => {
return discover(genres, keywords, actors, minYear, maxYear)
.then(res => {
return Promise.all(
res.results.map(item => getVideos(item.id)
.then(videos => videos.results[0])
)
).then(list => {
return {
...res,
results: res.results.map((item, index) => {
item.youtube = list[index];
return item;
})
}
})
})
};
export const getDetails = (id, language='en') => {
return api.request(`/movie/${id}`, 'GET', {language, append_to_response: "keywords,videos"})
};
| arddor/MovieAdvisor | app/utils/api.js | JavaScript | mit | 2,618 |
const excludedTables = ["blacklist", "musicCache", "timedEvents"];
const statPoster = require("../../modules/statPoster.js");
module.exports = async guild => {
let tables = await r.tableList().run();
for(let table of tables) {
let indexes = await r.table(table).indexList().run();
if(~indexes.indexOf("guildID")) r.table(table).getAll(guild.id, { index: "guildID" }).delete().run();
else r.table(table).filter({ guildID: guild.id }).delete().run();
}
if(bot.config.bot.serverChannel) {
let owner = bot.users.get(guild.ownerID);
let botCount = guild.members.filter(member => member.bot).length;
let botPercent = ((botCount / guild.memberCount) * 100).toFixed(2);
let userCount = guild.memberCount - botCount;
let userPercent = ((userCount / guild.memberCount) * 100).toFixed(2);
let content = "❌ LEFT GUILD ❌\n";
content += `Guild: ${guild.name} (${guild.id})\n`;
content += `Owner: ${owner.username}#${owner.discriminator} (${owner.id})\n`;
content += `Members: ${guild.memberCount} **|** `;
content += `Users: ${userCount} (${userPercent}%) **|** `;
content += `Bots: ${botCount} (${botPercent}%)`;
try {
await bot.createMessage(bot.config.bot.serverChannel, content);
} catch(err) {
console.error(`Failed to send message to server log: ${err.message}`);
}
}
statPoster();
};
| minemidnight/oxyl | src/bot/listeners/on/guildDelete.js | JavaScript | mit | 1,331 |
import { computed, get } from '@ember/object';
import { getOwner } from '@ember/application';
import { deprecate } from '@ember/debug';
export function ability(abilityName, resourceName) {
deprecate(
'Using ability() computed property is deprecated. Use getters and Can service directly.',
false,
{
for: 'ember-can',
since: {
enabled: '4.0.0',
},
id: 'ember-can.deprecate-ability-computed',
until: '5.0.0',
}
);
resourceName = resourceName || abilityName;
return computed(resourceName, function () {
let canService = getOwner(this).lookup('service:abilities');
return canService.abilityFor(abilityName, get(this, resourceName));
}).readOnly();
}
| minutebase/ember-can | addon/computed.js | JavaScript | mit | 721 |
/* global requirejs, require */
/*jslint node: true */
'use strict';
import Ember from 'ember';
import _keys from 'lodash/object/keys';
/*
This function looks through all files that have been loaded by Ember CLI and
finds the ones under /mirage/[factories, fixtures, scenarios, models]/, and exports
a hash containing the names of the files as keys and the data as values.
*/
export default function(prefix) {
let modules = ['factories', 'fixtures', 'scenarios', 'models', 'serializers'];
let mirageModuleRegExp = new RegExp(`^${prefix}/mirage/(${modules.join("|")})`);
let modulesMap = modules.reduce((memo, name) => {
memo[name] = {};
return memo;
}, {});
_keys(requirejs.entries).filter(function(key) {
return mirageModuleRegExp.test(key);
}).forEach(function(moduleName) {
if (moduleName.match('.jshint')) { // ignore autogenerated .jshint files
return;
}
let moduleParts = moduleName.split('/');
let moduleType = moduleParts[moduleParts.length - 2];
let moduleKey = moduleParts[moduleParts.length - 1];
Ember.assert('Subdirectories under ' + moduleType + ' are not supported',
moduleParts[moduleParts.length - 3] === 'mirage');
if (moduleType === 'scenario'){
Ember.assert('Only scenario/default.js is supported at this time.',
moduleKey !== 'default');
}
let module = require(moduleName, null, null, true);
if (!module) { throw new Error(moduleName + ' must export a ' + moduleType); }
let data = module['default'];
modulesMap[moduleType][moduleKey] = data;
});
return modulesMap;
}
| ballPointPenguin/ember-cli-mirage | addon/utils/read-modules.js | JavaScript | mit | 1,627 |
console.log("VS: loading content_script.js..." + new Date());
// Check if the communication between page and background.js has broken.
var last_message_time = new Date().getTime();
new Promise((resolve) => setTimeout(resolve, 1000000)).then(() => {
var now = new Date().getTime();
if (now - last_message_time > 500000) {
sendAlert('Not having message from background for at least 500s, force reloading');
reloadPage();
}
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// Update timestamp first.
last_message_time = new Date().getTime();
console.log("VS: received data from content_script.js" + new Date());
console.log(request);
var action = request["action"];
takeAction(action, request);
});
var already_logging_in = false;
function takeAction(action, request) {
var url = window.location.href;
console.log("VS: Taking action: " + action + " in " + url);
if (action === ACTION_FOR_HOMEPAGE) {
homePage(request);
} else if (action === ACTION_FOR_LOGIN_PAGE) {
loginPage(request);
} else if (action === ACTION_FOR_ASYNC_LOGIN) {
loginPage(request);
} else if (action === ACTION_FOR_DASHBOARD_PAGE) {
dashboardPage(request);
} else {
// Other cases.
console.log("VS: unknown action:" + new Date());
console.log(action);
return;
}
}
function dashboardPage(request) {
console.log("VS: In dashboard page" + new Date());
//var val = $('[data-reactid=".0.0.3.0.0.0.0.0.1.0.0.1.0"]');
//if (val) {
// var ts = new Date().getTime();
// var amount = val.text();
// if (!amount) {
// console.log("Failed to parse data from html page. " + new Date());
// } else {
// saveGenerationData({'amount': amount, 'time': ts});
// }
//} else {
// sendAlert('Failed to read data from Dashboard page' + window.location.href);
//}
//console.log("VS: setting to reload page in 60s: " + new Date());
//window.setInterval(function() {
console.log("VS: polling account data" + new Date());
$.ajax({url: "/api/fusion/accounts"}).done(function(msg) {
console.log("VS: got account data" + new Date());
var j = msg;
if (typeof(j) === "object" && 'accounts' in j) {
console.log(j['accounts']);
var acct = j['accounts'][0]['account_no'];
var newUrl = '/api/fusion/accounts/' + acct;
console.log("VS: polling account detail data" + new Date());
$.ajax({url: newUrl}).done(function(msg) {
console.log("VS: got account detail data" + new Date());
var j = msg;
if (typeof(j) === "object" && 'energyToday' in j) {
var ts = new Date().getTime();
var amount = j['energyToday'] / 1000.0;
console.log("VS: saveing energy data" + new Date());
saveGenerationData({'time': ts, 'amount': amount});
return;
}
sendAlert("Failed parse detailed account info from AJAX for: " + textStatus);
reloadPage();
}).fail(function(jqXHR, textStatus) {
sendAlert("Request failed for loading detailed account info from AJAX for: " + textStatus);
reloadPage();
});
return;
}
sendAlert('Failed to parse account data');
reloadPage();
}).fail(function(jqXHR, textStatus) {
sendAlert("Request failed for loading accounts AJAX for: " + textStatus);
reloadPage();
});
//}, 60000);
}
function loginPage(request) {
if (request) {
asyncLogin(request);
} else {
chrome.runtime.sendMessage({"action": ACTION_FOR_ASYNC_LOGIN});
}
}
function homePage(request) {
var links = $('A');
for (var i in links) {
var link = links[i];
if (link.href == LOGIN_PAGE) {
link.click();
}
}
}
function asyncLogin(request) {
if (already_logging_in) {
console.log("VS: already logging in. This is possible, ignoring.." + new Date());
return;
}
already_logging_in = true;
console.log("VS: gettting new data to login" + new Date());
console.log(request);
context = request['data'];
if ($("INPUT[data-reactid='.0.0.0.0.0.1.1']").val(context.username).length > 0
&& $("INPUT[data-reactid='.0.0.0.0.0.2.0']").val(context.passwd).length > 0) {
$("BUTTON[data-reactid='.0.0.0.0.0.4.0']").click();
new Promise((resolve) => setTimeout(resolve, 100000)).then(() => {
sendAlert('Login failed for username' + context.username + ' and passwd: ' + context.passwd);
});
}
$('.email-input.js-initial-focus').val(context.username);
$('.js-password-field').val(context.passwd);
new Promise((resolve) => setTimeout(resolve, 1500)).then(() => {
$('button.submit').click();
});
}
var action = urlToAction(window.location.href);
console.log("VS: intercepted action:" + action + " at " + new Date());
if (action != '') {
takeAction(action, null);
}
console.log("VS: loaded:" + window.location.href);
console.log("VS: registered on load event here handler in content_script.js" + new Date());
| redisliu/chrome-extensions | vivintsolar-monitor/content_script.js | JavaScript | mit | 5,501 |
var namespace_kluster_kite_1_1_large_objects_1_1_tests =
[
[ "ParcelsTest", "class_kluster_kite_1_1_large_objects_1_1_tests_1_1_parcels_test.html", "class_kluster_kite_1_1_large_objects_1_1_tests_1_1_parcels_test" ]
]; | KlusterKite/KlusterKite | Docs/Doxygen/html/namespace_kluster_kite_1_1_large_objects_1_1_tests.js | JavaScript | mit | 222 |
(function() {
angular.module('starter.controllers').controller('DetailController', DetailController);
DetailController.$inject = ['CarService', '$stateParams'];
function DetailController (CarService, $stateParams) {
var vm = this;
CarService.getCar($stateParams.id).$promise.then(function(data) {
vm.car = data;
CarService.setCurrentCar(data);
}
);
}
})();
| jyen/corporate-challenge | mobile/www/app/car/detail/detail.controller.js | JavaScript | mit | 401 |
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.DepthPassPlugin = function () {
this.enabled = false;
this.renderTarget = null;
var _gl,
_renderer,
_lights, _webglObjects, _webglObjectsImmediate,
_depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
_frustum = new THREE.Frustum(),
_projScreenMatrix = new THREE.Matrix4(),
_renderList = [];
this.init = function ( renderer, lights, webglObjects, webglObjectsImmediate ) {
_gl = renderer.context;
_renderer = renderer;
_lights = lights;
_webglObjects = webglObjects;
_webglObjectsImmediate = webglObjectsImmediate;
var depthShader = THREE.ShaderLib[ "depthRGBA" ];
var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
_depthMaterial = new THREE.ShaderMaterial( {
fragmentShader: depthShader.fragmentShader,
vertexShader: depthShader.vertexShader,
uniforms: depthUniforms
} );
_depthMaterialMorph = new THREE.ShaderMaterial( {
fragmentShader: depthShader.fragmentShader,
vertexShader: depthShader.vertexShader,
uniforms: depthUniforms,
morphTargets: true
} );
_depthMaterialSkin = new THREE.ShaderMaterial( {
fragmentShader: depthShader.fragmentShader,
vertexShader: depthShader.vertexShader,
uniforms: depthUniforms,
skinning: true
} );
_depthMaterialMorphSkin = new THREE.ShaderMaterial( {
fragmentShader: depthShader.fragmentShader,
vertexShader: depthShader.vertexShader,
uniforms: depthUniforms,
morphTargets: true,
skinning: true
} );
_depthMaterial._shadowPass = true;
_depthMaterialMorph._shadowPass = true;
_depthMaterialSkin._shadowPass = true;
_depthMaterialMorphSkin._shadowPass = true;
};
this.render = function ( scene, camera ) {
if ( ! this.enabled ) return;
this.update( scene, camera );
};
this.update = function ( scene, camera ) {
var i, il, j, jl, n,
program, buffer, material,
webglObject, object, light,
renderList,
fog = null;
// set GL state for depth map
_gl.clearColor( 1, 1, 1, 1 );
_gl.disable( _gl.BLEND );
_renderer.state.setDepthTest( true );
// update scene
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
// update camera matrices and frustum
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// render depth map
_renderer.setRenderTarget( this.renderTarget );
_renderer.clear();
// set object matrices & frustum culling
_renderList.length = 0;
projectObject(scene, scene, camera);
// render regular objects
var objectMaterial, useMorphing, useSkinning;
for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
webglObject = _renderList[ j ];
object = webglObject.object;
buffer = webglObject.buffer;
// todo: create proper depth material for particles
if ( object instanceof THREE.PointCloud && ! object.customDepthMaterial ) continue;
objectMaterial = getObjectMaterial( object );
if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
if ( object.customDepthMaterial ) {
material = object.customDepthMaterial;
} else if ( useSkinning ) {
material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
} else if ( useMorphing ) {
material = _depthMaterialMorph;
} else {
material = _depthMaterial;
}
if ( buffer instanceof THREE.BufferGeometry ) {
_renderer.renderBufferDirect( camera, _lights, fog, material, buffer, object );
} else {
_renderer.renderBuffer( camera, _lights, fog, material, buffer, object );
}
}
// set matrices and render immediate objects
for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) {
webglObject = _webglObjectsImmediate[ j ];
object = webglObject.object;
if ( object.visible ) {
object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
_renderer.renderImmediateObject( camera, _lights, fog, _depthMaterial, object );
}
}
// restore GL state
var clearColor = _renderer.getClearColor(),
clearAlpha = _renderer.getClearAlpha();
_gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
_gl.enable( _gl.BLEND );
};
function projectObject(scene, object,camera) {
if ( object.visible ) {
var webglObjects = _webglObjects[object.id];
if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
for (var i = 0, l = webglObjects.length; i < l; i ++) {
var webglObject = webglObjects[i];
object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
_renderList.push(webglObject);
}
}
for (var i = 0, l = object.children.length; i < l; i ++) {
projectObject(scene, object.children[i], camera);
}
}
}
// For the moment just ignore objects that have multiple materials with different animation methods
// Only the first material will be taken into account for deciding which depth material to use
function getObjectMaterial( object ) {
return object.material instanceof THREE.MeshFaceMaterial
? object.material.materials[ 0 ]
: object.material;
}
};
| BenediktS/three.js | examples/js/renderers/plugins/DepthPassPlugin.js | JavaScript | mit | 5,549 |
import path from 'path'
let { context, file, mocha, options } = module.parent.context
let { it } = context
context.it = function (name, callback) {
if (callback) {
return it(...arguments);
} else {
callback = name
name = path.basename(file, '.js')
}
}
| Capt-Slow/wdio-mocha-framework | test/fixtures/tests.options.compilers.js | JavaScript | mit | 264 |
'use strict'
const { EventEmitter } = require('events')
const { Multiaddr } = require('multiaddr')
/**
* @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener
*/
/**
* @param {import('../')} libp2p
* @returns {Listener} a transport listener
*/
module.exports = (libp2p) => {
const listeningAddrs = new Map()
/**
* Add swarm handler and listen for incoming connections
*
* @param {Multiaddr} addr
* @returns {Promise<void>}
*/
async function listen (addr) {
const addrString = String(addr).split('/p2p-circuit').find(a => a !== '')
const relayConn = await libp2p.dial(new Multiaddr(addrString))
const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit')
listeningAddrs.set(relayConn.remotePeer.toB58String(), relayedAddr)
listener.emit('listening')
}
/**
* Get fixed up multiaddrs
*
* NOTE: This method will grab the peers multiaddrs and expand them such that:
*
* a) If it's an existing /p2p-circuit address for a specific relay i.e.
* `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the
* address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where
* `QmPeer` is this peers id
* b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit
* addr, such when dialing over a relay with this address, it will create the circuit using
* the encapsulated transport address. This is useful when for example, a peer should only
* be dialed over TCP rather than any other transport
*
* @returns {Multiaddr[]}
*/
function getAddrs () {
const addrs = []
for (const addr of listeningAddrs.values()) {
addrs.push(addr)
}
return addrs
}
/** @type Listener */
const listener = Object.assign(new EventEmitter(), {
close: () => Promise.resolve(),
listen,
getAddrs
})
// Remove listeningAddrs when a peer disconnects
libp2p.connectionManager.on('peer:disconnect', (connection) => {
const deleted = listeningAddrs.delete(connection.remotePeer.toB58String())
if (deleted) {
// Announce listen addresses change
listener.emit('close')
}
})
return listener
}
| libp2p/js-libp2p | src/circuit/listener.js | JavaScript | mit | 2,218 |
(function() {
$(function() {
$('.tooltip-examples a, .tooltip-paragraph-examples a').tooltip({
animation: false
});
$('.top-sign-in').on("click", function(e) {
$('.login-box').fadeIn("fast");
return false;
});
$('.login-box-close').on("click", function(e) {
$(this).closest(".login-box").fadeOut("fast");
return false;
});
prettyPrint();
$(".slider-browser-center").animate({
bottom: $(".slider-browser-center").data('position-bottom')
}, "fast", function() {
return $(".slider-browser-left").animate({
bottom: $(".slider-browser-left").data('position-bottom')
}, "fast", function() {
return $(".slider-browser-right").animate({
bottom: $(".slider-browser-right").data('position-bottom')
}, "fast");
});
});
$('.carousel').carousel({
interval: false
});
return $('a[data-toggle="testimonial"]').on("click", function(e) {
$(this).closest('.testimonials-users').find('a[data-toggle="testimonial"]').removeClass("active");
$(this).addClass("active");
$('.testimonials-speech').removeClass('active');
$('.testimonials-speech' + $(this).attr('href')).addClass('active');
return false;
});
});
$("body").on("touchstart.dropdown", ".dropdown-menu", function(e) {
return e.stopPropagation();
});
return $(document).on("click", ".dropdown-menu a", function() {
return document.location = $(this).attr("href");
});
}).call(this);
| lifeandscience/experimonth.lifeandscience.org | public/venera/js/main.js | JavaScript | mit | 1,521 |
var common = require('../common');
var connection = common.createConnection({port: common.fakeServerPort});
var assert = require('assert');
var server = common.createFakeServer();
var connectErr;
server.listen(common.fakeServerPort, function(err) {
if (err) throw err;
connection.connect(function(err) {
connectErr = err;
server.destroy();
});
});
server.on('connection', function(incomingConnection) {
var errno = 1130; // ER_HOST_NOT_PRIVILEGED
incomingConnection.deny('You suck.', errno);
});
process.on('exit', function() {
assert.equal(connectErr.code, 'ER_HOST_NOT_PRIVILEGED');
assert.equal(connectErr.fatal, true);
});
| cheekujodhpur/ipho2015 | node_modules/mysql/test/integration/test-host-denied-error.js | JavaScript | mit | 662 |
export default {
// 购物车的商品数量
cartCommodityCount: state => {
const totalCount = state.cartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
},
removeCommodityCount: state => {
const totalCount = state.removeCartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
}
}
| luoshi0429/vue2-yanxuan | src/store/getters.js | JavaScript | mit | 424 |
//this controller simply tells the dialogs service to open a mediaPicker window
//with a specified callback, this callback will receive an object with a selection on it
angular.module('umbraco')
.controller("Umbraco.PropertyEditors.ImageCropperController",
function ($rootScope, $routeParams, $scope, $log, mediaHelper, cropperHelper, $timeout, editorState, umbRequestHelper, fileManager) {
var config = angular.copy($scope.model.config);
//move previously saved value to the editor
if ($scope.model.value) {
//backwards compat with the old file upload (incase some-one swaps them..)
if (angular.isString($scope.model.value)) {
config.src = $scope.model.value;
$scope.model.value = config;
} else if ($scope.model.value.crops) {
//sync any config changes with the editor and drop outdated crops
_.each($scope.model.value.crops, function (saved) {
var configured = _.find(config.crops, function (item) { return item.alias === saved.alias });
if (configured && configured.height === saved.height && configured.width === saved.width) {
configured.coordinates = saved.coordinates;
}
});
$scope.model.value.crops = config.crops;
//restore focalpoint if missing
if (!$scope.model.value.focalPoint) {
$scope.model.value.focalPoint = { left: 0.5, top: 0.5 };
}
}
$scope.imageSrc = $scope.model.value.src;
}
//crop a specific crop
$scope.crop = function (crop) {
$scope.currentCrop = crop;
$scope.currentPoint = undefined;
};
//done cropping
$scope.done = function () {
$scope.currentCrop = undefined;
$scope.currentPoint = undefined;
};
//crop a specific crop
$scope.clear = function (crop) {
//clear current uploaded files
fileManager.setFiles($scope.model.alias, []);
//clear the ui
$scope.imageSrc = undefined;
if ($scope.model.value) {
delete $scope.model.value;
}
};
//show previews
$scope.togglePreviews = function () {
if ($scope.showPreviews) {
$scope.showPreviews = false;
$scope.tempShowPreviews = false;
} else {
$scope.showPreviews = true;
}
};
//on image selected, update the cropper
$scope.$on("filesSelected", function (ev, args) {
$scope.model.value = config;
if (args.files && args.files[0]) {
fileManager.setFiles($scope.model.alias, args.files);
var reader = new FileReader();
reader.onload = function (e) {
$scope.$apply(function () {
$scope.imageSrc = e.target.result;
});
};
reader.readAsDataURL(args.files[0]);
}
});
})
.run(function (mediaHelper, umbRequestHelper) {
if (mediaHelper && mediaHelper.registerFileResolver) {
mediaHelper.registerFileResolver("Umbraco.ImageCropper", function (property, entity, thumbnail) {
if (property.value.src) {
if (thumbnail === true) {
return property.value.src + "?width=600&mode=max";
}
else {
return property.value.src;
}
//this is a fallback in case the cropper has been asssigned a upload field
}
else if (angular.isString(property.value)) {
if (thumbnail) {
if (mediaHelper.detectIfImageByExtension(property.value)) {
var thumbnailUrl = umbRequestHelper.getApiUrl(
"imagesApiBaseUrl",
"GetBigThumbnail",
[{ originalImagePath: property.value }]);
return thumbnailUrl;
}
else {
return null;
}
}
else {
return property.value;
}
}
return null;
});
}
}); | zidad/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js | JavaScript | mit | 4,659 |
angular.module('phonebook')
.config(['$urlRouterProvider','$stateProvider',function($urlRouterProvider,$stateProvider){
$stateProvider
// Greeting State
.state('user.main',{
url : '/',
templateUrl : 'user/view/welcome.html',
controller : 'welcomeCtrl'
})
// Phonebook Display State
.state('user.PB',{
url : '/contacts',
templateUrl : 'user/view/displayContacts.html',
controller : 'cntctCtrl'
})
}]); | bhushankalvani/PFrepo | angularApp/user/user.routes.js | JavaScript | mit | 461 |
game.TitleScreen = me.ScreenObject.extend({
init: function(){
this.font = null;
},
onResetEvent: function() {
me.audio.stop("theme");
game.data.newHiScore = false;
me.game.world.addChild(new BackgroundLayer('bg', 1));
me.input.bindKey(me.input.KEY.ENTER, "enter", true);
me.input.bindKey(me.input.KEY.SPACE, "enter", true);
me.input.bindMouse(me.input.mouse.LEFT, me.input.KEY.ENTER);
this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) {
if (action === "enter") {
me.state.change(me.state.PLAY);
}
});
//logo
var logoImg = me.loader.getImage('logo');
var logo = new me.SpriteObject (
me.game.viewport.width/2 - 170,
-logoImg,
logoImg
);
me.game.world.addChild(logo, 10);
var logoTween = new me.Tween(logo.pos).to({y: me.game.viewport.height/2 - 100},
1000).easing(me.Tween.Easing.Exponential.InOut).start();
this.ground = new TheGround();
me.game.world.addChild(this.ground, 11);
me.game.world.addChild(new (me.Renderable.extend ({
// constructor
init: function() {
// size does not matter, it's just to avoid having a zero size
// renderable
this.parent(new me.Vector2d(), 100, 100);
//this.font = new me.Font('Arial Black', 20, 'black', 'left');
this.text = me.device.touch ? 'Tap to start' : 'PRESS SPACE OR CLICK LEFT MOUSE BUTTON TO START';
this.font = new me.Font('gamefont', 20, '#000');
},
update: function () {
return true;
},
draw: function (context) {
var measure = this.font.measureText(context, this.text);
this.font.draw(context, this.text, me.game.viewport.width/2 - measure.width/2, me.game.viewport.height/2 + 50);
}
})), 12);
},
onDestroyEvent: function() {
// unregister the event
me.event.unsubscribe(this.handler);
me.input.unbindKey(me.input.KEY.ENTER);
me.input.unbindKey(me.input.KEY.SPACE);
me.input.unbindMouse(me.input.mouse.LEFT);
me.game.world.removeChild(this.ground);
}
});
| jeshuamaxey/flappy-tom | js/screens/title.js | JavaScript | mit | 2,176 |
'use strict';
var _ = require('underscore'),
Util = require('../../shared/util'),
Base = require('./base'),
Action = require('../../action'),
Types = require('./types');
var _parent = Base.prototype;
var RandomWalk = Util.extend(Base, {
properties: ['walkPropability'],
type: Types.RANDOM_WALK,
_walkPropability: 0.3,
create: function(config) {
var me = this;
me.getConfig(config, ['walkPropability']);
_parent.create.apply(me, arguments);
},
decide: function() {
var me = this;
if (Math.random() > me._walkPropability) {
return null;
}
switch (_.random(3)) {
case 0:
return new Action.Move({deltaX: 1});
case 1:
return new Action.Move({deltaX: -1});
case 2:
return new Action.Move({deltaY: 1});
case 3:
return new Action.Move({deltaY: -1});
}
return null;
}
});
module.exports = RandomWalk; | DirtyHairy/mayrogue-deathmatch | goldmine/server/brain/strategy/randomWalk.js | JavaScript | mit | 1,069 |
import_module('Athena.Math');
m1 = new Athena.Math.Matrix3(1, 2, 3,
4, 5, 6,
7, 8, 9);
for (var row = 0; row < 3; ++row)
{
for (var col = 0; col < 3; ++col)
CHECK_CLOSE(row * 3 + col + 1, m1.get(row, col));
}
| Kanma/Athena-Math | unittests/scripting/js/Matrix3/CreationWithValues.js | JavaScript | mit | 282 |
version https://git-lfs.github.com/spec/v1
oid sha256:27606576bf3cd46c15755bdec387cc97145a4a0c0a5b3933c11d30ab8c6c5ec7
size 1825
| yogeshsaroya/new-cdnjs | ajax/libs/timelinejs/2.35.6/js/locale/el.js | JavaScript | mit | 129 |
import Objective from '../objective';
export default class KillShipsObjective extends Objective {
constructor (game, ships) {
super(game);
if (!Array.isArray(ships)) {
ships = [ships];
}
this.bots = _.filter(ships, ship => { return ship.alive; });
this.ships = ships;
}
isComplete () {
var all_dead = true;
for (var i = 0; i < this.ships.length; i++) {
if (this.ships[i].alive) {
all_dead = false;
break;
}
}
return all_dead;
}
};
| gaudeon/interstice | src/stage/objectives/kill_ships.js | JavaScript | mit | 622 |
// Calendar SK language
// Author: Peter Valach (pvalach@gmx.net)
// Encoding: utf-8
// Last update: 2003/10/29
// full day names
Calendar._DN = new Array
("NedeÄľa",
"Pondelok",
"Utorok",
"Streda",
"Ĺ tvrtok",
"Piatok",
"Sobota",
"NedeÄľa");
// short day names
Calendar._SDN = new Array
("Ned",
"Pon",
"Uto",
"Str",
"Ĺ tv",
"Pia",
"Sob",
"Ned");
// full month names
Calendar._MN = new Array
("Január",
"Február",
"Marec",
"AprĂl",
"Máj",
"JĂşn",
"JĂşl",
"August",
"September",
"OktĂłber",
"November",
"December");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"Máj",
"JĂşn",
"JĂşl",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendári";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"Poslednú verziu nájdete na: http://www.dynarch.com/projects/calendar/\n" +
"Distribuované pod GNU LGPL. Viď http://gnu.org/licenses/lgpl.html pre detaily." +
"\n\n" +
"Výber dátumu:\n" +
"- Použite tlačidlá \xab, \xbb pre výber roku\n" +
"- Použite tlačidlá " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " pre výber mesiaca\n" +
"- Ak ktorĂ©koÄľvek z tĂ˝chto tlaÄŤidiel podrĹľĂte dlhšie, zobrazĂ sa rĂ˝chly vĂ˝ber.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Výber času:\n" +
"- Kliknutie na niektorú položku času ju zvýši\n" +
"- Shift-klik ju znĂĹľi\n" +
"- Ak podrĹľĂte tlaÄŤĂtko stlaÄŤenĂ©, posĂşvanĂm menĂte hodnotu.";
Calendar._TT["PREV_YEAR"] = "Predošlý rok (podržte pre menu)";
Calendar._TT["PREV_MONTH"] = "Predošlý mesiac (podržte pre menu)";
Calendar._TT["GO_TODAY"] = "Prejsť na dnešok";
Calendar._TT["NEXT_MONTH"] = "Nasl. mesiac (podrĹľte pre menu)";
Calendar._TT["NEXT_YEAR"] = "Nasl. rok (podrĹľte pre menu)";
Calendar._TT["SEL_DATE"] = "Zvoľte dátum";
Calendar._TT["DRAG_TO_MOVE"] = "PodrĹľanĂm tlaÄŤĂtka zmenĂte polohu";
Calendar._TT["PART_TODAY"] = " (dnes)";
Calendar._TT["MON_FIRST"] = "ZobraziĹĄ pondelok ako prvĂ˝";
Calendar._TT["SUN_FIRST"] = "ZobraziĹĄ nedeÄľu ako prvĂş";
Calendar._TT["CLOSE"] = "ZavrieĹĄ";
Calendar._TT["TODAY"] = "Dnes";
Calendar._TT["TIME_PART"] = "(Shift-)klik/ĹĄahanie zmenĂ hodnotu";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "$d. %m. %Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e. %b";
Calendar._TT["WK"] = "týž";
| JoAutomation/todo-for-you | lib/js/jscalendar/lang/calendar-sk-utf8.js | JavaScript | mit | 2,589 |
System.config({
baseURL: ".",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime",
"optimisation.modules.system"
]
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
bundles: {
"build.js": [
"lib/main.js",
"lib/filelayer/ajaxUtil.js",
"lib/filelayer/corslite.js",
"github:shramov/leaflet-plugins@1.4.2",
"npm:leaflet@0.7.7",
"npm:togeojson@0.13.0",
"lib/filelayer/leaflet.filelayer.js",
"github:mholt/PapaParse@4.1.2",
"npm:font-awesome@4.5.0/css/font-awesome.min.css!github:systemjs/plugin-css@0.1.20",
"github:shramov/leaflet-plugins@1.4.2/control/Distance",
"npm:leaflet@0.7.7/dist/leaflet-src",
"npm:togeojson@0.13.0/togeojson",
"github:mholt/PapaParse@4.1.2/papaparse",
"github:jspm/nodelibs-process@0.1.2",
"github:jspm/nodelibs-process@0.1.2/index",
"npm:process@0.11.2",
"npm:process@0.11.2/browser"
]
},
map: {
"adm-zip": "npm:adm-zip@0.4.7",
"babel": "npm:babel-core@5.8.34",
"babel-runtime": "npm:babel-runtime@5.8.34",
"clean-css": "npm:clean-css@3.4.9",
"core-js": "npm:core-js@1.2.6",
"css": "github:systemjs/plugin-css@0.1.20",
"font-awesome": "npm:font-awesome@4.5.0",
"gildas-lormeau/zip.js": "github:gildas-lormeau/zip.js@master",
"leaflet": "npm:leaflet@0.7.7",
"mapbox/togeojson": "github:mapbox/togeojson@0.13.0",
"mholt/PapaParse": "github:mholt/PapaParse@4.1.2",
"shramov/leaflet-plugins": "github:shramov/leaflet-plugins@1.4.2",
"togeojson": "npm:togeojson@0.13.0",
"github:jspm/nodelibs-assert@0.1.0": {
"assert": "npm:assert@1.3.0"
},
"github:jspm/nodelibs-buffer@0.1.0": {
"buffer": "npm:buffer@3.6.0"
},
"github:jspm/nodelibs-constants@0.1.0": {
"constants-browserify": "npm:constants-browserify@0.0.1"
},
"github:jspm/nodelibs-crypto@0.1.0": {
"crypto-browserify": "npm:crypto-browserify@3.11.0"
},
"github:jspm/nodelibs-events@0.1.1": {
"events": "npm:events@1.0.2"
},
"github:jspm/nodelibs-http@1.7.1": {
"Base64": "npm:Base64@0.2.1",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"github:jspm/nodelibs-https@0.1.0": {
"https-browserify": "npm:https-browserify@0.0.0"
},
"github:jspm/nodelibs-os@0.1.0": {
"os-browserify": "npm:os-browserify@0.1.2"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.2": {
"process": "npm:process@0.11.2"
},
"github:jspm/nodelibs-stream@0.1.0": {
"stream-browserify": "npm:stream-browserify@1.0.0"
},
"github:jspm/nodelibs-string_decoder@0.1.0": {
"string_decoder": "npm:string_decoder@0.10.31"
},
"github:jspm/nodelibs-url@0.1.0": {
"url": "npm:url@0.10.3"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"github:jspm/nodelibs-vm@0.1.0": {
"vm-browserify": "npm:vm-browserify@0.0.4"
},
"github:jspm/nodelibs-zlib@0.1.0": {
"browserify-zlib": "npm:browserify-zlib@0.1.4"
},
"npm:adm-zip@0.4.7": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"zlib": "github:jspm/nodelibs-zlib@0.1.0"
},
"npm:amdefine@1.0.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"module": "github:jspm/nodelibs-module@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:asn1.js@4.3.0": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:assert@1.3.0": {
"util": "npm:util@0.10.3"
},
"npm:babel-runtime@5.8.34": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:browserify-aes@1.0.5": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"buffer-xor": "npm:buffer-xor@1.0.3",
"cipher-base": "npm:cipher-base@1.0.2",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:browserify-cipher@1.0.0": {
"browserify-aes": "npm:browserify-aes@1.0.5",
"browserify-des": "npm:browserify-des@1.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0"
},
"npm:browserify-des@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"des.js": "npm:des.js@1.0.0",
"inherits": "npm:inherits@2.0.1"
},
"npm:browserify-rsa@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"constants": "github:jspm/nodelibs-constants@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:browserify-sign@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"browserify-rsa": "npm:browserify-rsa@4.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.0.2",
"inherits": "npm:inherits@2.0.1",
"parse-asn1": "npm:parse-asn1@5.0.0",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:browserify-zlib@0.1.4": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"pako": "npm:pako@0.2.8",
"process": "github:jspm/nodelibs-process@0.1.2",
"readable-stream": "npm:readable-stream@2.0.5",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:buffer-xor@1.0.3": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:buffer@3.6.0": {
"base64-js": "npm:base64-js@0.0.8",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"ieee754": "npm:ieee754@1.1.6",
"isarray": "npm:isarray@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:cipher-base@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"string_decoder": "github:jspm/nodelibs-string_decoder@0.1.0"
},
"npm:clean-css@3.4.9": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"commander": "npm:commander@2.8.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"http": "github:jspm/nodelibs-http@1.7.1",
"https": "github:jspm/nodelibs-https@0.1.0",
"os": "github:jspm/nodelibs-os@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"source-map": "npm:source-map@0.4.4",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:commander@2.8.1": {
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"events": "github:jspm/nodelibs-events@0.1.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"graceful-readlink": "npm:graceful-readlink@1.0.1",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:concat-stream@1.4.10": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.13",
"typedarray": "npm:typedarray@0.0.6"
},
"npm:constants-browserify@0.0.1": {
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:core-js@1.2.6": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:core-util-is@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:create-ecdh@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.0.2"
},
"npm:create-hash@1.1.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"ripemd160": "npm:ripemd160@1.0.1",
"sha.js": "npm:sha.js@2.4.4"
},
"npm:create-hmac@1.1.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:crypto-browserify@3.11.0": {
"browserify-cipher": "npm:browserify-cipher@1.0.0",
"browserify-sign": "npm:browserify-sign@4.0.0",
"create-ecdh": "npm:create-ecdh@4.0.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"diffie-hellman": "npm:diffie-hellman@5.0.1",
"inherits": "npm:inherits@2.0.1",
"pbkdf2": "npm:pbkdf2@3.0.4",
"public-encrypt": "npm:public-encrypt@4.0.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:des.js@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0"
},
"npm:diffie-hellman@5.0.1": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"miller-rabin": "npm:miller-rabin@4.0.0",
"randombytes": "npm:randombytes@2.0.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:elliptic@6.0.2": {
"bn.js": "npm:bn.js@4.6.2",
"brorand": "npm:brorand@1.0.5",
"hash.js": "npm:hash.js@1.0.3",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:evp_bytestokey@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0"
},
"npm:font-awesome@4.5.0": {
"css": "github:systemjs/plugin-css@0.1.20"
},
"npm:graceful-readlink@1.0.1": {
"fs": "github:jspm/nodelibs-fs@0.1.2"
},
"npm:hash.js@1.0.3": {
"inherits": "npm:inherits@2.0.1"
},
"npm:https-browserify@0.0.0": {
"http": "github:jspm/nodelibs-http@1.7.1"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:leaflet@0.7.7": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"util": "github:jspm/nodelibs-util@0.1.0",
"zlib": "github:jspm/nodelibs-zlib@0.1.0"
},
"npm:miller-rabin@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"brorand": "npm:brorand@1.0.5"
},
"npm:os-browserify@0.1.2": {
"os": "github:jspm/nodelibs-os@0.1.0"
},
"npm:pako@0.2.8": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:parse-asn1@5.0.0": {
"asn1.js": "npm:asn1.js@4.3.0",
"browserify-aes": "npm:browserify-aes@1.0.5",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"pbkdf2": "npm:pbkdf2@3.0.4",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:pbkdf2@3.0.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:process-nextick-args@1.0.6": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:process@0.11.2": {
"assert": "github:jspm/nodelibs-assert@0.1.0"
},
"npm:public-encrypt@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"browserify-rsa": "npm:browserify-rsa@4.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"parse-asn1": "npm:parse-asn1@5.0.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:punycode@1.3.2": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:randombytes@2.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:readable-stream@1.1.13": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream-browserify": "npm:stream-browserify@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31"
},
"npm:readable-stream@2.0.5": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"process-nextick-args": "npm:process-nextick-args@1.0.6",
"string_decoder": "npm:string_decoder@0.10.31",
"util-deprecate": "npm:util-deprecate@1.0.2"
},
"npm:ripemd160@1.0.1": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:sha.js@2.4.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:source-map@0.4.4": {
"amdefine": "npm:amdefine@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:stream-browserify@1.0.0": {
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.13"
},
"npm:string_decoder@0.10.31": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:togeojson@0.13.0": {
"concat-stream": "npm:concat-stream@1.4.10",
"minimist": "npm:minimist@0.0.8",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:url@0.10.3": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"punycode": "npm:punycode@1.3.2",
"querystring": "npm:querystring@0.2.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:util-deprecate@1.0.2": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:vm-browserify@0.0.4": {
"indexof": "npm:indexof@0.0.1"
}
}
});
| p4535992/Leaflet.FileLayer-1 | config.js | JavaScript | mit | 16,544 |
// languages index
var localeIndex = {
"en" : 0,
"ja" : 1,
"es" : 2,
"hu" : 3,
"lt" : 4,
"ru" : 5,
"it" : 6,
"pt" : 7,
"sp_ch" : 8,
"fr" : 9,
"ge" : 10,
"ua" : 11,
"lv" : 12,
"no" : 13,
"pt_br" : 14
};
| miya2000/Twippera-OAuth | js/lng.js | JavaScript | mit | 251 |
import React, { PropTypes, Component } from 'react';
import { Breadcrumb, Table, Button, Col } from 'react-bootstrap';
import cx from 'classnames';
import _ from 'lodash';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ProductList.css';
import Link from '../Link';
class ProductList extends Component {
static propTypes = {
isFetching: PropTypes.bool,
rs: PropTypes.array,
popAddApp: PropTypes.func,
};
static defaultProps = {
isFetching: true,
rs: [],
popAddApp: () => {},
};
constructor() {
super();
this.renderRow = this.renderRow.bind(this);
}
renderRow(rowData, index) {
const appName = _.get(rowData, 'name');
return (
<tr key={_.get(rowData, 'name')}>
<td>
<Link to={`/apps/${appName}`}>{appName}</Link>
</td>
<td style={{ textAlign: 'left' }}>
<ul>
{
_.map(_.get(rowData, 'collaborators'), (item, email) => (
<li key={email}>
{email}
<span className={s.permission}>
(<em>{_.get(item, 'permission')}</em>)
</span>
{
_.get(item, 'isCurrentAccount') ?
<span className={cx(s.label, s.labelSuccess)}>
it's you
</span>
: null
}
</li>
))
}
</ul>
</td>
<td>
<ul>
{
_.map(_.get(rowData, 'deployments'), (item, email) => (
<li key={email} style={item === 'Production' ? { color: 'green' } : null} >
<Link to={`/apps/${appName}/${item}`}>{item}</Link>
</li>
))
}
</ul>
</td>
<td />
</tr>
);
}
render() {
const self = this;
const tipText = '暂无数据';
return (
<div className={s.root}>
<div className={s.container}>
<Breadcrumb>
<Breadcrumb.Item active>
应用列表
</Breadcrumb.Item>
</Breadcrumb>
<Col style={{ marginBottom: '20px' }}>
<Button
onClick={this.props.popAddApp}
bsStyle="primary"
>
添加应用
</Button>
</Col>
<Table striped bordered condensed hover responsive>
<thead>
<tr>
<th style={{ textAlign: 'center' }} >产品名</th>
<th style={{ textAlign: 'center' }} >成员</th>
<th style={{ textAlign: 'center' }} >Deployments</th>
<th style={{ textAlign: 'center' }} >操作</th>
</tr>
</thead>
<tbody>
{
this.props.rs.length > 0 ?
_.map(this.props.rs, (item, index) => self.renderRow(item, index))
:
<tr>
<td colSpan="4" >{tipText}</td>
</tr>
}
</tbody>
</Table>
</div>
</div>
);
}
}
export default withStyles(s)(ProductList);
| lisong/code-push-web | src/components/ProductList/ProductList.js | JavaScript | mit | 3,199 |
define(['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var globalExtraOptions = exports.globalExtraOptions = {
mappingDataStructure: {
class: 'class',
content: 'content',
disabled: 'disabled',
divider: 'divider',
groupLabel: 'group',
groupDisabled: 'disabled',
icon: 'icon',
maxOptions: 'maxOptions',
option: 'option',
subtext: 'subtext',
style: 'style',
title: 'title',
tokens: 'tokens'
}
};
var globalPickerOptions = exports.globalPickerOptions = {
dropupAuto: true,
showTick: true,
width: 'auto'
};
}); | ghiscoding/Aurelia-Bootstrap-Plugins | aurelia-bootstrap-select/dist/amd/picker-global-options.js | JavaScript | mit | 686 |
{
test.ok(
thrown instanceof axios.Cancel,
"Promise must be rejected with a Cancel obejct"
);
test.equal(thrown.message, "Operation has been canceled.");
test.done();
}
| stas-vilchik/bdd-ml | data/914.js | JavaScript | mit | 185 |
function closeObject(id) {
document.getElementById(id).style.display = 'none';
}
function openObject(id) {
document.getElementById(id).style.display = 'block';
}
function openClose(id){
if (document.getElementById(id).style.display == 'block'){
console.log('intenta cerrar');
closeObject(id);
}else{
console.log('intenta abrir');
openObject(id);
}
}
$(document).ready(function () {
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
$(".botonRectificarEvento").on("click", function () {
$.ajax({
type: 'POST',
data: { id: $(this).attr("data-id") },
url: Routing.generate('eventos_rectificacion_nueva',null,true),
context: document.body
})
.done(function (datos) {
if(datos.estado) {
$('#tituloPopUp').html('Rectificar Evento');
$("#contenidoPopUp").html(datos.vista);
$('.modal-dialog').removeClass('modal-lg');
$('#piePopUp').addClass('show');
$('#ventanaPopUp').modal('show');
}
});
});
$("#botonGuardarPopUp").on("click", function () {
var datosFormulario = $("#formularioRectificarEvento").serializeArray();
var urlFormulario = Routing.generate('eventos_rectificacion_crear',null,true);
$.ajax(
{
url : urlFormulario,
type: "POST",
data : datosFormulario,
success: function(datos)
{
if(datos.estado){
if(datos.rectificado){
$('#ventanaPopUp').modal('hide');
$( location ).attr("href", Routing.generate('eventos',null,true));
} else {
$("#contenidoPopUp").html(datos.html);
}
}
},
error: function() {
alert('error');
}
});
return false;
});
// Visualizar detalles
$('.botonMostrarDetallesEvento').on('click',function(){
$.ajax({
type: 'GET',
url: Routing.generate('eventos_detalle',{ id: $(this).attr('data-id') },true),
context: document.body
})
.done(function (html) {
$('#tituloPopUp').html('Detalle eventos');
$("#contenidoPopUp").html(html);
$('.modal-dialog').addClass('modal-lg');
$('#piePopUp').addClass('hide');
$('#piePopUp').removeClass('show');
$('#ventanaPopUp').modal('show');
});
});
//Agregar nuevo detalle
$('#ventanaPopUp').on("click",'#botonAgregarDetalle',function(){
var datosFormulario = $("#formularioAgregarDetalle").serializeArray();
var urlFormulario = Routing.generate('eventos_detalle_crear',null,true);
$.ajax(
{
url : urlFormulario,
type: "POST",
data : datosFormulario,
success: function(datos)
{
$("#contenidoPopUp").html(datos.html);
}
});
return false;
});
$('#ventanaPopUp').on('mouseover','#dp-detalle',function(){
$('#dp-detalle').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
$('#ventanaPopUp').on('mouseover','#dp-rectificar',function(){
$('#dp-rectificar').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
$(".estado-switch").bootstrapSwitch();
$('#botonFormularioRegistro').on('click',function(){
if(! $('#botonFormularioRegistro').hasClass('active')) {
$(':input','#formularioBusqueda')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
$('#formularioBusqueda').append('<input type="hidden" name="seccion" value="registro" />');
$('#formularioBusqueda').submit();
}
// $('#botonFormularioBusqueda').removeClass('active');
// $(this).addClass('active');
// $('#divFormularioRegistro').removeClass('hide');
// $('#divFormularioRegistro').addClass('show');
// $('#divFormularioBusqueda').removeClass('show');
// $('#divFormularioBusqueda').addClass('hide');
});
$('#botonFormularioBusqueda').on('click',function(){
$('#botonFormularioRegistro').removeClass('active');
$(this).addClass('active');
$('#divFormularioBusqueda').removeClass('hide');
$('#divFormularioBusqueda').addClass('show');
$('#divFormularioRegistro').removeClass('show');
$('#divFormularioRegistro').addClass('hide');
});
$('#dtp-fecha-desde').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
$('#dtp-fecha-hasta').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
| jogianotti/RegistroEventosIntendencia | src/RegistroEventos/CoreBundle/Resources/public/js/eventos.js | JavaScript | mit | 5,274 |
/* eslint-env node*/
var gutil = require('gulp-util')
var paths = {
layouts: {
componentsDir: './app/components/**/*.jade',
src: './app/views/**/*.jade',
dest: './app/public/assets/html/'
},
styles: {
componentsDir: './app/lib/stylesheets/**/*.styl',
src: './app/lib/stylesheets/styles.styl',
dest: './app/public/assets/css/'
},
scripts: {
entry: './app/lib/scripts/entry.jsx',
src: ['./app/lib/scripts/**/*.jsx', './app/lib/scripts/**/*.js'],
dest: './app/public/assets/js/'
}
}
var onError = function (error) {
gutil.log(gutil.colors.red(error))
this.emit('end')
}
module.exports = {
paths: paths,
onError: onError
}
| datyayu/cemetery | [JS-ES6][React] Raji - first version/gulp/config.js | JavaScript | mit | 716 |
/**
*
* app.js
*
* This is the entry file for the application
*
*/
import FilmLocationSearchComponent from '../MovieSearchApp/Containers/FilmSearchContainer/FilmSearchComponent';
import AppComponent from '../CommonComponent/app.js';
import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
console.log("current href",window.location.href);
const getAppRouter = () => {
return (
<Route component={AppComponent}>
<Route component={FilmLocationSearchComponent} path='/searchmovies' />
</Route>
);
}
export {
getAppRouter
}
| anil26/MovieSearchGoogleMaps | js/Routes/AppRouter.js | JavaScript | mit | 597 |
/* Accordion directive */
app.directive('vmfAccordionContainer', ['$compile', function($compile) {
return {
restrict: 'EA',
scope: {
type: '@',
headers: '=',
accData: '=',
selAcc: '=',
customClass:'='
},
link: function(scope, elem, attrs) {
var template;
if(scope.type === '1') {
template = '<table class="vmf-accordion-table1"><thead class="vmf-accordion-table-header"><tr><td class="col1"></td>';
var count = 1;
angular.forEach(scope.headers, function(item) {
// if(count === 1) {
// template += '<td colspan="2">' + item + '</td>';
// }
// else {
template += '<td class="col' + (count + 1) +'">' + item + '</td>';
// }
count += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-table-body">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="vmf-accordion-header" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td ><span class="vmf-arrow"></span></td><td colspan="3">' + item.header + '</td></tr>';
angular.forEach(item.contents, function(content) {
template += '<tr class="vmf-accordion-row" ng-show="activeIndex =='+ scope.accordionIndex + '"><td colspan="1"></td>';
angular.forEach(content, function(cellData) {
template += '<td colspan="1">' + cellData + '</td>';
});
template += '</tr>';
});
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row').hide();
}
else if(scope.type === '2') {
template = '<table class="vmf-accordion-table2"><thead class="vmf-accordion-table2-header" style="background-color: lightgray;"><tr><td class="col1"></td>';
var headerCount = 0;
angular.forEach(scope.headers, function(item) {
if(headerCount !== scope.headers.length - 1) {
template += '<td class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
else {
template += '<td colspan="2" class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
headerCount += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-table2-body">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="vmf-accordion-header2" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td><span class="vmf-arrow"></span></td>';
var accHeadersCount = 1;
angular.forEach(item.headers, function(header) {
if(accHeadersCount !== item.headers.length) {
template += '<td>' + header + '</td>';
}
else {
template += '<td class="vmf-acc-header-last-child">' + header + '</td>';
}
accHeadersCount += 1;
});
template += '</tr><tr class="vmf-accordion-row2"><td></td><td class="vmf-acc-header-last-child" colspan="' + item.headers.length + '"><table class="vmf-accordion-sub-table" ng-show="activeIndex =='+ scope.accordionIndex + '">';
var count = 0;
angular.forEach(item.contents, function(content) {
if(count !== 0) {
template += '<tr class="vmf-accordion-sub-table-row">';
angular.forEach(content, function(cellData) {
template += '<td>' + cellData + '</td>';
});
template += '</tr>';
}
else {
template += '<thead class="vmf-accordion-sub-table-header"><tr>';
var subHeaderCount = 1;
angular.forEach(content, function(cellData) {
template += '<td class="col' + subHeaderCount + '">' + cellData + '</td>';
subHeaderCount += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-sub-table-body">';
}
count += 1;
});
template += '</tbody></table></td></tr>';
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
if(scope.customClass){
angular.forEach(scope.customClass, function(item) {
elem.find(item.selector).addClass(item.cusclass);
});
}
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row2').hide();
// elem.find('.vmf-accordion-row2').hide();
}
scope.toggleAccordion = function(index) {
scope.activeIndex = scope.activeIndex === index ? -1 : index;
var accordions, accordionRows;
if(scope.type === '1') {
elem.find('.vmf-accordion-row').hide();
accordions = elem.find('.vmf-accordion-header');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
// accordions = elem.find('.vmf-accordion-header');
// console.log(accordions[index]);
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.vmf-accordion-header');
$(accordionRows).show();
}
}
else if(scope.type === '2') {
elem.find('.vmf-accordion-row2').hide();
accordions = elem.find('.vmf-accordion-header2');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.vmf-accordion-header2');
$(accordionRows).show();
}
}
};
scope.buttonClick = function($event, index) {
$event.stopPropagation();
scope.selAcc = index;
};
}
};
}]); | anandharshan/Web-components-DD | dev/modules/Accordion/accordionDirectives.js | JavaScript | mit | 8,055 |
/* ================================================================
* startserver by xdf(xudafeng[at]126.com)
*
* first created at : Mon Jun 02 2014 20:15:51 GMT+0800 (CST)
*
* ================================================================
* Copyright 2013 xdf
*
* Licensed under the MIT License
* You may not use this file except in compliance with the License.
*
* ================================================================ */
'use strict';
var logx = require('logx');
function *logger() {
var log = 'Method: '.gray + this.req.method.red;
log += ' Url: '.gray + this.req.url.red;
logx.info(log);
yield this.next();
}
module.exports = logger;
| xudafeng/startserver | lib/middleware/logger/index.js | JavaScript | mit | 675 |
/**
* Default admin
*/
new User({
firstName: 'Admin',
lastName: 'Admin',
username: 'admin',
type: 'admin',
password: 'admin',
email: 'admin@admin.com',
subscribed: false,
}).save((u) => {
})
/**
* Test users
*/
new User({
firstName: 'Jonathan',
lastName: 'Santos',
username: 'santojon',
type: 'user',
password: 'test',
email: 'santojon5@gmail.com',
gender: 'Male',
subscribed: true,
image: 'https://avatars1.githubusercontent.com/u/4976482'
}).save((u) => {
UserController.updateUser(u)
})
new User({
firstName: 'Raphael',
lastName: 'Tulyo',
username: 'crazybird',
type: 'user',
password: 'test',
email: 'rtsd@cin.ufpe.br',
gender: 'Male',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
new User({
firstName: 'Vinícius',
lastName: 'Emanuel',
username: 'vems',
type: 'user',
password: 'test',
email: 'vems@cin.ufpe.br',
gender: 'Male',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
/**
* More test users
*/
for (i = 0; i < 5; i++) {
new User({
firstName: 'Test' + i,
lastName: '' + i,
username: 'testuser' + i,
type: 'user',
password: 'test',
email: 'test' + i + '@test.br',
gender: (i % 2 === 0) ? 'Male' : 'Female',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
}
Subscription.findAll().forEach((s) => {
s.status = true
s.update(s)
}) | santojon/hardStone | bootstrap.js | JavaScript | mit | 1,538 |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M2 21.5c0 .28.22.5.49.5h13.02c.27 0 .49-.22.49-.5V20H2v1.5zM15.5 16H11v-2H7v2H2.5c-.28 0-.5.22-.5.5V18h14v-1.5c0-.28-.22-.5-.5-.5zm4.97-.55c.99-1.07 1.53-2.48 1.53-3.94V2h-6v9.47c0 1.48.58 2.92 1.6 4l.4.42V22h4v-2h-2v-4.03l.47-.52zM18 4h2v4h-2V4zm1.03 10.07c-.65-.71-1.03-1.65-1.03-2.6V10h2v1.51c0 .95-.34 1.85-.97 2.56z" />
, 'BrunchDiningOutlined');
| callemall/material-ui | packages/material-ui-icons/src/BrunchDiningOutlined.js | JavaScript | mit | 477 |
var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
const notUtils = require('./notifications-utils.js');
module.exports = [
function (session) {
session.beginDialog('notifications-common-symbol');
},
function (session, results) {
var pair = results.response;
session.dialogData.symbol = pair;
builder.Prompts.number(session, 'How big should the interval be?');
},
function (session, results) {
session.dialogData.interval = results.response;
builder.Prompts.text(session, "What name would you like to give to this notification?");
},
function (session, results) {
var sub = notUtils.getBaseNotification('interval', session.message.address);
sub.symbol = session.dialogData.symbol;
sub.interval = session.dialogData.interval;
sub.previousprice = 0;
sub.isfirstun = true;
sub.name = results.response;
notUtils.createNotification(sub).then((r) => {
session.endDialog('Notification created!');
}).catch((e) => {
session.endDialog('Couldn\'t create notification: ' + e);
});
}
]; | jantielens/CryptoBuddy | messages/dialogs/notifications-add-interval.js | JavaScript | mit | 1,193 |
version https://git-lfs.github.com/spec/v1
oid sha256:a396601eca15b0c281513d01941cfd37300b927b32a1bb9bb6e708a9910f1b49
size 2712
| yogeshsaroya/new-cdnjs | ajax/libs/ckeditor/4.2/plugins/a11yhelp/dialogs/lang/sr-latn.min.js | JavaScript | mit | 129 |
import _ from 'lodash';
/**
* Represents a channel with which commands can be invoked.
*
* Channels are one-per-origin (protocol/domain/port).
*/
class Channel {
constructor(config, $rootScope, $timeout, contentWindow) {
this.config = config;
this.$rootScope = $rootScope;
this.$timeout = $timeout;
this._contentWindow = contentWindow;
this.messageCounter = 0;
}
ab2str(buffer) {
let result = "";
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
result += String.fromCharCode(bytes[i]);
}
return result;
};
/**
* Fire and forget pattern that sends the command to the target without waiting for a response.
*/
invokeDirect(command, data, targetOrigin, transferrablePropertyPath) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let transferrableProperty = undefined;
if (transferrablePropertyPath) {
transferrableProperty = _.get(data, transferrablePropertyPath);
}
if (transferrableProperty)
this._contentWindow.postMessage(data, targetOrigin, [transferrableProperty]);
else
this._contentWindow.postMessage(data, targetOrigin);
}
/**
* Invokes the specified command on the channel with the specified data, constrained to the specified domain awaiting for max ms specified in timeout
*/
async invoke(command, data, targetOrigin, timeout, transferrablePropertyPath) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
if (!timeout) {
timeout = 0;
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let resolve, reject;
let promise = new Promise((innerResolve, innerReject) => {
resolve = innerResolve;
reject = innerReject;
});
let timeoutPromise;
if (timeout > 0) {
timeoutPromise = this.$timeout(() => {
reject(new Error(`invoke() timed out while waiting for a response while executing ${data.command}`));
}, timeout);
}
let removeMonitor = this.$rootScope.$on(this.config.crossDomainMessageSink.incomingMessageName, (event, response) => {
if (response.postMessageId !== data.postMessageId)
return;
if (response.result === "error") {
reject(response);
}
else {
if (response.data) {
let contentType = response.headers["content-type"] || response.headers["Content-Type"];
if (contentType.startsWith("application/json")) {
let str = this.ab2str(response.data);
if (str.length > 0) {
try
{
response.data = JSON.parse(str);
}
catch(ex) {
}
}
} else if (contentType.startsWith("text")) {
response.data = this.ab2str(response.data);
}
}
resolve(response);
}
removeMonitor();
if (timeoutPromise)
this.$timeout.cancel(timeoutPromise);
});
let transferrableProperty = undefined;
if (transferrablePropertyPath) {
transferrableProperty = _.get(data, transferrablePropertyPath);
}
if (transferrableProperty)
this._contentWindow.postMessage(data, targetOrigin, [transferrableProperty]);
else
this._contentWindow.postMessage(data, targetOrigin);
return promise;
}
}
module.exports = Channel; | beyond-sharepoint/sp-angular-webpack | src/ng-sharepoint/Channel.js | JavaScript | mit | 4,352 |
// config/database.js
module.exports = {
'secret': 'puneetvashisht',
'url' : 'mongodb://localhost/userdb' // looks like mongodb://<user>:<pass>@mongo.onmodulus.net:27017/Mikha4ot
};
| arun2786/tk-mean | database.js | JavaScript | mit | 191 |
import {
LOAD_SEARCH_RESULT_SUCCESS,
CLEAR_SEARCH_RESULTS,
} from 'actions/search';
import { createActionHandlers } from 'utils/reducer/actions-handlers';
const actionHandlers = {};
export function loadSearchResultSuccess(state, searchResultsList) {
return searchResultsList.reduce((acc, result) => {
return {
...acc,
[result.id]: result,
};
}, {});
}
export function clearSearchResult() {
return {};
}
actionHandlers[LOAD_SEARCH_RESULT_SUCCESS] = loadSearchResultSuccess;
actionHandlers[CLEAR_SEARCH_RESULTS] = clearSearchResult;
export default createActionHandlers(actionHandlers);
| InseeFr/Pogues | src/reducers/search-result-by-id.js | JavaScript | mit | 619 |
/**
* Created by huangxinghui on 2016/1/20.
*/
var $ = require('jquery')
var Widget = require('../../widget')
var plugin = require('../../plugin')
var TreeNode = require('./treenode')
var Tree = Widget.extend({
options: {
'labelField': null,
'labelFunction': null,
'childrenField': 'children',
'autoOpen': true
},
events: {
'click li': '_onSelect',
'click i': '_onExpand'
},
_create: function() {
this.$element.addClass('tree')
var that = this
var $ul = $('<ul></ul>')
this._loadFromDataSource()
this.nodes.forEach(function(node) {
that._createNode(node)
$ul.append(node.element)
})
this.$element.append($ul)
},
_onSelect: function(e) {
var $li = $(e.currentTarget),
node = $li.data('node')
e.preventDefault()
if (!$li.hasClass('active')) {
this._setSelectedNode(node)
this._trigger('itemClick', node.data)
}
},
_onExpand: function(e) {
var $li = $(e.currentTarget).closest('li'),
node = $li.data('node')
e.preventDefault()
if (node.isOpen) {
this.collapseNode(node)
}
else {
this.expandNode(node)
}
},
_setSelectedNode: function(node) {
var $active = this.$element.find('.active')
$active.removeClass('active')
var $li = node.element
$li.addClass('active')
this._trigger('change', node.data)
},
_createNode: function(node) {
if (node.isBranch()) {
this._createFolder(node)
}
else {
this._createLeaf(node)
}
},
_createLeaf: function(node) {
var html = ['<li><a href="#"><span>']
html.push(this._createIndentationHtml(node.getLevel()))
html.push(this.itemToLabel(node.data))
html.push('</span></a></li>')
var $li = $(html.join(''))
$li.data('node', node)
node.element = $li
return $li
},
_createFolder: function(node) {
var that = this
var html = []
if (node.isOpen) {
html.push('<li class="open"><a href="#"><span>')
html.push(this._createIndentationHtml(node.getLevel() - 1))
html.push('<i class="glyphicon glyphicon-minus-sign js-folder"></i>')
}
else {
html.push('<li><a href="#"><span>')
html.push(this._createIndentationHtml(node.getLevel() - 1))
html.push('<i class="glyphicon glyphicon-plus-sign js-folder"></i>')
}
html.push(this.itemToLabel(node.data))
html.push('</span></a></li>')
var $li = $(html.join(''))
var $ul = $('<ul class="children-list"></ul>')
node.children.forEach(function(childNode) {
that._createNode(childNode)
$ul.append(childNode.element)
})
$li.append($ul)
$li.data('node', node)
node.element = $li
return $li
},
_createLabel: function(node) {
var html = ['<span>']
var level = node.getLevel()
if (node.isBranch()) {
html.push(this._createIndentationHtml(level - 1))
html.push('<i class="glyphicon ',
node.isOpen ? 'glyphicon-minus-sign' : 'glyphicon-plus-sign',
' js-folder"></i>')
}
else {
html.push(this._createIndentationHtml(level))
}
html.push(this.itemToLabel(node.data))
html.push('</span>')
return html.join('')
},
_createIndentationHtml: function(count) {
var html = []
for (var i = 0; i < count; i++) {
html.push('<i class="glyphicon tree-indentation"></i>')
}
return html.join('')
},
_loadFromDataSource: function() {
var node, children, nodes = [], that = this
if (this.options.dataSource) {
this.options.dataSource.forEach(function(item) {
node = new TreeNode(item)
children = item[that.options.childrenField]
if (children) {
node.isOpen = that.options.autoOpen
that._loadFromArray(children, node)
}
nodes.push(node)
})
}
this.nodes = nodes
},
_loadFromArray: function(array, parentNode) {
var node, children, that = this
array.forEach(function(item) {
node = new TreeNode(item)
parentNode.addChild(node)
children = item[that.childrenField]
if (children) {
node.isOpen = that.autoOpen
that._loadFromArray(children, node)
}
})
},
expandNode: function(node) {
if (!node.isBranch()) {
return
}
var $li = node.element
var $disclosureIcon = $li.children('a').find('.js-folder')
if (!node.isOpen) {
node.isOpen = true
$li.addClass('open')
$disclosureIcon.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign')
this._trigger('itemOpen')
}
},
collapseNode: function(node) {
if (!node.isBranch()) {
return
}
var $li = node.element
var $disclosureIcon = $li.children('a').find('.js-folder')
if (node.isOpen) {
node.isOpen = false
$li.removeClass('open')
$disclosureIcon.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign')
this._trigger('itemClose')
}
},
expandAll: function() {
var that = this
this.nodes.forEach(function(node) {
that.expandNode(node)
})
},
collapseAll: function() {
var that = this
this.nodes.forEach(function(node) {
that.collapseNode(node)
})
},
append: function(item, parentNode) {
var $ul, $li, $prev, node = new TreeNode(item)
if (parentNode.isBranch()) {
parentNode.addChild(node)
$ul = parentNode.element.children('ul')
this._createNode(node)
$li = node.element
$ul.append($li)
}
else {
parentNode.addChild(node)
$li = parentNode.element
$prev = $li.prev()
$ul = $li.parent()
parentNode.element = null
$li.remove()
$li = this._createFolder(parentNode)
if ($prev.length) {
$prev.after($li)
}
else {
$ul.append($li)
}
}
this.expandNode(parentNode)
this._setSelectedNode(node)
},
remove: function(node) {
var parentNode = node.parent
node.element.remove()
node.destroy()
this._setSelectedNode(parentNode)
},
update: function(node) {
var $li = node.element
$li.children('a').html(this._createLabel(node))
},
getSelectedNode: function() {
var $li = this.$element.find('.active')
return $li.data('node')
},
getSelectedItem: function() {
var node = this.getSelectedNode()
return node.data
},
itemToLabel: function(data) {
if (!data) {
return ''
}
if (this.options.labelFunction != null) {
return this.options.labelFunction(data)
}
else if (this.options.labelField != null) {
return data[this.options.labelField]
}
else {
return data
}
}
})
plugin('tree', Tree)
| huang-x-h/Bean.js | src/components/tree/index.js | JavaScript | mit | 6,725 |
function solve(args) {
function biSearch(array, searchedNumber, start, end) {
for (var i = start; i <= end; i += 1) {
if (+array[i] === searchedNumber) {
return i;
}
}
return -1;
}
var data = args[0].split('\n'),
numberN = +data.shift(),
numberX = +data.pop();
var firstIndex = 0;
var lastIndex = data.length - 1;
var resultIndex = 0;
var middle = 0;
for (var j = firstIndex; j < lastIndex; j += 1) {
middle = (lastIndex / 2) | 0;
if (+data[middle] === numberX) {
resultIndex = middle;
break;
}
if (+data[middle] < numberX) {
firstIndex = middle;
resultIndex = biSearch(data, numberX, firstIndex, lastIndex);
}
if (+data[middle] > numberX) {
lastIndex = middle;
resultIndex = biSearch(data, numberX, firstIndex, lastIndex);
}
}
if (resultIndex >= 0 && resultIndex < data.length) {
console.log(resultIndex);
} else {
console.log('-1');
}
} | jorosoft/Telerik-Academy | Homeworks/JS Fundamentals/07. Arrays/07. Binary search/binary-search.js | JavaScript | mit | 1,110 |
#!/usr/bin/env node
var pluginlist = [
];
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
console.log(stdout);
}
pluginlist.forEach(function(plug) {
exec("cordova plugin add " + plug, puts);
});
| ozsay/ionic-brackets | templates/plugins_hook.js | JavaScript | mit | 240 |
const path = require('path');
require('dotenv').config();
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin } = require('aurelia-webpack-plugin');
const { optimize: { CommonsChunkPlugin }, ProvidePlugin } = require('webpack')
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig)
// primary config:
const title = 'TechRadar';
const outDir = path.resolve(__dirname, 'dist');
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
const cssRules = [
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })] }
}
]
module.exports = ({ production, server, extractCss, coverage } = {}) => ({
resolve: {
extensions: ['.ts', '.js'],
modules: [srcDir, 'node_modules'],
alias: {
'aurelia-binding$': path.resolve(__dirname, 'node_modules/aurelia-binding/dist/amd/aurelia-binding.js')
}
},
entry: {
app: ['./src/main']
},
output: {
path: outDir,
publicPath: baseUrl,
filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
chunkFilename: production ? '[chunkhash].chunk.js' : '[hash].chunk.js',
},
devServer: {
contentBase: baseUrl,
},
module: {
rules: [
// CSS required in JS/TS files should use the style-loader that auto-injects it into the website
// only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
{
test: /\.css$/i,
issuer: [{ not: [{ test: /\.html$/i }] }],
use: extractCss ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssRules,
}) : ['style-loader', ...cssRules],
},
{
test: /\.css$/i,
issuer: [{ test: /\.html$/i }],
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
use: cssRules,
},
{ test: /\.html$/i, loader: 'html-loader' },
{ test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
{ test: /\.json$/i, loader: 'json-loader' },
// use Bluebird as the global Promise implementation:
{ test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' },
// exposes jQuery globally as $ and as jQuery:
{ test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery' },
// embed small images and fonts as Data Urls and larger ones as files:
{ test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
{ test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
{ test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
// load these fonts normally, as files:
{ test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' },
...when(coverage, {
test: /\.[jt]s$/i, loader: 'istanbul-instrumenter-loader',
include: srcDir, exclude: [/\.{spec,test}\.[jt]s$/i],
enforce: 'post', options: { esModules: true },
})
]
},
plugins: [
new BrowserSyncPlugin({
// browse to http://localhost:3000/ during development,
// ./public directory is being served
host: 'localhost',
port: 3000,
server: { baseDir: ['dist'] }
}),
new AureliaPlugin(),
new ProvidePlugin({
'Promise': 'bluebird',
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
}),
new TsConfigPathsPlugin(),
new CheckerPlugin(),
new HtmlWebpackPlugin({
template: 'index.ejs',
minify: production ? {
removeComments: true,
collapseWhitespace: true
} : undefined,
metadata: {
// available in index.ejs //
title, server, baseUrl
},
}),
// new UglifyJSPlugin(),
new CopyWebpackPlugin([
{ from: 'static/favicon.ico', to: 'favicon.ico' }
,{ from: './../tr-host/projects', to: 'projects' }
,{ from: 'img', to: 'img' }
]),
...when(extractCss, new ExtractTextPlugin({
filename: production ? '[contenthash].css' : '[id].css',
allChunks: true,
})),
...when(production, new CommonsChunkPlugin({
name: ['vendor']
})),
...when(production, new CopyWebpackPlugin([
{ from: 'static/favicon.ico', to: 'favicon.ico' }
]))
// ,
// new BundleAnalyzerPlugin({
// // Can be `server`, `static` or `disabled`.
// // In `server` mode analyzer will start HTTP server to show bundle report.
// // In `static` mode single HTML file with bundle report will be generated.
// // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
// analyzerMode: 'static',
// // Host that will be used in `server` mode to start HTTP server.
// analyzerHost: '127.0.0.1',
// // Port that will be used in `server` mode to start HTTP server.
// analyzerPort: 8888,
// // Path to bundle report file that will be generated in `static` mode.
// // Relative to bundles output directory.
// reportFilename: 'report.html',
// // Module sizes to show in report by default.
// // Should be one of `stat`, `parsed` or `gzip`.
// // See "Definitions" section for more information.
// defaultSizes: 'parsed',
// // Automatically open report in default browser
// openAnalyzer: false,
// // If `true`, Webpack Stats JSON file will be generated in bundles output directory
// generateStatsFile: false,
// // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
// // Relative to bundles output directory.
// statsFilename: 'stats.json',
// // Options for `stats.toJson()` method.
// // For example you can exclude sources of your modules from stats file with `source: false` option.
// // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
// statsOptions: null,
// // Log level. Can be 'info', 'warn', 'error' or 'silent'.
// logLevel: 'info'
// })
],
})
| Make-IT-TR/TechRadar | tr-app/webpack.config.js | JavaScript | mit | 7,154 |
/** @jsx m */
import m from 'mithril';
import { linkTo, hrefTo } from '@storybook/addon-links';
const Main = {
view: vnode => (
<article
style={{
padding: 15,
lineHeight: 1.4,
fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif',
backgroundColor: '#ffffff',
}}
>
{vnode.children}
</article>
),
};
const Title = {
view: vnode => <h1>{vnode.children}</h1>,
};
const Note = {
view: vnode => (
<p
style={{
opacity: 0.5,
}}
>
{vnode.children}
</p>
),
};
const InlineCode = {
view: vnode => (
<code
style={{
fontSize: 15,
fontWeight: 600,
padding: '2px 5px',
border: '1px solid #eae9e9',
borderRadius: 4,
backgroundColor: '#f3f2f2',
color: '#3a3a3a',
}}
>
{vnode.children}
</code>
),
};
const Link = {
view: vnode => (
<a
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
{...vnode.attrs}
>
{vnode.children}
</a>
),
};
const NavButton = {
view: vnode => (
<button
type="button"
style={{
borderTop: 'none',
borderRight: 'none',
borderLeft: 'none',
backgroundColor: 'transparent',
padding: 0,
cursor: 'pointer',
font: 'inherit',
}}
{...vnode.attrs}
>
{vnode.children}
</button>
),
};
const StoryLink = {
oninit: vnode => {
// eslint-disable-next-line no-param-reassign
vnode.state.href = '/';
// eslint-disable-next-line no-param-reassign
vnode.state.onclick = () => {
linkTo(vnode.attrs.kind, vnode.attrs.story)();
return false;
};
StoryLink.updateHref(vnode);
},
updateHref: async vnode => {
const href = await hrefTo(vnode.attrs.kind, vnode.attrs.story);
// eslint-disable-next-line no-param-reassign
vnode.state.href = href;
m.redraw();
},
view: vnode => (
<a
href={vnode.state.href}
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
onClick={vnode.state.onclick}
>
{vnode.children}
</a>
),
};
const Welcome = {
view: vnode => (
<Main>
<Title>Welcome to storybook</Title>
<p>This is a UI component dev environment for your app.</p>
<p>
We've added some basic stories inside the <InlineCode>src/stories</InlineCode> directory.
<br />A story is a single state of one or more UI components. You can have as many stories
as you want.
<br />
(Basically a story is like a visual test case.)
</p>
<p>
See these sample
{vnode.attrs.showApp ? (
<NavButton onclick={vnode.attrs.showApp}>stories</NavButton>
) : (
<StoryLink kind={vnode.attrs.showKind} story={vnode.attrs.showStory}>
stories
</StoryLink>
)}
for a component called <InlineCode>Button</InlineCode>.
</p>
<p>
Just like that, you can add your own components as stories.
<br />
You can also edit those components and see changes right away.
<br />
(Try editing the <InlineCode>Button</InlineCode> stories located at
<InlineCode>src/stories/1-Button.stories.js</InlineCode>
.)
</p>
<p>
Usually we create stories with smaller UI components in the app.
<br />
Have a look at the
<Link
href="https://storybook.js.org/basics/writing-stories"
target="_blank"
rel="noopener noreferrer"
>
Writing Stories
</Link>
section in our documentation.
</p>
<Note>
<b>NOTE:</b>
<br />
Have a look at the <InlineCode>.storybook/webpack.config.js</InlineCode> to add webpack
loaders and plugins you are using in this project.
</Note>
</Main>
),
};
export default Welcome;
| storybooks/react-storybook | lib/cli/generators/MITHRIL/template-csf/stories/Welcome.js | JavaScript | mit | 4,185 |
window.Lunchiatto.module('Transfer', function(Transfer, App, Backbone, Marionette, $, _) {
return Transfer.Layout = Marionette.LayoutView.extend({
template: 'transfers/layout',
ui: {
receivedTransfers: '.received-transfers',
submittedTransfers: '.submitted-transfers'
},
behaviors: {
Animateable: {
types: ['fadeIn']
},
Titleable: {}
},
regions: {
receivedTransfers: '@ui.receivedTransfers',
submittedTransfers: '@ui.submittedTransfers'
},
onRender() {
this._showTransfers('received');
this._showTransfers('submitted');
},
_showTransfers(type) {
const transfers = new App.Entities.Transfers([], {type});
transfers.optionedFetch({
success: transfers => {
App.getUsers().then(() => {
const view = new App.Transfer.List({
collection: transfers});
this[`${type}Transfers`].show(view);
});
}
});
},
_htmlTitle() {
return 'Transfers';
}
});
});
| lunchiatto/web | app/assets/javascripts/modules/transfer/views/layout.js | JavaScript | mit | 1,061 |
'use strict';
var i18n = require('./i18n.js')
i18n.add_translation("pt-BR", {
test: 'OK',
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
i18n.locale = 'pt-BR';
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('greetings.welcome'));
console.log("Hallo");
// Example 2
i18n.add_translation("pt-BR", {
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
console.log(i18n.t('greetings.hello'));
i18n.add_translation("pt-BR", {
test: 'OK',
greetings: {
hello: 'Oi',
bye: 'Tchau'
}
});
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('test'));
| felipediesel/simple-i18n | node.js | JavaScript | mit | 617 |
/**
* @flow
*/
/* eslint-disable */
'use strict';
/*::
import type { ReaderFragment } from 'relay-runtime';
export type ReactionContent = "CONFUSED" | "EYES" | "HEART" | "HOORAY" | "LAUGH" | "ROCKET" | "THUMBS_DOWN" | "THUMBS_UP" | "%future added value";
import type { FragmentReference } from "relay-runtime";
declare export opaque type emojiReactionsView_reactable$ref: FragmentReference;
declare export opaque type emojiReactionsView_reactable$fragmentType: emojiReactionsView_reactable$ref;
export type emojiReactionsView_reactable = {|
+id: string,
+reactionGroups: ?$ReadOnlyArray<{|
+content: ReactionContent,
+viewerHasReacted: boolean,
+users: {|
+totalCount: number
|},
|}>,
+viewerCanReact: boolean,
+$refType: emojiReactionsView_reactable$ref,
|};
export type emojiReactionsView_reactable$data = emojiReactionsView_reactable;
export type emojiReactionsView_reactable$key = {
+$data?: emojiReactionsView_reactable$data,
+$fragmentRefs: emojiReactionsView_reactable$ref,
};
*/
const node/*: ReaderFragment*/ = {
"kind": "Fragment",
"name": "emojiReactionsView_reactable",
"type": "Reactable",
"metadata": null,
"argumentDefinitions": [],
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "id",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "reactionGroups",
"storageKey": null,
"args": null,
"concreteType": "ReactionGroup",
"plural": true,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "content",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "viewerHasReacted",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "users",
"storageKey": null,
"args": null,
"concreteType": "ReactingUserConnection",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "totalCount",
"args": null,
"storageKey": null
}
]
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "viewerCanReact",
"args": null,
"storageKey": null
}
]
};
// prettier-ignore
(node/*: any*/).hash = 'fde156007f42d841401632fce79875d5';
module.exports = node;
| atom/github | lib/views/__generated__/emojiReactionsView_reactable.graphql.js | JavaScript | mit | 2,624 |
(function() {
'use strict';
angular
.module('app.match')
.run(appRun);
appRun.$inject = ['routerHelper'];
/* @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [{
state: 'match',
config: {
url: '/match/:id',
templateUrl: 'app/match/match.html',
controller: 'MatchController',
controllerAs: 'vm',
title: 'Match',
settings: {
nav: 2,
content: '<i class="fa fa-lock"></i> Match'
}
}
}];
}
})(); | otaviosoares/f2f | src/client/app/match/match.route.js | JavaScript | mit | 593 |
var loadJsons = require('../lib/loadJsons');
describe("Get a recursive directory load of JSONs", function() {
var data;
beforeEach(function(done) {
if(data) done();
else {
loadJsons("./specs")(function(d) {
data = d;
done();
});
}
});
it("Should return right number of jsons", function() {
expect(data.length).toBe(6);
});
it("Should have a @type field on all objects", function() {
data.forEach(function(d) {
expect(d['@type']).toBeDefined();
});
});
});
| polidore/dfg | specs/fileBased.spec.js | JavaScript | mit | 531 |
import axios from 'axios';
import { updateRadius } from './radius-reducer';
import { AddBType } from './b-type-reducer';
// import { create as createUser } from './users';
// import history from '../history';
/* ------------------ ACTIONS --------------------- */
const ADD_B_TYPE = 'ADD_B_TYPE';
const ADD_LNG_LAT = 'ADD_LNG_LAT';
const UPDATE_RADIUS = 'UPDATE_RADIUS';
const SWITCH_MEASUREMENT = 'SWITCH_MEASUREMENT';
/* -------------- ACTION CREATORS ----------------- */
export const addLngLat = (latitude, longitude) => ({
type: ADD_LNG_LAT,
latitude,
longitude
});
export const switchMeasurement = measurement => ({
type: SWITCH_MEASUREMENT,
measurement
});
/* ------------------ REDUCER --------------------- */
export default function reducer (state = {
latitude: null,
longitude: null,
radius: null,
businessType: null,
distanceMeasurement: 'miles'
}, action) {
switch (action.type) {
case ADD_B_TYPE:
state.businessType = action.typeStr;
break;
case ADD_LNG_LAT:
state.latitude = action.latitude;
state.longitude = action.longitude;
break;
case UPDATE_RADIUS:
state.radius = action.radInt;
break;
case SWITCH_MEASUREMENT:
state.distanceMeasurement = action.measurement;
break;
default:
return state;
}
return state;
}
| Bullseyed/Bullseye | app/reducers/report.js | JavaScript | mit | 1,361 |