repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
jonschlinkert/write-yaml
index.js
toYaml
function toYaml(data, options) { var defaults = {indent: 2, skipInvalid: false, flowLevel: -1}; var opts = extend(defaults, options); var fn = opts.safe ? yaml.safeDump : yaml.dump; return fn(data, opts); }
javascript
function toYaml(data, options) { var defaults = {indent: 2, skipInvalid: false, flowLevel: -1}; var opts = extend(defaults, options); var fn = opts.safe ? yaml.safeDump : yaml.dump; return fn(data, opts); }
[ "function", "toYaml", "(", "data", ",", "options", ")", "{", "var", "defaults", "=", "{", "indent", ":", "2", ",", "skipInvalid", ":", "false", ",", "flowLevel", ":", "-", "1", "}", ";", "var", "opts", "=", "extend", "(", "defaults", ",", "options", ")", ";", "var", "fn", "=", "opts", ".", "safe", "?", "yaml", ".", "safeDump", ":", "yaml", ".", "dump", ";", "return", "fn", "(", "data", ",", "opts", ")", ";", "}" ]
Convert data to yaml with the specified defaults and user-defined options
[ "Convert", "data", "to", "yaml", "with", "the", "specified", "defaults", "and", "user", "-", "defined", "options" ]
c261c12a77003e7cd31016021db61f646cb80b83
https://github.com/jonschlinkert/write-yaml/blob/c261c12a77003e7cd31016021db61f646cb80b83/index.js#L60-L65
train
benchpressjs/benchpressjs
lib/compiler/codegen.js
codegen
function codegen(compiled, options) { const { code } = generate(t.file(t.program(compiled)), Object.assign({}, defaults, options)); return code; }
javascript
function codegen(compiled, options) { const { code } = generate(t.file(t.program(compiled)), Object.assign({}, defaults, options)); return code; }
[ "function", "codegen", "(", "compiled", ",", "options", ")", "{", "const", "{", "code", "}", "=", "generate", "(", "t", ".", "file", "(", "t", ".", "program", "(", "compiled", ")", ")", ",", "Object", ".", "assign", "(", "{", "}", ",", "defaults", ",", "options", ")", ")", ";", "return", "code", ";", "}" ]
Generate JS code from a compiled syntax tree @param {object} compiled - Compiled JS AST @param {object} options - Babel generator options
[ "Generate", "JS", "code", "from", "a", "compiled", "syntax", "tree" ]
bf1f8b997da86867700c9a7dfc90bd33fb49270f
https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/codegen.js#L16-L20
train
benchpressjs/benchpressjs
lib/compiler/blocks.js
getBlocks
function getBlocks(ast) { ast = Array.isArray(ast) ? ast : [ast]; return ast.map((node) => { if (t.isReturnStatement(node)) { return getBlocks(node.argument); } if (t.isConditionalExpression(node)) { return node.alternate ? [ ...getBlocks(node.consequent), ...getBlocks(node.alternate), ] : getBlocks(node.consequent); } if (t.isBinaryExpression(node)) { return handleBinaryExpression(node); } return null; }).filter(Boolean).reduce((prev, arr) => prev.concat(arr), []); }
javascript
function getBlocks(ast) { ast = Array.isArray(ast) ? ast : [ast]; return ast.map((node) => { if (t.isReturnStatement(node)) { return getBlocks(node.argument); } if (t.isConditionalExpression(node)) { return node.alternate ? [ ...getBlocks(node.consequent), ...getBlocks(node.alternate), ] : getBlocks(node.consequent); } if (t.isBinaryExpression(node)) { return handleBinaryExpression(node); } return null; }).filter(Boolean).reduce((prev, arr) => prev.concat(arr), []); }
[ "function", "getBlocks", "(", "ast", ")", "{", "ast", "=", "Array", ".", "isArray", "(", "ast", ")", "?", "ast", ":", "[", "ast", "]", ";", "return", "ast", ".", "map", "(", "(", "node", ")", "=>", "{", "if", "(", "t", ".", "isReturnStatement", "(", "node", ")", ")", "{", "return", "getBlocks", "(", "node", ".", "argument", ")", ";", "}", "if", "(", "t", ".", "isConditionalExpression", "(", "node", ")", ")", "{", "return", "node", ".", "alternate", "?", "[", "...", "getBlocks", "(", "node", ".", "consequent", ")", ",", "...", "getBlocks", "(", "node", ".", "alternate", ")", ",", "]", ":", "getBlocks", "(", "node", ".", "consequent", ")", ";", "}", "if", "(", "t", ".", "isBinaryExpression", "(", "node", ")", ")", "{", "return", "handleBinaryExpression", "(", "node", ")", ";", "}", "return", "null", ";", "}", ")", ".", "filter", "(", "Boolean", ")", ".", "reduce", "(", "(", "prev", ",", "arr", ")", "=>", "prev", ".", "concat", "(", "arr", ")", ",", "[", "]", ")", ";", "}" ]
Get block from ast array @param {object[]} ast @returns {object}
[ "Get", "block", "from", "ast", "array" ]
bf1f8b997da86867700c9a7dfc90bd33fb49270f
https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/blocks.js#L37-L56
train
benchpressjs/benchpressjs
lib/compiler/blocks.js
blocks
function blocks(ast) { const body = [ast]; // start with body of function const nodes = getBlocks(ast.body.body); if (nodes.length) { const { props } = nodes.reduce(everyBlock, { keysUsed: [], props: [] }); body.push(t.expressionStatement(t.assignmentExpression( '=', c.BLOCKS, t.objectExpression(props) ))); } return body; }
javascript
function blocks(ast) { const body = [ast]; // start with body of function const nodes = getBlocks(ast.body.body); if (nodes.length) { const { props } = nodes.reduce(everyBlock, { keysUsed: [], props: [] }); body.push(t.expressionStatement(t.assignmentExpression( '=', c.BLOCKS, t.objectExpression(props) ))); } return body; }
[ "function", "blocks", "(", "ast", ")", "{", "const", "body", "=", "[", "ast", "]", ";", "const", "nodes", "=", "getBlocks", "(", "ast", ".", "body", ".", "body", ")", ";", "if", "(", "nodes", ".", "length", ")", "{", "const", "{", "props", "}", "=", "nodes", ".", "reduce", "(", "everyBlock", ",", "{", "keysUsed", ":", "[", "]", ",", "props", ":", "[", "]", "}", ")", ";", "body", ".", "push", "(", "t", ".", "expressionStatement", "(", "t", ".", "assignmentExpression", "(", "'='", ",", "c", ".", "BLOCKS", ",", "t", ".", "objectExpression", "(", "props", ")", ")", ")", ")", ";", "}", "return", "body", ";", "}" ]
Pull top-level blocks out of ast and expose them at `compiled.blocks` @param {object} ast @returns {object}
[ "Pull", "top", "-", "level", "blocks", "out", "of", "ast", "and", "expose", "them", "at", "compiled", ".", "blocks" ]
bf1f8b997da86867700c9a7dfc90bd33fb49270f
https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/blocks.js#L87-L101
train
benchpressjs/benchpressjs
lib/evaluate.js
evaluate
function evaluate(code) { const context = { module: { exports: {}, }, }; // eslint-disable-next-line no-new-func const renderFunction = new Function('module', code); renderFunction(context.module); const template = context.module.exports; return template; }
javascript
function evaluate(code) { const context = { module: { exports: {}, }, }; // eslint-disable-next-line no-new-func const renderFunction = new Function('module', code); renderFunction(context.module); const template = context.module.exports; return template; }
[ "function", "evaluate", "(", "code", ")", "{", "const", "context", "=", "{", "module", ":", "{", "exports", ":", "{", "}", ",", "}", ",", "}", ";", "const", "renderFunction", "=", "new", "Function", "(", "'module'", ",", "code", ")", ";", "renderFunction", "(", "context", ".", "module", ")", ";", "const", "template", "=", "context", ".", "module", ".", "exports", ";", "return", "template", ";", "}" ]
Evaluate a compiled template for use on the server @private @param {string} code - Compiled JS code @returns {function}
[ "Evaluate", "a", "compiled", "template", "for", "use", "on", "the", "server" ]
bf1f8b997da86867700c9a7dfc90bd33fb49270f
https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/evaluate.js#L9-L23
train
benchpressjs/benchpressjs
lib/compiler/compiler.js
PathExpression
function PathExpression(path) { const iterPattern = /^(.*)\[(\d+)]$/; const paths = path.split('.').reduce((prev, key) => { const matches = key.match(iterPattern); if (matches) { const [, rest, index] = matches; return [...prev, t.stringLiteral(rest), c.KEY_I(index)]; } return [...prev, t.stringLiteral(key)]; }, []); return paths; }
javascript
function PathExpression(path) { const iterPattern = /^(.*)\[(\d+)]$/; const paths = path.split('.').reduce((prev, key) => { const matches = key.match(iterPattern); if (matches) { const [, rest, index] = matches; return [...prev, t.stringLiteral(rest), c.KEY_I(index)]; } return [...prev, t.stringLiteral(key)]; }, []); return paths; }
[ "function", "PathExpression", "(", "path", ")", "{", "const", "iterPattern", "=", "/", "^(.*)\\[(\\d+)]$", "/", ";", "const", "paths", "=", "path", ".", "split", "(", "'.'", ")", ".", "reduce", "(", "(", "prev", ",", "key", ")", "=>", "{", "const", "matches", "=", "key", ".", "match", "(", "iterPattern", ")", ";", "if", "(", "matches", ")", "{", "const", "[", ",", "rest", ",", "index", "]", "=", "matches", ";", "return", "[", "...", "prev", ",", "t", ".", "stringLiteral", "(", "rest", ")", ",", "c", ".", "KEY_I", "(", "index", ")", "]", ";", "}", "return", "[", "...", "prev", ",", "t", ".", "stringLiteral", "(", "key", ")", "]", ";", "}", ",", "[", "]", ")", ";", "return", "paths", ";", "}" ]
Helpers for constructing AST nodes
[ "Helpers", "for", "constructing", "AST", "nodes" ]
bf1f8b997da86867700c9a7dfc90bd33fb49270f
https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/compiler.js#L10-L22
train
benchpressjs/benchpressjs
lib/compiler/compiler.js
ConcatStringList
function ConcatStringList(outputs) { return outputs.length ? outputs.reduce( (prev, next) => t.binaryExpression('+', prev, next) ) : t.stringLiteral(''); }
javascript
function ConcatStringList(outputs) { return outputs.length ? outputs.reduce( (prev, next) => t.binaryExpression('+', prev, next) ) : t.stringLiteral(''); }
[ "function", "ConcatStringList", "(", "outputs", ")", "{", "return", "outputs", ".", "length", "?", "outputs", ".", "reduce", "(", "(", "prev", ",", "next", ")", "=>", "t", ".", "binaryExpression", "(", "'+'", ",", "prev", ",", "next", ")", ")", ":", "t", ".", "stringLiteral", "(", "''", ")", ";", "}" ]
take an array of string expressions and convert it to direct concatenation like this a + b + c + d
[ "take", "an", "array", "of", "string", "expressions", "and", "convert", "it", "to", "direct", "concatenation", "like", "this", "a", "+", "b", "+", "c", "+", "d" ]
bf1f8b997da86867700c9a7dfc90bd33fb49270f
https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/compiler.js#L43-L47
train
benchpressjs/benchpressjs
lib/compiler/compiler.js
UnsafeIter
function UnsafeIter(branch) { const key = c.KEY_I(branch.iterSuffix); const arr = t.identifier('arr'); const output = t.identifier('output'); return t.callExpression(t.functionExpression(null, [], t.blockStatement([ t.variableDeclaration('var', [ t.variableDeclarator(arr, Guard(branch.subject.path)), t.variableDeclarator(output, t.stringLiteral('')), t.variableDeclarator(c.LENGTH, t.memberExpression(arr, c.LENGTH)), t.variableDeclarator(c.INDEX, t.numericLiteral(0)), t.variableDeclarator(key), t.variableDeclarator(c.KEY), ]), t.forStatement( null, t.binaryExpression('<', c.INDEX, c.LENGTH), t.updateExpression('++', c.INDEX), t.blockStatement([ t.expressionStatement(t.assignmentExpression('=', key, c.INDEX)), t.expressionStatement(t.assignmentExpression('=', c.KEY, c.INDEX)), t.expressionStatement(t.assignmentExpression('+=', output, ConcatStringList(compile(branch.body)))), ]), ), t.returnStatement(output), ])), []); }
javascript
function UnsafeIter(branch) { const key = c.KEY_I(branch.iterSuffix); const arr = t.identifier('arr'); const output = t.identifier('output'); return t.callExpression(t.functionExpression(null, [], t.blockStatement([ t.variableDeclaration('var', [ t.variableDeclarator(arr, Guard(branch.subject.path)), t.variableDeclarator(output, t.stringLiteral('')), t.variableDeclarator(c.LENGTH, t.memberExpression(arr, c.LENGTH)), t.variableDeclarator(c.INDEX, t.numericLiteral(0)), t.variableDeclarator(key), t.variableDeclarator(c.KEY), ]), t.forStatement( null, t.binaryExpression('<', c.INDEX, c.LENGTH), t.updateExpression('++', c.INDEX), t.blockStatement([ t.expressionStatement(t.assignmentExpression('=', key, c.INDEX)), t.expressionStatement(t.assignmentExpression('=', c.KEY, c.INDEX)), t.expressionStatement(t.assignmentExpression('+=', output, ConcatStringList(compile(branch.body)))), ]), ), t.returnStatement(output), ])), []); }
[ "function", "UnsafeIter", "(", "branch", ")", "{", "const", "key", "=", "c", ".", "KEY_I", "(", "branch", ".", "iterSuffix", ")", ";", "const", "arr", "=", "t", ".", "identifier", "(", "'arr'", ")", ";", "const", "output", "=", "t", ".", "identifier", "(", "'output'", ")", ";", "return", "t", ".", "callExpression", "(", "t", ".", "functionExpression", "(", "null", ",", "[", "]", ",", "t", ".", "blockStatement", "(", "[", "t", ".", "variableDeclaration", "(", "'var'", ",", "[", "t", ".", "variableDeclarator", "(", "arr", ",", "Guard", "(", "branch", ".", "subject", ".", "path", ")", ")", ",", "t", ".", "variableDeclarator", "(", "output", ",", "t", ".", "stringLiteral", "(", "''", ")", ")", ",", "t", ".", "variableDeclarator", "(", "c", ".", "LENGTH", ",", "t", ".", "memberExpression", "(", "arr", ",", "c", ".", "LENGTH", ")", ")", ",", "t", ".", "variableDeclarator", "(", "c", ".", "INDEX", ",", "t", ".", "numericLiteral", "(", "0", ")", ")", ",", "t", ".", "variableDeclarator", "(", "key", ")", ",", "t", ".", "variableDeclarator", "(", "c", ".", "KEY", ")", ",", "]", ")", ",", "t", ".", "forStatement", "(", "null", ",", "t", ".", "binaryExpression", "(", "'<'", ",", "c", ".", "INDEX", ",", "c", ".", "LENGTH", ")", ",", "t", ".", "updateExpression", "(", "'++'", ",", "c", ".", "INDEX", ")", ",", "t", ".", "blockStatement", "(", "[", "t", ".", "expressionStatement", "(", "t", ".", "assignmentExpression", "(", "'='", ",", "key", ",", "c", ".", "INDEX", ")", ")", ",", "t", ".", "expressionStatement", "(", "t", ".", "assignmentExpression", "(", "'='", ",", "c", ".", "KEY", ",", "c", ".", "INDEX", ")", ")", ",", "t", ".", "expressionStatement", "(", "t", ".", "assignmentExpression", "(", "'+='", ",", "output", ",", "ConcatStringList", "(", "compile", "(", "branch", ".", "body", ")", ")", ")", ")", ",", "]", ")", ",", ")", ",", "t", ".", "returnStatement", "(", "output", ")", ",", "]", ")", ")", ",", "[", "]", ")", ";", "}" ]
inline iteration unsafely only supports iterating over arrays-likes
[ "inline", "iteration", "unsafely", "only", "supports", "iterating", "over", "arrays", "-", "likes" ]
bf1f8b997da86867700c9a7dfc90bd33fb49270f
https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/compiler.js#L50-L77
train
benchpressjs/benchpressjs
lib/compiler/tokenizer.js
tokenizer
function tokenizer(input) { const topLevelTokens = getTopLevelTokens(); const length = input.length; const output = []; let cursor = 0; let lastBreak = 0; while (cursor < length) { const slice = input.slice(cursor); const found = matchPattern(topLevelTokens, slice, false); if (found && input[cursor - 1] === '\\') { const text = input.slice(lastBreak, cursor - 1); if (text) { output.push(new Text(text)); } const escapedText = found[1][0]; output.push(new Text(escapedText)); cursor += escapedText.length; lastBreak = cursor; } else if (found) { const [Tok, matches] = found; const text = input.slice(lastBreak, cursor); if (text) { output.push(new Text(text)); } output.push(new Tok(...matches)); cursor += matches[0].length; lastBreak = cursor; } else { cursor += 1; } } const text = input.slice(lastBreak, cursor); if (text) { output.push(new Text(text)); } // if there are more closes than opens // intelligently remove extra ones return removeExtraCloses(output); }
javascript
function tokenizer(input) { const topLevelTokens = getTopLevelTokens(); const length = input.length; const output = []; let cursor = 0; let lastBreak = 0; while (cursor < length) { const slice = input.slice(cursor); const found = matchPattern(topLevelTokens, slice, false); if (found && input[cursor - 1] === '\\') { const text = input.slice(lastBreak, cursor - 1); if (text) { output.push(new Text(text)); } const escapedText = found[1][0]; output.push(new Text(escapedText)); cursor += escapedText.length; lastBreak = cursor; } else if (found) { const [Tok, matches] = found; const text = input.slice(lastBreak, cursor); if (text) { output.push(new Text(text)); } output.push(new Tok(...matches)); cursor += matches[0].length; lastBreak = cursor; } else { cursor += 1; } } const text = input.slice(lastBreak, cursor); if (text) { output.push(new Text(text)); } // if there are more closes than opens // intelligently remove extra ones return removeExtraCloses(output); }
[ "function", "tokenizer", "(", "input", ")", "{", "const", "topLevelTokens", "=", "getTopLevelTokens", "(", ")", ";", "const", "length", "=", "input", ".", "length", ";", "const", "output", "=", "[", "]", ";", "let", "cursor", "=", "0", ";", "let", "lastBreak", "=", "0", ";", "while", "(", "cursor", "<", "length", ")", "{", "const", "slice", "=", "input", ".", "slice", "(", "cursor", ")", ";", "const", "found", "=", "matchPattern", "(", "topLevelTokens", ",", "slice", ",", "false", ")", ";", "if", "(", "found", "&&", "input", "[", "cursor", "-", "1", "]", "===", "'\\\\'", ")", "\\\\", "else", "{", "const", "text", "=", "input", ".", "slice", "(", "lastBreak", ",", "cursor", "-", "1", ")", ";", "if", "(", "text", ")", "{", "output", ".", "push", "(", "new", "Text", "(", "text", ")", ")", ";", "}", "const", "escapedText", "=", "found", "[", "1", "]", "[", "0", "]", ";", "output", ".", "push", "(", "new", "Text", "(", "escapedText", ")", ")", ";", "cursor", "+=", "escapedText", ".", "length", ";", "lastBreak", "=", "cursor", ";", "}", "}", "if", "(", "found", ")", "{", "const", "[", "Tok", ",", "matches", "]", "=", "found", ";", "const", "text", "=", "input", ".", "slice", "(", "lastBreak", ",", "cursor", ")", ";", "if", "(", "text", ")", "{", "output", ".", "push", "(", "new", "Text", "(", "text", ")", ")", ";", "}", "output", ".", "push", "(", "new", "Tok", "(", "...", "matches", ")", ")", ";", "cursor", "+=", "matches", "[", "0", "]", ".", "length", ";", "lastBreak", "=", "cursor", ";", "}", "else", "{", "cursor", "+=", "1", ";", "}", "const", "text", "=", "input", ".", "slice", "(", "lastBreak", ",", "cursor", ")", ";", "if", "(", "text", ")", "{", "output", ".", "push", "(", "new", "Text", "(", "text", ")", ")", ";", "}", "}" ]
Generate an array of tokens describing the template @param {string} input @return {Token[]}
[ "Generate", "an", "array", "of", "tokens", "describing", "the", "template" ]
bf1f8b997da86867700c9a7dfc90bd33fb49270f
https://github.com/benchpressjs/benchpressjs/blob/bf1f8b997da86867700c9a7dfc90bd33fb49270f/lib/compiler/tokenizer.js#L97-L145
train
marcuswestin/require
lib/getDependencyLevels.js
_buildDependencyTreeOf
function _buildDependencyTreeOf(node) { var requireStatements = getRequireStatements(getCode(node.path)) if (requireStatements.length == 0) { return leaves.push(node) } each(requireStatements, function(requireStatement) { var childNode = [] childNode.path = resolve.requireStatement(requireStatement, node.path) childNode.parent = node node.push(childNode) _buildDependencyTreeOf(childNode) }) node.waitingForNumChildren = node.length }
javascript
function _buildDependencyTreeOf(node) { var requireStatements = getRequireStatements(getCode(node.path)) if (requireStatements.length == 0) { return leaves.push(node) } each(requireStatements, function(requireStatement) { var childNode = [] childNode.path = resolve.requireStatement(requireStatement, node.path) childNode.parent = node node.push(childNode) _buildDependencyTreeOf(childNode) }) node.waitingForNumChildren = node.length }
[ "function", "_buildDependencyTreeOf", "(", "node", ")", "{", "var", "requireStatements", "=", "getRequireStatements", "(", "getCode", "(", "node", ".", "path", ")", ")", "if", "(", "requireStatements", ".", "length", "==", "0", ")", "{", "return", "leaves", ".", "push", "(", "node", ")", "}", "each", "(", "requireStatements", ",", "function", "(", "requireStatement", ")", "{", "var", "childNode", "=", "[", "]", "childNode", ".", "path", "=", "resolve", ".", "requireStatement", "(", "requireStatement", ",", "node", ".", "path", ")", "childNode", ".", "parent", "=", "node", "node", ".", "push", "(", "childNode", ")", "_buildDependencyTreeOf", "(", "childNode", ")", "}", ")", "node", ".", "waitingForNumChildren", "=", "node", ".", "length", "}" ]
builds full dependency tree, noting every dependency of every node
[ "builds", "full", "dependency", "tree", "noting", "every", "dependency", "of", "every", "node" ]
7d139217ed0a77bdc2a06396ca50cc2dab22510a
https://github.com/marcuswestin/require/blob/7d139217ed0a77bdc2a06396ca50cc2dab22510a/lib/getDependencyLevels.js#L22-L35
train
marcuswestin/require
lib/getDependencyLevels.js
_buildLevel
function _buildLevel(nodes) { var level = [] levels.push(level) var parents = [] each(nodes, function(node) { if (!seenPaths[node.path]) { seenPaths[node.path] = true level.push(node.path) } if (node.isRoot) { return } node.parent.waitingForNumChildren -= 1 if (node.parent.waitingForNumChildren == 0) { parents.push(node.parent) } }) if (!parents.length) { return } _buildLevel(parents) }
javascript
function _buildLevel(nodes) { var level = [] levels.push(level) var parents = [] each(nodes, function(node) { if (!seenPaths[node.path]) { seenPaths[node.path] = true level.push(node.path) } if (node.isRoot) { return } node.parent.waitingForNumChildren -= 1 if (node.parent.waitingForNumChildren == 0) { parents.push(node.parent) } }) if (!parents.length) { return } _buildLevel(parents) }
[ "function", "_buildLevel", "(", "nodes", ")", "{", "var", "level", "=", "[", "]", "levels", ".", "push", "(", "level", ")", "var", "parents", "=", "[", "]", "each", "(", "nodes", ",", "function", "(", "node", ")", "{", "if", "(", "!", "seenPaths", "[", "node", ".", "path", "]", ")", "{", "seenPaths", "[", "node", ".", "path", "]", "=", "true", "level", ".", "push", "(", "node", ".", "path", ")", "}", "if", "(", "node", ".", "isRoot", ")", "{", "return", "}", "node", ".", "parent", ".", "waitingForNumChildren", "-=", "1", "if", "(", "node", ".", "parent", ".", "waitingForNumChildren", "==", "0", ")", "{", "parents", ".", "push", "(", "node", ".", "parent", ")", "}", "}", ")", "if", "(", "!", "parents", ".", "length", ")", "{", "return", "}", "_buildLevel", "(", "parents", ")", "}" ]
builds a list of dependency levels, where nodes in each level is dependent only on nodes in levels below it the dependency levels allow for parallel loading of every file in any given level
[ "builds", "a", "list", "of", "dependency", "levels", "where", "nodes", "in", "each", "level", "is", "dependent", "only", "on", "nodes", "in", "levels", "below", "it", "the", "dependency", "levels", "allow", "for", "parallel", "loading", "of", "every", "file", "in", "any", "given", "level" ]
7d139217ed0a77bdc2a06396ca50cc2dab22510a
https://github.com/marcuswestin/require/blob/7d139217ed0a77bdc2a06396ca50cc2dab22510a/lib/getDependencyLevels.js#L39-L58
train
pvorb/node-crypt
crypt.js
function(n) { // If number given, swap endian if (n.constructor == Number) { return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; } // Else, assume array and swap all items for (var i = 0; i < n.length; i++) n[i] = crypt.endian(n[i]); return n; }
javascript
function(n) { // If number given, swap endian if (n.constructor == Number) { return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; } // Else, assume array and swap all items for (var i = 0; i < n.length; i++) n[i] = crypt.endian(n[i]); return n; }
[ "function", "(", "n", ")", "{", "if", "(", "n", ".", "constructor", "==", "Number", ")", "{", "return", "crypt", ".", "rotl", "(", "n", ",", "8", ")", "&", "0x00FF00FF", "|", "crypt", ".", "rotl", "(", "n", ",", "24", ")", "&", "0xFF00FF00", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ".", "length", ";", "i", "++", ")", "n", "[", "i", "]", "=", "crypt", ".", "endian", "(", "n", "[", "i", "]", ")", ";", "return", "n", ";", "}" ]
Swap big-endian to little-endian and vice versa
[ "Swap", "big", "-", "endian", "to", "little", "-", "endian", "and", "vice", "versa" ]
b275e2cde03cab40206dbb2a551b781f51feca3f
https://github.com/pvorb/node-crypt/blob/b275e2cde03cab40206dbb2a551b781f51feca3f/crypt.js#L17-L27
train
pvorb/node-crypt
crypt.js
function(n) { for (var bytes = []; n > 0; n--) bytes.push(Math.floor(Math.random() * 256)); return bytes; }
javascript
function(n) { for (var bytes = []; n > 0; n--) bytes.push(Math.floor(Math.random() * 256)); return bytes; }
[ "function", "(", "n", ")", "{", "for", "(", "var", "bytes", "=", "[", "]", ";", "n", ">", "0", ";", "n", "--", ")", "bytes", ".", "push", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "256", ")", ")", ";", "return", "bytes", ";", "}" ]
Generate an array of any length of random bytes
[ "Generate", "an", "array", "of", "any", "length", "of", "random", "bytes" ]
b275e2cde03cab40206dbb2a551b781f51feca3f
https://github.com/pvorb/node-crypt/blob/b275e2cde03cab40206dbb2a551b781f51feca3f/crypt.js#L30-L34
train
pvorb/node-crypt
crypt.js
function(words) { for (var bytes = [], b = 0; b < words.length * 32; b += 8) bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); return bytes; }
javascript
function(words) { for (var bytes = [], b = 0; b < words.length * 32; b += 8) bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); return bytes; }
[ "function", "(", "words", ")", "{", "for", "(", "var", "bytes", "=", "[", "]", ",", "b", "=", "0", ";", "b", "<", "words", ".", "length", "*", "32", ";", "b", "+=", "8", ")", "bytes", ".", "push", "(", "(", "words", "[", "b", ">>>", "5", "]", ">>>", "(", "24", "-", "b", "%", "32", ")", ")", "&", "0xFF", ")", ";", "return", "bytes", ";", "}" ]
Convert big-endian 32-bit words to a byte array
[ "Convert", "big", "-", "endian", "32", "-", "bit", "words", "to", "a", "byte", "array" ]
b275e2cde03cab40206dbb2a551b781f51feca3f
https://github.com/pvorb/node-crypt/blob/b275e2cde03cab40206dbb2a551b781f51feca3f/crypt.js#L44-L48
train
pvorb/node-crypt
crypt.js
function(bytes) { for (var hex = [], i = 0; i < bytes.length; i++) { hex.push((bytes[i] >>> 4).toString(16)); hex.push((bytes[i] & 0xF).toString(16)); } return hex.join(''); }
javascript
function(bytes) { for (var hex = [], i = 0; i < bytes.length; i++) { hex.push((bytes[i] >>> 4).toString(16)); hex.push((bytes[i] & 0xF).toString(16)); } return hex.join(''); }
[ "function", "(", "bytes", ")", "{", "for", "(", "var", "hex", "=", "[", "]", ",", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")", "{", "hex", ".", "push", "(", "(", "bytes", "[", "i", "]", ">>>", "4", ")", ".", "toString", "(", "16", ")", ")", ";", "hex", ".", "push", "(", "(", "bytes", "[", "i", "]", "&", "0xF", ")", ".", "toString", "(", "16", ")", ")", ";", "}", "return", "hex", ".", "join", "(", "''", ")", ";", "}" ]
Convert a byte array to a hex string
[ "Convert", "a", "byte", "array", "to", "a", "hex", "string" ]
b275e2cde03cab40206dbb2a551b781f51feca3f
https://github.com/pvorb/node-crypt/blob/b275e2cde03cab40206dbb2a551b781f51feca3f/crypt.js#L51-L57
train
pvorb/node-crypt
crypt.js
function(bytes) { for (var base64 = [], i = 0; i < bytes.length; i += 3) { var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; for (var j = 0; j < 4; j++) if (i * 8 + j * 6 <= bytes.length * 8) base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); else base64.push('='); } return base64.join(''); }
javascript
function(bytes) { for (var base64 = [], i = 0; i < bytes.length; i += 3) { var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; for (var j = 0; j < 4; j++) if (i * 8 + j * 6 <= bytes.length * 8) base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); else base64.push('='); } return base64.join(''); }
[ "function", "(", "bytes", ")", "{", "for", "(", "var", "base64", "=", "[", "]", ",", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "+=", "3", ")", "{", "var", "triplet", "=", "(", "bytes", "[", "i", "]", "<<", "16", ")", "|", "(", "bytes", "[", "i", "+", "1", "]", "<<", "8", ")", "|", "bytes", "[", "i", "+", "2", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "4", ";", "j", "++", ")", "if", "(", "i", "*", "8", "+", "j", "*", "6", "<=", "bytes", ".", "length", "*", "8", ")", "base64", ".", "push", "(", "base64map", ".", "charAt", "(", "(", "triplet", ">>>", "6", "*", "(", "3", "-", "j", ")", ")", "&", "0x3F", ")", ")", ";", "else", "base64", ".", "push", "(", "'='", ")", ";", "}", "return", "base64", ".", "join", "(", "''", ")", ";", "}" ]
Convert a byte array to a base-64 string
[ "Convert", "a", "byte", "array", "to", "a", "base", "-", "64", "string" ]
b275e2cde03cab40206dbb2a551b781f51feca3f
https://github.com/pvorb/node-crypt/blob/b275e2cde03cab40206dbb2a551b781f51feca3f/crypt.js#L67-L77
train
pvorb/node-crypt
crypt.js
function(base64) { // Remove non-base-64 characters base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { if (imod4 == 0) continue; bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); } return bytes; }
javascript
function(base64) { // Remove non-base-64 characters base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { if (imod4 == 0) continue; bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); } return bytes; }
[ "function", "(", "base64", ")", "{", "base64", "=", "base64", ".", "replace", "(", "/", "[^A-Z0-9+\\/]", "/", "ig", ",", "''", ")", ";", "for", "(", "var", "bytes", "=", "[", "]", ",", "i", "=", "0", ",", "imod4", "=", "0", ";", "i", "<", "base64", ".", "length", ";", "imod4", "=", "++", "i", "%", "4", ")", "{", "if", "(", "imod4", "==", "0", ")", "continue", ";", "bytes", ".", "push", "(", "(", "(", "base64map", ".", "indexOf", "(", "base64", ".", "charAt", "(", "i", "-", "1", ")", ")", "&", "(", "Math", ".", "pow", "(", "2", ",", "-", "2", "*", "imod4", "+", "8", ")", "-", "1", ")", ")", "<<", "(", "imod4", "*", "2", ")", ")", "|", "(", "base64map", ".", "indexOf", "(", "base64", ".", "charAt", "(", "i", ")", ")", ">>>", "(", "6", "-", "imod4", "*", "2", ")", ")", ")", ";", "}", "return", "bytes", ";", "}" ]
Convert a base-64 string to a byte array
[ "Convert", "a", "base", "-", "64", "string", "to", "a", "byte", "array" ]
b275e2cde03cab40206dbb2a551b781f51feca3f
https://github.com/pvorb/node-crypt/blob/b275e2cde03cab40206dbb2a551b781f51feca3f/crypt.js#L80-L92
train
thomaschaaf/node-ftdi
index.js
FtdiDevice
function FtdiDevice(settings) { if (typeof(settings) === 'number') { settings = { index: settings }; } EventEmitter.call(this); this.deviceSettings = settings; this.FTDIDevice = new FTDIDevice(settings); }
javascript
function FtdiDevice(settings) { if (typeof(settings) === 'number') { settings = { index: settings }; } EventEmitter.call(this); this.deviceSettings = settings; this.FTDIDevice = new FTDIDevice(settings); }
[ "function", "FtdiDevice", "(", "settings", ")", "{", "if", "(", "typeof", "(", "settings", ")", "===", "'number'", ")", "{", "settings", "=", "{", "index", ":", "settings", "}", ";", "}", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "deviceSettings", "=", "settings", ";", "this", ".", "FTDIDevice", "=", "new", "FTDIDevice", "(", "settings", ")", ";", "}" ]
FtdiDevice represents your physical device. On error 'error' will be emitted. @param {Object || Number} settings The device settings (locationId, serial, index, description).
[ "FtdiDevice", "represents", "your", "physical", "device", ".", "On", "error", "error", "will", "be", "emitted", "." ]
b8b3a6db1c0377a87613384c9ddab89980d7d2e2
https://github.com/thomaschaaf/node-ftdi/blob/b8b3a6db1c0377a87613384c9ddab89980d7d2e2/index.js#L33-L43
train
thomaschaaf/node-ftdi
index.js
function(vid, pid, callback) { if (arguments.length === 2) { callback = pid; pid = null; } else if (arguments.length === 1) { callback = vid; vid = null; pid = null; } FTDIDriver.findAll(vid, pid, callback); }
javascript
function(vid, pid, callback) { if (arguments.length === 2) { callback = pid; pid = null; } else if (arguments.length === 1) { callback = vid; vid = null; pid = null; } FTDIDriver.findAll(vid, pid, callback); }
[ "function", "(", "vid", ",", "pid", ",", "callback", ")", "{", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "callback", "=", "pid", ";", "pid", "=", "null", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "callback", "=", "vid", ";", "vid", "=", "null", ";", "pid", "=", "null", ";", "}", "FTDIDriver", ".", "findAll", "(", "vid", ",", "pid", ",", "callback", ")", ";", "}" ]
Calls the callback with an array of found devices. @param {Number} vid The vendor id. [optional] @param {Number} pid The product id. [optional] @param {Function} callback The function, that will be called when finished finding. `function(err, devices){}` devices is an array of device objects.
[ "Calls", "the", "callback", "with", "an", "array", "of", "found", "devices", "." ]
b8b3a6db1c0377a87613384c9ddab89980d7d2e2
https://github.com/thomaschaaf/node-ftdi/blob/b8b3a6db1c0377a87613384c9ddab89980d7d2e2/index.js#L136-L147
train
mljs/levenberg-marquardt
src/step.js
matrixFunction
function matrixFunction(data, evaluatedData) { const m = data.x.length; var ans = new Array(m); for (var point = 0; point < m; point++) { ans[point] = [data.y[point] - evaluatedData[point]]; } return new Matrix(ans); }
javascript
function matrixFunction(data, evaluatedData) { const m = data.x.length; var ans = new Array(m); for (var point = 0; point < m; point++) { ans[point] = [data.y[point] - evaluatedData[point]]; } return new Matrix(ans); }
[ "function", "matrixFunction", "(", "data", ",", "evaluatedData", ")", "{", "const", "m", "=", "data", ".", "x", ".", "length", ";", "var", "ans", "=", "new", "Array", "(", "m", ")", ";", "for", "(", "var", "point", "=", "0", ";", "point", "<", "m", ";", "point", "++", ")", "{", "ans", "[", "point", "]", "=", "[", "data", ".", "y", "[", "point", "]", "-", "evaluatedData", "[", "point", "]", "]", ";", "}", "return", "new", "Matrix", "(", "ans", ")", ";", "}" ]
Matrix function over the samples @ignore @param {{x:Array<number>, y:Array<number>}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] @param {Array<number>} evaluatedData - Array of previous evaluated function values @return {Matrix}
[ "Matrix", "function", "over", "the", "samples" ]
01746a1b2c18c75f4c31c1cd6917c92c3fdcfe6e
https://github.com/mljs/levenberg-marquardt/blob/01746a1b2c18c75f4c31c1cd6917c92c3fdcfe6e/src/step.js#L45-L55
train
alecxe/eslint-plugin-protractor
lib/rules/array-callback-return.js
getLocation
function getLocation (node, sourceCode) { if (node.type === 'ArrowFunctionExpression') { return sourceCode.getTokenBefore(node.body) } return node.id || node }
javascript
function getLocation (node, sourceCode) { if (node.type === 'ArrowFunctionExpression') { return sourceCode.getTokenBefore(node.body) } return node.id || node }
[ "function", "getLocation", "(", "node", ",", "sourceCode", ")", "{", "if", "(", "node", ".", "type", "===", "'ArrowFunctionExpression'", ")", "{", "return", "sourceCode", ".", "getTokenBefore", "(", "node", ".", "body", ")", "}", "return", "node", ".", "id", "||", "node", "}" ]
Gets a readable location. - FunctionExpression -> the function name or `function` keyword. - ArrowFunctionExpression -> `=>` token. @param {ASTNode} node - A function node to get. @param {SourceCode} sourceCode - A source code to get tokens. @returns {ASTNode|Token} The node or the token of a location.
[ "Gets", "a", "readable", "location", "." ]
daac6ce46f089c8e3a9d4de467a653bcc584ada4
https://github.com/alecxe/eslint-plugin-protractor/blob/daac6ce46f089c8e3a9d4de467a653bcc584ada4/lib/rules/array-callback-return.js#L41-L46
train
alecxe/eslint-plugin-protractor
lib/rules/array-callback-return.js
function (codePath, node) { funcInfo = { upper: funcInfo, codePath: codePath, hasReturn: false, shouldCheck: TARGET_NODE_TYPE.test(node.type) && node.body.type === 'BlockStatement' && isCallbackOfArrayMethod(node) } }
javascript
function (codePath, node) { funcInfo = { upper: funcInfo, codePath: codePath, hasReturn: false, shouldCheck: TARGET_NODE_TYPE.test(node.type) && node.body.type === 'BlockStatement' && isCallbackOfArrayMethod(node) } }
[ "function", "(", "codePath", ",", "node", ")", "{", "funcInfo", "=", "{", "upper", ":", "funcInfo", ",", "codePath", ":", "codePath", ",", "hasReturn", ":", "false", ",", "shouldCheck", ":", "TARGET_NODE_TYPE", ".", "test", "(", "node", ".", "type", ")", "&&", "node", ".", "body", ".", "type", "===", "'BlockStatement'", "&&", "isCallbackOfArrayMethod", "(", "node", ")", "}", "}" ]
Stacks this function's information.
[ "Stacks", "this", "function", "s", "information", "." ]
daac6ce46f089c8e3a9d4de467a653bcc584ada4
https://github.com/alecxe/eslint-plugin-protractor/blob/daac6ce46f089c8e3a9d4de467a653bcc584ada4/lib/rules/array-callback-return.js#L147-L156
train
alecxe/eslint-plugin-protractor
lib/rules/array-callback-return.js
function (node) { if (funcInfo.shouldCheck) { funcInfo.hasReturn = true if (!node.argument) { context.report({ node: node, message: 'Expected a return value' }) } } }
javascript
function (node) { if (funcInfo.shouldCheck) { funcInfo.hasReturn = true if (!node.argument) { context.report({ node: node, message: 'Expected a return value' }) } } }
[ "function", "(", "node", ")", "{", "if", "(", "funcInfo", ".", "shouldCheck", ")", "{", "funcInfo", ".", "hasReturn", "=", "true", "if", "(", "!", "node", ".", "argument", ")", "{", "context", ".", "report", "(", "{", "node", ":", "node", ",", "message", ":", "'Expected a return value'", "}", ")", "}", "}", "}" ]
Checks the return statement is valid.
[ "Checks", "the", "return", "statement", "is", "valid", "." ]
daac6ce46f089c8e3a9d4de467a653bcc584ada4
https://github.com/alecxe/eslint-plugin-protractor/blob/daac6ce46f089c8e3a9d4de467a653bcc584ada4/lib/rules/array-callback-return.js#L164-L175
train
alecxe/eslint-plugin-protractor
lib/rules/no-promise-in-if.js
hasPromise
function hasPromise (node, inBooleanPosition) { switch (node.type) { case 'CallExpression': return hasPromiseMethod(node) case 'UnaryExpression': return hasPromise(node.argument, true) case 'BinaryExpression': return hasPromise(node.left, false) || hasPromise(node.right, false) case 'LogicalExpression': var leftHasPromise = hasPromise(node.left, inBooleanPosition) var rightHasPromise = hasPromise(node.right, inBooleanPosition) return leftHasPromise || rightHasPromise case 'AssignmentExpression': return (node.operator === '=') && hasPromise(node.right, inBooleanPosition) case 'SequenceExpression': return hasPromise(node.expressions[node.expressions.length - 1], inBooleanPosition) } return false }
javascript
function hasPromise (node, inBooleanPosition) { switch (node.type) { case 'CallExpression': return hasPromiseMethod(node) case 'UnaryExpression': return hasPromise(node.argument, true) case 'BinaryExpression': return hasPromise(node.left, false) || hasPromise(node.right, false) case 'LogicalExpression': var leftHasPromise = hasPromise(node.left, inBooleanPosition) var rightHasPromise = hasPromise(node.right, inBooleanPosition) return leftHasPromise || rightHasPromise case 'AssignmentExpression': return (node.operator === '=') && hasPromise(node.right, inBooleanPosition) case 'SequenceExpression': return hasPromise(node.expressions[node.expressions.length - 1], inBooleanPosition) } return false }
[ "function", "hasPromise", "(", "node", ",", "inBooleanPosition", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "'CallExpression'", ":", "return", "hasPromiseMethod", "(", "node", ")", "case", "'UnaryExpression'", ":", "return", "hasPromise", "(", "node", ".", "argument", ",", "true", ")", "case", "'BinaryExpression'", ":", "return", "hasPromise", "(", "node", ".", "left", ",", "false", ")", "||", "hasPromise", "(", "node", ".", "right", ",", "false", ")", "case", "'LogicalExpression'", ":", "var", "leftHasPromise", "=", "hasPromise", "(", "node", ".", "left", ",", "inBooleanPosition", ")", "var", "rightHasPromise", "=", "hasPromise", "(", "node", ".", "right", ",", "inBooleanPosition", ")", "return", "leftHasPromise", "||", "rightHasPromise", "case", "'AssignmentExpression'", ":", "return", "(", "node", ".", "operator", "===", "'='", ")", "&&", "hasPromise", "(", "node", ".", "right", ",", "inBooleanPosition", ")", "case", "'SequenceExpression'", ":", "return", "hasPromise", "(", "node", ".", "expressions", "[", "node", ".", "expressions", ".", "length", "-", "1", "]", ",", "inBooleanPosition", ")", "}", "return", "false", "}" ]
Checks if a node has a promise checked for truthiness. @param {ASTNode} node The AST node to check. @param {boolean} inBooleanPosition `false` if checking branch of a condition. `true` in all other cases @returns {Bool} method name, false if no promise truthiness check found. @private
[ "Checks", "if", "a", "node", "has", "a", "promise", "checked", "for", "truthiness", "." ]
daac6ce46f089c8e3a9d4de467a653bcc584ada4
https://github.com/alecxe/eslint-plugin-protractor/blob/daac6ce46f089c8e3a9d4de467a653bcc584ada4/lib/rules/no-promise-in-if.js#L49-L73
train
alecxe/eslint-plugin-protractor
lib/rules/valid-locator-type.js
isArgumentLiteral
function isArgumentLiteral (node) { return node.arguments && node.arguments.length && node.arguments[0].type === 'Literal' }
javascript
function isArgumentLiteral (node) { return node.arguments && node.arguments.length && node.arguments[0].type === 'Literal' }
[ "function", "isArgumentLiteral", "(", "node", ")", "{", "return", "node", ".", "arguments", "&&", "node", ".", "arguments", ".", "length", "&&", "node", ".", "arguments", "[", "0", "]", ".", "type", "===", "'Literal'", "}" ]
Checks if a given CallExpression node has the first literal argument @param {ASTNode} node - A node to check. @returns {boolean}
[ "Checks", "if", "a", "given", "CallExpression", "node", "has", "the", "first", "literal", "argument" ]
daac6ce46f089c8e3a9d4de467a653bcc584ada4
https://github.com/alecxe/eslint-plugin-protractor/blob/daac6ce46f089c8e3a9d4de467a653bcc584ada4/lib/rules/valid-locator-type.js#L59-L61
train
alecxe/eslint-plugin-protractor
lib/rules/valid-locator-type.js
isArgumentByLocator
function isArgumentByLocator (node) { if (node.arguments && node.arguments.length && node.arguments[0].type === 'CallExpression') { var argument = node.arguments[0] if (argument.callee && argument.callee.object && argument.callee.object.name === 'by') { return true } } return false }
javascript
function isArgumentByLocator (node) { if (node.arguments && node.arguments.length && node.arguments[0].type === 'CallExpression') { var argument = node.arguments[0] if (argument.callee && argument.callee.object && argument.callee.object.name === 'by') { return true } } return false }
[ "function", "isArgumentByLocator", "(", "node", ")", "{", "if", "(", "node", ".", "arguments", "&&", "node", ".", "arguments", ".", "length", "&&", "node", ".", "arguments", "[", "0", "]", ".", "type", "===", "'CallExpression'", ")", "{", "var", "argument", "=", "node", ".", "arguments", "[", "0", "]", "if", "(", "argument", ".", "callee", "&&", "argument", ".", "callee", ".", "object", "&&", "argument", ".", "callee", ".", "object", ".", "name", "===", "'by'", ")", "{", "return", "true", "}", "}", "return", "false", "}" ]
Checks if a given CallExpression node has the argument the "by" expression @param {ASTNode} node - A node to check. @returns {boolean}
[ "Checks", "if", "a", "given", "CallExpression", "node", "has", "the", "argument", "the", "by", "expression" ]
daac6ce46f089c8e3a9d4de467a653bcc584ada4
https://github.com/alecxe/eslint-plugin-protractor/blob/daac6ce46f089c8e3a9d4de467a653bcc584ada4/lib/rules/valid-locator-type.js#L69-L77
train
tinganho/connect-modrewrite
index.js
_proxy
function _proxy(rule, metas) { var opts = _getRequestOpts(metas.req, rule); var request = httpsSyntax.test(rule.replace) ? httpsReq : httpReq; var pipe = request(opts, function (res) { res.headers.via = opts.headers.via; metas.res.writeHead(res.statusCode, res.headers); res.on('error', function (err) { metas.next(err); }); res.pipe(metas.res); }); pipe.on('error', function (err) { metas.next(err); }); if(!metas.req.readable) { pipe.end(); } else { metas.req.pipe(pipe); } }
javascript
function _proxy(rule, metas) { var opts = _getRequestOpts(metas.req, rule); var request = httpsSyntax.test(rule.replace) ? httpsReq : httpReq; var pipe = request(opts, function (res) { res.headers.via = opts.headers.via; metas.res.writeHead(res.statusCode, res.headers); res.on('error', function (err) { metas.next(err); }); res.pipe(metas.res); }); pipe.on('error', function (err) { metas.next(err); }); if(!metas.req.readable) { pipe.end(); } else { metas.req.pipe(pipe); } }
[ "function", "_proxy", "(", "rule", ",", "metas", ")", "{", "var", "opts", "=", "_getRequestOpts", "(", "metas", ".", "req", ",", "rule", ")", ";", "var", "request", "=", "httpsSyntax", ".", "test", "(", "rule", ".", "replace", ")", "?", "httpsReq", ":", "httpReq", ";", "var", "pipe", "=", "request", "(", "opts", ",", "function", "(", "res", ")", "{", "res", ".", "headers", ".", "via", "=", "opts", ".", "headers", ".", "via", ";", "metas", ".", "res", ".", "writeHead", "(", "res", ".", "statusCode", ",", "res", ".", "headers", ")", ";", "res", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "metas", ".", "next", "(", "err", ")", ";", "}", ")", ";", "res", ".", "pipe", "(", "metas", ".", "res", ")", ";", "}", ")", ";", "pipe", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "metas", ".", "next", "(", "err", ")", ";", "}", ")", ";", "if", "(", "!", "metas", ".", "req", ".", "readable", ")", "{", "pipe", ".", "end", "(", ")", ";", "}", "else", "{", "metas", ".", "req", ".", "pipe", "(", "pipe", ")", ";", "}", "}" ]
Proxy the request @param {Object} rule @param {Object} metas @return {void} @api private
[ "Proxy", "the", "request" ]
c3c20f76463da8b32a6790e206b36d8b86193f5e
https://github.com/tinganho/connect-modrewrite/blob/c3c20f76463da8b32a6790e206b36d8b86193f5e/index.js#L194-L216
train
tinganho/connect-modrewrite
index.js
_getRequestOpts
function _getRequestOpts(req, rule) { var opts = url.parse(req.url.replace(rule.regexp, rule.replace), true); var query = (opts.search != null) ? opts.search : ''; if(query) { opts.path = opts.pathname + query; } opts.method = req.method; opts.headers = req.headers; opts.agent = false; opts.rejectUnauthorized = false; opts.requestCert = false; var via = defaultVia; if(req.headers.via) { via = req.headers.via + ', ' + via; } opts.headers.via = via; delete opts.headers['host']; return opts; }
javascript
function _getRequestOpts(req, rule) { var opts = url.parse(req.url.replace(rule.regexp, rule.replace), true); var query = (opts.search != null) ? opts.search : ''; if(query) { opts.path = opts.pathname + query; } opts.method = req.method; opts.headers = req.headers; opts.agent = false; opts.rejectUnauthorized = false; opts.requestCert = false; var via = defaultVia; if(req.headers.via) { via = req.headers.via + ', ' + via; } opts.headers.via = via; delete opts.headers['host']; return opts; }
[ "function", "_getRequestOpts", "(", "req", ",", "rule", ")", "{", "var", "opts", "=", "url", ".", "parse", "(", "req", ".", "url", ".", "replace", "(", "rule", ".", "regexp", ",", "rule", ".", "replace", ")", ",", "true", ")", ";", "var", "query", "=", "(", "opts", ".", "search", "!=", "null", ")", "?", "opts", ".", "search", ":", "''", ";", "if", "(", "query", ")", "{", "opts", ".", "path", "=", "opts", ".", "pathname", "+", "query", ";", "}", "opts", ".", "method", "=", "req", ".", "method", ";", "opts", ".", "headers", "=", "req", ".", "headers", ";", "opts", ".", "agent", "=", "false", ";", "opts", ".", "rejectUnauthorized", "=", "false", ";", "opts", ".", "requestCert", "=", "false", ";", "var", "via", "=", "defaultVia", ";", "if", "(", "req", ".", "headers", ".", "via", ")", "{", "via", "=", "req", ".", "headers", ".", "via", "+", "', '", "+", "via", ";", "}", "opts", ".", "headers", ".", "via", "=", "via", ";", "delete", "opts", ".", "headers", "[", "'host'", "]", ";", "return", "opts", ";", "}" ]
Get request options @param {HTTPRequest} req @param {Object} rule @return {Object} @api private
[ "Get", "request", "options" ]
c3c20f76463da8b32a6790e206b36d8b86193f5e
https://github.com/tinganho/connect-modrewrite/blob/c3c20f76463da8b32a6790e206b36d8b86193f5e/index.js#L227-L248
train
peerigon/dynamic-config
plugins/extend/argv/index.js
argvPlugin
function argvPlugin(dynamicConfig, options) { var self = this; var separator; var whitelist; if (options && typeof options === "object") { separator = options.separator; whitelist = options.whitelist; } this(dynamicConfig).after("loadConfigFile", function (result) { self.override.result = merge(result, minimist(process.argv.slice(2)), separator, whitelist); }); }
javascript
function argvPlugin(dynamicConfig, options) { var self = this; var separator; var whitelist; if (options && typeof options === "object") { separator = options.separator; whitelist = options.whitelist; } this(dynamicConfig).after("loadConfigFile", function (result) { self.override.result = merge(result, minimist(process.argv.slice(2)), separator, whitelist); }); }
[ "function", "argvPlugin", "(", "dynamicConfig", ",", "options", ")", "{", "var", "self", "=", "this", ";", "var", "separator", ";", "var", "whitelist", ";", "if", "(", "options", "&&", "typeof", "options", "===", "\"object\"", ")", "{", "separator", "=", "options", ".", "separator", ";", "whitelist", "=", "options", ".", "whitelist", ";", "}", "this", "(", "dynamicConfig", ")", ".", "after", "(", "\"loadConfigFile\"", ",", "function", "(", "result", ")", "{", "self", ".", "override", ".", "result", "=", "merge", "(", "result", ",", "minimist", "(", "process", ".", "argv", ".", "slice", "(", "2", ")", ")", ",", "separator", ",", "whitelist", ")", ";", "}", ")", ";", "}" ]
Merge arguments from argv into config. @param {Function} dynamicConfig @param {Object} [options] @param {string} [options.separator=":"] @param {Array} [options.whitelist=[]] @this pluginContext
[ "Merge", "arguments", "from", "argv", "into", "config", "." ]
d75e1d7f42ef416145d91affa5ce0489e1bd2fce
https://github.com/peerigon/dynamic-config/blob/d75e1d7f42ef416145d91affa5ce0489e1bd2fce/plugins/extend/argv/index.js#L16-L29
train
peerigon/dynamic-config
plugins/extend/env/index.js
envPlugin
function envPlugin(dynamicConfig, options) { var self = this; var separator; var whitelist; if (options && typeof options === "object") { separator = options.separator; whitelist = options.whitelist; } this(dynamicConfig).after("loadConfigFile", function (result) { self.override.result = merge(result, process.env, separator, whitelist); }); }
javascript
function envPlugin(dynamicConfig, options) { var self = this; var separator; var whitelist; if (options && typeof options === "object") { separator = options.separator; whitelist = options.whitelist; } this(dynamicConfig).after("loadConfigFile", function (result) { self.override.result = merge(result, process.env, separator, whitelist); }); }
[ "function", "envPlugin", "(", "dynamicConfig", ",", "options", ")", "{", "var", "self", "=", "this", ";", "var", "separator", ";", "var", "whitelist", ";", "if", "(", "options", "&&", "typeof", "options", "===", "\"object\"", ")", "{", "separator", "=", "options", ".", "separator", ";", "whitelist", "=", "options", ".", "whitelist", ";", "}", "this", "(", "dynamicConfig", ")", ".", "after", "(", "\"loadConfigFile\"", ",", "function", "(", "result", ")", "{", "self", ".", "override", ".", "result", "=", "merge", "(", "result", ",", "process", ".", "env", ",", "separator", ",", "whitelist", ")", ";", "}", ")", ";", "}" ]
Merge from env into config. @param {Function} dynamicConfig @param {Object} [options] @param {string} [options.separator=":"] @param {Array} [options.whitelist=[]] @this pluginContext
[ "Merge", "from", "env", "into", "config", "." ]
d75e1d7f42ef416145d91affa5ce0489e1bd2fce
https://github.com/peerigon/dynamic-config/blob/d75e1d7f42ef416145d91affa5ce0489e1bd2fce/plugins/extend/env/index.js#L15-L28
train
RIAEvangelist/serialport-js
lib/open.js
open
function open (path, delimiter = '\r\n') { const self = this; const flags = 'r+'; return new Promise((resolve, reject) => { // Open file for reading and writing. An exception occurs if the file does not exist. fs.open(path, flags, (error, fd) => { if (error) { reject(error); return; } try { let promise = self.term(path, delimiter, fd); resolve(promise); } catch (termError) { reject(termError); } }); }); }
javascript
function open (path, delimiter = '\r\n') { const self = this; const flags = 'r+'; return new Promise((resolve, reject) => { // Open file for reading and writing. An exception occurs if the file does not exist. fs.open(path, flags, (error, fd) => { if (error) { reject(error); return; } try { let promise = self.term(path, delimiter, fd); resolve(promise); } catch (termError) { reject(termError); } }); }); }
[ "function", "open", "(", "path", ",", "delimiter", "=", "'\\r\\n'", ")", "\\r" ]
Opens the serialport. @param {String} path - Absolute path to the file @param {String} [delimiter='\r\n'] - Received data line delimiter @return {Promise}
[ "Opens", "the", "serialport", "." ]
1795892ea025a1b3fdf4eb04d5adee6d011669d3
https://github.com/RIAEvangelist/serialport-js/blob/1795892ea025a1b3fdf4eb04d5adee6d011669d3/lib/open.js#L14-L35
train
thlorenz/bunyan-format
lib/format-record.js
isValidRecord
function isValidRecord(rec) { if (rec.v === null || rec.level === null || rec.name === null || rec.hostname === null || rec.pid === null || rec.time === null || rec.msg === null) { // Not valid Bunyan log. return false; } else { return true; } }
javascript
function isValidRecord(rec) { if (rec.v === null || rec.level === null || rec.name === null || rec.hostname === null || rec.pid === null || rec.time === null || rec.msg === null) { // Not valid Bunyan log. return false; } else { return true; } }
[ "function", "isValidRecord", "(", "rec", ")", "{", "if", "(", "rec", ".", "v", "===", "null", "||", "rec", ".", "level", "===", "null", "||", "rec", ".", "name", "===", "null", "||", "rec", ".", "hostname", "===", "null", "||", "rec", ".", "pid", "===", "null", "||", "rec", ".", "time", "===", "null", "||", "rec", ".", "msg", "===", "null", ")", "{", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Is this a valid Bunyan log record.
[ "Is", "this", "a", "valid", "Bunyan", "log", "record", "." ]
da4ea06a283e650acfc7a595ce65c5095ab3e4d1
https://github.com/thlorenz/bunyan-format/blob/da4ea06a283e650acfc7a595ce65c5095ab3e4d1/lib/format-record.js#L59-L72
train
RIAEvangelist/serialport-js
lib/term.js
term
function term (portPath, delimiter, fd) { return new Promise((resolve, reject) => { let out = '', event = new events.EventEmitter(); try { const _fd = { fd: fd }; // Open a write stream Duplex.Writable = fs.createWriteStream(null, _fd); // Open a read stream Duplex.Readable = fs.createReadStream(null, _fd); Duplex.Readable.setEncoding('utf8'); } catch (error) { reject(error); return; } /** * Serial data receiver; emits the data when received. * @param {String} data - The received data */ Duplex.Readable.on('data', function (data) { if (!data) return; out += data; if (delimiter) { // Check if he data contains the delimiter if (out.indexOf(delimiter) < 0) { return; } // Replace the delimiter in the output data out = out.replace(delimiter, ''); } // Emit the output event.emit('data', out); // Reset the output out = ''; }); /** * Eventhandler that will close the communication. * @param {String} data - The last received data */ const onend = (data) => { if (!event.isOpen) return; event.isOpen = false; event.emit('closed', data); }; /** * Sends data to the serialport. * @param {String} data - The data to send */ const onsend = (data) => { if (!event.isOpen) return; Duplex.Writable.write(data + delimiter); }; /** * Closes the read- and writeable stream. */ const onclose = () => { // end will call `closed()` Duplex.Readable.destroy(); Duplex.Writable.destroy(); }; // Readable error handler Duplex.Readable.on('error', function (error) { process.nextTick(() => event.emit('error', error)); }); // Writable error handler Duplex.Writable.on('error', function (error) { process.nextTick(() => event.emit('error', error)); }); // Readable end handler Duplex.Readable.on('end', onend); event.serialPort = portPath; event.send = onsend; event.close = onclose; event.isOpen = true; resolve(event); }); }
javascript
function term (portPath, delimiter, fd) { return new Promise((resolve, reject) => { let out = '', event = new events.EventEmitter(); try { const _fd = { fd: fd }; // Open a write stream Duplex.Writable = fs.createWriteStream(null, _fd); // Open a read stream Duplex.Readable = fs.createReadStream(null, _fd); Duplex.Readable.setEncoding('utf8'); } catch (error) { reject(error); return; } /** * Serial data receiver; emits the data when received. * @param {String} data - The received data */ Duplex.Readable.on('data', function (data) { if (!data) return; out += data; if (delimiter) { // Check if he data contains the delimiter if (out.indexOf(delimiter) < 0) { return; } // Replace the delimiter in the output data out = out.replace(delimiter, ''); } // Emit the output event.emit('data', out); // Reset the output out = ''; }); /** * Eventhandler that will close the communication. * @param {String} data - The last received data */ const onend = (data) => { if (!event.isOpen) return; event.isOpen = false; event.emit('closed', data); }; /** * Sends data to the serialport. * @param {String} data - The data to send */ const onsend = (data) => { if (!event.isOpen) return; Duplex.Writable.write(data + delimiter); }; /** * Closes the read- and writeable stream. */ const onclose = () => { // end will call `closed()` Duplex.Readable.destroy(); Duplex.Writable.destroy(); }; // Readable error handler Duplex.Readable.on('error', function (error) { process.nextTick(() => event.emit('error', error)); }); // Writable error handler Duplex.Writable.on('error', function (error) { process.nextTick(() => event.emit('error', error)); }); // Readable end handler Duplex.Readable.on('end', onend); event.serialPort = portPath; event.send = onsend; event.close = onclose; event.isOpen = true; resolve(event); }); }
[ "function", "term", "(", "portPath", ",", "delimiter", ",", "fd", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "out", "=", "''", ",", "event", "=", "new", "events", ".", "EventEmitter", "(", ")", ";", "try", "{", "const", "_fd", "=", "{", "fd", ":", "fd", "}", ";", "Duplex", ".", "Writable", "=", "fs", ".", "createWriteStream", "(", "null", ",", "_fd", ")", ";", "Duplex", ".", "Readable", "=", "fs", ".", "createReadStream", "(", "null", ",", "_fd", ")", ";", "Duplex", ".", "Readable", ".", "setEncoding", "(", "'utf8'", ")", ";", "}", "catch", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "return", ";", "}", "Duplex", ".", "Readable", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "if", "(", "!", "data", ")", "return", ";", "out", "+=", "data", ";", "if", "(", "delimiter", ")", "{", "if", "(", "out", ".", "indexOf", "(", "delimiter", ")", "<", "0", ")", "{", "return", ";", "}", "out", "=", "out", ".", "replace", "(", "delimiter", ",", "''", ")", ";", "}", "event", ".", "emit", "(", "'data'", ",", "out", ")", ";", "out", "=", "''", ";", "}", ")", ";", "const", "onend", "=", "(", "data", ")", "=>", "{", "if", "(", "!", "event", ".", "isOpen", ")", "return", ";", "event", ".", "isOpen", "=", "false", ";", "event", ".", "emit", "(", "'closed'", ",", "data", ")", ";", "}", ";", "const", "onsend", "=", "(", "data", ")", "=>", "{", "if", "(", "!", "event", ".", "isOpen", ")", "return", ";", "Duplex", ".", "Writable", ".", "write", "(", "data", "+", "delimiter", ")", ";", "}", ";", "const", "onclose", "=", "(", ")", "=>", "{", "Duplex", ".", "Readable", ".", "destroy", "(", ")", ";", "Duplex", ".", "Writable", ".", "destroy", "(", ")", ";", "}", ";", "Duplex", ".", "Readable", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "process", ".", "nextTick", "(", "(", ")", "=>", "event", ".", "emit", "(", "'error'", ",", "error", ")", ")", ";", "}", ")", ";", "Duplex", ".", "Writable", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "process", ".", "nextTick", "(", "(", ")", "=>", "event", ".", "emit", "(", "'error'", ",", "error", ")", ")", ";", "}", ")", ";", "Duplex", ".", "Readable", ".", "on", "(", "'end'", ",", "onend", ")", ";", "event", ".", "serialPort", "=", "portPath", ";", "event", ".", "send", "=", "onsend", ";", "event", ".", "close", "=", "onclose", ";", "event", ".", "isOpen", "=", "true", ";", "resolve", "(", "event", ")", ";", "}", ")", ";", "}" ]
Read and write to serial port. @param {String} portPath - Path to the serialport @param {String} delimiter - Serial output delimiter @param {Object} fd - Filedescriptor @return {Promise}
[ "Read", "and", "write", "to", "serial", "port", "." ]
1795892ea025a1b3fdf4eb04d5adee6d011669d3
https://github.com/RIAEvangelist/serialport-js/blob/1795892ea025a1b3fdf4eb04d5adee6d011669d3/lib/term.js#L17-L111
train
flatiron/plates
lib/plates.js
compileMappings
function compileMappings(oldMappings) { var mappings = oldMappings.slice(0); mappings.sort(function(map1, map2) { if (!map1.attribute) return 1; if (!map2.attribute) return -1; if (map1.attribute !== map2.attribute) { return map1.attribute < map2.attribute ? -1 : 1; } if (map1.value !== map2.value) { return map1.value < map2.value ? -1 : 1; } if (! ('replace' in map1) && ! ('replace' in map2)) { throw new Error('Conflicting mappings for attribute ' + map1.attribute + ' and value ' + map1.value); } if (map1.replace) { return 1; } return -1; }); return mappings; }
javascript
function compileMappings(oldMappings) { var mappings = oldMappings.slice(0); mappings.sort(function(map1, map2) { if (!map1.attribute) return 1; if (!map2.attribute) return -1; if (map1.attribute !== map2.attribute) { return map1.attribute < map2.attribute ? -1 : 1; } if (map1.value !== map2.value) { return map1.value < map2.value ? -1 : 1; } if (! ('replace' in map1) && ! ('replace' in map2)) { throw new Error('Conflicting mappings for attribute ' + map1.attribute + ' and value ' + map1.value); } if (map1.replace) { return 1; } return -1; }); return mappings; }
[ "function", "compileMappings", "(", "oldMappings", ")", "{", "var", "mappings", "=", "oldMappings", ".", "slice", "(", "0", ")", ";", "mappings", ".", "sort", "(", "function", "(", "map1", ",", "map2", ")", "{", "if", "(", "!", "map1", ".", "attribute", ")", "return", "1", ";", "if", "(", "!", "map2", ".", "attribute", ")", "return", "-", "1", ";", "if", "(", "map1", ".", "attribute", "!==", "map2", ".", "attribute", ")", "{", "return", "map1", ".", "attribute", "<", "map2", ".", "attribute", "?", "-", "1", ":", "1", ";", "}", "if", "(", "map1", ".", "value", "!==", "map2", ".", "value", ")", "{", "return", "map1", ".", "value", "<", "map2", ".", "value", "?", "-", "1", ":", "1", ";", "}", "if", "(", "!", "(", "'replace'", "in", "map1", ")", "&&", "!", "(", "'replace'", "in", "map2", ")", ")", "{", "throw", "new", "Error", "(", "'Conflicting mappings for attribute '", "+", "map1", ".", "attribute", "+", "' and value '", "+", "map1", ".", "value", ")", ";", "}", "if", "(", "map1", ".", "replace", ")", "{", "return", "1", ";", "}", "return", "-", "1", ";", "}", ")", ";", "return", "mappings", ";", "}" ]
compileMappings sort the mappings so that mappings for the same attribute and value go consecutive and inside those, those that change attributes appear first.
[ "compileMappings", "sort", "the", "mappings", "so", "that", "mappings", "for", "the", "same", "attribute", "and", "value", "go", "consecutive", "and", "inside", "those", "those", "that", "change", "attributes", "appear", "first", "." ]
73b087596495fb450fa67996846cb8dc3f02ab4a
https://github.com/flatiron/plates/blob/73b087596495fb450fa67996846cb8dc3f02ab4a/lib/plates.js#L71-L94
train
flatiron/plates
lib/plates.js
matchClosing
function matchClosing(input, tagname, html) { var closeTag = '</' + tagname + '>', openTag = new RegExp('< *' + tagname + '( *|>)', 'g'), closeCount = 0, openCount = -1, from, to, chunk ; from = html.search(input); to = from; while(to > -1 && closeCount !== openCount) { to = html.indexOf(closeTag, to); if (to > -1) { to += tagname.length + 3; closeCount ++; chunk = html.slice(from, to); openCount = chunk.match(openTag).length; } } if (to === -1) { throw new Error('Unmatched tag ' + tagname + ' in ' + html) } return chunk; }
javascript
function matchClosing(input, tagname, html) { var closeTag = '</' + tagname + '>', openTag = new RegExp('< *' + tagname + '( *|>)', 'g'), closeCount = 0, openCount = -1, from, to, chunk ; from = html.search(input); to = from; while(to > -1 && closeCount !== openCount) { to = html.indexOf(closeTag, to); if (to > -1) { to += tagname.length + 3; closeCount ++; chunk = html.slice(from, to); openCount = chunk.match(openTag).length; } } if (to === -1) { throw new Error('Unmatched tag ' + tagname + ' in ' + html) } return chunk; }
[ "function", "matchClosing", "(", "input", ",", "tagname", ",", "html", ")", "{", "var", "closeTag", "=", "'</'", "+", "tagname", "+", "'>'", ",", "openTag", "=", "new", "RegExp", "(", "'< *'", "+", "tagname", "+", "'( *|>)'", ",", "'g'", ")", ",", "closeCount", "=", "0", ",", "openCount", "=", "-", "1", ",", "from", ",", "to", ",", "chunk", ";", "from", "=", "html", ".", "search", "(", "input", ")", ";", "to", "=", "from", ";", "while", "(", "to", ">", "-", "1", "&&", "closeCount", "!==", "openCount", ")", "{", "to", "=", "html", ".", "indexOf", "(", "closeTag", ",", "to", ")", ";", "if", "(", "to", ">", "-", "1", ")", "{", "to", "+=", "tagname", ".", "length", "+", "3", ";", "closeCount", "++", ";", "chunk", "=", "html", ".", "slice", "(", "from", ",", "to", ")", ";", "openCount", "=", "chunk", ".", "match", "(", "openTag", ")", ".", "length", ";", "}", "}", "if", "(", "to", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "'Unmatched tag '", "+", "tagname", "+", "' in '", "+", "html", ")", "}", "return", "chunk", ";", "}" ]
Matches a closing tag to a open tag
[ "Matches", "a", "closing", "tag", "to", "a", "open", "tag" ]
73b087596495fb450fa67996846cb8dc3f02ab4a
https://github.com/flatiron/plates/blob/73b087596495fb450fa67996846cb8dc3f02ab4a/lib/plates.js#L99-L124
train
thlorenz/bunyan-format
index.js
BunyanFormatWritable
function BunyanFormatWritable (opts, out) { if (!(this instanceof BunyanFormatWritable)) return new BunyanFormatWritable(opts, out); opts = opts || {}; opts.objectMode = true; Writable.call(this, opts); this.opts = xtend({ outputMode: 'short', color: true, colorFromLevel: { 10: 'brightBlack', // TRACE 20: 'brightBlack', // DEBUG 30: 'green', // INFO 40: 'magenta', // WARN 50: 'red', // ERROR 60: 'brightRed', // FATAL } }, opts); this.out = out || process.stdout; }
javascript
function BunyanFormatWritable (opts, out) { if (!(this instanceof BunyanFormatWritable)) return new BunyanFormatWritable(opts, out); opts = opts || {}; opts.objectMode = true; Writable.call(this, opts); this.opts = xtend({ outputMode: 'short', color: true, colorFromLevel: { 10: 'brightBlack', // TRACE 20: 'brightBlack', // DEBUG 30: 'green', // INFO 40: 'magenta', // WARN 50: 'red', // ERROR 60: 'brightRed', // FATAL } }, opts); this.out = out || process.stdout; }
[ "function", "BunyanFormatWritable", "(", "opts", ",", "out", ")", "{", "if", "(", "!", "(", "this", "instanceof", "BunyanFormatWritable", ")", ")", "return", "new", "BunyanFormatWritable", "(", "opts", ",", "out", ")", ";", "opts", "=", "opts", "||", "{", "}", ";", "opts", ".", "objectMode", "=", "true", ";", "Writable", ".", "call", "(", "this", ",", "opts", ")", ";", "this", ".", "opts", "=", "xtend", "(", "{", "outputMode", ":", "'short'", ",", "color", ":", "true", ",", "colorFromLevel", ":", "{", "10", ":", "'brightBlack'", ",", "20", ":", "'brightBlack'", ",", "30", ":", "'green'", ",", "40", ":", "'magenta'", ",", "50", ":", "'red'", ",", "60", ":", "'brightRed'", ",", "}", "}", ",", "opts", ")", ";", "this", ".", "out", "=", "out", "||", "process", ".", "stdout", ";", "}" ]
Creates a writable stream that formats bunyan records written to it. @name BunyanFormatWritable @function @param opts {Options} passed to bunyan format function - outputMode: short|long|simple|json|bunyan - color (true): toggles colors in output - colorFromLevel: allows overriding log level colors @param out {Stream} (process.stdout) writable stream to write @return {WritableStream} that you can pipe bunyan output into
[ "Creates", "a", "writable", "stream", "that", "formats", "bunyan", "records", "written", "to", "it", "." ]
da4ea06a283e650acfc7a595ce65c5095ab3e4d1
https://github.com/thlorenz/bunyan-format/blob/da4ea06a283e650acfc7a595ce65c5095ab3e4d1/index.js#L27-L47
train
intuit/node-pom-parser
lib/index.js
_parseWithXml2js
function _parseWithXml2js(xmlContent) { return new Promise(function(resolve, reject) { // parse the pom, erasing all xml2js.parseString(xmlContent, XML2JS_OPTS, function(err, pomObject) { if (err) { // Reject with the error reject(err); } // Replace the arrays with single elements with strings removeSingleArrays(pomObject); // Response to the call resolve({ pomXml: xmlContent, // Only add the pomXml when loaded from the file-system. pomObject: pomObject // Always add the object }); }); }); }
javascript
function _parseWithXml2js(xmlContent) { return new Promise(function(resolve, reject) { // parse the pom, erasing all xml2js.parseString(xmlContent, XML2JS_OPTS, function(err, pomObject) { if (err) { // Reject with the error reject(err); } // Replace the arrays with single elements with strings removeSingleArrays(pomObject); // Response to the call resolve({ pomXml: xmlContent, // Only add the pomXml when loaded from the file-system. pomObject: pomObject // Always add the object }); }); }); }
[ "function", "_parseWithXml2js", "(", "xmlContent", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "xml2js", ".", "parseString", "(", "xmlContent", ",", "XML2JS_OPTS", ",", "function", "(", "err", ",", "pomObject", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "removeSingleArrays", "(", "pomObject", ")", ";", "resolve", "(", "{", "pomXml", ":", "xmlContent", ",", "pomObject", ":", "pomObject", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Parses the given xml content. @param xmlContent {string} Is the xml content in string using utf-8 format. @param loadedXml {boolean} Whether the xml was loaded from the file-system. @param callback {function} The callback function using Javascript PCS.
[ "Parses", "the", "given", "xml", "content", "." ]
d59c365fb15a9993b0db19d87da407dccf8f744d
https://github.com/intuit/node-pom-parser/blob/d59c365fb15a9993b0db19d87da407dccf8f744d/lib/index.js#L68-L87
train
intuit/node-pom-parser
lib/index.js
removeSingleArrays
function removeSingleArrays(obj) { // Traverse all the elements of the object traverse(obj).forEach(function traversing(value) { // As the XML parser returns single fields as arrays. if (value instanceof Array && value.length === 1) { this.update(value[0]); } }); }
javascript
function removeSingleArrays(obj) { // Traverse all the elements of the object traverse(obj).forEach(function traversing(value) { // As the XML parser returns single fields as arrays. if (value instanceof Array && value.length === 1) { this.update(value[0]); } }); }
[ "function", "removeSingleArrays", "(", "obj", ")", "{", "traverse", "(", "obj", ")", ".", "forEach", "(", "function", "traversing", "(", "value", ")", "{", "if", "(", "value", "instanceof", "Array", "&&", "value", ".", "length", "===", "1", ")", "{", "this", ".", "update", "(", "value", "[", "0", "]", ")", ";", "}", "}", ")", ";", "}" ]
Removes all the arrays with single elements with a string value. @param {object} o is the object to be traversed.
[ "Removes", "all", "the", "arrays", "with", "single", "elements", "with", "a", "string", "value", "." ]
d59c365fb15a9993b0db19d87da407dccf8f744d
https://github.com/intuit/node-pom-parser/blob/d59c365fb15a9993b0db19d87da407dccf8f744d/lib/index.js#L93-L101
train
nikhilmodak/gulp-ngdocs
index.js
joinNodeModules
function joinNodeModules(jsPaths){ _.each(jsPaths, function(jsPath){ var libPath = path.join(nodeModules, jsPath), flattenedLibPath = path.join(flattenedNodeModules, jsPath); if (fs.existsSync(libPath)) { defaultScripts.push(libPath); } else if (fs.existsSync(flattenedLibPath)) { defaultScripts.push(flattenedLibPath); } else { console.error('Could not find ' + jsPath); } }); }
javascript
function joinNodeModules(jsPaths){ _.each(jsPaths, function(jsPath){ var libPath = path.join(nodeModules, jsPath), flattenedLibPath = path.join(flattenedNodeModules, jsPath); if (fs.existsSync(libPath)) { defaultScripts.push(libPath); } else if (fs.existsSync(flattenedLibPath)) { defaultScripts.push(flattenedLibPath); } else { console.error('Could not find ' + jsPath); } }); }
[ "function", "joinNodeModules", "(", "jsPaths", ")", "{", "_", ".", "each", "(", "jsPaths", ",", "function", "(", "jsPath", ")", "{", "var", "libPath", "=", "path", ".", "join", "(", "nodeModules", ",", "jsPath", ")", ",", "flattenedLibPath", "=", "path", ".", "join", "(", "flattenedNodeModules", ",", "jsPath", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "libPath", ")", ")", "{", "defaultScripts", ".", "push", "(", "libPath", ")", ";", "}", "else", "if", "(", "fs", ".", "existsSync", "(", "flattenedLibPath", ")", ")", "{", "defaultScripts", ".", "push", "(", "flattenedLibPath", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'Could not find '", "+", "jsPath", ")", ";", "}", "}", ")", ";", "}" ]
Sets default script paths
[ "Sets", "default", "script", "paths" ]
84d412873727426a0b616243b42668e1e3ba7474
https://github.com/nikhilmodak/gulp-ngdocs/blob/84d412873727426a0b616243b42668e1e3ba7474/index.js#L124-L137
train
RIAEvangelist/serialport-js
lib/find.js
find
function find () { const serialPath = this.paths.linux.serial; const readLink = (file, filePath) => ( new Promise((resolve, reject) => { fs.readlink(filePath, (error, link) => { if (error) { reject(error); } else { resolve({ 'info': file.replace(/\_/g, ' '), 'port': path.resolve(serialPath, link) }); } }); }) ); const readDir = (directory) => ( new Promise((resolve, reject) => { fs.readdir(directory, (error, files) => { if (error) { reject(error); } else { resolve(files); } }); }) ); return new Promise(async (resolve, reject) => { try { const files = await readDir(this.paths.linux.serial); if (!files.length) { // Resolve if the directory is empty resolve([]); } let promises = []; files.forEach((file) => { const filePath = path.join(serialPath, file); promises.push(readLink(file, filePath)); }); // Wait for all promisses to be resolved this.ports = await Promise.all(promises); resolve(this.ports); } catch (error) { reject(error); } }); }
javascript
function find () { const serialPath = this.paths.linux.serial; const readLink = (file, filePath) => ( new Promise((resolve, reject) => { fs.readlink(filePath, (error, link) => { if (error) { reject(error); } else { resolve({ 'info': file.replace(/\_/g, ' '), 'port': path.resolve(serialPath, link) }); } }); }) ); const readDir = (directory) => ( new Promise((resolve, reject) => { fs.readdir(directory, (error, files) => { if (error) { reject(error); } else { resolve(files); } }); }) ); return new Promise(async (resolve, reject) => { try { const files = await readDir(this.paths.linux.serial); if (!files.length) { // Resolve if the directory is empty resolve([]); } let promises = []; files.forEach((file) => { const filePath = path.join(serialPath, file); promises.push(readLink(file, filePath)); }); // Wait for all promisses to be resolved this.ports = await Promise.all(promises); resolve(this.ports); } catch (error) { reject(error); } }); }
[ "function", "find", "(", ")", "{", "const", "serialPath", "=", "this", ".", "paths", ".", "linux", ".", "serial", ";", "const", "readLink", "=", "(", "file", ",", "filePath", ")", "=>", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "readlink", "(", "filePath", ",", "(", "error", ",", "link", ")", "=>", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "else", "{", "resolve", "(", "{", "'info'", ":", "file", ".", "replace", "(", "/", "\\_", "/", "g", ",", "' '", ")", ",", "'port'", ":", "path", ".", "resolve", "(", "serialPath", ",", "link", ")", "}", ")", ";", "}", "}", ")", ";", "}", ")", ")", ";", "const", "readDir", "=", "(", "directory", ")", "=>", "(", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "readdir", "(", "directory", ",", "(", "error", ",", "files", ")", "=>", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "else", "{", "resolve", "(", "files", ")", ";", "}", "}", ")", ";", "}", ")", ")", ";", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "const", "files", "=", "await", "readDir", "(", "this", ".", "paths", ".", "linux", ".", "serial", ")", ";", "if", "(", "!", "files", ".", "length", ")", "{", "resolve", "(", "[", "]", ")", ";", "}", "let", "promises", "=", "[", "]", ";", "files", ".", "forEach", "(", "(", "file", ")", "=>", "{", "const", "filePath", "=", "path", ".", "join", "(", "serialPath", ",", "file", ")", ";", "promises", ".", "push", "(", "readLink", "(", "file", ",", "filePath", ")", ")", ";", "}", ")", ";", "this", ".", "ports", "=", "await", "Promise", ".", "all", "(", "promises", ")", ";", "resolve", "(", "this", ".", "ports", ")", ";", "}", "catch", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "}", ")", ";", "}" ]
Find all registered serial ports by-id @return {Promise<Object[]|Error>}
[ "Find", "all", "registered", "serial", "ports", "by", "-", "id" ]
1795892ea025a1b3fdf4eb04d5adee6d011669d3
https://github.com/RIAEvangelist/serialport-js/blob/1795892ea025a1b3fdf4eb04d5adee6d011669d3/lib/find.js#L14-L65
train
RIAEvangelist/serialport-js
lib/find.js
findById
function findById (id) { return new Promise(async (resolve, reject) => { try { if (!id || !id.length) { throw new Error('Undefined parameter id!'); } const ports = await this.find(); const result = ports.filter(port => port.info.includes(id)); if (!result.length) { resolve(null); } else { resolve(result[0]); } } catch (error) { reject(error); } }); }
javascript
function findById (id) { return new Promise(async (resolve, reject) => { try { if (!id || !id.length) { throw new Error('Undefined parameter id!'); } const ports = await this.find(); const result = ports.filter(port => port.info.includes(id)); if (!result.length) { resolve(null); } else { resolve(result[0]); } } catch (error) { reject(error); } }); }
[ "function", "findById", "(", "id", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "if", "(", "!", "id", "||", "!", "id", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Undefined parameter id!'", ")", ";", "}", "const", "ports", "=", "await", "this", ".", "find", "(", ")", ";", "const", "result", "=", "ports", ".", "filter", "(", "port", "=>", "port", ".", "info", ".", "includes", "(", "id", ")", ")", ";", "if", "(", "!", "result", ".", "length", ")", "{", "resolve", "(", "null", ")", ";", "}", "else", "{", "resolve", "(", "result", "[", "0", "]", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "}", ")", ";", "}" ]
Find a serialport by id. @param {String} id - The serial device id. @return {Promise<Object|Error>}
[ "Find", "a", "serialport", "by", "id", "." ]
1795892ea025a1b3fdf4eb04d5adee6d011669d3
https://github.com/RIAEvangelist/serialport-js/blob/1795892ea025a1b3fdf4eb04d5adee6d011669d3/lib/find.js#L72-L91
train
tencentyun/cos-js-sdk-v4
src/qcloud_sdk.js
sliceInit
function sliceInit(opt) { var defer = $.Deferred(); var file = opt.file; var that = this; var url = this.getCgiUrl(opt.path, opt.sign); var formData = new FormData(); var uploadparts = opt.uploadparts; formData.append('uploadparts', JSON.stringify(uploadparts)); formData.append('sha', opt.sha); formData.append('op', 'upload_slice_init'); formData.append('filesize', file.size); formData.append('slice_size', opt.sliceSize); formData.append('biz_attr', opt.biz_attr); formData.append('insertOnly', opt.insertOnly); $.ajax({ type: 'POST', dataType: "JSON", url: url, data: formData, success: function (res) { if (opt.globalTask.state === 'cancel') return; res = res || {}; if (res.code == 0) { if (res.data.access_url) {//如果秒传命中则直接返回 defer.resolve(res); return; } var session = res.data.session; var sliceSize = parseInt(res.data.slice_size); var offset = res.data.offset || 0; opt.session = session; opt.slice_size = sliceSize; opt.offset = offset; sliceUpload.call(that, opt).done(function (r) { defer.resolve(r); }).fail(function (r) { defer.reject(r); }); // 保存正在上传的 session 文件分片 sha1,用于下一次续传优化判断是否不一样的文件 var sItem, sha1Samples = {}; for (var i = 1; i < opt.uploadparts.length; i *= 2) { sItem = opt.uploadparts[i - 1]; sha1Samples[sItem.offset + '-' + sItem.datalen] = sItem.datasha; } sItem = opt.uploadparts[opt.uploadparts.length - 1]; sha1Samples[sItem.offset + '-' + sItem.datalen] = sItem.datasha; rememberSha1(opt.session, sha1Samples, that.sha1CacheExpired); } else { defer.reject(res); } }, error: function () { defer.reject(); }, processData: false, contentType: false }); return defer.promise(); }
javascript
function sliceInit(opt) { var defer = $.Deferred(); var file = opt.file; var that = this; var url = this.getCgiUrl(opt.path, opt.sign); var formData = new FormData(); var uploadparts = opt.uploadparts; formData.append('uploadparts', JSON.stringify(uploadparts)); formData.append('sha', opt.sha); formData.append('op', 'upload_slice_init'); formData.append('filesize', file.size); formData.append('slice_size', opt.sliceSize); formData.append('biz_attr', opt.biz_attr); formData.append('insertOnly', opt.insertOnly); $.ajax({ type: 'POST', dataType: "JSON", url: url, data: formData, success: function (res) { if (opt.globalTask.state === 'cancel') return; res = res || {}; if (res.code == 0) { if (res.data.access_url) {//如果秒传命中则直接返回 defer.resolve(res); return; } var session = res.data.session; var sliceSize = parseInt(res.data.slice_size); var offset = res.data.offset || 0; opt.session = session; opt.slice_size = sliceSize; opt.offset = offset; sliceUpload.call(that, opt).done(function (r) { defer.resolve(r); }).fail(function (r) { defer.reject(r); }); // 保存正在上传的 session 文件分片 sha1,用于下一次续传优化判断是否不一样的文件 var sItem, sha1Samples = {}; for (var i = 1; i < opt.uploadparts.length; i *= 2) { sItem = opt.uploadparts[i - 1]; sha1Samples[sItem.offset + '-' + sItem.datalen] = sItem.datasha; } sItem = opt.uploadparts[opt.uploadparts.length - 1]; sha1Samples[sItem.offset + '-' + sItem.datalen] = sItem.datasha; rememberSha1(opt.session, sha1Samples, that.sha1CacheExpired); } else { defer.reject(res); } }, error: function () { defer.reject(); }, processData: false, contentType: false }); return defer.promise(); }
[ "function", "sliceInit", "(", "opt", ")", "{", "var", "defer", "=", "$", ".", "Deferred", "(", ")", ";", "var", "file", "=", "opt", ".", "file", ";", "var", "that", "=", "this", ";", "var", "url", "=", "this", ".", "getCgiUrl", "(", "opt", ".", "path", ",", "opt", ".", "sign", ")", ";", "var", "formData", "=", "new", "FormData", "(", ")", ";", "var", "uploadparts", "=", "opt", ".", "uploadparts", ";", "formData", ".", "append", "(", "'uploadparts'", ",", "JSON", ".", "stringify", "(", "uploadparts", ")", ")", ";", "formData", ".", "append", "(", "'sha'", ",", "opt", ".", "sha", ")", ";", "formData", ".", "append", "(", "'op'", ",", "'upload_slice_init'", ")", ";", "formData", ".", "append", "(", "'filesize'", ",", "file", ".", "size", ")", ";", "formData", ".", "append", "(", "'slice_size'", ",", "opt", ".", "sliceSize", ")", ";", "formData", ".", "append", "(", "'biz_attr'", ",", "opt", ".", "biz_attr", ")", ";", "formData", ".", "append", "(", "'insertOnly'", ",", "opt", ".", "insertOnly", ")", ";", "$", ".", "ajax", "(", "{", "type", ":", "'POST'", ",", "dataType", ":", "\"JSON\"", ",", "url", ":", "url", ",", "data", ":", "formData", ",", "success", ":", "function", "(", "res", ")", "{", "if", "(", "opt", ".", "globalTask", ".", "state", "===", "'cancel'", ")", "return", ";", "res", "=", "res", "||", "{", "}", ";", "if", "(", "res", ".", "code", "==", "0", ")", "{", "if", "(", "res", ".", "data", ".", "access_url", ")", "{", "defer", ".", "resolve", "(", "res", ")", ";", "return", ";", "}", "var", "session", "=", "res", ".", "data", ".", "session", ";", "var", "sliceSize", "=", "parseInt", "(", "res", ".", "data", ".", "slice_size", ")", ";", "var", "offset", "=", "res", ".", "data", ".", "offset", "||", "0", ";", "opt", ".", "session", "=", "session", ";", "opt", ".", "slice_size", "=", "sliceSize", ";", "opt", ".", "offset", "=", "offset", ";", "sliceUpload", ".", "call", "(", "that", ",", "opt", ")", ".", "done", "(", "function", "(", "r", ")", "{", "defer", ".", "resolve", "(", "r", ")", ";", "}", ")", ".", "fail", "(", "function", "(", "r", ")", "{", "defer", ".", "reject", "(", "r", ")", ";", "}", ")", ";", "var", "sItem", ",", "sha1Samples", "=", "{", "}", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "opt", ".", "uploadparts", ".", "length", ";", "i", "*=", "2", ")", "{", "sItem", "=", "opt", ".", "uploadparts", "[", "i", "-", "1", "]", ";", "sha1Samples", "[", "sItem", ".", "offset", "+", "'-'", "+", "sItem", ".", "datalen", "]", "=", "sItem", ".", "datasha", ";", "}", "sItem", "=", "opt", ".", "uploadparts", "[", "opt", ".", "uploadparts", ".", "length", "-", "1", "]", ";", "sha1Samples", "[", "sItem", ".", "offset", "+", "'-'", "+", "sItem", ".", "datalen", "]", "=", "sItem", ".", "datasha", ";", "rememberSha1", "(", "opt", ".", "session", ",", "sha1Samples", ",", "that", ".", "sha1CacheExpired", ")", ";", "}", "else", "{", "defer", ".", "reject", "(", "res", ")", ";", "}", "}", ",", "error", ":", "function", "(", ")", "{", "defer", ".", "reject", "(", ")", ";", "}", ",", "processData", ":", "false", ",", "contentType", ":", "false", "}", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}" ]
slice upload init
[ "slice", "upload", "init" ]
e7e61fb82d004b0bdb04abde62a5d047beec8a2a
https://github.com/tencentyun/cos-js-sdk-v4/blob/e7e61fb82d004b0bdb04abde62a5d047beec8a2a/src/qcloud_sdk.js#L711-L779
train
geo-frontend/nlmaps
examples/googlemaps-attribution.js
AttributionControl
function AttributionControl(controlDiv) { // Set CSS for the control border. let controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.opacity = '0.7'; controlUI.style.border = '2px solid #fff'; controlUI.style.cursor = 'pointer'; controlDiv.appendChild(controlUI); // Set CSS for the control interior. let controlText = document.createElement('div'); controlText.style.color = 'rgb(25,25,25)'; controlText.style.fontFamily = 'Roboto,Arial,sans-serif'; controlText.style.fontSize = '10px'; controlText.innerHTML = ATTR; controlUI.appendChild(controlText); return controlDiv; }
javascript
function AttributionControl(controlDiv) { // Set CSS for the control border. let controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.opacity = '0.7'; controlUI.style.border = '2px solid #fff'; controlUI.style.cursor = 'pointer'; controlDiv.appendChild(controlUI); // Set CSS for the control interior. let controlText = document.createElement('div'); controlText.style.color = 'rgb(25,25,25)'; controlText.style.fontFamily = 'Roboto,Arial,sans-serif'; controlText.style.fontSize = '10px'; controlText.innerHTML = ATTR; controlUI.appendChild(controlText); return controlDiv; }
[ "function", "AttributionControl", "(", "controlDiv", ")", "{", "let", "controlUI", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "controlUI", ".", "style", ".", "backgroundColor", "=", "'#fff'", ";", "controlUI", ".", "style", ".", "opacity", "=", "'0.7'", ";", "controlUI", ".", "style", ".", "border", "=", "'2px solid #fff'", ";", "controlUI", ".", "style", ".", "cursor", "=", "'pointer'", ";", "controlDiv", ".", "appendChild", "(", "controlUI", ")", ";", "let", "controlText", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "controlText", ".", "style", ".", "color", "=", "'rgb(25,25,25)'", ";", "controlText", ".", "style", ".", "fontFamily", "=", "'Roboto,Arial,sans-serif'", ";", "controlText", ".", "style", ".", "fontSize", "=", "'10px'", ";", "controlText", ".", "innerHTML", "=", "ATTR", ";", "controlUI", ".", "appendChild", "(", "controlText", ")", ";", "return", "controlDiv", ";", "}" ]
now add an attribution control. in real life you might add CSS classes instead of setting the style here.
[ "now", "add", "an", "attribution", "control", ".", "in", "real", "life", "you", "might", "add", "CSS", "classes", "instead", "of", "setting", "the", "style", "here", "." ]
4943c4e0174e491d8ae2225da56f8ea893c5a135
https://github.com/geo-frontend/nlmaps/blob/4943c4e0174e491d8ae2225da56f8ea893c5a135/examples/googlemaps-attribution.js#L28-L45
train
centrifugal/jscent
lib/errors.js
RequestError
function RequestError(message, url, error, statusCode, body) { this.name = 'RequestError'; this.stack = (new Error()).stack; /** @member {String} error message */ this.message = message; /** @member {String} request URL */ this.url = url; /** @member optional error cause */ this.error = error; /** @member {Integer} response status code, if received */ this.statusCode = statusCode; /** @member {String} response body, if received */ this.body = body; }
javascript
function RequestError(message, url, error, statusCode, body) { this.name = 'RequestError'; this.stack = (new Error()).stack; /** @member {String} error message */ this.message = message; /** @member {String} request URL */ this.url = url; /** @member optional error cause */ this.error = error; /** @member {Integer} response status code, if received */ this.statusCode = statusCode; /** @member {String} response body, if received */ this.body = body; }
[ "function", "RequestError", "(", "message", ",", "url", ",", "error", ",", "statusCode", ",", "body", ")", "{", "this", ".", "name", "=", "'RequestError'", ";", "this", ".", "stack", "=", "(", "new", "Error", "(", ")", ")", ".", "stack", ";", "this", ".", "message", "=", "message", ";", "this", ".", "url", "=", "url", ";", "this", ".", "error", "=", "error", ";", "this", ".", "statusCode", "=", "statusCode", ";", "this", ".", "body", "=", "body", ";", "}" ]
Contains information about an HTTP request error. @constructor @extends Error @param {String} message error message @param {String} url request URL @param [error] optional error cause @param {Integer} [statusCode] response status code, if received @param {String} [body] response body, if received
[ "Contains", "information", "about", "an", "HTTP", "request", "error", "." ]
af11fc464585ba1b3065f8883884f4db4d2b4fa4
https://github.com/centrifugal/jscent/blob/af11fc464585ba1b3065f8883884f4db4d2b4fa4/lib/errors.js#L11-L25
train
geo-frontend/nlmaps
packages/lib/featurequery.js
function(source, baseUrl, requestFormatter, responseFormatter) { const querier = pointToQuery(baseUrl, requestFormatter, responseFormatter)(source); querier.subscribe = function(callback) { querier(0, callback) } return querier; }
javascript
function(source, baseUrl, requestFormatter, responseFormatter) { const querier = pointToQuery(baseUrl, requestFormatter, responseFormatter)(source); querier.subscribe = function(callback) { querier(0, callback) } return querier; }
[ "function", "(", "source", ",", "baseUrl", ",", "requestFormatter", ",", "responseFormatter", ")", "{", "const", "querier", "=", "pointToQuery", "(", "baseUrl", ",", "requestFormatter", ",", "responseFormatter", ")", "(", "source", ")", ";", "querier", ".", "subscribe", "=", "function", "(", "callback", ")", "{", "querier", "(", "0", ",", "callback", ")", "}", "return", "querier", ";", "}" ]
constructor to create a 'clickpricker' in one go.
[ "constructor", "to", "create", "a", "clickpricker", "in", "one", "go", "." ]
4943c4e0174e491d8ae2225da56f8ea893c5a135
https://github.com/geo-frontend/nlmaps/blob/4943c4e0174e491d8ae2225da56f8ea893c5a135/packages/lib/featurequery.js#L41-L47
train
psykzz/albion-api
lib/index.js
baseRequest
function baseRequest(uri, cb) { var url = `${BASE_URL}${uri}`; request(url, function (error, response, body) { debug(`Url: ${url} statusCode: ${response && response.statusCode}`); if(error || (response && response.statusCode === 404)) { cb(error || response); } cb(null, JSON.parse(body)); }); }
javascript
function baseRequest(uri, cb) { var url = `${BASE_URL}${uri}`; request(url, function (error, response, body) { debug(`Url: ${url} statusCode: ${response && response.statusCode}`); if(error || (response && response.statusCode === 404)) { cb(error || response); } cb(null, JSON.parse(body)); }); }
[ "function", "baseRequest", "(", "uri", ",", "cb", ")", "{", "var", "url", "=", "`", "${", "BASE_URL", "}", "${", "uri", "}", "`", ";", "request", "(", "url", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "debug", "(", "`", "${", "url", "}", "${", "response", "&&", "response", ".", "statusCode", "}", "`", ")", ";", "if", "(", "error", "||", "(", "response", "&&", "response", ".", "statusCode", "===", "404", ")", ")", "{", "cb", "(", "error", "||", "response", ")", ";", "}", "cb", "(", "null", ",", "JSON", ".", "parse", "(", "body", ")", ")", ";", "}", ")", ";", "}" ]
baseRequest - description @param {type} uri description @param {callback} cb description @private
[ "baseRequest", "-", "description" ]
8bbcdd705701190a184dd41fe6a60421172c932a
https://github.com/psykzz/albion-api/blob/8bbcdd705701190a184dd41fe6a60421172c932a/lib/index.js#L14-L23
train
psykzz/albion-api
lib/index.js
getServerStatus
function getServerStatus(cb) { async.parallel({ live: (cb) => { request('http://live.albiononline.com/status.txt', (error, response, body) => { if(error) { return cb(error); } cb(null, JSON.parse(body.trim())); }); }, staging: (cb) => { request('http://staging.albiononline.com/status.txt', (error, response, body) => { if(error) { return cb(error); } cb(null, JSON.parse(body.trim())); }); } }, (e, rs) => { if(e) { return cb(e); } cb(null, { live: { status: rs.live.status, message: rs.live.message, }, staging: { status: rs.staging.status, message: rs.staging.message, } }); }); }
javascript
function getServerStatus(cb) { async.parallel({ live: (cb) => { request('http://live.albiononline.com/status.txt', (error, response, body) => { if(error) { return cb(error); } cb(null, JSON.parse(body.trim())); }); }, staging: (cb) => { request('http://staging.albiononline.com/status.txt', (error, response, body) => { if(error) { return cb(error); } cb(null, JSON.parse(body.trim())); }); } }, (e, rs) => { if(e) { return cb(e); } cb(null, { live: { status: rs.live.status, message: rs.live.message, }, staging: { status: rs.staging.status, message: rs.staging.message, } }); }); }
[ "function", "getServerStatus", "(", "cb", ")", "{", "async", ".", "parallel", "(", "{", "live", ":", "(", "cb", ")", "=>", "{", "request", "(", "'http://live.albiononline.com/status.txt'", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "error", ")", "{", "return", "cb", "(", "error", ")", ";", "}", "cb", "(", "null", ",", "JSON", ".", "parse", "(", "body", ".", "trim", "(", ")", ")", ")", ";", "}", ")", ";", "}", ",", "staging", ":", "(", "cb", ")", "=>", "{", "request", "(", "'http://staging.albiononline.com/status.txt'", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "error", ")", "{", "return", "cb", "(", "error", ")", ";", "}", "cb", "(", "null", ",", "JSON", ".", "parse", "(", "body", ".", "trim", "(", ")", ")", ")", ";", "}", ")", ";", "}", "}", ",", "(", "e", ",", "rs", ")", "=>", "{", "if", "(", "e", ")", "{", "return", "cb", "(", "e", ")", ";", "}", "cb", "(", "null", ",", "{", "live", ":", "{", "status", ":", "rs", ".", "live", ".", "status", ",", "message", ":", "rs", ".", "live", ".", "message", ",", "}", ",", "staging", ":", "{", "status", ":", "rs", ".", "staging", ".", "status", ",", "message", ":", "rs", ".", "staging", ".", "message", ",", "}", "}", ")", ";", "}", ")", ";", "}" ]
getServerStatus - description @param {callback} cb description
[ "getServerStatus", "-", "description" ]
8bbcdd705701190a184dd41fe6a60421172c932a
https://github.com/psykzz/albion-api/blob/8bbcdd705701190a184dd41fe6a60421172c932a/lib/index.js#L30-L64
train
psykzz/albion-api
lib/index.js
getGuildTopKills
function getGuildTopKills(guildId, opts, cb) { opts = opts || {}; query = "?"; if(opts.limit) { query += `limit=${opts.limit}`; } if(opts.offset) { query += `offset=${opts.offset}`; } if(opts.range) { // week, lastWeek, month, lastMonth query += `range=${opts.range}`; } // https://gameinfo.albiononline.com/api/gameinfo/guilds/vFUVDtWgQwK-4NNwf0xo_w/data baseRequest(`/guilds/${guildId}/top${query}`, cb); }
javascript
function getGuildTopKills(guildId, opts, cb) { opts = opts || {}; query = "?"; if(opts.limit) { query += `limit=${opts.limit}`; } if(opts.offset) { query += `offset=${opts.offset}`; } if(opts.range) { // week, lastWeek, month, lastMonth query += `range=${opts.range}`; } // https://gameinfo.albiononline.com/api/gameinfo/guilds/vFUVDtWgQwK-4NNwf0xo_w/data baseRequest(`/guilds/${guildId}/top${query}`, cb); }
[ "function", "getGuildTopKills", "(", "guildId", ",", "opts", ",", "cb", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "query", "=", "\"?\"", ";", "if", "(", "opts", ".", "limit", ")", "{", "query", "+=", "`", "${", "opts", ".", "limit", "}", "`", ";", "}", "if", "(", "opts", ".", "offset", ")", "{", "query", "+=", "`", "${", "opts", ".", "offset", "}", "`", ";", "}", "if", "(", "opts", ".", "range", ")", "{", "query", "+=", "`", "${", "opts", ".", "range", "}", "`", ";", "}", "baseRequest", "(", "`", "${", "guildId", "}", "${", "query", "}", "`", ",", "cb", ")", ";", "}" ]
getGuildTopKills - description @param {string} guildId description @param {object} opts description @param {callback} cb description
[ "getGuildTopKills", "-", "description" ]
8bbcdd705701190a184dd41fe6a60421172c932a
https://github.com/psykzz/albion-api/blob/8bbcdd705701190a184dd41fe6a60421172c932a/lib/index.js#L160-L174
train
psykzz/albion-api
lib/index.js
getPlayerTopKills
function getPlayerTopKills(playerId, opts, cb) { // https://gameinfo.albiononline.com/api/gameinfo/players/Nubya8P6QWGhI6hDLQHIQQ opts = opts || {}; query = "?"; if(opts.limit) { query += `limit=${opts.limit}`; } if(opts.offset) { query += `offset=${opts.offset}`; } if(opts.range) { // week, lastWeek, month, lastMonth query += `range=${opts.range}`; } baseRequest(`/players/${playerId}/topkills${query}`, cb); }
javascript
function getPlayerTopKills(playerId, opts, cb) { // https://gameinfo.albiononline.com/api/gameinfo/players/Nubya8P6QWGhI6hDLQHIQQ opts = opts || {}; query = "?"; if(opts.limit) { query += `limit=${opts.limit}`; } if(opts.offset) { query += `offset=${opts.offset}`; } if(opts.range) { // week, lastWeek, month, lastMonth query += `range=${opts.range}`; } baseRequest(`/players/${playerId}/topkills${query}`, cb); }
[ "function", "getPlayerTopKills", "(", "playerId", ",", "opts", ",", "cb", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "query", "=", "\"?\"", ";", "if", "(", "opts", ".", "limit", ")", "{", "query", "+=", "`", "${", "opts", ".", "limit", "}", "`", ";", "}", "if", "(", "opts", ".", "offset", ")", "{", "query", "+=", "`", "${", "opts", ".", "offset", "}", "`", ";", "}", "if", "(", "opts", ".", "range", ")", "{", "query", "+=", "`", "${", "opts", ".", "range", "}", "`", ";", "}", "baseRequest", "(", "`", "${", "playerId", "}", "${", "query", "}", "`", ",", "cb", ")", ";", "}" ]
getPlayerTopKills - description @param {string} playerId description @param {object} opts Options @param {callback} cb description
[ "getPlayerTopKills", "-", "description" ]
8bbcdd705701190a184dd41fe6a60421172c932a
https://github.com/psykzz/albion-api/blob/8bbcdd705701190a184dd41fe6a60421172c932a/lib/index.js#L231-L245
train
geo-frontend/nlmaps
dist/nlmaps.iife.js
_enumKeys
function _enumKeys(it) { var result = _objectKeys(it); var getSymbols = _objectGops.f; if (getSymbols) { var symbols = getSymbols(it); var isEnum = _objectPie.f; var i = 0; var key; while (symbols.length > i) { if (isEnum.call(it, key = symbols[i++])) result.push(key); } }return result; }
javascript
function _enumKeys(it) { var result = _objectKeys(it); var getSymbols = _objectGops.f; if (getSymbols) { var symbols = getSymbols(it); var isEnum = _objectPie.f; var i = 0; var key; while (symbols.length > i) { if (isEnum.call(it, key = symbols[i++])) result.push(key); } }return result; }
[ "function", "_enumKeys", "(", "it", ")", "{", "var", "result", "=", "_objectKeys", "(", "it", ")", ";", "var", "getSymbols", "=", "_objectGops", ".", "f", ";", "if", "(", "getSymbols", ")", "{", "var", "symbols", "=", "getSymbols", "(", "it", ")", ";", "var", "isEnum", "=", "_objectPie", ".", "f", ";", "var", "i", "=", "0", ";", "var", "key", ";", "while", "(", "symbols", ".", "length", ">", "i", ")", "{", "if", "(", "isEnum", ".", "call", "(", "it", ",", "key", "=", "symbols", "[", "i", "++", "]", ")", ")", "result", ".", "push", "(", "key", ")", ";", "}", "}", "return", "result", ";", "}" ]
all enumerable object keys, includes symbols
[ "all", "enumerable", "object", "keys", "includes", "symbols" ]
4943c4e0174e491d8ae2225da56f8ea893c5a135
https://github.com/geo-frontend/nlmaps/blob/4943c4e0174e491d8ae2225da56f8ea893c5a135/dist/nlmaps.iife.js#L467-L479
train
geo-frontend/nlmaps
dist/nlmaps.iife.js
_flags
function _flags() { var that = _anObject(this); var result = ''; if (that.global) result += 'g'; if (that.ignoreCase) result += 'i'; if (that.multiline) result += 'm'; if (that.unicode) result += 'u'; if (that.sticky) result += 'y'; return result; }
javascript
function _flags() { var that = _anObject(this); var result = ''; if (that.global) result += 'g'; if (that.ignoreCase) result += 'i'; if (that.multiline) result += 'm'; if (that.unicode) result += 'u'; if (that.sticky) result += 'y'; return result; }
[ "function", "_flags", "(", ")", "{", "var", "that", "=", "_anObject", "(", "this", ")", ";", "var", "result", "=", "''", ";", "if", "(", "that", ".", "global", ")", "result", "+=", "'g'", ";", "if", "(", "that", ".", "ignoreCase", ")", "result", "+=", "'i'", ";", "if", "(", "that", ".", "multiline", ")", "result", "+=", "'m'", ";", "if", "(", "that", ".", "unicode", ")", "result", "+=", "'u'", ";", "if", "(", "that", ".", "sticky", ")", "result", "+=", "'y'", ";", "return", "result", ";", "}" ]
21.2.5.3 get RegExp.prototype.flags
[ "21", ".", "2", ".", "5", ".", "3", "get", "RegExp", ".", "prototype", ".", "flags" ]
4943c4e0174e491d8ae2225da56f8ea893c5a135
https://github.com/geo-frontend/nlmaps/blob/4943c4e0174e491d8ae2225da56f8ea893c5a135/dist/nlmaps.iife.js#L2602-L2611
train
geo-frontend/nlmaps
scripts/helpers.js
determineTaskList
function determineTaskList(packages, server=false) { if ( packages === null ) { return server ? conf.live_server_packages : conf.packages; } else if (typeof packages === 'string'){ return packages.split(',') } else { throw 'problem reading list of packages. It is neither empty nor a comma-separated list.' } }
javascript
function determineTaskList(packages, server=false) { if ( packages === null ) { return server ? conf.live_server_packages : conf.packages; } else if (typeof packages === 'string'){ return packages.split(',') } else { throw 'problem reading list of packages. It is neither empty nor a comma-separated list.' } }
[ "function", "determineTaskList", "(", "packages", ",", "server", "=", "false", ")", "{", "if", "(", "packages", "===", "null", ")", "{", "return", "server", "?", "conf", ".", "live_server_packages", ":", "conf", ".", "packages", ";", "}", "else", "if", "(", "typeof", "packages", "===", "'string'", ")", "{", "return", "packages", ".", "split", "(", "','", ")", "}", "else", "{", "throw", "'problem reading list of packages. It is neither empty nor a comma-separated list.'", "}", "}" ]
server argument selects packages from config for which it makes sense to start live-server.
[ "server", "argument", "selects", "packages", "from", "config", "for", "which", "it", "makes", "sense", "to", "start", "live", "-", "server", "." ]
4943c4e0174e491d8ae2225da56f8ea893c5a135
https://github.com/geo-frontend/nlmaps/blob/4943c4e0174e491d8ae2225da56f8ea893c5a135/scripts/helpers.js#L43-L51
train
geo-frontend/nlmaps
scripts/helpers.js
isRegisteredTask
function isRegisteredTask(arg) { const flag = this.server ? conf.live_server_packages.includes(arg) : conf.packages.includes(arg); if (!flag) { console.log('WARNING: a package name (' + arg +') was provided which is not specified in scripts/conf.json. Ignoring it.') } return flag; }
javascript
function isRegisteredTask(arg) { const flag = this.server ? conf.live_server_packages.includes(arg) : conf.packages.includes(arg); if (!flag) { console.log('WARNING: a package name (' + arg +') was provided which is not specified in scripts/conf.json. Ignoring it.') } return flag; }
[ "function", "isRegisteredTask", "(", "arg", ")", "{", "const", "flag", "=", "this", ".", "server", "?", "conf", ".", "live_server_packages", ".", "includes", "(", "arg", ")", ":", "conf", ".", "packages", ".", "includes", "(", "arg", ")", ";", "if", "(", "!", "flag", ")", "{", "console", ".", "log", "(", "'WARNING: a package name ('", "+", "arg", "+", "') was provided which is not specified in scripts/conf.json. Ignoring it.'", ")", "}", "return", "flag", ";", "}" ]
server argument to check against all packages or only those for which starting live-server makes sense
[ "server", "argument", "to", "check", "against", "all", "packages", "or", "only", "those", "for", "which", "starting", "live", "-", "server", "makes", "sense" ]
4943c4e0174e491d8ae2225da56f8ea893c5a135
https://github.com/geo-frontend/nlmaps/blob/4943c4e0174e491d8ae2225da56f8ea893c5a135/scripts/helpers.js#L57-L63
train
geo-frontend/nlmaps
packages/nlmaps/src/index.js
setMapLoc
function setMapLoc(lib, opts, map) { let oldZoom; let view; switch (lib) { case 'leaflet': map.panTo([opts.lat,opts.lon]); if (opts.zoom){map.setZoom(opts.zoom)} break; case 'googlemaps': map.setCenter({lat: opts.lat,lng:opts.lon}); if (opts.zoom) {map.setZoom(opts.zoom)} break; case 'openlayers': oldZoom = map.getView().getZoom(); view = new ol.View({ center: ol.proj.fromLonLat([opts.lon,opts.lat]), zoom: opts.zoom? opts.zoom: oldZoom }); map.setView(view); } }
javascript
function setMapLoc(lib, opts, map) { let oldZoom; let view; switch (lib) { case 'leaflet': map.panTo([opts.lat,opts.lon]); if (opts.zoom){map.setZoom(opts.zoom)} break; case 'googlemaps': map.setCenter({lat: opts.lat,lng:opts.lon}); if (opts.zoom) {map.setZoom(opts.zoom)} break; case 'openlayers': oldZoom = map.getView().getZoom(); view = new ol.View({ center: ol.proj.fromLonLat([opts.lon,opts.lat]), zoom: opts.zoom? opts.zoom: oldZoom }); map.setView(view); } }
[ "function", "setMapLoc", "(", "lib", ",", "opts", ",", "map", ")", "{", "let", "oldZoom", ";", "let", "view", ";", "switch", "(", "lib", ")", "{", "case", "'leaflet'", ":", "map", ".", "panTo", "(", "[", "opts", ".", "lat", ",", "opts", ".", "lon", "]", ")", ";", "if", "(", "opts", ".", "zoom", ")", "{", "map", ".", "setZoom", "(", "opts", ".", "zoom", ")", "}", "break", ";", "case", "'googlemaps'", ":", "map", ".", "setCenter", "(", "{", "lat", ":", "opts", ".", "lat", ",", "lng", ":", "opts", ".", "lon", "}", ")", ";", "if", "(", "opts", ".", "zoom", ")", "{", "map", ".", "setZoom", "(", "opts", ".", "zoom", ")", "}", "break", ";", "case", "'openlayers'", ":", "oldZoom", "=", "map", ".", "getView", "(", ")", ".", "getZoom", "(", ")", ";", "view", "=", "new", "ol", ".", "View", "(", "{", "center", ":", "ol", ".", "proj", ".", "fromLonLat", "(", "[", "opts", ".", "lon", ",", "opts", ".", "lat", "]", ")", ",", "zoom", ":", "opts", ".", "zoom", "?", "opts", ".", "zoom", ":", "oldZoom", "}", ")", ";", "map", ".", "setView", "(", "view", ")", ";", "}", "}" ]
can set center, with optional zoom. eslint-disable-next-line no-unused-vars
[ "can", "set", "center", "with", "optional", "zoom", ".", "eslint", "-", "disable", "-", "next", "-", "line", "no", "-", "unused", "-", "vars" ]
4943c4e0174e491d8ae2225da56f8ea893c5a135
https://github.com/geo-frontend/nlmaps/blob/4943c4e0174e491d8ae2225da56f8ea893c5a135/packages/nlmaps/src/index.js#L143-L163
train
kayomarz/dynamodb-data-types
lib/AttributeValue.js
wrap1
function wrap1(val, opts, key) { switch(getType(val, opts, key)) { case 'B': return {'B': val}; case 'BS': return {'BS': val}; case 'N': return {'N': val.toString()}; case 'NS': return {'NS': eachToString(val)}; case 'S': return {'S': val.toString()}; case 'SS': return {'SS': eachToString(val)}; case 'BOOL': return {'BOOL': val ? true: false}; case 'L': return {'L': val.map(function(obj){ return wrap1(obj, opts); })}; case 'M': return {'M': wrap(val, opts)}; case 'NULL': return {'NULL': true}; default: return; } }
javascript
function wrap1(val, opts, key) { switch(getType(val, opts, key)) { case 'B': return {'B': val}; case 'BS': return {'BS': val}; case 'N': return {'N': val.toString()}; case 'NS': return {'NS': eachToString(val)}; case 'S': return {'S': val.toString()}; case 'SS': return {'SS': eachToString(val)}; case 'BOOL': return {'BOOL': val ? true: false}; case 'L': return {'L': val.map(function(obj){ return wrap1(obj, opts); })}; case 'M': return {'M': wrap(val, opts)}; case 'NULL': return {'NULL': true}; default: return; } }
[ "function", "wrap1", "(", "val", ",", "opts", ",", "key", ")", "{", "switch", "(", "getType", "(", "val", ",", "opts", ",", "key", ")", ")", "{", "case", "'B'", ":", "return", "{", "'B'", ":", "val", "}", ";", "case", "'BS'", ":", "return", "{", "'BS'", ":", "val", "}", ";", "case", "'N'", ":", "return", "{", "'N'", ":", "val", ".", "toString", "(", ")", "}", ";", "case", "'NS'", ":", "return", "{", "'NS'", ":", "eachToString", "(", "val", ")", "}", ";", "case", "'S'", ":", "return", "{", "'S'", ":", "val", ".", "toString", "(", ")", "}", ";", "case", "'SS'", ":", "return", "{", "'SS'", ":", "eachToString", "(", "val", ")", "}", ";", "case", "'BOOL'", ":", "return", "{", "'BOOL'", ":", "val", "?", "true", ":", "false", "}", ";", "case", "'L'", ":", "return", "{", "'L'", ":", "val", ".", "map", "(", "function", "(", "obj", ")", "{", "return", "wrap1", "(", "obj", ",", "opts", ")", ";", "}", ")", "}", ";", "case", "'M'", ":", "return", "{", "'M'", ":", "wrap", "(", "val", ",", "opts", ")", "}", ";", "case", "'NULL'", ":", "return", "{", "'NULL'", ":", "true", "}", ";", "default", ":", "return", ";", "}", "}" ]
Wrap a single value into DynamoDB's AttributeValue. @param {String|Number|Array} val The value to wrap. @return {Object} DynamoDB AttributeValue.
[ "Wrap", "a", "single", "value", "into", "DynamoDB", "s", "AttributeValue", "." ]
7e4afb360e8aa61a0812709a8d5e64cbb400f192
https://github.com/kayomarz/dynamodb-data-types/blob/7e4afb360e8aa61a0812709a8d5e64cbb400f192/lib/AttributeValue.js#L110-L124
train
kayomarz/dynamodb-data-types
lib/AttributeValue.js
wrap
function wrap(obj, opts) { var result = {}; for (var key in obj) { if(obj.hasOwnProperty(key)) { var wrapped = wrap1(obj[key], opts, key); if (typeof wrapped !== 'undefined') result[key] = wrapped; } } return result; }
javascript
function wrap(obj, opts) { var result = {}; for (var key in obj) { if(obj.hasOwnProperty(key)) { var wrapped = wrap1(obj[key], opts, key); if (typeof wrapped !== 'undefined') result[key] = wrapped; } } return result; }
[ "function", "wrap", "(", "obj", ",", "opts", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "var", "wrapped", "=", "wrap1", "(", "obj", "[", "key", "]", ",", "opts", ",", "key", ")", ";", "if", "(", "typeof", "wrapped", "!==", "'undefined'", ")", "result", "[", "key", "]", "=", "wrapped", ";", "}", "}", "return", "result", ";", "}" ]
Wrap object properties into DynamoDB's AttributeValue data type. @param {Object} obj The object to wrap. @return {Object} A DynamoDb AttributeValue.
[ "Wrap", "object", "properties", "into", "DynamoDB", "s", "AttributeValue", "data", "type", "." ]
7e4afb360e8aa61a0812709a8d5e64cbb400f192
https://github.com/kayomarz/dynamodb-data-types/blob/7e4afb360e8aa61a0812709a8d5e64cbb400f192/lib/AttributeValue.js#L131-L141
train
kayomarz/dynamodb-data-types
lib/AttributeValue.js
unwrap1
function unwrap1(dynamoData) { var keys = Object.keys(dynamoData); if (keys.length !== 1) throw new Error('Unexpected DynamoDB AttributeValue'); var typeStr = keys[0]; if (!unwrapFns.hasOwnProperty(typeStr)) throw errs.NoDatatype; var val = dynamoData[typeStr]; return unwrapFns[typeStr] ? unwrapFns[typeStr](val) : val; }
javascript
function unwrap1(dynamoData) { var keys = Object.keys(dynamoData); if (keys.length !== 1) throw new Error('Unexpected DynamoDB AttributeValue'); var typeStr = keys[0]; if (!unwrapFns.hasOwnProperty(typeStr)) throw errs.NoDatatype; var val = dynamoData[typeStr]; return unwrapFns[typeStr] ? unwrapFns[typeStr](val) : val; }
[ "function", "unwrap1", "(", "dynamoData", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "dynamoData", ")", ";", "if", "(", "keys", ".", "length", "!==", "1", ")", "throw", "new", "Error", "(", "'Unexpected DynamoDB AttributeValue'", ")", ";", "var", "typeStr", "=", "keys", "[", "0", "]", ";", "if", "(", "!", "unwrapFns", ".", "hasOwnProperty", "(", "typeStr", ")", ")", "throw", "errs", ".", "NoDatatype", ";", "var", "val", "=", "dynamoData", "[", "typeStr", "]", ";", "return", "unwrapFns", "[", "typeStr", "]", "?", "unwrapFns", "[", "typeStr", "]", "(", "val", ")", ":", "val", ";", "}" ]
Unwrap a single DynamoDB's AttributeValue to a value of the appropriate javascript type. @param {Object} attributeValue The DynamoDB AttributeValue. @return {String|Number|Array} The javascript value.
[ "Unwrap", "a", "single", "DynamoDB", "s", "AttributeValue", "to", "a", "value", "of", "the", "appropriate", "javascript", "type", "." ]
7e4afb360e8aa61a0812709a8d5e64cbb400f192
https://github.com/kayomarz/dynamodb-data-types/blob/7e4afb360e8aa61a0812709a8d5e64cbb400f192/lib/AttributeValue.js#L166-L175
train
kayomarz/dynamodb-data-types
lib/AttributeValue.js
unwrap
function unwrap(attrVal) { var result = {}; for (var key in attrVal) { if(attrVal.hasOwnProperty(key)) { var value = attrVal[key]; if (value !== null && typeof value !== 'undefined') result[key] = unwrap1(attrVal[key]); } } return result; }
javascript
function unwrap(attrVal) { var result = {}; for (var key in attrVal) { if(attrVal.hasOwnProperty(key)) { var value = attrVal[key]; if (value !== null && typeof value !== 'undefined') result[key] = unwrap1(attrVal[key]); } } return result; }
[ "function", "unwrap", "(", "attrVal", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "var", "key", "in", "attrVal", ")", "{", "if", "(", "attrVal", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "var", "value", "=", "attrVal", "[", "key", "]", ";", "if", "(", "value", "!==", "null", "&&", "typeof", "value", "!==", "'undefined'", ")", "result", "[", "key", "]", "=", "unwrap1", "(", "attrVal", "[", "key", "]", ")", ";", "}", "}", "return", "result", ";", "}" ]
Unwrap DynamoDB AttributeValues to values of the appropriate types. @param {Object} attributeValue The DynamoDb AttributeValue to unwrap. @return {Object} Unwrapped object with properties.
[ "Unwrap", "DynamoDB", "AttributeValues", "to", "values", "of", "the", "appropriate", "types", "." ]
7e4afb360e8aa61a0812709a8d5e64cbb400f192
https://github.com/kayomarz/dynamodb-data-types/blob/7e4afb360e8aa61a0812709a8d5e64cbb400f192/lib/AttributeValue.js#L182-L192
train
CascadeEnergy/dynamoDb-marshaler
lib/marshalingCommands.js
marshalList
function marshalList(item, marshal) { return transform(_.isArray, _.compose(objOf('L'), _.map(marshal)), item); }
javascript
function marshalList(item, marshal) { return transform(_.isArray, _.compose(objOf('L'), _.map(marshal)), item); }
[ "function", "marshalList", "(", "item", ",", "marshal", ")", "{", "return", "transform", "(", "_", ".", "isArray", ",", "_", ".", "compose", "(", "objOf", "(", "'L'", ")", ",", "_", ".", "map", "(", "marshal", ")", ")", ",", "item", ")", ";", "}" ]
Converts mixed array to DynamoDb "L" @param item @param marshal @returns {*}
[ "Converts", "mixed", "array", "to", "DynamoDb", "L" ]
38bddd0e886dfd285975ba82319fac069f52d243
https://github.com/CascadeEnergy/dynamoDb-marshaler/blob/38bddd0e886dfd285975ba82319fac069f52d243/lib/marshalingCommands.js#L24-L26
train
CascadeEnergy/dynamoDb-marshaler
lib/marshalingCommands.js
marshalMap
function marshalMap(item, marshal) { return transform(_.isPlainObject, _.compose(objOf('M'), _.mapValues(marshal)), item); }
javascript
function marshalMap(item, marshal) { return transform(_.isPlainObject, _.compose(objOf('M'), _.mapValues(marshal)), item); }
[ "function", "marshalMap", "(", "item", ",", "marshal", ")", "{", "return", "transform", "(", "_", ".", "isPlainObject", ",", "_", ".", "compose", "(", "objOf", "(", "'M'", ")", ",", "_", ".", "mapValues", "(", "marshal", ")", ")", ",", "item", ")", ";", "}" ]
Converts object literal to DynamoDb "M" @param item @param marshal @returns {*}
[ "Converts", "object", "literal", "to", "DynamoDb", "M" ]
38bddd0e886dfd285975ba82319fac069f52d243
https://github.com/CascadeEnergy/dynamoDb-marshaler/blob/38bddd0e886dfd285975ba82319fac069f52d243/lib/marshalingCommands.js#L35-L37
train
anseki/htmlclean
lib/htmlclean.js
function(str, tagInner) { tagInner = tagInner .replace(/^ +| +$/g, '') // Not .trim() that removes \f. .replace(/(?: *\/ +| +\/ *)/g, '/') // Remove whitespaces in </ p> or <br /> .replace(/ *= */g, '='); return '<' + tagInner + '>'; }
javascript
function(str, tagInner) { tagInner = tagInner .replace(/^ +| +$/g, '') // Not .trim() that removes \f. .replace(/(?: *\/ +| +\/ *)/g, '/') // Remove whitespaces in </ p> or <br /> .replace(/ *= */g, '='); return '<' + tagInner + '>'; }
[ "function", "(", "str", ",", "tagInner", ")", "{", "tagInner", "=", "tagInner", ".", "replace", "(", "/", "^ +| +$", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "(?: *\\/ +| +\\/ *)", "/", "g", ",", "'/'", ")", ".", "replace", "(", "/", " *= *", "/", "g", ",", "'='", ")", ";", "return", "'<'", "+", "tagInner", "+", "'>'", ";", "}" ]
`>` in attributes were already replaced
[ ">", "in", "attributes", "were", "already", "replaced" ]
5798eebea5253848282563bea04211899336bf7a
https://github.com/anseki/htmlclean/blob/5798eebea5253848282563bea04211899336bf7a/lib/htmlclean.js#L293-L299
train
CascadeEnergy/dynamoDb-marshaler
lib/unmarshalingCommands.js
unmarshalList
function unmarshalList(item, unmarshal) { return transform(_.has('L'), _.compose(_.map(unmarshal), _.property('L')), item); }
javascript
function unmarshalList(item, unmarshal) { return transform(_.has('L'), _.compose(_.map(unmarshal), _.property('L')), item); }
[ "function", "unmarshalList", "(", "item", ",", "unmarshal", ")", "{", "return", "transform", "(", "_", ".", "has", "(", "'L'", ")", ",", "_", ".", "compose", "(", "_", ".", "map", "(", "unmarshal", ")", ",", "_", ".", "property", "(", "'L'", ")", ")", ",", "item", ")", ";", "}" ]
Converts DynamoDb "L" to mixed array @param item @param unmarshal @returns {*}
[ "Converts", "DynamoDb", "L", "to", "mixed", "array" ]
38bddd0e886dfd285975ba82319fac069f52d243
https://github.com/CascadeEnergy/dynamoDb-marshaler/blob/38bddd0e886dfd285975ba82319fac069f52d243/lib/unmarshalingCommands.js#L14-L16
train
CascadeEnergy/dynamoDb-marshaler
lib/unmarshalingCommands.js
unmarshalMap
function unmarshalMap(item, unmarshal) { return transform(_.has('M'), _.compose(_.mapValues(unmarshal), _.property('M')), item); }
javascript
function unmarshalMap(item, unmarshal) { return transform(_.has('M'), _.compose(_.mapValues(unmarshal), _.property('M')), item); }
[ "function", "unmarshalMap", "(", "item", ",", "unmarshal", ")", "{", "return", "transform", "(", "_", ".", "has", "(", "'M'", ")", ",", "_", ".", "compose", "(", "_", ".", "mapValues", "(", "unmarshal", ")", ",", "_", ".", "property", "(", "'M'", ")", ")", ",", "item", ")", ";", "}" ]
Converts DynamoDb "M" to object literal @param item @param unmarshal @returns {*}
[ "Converts", "DynamoDb", "M", "to", "object", "literal" ]
38bddd0e886dfd285975ba82319fac069f52d243
https://github.com/CascadeEnergy/dynamoDb-marshaler/blob/38bddd0e886dfd285975ba82319fac069f52d243/lib/unmarshalingCommands.js#L25-L27
train
CascadeEnergy/dynamoDb-marshaler
lib/unmarshalingCommands.js
unmarshalPassThrough
function unmarshalPassThrough(item) { var key = _.find(function(type) { return _.has(type, item); }, ['S', 'B', 'BS', 'BOOL']); return !key ? void 0 : item[key]; }
javascript
function unmarshalPassThrough(item) { var key = _.find(function(type) { return _.has(type, item); }, ['S', 'B', 'BS', 'BOOL']); return !key ? void 0 : item[key]; }
[ "function", "unmarshalPassThrough", "(", "item", ")", "{", "var", "key", "=", "_", ".", "find", "(", "function", "(", "type", ")", "{", "return", "_", ".", "has", "(", "type", ",", "item", ")", ";", "}", ",", "[", "'S'", ",", "'B'", ",", "'BS'", ",", "'BOOL'", "]", ")", ";", "return", "!", "key", "?", "void", "0", ":", "item", "[", "key", "]", ";", "}" ]
Converts DynamoDb "S", "B", "BS", "BOOL" to values. @param item @returns {*}
[ "Converts", "DynamoDb", "S", "B", "BS", "BOOL", "to", "values", "." ]
38bddd0e886dfd285975ba82319fac069f52d243
https://github.com/CascadeEnergy/dynamoDb-marshaler/blob/38bddd0e886dfd285975ba82319fac069f52d243/lib/unmarshalingCommands.js#L68-L74
train
sandflow/imscJS
src/main/js/styles.js
StylingAttributeDefinition
function StylingAttributeDefinition(ns, name, initialValue, appliesTo, isInherit, isAnimatable, parseFunc, computeFunc) { this.name = name; this.ns = ns; this.qname = ns + " " + name; this.inherit = isInherit; this.animatable = isAnimatable; this.initial = initialValue; this.applies = appliesTo; this.parse = parseFunc; this.compute = computeFunc; }
javascript
function StylingAttributeDefinition(ns, name, initialValue, appliesTo, isInherit, isAnimatable, parseFunc, computeFunc) { this.name = name; this.ns = ns; this.qname = ns + " " + name; this.inherit = isInherit; this.animatable = isAnimatable; this.initial = initialValue; this.applies = appliesTo; this.parse = parseFunc; this.compute = computeFunc; }
[ "function", "StylingAttributeDefinition", "(", "ns", ",", "name", ",", "initialValue", ",", "appliesTo", ",", "isInherit", ",", "isAnimatable", ",", "parseFunc", ",", "computeFunc", ")", "{", "this", ".", "name", "=", "name", ";", "this", ".", "ns", "=", "ns", ";", "this", ".", "qname", "=", "ns", "+", "\" \"", "+", "name", ";", "this", ".", "inherit", "=", "isInherit", ";", "this", ".", "animatable", "=", "isAnimatable", ";", "this", ".", "initial", "=", "initialValue", ";", "this", ".", "applies", "=", "appliesTo", ";", "this", ".", "parse", "=", "parseFunc", ";", "this", ".", "compute", "=", "computeFunc", ";", "}" ]
wrapper for non-node envs
[ "wrapper", "for", "non", "-", "node", "envs" ]
0917ee9c7c7e82342529f51348580889a78d1022
https://github.com/sandflow/imscJS/blob/0917ee9c7c7e82342529f51348580889a78d1022/src/main/js/styles.js#L34-L44
train
zumba/angular-waypoints
dist/angular-waypoints.all.js
parseWaypoint
function parseWaypoint(qualifiedWaypoint) { var parts; if (!parsedWaypoints[qualifiedWaypoint]) { parts = qualifiedWaypoint.split('.'); if (parts.length === 1) { parts.unshift('globals'); } parsedWaypoints[qualifiedWaypoint] = { namespace : parts.shift(), waypoint : parts.join('.') }; } return parsedWaypoints[qualifiedWaypoint]; }
javascript
function parseWaypoint(qualifiedWaypoint) { var parts; if (!parsedWaypoints[qualifiedWaypoint]) { parts = qualifiedWaypoint.split('.'); if (parts.length === 1) { parts.unshift('globals'); } parsedWaypoints[qualifiedWaypoint] = { namespace : parts.shift(), waypoint : parts.join('.') }; } return parsedWaypoints[qualifiedWaypoint]; }
[ "function", "parseWaypoint", "(", "qualifiedWaypoint", ")", "{", "var", "parts", ";", "if", "(", "!", "parsedWaypoints", "[", "qualifiedWaypoint", "]", ")", "{", "parts", "=", "qualifiedWaypoint", ".", "split", "(", "'.'", ")", ";", "if", "(", "parts", ".", "length", "===", "1", ")", "{", "parts", ".", "unshift", "(", "'globals'", ")", ";", "}", "parsedWaypoints", "[", "qualifiedWaypoint", "]", "=", "{", "namespace", ":", "parts", ".", "shift", "(", ")", ",", "waypoint", ":", "parts", ".", "join", "(", "'.'", ")", "}", ";", "}", "return", "parsedWaypoints", "[", "qualifiedWaypoint", "]", ";", "}" ]
Get a namespace for the waypoint @param String qualifiedWaypoint @return String
[ "Get", "a", "namespace", "for", "the", "waypoint" ]
b574303913ac003cd0f73ca103d7109712567d4d
https://github.com/zumba/angular-waypoints/blob/b574303913ac003cd0f73ca103d7109712567d4d/dist/angular-waypoints.all.js#L820-L833
train
zumba/angular-waypoints
dist/angular-waypoints.all.js
setWaypoint
function setWaypoint(collection, waypoint) { angular.forEach(collection, function (value, waypoint) { collection[waypoint] = false; }); collection[waypoint] = true; }
javascript
function setWaypoint(collection, waypoint) { angular.forEach(collection, function (value, waypoint) { collection[waypoint] = false; }); collection[waypoint] = true; }
[ "function", "setWaypoint", "(", "collection", ",", "waypoint", ")", "{", "angular", ".", "forEach", "(", "collection", ",", "function", "(", "value", ",", "waypoint", ")", "{", "collection", "[", "waypoint", "]", "=", "false", ";", "}", ")", ";", "collection", "[", "waypoint", "]", "=", "true", ";", "}" ]
Sets all waypoints in the colleciton to false, and sets the indicated waypoint to true. @param Object collection @param String waypoint
[ "Sets", "all", "waypoints", "in", "the", "colleciton", "to", "false", "and", "sets", "the", "indicated", "waypoint", "to", "true", "." ]
b574303913ac003cd0f73ca103d7109712567d4d
https://github.com/zumba/angular-waypoints/blob/b574303913ac003cd0f73ca103d7109712567d4d/dist/angular-waypoints.all.js#L841-L846
train
u-wave/react-list-lazy-load
src/LazyList.js
eagerSlice
function eagerSlice (list, start, end) { const sliced = [] for (let i = start; i < end; i++) { sliced.push(list[i]) } return sliced }
javascript
function eagerSlice (list, start, end) { const sliced = [] for (let i = start; i < end; i++) { sliced.push(list[i]) } return sliced }
[ "function", "eagerSlice", "(", "list", ",", "start", ",", "end", ")", "{", "const", "sliced", "=", "[", "]", "for", "(", "let", "i", "=", "start", ";", "i", "<", "end", ";", "i", "++", ")", "{", "sliced", ".", "push", "(", "list", "[", "i", "]", ")", "}", "return", "sliced", "}" ]
Like `.slice`, but doesn't care about array bounds. [0, 1].slice(1, 3) === [1] eagerSlice([0, 1], 1, 3) === [1, undefined, undefined]
[ "Like", ".", "slice", "but", "doesn", "t", "care", "about", "array", "bounds", "." ]
d643c0443ebe376b07a971d7668ff99245dae903
https://github.com/u-wave/react-list-lazy-load/blob/d643c0443ebe376b07a971d7668ff99245dae903/src/LazyList.js#L35-L41
train
zeeshanhyder/angular-tag-cloud
src/ng-tag-cloud.js
function(elem, other_elems) { // Pairwise overlap detection var overlapping = function(a, b) { if (Math.abs(2.0*a.offsetLeft + a.offsetWidth - 2.0*b.offsetLeft - b.offsetWidth) < a.offsetWidth + b.offsetWidth) { if (Math.abs(2.0*a.offsetTop + a.offsetHeight - 2.0*b.offsetTop - b.offsetHeight) < a.offsetHeight + b.offsetHeight) { return true; } } return false; }; var i = 0; // Check elements for overlap one by one, stop and return false as soon as an overlap is found for(i = 0; i < other_elems.length; i++) { if (overlapping(elem, other_elems[i])) { return true; } } return false; }
javascript
function(elem, other_elems) { // Pairwise overlap detection var overlapping = function(a, b) { if (Math.abs(2.0*a.offsetLeft + a.offsetWidth - 2.0*b.offsetLeft - b.offsetWidth) < a.offsetWidth + b.offsetWidth) { if (Math.abs(2.0*a.offsetTop + a.offsetHeight - 2.0*b.offsetTop - b.offsetHeight) < a.offsetHeight + b.offsetHeight) { return true; } } return false; }; var i = 0; // Check elements for overlap one by one, stop and return false as soon as an overlap is found for(i = 0; i < other_elems.length; i++) { if (overlapping(elem, other_elems[i])) { return true; } } return false; }
[ "function", "(", "elem", ",", "other_elems", ")", "{", "var", "overlapping", "=", "function", "(", "a", ",", "b", ")", "{", "if", "(", "Math", ".", "abs", "(", "2.0", "*", "a", ".", "offsetLeft", "+", "a", ".", "offsetWidth", "-", "2.0", "*", "b", ".", "offsetLeft", "-", "b", ".", "offsetWidth", ")", "<", "a", ".", "offsetWidth", "+", "b", ".", "offsetWidth", ")", "{", "if", "(", "Math", ".", "abs", "(", "2.0", "*", "a", ".", "offsetTop", "+", "a", ".", "offsetHeight", "-", "2.0", "*", "b", ".", "offsetTop", "-", "b", ".", "offsetHeight", ")", "<", "a", ".", "offsetHeight", "+", "b", ".", "offsetHeight", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", ";", "var", "i", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "other_elems", ".", "length", ";", "i", "++", ")", "{", "if", "(", "overlapping", "(", "elem", ",", "other_elems", "[", "i", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Helper function to test if an element overlaps others
[ "Helper", "function", "to", "test", "if", "an", "element", "overlaps", "others" ]
c3dd25eb98832b6408fce8d4db545ba2ec8051e6
https://github.com/zeeshanhyder/angular-tag-cloud/blob/c3dd25eb98832b6408fce8d4db545ba2ec8051e6/src/ng-tag-cloud.js#L101-L119
train
zeeshanhyder/angular-tag-cloud
src/ng-tag-cloud.js
function(a, b) { if (Math.abs(2.0*a.offsetLeft + a.offsetWidth - 2.0*b.offsetLeft - b.offsetWidth) < a.offsetWidth + b.offsetWidth) { if (Math.abs(2.0*a.offsetTop + a.offsetHeight - 2.0*b.offsetTop - b.offsetHeight) < a.offsetHeight + b.offsetHeight) { return true; } } return false; }
javascript
function(a, b) { if (Math.abs(2.0*a.offsetLeft + a.offsetWidth - 2.0*b.offsetLeft - b.offsetWidth) < a.offsetWidth + b.offsetWidth) { if (Math.abs(2.0*a.offsetTop + a.offsetHeight - 2.0*b.offsetTop - b.offsetHeight) < a.offsetHeight + b.offsetHeight) { return true; } } return false; }
[ "function", "(", "a", ",", "b", ")", "{", "if", "(", "Math", ".", "abs", "(", "2.0", "*", "a", ".", "offsetLeft", "+", "a", ".", "offsetWidth", "-", "2.0", "*", "b", ".", "offsetLeft", "-", "b", ".", "offsetWidth", ")", "<", "a", ".", "offsetWidth", "+", "b", ".", "offsetWidth", ")", "{", "if", "(", "Math", ".", "abs", "(", "2.0", "*", "a", ".", "offsetTop", "+", "a", ".", "offsetHeight", "-", "2.0", "*", "b", ".", "offsetTop", "-", "b", ".", "offsetHeight", ")", "<", "a", ".", "offsetHeight", "+", "b", ".", "offsetHeight", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Pairwise overlap detection
[ "Pairwise", "overlap", "detection" ]
c3dd25eb98832b6408fce8d4db545ba2ec8051e6
https://github.com/zeeshanhyder/angular-tag-cloud/blob/c3dd25eb98832b6408fce8d4db545ba2ec8051e6/src/ng-tag-cloud.js#L103-L110
train
intuit/istanbul-cobertura-badger
lib/index.js
istanbulCoberturaBadger
function istanbulCoberturaBadger(opts, callback) { // Resolve the options opts = extend({ // Setting the default coverage file generated by istanbul cobertura report. istanbulReportFile: "./coverage/cobertura-coverage.xml", // The default location for the destination being the coverage directory from istanbul. destinationDir: null, // The shields host to be used for retrieving the badge. https://github.com/badges/shields shieldsHost: process.env.SHIELDS_HOST || "https://img.shields.io", // The style of shield icon to generate (plastic, flat-square, flat) shieldStyle: "flat", // The name of the badge file to be generated badgeFileName: "coverage", // The thresholds to be used to give colors to the badge. thresholds: defaultThresholds }, opts); opts.badgeFormat = opts.badgeFormat || "svg"; reportParser(opts.istanbulReportFile, function(err, report) { if (err) { return callback(err); } // The color depends on the fixed thresholds (RED: 0 >= % < 60) (YELLOW: 60 >= % < 90) (GREEN: % >= 90) var color = report.overallPercent >= opts.thresholds.excellent ? "brightgreen" : (report.overallPercent >= opts.thresholds.good ? "yellow" : "red"); // The shields service that will give badges. var url = opts.shieldsHost + "/badge/coverage-" + report.overallPercent; url += "%25-" + color + "." + opts.badgeFormat + "?style=" + opts.shieldStyle; // Save always as coverage image. var badgeFileName = path.join(opts.destinationDir, opts.badgeFileName + "." + opts.badgeFormat); downloader(url, badgeFileName, function(err, downloadResult) { if (err) { return callback(err); } report.url = url; report.badgeFile = downloadResult; report.color = color; return callback(null, report); }); }); }
javascript
function istanbulCoberturaBadger(opts, callback) { // Resolve the options opts = extend({ // Setting the default coverage file generated by istanbul cobertura report. istanbulReportFile: "./coverage/cobertura-coverage.xml", // The default location for the destination being the coverage directory from istanbul. destinationDir: null, // The shields host to be used for retrieving the badge. https://github.com/badges/shields shieldsHost: process.env.SHIELDS_HOST || "https://img.shields.io", // The style of shield icon to generate (plastic, flat-square, flat) shieldStyle: "flat", // The name of the badge file to be generated badgeFileName: "coverage", // The thresholds to be used to give colors to the badge. thresholds: defaultThresholds }, opts); opts.badgeFormat = opts.badgeFormat || "svg"; reportParser(opts.istanbulReportFile, function(err, report) { if (err) { return callback(err); } // The color depends on the fixed thresholds (RED: 0 >= % < 60) (YELLOW: 60 >= % < 90) (GREEN: % >= 90) var color = report.overallPercent >= opts.thresholds.excellent ? "brightgreen" : (report.overallPercent >= opts.thresholds.good ? "yellow" : "red"); // The shields service that will give badges. var url = opts.shieldsHost + "/badge/coverage-" + report.overallPercent; url += "%25-" + color + "." + opts.badgeFormat + "?style=" + opts.shieldStyle; // Save always as coverage image. var badgeFileName = path.join(opts.destinationDir, opts.badgeFileName + "." + opts.badgeFormat); downloader(url, badgeFileName, function(err, downloadResult) { if (err) { return callback(err); } report.url = url; report.badgeFile = downloadResult; report.color = color; return callback(null, report); }); }); }
[ "function", "istanbulCoberturaBadger", "(", "opts", ",", "callback", ")", "{", "opts", "=", "extend", "(", "{", "istanbulReportFile", ":", "\"./coverage/cobertura-coverage.xml\"", ",", "destinationDir", ":", "null", ",", "shieldsHost", ":", "process", ".", "env", ".", "SHIELDS_HOST", "||", "\"https://img.shields.io\"", ",", "shieldStyle", ":", "\"flat\"", ",", "badgeFileName", ":", "\"coverage\"", ",", "thresholds", ":", "defaultThresholds", "}", ",", "opts", ")", ";", "opts", ".", "badgeFormat", "=", "opts", ".", "badgeFormat", "||", "\"svg\"", ";", "reportParser", "(", "opts", ".", "istanbulReportFile", ",", "function", "(", "err", ",", "report", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "var", "color", "=", "report", ".", "overallPercent", ">=", "opts", ".", "thresholds", ".", "excellent", "?", "\"brightgreen\"", ":", "(", "report", ".", "overallPercent", ">=", "opts", ".", "thresholds", ".", "good", "?", "\"yellow\"", ":", "\"red\"", ")", ";", "var", "url", "=", "opts", ".", "shieldsHost", "+", "\"/badge/coverage-\"", "+", "report", ".", "overallPercent", ";", "url", "+=", "\"%25-\"", "+", "color", "+", "\".\"", "+", "opts", ".", "badgeFormat", "+", "\"?style=\"", "+", "opts", ".", "shieldStyle", ";", "var", "badgeFileName", "=", "path", ".", "join", "(", "opts", ".", "destinationDir", ",", "opts", ".", "badgeFileName", "+", "\".\"", "+", "opts", ".", "badgeFormat", ")", ";", "downloader", "(", "url", ",", "badgeFileName", ",", "function", "(", "err", ",", "downloadResult", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "report", ".", "url", "=", "url", ";", "report", ".", "badgeFile", "=", "downloadResult", ";", "report", ".", "color", "=", "color", ";", "return", "callback", "(", "null", ",", "report", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates a code coverage badge based on the cobertura report generated by istanbul. @param {Object} opts is the set of properties provided to the api. @param {Function} callback is the CPS function to get the results.
[ "Creates", "a", "code", "coverage", "badge", "based", "on", "the", "cobertura", "report", "generated", "by", "istanbul", "." ]
f0621f0e30a504819a0e25e86586181a2aae4c00
https://github.com/intuit/istanbul-cobertura-badger/blob/f0621f0e30a504819a0e25e86586181a2aae4c00/lib/index.js#L19-L66
train
intuit/istanbul-cobertura-badger
lib/coberturaReportParser.js
processReport
function processReport(xml, computation) { if (xml.packages.package instanceof Array) { // Process all the packages xml.packages.package.forEach(function(packageObject) { processPackage(packageObject, computation); }); } else { processPackage(xml.packages.package, computation); } }
javascript
function processReport(xml, computation) { if (xml.packages.package instanceof Array) { // Process all the packages xml.packages.package.forEach(function(packageObject) { processPackage(packageObject, computation); }); } else { processPackage(xml.packages.package, computation); } }
[ "function", "processReport", "(", "xml", ",", "computation", ")", "{", "if", "(", "xml", ".", "packages", ".", "package", "instanceof", "Array", ")", "{", "xml", ".", "packages", ".", "package", ".", "forEach", "(", "function", "(", "packageObject", ")", "{", "processPackage", "(", "packageObject", ",", "computation", ")", ";", "}", ")", ";", "}", "else", "{", "processPackage", "(", "xml", ".", "packages", ".", "package", ",", "computation", ")", ";", "}", "}" ]
Processes the XML report based on the package. <package>...</package> @param {Object} xml is the parsed report. @param {Object} computation is result of computation.
[ "Processes", "the", "XML", "report", "based", "on", "the", "package", "." ]
f0621f0e30a504819a0e25e86586181a2aae4c00
https://github.com/intuit/istanbul-cobertura-badger/blob/f0621f0e30a504819a0e25e86586181a2aae4c00/lib/coberturaReportParser.js#L13-L23
train
intuit/istanbul-cobertura-badger
lib/coberturaReportParser.js
processPackage
function processPackage(packageObject, computation) { if (packageObject.classes.class instanceof Array) { // Process each individual class packageObject.classes.class.forEach(function(clazz) { processClass(clazz, computation); }); } else { // Single class to be processed processClass(packageObject.classes.class, computation); } }
javascript
function processPackage(packageObject, computation) { if (packageObject.classes.class instanceof Array) { // Process each individual class packageObject.classes.class.forEach(function(clazz) { processClass(clazz, computation); }); } else { // Single class to be processed processClass(packageObject.classes.class, computation); } }
[ "function", "processPackage", "(", "packageObject", ",", "computation", ")", "{", "if", "(", "packageObject", ".", "classes", ".", "class", "instanceof", "Array", ")", "{", "packageObject", ".", "classes", ".", "class", ".", "forEach", "(", "function", "(", "clazz", ")", "{", "processClass", "(", "clazz", ",", "computation", ")", ";", "}", ")", ";", "}", "else", "{", "processClass", "(", "packageObject", ".", "classes", ".", "class", ",", "computation", ")", ";", "}", "}" ]
Processes the individual package entry. <package><class></package> @param {Object} packageObject is the package object from the report. @param {Object} computation is the result of the computation.
[ "Processes", "the", "individual", "package", "entry", "." ]
f0621f0e30a504819a0e25e86586181a2aae4c00
https://github.com/intuit/istanbul-cobertura-badger/blob/f0621f0e30a504819a0e25e86586181a2aae4c00/lib/coberturaReportParser.js#L33-L44
train
intuit/istanbul-cobertura-badger
lib/coberturaReportParser.js
processClass
function processClass(clazz, computation) { if (!clazz.methods.method) { return; } if (clazz.methods.method instanceof Array) { clazz.methods.method.forEach(function(method) { ++computation.total; // Incremente the total number of methods if there were hits. Don't increment for no hit computation.passed = parseInt(method.hits) > 0 ? ++computation.passed : computation.passed; }); } else { // That's the method object itself. ++computation.total; computation.passed = parseInt(clazz.methods.method.hits) > 0 ? ++computation.passed : computation.passed; } }
javascript
function processClass(clazz, computation) { if (!clazz.methods.method) { return; } if (clazz.methods.method instanceof Array) { clazz.methods.method.forEach(function(method) { ++computation.total; // Incremente the total number of methods if there were hits. Don't increment for no hit computation.passed = parseInt(method.hits) > 0 ? ++computation.passed : computation.passed; }); } else { // That's the method object itself. ++computation.total; computation.passed = parseInt(clazz.methods.method.hits) > 0 ? ++computation.passed : computation.passed; } }
[ "function", "processClass", "(", "clazz", ",", "computation", ")", "{", "if", "(", "!", "clazz", ".", "methods", ".", "method", ")", "{", "return", ";", "}", "if", "(", "clazz", ".", "methods", ".", "method", "instanceof", "Array", ")", "{", "clazz", ".", "methods", ".", "method", ".", "forEach", "(", "function", "(", "method", ")", "{", "++", "computation", ".", "total", ";", "computation", ".", "passed", "=", "parseInt", "(", "method", ".", "hits", ")", ">", "0", "?", "++", "computation", ".", "passed", ":", "computation", ".", "passed", ";", "}", ")", ";", "}", "else", "{", "++", "computation", ".", "total", ";", "computation", ".", "passed", "=", "parseInt", "(", "clazz", ".", "methods", ".", "method", ".", "hits", ")", ">", "0", "?", "++", "computation", ".", "passed", ":", "computation", ".", "passed", ";", "}", "}" ]
Processes the individual Class and compute totals. <class>...</class> @param {Object} clazz is the class object from the report. @param {Object} computation is the result of the computation.
[ "Processes", "the", "individual", "Class", "and", "compute", "totals", "." ]
f0621f0e30a504819a0e25e86586181a2aae4c00
https://github.com/intuit/istanbul-cobertura-badger/blob/f0621f0e30a504819a0e25e86586181a2aae4c00/lib/coberturaReportParser.js#L54-L70
train
swissmanu/harmonyhubjs-client
lib/harmonyclient.js
HarmonyClient
function HarmonyClient (xmppClient) { debug('create new harmony client') var self = this self._xmppClient = xmppClient self._responseHandlerQueue = [] self._availableCommandsCache = null function handleStanza (stanza) { debug('handleStanza(' + stanza.toString() + ')') // Check for state digest: var event = stanza.getChild('event') if (event && event.attr('type') === 'connect.stateDigest?notify') { onStateDigest.call(self, JSON.parse(event.getText())) } // Check for queued response handlers: self._responseHandlerQueue.forEach(function (responseHandler, index, array) { if (responseHandler.canHandleStanza(stanza)) { debug('received response stanza for queued response handler') var response = stanza.getChildText('oa') var decodedResponse if (responseHandler.responseType === 'json') { decodedResponse = JSON.parse(response) } else { decodedResponse = xmppUtil.decodeColonSeparatedResponse(response) } responseHandler.deferred.resolve(decodedResponse) array.splice(index, 1) } }) } xmppClient.on('stanza', handleStanza.bind(self)) xmppClient.on('error', function (error) { debug('XMPP Error: ' + error.message) }) EventEmitter.call(this) }
javascript
function HarmonyClient (xmppClient) { debug('create new harmony client') var self = this self._xmppClient = xmppClient self._responseHandlerQueue = [] self._availableCommandsCache = null function handleStanza (stanza) { debug('handleStanza(' + stanza.toString() + ')') // Check for state digest: var event = stanza.getChild('event') if (event && event.attr('type') === 'connect.stateDigest?notify') { onStateDigest.call(self, JSON.parse(event.getText())) } // Check for queued response handlers: self._responseHandlerQueue.forEach(function (responseHandler, index, array) { if (responseHandler.canHandleStanza(stanza)) { debug('received response stanza for queued response handler') var response = stanza.getChildText('oa') var decodedResponse if (responseHandler.responseType === 'json') { decodedResponse = JSON.parse(response) } else { decodedResponse = xmppUtil.decodeColonSeparatedResponse(response) } responseHandler.deferred.resolve(decodedResponse) array.splice(index, 1) } }) } xmppClient.on('stanza', handleStanza.bind(self)) xmppClient.on('error', function (error) { debug('XMPP Error: ' + error.message) }) EventEmitter.call(this) }
[ "function", "HarmonyClient", "(", "xmppClient", ")", "{", "debug", "(", "'create new harmony client'", ")", "var", "self", "=", "this", "self", ".", "_xmppClient", "=", "xmppClient", "self", ".", "_responseHandlerQueue", "=", "[", "]", "self", ".", "_availableCommandsCache", "=", "null", "function", "handleStanza", "(", "stanza", ")", "{", "debug", "(", "'handleStanza('", "+", "stanza", ".", "toString", "(", ")", "+", "')'", ")", "var", "event", "=", "stanza", ".", "getChild", "(", "'event'", ")", "if", "(", "event", "&&", "event", ".", "attr", "(", "'type'", ")", "===", "'connect.stateDigest?notify'", ")", "{", "onStateDigest", ".", "call", "(", "self", ",", "JSON", ".", "parse", "(", "event", ".", "getText", "(", ")", ")", ")", "}", "self", ".", "_responseHandlerQueue", ".", "forEach", "(", "function", "(", "responseHandler", ",", "index", ",", "array", ")", "{", "if", "(", "responseHandler", ".", "canHandleStanza", "(", "stanza", ")", ")", "{", "debug", "(", "'received response stanza for queued response handler'", ")", "var", "response", "=", "stanza", ".", "getChildText", "(", "'oa'", ")", "var", "decodedResponse", "if", "(", "responseHandler", ".", "responseType", "===", "'json'", ")", "{", "decodedResponse", "=", "JSON", ".", "parse", "(", "response", ")", "}", "else", "{", "decodedResponse", "=", "xmppUtil", ".", "decodeColonSeparatedResponse", "(", "response", ")", "}", "responseHandler", ".", "deferred", ".", "resolve", "(", "decodedResponse", ")", "array", ".", "splice", "(", "index", ",", "1", ")", "}", "}", ")", "}", "xmppClient", ".", "on", "(", "'stanza'", ",", "handleStanza", ".", "bind", "(", "self", ")", ")", "xmppClient", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "debug", "(", "'XMPP Error: '", "+", "error", ".", "message", ")", "}", ")", "EventEmitter", ".", "call", "(", "this", ")", "}" ]
Creates a new HarmonyClient using the given xmppClient to communication. @param xmppClient @constructor
[ "Creates", "a", "new", "HarmonyClient", "using", "the", "given", "xmppClient", "to", "communication", "." ]
6819cf7e2ffe0e608f013959cd1c447e0c12ec93
https://github.com/swissmanu/harmonyhubjs-client/blob/6819cf7e2ffe0e608f013959cd1c447e0c12ec93/lib/harmonyclient.js#L13-L56
train
swissmanu/harmonyhubjs-client
lib/harmonyclient.js
startActivity
function startActivity (activityId) { var timestamp = new Date().getTime() var body = 'activityId=' + activityId + ':timestamp=' + timestamp return this.request('startactivity', body, 'encoded', function (stanza) { // This canHandleStanzaFn waits for a stanza that confirms starting the activity. var event = stanza.getChild('event') var canHandleStanza = false if (event && event.attr('type') === 'connect.stateDigest?notify') { var digest = JSON.parse(event.getText()) if (activityId === '-1' && digest.activityId === activityId && digest.activityStatus === 0) { canHandleStanza = true } else if (activityId !== '-1' && digest.activityId === activityId && digest.activityStatus === 2) { canHandleStanza = true } } return canHandleStanza }) }
javascript
function startActivity (activityId) { var timestamp = new Date().getTime() var body = 'activityId=' + activityId + ':timestamp=' + timestamp return this.request('startactivity', body, 'encoded', function (stanza) { // This canHandleStanzaFn waits for a stanza that confirms starting the activity. var event = stanza.getChild('event') var canHandleStanza = false if (event && event.attr('type') === 'connect.stateDigest?notify') { var digest = JSON.parse(event.getText()) if (activityId === '-1' && digest.activityId === activityId && digest.activityStatus === 0) { canHandleStanza = true } else if (activityId !== '-1' && digest.activityId === activityId && digest.activityStatus === 2) { canHandleStanza = true } } return canHandleStanza }) }
[ "function", "startActivity", "(", "activityId", ")", "{", "var", "timestamp", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", "var", "body", "=", "'activityId='", "+", "activityId", "+", "':timestamp='", "+", "timestamp", "return", "this", ".", "request", "(", "'startactivity'", ",", "body", ",", "'encoded'", ",", "function", "(", "stanza", ")", "{", "var", "event", "=", "stanza", ".", "getChild", "(", "'event'", ")", "var", "canHandleStanza", "=", "false", "if", "(", "event", "&&", "event", ".", "attr", "(", "'type'", ")", "===", "'connect.stateDigest?notify'", ")", "{", "var", "digest", "=", "JSON", ".", "parse", "(", "event", ".", "getText", "(", ")", ")", "if", "(", "activityId", "===", "'-1'", "&&", "digest", ".", "activityId", "===", "activityId", "&&", "digest", ".", "activityStatus", "===", "0", ")", "{", "canHandleStanza", "=", "true", "}", "else", "if", "(", "activityId", "!==", "'-1'", "&&", "digest", ".", "activityId", "===", "activityId", "&&", "digest", ".", "activityStatus", "===", "2", ")", "{", "canHandleStanza", "=", "true", "}", "}", "return", "canHandleStanza", "}", ")", "}" ]
Starts an activity with the given id. @param activityId @returns {Q.Promise}
[ "Starts", "an", "activity", "with", "the", "given", "id", "." ]
6819cf7e2ffe0e608f013959cd1c447e0c12ec93
https://github.com/swissmanu/harmonyhubjs-client/blob/6819cf7e2ffe0e608f013959cd1c447e0c12ec93/lib/harmonyclient.js#L99-L118
train
swissmanu/harmonyhubjs-client
lib/harmonyclient.js
isOff
function isOff () { debug('check if turned off') return this.getCurrentActivity() .then(function (activityId) { var off = (activityId === '-1') debug(off ? 'system is currently off' : 'system is currently on with activity ' + activityId) return off }) }
javascript
function isOff () { debug('check if turned off') return this.getCurrentActivity() .then(function (activityId) { var off = (activityId === '-1') debug(off ? 'system is currently off' : 'system is currently on with activity ' + activityId) return off }) }
[ "function", "isOff", "(", ")", "{", "debug", "(", "'check if turned off'", ")", "return", "this", ".", "getCurrentActivity", "(", ")", ".", "then", "(", "function", "(", "activityId", ")", "{", "var", "off", "=", "(", "activityId", "===", "'-1'", ")", "debug", "(", "off", "?", "'system is currently off'", ":", "'system is currently on with activity '", "+", "activityId", ")", "return", "off", "}", ")", "}" ]
Checks if the hub has now activity turned on. This is implemented by checking the hubs current activity. If the activities id is equal to -1, no activity is on currently. @returns {Q.Promise}
[ "Checks", "if", "the", "hub", "has", "now", "activity", "turned", "on", ".", "This", "is", "implemented", "by", "checking", "the", "hubs", "current", "activity", ".", "If", "the", "activities", "id", "is", "equal", "to", "-", "1", "no", "activity", "is", "on", "currently", "." ]
6819cf7e2ffe0e608f013959cd1c447e0c12ec93
https://github.com/swissmanu/harmonyhubjs-client/blob/6819cf7e2ffe0e608f013959cd1c447e0c12ec93/lib/harmonyclient.js#L136-L146
train
swissmanu/harmonyhubjs-client
lib/harmonyclient.js
getAvailableCommands
function getAvailableCommands () { debug('retrieve available commands') if (this._availableCommandsCache) { debug('using cached config') var deferred = Q.defer() deferred.resolve(this._availableCommandsCache) return deferred.promise } var self = this return this.request('config', undefined, 'json') .then(function (response) { self._availableCommandsCache = response return response }) }
javascript
function getAvailableCommands () { debug('retrieve available commands') if (this._availableCommandsCache) { debug('using cached config') var deferred = Q.defer() deferred.resolve(this._availableCommandsCache) return deferred.promise } var self = this return this.request('config', undefined, 'json') .then(function (response) { self._availableCommandsCache = response return response }) }
[ "function", "getAvailableCommands", "(", ")", "{", "debug", "(", "'retrieve available commands'", ")", "if", "(", "this", ".", "_availableCommandsCache", ")", "{", "debug", "(", "'using cached config'", ")", "var", "deferred", "=", "Q", ".", "defer", "(", ")", "deferred", ".", "resolve", "(", "this", ".", "_availableCommandsCache", ")", "return", "deferred", ".", "promise", "}", "var", "self", "=", "this", "return", "this", ".", "request", "(", "'config'", ",", "undefined", ",", "'json'", ")", ".", "then", "(", "function", "(", "response", ")", "{", "self", ".", "_availableCommandsCache", "=", "response", "return", "response", "}", ")", "}" ]
Acquires all available commands from the hub when resolving the returned promise. @returns {Q.Promise}
[ "Acquires", "all", "available", "commands", "from", "the", "hub", "when", "resolving", "the", "returned", "promise", "." ]
6819cf7e2ffe0e608f013959cd1c447e0c12ec93
https://github.com/swissmanu/harmonyhubjs-client/blob/6819cf7e2ffe0e608f013959cd1c447e0c12ec93/lib/harmonyclient.js#L153-L169
train
swissmanu/harmonyhubjs-client
lib/harmonyclient.js
buildCommandIqStanza
function buildCommandIqStanza (command, body) { debug('buildCommandIqStanza for command "' + command + '" with body ' + body) return xmppUtil.buildIqStanza( 'get' , 'connect.logitech.com' , 'vnd.logitech.harmony/vnd.logitech.harmony.engine?' + command , body ) }
javascript
function buildCommandIqStanza (command, body) { debug('buildCommandIqStanza for command "' + command + '" with body ' + body) return xmppUtil.buildIqStanza( 'get' , 'connect.logitech.com' , 'vnd.logitech.harmony/vnd.logitech.harmony.engine?' + command , body ) }
[ "function", "buildCommandIqStanza", "(", "command", ",", "body", ")", "{", "debug", "(", "'buildCommandIqStanza for command \"'", "+", "command", "+", "'\" with body '", "+", "body", ")", "return", "xmppUtil", ".", "buildIqStanza", "(", "'get'", ",", "'connect.logitech.com'", ",", "'vnd.logitech.harmony/vnd.logitech.harmony.engine?'", "+", "command", ",", "body", ")", "}" ]
Builds an IQ stanza containing a specific command with given body, ready to send to the hub. @param command @param body @returns {Stanza}
[ "Builds", "an", "IQ", "stanza", "containing", "a", "specific", "command", "with", "given", "body", "ready", "to", "send", "to", "the", "hub", "." ]
6819cf7e2ffe0e608f013959cd1c447e0c12ec93
https://github.com/swissmanu/harmonyhubjs-client/blob/6819cf7e2ffe0e608f013959cd1c447e0c12ec93/lib/harmonyclient.js#L178-L187
train
swissmanu/harmonyhubjs-client
lib/harmonyclient.js
request
function request (command, body, expectedResponseType, canHandleStanzaPredicate) { debug('request with command "' + command + '" with body ' + body) var deferred = Q.defer() var iq = buildCommandIqStanza(command, body) var id = iq.attr('id') expectedResponseType = expectedResponseType || 'encoded' canHandleStanzaPredicate = canHandleStanzaPredicate || defaultCanHandleStanzaPredicate.bind(null, id) this._responseHandlerQueue.push({ canHandleStanza: canHandleStanzaPredicate, deferred: deferred, responseType: expectedResponseType }) this._xmppClient.send(iq) return deferred.promise }
javascript
function request (command, body, expectedResponseType, canHandleStanzaPredicate) { debug('request with command "' + command + '" with body ' + body) var deferred = Q.defer() var iq = buildCommandIqStanza(command, body) var id = iq.attr('id') expectedResponseType = expectedResponseType || 'encoded' canHandleStanzaPredicate = canHandleStanzaPredicate || defaultCanHandleStanzaPredicate.bind(null, id) this._responseHandlerQueue.push({ canHandleStanza: canHandleStanzaPredicate, deferred: deferred, responseType: expectedResponseType }) this._xmppClient.send(iq) return deferred.promise }
[ "function", "request", "(", "command", ",", "body", ",", "expectedResponseType", ",", "canHandleStanzaPredicate", ")", "{", "debug", "(", "'request with command \"'", "+", "command", "+", "'\" with body '", "+", "body", ")", "var", "deferred", "=", "Q", ".", "defer", "(", ")", "var", "iq", "=", "buildCommandIqStanza", "(", "command", ",", "body", ")", "var", "id", "=", "iq", ".", "attr", "(", "'id'", ")", "expectedResponseType", "=", "expectedResponseType", "||", "'encoded'", "canHandleStanzaPredicate", "=", "canHandleStanzaPredicate", "||", "defaultCanHandleStanzaPredicate", ".", "bind", "(", "null", ",", "id", ")", "this", ".", "_responseHandlerQueue", ".", "push", "(", "{", "canHandleStanza", ":", "canHandleStanzaPredicate", ",", "deferred", ":", "deferred", ",", "responseType", ":", "expectedResponseType", "}", ")", "this", ".", "_xmppClient", ".", "send", "(", "iq", ")", "return", "deferred", ".", "promise", "}" ]
Sends a command with the given body to the hub. The returned promise gets resolved as soon as a response for this very request arrives. By specifying expectedResponseType with either "json" or "encoded", you advice the response stanza handler how you expect the responses data encoding. See the protocol guide for further information. The cnaHandleStanzaFn parameter allows to define a predicate to determine if an incoming stanza is the response to your request. This can be handy if a generic stateDigest message might be the acknowledgment to your initial request. * @param command @param body @param expectedResponseType @param canHandleStanzaPredicate @returns {Q.Promise}
[ "Sends", "a", "command", "with", "the", "given", "body", "to", "the", "hub", ".", "The", "returned", "promise", "gets", "resolved", "as", "soon", "as", "a", "response", "for", "this", "very", "request", "arrives", "." ]
6819cf7e2ffe0e608f013959cd1c447e0c12ec93
https://github.com/swissmanu/harmonyhubjs-client/blob/6819cf7e2ffe0e608f013959cd1c447e0c12ec93/lib/harmonyclient.js#L211-L228
train
swissmanu/harmonyhubjs-client
lib/harmonyclient.js
send
function send (command, body) { debug('send command "' + command + '" with body ' + body) this._xmppClient.send(buildCommandIqStanza(command, body)) return Q() }
javascript
function send (command, body) { debug('send command "' + command + '" with body ' + body) this._xmppClient.send(buildCommandIqStanza(command, body)) return Q() }
[ "function", "send", "(", "command", ",", "body", ")", "{", "debug", "(", "'send command \"'", "+", "command", "+", "'\" with body '", "+", "body", ")", "this", ".", "_xmppClient", ".", "send", "(", "buildCommandIqStanza", "(", "command", ",", "body", ")", ")", "return", "Q", "(", ")", "}" ]
Sends a command with given body to the hub. The returned promise gets immediately resolved since this function does not expect any specific response from the hub. @param command @param body @returns {Q.Promise}
[ "Sends", "a", "command", "with", "given", "body", "to", "the", "hub", ".", "The", "returned", "promise", "gets", "immediately", "resolved", "since", "this", "function", "does", "not", "expect", "any", "specific", "response", "from", "the", "hub", "." ]
6819cf7e2ffe0e608f013959cd1c447e0c12ec93
https://github.com/swissmanu/harmonyhubjs-client/blob/6819cf7e2ffe0e608f013959cd1c447e0c12ec93/lib/harmonyclient.js#L238-L242
train
gamesys/moonshine
vm/src/lib.js
function (table) { var mt; if (table instanceof shine.Table) { if ((mt = table.__shine.metatable) && (mt = mt.__metatable)) return mt; return table.__shine.metatable; } else if (typeof table == 'string') { return stringMetatable; } }
javascript
function (table) { var mt; if (table instanceof shine.Table) { if ((mt = table.__shine.metatable) && (mt = mt.__metatable)) return mt; return table.__shine.metatable; } else if (typeof table == 'string') { return stringMetatable; } }
[ "function", "(", "table", ")", "{", "var", "mt", ";", "if", "(", "table", "instanceof", "shine", ".", "Table", ")", "{", "if", "(", "(", "mt", "=", "table", ".", "__shine", ".", "metatable", ")", "&&", "(", "mt", "=", "mt", ".", "__metatable", ")", ")", "return", "mt", ";", "return", "table", ".", "__shine", ".", "metatable", ";", "}", "else", "if", "(", "typeof", "table", "==", "'string'", ")", "{", "return", "stringMetatable", ";", "}", "}" ]
Implementation of Lua's getmetatable function. @param {object} table The table from which to obtain the metatable.
[ "Implementation", "of", "Lua", "s", "getmetatable", "function", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/src/lib.js#L267-L277
train
gamesys/moonshine
vm/src/lib.js
function (table, index) { // SLOOOOOOOW... var found = (index === undefined), numValues = table.__shine.numValues, keys, key, value, i, l; if (found || (typeof index == 'number' && index > 0 && index == index >> 0)) { if ('keys' in Object) { // Use Object.keys, if available. keys = Object['keys'](numValues); if (found) { // First pass i = 1; } else if (i = keys.indexOf('' + index) + 1) { found = true; } if (found) { while ((key = keys[i]) !== void 0 && (value = numValues[key]) === void 0) i++; if (value !== void 0) return [key >>= 0, value]; } } else { // Else use for-in (faster than for loop on tables with large holes) for (l in numValues) { i = l >> 0; if (!found) { if (i === index) found = true; } else if (numValues[i] !== undefined) { return [i, numValues[i]]; } } } } for (i in table) { if (table.hasOwnProperty(i) && !(i in shine.Table.prototype) && i !== '__shine') { if (!found) { if (i == index) found = true; } else if (table.hasOwnProperty(i) && table[i] !== undefined && ('' + i).substr(0, 2) != '__') { return [i, table[i]]; } } } for (i in table.__shine.keys) { if (table.__shine.keys.hasOwnProperty(i)) { var key = table.__shine.keys[i]; if (!found) { if (key === index) found = true; } else if (table.__shine.values[i] !== undefined) { return [key, table.__shine.values[i]]; } } } return shine.gc.createArray(); }
javascript
function (table, index) { // SLOOOOOOOW... var found = (index === undefined), numValues = table.__shine.numValues, keys, key, value, i, l; if (found || (typeof index == 'number' && index > 0 && index == index >> 0)) { if ('keys' in Object) { // Use Object.keys, if available. keys = Object['keys'](numValues); if (found) { // First pass i = 1; } else if (i = keys.indexOf('' + index) + 1) { found = true; } if (found) { while ((key = keys[i]) !== void 0 && (value = numValues[key]) === void 0) i++; if (value !== void 0) return [key >>= 0, value]; } } else { // Else use for-in (faster than for loop on tables with large holes) for (l in numValues) { i = l >> 0; if (!found) { if (i === index) found = true; } else if (numValues[i] !== undefined) { return [i, numValues[i]]; } } } } for (i in table) { if (table.hasOwnProperty(i) && !(i in shine.Table.prototype) && i !== '__shine') { if (!found) { if (i == index) found = true; } else if (table.hasOwnProperty(i) && table[i] !== undefined && ('' + i).substr(0, 2) != '__') { return [i, table[i]]; } } } for (i in table.__shine.keys) { if (table.__shine.keys.hasOwnProperty(i)) { var key = table.__shine.keys[i]; if (!found) { if (key === index) found = true; } else if (table.__shine.values[i] !== undefined) { return [key, table.__shine.values[i]]; } } } return shine.gc.createArray(); }
[ "function", "(", "table", ",", "index", ")", "{", "var", "found", "=", "(", "index", "===", "undefined", ")", ",", "numValues", "=", "table", ".", "__shine", ".", "numValues", ",", "keys", ",", "key", ",", "value", ",", "i", ",", "l", ";", "if", "(", "found", "||", "(", "typeof", "index", "==", "'number'", "&&", "index", ">", "0", "&&", "index", "==", "index", ">>", "0", ")", ")", "{", "if", "(", "'keys'", "in", "Object", ")", "{", "keys", "=", "Object", "[", "'keys'", "]", "(", "numValues", ")", ";", "if", "(", "found", ")", "{", "i", "=", "1", ";", "}", "else", "if", "(", "i", "=", "keys", ".", "indexOf", "(", "''", "+", "index", ")", "+", "1", ")", "{", "found", "=", "true", ";", "}", "if", "(", "found", ")", "{", "while", "(", "(", "key", "=", "keys", "[", "i", "]", ")", "!==", "void", "0", "&&", "(", "value", "=", "numValues", "[", "key", "]", ")", "===", "void", "0", ")", "i", "++", ";", "if", "(", "value", "!==", "void", "0", ")", "return", "[", "key", ">>=", "0", ",", "value", "]", ";", "}", "}", "else", "{", "for", "(", "l", "in", "numValues", ")", "{", "i", "=", "l", ">>", "0", ";", "if", "(", "!", "found", ")", "{", "if", "(", "i", "===", "index", ")", "found", "=", "true", ";", "}", "else", "if", "(", "numValues", "[", "i", "]", "!==", "undefined", ")", "{", "return", "[", "i", ",", "numValues", "[", "i", "]", "]", ";", "}", "}", "}", "}", "for", "(", "i", "in", "table", ")", "{", "if", "(", "table", ".", "hasOwnProperty", "(", "i", ")", "&&", "!", "(", "i", "in", "shine", ".", "Table", ".", "prototype", ")", "&&", "i", "!==", "'__shine'", ")", "{", "if", "(", "!", "found", ")", "{", "if", "(", "i", "==", "index", ")", "found", "=", "true", ";", "}", "else", "if", "(", "table", ".", "hasOwnProperty", "(", "i", ")", "&&", "table", "[", "i", "]", "!==", "undefined", "&&", "(", "''", "+", "i", ")", ".", "substr", "(", "0", ",", "2", ")", "!=", "'__'", ")", "{", "return", "[", "i", ",", "table", "[", "i", "]", "]", ";", "}", "}", "}", "for", "(", "i", "in", "table", ".", "__shine", ".", "keys", ")", "{", "if", "(", "table", ".", "__shine", ".", "keys", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "var", "key", "=", "table", ".", "__shine", ".", "keys", "[", "i", "]", ";", "if", "(", "!", "found", ")", "{", "if", "(", "key", "===", "index", ")", "found", "=", "true", ";", "}", "else", "if", "(", "table", ".", "__shine", ".", "values", "[", "i", "]", "!==", "undefined", ")", "{", "return", "[", "key", ",", "table", ".", "__shine", ".", "values", "[", "i", "]", "]", ";", "}", "}", "}", "return", "shine", ".", "gc", ".", "createArray", "(", ")", ";", "}" ]
Implementation of Lua's next function. @param {object} table The table that will receive the metatable. @param {object} index Index of the item to return.
[ "Implementation", "of", "Lua", "s", "next", "function", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/src/lib.js#L344-L411
train
gamesys/moonshine
vm/src/lib.js
function (table) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in pairs(). Table expected'); return [shine.lib.next, table]; }
javascript
function (table) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in pairs(). Table expected'); return [shine.lib.next, table]; }
[ "function", "(", "table", ")", "{", "if", "(", "!", "(", "(", "table", "||", "shine", ".", "EMPTY_OBJ", ")", "instanceof", "shine", ".", "Table", ")", ")", "throw", "new", "shine", ".", "Error", "(", "'Bad argument #1 in pairs(). Table expected'", ")", ";", "return", "[", "shine", ".", "lib", ".", "next", ",", "table", "]", ";", "}" ]
Implementation of Lua's pairs function. @param {object} table The table to be iterated over.
[ "Implementation", "of", "Lua", "s", "pairs", "function", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/src/lib.js#L420-L423
train
gamesys/moonshine
vm/src/lib.js
function (table, metatable) { var mt; if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in setmetatable(). Table expected'); if (!(metatable === undefined || (metatable || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #2 in setmetatable(). Nil or table expected'); if ((mt = table.__shine.metatable) && (mt = mt.__metatable)) throw new shine.Error('cannot change a protected metatable'); shine.gc.incrRef(metatable); shine.gc.decrRef(table.__shine.metatable); table.__shine.metatable = metatable; return table; }
javascript
function (table, metatable) { var mt; if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in setmetatable(). Table expected'); if (!(metatable === undefined || (metatable || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #2 in setmetatable(). Nil or table expected'); if ((mt = table.__shine.metatable) && (mt = mt.__metatable)) throw new shine.Error('cannot change a protected metatable'); shine.gc.incrRef(metatable); shine.gc.decrRef(table.__shine.metatable); table.__shine.metatable = metatable; return table; }
[ "function", "(", "table", ",", "metatable", ")", "{", "var", "mt", ";", "if", "(", "!", "(", "(", "table", "||", "shine", ".", "EMPTY_OBJ", ")", "instanceof", "shine", ".", "Table", ")", ")", "throw", "new", "shine", ".", "Error", "(", "'Bad argument #1 in setmetatable(). Table expected'", ")", ";", "if", "(", "!", "(", "metatable", "===", "undefined", "||", "(", "metatable", "||", "shine", ".", "EMPTY_OBJ", ")", "instanceof", "shine", ".", "Table", ")", ")", "throw", "new", "shine", ".", "Error", "(", "'Bad argument #2 in setmetatable(). Nil or table expected'", ")", ";", "if", "(", "(", "mt", "=", "table", ".", "__shine", ".", "metatable", ")", "&&", "(", "mt", "=", "mt", ".", "__metatable", ")", ")", "throw", "new", "shine", ".", "Error", "(", "'cannot change a protected metatable'", ")", ";", "shine", ".", "gc", ".", "incrRef", "(", "metatable", ")", ";", "shine", ".", "gc", ".", "decrRef", "(", "table", ".", "__shine", ".", "metatable", ")", ";", "table", ".", "__shine", ".", "metatable", "=", "metatable", ";", "return", "table", ";", "}" ]
Implementation of Lua's setmetatable function. @param {object} table The table that will receive the metatable. @param {object} metatable The metatable to attach.
[ "Implementation", "of", "Lua", "s", "setmetatable", "function", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/src/lib.js#L621-L634
train
gamesys/moonshine
vm/src/lib.js
function (min, max) { if (min === undefined && max === undefined) return getRandom(); if (typeof min !== 'number') throw new shine.Error("bad argument #1 to 'random' (number expected)"); if (max === undefined) { max = min; min = 1; } else if (typeof max !== 'number') { throw new shine.Error("bad argument #2 to 'random' (number expected)"); } if (min > max) throw new shine.Error("bad argument #2 to 'random' (interval is empty)"); return Math.floor(getRandom() * (max - min + 1) + min); }
javascript
function (min, max) { if (min === undefined && max === undefined) return getRandom(); if (typeof min !== 'number') throw new shine.Error("bad argument #1 to 'random' (number expected)"); if (max === undefined) { max = min; min = 1; } else if (typeof max !== 'number') { throw new shine.Error("bad argument #2 to 'random' (number expected)"); } if (min > max) throw new shine.Error("bad argument #2 to 'random' (interval is empty)"); return Math.floor(getRandom() * (max - min + 1) + min); }
[ "function", "(", "min", ",", "max", ")", "{", "if", "(", "min", "===", "undefined", "&&", "max", "===", "undefined", ")", "return", "getRandom", "(", ")", ";", "if", "(", "typeof", "min", "!==", "'number'", ")", "throw", "new", "shine", ".", "Error", "(", "\"bad argument #1 to 'random' (number expected)\"", ")", ";", "if", "(", "max", "===", "undefined", ")", "{", "max", "=", "min", ";", "min", "=", "1", ";", "}", "else", "if", "(", "typeof", "max", "!==", "'number'", ")", "{", "throw", "new", "shine", ".", "Error", "(", "\"bad argument #2 to 'random' (number expected)\"", ")", ";", "}", "if", "(", "min", ">", "max", ")", "throw", "new", "shine", ".", "Error", "(", "\"bad argument #2 to 'random' (interval is empty)\"", ")", ";", "return", "Math", ".", "floor", "(", "getRandom", "(", ")", "*", "(", "max", "-", "min", "+", "1", ")", "+", "min", ")", ";", "}" ]
Implementation of Lua's math.random function.
[ "Implementation", "of", "Lua", "s", "math", ".", "random", "function", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/src/lib.js#L1221-L1237
train
gamesys/moonshine
vm/src/lib.js
function (table) { var time; if (!table) { time = Date['now']? Date['now']() : new Date().getTime(); } else { var day, month, year, hour, min, sec; if (!(day = table.getMember('day'))) throw new shine.Error("Field 'day' missing in date table"); if (!(month = table.getMember('month'))) throw new shine.Error("Field 'month' missing in date table"); if (!(year = table.getMember('year'))) throw new shine.Error("Field 'year' missing in date table"); hour = table.getMember('hour') || 12; min = table.getMember('min') || 0; sec = table.getMember('sec') || 0; if (table.getMember('isdst')) hour--; time = new Date(year, month - 1, day, hour, min, sec).getTime(); } return Math.floor(time / 1000); }
javascript
function (table) { var time; if (!table) { time = Date['now']? Date['now']() : new Date().getTime(); } else { var day, month, year, hour, min, sec; if (!(day = table.getMember('day'))) throw new shine.Error("Field 'day' missing in date table"); if (!(month = table.getMember('month'))) throw new shine.Error("Field 'month' missing in date table"); if (!(year = table.getMember('year'))) throw new shine.Error("Field 'year' missing in date table"); hour = table.getMember('hour') || 12; min = table.getMember('min') || 0; sec = table.getMember('sec') || 0; if (table.getMember('isdst')) hour--; time = new Date(year, month - 1, day, hour, min, sec).getTime(); } return Math.floor(time / 1000); }
[ "function", "(", "table", ")", "{", "var", "time", ";", "if", "(", "!", "table", ")", "{", "time", "=", "Date", "[", "'now'", "]", "?", "Date", "[", "'now'", "]", "(", ")", ":", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "}", "else", "{", "var", "day", ",", "month", ",", "year", ",", "hour", ",", "min", ",", "sec", ";", "if", "(", "!", "(", "day", "=", "table", ".", "getMember", "(", "'day'", ")", ")", ")", "throw", "new", "shine", ".", "Error", "(", "\"Field 'day' missing in date table\"", ")", ";", "if", "(", "!", "(", "month", "=", "table", ".", "getMember", "(", "'month'", ")", ")", ")", "throw", "new", "shine", ".", "Error", "(", "\"Field 'month' missing in date table\"", ")", ";", "if", "(", "!", "(", "year", "=", "table", ".", "getMember", "(", "'year'", ")", ")", ")", "throw", "new", "shine", ".", "Error", "(", "\"Field 'year' missing in date table\"", ")", ";", "hour", "=", "table", ".", "getMember", "(", "'hour'", ")", "||", "12", ";", "min", "=", "table", ".", "getMember", "(", "'min'", ")", "||", "0", ";", "sec", "=", "table", ".", "getMember", "(", "'sec'", ")", "||", "0", ";", "if", "(", "table", ".", "getMember", "(", "'isdst'", ")", ")", "hour", "--", ";", "time", "=", "new", "Date", "(", "year", ",", "month", "-", "1", ",", "day", ",", "hour", ",", "min", ",", "sec", ")", ".", "getTime", "(", ")", ";", "}", "return", "Math", ".", "floor", "(", "time", "/", "1000", ")", ";", "}" ]
Implementation of Lua's os.time function. @param {object} table The table that will receive the metatable.
[ "Implementation", "of", "Lua", "s", "os", ".", "time", "function", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/src/lib.js#L1400-L1421
train
gamesys/moonshine
vm/src/lib.js
function (table, index, obj) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in table.insert(). Table expected'); if (obj == undefined) { obj = index; index = table.__shine.numValues.length; } else { index = shine.utils.coerceToNumber(index, "Bad argument #2 to 'insert' (number expected)"); } table.__shine.numValues.splice(index, 0, undefined); table.setMember(index, obj); }
javascript
function (table, index, obj) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in table.insert(). Table expected'); if (obj == undefined) { obj = index; index = table.__shine.numValues.length; } else { index = shine.utils.coerceToNumber(index, "Bad argument #2 to 'insert' (number expected)"); } table.__shine.numValues.splice(index, 0, undefined); table.setMember(index, obj); }
[ "function", "(", "table", ",", "index", ",", "obj", ")", "{", "if", "(", "!", "(", "(", "table", "||", "shine", ".", "EMPTY_OBJ", ")", "instanceof", "shine", ".", "Table", ")", ")", "throw", "new", "shine", ".", "Error", "(", "'Bad argument #1 in table.insert(). Table expected'", ")", ";", "if", "(", "obj", "==", "undefined", ")", "{", "obj", "=", "index", ";", "index", "=", "table", ".", "__shine", ".", "numValues", ".", "length", ";", "}", "else", "{", "index", "=", "shine", ".", "utils", ".", "coerceToNumber", "(", "index", ",", "\"Bad argument #2 to 'insert' (number expected)\"", ")", ";", "}", "table", ".", "__shine", ".", "numValues", ".", "splice", "(", "index", ",", "0", ",", "undefined", ")", ";", "table", ".", "setMember", "(", "index", ",", "obj", ")", ";", "}" ]
Implementation of Lua's table.insert function. @param {object} table The table in which to insert. @param {object} index The poostion to insert. @param {object} obj The value to insert.
[ "Implementation", "of", "Lua", "s", "table", ".", "insert", "function", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/src/lib.js#L2015-L2027
train
gamesys/moonshine
vm/src/lib.js
function (table, index) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in table.remove(). Table expected'); var max = shine.lib.table.getn(table), vals = table.__shine.numValues, result; if (index > max) return; if (index == undefined) index = max; result = vals.splice(index, 1); while (index < max && vals[index] === undefined) delete vals[index++]; return result; }
javascript
function (table, index) { if (!((table || shine.EMPTY_OBJ) instanceof shine.Table)) throw new shine.Error('Bad argument #1 in table.remove(). Table expected'); var max = shine.lib.table.getn(table), vals = table.__shine.numValues, result; if (index > max) return; if (index == undefined) index = max; result = vals.splice(index, 1); while (index < max && vals[index] === undefined) delete vals[index++]; return result; }
[ "function", "(", "table", ",", "index", ")", "{", "if", "(", "!", "(", "(", "table", "||", "shine", ".", "EMPTY_OBJ", ")", "instanceof", "shine", ".", "Table", ")", ")", "throw", "new", "shine", ".", "Error", "(", "'Bad argument #1 in table.remove(). Table expected'", ")", ";", "var", "max", "=", "shine", ".", "lib", ".", "table", ".", "getn", "(", "table", ")", ",", "vals", "=", "table", ".", "__shine", ".", "numValues", ",", "result", ";", "if", "(", "index", ">", "max", ")", "return", ";", "if", "(", "index", "==", "undefined", ")", "index", "=", "max", ";", "result", "=", "vals", ".", "splice", "(", "index", ",", "1", ")", ";", "while", "(", "index", "<", "max", "&&", "vals", "[", "index", "]", "===", "undefined", ")", "delete", "vals", "[", "index", "++", "]", ";", "return", "result", ";", "}" ]
Implementation of Lua's table.remove function. @param {object} table The table from which to remove an element. @param {object} index The position of the element to remove.
[ "Implementation", "of", "Lua", "s", "table", ".", "remove", "function", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/src/lib.js#L2060-L2074
train
gamesys/moonshine
vm/moonshine.js
function (obj) { for (var i in obj) if (obj.hasOwnProperty(i)) delete obj[i]; this.objects.push(obj); // this.collected++; }
javascript
function (obj) { for (var i in obj) if (obj.hasOwnProperty(i)) delete obj[i]; this.objects.push(obj); // this.collected++; }
[ "function", "(", "obj", ")", "{", "for", "(", "var", "i", "in", "obj", ")", "if", "(", "obj", ".", "hasOwnProperty", "(", "i", ")", ")", "delete", "obj", "[", "i", "]", ";", "this", ".", "objects", ".", "push", "(", "obj", ")", ";", "}" ]
Prepare an object for reuse. @param {Object} obj Object to be used.
[ "Prepare", "an", "object", "for", "reuse", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/moonshine.js#L134-L138
train
gamesys/moonshine
vm/moonshine.js
function (val) { if (!val || !(val instanceof shine.Table) || val.__shine.refCount === undefined) return; if (--val.__shine.refCount == 0) this.collect(val); }
javascript
function (val) { if (!val || !(val instanceof shine.Table) || val.__shine.refCount === undefined) return; if (--val.__shine.refCount == 0) this.collect(val); }
[ "function", "(", "val", ")", "{", "if", "(", "!", "val", "||", "!", "(", "val", "instanceof", "shine", ".", "Table", ")", "||", "val", ".", "__shine", ".", "refCount", "===", "undefined", ")", "return", ";", "if", "(", "--", "val", ".", "__shine", ".", "refCount", "==", "0", ")", "this", ".", "collect", "(", "val", ")", ";", "}" ]
Reduces the number of references associated with an object by one and collect it if necessary. @param {Object} Any object.
[ "Reduces", "the", "number", "of", "references", "associated", "with", "an", "object", "by", "one", "and", "collect", "it", "if", "necessary", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/moonshine.js#L171-L174
train
gamesys/moonshine
vm/moonshine.js
function (val) { if (val === undefined || val === null) return; if (val instanceof Array) return this.cacheArray(val); if (typeof val == 'object' && val.constructor == Object) return this.cacheObject(val); if (!(val instanceof shine.Table) || val.__shine.refCount === undefined) return; var i, l, meta = val.__shine; for (i = 0, l = meta.keys.length; i < l; i++) this.decrRef(meta.keys[i]); for (i = 0, l = meta.values.length; i < l; i++) this.decrRef(meta.values[i]); for (i = 0, l = meta.numValues.length; i < l; i++) this.decrRef(meta.numValues[i]); this.cacheArray(meta.keys); this.cacheArray(meta.values); delete meta.keys; delete meta.values; this.cacheObject(meta); delete val.__shine; for (i in val) if (val.hasOwnProperty(i)) this.decrRef(val[i]); }
javascript
function (val) { if (val === undefined || val === null) return; if (val instanceof Array) return this.cacheArray(val); if (typeof val == 'object' && val.constructor == Object) return this.cacheObject(val); if (!(val instanceof shine.Table) || val.__shine.refCount === undefined) return; var i, l, meta = val.__shine; for (i = 0, l = meta.keys.length; i < l; i++) this.decrRef(meta.keys[i]); for (i = 0, l = meta.values.length; i < l; i++) this.decrRef(meta.values[i]); for (i = 0, l = meta.numValues.length; i < l; i++) this.decrRef(meta.numValues[i]); this.cacheArray(meta.keys); this.cacheArray(meta.values); delete meta.keys; delete meta.values; this.cacheObject(meta); delete val.__shine; for (i in val) if (val.hasOwnProperty(i)) this.decrRef(val[i]); }
[ "function", "(", "val", ")", "{", "if", "(", "val", "===", "undefined", "||", "val", "===", "null", ")", "return", ";", "if", "(", "val", "instanceof", "Array", ")", "return", "this", ".", "cacheArray", "(", "val", ")", ";", "if", "(", "typeof", "val", "==", "'object'", "&&", "val", ".", "constructor", "==", "Object", ")", "return", "this", ".", "cacheObject", "(", "val", ")", ";", "if", "(", "!", "(", "val", "instanceof", "shine", ".", "Table", ")", "||", "val", ".", "__shine", ".", "refCount", "===", "undefined", ")", "return", ";", "var", "i", ",", "l", ",", "meta", "=", "val", ".", "__shine", ";", "for", "(", "i", "=", "0", ",", "l", "=", "meta", ".", "keys", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "this", ".", "decrRef", "(", "meta", ".", "keys", "[", "i", "]", ")", ";", "for", "(", "i", "=", "0", ",", "l", "=", "meta", ".", "values", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "this", ".", "decrRef", "(", "meta", ".", "values", "[", "i", "]", ")", ";", "for", "(", "i", "=", "0", ",", "l", "=", "meta", ".", "numValues", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "this", ".", "decrRef", "(", "meta", ".", "numValues", "[", "i", "]", ")", ";", "this", ".", "cacheArray", "(", "meta", ".", "keys", ")", ";", "this", ".", "cacheArray", "(", "meta", ".", "values", ")", ";", "delete", "meta", ".", "keys", ";", "delete", "meta", ".", "values", ";", "this", ".", "cacheObject", "(", "meta", ")", ";", "delete", "val", ".", "__shine", ";", "for", "(", "i", "in", "val", ")", "if", "(", "val", ".", "hasOwnProperty", "(", "i", ")", ")", "this", ".", "decrRef", "(", "val", "[", "i", "]", ")", ";", "}" ]
Collect an object. @param {Object} Any object.
[ "Collect", "an", "object", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/moonshine.js#L195-L219
train
gamesys/moonshine
vm/moonshine.js
formatValue
function formatValue (value) { if (typeof value == 'string') { value = value.replace(NEWLINE_PATTERN, '\\n'); value = value.replace(APOS_PATTERN, '\\\''); return "'" + value + "'"; } return value; }
javascript
function formatValue (value) { if (typeof value == 'string') { value = value.replace(NEWLINE_PATTERN, '\\n'); value = value.replace(APOS_PATTERN, '\\\''); return "'" + value + "'"; } return value; }
[ "function", "formatValue", "(", "value", ")", "{", "if", "(", "typeof", "value", "==", "'string'", ")", "{", "value", "=", "value", ".", "replace", "(", "NEWLINE_PATTERN", ",", "'\\\\n'", ")", ";", "\\\\", "value", "=", "value", ".", "replace", "(", "APOS_PATTERN", ",", "'\\\\\\''", ")", ";", "}", "\\\\", "}" ]
Returns a parsable string representation of a primative value. @param {object} value The input value. @returns {string} A string-encoded representation.
[ "Returns", "a", "parsable", "string", "representation", "of", "a", "primative", "value", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/moonshine.js#L3637-L3645
train
gamesys/moonshine
vm/moonshine.js
function (val, errorMessage) { switch(true) { case typeof val == 'string': return val; case val === undefined: case val === null: return 'nil'; case val === Infinity: return 'inf'; case val === -Infinity: return '-inf'; case typeof val == 'number': case typeof val == 'boolean': return window.isNaN(val)? 'nan' : '' + val; default: return throwCoerceError(val, errorMessage) || ''; } }
javascript
function (val, errorMessage) { switch(true) { case typeof val == 'string': return val; case val === undefined: case val === null: return 'nil'; case val === Infinity: return 'inf'; case val === -Infinity: return '-inf'; case typeof val == 'number': case typeof val == 'boolean': return window.isNaN(val)? 'nan' : '' + val; default: return throwCoerceError(val, errorMessage) || ''; } }
[ "function", "(", "val", ",", "errorMessage", ")", "{", "switch", "(", "true", ")", "{", "case", "typeof", "val", "==", "'string'", ":", "return", "val", ";", "case", "val", "===", "undefined", ":", "case", "val", "===", "null", ":", "return", "'nil'", ";", "case", "val", "===", "Infinity", ":", "return", "'inf'", ";", "case", "val", "===", "-", "Infinity", ":", "return", "'-inf'", ";", "case", "typeof", "val", "==", "'number'", ":", "case", "typeof", "val", "==", "'boolean'", ":", "return", "window", ".", "isNaN", "(", "val", ")", "?", "'nan'", ":", "''", "+", "val", ";", "default", ":", "return", "throwCoerceError", "(", "val", ",", "errorMessage", ")", "||", "''", ";", "}", "}" ]
Coerces a value from its current type to a string in the same manner as Lua. @param {Object} val The value to be converted. @param {String} [error] The error message to throw if the conversion fails. @returns {String} The converted value.
[ "Coerces", "a", "value", "from", "its", "current", "type", "to", "a", "string", "in", "the", "same", "manner", "as", "Lua", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/moonshine.js#L6480-L6502
train
gamesys/moonshine
vm/moonshine.js
function (table) { var isArr = shine.lib.table.getn (table) > 0, result = shine.gc['create' + (isArr? 'Array' : 'Object')](), numValues = table.__shine.numValues, i, l = numValues.length; for (i = 1; i < l; i++) { result[i - 1] = ((numValues[i] || shine.EMPTY_OBJ) instanceof shine.Table)? shine.utils.toObject(numValues[i]) : numValues[i]; } for (i in table) { if (table.hasOwnProperty(i) && !(i in shine.Table.prototype) && i !== '__shine') { result[i] = ((table[i] || shine.EMPTY_OBJ) instanceof shine.Table)? shine.utils.toObject(table[i]) : table[i]; } } return result; }
javascript
function (table) { var isArr = shine.lib.table.getn (table) > 0, result = shine.gc['create' + (isArr? 'Array' : 'Object')](), numValues = table.__shine.numValues, i, l = numValues.length; for (i = 1; i < l; i++) { result[i - 1] = ((numValues[i] || shine.EMPTY_OBJ) instanceof shine.Table)? shine.utils.toObject(numValues[i]) : numValues[i]; } for (i in table) { if (table.hasOwnProperty(i) && !(i in shine.Table.prototype) && i !== '__shine') { result[i] = ((table[i] || shine.EMPTY_OBJ) instanceof shine.Table)? shine.utils.toObject(table[i]) : table[i]; } } return result; }
[ "function", "(", "table", ")", "{", "var", "isArr", "=", "shine", ".", "lib", ".", "table", ".", "getn", "(", "table", ")", ">", "0", ",", "result", "=", "shine", ".", "gc", "[", "'create'", "+", "(", "isArr", "?", "'Array'", ":", "'Object'", ")", "]", "(", ")", ",", "numValues", "=", "table", ".", "__shine", ".", "numValues", ",", "i", ",", "l", "=", "numValues", ".", "length", ";", "for", "(", "i", "=", "1", ";", "i", "<", "l", ";", "i", "++", ")", "{", "result", "[", "i", "-", "1", "]", "=", "(", "(", "numValues", "[", "i", "]", "||", "shine", ".", "EMPTY_OBJ", ")", "instanceof", "shine", ".", "Table", ")", "?", "shine", ".", "utils", ".", "toObject", "(", "numValues", "[", "i", "]", ")", ":", "numValues", "[", "i", "]", ";", "}", "for", "(", "i", "in", "table", ")", "{", "if", "(", "table", ".", "hasOwnProperty", "(", "i", ")", "&&", "!", "(", "i", "in", "shine", ".", "Table", ".", "prototype", ")", "&&", "i", "!==", "'__shine'", ")", "{", "result", "[", "i", "]", "=", "(", "(", "table", "[", "i", "]", "||", "shine", ".", "EMPTY_OBJ", ")", "instanceof", "shine", ".", "Table", ")", "?", "shine", ".", "utils", ".", "toObject", "(", "table", "[", "i", "]", ")", ":", "table", "[", "i", "]", ";", "}", "}", "return", "result", ";", "}" ]
Converts a Lua table and all of its nested properties to a JavaScript objects or arrays. @param {shine.Table} table The Lua table object. @returns {Object} The converted object.
[ "Converts", "a", "Lua", "table", "and", "all", "of", "its", "nested", "properties", "to", "a", "JavaScript", "objects", "or", "arrays", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/moonshine.js#L6551-L6569
train
gamesys/moonshine
vm/moonshine.js
function (url, success, error) { var xhr = new XMLHttpRequest(), parse; xhr.open('GET', url, true); // Use ArrayBuffer where possible. Luac files do not load properly with 'text'. if ('ArrayBuffer' in window) { xhr.responseType = 'arraybuffer'; parse = function (data) { // There is a limit on the number of arguments one can pass to a function. So far iPad is the lowest, and 10000 is safe. // If safe number of arguments to pass to fromCharCode: if (data.byteLength <= 10000) return String.fromCharCode.apply(String, Array.prototype.slice.call(new Uint8Array(data))); // otherwise break up bytearray: var i, l, arr = new Uint8Array(data), result = ''; for (i = 0, l = data.byteLength; i < l; i += 10000) { result += String.fromCharCode.apply(String, Array.prototype.slice.call(arr.subarray(i, Math.min(i + 10000, l)))); } return result; }; } else { xhr.responseType = 'text'; parse = function (data) { return data; }; } xhr.onload = function (e) { if (this.status == 200) { if (success) success(parse(this.response)); } else { if (error) error(this.status); } } xhr.send(shine.EMPTY_OBJ); }
javascript
function (url, success, error) { var xhr = new XMLHttpRequest(), parse; xhr.open('GET', url, true); // Use ArrayBuffer where possible. Luac files do not load properly with 'text'. if ('ArrayBuffer' in window) { xhr.responseType = 'arraybuffer'; parse = function (data) { // There is a limit on the number of arguments one can pass to a function. So far iPad is the lowest, and 10000 is safe. // If safe number of arguments to pass to fromCharCode: if (data.byteLength <= 10000) return String.fromCharCode.apply(String, Array.prototype.slice.call(new Uint8Array(data))); // otherwise break up bytearray: var i, l, arr = new Uint8Array(data), result = ''; for (i = 0, l = data.byteLength; i < l; i += 10000) { result += String.fromCharCode.apply(String, Array.prototype.slice.call(arr.subarray(i, Math.min(i + 10000, l)))); } return result; }; } else { xhr.responseType = 'text'; parse = function (data) { return data; }; } xhr.onload = function (e) { if (this.status == 200) { if (success) success(parse(this.response)); } else { if (error) error(this.status); } } xhr.send(shine.EMPTY_OBJ); }
[ "function", "(", "url", ",", "success", ",", "error", ")", "{", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ",", "parse", ";", "xhr", ".", "open", "(", "'GET'", ",", "url", ",", "true", ")", ";", "if", "(", "'ArrayBuffer'", "in", "window", ")", "{", "xhr", ".", "responseType", "=", "'arraybuffer'", ";", "parse", "=", "function", "(", "data", ")", "{", "if", "(", "data", ".", "byteLength", "<=", "10000", ")", "return", "String", ".", "fromCharCode", ".", "apply", "(", "String", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "new", "Uint8Array", "(", "data", ")", ")", ")", ";", "var", "i", ",", "l", ",", "arr", "=", "new", "Uint8Array", "(", "data", ")", ",", "result", "=", "''", ";", "for", "(", "i", "=", "0", ",", "l", "=", "data", ".", "byteLength", ";", "i", "<", "l", ";", "i", "+=", "10000", ")", "{", "result", "+=", "String", ".", "fromCharCode", ".", "apply", "(", "String", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arr", ".", "subarray", "(", "i", ",", "Math", ".", "min", "(", "i", "+", "10000", ",", "l", ")", ")", ")", ")", ";", "}", "return", "result", ";", "}", ";", "}", "else", "{", "xhr", ".", "responseType", "=", "'text'", ";", "parse", "=", "function", "(", "data", ")", "{", "return", "data", ";", "}", ";", "}", "xhr", ".", "onload", "=", "function", "(", "e", ")", "{", "if", "(", "this", ".", "status", "==", "200", ")", "{", "if", "(", "success", ")", "success", "(", "parse", "(", "this", ".", "response", ")", ")", ";", "}", "else", "{", "if", "(", "error", ")", "error", "(", "this", ".", "status", ")", ";", "}", "}", "xhr", ".", "send", "(", "shine", ".", "EMPTY_OBJ", ")", ";", "}" ]
Makes an HTTP GET request. @param {String} url The URL to request. @param {Function} success The callback to be executed upon a successful outcome. @param {Function} error The callback to be executed upon an unsuccessful outcome.
[ "Makes", "an", "HTTP", "GET", "request", "." ]
880a44077604fa397ea363e5d683105e58478c5f
https://github.com/gamesys/moonshine/blob/880a44077604fa397ea363e5d683105e58478c5f/vm/moonshine.js#L6592-L6635
train
segmentio/snippet
lib/index.js
defaults
function defaults(options) { options || (options = {}); options.apiKey || (options.apiKey = 'YOUR_API_KEY'); options.host || (options.host = 'cdn.segment.com'); if (!has.call(options, 'page')) options.page = true; if (!has.call(options, 'load')) options.load = true; return options; }
javascript
function defaults(options) { options || (options = {}); options.apiKey || (options.apiKey = 'YOUR_API_KEY'); options.host || (options.host = 'cdn.segment.com'); if (!has.call(options, 'page')) options.page = true; if (!has.call(options, 'load')) options.load = true; return options; }
[ "function", "defaults", "(", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "options", ".", "apiKey", "||", "(", "options", ".", "apiKey", "=", "'YOUR_API_KEY'", ")", ";", "options", ".", "host", "||", "(", "options", ".", "host", "=", "'cdn.segment.com'", ")", ";", "if", "(", "!", "has", ".", "call", "(", "options", ",", "'page'", ")", ")", "options", ".", "page", "=", "true", ";", "if", "(", "!", "has", ".", "call", "(", "options", ",", "'load'", ")", ")", "options", ".", "load", "=", "true", ";", "return", "options", ";", "}" ]
Back an options object with the snippet defaults. @param {Object} options (optional) @return {Object}
[ "Back", "an", "options", "object", "with", "the", "snippet", "defaults", "." ]
564a594e5284ae6469bb4e864cabde66ce7f0c1b
https://github.com/segmentio/snippet/blob/564a594e5284ae6469bb4e864cabde66ce7f0c1b/lib/index.js#L52-L59
train
segmentio/snippet
lib/index.js
renderPage
function renderPage(page) { if (!page) return ''; var args = []; if (page.category) args.push(page.category); if (page.name) args.push(page.name); if (page.properties) args.push(page.properties); // eslint-disable-next-line no-restricted-globals var res = 'analytics.page(' + map(JSON.stringify, args).join(', ') + ');'; return res; }
javascript
function renderPage(page) { if (!page) return ''; var args = []; if (page.category) args.push(page.category); if (page.name) args.push(page.name); if (page.properties) args.push(page.properties); // eslint-disable-next-line no-restricted-globals var res = 'analytics.page(' + map(JSON.stringify, args).join(', ') + ');'; return res; }
[ "function", "renderPage", "(", "page", ")", "{", "if", "(", "!", "page", ")", "return", "''", ";", "var", "args", "=", "[", "]", ";", "if", "(", "page", ".", "category", ")", "args", ".", "push", "(", "page", ".", "category", ")", ";", "if", "(", "page", ".", "name", ")", "args", ".", "push", "(", "page", ".", "name", ")", ";", "if", "(", "page", ".", "properties", ")", "args", ".", "push", "(", "page", ".", "properties", ")", ";", "var", "res", "=", "'analytics.page('", "+", "map", "(", "JSON", ".", "stringify", ",", "args", ")", ".", "join", "(", "', '", ")", "+", "');'", ";", "return", "res", ";", "}" ]
Handlebars helper which will render the window.analytics.page call. By default just render the empty call, adding whatever arguments are passed in explicitly. @param {Object|Boolean} page options (name, category, properties) @return {String}
[ "Handlebars", "helper", "which", "will", "render", "the", "window", ".", "analytics", ".", "page", "call", "." ]
564a594e5284ae6469bb4e864cabde66ce7f0c1b
https://github.com/segmentio/snippet/blob/564a594e5284ae6469bb4e864cabde66ce7f0c1b/lib/index.js#L71-L84
train
recharts/recharts-scale
src/getNiceTickValues.js
getValidInterval
function getValidInterval([min, max]) { let [validMin, validMax] = [min, max]; // exchange if (min > max) { [validMin, validMax] = [max, min]; } return [validMin, validMax]; }
javascript
function getValidInterval([min, max]) { let [validMin, validMax] = [min, max]; // exchange if (min > max) { [validMin, validMax] = [max, min]; } return [validMin, validMax]; }
[ "function", "getValidInterval", "(", "[", "min", ",", "max", "]", ")", "{", "let", "[", "validMin", ",", "validMax", "]", "=", "[", "min", ",", "max", "]", ";", "if", "(", "min", ">", "max", ")", "{", "[", "validMin", ",", "validMax", "]", "=", "[", "max", ",", "min", "]", ";", "}", "return", "[", "validMin", ",", "validMax", "]", ";", "}" ]
Calculate a interval of a minimum value and a maximum value @param {Number} min The minimum value @param {Number} max The maximum value @return {Array} An interval
[ "Calculate", "a", "interval", "of", "a", "minimum", "value", "and", "a", "maximum", "value" ]
8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a
https://github.com/recharts/recharts-scale/blob/8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a/src/getNiceTickValues.js#L19-L28
train
recharts/recharts-scale
src/getNiceTickValues.js
getFormatStep
function getFormatStep(roughStep, allowDecimals, correctionFactor) { if (roughStep.lte(0)) { return new Decimal(0); } const digitCount = Arithmetic.getDigitCount(roughStep.toNumber()); // The ratio between the rough step and the smallest number which has a bigger // order of magnitudes than the rough step const digitCountValue = new Decimal(10).pow(digitCount); const stepRatio = roughStep.div(digitCountValue); // When an integer and a float multiplied, the accuracy of result may be wrong const stepRatioScale = digitCount !== 1 ? 0.05 : 0.1; const amendStepRatio = new Decimal( Math.ceil(stepRatio.div(stepRatioScale).toNumber()), ).add(correctionFactor).mul(stepRatioScale); const formatStep = amendStepRatio.mul(digitCountValue); return allowDecimals ? formatStep : new Decimal(Math.ceil(formatStep)); }
javascript
function getFormatStep(roughStep, allowDecimals, correctionFactor) { if (roughStep.lte(0)) { return new Decimal(0); } const digitCount = Arithmetic.getDigitCount(roughStep.toNumber()); // The ratio between the rough step and the smallest number which has a bigger // order of magnitudes than the rough step const digitCountValue = new Decimal(10).pow(digitCount); const stepRatio = roughStep.div(digitCountValue); // When an integer and a float multiplied, the accuracy of result may be wrong const stepRatioScale = digitCount !== 1 ? 0.05 : 0.1; const amendStepRatio = new Decimal( Math.ceil(stepRatio.div(stepRatioScale).toNumber()), ).add(correctionFactor).mul(stepRatioScale); const formatStep = amendStepRatio.mul(digitCountValue); return allowDecimals ? formatStep : new Decimal(Math.ceil(formatStep)); }
[ "function", "getFormatStep", "(", "roughStep", ",", "allowDecimals", ",", "correctionFactor", ")", "{", "if", "(", "roughStep", ".", "lte", "(", "0", ")", ")", "{", "return", "new", "Decimal", "(", "0", ")", ";", "}", "const", "digitCount", "=", "Arithmetic", ".", "getDigitCount", "(", "roughStep", ".", "toNumber", "(", ")", ")", ";", "const", "digitCountValue", "=", "new", "Decimal", "(", "10", ")", ".", "pow", "(", "digitCount", ")", ";", "const", "stepRatio", "=", "roughStep", ".", "div", "(", "digitCountValue", ")", ";", "const", "stepRatioScale", "=", "digitCount", "!==", "1", "?", "0.05", ":", "0.1", ";", "const", "amendStepRatio", "=", "new", "Decimal", "(", "Math", ".", "ceil", "(", "stepRatio", ".", "div", "(", "stepRatioScale", ")", ".", "toNumber", "(", ")", ")", ",", ")", ".", "add", "(", "correctionFactor", ")", ".", "mul", "(", "stepRatioScale", ")", ";", "const", "formatStep", "=", "amendStepRatio", ".", "mul", "(", "digitCountValue", ")", ";", "return", "allowDecimals", "?", "formatStep", ":", "new", "Decimal", "(", "Math", ".", "ceil", "(", "formatStep", ")", ")", ";", "}" ]
Calculate the step which is easy to understand between ticks, like 10, 20, 25 @param {Decimal} roughStep The rough step calculated by deviding the difference by the tickCount @param {Boolean} allowDecimals Allow the ticks to be decimals or not @param {Integer} correctionFactor A correction factor @return {Decimal} The step which is easy to understand between two ticks
[ "Calculate", "the", "step", "which", "is", "easy", "to", "understand", "between", "ticks", "like", "10", "20", "25" ]
8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a
https://github.com/recharts/recharts-scale/blob/8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a/src/getNiceTickValues.js#L39-L56
train