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
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
kevoree/kevoree-js
tools/kevoree-kevscript/lib/util/model-helper.js
isCompatible
function isCompatible(tdef, node) { if (tdef && node) { if (tdef.select('metaData[name=virtual]').array.length > 0) { // tdef is virtual, so it is compatible return true; } else { const nodePlatforms = getPlatforms(node.typeDefinition); for (let i = 0; i < nodePlatforms.length; i++) { if (tdef.select('deployUnits[name=*]/filters[name=platform,value=' + nodePlatforms[i] + ']').array.length > 0) { return true; } } } } return false; }
javascript
function isCompatible(tdef, node) { if (tdef && node) { if (tdef.select('metaData[name=virtual]').array.length > 0) { // tdef is virtual, so it is compatible return true; } else { const nodePlatforms = getPlatforms(node.typeDefinition); for (let i = 0; i < nodePlatforms.length; i++) { if (tdef.select('deployUnits[name=*]/filters[name=platform,value=' + nodePlatforms[i] + ']').array.length > 0) { return true; } } } } return false; }
[ "function", "isCompatible", "(", "tdef", ",", "node", ")", "{", "if", "(", "tdef", "&&", "node", ")", "{", "if", "(", "tdef", ".", "select", "(", "'metaData[name=virtual]'", ")", ".", "array", ".", "length", ">", "0", ")", "{", "return", "true", ";", "}", "else", "{", "const", "nodePlatforms", "=", "getPlatforms", "(", "node", ".", "typeDefinition", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "nodePlatforms", ".", "length", ";", "i", "++", ")", "{", "if", "(", "tdef", ".", "select", "(", "'deployUnits[name=*]/filters[name=platform,value='", "+", "nodePlatforms", "[", "i", "]", "+", "']'", ")", ".", "array", ".", "length", ">", "0", ")", "{", "return", "true", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Returns whether or not the given "tdef" is compatible with the given "node" if the tdef has a platform compatible with the node type @param tdef @param node @returns {Boolean}
[ "Returns", "whether", "or", "not", "the", "given", "tdef", "is", "compatible", "with", "the", "given", "node", "if", "the", "tdef", "has", "a", "platform", "compatible", "with", "the", "node", "type" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-kevscript/lib/util/model-helper.js#L60-L77
train
kevoree/kevoree-js
tools/kevoree-kevscript/lib/util/model-helper.js
getFQN
function getFQN(tdef) { const hasPreRelease = tdef.deployUnits.array.some((du) => { return semver.prerelease(du.version) !== null; }); const duTag = hasPreRelease ? '/LATEST' : ''; let fqn = tdef.name + '/' + tdef.version + duTag; function walk(pkg) { if (pkg.eContainer()) { fqn = pkg.name + '.' + fqn; walk(pkg.eContainer()); } } walk(tdef.eContainer()); return fqn; }
javascript
function getFQN(tdef) { const hasPreRelease = tdef.deployUnits.array.some((du) => { return semver.prerelease(du.version) !== null; }); const duTag = hasPreRelease ? '/LATEST' : ''; let fqn = tdef.name + '/' + tdef.version + duTag; function walk(pkg) { if (pkg.eContainer()) { fqn = pkg.name + '.' + fqn; walk(pkg.eContainer()); } } walk(tdef.eContainer()); return fqn; }
[ "function", "getFQN", "(", "tdef", ")", "{", "const", "hasPreRelease", "=", "tdef", ".", "deployUnits", ".", "array", ".", "some", "(", "(", "du", ")", "=>", "{", "return", "semver", ".", "prerelease", "(", "du", ".", "version", ")", "!==", "null", ";", "}", ")", ";", "const", "duTag", "=", "hasPreRelease", "?", "'/LATEST'", ":", "''", ";", "let", "fqn", "=", "tdef", ".", "name", "+", "'/'", "+", "tdef", ".", "version", "+", "duTag", ";", "function", "walk", "(", "pkg", ")", "{", "if", "(", "pkg", ".", "eContainer", "(", ")", ")", "{", "fqn", "=", "pkg", ".", "name", "+", "'.'", "+", "fqn", ";", "walk", "(", "pkg", ".", "eContainer", "(", ")", ")", ";", "}", "}", "walk", "(", "tdef", ".", "eContainer", "(", ")", ")", ";", "return", "fqn", ";", "}" ]
Returns the FQN of the given TypeDefinition @param tdef @returns {String}
[ "Returns", "the", "FQN", "of", "the", "given", "TypeDefinition" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-kevscript/lib/util/model-helper.js#L84-L103
train
EikosPartners/scalejs
src/scalejs.base.log.js
formatException
function formatException (ex) { var stack = (ex.stack) ? String(ex.stack) : '', message = ex.message || ''; return 'Error: ' + message + '\nStack: ' + stack; }
javascript
function formatException (ex) { var stack = (ex.stack) ? String(ex.stack) : '', message = ex.message || ''; return 'Error: ' + message + '\nStack: ' + stack; }
[ "function", "formatException", "(", "ex", ")", "{", "var", "stack", "=", "(", "ex", ".", "stack", ")", "?", "String", "(", "ex", ".", "stack", ")", ":", "''", ",", "message", "=", "ex", ".", "message", "||", "''", ";", "return", "'Error: '", "+", "message", "+", "'\\nStack: '", "+", "\\n", ";", "}" ]
Formats an exception for better output @param {Object} ex exception object @memberOf log @return {String} formatted exception
[ "Formats", "an", "exception", "for", "better", "output" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/src/scalejs.base.log.js#L79-L83
train
novacrazy/scriptor
bin/scriptor.js
onError
function onError( error ) { logger.error( error.stack || error ); process.exit( EXIT_FAILURE ); }
javascript
function onError( error ) { logger.error( error.stack || error ); process.exit( EXIT_FAILURE ); }
[ "function", "onError", "(", "error", ")", "{", "logger", ".", "error", "(", "error", ".", "stack", "||", "error", ")", ";", "process", ".", "exit", "(", "EXIT_FAILURE", ")", ";", "}" ]
Unhandled errors are printed and the process is killed
[ "Unhandled", "errors", "are", "printed", "and", "the", "process", "is", "killed" ]
eef8051c85e2b26cf41bafec0873874d3710d111
https://github.com/novacrazy/scriptor/blob/eef8051c85e2b26cf41bafec0873874d3710d111/bin/scriptor.js#L73-L76
train
datagovsg/datagovsg-plottable-charts
lib/datagovsg-charts.js
baseIsMatch
function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; }
javascript
function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; }
[ "function", "baseIsMatch", "(", "object", ",", "source", ",", "matchData", ",", "customizer", ")", "{", "var", "index", "=", "matchData", ".", "length", ",", "length", "=", "index", ",", "noCustomizer", "=", "!", "customizer", ";", "if", "(", "object", "==", "null", ")", "{", "return", "!", "length", ";", "}", "object", "=", "Object", "(", "object", ")", ";", "while", "(", "index", "--", ")", "{", "var", "data", "=", "matchData", "[", "index", "]", ";", "if", "(", "(", "noCustomizer", "&&", "data", "[", "2", "]", ")", "?", "data", "[", "1", "]", "!==", "object", "[", "data", "[", "0", "]", "]", ":", "!", "(", "data", "[", "0", "]", "in", "object", ")", ")", "{", "return", "false", ";", "}", "}", "while", "(", "++", "index", "<", "length", ")", "{", "data", "=", "matchData", "[", "index", "]", ";", "var", "key", "=", "data", "[", "0", "]", ",", "objValue", "=", "object", "[", "key", "]", ",", "srcValue", "=", "data", "[", "1", "]", ";", "if", "(", "noCustomizer", "&&", "data", "[", "2", "]", ")", "{", "if", "(", "objValue", "===", "undefined", "&&", "!", "(", "key", "in", "object", ")", ")", "{", "return", "false", ";", "}", "}", "else", "{", "var", "stack", "=", "new", "_Stack", ";", "if", "(", "customizer", ")", "{", "var", "result", "=", "customizer", "(", "objValue", ",", "srcValue", ",", "key", ",", "object", ",", "source", ",", "stack", ")", ";", "}", "if", "(", "!", "(", "result", "===", "undefined", "?", "_baseIsEqual", "(", "srcValue", ",", "objValue", ",", "COMPARE_PARTIAL_FLAG", "|", "COMPARE_UNORDERED_FLAG", ",", "customizer", ",", "stack", ")", ":", "result", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
The base implementation of `_.isMatch` without support for iteratee shorthands. @private @param {Object} object The object to inspect. @param {Object} source The object of property values to match. @param {Array} matchData The property names, values, and compare flags to match. @param {Function} [customizer] The function to customize comparisons. @returns {boolean} Returns `true` if `object` is a match, else `false`.
[ "The", "base", "implementation", "of", "_", ".", "isMatch", "without", "support", "for", "iteratee", "shorthands", "." ]
f08c65c50f4be32dacb984ba5fd916e23d11e9d2
https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/datagovsg-charts.js#L3101-L3143
train
datagovsg/datagovsg-plottable-charts
lib/datagovsg-charts.js
compareAscending
function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; }
javascript
function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; }
[ "function", "compareAscending", "(", "value", ",", "other", ")", "{", "if", "(", "value", "!==", "other", ")", "{", "var", "valIsDefined", "=", "value", "!==", "undefined", ",", "valIsNull", "=", "value", "===", "null", ",", "valIsReflexive", "=", "value", "===", "value", ",", "valIsSymbol", "=", "isSymbol_1", "(", "value", ")", ";", "var", "othIsDefined", "=", "other", "!==", "undefined", ",", "othIsNull", "=", "other", "===", "null", ",", "othIsReflexive", "=", "other", "===", "other", ",", "othIsSymbol", "=", "isSymbol_1", "(", "other", ")", ";", "if", "(", "(", "!", "othIsNull", "&&", "!", "othIsSymbol", "&&", "!", "valIsSymbol", "&&", "value", ">", "other", ")", "||", "(", "valIsSymbol", "&&", "othIsDefined", "&&", "othIsReflexive", "&&", "!", "othIsNull", "&&", "!", "othIsSymbol", ")", "||", "(", "valIsNull", "&&", "othIsDefined", "&&", "othIsReflexive", ")", "||", "(", "!", "valIsDefined", "&&", "othIsReflexive", ")", "||", "!", "valIsReflexive", ")", "{", "return", "1", ";", "}", "if", "(", "(", "!", "valIsNull", "&&", "!", "valIsSymbol", "&&", "!", "othIsSymbol", "&&", "value", "<", "other", ")", "||", "(", "othIsSymbol", "&&", "valIsDefined", "&&", "valIsReflexive", "&&", "!", "valIsNull", "&&", "!", "valIsSymbol", ")", "||", "(", "othIsNull", "&&", "valIsDefined", "&&", "valIsReflexive", ")", "||", "(", "!", "othIsDefined", "&&", "valIsReflexive", ")", "||", "!", "othIsReflexive", ")", "{", "return", "-", "1", ";", "}", "}", "return", "0", ";", "}" ]
Compares values to sort them in ascending order. @private @param {*} value The value to compare. @param {*} other The other value to compare. @returns {number} Returns the sort order indicator for `value`.
[ "Compares", "values", "to", "sort", "them", "in", "ascending", "order", "." ]
f08c65c50f4be32dacb984ba5fd916e23d11e9d2
https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/datagovsg-charts.js#L3884-L3912
train
datagovsg/datagovsg-plottable-charts
lib/datagovsg-charts.js
customizeTimeAxis
function customizeTimeAxis(component, type) { var axis = component.xAxis; if (axis instanceof Plottable.Axes.Time) { var customTimeAxisConfigs = getCustomTimeAxisConfigs(type); axis.axisConfigurations(customTimeAxisConfigs); if (type === 'year' || type === 'financial_year') { axis.tierLabelPositions(customTimeAxisConfigs.map(function (v) { return 'center'; })); } } }
javascript
function customizeTimeAxis(component, type) { var axis = component.xAxis; if (axis instanceof Plottable.Axes.Time) { var customTimeAxisConfigs = getCustomTimeAxisConfigs(type); axis.axisConfigurations(customTimeAxisConfigs); if (type === 'year' || type === 'financial_year') { axis.tierLabelPositions(customTimeAxisConfigs.map(function (v) { return 'center'; })); } } }
[ "function", "customizeTimeAxis", "(", "component", ",", "type", ")", "{", "var", "axis", "=", "component", ".", "xAxis", ";", "if", "(", "axis", "instanceof", "Plottable", ".", "Axes", ".", "Time", ")", "{", "var", "customTimeAxisConfigs", "=", "getCustomTimeAxisConfigs", "(", "type", ")", ";", "axis", ".", "axisConfigurations", "(", "customTimeAxisConfigs", ")", ";", "if", "(", "type", "===", "'year'", "||", "type", "===", "'financial_year'", ")", "{", "axis", ".", "tierLabelPositions", "(", "customTimeAxisConfigs", ".", "map", "(", "function", "(", "v", ")", "{", "return", "'center'", ";", "}", ")", ")", ";", "}", "}", "}" ]
type can be one of the following 'year' 'financial_year' 'half_year' 'financial_half_year' 'quarter' 'financial_quarter' 'month' 'week' 'date' 'datetime' 'time'
[ "type", "can", "be", "one", "of", "the", "following", "year", "financial_year", "half_year", "financial_half_year", "quarter", "financial_quarter", "month", "week", "date", "datetime", "time" ]
f08c65c50f4be32dacb984ba5fd916e23d11e9d2
https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/datagovsg-charts.js#L5715-L5726
train
datagovsg/datagovsg-plottable-charts
lib/datagovsg-charts.js
removeInnerPadding
function removeInnerPadding(component) { var _makeInnerScale = component.plot._makeInnerScale; component.plot._makeInnerScale = function () { return _makeInnerScale.call(this).innerPadding(0).outerPadding(0); }; }
javascript
function removeInnerPadding(component) { var _makeInnerScale = component.plot._makeInnerScale; component.plot._makeInnerScale = function () { return _makeInnerScale.call(this).innerPadding(0).outerPadding(0); }; }
[ "function", "removeInnerPadding", "(", "component", ")", "{", "var", "_makeInnerScale", "=", "component", ".", "plot", ".", "_makeInnerScale", ";", "component", ".", "plot", ".", "_makeInnerScale", "=", "function", "(", ")", "{", "return", "_makeInnerScale", ".", "call", "(", "this", ")", ".", "innerPadding", "(", "0", ")", ".", "outerPadding", "(", "0", ")", ";", "}", ";", "}" ]
FIXME Very very hackish stuff Might break when upgrading to Plottable 3.0
[ "FIXME", "Very", "very", "hackish", "stuff", "Might", "break", "when", "upgrading", "to", "Plottable", "3", ".", "0" ]
f08c65c50f4be32dacb984ba5fd916e23d11e9d2
https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/datagovsg-charts.js#L5734-L5739
train
kflorence/gulp-pretty-url
index.js
prettyUrl
function prettyUrl(file) { file.extname = ".html"; if (file.basename !== "index") { file.dirname = path.join(file.dirname, file.basename); file.basename = "index"; } return file; }
javascript
function prettyUrl(file) { file.extname = ".html"; if (file.basename !== "index") { file.dirname = path.join(file.dirname, file.basename); file.basename = "index"; } return file; }
[ "function", "prettyUrl", "(", "file", ")", "{", "file", ".", "extname", "=", "\".html\"", ";", "if", "(", "file", ".", "basename", "!==", "\"index\"", ")", "{", "file", ".", "dirname", "=", "path", ".", "join", "(", "file", ".", "dirname", ",", "file", ".", "basename", ")", ";", "file", ".", "basename", "=", "\"index\"", ";", "}", "return", "file", ";", "}" ]
Generate pretty URLs for files piped through this method. @see `gulp-rename` for more information @param {Object} file Object containing file path information @return Modified file path object
[ "Generate", "pretty", "URLs", "for", "files", "piped", "through", "this", "method", "." ]
ec7440ae2161d44c4f553d4ebe6644082344640c
https://github.com/kflorence/gulp-pretty-url/blob/ec7440ae2161d44c4f553d4ebe6644082344640c/index.js#L12-L21
train
dbowring/elm-forest
lib/forest.js
function (name) { if (name === undefined || name === 'stable') { return 0; } else if (name === 'alpha') { return Number.MAX_SAFE_INTEGER - 1; } else if (name == 'beta') { return Number.MAX_SAFE_INTEGER - 2; } else { // Possibly something like "RC", but for not officially supported return Number.MAX_SAFE_INTEGER - 3; } }
javascript
function (name) { if (name === undefined || name === 'stable') { return 0; } else if (name === 'alpha') { return Number.MAX_SAFE_INTEGER - 1; } else if (name == 'beta') { return Number.MAX_SAFE_INTEGER - 2; } else { // Possibly something like "RC", but for not officially supported return Number.MAX_SAFE_INTEGER - 3; } }
[ "function", "(", "name", ")", "{", "if", "(", "name", "===", "undefined", "||", "name", "===", "'stable'", ")", "{", "return", "0", ";", "}", "else", "if", "(", "name", "===", "'alpha'", ")", "{", "return", "Number", ".", "MAX_SAFE_INTEGER", "-", "1", ";", "}", "else", "if", "(", "name", "==", "'beta'", ")", "{", "return", "Number", ".", "MAX_SAFE_INTEGER", "-", "2", ";", "}", "else", "{", "return", "Number", ".", "MAX_SAFE_INTEGER", "-", "3", ";", "}", "}" ]
Convert a release stage into a number
[ "Convert", "a", "release", "stage", "into", "a", "number" ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L187-L201
train
dbowring/elm-forest
lib/forest.js
function (constraint) { let first = /((?:\d+(?:\.\d+){0,2}))\s+(\<=|\>=|\<|\>)\s+v/; let second = /v\s+(\<=|\>=|\<|\>)\s+((?:\d+(?:\.\d+){0,2}))/; let firstMatch = constraint.match(first); let secondMatch = constraint.match(second); ; let alwaysFail = (v) => false; let firstOp = { '<': (a) => (v) => a < v, '<=': (a) => (v) => a <= v, '>': (a) => (v) => a > v, '>=': (a) => (v) => a >= v, }; let secondOp = { '<': (a) => (v) => v < a, '<=': (a) => (v) => v <= a, '>': (a) => (v) => v > a, '>=': (a) => (v) => v >= a, }; if (firstMatch && secondMatch) { let firstVersion = parseVersionString(firstMatch[1]); let secondVersion = parseVersionString(secondMatch[2]); return [ firstVersion ? firstOp[firstMatch[2]](firstVersion) : alwaysFail, secondVersion ? secondOp[secondMatch[1]](secondVersion) : alwaysFail ]; } return null; }
javascript
function (constraint) { let first = /((?:\d+(?:\.\d+){0,2}))\s+(\<=|\>=|\<|\>)\s+v/; let second = /v\s+(\<=|\>=|\<|\>)\s+((?:\d+(?:\.\d+){0,2}))/; let firstMatch = constraint.match(first); let secondMatch = constraint.match(second); ; let alwaysFail = (v) => false; let firstOp = { '<': (a) => (v) => a < v, '<=': (a) => (v) => a <= v, '>': (a) => (v) => a > v, '>=': (a) => (v) => a >= v, }; let secondOp = { '<': (a) => (v) => v < a, '<=': (a) => (v) => v <= a, '>': (a) => (v) => v > a, '>=': (a) => (v) => v >= a, }; if (firstMatch && secondMatch) { let firstVersion = parseVersionString(firstMatch[1]); let secondVersion = parseVersionString(secondMatch[2]); return [ firstVersion ? firstOp[firstMatch[2]](firstVersion) : alwaysFail, secondVersion ? secondOp[secondMatch[1]](secondVersion) : alwaysFail ]; } return null; }
[ "function", "(", "constraint", ")", "{", "let", "first", "=", "/", "((?:\\d+(?:\\.\\d+){0,2}))\\s+(\\<=|\\>=|\\<|\\>)\\s+v", "/", ";", "let", "second", "=", "/", "v\\s+(\\<=|\\>=|\\<|\\>)\\s+((?:\\d+(?:\\.\\d+){0,2}))", "/", ";", "let", "firstMatch", "=", "constraint", ".", "match", "(", "first", ")", ";", "let", "secondMatch", "=", "constraint", ".", "match", "(", "second", ")", ";", ";", "let", "alwaysFail", "=", "(", "v", ")", "=>", "false", ";", "let", "firstOp", "=", "{", "'<'", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "a", "<", "v", ",", "'<='", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "a", "<=", "v", ",", "'>'", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "a", ">", "v", ",", "'>='", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "a", ">=", "v", ",", "}", ";", "let", "secondOp", "=", "{", "'<'", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "v", "<", "a", ",", "'<='", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "v", "<=", "a", ",", "'>'", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "v", ">", "a", ",", "'>='", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "v", ">=", "a", ",", "}", ";", "if", "(", "firstMatch", "&&", "secondMatch", ")", "{", "let", "firstVersion", "=", "parseVersionString", "(", "firstMatch", "[", "1", "]", ")", ";", "let", "secondVersion", "=", "parseVersionString", "(", "secondMatch", "[", "2", "]", ")", ";", "return", "[", "firstVersion", "?", "firstOp", "[", "firstMatch", "[", "2", "]", "]", "(", "firstVersion", ")", ":", "alwaysFail", ",", "secondVersion", "?", "secondOp", "[", "secondMatch", "[", "1", "]", "]", "(", "secondVersion", ")", ":", "alwaysFail", "]", ";", "}", "return", "null", ";", "}" ]
Parse a constarint such as `0.18.0 <= v < 0.19.0` into a list of functions to test against a `v` value The value of `v` itself should match the type returned by `parseVersionString`.
[ "Parse", "a", "constarint", "such", "as", "0", ".", "18", ".", "0", "<", "=", "v", "<", "0", ".", "19", ".", "0", "into", "a", "list", "of", "functions", "to", "test", "against", "a", "v", "value", "The", "value", "of", "v", "itself", "should", "match", "the", "type", "returned", "by", "parseVersionString", "." ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L208-L236
train
dbowring/elm-forest
lib/forest.js
function (dirname) { return new Promise((resolve, reject) => { fs.mkdir(dirname, (err) => { if (err) { reject(err); } else { resolve(dirname); } }); }); }
javascript
function (dirname) { return new Promise((resolve, reject) => { fs.mkdir(dirname, (err) => { if (err) { reject(err); } else { resolve(dirname); } }); }); }
[ "function", "(", "dirname", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "mkdir", "(", "dirname", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "dirname", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Non-Recursive mkdir
[ "Non", "-", "Recursive", "mkdir" ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L261-L272
train
dbowring/elm-forest
lib/forest.js
function () { let noop = function () { }; let log = { error: npmlog.error, warn: npmlog.warn, info: noop, verbose: noop, silly: noop, http: noop, pause: noop, resume: noop }; return new RegClient({ log: log }); }
javascript
function () { let noop = function () { }; let log = { error: npmlog.error, warn: npmlog.warn, info: noop, verbose: noop, silly: noop, http: noop, pause: noop, resume: noop }; return new RegClient({ log: log }); }
[ "function", "(", ")", "{", "let", "noop", "=", "function", "(", ")", "{", "}", ";", "let", "log", "=", "{", "error", ":", "npmlog", ".", "error", ",", "warn", ":", "npmlog", ".", "warn", ",", "info", ":", "noop", ",", "verbose", ":", "noop", ",", "silly", ":", "noop", ",", "http", ":", "noop", ",", "pause", ":", "noop", ",", "resume", ":", "noop", "}", ";", "return", "new", "RegClient", "(", "{", "log", ":", "log", "}", ")", ";", "}" ]
Get a NPM client that does minimal console spam NPM Erorrs and warnings will still be sent to the console.
[ "Get", "a", "NPM", "client", "that", "does", "minimal", "console", "spam", "NPM", "Erorrs", "and", "warnings", "will", "still", "be", "sent", "to", "the", "console", "." ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L313-L326
train
dbowring/elm-forest
lib/forest.js
function (version) { return __awaiter(this, void 0, void 0, function* () { let versions = yield ForestInternal.queryElmVersions(); let result = ForestInternal.findSuitable(version, versions); if (result === null) { throw new ForestError(Errors.NoMatchingVersion, `Unable to find an Elm version matching ${version} on NPM`); } return Promise.resolve(result); }); }
javascript
function (version) { return __awaiter(this, void 0, void 0, function* () { let versions = yield ForestInternal.queryElmVersions(); let result = ForestInternal.findSuitable(version, versions); if (result === null) { throw new ForestError(Errors.NoMatchingVersion, `Unable to find an Elm version matching ${version} on NPM`); } return Promise.resolve(result); }); }
[ "function", "(", "version", ")", "{", "return", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "*", "(", ")", "{", "let", "versions", "=", "yield", "ForestInternal", ".", "queryElmVersions", "(", ")", ";", "let", "result", "=", "ForestInternal", ".", "findSuitable", "(", "version", ",", "versions", ")", ";", "if", "(", "result", "===", "null", ")", "{", "throw", "new", "ForestError", "(", "Errors", ".", "NoMatchingVersion", ",", "`", "${", "version", "}", "`", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "result", ")", ";", "}", ")", ";", "}" ]
Expand a version by asking npm
[ "Expand", "a", "version", "by", "asking", "npm" ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L379-L388
train
dbowring/elm-forest
lib/forest.js
function (path) { return new Promise((resolve, reject) => { fs.access(path, fs.constants.F_OK, (err) => { if (err === null) { resolve(true); } else if (err.code === 'ENOENT') { resolve(false); } else { reject(err); } }); }); }
javascript
function (path) { return new Promise((resolve, reject) => { fs.access(path, fs.constants.F_OK, (err) => { if (err === null) { resolve(true); } else if (err.code === 'ENOENT') { resolve(false); } else { reject(err); } }); }); }
[ "function", "(", "path", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "access", "(", "path", ",", "fs", ".", "constants", ".", "F_OK", ",", "(", "err", ")", "=>", "{", "if", "(", "err", "===", "null", ")", "{", "resolve", "(", "true", ")", ";", "}", "else", "if", "(", "err", ".", "code", "===", "'ENOENT'", ")", "{", "resolve", "(", "false", ")", ";", "}", "else", "{", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Does `path` exist on the filesystem?
[ "Does", "path", "exist", "on", "the", "filesystem?" ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L510-L524
train
facet/core
lib/router-manifest.js
function(){ this.manifest = { apiEventType: '', apiModelId: '', // this is the id for this module routeBase: '', // this can be overwritten routes: [ ], routeErrorMessages: { conditions: 'No query conditions were specified', query: 'Error querying for item(s): ', notFound: 'No item was found.', find: 'No item(s) matched your criteria.', findOne: 'No item matched your criteria.', update: 'No updates were specified.', updateMatch: 'No items were updated based on your criteria.', create: 'No data supplied for creating new item.', createMatch: 'No item was created based on your criteria.', remove: 'No data supplied for removing item.', removeMatch: 'No item was removed based on your criteria.' } }; // return this object return this; }
javascript
function(){ this.manifest = { apiEventType: '', apiModelId: '', // this is the id for this module routeBase: '', // this can be overwritten routes: [ ], routeErrorMessages: { conditions: 'No query conditions were specified', query: 'Error querying for item(s): ', notFound: 'No item was found.', find: 'No item(s) matched your criteria.', findOne: 'No item matched your criteria.', update: 'No updates were specified.', updateMatch: 'No items were updated based on your criteria.', create: 'No data supplied for creating new item.', createMatch: 'No item was created based on your criteria.', remove: 'No data supplied for removing item.', removeMatch: 'No item was removed based on your criteria.' } }; // return this object return this; }
[ "function", "(", ")", "{", "this", ".", "manifest", "=", "{", "apiEventType", ":", "''", ",", "apiModelId", ":", "''", ",", "routeBase", ":", "''", ",", "routes", ":", "[", "]", ",", "routeErrorMessages", ":", "{", "conditions", ":", "'No query conditions were specified'", ",", "query", ":", "'Error querying for item(s): '", ",", "notFound", ":", "'No item was found.'", ",", "find", ":", "'No item(s) matched your criteria.'", ",", "findOne", ":", "'No item matched your criteria.'", ",", "update", ":", "'No updates were specified.'", ",", "updateMatch", ":", "'No items were updated based on your criteria.'", ",", "create", ":", "'No data supplied for creating new item.'", ",", "createMatch", ":", "'No item was created based on your criteria.'", ",", "remove", ":", "'No data supplied for removing item.'", ",", "removeMatch", ":", "'No item was removed based on your criteria.'", "}", "}", ";", "return", "this", ";", "}" ]
Router Manifest constructor @return {Object} The Router Manifest Object
[ "Router", "Manifest", "constructor" ]
8e74c1545956dfbfa298a0fa477506980eca362e
https://github.com/facet/core/blob/8e74c1545956dfbfa298a0fa477506980eca362e/lib/router-manifest.js#L11-L36
train
sourcegraph/jsg
symbol_id.js
cleanPath
function cleanPath(p) { p = JSON.stringify(p); return p.slice(1, p.length - 1); }
javascript
function cleanPath(p) { p = JSON.stringify(p); return p.slice(1, p.length - 1); }
[ "function", "cleanPath", "(", "p", ")", "{", "p", "=", "JSON", ".", "stringify", "(", "p", ")", ";", "return", "p", ".", "slice", "(", "1", ",", "p", ".", "length", "-", "1", ")", ";", "}" ]
cleanPath escapes unprintable chars in p.
[ "cleanPath", "escapes", "unprintable", "chars", "in", "p", "." ]
83526b95285bd4381be24b21c6aa47b9dab13bbe
https://github.com/sourcegraph/jsg/blob/83526b95285bd4381be24b21c6aa47b9dab13bbe/symbol_id.js#L17-L20
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js
isHelper
function isHelper(node) { if (t.isMemberExpression(node)) { return isHelper(node.object) || isHelper(node.property); } else if (t.isIdentifier(node)) { return node.name === "require" || node.name[0] === "_"; } else if (t.isCallExpression(node)) { return isHelper(node.callee); } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); } else { return false; } }
javascript
function isHelper(node) { if (t.isMemberExpression(node)) { return isHelper(node.object) || isHelper(node.property); } else if (t.isIdentifier(node)) { return node.name === "require" || node.name[0] === "_"; } else if (t.isCallExpression(node)) { return isHelper(node.callee); } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); } else { return false; } }
[ "function", "isHelper", "(", "node", ")", "{", "if", "(", "t", ".", "isMemberExpression", "(", "node", ")", ")", "{", "return", "isHelper", "(", "node", ".", "object", ")", "||", "isHelper", "(", "node", ".", "property", ")", ";", "}", "else", "if", "(", "t", ".", "isIdentifier", "(", "node", ")", ")", "{", "return", "node", ".", "name", "===", "\"require\"", "||", "node", ".", "name", "[", "0", "]", "===", "\"_\"", ";", "}", "else", "if", "(", "t", ".", "isCallExpression", "(", "node", ")", ")", "{", "return", "isHelper", "(", "node", ".", "callee", ")", ";", "}", "else", "if", "(", "t", ".", "isBinary", "(", "node", ")", "||", "t", ".", "isAssignmentExpression", "(", "node", ")", ")", "{", "return", "t", ".", "isIdentifier", "(", "node", ".", "left", ")", "&&", "isHelper", "(", "node", ".", "left", ")", "||", "isHelper", "(", "node", ".", "right", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Test if a node is or has a helper.
[ "Test", "if", "a", "node", "is", "or", "has", "a", "helper", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js#L62-L74
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js
AssignmentExpression
function AssignmentExpression(node) { var state = crawl(node.right); if (state.hasCall && state.hasHelper || state.hasFunction) { return { before: state.hasFunction, after: true }; } }
javascript
function AssignmentExpression(node) { var state = crawl(node.right); if (state.hasCall && state.hasHelper || state.hasFunction) { return { before: state.hasFunction, after: true }; } }
[ "function", "AssignmentExpression", "(", "node", ")", "{", "var", "state", "=", "crawl", "(", "node", ".", "right", ")", ";", "if", "(", "state", ".", "hasCall", "&&", "state", ".", "hasHelper", "||", "state", ".", "hasFunction", ")", "{", "return", "{", "before", ":", "state", ".", "hasFunction", ",", "after", ":", "true", "}", ";", "}", "}" ]
Test if AssignmentExpression needs whitespace.
[ "Test", "if", "AssignmentExpression", "needs", "whitespace", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js#L94-L102
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js
CallExpression
function CallExpression(node) { if (t.isFunction(node.callee) || isHelper(node)) { return { before: true, after: true }; } }
javascript
function CallExpression(node) { if (t.isFunction(node.callee) || isHelper(node)) { return { before: true, after: true }; } }
[ "function", "CallExpression", "(", "node", ")", "{", "if", "(", "t", ".", "isFunction", "(", "node", ".", "callee", ")", "||", "isHelper", "(", "node", ")", ")", "{", "return", "{", "before", ":", "true", ",", "after", ":", "true", "}", ";", "}", "}" ]
Test if CallExpression needs whitespace.
[ "Test", "if", "CallExpression", "needs", "whitespace", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js#L142-L149
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js
IfStatement
function IfStatement(node) { if (t.isBlockStatement(node.consequent)) { return { before: true, after: true }; } }
javascript
function IfStatement(node) { if (t.isBlockStatement(node.consequent)) { return { before: true, after: true }; } }
[ "function", "IfStatement", "(", "node", ")", "{", "if", "(", "t", ".", "isBlockStatement", "(", "node", ".", "consequent", ")", ")", "{", "return", "{", "before", ":", "true", ",", "after", ":", "true", "}", ";", "}", "}" ]
Test if IfStatement needs whitespace.
[ "Test", "if", "IfStatement", "needs", "whitespace", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js#L178-L185
train
brycebaril/multibuffer
index.js
encode
function encode(buffer, extra) { if (!extra) extra = 0 var blen = buffer.length var lenbytes = vencode(blen) var mb = new Buffer(extra + blen + lenbytes.length) for (var i = 0; i < lenbytes.length; i++) { mb.writeUInt8(lenbytes[i], extra + i) } buffer.copy(mb, lenbytes.length + extra, 0, blen) return mb }
javascript
function encode(buffer, extra) { if (!extra) extra = 0 var blen = buffer.length var lenbytes = vencode(blen) var mb = new Buffer(extra + blen + lenbytes.length) for (var i = 0; i < lenbytes.length; i++) { mb.writeUInt8(lenbytes[i], extra + i) } buffer.copy(mb, lenbytes.length + extra, 0, blen) return mb }
[ "function", "encode", "(", "buffer", ",", "extra", ")", "{", "if", "(", "!", "extra", ")", "extra", "=", "0", "var", "blen", "=", "buffer", ".", "length", "var", "lenbytes", "=", "vencode", "(", "blen", ")", "var", "mb", "=", "new", "Buffer", "(", "extra", "+", "blen", "+", "lenbytes", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lenbytes", ".", "length", ";", "i", "++", ")", "{", "mb", ".", "writeUInt8", "(", "lenbytes", "[", "i", "]", ",", "extra", "+", "i", ")", "}", "buffer", ".", "copy", "(", "mb", ",", "lenbytes", ".", "length", "+", "extra", ",", "0", ",", "blen", ")", "return", "mb", "}" ]
Encode a buffer with a varint prefix containing the buffer's length. @param {Buffer} buffer The buffer to encode @param {int} extra How many extra empty leading bytes to put in the buffer @return {Buffer} An encoded buffer longer than before.
[ "Encode", "a", "buffer", "with", "a", "varint", "prefix", "containing", "the", "buffer", "s", "length", "." ]
ededac93ab213c743b2ee81623532bee9b0d5195
https://github.com/brycebaril/multibuffer/blob/ededac93ab213c743b2ee81623532bee9b0d5195/index.js#L16-L26
train
brycebaril/multibuffer
index.js
pack
function pack(buffs, extra) { var lengths = [], lenbytes = [], len = buffs.length, extra = extra || 0, sum = 0, offset = 0, mb, i for (i = 0; i < len; i++) { lengths.push(buffs[i].length) lenbytes.push(vencode(lengths[i])) sum += lengths[i] + lenbytes[i].length + extra } mb = new Buffer(sum) for (i = 0; i < len; i++) { for (var j = 0; j < lenbytes[i].length; j++) { mb.writeUInt8(lenbytes[i][j], offset + extra) offset = offset + 1 + extra } buffs[i].copy(mb, offset, 0, lengths[i]) offset += lengths[i] } return mb }
javascript
function pack(buffs, extra) { var lengths = [], lenbytes = [], len = buffs.length, extra = extra || 0, sum = 0, offset = 0, mb, i for (i = 0; i < len; i++) { lengths.push(buffs[i].length) lenbytes.push(vencode(lengths[i])) sum += lengths[i] + lenbytes[i].length + extra } mb = new Buffer(sum) for (i = 0; i < len; i++) { for (var j = 0; j < lenbytes[i].length; j++) { mb.writeUInt8(lenbytes[i][j], offset + extra) offset = offset + 1 + extra } buffs[i].copy(mb, offset, 0, lengths[i]) offset += lengths[i] } return mb }
[ "function", "pack", "(", "buffs", ",", "extra", ")", "{", "var", "lengths", "=", "[", "]", ",", "lenbytes", "=", "[", "]", ",", "len", "=", "buffs", ".", "length", ",", "extra", "=", "extra", "||", "0", ",", "sum", "=", "0", ",", "offset", "=", "0", ",", "mb", ",", "i", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "lengths", ".", "push", "(", "buffs", "[", "i", "]", ".", "length", ")", "lenbytes", ".", "push", "(", "vencode", "(", "lengths", "[", "i", "]", ")", ")", "sum", "+=", "lengths", "[", "i", "]", "+", "lenbytes", "[", "i", "]", ".", "length", "+", "extra", "}", "mb", "=", "new", "Buffer", "(", "sum", ")", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "lenbytes", "[", "i", "]", ".", "length", ";", "j", "++", ")", "{", "mb", ".", "writeUInt8", "(", "lenbytes", "[", "i", "]", "[", "j", "]", ",", "offset", "+", "extra", ")", "offset", "=", "offset", "+", "1", "+", "extra", "}", "buffs", "[", "i", "]", ".", "copy", "(", "mb", ",", "offset", ",", "0", ",", "lengths", "[", "i", "]", ")", "offset", "+=", "lengths", "[", "i", "]", "}", "return", "mb", "}" ]
Combine an array of buffers into a single buffer encoded such that they can all be extracted again. @param {Array[Buffer]} buffs An array of Buffers @param {int} extra How many extra empty leading bytes to put in each buffer @return {Buffer} A single buffer that is an encoded concatentation of buffs
[ "Combine", "an", "array", "of", "buffers", "into", "a", "single", "buffer", "encoded", "such", "that", "they", "can", "all", "be", "extracted", "again", "." ]
ededac93ab213c743b2ee81623532bee9b0d5195
https://github.com/brycebaril/multibuffer/blob/ededac93ab213c743b2ee81623532bee9b0d5195/index.js#L34-L60
train
brycebaril/multibuffer
index.js
unpack
function unpack(multibuffer) { var buffs = [] var offset = 0 var length while (offset < multibuffer.length) { length = vdecode(multibuffer.slice(offset)) offset += vdecode.bytes buffs.push(multibuffer.slice(offset, offset + length)) offset += length } return buffs }
javascript
function unpack(multibuffer) { var buffs = [] var offset = 0 var length while (offset < multibuffer.length) { length = vdecode(multibuffer.slice(offset)) offset += vdecode.bytes buffs.push(multibuffer.slice(offset, offset + length)) offset += length } return buffs }
[ "function", "unpack", "(", "multibuffer", ")", "{", "var", "buffs", "=", "[", "]", "var", "offset", "=", "0", "var", "length", "while", "(", "offset", "<", "multibuffer", ".", "length", ")", "{", "length", "=", "vdecode", "(", "multibuffer", ".", "slice", "(", "offset", ")", ")", "offset", "+=", "vdecode", ".", "bytes", "buffs", ".", "push", "(", "multibuffer", ".", "slice", "(", "offset", ",", "offset", "+", "length", ")", ")", "offset", "+=", "length", "}", "return", "buffs", "}" ]
Split an encoded multibuffer into the original buffers @param {Buffer} multibuffer An encoded multibuffer @return {Array[Buffer]} The encoded Buffers
[ "Split", "an", "encoded", "multibuffer", "into", "the", "original", "buffers" ]
ededac93ab213c743b2ee81623532bee9b0d5195
https://github.com/brycebaril/multibuffer/blob/ededac93ab213c743b2ee81623532bee9b0d5195/index.js#L67-L80
train
brycebaril/multibuffer
index.js
readPartial
function readPartial(multibuffer) { var dataLength = vdecode(multibuffer) var read = vdecode.bytes if (multibuffer.length < read + dataLength) return [null, multibuffer] var first = multibuffer.slice(read, read + dataLength) var rest = multibuffer.slice(read + dataLength) if (rest.length === 0) rest = null return [first, rest] }
javascript
function readPartial(multibuffer) { var dataLength = vdecode(multibuffer) var read = vdecode.bytes if (multibuffer.length < read + dataLength) return [null, multibuffer] var first = multibuffer.slice(read, read + dataLength) var rest = multibuffer.slice(read + dataLength) if (rest.length === 0) rest = null return [first, rest] }
[ "function", "readPartial", "(", "multibuffer", ")", "{", "var", "dataLength", "=", "vdecode", "(", "multibuffer", ")", "var", "read", "=", "vdecode", ".", "bytes", "if", "(", "multibuffer", ".", "length", "<", "read", "+", "dataLength", ")", "return", "[", "null", ",", "multibuffer", "]", "var", "first", "=", "multibuffer", ".", "slice", "(", "read", ",", "read", "+", "dataLength", ")", "var", "rest", "=", "multibuffer", ".", "slice", "(", "read", "+", "dataLength", ")", "if", "(", "rest", ".", "length", "===", "0", ")", "rest", "=", "null", "return", "[", "first", ",", "rest", "]", "}" ]
Fetch the first encoded buffer from a multibuffer, and the rest of the multibuffer. @param {Buffer} multibuffer An encoded multibuffer. @return {Array} [Buffer, Buffer] where the first buffer is the first encoded buffer, and the second is the rest of the multibuffer.
[ "Fetch", "the", "first", "encoded", "buffer", "from", "a", "multibuffer", "and", "the", "rest", "of", "the", "multibuffer", "." ]
ededac93ab213c743b2ee81623532bee9b0d5195
https://github.com/brycebaril/multibuffer/blob/ededac93ab213c743b2ee81623532bee9b0d5195/index.js#L87-L95
train
stadt-bielefeld/mapfile2js
src/build/determineKeyValueSpaces.js
determineKeyValueSpaces
function determineKeyValueSpaces(obj, tabSize) { let lastDepth = 0; let spacesIndex = 0; let spaces = []; //iterate over all lines obj.forEach((line) => { if (lastDepth !== line.depth) { spacesIndex++; } //key found if (line.key) { //value found if (line.value) { //block line found if (line.isBlockLine) { line.keyValueSpaces = ' '; } else { if (!spaces[spacesIndex]) { spaces[spacesIndex] = { maxKeyLength: 1 }; } //determine maxKeyLength if (spaces[spacesIndex].maxKeyLength < line.key.length) { if (spaces[spacesIndex].maxKeyLength < line.key.length) { spaces[spacesIndex].maxKeyLength = line.key.length; } } } } } lastDepth = line.depth; }); // reset the counters lastDepth = 0; spacesIndex = 0; //iterate over all lines obj.forEach((line) => { if (lastDepth !== line.depth) { spacesIndex++; } //key found if (line.key) { //value found if (line.value) { //block line found if (!line.isBlockLine) { if(spaces[spacesIndex]){ let numSpaces = spaces[spacesIndex].maxKeyLength - line.key.length + tabSize; line.keyValueSpaces = ''; for (let i = 0; i < numSpaces; i++) { line.keyValueSpaces += ' '; } } } } } lastDepth = line.depth; }); console.log(obj); return obj; }
javascript
function determineKeyValueSpaces(obj, tabSize) { let lastDepth = 0; let spacesIndex = 0; let spaces = []; //iterate over all lines obj.forEach((line) => { if (lastDepth !== line.depth) { spacesIndex++; } //key found if (line.key) { //value found if (line.value) { //block line found if (line.isBlockLine) { line.keyValueSpaces = ' '; } else { if (!spaces[spacesIndex]) { spaces[spacesIndex] = { maxKeyLength: 1 }; } //determine maxKeyLength if (spaces[spacesIndex].maxKeyLength < line.key.length) { if (spaces[spacesIndex].maxKeyLength < line.key.length) { spaces[spacesIndex].maxKeyLength = line.key.length; } } } } } lastDepth = line.depth; }); // reset the counters lastDepth = 0; spacesIndex = 0; //iterate over all lines obj.forEach((line) => { if (lastDepth !== line.depth) { spacesIndex++; } //key found if (line.key) { //value found if (line.value) { //block line found if (!line.isBlockLine) { if(spaces[spacesIndex]){ let numSpaces = spaces[spacesIndex].maxKeyLength - line.key.length + tabSize; line.keyValueSpaces = ''; for (let i = 0; i < numSpaces; i++) { line.keyValueSpaces += ' '; } } } } } lastDepth = line.depth; }); console.log(obj); return obj; }
[ "function", "determineKeyValueSpaces", "(", "obj", ",", "tabSize", ")", "{", "let", "lastDepth", "=", "0", ";", "let", "spacesIndex", "=", "0", ";", "let", "spaces", "=", "[", "]", ";", "obj", ".", "forEach", "(", "(", "line", ")", "=>", "{", "if", "(", "lastDepth", "!==", "line", ".", "depth", ")", "{", "spacesIndex", "++", ";", "}", "if", "(", "line", ".", "key", ")", "{", "if", "(", "line", ".", "value", ")", "{", "if", "(", "line", ".", "isBlockLine", ")", "{", "line", ".", "keyValueSpaces", "=", "' '", ";", "}", "else", "{", "if", "(", "!", "spaces", "[", "spacesIndex", "]", ")", "{", "spaces", "[", "spacesIndex", "]", "=", "{", "maxKeyLength", ":", "1", "}", ";", "}", "if", "(", "spaces", "[", "spacesIndex", "]", ".", "maxKeyLength", "<", "line", ".", "key", ".", "length", ")", "{", "if", "(", "spaces", "[", "spacesIndex", "]", ".", "maxKeyLength", "<", "line", ".", "key", ".", "length", ")", "{", "spaces", "[", "spacesIndex", "]", ".", "maxKeyLength", "=", "line", ".", "key", ".", "length", ";", "}", "}", "}", "}", "}", "lastDepth", "=", "line", ".", "depth", ";", "}", ")", ";", "lastDepth", "=", "0", ";", "spacesIndex", "=", "0", ";", "obj", ".", "forEach", "(", "(", "line", ")", "=>", "{", "if", "(", "lastDepth", "!==", "line", ".", "depth", ")", "{", "spacesIndex", "++", ";", "}", "if", "(", "line", ".", "key", ")", "{", "if", "(", "line", ".", "value", ")", "{", "if", "(", "!", "line", ".", "isBlockLine", ")", "{", "if", "(", "spaces", "[", "spacesIndex", "]", ")", "{", "let", "numSpaces", "=", "spaces", "[", "spacesIndex", "]", ".", "maxKeyLength", "-", "line", ".", "key", ".", "length", "+", "tabSize", ";", "line", ".", "keyValueSpaces", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "numSpaces", ";", "i", "++", ")", "{", "line", ".", "keyValueSpaces", "+=", "' '", ";", "}", "}", "}", "}", "}", "lastDepth", "=", "line", ".", "depth", ";", "}", ")", ";", "console", ".", "log", "(", "obj", ")", ";", "return", "obj", ";", "}" ]
Determines the spaces between key and value @param {array} obj Array of line objects @param {number} tabSize Tab size in spaces
[ "Determines", "the", "spaces", "between", "key", "and", "value" ]
08497189503e8823d1c9f26b74ce4ad1025e59dd
https://github.com/stadt-bielefeld/mapfile2js/blob/08497189503e8823d1c9f26b74ce4ad1025e59dd/src/build/determineKeyValueSpaces.js#L7-L88
train
Floobits/dmp
lib/dmp.js
match_bitapScore_
function match_bitapScore_(e, x) { var accuracy = e / pattern.length; var proximity = Math.abs(loc - x); if (!self.Match_Distance) { // Dodge divide by zero error. return proximity ? 1.0 : accuracy; } return accuracy + (proximity / self.Match_Distance); }
javascript
function match_bitapScore_(e, x) { var accuracy = e / pattern.length; var proximity = Math.abs(loc - x); if (!self.Match_Distance) { // Dodge divide by zero error. return proximity ? 1.0 : accuracy; } return accuracy + (proximity / self.Match_Distance); }
[ "function", "match_bitapScore_", "(", "e", ",", "x", ")", "{", "var", "accuracy", "=", "e", "/", "pattern", ".", "length", ";", "var", "proximity", "=", "Math", ".", "abs", "(", "loc", "-", "x", ")", ";", "if", "(", "!", "self", ".", "Match_Distance", ")", "{", "return", "proximity", "?", "1.0", ":", "accuracy", ";", "}", "return", "accuracy", "+", "(", "proximity", "/", "self", ".", "Match_Distance", ")", ";", "}" ]
'this' becomes 'window' in a closure. Compute and return the score for a match with e errors and x location. Accesses loc and pattern through being a closure. @param {number} e Number of errors in match. @param {number} x Location of match. @return {number} Overall score for match (0.0 = good, 1.0 = bad). @private
[ "this", "becomes", "window", "in", "a", "closure", ".", "Compute", "and", "return", "the", "score", "for", "a", "match", "with", "e", "errors", "and", "x", "location", ".", "Accesses", "loc", "and", "pattern", "through", "being", "a", "closure", "." ]
8da90ab40e64d193802097c22506dd31f300d9c2
https://github.com/Floobits/dmp/blob/8da90ab40e64d193802097c22506dd31f300d9c2/lib/dmp.js#L1456-L1464
train
jschaefer-io/tasap
index.js
TpBuilderProcess
function TpBuilderProcess(str, options){ let init = str; if (typeof str === 'object') { init = init.map((item) => '{{@ ' + item + ' }}').join('\n'); } return new TpBuilder(init, options).parse(); }
javascript
function TpBuilderProcess(str, options){ let init = str; if (typeof str === 'object') { init = init.map((item) => '{{@ ' + item + ' }}').join('\n'); } return new TpBuilder(init, options).parse(); }
[ "function", "TpBuilderProcess", "(", "str", ",", "options", ")", "{", "let", "init", "=", "str", ";", "if", "(", "typeof", "str", "===", "'object'", ")", "{", "init", "=", "init", ".", "map", "(", "(", "item", ")", "=>", "'{{@ '", "+", "item", "+", "' }}'", ")", ".", "join", "(", "'\\n'", ")", ";", "}", "\\n", "}" ]
Main Process starting process @param {string|object} str content @param {array} options options array for tasap @returns TpBuilder
[ "Main", "Process", "starting", "process" ]
ba4982fcf36fd293aab8281c2291fa62de8a2f23
https://github.com/jschaefer-io/tasap/blob/ba4982fcf36fd293aab8281c2291fa62de8a2f23/index.js#L13-L19
train
Node-Ops/node-apt-get
index.js
function(options) { options = options || {}; var optionsArray = []; // Go through the available options, // set either the passed option // or the default for (var i in apt.options) { if (typeof options[i] !== 'undefined') { addOption(optionsArray, i, options[i]); } else { addOption(optionsArray, i, apt.options[i]); } } return optionsArray; }
javascript
function(options) { options = options || {}; var optionsArray = []; // Go through the available options, // set either the passed option // or the default for (var i in apt.options) { if (typeof options[i] !== 'undefined') { addOption(optionsArray, i, options[i]); } else { addOption(optionsArray, i, apt.options[i]); } } return optionsArray; }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "optionsArray", "=", "[", "]", ";", "for", "(", "var", "i", "in", "apt", ".", "options", ")", "{", "if", "(", "typeof", "options", "[", "i", "]", "!==", "'undefined'", ")", "{", "addOption", "(", "optionsArray", ",", "i", ",", "options", "[", "i", "]", ")", ";", "}", "else", "{", "addOption", "(", "optionsArray", ",", "i", ",", "apt", ".", "options", "[", "i", "]", ")", ";", "}", "}", "return", "optionsArray", ";", "}" ]
Parses the options adding them to an options array which is returned
[ "Parses", "the", "options", "adding", "them", "to", "an", "options", "array", "which", "is", "returned" ]
db5bb8b763dd6f71f1356eadc5875aaf4a215875
https://github.com/Node-Ops/node-apt-get/blob/db5bb8b763dd6f71f1356eadc5875aaf4a215875/index.js#L54-L70
train
Node-Ops/node-apt-get
index.js
function(optsArr, name, value) { switch(typeof value) { case 'boolean': if (value) optsArr.push('--' + name); break; case 'string': optsArr.push('--' + name); optsArr.push(value); break; case 'function': optsArr.push(value()); break; }; }
javascript
function(optsArr, name, value) { switch(typeof value) { case 'boolean': if (value) optsArr.push('--' + name); break; case 'string': optsArr.push('--' + name); optsArr.push(value); break; case 'function': optsArr.push(value()); break; }; }
[ "function", "(", "optsArr", ",", "name", ",", "value", ")", "{", "switch", "(", "typeof", "value", ")", "{", "case", "'boolean'", ":", "if", "(", "value", ")", "optsArr", ".", "push", "(", "'--'", "+", "name", ")", ";", "break", ";", "case", "'string'", ":", "optsArr", ".", "push", "(", "'--'", "+", "name", ")", ";", "optsArr", ".", "push", "(", "value", ")", ";", "break", ";", "case", "'function'", ":", "optsArr", ".", "push", "(", "value", "(", ")", ")", ";", "break", ";", "}", ";", "}" ]
Adds to the options array based on the type of argument provided
[ "Adds", "to", "the", "options", "array", "based", "on", "the", "type", "of", "argument", "provided" ]
db5bb8b763dd6f71f1356eadc5875aaf4a215875
https://github.com/Node-Ops/node-apt-get/blob/db5bb8b763dd6f71f1356eadc5875aaf4a215875/index.js#L74-L87
train
Node-Ops/node-apt-get
index.js
function(command, options) { options = options || []; options.unshift(command); return childProcess.spawn(apt.command, options, apt.spawnOptions); }
javascript
function(command, options) { options = options || []; options.unshift(command); return childProcess.spawn(apt.command, options, apt.spawnOptions); }
[ "function", "(", "command", ",", "options", ")", "{", "options", "=", "options", "||", "[", "]", ";", "options", ".", "unshift", "(", "command", ")", ";", "return", "childProcess", ".", "spawn", "(", "apt", ".", "command", ",", "options", ",", "apt", ".", "spawnOptions", ")", ";", "}" ]
A spawn helper to spawn apt-get commands
[ "A", "spawn", "helper", "to", "spawn", "apt", "-", "get", "commands" ]
db5bb8b763dd6f71f1356eadc5875aaf4a215875
https://github.com/Node-Ops/node-apt-get/blob/db5bb8b763dd6f71f1356eadc5875aaf4a215875/index.js#L90-L94
train
Mapita/Canary
dist/src/util.js
getOrdinal
function getOrdinal(value) { const lastDigit = value % 10; if (lastDigit === 1) { return `${value}st`; } else if (lastDigit === 2) { return `${value}nd`; } else if (lastDigit === 3) { return `${value}rd`; } else { return `${value}th`; } }
javascript
function getOrdinal(value) { const lastDigit = value % 10; if (lastDigit === 1) { return `${value}st`; } else if (lastDigit === 2) { return `${value}nd`; } else if (lastDigit === 3) { return `${value}rd`; } else { return `${value}th`; } }
[ "function", "getOrdinal", "(", "value", ")", "{", "const", "lastDigit", "=", "value", "%", "10", ";", "if", "(", "lastDigit", "===", "1", ")", "{", "return", "`", "${", "value", "}", "`", ";", "}", "else", "if", "(", "lastDigit", "===", "2", ")", "{", "return", "`", "${", "value", "}", "`", ";", "}", "else", "if", "(", "lastDigit", "===", "3", ")", "{", "return", "`", "${", "value", "}", "`", ";", "}", "else", "{", "return", "`", "${", "value", "}", "`", ";", "}", "}" ]
Helper function to get an ordinal string like "1st", "2nd", "3rd"... Expects the input to be an integer. This is used to produce helpful names for tests and callbacks that weren't assigned more descriptive names by their developer.
[ "Helper", "function", "to", "get", "an", "ordinal", "string", "like", "1st", "2nd", "3rd", "...", "Expects", "the", "input", "to", "be", "an", "integer", ".", "This", "is", "used", "to", "produce", "helpful", "names", "for", "tests", "and", "callbacks", "that", "weren", "t", "assigned", "more", "descriptive", "names", "by", "their", "developer", "." ]
c12c97afc741ac3cbc4727cd28566efbcaf066d9
https://github.com/Mapita/Canary/blob/c12c97afc741ac3cbc4727cd28566efbcaf066d9/dist/src/util.js#L21-L35
train
Mapita/Canary
dist/src/util.js
getCallerLocation
function getCallerLocation() { const error = new Error(); if (error.stack) { const lines = error.stack.split("\n"); for (let i = 2; i < lines.length; i++) { if (i > 0 && lines[i] === " at <anonymous>") { const paren = lines[i - 1].indexOf("("); if (paren >= 0) { return lines[i - 1].slice(paren + 1, lines[i - 1].length - 1); } else { return ""; } } else if (!lines[i].startsWith(" at CanaryTest.") && !lines[i].startsWith(" at new CanaryTest")) { const paren = lines[i].indexOf("("); if (paren >= 0) { return lines[i].slice(paren + 1, lines[i].length - 1); } else { return lines[i].slice(7, lines[i].length); } } } } return ""; }
javascript
function getCallerLocation() { const error = new Error(); if (error.stack) { const lines = error.stack.split("\n"); for (let i = 2; i < lines.length; i++) { if (i > 0 && lines[i] === " at <anonymous>") { const paren = lines[i - 1].indexOf("("); if (paren >= 0) { return lines[i - 1].slice(paren + 1, lines[i - 1].length - 1); } else { return ""; } } else if (!lines[i].startsWith(" at CanaryTest.") && !lines[i].startsWith(" at new CanaryTest")) { const paren = lines[i].indexOf("("); if (paren >= 0) { return lines[i].slice(paren + 1, lines[i].length - 1); } else { return lines[i].slice(7, lines[i].length); } } } } return ""; }
[ "function", "getCallerLocation", "(", ")", "{", "const", "error", "=", "new", "Error", "(", ")", ";", "if", "(", "error", ".", "stack", ")", "{", "const", "lines", "=", "error", ".", "stack", ".", "split", "(", "\"\\n\"", ")", ";", "\\n", "}", "for", "(", "let", "i", "=", "2", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", ">", "0", "&&", "lines", "[", "i", "]", "===", "\" at <anonymous>\"", ")", "{", "const", "paren", "=", "lines", "[", "i", "-", "1", "]", ".", "indexOf", "(", "\"(\"", ")", ";", "if", "(", "paren", ">=", "0", ")", "{", "return", "lines", "[", "i", "-", "1", "]", ".", "slice", "(", "paren", "+", "1", ",", "lines", "[", "i", "-", "1", "]", ".", "length", "-", "1", ")", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}", "else", "if", "(", "!", "lines", "[", "i", "]", ".", "startsWith", "(", "\" at CanaryTest.\"", ")", "&&", "!", "lines", "[", "i", "]", ".", "startsWith", "(", "\" at new CanaryTest\"", ")", ")", "{", "const", "paren", "=", "lines", "[", "i", "]", ".", "indexOf", "(", "\"(\"", ")", ";", "if", "(", "paren", ">=", "0", ")", "{", "return", "lines", "[", "i", "]", ".", "slice", "(", "paren", "+", "1", ",", "lines", "[", "i", "]", ".", "length", "-", "1", ")", ";", "}", "else", "{", "return", "lines", "[", "i", "]", ".", "slice", "(", "7", ",", "lines", "[", "i", "]", ".", "length", ")", ";", "}", "}", "}", "}" ]
Helper function to get the path to the file where a test was defined.
[ "Helper", "function", "to", "get", "the", "path", "to", "the", "file", "where", "a", "test", "was", "defined", "." ]
c12c97afc741ac3cbc4727cd28566efbcaf066d9
https://github.com/Mapita/Canary/blob/c12c97afc741ac3cbc4727cd28566efbcaf066d9/dist/src/util.js#L38-L65
train
Mapita/Canary
dist/src/util.js
normalizePath
function normalizePath(path) { // Separate the path into parts (delimited by slashes) let parts = [""]; for (let char of path) { if (char === "/" || char === "\\") { if (parts[parts.length - 1].length) { parts.push(""); } } else { parts[parts.length - 1] += char; } } // Special case for when the entire path was "." if (parts.length === 1 && parts[0] === ".") { return "."; } // Resolve "." and ".." let i = 0; while (i < parts.length) { if (parts[i] === ".") { parts.splice(i, 1); } else if (i > 0 && parts[i] === "..") { parts.splice(i - 1, 2); i--; } else { i++; } } // Build the resulting path let result = ""; for (let part of parts) { if (part && part.length) { if (result.length) { result += "/"; } result += part; } } // Retain a slash at the beginning of the string if (path[0] === "/" || path[0] === "\\") { result = "/" + result; } // All done! return result; }
javascript
function normalizePath(path) { // Separate the path into parts (delimited by slashes) let parts = [""]; for (let char of path) { if (char === "/" || char === "\\") { if (parts[parts.length - 1].length) { parts.push(""); } } else { parts[parts.length - 1] += char; } } // Special case for when the entire path was "." if (parts.length === 1 && parts[0] === ".") { return "."; } // Resolve "." and ".." let i = 0; while (i < parts.length) { if (parts[i] === ".") { parts.splice(i, 1); } else if (i > 0 && parts[i] === "..") { parts.splice(i - 1, 2); i--; } else { i++; } } // Build the resulting path let result = ""; for (let part of parts) { if (part && part.length) { if (result.length) { result += "/"; } result += part; } } // Retain a slash at the beginning of the string if (path[0] === "/" || path[0] === "\\") { result = "/" + result; } // All done! return result; }
[ "function", "normalizePath", "(", "path", ")", "{", "let", "parts", "=", "[", "\"\"", "]", ";", "for", "(", "let", "char", "of", "path", ")", "{", "if", "(", "char", "===", "\"/\"", "||", "char", "===", "\"\\\\\"", ")", "\\\\", "else", "{", "if", "(", "parts", "[", "parts", ".", "length", "-", "1", "]", ".", "length", ")", "{", "parts", ".", "push", "(", "\"\"", ")", ";", "}", "}", "}", "{", "parts", "[", "parts", ".", "length", "-", "1", "]", "+=", "char", ";", "}", "if", "(", "parts", ".", "length", "===", "1", "&&", "parts", "[", "0", "]", "===", "\".\"", ")", "{", "return", "\".\"", ";", "}", "let", "i", "=", "0", ";", "while", "(", "i", "<", "parts", ".", "length", ")", "{", "if", "(", "parts", "[", "i", "]", "===", "\".\"", ")", "{", "parts", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "else", "if", "(", "i", ">", "0", "&&", "parts", "[", "i", "]", "===", "\"..\"", ")", "{", "parts", ".", "splice", "(", "i", "-", "1", ",", "2", ")", ";", "i", "--", ";", "}", "else", "{", "i", "++", ";", "}", "}", "let", "result", "=", "\"\"", ";", "for", "(", "let", "part", "of", "parts", ")", "{", "if", "(", "part", "&&", "part", ".", "length", ")", "{", "if", "(", "result", ".", "length", ")", "{", "result", "+=", "\"/\"", ";", "}", "result", "+=", "part", ";", "}", "}", "if", "(", "path", "[", "0", "]", "===", "\"/\"", "||", "path", "[", "0", "]", "===", "\"\\\\\"", ")", "\\\\", "}" ]
Helper function to normalize a file path for comparison. Makes all slashes forward slashes, removes trailing and redundant slashes, and resolves "." and "..".
[ "Helper", "function", "to", "normalize", "a", "file", "path", "for", "comparison", ".", "Makes", "all", "slashes", "forward", "slashes", "removes", "trailing", "and", "redundant", "slashes", "and", "resolves", ".", "and", "..", "." ]
c12c97afc741ac3cbc4727cd28566efbcaf066d9
https://github.com/Mapita/Canary/blob/c12c97afc741ac3cbc4727cd28566efbcaf066d9/dist/src/util.js#L70-L117
train
strugee/node-smart-spawn
index.js
maybeFireCallback
function maybeFireCallback() { // This function is called in any place where we might have completed a task that allows us to fire if (callbackFired) return; // If everything is ready, we *should* fire the callback, and it hasn't already been fired, then do so if (stdoutReady && stderrReady && wantCallback && !callbackFired) { callbackFired = true; callback(callbackErr, stdout); } }
javascript
function maybeFireCallback() { // This function is called in any place where we might have completed a task that allows us to fire if (callbackFired) return; // If everything is ready, we *should* fire the callback, and it hasn't already been fired, then do so if (stdoutReady && stderrReady && wantCallback && !callbackFired) { callbackFired = true; callback(callbackErr, stdout); } }
[ "function", "maybeFireCallback", "(", ")", "{", "if", "(", "callbackFired", ")", "return", ";", "if", "(", "stdoutReady", "&&", "stderrReady", "&&", "wantCallback", "&&", "!", "callbackFired", ")", "{", "callbackFired", "=", "true", ";", "callback", "(", "callbackErr", ",", "stdout", ")", ";", "}", "}" ]
Done here so it gets the right scope
[ "Done", "here", "so", "it", "gets", "the", "right", "scope" ]
b57710af42af8a48085756897683b9e175bb8324
https://github.com/strugee/node-smart-spawn/blob/b57710af42af8a48085756897683b9e175bb8324/index.js#L33-L43
train
PAI-Tech/PAI-BOT-JS
src/pai-bot/src/modules/bot-base-modules.js
loadModulesConfig
async function loadModulesConfig() { if(!modulesLoaded) { for (let i = 0; i < modules.length; i++) { await applyBotDataSource(modules[i]); } modulesLoaded = true; } }
javascript
async function loadModulesConfig() { if(!modulesLoaded) { for (let i = 0; i < modules.length; i++) { await applyBotDataSource(modules[i]); } modulesLoaded = true; } }
[ "async", "function", "loadModulesConfig", "(", ")", "{", "if", "(", "!", "modulesLoaded", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "modules", ".", "length", ";", "i", "++", ")", "{", "await", "applyBotDataSource", "(", "modules", "[", "i", "]", ")", ";", "}", "modulesLoaded", "=", "true", ";", "}", "}" ]
Load configuration for every module @return {Promise<void>}
[ "Load", "configuration", "for", "every", "module" ]
7744e54f580e18264861e33f2c05aac58b5ad1d9
https://github.com/PAI-Tech/PAI-BOT-JS/blob/7744e54f580e18264861e33f2c05aac58b5ad1d9/src/pai-bot/src/modules/bot-base-modules.js#L29-L39
train
fergiemcdowall/search-index-deleter
deleter.js
function (options, callback) { var Deleter = {} // Delete all docs with the IDs found in deleteBatch Deleter.deleteBatch = function (deleteBatch, APICallback) { tryDeleteBatch(options, deleteBatch, function (err) { return APICallback(err) }) } // Flush the db (delete all entries) Deleter.flush = function (APICallback) { flush(options, function (err) { return APICallback(err) }) } return callback(null, Deleter) }
javascript
function (options, callback) { var Deleter = {} // Delete all docs with the IDs found in deleteBatch Deleter.deleteBatch = function (deleteBatch, APICallback) { tryDeleteBatch(options, deleteBatch, function (err) { return APICallback(err) }) } // Flush the db (delete all entries) Deleter.flush = function (APICallback) { flush(options, function (err) { return APICallback(err) }) } return callback(null, Deleter) }
[ "function", "(", "options", ",", "callback", ")", "{", "var", "Deleter", "=", "{", "}", "Deleter", ".", "deleteBatch", "=", "function", "(", "deleteBatch", ",", "APICallback", ")", "{", "tryDeleteBatch", "(", "options", ",", "deleteBatch", ",", "function", "(", "err", ")", "{", "return", "APICallback", "(", "err", ")", "}", ")", "}", "Deleter", ".", "flush", "=", "function", "(", "APICallback", ")", "{", "flush", "(", "options", ",", "function", "(", "err", ")", "{", "return", "APICallback", "(", "err", ")", "}", ")", "}", "return", "callback", "(", "null", ",", "Deleter", ")", "}" ]
Define API calls
[ "Define", "API", "calls" ]
a1e5c3d9b3e4202fb71ba479203cdb505990ed59
https://github.com/fergiemcdowall/search-index-deleter/blob/a1e5c3d9b3e4202fb71ba479203cdb505990ed59/deleter.js#L33-L48
train
thirdcoder/balanced-ternary
bt.js
bts2n
function bts2n(s) { var n = 0; for (var i = 0; i < s.length; ++i) { var ch = s.charAt(i); var digit = BT_DIGIT_TO_N[ch]; if (digit === undefined) throw new Error('bts2n('+s+'): invalid digit character: '+ch); //console.log(i,digit,3**i,n,s,ch); n += pow3(s.length - i - 1) * digit; } return n; }
javascript
function bts2n(s) { var n = 0; for (var i = 0; i < s.length; ++i) { var ch = s.charAt(i); var digit = BT_DIGIT_TO_N[ch]; if (digit === undefined) throw new Error('bts2n('+s+'): invalid digit character: '+ch); //console.log(i,digit,3**i,n,s,ch); n += pow3(s.length - i - 1) * digit; } return n; }
[ "function", "bts2n", "(", "s", ")", "{", "var", "n", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "s", ".", "length", ";", "++", "i", ")", "{", "var", "ch", "=", "s", ".", "charAt", "(", "i", ")", ";", "var", "digit", "=", "BT_DIGIT_TO_N", "[", "ch", "]", ";", "if", "(", "digit", "===", "undefined", ")", "throw", "new", "Error", "(", "'bts2n('", "+", "s", "+", "'): invalid digit character: '", "+", "ch", ")", ";", "n", "+=", "pow3", "(", "s", ".", "length", "-", "i", "-", "1", ")", "*", "digit", ";", "}", "return", "n", ";", "}" ]
parse balanced ternary string to signed integer
[ "parse", "balanced", "ternary", "string", "to", "signed", "integer" ]
79be6619cc68c161171925b34c3a820d39f4b1e9
https://github.com/thirdcoder/balanced-ternary/blob/79be6619cc68c161171925b34c3a820d39f4b1e9/bt.js#L24-L34
train
thirdcoder/balanced-ternary
bt.js
n2bts
function n2bts(n_) { var neg = n_ < 0; var n = Math.abs(n_); var s = ''; do { var digit = n % 3; // balance the ternary http://stackoverflow.com/questions/26456597/how-to-convert-from-unbalanced-to-balanced-ternary if (digit === 2) { digit = -1; ++n; } //console.log('digit',digit,n,n_,s); // if number has negative sign, flip all digits if (neg) { digit = -digit; } s = N_TO_BT_DIGIT[digit] + s; n = ~~(n / 3); // truncate, not floor! negatives } while(n); //console.log('n2bts',n_,s); return s; }
javascript
function n2bts(n_) { var neg = n_ < 0; var n = Math.abs(n_); var s = ''; do { var digit = n % 3; // balance the ternary http://stackoverflow.com/questions/26456597/how-to-convert-from-unbalanced-to-balanced-ternary if (digit === 2) { digit = -1; ++n; } //console.log('digit',digit,n,n_,s); // if number has negative sign, flip all digits if (neg) { digit = -digit; } s = N_TO_BT_DIGIT[digit] + s; n = ~~(n / 3); // truncate, not floor! negatives } while(n); //console.log('n2bts',n_,s); return s; }
[ "function", "n2bts", "(", "n_", ")", "{", "var", "neg", "=", "n_", "<", "0", ";", "var", "n", "=", "Math", ".", "abs", "(", "n_", ")", ";", "var", "s", "=", "''", ";", "do", "{", "var", "digit", "=", "n", "%", "3", ";", "if", "(", "digit", "===", "2", ")", "{", "digit", "=", "-", "1", ";", "++", "n", ";", "}", "if", "(", "neg", ")", "{", "digit", "=", "-", "digit", ";", "}", "s", "=", "N_TO_BT_DIGIT", "[", "digit", "]", "+", "s", ";", "n", "=", "~", "~", "(", "n", "/", "3", ")", ";", "}", "while", "(", "n", ")", ";", "return", "s", ";", "}" ]
signed integer to balanced ternary string
[ "signed", "integer", "to", "balanced", "ternary", "string" ]
79be6619cc68c161171925b34c3a820d39f4b1e9
https://github.com/thirdcoder/balanced-ternary/blob/79be6619cc68c161171925b34c3a820d39f4b1e9/bt.js#L38-L64
train
kevoree/kevoree-js
libraries/group/ws/lib/Protocol.js
startsWith
function startsWith(src, target) { if (target && target.length > 0) { return (src.substr(0, target.length) === target); } else { return false; } }
javascript
function startsWith(src, target) { if (target && target.length > 0) { return (src.substr(0, target.length) === target); } else { return false; } }
[ "function", "startsWith", "(", "src", ",", "target", ")", "{", "if", "(", "target", "&&", "target", ".", "length", ">", "0", ")", "{", "return", "(", "src", ".", "substr", "(", "0", ",", "target", ".", "length", ")", "===", "target", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Checks whether or not 'src' string starts with 'target' string @param {String} src source string to look into @param {String} target string to find at the beginning @returns {boolean} true if 'src' has 'target' at his beginning
[ "Checks", "whether", "or", "not", "src", "string", "starts", "with", "target", "string" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/libraries/group/ws/lib/Protocol.js#L26-L32
train
mreinstein/substrate-build
index.js
resolveScriptPaths
function resolveScriptPaths (filePath, m) { const toParse = [ m ] const lookup = {} // key is module name, value is path while (toParse.length) { let node = toParse.pop() if (node.children) for (let n of node.children) toParse.push(n) if (!node.scripts) continue for (let entry of node.scripts) { let moduleName = camelcase(path.parse(entry.source).name) lookup[moduleName] = entry.source entry.module = moduleName } } return lookup }
javascript
function resolveScriptPaths (filePath, m) { const toParse = [ m ] const lookup = {} // key is module name, value is path while (toParse.length) { let node = toParse.pop() if (node.children) for (let n of node.children) toParse.push(n) if (!node.scripts) continue for (let entry of node.scripts) { let moduleName = camelcase(path.parse(entry.source).name) lookup[moduleName] = entry.source entry.module = moduleName } } return lookup }
[ "function", "resolveScriptPaths", "(", "filePath", ",", "m", ")", "{", "const", "toParse", "=", "[", "m", "]", "const", "lookup", "=", "{", "}", "while", "(", "toParse", ".", "length", ")", "{", "let", "node", "=", "toParse", ".", "pop", "(", ")", "if", "(", "node", ".", "children", ")", "for", "(", "let", "n", "of", "node", ".", "children", ")", "toParse", ".", "push", "(", "n", ")", "if", "(", "!", "node", ".", "scripts", ")", "continue", "for", "(", "let", "entry", "of", "node", ".", "scripts", ")", "{", "let", "moduleName", "=", "camelcase", "(", "path", ".", "parse", "(", "entry", ".", "source", ")", ".", "name", ")", "lookup", "[", "moduleName", "]", "=", "entry", ".", "source", "entry", ".", "module", "=", "moduleName", "}", "}", "return", "lookup", "}" ]
iterate over a substrate model, resolving all script paths
[ "iterate", "over", "a", "substrate", "model", "resolving", "all", "script", "paths" ]
7cae41956a2926f5dfe8bd496a50a1a5094a59e3
https://github.com/mreinstein/substrate-build/blob/7cae41956a2926f5dfe8bd496a50a1a5094a59e3/index.js#L78-L100
train
mreinstein/substrate-build
index.js
compileModel
async function compileModel (projectPath, model) { await copyExternalScripts(projectPath, model) deInlineScripts(projectPath, model) const lookup = resolveScriptPaths(projectPath, model) let imports = '' for (let moduleName in lookup) { let p = path.isAbsolute(lookup[moduleName]) ? lookup[moduleName] : `./${path.normalize(lookup[moduleName])}` imports += `import ${moduleName} from '${p}'\n` } const pre = JSON.stringify(model, null, 2) let post = pre for (let moduleName in lookup) post = replaceAll(post, moduleName) return `import substrate from 'substrate' // imports generated by the compiler ${imports} const dom = document.createElement('div') dom.id = 'myapp' document.body.appendChild(dom) const model = ${post} const app = substrate({ dom, node: model.rootNode, registry: model.registry })` }
javascript
async function compileModel (projectPath, model) { await copyExternalScripts(projectPath, model) deInlineScripts(projectPath, model) const lookup = resolveScriptPaths(projectPath, model) let imports = '' for (let moduleName in lookup) { let p = path.isAbsolute(lookup[moduleName]) ? lookup[moduleName] : `./${path.normalize(lookup[moduleName])}` imports += `import ${moduleName} from '${p}'\n` } const pre = JSON.stringify(model, null, 2) let post = pre for (let moduleName in lookup) post = replaceAll(post, moduleName) return `import substrate from 'substrate' // imports generated by the compiler ${imports} const dom = document.createElement('div') dom.id = 'myapp' document.body.appendChild(dom) const model = ${post} const app = substrate({ dom, node: model.rootNode, registry: model.registry })` }
[ "async", "function", "compileModel", "(", "projectPath", ",", "model", ")", "{", "await", "copyExternalScripts", "(", "projectPath", ",", "model", ")", "deInlineScripts", "(", "projectPath", ",", "model", ")", "const", "lookup", "=", "resolveScriptPaths", "(", "projectPath", ",", "model", ")", "let", "imports", "=", "''", "for", "(", "let", "moduleName", "in", "lookup", ")", "{", "let", "p", "=", "path", ".", "isAbsolute", "(", "lookup", "[", "moduleName", "]", ")", "?", "lookup", "[", "moduleName", "]", ":", "`", "${", "path", ".", "normalize", "(", "lookup", "[", "moduleName", "]", ")", "}", "`", "imports", "+=", "`", "${", "moduleName", "}", "${", "p", "}", "\\n", "`", "}", "const", "pre", "=", "JSON", ".", "stringify", "(", "model", ",", "null", ",", "2", ")", "let", "post", "=", "pre", "for", "(", "let", "moduleName", "in", "lookup", ")", "post", "=", "replaceAll", "(", "post", ",", "moduleName", ")", "return", "`", "${", "imports", "}", "${", "post", "}", "`", "}" ]
generate a build suitable for bundling by staticly compiling an input json model
[ "generate", "a", "build", "suitable", "for", "bundling", "by", "staticly", "compiling", "an", "input", "json", "model" ]
7cae41956a2926f5dfe8bd496a50a1a5094a59e3
https://github.com/mreinstein/substrate-build/blob/7cae41956a2926f5dfe8bd496a50a1a5094a59e3/index.js#L130-L160
train
bicarbon8/PhantomFunctionalTest
dist/pft-module.js
function () { var s = null; if (PFT.tester._suites.length > 0) { s = PFT.tester._suites[PFT.tester._suites.length - 1]; } return s; }
javascript
function () { var s = null; if (PFT.tester._suites.length > 0) { s = PFT.tester._suites[PFT.tester._suites.length - 1]; } return s; }
[ "function", "(", ")", "{", "var", "s", "=", "null", ";", "if", "(", "PFT", ".", "tester", ".", "_suites", ".", "length", ">", "0", ")", "{", "s", "=", "PFT", ".", "tester", ".", "_suites", "[", "PFT", ".", "tester", ".", "_suites", ".", "length", "-", "1", "]", ";", "}", "return", "s", ";", "}" ]
function will get the current suite in use. this is primarily used for associating a suite with a test
[ "function", "will", "get", "the", "current", "suite", "in", "use", ".", "this", "is", "primarily", "used", "for", "associating", "a", "suite", "with", "a", "test" ]
dcfd01cabac30f05d2c380f06103c81eaf0594f9
https://github.com/bicarbon8/PhantomFunctionalTest/blob/dcfd01cabac30f05d2c380f06103c81eaf0594f9/dist/pft-module.js#L942-L948
train
bicarbon8/PhantomFunctionalTest
dist/pft-module.js
function () { var t = null; if (PFT.tester._tests.length > 0) { t = PFT.tester._tests[PFT.tester._tests.length - 1]; } return t; }
javascript
function () { var t = null; if (PFT.tester._tests.length > 0) { t = PFT.tester._tests[PFT.tester._tests.length - 1]; } return t; }
[ "function", "(", ")", "{", "var", "t", "=", "null", ";", "if", "(", "PFT", ".", "tester", ".", "_tests", ".", "length", ">", "0", ")", "{", "t", "=", "PFT", ".", "tester", ".", "_tests", "[", "PFT", ".", "tester", ".", "_tests", ".", "length", "-", "1", "]", ";", "}", "return", "t", ";", "}" ]
function will get the currently executing test
[ "function", "will", "get", "the", "currently", "executing", "test" ]
dcfd01cabac30f05d2c380f06103c81eaf0594f9
https://github.com/bicarbon8/PhantomFunctionalTest/blob/dcfd01cabac30f05d2c380f06103c81eaf0594f9/dist/pft-module.js#L953-L959
train
bicarbon8/PhantomFunctionalTest
dist/pft-module.js
function (testObj) { var duration = PFT.convertMsToHumanReadable(new Date().getTime() - testObj.startTime); testObj.duration = duration; var suite = ""; if (testObj.suite) { if (testObj.suite.name) { suite = testObj.suite.name + " - "; } } var msg = "Completed: '" + suite + testObj.name + "' in " + duration + " with " + testObj.passes + " passes, " + testObj.failures.length + " failures, " + testObj.errors.length + " errors."; PFT.logger.log(PFT.logger.TEST, msg); PFT.tester.onTestCompleted({ test: testObj }); try { testObj.page.close(); } catch (e) { PFT.warn(e); } PFT.tester.remainingCount--; PFT.tester.exitIfDoneTesting(); }
javascript
function (testObj) { var duration = PFT.convertMsToHumanReadable(new Date().getTime() - testObj.startTime); testObj.duration = duration; var suite = ""; if (testObj.suite) { if (testObj.suite.name) { suite = testObj.suite.name + " - "; } } var msg = "Completed: '" + suite + testObj.name + "' in " + duration + " with " + testObj.passes + " passes, " + testObj.failures.length + " failures, " + testObj.errors.length + " errors."; PFT.logger.log(PFT.logger.TEST, msg); PFT.tester.onTestCompleted({ test: testObj }); try { testObj.page.close(); } catch (e) { PFT.warn(e); } PFT.tester.remainingCount--; PFT.tester.exitIfDoneTesting(); }
[ "function", "(", "testObj", ")", "{", "var", "duration", "=", "PFT", ".", "convertMsToHumanReadable", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "testObj", ".", "startTime", ")", ";", "testObj", ".", "duration", "=", "duration", ";", "var", "suite", "=", "\"\"", ";", "if", "(", "testObj", ".", "suite", ")", "{", "if", "(", "testObj", ".", "suite", ".", "name", ")", "{", "suite", "=", "testObj", ".", "suite", ".", "name", "+", "\" - \"", ";", "}", "}", "var", "msg", "=", "\"Completed: '\"", "+", "suite", "+", "testObj", ".", "name", "+", "\"' in \"", "+", "duration", "+", "\" with \"", "+", "testObj", ".", "passes", "+", "\" passes, \"", "+", "testObj", ".", "failures", ".", "length", "+", "\" failures, \"", "+", "testObj", ".", "errors", ".", "length", "+", "\" errors.\"", ";", "PFT", ".", "logger", ".", "log", "(", "PFT", ".", "logger", ".", "TEST", ",", "msg", ")", ";", "PFT", ".", "tester", ".", "onTestCompleted", "(", "{", "test", ":", "testObj", "}", ")", ";", "try", "{", "testObj", ".", "page", ".", "close", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "PFT", ".", "warn", "(", "e", ")", ";", "}", "PFT", ".", "tester", ".", "remainingCount", "--", ";", "PFT", ".", "tester", ".", "exitIfDoneTesting", "(", ")", ";", "}" ]
function will close out the currently running test objects, but any async tasks will continue running.
[ "function", "will", "close", "out", "the", "currently", "running", "test", "objects", "but", "any", "async", "tasks", "will", "continue", "running", "." ]
dcfd01cabac30f05d2c380f06103c81eaf0594f9
https://github.com/bicarbon8/PhantomFunctionalTest/blob/dcfd01cabac30f05d2c380f06103c81eaf0594f9/dist/pft-module.js#L1059-L1079
train
bicarbon8/PhantomFunctionalTest
dist/pft-module.js
function (msg) { // restart MutexJs in case exception caused fatal javascript halt MutexJs.recover(); // unexpected exception so log in errors and move to next var t = PFT.tester.currentTest(); t.errors.push(msg); PFT.tester.onError({ test: t, message: msg }); PFT.tester.closeTest(t); // move to next test MutexJs.release(t.runUnlockId); }
javascript
function (msg) { // restart MutexJs in case exception caused fatal javascript halt MutexJs.recover(); // unexpected exception so log in errors and move to next var t = PFT.tester.currentTest(); t.errors.push(msg); PFT.tester.onError({ test: t, message: msg }); PFT.tester.closeTest(t); // move to next test MutexJs.release(t.runUnlockId); }
[ "function", "(", "msg", ")", "{", "MutexJs", ".", "recover", "(", ")", ";", "var", "t", "=", "PFT", ".", "tester", ".", "currentTest", "(", ")", ";", "t", ".", "errors", ".", "push", "(", "msg", ")", ";", "PFT", ".", "tester", ".", "onError", "(", "{", "test", ":", "t", ",", "message", ":", "msg", "}", ")", ";", "PFT", ".", "tester", ".", "closeTest", "(", "t", ")", ";", "MutexJs", ".", "release", "(", "t", ".", "runUnlockId", ")", ";", "}" ]
function provides handling for expected exceptions thrown to halt the currently running script. typically this will be called from the phantom.onError function if tests are running. @ignore
[ "function", "provides", "handling", "for", "expected", "exceptions", "thrown", "to", "halt", "the", "currently", "running", "script", ".", "typically", "this", "will", "be", "called", "from", "the", "phantom", ".", "onError", "function", "if", "tests", "are", "running", "." ]
dcfd01cabac30f05d2c380f06103c81eaf0594f9
https://github.com/bicarbon8/PhantomFunctionalTest/blob/dcfd01cabac30f05d2c380f06103c81eaf0594f9/dist/pft-module.js#L1191-L1203
train
unicornjs/unicornjs
core-services/uBroker/index.js
uBrokersManager
function uBrokersManager(){ var listenClient = redis.createClient(config.redis[0].port, config.redis[0].server); listenClient.on("error", function (err) { console.log("Redis listen error " + err); }); listenClient.on('message', function(channel, message) { client.get('uBrokers', function(err, reply) { uBrokers = JSON.parse(reply); }); }); listenClient.subscribe('uBrokersChannel'); }
javascript
function uBrokersManager(){ var listenClient = redis.createClient(config.redis[0].port, config.redis[0].server); listenClient.on("error", function (err) { console.log("Redis listen error " + err); }); listenClient.on('message', function(channel, message) { client.get('uBrokers', function(err, reply) { uBrokers = JSON.parse(reply); }); }); listenClient.subscribe('uBrokersChannel'); }
[ "function", "uBrokersManager", "(", ")", "{", "var", "listenClient", "=", "redis", ".", "createClient", "(", "config", ".", "redis", "[", "0", "]", ".", "port", ",", "config", ".", "redis", "[", "0", "]", ".", "server", ")", ";", "listenClient", ".", "on", "(", "\"error\"", ",", "function", "(", "err", ")", "{", "console", ".", "log", "(", "\"Redis listen error \"", "+", "err", ")", ";", "}", ")", ";", "listenClient", ".", "on", "(", "'message'", ",", "function", "(", "channel", ",", "message", ")", "{", "client", ".", "get", "(", "'uBrokers'", ",", "function", "(", "err", ",", "reply", ")", "{", "uBrokers", "=", "JSON", ".", "parse", "(", "reply", ")", ";", "}", ")", ";", "}", ")", ";", "listenClient", ".", "subscribe", "(", "'uBrokersChannel'", ")", ";", "}" ]
uBroker Manager Handler the negotiation of messages between uBrokers
[ "uBroker", "Manager", "Handler", "the", "negotiation", "of", "messages", "between", "uBrokers" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/core-services/uBroker/index.js#L141-L155
train
unicornjs/unicornjs
core-services/uBroker/index.js
selectService
function selectService (service){ if(typeof(uServices[service]) !== 'undefined'){ if (uServices[service].length !== 0 ) { var uService = uServices[service], //array activeuService = uService[0]; // the first service should be active but if is not, should look for an active one if (activeuService.status == 0) { var foundOne = false; for ( var i = 0 ; i < uService.length ; i++ ){ if ( foundOne == false && uService[i].status == 1 ) { activeuService = uService[i]; foundOne = true; } } //if there is not active service just stay whith the first one } activeuService.status = 0; //change state to busy uService.shift(); //take the service out of the list uService.push(activeuService); // pushing the service at the end of the list uService[0].status = 1; //activate other service //save the new uServices uServices[service] = uService; // changing the variable on redis client.set('uServices', JSON.stringify(uServices)); // Publish that it did an update client.publish('uServicesChannel', 'UPDATE'); return activeuService; } else { //not services availables console.log('Not services %s available', service); //return error to broker return 'Not services '+service+' available' } } else { return "not services with name "+service; // return an error cause there are no services with that name } }
javascript
function selectService (service){ if(typeof(uServices[service]) !== 'undefined'){ if (uServices[service].length !== 0 ) { var uService = uServices[service], //array activeuService = uService[0]; // the first service should be active but if is not, should look for an active one if (activeuService.status == 0) { var foundOne = false; for ( var i = 0 ; i < uService.length ; i++ ){ if ( foundOne == false && uService[i].status == 1 ) { activeuService = uService[i]; foundOne = true; } } //if there is not active service just stay whith the first one } activeuService.status = 0; //change state to busy uService.shift(); //take the service out of the list uService.push(activeuService); // pushing the service at the end of the list uService[0].status = 1; //activate other service //save the new uServices uServices[service] = uService; // changing the variable on redis client.set('uServices', JSON.stringify(uServices)); // Publish that it did an update client.publish('uServicesChannel', 'UPDATE'); return activeuService; } else { //not services availables console.log('Not services %s available', service); //return error to broker return 'Not services '+service+' available' } } else { return "not services with name "+service; // return an error cause there are no services with that name } }
[ "function", "selectService", "(", "service", ")", "{", "if", "(", "typeof", "(", "uServices", "[", "service", "]", ")", "!==", "'undefined'", ")", "{", "if", "(", "uServices", "[", "service", "]", ".", "length", "!==", "0", ")", "{", "var", "uService", "=", "uServices", "[", "service", "]", ",", "activeuService", "=", "uService", "[", "0", "]", ";", "if", "(", "activeuService", ".", "status", "==", "0", ")", "{", "var", "foundOne", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "uService", ".", "length", ";", "i", "++", ")", "{", "if", "(", "foundOne", "==", "false", "&&", "uService", "[", "i", "]", ".", "status", "==", "1", ")", "{", "activeuService", "=", "uService", "[", "i", "]", ";", "foundOne", "=", "true", ";", "}", "}", "}", "activeuService", ".", "status", "=", "0", ";", "uService", ".", "shift", "(", ")", ";", "uService", ".", "push", "(", "activeuService", ")", ";", "uService", "[", "0", "]", ".", "status", "=", "1", ";", "uServices", "[", "service", "]", "=", "uService", ";", "client", ".", "set", "(", "'uServices'", ",", "JSON", ".", "stringify", "(", "uServices", ")", ")", ";", "client", ".", "publish", "(", "'uServicesChannel'", ",", "'UPDATE'", ")", ";", "return", "activeuService", ";", "}", "else", "{", "console", ".", "log", "(", "'Not services %s available'", ",", "service", ")", ";", "return", "'Not services '", "+", "service", "+", "' available'", "}", "}", "else", "{", "return", "\"not services with name \"", "+", "service", ";", "}", "}" ]
Select a service to assign a job and activate the next service @param service @returns {*}
[ "Select", "a", "service", "to", "assign", "a", "job", "and", "activate", "the", "next", "service" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/core-services/uBroker/index.js#L162-L207
train
unicornjs/unicornjs
core-services/uBroker/index.js
addService
function addService(service, serviceObject){ client.get('uServices', function(err, reply) { if (reply == null){ //extend this object //add a key with service name and value service channel //this is the first service i should activate it var newObjectToPush = JSON.parse('{"' + service + '": []}');//found a fancy way to make this serviceObject.status = 1; newObjectToPush[service].push(serviceObject); extend(uServices, newObjectToPush); setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } else { uServices = JSON.parse(reply); if (typeof(uServices[service]) !== 'undefined') { var uService = uServices[service]; uService.push(serviceObject); //save the new uServices uServices[service] = uService; setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } else { //extend this object //add a key with service name and value service channel var stringObject = '{"' + service + '": []}'; //found a fancy way to make this var objectToPush = JSON.parse(stringObject); objectToPush[service].push(serviceObject); extend(uServices, objectToPush); setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } } }); }
javascript
function addService(service, serviceObject){ client.get('uServices', function(err, reply) { if (reply == null){ //extend this object //add a key with service name and value service channel //this is the first service i should activate it var newObjectToPush = JSON.parse('{"' + service + '": []}');//found a fancy way to make this serviceObject.status = 1; newObjectToPush[service].push(serviceObject); extend(uServices, newObjectToPush); setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } else { uServices = JSON.parse(reply); if (typeof(uServices[service]) !== 'undefined') { var uService = uServices[service]; uService.push(serviceObject); //save the new uServices uServices[service] = uService; setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } else { //extend this object //add a key with service name and value service channel var stringObject = '{"' + service + '": []}'; //found a fancy way to make this var objectToPush = JSON.parse(stringObject); objectToPush[service].push(serviceObject); extend(uServices, objectToPush); setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } } }); }
[ "function", "addService", "(", "service", ",", "serviceObject", ")", "{", "client", ".", "get", "(", "'uServices'", ",", "function", "(", "err", ",", "reply", ")", "{", "if", "(", "reply", "==", "null", ")", "{", "var", "newObjectToPush", "=", "JSON", ".", "parse", "(", "'{\"'", "+", "service", "+", "'\": []}'", ")", ";", "serviceObject", ".", "status", "=", "1", ";", "newObjectToPush", "[", "service", "]", ".", "push", "(", "serviceObject", ")", ";", "extend", "(", "uServices", ",", "newObjectToPush", ")", ";", "setAndPublish", "(", "'uServices'", ",", "uServices", ",", "'uServicesChannel'", ",", "'UPDATE'", ")", "}", "else", "{", "uServices", "=", "JSON", ".", "parse", "(", "reply", ")", ";", "if", "(", "typeof", "(", "uServices", "[", "service", "]", ")", "!==", "'undefined'", ")", "{", "var", "uService", "=", "uServices", "[", "service", "]", ";", "uService", ".", "push", "(", "serviceObject", ")", ";", "uServices", "[", "service", "]", "=", "uService", ";", "setAndPublish", "(", "'uServices'", ",", "uServices", ",", "'uServicesChannel'", ",", "'UPDATE'", ")", "}", "else", "{", "var", "stringObject", "=", "'{\"'", "+", "service", "+", "'\": []}'", ";", "var", "objectToPush", "=", "JSON", ".", "parse", "(", "stringObject", ")", ";", "objectToPush", "[", "service", "]", ".", "push", "(", "serviceObject", ")", ";", "extend", "(", "uServices", ",", "objectToPush", ")", ";", "setAndPublish", "(", "'uServices'", ",", "uServices", ",", "'uServicesChannel'", ",", "'UPDATE'", ")", "}", "}", "}", ")", ";", "}" ]
Receive a service name and an object and stored it redis @addService @param service {String} @param serviceObject {Object}
[ "Receive", "a", "service", "name", "and", "an", "object", "and", "stored", "it", "redis" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/core-services/uBroker/index.js#L215-L254
train
unicornjs/unicornjs
core-services/uBroker/index.js
setAndPublish
function setAndPublish(variableName, object, channel, option){ client.set(variableName, JSON.stringify(object)); // Publish that it did an update client.publish(channel, option); }
javascript
function setAndPublish(variableName, object, channel, option){ client.set(variableName, JSON.stringify(object)); // Publish that it did an update client.publish(channel, option); }
[ "function", "setAndPublish", "(", "variableName", ",", "object", ",", "channel", ",", "option", ")", "{", "client", ".", "set", "(", "variableName", ",", "JSON", ".", "stringify", "(", "object", ")", ")", ";", "client", ".", "publish", "(", "channel", ",", "option", ")", ";", "}" ]
Set a variable on redis @param variableName @param object @param channel @param option
[ "Set", "a", "variable", "on", "redis" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/core-services/uBroker/index.js#L263-L268
train
Bill4Time/mongo-fast-join
Join.js
pushOrPut
function pushOrPut (currentBin, index) { var temp = currentBin; if (Array.isArray(currentBin)) { if (currentBin.indexOf(index) === -1) { currentBin.push(index);//only add if this is a unique index to prevent dup'ing indexes, and associations } } else { temp = [index]; } return temp; }
javascript
function pushOrPut (currentBin, index) { var temp = currentBin; if (Array.isArray(currentBin)) { if (currentBin.indexOf(index) === -1) { currentBin.push(index);//only add if this is a unique index to prevent dup'ing indexes, and associations } } else { temp = [index]; } return temp; }
[ "function", "pushOrPut", "(", "currentBin", ",", "index", ")", "{", "var", "temp", "=", "currentBin", ";", "if", "(", "Array", ".", "isArray", "(", "currentBin", ")", ")", "{", "if", "(", "currentBin", ".", "indexOf", "(", "index", ")", "===", "-", "1", ")", "{", "currentBin", ".", "push", "(", "index", ")", ";", "}", "}", "else", "{", "temp", "=", "[", "index", "]", ";", "}", "return", "temp", ";", "}" ]
Put a new index value into the array at the given bin, making a new array if there is none. @param currentBin The location in which to put the array @param index the index value to put in the array @returns the newly created array if there was one created. Must be assigned into the correct spot
[ "Put", "a", "new", "index", "value", "into", "the", "array", "at", "the", "given", "bin", "making", "a", "new", "array", "if", "there", "is", "none", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L111-L121
train
Bill4Time/mongo-fast-join
Join.js
buildHashTableIndices
function buildHashTableIndices (bin, leftValue, index, accessors, rightKeys) { var i, length = accessors.length, lastBin, val; for (i = 0; i < length; i += 1) { val = accessors[i](leftValue); if (typeof val === "undefined") { return; } if (i + 1 === length) { if (Array.isArray(val)) { //for each value in val, put that key in val.forEach(function (subValue) { var boot = putKeyInBin(bin, subValue); bin[subValue] = pushOrPut(boot, index); bin[subValue].$val = subValue; }); } else { bin[val] = pushOrPut(bin[val], index); bin[val].$val = val; } } else if (Array.isArray(val)) { lastBin = bin; val.forEach(function (subDocumentValue) {//sub vals are for basically supposed to be payment ids var rightKeySubset = rightKeys.slice(i + 1); if (isNullOrUndefined(bin[subDocumentValue])) { bin[subDocumentValue] = {$val: subDocumentValue};//Store $val to maintain the data type } buildHashTableIndices(bin[subDocumentValue], leftValue, index, accessors.slice(i + 1), rightKeySubset); }); return;//don't go through the rest of the accessors, this recursion will take care of those } else { bin = putKeyInBin(bin, val); } } }
javascript
function buildHashTableIndices (bin, leftValue, index, accessors, rightKeys) { var i, length = accessors.length, lastBin, val; for (i = 0; i < length; i += 1) { val = accessors[i](leftValue); if (typeof val === "undefined") { return; } if (i + 1 === length) { if (Array.isArray(val)) { //for each value in val, put that key in val.forEach(function (subValue) { var boot = putKeyInBin(bin, subValue); bin[subValue] = pushOrPut(boot, index); bin[subValue].$val = subValue; }); } else { bin[val] = pushOrPut(bin[val], index); bin[val].$val = val; } } else if (Array.isArray(val)) { lastBin = bin; val.forEach(function (subDocumentValue) {//sub vals are for basically supposed to be payment ids var rightKeySubset = rightKeys.slice(i + 1); if (isNullOrUndefined(bin[subDocumentValue])) { bin[subDocumentValue] = {$val: subDocumentValue};//Store $val to maintain the data type } buildHashTableIndices(bin[subDocumentValue], leftValue, index, accessors.slice(i + 1), rightKeySubset); }); return;//don't go through the rest of the accessors, this recursion will take care of those } else { bin = putKeyInBin(bin, val); } } }
[ "function", "buildHashTableIndices", "(", "bin", ",", "leftValue", ",", "index", ",", "accessors", ",", "rightKeys", ")", "{", "var", "i", ",", "length", "=", "accessors", ".", "length", ",", "lastBin", ",", "val", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "val", "=", "accessors", "[", "i", "]", "(", "leftValue", ")", ";", "if", "(", "typeof", "val", "===", "\"undefined\"", ")", "{", "return", ";", "}", "if", "(", "i", "+", "1", "===", "length", ")", "{", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "val", ".", "forEach", "(", "function", "(", "subValue", ")", "{", "var", "boot", "=", "putKeyInBin", "(", "bin", ",", "subValue", ")", ";", "bin", "[", "subValue", "]", "=", "pushOrPut", "(", "boot", ",", "index", ")", ";", "bin", "[", "subValue", "]", ".", "$val", "=", "subValue", ";", "}", ")", ";", "}", "else", "{", "bin", "[", "val", "]", "=", "pushOrPut", "(", "bin", "[", "val", "]", ",", "index", ")", ";", "bin", "[", "val", "]", ".", "$val", "=", "val", ";", "}", "}", "else", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "lastBin", "=", "bin", ";", "val", ".", "forEach", "(", "function", "(", "subDocumentValue", ")", "{", "var", "rightKeySubset", "=", "rightKeys", ".", "slice", "(", "i", "+", "1", ")", ";", "if", "(", "isNullOrUndefined", "(", "bin", "[", "subDocumentValue", "]", ")", ")", "{", "bin", "[", "subDocumentValue", "]", "=", "{", "$val", ":", "subDocumentValue", "}", ";", "}", "buildHashTableIndices", "(", "bin", "[", "subDocumentValue", "]", ",", "leftValue", ",", "index", ",", "accessors", ".", "slice", "(", "i", "+", "1", ")", ",", "rightKeySubset", ")", ";", "}", ")", ";", "return", ";", "}", "else", "{", "bin", "=", "putKeyInBin", "(", "bin", ",", "val", ")", ";", "}", "}", "}" ]
Create the hash table which maps unique left key combination to an array of numbers representing the indexes of the source data where those unique left key combinations were found. Use this map in the joining process to add join subdocuments to the source data. @param bin The bin object into which keys and indexes will be put @param leftValue the left document from which to retrieve key values @param index the index in the source data that the leftvalue lives at @param accessors The accessor functions which retrieve the value for each join key from the leftValue. @param rightKeys The keys in the right hand set which are being joined on
[ "Create", "the", "hash", "table", "which", "maps", "unique", "left", "key", "combination", "to", "an", "array", "of", "numbers", "representing", "the", "indexes", "of", "the", "source", "data", "where", "those", "unique", "left", "key", "combinations", "were", "found", ".", "Use", "this", "map", "in", "the", "joining", "process", "to", "add", "join", "subdocuments", "to", "the", "source", "data", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L135-L176
train
Bill4Time/mongo-fast-join
Join.js
buildQueriesFromHashBin
function buildQueriesFromHashBin (keyHashBin, rightKeys, level, valuePath, orQueries, inQueries) { var keys = Object.getOwnPropertyNames(keyHashBin), or; valuePath = valuePath || []; if (level === rightKeys.length) { or = {}; rightKeys.forEach(function (key, i) { inQueries[i].push(valuePath[i]); or[key] = valuePath[i]; }); orQueries.push(or); //start returning //take the value path and begin making objects out of it } else { keys.forEach(function (key) { if (key !== "$val") { var newPath = valuePath.slice(), value = keyHashBin[key].$val; newPath.push(value);//now have a copied array buildQueriesFromHashBin(keyHashBin[key], rightKeys, level + 1, newPath, orQueries, inQueries); } }); } }
javascript
function buildQueriesFromHashBin (keyHashBin, rightKeys, level, valuePath, orQueries, inQueries) { var keys = Object.getOwnPropertyNames(keyHashBin), or; valuePath = valuePath || []; if (level === rightKeys.length) { or = {}; rightKeys.forEach(function (key, i) { inQueries[i].push(valuePath[i]); or[key] = valuePath[i]; }); orQueries.push(or); //start returning //take the value path and begin making objects out of it } else { keys.forEach(function (key) { if (key !== "$val") { var newPath = valuePath.slice(), value = keyHashBin[key].$val; newPath.push(value);//now have a copied array buildQueriesFromHashBin(keyHashBin[key], rightKeys, level + 1, newPath, orQueries, inQueries); } }); } }
[ "function", "buildQueriesFromHashBin", "(", "keyHashBin", ",", "rightKeys", ",", "level", ",", "valuePath", ",", "orQueries", ",", "inQueries", ")", "{", "var", "keys", "=", "Object", ".", "getOwnPropertyNames", "(", "keyHashBin", ")", ",", "or", ";", "valuePath", "=", "valuePath", "||", "[", "]", ";", "if", "(", "level", "===", "rightKeys", ".", "length", ")", "{", "or", "=", "{", "}", ";", "rightKeys", ".", "forEach", "(", "function", "(", "key", ",", "i", ")", "{", "inQueries", "[", "i", "]", ".", "push", "(", "valuePath", "[", "i", "]", ")", ";", "or", "[", "key", "]", "=", "valuePath", "[", "i", "]", ";", "}", ")", ";", "orQueries", ".", "push", "(", "or", ")", ";", "}", "else", "{", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", "!==", "\"$val\"", ")", "{", "var", "newPath", "=", "valuePath", ".", "slice", "(", ")", ",", "value", "=", "keyHashBin", "[", "key", "]", ".", "$val", ";", "newPath", ".", "push", "(", "value", ")", ";", "buildQueriesFromHashBin", "(", "keyHashBin", "[", "key", "]", ",", "rightKeys", ",", "level", "+", "1", ",", "newPath", ",", "orQueries", ",", "inQueries", ")", ";", "}", "}", ")", ";", "}", "}" ]
Build the in and or queries that will be used to query for the join documents. @param keyHashBin The bin to use to retrieve the query vals from @param rightKeys The keys which will exists in the join documents @param level The current level of recursion which will correspond to the accessor and the index of the right key @param valuePath The values that have been gathered so far. Ordinally corresponding to the right keys @param orQueries The total list of $or queries generated @param inQueries The total list of $in queries generated
[ "Build", "the", "in", "and", "or", "queries", "that", "will", "be", "used", "to", "query", "for", "the", "join", "documents", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L189-L216
train
Bill4Time/mongo-fast-join
Join.js
arrayJoin
function arrayJoin (results, args) { var srcDataArray = results,//use these results as the source of the join joinCollection = args.joinCollection,//This is the mongoDB.Collection to use to join on joinQuery = args.joinQuery, joinType = args.joinType || 'left', rightKeys = args.rightKeys || [args.rightKey],//Get the value of the key being joined upon newKey = args.newKey,//The new field onto which the joined document will be mapped callback = args.callback,//The callback to call at this level of the join length, i, subqueries, keyHashBin = {}, accessors = [], joinLookups = [], inQueries = [], leftKeys = args.leftKeys || [args.leftKey];//place to put incoming join results rightKeys.forEach(function () { inQueries.push([]); }); leftKeys.forEach(function (key) {//generate the accessors for each entry in the composite key accessors.push(getKeyValueAccessorFromKey(key)); }); length = results.length; //get the path first for (i = 0; i < length; i += 1) { buildHashTableIndices(keyHashBin, results[i], i, accessors, rightKeys, inQueries, joinLookups, {}); }//create the path buildQueriesFromHashBin(keyHashBin, rightKeys, 0, [], joinLookups, inQueries); if (!Array.isArray(srcDataArray)) { srcDataArray = [srcDataArray]; } subqueries = getSubqueries(inQueries, joinLookups, joinQuery, args.pageSize || 25, rightKeys);//example runSubqueries(subqueries, function (items) { var un; performJoining(srcDataArray, items, { rightKeyPropertyPaths: rightKeys, newKey: newKey, keyHashBin: keyHashBin }); if (joinType === "inner") { removeNonMatchesLeft(srcDataArray, newKey); } if (joinStack.length > 0) { arrayJoin(srcDataArray, joinStack.shift()); } else { callIfFunction(finalCallback, [un, srcDataArray]); } callIfFunction(callback, [un, srcDataArray]); }, joinCollection); }
javascript
function arrayJoin (results, args) { var srcDataArray = results,//use these results as the source of the join joinCollection = args.joinCollection,//This is the mongoDB.Collection to use to join on joinQuery = args.joinQuery, joinType = args.joinType || 'left', rightKeys = args.rightKeys || [args.rightKey],//Get the value of the key being joined upon newKey = args.newKey,//The new field onto which the joined document will be mapped callback = args.callback,//The callback to call at this level of the join length, i, subqueries, keyHashBin = {}, accessors = [], joinLookups = [], inQueries = [], leftKeys = args.leftKeys || [args.leftKey];//place to put incoming join results rightKeys.forEach(function () { inQueries.push([]); }); leftKeys.forEach(function (key) {//generate the accessors for each entry in the composite key accessors.push(getKeyValueAccessorFromKey(key)); }); length = results.length; //get the path first for (i = 0; i < length; i += 1) { buildHashTableIndices(keyHashBin, results[i], i, accessors, rightKeys, inQueries, joinLookups, {}); }//create the path buildQueriesFromHashBin(keyHashBin, rightKeys, 0, [], joinLookups, inQueries); if (!Array.isArray(srcDataArray)) { srcDataArray = [srcDataArray]; } subqueries = getSubqueries(inQueries, joinLookups, joinQuery, args.pageSize || 25, rightKeys);//example runSubqueries(subqueries, function (items) { var un; performJoining(srcDataArray, items, { rightKeyPropertyPaths: rightKeys, newKey: newKey, keyHashBin: keyHashBin }); if (joinType === "inner") { removeNonMatchesLeft(srcDataArray, newKey); } if (joinStack.length > 0) { arrayJoin(srcDataArray, joinStack.shift()); } else { callIfFunction(finalCallback, [un, srcDataArray]); } callIfFunction(callback, [un, srcDataArray]); }, joinCollection); }
[ "function", "arrayJoin", "(", "results", ",", "args", ")", "{", "var", "srcDataArray", "=", "results", ",", "joinCollection", "=", "args", ".", "joinCollection", ",", "joinQuery", "=", "args", ".", "joinQuery", ",", "joinType", "=", "args", ".", "joinType", "||", "'left'", ",", "rightKeys", "=", "args", ".", "rightKeys", "||", "[", "args", ".", "rightKey", "]", ",", "newKey", "=", "args", ".", "newKey", ",", "callback", "=", "args", ".", "callback", ",", "length", ",", "i", ",", "subqueries", ",", "keyHashBin", "=", "{", "}", ",", "accessors", "=", "[", "]", ",", "joinLookups", "=", "[", "]", ",", "inQueries", "=", "[", "]", ",", "leftKeys", "=", "args", ".", "leftKeys", "||", "[", "args", ".", "leftKey", "]", ";", "rightKeys", ".", "forEach", "(", "function", "(", ")", "{", "inQueries", ".", "push", "(", "[", "]", ")", ";", "}", ")", ";", "leftKeys", ".", "forEach", "(", "function", "(", "key", ")", "{", "accessors", ".", "push", "(", "getKeyValueAccessorFromKey", "(", "key", ")", ")", ";", "}", ")", ";", "length", "=", "results", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "buildHashTableIndices", "(", "keyHashBin", ",", "results", "[", "i", "]", ",", "i", ",", "accessors", ",", "rightKeys", ",", "inQueries", ",", "joinLookups", ",", "{", "}", ")", ";", "}", "buildQueriesFromHashBin", "(", "keyHashBin", ",", "rightKeys", ",", "0", ",", "[", "]", ",", "joinLookups", ",", "inQueries", ")", ";", "if", "(", "!", "Array", ".", "isArray", "(", "srcDataArray", ")", ")", "{", "srcDataArray", "=", "[", "srcDataArray", "]", ";", "}", "subqueries", "=", "getSubqueries", "(", "inQueries", ",", "joinLookups", ",", "joinQuery", ",", "args", ".", "pageSize", "||", "25", ",", "rightKeys", ")", ";", "runSubqueries", "(", "subqueries", ",", "function", "(", "items", ")", "{", "var", "un", ";", "performJoining", "(", "srcDataArray", ",", "items", ",", "{", "rightKeyPropertyPaths", ":", "rightKeys", ",", "newKey", ":", "newKey", ",", "keyHashBin", ":", "keyHashBin", "}", ")", ";", "if", "(", "joinType", "===", "\"inner\"", ")", "{", "removeNonMatchesLeft", "(", "srcDataArray", ",", "newKey", ")", ";", "}", "if", "(", "joinStack", ".", "length", ">", "0", ")", "{", "arrayJoin", "(", "srcDataArray", ",", "joinStack", ".", "shift", "(", ")", ")", ";", "}", "else", "{", "callIfFunction", "(", "finalCallback", ",", "[", "un", ",", "srcDataArray", "]", ")", ";", "}", "callIfFunction", "(", "callback", ",", "[", "un", ",", "srcDataArray", "]", ")", ";", "}", ",", "joinCollection", ")", ";", "}" ]
Begin the joining process by compiling some data and performing a query for the objects to be joined. @param results The results of the previous join or query @param args The user supplied arguments which will configure this join
[ "Begin", "the", "joining", "process", "by", "compiling", "some", "data", "and", "performing", "a", "query", "for", "the", "objects", "to", "be", "joined", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L225-L285
train
Bill4Time/mongo-fast-join
Join.js
getSubqueries
function getSubqueries (inQueries, orQueries, otherQuery, pageSize, rightKeys) { var subqueries = [], numberOfChunks, i, inQuery, orQuery, queryArray, from, to; // this is a stupid way to turn numbers into 1 numberOfChunks = (orQueries.length / pageSize) + (!!(orQueries.length % pageSize)); for (i = 0; i < numberOfChunks; i += 1) { inQuery = {}; from = i * pageSize; to = from + pageSize; rightKeys.forEach(function (key, index) { inQuery[rightKeys[index]] = {$in: inQueries[index].slice(from, to)}; }); orQuery = { $or: orQueries.slice(from, to)}; queryArray = [ { $match: inQuery }, { $match: orQuery } ]; if(otherQuery) { queryArray.push({ $match: otherQuery }); //Push this to the end on the assumption that the join properties will be indexed, and the arbitrary //filter properties won't be indexed. } subqueries.push(queryArray); } return subqueries; }
javascript
function getSubqueries (inQueries, orQueries, otherQuery, pageSize, rightKeys) { var subqueries = [], numberOfChunks, i, inQuery, orQuery, queryArray, from, to; // this is a stupid way to turn numbers into 1 numberOfChunks = (orQueries.length / pageSize) + (!!(orQueries.length % pageSize)); for (i = 0; i < numberOfChunks; i += 1) { inQuery = {}; from = i * pageSize; to = from + pageSize; rightKeys.forEach(function (key, index) { inQuery[rightKeys[index]] = {$in: inQueries[index].slice(from, to)}; }); orQuery = { $or: orQueries.slice(from, to)}; queryArray = [ { $match: inQuery }, { $match: orQuery } ]; if(otherQuery) { queryArray.push({ $match: otherQuery }); //Push this to the end on the assumption that the join properties will be indexed, and the arbitrary //filter properties won't be indexed. } subqueries.push(queryArray); } return subqueries; }
[ "function", "getSubqueries", "(", "inQueries", ",", "orQueries", ",", "otherQuery", ",", "pageSize", ",", "rightKeys", ")", "{", "var", "subqueries", "=", "[", "]", ",", "numberOfChunks", ",", "i", ",", "inQuery", ",", "orQuery", ",", "queryArray", ",", "from", ",", "to", ";", "numberOfChunks", "=", "(", "orQueries", ".", "length", "/", "pageSize", ")", "+", "(", "!", "!", "(", "orQueries", ".", "length", "%", "pageSize", ")", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "numberOfChunks", ";", "i", "+=", "1", ")", "{", "inQuery", "=", "{", "}", ";", "from", "=", "i", "*", "pageSize", ";", "to", "=", "from", "+", "pageSize", ";", "rightKeys", ".", "forEach", "(", "function", "(", "key", ",", "index", ")", "{", "inQuery", "[", "rightKeys", "[", "index", "]", "]", "=", "{", "$in", ":", "inQueries", "[", "index", "]", ".", "slice", "(", "from", ",", "to", ")", "}", ";", "}", ")", ";", "orQuery", "=", "{", "$or", ":", "orQueries", ".", "slice", "(", "from", ",", "to", ")", "}", ";", "queryArray", "=", "[", "{", "$match", ":", "inQuery", "}", ",", "{", "$match", ":", "orQuery", "}", "]", ";", "if", "(", "otherQuery", ")", "{", "queryArray", ".", "push", "(", "{", "$match", ":", "otherQuery", "}", ")", ";", "}", "subqueries", ".", "push", "(", "queryArray", ")", ";", "}", "return", "subqueries", ";", "}" ]
Get the paged subqueries
[ "Get", "the", "paged", "subqueries" ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L295-L328
train
Bill4Time/mongo-fast-join
Join.js
runSubqueries
function runSubqueries (subQueries, callback, collection) { var i, responsesReceived = 0, length = subQueries.length, joinedSet = [];//The array where the results are going to get stuffed if (subQueries.length > 0) { for (i = 0; i < subQueries.length; i += 1) { collection.aggregate(subQueries[i], function (err, results) { joinedSet = joinedSet.concat(results); responsesReceived += 1; if (responsesReceived === length) { callback(joinedSet); } }); } } else { callback([]); } return joinedSet; }
javascript
function runSubqueries (subQueries, callback, collection) { var i, responsesReceived = 0, length = subQueries.length, joinedSet = [];//The array where the results are going to get stuffed if (subQueries.length > 0) { for (i = 0; i < subQueries.length; i += 1) { collection.aggregate(subQueries[i], function (err, results) { joinedSet = joinedSet.concat(results); responsesReceived += 1; if (responsesReceived === length) { callback(joinedSet); } }); } } else { callback([]); } return joinedSet; }
[ "function", "runSubqueries", "(", "subQueries", ",", "callback", ",", "collection", ")", "{", "var", "i", ",", "responsesReceived", "=", "0", ",", "length", "=", "subQueries", ".", "length", ",", "joinedSet", "=", "[", "]", ";", "if", "(", "subQueries", ".", "length", ">", "0", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "subQueries", ".", "length", ";", "i", "+=", "1", ")", "{", "collection", ".", "aggregate", "(", "subQueries", "[", "i", "]", ",", "function", "(", "err", ",", "results", ")", "{", "joinedSet", "=", "joinedSet", ".", "concat", "(", "results", ")", ";", "responsesReceived", "+=", "1", ";", "if", "(", "responsesReceived", "===", "length", ")", "{", "callback", "(", "joinedSet", ")", ";", "}", "}", ")", ";", "}", "}", "else", "{", "callback", "(", "[", "]", ")", ";", "}", "return", "joinedSet", ";", "}" ]
Run the sub queries individually, leveraging concurrency on the server for better performance.
[ "Run", "the", "sub", "queries", "individually", "leveraging", "concurrency", "on", "the", "server", "for", "better", "performance", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L335-L358
train
Bill4Time/mongo-fast-join
Join.js
getKeyValueAccessorFromKey
function getKeyValueAccessorFromKey (lookupValue) { var accessorFunction; if (typeof lookupValue === "string") { accessorFunction = function (resultValue) { var args = [resultValue]; args = args.concat(lookupValue.split(".")); return safeObjectAccess.apply(this, args); }; } else if (typeof lookupValue === "function") { accessorFunction = lookupValue; } return accessorFunction; }
javascript
function getKeyValueAccessorFromKey (lookupValue) { var accessorFunction; if (typeof lookupValue === "string") { accessorFunction = function (resultValue) { var args = [resultValue]; args = args.concat(lookupValue.split(".")); return safeObjectAccess.apply(this, args); }; } else if (typeof lookupValue === "function") { accessorFunction = lookupValue; } return accessorFunction; }
[ "function", "getKeyValueAccessorFromKey", "(", "lookupValue", ")", "{", "var", "accessorFunction", ";", "if", "(", "typeof", "lookupValue", "===", "\"string\"", ")", "{", "accessorFunction", "=", "function", "(", "resultValue", ")", "{", "var", "args", "=", "[", "resultValue", "]", ";", "args", "=", "args", ".", "concat", "(", "lookupValue", ".", "split", "(", "\".\"", ")", ")", ";", "return", "safeObjectAccess", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ";", "}", "else", "if", "(", "typeof", "lookupValue", "===", "\"function\"", ")", "{", "accessorFunction", "=", "lookupValue", ";", "}", "return", "accessorFunction", ";", "}" ]
Use the lookup value type to build an accessor function for each join key. The lookup algorithm respects dot notation. Currently supports strings and functions. @param lookupValue The key being used to lookup the value. @returns {Function} used to lookup value from an object
[ "Use", "the", "lookup", "value", "type", "to", "build", "an", "accessor", "function", "for", "each", "join", "key", ".", "The", "lookup", "algorithm", "respects", "dot", "notation", ".", "Currently", "supports", "strings", "and", "functions", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L368-L383
train
Bill4Time/mongo-fast-join
Join.js
performJoining
function performJoining (sourceData, joinSet, joinArgs) { var length = joinSet.length, i, rightKeyAccessors = []; joinArgs.rightKeyPropertyPaths.forEach(function (keyValue) { rightKeyAccessors.push(getKeyValueAccessorFromKey(keyValue)); }); for (i = 0; i < length; i += 1) { var rightRecord = joinSet[i], currentBin = joinArgs.keyHashBin; if (isNullOrUndefined(rightRecord)) { continue;//move onto the next, can't join on records that don't exist } //for each entry in the join set add it to the source document at the correct index rightKeyAccessors.forEach(function (accessor) { currentBin = currentBin[accessor(rightRecord)]; }); currentBin.forEach(function (sourceDataIndex) { var theObject = sourceData[sourceDataIndex][joinArgs.newKey]; if (isNullOrUndefined(theObject)) {//Handle adding multiple matches to the same sub document sourceData[sourceDataIndex][joinArgs.newKey] = rightRecord; } else if (Array.isArray(theObject)) { theObject.push(rightRecord); } else { sourceData[sourceDataIndex][joinArgs.newKey] = [theObject, rightRecord]; } }); } }
javascript
function performJoining (sourceData, joinSet, joinArgs) { var length = joinSet.length, i, rightKeyAccessors = []; joinArgs.rightKeyPropertyPaths.forEach(function (keyValue) { rightKeyAccessors.push(getKeyValueAccessorFromKey(keyValue)); }); for (i = 0; i < length; i += 1) { var rightRecord = joinSet[i], currentBin = joinArgs.keyHashBin; if (isNullOrUndefined(rightRecord)) { continue;//move onto the next, can't join on records that don't exist } //for each entry in the join set add it to the source document at the correct index rightKeyAccessors.forEach(function (accessor) { currentBin = currentBin[accessor(rightRecord)]; }); currentBin.forEach(function (sourceDataIndex) { var theObject = sourceData[sourceDataIndex][joinArgs.newKey]; if (isNullOrUndefined(theObject)) {//Handle adding multiple matches to the same sub document sourceData[sourceDataIndex][joinArgs.newKey] = rightRecord; } else if (Array.isArray(theObject)) { theObject.push(rightRecord); } else { sourceData[sourceDataIndex][joinArgs.newKey] = [theObject, rightRecord]; } }); } }
[ "function", "performJoining", "(", "sourceData", ",", "joinSet", ",", "joinArgs", ")", "{", "var", "length", "=", "joinSet", ".", "length", ",", "i", ",", "rightKeyAccessors", "=", "[", "]", ";", "joinArgs", ".", "rightKeyPropertyPaths", ".", "forEach", "(", "function", "(", "keyValue", ")", "{", "rightKeyAccessors", ".", "push", "(", "getKeyValueAccessorFromKey", "(", "keyValue", ")", ")", ";", "}", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "var", "rightRecord", "=", "joinSet", "[", "i", "]", ",", "currentBin", "=", "joinArgs", ".", "keyHashBin", ";", "if", "(", "isNullOrUndefined", "(", "rightRecord", ")", ")", "{", "continue", ";", "}", "rightKeyAccessors", ".", "forEach", "(", "function", "(", "accessor", ")", "{", "currentBin", "=", "currentBin", "[", "accessor", "(", "rightRecord", ")", "]", ";", "}", ")", ";", "currentBin", ".", "forEach", "(", "function", "(", "sourceDataIndex", ")", "{", "var", "theObject", "=", "sourceData", "[", "sourceDataIndex", "]", "[", "joinArgs", ".", "newKey", "]", ";", "if", "(", "isNullOrUndefined", "(", "theObject", ")", ")", "{", "sourceData", "[", "sourceDataIndex", "]", "[", "joinArgs", ".", "newKey", "]", "=", "rightRecord", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "theObject", ")", ")", "{", "theObject", ".", "push", "(", "rightRecord", ")", ";", "}", "else", "{", "sourceData", "[", "sourceDataIndex", "]", "[", "joinArgs", ".", "newKey", "]", "=", "[", "theObject", ",", "rightRecord", "]", ";", "}", "}", ")", ";", "}", "}" ]
Join the join set with the original query results at the new key. @param sourceData The original result set @param joinSet The results returned from the join query @param joinArgs The arguments used to join the source to the join set
[ "Join", "the", "join", "set", "with", "the", "original", "query", "results", "at", "the", "new", "key", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L393-L427
train
Bill4Time/mongo-fast-join
Join.js
safeObjectAccess
function safeObjectAccess () { var object = arguments[0], length = arguments.length, args = arguments, i, results, temp; if (!isNullOrUndefined(object)) { for (i = 1; i < length; i += 1) { if (Array.isArray(object)) {//if it's an array find the values from those results results = []; object.forEach(function (subDocument) { temp = safeObjectAccess.apply( safeObjectAccess, [subDocument].concat(Array.prototype.slice.apply(args, [i, length])) ); if (Array.isArray(temp)) { results = results.concat(temp); } else { results.push(temp); } }); break; } if (typeof object !== "undefined") { object = object[arguments[i]]; } else { break; } } } return results || object }
javascript
function safeObjectAccess () { var object = arguments[0], length = arguments.length, args = arguments, i, results, temp; if (!isNullOrUndefined(object)) { for (i = 1; i < length; i += 1) { if (Array.isArray(object)) {//if it's an array find the values from those results results = []; object.forEach(function (subDocument) { temp = safeObjectAccess.apply( safeObjectAccess, [subDocument].concat(Array.prototype.slice.apply(args, [i, length])) ); if (Array.isArray(temp)) { results = results.concat(temp); } else { results.push(temp); } }); break; } if (typeof object !== "undefined") { object = object[arguments[i]]; } else { break; } } } return results || object }
[ "function", "safeObjectAccess", "(", ")", "{", "var", "object", "=", "arguments", "[", "0", "]", ",", "length", "=", "arguments", ".", "length", ",", "args", "=", "arguments", ",", "i", ",", "results", ",", "temp", ";", "if", "(", "!", "isNullOrUndefined", "(", "object", ")", ")", "{", "for", "(", "i", "=", "1", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "if", "(", "Array", ".", "isArray", "(", "object", ")", ")", "{", "results", "=", "[", "]", ";", "object", ".", "forEach", "(", "function", "(", "subDocument", ")", "{", "temp", "=", "safeObjectAccess", ".", "apply", "(", "safeObjectAccess", ",", "[", "subDocument", "]", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "apply", "(", "args", ",", "[", "i", ",", "length", "]", ")", ")", ")", ";", "if", "(", "Array", ".", "isArray", "(", "temp", ")", ")", "{", "results", "=", "results", ".", "concat", "(", "temp", ")", ";", "}", "else", "{", "results", ".", "push", "(", "temp", ")", ";", "}", "}", ")", ";", "break", ";", "}", "if", "(", "typeof", "object", "!==", "\"undefined\"", ")", "{", "object", "=", "object", "[", "arguments", "[", "i", "]", "]", ";", "}", "else", "{", "break", ";", "}", "}", "}", "return", "results", "||", "object", "}" ]
Access an object without having to worry about "cannot access property '' of undefined" errors. Some extra, necessary and ugly convenience built in is that, if we encounter an array on the lookup path, we recursively drill down into each array value, returning the values discovered in each of those paths. It's kind of a headache, but necessary. @returns The value you were looking for or undefined
[ "Access", "an", "object", "without", "having", "to", "worry", "about", "cannot", "access", "property", "of", "undefined", "errors", ".", "Some", "extra", "necessary", "and", "ugly", "convenience", "built", "in", "is", "that", "if", "we", "encounter", "an", "array", "on", "the", "lookup", "path", "we", "recursively", "drill", "down", "into", "each", "array", "value", "returning", "the", "values", "discovered", "in", "each", "of", "those", "paths", ".", "It", "s", "kind", "of", "a", "headache", "but", "necessary", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L444-L479
train
mikolalysenko/bitmap-triangulate
ortho.js
takeCurve
function takeCurve(pred) { for(var i=0, n=horizon.length; i<n; ++i) { var c = horizon[i] if(pred(c)) { horizon[i] = horizon[n-1] horizon.pop() return c } } return null }
javascript
function takeCurve(pred) { for(var i=0, n=horizon.length; i<n; ++i) { var c = horizon[i] if(pred(c)) { horizon[i] = horizon[n-1] horizon.pop() return c } } return null }
[ "function", "takeCurve", "(", "pred", ")", "{", "for", "(", "var", "i", "=", "0", ",", "n", "=", "horizon", ".", "length", ";", "i", "<", "n", ";", "++", "i", ")", "{", "var", "c", "=", "horizon", "[", "i", "]", "if", "(", "pred", "(", "c", ")", ")", "{", "horizon", "[", "i", "]", "=", "horizon", "[", "n", "-", "1", "]", "horizon", ".", "pop", "(", ")", "return", "c", "}", "}", "return", "null", "}" ]
Finds and remove the first curve in horizon matching predicate
[ "Finds", "and", "remove", "the", "first", "curve", "in", "horizon", "matching", "predicate" ]
bdeaf0d4c988c9b26ec050deb786cdbdbe42054b
https://github.com/mikolalysenko/bitmap-triangulate/blob/bdeaf0d4c988c9b26ec050deb786cdbdbe42054b/ortho.js#L27-L37
train
mikolalysenko/bitmap-triangulate
ortho.js
reflexLeft
function reflexLeft(left, p, i0, i1) { for(var i=i1; i>i0; --i) { var a = left[i-1] var b = left[i] if(orient(a, b, p) <= 0) { cells.push([a[2], b[2], p[2]]) } else { return i } } return i0 }
javascript
function reflexLeft(left, p, i0, i1) { for(var i=i1; i>i0; --i) { var a = left[i-1] var b = left[i] if(orient(a, b, p) <= 0) { cells.push([a[2], b[2], p[2]]) } else { return i } } return i0 }
[ "function", "reflexLeft", "(", "left", ",", "p", ",", "i0", ",", "i1", ")", "{", "for", "(", "var", "i", "=", "i1", ";", "i", ">", "i0", ";", "--", "i", ")", "{", "var", "a", "=", "left", "[", "i", "-", "1", "]", "var", "b", "=", "left", "[", "i", "]", "if", "(", "orient", "(", "a", ",", "b", ",", "p", ")", "<=", "0", ")", "{", "cells", ".", "push", "(", "[", "a", "[", "2", "]", ",", "b", "[", "2", "]", ",", "p", "[", "2", "]", "]", ")", "}", "else", "{", "return", "i", "}", "}", "return", "i0", "}" ]
Remove all left reflex vertices starting from p
[ "Remove", "all", "left", "reflex", "vertices", "starting", "from", "p" ]
bdeaf0d4c988c9b26ec050deb786cdbdbe42054b
https://github.com/mikolalysenko/bitmap-triangulate/blob/bdeaf0d4c988c9b26ec050deb786cdbdbe42054b/ortho.js#L40-L51
train
mikolalysenko/bitmap-triangulate
ortho.js
reflexRight
function reflexRight(right, p, i0, i1) { for(var i=i0; i<i1; ++i) { var a = right[i] var b = right[i+1] if(orient(p, a, b) <= 0) { cells.push([p[2], a[2], b[2]]) } else { return i } } return i1 }
javascript
function reflexRight(right, p, i0, i1) { for(var i=i0; i<i1; ++i) { var a = right[i] var b = right[i+1] if(orient(p, a, b) <= 0) { cells.push([p[2], a[2], b[2]]) } else { return i } } return i1 }
[ "function", "reflexRight", "(", "right", ",", "p", ",", "i0", ",", "i1", ")", "{", "for", "(", "var", "i", "=", "i0", ";", "i", "<", "i1", ";", "++", "i", ")", "{", "var", "a", "=", "right", "[", "i", "]", "var", "b", "=", "right", "[", "i", "+", "1", "]", "if", "(", "orient", "(", "p", ",", "a", ",", "b", ")", "<=", "0", ")", "{", "cells", ".", "push", "(", "[", "p", "[", "2", "]", ",", "a", "[", "2", "]", ",", "b", "[", "2", "]", "]", ")", "}", "else", "{", "return", "i", "}", "}", "return", "i1", "}" ]
Remove all right reflex vertices starting from p
[ "Remove", "all", "right", "reflex", "vertices", "starting", "from", "p" ]
bdeaf0d4c988c9b26ec050deb786cdbdbe42054b
https://github.com/mikolalysenko/bitmap-triangulate/blob/bdeaf0d4c988c9b26ec050deb786cdbdbe42054b/ortho.js#L54-L65
train
mikolalysenko/bitmap-triangulate
ortho.js
mergeSegment
function mergeSegment(row, x0, x1) { //Take left and right curves out of horizon var left = takeCurve(function(c) { return c[c.length-1][0] === x0 }) var right = takeCurve(function(c) { return c[0][0] === x1 }) //Create new vertices var p0 = [x0,row,vertices.length] var p1 = [x1,row,vertices.length+1] vertices.push([x0, row], [x1,row]) //Merge chains var ncurve = [] if(left) { var l1 = reflexLeft(left, p0, 0, left.length-1) for(var i=0; i<=l1; ++i) { ncurve.push(left[i]) } } ncurve.push(p0, p1) if(right) { var r0 = reflexRight(right, p1, 0, right.length-1) for(var i=r0; i<right.length; ++i) { ncurve.push(right[i]) } } //Append new chain to horizon horizon.push(ncurve) }
javascript
function mergeSegment(row, x0, x1) { //Take left and right curves out of horizon var left = takeCurve(function(c) { return c[c.length-1][0] === x0 }) var right = takeCurve(function(c) { return c[0][0] === x1 }) //Create new vertices var p0 = [x0,row,vertices.length] var p1 = [x1,row,vertices.length+1] vertices.push([x0, row], [x1,row]) //Merge chains var ncurve = [] if(left) { var l1 = reflexLeft(left, p0, 0, left.length-1) for(var i=0; i<=l1; ++i) { ncurve.push(left[i]) } } ncurve.push(p0, p1) if(right) { var r0 = reflexRight(right, p1, 0, right.length-1) for(var i=r0; i<right.length; ++i) { ncurve.push(right[i]) } } //Append new chain to horizon horizon.push(ncurve) }
[ "function", "mergeSegment", "(", "row", ",", "x0", ",", "x1", ")", "{", "var", "left", "=", "takeCurve", "(", "function", "(", "c", ")", "{", "return", "c", "[", "c", ".", "length", "-", "1", "]", "[", "0", "]", "===", "x0", "}", ")", "var", "right", "=", "takeCurve", "(", "function", "(", "c", ")", "{", "return", "c", "[", "0", "]", "[", "0", "]", "===", "x1", "}", ")", "var", "p0", "=", "[", "x0", ",", "row", ",", "vertices", ".", "length", "]", "var", "p1", "=", "[", "x1", ",", "row", ",", "vertices", ".", "length", "+", "1", "]", "vertices", ".", "push", "(", "[", "x0", ",", "row", "]", ",", "[", "x1", ",", "row", "]", ")", "var", "ncurve", "=", "[", "]", "if", "(", "left", ")", "{", "var", "l1", "=", "reflexLeft", "(", "left", ",", "p0", ",", "0", ",", "left", ".", "length", "-", "1", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "l1", ";", "++", "i", ")", "{", "ncurve", ".", "push", "(", "left", "[", "i", "]", ")", "}", "}", "ncurve", ".", "push", "(", "p0", ",", "p1", ")", "if", "(", "right", ")", "{", "var", "r0", "=", "reflexRight", "(", "right", ",", "p1", ",", "0", ",", "right", ".", "length", "-", "1", ")", "for", "(", "var", "i", "=", "r0", ";", "i", "<", "right", ".", "length", ";", "++", "i", ")", "{", "ncurve", ".", "push", "(", "right", "[", "i", "]", ")", "}", "}", "horizon", ".", "push", "(", "ncurve", ")", "}" ]
Insert new segment into horizon
[ "Insert", "new", "segment", "into", "horizon" ]
bdeaf0d4c988c9b26ec050deb786cdbdbe42054b
https://github.com/mikolalysenko/bitmap-triangulate/blob/bdeaf0d4c988c9b26ec050deb786cdbdbe42054b/ortho.js#L68-L100
train
kalinchernev/odp
lib/odp.js
_sendRequest
function _sendRequest (options) { return new Promise((resolve, reject) => { var query = querystring.stringify(options.query) var bodyData = JSON.stringify(options.body) request({ url: _baseUrl + `/${options.endpoint}?${query}`, headers: headers, method: options.method, body: bodyData }, (error, response, body) => { if (error) { reject(error) } resolve(body) }) }) }
javascript
function _sendRequest (options) { return new Promise((resolve, reject) => { var query = querystring.stringify(options.query) var bodyData = JSON.stringify(options.body) request({ url: _baseUrl + `/${options.endpoint}?${query}`, headers: headers, method: options.method, body: bodyData }, (error, response, body) => { if (error) { reject(error) } resolve(body) }) }) }
[ "function", "_sendRequest", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "query", "=", "querystring", ".", "stringify", "(", "options", ".", "query", ")", "var", "bodyData", "=", "JSON", ".", "stringify", "(", "options", ".", "body", ")", "request", "(", "{", "url", ":", "_baseUrl", "+", "`", "${", "options", ".", "endpoint", "}", "${", "query", "}", "`", ",", "headers", ":", "headers", ",", "method", ":", "options", ".", "method", ",", "body", ":", "bodyData", "}", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", "}", "resolve", "(", "body", ")", "}", ")", "}", ")", "}" ]
Calls the service and return the data in a promise, but with POST. @function @private @name _sendRequest @param {object} options - The request set of options. @param {string} options.endpoint - Resource endpoint, without any slashes. @param {object} options.query - The query parameters for the request. @param {object} options.body - The body if POST, PUT @param {string} options.method - The method to be used. @returns {Promise} The response in a promise.
[ "Calls", "the", "service", "and", "return", "the", "data", "in", "a", "promise", "but", "with", "POST", "." ]
8b92122e99bc143d8737401aa225acc17f2a9aa1
https://github.com/kalinchernev/odp/blob/8b92122e99bc143d8737401aa225acc17f2a9aa1/lib/odp.js#L29-L46
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/inference/index.js
getTypeAnnotation
function getTypeAnnotation() { if (this.typeAnnotation) return this.typeAnnotation; var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); if (t.isTypeAnnotation(type)) type = type.typeAnnotation; return this.typeAnnotation = type; }
javascript
function getTypeAnnotation() { if (this.typeAnnotation) return this.typeAnnotation; var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); if (t.isTypeAnnotation(type)) type = type.typeAnnotation; return this.typeAnnotation = type; }
[ "function", "getTypeAnnotation", "(", ")", "{", "if", "(", "this", ".", "typeAnnotation", ")", "return", "this", ".", "typeAnnotation", ";", "var", "type", "=", "this", ".", "_getTypeAnnotation", "(", ")", "||", "t", ".", "anyTypeAnnotation", "(", ")", ";", "if", "(", "t", ".", "isTypeAnnotation", "(", "type", ")", ")", "type", "=", "type", ".", "typeAnnotation", ";", "return", "this", ".", "typeAnnotation", "=", "type", ";", "}" ]
Infer the type of the current `NodePath`.
[ "Infer", "the", "type", "of", "the", "current", "NodePath", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/inference/index.js#L28-L34
train
skerit/protoblast
lib/string.js
getNormalizedTag
function getNormalizedTag(tag_buffer) { var match = NORMALIZE_TAG_REGEX.exec(tag_buffer); return match ? match[1].toLowerCase() : null; }
javascript
function getNormalizedTag(tag_buffer) { var match = NORMALIZE_TAG_REGEX.exec(tag_buffer); return match ? match[1].toLowerCase() : null; }
[ "function", "getNormalizedTag", "(", "tag_buffer", ")", "{", "var", "match", "=", "NORMALIZE_TAG_REGEX", ".", "exec", "(", "tag_buffer", ")", ";", "return", "match", "?", "match", "[", "1", "]", ".", "toLowerCase", "(", ")", ":", "null", ";", "}" ]
Get the tag name @author Jelle De Loecker <[email protected]> @since 0.6.3 @version 0.6.3 @param {String} tag_buffer @return {String} The lowercase tag name
[ "Get", "the", "tag", "name" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/string.js#L643-L646
train
stadt-bielefeld/mapfile2js
src/parse/determineDepth.js
determineDepth
function determineDepth(obj){ let depth = 0; obj.forEach((line)=>{ line.depth = depth; if(line.isBlockKey){ depth++; }else{ if(line.key){ if(line.key.toUpperCase() === 'END'){ depth--; line.depth = depth; } } } }); return obj; }
javascript
function determineDepth(obj){ let depth = 0; obj.forEach((line)=>{ line.depth = depth; if(line.isBlockKey){ depth++; }else{ if(line.key){ if(line.key.toUpperCase() === 'END'){ depth--; line.depth = depth; } } } }); return obj; }
[ "function", "determineDepth", "(", "obj", ")", "{", "let", "depth", "=", "0", ";", "obj", ".", "forEach", "(", "(", "line", ")", "=>", "{", "line", ".", "depth", "=", "depth", ";", "if", "(", "line", ".", "isBlockKey", ")", "{", "depth", "++", ";", "}", "else", "{", "if", "(", "line", ".", "key", ")", "{", "if", "(", "line", ".", "key", ".", "toUpperCase", "(", ")", "===", "'END'", ")", "{", "depth", "--", ";", "line", ".", "depth", "=", "depth", ";", "}", "}", "}", "}", ")", ";", "return", "obj", ";", "}" ]
Determines the depth of every line of mapfile. @param {array} obj Array of line objects
[ "Determines", "the", "depth", "of", "every", "line", "of", "mapfile", "." ]
08497189503e8823d1c9f26b74ce4ad1025e59dd
https://github.com/stadt-bielefeld/mapfile2js/blob/08497189503e8823d1c9f26b74ce4ad1025e59dd/src/parse/determineDepth.js#L6-L27
train
RangerMauve/hex-to-32
index.js
encode
function encode(hexString) { // Convert to array of bytes var bytes = Buffer.from(hexString, "hex"); var encoded = base32.stringify(bytes); // strip padding & lowercase return encoded.replace(/(=+)$/, '').toLowerCase(); }
javascript
function encode(hexString) { // Convert to array of bytes var bytes = Buffer.from(hexString, "hex"); var encoded = base32.stringify(bytes); // strip padding & lowercase return encoded.replace(/(=+)$/, '').toLowerCase(); }
[ "function", "encode", "(", "hexString", ")", "{", "var", "bytes", "=", "Buffer", ".", "from", "(", "hexString", ",", "\"hex\"", ")", ";", "var", "encoded", "=", "base32", ".", "stringify", "(", "bytes", ")", ";", "return", "encoded", ".", "replace", "(", "/", "(=+)$", "/", ",", "''", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Convert a string of hex characters to a base32 encoded string @param {String} hexString The hex string to encode
[ "Convert", "a", "string", "of", "hex", "characters", "to", "a", "base32", "encoded", "string" ]
68c6e4159bec5a8722ceeb41765417480b6d4468
https://github.com/RangerMauve/hex-to-32/blob/68c6e4159bec5a8722ceeb41765417480b6d4468/index.js#L12-L19
train
RangerMauve/hex-to-32
index.js
decode
function decode(base32String) { // Decode to Buffer var bytes = base32.parse(base32String, { out: Buffer.alloc, loose: true }); return bytes.toString("hex"); }
javascript
function decode(base32String) { // Decode to Buffer var bytes = base32.parse(base32String, { out: Buffer.alloc, loose: true }); return bytes.toString("hex"); }
[ "function", "decode", "(", "base32String", ")", "{", "var", "bytes", "=", "base32", ".", "parse", "(", "base32String", ",", "{", "out", ":", "Buffer", ".", "alloc", ",", "loose", ":", "true", "}", ")", ";", "return", "bytes", ".", "toString", "(", "\"hex\"", ")", ";", "}" ]
Convert a base32 encoded string to a hex string @param {String} base32String The base32 encoded string
[ "Convert", "a", "base32", "encoded", "string", "to", "a", "hex", "string" ]
68c6e4159bec5a8722ceeb41765417480b6d4468
https://github.com/RangerMauve/hex-to-32/blob/68c6e4159bec5a8722ceeb41765417480b6d4468/index.js#L25-L33
train
andrehrf/horus-client
index.js
function(setArr, cb){ if(typeof setArr === "string") var postData = querystring.stringify([setArr]); else if(typeof setArr === "object" || typeof setArr === "array") var postData = querystring.stringify(setArr); var options = { host: urlArr.hostname, path: "/set", port: urlArr.port, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; var postRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error) { if(typeof cb === "function") cb(error); }); res.on('data', function (chunk) { result += chunk; }); res.on('end', function (chunk) { if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null; cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); postRequest.write(postData); postRequest.end(); }
javascript
function(setArr, cb){ if(typeof setArr === "string") var postData = querystring.stringify([setArr]); else if(typeof setArr === "object" || typeof setArr === "array") var postData = querystring.stringify(setArr); var options = { host: urlArr.hostname, path: "/set", port: urlArr.port, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; var postRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error) { if(typeof cb === "function") cb(error); }); res.on('data', function (chunk) { result += chunk; }); res.on('end', function (chunk) { if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null; cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); postRequest.write(postData); postRequest.end(); }
[ "function", "(", "setArr", ",", "cb", ")", "{", "if", "(", "typeof", "setArr", "===", "\"string\"", ")", "var", "postData", "=", "querystring", ".", "stringify", "(", "[", "setArr", "]", ")", ";", "else", "if", "(", "typeof", "setArr", "===", "\"object\"", "||", "typeof", "setArr", "===", "\"array\"", ")", "var", "postData", "=", "querystring", ".", "stringify", "(", "setArr", ")", ";", "var", "options", "=", "{", "host", ":", "urlArr", ".", "hostname", ",", "path", ":", "\"/set\"", ",", "port", ":", "urlArr", ".", "port", ",", "method", ":", "'POST'", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", ",", "'Content-Length'", ":", "Buffer", ".", "byteLength", "(", "postData", ")", "}", "}", ";", "var", "postRequest", "=", "protocol", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "var", "result", "=", "\"\"", ";", "if", "(", "res", ".", "statusCode", "===", "200", ")", "{", "res", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "error", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "result", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", "chunk", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "{", "var", "resultObj", "=", "JSON", ".", "parse", "(", "result", ")", ";", "var", "err", "=", "(", "resultObj", ".", "status", "===", "\"error\"", ")", "?", "resultObj", "[", "\"msg\"", "]", ":", "null", ";", "cb", "(", "err", ",", "resultObj", ")", ";", "}", "}", ")", ";", "}", "else", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "\"Request return HTTP \"", "+", "res", ".", "statusCode", ")", ";", "}", "}", ")", ";", "postRequest", ".", "write", "(", "postData", ")", ";", "postRequest", ".", "end", "(", ")", ";", "}" ]
Function do set links to watch @param array setArr @param function cb @return void
[ "Function", "do", "set", "links", "to", "watch" ]
a32bd3a91b7af93ad8640789315ddabfc5ee8931
https://github.com/andrehrf/horus-client/blob/a32bd3a91b7af93ad8640789315ddabfc5ee8931/index.js#L23-L69
train
andrehrf/horus-client
index.js
function(link, cb){ var options = { host: urlArr.hostname, port: urlArr.port, path: urlArr.path+"?link="+encodeURIComponent(link), method: 'GET' }; var getRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error) { if(typeof cb === "function") cb(error); }); res.on('data', function (chunk) { result += chunk; }); res.on('end', function (chunk) { if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); getRequest.end(); }
javascript
function(link, cb){ var options = { host: urlArr.hostname, port: urlArr.port, path: urlArr.path+"?link="+encodeURIComponent(link), method: 'GET' }; var getRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error) { if(typeof cb === "function") cb(error); }); res.on('data', function (chunk) { result += chunk; }); res.on('end', function (chunk) { if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); getRequest.end(); }
[ "function", "(", "link", ",", "cb", ")", "{", "var", "options", "=", "{", "host", ":", "urlArr", ".", "hostname", ",", "port", ":", "urlArr", ".", "port", ",", "path", ":", "urlArr", ".", "path", "+", "\"?link=\"", "+", "encodeURIComponent", "(", "link", ")", ",", "method", ":", "'GET'", "}", ";", "var", "getRequest", "=", "protocol", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "var", "result", "=", "\"\"", ";", "if", "(", "res", ".", "statusCode", "===", "200", ")", "{", "res", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "error", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "result", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", "chunk", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "{", "var", "resultObj", "=", "JSON", ".", "parse", "(", "result", ")", ";", "var", "err", "=", "(", "resultObj", ".", "status", "===", "\"error\"", ")", "?", "resultObj", "[", "\"msg\"", "]", ":", "null", "cb", "(", "err", ",", "resultObj", ")", ";", "}", "}", ")", ";", "}", "else", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "\"Request return HTTP \"", "+", "res", ".", "statusCode", ")", ";", "}", "}", ")", ";", "getRequest", ".", "end", "(", ")", ";", "}" ]
Function do get link status @param string link @param function cb @return void
[ "Function", "do", "get", "link", "status" ]
a32bd3a91b7af93ad8640789315ddabfc5ee8931
https://github.com/andrehrf/horus-client/blob/a32bd3a91b7af93ad8640789315ddabfc5ee8931/index.js#L78-L114
train
andrehrf/horus-client
index.js
function(link, cb){ var id = Math.abs(crc32.str(md5(link))); var options = { host: urlArr.hostname, port: urlArr.port, path: "/delete/"+id, method: 'DELETE', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; var deleteRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error){ if(typeof cb === "function") cb(error); }); res.on('data', function(chunk){ result += chunk; }); res.on('end', function(chunk){ if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); deleteRequest.end(); }
javascript
function(link, cb){ var id = Math.abs(crc32.str(md5(link))); var options = { host: urlArr.hostname, port: urlArr.port, path: "/delete/"+id, method: 'DELETE', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; var deleteRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error){ if(typeof cb === "function") cb(error); }); res.on('data', function(chunk){ result += chunk; }); res.on('end', function(chunk){ if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); deleteRequest.end(); }
[ "function", "(", "link", ",", "cb", ")", "{", "var", "id", "=", "Math", ".", "abs", "(", "crc32", ".", "str", "(", "md5", "(", "link", ")", ")", ")", ";", "var", "options", "=", "{", "host", ":", "urlArr", ".", "hostname", ",", "port", ":", "urlArr", ".", "port", ",", "path", ":", "\"/delete/\"", "+", "id", ",", "method", ":", "'DELETE'", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "}", ";", "var", "deleteRequest", "=", "protocol", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "var", "result", "=", "\"\"", ";", "if", "(", "res", ".", "statusCode", "===", "200", ")", "{", "res", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "error", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "result", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", "chunk", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "{", "var", "resultObj", "=", "JSON", ".", "parse", "(", "result", ")", ";", "var", "err", "=", "(", "resultObj", ".", "status", "===", "\"error\"", ")", "?", "resultObj", "[", "\"msg\"", "]", ":", "null", "cb", "(", "err", ",", "resultObj", ")", ";", "}", "}", ")", ";", "}", "else", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "\"Request return HTTP \"", "+", "res", ".", "statusCode", ")", ";", "}", "}", ")", ";", "deleteRequest", ".", "end", "(", ")", ";", "}" ]
Function to remove link to waitch list @returns {undefined}
[ "Function", "to", "remove", "link", "to", "waitch", "list" ]
a32bd3a91b7af93ad8640789315ddabfc5ee8931
https://github.com/andrehrf/horus-client/blob/a32bd3a91b7af93ad8640789315ddabfc5ee8931/index.js#L121-L162
train
qmachine/qm-nodejs
lib/qm/service.js
function (request) { // This function is the default logging function. return { host: request.headers.host, method: request.method, timestamp: new Date(), url: request.url }; }
javascript
function (request) { // This function is the default logging function. return { host: request.headers.host, method: request.method, timestamp: new Date(), url: request.url }; }
[ "function", "(", "request", ")", "{", "return", "{", "host", ":", "request", ".", "headers", ".", "host", ",", "method", ":", "request", ".", "method", ",", "timestamp", ":", "new", "Date", "(", ")", ",", "url", ":", "request", ".", "url", "}", ";", "}" ]
- aka INADDR_ANY
[ "-", "aka", "INADDR_ANY" ]
755b55e04e6ca4716504a7c705804ca07df8360f
https://github.com/qmachine/qm-nodejs/blob/755b55e04e6ca4716504a7c705804ca07df8360f/lib/qm/service.js#L130-L138
train
solid/folder-pane
folderPane.js
function (newPaneOptions) { var kb = UI.store var newInstance = newPaneOptions.newInstance || kb.sym(newPaneOptions.newBase) var u = newInstance.uri if (u.endsWith('/')) { u = u.slice(0, -1) // chop off trailer }// { throw new Error('URI of new folder must end in "/" :' + u) } newPaneOptions.newInstance = kb.sym(u + '/') // @@@@ kludge until we can get the solid-client version working // Force the folder by saving a dummy file inside it return kb.fetcher.webOperation('PUT', newInstance.uri + '.dummy') .then(function () { console.log('New folder created: ' + newInstance.uri) return kb.fetcher.delete(newInstance.uri + '.dummy') }) .then(function () { console.log('Dummy file deleted : ' + newInstance.uri + '.dummy') /* return kb.fetcher.createContainer(parentURI, folderName) // Not BOTH ways }) .then(function () { */ console.log('New container created: ' + newInstance.uri) return newPaneOptions }) }
javascript
function (newPaneOptions) { var kb = UI.store var newInstance = newPaneOptions.newInstance || kb.sym(newPaneOptions.newBase) var u = newInstance.uri if (u.endsWith('/')) { u = u.slice(0, -1) // chop off trailer }// { throw new Error('URI of new folder must end in "/" :' + u) } newPaneOptions.newInstance = kb.sym(u + '/') // @@@@ kludge until we can get the solid-client version working // Force the folder by saving a dummy file inside it return kb.fetcher.webOperation('PUT', newInstance.uri + '.dummy') .then(function () { console.log('New folder created: ' + newInstance.uri) return kb.fetcher.delete(newInstance.uri + '.dummy') }) .then(function () { console.log('Dummy file deleted : ' + newInstance.uri + '.dummy') /* return kb.fetcher.createContainer(parentURI, folderName) // Not BOTH ways }) .then(function () { */ console.log('New container created: ' + newInstance.uri) return newPaneOptions }) }
[ "function", "(", "newPaneOptions", ")", "{", "var", "kb", "=", "UI", ".", "store", "var", "newInstance", "=", "newPaneOptions", ".", "newInstance", "||", "kb", ".", "sym", "(", "newPaneOptions", ".", "newBase", ")", "var", "u", "=", "newInstance", ".", "uri", "if", "(", "u", ".", "endsWith", "(", "'/'", ")", ")", "{", "u", "=", "u", ".", "slice", "(", "0", ",", "-", "1", ")", "}", "newPaneOptions", ".", "newInstance", "=", "kb", ".", "sym", "(", "u", "+", "'/'", ")", "return", "kb", ".", "fetcher", ".", "webOperation", "(", "'PUT'", ",", "newInstance", ".", "uri", "+", "'.dummy'", ")", ".", "then", "(", "function", "(", ")", "{", "console", ".", "log", "(", "'New folder created: '", "+", "newInstance", ".", "uri", ")", "return", "kb", ".", "fetcher", ".", "delete", "(", "newInstance", ".", "uri", "+", "'.dummy'", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "console", ".", "log", "(", "'Dummy file deleted : '", "+", "newInstance", ".", "uri", "+", "'.dummy'", ")", "console", ".", "log", "(", "'New container created: '", "+", "newInstance", ".", "uri", ")", "return", "newPaneOptions", "}", ")", "}" ]
Create a new folder in a Solid system,
[ "Create", "a", "new", "folder", "in", "a", "Solid", "system" ]
ef48b49a7b5e7c7475ad8acb566e921078604b7b
https://github.com/solid/folder-pane/blob/ef48b49a7b5e7c7475ad8acb566e921078604b7b/folderPane.js#L17-L44
train
solid/folder-pane
folderPane.js
function (obj) { // @@ This hiddenness should actually be server defined var pathEnd = obj.uri.slice(obj.dir().uri.length) return !(pathEnd.startsWith('.') || pathEnd.endsWith('.acl') || pathEnd.endsWith('~')) }
javascript
function (obj) { // @@ This hiddenness should actually be server defined var pathEnd = obj.uri.slice(obj.dir().uri.length) return !(pathEnd.startsWith('.') || pathEnd.endsWith('.acl') || pathEnd.endsWith('~')) }
[ "function", "(", "obj", ")", "{", "var", "pathEnd", "=", "obj", ".", "uri", ".", "slice", "(", "obj", ".", "dir", "(", ")", ".", "uri", ".", "length", ")", "return", "!", "(", "pathEnd", ".", "startsWith", "(", "'.'", ")", "||", "pathEnd", ".", "endsWith", "(", "'.acl'", ")", "||", "pathEnd", ".", "endsWith", "(", "'~'", ")", ")", "}" ]
If this is an LDP container just list the directory
[ "If", "this", "is", "an", "LDP", "container", "just", "list", "the", "directory" ]
ef48b49a7b5e7c7475ad8acb566e921078604b7b
https://github.com/solid/folder-pane/blob/ef48b49a7b5e7c7475ad8acb566e921078604b7b/folderPane.js#L79-L82
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/api/browser.js
runScripts
function runScripts() { var scripts = []; var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"]; var index = 0; /** * Transform and execute script. Ensures correct load order. */ var exec = function exec() { var param = scripts[index]; if (param instanceof Array) { transform.run.apply(transform, param); index++; exec(); } }; /** * Load, transform, and execute all scripts. */ var run = function run(script, i) { var opts = {}; if (script.src) { transform.load(script.src, function (param) { scripts[i] = param; exec(); }, opts, true); } else { opts.filename = "embedded"; scripts[i] = [script.innerHTML, opts]; } }; // Collect scripts with Babel `types`. var _scripts = global.document.getElementsByTagName("script"); for (var i = 0; i < _scripts.length; ++i) { var _script = _scripts[i]; if (types.indexOf(_script.type) >= 0) scripts.push(_script); } for (i in scripts) { run(scripts[i], i); } exec(); }
javascript
function runScripts() { var scripts = []; var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"]; var index = 0; /** * Transform and execute script. Ensures correct load order. */ var exec = function exec() { var param = scripts[index]; if (param instanceof Array) { transform.run.apply(transform, param); index++; exec(); } }; /** * Load, transform, and execute all scripts. */ var run = function run(script, i) { var opts = {}; if (script.src) { transform.load(script.src, function (param) { scripts[i] = param; exec(); }, opts, true); } else { opts.filename = "embedded"; scripts[i] = [script.innerHTML, opts]; } }; // Collect scripts with Babel `types`. var _scripts = global.document.getElementsByTagName("script"); for (var i = 0; i < _scripts.length; ++i) { var _script = _scripts[i]; if (types.indexOf(_script.type) >= 0) scripts.push(_script); } for (i in scripts) { run(scripts[i], i); } exec(); }
[ "function", "runScripts", "(", ")", "{", "var", "scripts", "=", "[", "]", ";", "var", "types", "=", "[", "\"text/ecmascript-6\"", ",", "\"text/6to5\"", ",", "\"text/babel\"", ",", "\"module\"", "]", ";", "var", "index", "=", "0", ";", "var", "exec", "=", "function", "exec", "(", ")", "{", "var", "param", "=", "scripts", "[", "index", "]", ";", "if", "(", "param", "instanceof", "Array", ")", "{", "transform", ".", "run", ".", "apply", "(", "transform", ",", "param", ")", ";", "index", "++", ";", "exec", "(", ")", ";", "}", "}", ";", "var", "run", "=", "function", "run", "(", "script", ",", "i", ")", "{", "var", "opts", "=", "{", "}", ";", "if", "(", "script", ".", "src", ")", "{", "transform", ".", "load", "(", "script", ".", "src", ",", "function", "(", "param", ")", "{", "scripts", "[", "i", "]", "=", "param", ";", "exec", "(", ")", ";", "}", ",", "opts", ",", "true", ")", ";", "}", "else", "{", "opts", ".", "filename", "=", "\"embedded\"", ";", "scripts", "[", "i", "]", "=", "[", "script", ".", "innerHTML", ",", "opts", "]", ";", "}", "}", ";", "var", "_scripts", "=", "global", ".", "document", ".", "getElementsByTagName", "(", "\"script\"", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "_scripts", ".", "length", ";", "++", "i", ")", "{", "var", "_script", "=", "_scripts", "[", "i", "]", ";", "if", "(", "types", ".", "indexOf", "(", "_script", ".", "type", ")", ">=", "0", ")", "scripts", ".", "push", "(", "_script", ")", ";", "}", "for", "(", "i", "in", "scripts", ")", "{", "run", "(", "scripts", "[", "i", "]", ",", "i", ")", ";", "}", "exec", "(", ")", ";", "}" ]
Load and transform all scripts of `types`. @example <script type="module"></script>
[ "Load", "and", "transform", "all", "scripts", "of", "types", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/api/browser.js#L74-L124
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/index.js
find
function find(obj, node, parent) { if (!obj) return; var result; var types = Object.keys(obj); for (var i = 0; i < types.length; i++) { var type = types[i]; if (t.is(type, node)) { var fn = obj[type]; result = fn(node, parent); if (result != null) break; } } return result; }
javascript
function find(obj, node, parent) { if (!obj) return; var result; var types = Object.keys(obj); for (var i = 0; i < types.length; i++) { var type = types[i]; if (t.is(type, node)) { var fn = obj[type]; result = fn(node, parent); if (result != null) break; } } return result; }
[ "function", "find", "(", "obj", ",", "node", ",", "parent", ")", "{", "if", "(", "!", "obj", ")", "return", ";", "var", "result", ";", "var", "types", "=", "Object", ".", "keys", "(", "obj", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "types", ".", "length", ";", "i", "++", ")", "{", "var", "type", "=", "types", "[", "i", "]", ";", "if", "(", "t", ".", "is", "(", "type", ",", "node", ")", ")", "{", "var", "fn", "=", "obj", "[", "type", "]", ";", "result", "=", "fn", "(", "node", ",", "parent", ")", ";", "if", "(", "result", "!=", "null", ")", "break", ";", "}", "}", "return", "result", ";", "}" ]
Test if node matches a set of type-matcher pairs. @example find({ VariableDeclaration(node, parent) { return true; } }, node, parent);
[ "Test", "if", "node", "matches", "a", "set", "of", "type", "-", "matcher", "pairs", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/index.js#L48-L64
train
carlwoodward/run-markdown
index.js
writeAndRunCodeBlocks
function writeAndRunCodeBlocks(codeBlocks) { var dir = '.runnable-markdown-' + rand.generateKey(7); return makeTempDir(dir) .then(function() { return new Promise(function(fulfill, reject) { async.mapSeries(codeBlocks, function(codeBlock, callback) { appendCodeBlockToFile(codeBlock, dir) .then(runCodeBlock) .then(function(codeBlock) { callback(null, codeBlock); }) .catch(function(err) { callback(err, null); }); }, convertAsyncResultToPromise(fulfill, reject)); }); }) .then(function(codeBlocks) { return removeOldDir(dir) .then(function() { return codeBlocks; }); }); }
javascript
function writeAndRunCodeBlocks(codeBlocks) { var dir = '.runnable-markdown-' + rand.generateKey(7); return makeTempDir(dir) .then(function() { return new Promise(function(fulfill, reject) { async.mapSeries(codeBlocks, function(codeBlock, callback) { appendCodeBlockToFile(codeBlock, dir) .then(runCodeBlock) .then(function(codeBlock) { callback(null, codeBlock); }) .catch(function(err) { callback(err, null); }); }, convertAsyncResultToPromise(fulfill, reject)); }); }) .then(function(codeBlocks) { return removeOldDir(dir) .then(function() { return codeBlocks; }); }); }
[ "function", "writeAndRunCodeBlocks", "(", "codeBlocks", ")", "{", "var", "dir", "=", "'.runnable-markdown-'", "+", "rand", ".", "generateKey", "(", "7", ")", ";", "return", "makeTempDir", "(", "dir", ")", ".", "then", "(", "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "async", ".", "mapSeries", "(", "codeBlocks", ",", "function", "(", "codeBlock", ",", "callback", ")", "{", "appendCodeBlockToFile", "(", "codeBlock", ",", "dir", ")", ".", "then", "(", "runCodeBlock", ")", ".", "then", "(", "function", "(", "codeBlock", ")", "{", "callback", "(", "null", ",", "codeBlock", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "}", ")", ";", "}", ",", "convertAsyncResultToPromise", "(", "fulfill", ",", "reject", ")", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "codeBlocks", ")", "{", "return", "removeOldDir", "(", "dir", ")", ".", "then", "(", "function", "(", ")", "{", "return", "codeBlocks", ";", "}", ")", ";", "}", ")", ";", "}" ]
Returns the same list of code blocks as what is passed in, but each filename includes the directory where it is stored.
[ "Returns", "the", "same", "list", "of", "code", "blocks", "as", "what", "is", "passed", "in", "but", "each", "filename", "includes", "the", "directory", "where", "it", "is", "stored", "." ]
22dd6270540f735608c1c5d562ee04675702beb7
https://github.com/carlwoodward/run-markdown/blob/22dd6270540f735608c1c5d562ee04675702beb7/index.js#L121-L144
train
carlwoodward/run-markdown
index.js
runCodeBlock
function runCodeBlock(codeBlock) { var dir = path.dirname(codeBlock.filename); return new Promise(function(fulfill, reject) { var filenameWithoutDir = codeBlock.filename.replace(dir + '/', ''); var command = runner(codeBlock, filenameWithoutDir); if (command === null) { fulfill(codeBlock); return; } exec(command, {cwd: dir}, function(error, stdout, stderr) { if (error) { console.error(error); reject(error); } else { if (stdout) { console.log(stdout); } if (stderr) { console.error(stderr); } fulfill(codeBlock); } }); }); }
javascript
function runCodeBlock(codeBlock) { var dir = path.dirname(codeBlock.filename); return new Promise(function(fulfill, reject) { var filenameWithoutDir = codeBlock.filename.replace(dir + '/', ''); var command = runner(codeBlock, filenameWithoutDir); if (command === null) { fulfill(codeBlock); return; } exec(command, {cwd: dir}, function(error, stdout, stderr) { if (error) { console.error(error); reject(error); } else { if (stdout) { console.log(stdout); } if (stderr) { console.error(stderr); } fulfill(codeBlock); } }); }); }
[ "function", "runCodeBlock", "(", "codeBlock", ")", "{", "var", "dir", "=", "path", ".", "dirname", "(", "codeBlock", ".", "filename", ")", ";", "return", "new", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "var", "filenameWithoutDir", "=", "codeBlock", ".", "filename", ".", "replace", "(", "dir", "+", "'/'", ",", "''", ")", ";", "var", "command", "=", "runner", "(", "codeBlock", ",", "filenameWithoutDir", ")", ";", "if", "(", "command", "===", "null", ")", "{", "fulfill", "(", "codeBlock", ")", ";", "return", ";", "}", "exec", "(", "command", ",", "{", "cwd", ":", "dir", "}", ",", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", ";", "reject", "(", "error", ")", ";", "}", "else", "{", "if", "(", "stdout", ")", "{", "console", ".", "log", "(", "stdout", ")", ";", "}", "if", "(", "stderr", ")", "{", "console", ".", "error", "(", "stderr", ")", ";", "}", "fulfill", "(", "codeBlock", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Runs a code block. Uses specially runners for files like Gemfile and package.json. Returns codeBlock.
[ "Runs", "a", "code", "block", ".", "Uses", "specially", "runners", "for", "files", "like", "Gemfile", "and", "package", ".", "json", ".", "Returns", "codeBlock", "." ]
22dd6270540f735608c1c5d562ee04675702beb7
https://github.com/carlwoodward/run-markdown/blob/22dd6270540f735608c1c5d562ee04675702beb7/index.js#L177-L201
train
jlas/quirky
game-client.js
countdownTimer
function countdownTimer() { $(COUNTDOWN).html("0m 0s"); var end_t = COUNTDOWNTIME; var start_t = (new Date()).getTime()/1000; function countdown() { var cur_t = (new Date()).getTime()/1000; var timeleft = (end_t - (cur_t - start_t)); if (timeleft >= 0) { var min = Math.floor(timeleft / 60); var sec = Math.floor(timeleft % 60); $(COUNTDOWN).html(min + "m " + sec + "s"); COUNTDOWNTID = setTimeout(countdown, 1000); } else { $.post("/games/" + enc($.cookie("game")) + "/players", {end_turn: true}, function() { getPlayers(); }); } } countdown(); }
javascript
function countdownTimer() { $(COUNTDOWN).html("0m 0s"); var end_t = COUNTDOWNTIME; var start_t = (new Date()).getTime()/1000; function countdown() { var cur_t = (new Date()).getTime()/1000; var timeleft = (end_t - (cur_t - start_t)); if (timeleft >= 0) { var min = Math.floor(timeleft / 60); var sec = Math.floor(timeleft % 60); $(COUNTDOWN).html(min + "m " + sec + "s"); COUNTDOWNTID = setTimeout(countdown, 1000); } else { $.post("/games/" + enc($.cookie("game")) + "/players", {end_turn: true}, function() { getPlayers(); }); } } countdown(); }
[ "function", "countdownTimer", "(", ")", "{", "$", "(", "COUNTDOWN", ")", ".", "html", "(", "\"0m 0s\"", ")", ";", "var", "end_t", "=", "COUNTDOWNTIME", ";", "var", "start_t", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "/", "1000", ";", "function", "countdown", "(", ")", "{", "var", "cur_t", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "/", "1000", ";", "var", "timeleft", "=", "(", "end_t", "-", "(", "cur_t", "-", "start_t", ")", ")", ";", "if", "(", "timeleft", ">=", "0", ")", "{", "var", "min", "=", "Math", ".", "floor", "(", "timeleft", "/", "60", ")", ";", "var", "sec", "=", "Math", ".", "floor", "(", "timeleft", "%", "60", ")", ";", "$", "(", "COUNTDOWN", ")", ".", "html", "(", "min", "+", "\"m \"", "+", "sec", "+", "\"s\"", ")", ";", "COUNTDOWNTID", "=", "setTimeout", "(", "countdown", ",", "1000", ")", ";", "}", "else", "{", "$", ".", "post", "(", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/players\"", ",", "{", "end_turn", ":", "true", "}", ",", "function", "(", ")", "{", "getPlayers", "(", ")", ";", "}", ")", ";", "}", "}", "countdown", "(", ")", ";", "}" ]
Countdown timer. Update onscreen timer and end turn if time gets too low.
[ "Countdown", "timer", ".", "Update", "onscreen", "timer", "and", "end", "turn", "if", "time", "gets", "too", "low", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L112-L132
train
jlas/quirky
game-client.js
drawTurnInfo
function drawTurnInfo(pdata) { var my_game = $.cookie("game"); var my_player = pdata[$.cookie("player")]; $(PIECES).empty(); $(ADDPIECE).show(); // allow player to end his turn if (my_player.has_turn) { $(ENDTURN).removeAttr('disabled'); $(TURN).html("It's your turn! You have " + "<span id='countdown'>0m 0s</span> left."); $(ENDTURN)[0].onclick = function() { $.post("/games/" + enc(my_game) + "/players", {end_turn: true}, function() { getPlayers(); /* Typically we let HAVETURN get updated from the server * in onGetPlayers(), but if there is only one player this * doesn't work very well (the player has to refresh manually). * So we force it to false here in this special case. */ if (Object.keys(pdata).length === 1) { HAVETURN = false; clearTimeout(COUNTDOWNTID); } }); }; } else { $(ENDTURN).attr('disabled', ''); $(TURN).html("It's not your turn."); } getPiecesLeft(); getBoard(); getMyPieces(my_player); }
javascript
function drawTurnInfo(pdata) { var my_game = $.cookie("game"); var my_player = pdata[$.cookie("player")]; $(PIECES).empty(); $(ADDPIECE).show(); // allow player to end his turn if (my_player.has_turn) { $(ENDTURN).removeAttr('disabled'); $(TURN).html("It's your turn! You have " + "<span id='countdown'>0m 0s</span> left."); $(ENDTURN)[0].onclick = function() { $.post("/games/" + enc(my_game) + "/players", {end_turn: true}, function() { getPlayers(); /* Typically we let HAVETURN get updated from the server * in onGetPlayers(), but if there is only one player this * doesn't work very well (the player has to refresh manually). * So we force it to false here in this special case. */ if (Object.keys(pdata).length === 1) { HAVETURN = false; clearTimeout(COUNTDOWNTID); } }); }; } else { $(ENDTURN).attr('disabled', ''); $(TURN).html("It's not your turn."); } getPiecesLeft(); getBoard(); getMyPieces(my_player); }
[ "function", "drawTurnInfo", "(", "pdata", ")", "{", "var", "my_game", "=", "$", ".", "cookie", "(", "\"game\"", ")", ";", "var", "my_player", "=", "pdata", "[", "$", ".", "cookie", "(", "\"player\"", ")", "]", ";", "$", "(", "PIECES", ")", ".", "empty", "(", ")", ";", "$", "(", "ADDPIECE", ")", ".", "show", "(", ")", ";", "if", "(", "my_player", ".", "has_turn", ")", "{", "$", "(", "ENDTURN", ")", ".", "removeAttr", "(", "'disabled'", ")", ";", "$", "(", "TURN", ")", ".", "html", "(", "\"It's your turn! You have \"", "+", "\"<span id='countdown'>0m 0s</span> left.\"", ")", ";", "$", "(", "ENDTURN", ")", "[", "0", "]", ".", "onclick", "=", "function", "(", ")", "{", "$", ".", "post", "(", "\"/games/\"", "+", "enc", "(", "my_game", ")", "+", "\"/players\"", ",", "{", "end_turn", ":", "true", "}", ",", "function", "(", ")", "{", "getPlayers", "(", ")", ";", "if", "(", "Object", ".", "keys", "(", "pdata", ")", ".", "length", "===", "1", ")", "{", "HAVETURN", "=", "false", ";", "clearTimeout", "(", "COUNTDOWNTID", ")", ";", "}", "}", ")", ";", "}", ";", "}", "else", "{", "$", "(", "ENDTURN", ")", ".", "attr", "(", "'disabled'", ",", "''", ")", ";", "$", "(", "TURN", ")", ".", "html", "(", "\"It's not your turn.\"", ")", ";", "}", "getPiecesLeft", "(", ")", ";", "getBoard", "(", ")", ";", "getMyPieces", "(", "my_player", ")", ";", "}" ]
Draw player's pieces and It's Your Turn info. @param {obj} pdata json data from the server
[ "Draw", "player", "s", "pieces", "and", "It", "s", "Your", "Turn", "info", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L181-L215
train
jlas/quirky
game-client.js
getMyPieces
function getMyPieces(player) { for (var i in player.pieces) { var piece = player.pieces[i]; $(PIECES).append('<div class="piece" style="color:'+ pastels[piece.color]+'">'+ushapes[piece.shape]+'</div>'); $(PIECECLS+":last-child").data("piece", piece); $(PIECES).append("<div style='float: left; margin: 3px'></div>"); } function setDimensions() { $(PIECECLS).width($(GRIDCLS).width()); $(PIECECLS).height($(GRIDCLS).height()); var fontsize = $(GRIDCLS).css("font-size"); $(PIECECLS).css("font-size", fontsize); $(PIECECLS).css("line-height", fontsize); } /* Style switching is flaky here, we're depending on the width that was set * in getBoard() and maybe that happens too fast sometimes. So we add a * setTimeout to try setting dimensions again in a short while. */ setDimensions(); setTimeout(setDimensions, 250); if (player.has_turn) $(PIECECLS).draggable({ containment: "#board", snap: ".snapgrid" }); }
javascript
function getMyPieces(player) { for (var i in player.pieces) { var piece = player.pieces[i]; $(PIECES).append('<div class="piece" style="color:'+ pastels[piece.color]+'">'+ushapes[piece.shape]+'</div>'); $(PIECECLS+":last-child").data("piece", piece); $(PIECES).append("<div style='float: left; margin: 3px'></div>"); } function setDimensions() { $(PIECECLS).width($(GRIDCLS).width()); $(PIECECLS).height($(GRIDCLS).height()); var fontsize = $(GRIDCLS).css("font-size"); $(PIECECLS).css("font-size", fontsize); $(PIECECLS).css("line-height", fontsize); } /* Style switching is flaky here, we're depending on the width that was set * in getBoard() and maybe that happens too fast sometimes. So we add a * setTimeout to try setting dimensions again in a short while. */ setDimensions(); setTimeout(setDimensions, 250); if (player.has_turn) $(PIECECLS).draggable({ containment: "#board", snap: ".snapgrid" }); }
[ "function", "getMyPieces", "(", "player", ")", "{", "for", "(", "var", "i", "in", "player", ".", "pieces", ")", "{", "var", "piece", "=", "player", ".", "pieces", "[", "i", "]", ";", "$", "(", "PIECES", ")", ".", "append", "(", "'<div class=\"piece\" style=\"color:'", "+", "pastels", "[", "piece", ".", "color", "]", "+", "'\">'", "+", "ushapes", "[", "piece", ".", "shape", "]", "+", "'</div>'", ")", ";", "$", "(", "PIECECLS", "+", "\":last-child\"", ")", ".", "data", "(", "\"piece\"", ",", "piece", ")", ";", "$", "(", "PIECES", ")", ".", "append", "(", "\"<div style='float: left; margin: 3px'></div>\"", ")", ";", "}", "function", "setDimensions", "(", ")", "{", "$", "(", "PIECECLS", ")", ".", "width", "(", "$", "(", "GRIDCLS", ")", ".", "width", "(", ")", ")", ";", "$", "(", "PIECECLS", ")", ".", "height", "(", "$", "(", "GRIDCLS", ")", ".", "height", "(", ")", ")", ";", "var", "fontsize", "=", "$", "(", "GRIDCLS", ")", ".", "css", "(", "\"font-size\"", ")", ";", "$", "(", "PIECECLS", ")", ".", "css", "(", "\"font-size\"", ",", "fontsize", ")", ";", "$", "(", "PIECECLS", ")", ".", "css", "(", "\"line-height\"", ",", "fontsize", ")", ";", "}", "setDimensions", "(", ")", ";", "setTimeout", "(", "setDimensions", ",", "250", ")", ";", "if", "(", "player", ".", "has_turn", ")", "$", "(", "PIECECLS", ")", ".", "draggable", "(", "{", "containment", ":", "\"#board\"", ",", "snap", ":", "\".snapgrid\"", "}", ")", ";", "}" ]
Add player's pieces to his sideboard and make active if it's his turn. @param {obj} player
[ "Add", "player", "s", "pieces", "to", "his", "sideboard", "and", "make", "active", "if", "it", "s", "his", "turn", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L221-L249
train
jlas/quirky
game-client.js
getPiecesLeft
function getPiecesLeft() { $.getJSON("/games/" + enc($.cookie("game")) + "/pieces", function(data) { $(GAMEPIECES).empty(); var npieces = 0; for (var i in data) npieces += data[i].count; $(GAMEPIECES).html(npieces); }); }
javascript
function getPiecesLeft() { $.getJSON("/games/" + enc($.cookie("game")) + "/pieces", function(data) { $(GAMEPIECES).empty(); var npieces = 0; for (var i in data) npieces += data[i].count; $(GAMEPIECES).html(npieces); }); }
[ "function", "getPiecesLeft", "(", ")", "{", "$", ".", "getJSON", "(", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/pieces\"", ",", "function", "(", "data", ")", "{", "$", "(", "GAMEPIECES", ")", ".", "empty", "(", ")", ";", "var", "npieces", "=", "0", ";", "for", "(", "var", "i", "in", "data", ")", "npieces", "+=", "data", "[", "i", "]", ".", "count", ";", "$", "(", "GAMEPIECES", ")", ".", "html", "(", "npieces", ")", ";", "}", ")", ";", "}" ]
Publish the number of pieces left in the bag.
[ "Publish", "the", "number", "of", "pieces", "left", "in", "the", "bag", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L254-L263
train
jlas/quirky
game-client.js
onPieceDrop
function onPieceDrop(event, ui) { var col = $(this).data().col; var row = $(this).data().row; var piece = $(ui.draggable).data().piece; $.ajax({ type: 'POST', url: "/games/" + enc($.cookie("game")) + "/board", data: { shape: piece.shape, color: piece.color, row: row, column: col }, success: function() { $(ERRORS).empty(); }, error: function (jqXHR, textStatus, errorThrown) { $(ERRORS).empty(); $(ERRORS).append("<div class='error'>&#9888; "+jqXHR.responseText+"</div>"); }, complete: function() { $.getJSON("/games/" + enc($.cookie("game")) + "/players", drawTurnInfo); } }); }
javascript
function onPieceDrop(event, ui) { var col = $(this).data().col; var row = $(this).data().row; var piece = $(ui.draggable).data().piece; $.ajax({ type: 'POST', url: "/games/" + enc($.cookie("game")) + "/board", data: { shape: piece.shape, color: piece.color, row: row, column: col }, success: function() { $(ERRORS).empty(); }, error: function (jqXHR, textStatus, errorThrown) { $(ERRORS).empty(); $(ERRORS).append("<div class='error'>&#9888; "+jqXHR.responseText+"</div>"); }, complete: function() { $.getJSON("/games/" + enc($.cookie("game")) + "/players", drawTurnInfo); } }); }
[ "function", "onPieceDrop", "(", "event", ",", "ui", ")", "{", "var", "col", "=", "$", "(", "this", ")", ".", "data", "(", ")", ".", "col", ";", "var", "row", "=", "$", "(", "this", ")", ".", "data", "(", ")", ".", "row", ";", "var", "piece", "=", "$", "(", "ui", ".", "draggable", ")", ".", "data", "(", ")", ".", "piece", ";", "$", ".", "ajax", "(", "{", "type", ":", "'POST'", ",", "url", ":", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/board\"", ",", "data", ":", "{", "shape", ":", "piece", ".", "shape", ",", "color", ":", "piece", ".", "color", ",", "row", ":", "row", ",", "column", ":", "col", "}", ",", "success", ":", "function", "(", ")", "{", "$", "(", "ERRORS", ")", ".", "empty", "(", ")", ";", "}", ",", "error", ":", "function", "(", "jqXHR", ",", "textStatus", ",", "errorThrown", ")", "{", "$", "(", "ERRORS", ")", ".", "empty", "(", ")", ";", "$", "(", "ERRORS", ")", ".", "append", "(", "\"<div class='error'>&#9888; \"", "+", "jqXHR", ".", "responseText", "+", "\"</div>\"", ")", ";", "}", ",", "complete", ":", "function", "(", ")", "{", "$", ".", "getJSON", "(", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/players\"", ",", "drawTurnInfo", ")", ";", "}", "}", ")", ";", "}" ]
When piece is dropped, send a POST to the server to add to board. Either the piece will be added or we get an error back for invalid placements.
[ "When", "piece", "is", "dropped", "send", "a", "POST", "to", "the", "server", "to", "add", "to", "board", ".", "Either", "the", "piece", "will", "be", "added", "or", "we", "get", "an", "error", "back", "for", "invalid", "placements", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L269-L294
train
jlas/quirky
game-client.js
drawChatIn
function drawChatIn() { $(CHATIN).show(); function submit() { var chatin = $(CHATIN+"> input")[0].value; if (!CHATRE.test(chatin)) { if(chatin) { alert("Your input text is too long!"); } return false; } var game = $.cookie("game"); var resource; if (game) { resource = "/games/" + enc(game) + "/chat"; } else { resource = "/chat"; } $.post(resource, { input: chatin, name: $.cookie("player") }, function() { $(CHATIN+"> input").val(''); // post was succesful, so clear input drawChatLog(); }); } $(CHATIN+"> button").click(submit); $(CHATIN+"> input:visible").focus(); $(CHATIN+"> input").keydown(function(event) { if (event.keyCode === 13) { submit(); } }); }
javascript
function drawChatIn() { $(CHATIN).show(); function submit() { var chatin = $(CHATIN+"> input")[0].value; if (!CHATRE.test(chatin)) { if(chatin) { alert("Your input text is too long!"); } return false; } var game = $.cookie("game"); var resource; if (game) { resource = "/games/" + enc(game) + "/chat"; } else { resource = "/chat"; } $.post(resource, { input: chatin, name: $.cookie("player") }, function() { $(CHATIN+"> input").val(''); // post was succesful, so clear input drawChatLog(); }); } $(CHATIN+"> button").click(submit); $(CHATIN+"> input:visible").focus(); $(CHATIN+"> input").keydown(function(event) { if (event.keyCode === 13) { submit(); } }); }
[ "function", "drawChatIn", "(", ")", "{", "$", "(", "CHATIN", ")", ".", "show", "(", ")", ";", "function", "submit", "(", ")", "{", "var", "chatin", "=", "$", "(", "CHATIN", "+", "\"> input\"", ")", "[", "0", "]", ".", "value", ";", "if", "(", "!", "CHATRE", ".", "test", "(", "chatin", ")", ")", "{", "if", "(", "chatin", ")", "{", "alert", "(", "\"Your input text is too long!\"", ")", ";", "}", "return", "false", ";", "}", "var", "game", "=", "$", ".", "cookie", "(", "\"game\"", ")", ";", "var", "resource", ";", "if", "(", "game", ")", "{", "resource", "=", "\"/games/\"", "+", "enc", "(", "game", ")", "+", "\"/chat\"", ";", "}", "else", "{", "resource", "=", "\"/chat\"", ";", "}", "$", ".", "post", "(", "resource", ",", "{", "input", ":", "chatin", ",", "name", ":", "$", ".", "cookie", "(", "\"player\"", ")", "}", ",", "function", "(", ")", "{", "$", "(", "CHATIN", "+", "\"> input\"", ")", ".", "val", "(", "''", ")", ";", "drawChatLog", "(", ")", ";", "}", ")", ";", "}", "$", "(", "CHATIN", "+", "\"> button\"", ")", ".", "click", "(", "submit", ")", ";", "$", "(", "CHATIN", "+", "\"> input:visible\"", ")", ".", "focus", "(", ")", ";", "$", "(", "CHATIN", "+", "\"> input\"", ")", ".", "keydown", "(", "function", "(", "event", ")", "{", "if", "(", "event", ".", "keyCode", "===", "13", ")", "{", "submit", "(", ")", ";", "}", "}", ")", ";", "}" ]
Draw the chat input.
[ "Draw", "the", "chat", "input", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L400-L432
train
jlas/quirky
game-client.js
drawAddGuest
function drawAddGuest() { $(ADDGUEST).show(); function submit() { var name = $(ADDGUESTFRM+"> input")[0].value; if (!NAMERE.test(name)) { if(name) { alert("Your input text is too long!"); } return false; } $.cookie("player", name); main(); } $(ADDGUESTFRM+"> button").click(submit); $(ADDGUESTFRM+"> input:visible").focus(); $(ADDGUESTFRM+"> input").keydown(function(event) { if (event.keyCode === 13) { submit(); } }); }
javascript
function drawAddGuest() { $(ADDGUEST).show(); function submit() { var name = $(ADDGUESTFRM+"> input")[0].value; if (!NAMERE.test(name)) { if(name) { alert("Your input text is too long!"); } return false; } $.cookie("player", name); main(); } $(ADDGUESTFRM+"> button").click(submit); $(ADDGUESTFRM+"> input:visible").focus(); $(ADDGUESTFRM+"> input").keydown(function(event) { if (event.keyCode === 13) { submit(); } }); }
[ "function", "drawAddGuest", "(", ")", "{", "$", "(", "ADDGUEST", ")", ".", "show", "(", ")", ";", "function", "submit", "(", ")", "{", "var", "name", "=", "$", "(", "ADDGUESTFRM", "+", "\"> input\"", ")", "[", "0", "]", ".", "value", ";", "if", "(", "!", "NAMERE", ".", "test", "(", "name", ")", ")", "{", "if", "(", "name", ")", "{", "alert", "(", "\"Your input text is too long!\"", ")", ";", "}", "return", "false", ";", "}", "$", ".", "cookie", "(", "\"player\"", ",", "name", ")", ";", "main", "(", ")", ";", "}", "$", "(", "ADDGUESTFRM", "+", "\"> button\"", ")", ".", "click", "(", "submit", ")", ";", "$", "(", "ADDGUESTFRM", "+", "\"> input:visible\"", ")", ".", "focus", "(", ")", ";", "$", "(", "ADDGUESTFRM", "+", "\"> input\"", ")", ".", "keydown", "(", "function", "(", "event", ")", "{", "if", "(", "event", ".", "keyCode", "===", "13", ")", "{", "submit", "(", ")", ";", "}", "}", ")", ";", "}" ]
Draw the add guest widget. - Set the player cookie when the user submits and switch to displaying the chat input.
[ "Draw", "the", "add", "guest", "widget", ".", "-", "Set", "the", "player", "cookie", "when", "the", "user", "submits", "and", "switch", "to", "displaying", "the", "chat", "input", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L439-L460
train
jlas/quirky
game-client.js
drawLobby
function drawLobby(games) { $(LOBBYCHAT).append($(CHATPNL)[0]); $(CHATPNL).addClass('lobby_chat_panel'); drawGameList(games); // setup future calls to get game list function pollGames() { $.getJSON("/games", drawGameList); GETGAMESTID = setTimeout(pollGames, 2000); } GETGAMESTID = setTimeout(pollGames, 2000); }
javascript
function drawLobby(games) { $(LOBBYCHAT).append($(CHATPNL)[0]); $(CHATPNL).addClass('lobby_chat_panel'); drawGameList(games); // setup future calls to get game list function pollGames() { $.getJSON("/games", drawGameList); GETGAMESTID = setTimeout(pollGames, 2000); } GETGAMESTID = setTimeout(pollGames, 2000); }
[ "function", "drawLobby", "(", "games", ")", "{", "$", "(", "LOBBYCHAT", ")", ".", "append", "(", "$", "(", "CHATPNL", ")", "[", "0", "]", ")", ";", "$", "(", "CHATPNL", ")", ".", "addClass", "(", "'lobby_chat_panel'", ")", ";", "drawGameList", "(", "games", ")", ";", "function", "pollGames", "(", ")", "{", "$", ".", "getJSON", "(", "\"/games\"", ",", "drawGameList", ")", ";", "GETGAMESTID", "=", "setTimeout", "(", "pollGames", ",", "2000", ")", ";", "}", "GETGAMESTID", "=", "setTimeout", "(", "pollGames", ",", "2000", ")", ";", "}" ]
Draw the lobby.
[ "Draw", "the", "lobby", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L588-L599
train
jlas/quirky
game-client.js
drawGame
function drawGame() { getPlayers(); getBoard(); getPiecesLeft(); $(SIDEBOARD).append("<hr/>"); $(SIDEBOARD).append($(CHATPNL)); $(CHATPNL).addClass('game_chat_panel'); $(LEAVEGAME)[0].onclick = function () { clearTimeout(GETPLAYERSTID); $.ajax({ type: 'DELETE', url: "/games/" + enc($.cookie("game")) + "/players", data: {name: $.cookie("player")}, success: function() { $.removeCookie('game'); location.reload(); } }); }; // setup future calls function pollPlayers() { getPlayers(); GETPLAYERSTID = setTimeout(pollPlayers, 2000); } GETPLAYERSTID = setTimeout(pollPlayers, 2000); }
javascript
function drawGame() { getPlayers(); getBoard(); getPiecesLeft(); $(SIDEBOARD).append("<hr/>"); $(SIDEBOARD).append($(CHATPNL)); $(CHATPNL).addClass('game_chat_panel'); $(LEAVEGAME)[0].onclick = function () { clearTimeout(GETPLAYERSTID); $.ajax({ type: 'DELETE', url: "/games/" + enc($.cookie("game")) + "/players", data: {name: $.cookie("player")}, success: function() { $.removeCookie('game'); location.reload(); } }); }; // setup future calls function pollPlayers() { getPlayers(); GETPLAYERSTID = setTimeout(pollPlayers, 2000); } GETPLAYERSTID = setTimeout(pollPlayers, 2000); }
[ "function", "drawGame", "(", ")", "{", "getPlayers", "(", ")", ";", "getBoard", "(", ")", ";", "getPiecesLeft", "(", ")", ";", "$", "(", "SIDEBOARD", ")", ".", "append", "(", "\"<hr/>\"", ")", ";", "$", "(", "SIDEBOARD", ")", ".", "append", "(", "$", "(", "CHATPNL", ")", ")", ";", "$", "(", "CHATPNL", ")", ".", "addClass", "(", "'game_chat_panel'", ")", ";", "$", "(", "LEAVEGAME", ")", "[", "0", "]", ".", "onclick", "=", "function", "(", ")", "{", "clearTimeout", "(", "GETPLAYERSTID", ")", ";", "$", ".", "ajax", "(", "{", "type", ":", "'DELETE'", ",", "url", ":", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/players\"", ",", "data", ":", "{", "name", ":", "$", ".", "cookie", "(", "\"player\"", ")", "}", ",", "success", ":", "function", "(", ")", "{", "$", ".", "removeCookie", "(", "'game'", ")", ";", "location", ".", "reload", "(", ")", ";", "}", "}", ")", ";", "}", ";", "function", "pollPlayers", "(", ")", "{", "getPlayers", "(", ")", ";", "GETPLAYERSTID", "=", "setTimeout", "(", "pollPlayers", ",", "2000", ")", ";", "}", "GETPLAYERSTID", "=", "setTimeout", "(", "pollPlayers", ",", "2000", ")", ";", "}" ]
Draw the game.
[ "Draw", "the", "game", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L604-L630
train
jlas/quirky
game-client.js
gameOrLobby
function gameOrLobby(games) { $(LOBBY).hide(); $(GAMEROOM).hide(); $(ADDGUEST).hide(); if (!$.cookie("player")) { drawAddGuest(); return; } // hide the fork me banner from now on $(FORKME).hide(); var my_game = $.cookie("game"); // User is not in a valid game if (typeof games[my_game] === 'undefined') { $.removeCookie('game'); $(LOBBY).show(); drawLobby(games); } else { $(GAMEROOM).show(); drawGame(); } $(CHATPNL).show(); drawChatLog(); drawChatIn(); // setup future calls to get chat function pollChat() { drawChatLog(); DRAWCHATTID = setTimeout(pollChat, 2000); } DRAWCHATTID = setTimeout(pollChat, 2000); }
javascript
function gameOrLobby(games) { $(LOBBY).hide(); $(GAMEROOM).hide(); $(ADDGUEST).hide(); if (!$.cookie("player")) { drawAddGuest(); return; } // hide the fork me banner from now on $(FORKME).hide(); var my_game = $.cookie("game"); // User is not in a valid game if (typeof games[my_game] === 'undefined') { $.removeCookie('game'); $(LOBBY).show(); drawLobby(games); } else { $(GAMEROOM).show(); drawGame(); } $(CHATPNL).show(); drawChatLog(); drawChatIn(); // setup future calls to get chat function pollChat() { drawChatLog(); DRAWCHATTID = setTimeout(pollChat, 2000); } DRAWCHATTID = setTimeout(pollChat, 2000); }
[ "function", "gameOrLobby", "(", "games", ")", "{", "$", "(", "LOBBY", ")", ".", "hide", "(", ")", ";", "$", "(", "GAMEROOM", ")", ".", "hide", "(", ")", ";", "$", "(", "ADDGUEST", ")", ".", "hide", "(", ")", ";", "if", "(", "!", "$", ".", "cookie", "(", "\"player\"", ")", ")", "{", "drawAddGuest", "(", ")", ";", "return", ";", "}", "$", "(", "FORKME", ")", ".", "hide", "(", ")", ";", "var", "my_game", "=", "$", ".", "cookie", "(", "\"game\"", ")", ";", "if", "(", "typeof", "games", "[", "my_game", "]", "===", "'undefined'", ")", "{", "$", ".", "removeCookie", "(", "'game'", ")", ";", "$", "(", "LOBBY", ")", ".", "show", "(", ")", ";", "drawLobby", "(", "games", ")", ";", "}", "else", "{", "$", "(", "GAMEROOM", ")", ".", "show", "(", ")", ";", "drawGame", "(", ")", ";", "}", "$", "(", "CHATPNL", ")", ".", "show", "(", ")", ";", "drawChatLog", "(", ")", ";", "drawChatIn", "(", ")", ";", "function", "pollChat", "(", ")", "{", "drawChatLog", "(", ")", ";", "DRAWCHATTID", "=", "setTimeout", "(", "pollChat", ",", "2000", ")", ";", "}", "DRAWCHATTID", "=", "setTimeout", "(", "pollChat", ",", "2000", ")", ";", "}" ]
Display the lobby, a game room, or the add guest for the user.
[ "Display", "the", "lobby", "a", "game", "room", "or", "the", "add", "guest", "for", "the", "user", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L635-L668
train
WindomZ/fmtconv
lib/converter.js
fmtconv
function fmtconv (input, output, compact = false) { if (!input) { throw new TypeError('"input" argument must be a file path') } else if (!output) { throw new TypeError('"output" argument must be a file path') } let extInput = path.extname(input).toLowerCase() if (extInput !== '.yaml' && extInput !== '.yml' && extInput !== '.json') { throw new TypeError('"input" file extension must be ".yaml" or ".yml" or ".json"') } let extOutput = path.extname(output).toLowerCase() if (extOutput !== '.yaml' && extOutput !== '.yml' && extOutput !== '.json') { throw new TypeError('"output" file extension must be ".yaml" or ".yml" or ".json"') } fs.accessSync(input, fs.R_OK) let doc = '' + fs.readFileSync(input) switch (extInput) { case '.yaml': case '.yml': switch (extOutput) { case '.json': fs.writeFileSync(output, transcode.stringYAML2JSON(doc, compact), null) break default: fs.writeFileSync(output, transcode.stringYAML2YAML(doc, compact), null) break } break case '.json': switch (extOutput) { case '.yaml': case '.yml': fs.writeFileSync(output, transcode.stringJSON2YAML(doc, compact), null) break default: fs.writeFileSync(output, transcode.stringJSON2JSON(doc, compact), null) break } break } }
javascript
function fmtconv (input, output, compact = false) { if (!input) { throw new TypeError('"input" argument must be a file path') } else if (!output) { throw new TypeError('"output" argument must be a file path') } let extInput = path.extname(input).toLowerCase() if (extInput !== '.yaml' && extInput !== '.yml' && extInput !== '.json') { throw new TypeError('"input" file extension must be ".yaml" or ".yml" or ".json"') } let extOutput = path.extname(output).toLowerCase() if (extOutput !== '.yaml' && extOutput !== '.yml' && extOutput !== '.json') { throw new TypeError('"output" file extension must be ".yaml" or ".yml" or ".json"') } fs.accessSync(input, fs.R_OK) let doc = '' + fs.readFileSync(input) switch (extInput) { case '.yaml': case '.yml': switch (extOutput) { case '.json': fs.writeFileSync(output, transcode.stringYAML2JSON(doc, compact), null) break default: fs.writeFileSync(output, transcode.stringYAML2YAML(doc, compact), null) break } break case '.json': switch (extOutput) { case '.yaml': case '.yml': fs.writeFileSync(output, transcode.stringJSON2YAML(doc, compact), null) break default: fs.writeFileSync(output, transcode.stringJSON2JSON(doc, compact), null) break } break } }
[ "function", "fmtconv", "(", "input", ",", "output", ",", "compact", "=", "false", ")", "{", "if", "(", "!", "input", ")", "{", "throw", "new", "TypeError", "(", "'\"input\" argument must be a file path'", ")", "}", "else", "if", "(", "!", "output", ")", "{", "throw", "new", "TypeError", "(", "'\"output\" argument must be a file path'", ")", "}", "let", "extInput", "=", "path", ".", "extname", "(", "input", ")", ".", "toLowerCase", "(", ")", "if", "(", "extInput", "!==", "'.yaml'", "&&", "extInput", "!==", "'.yml'", "&&", "extInput", "!==", "'.json'", ")", "{", "throw", "new", "TypeError", "(", "'\"input\" file extension must be \".yaml\" or \".yml\" or \".json\"'", ")", "}", "let", "extOutput", "=", "path", ".", "extname", "(", "output", ")", ".", "toLowerCase", "(", ")", "if", "(", "extOutput", "!==", "'.yaml'", "&&", "extOutput", "!==", "'.yml'", "&&", "extOutput", "!==", "'.json'", ")", "{", "throw", "new", "TypeError", "(", "'\"output\" file extension must be \".yaml\" or \".yml\" or \".json\"'", ")", "}", "fs", ".", "accessSync", "(", "input", ",", "fs", ".", "R_OK", ")", "let", "doc", "=", "''", "+", "fs", ".", "readFileSync", "(", "input", ")", "switch", "(", "extInput", ")", "{", "case", "'.yaml'", ":", "case", "'.yml'", ":", "switch", "(", "extOutput", ")", "{", "case", "'.json'", ":", "fs", ".", "writeFileSync", "(", "output", ",", "transcode", ".", "stringYAML2JSON", "(", "doc", ",", "compact", ")", ",", "null", ")", "break", "default", ":", "fs", ".", "writeFileSync", "(", "output", ",", "transcode", ".", "stringYAML2YAML", "(", "doc", ",", "compact", ")", ",", "null", ")", "break", "}", "break", "case", "'.json'", ":", "switch", "(", "extOutput", ")", "{", "case", "'.yaml'", ":", "case", "'.yml'", ":", "fs", ".", "writeFileSync", "(", "output", ",", "transcode", ".", "stringJSON2YAML", "(", "doc", ",", "compact", ")", ",", "null", ")", "break", "default", ":", "fs", ".", "writeFileSync", "(", "output", ",", "transcode", ".", "stringJSON2JSON", "(", "doc", ",", "compact", ")", ",", "null", ")", "break", "}", "break", "}", "}" ]
Convert between JSON and YAML format files. @param {string} input @param {string} output @param {boolean} [compact] @api public
[ "Convert", "between", "JSON", "and", "YAML", "format", "files", "." ]
80923dc9d63714a92bac2f7d4f412a2b46c063a1
https://github.com/WindomZ/fmtconv/blob/80923dc9d63714a92bac2f7d4f412a2b46c063a1/lib/converter.js#L19-L64
train
andrglo/mssql-cr-layer
src/index.js
MssqlCrLayer
function MssqlCrLayer(config) { if (!(this instanceof MssqlCrLayer)) { return new MssqlCrLayer(config) } const mssqlConfig = toMssqlConfig(config) connectionParams.set(this, mssqlConfig) this.user = mssqlConfig.user this.database = mssqlConfig.database this.host = mssqlConfig.server this.port = mssqlConfig.port this.ISOLATION_LEVEL = (config && config.ISOLATION_LEVEL) || 'READ_COMMITTED' }
javascript
function MssqlCrLayer(config) { if (!(this instanceof MssqlCrLayer)) { return new MssqlCrLayer(config) } const mssqlConfig = toMssqlConfig(config) connectionParams.set(this, mssqlConfig) this.user = mssqlConfig.user this.database = mssqlConfig.database this.host = mssqlConfig.server this.port = mssqlConfig.port this.ISOLATION_LEVEL = (config && config.ISOLATION_LEVEL) || 'READ_COMMITTED' }
[ "function", "MssqlCrLayer", "(", "config", ")", "{", "if", "(", "!", "(", "this", "instanceof", "MssqlCrLayer", ")", ")", "{", "return", "new", "MssqlCrLayer", "(", "config", ")", "}", "const", "mssqlConfig", "=", "toMssqlConfig", "(", "config", ")", "connectionParams", ".", "set", "(", "this", ",", "mssqlConfig", ")", "this", ".", "user", "=", "mssqlConfig", ".", "user", "this", ".", "database", "=", "mssqlConfig", ".", "database", "this", ".", "host", "=", "mssqlConfig", ".", "server", "this", ".", "port", "=", "mssqlConfig", ".", "port", "this", ".", "ISOLATION_LEVEL", "=", "(", "config", "&&", "config", ".", "ISOLATION_LEVEL", ")", "||", "'READ_COMMITTED'", "}" ]
SQL Server common requests interface layer @param config {object} user: <username>, password: <password>, host: <host>, pool: { max: <max pool size>, idleTimeout: <idle timeout in milliseconds> } @returns {MssqlCrLayer} @constructor
[ "SQL", "Server", "common", "requests", "interface", "layer" ]
59d3f45a9a8a5bd93053a652c72df5dbf61833b6
https://github.com/andrglo/mssql-cr-layer/blob/59d3f45a9a8a5bd93053a652c72df5dbf61833b6/src/index.js#L25-L36
train
dreampiggy/functional.js
Retroactive/lib/data_structures/graph.js
Graph
function Graph(directed) { this.directed = (directed === undefined ? true : !!directed); this.adjList = Object.create(null); this.vertices = new HashSet(); }
javascript
function Graph(directed) { this.directed = (directed === undefined ? true : !!directed); this.adjList = Object.create(null); this.vertices = new HashSet(); }
[ "function", "Graph", "(", "directed", ")", "{", "this", ".", "directed", "=", "(", "directed", "===", "undefined", "?", "true", ":", "!", "!", "directed", ")", ";", "this", ".", "adjList", "=", "Object", ".", "create", "(", "null", ")", ";", "this", ".", "vertices", "=", "new", "HashSet", "(", ")", ";", "}" ]
Adjacency list representation of a graph @param {bool} directed
[ "Adjacency", "list", "representation", "of", "a", "graph" ]
ec7b7213de7965659a8a1e8fa61438e3ae564260
https://github.com/dreampiggy/functional.js/blob/ec7b7213de7965659a8a1e8fa61438e3ae564260/Retroactive/lib/data_structures/graph.js#L9-L13
train
KodersLab/react-native-for-web-stylesheet
lib/storage.js
pick
function pick(propName, propValue) { var possibleClassIds = Object.keys(storage[propName] || {}).filter(function (classId) { return (0, _lodash2.default)(storage[propName][classId], propValue); }); return possibleClassIds.length > 0 ? parseInt(possibleClassIds[0], 10) : null; }
javascript
function pick(propName, propValue) { var possibleClassIds = Object.keys(storage[propName] || {}).filter(function (classId) { return (0, _lodash2.default)(storage[propName][classId], propValue); }); return possibleClassIds.length > 0 ? parseInt(possibleClassIds[0], 10) : null; }
[ "function", "pick", "(", "propName", ",", "propValue", ")", "{", "var", "possibleClassIds", "=", "Object", ".", "keys", "(", "storage", "[", "propName", "]", "||", "{", "}", ")", ".", "filter", "(", "function", "(", "classId", ")", "{", "return", "(", "0", ",", "_lodash2", ".", "default", ")", "(", "storage", "[", "propName", "]", "[", "classId", "]", ",", "propValue", ")", ";", "}", ")", ";", "return", "possibleClassIds", ".", "length", ">", "0", "?", "parseInt", "(", "possibleClassIds", "[", "0", "]", ",", "10", ")", ":", "null", ";", "}" ]
get the classId
[ "get", "the", "classId" ]
963c70925aa8d3d6581c40afcccb3be31bf257b8
https://github.com/KodersLab/react-native-for-web-stylesheet/blob/963c70925aa8d3d6581c40afcccb3be31bf257b8/lib/storage.js#L20-L26
train
KodersLab/react-native-for-web-stylesheet
lib/storage.js
put
function put(propName, propValue, classId) { if (pick(propName, propValue)) return false; if (!classId) { nextClassId++; classId = nextClassId; } nextClassId = nextClassId < classId ? classId : nextClassId; storage[propName] = storage[propName] || {}; storage[propName][classId] = propValue; return true; }
javascript
function put(propName, propValue, classId) { if (pick(propName, propValue)) return false; if (!classId) { nextClassId++; classId = nextClassId; } nextClassId = nextClassId < classId ? classId : nextClassId; storage[propName] = storage[propName] || {}; storage[propName][classId] = propValue; return true; }
[ "function", "put", "(", "propName", ",", "propValue", ",", "classId", ")", "{", "if", "(", "pick", "(", "propName", ",", "propValue", ")", ")", "return", "false", ";", "if", "(", "!", "classId", ")", "{", "nextClassId", "++", ";", "classId", "=", "nextClassId", ";", "}", "nextClassId", "=", "nextClassId", "<", "classId", "?", "classId", ":", "nextClassId", ";", "storage", "[", "propName", "]", "=", "storage", "[", "propName", "]", "||", "{", "}", ";", "storage", "[", "propName", "]", "[", "classId", "]", "=", "propValue", ";", "return", "true", ";", "}" ]
sets the classId
[ "sets", "the", "classId" ]
963c70925aa8d3d6581c40afcccb3be31bf257b8
https://github.com/KodersLab/react-native-for-web-stylesheet/blob/963c70925aa8d3d6581c40afcccb3be31bf257b8/lib/storage.js#L29-L43
train
ben-eb/postcss-font-family
index.js
removeAfterKeyword
function removeAfterKeyword () { var hasKeyword = false; return function (family) { if (~keywords.indexOf(family)) { hasKeyword = true; return true; } return !hasKeyword; }; }
javascript
function removeAfterKeyword () { var hasKeyword = false; return function (family) { if (~keywords.indexOf(family)) { hasKeyword = true; return true; } return !hasKeyword; }; }
[ "function", "removeAfterKeyword", "(", ")", "{", "var", "hasKeyword", "=", "false", ";", "return", "function", "(", "family", ")", "{", "if", "(", "~", "keywords", ".", "indexOf", "(", "family", ")", ")", "{", "hasKeyword", "=", "true", ";", "return", "true", ";", "}", "return", "!", "hasKeyword", ";", "}", ";", "}" ]
No point in keeping the rest of the declaration after a keyword
[ "No", "point", "in", "keeping", "the", "rest", "of", "the", "declaration", "after", "a", "keyword" ]
22cb5bc3efc892b93e50763c5e07ce519e7eb453
https://github.com/ben-eb/postcss-font-family/blob/22cb5bc3efc892b93e50763c5e07ce519e7eb453/index.js#L22-L31
train
gdbots/common-js
src/isValidUri.js
urlStyleUriRegex
function urlStyleUriRegex() { const protocol = '(?:[A-Za-z]{3,9}://)'; const auth = '(?:\\S+(?::\\S*)?@)?'; const ipv4 = '(?:\\[?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\]?'; const host = '(?:(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)'; const domain = '(?:\\.(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)*'; const tld = '(?:\\.(?:[a-zA-Z]{2,}))\\.?'; const port = '(?::\\d{2,5})?'; const path = '(?:[/?#][\\x21-\\x7F]*)?'; // ascii no whitespaces const regex = `(?:${protocol}|www\\.)${auth}(?:localhost|${ipv4}|${host}${domain}${tld})${port}${path}`; return new RegExp(`^${regex}$`, 'i'); }
javascript
function urlStyleUriRegex() { const protocol = '(?:[A-Za-z]{3,9}://)'; const auth = '(?:\\S+(?::\\S*)?@)?'; const ipv4 = '(?:\\[?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\]?'; const host = '(?:(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)'; const domain = '(?:\\.(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)*'; const tld = '(?:\\.(?:[a-zA-Z]{2,}))\\.?'; const port = '(?::\\d{2,5})?'; const path = '(?:[/?#][\\x21-\\x7F]*)?'; // ascii no whitespaces const regex = `(?:${protocol}|www\\.)${auth}(?:localhost|${ipv4}|${host}${domain}${tld})${port}${path}`; return new RegExp(`^${regex}$`, 'i'); }
[ "function", "urlStyleUriRegex", "(", ")", "{", "const", "protocol", "=", "'(?:[A-Za-z]{3,9}://)'", ";", "const", "auth", "=", "'(?:\\\\S+(?::\\\\S*)?@)?'", ";", "\\\\", "\\\\", "const", "ipv4", "=", "'(?:\\\\[?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\\\]?'", ";", "\\\\", "\\\\", "\\\\", "const", "host", "=", "'(?:(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)'", ";", "const", "domain", "=", "'(?:\\\\.(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)*'", ";", "}" ]
Compose a url style uri regex The most common form of URI is the Uniform Resource Locator (URL), frequently referred to informally as a web address. More rarely seen in usage is the Uniform Resource Name (URN), which was designed to complement URLs by providing a mechanism for the identification of resources in particular namespaces. - scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] - https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
[ "Compose", "a", "url", "style", "uri", "regex" ]
a2aa6d68ed1ba525498d278a88571e664f0d4ac3
https://github.com/gdbots/common-js/blob/a2aa6d68ed1ba525498d278a88571e664f0d4ac3/src/isValidUri.js#L20-L32
train
trabus/ember-cli-mv
lib/tasks/verify-file.js
function(destPath) { var exists, stats; var dirpath = path.dirname(destPath); try{ stats = fs.lstatSync(dirpath); exists = stats.isDirectory(); } catch(e) { this.createDestDir = dirpath; } return !!exists; }
javascript
function(destPath) { var exists, stats; var dirpath = path.dirname(destPath); try{ stats = fs.lstatSync(dirpath); exists = stats.isDirectory(); } catch(e) { this.createDestDir = dirpath; } return !!exists; }
[ "function", "(", "destPath", ")", "{", "var", "exists", ",", "stats", ";", "var", "dirpath", "=", "path", ".", "dirname", "(", "destPath", ")", ";", "try", "{", "stats", "=", "fs", ".", "lstatSync", "(", "dirpath", ")", ";", "exists", "=", "stats", ".", "isDirectory", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "this", ".", "createDestDir", "=", "dirpath", ";", "}", "return", "!", "!", "exists", ";", "}" ]
determine if we need to create the destination directory
[ "determine", "if", "we", "need", "to", "create", "the", "destination", "directory" ]
3887906b48de90f74c8c0f5a74697609f83e792b
https://github.com/trabus/ember-cli-mv/blob/3887906b48de90f74c8c0f5a74697609f83e792b/lib/tasks/verify-file.js#L64-L74
train
trabus/ember-cli-mv
lib/tasks/verify-file.js
function(destPath) { this.checkDestDir(destPath); var exists = existsSync(destPath); // we warn if // if (exists) { // this.ui.writeLine('The destination path: ' + destPath + ' already exists. Cannot overrwrite.', 'WARNING'); // } return { destExists: exists, destDir: this.createDestDir }; }
javascript
function(destPath) { this.checkDestDir(destPath); var exists = existsSync(destPath); // we warn if // if (exists) { // this.ui.writeLine('The destination path: ' + destPath + ' already exists. Cannot overrwrite.', 'WARNING'); // } return { destExists: exists, destDir: this.createDestDir }; }
[ "function", "(", "destPath", ")", "{", "this", ".", "checkDestDir", "(", "destPath", ")", ";", "var", "exists", "=", "existsSync", "(", "destPath", ")", ";", "return", "{", "destExists", ":", "exists", ",", "destDir", ":", "this", ".", "createDestDir", "}", ";", "}" ]
determine if the file already exists and will be overwritten
[ "determine", "if", "the", "file", "already", "exists", "and", "will", "be", "overwritten" ]
3887906b48de90f74c8c0f5a74697609f83e792b
https://github.com/trabus/ember-cli-mv/blob/3887906b48de90f74c8c0f5a74697609f83e792b/lib/tasks/verify-file.js#L137-L149
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/modification.js
hoist
function hoist() { var scope = arguments.length <= 0 || arguments[0] === undefined ? this.scope : arguments[0]; var hoister = new _libHoister2["default"](this, scope); return hoister.run(); }
javascript
function hoist() { var scope = arguments.length <= 0 || arguments[0] === undefined ? this.scope : arguments[0]; var hoister = new _libHoister2["default"](this, scope); return hoister.run(); }
[ "function", "hoist", "(", ")", "{", "var", "scope", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "this", ".", "scope", ":", "arguments", "[", "0", "]", ";", "var", "hoister", "=", "new", "_libHoister2", "[", "\"default\"", "]", "(", "this", ",", "scope", ")", ";", "return", "hoister", ".", "run", "(", ")", ";", "}" ]
Hoist the current node to the highest scope possible and return a UID referencing it.
[ "Hoist", "the", "current", "node", "to", "the", "highest", "scope", "possible", "and", "return", "a", "UID", "referencing", "it", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/modification.js#L252-L257
train
plepe/openstreetmap-date-parser
src/parser.js
osmDateParser
function osmDateParser (value, options) { var m, v, g m = value.match(/^(.*)\.\.(.*)$/) if (m) { let s = osmDateParser(m[1]) let e = osmDateParser(m[2]) if (s === null || e === null) { return null } if (s[0] > e[1]) { return null } return [ s[0], e[1] ] } m = value.match(/^(\d*) BCE?$/i) if (m) { [ v, g ] = parseDate(value) return [ v, v ] } m = value.match(/^before (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ null, v - 1 ] } m = value.match(/^after (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ v + g, null ] } m = value.match(/^early (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ v, Math.round(v + g * 0.33) ] } m = value.match(/^mid (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ Math.round(v + g * 0.33), Math.round(v + g * 0.67 - 1) ] } m = value.match(/^late (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ Math.round(v + g * 0.67 - 1), v + g - 1 ] } m = parseDate(value) if (m) { [ v, g ] = m return [ v, v + g - 1 ] } return null }
javascript
function osmDateParser (value, options) { var m, v, g m = value.match(/^(.*)\.\.(.*)$/) if (m) { let s = osmDateParser(m[1]) let e = osmDateParser(m[2]) if (s === null || e === null) { return null } if (s[0] > e[1]) { return null } return [ s[0], e[1] ] } m = value.match(/^(\d*) BCE?$/i) if (m) { [ v, g ] = parseDate(value) return [ v, v ] } m = value.match(/^before (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ null, v - 1 ] } m = value.match(/^after (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ v + g, null ] } m = value.match(/^early (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ v, Math.round(v + g * 0.33) ] } m = value.match(/^mid (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ Math.round(v + g * 0.33), Math.round(v + g * 0.67 - 1) ] } m = value.match(/^late (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ Math.round(v + g * 0.67 - 1), v + g - 1 ] } m = parseDate(value) if (m) { [ v, g ] = m return [ v, v + g - 1 ] } return null }
[ "function", "osmDateParser", "(", "value", ",", "options", ")", "{", "var", "m", ",", "v", ",", "g", "m", "=", "value", ".", "match", "(", "/", "^(.*)\\.\\.(.*)$", "/", ")", "if", "(", "m", ")", "{", "let", "s", "=", "osmDateParser", "(", "m", "[", "1", "]", ")", "let", "e", "=", "osmDateParser", "(", "m", "[", "2", "]", ")", "if", "(", "s", "===", "null", "||", "e", "===", "null", ")", "{", "return", "null", "}", "if", "(", "s", "[", "0", "]", ">", "e", "[", "1", "]", ")", "{", "return", "null", "}", "return", "[", "s", "[", "0", "]", ",", "e", "[", "1", "]", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^(\\d*) BCE?$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "value", ")", "return", "[", "v", ",", "v", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^before (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "null", ",", "v", "-", "1", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^after (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "v", "+", "g", ",", "null", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^early (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "v", ",", "Math", ".", "round", "(", "v", "+", "g", "*", "0.33", ")", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^mid (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "Math", ".", "round", "(", "v", "+", "g", "*", "0.33", ")", ",", "Math", ".", "round", "(", "v", "+", "g", "*", "0.67", "-", "1", ")", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^late (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "Math", ".", "round", "(", "v", "+", "g", "*", "0.67", "-", "1", ")", ",", "v", "+", "g", "-", "1", "]", "}", "m", "=", "parseDate", "(", "value", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "m", "return", "[", "v", ",", "v", "+", "g", "-", "1", "]", "}", "return", "null", "}" ]
return the lowest or highest possible year which fits the value
[ "return", "the", "lowest", "or", "highest", "possible", "year", "which", "fits", "the", "value" ]
9c5d794c5b7c8fd5f42c7348719a812802e094dd
https://github.com/plepe/openstreetmap-date-parser/blob/9c5d794c5b7c8fd5f42c7348719a812802e094dd/src/parser.js#L34-L93
train