id
int32
0
58k
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
31,400
sinnerschrader/boilerplate-server
source/library/utilities/execute.js
handleError
function handleError(error) { console.log(`${options.entry} failed.`); console.trace(error); setTimeout(() => { throw error; }); }
javascript
function handleError(error) { console.log(`${options.entry} failed.`); console.trace(error); setTimeout(() => { throw error; }); }
[ "function", "handleError", "(", "error", ")", "{", "console", ".", "log", "(", "`", "${", "options", ".", "entry", "}", "`", ")", ";", "console", ".", "trace", "(", "error", ")", ";", "setTimeout", "(", "(", ")", "=>", "{", "throw", "error", ";", ...
Handles and escalates top level Promise errors causing the process to crash if uncatched @param {object} error - Error object to print and escalete @private
[ "Handles", "and", "escalates", "top", "level", "Promise", "errors", "causing", "the", "process", "to", "crash", "if", "uncatched" ]
5a16535af5d5a39d3d8301eeaaa5065f04307bd5
https://github.com/sinnerschrader/boilerplate-server/blob/5a16535af5d5a39d3d8301eeaaa5065f04307bd5/source/library/utilities/execute.js#L32-L39
31,401
ajay2507/lasso-unpack
lib/utils.js
getArguments
function getArguments(node) { if (node && node.arguments && node.arguments.length > 0) { return node.arguments; } return []; }
javascript
function getArguments(node) { if (node && node.arguments && node.arguments.length > 0) { return node.arguments; } return []; }
[ "function", "getArguments", "(", "node", ")", "{", "if", "(", "node", "&&", "node", ".", "arguments", "&&", "node", ".", "arguments", ".", "length", ">", "0", ")", "{", "return", "node", ".", "arguments", ";", "}", "return", "[", "]", ";", "}" ]
get Arguments from the AST tree.
[ "get", "Arguments", "from", "the", "AST", "tree", "." ]
fb228b00a549eedfafec7e8eaf9999d69db82a0c
https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/utils.js#L10-L15
31,402
ajay2507/lasso-unpack
lib/utils.js
extractLiteralFromInstalled
function extractLiteralFromInstalled(stats, element) { if (element.length === 0) return stats; let value = ""; if (validLiteral(element[0])) { value = element[0].value; // let array = value.split('$'); // if (array.length == 0) { // stats.setPackageName(value); // } else { // stats.setPackageName(array[0]); // stats.setPackageVersion(array[1]); // } stats.setPackageName(value); } if (validLiteral(element[1])) { value = element[1].value; stats.setFileName(value); } if (validLiteral(element[2])) { value = element[2].value; stats.setVersion(value); } return stats; }
javascript
function extractLiteralFromInstalled(stats, element) { if (element.length === 0) return stats; let value = ""; if (validLiteral(element[0])) { value = element[0].value; // let array = value.split('$'); // if (array.length == 0) { // stats.setPackageName(value); // } else { // stats.setPackageName(array[0]); // stats.setPackageVersion(array[1]); // } stats.setPackageName(value); } if (validLiteral(element[1])) { value = element[1].value; stats.setFileName(value); } if (validLiteral(element[2])) { value = element[2].value; stats.setVersion(value); } return stats; }
[ "function", "extractLiteralFromInstalled", "(", "stats", ",", "element", ")", "{", "if", "(", "element", ".", "length", "===", "0", ")", "return", "stats", ";", "let", "value", "=", "\"\"", ";", "if", "(", "validLiteral", "(", "element", "[", "0", "]", ...
Extract packageName, version and fileName from given literal if type = "installed".
[ "Extract", "packageName", "version", "and", "fileName", "from", "given", "literal", "if", "type", "=", "installed", "." ]
fb228b00a549eedfafec7e8eaf9999d69db82a0c
https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/utils.js#L18-L41
31,403
ajay2507/lasso-unpack
lib/utils.js
extractLiteralFromDef
function extractLiteralFromDef(stats, element) { if (validLiteral(element)) { stats.setPath(element.value); let arrayLiteral = element.value.split('/'); let length = arrayLiteral.length; if (length > 0) { const index = validIndex(arrayLiteral); stats.setPackageName(arrayLiteral[index].split("$")[0]); stats.setVersion(arrayLiteral[index].split("$")[1] || ''); stats.setFileName(arrayLiteral.splice(index + 1, length).join('/')); } } return stats; }
javascript
function extractLiteralFromDef(stats, element) { if (validLiteral(element)) { stats.setPath(element.value); let arrayLiteral = element.value.split('/'); let length = arrayLiteral.length; if (length > 0) { const index = validIndex(arrayLiteral); stats.setPackageName(arrayLiteral[index].split("$")[0]); stats.setVersion(arrayLiteral[index].split("$")[1] || ''); stats.setFileName(arrayLiteral.splice(index + 1, length).join('/')); } } return stats; }
[ "function", "extractLiteralFromDef", "(", "stats", ",", "element", ")", "{", "if", "(", "validLiteral", "(", "element", ")", ")", "{", "stats", ".", "setPath", "(", "element", ".", "value", ")", ";", "let", "arrayLiteral", "=", "element", ".", "value", "...
Extract packageName, version and fileName from given literal if type = "def".
[ "Extract", "packageName", "version", "and", "fileName", "from", "given", "literal", "if", "type", "=", "def", "." ]
fb228b00a549eedfafec7e8eaf9999d69db82a0c
https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/utils.js#L63-L76
31,404
ajay2507/lasso-unpack
lib/utils.js
isFunctionExpression
function isFunctionExpression(node) { if (node && node.callee && node.callee.type === 'FunctionExpression') { return true; } return false; }
javascript
function isFunctionExpression(node) { if (node && node.callee && node.callee.type === 'FunctionExpression') { return true; } return false; }
[ "function", "isFunctionExpression", "(", "node", ")", "{", "if", "(", "node", "&&", "node", ".", "callee", "&&", "node", ".", "callee", ".", "type", "===", "'FunctionExpression'", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
check valid function expression or not.
[ "check", "valid", "function", "expression", "or", "not", "." ]
fb228b00a549eedfafec7e8eaf9999d69db82a0c
https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/utils.js#L111-L116
31,405
mmacmillan/grunt-jsdox
tasks/jsdox.js
publish
function publish(target, data, done) { if(data.enabled !== true) return grunt.fail.fatal('publishing is disabled; set "publish.enabled" to true to enable'); if(!data.path) return grunt.fail.fatal('the "publish.path" attribute must be provided for the publish task'); if(!data.message) return grunt.fail.fatal('the "publish.message" attribute must be provided for the publish task'); /** * provide the defaults for the git commands. by default, we are assuming the markdown repo is stored * in a separate directory, so our git commands need to support that...provide the git-dir and work-tree * paths. the standard publish process is: * * git add . * git commit -m <configured commit message> * git push <remoteName> <remoteBranch> (defaults to upstream master) * */ _.defaults(data, { addCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'add', '.'], commitCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'commit', '-m', data.message], pushCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'push', data.remoteName || 'upstream', data.remoteBranch || 'master'] }); //run the git commands, using promises to handle when complete function cmd(args) { var def = Q.defer(); grunt.util.spawn({ cmd: 'git', args: args }, def.resolve); return def.promise; } //add, commit, and publish the doc repository cmd(data.addCmd) .then(cmd.bind(this, data.commitCmd)) .then(cmd.bind(this, data.pushCmd)) .then(done); }
javascript
function publish(target, data, done) { if(data.enabled !== true) return grunt.fail.fatal('publishing is disabled; set "publish.enabled" to true to enable'); if(!data.path) return grunt.fail.fatal('the "publish.path" attribute must be provided for the publish task'); if(!data.message) return grunt.fail.fatal('the "publish.message" attribute must be provided for the publish task'); /** * provide the defaults for the git commands. by default, we are assuming the markdown repo is stored * in a separate directory, so our git commands need to support that...provide the git-dir and work-tree * paths. the standard publish process is: * * git add . * git commit -m <configured commit message> * git push <remoteName> <remoteBranch> (defaults to upstream master) * */ _.defaults(data, { addCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'add', '.'], commitCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'commit', '-m', data.message], pushCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'push', data.remoteName || 'upstream', data.remoteBranch || 'master'] }); //run the git commands, using promises to handle when complete function cmd(args) { var def = Q.defer(); grunt.util.spawn({ cmd: 'git', args: args }, def.resolve); return def.promise; } //add, commit, and publish the doc repository cmd(data.addCmd) .then(cmd.bind(this, data.commitCmd)) .then(cmd.bind(this, data.pushCmd)) .then(done); }
[ "function", "publish", "(", "target", ",", "data", ",", "done", ")", "{", "if", "(", "data", ".", "enabled", "!==", "true", ")", "return", "grunt", ".", "fail", ".", "fatal", "(", "'publishing is disabled; set \"publish.enabled\" to true to enable'", ")", ";", ...
publishes the 'dest' folder to the git repo it is currently configured for. this code only issues git commands; it doesn't target any specific repo...setting up the markdown repo ahead of time is necessary. @param target the target action, which is always 'publish'; ignore @param data the data for the publish action @param done the handler to end the async operation @returns {*}
[ "publishes", "the", "dest", "folder", "to", "the", "git", "repo", "it", "is", "currently", "configured", "for", ".", "this", "code", "only", "issues", "git", "commands", ";", "it", "doesn", "t", "target", "any", "specific", "repo", "...", "setting", "up", ...
bafce5b121ba25ba2509eca1fa3351f957e9733d
https://github.com/mmacmillan/grunt-jsdox/blob/bafce5b121ba25ba2509eca1fa3351f957e9733d/tasks/jsdox.js#L29-L67
31,406
mmacmillan/grunt-jsdox
tasks/jsdox.js
cmd
function cmd(args) { var def = Q.defer(); grunt.util.spawn({ cmd: 'git', args: args }, def.resolve); return def.promise; }
javascript
function cmd(args) { var def = Q.defer(); grunt.util.spawn({ cmd: 'git', args: args }, def.resolve); return def.promise; }
[ "function", "cmd", "(", "args", ")", "{", "var", "def", "=", "Q", ".", "defer", "(", ")", ";", "grunt", ".", "util", ".", "spawn", "(", "{", "cmd", ":", "'git'", ",", "args", ":", "args", "}", ",", "def", ".", "resolve", ")", ";", "return", "...
run the git commands, using promises to handle when complete
[ "run", "the", "git", "commands", "using", "promises", "to", "handle", "when", "complete" ]
bafce5b121ba25ba2509eca1fa3351f957e9733d
https://github.com/mmacmillan/grunt-jsdox/blob/bafce5b121ba25ba2509eca1fa3351f957e9733d/tasks/jsdox.js#L56-L60
31,407
vineyard-bloom/vineyard-lawn
src/api.js
getArguments
function getArguments(req) { const result = req.body || {}; for (let i in req.query) { result[i] = req.query[i]; } return result; }
javascript
function getArguments(req) { const result = req.body || {}; for (let i in req.query) { result[i] = req.query[i]; } return result; }
[ "function", "getArguments", "(", "req", ")", "{", "const", "result", "=", "req", ".", "body", "||", "{", "}", ";", "for", "(", "let", "i", "in", "req", ".", "query", ")", "{", "result", "[", "i", "]", "=", "req", ".", "query", "[", "i", "]", ...
This function is currently modifying req.body for performance though could be changed if it ever caused problems.
[ "This", "function", "is", "currently", "modifying", "req", ".", "body", "for", "performance", "though", "could", "be", "changed", "if", "it", "ever", "caused", "problems", "." ]
f36000716befa9bf467b8f29c3f0568368d4854e
https://github.com/vineyard-bloom/vineyard-lawn/blob/f36000716befa9bf467b8f29c3f0568368d4854e/src/api.js#L38-L44
31,408
maxrimue/node-autostart
index.js
isAutostartEnabled
function isAutostartEnabled(key, callback) { if (arguments.length < 1) { throw new Error('Not enough arguments passed to isAutostartEnabled()'); } else if (typeof key !== 'string') { throw new TypeError('Passed "key" to disableAutostart() is not a string.'); } if (typeof callback !== 'function') { return new Promise((resolve, reject) => { autostart.isAutostartEnabled(key, (error, isEnabled) => { if (error) { reject(error); } else { resolve(isEnabled); } }); }); } autostart.isAutostartEnabled(key, (error, isEnabled) => { callback(error, isEnabled); }); }
javascript
function isAutostartEnabled(key, callback) { if (arguments.length < 1) { throw new Error('Not enough arguments passed to isAutostartEnabled()'); } else if (typeof key !== 'string') { throw new TypeError('Passed "key" to disableAutostart() is not a string.'); } if (typeof callback !== 'function') { return new Promise((resolve, reject) => { autostart.isAutostartEnabled(key, (error, isEnabled) => { if (error) { reject(error); } else { resolve(isEnabled); } }); }); } autostart.isAutostartEnabled(key, (error, isEnabled) => { callback(error, isEnabled); }); }
[ "function", "isAutostartEnabled", "(", "key", ",", "callback", ")", "{", "if", "(", "arguments", ".", "length", "<", "1", ")", "{", "throw", "new", "Error", "(", "'Not enough arguments passed to isAutostartEnabled()'", ")", ";", "}", "else", "if", "(", "typeof...
Checks if autostart is enabled @param {String} key @param {Function} callback
[ "Checks", "if", "autostart", "is", "enabled" ]
486d4476c78f646fabf43988d3f460cc9142f438
https://github.com/maxrimue/node-autostart/blob/486d4476c78f646fabf43988d3f460cc9142f438/index.js#L77-L99
31,409
obliquid/jslardo
public/javascripts/jq/jquery.ui.touch.js
iPadTouchStart
function iPadTouchStart(event) { var touches = event.changedTouches, first = touches[0], type = "mouseover", simulatedEvent = document.createEvent("MouseEvent"); // // Mouse over first - I have live events attached on mouse over // simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null); first.target.dispatchEvent(simulatedEvent); type = "mousedown"; simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null); first.target.dispatchEvent(simulatedEvent); if (!tapValid) { lastTap = first.target; tapValid = true; tapTimeout = window.setTimeout("cancelTap();", 600); startHold(event); } else { window.clearTimeout(tapTimeout); // // If a double tap is still a possibility and the elements are the same // Then perform a double click // if (first.target == lastTap) { lastTap = null; tapValid = false; type = "click"; simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null); first.target.dispatchEvent(simulatedEvent); type = "dblclick"; simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null); first.target.dispatchEvent(simulatedEvent); } else { lastTap = first.target; tapValid = true; tapTimeout = window.setTimeout("cancelTap();", 600); startHold(event); } } }
javascript
function iPadTouchStart(event) { var touches = event.changedTouches, first = touches[0], type = "mouseover", simulatedEvent = document.createEvent("MouseEvent"); // // Mouse over first - I have live events attached on mouse over // simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null); first.target.dispatchEvent(simulatedEvent); type = "mousedown"; simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null); first.target.dispatchEvent(simulatedEvent); if (!tapValid) { lastTap = first.target; tapValid = true; tapTimeout = window.setTimeout("cancelTap();", 600); startHold(event); } else { window.clearTimeout(tapTimeout); // // If a double tap is still a possibility and the elements are the same // Then perform a double click // if (first.target == lastTap) { lastTap = null; tapValid = false; type = "click"; simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null); first.target.dispatchEvent(simulatedEvent); type = "dblclick"; simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null); first.target.dispatchEvent(simulatedEvent); } else { lastTap = first.target; tapValid = true; tapTimeout = window.setTimeout("cancelTap();", 600); startHold(event); } } }
[ "function", "iPadTouchStart", "(", "event", ")", "{", "var", "touches", "=", "event", ".", "changedTouches", ",", "first", "=", "touches", "[", "0", "]", ",", "type", "=", "\"mouseover\"", ",", "simulatedEvent", "=", "document", ".", "createEvent", "(", "\...
mouse over event then mouse down
[ "mouse", "over", "event", "then", "mouse", "down" ]
84225f280e0cce8d46bff8cc2d16f2c8f9633fac
https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/public/javascripts/jq/jquery.ui.touch.js#L108-L166
31,410
seebees/ironmq
libs/index.js
parseResponse
function parseResponse(cb) { return function parse(err, response, body) { // TODO Handel the errors cb(err, JSON.parse(body)) } }
javascript
function parseResponse(cb) { return function parse(err, response, body) { // TODO Handel the errors cb(err, JSON.parse(body)) } }
[ "function", "parseResponse", "(", "cb", ")", "{", "return", "function", "parse", "(", "err", ",", "response", ",", "body", ")", "{", "// TODO Handel the errors", "cb", "(", "err", ",", "JSON", ".", "parse", "(", "body", ")", ")", "}", "}" ]
one function to handle all the return errors
[ "one", "function", "to", "handle", "all", "the", "return", "errors" ]
28661aa21a43a28f80d341049b42f1b05cfc6870
https://github.com/seebees/ironmq/blob/28661aa21a43a28f80d341049b42f1b05cfc6870/libs/index.js#L243-L248
31,411
amida-tech/rxnorm-js
lib/rxnorm.js
query
function query(base, q, callback) { // Added unescape to fix URI errors resulting from hexadecimal escape sequences var url = util.format("%s?%s", base, querystring.unescape(querystring.stringify(q))); request(url, function (err, response) { if (err) return callback(err); callback(null, response.body); }); }
javascript
function query(base, q, callback) { // Added unescape to fix URI errors resulting from hexadecimal escape sequences var url = util.format("%s?%s", base, querystring.unescape(querystring.stringify(q))); request(url, function (err, response) { if (err) return callback(err); callback(null, response.body); }); }
[ "function", "query", "(", "base", ",", "q", ",", "callback", ")", "{", "// Added unescape to fix URI errors resulting from hexadecimal escape sequences", "var", "url", "=", "util", ".", "format", "(", "\"%s?%s\"", ",", "base", ",", "querystring", ".", "unescape", "(...
generic GET query with any endpoint
[ "generic", "GET", "query", "with", "any", "endpoint" ]
967682eef73c531ea14e43bb01af99015a1989eb
https://github.com/amida-tech/rxnorm-js/blob/967682eef73c531ea14e43bb01af99015a1989eb/lib/rxnorm.js#L10-L17
31,412
amida-tech/rxnorm-js
lib/rxnorm.js
queryRxNormApproximate
function queryRxNormApproximate(medname, maxEntries, callback) { // maxEntries is optional if (!callback) { callback = maxEntries; maxEntries = 5; } query("http://rxnav.nlm.nih.gov/REST/approximateTerm.json", { term: medname, maxEntries: maxEntries }, callback); }
javascript
function queryRxNormApproximate(medname, maxEntries, callback) { // maxEntries is optional if (!callback) { callback = maxEntries; maxEntries = 5; } query("http://rxnav.nlm.nih.gov/REST/approximateTerm.json", { term: medname, maxEntries: maxEntries }, callback); }
[ "function", "queryRxNormApproximate", "(", "medname", ",", "maxEntries", ",", "callback", ")", "{", "// maxEntries is optional", "if", "(", "!", "callback", ")", "{", "callback", "=", "maxEntries", ";", "maxEntries", "=", "5", ";", "}", "query", "(", "\"http:/...
find a medication by approximate name
[ "find", "a", "medication", "by", "approximate", "name" ]
967682eef73c531ea14e43bb01af99015a1989eb
https://github.com/amida-tech/rxnorm-js/blob/967682eef73c531ea14e43bb01af99015a1989eb/lib/rxnorm.js#L63-L74
31,413
amida-tech/rxnorm-js
lib/rxnorm.js
function (cb) { fs.readFile(path.resolve(__dirname, "dose_form_groups.txt"), "UTF-8", function (err, doseForms) { if (err) return cb(err); // each group is a new line in the file doseFormGroups = doseForms.toString().split("\n").filter(function (form) { // ignore empty lines return form.length > 0; }); cb(); }); }
javascript
function (cb) { fs.readFile(path.resolve(__dirname, "dose_form_groups.txt"), "UTF-8", function (err, doseForms) { if (err) return cb(err); // each group is a new line in the file doseFormGroups = doseForms.toString().split("\n").filter(function (form) { // ignore empty lines return form.length > 0; }); cb(); }); }
[ "function", "(", "cb", ")", "{", "fs", ".", "readFile", "(", "path", ".", "resolve", "(", "__dirname", ",", "\"dose_form_groups.txt\"", ")", ",", "\"UTF-8\"", ",", "function", "(", "err", ",", "doseForms", ")", "{", "if", "(", "err", ")", "return", "cb...
read in doseFormGroups from text file
[ "read", "in", "doseFormGroups", "from", "text", "file" ]
967682eef73c531ea14e43bb01af99015a1989eb
https://github.com/amida-tech/rxnorm-js/blob/967682eef73c531ea14e43bb01af99015a1989eb/lib/rxnorm.js#L104-L114
31,414
amida-tech/rxnorm-js
lib/rxnorm.js
queryRxNormGroup
function queryRxNormGroup(medname, callback) { query("http://rxnav.nlm.nih.gov/REST/drugs.json", { name: medname }, function (err, body) { if (err) return callback(err); drugFormList(JSON.parse(body), callback); }); }
javascript
function queryRxNormGroup(medname, callback) { query("http://rxnav.nlm.nih.gov/REST/drugs.json", { name: medname }, function (err, body) { if (err) return callback(err); drugFormList(JSON.parse(body), callback); }); }
[ "function", "queryRxNormGroup", "(", "medname", ",", "callback", ")", "{", "query", "(", "\"http://rxnav.nlm.nih.gov/REST/drugs.json\"", ",", "{", "name", ":", "medname", "}", ",", "function", "(", "err", ",", "body", ")", "{", "if", "(", "err", ")", "return...
query dose form groups
[ "query", "dose", "form", "groups" ]
967682eef73c531ea14e43bb01af99015a1989eb
https://github.com/amida-tech/rxnorm-js/blob/967682eef73c531ea14e43bb01af99015a1989eb/lib/rxnorm.js#L251-L258
31,415
mziccard/node-timsort
src/timsort.js
minRunLength
function minRunLength(n) { let r = 0; while (n >= DEFAULT_MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r; }
javascript
function minRunLength(n) { let r = 0; while (n >= DEFAULT_MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r; }
[ "function", "minRunLength", "(", "n", ")", "{", "let", "r", "=", "0", ";", "while", "(", "n", ">=", "DEFAULT_MIN_MERGE", ")", "{", "r", "|=", "(", "n", "&", "1", ")", ";", "n", ">>=", "1", ";", "}", "return", "n", "+", "r", ";", "}" ]
Compute minimum run length for TimSort @param {number} n - The size of the array to sort.
[ "Compute", "minimum", "run", "length", "for", "TimSort" ]
f8acc9e336117356d354ccb15133d10c92444322
https://github.com/mziccard/node-timsort/blob/f8acc9e336117356d354ccb15133d10c92444322/src/timsort.js#L121-L130
31,416
greggman/HappyFunTimes
server/player.js
function(client, relayServer, id) { this.client = client; this.relayServer = relayServer; this.id = id; debug("" + id + ": start player"); var addPlayerToGame = function(data) { var game = this.relayServer.addPlayerToGame(this, data.gameId, data.data); if (!game) { // TODO: Make this URL set from some global so we can set it some place else. debug("game does not exist:", data.gameId); this.disconnect(); } else { this.setGame(game); } }.bind(this); this.setGame = function(game) { this.game = game; }.bind(this); var assignAsServerForGame = function(data) { this.client.on('message', undefined); this.client.on('disconnect', undefined); this.relayServer.assignAsClientForGame(data, this.client); }.bind(this); var passMessageFromPlayerToGame = function(data) { if (!this.game) { console.warn("player " + this.id + " has no game"); return; } this.game.send(this, { cmd: 'update', id: this.id, data: data, }); }.bind(this); var messageHandlers = { 'join': addPlayerToGame, 'server': assignAsServerForGame, 'update': passMessageFromPlayerToGame, }; var onMessage = function(message) { var cmd = message.cmd; var handler = messageHandlers[cmd]; if (!handler) { console.error("unknown player message: " + cmd); return; } handler(message.data); }; var onDisconnect = function() { debug("" + this.id + ": disconnected"); if (this.game) { this.game.removePlayer(this); } this.disconnect(); }.bind(this); client.on('message', onMessage); client.on('disconnect', onDisconnect); }
javascript
function(client, relayServer, id) { this.client = client; this.relayServer = relayServer; this.id = id; debug("" + id + ": start player"); var addPlayerToGame = function(data) { var game = this.relayServer.addPlayerToGame(this, data.gameId, data.data); if (!game) { // TODO: Make this URL set from some global so we can set it some place else. debug("game does not exist:", data.gameId); this.disconnect(); } else { this.setGame(game); } }.bind(this); this.setGame = function(game) { this.game = game; }.bind(this); var assignAsServerForGame = function(data) { this.client.on('message', undefined); this.client.on('disconnect', undefined); this.relayServer.assignAsClientForGame(data, this.client); }.bind(this); var passMessageFromPlayerToGame = function(data) { if (!this.game) { console.warn("player " + this.id + " has no game"); return; } this.game.send(this, { cmd: 'update', id: this.id, data: data, }); }.bind(this); var messageHandlers = { 'join': addPlayerToGame, 'server': assignAsServerForGame, 'update': passMessageFromPlayerToGame, }; var onMessage = function(message) { var cmd = message.cmd; var handler = messageHandlers[cmd]; if (!handler) { console.error("unknown player message: " + cmd); return; } handler(message.data); }; var onDisconnect = function() { debug("" + this.id + ": disconnected"); if (this.game) { this.game.removePlayer(this); } this.disconnect(); }.bind(this); client.on('message', onMessage); client.on('disconnect', onDisconnect); }
[ "function", "(", "client", ",", "relayServer", ",", "id", ")", "{", "this", ".", "client", "=", "client", ";", "this", ".", "relayServer", "=", "relayServer", ";", "this", ".", "id", "=", "id", ";", "debug", "(", "\"\"", "+", "id", "+", "\": start pl...
A Player in a game. @constructor @param {!Client} client The websocket for this player @param {!RelayServer} relayServer The server managing this player. @param {string} id a unique id for this player.
[ "A", "Player", "in", "a", "game", "." ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/server/player.js#L45-L112
31,417
greggman/HappyFunTimes
server/game-group.js
function(gameId, relayServer, options) { options = options || {}; this.options = options; this.gameId = gameId; this.relayServer = relayServer; this.games = []; // first game is the "master" this.nextGameId = 0; // start at 0 because it's easy to switch games with (gameNum + numGames + dir) % numGames }
javascript
function(gameId, relayServer, options) { options = options || {}; this.options = options; this.gameId = gameId; this.relayServer = relayServer; this.games = []; // first game is the "master" this.nextGameId = 0; // start at 0 because it's easy to switch games with (gameNum + numGames + dir) % numGames }
[ "function", "(", "gameId", ",", "relayServer", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "options", "=", "options", ";", "this", ".", "gameId", "=", "gameId", ";", "this", ".", "relayServer", "=", "relayServ...
Represents a group of games. Normally a group only has 1 game but for situations where we need more than 1 game ...
[ "Represents", "a", "group", "of", "games", "." ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/server/game-group.js#L45-L52
31,418
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
function(str, opt_obj) { var dst = opt_obj || {}; try { var q = str.indexOf("?"); var e = str.indexOf("#"); if (e < 0) { e = str.length; } var query = str.substring(q + 1, e); searchStringToObject(query, dst); } catch (e) { console.error(e); } return dst; }
javascript
function(str, opt_obj) { var dst = opt_obj || {}; try { var q = str.indexOf("?"); var e = str.indexOf("#"); if (e < 0) { e = str.length; } var query = str.substring(q + 1, e); searchStringToObject(query, dst); } catch (e) { console.error(e); } return dst; }
[ "function", "(", "str", ",", "opt_obj", ")", "{", "var", "dst", "=", "opt_obj", "||", "{", "}", ";", "try", "{", "var", "q", "=", "str", ".", "indexOf", "(", "\"?\"", ")", ";", "var", "e", "=", "str", ".", "indexOf", "(", "\"#\"", ")", ";", "...
Reads the query values from a URL like string. @param {String} url URL like string eg. http://foo?key=value @param {Object} [opt_obj] Object to attach key values to @return {Object} Object with key values from URL @memberOf module:Misc
[ "Reads", "the", "query", "values", "from", "a", "URL", "like", "string", "." ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L132-L146
31,419
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
gotoIFrame
function gotoIFrame(src) { var iframe = document.createElement("iframe"); iframe.style.display = "none"; iframe.src = src; document.body.appendChild(iframe); return iframe; }
javascript
function gotoIFrame(src) { var iframe = document.createElement("iframe"); iframe.style.display = "none"; iframe.src = src; document.body.appendChild(iframe); return iframe; }
[ "function", "gotoIFrame", "(", "src", ")", "{", "var", "iframe", "=", "document", ".", "createElement", "(", "\"iframe\"", ")", ";", "iframe", ".", "style", ".", "display", "=", "\"none\"", ";", "iframe", ".", "src", "=", "src", ";", "document", ".", "...
Creates an invisible iframe and sets the src @param {string} src the source for the iframe @return {HTMLIFrameElement} The iframe
[ "Creates", "an", "invisible", "iframe", "and", "sets", "the", "src" ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L214-L220
31,420
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
function(opt_randFunc) { var randFunc = opt_randFunc || randInt; var strong = randFunc(3); var colors = []; for (var ii = 0; ii < 3; ++ii) { colors.push(randFunc(128) + (ii === strong ? 128 : 64)); } return "rgb(" + colors.join(",") + ")"; }
javascript
function(opt_randFunc) { var randFunc = opt_randFunc || randInt; var strong = randFunc(3); var colors = []; for (var ii = 0; ii < 3; ++ii) { colors.push(randFunc(128) + (ii === strong ? 128 : 64)); } return "rgb(" + colors.join(",") + ")"; }
[ "function", "(", "opt_randFunc", ")", "{", "var", "randFunc", "=", "opt_randFunc", "||", "randInt", ";", "var", "strong", "=", "randFunc", "(", "3", ")", ";", "var", "colors", "=", "[", "]", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", ...
get a random CSS color @param {function(number): number?) opt_randFunc function to generate random numbers @return {string} random css color @memberOf module:Misc
[ "get", "a", "random", "CSS", "color" ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L238-L246
31,421
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
function(opt_randFunc) { var randFunc = opt_randFunc || randInt; var strong = randFunc(3); var color = 0xFF; for (var ii = 0; ii < 3; ++ii) { color = (color << 8) | (randFunc(128) + (ii === strong ? 128 : 64)); } return color; }
javascript
function(opt_randFunc) { var randFunc = opt_randFunc || randInt; var strong = randFunc(3); var color = 0xFF; for (var ii = 0; ii < 3; ++ii) { color = (color << 8) | (randFunc(128) + (ii === strong ? 128 : 64)); } return color; }
[ "function", "(", "opt_randFunc", ")", "{", "var", "randFunc", "=", "opt_randFunc", "||", "randInt", ";", "var", "strong", "=", "randFunc", "(", "3", ")", ";", "var", "color", "=", "0xFF", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "3",...
get a random 32bit color @param {function(number): number?) opt_randFunc function to generate random numbers @return {string} random 32bit color @memberOf module:Misc
[ "get", "a", "random", "32bit", "color" ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L263-L271
31,422
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
function(selector) { for (var ii = 0; ii < document.styleSheets.length; ++ii) { var styleSheet = document.styleSheets[ii]; var rules = styleSheet.cssRules || styleSheet.rules; if (rules) { for (var rr = 0; rr < rules.length; ++rr) { var rule = rules[rr]; if (rule.selectorText === selector) { return rule; } } } } }
javascript
function(selector) { for (var ii = 0; ii < document.styleSheets.length; ++ii) { var styleSheet = document.styleSheets[ii]; var rules = styleSheet.cssRules || styleSheet.rules; if (rules) { for (var rr = 0; rr < rules.length; ++rr) { var rule = rules[rr]; if (rule.selectorText === selector) { return rule; } } } } }
[ "function", "(", "selector", ")", "{", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "document", ".", "styleSheets", ".", "length", ";", "++", "ii", ")", "{", "var", "styleSheet", "=", "document", ".", "styleSheets", "[", "ii", "]", ";", "var"...
finds a CSS rule. @param {string} selector @return {Rule?} matching css rule @memberOf module:Misc
[ "finds", "a", "CSS", "rule", "." ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L279-L292
31,423
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
function(element) { var r = { x: element.offsetLeft, y: element.offsetTop }; if (element.offsetParent) { var tmp = getAbsolutePosition(element.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }
javascript
function(element) { var r = { x: element.offsetLeft, y: element.offsetTop }; if (element.offsetParent) { var tmp = getAbsolutePosition(element.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }
[ "function", "(", "element", ")", "{", "var", "r", "=", "{", "x", ":", "element", ".", "offsetLeft", ",", "y", ":", "element", ".", "offsetTop", "}", ";", "if", "(", "element", ".", "offsetParent", ")", "{", "var", "tmp", "=", "getAbsolutePosition", "...
Returns the absolute position of an element for certain browsers. @param {HTMLElement} element The element to get a position for. @returns {Object} An object containing x and y as the absolute position of the given element. @memberOf module:Misc
[ "Returns", "the", "absolute", "position", "of", "an", "element", "for", "certain", "browsers", "." ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L314-L322
31,424
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
function(canvas, useDevicePixelRatio) { var mult = useDevicePixelRatio ? window.devicePixelRatio : 1; mult = mult || 1; var width = Math.floor(canvas.clientWidth * mult); var height = Math.floor(canvas.clientHeight * mult); if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; return true; } }
javascript
function(canvas, useDevicePixelRatio) { var mult = useDevicePixelRatio ? window.devicePixelRatio : 1; mult = mult || 1; var width = Math.floor(canvas.clientWidth * mult); var height = Math.floor(canvas.clientHeight * mult); if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; return true; } }
[ "function", "(", "canvas", ",", "useDevicePixelRatio", ")", "{", "var", "mult", "=", "useDevicePixelRatio", "?", "window", ".", "devicePixelRatio", ":", "1", ";", "mult", "=", "mult", "||", "1", ";", "var", "width", "=", "Math", ".", "floor", "(", "canva...
Resizes a cavnas to match its CSS displayed size. @param {Canvas} canvas canvas to resize. @param {boolean?} useDevicePixelRatio if true canvas will be created to match devicePixelRatio. @memberOf module:Misc
[ "Resizes", "a", "cavnas", "to", "match", "its", "CSS", "displayed", "size", "." ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L419-L430
31,425
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
applyObject
function applyObject(src, dst) { Object.keys(src).forEach(function(key) { dst[key] = src[key]; }); return dst; }
javascript
function applyObject(src, dst) { Object.keys(src).forEach(function(key) { dst[key] = src[key]; }); return dst; }
[ "function", "applyObject", "(", "src", ",", "dst", ")", "{", "Object", ".", "keys", "(", "src", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "dst", "[", "key", "]", "=", "src", "[", "key", "]", ";", "}", ")", ";", "return", "dst"...
Copies all the src properties to the dst @param {Object} src an object with some properties @param {Object} dst an object to receive copes of the properties @return returns the dst object.
[ "Copies", "all", "the", "src", "properties", "to", "the", "dst" ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L438-L443
31,426
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
makeRandomId
function makeRandomId(digits) { digits = digits || 16; var id = ""; for (var ii = 0; ii < digits; ++ii) { id = id + ((Math.random() * 16 | 0)).toString(16); } return id; }
javascript
function makeRandomId(digits) { digits = digits || 16; var id = ""; for (var ii = 0; ii < digits; ++ii) { id = id + ((Math.random() * 16 | 0)).toString(16); } return id; }
[ "function", "makeRandomId", "(", "digits", ")", "{", "digits", "=", "digits", "||", "16", ";", "var", "id", "=", "\"\"", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "digits", ";", "++", "ii", ")", "{", "id", "=", "id", "+", "(", "...
Creates a random id @param {number} [digits] number of digits. default 16
[ "Creates", "a", "random", "id" ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L481-L488
31,427
greggman/HappyFunTimes
src/hft/scripts/misc/misc.js
applyListeners
function applyListeners(emitter, listeners) { Object.keys(listeners).forEach(function(name) { emitter.addEventListener(name, listeners[name]); }); }
javascript
function applyListeners(emitter, listeners) { Object.keys(listeners).forEach(function(name) { emitter.addEventListener(name, listeners[name]); }); }
[ "function", "applyListeners", "(", "emitter", ",", "listeners", ")", "{", "Object", ".", "keys", "(", "listeners", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "emitter", ".", "addEventListener", "(", "name", ",", "listeners", "[", "name", ...
Applies an object of listeners to an emitter. Example: applyListeners(someDivElement, { mousedown: someFunc1, mousemove: someFunc2, mouseup: someFunc3, }); Which is the same as someDivElement.addEventListener("mousedown", someFunc1); someDivElement.addEventListener("mousemove", someFunc2); someDivElement.addEventListener("mouseup", someFunc3); @param {Emitter} emitter some object that emits events and has a function `addEventListener` @param {Object.<string, function>} listeners eventname function pairs.
[ "Applies", "an", "object", "of", "listeners", "to", "an", "emitter", "." ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L510-L514
31,428
greggman/HappyFunTimes
src/hft/scripts/syncedclock.js
function(opt_syncRateSeconds, callback) { var query = misc.parseUrlQuery(); var url = (query.hftUrl || window.location.href).replace("ws:", "http:"); var syncRateMS = (opt_syncRateSeconds || 10) * 1000; var timeOffset = 0; var syncToServer = function(queueNext) { var sendTime = getLocalTime(); io.sendJSON(url, {cmd: 'time'}, function(exception, obj) { if (exception) { console.error("syncToServer: " + exception); } else { var receiveTime = getLocalTime(); var duration = receiveTime - sendTime; var serverTime = obj.time + duration * 0.5; timeOffset = serverTime - receiveTime; if (callback) { callback(); callback = undefined; } //g_services.logger.log("duration: ", duration, " timeOff:", timeOffset); } if (queueNext) { setTimeout(function() { syncToServer(true); }, syncRateMS); } }); }; var syncToServerNoQueue = function() { syncToServer(false); }; syncToServer(true); setTimeout(syncToServerNoQueue, 1000); setTimeout(syncToServerNoQueue, 2000); setTimeout(syncToServerNoQueue, 4000); /** * Gets the current time in seconds. * @private */ this.getTime = function() { return getLocalTime() + timeOffset; }; }
javascript
function(opt_syncRateSeconds, callback) { var query = misc.parseUrlQuery(); var url = (query.hftUrl || window.location.href).replace("ws:", "http:"); var syncRateMS = (opt_syncRateSeconds || 10) * 1000; var timeOffset = 0; var syncToServer = function(queueNext) { var sendTime = getLocalTime(); io.sendJSON(url, {cmd: 'time'}, function(exception, obj) { if (exception) { console.error("syncToServer: " + exception); } else { var receiveTime = getLocalTime(); var duration = receiveTime - sendTime; var serverTime = obj.time + duration * 0.5; timeOffset = serverTime - receiveTime; if (callback) { callback(); callback = undefined; } //g_services.logger.log("duration: ", duration, " timeOff:", timeOffset); } if (queueNext) { setTimeout(function() { syncToServer(true); }, syncRateMS); } }); }; var syncToServerNoQueue = function() { syncToServer(false); }; syncToServer(true); setTimeout(syncToServerNoQueue, 1000); setTimeout(syncToServerNoQueue, 2000); setTimeout(syncToServerNoQueue, 4000); /** * Gets the current time in seconds. * @private */ this.getTime = function() { return getLocalTime() + timeOffset; }; }
[ "function", "(", "opt_syncRateSeconds", ",", "callback", ")", "{", "var", "query", "=", "misc", ".", "parseUrlQuery", "(", ")", ";", "var", "url", "=", "(", "query", ".", "hftUrl", "||", "window", ".", "location", ".", "href", ")", ".", "replace", "(",...
A clock that gets the current time in seconds attempting to keep the clock synced to the server. @constructor
[ "A", "clock", "that", "gets", "the", "current", "time", "in", "seconds", "attempting", "to", "keep", "the", "clock", "synced", "to", "the", "server", "." ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/syncedclock.js#L120-L167
31,429
greggman/HappyFunTimes
docs/assets/js/io.js
function(url, jsonObject, callback, options) { var options = JSON.parse(JSON.stringify(options || {})); options.headers = options.headers || {}; options.headers["Content-type"] = "application/json"; return request( url, JSON.stringify(jsonObject), function(err, content) { if (err) { return callback(err); } try { var json = JSON.parse(content); } catch (e) { return callback(e); } callback(null, json); }, options); }
javascript
function(url, jsonObject, callback, options) { var options = JSON.parse(JSON.stringify(options || {})); options.headers = options.headers || {}; options.headers["Content-type"] = "application/json"; return request( url, JSON.stringify(jsonObject), function(err, content) { if (err) { return callback(err); } try { var json = JSON.parse(content); } catch (e) { return callback(e); } callback(null, json); }, options); }
[ "function", "(", "url", ",", "jsonObject", ",", "callback", ",", "options", ")", "{", "var", "options", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "options", "||", "{", "}", ")", ")", ";", "options", ".", "headers", "=", "options"...
sends a JSON 'POST' request, returns JSON repsonse @memberOf module:IO @param {string} url url to POST to. @param {Object=} jsonObject JavaScript object on which to call JSON.stringify. @param {!function(error, object)} callback Function to call on success or failure. If successful error will be null, object will be json result from request. @param {module:IO~Request~Options?} options
[ "sends", "a", "JSON", "POST", "request", "returns", "JSON", "repsonse" ]
1c29e334ef9eca269980f5fc2b73894452688490
https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/docs/assets/js/io.js#L141-L160
31,430
alexindigo/asynckit
lib/readable_serial.js
ReadableSerial
function ReadableSerial(list, iterator, callback) { if (!(this instanceof ReadableSerial)) { return new ReadableSerial(list, iterator, callback); } // turn on object mode ReadableSerial.super_.call(this, {objectMode: true}); this._start(serial, list, iterator, callback); }
javascript
function ReadableSerial(list, iterator, callback) { if (!(this instanceof ReadableSerial)) { return new ReadableSerial(list, iterator, callback); } // turn on object mode ReadableSerial.super_.call(this, {objectMode: true}); this._start(serial, list, iterator, callback); }
[ "function", "ReadableSerial", "(", "list", ",", "iterator", ",", "callback", ")", "{", "if", "(", "!", "(", "this", "instanceof", "ReadableSerial", ")", ")", "{", "return", "new", "ReadableSerial", "(", "list", ",", "iterator", ",", "callback", ")", ";", ...
Streaming wrapper to `asynckit.serial` @param {array|object} list - array or object (named list) to iterate over @param {function} iterator - iterator to run @param {function} callback - invoked when all elements processed @returns {stream.Readable#}
[ "Streaming", "wrapper", "to", "asynckit", ".", "serial" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/readable_serial.js#L14-L25
31,431
alexindigo/asynckit
lib/streamify.js
wrapIterator
function wrapIterator(iterator) { var stream = this; return function(item, key, cb) { var aborter , wrappedCb = async(wrapIteratorCallback.call(stream, cb, key)) ; stream.jobs[key] = wrappedCb; // it's either shortcut (item, cb) if (iterator.length == 2) { aborter = iterator(item, wrappedCb); } // or long format (item, key, cb) else { aborter = iterator(item, key, wrappedCb); } return aborter; }; }
javascript
function wrapIterator(iterator) { var stream = this; return function(item, key, cb) { var aborter , wrappedCb = async(wrapIteratorCallback.call(stream, cb, key)) ; stream.jobs[key] = wrappedCb; // it's either shortcut (item, cb) if (iterator.length == 2) { aborter = iterator(item, wrappedCb); } // or long format (item, key, cb) else { aborter = iterator(item, key, wrappedCb); } return aborter; }; }
[ "function", "wrapIterator", "(", "iterator", ")", "{", "var", "stream", "=", "this", ";", "return", "function", "(", "item", ",", "key", ",", "cb", ")", "{", "var", "aborter", ",", "wrappedCb", "=", "async", "(", "wrapIteratorCallback", ".", "call", "(",...
Wraps iterators with long signature @this ReadableAsyncKit# @param {function} iterator - function to wrap @returns {function} - wrapped function
[ "Wraps", "iterators", "with", "long", "signature" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L16-L41
31,432
alexindigo/asynckit
lib/streamify.js
wrapCallback
function wrapCallback(callback) { var stream = this; var wrapped = function(error, result) { return finisher.call(stream, error, result, callback); }; return wrapped; }
javascript
function wrapCallback(callback) { var stream = this; var wrapped = function(error, result) { return finisher.call(stream, error, result, callback); }; return wrapped; }
[ "function", "wrapCallback", "(", "callback", ")", "{", "var", "stream", "=", "this", ";", "var", "wrapped", "=", "function", "(", "error", ",", "result", ")", "{", "return", "finisher", ".", "call", "(", "stream", ",", "error", ",", "result", ",", "cal...
Wraps provided callback function allowing to execute snitch function before real callback @this ReadableAsyncKit# @param {function} callback - function to wrap @returns {function} - wrapped function
[ "Wraps", "provided", "callback", "function", "allowing", "to", "execute", "snitch", "function", "before", "real", "callback" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L52-L62
31,433
alexindigo/asynckit
lib/streamify.js
wrapIteratorCallback
function wrapIteratorCallback(callback, key) { var stream = this; return function(error, output) { // don't repeat yourself if (!(key in stream.jobs)) { callback(error, output); return; } // clean up jobs delete stream.jobs[key]; return streamer.call(stream, error, {key: key, value: output}, callback); }; }
javascript
function wrapIteratorCallback(callback, key) { var stream = this; return function(error, output) { // don't repeat yourself if (!(key in stream.jobs)) { callback(error, output); return; } // clean up jobs delete stream.jobs[key]; return streamer.call(stream, error, {key: key, value: output}, callback); }; }
[ "function", "wrapIteratorCallback", "(", "callback", ",", "key", ")", "{", "var", "stream", "=", "this", ";", "return", "function", "(", "error", ",", "output", ")", "{", "// don't repeat yourself", "if", "(", "!", "(", "key", "in", "stream", ".", "jobs", ...
Wraps provided iterator callback function makes sure snitch only called once, but passes secondary calls to the original callback @this ReadableAsyncKit# @param {function} callback - callback to wrap @param {number|string} key - iteration key @returns {function} wrapped callback
[ "Wraps", "provided", "iterator", "callback", "function", "makes", "sure", "snitch", "only", "called", "once", "but", "passes", "secondary", "calls", "to", "the", "original", "callback" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L74-L92
31,434
alexindigo/asynckit
lib/streamify.js
streamer
function streamer(error, output, callback) { if (error && !this.error) { this.error = error; this.pause(); this.emit('error', error); // send back value only, as expected callback(error, output && output.value); return; } // stream stuff this.push(output); // back to original track // send back value only, as expected callback(error, output && output.value); }
javascript
function streamer(error, output, callback) { if (error && !this.error) { this.error = error; this.pause(); this.emit('error', error); // send back value only, as expected callback(error, output && output.value); return; } // stream stuff this.push(output); // back to original track // send back value only, as expected callback(error, output && output.value); }
[ "function", "streamer", "(", "error", ",", "output", ",", "callback", ")", "{", "if", "(", "error", "&&", "!", "this", ".", "error", ")", "{", "this", ".", "error", "=", "error", ";", "this", ".", "pause", "(", ")", ";", "this", ".", "emit", "(",...
Stream wrapper for iterator callback @this ReadableAsyncKit# @param {mixed} error - error response @param {mixed} output - iterator output @param {function} callback - callback that expects iterator results
[ "Stream", "wrapper", "for", "iterator", "callback" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L102-L120
31,435
alexindigo/asynckit
lib/streamify.js
finisher
function finisher(error, output, callback) { // signal end of the stream // only for successfully finished streams if (!error) { this.push(null); } // back to original track callback(error, output); }
javascript
function finisher(error, output, callback) { // signal end of the stream // only for successfully finished streams if (!error) { this.push(null); } // back to original track callback(error, output); }
[ "function", "finisher", "(", "error", ",", "output", ",", "callback", ")", "{", "// signal end of the stream", "// only for successfully finished streams", "if", "(", "!", "error", ")", "{", "this", ".", "push", "(", "null", ")", ";", "}", "// back to original tra...
Stream wrapper for finishing callback @this ReadableAsyncKit# @param {mixed} error - error response @param {mixed} output - iterator output @param {function} callback - callback that expects final results
[ "Stream", "wrapper", "for", "finishing", "callback" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L130-L141
31,436
alexindigo/asynckit
lib/iterate.js
iterate
function iterate(list, iterator, state, callback) { // store current index var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; state.jobs[key] = runJob(iterator, key, list[key], function(error, output) { // don't repeat yourself // skip secondary callbacks if (!(key in state.jobs)) { return; } // clean up jobs delete state.jobs[key]; if (error) { // don't process rest of the results // stop still active jobs // and reset the list abort(state); } else { state.results[key] = output; } // return salvaged results callback(error, state.results); }); }
javascript
function iterate(list, iterator, state, callback) { // store current index var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; state.jobs[key] = runJob(iterator, key, list[key], function(error, output) { // don't repeat yourself // skip secondary callbacks if (!(key in state.jobs)) { return; } // clean up jobs delete state.jobs[key]; if (error) { // don't process rest of the results // stop still active jobs // and reset the list abort(state); } else { state.results[key] = output; } // return salvaged results callback(error, state.results); }); }
[ "function", "iterate", "(", "list", ",", "iterator", ",", "state", ",", "callback", ")", "{", "// store current index", "var", "key", "=", "state", "[", "'keyedList'", "]", "?", "state", "[", "'keyedList'", "]", "[", "state", ".", "index", "]", ":", "sta...
Iterates over each job object @param {array|object} list - array or object (named list) to iterate over @param {function} iterator - iterator to run @param {object} state - current job status @param {function} callback - invoked when all elements processed
[ "Iterates", "over", "each", "job", "object" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/iterate.js#L16-L48
31,437
alexindigo/asynckit
lib/iterate.js
runJob
function runJob(iterator, key, item, callback) { var aborter; // allow shortcut if iterator expects only two arguments if (iterator.length == 2) { aborter = iterator(item, async(callback)); } // otherwise go with full three arguments else { aborter = iterator(item, key, async(callback)); } return aborter; }
javascript
function runJob(iterator, key, item, callback) { var aborter; // allow shortcut if iterator expects only two arguments if (iterator.length == 2) { aborter = iterator(item, async(callback)); } // otherwise go with full three arguments else { aborter = iterator(item, key, async(callback)); } return aborter; }
[ "function", "runJob", "(", "iterator", ",", "key", ",", "item", ",", "callback", ")", "{", "var", "aborter", ";", "// allow shortcut if iterator expects only two arguments", "if", "(", "iterator", ".", "length", "==", "2", ")", "{", "aborter", "=", "iterator", ...
Runs iterator over provided job element @param {function} iterator - iterator to invoke @param {string|number} key - key/index of the element in the list of jobs @param {mixed} item - job description @param {function} callback - invoked after iterator is done with the job @returns {function|mixed} - job abort function or something else
[ "Runs", "iterator", "over", "provided", "job", "element" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/iterate.js#L59-L75
31,438
alexindigo/asynckit
serialOrdered.js
serialOrdered
function serialOrdered(list, iterator, sortMethod, callback) { var state = initState(list, sortMethod); iterate(list, iterator, state, function iteratorHandler(error, result) { if (error) { callback(error, result); return; } state.index++; // are we there yet? if (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, iteratorHandler); return; } // done here callback(null, state.results); }); return terminator.bind(state, callback); }
javascript
function serialOrdered(list, iterator, sortMethod, callback) { var state = initState(list, sortMethod); iterate(list, iterator, state, function iteratorHandler(error, result) { if (error) { callback(error, result); return; } state.index++; // are we there yet? if (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, iteratorHandler); return; } // done here callback(null, state.results); }); return terminator.bind(state, callback); }
[ "function", "serialOrdered", "(", "list", ",", "iterator", ",", "sortMethod", ",", "callback", ")", "{", "var", "state", "=", "initState", "(", "list", ",", "sortMethod", ")", ";", "iterate", "(", "list", ",", "iterator", ",", "state", ",", "function", "...
Runs iterator over provided sorted array elements in series @param {array|object} list - array or object (named list) to iterate over @param {function} iterator - iterator to run @param {function} sortMethod - custom sort function @param {function} callback - invoked when all elements processed @returns {function} - jobs terminator
[ "Runs", "iterator", "over", "provided", "sorted", "array", "elements", "in", "series" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/serialOrdered.js#L21-L47
31,439
alexindigo/asynckit
lib/readable_parallel.js
ReadableParallel
function ReadableParallel(list, iterator, callback) { if (!(this instanceof ReadableParallel)) { return new ReadableParallel(list, iterator, callback); } // turn on object mode ReadableParallel.super_.call(this, {objectMode: true}); this._start(parallel, list, iterator, callback); }
javascript
function ReadableParallel(list, iterator, callback) { if (!(this instanceof ReadableParallel)) { return new ReadableParallel(list, iterator, callback); } // turn on object mode ReadableParallel.super_.call(this, {objectMode: true}); this._start(parallel, list, iterator, callback); }
[ "function", "ReadableParallel", "(", "list", ",", "iterator", ",", "callback", ")", "{", "if", "(", "!", "(", "this", "instanceof", "ReadableParallel", ")", ")", "{", "return", "new", "ReadableParallel", "(", "list", ",", "iterator", ",", "callback", ")", ...
Streaming wrapper to `asynckit.parallel` @param {array|object} list - array or object (named list) to iterate over @param {function} iterator - iterator to run @param {function} callback - invoked when all elements processed @returns {stream.Readable#}
[ "Streaming", "wrapper", "to", "asynckit", ".", "parallel" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/readable_parallel.js#L14-L25
31,440
alexindigo/asynckit
lib/readable_serial_ordered.js
ReadableSerialOrdered
function ReadableSerialOrdered(list, iterator, sortMethod, callback) { if (!(this instanceof ReadableSerialOrdered)) { return new ReadableSerialOrdered(list, iterator, sortMethod, callback); } // turn on object mode ReadableSerialOrdered.super_.call(this, {objectMode: true}); this._start(serialOrdered, list, iterator, sortMethod, callback); }
javascript
function ReadableSerialOrdered(list, iterator, sortMethod, callback) { if (!(this instanceof ReadableSerialOrdered)) { return new ReadableSerialOrdered(list, iterator, sortMethod, callback); } // turn on object mode ReadableSerialOrdered.super_.call(this, {objectMode: true}); this._start(serialOrdered, list, iterator, sortMethod, callback); }
[ "function", "ReadableSerialOrdered", "(", "list", ",", "iterator", ",", "sortMethod", ",", "callback", ")", "{", "if", "(", "!", "(", "this", "instanceof", "ReadableSerialOrdered", ")", ")", "{", "return", "new", "ReadableSerialOrdered", "(", "list", ",", "ite...
Streaming wrapper to `asynckit.serialOrdered` @param {array|object} list - array or object (named list) to iterate over @param {function} iterator - iterator to run @param {function} sortMethod - custom sort function @param {function} callback - invoked when all elements processed @returns {stream.Readable#}
[ "Streaming", "wrapper", "to", "asynckit", ".", "serialOrdered" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/readable_serial_ordered.js#L18-L29
31,441
alexindigo/asynckit
lib/readable_asynckit.js
_start
function _start() { // first argument – runner function var runner = arguments[0] // take away first argument , args = Array.prototype.slice.call(arguments, 1) // second argument - input data , input = args[0] // last argument - result callback , endCb = streamify.callback.call(this, args[args.length - 1]) ; args[args.length - 1] = endCb; // third argument - iterator args[1] = streamify.iterator.call(this, args[1]); // allow time for proper setup defer(function() { if (!this.destroyed) { this.terminator = runner.apply(null, args); } else { endCb(null, Array.isArray(input) ? [] : {}); } }.bind(this)); }
javascript
function _start() { // first argument – runner function var runner = arguments[0] // take away first argument , args = Array.prototype.slice.call(arguments, 1) // second argument - input data , input = args[0] // last argument - result callback , endCb = streamify.callback.call(this, args[args.length - 1]) ; args[args.length - 1] = endCb; // third argument - iterator args[1] = streamify.iterator.call(this, args[1]); // allow time for proper setup defer(function() { if (!this.destroyed) { this.terminator = runner.apply(null, args); } else { endCb(null, Array.isArray(input) ? [] : {}); } }.bind(this)); }
[ "function", "_start", "(", ")", "{", "// first argument – runner function", "var", "runner", "=", "arguments", "[", "0", "]", "// take away first argument", ",", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")"...
Starts provided jobs in async manner @private
[ "Starts", "provided", "jobs", "in", "async", "manner" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/readable_asynckit.js#L51-L79
31,442
alexindigo/asynckit
lib/state.js
state
function state(list, sortMethod) { var isNamedList = !Array.isArray(list) , initState = { index : 0, keyedList: isNamedList || sortMethod ? Object.keys(list) : null, jobs : {}, results : isNamedList ? {} : [], size : isNamedList ? Object.keys(list).length : list.length } ; if (sortMethod) { // sort array keys based on it's values // sort object's keys just on own merit initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) { return sortMethod(list[a], list[b]); }); } return initState; }
javascript
function state(list, sortMethod) { var isNamedList = !Array.isArray(list) , initState = { index : 0, keyedList: isNamedList || sortMethod ? Object.keys(list) : null, jobs : {}, results : isNamedList ? {} : [], size : isNamedList ? Object.keys(list).length : list.length } ; if (sortMethod) { // sort array keys based on it's values // sort object's keys just on own merit initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) { return sortMethod(list[a], list[b]); }); } return initState; }
[ "function", "state", "(", "list", ",", "sortMethod", ")", "{", "var", "isNamedList", "=", "!", "Array", ".", "isArray", "(", "list", ")", ",", "initState", "=", "{", "index", ":", "0", ",", "keyedList", ":", "isNamedList", "||", "sortMethod", "?", "Obj...
Creates initial state object for iteration over list @param {array|object} list - list to iterate over @param {function|null} sortMethod - function to use for keys sort, or `null` to keep them as is @returns {object} - initial state object
[ "Creates", "initial", "state", "object", "for", "iteration", "over", "list" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/state.js#L13-L37
31,443
alexindigo/asynckit
lib/abort.js
abort
function abort(state) { Object.keys(state.jobs).forEach(clean.bind(state)); // reset leftover jobs state.jobs = {}; }
javascript
function abort(state) { Object.keys(state.jobs).forEach(clean.bind(state)); // reset leftover jobs state.jobs = {}; }
[ "function", "abort", "(", "state", ")", "{", "Object", ".", "keys", "(", "state", ".", "jobs", ")", ".", "forEach", "(", "clean", ".", "bind", "(", "state", ")", ")", ";", "// reset leftover jobs", "state", ".", "jobs", "=", "{", "}", ";", "}" ]
Aborts leftover active jobs @param {object} state - current state object
[ "Aborts", "leftover", "active", "jobs" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/abort.js#L9-L15
31,444
alexindigo/asynckit
lib/async.js
async
function async(callback) { var isAsync = false; // check if async happened defer(function() { isAsync = true; }); return function async_callback(err, result) { if (isAsync) { callback(err, result); } else { defer(function nextTick_callback() { callback(err, result); }); } }; }
javascript
function async(callback) { var isAsync = false; // check if async happened defer(function() { isAsync = true; }); return function async_callback(err, result) { if (isAsync) { callback(err, result); } else { defer(function nextTick_callback() { callback(err, result); }); } }; }
[ "function", "async", "(", "callback", ")", "{", "var", "isAsync", "=", "false", ";", "// check if async happened", "defer", "(", "function", "(", ")", "{", "isAsync", "=", "true", ";", "}", ")", ";", "return", "function", "async_callback", "(", "err", ",",...
Runs provided callback asynchronously even if callback itself is not @param {function} callback - callback to invoke @returns {function} - augmented callback
[ "Runs", "provided", "callback", "asynchronously", "even", "if", "callback", "itself", "is", "not" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/async.js#L13-L34
31,445
alexindigo/asynckit
parallel.js
parallel
function parallel(list, iterator, callback) { var state = initState(list); while (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, function(error, result) { if (error) { callback(error, result); return; } // looks like it's the last one if (Object.keys(state.jobs).length === 0) { callback(null, state.results); return; } }); state.index++; } return terminator.bind(state, callback); }
javascript
function parallel(list, iterator, callback) { var state = initState(list); while (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, function(error, result) { if (error) { callback(error, result); return; } // looks like it's the last one if (Object.keys(state.jobs).length === 0) { callback(null, state.results); return; } }); state.index++; } return terminator.bind(state, callback); }
[ "function", "parallel", "(", "list", ",", "iterator", ",", "callback", ")", "{", "var", "state", "=", "initState", "(", "list", ")", ";", "while", "(", "state", ".", "index", "<", "(", "state", "[", "'keyedList'", "]", "||", "list", ")", ".", "length...
Runs iterator over provided array elements in parallel @param {array|object} list - array or object (named list) to iterate over @param {function} iterator - iterator to run @param {function} callback - invoked when all elements processed @returns {function} - jobs terminator
[ "Runs", "iterator", "over", "provided", "array", "elements", "in", "parallel" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/parallel.js#L17-L43
31,446
alexindigo/asynckit
lib/terminator.js
terminator
function terminator(callback) { if (!Object.keys(this.jobs).length) { return; } // fast forward iteration index this.index = this.size; // abort jobs abort(this); // send back results we have so far async(callback)(null, this.results); }
javascript
function terminator(callback) { if (!Object.keys(this.jobs).length) { return; } // fast forward iteration index this.index = this.size; // abort jobs abort(this); // send back results we have so far async(callback)(null, this.results); }
[ "function", "terminator", "(", "callback", ")", "{", "if", "(", "!", "Object", ".", "keys", "(", "this", ".", "jobs", ")", ".", "length", ")", "{", "return", ";", "}", "// fast forward iteration index", "this", ".", "index", "=", "this", ".", "size", "...
Terminates jobs in the attached state context @this AsyncKitState# @param {function} callback - final callback to invoke after termination
[ "Terminates", "jobs", "in", "the", "attached", "state", "context" ]
583a75ed4fe41761b66416bb6e703ebb1f8963bf
https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/terminator.js#L14-L29
31,447
af83/oauth2_client_node
lib/oauth2_client.js
function(serverName, config, options) { this.methods[serverName] = {}; this.config.servers[serverName] = config; var self = this; ['valid_grant', 'treat_access_token', 'transform_token_response'].forEach(function(fctName) { self.methods[serverName][fctName] = options[fctName] || self[fctName].bind(self); }); }
javascript
function(serverName, config, options) { this.methods[serverName] = {}; this.config.servers[serverName] = config; var self = this; ['valid_grant', 'treat_access_token', 'transform_token_response'].forEach(function(fctName) { self.methods[serverName][fctName] = options[fctName] || self[fctName].bind(self); }); }
[ "function", "(", "serverName", ",", "config", ",", "options", ")", "{", "this", ".", "methods", "[", "serverName", "]", "=", "{", "}", ";", "this", ".", "config", ".", "servers", "[", "serverName", "]", "=", "config", ";", "var", "self", "=", "this",...
Add oauth2 server
[ "Add", "oauth2", "server" ]
40d5e56e717f88f6b2b9a725ca77a90b0a775535
https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L44-L51
31,448
af83/oauth2_client_node
lib/oauth2_client.js
function(data, code, callback) { var self = this; var cconfig = this.config.client; var sconfig = this.config.servers[data.oauth2_server_id]; request.post({uri: sconfig.server_token_endpoint, headers: {'content-type': 'application/x-www-form-urlencoded'}, body: querystring.stringify({ grant_type: "authorization_code", client_id: sconfig.client_id, code: code, client_secret: sconfig.client_secret, redirect_uri: cconfig.redirect_uri }) }, function(error, response, body) { console.log(body); if (!error && response.statusCode == 200) { try { var methods = self.methods[data.oauth2_server_id]; var token = methods.transform_token_response(body) callback(null, token); } catch(err) { callback(err); } } else { // TODO: check if error code indicates problem on the client, console.error(error, body); callback(error); } }); }
javascript
function(data, code, callback) { var self = this; var cconfig = this.config.client; var sconfig = this.config.servers[data.oauth2_server_id]; request.post({uri: sconfig.server_token_endpoint, headers: {'content-type': 'application/x-www-form-urlencoded'}, body: querystring.stringify({ grant_type: "authorization_code", client_id: sconfig.client_id, code: code, client_secret: sconfig.client_secret, redirect_uri: cconfig.redirect_uri }) }, function(error, response, body) { console.log(body); if (!error && response.statusCode == 200) { try { var methods = self.methods[data.oauth2_server_id]; var token = methods.transform_token_response(body) callback(null, token); } catch(err) { callback(err); } } else { // TODO: check if error code indicates problem on the client, console.error(error, body); callback(error); } }); }
[ "function", "(", "data", ",", "code", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "cconfig", "=", "this", ".", "config", ".", "client", ";", "var", "sconfig", "=", "this", ".", "config", ".", "servers", "[", "data", ".", "oau...
Valid the grant given by user requesting the OAuth2 server at OAuth2 token endpoint. Arguments: - data: hash containing: - oauth2_server_id: string, the OAuth2 server is (ex: "facebook.com"). - next_url: string, the next_url associated with the OAuth2 request. - state: hash, state associated with the OAuth2 request. - code: the authorization code given by OAuth2 server to user. - callback: function to be called once grant is validated/rejected. Called with the access_token returned by OAuth2 server as first parameter. If given token might be null, meaning it was rejected by OAuth2 server.
[ "Valid", "the", "grant", "given", "by", "user", "requesting", "the", "OAuth2", "server", "at", "OAuth2", "token", "endpoint", "." ]
40d5e56e717f88f6b2b9a725ca77a90b0a775535
https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L87-L116
31,449
af83/oauth2_client_node
lib/oauth2_client.js
function(req, res) { var params = URL.parse(req.url, true).query , code = params.code , state = params.state ; if(!code) { res.writeHead(400, {'Content-Type': 'text/plain'}); return res.end('The "code" parameter is missing.'); } if(!state) { res.writeHead(400, {'Content-Type': 'text/plain'}); return res.end('The "state" parameter is missing.'); } try { state = this.serializer.parse(state); } catch(err) { res.writeHead(400, {'Content-Type': 'text/plain'}); return res.end('The "state" parameter is invalid.'); } var data = { oauth2_server_id: state[0] , next_url: state[1] , state: state[2] } var methods = this.methods[data.oauth2_server_id]; methods.valid_grant(data, code, function(err, token) { if (err) return server_error(res, err); if(!token) { res.writeHead(400, {'Content-Type': 'text/plain'}); res.end('Invalid grant.'); return; } data.token = token; methods.treat_access_token(data, req, res, function() { redirect(res, data.next_url); }, function(err){server_error(res, err)}); }); }
javascript
function(req, res) { var params = URL.parse(req.url, true).query , code = params.code , state = params.state ; if(!code) { res.writeHead(400, {'Content-Type': 'text/plain'}); return res.end('The "code" parameter is missing.'); } if(!state) { res.writeHead(400, {'Content-Type': 'text/plain'}); return res.end('The "state" parameter is missing.'); } try { state = this.serializer.parse(state); } catch(err) { res.writeHead(400, {'Content-Type': 'text/plain'}); return res.end('The "state" parameter is invalid.'); } var data = { oauth2_server_id: state[0] , next_url: state[1] , state: state[2] } var methods = this.methods[data.oauth2_server_id]; methods.valid_grant(data, code, function(err, token) { if (err) return server_error(res, err); if(!token) { res.writeHead(400, {'Content-Type': 'text/plain'}); res.end('Invalid grant.'); return; } data.token = token; methods.treat_access_token(data, req, res, function() { redirect(res, data.next_url); }, function(err){server_error(res, err)}); }); }
[ "function", "(", "req", ",", "res", ")", "{", "var", "params", "=", "URL", ".", "parse", "(", "req", ".", "url", ",", "true", ")", ".", "query", ",", "code", "=", "params", ".", "code", ",", "state", "=", "params", ".", "state", ";", "if", "(",...
Check the grant given by user to login in authserver is a good one. Arguments: - req - res
[ "Check", "the", "grant", "given", "by", "user", "to", "login", "in", "authserver", "is", "a", "good", "one", "." ]
40d5e56e717f88f6b2b9a725ca77a90b0a775535
https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L150-L188
31,450
af83/oauth2_client_node
lib/oauth2_client.js
function(oauth2_server_id, res, next_url, state) { var sconfig = this.config.servers[oauth2_server_id]; var cconfig = this.config.client; var data = { client_id: sconfig.client_id, redirect_uri: cconfig.redirect_uri, response_type: 'code', state: this.serializer.stringify([oauth2_server_id, next_url, state || null]) }; var url = sconfig.server_authorize_endpoint +'?'+ querystring.stringify(data); redirect(res, url); }
javascript
function(oauth2_server_id, res, next_url, state) { var sconfig = this.config.servers[oauth2_server_id]; var cconfig = this.config.client; var data = { client_id: sconfig.client_id, redirect_uri: cconfig.redirect_uri, response_type: 'code', state: this.serializer.stringify([oauth2_server_id, next_url, state || null]) }; var url = sconfig.server_authorize_endpoint +'?'+ querystring.stringify(data); redirect(res, url); }
[ "function", "(", "oauth2_server_id", ",", "res", ",", "next_url", ",", "state", ")", "{", "var", "sconfig", "=", "this", ".", "config", ".", "servers", "[", "oauth2_server_id", "]", ";", "var", "cconfig", "=", "this", ".", "config", ".", "client", ";", ...
Redirects the user to OAuth2 server for authentication. Arguments: - oauth2_server_id: OAuth2 server identification (ex: "facebook.com"). - res - next_url: an url to redirect to once the process is complete. - state: optional, a hash containing info you want to retrieve at the end of the process.
[ "Redirects", "the", "user", "to", "OAuth2", "server", "for", "authentication", "." ]
40d5e56e717f88f6b2b9a725ca77a90b0a775535
https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L200-L211
31,451
af83/oauth2_client_node
lib/oauth2_client.js
function(req, params) { if(!params) { params = URL.parse(req.url, true).query; } var cconfig = this.config.client; var next = params.next || cconfig.default_redirection_url; var url = cconfig.base_url + next; return url; }
javascript
function(req, params) { if(!params) { params = URL.parse(req.url, true).query; } var cconfig = this.config.client; var next = params.next || cconfig.default_redirection_url; var url = cconfig.base_url + next; return url; }
[ "function", "(", "req", ",", "params", ")", "{", "if", "(", "!", "params", ")", "{", "params", "=", "URL", ".", "parse", "(", "req", ".", "url", ",", "true", ")", ".", "query", ";", "}", "var", "cconfig", "=", "this", ".", "config", ".", "clien...
Returns value of next url query parameter if present, default otherwise. The next query parameter should not contain the domain, the result will.
[ "Returns", "value", "of", "next", "url", "query", "parameter", "if", "present", "default", "otherwise", ".", "The", "next", "query", "parameter", "should", "not", "contain", "the", "domain", "the", "result", "will", "." ]
40d5e56e717f88f6b2b9a725ca77a90b0a775535
https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L217-L225
31,452
af83/oauth2_client_node
lib/oauth2_client.js
function(req, res) { var params = URL.parse(req.url, true).query; var oauth2_server_id = params.provider || this.config.default_server; var next_url = this.nexturl_query(req, params); this.redirects_for_login(oauth2_server_id, res, next_url); }
javascript
function(req, res) { var params = URL.parse(req.url, true).query; var oauth2_server_id = params.provider || this.config.default_server; var next_url = this.nexturl_query(req, params); this.redirects_for_login(oauth2_server_id, res, next_url); }
[ "function", "(", "req", ",", "res", ")", "{", "var", "params", "=", "URL", ".", "parse", "(", "req", ".", "url", ",", "true", ")", ".", "query", ";", "var", "oauth2_server_id", "=", "params", ".", "provider", "||", "this", ".", "config", ".", "defa...
Triggers redirects_for_login with next param if present in url query.
[ "Triggers", "redirects_for_login", "with", "next", "param", "if", "present", "in", "url", "query", "." ]
40d5e56e717f88f6b2b9a725ca77a90b0a775535
https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L238-L243
31,453
af83/oauth2_client_node
lib/oauth2_client.js
function() { var client = this; var cconf = this.config.client; return router(function(app) { app.get(cconf.process_login_url, client.auth_process_login.bind(client)); app.get(cconf.login_url, client.login.bind(client)); app.get(cconf.logout_url, client.logout.bind(client)); }); }
javascript
function() { var client = this; var cconf = this.config.client; return router(function(app) { app.get(cconf.process_login_url, client.auth_process_login.bind(client)); app.get(cconf.login_url, client.login.bind(client)); app.get(cconf.logout_url, client.logout.bind(client)); }); }
[ "function", "(", ")", "{", "var", "client", "=", "this", ";", "var", "cconf", "=", "this", ".", "config", ".", "client", ";", "return", "router", "(", "function", "(", "app", ")", "{", "app", ".", "get", "(", "cconf", ".", "process_login_url", ",", ...
Returns OAuth2 client connect middleware. This middleware will intercep requests aiming at OAuth2 client and treat them.
[ "Returns", "OAuth2", "client", "connect", "middleware", "." ]
40d5e56e717f88f6b2b9a725ca77a90b0a775535
https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L251-L260
31,454
af83/oauth2_client_node
lib/oauth2_client.js
createClient
function createClient(conf, options) { conf.default_redirection_url = conf.default_redirection_url || '/'; options = options || {}; return new OAuth2Client(conf, options); }
javascript
function createClient(conf, options) { conf.default_redirection_url = conf.default_redirection_url || '/'; options = options || {}; return new OAuth2Client(conf, options); }
[ "function", "createClient", "(", "conf", ",", "options", ")", "{", "conf", ".", "default_redirection_url", "=", "conf", ".", "default_redirection_url", "||", "'/'", ";", "options", "=", "options", "||", "{", "}", ";", "return", "new", "OAuth2Client", "(", "c...
Returns OAuth2 client Arguments: - config: hash containing: - client, hash containing: - base_url: The base URL of the OAuth2 client. Ex: http://domain.com:8080 - process_login_url: the URL where to the OAuth2 server must redirect the user when authenticated. - login_url: the URL where the user must go to be redirected to OAuth2 server for authentication. - logout_url: the URL where the user must go so that his session is cleared, and he is unlogged from client. - default_redirection_url: default URL to redirect to after login / logout. Optional, default to '/'. - crypt_key: string, encryption key used to crypt information contained in the states. This is a symmetric key and must be kept secret. - sign_key: string, signature key used to sign (HMAC) issued states. This is a symmetric key and must be kept secret. - default_server: which server to use for default login when user access login_url (ex: 'facebook.com'). - servers: hash associating OAuth2 server ids (ex: "facebook.com") with a hash containing (for each): - server_authorize_endpoint: full URL, OAuth2 server token endpoint (ex: "https://graph.facebook.com/oauth/authorize"). - server_token_endpoint: full url, where to check the token (ex: "https://graph.facebook.com/oauth/access_token"). - client_id: the client id as registered by this OAuth2 server. - client_secret: shared secret between client and this OAuth2 server. - options: optional, hash associating OAuth2 server ids (ex: "facebook.com") with hash containing some options specific to the server. Not all servers have to be listed here, neither all options. Possible options: - valid_grant: a function which will replace the default one to check the grant is ok. You might want to use this shortcut if you have a faster way of checking than requesting the OAuth2 server with an HTTP request. - treat_access_token: a function which will replace the default one to do something with the access token. You will tipically use that function to set some info in session. - transform_token_response: a function which will replace the default one to obtain a hash containing the access_token from the OAuth2 server reply. This method should be provided if the OAuth2 server we are requesting does not return JSON encoded data.
[ "Returns", "OAuth2", "client" ]
40d5e56e717f88f6b2b9a725ca77a90b0a775535
https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L314-L318
31,455
bvalosek/tiny-ecs
lib/Loop.js
Loop
function Loop(messenger) { // Messenger we'll use for clock signals this.messenger = messenger || new Messenger(); this.fixedDuration = 8; this.started = false; // Live stats this.currentTime = 0; this.fixedStepsPerFrame = 0; this.fixedTimePerFrame = 0; this.renderTimePerFrame = 0; this.frameTime = 0; }
javascript
function Loop(messenger) { // Messenger we'll use for clock signals this.messenger = messenger || new Messenger(); this.fixedDuration = 8; this.started = false; // Live stats this.currentTime = 0; this.fixedStepsPerFrame = 0; this.fixedTimePerFrame = 0; this.renderTimePerFrame = 0; this.frameTime = 0; }
[ "function", "Loop", "(", "messenger", ")", "{", "// Messenger we'll use for clock signals", "this", ".", "messenger", "=", "messenger", "||", "new", "Messenger", "(", ")", ";", "this", ".", "fixedDuration", "=", "8", ";", "this", ".", "started", "=", "false", ...
Game loop with independent clock events for fixed durations and variable durations. @param {Messenger} messenger @constructor
[ "Game", "loop", "with", "independent", "clock", "events", "for", "fixed", "durations", "and", "variable", "durations", "." ]
c74f65660f622a9a32eca200f49fafc1728e6d4d
https://github.com/bvalosek/tiny-ecs/blob/c74f65660f622a9a32eca200f49fafc1728e6d4d/lib/Loop.js#L11-L25
31,456
ryanseys/lune
lib/lune.js
kepler
function kepler (m, ecc) { const epsilon = 1e-6 m = torad(m) let e = m while (1) { const delta = e - ecc * Math.sin(e) - m e -= delta / (1.0 - ecc * Math.cos(e)) if (Math.abs(delta) <= epsilon) { break } } return e }
javascript
function kepler (m, ecc) { const epsilon = 1e-6 m = torad(m) let e = m while (1) { const delta = e - ecc * Math.sin(e) - m e -= delta / (1.0 - ecc * Math.cos(e)) if (Math.abs(delta) <= epsilon) { break } } return e }
[ "function", "kepler", "(", "m", ",", "ecc", ")", "{", "const", "epsilon", "=", "1e-6", "m", "=", "torad", "(", "m", ")", "let", "e", "=", "m", "while", "(", "1", ")", "{", "const", "delta", "=", "e", "-", "ecc", "*", "Math", ".", "sin", "(", ...
Solve the equation of Kepler.
[ "Solve", "the", "equation", "of", "Kepler", "." ]
667d6ff778d0deb2cd09988e3d89eb8ca0428a23
https://github.com/ryanseys/lune/blob/667d6ff778d0deb2cd09988e3d89eb8ca0428a23/lib/lune.js#L99-L114
31,457
ryanseys/lune
lib/lune.js
phase
function phase (phase_date) { if (!phase_date) { phase_date = new Date() } phase_date = julian.fromDate(phase_date) const day = phase_date - EPOCH // calculate sun position const sun_mean_anomaly = (360.0 / 365.2422) * day + (ECLIPTIC_LONGITUDE_EPOCH - ECLIPTIC_LONGITUDE_PERIGEE) const sun_true_anomaly = 2 * todeg(Math.atan( Math.sqrt((1.0 + ECCENTRICITY) / (1.0 - ECCENTRICITY)) * Math.tan(0.5 * kepler(sun_mean_anomaly, ECCENTRICITY)) )) const sun_ecliptic_longitude = ECLIPTIC_LONGITUDE_PERIGEE + sun_true_anomaly const sun_orbital_distance_factor = (1 + ECCENTRICITY * dcos(sun_true_anomaly)) / (1 - ECCENTRICITY * ECCENTRICITY) // calculate moon position const moon_mean_longitude = MOON_MEAN_LONGITUDE_EPOCH + 13.1763966 * day const moon_mean_anomaly = moon_mean_longitude - 0.1114041 * day - MOON_MEAN_PERIGEE_EPOCH const moon_evection = 1.2739 * dsin( 2 * (moon_mean_longitude - sun_ecliptic_longitude) - moon_mean_anomaly ) const moon_annual_equation = 0.1858 * dsin(sun_mean_anomaly) // XXX: what is the proper name for this value? const moon_mp = moon_mean_anomaly + moon_evection - moon_annual_equation - 0.37 * dsin(sun_mean_anomaly) const moon_equation_center_correction = 6.2886 * dsin(moon_mp) const moon_corrected_longitude = moon_mean_longitude + moon_evection + moon_equation_center_correction - moon_annual_equation + 0.214 * dsin(2.0 * moon_mp) const moon_age = fixangle( moon_corrected_longitude - sun_ecliptic_longitude + 0.6583 * dsin( 2 * (moon_corrected_longitude - sun_ecliptic_longitude) ) ) const moon_distance = (MOON_SMAXIS * (1.0 - MOON_ECCENTRICITY * MOON_ECCENTRICITY)) / (1.0 + MOON_ECCENTRICITY * dcos(moon_mp + moon_equation_center_correction)) return { phase: (1.0 / 360.0) * moon_age, illuminated: 0.5 * (1.0 - dcos(moon_age)), age: (SYNODIC_MONTH / 360.0) * moon_age, distance: moon_distance, angular_diameter: MOON_ANGULAR_SIZE_SMAXIS / moon_distance, sun_distance: SUN_SMAXIS / sun_orbital_distance_factor, sun_angular_diameter: SUN_ANGULAR_SIZE_SMAXIS * sun_orbital_distance_factor } }
javascript
function phase (phase_date) { if (!phase_date) { phase_date = new Date() } phase_date = julian.fromDate(phase_date) const day = phase_date - EPOCH // calculate sun position const sun_mean_anomaly = (360.0 / 365.2422) * day + (ECLIPTIC_LONGITUDE_EPOCH - ECLIPTIC_LONGITUDE_PERIGEE) const sun_true_anomaly = 2 * todeg(Math.atan( Math.sqrt((1.0 + ECCENTRICITY) / (1.0 - ECCENTRICITY)) * Math.tan(0.5 * kepler(sun_mean_anomaly, ECCENTRICITY)) )) const sun_ecliptic_longitude = ECLIPTIC_LONGITUDE_PERIGEE + sun_true_anomaly const sun_orbital_distance_factor = (1 + ECCENTRICITY * dcos(sun_true_anomaly)) / (1 - ECCENTRICITY * ECCENTRICITY) // calculate moon position const moon_mean_longitude = MOON_MEAN_LONGITUDE_EPOCH + 13.1763966 * day const moon_mean_anomaly = moon_mean_longitude - 0.1114041 * day - MOON_MEAN_PERIGEE_EPOCH const moon_evection = 1.2739 * dsin( 2 * (moon_mean_longitude - sun_ecliptic_longitude) - moon_mean_anomaly ) const moon_annual_equation = 0.1858 * dsin(sun_mean_anomaly) // XXX: what is the proper name for this value? const moon_mp = moon_mean_anomaly + moon_evection - moon_annual_equation - 0.37 * dsin(sun_mean_anomaly) const moon_equation_center_correction = 6.2886 * dsin(moon_mp) const moon_corrected_longitude = moon_mean_longitude + moon_evection + moon_equation_center_correction - moon_annual_equation + 0.214 * dsin(2.0 * moon_mp) const moon_age = fixangle( moon_corrected_longitude - sun_ecliptic_longitude + 0.6583 * dsin( 2 * (moon_corrected_longitude - sun_ecliptic_longitude) ) ) const moon_distance = (MOON_SMAXIS * (1.0 - MOON_ECCENTRICITY * MOON_ECCENTRICITY)) / (1.0 + MOON_ECCENTRICITY * dcos(moon_mp + moon_equation_center_correction)) return { phase: (1.0 / 360.0) * moon_age, illuminated: 0.5 * (1.0 - dcos(moon_age)), age: (SYNODIC_MONTH / 360.0) * moon_age, distance: moon_distance, angular_diameter: MOON_ANGULAR_SIZE_SMAXIS / moon_distance, sun_distance: SUN_SMAXIS / sun_orbital_distance_factor, sun_angular_diameter: SUN_ANGULAR_SIZE_SMAXIS * sun_orbital_distance_factor } }
[ "function", "phase", "(", "phase_date", ")", "{", "if", "(", "!", "phase_date", ")", "{", "phase_date", "=", "new", "Date", "(", ")", "}", "phase_date", "=", "julian", ".", "fromDate", "(", "phase_date", ")", "const", "day", "=", "phase_date", "-", "EP...
Finds the phase information for specific date. @param {Date} phase_date Date to get phase information of. @return {Object} Phase data
[ "Finds", "the", "phase", "information", "for", "specific", "date", "." ]
667d6ff778d0deb2cd09988e3d89eb8ca0428a23
https://github.com/ryanseys/lune/blob/667d6ff778d0deb2cd09988e3d89eb8ca0428a23/lib/lune.js#L121-L190
31,458
ryanseys/lune
lib/lune.js
phase_hunt
function phase_hunt (sdate) { if (!sdate) { sdate = new Date() } let adate = new Date(sdate.getTime() - (45 * 86400000)) // 45 days prior let k1 = Math.floor(12.3685 * (adate.getFullYear() + (1.0 / 12.0) * adate.getMonth() - 1900)) let nt1 = meanphase(adate.getTime(), k1) sdate = julian.fromDate(sdate) adate = nt1 + SYNODIC_MONTH let k2 = k1 + 1 let nt2 = meanphase(adate, k2) while (nt1 > sdate || sdate >= nt2) { adate += SYNODIC_MONTH k1++ k2++ nt1 = nt2 nt2 = meanphase(adate, k2) } return { new_date: truephase(k1, NEW), q1_date: truephase(k1, FIRST), full_date: truephase(k1, FULL), q3_date: truephase(k1, LAST), nextnew_date: truephase(k2, NEW) } }
javascript
function phase_hunt (sdate) { if (!sdate) { sdate = new Date() } let adate = new Date(sdate.getTime() - (45 * 86400000)) // 45 days prior let k1 = Math.floor(12.3685 * (adate.getFullYear() + (1.0 / 12.0) * adate.getMonth() - 1900)) let nt1 = meanphase(adate.getTime(), k1) sdate = julian.fromDate(sdate) adate = nt1 + SYNODIC_MONTH let k2 = k1 + 1 let nt2 = meanphase(adate, k2) while (nt1 > sdate || sdate >= nt2) { adate += SYNODIC_MONTH k1++ k2++ nt1 = nt2 nt2 = meanphase(adate, k2) } return { new_date: truephase(k1, NEW), q1_date: truephase(k1, FIRST), full_date: truephase(k1, FULL), q3_date: truephase(k1, LAST), nextnew_date: truephase(k2, NEW) } }
[ "function", "phase_hunt", "(", "sdate", ")", "{", "if", "(", "!", "sdate", ")", "{", "sdate", "=", "new", "Date", "(", ")", "}", "let", "adate", "=", "new", "Date", "(", "sdate", ".", "getTime", "(", ")", "-", "(", "45", "*", "86400000", ")", "...
Find time of phases of the moon which surround the current date. Five phases are found, starting and ending with the new moons which bound the current lunation. @param {Date} sdate Date to start hunting from (defaults to current date) @return {Object} Object containing recent past and future phases
[ "Find", "time", "of", "phases", "of", "the", "moon", "which", "surround", "the", "current", "date", ".", "Five", "phases", "are", "found", "starting", "and", "ending", "with", "the", "new", "moons", "which", "bound", "the", "current", "lunation", "." ]
667d6ff778d0deb2cd09988e3d89eb8ca0428a23
https://github.com/ryanseys/lune/blob/667d6ff778d0deb2cd09988e3d89eb8ca0428a23/lib/lune.js#L301-L329
31,459
dundalek/react-blessed-contrib
examples/dashboard.js
generateTable
function generateTable() { var data = [] for (var i=0; i<30; i++) { var row = [] row.push(commands[Math.round(Math.random()*(commands.length-1))]) row.push(Math.round(Math.random()*5)) row.push(Math.round(Math.random()*100)) data.push(row) } return {headers: ['Process', 'Cpu (%)', 'Memory'], data: data}; }
javascript
function generateTable() { var data = [] for (var i=0; i<30; i++) { var row = [] row.push(commands[Math.round(Math.random()*(commands.length-1))]) row.push(Math.round(Math.random()*5)) row.push(Math.round(Math.random()*100)) data.push(row) } return {headers: ['Process', 'Cpu (%)', 'Memory'], data: data}; }
[ "function", "generateTable", "(", ")", "{", "var", "data", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "30", ";", "i", "++", ")", "{", "var", "row", "=", "[", "]", "row", ".", "push", "(", "commands", "[", "Math", ".", "...
set dummy data for table
[ "set", "dummy", "data", "for", "table" ]
2beb36f4416665aaca5dfb85a49dbcd625911e1d
https://github.com/dundalek/react-blessed-contrib/blob/2beb36f4416665aaca5dfb85a49dbcd625911e1d/examples/dashboard.js#L13-L25
31,460
dundalek/react-blessed-contrib
src/index.js
Grid
function Grid(props) { const grid = new contrib.grid({...props, screen: { append: () => {} }}); const children = props.children instanceof Array ? props.children : [props.children]; return React.createElement(props.component || 'element', {}, children.map((child, key) => { const props = child.props; const options = grid.set(props.row, props.col, props.rowSpan || 1, props.colSpan || 1, x => x, props.options); options.key = key; return React.cloneElement(child, options); })); }
javascript
function Grid(props) { const grid = new contrib.grid({...props, screen: { append: () => {} }}); const children = props.children instanceof Array ? props.children : [props.children]; return React.createElement(props.component || 'element', {}, children.map((child, key) => { const props = child.props; const options = grid.set(props.row, props.col, props.rowSpan || 1, props.colSpan || 1, x => x, props.options); options.key = key; return React.cloneElement(child, options); })); }
[ "function", "Grid", "(", "props", ")", "{", "const", "grid", "=", "new", "contrib", ".", "grid", "(", "{", "...", "props", ",", "screen", ":", "{", "append", ":", "(", ")", "=>", "{", "}", "}", "}", ")", ";", "const", "children", "=", "props", ...
We stub methods for contrib.grid to let it compute params for us which we then render in the React way
[ "We", "stub", "methods", "for", "contrib", ".", "grid", "to", "let", "it", "compute", "params", "for", "us", "which", "we", "then", "render", "in", "the", "React", "way" ]
2beb36f4416665aaca5dfb85a49dbcd625911e1d
https://github.com/dundalek/react-blessed-contrib/blob/2beb36f4416665aaca5dfb85a49dbcd625911e1d/src/index.js#L53-L62
31,461
grncdr/js-shell-parse
build.js
parse
function parse (input, opts) { // Wrap parser.parse to allow specifying the start rule // as a shorthand option if (!opts) { opts = {} } else if (typeof opts == 'string') { opts = { startRule: opts } } return parser.parse(input, opts) }
javascript
function parse (input, opts) { // Wrap parser.parse to allow specifying the start rule // as a shorthand option if (!opts) { opts = {} } else if (typeof opts == 'string') { opts = { startRule: opts } } return parser.parse(input, opts) }
[ "function", "parse", "(", "input", ",", "opts", ")", "{", "// Wrap parser.parse to allow specifying the start rule", "// as a shorthand option", "if", "(", "!", "opts", ")", "{", "opts", "=", "{", "}", "}", "else", "if", "(", "typeof", "opts", "==", "'string'", ...
This isn't called directly, but stringified into the resulting source
[ "This", "isn", "t", "called", "directly", "but", "stringified", "into", "the", "resulting", "source" ]
f5f65af37f42b120912bbad608e9da1cd909c27c
https://github.com/grncdr/js-shell-parse/blob/f5f65af37f42b120912bbad608e9da1cd909c27c/build.js#L58-L68
31,462
easylogic/codemirror-colorpicker
addon/codemirror-colorpicker.js
partial
function partial(area) { var allFilter = null; for (var _len2 = arguments.length, filters = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { filters[_key2 - 1] = arguments[_key2]; } if (filters.length == 1 && typeof filters[0] === 'string') { allFilter = filter$1(filters[0]); } else { allFilter = merge$1(filters); } return function (bitmap, done) { var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; allFilter(getBitmap(bitmap, area), function (newBitmap) { done(putBitmap(bitmap, newBitmap, area)); }, opt); }; }
javascript
function partial(area) { var allFilter = null; for (var _len2 = arguments.length, filters = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { filters[_key2 - 1] = arguments[_key2]; } if (filters.length == 1 && typeof filters[0] === 'string') { allFilter = filter$1(filters[0]); } else { allFilter = merge$1(filters); } return function (bitmap, done) { var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; allFilter(getBitmap(bitmap, area), function (newBitmap) { done(putBitmap(bitmap, newBitmap, area)); }, opt); }; }
[ "function", "partial", "(", "area", ")", "{", "var", "allFilter", "=", "null", ";", "for", "(", "var", "_len2", "=", "arguments", ".", "length", ",", "filters", "=", "Array", "(", "_len2", ">", "1", "?", "_len2", "-", "1", ":", "0", ")", ",", "_k...
apply filter into special area F.partial({x,y,width,height}, filter, filter, filter ) F.partial({x,y,width,height}, 'filter' ) @param {{x, y, width, height}} area @param {*} filters
[ "apply", "filter", "into", "special", "area" ]
5dc686d8394b89fefb1ff1ac968521575f41d1cd
https://github.com/easylogic/codemirror-colorpicker/blob/5dc686d8394b89fefb1ff1ac968521575f41d1cd/addon/codemirror-colorpicker.js#L4028-L4048
31,463
darach/eep-js
samples/custom.js
function(regex) { var self = this; var re = new RegExp(regex); var keys = {}; self.init = function() { keys = {}; }; self.accumulate = function(line) { var m = re.exec(line); if (m == null) return; var k = m[1]; // use 1st group as key var v = keys[k]; if (v) keys[k] = v+1; else keys[k] = 1; // count by key }; self.compensate = function(line) { var m = re.exec(line); if (m == null) return; var k = m[1]; // use 1st group as key var v = keys[k]; if (v) keys[k] = v-1; else keys[k] = 1; }; self.emit = function() { return keys; }; self.make = function() { return new WideFinderFunction(regex); }; }
javascript
function(regex) { var self = this; var re = new RegExp(regex); var keys = {}; self.init = function() { keys = {}; }; self.accumulate = function(line) { var m = re.exec(line); if (m == null) return; var k = m[1]; // use 1st group as key var v = keys[k]; if (v) keys[k] = v+1; else keys[k] = 1; // count by key }; self.compensate = function(line) { var m = re.exec(line); if (m == null) return; var k = m[1]; // use 1st group as key var v = keys[k]; if (v) keys[k] = v-1; else keys[k] = 1; }; self.emit = function() { return keys; }; self.make = function() { return new WideFinderFunction(regex); }; }
[ "function", "(", "regex", ")", "{", "var", "self", "=", "this", ";", "var", "re", "=", "new", "RegExp", "(", "regex", ")", ";", "var", "keys", "=", "{", "}", ";", "self", ".", "init", "=", "function", "(", ")", "{", "keys", "=", "{", "}", ";"...
Widefinder aggregate function
[ "Widefinder", "aggregate", "function" ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/samples/custom.js#L9-L31
31,464
darach/eep-js
lib/eep.aggregate_function.js
AggregateFunction
function AggregateFunction() { var self = this; // function type can be one of // - simple (default) // - ordered - will require window to store elements in arrival and sorted order // self.type = "simple"; // invoked when a window opens - should 'reset' or 'zero' a windows internal state self.init = function() { throw "Must subclass"; }; // invoked when an event is enqueued into a window self.accumulate = function(value) { throw "Must subclass"; }; // invoked to compensate sliding window overwrite self.compensate = function(value) { throw "Must subclass"; }; // invoked when a window closes self.emit = function() { throw "Must subclass"; }; // used by window implementations variously to preallocate function instances - makes things 'fast', basically self.make = function(win) { throw "Must subclass"; }; }
javascript
function AggregateFunction() { var self = this; // function type can be one of // - simple (default) // - ordered - will require window to store elements in arrival and sorted order // self.type = "simple"; // invoked when a window opens - should 'reset' or 'zero' a windows internal state self.init = function() { throw "Must subclass"; }; // invoked when an event is enqueued into a window self.accumulate = function(value) { throw "Must subclass"; }; // invoked to compensate sliding window overwrite self.compensate = function(value) { throw "Must subclass"; }; // invoked when a window closes self.emit = function() { throw "Must subclass"; }; // used by window implementations variously to preallocate function instances - makes things 'fast', basically self.make = function(win) { throw "Must subclass"; }; }
[ "function", "AggregateFunction", "(", ")", "{", "var", "self", "=", "this", ";", "// function type can be one of", "// - simple (default)", "// - ordered - will require window to store elements in arrival and sorted order", "//", "self", ".", "type", "=", "\"simple\"", ";", "...
Constraints computations on event streams to a simple functional contract
[ "Constraints", "computations", "on", "event", "streams", "to", "a", "simple", "functional", "contract" ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.aggregate_function.js#L25-L42
31,465
darach/eep-js
lib/eep.fn.stats.js
CountFunction
function CountFunction(win) { var self = this, n; self.name = "count"; self.type = "simple"; self.init = function() { n = 0; }; self.accumulate = function(ignored) { n += 1; }; self.compensate = function(ignored) { n -= 1; }; self.emit = function() { return n; }; self.make = function(win) { return new CountFunction(win); }; }
javascript
function CountFunction(win) { var self = this, n; self.name = "count"; self.type = "simple"; self.init = function() { n = 0; }; self.accumulate = function(ignored) { n += 1; }; self.compensate = function(ignored) { n -= 1; }; self.emit = function() { return n; }; self.make = function(win) { return new CountFunction(win); }; }
[ "function", "CountFunction", "(", "win", ")", "{", "var", "self", "=", "this", ",", "n", ";", "self", ".", "name", "=", "\"count\"", ";", "self", ".", "type", "=", "\"simple\"", ";", "self", ".", "init", "=", "function", "(", ")", "{", "n", "=", ...
Count all the things
[ "Count", "all", "the", "things" ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L26-L35
31,466
darach/eep-js
lib/eep.fn.stats.js
SumFunction
function SumFunction(win) { var self = this, s; self.name = "sum"; self.type = "simple"; self.init = function() { s = 0; }; self.accumulate = function(v) { s += v; }; self.compensate = function(v) { s -= v; }; self.emit = function() { return s; }; self.make = function(win) { return new SumFunction(win); }; }
javascript
function SumFunction(win) { var self = this, s; self.name = "sum"; self.type = "simple"; self.init = function() { s = 0; }; self.accumulate = function(v) { s += v; }; self.compensate = function(v) { s -= v; }; self.emit = function() { return s; }; self.make = function(win) { return new SumFunction(win); }; }
[ "function", "SumFunction", "(", "win", ")", "{", "var", "self", "=", "this", ",", "s", ";", "self", ".", "name", "=", "\"sum\"", ";", "self", ".", "type", "=", "\"simple\"", ";", "self", ".", "init", "=", "function", "(", ")", "{", "s", "=", "0",...
Sum all the things
[ "Sum", "all", "the", "things" ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L39-L48
31,467
darach/eep-js
lib/eep.fn.stats.js
MinFunction
function MinFunction(win) { var self = this, r; self.win = win; self.name = "min"; self.type = "ordered_reverse"; self.init = function() { r = null; }; self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v < r) ? v : r; }; self.compensate = function(v) { r = self.win.min(); }; self.emit = function() { return r; }; self.make = function(win) { return new MinFunction(win); }; }
javascript
function MinFunction(win) { var self = this, r; self.win = win; self.name = "min"; self.type = "ordered_reverse"; self.init = function() { r = null; }; self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v < r) ? v : r; }; self.compensate = function(v) { r = self.win.min(); }; self.emit = function() { return r; }; self.make = function(win) { return new MinFunction(win); }; }
[ "function", "MinFunction", "(", "win", ")", "{", "var", "self", "=", "this", ",", "r", ";", "self", ".", "win", "=", "win", ";", "self", ".", "name", "=", "\"min\"", ";", "self", ".", "type", "=", "\"ordered_reverse\"", ";", "self", ".", "init", "=...
Get the smallest of all the things
[ "Get", "the", "smallest", "of", "all", "the", "things" ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L52-L62
31,468
darach/eep-js
lib/eep.fn.stats.js
MaxFunction
function MaxFunction(win) { var self = this, r; self.win = win; self.name = "max"; self.type = "ordered_reverse"; self.init = function() { r = null; }; self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v > r) ? v : r; }; self.compensate = function(v) { r = self.win.max(); }; self.emit = function() { return r; }; self.make = function(win) { return new MaxFunction(win); }; }
javascript
function MaxFunction(win) { var self = this, r; self.win = win; self.name = "max"; self.type = "ordered_reverse"; self.init = function() { r = null; }; self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v > r) ? v : r; }; self.compensate = function(v) { r = self.win.max(); }; self.emit = function() { return r; }; self.make = function(win) { return new MaxFunction(win); }; }
[ "function", "MaxFunction", "(", "win", ")", "{", "var", "self", "=", "this", ",", "r", ";", "self", ".", "win", "=", "win", ";", "self", ".", "name", "=", "\"max\"", ";", "self", ".", "type", "=", "\"ordered_reverse\"", ";", "self", ".", "init", "=...
Get the biggest of all the things
[ "Get", "the", "biggest", "of", "all", "the", "things" ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L66-L76
31,469
darach/eep-js
lib/eep.fn.stats.js
VarianceFunction
function VarianceFunction(win) { var self = this, m, m2, d, n; self.name = "vars"; self.type = "simple"; self.init = function() { m = 0; m2 = 0; d = 0; n = 0; }; self.accumulate = function(v) { n+=1; d = v - m; m = d/n + m; m2 = m2 + d*(v - m); }; self.compensate = function(v) { n-=1; d = m - v; m = m + d/n; m2 = d*(v - m) + m2; }; self.emit = function() { return m2/(n-1); }; self.make = function(win) { return new VarianceFunction(win); }; }
javascript
function VarianceFunction(win) { var self = this, m, m2, d, n; self.name = "vars"; self.type = "simple"; self.init = function() { m = 0; m2 = 0; d = 0; n = 0; }; self.accumulate = function(v) { n+=1; d = v - m; m = d/n + m; m2 = m2 + d*(v - m); }; self.compensate = function(v) { n-=1; d = m - v; m = m + d/n; m2 = d*(v - m) + m2; }; self.emit = function() { return m2/(n-1); }; self.make = function(win) { return new VarianceFunction(win); }; }
[ "function", "VarianceFunction", "(", "win", ")", "{", "var", "self", "=", "this", ",", "m", ",", "m2", ",", "d", ",", "n", ";", "self", ".", "name", "=", "\"vars\"", ";", "self", ".", "type", "=", "\"simple\"", ";", "self", ".", "init", "=", "fun...
Get the sample variance of all the things
[ "Get", "the", "sample", "variance", "of", "all", "the", "things" ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L93-L102
31,470
darach/eep-js
lib/eep.fn.stats.js
StdevFunction
function StdevFunction(win) { var self = this, m, m2, d, n; self.name = "stdevs"; self.type = "simple"; self.init = function() { m = 0, m2 = 0, d = 0, n = 0; }; self.accumulate = function(v) { n+=1; d = v - m; m = m + d/n; m2 = m2 + d*(v-m); }; self.compensate = function(v) { n-=1; d = m - v; m = d/n + m; m2 = d*(v-m) + m2; }; self.emit = function() { return Math.sqrt(m2/(n-1)); }; self.make = function(win) { return new StdevFunction(win); }; }
javascript
function StdevFunction(win) { var self = this, m, m2, d, n; self.name = "stdevs"; self.type = "simple"; self.init = function() { m = 0, m2 = 0, d = 0, n = 0; }; self.accumulate = function(v) { n+=1; d = v - m; m = m + d/n; m2 = m2 + d*(v-m); }; self.compensate = function(v) { n-=1; d = m - v; m = d/n + m; m2 = d*(v-m) + m2; }; self.emit = function() { return Math.sqrt(m2/(n-1)); }; self.make = function(win) { return new StdevFunction(win); }; }
[ "function", "StdevFunction", "(", "win", ")", "{", "var", "self", "=", "this", ",", "m", ",", "m2", ",", "d", ",", "n", ";", "self", ".", "name", "=", "\"stdevs\"", ";", "self", ".", "type", "=", "\"simple\"", ";", "self", ".", "init", "=", "func...
Get the standard deviation of all the things
[ "Get", "the", "standard", "deviation", "of", "all", "the", "things" ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L106-L125
31,471
darach/eep-js
lib/eep.clock_counting.js
CountingClock
function CountingClock() { var self = this, at, mark = null; self.at = function() { return at; }; self.init = function() { at = mark = 0; return at; }; self.inc = function() { at += 1; }; self.tick = function() { if (mark === null) { mark = at + 1; } return ((at - mark) >= 1); }; self.tock = function(elapsed) { var d = at - elapsed; if ( d >= 1) { mark += 1; return true; } return false; }; }
javascript
function CountingClock() { var self = this, at, mark = null; self.at = function() { return at; }; self.init = function() { at = mark = 0; return at; }; self.inc = function() { at += 1; }; self.tick = function() { if (mark === null) { mark = at + 1; } return ((at - mark) >= 1); }; self.tock = function(elapsed) { var d = at - elapsed; if ( d >= 1) { mark += 1; return true; } return false; }; }
[ "function", "CountingClock", "(", ")", "{", "var", "self", "=", "this", ",", "at", ",", "mark", "=", "null", ";", "self", ".", "at", "=", "function", "(", ")", "{", "return", "at", ";", "}", ";", "self", ".", "init", "=", "function", "(", ")", ...
Simple monotonic clock. Ticks and tocks like the count on Sesame St. Mwa ha ha. Monotonic, basically.
[ "Simple", "monotonic", "clock", ".", "Ticks", "and", "tocks", "like", "the", "count", "on", "Sesame", "St", ".", "Mwa", "ha", "ha", ".", "Monotonic", "basically", "." ]
1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6
https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.clock_counting.js#L26-L58
31,472
nymag/nymag-fs
index.js
getFolders
function getFolders(dir) { try { return fs.readdirSync(dir) .filter(function (file) { return exports.isDirectory(path.join(dir, file)); }); } catch (ex) { return []; } }
javascript
function getFolders(dir) { try { return fs.readdirSync(dir) .filter(function (file) { return exports.isDirectory(path.join(dir, file)); }); } catch (ex) { return []; } }
[ "function", "getFolders", "(", "dir", ")", "{", "try", "{", "return", "fs", ".", "readdirSync", "(", "dir", ")", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "exports", ".", "isDirectory", "(", "path", ".", "join", "(", "dir", ","...
Get folder names. Should only occur once per directory. @param {string} dir enclosing folder @return {[]} array of folder names
[ "Get", "folder", "names", "." ]
94dcd3be2c0593b676131a9760c2318c75255a71
https://github.com/nymag/nymag-fs/blob/94dcd3be2c0593b676131a9760c2318c75255a71/index.js#L80-L89
31,473
nymag/nymag-fs
index.js
tryRequire
function tryRequire(filePath) { let resolvedPath = req.resolve(filePath); if (resolvedPath) { return req(resolvedPath); } return undefined; }
javascript
function tryRequire(filePath) { let resolvedPath = req.resolve(filePath); if (resolvedPath) { return req(resolvedPath); } return undefined; }
[ "function", "tryRequire", "(", "filePath", ")", "{", "let", "resolvedPath", "=", "req", ".", "resolve", "(", "filePath", ")", ";", "if", "(", "resolvedPath", ")", "{", "return", "req", "(", "resolvedPath", ")", ";", "}", "return", "undefined", ";", "}" ]
Try to require a module, do not fail if module is missing @param {string} filePath @returns {module} @throw if fails for reason other than missing module
[ "Try", "to", "require", "a", "module", "do", "not", "fail", "if", "module", "is", "missing" ]
94dcd3be2c0593b676131a9760c2318c75255a71
https://github.com/nymag/nymag-fs/blob/94dcd3be2c0593b676131a9760c2318c75255a71/index.js#L97-L105
31,474
nymag/nymag-fs
index.js
tryRequireEach
function tryRequireEach(paths) { let result; while (!result && paths.length) { result = tryRequire(paths.shift()); } return result; }
javascript
function tryRequireEach(paths) { let result; while (!result && paths.length) { result = tryRequire(paths.shift()); } return result; }
[ "function", "tryRequireEach", "(", "paths", ")", "{", "let", "result", ";", "while", "(", "!", "result", "&&", "paths", ".", "length", ")", "{", "result", "=", "tryRequire", "(", "paths", ".", "shift", "(", ")", ")", ";", "}", "return", "result", ";"...
Try to get a module, or return false. @param {[string]} paths Possible paths to find their module. @returns {object|false}
[ "Try", "to", "get", "a", "module", "or", "return", "false", "." ]
94dcd3be2c0593b676131a9760c2318c75255a71
https://github.com/nymag/nymag-fs/blob/94dcd3be2c0593b676131a9760c2318c75255a71/index.js#L113-L121
31,475
nymag/nymag-fs
control.js
memoize
function memoize(fn) { const dataProp = '__data__.string.__data__', memFn = _.memoize.apply(_, _.slice(arguments)), report = _.throttle(reportMemoryLeak, minute), controlFn = function () { const result = memFn.apply(null, _.slice(arguments)); if (_.size(_.get(memFn, `cache.${dataProp}`)) >= memoryLeakThreshold) { report(fn, _.get(memFn, `cache.${dataProp}`)); } return result; }; Object.defineProperty(controlFn, 'cache', defineWritable({ get() { return memFn.cache; }, set(value) { memFn.cache = value; } })); return controlFn; }
javascript
function memoize(fn) { const dataProp = '__data__.string.__data__', memFn = _.memoize.apply(_, _.slice(arguments)), report = _.throttle(reportMemoryLeak, minute), controlFn = function () { const result = memFn.apply(null, _.slice(arguments)); if (_.size(_.get(memFn, `cache.${dataProp}`)) >= memoryLeakThreshold) { report(fn, _.get(memFn, `cache.${dataProp}`)); } return result; }; Object.defineProperty(controlFn, 'cache', defineWritable({ get() { return memFn.cache; }, set(value) { memFn.cache = value; } })); return controlFn; }
[ "function", "memoize", "(", "fn", ")", "{", "const", "dataProp", "=", "'__data__.string.__data__'", ",", "memFn", "=", "_", ".", "memoize", ".", "apply", "(", "_", ",", "_", ".", "slice", "(", "arguments", ")", ")", ",", "report", "=", "_", ".", "thr...
Memoize, but warn if the target is not suitable for memoization @param {function} fn @returns {function}
[ "Memoize", "but", "warn", "if", "the", "target", "is", "not", "suitable", "for", "memoization" ]
94dcd3be2c0593b676131a9760c2318c75255a71
https://github.com/nymag/nymag-fs/blob/94dcd3be2c0593b676131a9760c2318c75255a71/control.js#L42-L62
31,476
IonicaBizau/iterate-object
lib/index.js
iterateObject
function iterateObject(obj, fn) { var i = 0 , keys = [] ; if (Array.isArray(obj)) { for (; i < obj.length; ++i) { if (fn(obj[i], i, obj) === false) { break; } } } else if (typeof obj === "object" && obj !== null) { keys = Object.keys(obj); for (; i < keys.length; ++i) { if (fn(obj[keys[i]], keys[i], obj) === false) { break; } } } }
javascript
function iterateObject(obj, fn) { var i = 0 , keys = [] ; if (Array.isArray(obj)) { for (; i < obj.length; ++i) { if (fn(obj[i], i, obj) === false) { break; } } } else if (typeof obj === "object" && obj !== null) { keys = Object.keys(obj); for (; i < keys.length; ++i) { if (fn(obj[keys[i]], keys[i], obj) === false) { break; } } } }
[ "function", "iterateObject", "(", "obj", ",", "fn", ")", "{", "var", "i", "=", "0", ",", "keys", "=", "[", "]", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "for", "(", ";", "i", "<", "obj", ".", "length", ";", "++", ...
iterateObject Iterates an object. Note the object field order may differ. @name iterateObject @function @param {Object} obj The input object. @param {Function} fn A function that will be called with the current value, field name and provided object. @return {Function} The `iterateObject` function.
[ "iterateObject", "Iterates", "an", "object", ".", "Note", "the", "object", "field", "order", "may", "differ", "." ]
8c96db262c95c62524cc4c5ab7374439a5ff8971
https://github.com/IonicaBizau/iterate-object/blob/8c96db262c95c62524cc4c5ab7374439a5ff8971/lib/index.js#L11-L30
31,477
gbv/jskos-tools
lib/tools.js
compareMappingsDeep
function compareMappingsDeep(mapping1, mapping2) { return _.isEqualWith(mapping1, mapping2, (object1, object2, prop) => { let mapping1 = { [prop]: object1 } let mapping2 = { [prop]: object2 } if (prop == "from" || prop == "to") { if (!_.isEqual(Object.getOwnPropertyNames(_.get(object1, prop, {})), Object.getOwnPropertyNames(_.get(object2, prop, {})))) { return false } return _.isEqualWith(conceptsOfMapping(mapping1, prop), conceptsOfMapping(mapping2, prop), (concept1, concept2, index) => { if (index != undefined) { return compare(concept1, concept2) } return undefined }) } if (prop == "fromScheme" || prop == "toScheme") { return compare(object1, object2) } // Let lodash's isEqual do the comparison return undefined }) }
javascript
function compareMappingsDeep(mapping1, mapping2) { return _.isEqualWith(mapping1, mapping2, (object1, object2, prop) => { let mapping1 = { [prop]: object1 } let mapping2 = { [prop]: object2 } if (prop == "from" || prop == "to") { if (!_.isEqual(Object.getOwnPropertyNames(_.get(object1, prop, {})), Object.getOwnPropertyNames(_.get(object2, prop, {})))) { return false } return _.isEqualWith(conceptsOfMapping(mapping1, prop), conceptsOfMapping(mapping2, prop), (concept1, concept2, index) => { if (index != undefined) { return compare(concept1, concept2) } return undefined }) } if (prop == "fromScheme" || prop == "toScheme") { return compare(object1, object2) } // Let lodash's isEqual do the comparison return undefined }) }
[ "function", "compareMappingsDeep", "(", "mapping1", ",", "mapping2", ")", "{", "return", "_", ".", "isEqualWith", "(", "mapping1", ",", "mapping2", ",", "(", "object1", ",", "object2", ",", "prop", ")", "=>", "{", "let", "mapping1", "=", "{", "[", "prop"...
Compare two mappings based on their properties. Concept sets and schemes are compared by URI. @memberof module:jskos-tools
[ "Compare", "two", "mappings", "based", "on", "their", "properties", ".", "Concept", "sets", "and", "schemes", "are", "compared", "by", "URI", "." ]
da8672203362ea874f4ab9cdd34b990369987075
https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/tools.js#L419-L440
31,478
bem-contrib/md-to-bemjson
packages/mdast-util-to-bemjson/lib/index.js
toBemjson
function toBemjson(tree, options) { const transform = transformFactory(tree, options); return traverse(transform, tree); }
javascript
function toBemjson(tree, options) { const transform = transformFactory(tree, options); return traverse(transform, tree); }
[ "function", "toBemjson", "(", "tree", ",", "options", ")", "{", "const", "transform", "=", "transformFactory", "(", "tree", ",", "options", ")", ";", "return", "traverse", "(", "transform", ",", "tree", ")", ";", "}" ]
Augments bemNode with custom logic @callback BjsonConverter~augmentCallback @param {Object} bemNode - representation of bem entity @returns {Object} - must return bemNode Transform `tree`, which is an MDAST node, to a Bemjson node. @param {Node} tree - MDAST tree @param {Object} options - transform options @return {Object}
[ "Augments", "bemNode", "with", "custom", "logic" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/index.js#L21-L25
31,479
rangle/koast
lib/authentication/oauth.js
makeLoginHandler
function makeLoginHandler(provider, providerAccounts) { return function (accessToken, refreshToken, profile, done) { log.debug('Authentiated for ' + provider); log.debug(profile); profile.provider = provider; profile.idWithProvider = profile.id; exports.getUserFromProfile(providerAccounts, profile) .then(function (userRecord) { // Save the user if they are new. var fieldsToCopy = ['provider', 'displayName', 'emails']; if (userRecord && userRecord.data) { return userRecord; } else { userRecord = { isAuthenticated: true }; userRecord.meta = { isRegistered: false }; userRecord.data = { idWithProvider: profile.id, }; fieldsToCopy.forEach(function (key) { userRecord.data[key] = profile[key]; }); return providerAccounts.create(userRecord.data) .then(function () { return userRecord; }); } }) .then(function (userRecord) { done(null, userRecord); }) .then(null, function (error) { log.error(error); done(error); }) .then(null, log.error); }; }
javascript
function makeLoginHandler(provider, providerAccounts) { return function (accessToken, refreshToken, profile, done) { log.debug('Authentiated for ' + provider); log.debug(profile); profile.provider = provider; profile.idWithProvider = profile.id; exports.getUserFromProfile(providerAccounts, profile) .then(function (userRecord) { // Save the user if they are new. var fieldsToCopy = ['provider', 'displayName', 'emails']; if (userRecord && userRecord.data) { return userRecord; } else { userRecord = { isAuthenticated: true }; userRecord.meta = { isRegistered: false }; userRecord.data = { idWithProvider: profile.id, }; fieldsToCopy.forEach(function (key) { userRecord.data[key] = profile[key]; }); return providerAccounts.create(userRecord.data) .then(function () { return userRecord; }); } }) .then(function (userRecord) { done(null, userRecord); }) .then(null, function (error) { log.error(error); done(error); }) .then(null, log.error); }; }
[ "function", "makeLoginHandler", "(", "provider", ",", "providerAccounts", ")", "{", "return", "function", "(", "accessToken", ",", "refreshToken", ",", "profile", ",", "done", ")", "{", "log", ".", "debug", "(", "'Authentiated for '", "+", "provider", ")", ";"...
Makes a handler to be called after the user was authenticated with an OAuth provider.
[ "Makes", "a", "handler", "to", "be", "called", "after", "the", "user", "was", "authenticated", "with", "an", "OAuth", "provider", "." ]
446dfaba7f80c03ae17d86b34dfafd6328be1ba6
https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/oauth.js#L73-L117
31,480
rangle/koast
lib/authentication/oauth.js
redirectToNext
function redirectToNext(req, res) { var redirectTo = req.session.next || ''; req.session.next = null; // Null it so that we do not use it again. res.redirect(redirectTo); }
javascript
function redirectToNext(req, res) { var redirectTo = req.session.next || ''; req.session.next = null; // Null it so that we do not use it again. res.redirect(redirectTo); }
[ "function", "redirectToNext", "(", "req", ",", "res", ")", "{", "var", "redirectTo", "=", "req", ".", "session", ".", "next", "||", "''", ";", "req", ".", "session", ".", "next", "=", "null", ";", "// Null it so that we do not use it again.", "res", ".", "...
Redirects the user to the new url.
[ "Redirects", "the", "user", "to", "the", "new", "url", "." ]
446dfaba7f80c03ae17d86b34dfafd6328be1ba6
https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/oauth.js#L120-L124
31,481
rangle/koast
lib/authentication/oauth.js
setupStrategies
function setupStrategies(auth) { var result = {}; if (auth.maintenance === 'token') { result = { facebook: require('passport-facebook').Strategy, twitter: require('passport-twitter').Strategy }; } else { result = { google: require('passport-google-oauth').OAuth2Strategy, facebook: require('passport-facebook').Strategy, twitter: require('passport-twitter').Strategy }; } return result; }
javascript
function setupStrategies(auth) { var result = {}; if (auth.maintenance === 'token') { result = { facebook: require('passport-facebook').Strategy, twitter: require('passport-twitter').Strategy }; } else { result = { google: require('passport-google-oauth').OAuth2Strategy, facebook: require('passport-facebook').Strategy, twitter: require('passport-twitter').Strategy }; } return result; }
[ "function", "setupStrategies", "(", "auth", ")", "{", "var", "result", "=", "{", "}", ";", "if", "(", "auth", ".", "maintenance", "===", "'token'", ")", "{", "result", "=", "{", "facebook", ":", "require", "(", "'passport-facebook'", ")", ".", "Strategy"...
setup strategies that we can use google OAuth2Strategy requires session, which we do not setup if using token
[ "setup", "strategies", "that", "we", "can", "use", "google", "OAuth2Strategy", "requires", "session", "which", "we", "do", "not", "setup", "if", "using", "token" ]
446dfaba7f80c03ae17d86b34dfafd6328be1ba6
https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/oauth.js#L238-L254
31,482
RavelLaw/e3
addon/utils/shadow/line-interpolation/monotone.js
d3_svg_lineHermite
function d3_svg_lineHermite(points, tangents) { if (tangents.length < 1 || (points.length !== tangents.length && points.length !== tangents.length + 2)) { return points; } var quad = points.length !== tangents.length, commands = [], p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; if (quad) { commands.push([ p[0] - t0[0] * 2 / 3, p[1] - t0[1] * 2 / 3, p[0], p[1] ]); p0 = points[1]; pi = 2; } if (tangents.length > 1) { t = tangents[1]; p = points[pi]; pi++; commands.push([ p0[0] + t0[0], p0[1] + t0[1], p[0] - t[0], p[1] - t[1], p[0], p[1] ]); for (var i = 2; i < tangents.length; i++, pi++) { p = points[pi]; t = tangents[i]; let lt = tangents[i - 1]; let lp = points[i - 1]; commands.push([ lp[0] + lt[0], // Add the last tangent but reflected lp[1] + lt[1], p[0] - t[0], p[1] - t[1], p[0], p[1] ]); } } if (quad) { var lp = points[pi]; commands.push([ p[0] + t[0] * 2 / 3, p[1] + t[1] * 2 / 3, lp[0], lp[1] ]); } return commands; }
javascript
function d3_svg_lineHermite(points, tangents) { if (tangents.length < 1 || (points.length !== tangents.length && points.length !== tangents.length + 2)) { return points; } var quad = points.length !== tangents.length, commands = [], p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; if (quad) { commands.push([ p[0] - t0[0] * 2 / 3, p[1] - t0[1] * 2 / 3, p[0], p[1] ]); p0 = points[1]; pi = 2; } if (tangents.length > 1) { t = tangents[1]; p = points[pi]; pi++; commands.push([ p0[0] + t0[0], p0[1] + t0[1], p[0] - t[0], p[1] - t[1], p[0], p[1] ]); for (var i = 2; i < tangents.length; i++, pi++) { p = points[pi]; t = tangents[i]; let lt = tangents[i - 1]; let lp = points[i - 1]; commands.push([ lp[0] + lt[0], // Add the last tangent but reflected lp[1] + lt[1], p[0] - t[0], p[1] - t[1], p[0], p[1] ]); } } if (quad) { var lp = points[pi]; commands.push([ p[0] + t[0] * 2 / 3, p[1] + t[1] * 2 / 3, lp[0], lp[1] ]); } return commands; }
[ "function", "d3_svg_lineHermite", "(", "points", ",", "tangents", ")", "{", "if", "(", "tangents", ".", "length", "<", "1", "||", "(", "points", ".", "length", "!==", "tangents", ".", "length", "&&", "points", ".", "length", "!==", "tangents", ".", "leng...
Hermite spline construction; generates "C" commands.
[ "Hermite", "spline", "construction", ";", "generates", "C", "commands", "." ]
7149b2a9ebddd5c512132a41f7ae7c3a2235ac0d
https://github.com/RavelLaw/e3/blob/7149b2a9ebddd5c512132a41f7ae7c3a2235ac0d/addon/utils/shadow/line-interpolation/monotone.js#L79-L144
31,483
Incroud/cassanova
lib/model.js
Model
function Model(name, table) { this.model = this; if(!name || typeof name !== "string"){ throw new Error("Attempting to instantiate a model without a valid name. Create models using the Cassanova.model API."); } if(!table){ throw new Error("Attempting to instantiate a model, " + name + ", without a valid table. Create models using the Cassanova.model API."); } this.name = name; this.table = table; }
javascript
function Model(name, table) { this.model = this; if(!name || typeof name !== "string"){ throw new Error("Attempting to instantiate a model without a valid name. Create models using the Cassanova.model API."); } if(!table){ throw new Error("Attempting to instantiate a model, " + name + ", without a valid table. Create models using the Cassanova.model API."); } this.name = name; this.table = table; }
[ "function", "Model", "(", "name", ",", "table", ")", "{", "this", ".", "model", "=", "this", ";", "if", "(", "!", "name", "||", "typeof", "name", "!==", "\"string\"", ")", "{", "throw", "new", "Error", "(", "\"Attempting to instantiate a model without a vali...
Cassanova.Model @param {String} name The name of the model. Used to creation and retrieve. @param {Table} table The table associated with the model.
[ "Cassanova", ".", "Model" ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/model.js#L9-L22
31,484
hoodiehq/pouchdb-hoodie-sync
lib/off.js
off
function off (state, eventName, handler) { if (arguments.length === 2) { state.emitter.removeAllListeners(eventName) } else { state.emitter.removeListener(eventName, handler) } return state.api }
javascript
function off (state, eventName, handler) { if (arguments.length === 2) { state.emitter.removeAllListeners(eventName) } else { state.emitter.removeListener(eventName, handler) } return state.api }
[ "function", "off", "(", "state", ",", "eventName", ",", "handler", ")", "{", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "state", ".", "emitter", ".", "removeAllListeners", "(", "eventName", ")", "}", "else", "{", "state", ".", "emitte...
unbinds event from handler @param {String} eventName push, pull, connect, disconnect @param {Function} handler function unbound from event @return {Promise}
[ "unbinds", "event", "from", "handler" ]
c489baf813020c7f0cbd111224432cb6718c90de
https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/off.js#L10-L18
31,485
bem-contrib/md-to-bemjson
packages/md-to-bemjson/lib/augment.js
augmentFactory
function augmentFactory(options) { /** * Apply custom augmentation * * @param {Object} bemNode - representation of bem entity * @returns {Object} bemNode */ function augment(bemNode) { if (bemNode.block === 'md-root') { bemNode.isRoot = true; } if (options.html) { bemNode = augmentHtml(bemNode, options.html); } if (options.map) { bemNode = augmentMap(bemNode, options.map); } if (options.prefix) { bemNode = augmentPrefix(bemNode, options.prefix); } if (options.scope) { bemNode = augmentScope(bemNode, options.scope); } if (bemNode.isRoot) delete bemNode.isRoot; return bemNode; } return augment; }
javascript
function augmentFactory(options) { /** * Apply custom augmentation * * @param {Object} bemNode - representation of bem entity * @returns {Object} bemNode */ function augment(bemNode) { if (bemNode.block === 'md-root') { bemNode.isRoot = true; } if (options.html) { bemNode = augmentHtml(bemNode, options.html); } if (options.map) { bemNode = augmentMap(bemNode, options.map); } if (options.prefix) { bemNode = augmentPrefix(bemNode, options.prefix); } if (options.scope) { bemNode = augmentScope(bemNode, options.scope); } if (bemNode.isRoot) delete bemNode.isRoot; return bemNode; } return augment; }
[ "function", "augmentFactory", "(", "options", ")", "{", "/**\n * Apply custom augmentation\n *\n * @param {Object} bemNode - representation of bem entity\n * @returns {Object} bemNode\n */", "function", "augment", "(", "bemNode", ")", "{", "if", "(", "bemNode", "....
create augment function with options @param {MDConverter~AugmentOptions} options - augmentation options @returns {Function}
[ "create", "augment", "function", "with", "options" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/md-to-bemjson/lib/augment.js#L13-L48
31,486
bem-contrib/md-to-bemjson
packages/md-to-bemjson/lib/augment.js
augmentScope
function augmentScope(bemNode, scope) { assert(typeof scope === 'string', 'options.scope must be string'); if (bemNode.isRoot) { bemNode.block = scope; } else { bemNode.elem = bemNode.block; bemNode.elemMods = bemNode.mods; delete bemNode.block; delete bemNode.mods; } return bemNode; }
javascript
function augmentScope(bemNode, scope) { assert(typeof scope === 'string', 'options.scope must be string'); if (bemNode.isRoot) { bemNode.block = scope; } else { bemNode.elem = bemNode.block; bemNode.elemMods = bemNode.mods; delete bemNode.block; delete bemNode.mods; } return bemNode; }
[ "function", "augmentScope", "(", "bemNode", ",", "scope", ")", "{", "assert", "(", "typeof", "scope", "===", "'string'", ",", "'options.scope must be string'", ")", ";", "if", "(", "bemNode", ".", "isRoot", ")", "{", "bemNode", ".", "block", "=", "scope", ...
Replace root with scope and blocks with elems. @param {Object} bemNode - representation of bem entity @param {string} scope - new root block name @returns {Object} bemNode
[ "Replace", "root", "with", "scope", "and", "blocks", "with", "elems", "." ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/md-to-bemjson/lib/augment.js#L80-L95
31,487
bem-contrib/md-to-bemjson
packages/md-to-bemjson/lib/augment.js
augmentMap
function augmentMap(bemNode, map) { const name = bemNode.block; if (map[name]) { assert(typeof map[name] === 'string', `options.map: new name of ${name} must be string`); bemNode.block = map[name]; } return bemNode; }
javascript
function augmentMap(bemNode, map) { const name = bemNode.block; if (map[name]) { assert(typeof map[name] === 'string', `options.map: new name of ${name} must be string`); bemNode.block = map[name]; } return bemNode; }
[ "function", "augmentMap", "(", "bemNode", ",", "map", ")", "{", "const", "name", "=", "bemNode", ".", "block", ";", "if", "(", "map", "[", "name", "]", ")", "{", "assert", "(", "typeof", "map", "[", "name", "]", "===", "'string'", ",", "`", "${", ...
Replace block names with new one @param {Object} bemNode - representation of bem entity @param {Object} map - key:blockName, value:newBlockName @returns {Object} bemNode
[ "Replace", "block", "names", "with", "new", "one" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/md-to-bemjson/lib/augment.js#L104-L113
31,488
tamaina/mfmf
dist/script/prelude/array.js
intersperse
function intersperse(sep, xs) { return concat(xs.map(x => [sep, x])).slice(1); }
javascript
function intersperse(sep, xs) { return concat(xs.map(x => [sep, x])).slice(1); }
[ "function", "intersperse", "(", "sep", ",", "xs", ")", "{", "return", "concat", "(", "xs", ".", "map", "(", "x", "=>", "[", "sep", ",", "x", "]", ")", ")", ".", "slice", "(", "1", ")", ";", "}" ]
Intersperse the element between the elements of the array @param sep The element to be interspersed
[ "Intersperse", "the", "element", "between", "the", "elements", "of", "the", "array" ]
31208f7265a37438ee0e7527969db91ded001f7c
https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L28-L30
31,489
tamaina/mfmf
dist/script/prelude/array.js
groupBy
function groupBy(f, xs) { const groups = []; for (const x of xs) { if (groups.length !== 0 && f(groups[groups.length - 1][0], x)) { groups[groups.length - 1].push(x); } else { groups.push([x]); } } return groups; }
javascript
function groupBy(f, xs) { const groups = []; for (const x of xs) { if (groups.length !== 0 && f(groups[groups.length - 1][0], x)) { groups[groups.length - 1].push(x); } else { groups.push([x]); } } return groups; }
[ "function", "groupBy", "(", "f", ",", "xs", ")", "{", "const", "groups", "=", "[", "]", ";", "for", "(", "const", "x", "of", "xs", ")", "{", "if", "(", "groups", ".", "length", "!==", "0", "&&", "f", "(", "groups", "[", "groups", ".", "length",...
Splits an array based on the equivalence relation. The concatenation of the result is equal to the argument.
[ "Splits", "an", "array", "based", "on", "the", "equivalence", "relation", ".", "The", "concatenation", "of", "the", "result", "is", "equal", "to", "the", "argument", "." ]
31208f7265a37438ee0e7527969db91ded001f7c
https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L66-L77
31,490
tamaina/mfmf
dist/script/prelude/array.js
groupOn
function groupOn(f, xs) { return groupBy((a, b) => f(a) === f(b), xs); }
javascript
function groupOn(f, xs) { return groupBy((a, b) => f(a) === f(b), xs); }
[ "function", "groupOn", "(", "f", ",", "xs", ")", "{", "return", "groupBy", "(", "(", "a", ",", "b", ")", "=>", "f", "(", "a", ")", "===", "f", "(", "b", ")", ",", "xs", ")", ";", "}" ]
Splits an array based on the equivalence relation induced by the function. The concatenation of the result is equal to the argument.
[ "Splits", "an", "array", "based", "on", "the", "equivalence", "relation", "induced", "by", "the", "function", ".", "The", "concatenation", "of", "the", "result", "is", "equal", "to", "the", "argument", "." ]
31208f7265a37438ee0e7527969db91ded001f7c
https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L83-L85
31,491
tamaina/mfmf
dist/script/prelude/array.js
lessThan
function lessThan(xs, ys) { for (let i = 0; i < Math.min(xs.length, ys.length); i++) { if (xs[i] < ys[i]) return true; if (xs[i] > ys[i]) return false; } return xs.length < ys.length; }
javascript
function lessThan(xs, ys) { for (let i = 0; i < Math.min(xs.length, ys.length); i++) { if (xs[i] < ys[i]) return true; if (xs[i] > ys[i]) return false; } return xs.length < ys.length; }
[ "function", "lessThan", "(", "xs", ",", "ys", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "Math", ".", "min", "(", "xs", ".", "length", ",", "ys", ".", "length", ")", ";", "i", "++", ")", "{", "if", "(", "xs", "[", "i", "]"...
Compare two arrays by lexicographical order
[ "Compare", "two", "arrays", "by", "lexicographical", "order" ]
31208f7265a37438ee0e7527969db91ded001f7c
https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L90-L98
31,492
tamaina/mfmf
dist/script/prelude/array.js
takeWhile
function takeWhile(f, xs) { const ys = []; for (const x of xs) { if (f(x)) { ys.push(x); } else { break; } } return ys; }
javascript
function takeWhile(f, xs) { const ys = []; for (const x of xs) { if (f(x)) { ys.push(x); } else { break; } } return ys; }
[ "function", "takeWhile", "(", "f", ",", "xs", ")", "{", "const", "ys", "=", "[", "]", ";", "for", "(", "const", "x", "of", "xs", ")", "{", "if", "(", "f", "(", "x", ")", ")", "{", "ys", ".", "push", "(", "x", ")", ";", "}", "else", "{", ...
Returns the longest prefix of elements that satisfy the predicate
[ "Returns", "the", "longest", "prefix", "of", "elements", "that", "satisfy", "the", "predicate" ]
31208f7265a37438ee0e7527969db91ded001f7c
https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L103-L114
31,493
fissionjs/fission
lib/renderables/collectionView.js
function(){ return { collection: configCollection, data: config.data, query: config.query, offset: config.offset, limit: config.limit, where: config.where, filter: config.filter, filters: config.filters, watch: config.watch, sort: config.sort }; }
javascript
function(){ return { collection: configCollection, data: config.data, query: config.query, offset: config.offset, limit: config.limit, where: config.where, filter: config.filter, filters: config.filters, watch: config.watch, sort: config.sort }; }
[ "function", "(", ")", "{", "return", "{", "collection", ":", "configCollection", ",", "data", ":", "config", ".", "data", ",", "query", ":", "config", ".", "query", ",", "offset", ":", "config", ".", "offset", ",", "limit", ":", "config", ".", "limit",...
most options can be passed via config or props props takes precedence
[ "most", "options", "can", "be", "passed", "via", "config", "or", "props", "props", "takes", "precedence" ]
e34eed78ed2386bb7934a69214e13f17fcd311c3
https://github.com/fissionjs/fission/blob/e34eed78ed2386bb7934a69214e13f17fcd311c3/lib/renderables/collectionView.js#L53-L66
31,494
fissionjs/fission
lib/renderables/collectionView.js
function(props) { if (typeof props !== 'object') { throw new Error('_configureItems called with invalid props'); } // not initialized yet if (!this._items) { return; } this._items.configure({ where: bindIfFn(props.where, this), filter: bindIfFn(props.filter, this), limit: bindIfFn(props.limit, this), offset: bindIfFn(props.offset, this), comparator: bindIfFn(props.sort, this) }, true); }
javascript
function(props) { if (typeof props !== 'object') { throw new Error('_configureItems called with invalid props'); } // not initialized yet if (!this._items) { return; } this._items.configure({ where: bindIfFn(props.where, this), filter: bindIfFn(props.filter, this), limit: bindIfFn(props.limit, this), offset: bindIfFn(props.offset, this), comparator: bindIfFn(props.sort, this) }, true); }
[ "function", "(", "props", ")", "{", "if", "(", "typeof", "props", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'_configureItems called with invalid props'", ")", ";", "}", "// not initialized yet", "if", "(", "!", "this", ".", "_items", ")", "...
internal fn to sync props to shadow collection
[ "internal", "fn", "to", "sync", "props", "to", "shadow", "collection" ]
e34eed78ed2386bb7934a69214e13f17fcd311c3
https://github.com/fissionjs/fission/blob/e34eed78ed2386bb7934a69214e13f17fcd311c3/lib/renderables/collectionView.js#L136-L151
31,495
cutting-room-floor/markers.js
dist/markers.js
reposition
function reposition(marker) { // remember the tile coordinate so we don't have to reproject every time if (!marker.coord) marker.coord = m.map.locationCoordinate(marker.location); var pos = m.map.coordinatePoint(marker.coord); var pos_loc, new_pos; // If this point has wound around the world, adjust its position // to the new, onscreen location if (pos.x < 0) { pos_loc = new MM.Location(marker.location.lat, marker.location.lon); pos_loc.lon += Math.ceil((left.lon - marker.location.lon) / 360) * 360; new_pos = m.map.locationPoint(pos_loc); if (new_pos.x < m.map.dimensions.x) { pos = new_pos; marker.coord = m.map.locationCoordinate(pos_loc); } } else if (pos.x > m.map.dimensions.x) { pos_loc = new MM.Location(marker.location.lat, marker.location.lon); pos_loc.lon -= Math.ceil((marker.location.lon - right.lon) / 360) * 360; new_pos = m.map.locationPoint(pos_loc); if (new_pos.x > 0) { pos = new_pos; marker.coord = m.map.locationCoordinate(pos_loc); } } pos.scale = 1; pos.width = pos.height = 0; MM.moveElement(marker.element, pos); }
javascript
function reposition(marker) { // remember the tile coordinate so we don't have to reproject every time if (!marker.coord) marker.coord = m.map.locationCoordinate(marker.location); var pos = m.map.coordinatePoint(marker.coord); var pos_loc, new_pos; // If this point has wound around the world, adjust its position // to the new, onscreen location if (pos.x < 0) { pos_loc = new MM.Location(marker.location.lat, marker.location.lon); pos_loc.lon += Math.ceil((left.lon - marker.location.lon) / 360) * 360; new_pos = m.map.locationPoint(pos_loc); if (new_pos.x < m.map.dimensions.x) { pos = new_pos; marker.coord = m.map.locationCoordinate(pos_loc); } } else if (pos.x > m.map.dimensions.x) { pos_loc = new MM.Location(marker.location.lat, marker.location.lon); pos_loc.lon -= Math.ceil((marker.location.lon - right.lon) / 360) * 360; new_pos = m.map.locationPoint(pos_loc); if (new_pos.x > 0) { pos = new_pos; marker.coord = m.map.locationCoordinate(pos_loc); } } pos.scale = 1; pos.width = pos.height = 0; MM.moveElement(marker.element, pos); }
[ "function", "reposition", "(", "marker", ")", "{", "// remember the tile coordinate so we don't have to reproject every time", "if", "(", "!", "marker", ".", "coord", ")", "marker", ".", "coord", "=", "m", ".", "map", ".", "locationCoordinate", "(", "marker", ".", ...
reposition a single marker element
[ "reposition", "a", "single", "marker", "element" ]
3feae089a43b4c10835bb0f147e8166333fc7b6a
https://github.com/cutting-room-floor/markers.js/blob/3feae089a43b4c10835bb0f147e8166333fc7b6a/dist/markers.js#L46-L75
31,496
cutting-room-floor/markers.js
dist/markers.js
stopPropagation
function stopPropagation(e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } return false; }
javascript
function stopPropagation(e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } return false; }
[ "function", "stopPropagation", "(", "e", ")", "{", "e", ".", "cancelBubble", "=", "true", ";", "if", "(", "e", ".", "stopPropagation", ")", "{", "e", ".", "stopPropagation", "(", ")", ";", "}", "return", "false", ";", "}" ]
Block mouse and touch events
[ "Block", "mouse", "and", "touch", "events" ]
3feae089a43b4c10835bb0f147e8166333fc7b6a
https://github.com/cutting-room-floor/markers.js/blob/3feae089a43b4c10835bb0f147e8166333fc7b6a/dist/markers.js#L430-L434
31,497
cutting-room-floor/markers.js
dist/markers.js
csv_parse
function csv_parse(text) { var header; return csv_parseRows(text, function(row, i) { if (i) { var o = {}, j = -1, m = header.length; while (++j < m) o[header[j]] = row[j]; return o; } else { header = row; return null; } }); }
javascript
function csv_parse(text) { var header; return csv_parseRows(text, function(row, i) { if (i) { var o = {}, j = -1, m = header.length; while (++j < m) o[header[j]] = row[j]; return o; } else { header = row; return null; } }); }
[ "function", "csv_parse", "(", "text", ")", "{", "var", "header", ";", "return", "csv_parseRows", "(", "text", ",", "function", "(", "row", ",", "i", ")", "{", "if", "(", "i", ")", "{", "var", "o", "=", "{", "}", ",", "j", "=", "-", "1", ",", ...
Extracted from d3
[ "Extracted", "from", "d3" ]
3feae089a43b4c10835bb0f147e8166333fc7b6a
https://github.com/cutting-room-floor/markers.js/blob/3feae089a43b4c10835bb0f147e8166333fc7b6a/dist/markers.js#L506-L518
31,498
Icinetic/baucis-swagger2
Controller.js
swagger20TypeFor
function swagger20TypeFor(type) { if (!type) { return null; } if (type === Number) { return 'number'; } if (type === Boolean) { return 'boolean'; } if (type === String || type === Date || type === mongoose.Schema.Types.ObjectId || type === mongoose.Schema.Types.Oid) { return 'string'; } if (type === mongoose.Schema.Types.Array || Array.isArray(type) || type.name === "Array") { return 'array'; } if (type === Object || type instanceof Object || type === mongoose.Schema.Types.Mixed || type === mongoose.Schema.Types.Buffer) { return null; } throw new Error('Unrecognized type: ' + type); }
javascript
function swagger20TypeFor(type) { if (!type) { return null; } if (type === Number) { return 'number'; } if (type === Boolean) { return 'boolean'; } if (type === String || type === Date || type === mongoose.Schema.Types.ObjectId || type === mongoose.Schema.Types.Oid) { return 'string'; } if (type === mongoose.Schema.Types.Array || Array.isArray(type) || type.name === "Array") { return 'array'; } if (type === Object || type instanceof Object || type === mongoose.Schema.Types.Mixed || type === mongoose.Schema.Types.Buffer) { return null; } throw new Error('Unrecognized type: ' + type); }
[ "function", "swagger20TypeFor", "(", "type", ")", "{", "if", "(", "!", "type", ")", "{", "return", "null", ";", "}", "if", "(", "type", "===", "Number", ")", "{", "return", "'number'", ";", "}", "if", "(", "type", "===", "Boolean", ")", "{", "retur...
Convert a Mongoose type into a Swagger type
[ "Convert", "a", "Mongoose", "type", "into", "a", "Swagger", "type" ]
502200ae8ac131849fe20d95636bf3170561e81e
https://github.com/Icinetic/baucis-swagger2/blob/502200ae8ac131849fe20d95636bf3170561e81e/Controller.js#L161-L183
31,499
Icinetic/baucis-swagger2
Controller.js
generatePropertyDefinition
function generatePropertyDefinition(name, path, definitionName) { var property = {}; var type = path.options.type ? swagger20TypeFor(path.options.type) : 'string'; // virtuals don't have type if (skipProperty(name, path, controller)) { return; } // Configure the property if (path.options.type === mongoose.Schema.Types.ObjectId) { if ("_id" === name) { property.type = 'string'; } else if (path.options.ref) { property.$ref = '#/definitions/' + utils.capitalize(path.options.ref); } } else if (path.schema) { //Choice (1. embed schema here or 2. reference and publish as a root definition) property.type = 'array'; property.items = { //2. reference $ref: '#/definitions/'+ definitionName + utils.capitalize(name) }; } else { property.type = type; if ('array' === type) { if (isArrayOfRefs(path.options.type)) { property.items = { type: 'string' //handle references as string (serialization for objectId) }; } else { var resolvedType = referenceForType(path.options.type); if (resolvedType.isPrimitive) { property.items = { type: resolvedType.type }; } else { property.items = { $ref: resolvedType.type }; } } } var format = swagger20TypeFormatFor(path.options.type); if (format) { property.format = format; } if ('__v' === name) { property.format = 'int32'; } } /* // Set enum values if applicable if (path.enumValues && path.enumValues.length > 0) { // Pending: property.allowableValues = { valueType: 'LIST', values: path.enumValues }; } // Set allowable values range if min or max is present if (!isNaN(path.options.min) || !isNaN(path.options.max)) { // Pending: property.allowableValues = { valueType: 'RANGE' }; } if (!isNaN(path.options.min)) { // Pending: property.allowableValues.min = path.options.min; } if (!isNaN(path.options.max)) { // Pending: property.allowableValues.max = path.options.max; } */ if (!property.type && !property.$ref) { warnInvalidType(name, path); property.type = 'string'; } return property; }
javascript
function generatePropertyDefinition(name, path, definitionName) { var property = {}; var type = path.options.type ? swagger20TypeFor(path.options.type) : 'string'; // virtuals don't have type if (skipProperty(name, path, controller)) { return; } // Configure the property if (path.options.type === mongoose.Schema.Types.ObjectId) { if ("_id" === name) { property.type = 'string'; } else if (path.options.ref) { property.$ref = '#/definitions/' + utils.capitalize(path.options.ref); } } else if (path.schema) { //Choice (1. embed schema here or 2. reference and publish as a root definition) property.type = 'array'; property.items = { //2. reference $ref: '#/definitions/'+ definitionName + utils.capitalize(name) }; } else { property.type = type; if ('array' === type) { if (isArrayOfRefs(path.options.type)) { property.items = { type: 'string' //handle references as string (serialization for objectId) }; } else { var resolvedType = referenceForType(path.options.type); if (resolvedType.isPrimitive) { property.items = { type: resolvedType.type }; } else { property.items = { $ref: resolvedType.type }; } } } var format = swagger20TypeFormatFor(path.options.type); if (format) { property.format = format; } if ('__v' === name) { property.format = 'int32'; } } /* // Set enum values if applicable if (path.enumValues && path.enumValues.length > 0) { // Pending: property.allowableValues = { valueType: 'LIST', values: path.enumValues }; } // Set allowable values range if min or max is present if (!isNaN(path.options.min) || !isNaN(path.options.max)) { // Pending: property.allowableValues = { valueType: 'RANGE' }; } if (!isNaN(path.options.min)) { // Pending: property.allowableValues.min = path.options.min; } if (!isNaN(path.options.max)) { // Pending: property.allowableValues.max = path.options.max; } */ if (!property.type && !property.$ref) { warnInvalidType(name, path); property.type = 'string'; } return property; }
[ "function", "generatePropertyDefinition", "(", "name", ",", "path", ",", "definitionName", ")", "{", "var", "property", "=", "{", "}", ";", "var", "type", "=", "path", ".", "options", ".", "type", "?", "swagger20TypeFor", "(", "path", ".", "options", ".", ...
A method used to generated a Swagger property for a model
[ "A", "method", "used", "to", "generated", "a", "Swagger", "property", "for", "a", "model" ]
502200ae8ac131849fe20d95636bf3170561e81e
https://github.com/Icinetic/baucis-swagger2/blob/502200ae8ac131849fe20d95636bf3170561e81e/Controller.js#L225-L301