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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
55,800
independentgeorge/glupost
index.js
pipify
function pipify(task) { const options = task.base ? { base: task.base } : {} let stream = gulp.src(task.src, options) // This is used to abort any further transforms in case of error. const state = { error: false } for (const transform of task.transforms) stream = stream.pipe(transform.pipe ? transform : pluginate(transform, state)) if (task.rename) stream = stream.pipe(rename(task.rename)) if (task.dest) stream = stream.pipe(gulp.dest(task.dest)) return stream }
javascript
function pipify(task) { const options = task.base ? { base: task.base } : {} let stream = gulp.src(task.src, options) // This is used to abort any further transforms in case of error. const state = { error: false } for (const transform of task.transforms) stream = stream.pipe(transform.pipe ? transform : pluginate(transform, state)) if (task.rename) stream = stream.pipe(rename(task.rename)) if (task.dest) stream = stream.pipe(gulp.dest(task.dest)) return stream }
[ "function", "pipify", "(", "task", ")", "{", "const", "options", "=", "task", ".", "base", "?", "{", "base", ":", "task", ".", "base", "}", ":", "{", "}", "let", "stream", "=", "gulp", ".", "src", "(", "task", ".", "src", ",", "options", ")", "// This is used to abort any further transforms in case of error.", "const", "state", "=", "{", "error", ":", "false", "}", "for", "(", "const", "transform", "of", "task", ".", "transforms", ")", "stream", "=", "stream", ".", "pipe", "(", "transform", ".", "pipe", "?", "transform", ":", "pluginate", "(", "transform", ",", "state", ")", ")", "if", "(", "task", ".", "rename", ")", "stream", "=", "stream", ".", "pipe", "(", "rename", "(", "task", ".", "rename", ")", ")", "if", "(", "task", ".", "dest", ")", "stream", "=", "stream", ".", "pipe", "(", "gulp", ".", "dest", "(", "task", ".", "dest", ")", ")", "return", "stream", "}" ]
Convert transform functions to a Stream.
[ "Convert", "transform", "functions", "to", "a", "Stream", "." ]
3a66d6d460d8e63552cecf28c32dfabe98fbd689
https://github.com/independentgeorge/glupost/blob/3a66d6d460d8e63552cecf28c32dfabe98fbd689/index.js#L124-L144
55,801
independentgeorge/glupost
index.js
pluginate
function pluginate(transform, state) { return through.obj((file, encoding, done) => { // Nothing to transform. if (file.isNull() || state.error) { done(null, file) return } // Transform function returns a vinyl file or file contents (in form of a // stream, a buffer or a string), or a promise which resolves with those. new Promise((resolve, reject) => { try { resolve(transform(file.contents, file)) } catch (e) { reject(e) } }).then((result) => { if (!Vinyl.isVinyl(result)) { if (result instanceof Buffer) file.contents = result else if (typeof result === "string") file.contents = Buffer.from(result) else throw new Error("Transforms must return/resolve with a file, a buffer or a string.") } }).catch((e) => { console.error(e) state.error = true }).then(() => { done(null, file) }) }) }
javascript
function pluginate(transform, state) { return through.obj((file, encoding, done) => { // Nothing to transform. if (file.isNull() || state.error) { done(null, file) return } // Transform function returns a vinyl file or file contents (in form of a // stream, a buffer or a string), or a promise which resolves with those. new Promise((resolve, reject) => { try { resolve(transform(file.contents, file)) } catch (e) { reject(e) } }).then((result) => { if (!Vinyl.isVinyl(result)) { if (result instanceof Buffer) file.contents = result else if (typeof result === "string") file.contents = Buffer.from(result) else throw new Error("Transforms must return/resolve with a file, a buffer or a string.") } }).catch((e) => { console.error(e) state.error = true }).then(() => { done(null, file) }) }) }
[ "function", "pluginate", "(", "transform", ",", "state", ")", "{", "return", "through", ".", "obj", "(", "(", "file", ",", "encoding", ",", "done", ")", "=>", "{", "// Nothing to transform.", "if", "(", "file", ".", "isNull", "(", ")", "||", "state", ".", "error", ")", "{", "done", "(", "null", ",", "file", ")", "return", "}", "// Transform function returns a vinyl file or file contents (in form of a", "// stream, a buffer or a string), or a promise which resolves with those.", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "resolve", "(", "transform", "(", "file", ".", "contents", ",", "file", ")", ")", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", "}", "}", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "if", "(", "!", "Vinyl", ".", "isVinyl", "(", "result", ")", ")", "{", "if", "(", "result", "instanceof", "Buffer", ")", "file", ".", "contents", "=", "result", "else", "if", "(", "typeof", "result", "===", "\"string\"", ")", "file", ".", "contents", "=", "Buffer", ".", "from", "(", "result", ")", "else", "throw", "new", "Error", "(", "\"Transforms must return/resolve with a file, a buffer or a string.\"", ")", "}", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "console", ".", "error", "(", "e", ")", "state", ".", "error", "=", "true", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "done", "(", "null", ",", "file", ")", "}", ")", "}", ")", "}" ]
Convert a string transform function into a stream.
[ "Convert", "a", "string", "transform", "function", "into", "a", "stream", "." ]
3a66d6d460d8e63552cecf28c32dfabe98fbd689
https://github.com/independentgeorge/glupost/blob/3a66d6d460d8e63552cecf28c32dfabe98fbd689/index.js#L148-L185
55,802
independentgeorge/glupost
index.js
watch
function watch(tasks) { if (tasks["watch"]) { console.warn("`watch` task redefined.") return } const names = Object.keys(tasks).filter((name) => tasks[name].watch) if (!names.length) return gulp.task("watch", () => { for (const name of names) { const glob = tasks[name].watch const watcher = gulp.watch(glob, gulp.task(name)) watcher.on("change", (path) => console.log(`${timestamp()} '${path}' was changed, running tasks...`)) } }) }
javascript
function watch(tasks) { if (tasks["watch"]) { console.warn("`watch` task redefined.") return } const names = Object.keys(tasks).filter((name) => tasks[name].watch) if (!names.length) return gulp.task("watch", () => { for (const name of names) { const glob = tasks[name].watch const watcher = gulp.watch(glob, gulp.task(name)) watcher.on("change", (path) => console.log(`${timestamp()} '${path}' was changed, running tasks...`)) } }) }
[ "function", "watch", "(", "tasks", ")", "{", "if", "(", "tasks", "[", "\"watch\"", "]", ")", "{", "console", ".", "warn", "(", "\"`watch` task redefined.\"", ")", "return", "}", "const", "names", "=", "Object", ".", "keys", "(", "tasks", ")", ".", "filter", "(", "(", "name", ")", "=>", "tasks", "[", "name", "]", ".", "watch", ")", "if", "(", "!", "names", ".", "length", ")", "return", "gulp", ".", "task", "(", "\"watch\"", ",", "(", ")", "=>", "{", "for", "(", "const", "name", "of", "names", ")", "{", "const", "glob", "=", "tasks", "[", "name", "]", ".", "watch", "const", "watcher", "=", "gulp", ".", "watch", "(", "glob", ",", "gulp", ".", "task", "(", "name", ")", ")", "watcher", ".", "on", "(", "\"change\"", ",", "(", "path", ")", "=>", "console", ".", "log", "(", "`", "${", "timestamp", "(", ")", "}", "${", "path", "}", "`", ")", ")", "}", "}", ")", "}" ]
Create the watch task if declared and triggered. Only top level tasks may be watched.
[ "Create", "the", "watch", "task", "if", "declared", "and", "triggered", ".", "Only", "top", "level", "tasks", "may", "be", "watched", "." ]
3a66d6d460d8e63552cecf28c32dfabe98fbd689
https://github.com/independentgeorge/glupost/blob/3a66d6d460d8e63552cecf28c32dfabe98fbd689/index.js#L190-L210
55,803
independentgeorge/glupost
index.js
expand
function expand(to, from) { const keys = Object.keys(from) for (const key of keys) { if (!to.hasOwnProperty(key)) to[key] = from[key] } }
javascript
function expand(to, from) { const keys = Object.keys(from) for (const key of keys) { if (!to.hasOwnProperty(key)) to[key] = from[key] } }
[ "function", "expand", "(", "to", ",", "from", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "from", ")", "for", "(", "const", "key", "of", "keys", ")", "{", "if", "(", "!", "to", ".", "hasOwnProperty", "(", "key", ")", ")", "to", "[", "key", "]", "=", "from", "[", "key", "]", "}", "}" ]
Add new properties on `from` to `to`.
[ "Add", "new", "properties", "on", "from", "to", "to", "." ]
3a66d6d460d8e63552cecf28c32dfabe98fbd689
https://github.com/independentgeorge/glupost/blob/3a66d6d460d8e63552cecf28c32dfabe98fbd689/index.js#L215-L223
55,804
Qwerios/madlib-hostmapping
lib/index.js
HostMapping
function HostMapping(settings) { settings.init("hostConfig", {}); settings.init("hostMapping", {}); settings.init("xdmConfig", {}); this.settings = settings; }
javascript
function HostMapping(settings) { settings.init("hostConfig", {}); settings.init("hostMapping", {}); settings.init("xdmConfig", {}); this.settings = settings; }
[ "function", "HostMapping", "(", "settings", ")", "{", "settings", ".", "init", "(", "\"hostConfig\"", ",", "{", "}", ")", ";", "settings", ".", "init", "(", "\"hostMapping\"", ",", "{", "}", ")", ";", "settings", ".", "init", "(", "\"xdmConfig\"", ",", "{", "}", ")", ";", "this", ".", "settings", "=", "settings", ";", "}" ]
The class constructor. You need to supply your instance of madlib-settings @function constructor @params settings {Object} madlib-settings instance @return None
[ "The", "class", "constructor", ".", "You", "need", "to", "supply", "your", "instance", "of", "madlib", "-", "settings" ]
88c87657e8739c4446ff80ed5b6b91fce892c9a3
https://github.com/Qwerios/madlib-hostmapping/blob/88c87657e8739c4446ff80ed5b6b91fce892c9a3/lib/index.js#L33-L38
55,805
Industryswarm/isnode-mod-data
lib/mongodb/mongodb/lib/utils.js
decorateWithCollation
function decorateWithCollation(command, target, options) { const topology = target.s && target.s.topology; if (!topology) { throw new TypeError('parameter "target" is missing a topology'); } const capabilities = target.s.topology.capabilities(); if (options.collation && typeof options.collation === 'object') { if (capabilities && capabilities.commandsTakeCollation) { command.collation = options.collation; } else { throw new MongoError(`server ${topology.s.coreTopology.name} does not support collation`); } } }
javascript
function decorateWithCollation(command, target, options) { const topology = target.s && target.s.topology; if (!topology) { throw new TypeError('parameter "target" is missing a topology'); } const capabilities = target.s.topology.capabilities(); if (options.collation && typeof options.collation === 'object') { if (capabilities && capabilities.commandsTakeCollation) { command.collation = options.collation; } else { throw new MongoError(`server ${topology.s.coreTopology.name} does not support collation`); } } }
[ "function", "decorateWithCollation", "(", "command", ",", "target", ",", "options", ")", "{", "const", "topology", "=", "target", ".", "s", "&&", "target", ".", "s", ".", "topology", ";", "if", "(", "!", "topology", ")", "{", "throw", "new", "TypeError", "(", "'parameter \"target\" is missing a topology'", ")", ";", "}", "const", "capabilities", "=", "target", ".", "s", ".", "topology", ".", "capabilities", "(", ")", ";", "if", "(", "options", ".", "collation", "&&", "typeof", "options", ".", "collation", "===", "'object'", ")", "{", "if", "(", "capabilities", "&&", "capabilities", ".", "commandsTakeCollation", ")", "{", "command", ".", "collation", "=", "options", ".", "collation", ";", "}", "else", "{", "throw", "new", "MongoError", "(", "`", "${", "topology", ".", "s", ".", "coreTopology", ".", "name", "}", "`", ")", ";", "}", "}", "}" ]
Applies collation to a given command. @param {object} [command] the command on which to apply collation @param {(Cursor|Collection)} [target] target of command @param {object} [options] options containing collation settings
[ "Applies", "collation", "to", "a", "given", "command", "." ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/utils.js#L584-L599
55,806
tandrewnichols/indeed
lib/expect.js
function(fn) { // Save off the existing spy method as __functionName var newName = '__' + fn; self[newName] = self[fn]; // This is the actual function that will be called when, // for example, calledWith() is invoked return function() { var func = self[newName]; // If this thing is a function, invoke it with all arguments; // otherwise, just grab the value of the property. var val = typeof func === 'function' ? func.apply(condition, arguments) : func; // Negate and return return !val; }; }
javascript
function(fn) { // Save off the existing spy method as __functionName var newName = '__' + fn; self[newName] = self[fn]; // This is the actual function that will be called when, // for example, calledWith() is invoked return function() { var func = self[newName]; // If this thing is a function, invoke it with all arguments; // otherwise, just grab the value of the property. var val = typeof func === 'function' ? func.apply(condition, arguments) : func; // Negate and return return !val; }; }
[ "function", "(", "fn", ")", "{", "// Save off the existing spy method as __functionName", "var", "newName", "=", "'__'", "+", "fn", ";", "self", "[", "newName", "]", "=", "self", "[", "fn", "]", ";", "// This is the actual function that will be called when,", "// for example, calledWith() is invoked", "return", "function", "(", ")", "{", "var", "func", "=", "self", "[", "newName", "]", ";", "// If this thing is a function, invoke it with all arguments;", "// otherwise, just grab the value of the property.", "var", "val", "=", "typeof", "func", "===", "'function'", "?", "func", ".", "apply", "(", "condition", ",", "arguments", ")", ":", "func", ";", "// Negate and return", "return", "!", "val", ";", "}", ";", "}" ]
Wrapper to create a function for negating spy methods
[ "Wrapper", "to", "create", "a", "function", "for", "negating", "spy", "methods" ]
d29d4c17d8b7c063cccd3c1dfd7c571603a187b2
https://github.com/tandrewnichols/indeed/blob/d29d4c17d8b7c063cccd3c1dfd7c571603a187b2/lib/expect.js#L31-L48
55,807
GuillaumeIsabelleX/gixdeko
src/nodejs/gixdeko/gixdeko.js
function (decorator, txt) { var decostr = "@" + decorator; var r = txt .replace(decostr, "") .trim() ; if (debug) console.log(`Cleaning deco: ${decorator} in ${txt} Result: ${r} `); return r; }
javascript
function (decorator, txt) { var decostr = "@" + decorator; var r = txt .replace(decostr, "") .trim() ; if (debug) console.log(`Cleaning deco: ${decorator} in ${txt} Result: ${r} `); return r; }
[ "function", "(", "decorator", ",", "txt", ")", "{", "var", "decostr", "=", "\"@\"", "+", "decorator", ";", "var", "r", "=", "txt", ".", "replace", "(", "decostr", ",", "\"\"", ")", ".", "trim", "(", ")", ";", "if", "(", "debug", ")", "console", ".", "log", "(", "`", "${", "decorator", "}", "${", "txt", "}", "${", "r", "}", "`", ")", ";", "return", "r", ";", "}" ]
Clean a string of a deko @param {*} decorator @param {*} txt
[ "Clean", "a", "string", "of", "a", "deko" ]
6762c04a27af8ff89e2bc3e53fc01b07b70afc9e
https://github.com/GuillaumeIsabelleX/gixdeko/blob/6762c04a27af8ff89e2bc3e53fc01b07b70afc9e/src/nodejs/gixdeko/gixdeko.js#L132-L144
55,808
GuillaumeIsabelleX/gixdeko
src/nodejs/gixdeko/gixdeko.js
extractDecorator2
function extractDecorator2(text) { try { var email = text.match(reSTCDeco); // console.log("DEBUG: reSTCDeco:" + email); var deco = email[0].split('@')[1]; return deco; } catch (error) { return ""; } // return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); }
javascript
function extractDecorator2(text) { try { var email = text.match(reSTCDeco); // console.log("DEBUG: reSTCDeco:" + email); var deco = email[0].split('@')[1]; return deco; } catch (error) { return ""; } // return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); }
[ "function", "extractDecorator2", "(", "text", ")", "{", "try", "{", "var", "email", "=", "text", ".", "match", "(", "reSTCDeco", ")", ";", "// console.log(\"DEBUG: reSTCDeco:\" + email);\r", "var", "deco", "=", "email", "[", "0", "]", ".", "split", "(", "'@'", ")", "[", "1", "]", ";", "return", "deco", ";", "}", "catch", "(", "error", ")", "{", "return", "\"\"", ";", "}", "// return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)/gi);\r", "}" ]
extraction decorator logics @param {*} text
[ "extraction", "decorator", "logics" ]
6762c04a27af8ff89e2bc3e53fc01b07b70afc9e
https://github.com/GuillaumeIsabelleX/gixdeko/blob/6762c04a27af8ff89e2bc3e53fc01b07b70afc9e/src/nodejs/gixdeko/gixdeko.js#L175-L187
55,809
Nichejs/Seminarjs
private/lib/core/mount.js
function (err, req, res, next) { if (seminarjs.get('logger')) { if (err instanceof Error) { console.log((err.type ? err.type + ' ' : '') + 'Error thrown for request: ' + req.url); } else { console.log('Error thrown for request: ' + req.url); } console.log(err.stack || err); } var msg = ''; if (seminarjs.get('env') === 'development') { if (err instanceof Error) { if (err.type) { msg += '<h2>' + err.type + '</h2>'; } msg += utils.textToHTML(err.message); } else if ('object' === typeof err) { msg += '<code>' + JSON.stringify(err) + '</code>'; } else if (err) { msg += err; } } res.status(500).send(seminarjs.wrapHTMLError('Sorry, an error occurred loading the page (500)', msg)); }
javascript
function (err, req, res, next) { if (seminarjs.get('logger')) { if (err instanceof Error) { console.log((err.type ? err.type + ' ' : '') + 'Error thrown for request: ' + req.url); } else { console.log('Error thrown for request: ' + req.url); } console.log(err.stack || err); } var msg = ''; if (seminarjs.get('env') === 'development') { if (err instanceof Error) { if (err.type) { msg += '<h2>' + err.type + '</h2>'; } msg += utils.textToHTML(err.message); } else if ('object' === typeof err) { msg += '<code>' + JSON.stringify(err) + '</code>'; } else if (err) { msg += err; } } res.status(500).send(seminarjs.wrapHTMLError('Sorry, an error occurred loading the page (500)', msg)); }
[ "function", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "if", "(", "seminarjs", ".", "get", "(", "'logger'", ")", ")", "{", "if", "(", "err", "instanceof", "Error", ")", "{", "console", ".", "log", "(", "(", "err", ".", "type", "?", "err", ".", "type", "+", "' '", ":", "''", ")", "+", "'Error thrown for request: '", "+", "req", ".", "url", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'Error thrown for request: '", "+", "req", ".", "url", ")", ";", "}", "console", ".", "log", "(", "err", ".", "stack", "||", "err", ")", ";", "}", "var", "msg", "=", "''", ";", "if", "(", "seminarjs", ".", "get", "(", "'env'", ")", "===", "'development'", ")", "{", "if", "(", "err", "instanceof", "Error", ")", "{", "if", "(", "err", ".", "type", ")", "{", "msg", "+=", "'<h2>'", "+", "err", ".", "type", "+", "'</h2>'", ";", "}", "msg", "+=", "utils", ".", "textToHTML", "(", "err", ".", "message", ")", ";", "}", "else", "if", "(", "'object'", "===", "typeof", "err", ")", "{", "msg", "+=", "'<code>'", "+", "JSON", ".", "stringify", "(", "err", ")", "+", "'</code>'", ";", "}", "else", "if", "(", "err", ")", "{", "msg", "+=", "err", ";", "}", "}", "res", ".", "status", "(", "500", ")", ".", "send", "(", "seminarjs", ".", "wrapHTMLError", "(", "'Sorry, an error occurred loading the page (500)'", ",", "msg", ")", ")", ";", "}" ]
Handle other errors
[ "Handle", "other", "errors" ]
53c4c1d5c33ffbf6320b10f25679bf181cbf853e
https://github.com/Nichejs/Seminarjs/blob/53c4c1d5c33ffbf6320b10f25679bf181cbf853e/private/lib/core/mount.js#L447-L475
55,810
richRemer/twixt-mutant
mutant.js
Mutant
function Mutant(obj) { var triggered, i = 0; mutations = {}; if (!obj.addEventListener) { obj = EventTarget(obj); } function trigger() { i++; if (triggered) return; triggered = setTimeout(function() { var evt = new MutationEvent(mutations, i); triggered = null; mutations = {}; i = 0; obj.dispatchEvent(evt); }, 0); } return new Proxy(obj, { deleteProperty: function(target, property) { if (property in target) { if (!(property in mutations)) { mutations[property] = target[property]; } delete target[property]; trigger(); } return true; }, defineProperty: function(target, property, descriptor) { var value = target[property]; Object.defineProperty(target, property, descriptor); if (!(property in mutations)) { if (target[property] !== value) { mutations[property] = value; trigger(); } } }, set: function(target, property, value, receiver) { if (value !== target[property]) { if (!(property in mutations)) { mutations[property] = target[property]; } target[property] = value; trigger(); } } }); }
javascript
function Mutant(obj) { var triggered, i = 0; mutations = {}; if (!obj.addEventListener) { obj = EventTarget(obj); } function trigger() { i++; if (triggered) return; triggered = setTimeout(function() { var evt = new MutationEvent(mutations, i); triggered = null; mutations = {}; i = 0; obj.dispatchEvent(evt); }, 0); } return new Proxy(obj, { deleteProperty: function(target, property) { if (property in target) { if (!(property in mutations)) { mutations[property] = target[property]; } delete target[property]; trigger(); } return true; }, defineProperty: function(target, property, descriptor) { var value = target[property]; Object.defineProperty(target, property, descriptor); if (!(property in mutations)) { if (target[property] !== value) { mutations[property] = value; trigger(); } } }, set: function(target, property, value, receiver) { if (value !== target[property]) { if (!(property in mutations)) { mutations[property] = target[property]; } target[property] = value; trigger(); } } }); }
[ "function", "Mutant", "(", "obj", ")", "{", "var", "triggered", ",", "i", "=", "0", ";", "mutations", "=", "{", "}", ";", "if", "(", "!", "obj", ".", "addEventListener", ")", "{", "obj", "=", "EventTarget", "(", "obj", ")", ";", "}", "function", "trigger", "(", ")", "{", "i", "++", ";", "if", "(", "triggered", ")", "return", ";", "triggered", "=", "setTimeout", "(", "function", "(", ")", "{", "var", "evt", "=", "new", "MutationEvent", "(", "mutations", ",", "i", ")", ";", "triggered", "=", "null", ";", "mutations", "=", "{", "}", ";", "i", "=", "0", ";", "obj", ".", "dispatchEvent", "(", "evt", ")", ";", "}", ",", "0", ")", ";", "}", "return", "new", "Proxy", "(", "obj", ",", "{", "deleteProperty", ":", "function", "(", "target", ",", "property", ")", "{", "if", "(", "property", "in", "target", ")", "{", "if", "(", "!", "(", "property", "in", "mutations", ")", ")", "{", "mutations", "[", "property", "]", "=", "target", "[", "property", "]", ";", "}", "delete", "target", "[", "property", "]", ";", "trigger", "(", ")", ";", "}", "return", "true", ";", "}", ",", "defineProperty", ":", "function", "(", "target", ",", "property", ",", "descriptor", ")", "{", "var", "value", "=", "target", "[", "property", "]", ";", "Object", ".", "defineProperty", "(", "target", ",", "property", ",", "descriptor", ")", ";", "if", "(", "!", "(", "property", "in", "mutations", ")", ")", "{", "if", "(", "target", "[", "property", "]", "!==", "value", ")", "{", "mutations", "[", "property", "]", "=", "value", ";", "trigger", "(", ")", ";", "}", "}", "}", ",", "set", ":", "function", "(", "target", ",", "property", ",", "value", ",", "receiver", ")", "{", "if", "(", "value", "!==", "target", "[", "property", "]", ")", "{", "if", "(", "!", "(", "property", "in", "mutations", ")", ")", "{", "mutations", "[", "property", "]", "=", "target", "[", "property", "]", ";", "}", "target", "[", "property", "]", "=", "value", ";", "trigger", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Create a object proxy that dispatches mutation events. @param {object} obj @returns {Mutant}
[ "Create", "a", "object", "proxy", "that", "dispatches", "mutation", "events", "." ]
13f91844dc794dc01475fd6ed720735e16b748bf
https://github.com/richRemer/twixt-mutant/blob/13f91844dc794dc01475fd6ed720735e16b748bf/mutant.js#L10-L71
55,811
richRemer/twixt-mutant
mutant.js
mutant
function mutant(obj) { if (!proxies.has(obj)) { proxies.set(obj, Mutant(obj)); } return proxies.get(obj); }
javascript
function mutant(obj) { if (!proxies.has(obj)) { proxies.set(obj, Mutant(obj)); } return proxies.get(obj); }
[ "function", "mutant", "(", "obj", ")", "{", "if", "(", "!", "proxies", ".", "has", "(", "obj", ")", ")", "{", "proxies", ".", "set", "(", "obj", ",", "Mutant", "(", "obj", ")", ")", ";", "}", "return", "proxies", ".", "get", "(", "obj", ")", ";", "}" ]
Return a Mutant proxy for the object. @param {object} obj @returns {Mutant}
[ "Return", "a", "Mutant", "proxy", "for", "the", "object", "." ]
13f91844dc794dc01475fd6ed720735e16b748bf
https://github.com/richRemer/twixt-mutant/blob/13f91844dc794dc01475fd6ed720735e16b748bf/mutant.js#L78-L84
55,812
robbyoconnor/tictactoe.js
lib/utils.js
ask
function ask(question, validValues, message) { readline.setDefaultOptions({ limit: validValues, limitMessage: message }); return readline.question(question); }
javascript
function ask(question, validValues, message) { readline.setDefaultOptions({ limit: validValues, limitMessage: message }); return readline.question(question); }
[ "function", "ask", "(", "question", ",", "validValues", ",", "message", ")", "{", "readline", ".", "setDefaultOptions", "(", "{", "limit", ":", "validValues", ",", "limitMessage", ":", "message", "}", ")", ";", "return", "readline", ".", "question", "(", "question", ")", ";", "}" ]
A helper function for getting user input @param {string} question The question to be asked @param {string} validValues Typically a regex or array @param {string} message The validation message @returns {string} the user input
[ "A", "helper", "function", "for", "getting", "user", "input" ]
1fc5850aaa9477e79027cdc5a19fc2202612980c
https://github.com/robbyoconnor/tictactoe.js/blob/1fc5850aaa9477e79027cdc5a19fc2202612980c/lib/utils.js#L20-L26
55,813
robbyoconnor/tictactoe.js
lib/utils.js
color
function color(c, bold, msg) { return bold ? clic.xterm(c).bold(msg) : clic.xterm(c)(msg); }
javascript
function color(c, bold, msg) { return bold ? clic.xterm(c).bold(msg) : clic.xterm(c)(msg); }
[ "function", "color", "(", "c", ",", "bold", ",", "msg", ")", "{", "return", "bold", "?", "clic", ".", "xterm", "(", "c", ")", ".", "bold", "(", "msg", ")", ":", "clic", ".", "xterm", "(", "c", ")", "(", "msg", ")", ";", "}" ]
Returns ANSI color strings for pretty CLI output @param {string} c @param {boolean} bold @param {string} msg @returns {string} the ANSI color string
[ "Returns", "ANSI", "color", "strings", "for", "pretty", "CLI", "output" ]
1fc5850aaa9477e79027cdc5a19fc2202612980c
https://github.com/robbyoconnor/tictactoe.js/blob/1fc5850aaa9477e79027cdc5a19fc2202612980c/lib/utils.js#L36-L38
55,814
springload/rikki-patterns
src/scripts/tasks/site.js
renderState
function renderState(env, stateDir, nav, componentData, state) { const statePath = Path.join(stateDir, 'index.html'); const raw = env.render('component-raw.html', { navigation: nav, component: componentData, state: state, config: config, tokens: getTokens(), }); mkdirp.sync(stateDir); fs.writeFileSync(statePath, raw, 'utf-8'); }
javascript
function renderState(env, stateDir, nav, componentData, state) { const statePath = Path.join(stateDir, 'index.html'); const raw = env.render('component-raw.html', { navigation: nav, component: componentData, state: state, config: config, tokens: getTokens(), }); mkdirp.sync(stateDir); fs.writeFileSync(statePath, raw, 'utf-8'); }
[ "function", "renderState", "(", "env", ",", "stateDir", ",", "nav", ",", "componentData", ",", "state", ")", "{", "const", "statePath", "=", "Path", ".", "join", "(", "stateDir", ",", "'index.html'", ")", ";", "const", "raw", "=", "env", ".", "render", "(", "'component-raw.html'", ",", "{", "navigation", ":", "nav", ",", "component", ":", "componentData", ",", "state", ":", "state", ",", "config", ":", "config", ",", "tokens", ":", "getTokens", "(", ")", ",", "}", ")", ";", "mkdirp", ".", "sync", "(", "stateDir", ")", ";", "fs", ".", "writeFileSync", "(", "statePath", ",", "raw", ",", "'utf-8'", ")", ";", "}" ]
Renders the `raw` view of each component's state
[ "Renders", "the", "raw", "view", "of", "each", "component", "s", "state" ]
9906f69f9a29f587911ff66cf997fcf2f4f90452
https://github.com/springload/rikki-patterns/blob/9906f69f9a29f587911ff66cf997fcf2f4f90452/src/scripts/tasks/site.js#L64-L77
55,815
springload/rikki-patterns
src/scripts/tasks/site.js
renderDocs
function renderDocs(SITE_DIR, name) { const env = templates.configure(); const nav = navigation.getNavigation(); const components = _.find(nav.children, { id: name }); components.children.forEach(component => { const dirPath = Path.join(SITE_DIR, component.path); console.log(dirPath); const htmlPath = Path.join(dirPath, 'index.html'); const rawDir = Path.join(SITE_DIR, 'raw', component.id); const componentData = findComponent(component.id); componentData.template = pathTrimStart( Path.join(component.path, `${component.id}.html`), ); const html = env.render('component.html', { navigation: nav, component: componentData, config: config, tokens: getTokens(), }); mkdirp.sync(rawDir); mkdirp.sync(dirPath); fs.writeFileSync(htmlPath, html, 'utf-8'); if (componentData.flavours) { componentData.flavours.forEach(flavour => { if (flavour.states) { flavour.states.forEach(variant => { const state = getStateFromFlavour( componentData, flavour.id, variant.id, ); const stateDir = Path.join( rawDir, flavour.id, variant.id, ); renderState(env, stateDir, nav, componentData, state); }); } if (flavour.state) { const stateDir = Path.join(rawDir, flavour.id); renderState( env, stateDir, nav, componentData, flavour.state, ); } }); } }); }
javascript
function renderDocs(SITE_DIR, name) { const env = templates.configure(); const nav = navigation.getNavigation(); const components = _.find(nav.children, { id: name }); components.children.forEach(component => { const dirPath = Path.join(SITE_DIR, component.path); console.log(dirPath); const htmlPath = Path.join(dirPath, 'index.html'); const rawDir = Path.join(SITE_DIR, 'raw', component.id); const componentData = findComponent(component.id); componentData.template = pathTrimStart( Path.join(component.path, `${component.id}.html`), ); const html = env.render('component.html', { navigation: nav, component: componentData, config: config, tokens: getTokens(), }); mkdirp.sync(rawDir); mkdirp.sync(dirPath); fs.writeFileSync(htmlPath, html, 'utf-8'); if (componentData.flavours) { componentData.flavours.forEach(flavour => { if (flavour.states) { flavour.states.forEach(variant => { const state = getStateFromFlavour( componentData, flavour.id, variant.id, ); const stateDir = Path.join( rawDir, flavour.id, variant.id, ); renderState(env, stateDir, nav, componentData, state); }); } if (flavour.state) { const stateDir = Path.join(rawDir, flavour.id); renderState( env, stateDir, nav, componentData, flavour.state, ); } }); } }); }
[ "function", "renderDocs", "(", "SITE_DIR", ",", "name", ")", "{", "const", "env", "=", "templates", ".", "configure", "(", ")", ";", "const", "nav", "=", "navigation", ".", "getNavigation", "(", ")", ";", "const", "components", "=", "_", ".", "find", "(", "nav", ".", "children", ",", "{", "id", ":", "name", "}", ")", ";", "components", ".", "children", ".", "forEach", "(", "component", "=>", "{", "const", "dirPath", "=", "Path", ".", "join", "(", "SITE_DIR", ",", "component", ".", "path", ")", ";", "console", ".", "log", "(", "dirPath", ")", ";", "const", "htmlPath", "=", "Path", ".", "join", "(", "dirPath", ",", "'index.html'", ")", ";", "const", "rawDir", "=", "Path", ".", "join", "(", "SITE_DIR", ",", "'raw'", ",", "component", ".", "id", ")", ";", "const", "componentData", "=", "findComponent", "(", "component", ".", "id", ")", ";", "componentData", ".", "template", "=", "pathTrimStart", "(", "Path", ".", "join", "(", "component", ".", "path", ",", "`", "${", "component", ".", "id", "}", "`", ")", ",", ")", ";", "const", "html", "=", "env", ".", "render", "(", "'component.html'", ",", "{", "navigation", ":", "nav", ",", "component", ":", "componentData", ",", "config", ":", "config", ",", "tokens", ":", "getTokens", "(", ")", ",", "}", ")", ";", "mkdirp", ".", "sync", "(", "rawDir", ")", ";", "mkdirp", ".", "sync", "(", "dirPath", ")", ";", "fs", ".", "writeFileSync", "(", "htmlPath", ",", "html", ",", "'utf-8'", ")", ";", "if", "(", "componentData", ".", "flavours", ")", "{", "componentData", ".", "flavours", ".", "forEach", "(", "flavour", "=>", "{", "if", "(", "flavour", ".", "states", ")", "{", "flavour", ".", "states", ".", "forEach", "(", "variant", "=>", "{", "const", "state", "=", "getStateFromFlavour", "(", "componentData", ",", "flavour", ".", "id", ",", "variant", ".", "id", ",", ")", ";", "const", "stateDir", "=", "Path", ".", "join", "(", "rawDir", ",", "flavour", ".", "id", ",", "variant", ".", "id", ",", ")", ";", "renderState", "(", "env", ",", "stateDir", ",", "nav", ",", "componentData", ",", "state", ")", ";", "}", ")", ";", "}", "if", "(", "flavour", ".", "state", ")", "{", "const", "stateDir", "=", "Path", ".", "join", "(", "rawDir", ",", "flavour", ".", "id", ")", ";", "renderState", "(", "env", ",", "stateDir", ",", "nav", ",", "componentData", ",", "flavour", ".", "state", ",", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
Renders the documentation for each component
[ "Renders", "the", "documentation", "for", "each", "component" ]
9906f69f9a29f587911ff66cf997fcf2f4f90452
https://github.com/springload/rikki-patterns/blob/9906f69f9a29f587911ff66cf997fcf2f4f90452/src/scripts/tasks/site.js#L80-L139
55,816
jdmota/mota-webdevtools
src/findFiles.js
function( string ) { var negated, matches, patterns = this.patterns, i = patterns.length; while ( i-- ) { negated = patterns[ i ].negated; matches = patterns[ i ].matcher( string ); if ( negated !== matches ) { return matches; } } return false; }
javascript
function( string ) { var negated, matches, patterns = this.patterns, i = patterns.length; while ( i-- ) { negated = patterns[ i ].negated; matches = patterns[ i ].matcher( string ); if ( negated !== matches ) { return matches; } } return false; }
[ "function", "(", "string", ")", "{", "var", "negated", ",", "matches", ",", "patterns", "=", "this", ".", "patterns", ",", "i", "=", "patterns", ".", "length", ";", "while", "(", "i", "--", ")", "{", "negated", "=", "patterns", "[", "i", "]", ".", "negated", ";", "matches", "=", "patterns", "[", "i", "]", ".", "matcher", "(", "string", ")", ";", "if", "(", "negated", "!==", "matches", ")", "{", "return", "matches", ";", "}", "}", "return", "false", ";", "}" ]
We start from the end negated matches 0 0 keep going 0 1 return true 1 0 return false 1 1 keep going
[ "We", "start", "from", "the", "end", "negated", "matches", "0", "0", "keep", "going", "0", "1", "return", "true", "1", "0", "return", "false", "1", "1", "keep", "going" ]
7ecba6bee3ce83cec33931380b9dc1f63aa6904a
https://github.com/jdmota/mota-webdevtools/blob/7ecba6bee3ce83cec33931380b9dc1f63aa6904a/src/findFiles.js#L33-L43
55,817
shinuza/captain-core
lib/models/users.js
find
function find(param) { var fn, asInt = parseInt(param, 10); fn = isNaN(asInt) ? findByUsername : findById; fn.apply(null, arguments); }
javascript
function find(param) { var fn, asInt = parseInt(param, 10); fn = isNaN(asInt) ? findByUsername : findById; fn.apply(null, arguments); }
[ "function", "find", "(", "param", ")", "{", "var", "fn", ",", "asInt", "=", "parseInt", "(", "param", ",", "10", ")", ";", "fn", "=", "isNaN", "(", "asInt", ")", "?", "findByUsername", ":", "findById", ";", "fn", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}" ]
Smart find, uses findByUsername or findBy @param {*} param
[ "Smart", "find", "uses", "findByUsername", "or", "findBy" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/users.js#L44-L48
55,818
shinuza/captain-core
lib/models/users.js
findByCredentials
function findByCredentials(username, password, cb) { crypto.encode(password, function(err, encoded) { if(err) { return cb(err); } db.getClient(function(err, client, done) { client.query(SELECT_CREDENTIALS, [username, encoded], function(err, r) { var result = r && r.rows[0]; if(!err && !result) { err = new exceptions.AuthenticationFailed(); } if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }); }
javascript
function findByCredentials(username, password, cb) { crypto.encode(password, function(err, encoded) { if(err) { return cb(err); } db.getClient(function(err, client, done) { client.query(SELECT_CREDENTIALS, [username, encoded], function(err, r) { var result = r && r.rows[0]; if(!err && !result) { err = new exceptions.AuthenticationFailed(); } if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }); }
[ "function", "findByCredentials", "(", "username", ",", "password", ",", "cb", ")", "{", "crypto", ".", "encode", "(", "password", ",", "function", "(", "err", ",", "encoded", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "db", ".", "getClient", "(", "function", "(", "err", ",", "client", ",", "done", ")", "{", "client", ".", "query", "(", "SELECT_CREDENTIALS", ",", "[", "username", ",", "encoded", "]", ",", "function", "(", "err", ",", "r", ")", "{", "var", "result", "=", "r", "&&", "r", ".", "rows", "[", "0", "]", ";", "if", "(", "!", "err", "&&", "!", "result", ")", "{", "err", "=", "new", "exceptions", ".", "AuthenticationFailed", "(", ")", ";", "}", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "done", "(", "err", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "result", ")", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Finds a user by `username` and `password` `cb` is passed with the matching user or exceptions.AuthenticationFailed @param {String} username @param {String} password @param {Function} cb
[ "Finds", "a", "user", "by", "username", "and", "password" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/users.js#L61-L79
55,819
shinuza/captain-core
lib/models/users.js
findByUsername
function findByUsername(username, cb) { db.getClient(function(err, client, done) { client.query(SELECT_USERNAME, [username], function(err, r) { var result = r && r.rows[0]; if(!err && !result) { err = new exceptions.NotFound(); } if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }
javascript
function findByUsername(username, cb) { db.getClient(function(err, client, done) { client.query(SELECT_USERNAME, [username], function(err, r) { var result = r && r.rows[0]; if(!err && !result) { err = new exceptions.NotFound(); } if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }
[ "function", "findByUsername", "(", "username", ",", "cb", ")", "{", "db", ".", "getClient", "(", "function", "(", "err", ",", "client", ",", "done", ")", "{", "client", ".", "query", "(", "SELECT_USERNAME", ",", "[", "username", "]", ",", "function", "(", "err", ",", "r", ")", "{", "var", "result", "=", "r", "&&", "r", ".", "rows", "[", "0", "]", ";", "if", "(", "!", "err", "&&", "!", "result", ")", "{", "err", "=", "new", "exceptions", ".", "NotFound", "(", ")", ";", "}", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "done", "(", "err", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "result", ")", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Finds a user by `username` `cb` is passed with the matching user or exceptions.NotFound @param {String} username @param {Function} cb
[ "Finds", "a", "user", "by", "username" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/users.js#L91-L105
55,820
shinuza/captain-core
lib/models/users.js
update
function update(id, body, cb) { if(body.password) { crypto.encode(body.password, function(err, encoded) { if(err) { return cb(err); } body.password = encoded; _update(id, body, cb); }); } else { _update(id, body, cb); } }
javascript
function update(id, body, cb) { if(body.password) { crypto.encode(body.password, function(err, encoded) { if(err) { return cb(err); } body.password = encoded; _update(id, body, cb); }); } else { _update(id, body, cb); } }
[ "function", "update", "(", "id", ",", "body", ",", "cb", ")", "{", "if", "(", "body", ".", "password", ")", "{", "crypto", ".", "encode", "(", "body", ".", "password", ",", "function", "(", "err", ",", "encoded", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "body", ".", "password", "=", "encoded", ";", "_update", "(", "id", ",", "body", ",", "cb", ")", ";", "}", ")", ";", "}", "else", "{", "_update", "(", "id", ",", "body", ",", "cb", ")", ";", "}", "}" ]
Updates user with `id` `cb` is passed with the updated user or: * exceptions.NotFound if the `id` is not found in the database * exceptions.AlreadyExists if the `username` conflicts with another user @param {Number} id @param {Object} body @param {Function} cb
[ "Updates", "user", "with", "id" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/users.js#L190-L200
55,821
kriserickson/generator-topcoat-touch
app/templates/_app.js
createPlaceHolder
function createPlaceHolder($page, type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $page.find('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... }
javascript
function createPlaceHolder($page, type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $page.find('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... }
[ "function", "createPlaceHolder", "(", "$page", ",", "type", ")", "{", "var", "placeHolders", "=", "{", "kittens", ":", "'placekitten.com'", ",", "bears", ":", "'placebear.com'", ",", "lorem", ":", "'lorempixel.com'", ",", "bacon", ":", "'baconmockup.com'", ",", "murray", ":", "'www.fillmurray.com'", "}", ";", "var", "gallery", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "getRandomInt", "(", "50", ",", "100", ")", ";", "i", "++", ")", "{", "gallery", "+=", "'<li class=\"photoClass\" style=\"background:url(http://'", "+", "placeHolders", "[", "type", "]", "+", "'/'", "+", "getRandomInt", "(", "200", ",", "300", ")", "+", "'/'", "+", "getRandomInt", "(", "200", ",", "300", ")", "+", "') 50% 50% no-repeat\"></li>'", ";", "}", "$page", ".", "find", "(", "'.photo-gallery'", ")", ".", "html", "(", "gallery", ")", ";", "tt", ".", "refreshScroll", "(", ")", ";", "// Refresh the scroller", "tt", ".", "scrollTo", "(", "0", ",", "0", ")", ";", "// Move back to the top of the page...", "}" ]
Create the placeholders in the gallery...
[ "Create", "the", "placeholders", "in", "the", "gallery", "..." ]
47d0f95ccfb7ab3c20feb7ed12158b872caac1e3
https://github.com/kriserickson/generator-topcoat-touch/blob/47d0f95ccfb7ab3c20feb7ed12158b872caac1e3/app/templates/_app.js#L116-L127
55,822
el-fuego/grunt-concat-properties
tasks/lib/writer.js
addToJSONRecursively
function addToJSONRecursively(contextNames, data, obj) { var currentContexName = contextNames.shift(); // last name if (!contextNames.length) { obj[currentContexName] = data; return; } if (!obj[currentContexName]) { obj[currentContexName] = {}; } addToJSONRecursively(contextNames, data, obj[currentContexName]); }
javascript
function addToJSONRecursively(contextNames, data, obj) { var currentContexName = contextNames.shift(); // last name if (!contextNames.length) { obj[currentContexName] = data; return; } if (!obj[currentContexName]) { obj[currentContexName] = {}; } addToJSONRecursively(contextNames, data, obj[currentContexName]); }
[ "function", "addToJSONRecursively", "(", "contextNames", ",", "data", ",", "obj", ")", "{", "var", "currentContexName", "=", "contextNames", ".", "shift", "(", ")", ";", "// last name", "if", "(", "!", "contextNames", ".", "length", ")", "{", "obj", "[", "currentContexName", "]", "=", "data", ";", "return", ";", "}", "if", "(", "!", "obj", "[", "currentContexName", "]", ")", "{", "obj", "[", "currentContexName", "]", "=", "{", "}", ";", "}", "addToJSONRecursively", "(", "contextNames", ",", "data", ",", "obj", "[", "currentContexName", "]", ")", ";", "}" ]
Add data to object at specified context obj.a.b.c = data; @param contextNames [{String}] f.e. ['a', 'b', 'c'..] @param data {String} data to set @param obj {Object} changable
[ "Add", "data", "to", "object", "at", "specified", "context", "obj", ".", "a", ".", "b", ".", "c", "=", "data", ";" ]
a7efad68106d81aec262deee12190c75952f09b3
https://github.com/el-fuego/grunt-concat-properties/blob/a7efad68106d81aec262deee12190c75952f09b3/tasks/lib/writer.js#L23-L37
55,823
el-fuego/grunt-concat-properties
tasks/lib/writer.js
propertyToString
function propertyToString(property) { return property.comment + utils.addQuotes(property.name.split('.').pop()) + ': ' + ( typeof options.sourceProcessor === 'function' ? options.sourceProcessor(property.source, property) : property.source ); }
javascript
function propertyToString(property) { return property.comment + utils.addQuotes(property.name.split('.').pop()) + ': ' + ( typeof options.sourceProcessor === 'function' ? options.sourceProcessor(property.source, property) : property.source ); }
[ "function", "propertyToString", "(", "property", ")", "{", "return", "property", ".", "comment", "+", "utils", ".", "addQuotes", "(", "property", ".", "name", ".", "split", "(", "'.'", ")", ".", "pop", "(", ")", ")", "+", "': '", "+", "(", "typeof", "options", ".", "sourceProcessor", "===", "'function'", "?", "options", ".", "sourceProcessor", "(", "property", ".", "source", ",", "property", ")", ":", "property", ".", "source", ")", ";", "}" ]
Concat property data to local definition as object method or attribute @param property {Object} @returns {string}
[ "Concat", "property", "data", "to", "local", "definition", "as", "object", "method", "or", "attribute" ]
a7efad68106d81aec262deee12190c75952f09b3
https://github.com/el-fuego/grunt-concat-properties/blob/a7efad68106d81aec262deee12190c75952f09b3/tasks/lib/writer.js#L44-L54
55,824
el-fuego/grunt-concat-properties
tasks/lib/writer.js
stringifyJSONProperties
function stringifyJSONProperties(obj) { var i, properties = []; for (i in obj) { properties.push( typeof obj[i] === 'string' ? obj[i] : utils.addQuotes(i) + ': ' + stringifyJSONProperties(obj[i]) ); } return '{\n' + properties.join(',\n\n') + '\n}'; }
javascript
function stringifyJSONProperties(obj) { var i, properties = []; for (i in obj) { properties.push( typeof obj[i] === 'string' ? obj[i] : utils.addQuotes(i) + ': ' + stringifyJSONProperties(obj[i]) ); } return '{\n' + properties.join(',\n\n') + '\n}'; }
[ "function", "stringifyJSONProperties", "(", "obj", ")", "{", "var", "i", ",", "properties", "=", "[", "]", ";", "for", "(", "i", "in", "obj", ")", "{", "properties", ".", "push", "(", "typeof", "obj", "[", "i", "]", "===", "'string'", "?", "obj", "[", "i", "]", ":", "utils", ".", "addQuotes", "(", "i", ")", "+", "': '", "+", "stringifyJSONProperties", "(", "obj", "[", "i", "]", ")", ")", ";", "}", "return", "'{\\n'", "+", "properties", ".", "join", "(", "',\\n\\n'", ")", "+", "'\\n}'", ";", "}" ]
Concat properties object to string @param obj {Object} properties as object f.e. {a: {b: '...'}} @returns {String}
[ "Concat", "properties", "object", "to", "string" ]
a7efad68106d81aec262deee12190c75952f09b3
https://github.com/el-fuego/grunt-concat-properties/blob/a7efad68106d81aec262deee12190c75952f09b3/tasks/lib/writer.js#L61-L74
55,825
el-fuego/grunt-concat-properties
tasks/lib/writer.js
addPropertiesToText
function addPropertiesToText(text, properties, filePath) { if (!properties.length) { return text; } var placeRegexp = patterns.getPlacePattern(properties[0].isFromPrototype), matchedData = placeRegexp.exec(text); // Can`t find properties place if (!matchedData) { grunt.log.error("No " + (properties[0].isFromPrototype ? "prototype" : "inline") + " properties place definition at " + filePath + ' (properties: ' + properties.map(function (p) {return p.name + ' at ' + p.filePath; }).join(', ') + ')'); return text; } // don`t use .replace with "$" at replacement text return text.replace(placeRegexp, function () { return (matchedData[1] ? matchedData[1] + ',' : '') + ('\n\n' + concatProperties(properties)) .replace(/\n(?!\r?\n)/g, '\n' + matchedData[2]); }); }
javascript
function addPropertiesToText(text, properties, filePath) { if (!properties.length) { return text; } var placeRegexp = patterns.getPlacePattern(properties[0].isFromPrototype), matchedData = placeRegexp.exec(text); // Can`t find properties place if (!matchedData) { grunt.log.error("No " + (properties[0].isFromPrototype ? "prototype" : "inline") + " properties place definition at " + filePath + ' (properties: ' + properties.map(function (p) {return p.name + ' at ' + p.filePath; }).join(', ') + ')'); return text; } // don`t use .replace with "$" at replacement text return text.replace(placeRegexp, function () { return (matchedData[1] ? matchedData[1] + ',' : '') + ('\n\n' + concatProperties(properties)) .replace(/\n(?!\r?\n)/g, '\n' + matchedData[2]); }); }
[ "function", "addPropertiesToText", "(", "text", ",", "properties", ",", "filePath", ")", "{", "if", "(", "!", "properties", ".", "length", ")", "{", "return", "text", ";", "}", "var", "placeRegexp", "=", "patterns", ".", "getPlacePattern", "(", "properties", "[", "0", "]", ".", "isFromPrototype", ")", ",", "matchedData", "=", "placeRegexp", ".", "exec", "(", "text", ")", ";", "// Can`t find properties place", "if", "(", "!", "matchedData", ")", "{", "grunt", ".", "log", ".", "error", "(", "\"No \"", "+", "(", "properties", "[", "0", "]", ".", "isFromPrototype", "?", "\"prototype\"", ":", "\"inline\"", ")", "+", "\" properties place definition at \"", "+", "filePath", "+", "' (properties: '", "+", "properties", ".", "map", "(", "function", "(", "p", ")", "{", "return", "p", ".", "name", "+", "' at '", "+", "p", ".", "filePath", ";", "}", ")", ".", "join", "(", "', '", ")", "+", "')'", ")", ";", "return", "text", ";", "}", "// don`t use .replace with \"$\" at replacement text", "return", "text", ".", "replace", "(", "placeRegexp", ",", "function", "(", ")", "{", "return", "(", "matchedData", "[", "1", "]", "?", "matchedData", "[", "1", "]", "+", "','", ":", "''", ")", "+", "(", "'\\n\\n'", "+", "concatProperties", "(", "properties", ")", ")", ".", "replace", "(", "/", "\\n(?!\\r?\\n)", "/", "g", ",", "'\\n'", "+", "matchedData", "[", "2", "]", ")", ";", "}", ")", ";", "}" ]
Replace place pattern with concated properties @param text {String} @param properties {Array} @param filePath {String} @returns {String}
[ "Replace", "place", "pattern", "with", "concated", "properties" ]
a7efad68106d81aec262deee12190c75952f09b3
https://github.com/el-fuego/grunt-concat-properties/blob/a7efad68106d81aec262deee12190c75952f09b3/tasks/lib/writer.js#L119-L142
55,826
rich-97/are-arrays
are-arrays.js
areArrays
function areArrays () { for (let i = 0; i < arguments.length; i++) { if (!Array.isArray(arguments[i])) { return false; } } return true; }
javascript
function areArrays () { for (let i = 0; i < arguments.length; i++) { if (!Array.isArray(arguments[i])) { return false; } } return true; }
[ "function", "areArrays", "(", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "arguments", "[", "i", "]", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
areArrays This takes any parameters @returns {boolean}
[ "areArrays", "This", "takes", "any", "parameters" ]
af8d15d3768b26d9de290fed208c97ea3c1e068e
https://github.com/rich-97/are-arrays/blob/af8d15d3768b26d9de290fed208c97ea3c1e068e/are-arrays.js#L17-L25
55,827
numbervine/misc-utils
dist/index.es.js
deepDiff
function deepDiff(obj1, obj2, path) { return merge_1(_deepDiff(obj1, obj2, path), _deepDiff(obj2, obj1, path)); }
javascript
function deepDiff(obj1, obj2, path) { return merge_1(_deepDiff(obj1, obj2, path), _deepDiff(obj2, obj1, path)); }
[ "function", "deepDiff", "(", "obj1", ",", "obj2", ",", "path", ")", "{", "return", "merge_1", "(", "_deepDiff", "(", "obj1", ",", "obj2", ",", "path", ")", ",", "_deepDiff", "(", "obj2", ",", "obj1", ",", "path", ")", ")", ";", "}" ]
Compares key value paris between `obj1` and `obj2` recursively, optionally starting from the node specified by `path` and returns an array of paths that are not shared by both objects, or contain different values @since 1.0.0 @category Misc @param {Object} obj1 First object for comparison @param {Object} obj2 Second object for comparison @param {String} path optional node specifying point to start object comparison @returns {Array} Paths not common to both objects, or containing different values
[ "Compares", "key", "value", "paris", "between", "obj1", "and", "obj2", "recursively", "optionally", "starting", "from", "the", "node", "specified", "by", "path", "and", "returns", "an", "array", "of", "paths", "that", "are", "not", "shared", "by", "both", "objects", "or", "contain", "different", "values" ]
763c2d646090ec6a74fda0d465b8124a9cf62a41
https://github.com/numbervine/misc-utils/blob/763c2d646090ec6a74fda0d465b8124a9cf62a41/dist/index.es.js#L4476-L4478
55,828
recursivefunk/nyce
lib/validate.js
checkFunctions
function checkFunctions (impl, schema) { const children = schema.describe().children const ret = { ok: true } for (let i in children) { if (impl.hasOwnProperty(i) && children.hasOwnProperty(i)) { if (children[ i ].flags && children[ i ].flags.func === true) { const func = impl[ i ] const funcSig = utils.parseFuncSig(func) let expectedArgs if (children[ i ].meta) { expectedArgs = children[ i ].meta[ 0 ].args if (!sameArray(funcSig, expectedArgs)) { ret.ok = false ret.message = errors.invalidSignature(i, expectedArgs, funcSig) } if (funcSig.length !== expectedArgs.length) { ret.ok = false ret.message = errors .unexpectedArgsLength(i, expectedArgs.length, funcSig.length) } } else { if (typeof impl[ i ] !== 'function') { ret.ok = false ret.message = `Property '${i}' is not a function!` } } if (!ret.ok) { return ret } } } } return ret }
javascript
function checkFunctions (impl, schema) { const children = schema.describe().children const ret = { ok: true } for (let i in children) { if (impl.hasOwnProperty(i) && children.hasOwnProperty(i)) { if (children[ i ].flags && children[ i ].flags.func === true) { const func = impl[ i ] const funcSig = utils.parseFuncSig(func) let expectedArgs if (children[ i ].meta) { expectedArgs = children[ i ].meta[ 0 ].args if (!sameArray(funcSig, expectedArgs)) { ret.ok = false ret.message = errors.invalidSignature(i, expectedArgs, funcSig) } if (funcSig.length !== expectedArgs.length) { ret.ok = false ret.message = errors .unexpectedArgsLength(i, expectedArgs.length, funcSig.length) } } else { if (typeof impl[ i ] !== 'function') { ret.ok = false ret.message = `Property '${i}' is not a function!` } } if (!ret.ok) { return ret } } } } return ret }
[ "function", "checkFunctions", "(", "impl", ",", "schema", ")", "{", "const", "children", "=", "schema", ".", "describe", "(", ")", ".", "children", "const", "ret", "=", "{", "ok", ":", "true", "}", "for", "(", "let", "i", "in", "children", ")", "{", "if", "(", "impl", ".", "hasOwnProperty", "(", "i", ")", "&&", "children", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "if", "(", "children", "[", "i", "]", ".", "flags", "&&", "children", "[", "i", "]", ".", "flags", ".", "func", "===", "true", ")", "{", "const", "func", "=", "impl", "[", "i", "]", "const", "funcSig", "=", "utils", ".", "parseFuncSig", "(", "func", ")", "let", "expectedArgs", "if", "(", "children", "[", "i", "]", ".", "meta", ")", "{", "expectedArgs", "=", "children", "[", "i", "]", ".", "meta", "[", "0", "]", ".", "args", "if", "(", "!", "sameArray", "(", "funcSig", ",", "expectedArgs", ")", ")", "{", "ret", ".", "ok", "=", "false", "ret", ".", "message", "=", "errors", ".", "invalidSignature", "(", "i", ",", "expectedArgs", ",", "funcSig", ")", "}", "if", "(", "funcSig", ".", "length", "!==", "expectedArgs", ".", "length", ")", "{", "ret", ".", "ok", "=", "false", "ret", ".", "message", "=", "errors", ".", "unexpectedArgsLength", "(", "i", ",", "expectedArgs", ".", "length", ",", "funcSig", ".", "length", ")", "}", "}", "else", "{", "if", "(", "typeof", "impl", "[", "i", "]", "!==", "'function'", ")", "{", "ret", ".", "ok", "=", "false", "ret", ".", "message", "=", "`", "${", "i", "}", "`", "}", "}", "if", "(", "!", "ret", ".", "ok", ")", "{", "return", "ret", "}", "}", "}", "}", "return", "ret", "}" ]
Does some funky joi object parsing and parses the function signature to extract parameter names
[ "Does", "some", "funky", "joi", "object", "parsing", "and", "parses", "the", "function", "signature", "to", "extract", "parameter", "names" ]
2b62a853a0c9cce99d8c982c5b7a28e2b4852081
https://github.com/recursivefunk/nyce/blob/2b62a853a0c9cce99d8c982c5b7a28e2b4852081/lib/validate.js#L41-L78
55,829
gmalysa/flux-link
lib/gen-dot.js
_dot_inner
function _dot_inner(elem, make_digraph, names) { var builder = []; var name = hash_name_get(elem, names); // Only push graphs/clusters for chains if (elem instanceof fl.ChainBase) { if (make_digraph) builder.push('digraph '+name+' {'); else builder.push('subgraph cluster_'+name+' {'); builder.push('label = '+name+';'); // Get the graph content for this chain, then add it var nest = get_chain_content(elem, names); Array.prototype.push.apply(builder, nest[0]); var chain_entry = nest[1]; var chain_exit = nest[2]; // Also insert special header node to indicate entry if (make_digraph) { var header = hash_name_get({name : 'Global Start'}, names); builder.push(header+' [shape=doublecircle];'); builder.push(header+' -> '+chain_entry+';'); builder.push(chain_exit+' [shape=doublecircle];'); } builder.push('}'); return [builder, chain_entry, chain_exit]; } else { // Just a normal function, return it in our results return [[], name, name]; } }
javascript
function _dot_inner(elem, make_digraph, names) { var builder = []; var name = hash_name_get(elem, names); // Only push graphs/clusters for chains if (elem instanceof fl.ChainBase) { if (make_digraph) builder.push('digraph '+name+' {'); else builder.push('subgraph cluster_'+name+' {'); builder.push('label = '+name+';'); // Get the graph content for this chain, then add it var nest = get_chain_content(elem, names); Array.prototype.push.apply(builder, nest[0]); var chain_entry = nest[1]; var chain_exit = nest[2]; // Also insert special header node to indicate entry if (make_digraph) { var header = hash_name_get({name : 'Global Start'}, names); builder.push(header+' [shape=doublecircle];'); builder.push(header+' -> '+chain_entry+';'); builder.push(chain_exit+' [shape=doublecircle];'); } builder.push('}'); return [builder, chain_entry, chain_exit]; } else { // Just a normal function, return it in our results return [[], name, name]; } }
[ "function", "_dot_inner", "(", "elem", ",", "make_digraph", ",", "names", ")", "{", "var", "builder", "=", "[", "]", ";", "var", "name", "=", "hash_name_get", "(", "elem", ",", "names", ")", ";", "// Only push graphs/clusters for chains", "if", "(", "elem", "instanceof", "fl", ".", "ChainBase", ")", "{", "if", "(", "make_digraph", ")", "builder", ".", "push", "(", "'digraph '", "+", "name", "+", "' {'", ")", ";", "else", "builder", ".", "push", "(", "'subgraph cluster_'", "+", "name", "+", "' {'", ")", ";", "builder", ".", "push", "(", "'label = '", "+", "name", "+", "';'", ")", ";", "// Get the graph content for this chain, then add it", "var", "nest", "=", "get_chain_content", "(", "elem", ",", "names", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "nest", "[", "0", "]", ")", ";", "var", "chain_entry", "=", "nest", "[", "1", "]", ";", "var", "chain_exit", "=", "nest", "[", "2", "]", ";", "// Also insert special header node to indicate entry", "if", "(", "make_digraph", ")", "{", "var", "header", "=", "hash_name_get", "(", "{", "name", ":", "'Global Start'", "}", ",", "names", ")", ";", "builder", ".", "push", "(", "header", "+", "' [shape=doublecircle];'", ")", ";", "builder", ".", "push", "(", "header", "+", "' -> '", "+", "chain_entry", "+", "';'", ")", ";", "builder", ".", "push", "(", "chain_exit", "+", "' [shape=doublecircle];'", ")", ";", "}", "builder", ".", "push", "(", "'}'", ")", ";", "return", "[", "builder", ",", "chain_entry", ",", "chain_exit", "]", ";", "}", "else", "{", "// Just a normal function, return it in our results", "return", "[", "[", "]", ",", "name", ",", "name", "]", ";", "}", "}" ]
Inner worker function used to build the actual DOT description @param elem The element to describe @param make_digraph Should this node be instantiated as a digraph or subgraph cluster @param names The hash table of functions and their names that have been seen @return Standard triple of [strings, first element, last element]
[ "Inner", "worker", "function", "used", "to", "build", "the", "actual", "DOT", "description" ]
567ac39a1f4a74f85465a58fb6fd96d64b1b765f
https://github.com/gmalysa/flux-link/blob/567ac39a1f4a74f85465a58fb6fd96d64b1b765f/lib/gen-dot.js#L30-L64
55,830
gmalysa/flux-link
lib/gen-dot.js
get_chain_content
function get_chain_content(elem, names) { if (elem instanceof fl.Branch) { return handle_branch(elem, names); } else if (elem instanceof fl.ParallelChain) { return handle_parallel(elem, names); } else if (elem instanceof fl.LoopChain) { return handle_loop(elem, names); } else if (elem instanceof fl.Chain) { return handle_chain(elem, names); } else { // A chain type we don't handle yet...shouldn't happen hopefully return [[], hash_name_get({name : 'unidentified'}), hash_name_get({name : 'unidentified'})]; } }
javascript
function get_chain_content(elem, names) { if (elem instanceof fl.Branch) { return handle_branch(elem, names); } else if (elem instanceof fl.ParallelChain) { return handle_parallel(elem, names); } else if (elem instanceof fl.LoopChain) { return handle_loop(elem, names); } else if (elem instanceof fl.Chain) { return handle_chain(elem, names); } else { // A chain type we don't handle yet...shouldn't happen hopefully return [[], hash_name_get({name : 'unidentified'}), hash_name_get({name : 'unidentified'})]; } }
[ "function", "get_chain_content", "(", "elem", ",", "names", ")", "{", "if", "(", "elem", "instanceof", "fl", ".", "Branch", ")", "{", "return", "handle_branch", "(", "elem", ",", "names", ")", ";", "}", "else", "if", "(", "elem", "instanceof", "fl", ".", "ParallelChain", ")", "{", "return", "handle_parallel", "(", "elem", ",", "names", ")", ";", "}", "else", "if", "(", "elem", "instanceof", "fl", ".", "LoopChain", ")", "{", "return", "handle_loop", "(", "elem", ",", "names", ")", ";", "}", "else", "if", "(", "elem", "instanceof", "fl", ".", "Chain", ")", "{", "return", "handle_chain", "(", "elem", ",", "names", ")", ";", "}", "else", "{", "// A chain type we don't handle yet...shouldn't happen hopefully", "return", "[", "[", "]", ",", "hash_name_get", "(", "{", "name", ":", "'unidentified'", "}", ")", ",", "hash_name_get", "(", "{", "name", ":", "'unidentified'", "}", ")", "]", ";", "}", "}" ]
Breakout function that simply calls the correct handler based on the type of the element supplied @param elem A chain-type object to get a dot description for @param names The hash table of functions and names that we've seen @return Standard triple of [strings, first element, last element]
[ "Breakout", "function", "that", "simply", "calls", "the", "correct", "handler", "based", "on", "the", "type", "of", "the", "element", "supplied" ]
567ac39a1f4a74f85465a58fb6fd96d64b1b765f
https://github.com/gmalysa/flux-link/blob/567ac39a1f4a74f85465a58fb6fd96d64b1b765f/lib/gen-dot.js#L73-L90
55,831
gmalysa/flux-link
lib/gen-dot.js
handle_branch
function handle_branch(elem, names) { var cond = _dot_inner(elem.cond.fn, false, names); var if_true = _dot_inner(elem.if_true.fn, false, names); var if_false = _dot_inner(elem.if_false.fn, false, names); var terminator = hash_name_get({name : 'branch_end'}, names); var builder = []; Array.prototype.push.apply(builder, cond[0]); Array.prototype.push.apply(builder, if_true[0]); Array.prototype.push.apply(builder, if_false[0]); builder.push(cond[2]+' [shape=Mdiamond];'); builder.push(cond[2]+' -> '+if_true[1]+' [label = true];'); builder.push(cond[2]+' -> '+if_false[1]+' [label = false];'); builder.push(if_true[2]+' -> '+terminator+';'); builder.push(if_false[2]+' -> '+terminator+';'); builder.push(terminator+' [shape=octagon];'); return [builder, cond[1], terminator]; }
javascript
function handle_branch(elem, names) { var cond = _dot_inner(elem.cond.fn, false, names); var if_true = _dot_inner(elem.if_true.fn, false, names); var if_false = _dot_inner(elem.if_false.fn, false, names); var terminator = hash_name_get({name : 'branch_end'}, names); var builder = []; Array.prototype.push.apply(builder, cond[0]); Array.prototype.push.apply(builder, if_true[0]); Array.prototype.push.apply(builder, if_false[0]); builder.push(cond[2]+' [shape=Mdiamond];'); builder.push(cond[2]+' -> '+if_true[1]+' [label = true];'); builder.push(cond[2]+' -> '+if_false[1]+' [label = false];'); builder.push(if_true[2]+' -> '+terminator+';'); builder.push(if_false[2]+' -> '+terminator+';'); builder.push(terminator+' [shape=octagon];'); return [builder, cond[1], terminator]; }
[ "function", "handle_branch", "(", "elem", ",", "names", ")", "{", "var", "cond", "=", "_dot_inner", "(", "elem", ".", "cond", ".", "fn", ",", "false", ",", "names", ")", ";", "var", "if_true", "=", "_dot_inner", "(", "elem", ".", "if_true", ".", "fn", ",", "false", ",", "names", ")", ";", "var", "if_false", "=", "_dot_inner", "(", "elem", ".", "if_false", ".", "fn", ",", "false", ",", "names", ")", ";", "var", "terminator", "=", "hash_name_get", "(", "{", "name", ":", "'branch_end'", "}", ",", "names", ")", ";", "var", "builder", "=", "[", "]", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "cond", "[", "0", "]", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "if_true", "[", "0", "]", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "if_false", "[", "0", "]", ")", ";", "builder", ".", "push", "(", "cond", "[", "2", "]", "+", "' [shape=Mdiamond];'", ")", ";", "builder", ".", "push", "(", "cond", "[", "2", "]", "+", "' -> '", "+", "if_true", "[", "1", "]", "+", "' [label = true];'", ")", ";", "builder", ".", "push", "(", "cond", "[", "2", "]", "+", "' -> '", "+", "if_false", "[", "1", "]", "+", "' [label = false];'", ")", ";", "builder", ".", "push", "(", "if_true", "[", "2", "]", "+", "' -> '", "+", "terminator", "+", "';'", ")", ";", "builder", ".", "push", "(", "if_false", "[", "2", "]", "+", "' -> '", "+", "terminator", "+", "';'", ")", ";", "builder", ".", "push", "(", "terminator", "+", "' [shape=octagon];'", ")", ";", "return", "[", "builder", ",", "cond", "[", "1", "]", ",", "terminator", "]", ";", "}" ]
Handle a branch-type chain, which includes fancy decision labels and formatting @param elem The branch element @param names The hash table of names we've seen @return Standard triple of [strings, first element, last element]
[ "Handle", "a", "branch", "-", "type", "chain", "which", "includes", "fancy", "decision", "labels", "and", "formatting" ]
567ac39a1f4a74f85465a58fb6fd96d64b1b765f
https://github.com/gmalysa/flux-link/blob/567ac39a1f4a74f85465a58fb6fd96d64b1b765f/lib/gen-dot.js#L99-L116
55,832
gmalysa/flux-link
lib/gen-dot.js
handle_parallel
function handle_parallel(elem, names) { var phead = hash_name_get({name : 'parallel_head'}, names); var ptail = hash_name_get({name : 'parallel_tail'}, names); var node; var builder = []; for (var i = 0; i < elem.fns.length; ++i) { node = _dot_inner(elem.fns[i].fn, false, names); Array.prototype.push.apply(builder, node[0]); builder.push(phead+' -> '+node[1]+';'); builder.push(node[2]+' -> '+ptail+';'); } builder.push(phead+' [shape=house];'); builder.push(ptail+' [shape=invhouse];'); return [builder, phead, ptail]; }
javascript
function handle_parallel(elem, names) { var phead = hash_name_get({name : 'parallel_head'}, names); var ptail = hash_name_get({name : 'parallel_tail'}, names); var node; var builder = []; for (var i = 0; i < elem.fns.length; ++i) { node = _dot_inner(elem.fns[i].fn, false, names); Array.prototype.push.apply(builder, node[0]); builder.push(phead+' -> '+node[1]+';'); builder.push(node[2]+' -> '+ptail+';'); } builder.push(phead+' [shape=house];'); builder.push(ptail+' [shape=invhouse];'); return [builder, phead, ptail]; }
[ "function", "handle_parallel", "(", "elem", ",", "names", ")", "{", "var", "phead", "=", "hash_name_get", "(", "{", "name", ":", "'parallel_head'", "}", ",", "names", ")", ";", "var", "ptail", "=", "hash_name_get", "(", "{", "name", ":", "'parallel_tail'", "}", ",", "names", ")", ";", "var", "node", ";", "var", "builder", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elem", ".", "fns", ".", "length", ";", "++", "i", ")", "{", "node", "=", "_dot_inner", "(", "elem", ".", "fns", "[", "i", "]", ".", "fn", ",", "false", ",", "names", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "node", "[", "0", "]", ")", ";", "builder", ".", "push", "(", "phead", "+", "' -> '", "+", "node", "[", "1", "]", "+", "';'", ")", ";", "builder", ".", "push", "(", "node", "[", "2", "]", "+", "' -> '", "+", "ptail", "+", "';'", ")", ";", "}", "builder", ".", "push", "(", "phead", "+", "' [shape=house];'", ")", ";", "builder", ".", "push", "(", "ptail", "+", "' [shape=invhouse];'", ")", ";", "return", "[", "builder", ",", "phead", ",", "ptail", "]", ";", "}" ]
Handle a parallel chain, which inserts head and footer nodes around the functions in the middle @param elem The parallel chain to describe in DOT @param names The hash table of functions and their names @return Standard triple of [strings, first element, last element]
[ "Handle", "a", "parallel", "chain", "which", "inserts", "head", "and", "footer", "nodes", "around", "the", "functions", "in", "the", "middle" ]
567ac39a1f4a74f85465a58fb6fd96d64b1b765f
https://github.com/gmalysa/flux-link/blob/567ac39a1f4a74f85465a58fb6fd96d64b1b765f/lib/gen-dot.js#L125-L141
55,833
gmalysa/flux-link
lib/gen-dot.js
handle_loop
function handle_loop(elem, names) { var cond = _dot_inner(elem.cond.fn, false, names); var node1 = _dot_inner(elem.fns[0].fn, false, names); var builder = []; var node2 = node1; Array.prototype.push.apply(builder, cond[0]); Array.prototype.push.apply(builder, node1[0]); builder.push(cond[2]+' [shape=Mdiamond];'); builder.push(cond[2]+' -> '+node1[1]+' [label = true];'); for (var i = 1; i < elem.fns.length; ++i) { node2 = _dot_inner(elem.fns[i].fn, false, names); Array.prototype.push.apply(builder, node2[0]); builder.push(node1[2]+' -> '+node2[1]+';'); node1 = node2; } builder.push(node2[2]+' -> '+cond[1]+';'); return [builder, cond[1], cond[2]]; }
javascript
function handle_loop(elem, names) { var cond = _dot_inner(elem.cond.fn, false, names); var node1 = _dot_inner(elem.fns[0].fn, false, names); var builder = []; var node2 = node1; Array.prototype.push.apply(builder, cond[0]); Array.prototype.push.apply(builder, node1[0]); builder.push(cond[2]+' [shape=Mdiamond];'); builder.push(cond[2]+' -> '+node1[1]+' [label = true];'); for (var i = 1; i < elem.fns.length; ++i) { node2 = _dot_inner(elem.fns[i].fn, false, names); Array.prototype.push.apply(builder, node2[0]); builder.push(node1[2]+' -> '+node2[1]+';'); node1 = node2; } builder.push(node2[2]+' -> '+cond[1]+';'); return [builder, cond[1], cond[2]]; }
[ "function", "handle_loop", "(", "elem", ",", "names", ")", "{", "var", "cond", "=", "_dot_inner", "(", "elem", ".", "cond", ".", "fn", ",", "false", ",", "names", ")", ";", "var", "node1", "=", "_dot_inner", "(", "elem", ".", "fns", "[", "0", "]", ".", "fn", ",", "false", ",", "names", ")", ";", "var", "builder", "=", "[", "]", ";", "var", "node2", "=", "node1", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "cond", "[", "0", "]", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "node1", "[", "0", "]", ")", ";", "builder", ".", "push", "(", "cond", "[", "2", "]", "+", "' [shape=Mdiamond];'", ")", ";", "builder", ".", "push", "(", "cond", "[", "2", "]", "+", "' -> '", "+", "node1", "[", "1", "]", "+", "' [label = true];'", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "elem", ".", "fns", ".", "length", ";", "++", "i", ")", "{", "node2", "=", "_dot_inner", "(", "elem", ".", "fns", "[", "i", "]", ".", "fn", ",", "false", ",", "names", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "node2", "[", "0", "]", ")", ";", "builder", ".", "push", "(", "node1", "[", "2", "]", "+", "' -> '", "+", "node2", "[", "1", "]", "+", "';'", ")", ";", "node1", "=", "node2", ";", "}", "builder", ".", "push", "(", "node2", "[", "2", "]", "+", "' -> '", "+", "cond", "[", "1", "]", "+", "';'", ")", ";", "return", "[", "builder", ",", "cond", "[", "1", "]", ",", "cond", "[", "2", "]", "]", ";", "}" ]
Handle a loop chain, which is a lot like a serial chain but with a starter condition node on top @param elem The loop chain to describe in DOT @param names The hash table of functions and their names @return Standard triple of [strings, first element, last element]
[ "Handle", "a", "loop", "chain", "which", "is", "a", "lot", "like", "a", "serial", "chain", "but", "with", "a", "starter", "condition", "node", "on", "top" ]
567ac39a1f4a74f85465a58fb6fd96d64b1b765f
https://github.com/gmalysa/flux-link/blob/567ac39a1f4a74f85465a58fb6fd96d64b1b765f/lib/gen-dot.js#L150-L170
55,834
gmalysa/flux-link
lib/gen-dot.js
handle_chain
function handle_chain(elem, names) { // Make sure the chain does something if (elem.fns.length === 0) { return [[], hash_name_get({name : '__empty__'}), hash_name_get({name : '__empty__'})]; } var builder = []; var node1 = _dot_inner(elem.fns[0].fn, false, names); var first = node1; var node2; for (var i = 1; i < elem.fns.length; ++i) { Array.prototype.push.apply(builder, node1[0]); node2 = _dot_inner(elem.fns[i].fn, false, names); builder.push(node1[2]+' -> '+node2[1]+';'); node1 = node2; } Array.prototype.push.apply(builder, node1[0]); return [builder, first[1], node2[2]]; }
javascript
function handle_chain(elem, names) { // Make sure the chain does something if (elem.fns.length === 0) { return [[], hash_name_get({name : '__empty__'}), hash_name_get({name : '__empty__'})]; } var builder = []; var node1 = _dot_inner(elem.fns[0].fn, false, names); var first = node1; var node2; for (var i = 1; i < elem.fns.length; ++i) { Array.prototype.push.apply(builder, node1[0]); node2 = _dot_inner(elem.fns[i].fn, false, names); builder.push(node1[2]+' -> '+node2[1]+';'); node1 = node2; } Array.prototype.push.apply(builder, node1[0]); return [builder, first[1], node2[2]]; }
[ "function", "handle_chain", "(", "elem", ",", "names", ")", "{", "// Make sure the chain does something", "if", "(", "elem", ".", "fns", ".", "length", "===", "0", ")", "{", "return", "[", "[", "]", ",", "hash_name_get", "(", "{", "name", ":", "'__empty__'", "}", ")", ",", "hash_name_get", "(", "{", "name", ":", "'__empty__'", "}", ")", "]", ";", "}", "var", "builder", "=", "[", "]", ";", "var", "node1", "=", "_dot_inner", "(", "elem", ".", "fns", "[", "0", "]", ".", "fn", ",", "false", ",", "names", ")", ";", "var", "first", "=", "node1", ";", "var", "node2", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "elem", ".", "fns", ".", "length", ";", "++", "i", ")", "{", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "node1", "[", "0", "]", ")", ";", "node2", "=", "_dot_inner", "(", "elem", ".", "fns", "[", "i", "]", ".", "fn", ",", "false", ",", "names", ")", ";", "builder", ".", "push", "(", "node1", "[", "2", "]", "+", "' -> '", "+", "node2", "[", "1", "]", "+", "';'", ")", ";", "node1", "=", "node2", ";", "}", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "builder", ",", "node1", "[", "0", "]", ")", ";", "return", "[", "builder", ",", "first", "[", "1", "]", ",", "node2", "[", "2", "]", "]", ";", "}" ]
Handle a serial chain of function, which just pushes each node with an edge to the next node in the chain @param elem The chain to pull elements from @param names The hash table of names that we've seen @return Standard triple of [strings, first element, last element]
[ "Handle", "a", "serial", "chain", "of", "function", "which", "just", "pushes", "each", "node", "with", "an", "edge", "to", "the", "next", "node", "in", "the", "chain" ]
567ac39a1f4a74f85465a58fb6fd96d64b1b765f
https://github.com/gmalysa/flux-link/blob/567ac39a1f4a74f85465a58fb6fd96d64b1b765f/lib/gen-dot.js#L179-L199
55,835
gmalysa/flux-link
lib/gen-dot.js
hash_name_get
function hash_name_get(elem, names) { var fname; if (elem.fn !== undefined) fname = format_name(helpers.fname(elem, elem.fn.name)); else fname = format_name(elem.name); var list = names[fname]; // First unique instance of a function gets to use its proper name if (list === undefined) { names[fname] = [{fn : elem, name : fname, count : 0}]; return fname; } // Search the linear chain for our element for (var i = 0; i < list.length; ++i) { if (list[i].fn === elem) { list[i].count += 1; return list[i].name+'__'+list[i].count; } } // Not in the list yet, add it with a unique name index fname = fname+'_'+list.length; list.push({fn : elem, name : fname, count : 0}); return fname; }
javascript
function hash_name_get(elem, names) { var fname; if (elem.fn !== undefined) fname = format_name(helpers.fname(elem, elem.fn.name)); else fname = format_name(elem.name); var list = names[fname]; // First unique instance of a function gets to use its proper name if (list === undefined) { names[fname] = [{fn : elem, name : fname, count : 0}]; return fname; } // Search the linear chain for our element for (var i = 0; i < list.length; ++i) { if (list[i].fn === elem) { list[i].count += 1; return list[i].name+'__'+list[i].count; } } // Not in the list yet, add it with a unique name index fname = fname+'_'+list.length; list.push({fn : elem, name : fname, count : 0}); return fname; }
[ "function", "hash_name_get", "(", "elem", ",", "names", ")", "{", "var", "fname", ";", "if", "(", "elem", ".", "fn", "!==", "undefined", ")", "fname", "=", "format_name", "(", "helpers", ".", "fname", "(", "elem", ",", "elem", ".", "fn", ".", "name", ")", ")", ";", "else", "fname", "=", "format_name", "(", "elem", ".", "name", ")", ";", "var", "list", "=", "names", "[", "fname", "]", ";", "// First unique instance of a function gets to use its proper name", "if", "(", "list", "===", "undefined", ")", "{", "names", "[", "fname", "]", "=", "[", "{", "fn", ":", "elem", ",", "name", ":", "fname", ",", "count", ":", "0", "}", "]", ";", "return", "fname", ";", "}", "// Search the linear chain for our element", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "++", "i", ")", "{", "if", "(", "list", "[", "i", "]", ".", "fn", "===", "elem", ")", "{", "list", "[", "i", "]", ".", "count", "+=", "1", ";", "return", "list", "[", "i", "]", ".", "name", "+", "'__'", "+", "list", "[", "i", "]", ".", "count", ";", "}", "}", "// Not in the list yet, add it with a unique name index", "fname", "=", "fname", "+", "'_'", "+", "list", ".", "length", ";", "list", ".", "push", "(", "{", "fn", ":", "elem", ",", "name", ":", "fname", ",", "count", ":", "0", "}", ")", ";", "return", "fname", ";", "}" ]
Retrieve the proper name to use in the graph, for a given element. If it doesn't exist in the hash table given, then it is added, and its allocated name is returned @param elem The element (chain or function) to look up in the hash table @param names The hash table to use to resolve and store names @return Properly formatted name for the given element
[ "Retrieve", "the", "proper", "name", "to", "use", "in", "the", "graph", "for", "a", "given", "element", ".", "If", "it", "doesn", "t", "exist", "in", "the", "hash", "table", "given", "then", "it", "is", "added", "and", "its", "allocated", "name", "is", "returned" ]
567ac39a1f4a74f85465a58fb6fd96d64b1b765f
https://github.com/gmalysa/flux-link/blob/567ac39a1f4a74f85465a58fb6fd96d64b1b765f/lib/gen-dot.js#L208-L234
55,836
mwri/polylock
lib/polylock.js
polylock
function polylock (params) { if (params === undefined) params = {}; this.queue = new polylock_ll(); this.ex_locks = {}; this.ex_reserved = {}; this.sh_locks = {}; this.op_num = 1; this.drain_for_writes = params.write_priority ? true : false; }
javascript
function polylock (params) { if (params === undefined) params = {}; this.queue = new polylock_ll(); this.ex_locks = {}; this.ex_reserved = {}; this.sh_locks = {}; this.op_num = 1; this.drain_for_writes = params.write_priority ? true : false; }
[ "function", "polylock", "(", "params", ")", "{", "if", "(", "params", "===", "undefined", ")", "params", "=", "{", "}", ";", "this", ".", "queue", "=", "new", "polylock_ll", "(", ")", ";", "this", ".", "ex_locks", "=", "{", "}", ";", "this", ".", "ex_reserved", "=", "{", "}", ";", "this", ".", "sh_locks", "=", "{", "}", ";", "this", ".", "op_num", "=", "1", ";", "this", ".", "drain_for_writes", "=", "params", ".", "write_priority", "?", "true", ":", "false", ";", "}" ]
Construct a 'polylock' resource manager. Optionally an object parameter may be passed with parameters. The only key recognised is 'write_priority', which if set to true, causes write locks to be prioritised over read locks.
[ "Construct", "a", "polylock", "resource", "manager", "." ]
09167924a38aad1a516de07d2a049900f88b89db
https://github.com/mwri/polylock/blob/09167924a38aad1a516de07d2a049900f88b89db/lib/polylock.js#L23-L36
55,837
adiwidjaja/frontend-pagebuilder
js/tinymce/plugins/link/plugin.js
function (editor, message, callback) { var rng = editor.selection.getRng(); Delay.setEditorTimeout(editor, function () { editor.windowManager.confirm(message, function (state) { editor.selection.setRng(rng); callback(state); }); }); }
javascript
function (editor, message, callback) { var rng = editor.selection.getRng(); Delay.setEditorTimeout(editor, function () { editor.windowManager.confirm(message, function (state) { editor.selection.setRng(rng); callback(state); }); }); }
[ "function", "(", "editor", ",", "message", ",", "callback", ")", "{", "var", "rng", "=", "editor", ".", "selection", ".", "getRng", "(", ")", ";", "Delay", ".", "setEditorTimeout", "(", "editor", ",", "function", "(", ")", "{", "editor", ".", "windowManager", ".", "confirm", "(", "message", ",", "function", "(", "state", ")", "{", "editor", ".", "selection", ".", "setRng", "(", "rng", ")", ";", "callback", "(", "state", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Delay confirm since onSubmit will move focus
[ "Delay", "confirm", "since", "onSubmit", "will", "move", "focus" ]
a08caa06cd9f919d575eb68f0d6b56fdedfb7d0f
https://github.com/adiwidjaja/frontend-pagebuilder/blob/a08caa06cd9f919d575eb68f0d6b56fdedfb7d0f/js/tinymce/plugins/link/plugin.js#L527-L536
55,838
cschuller/grunt-yakjs
grunt-yakjs.js
gruntYakTask
function gruntYakTask(grunt) { 'use strict'; /** * @type {!Array<string>} */ let filesToUpload = []; /** * @type {RequestSender} */ let requestSender; /** * Register task for grunt. */ grunt.registerMultiTask('yakjs', 'A grunt task to update the YAKjs via rest API.', function task() { /** * This tasks sends several http request asynchronous. * So let's get the done callback from the task runner. */ let done = this.async(); /** * @type {!TaskOptions} */ let options = this.options(new TaskOptions()); filesToUpload = []; this.files.forEach(file => { filesToUpload = filesToUpload.concat(file.src); }); let logger = { log: grunt.log.writeln, error: grunt.log.error }; uploadFiles(filesToUpload, options, logger) .then(() => { grunt.log.writeln(''); grunt.log.ok('All files uploaded.'); }) .then(() => { return clearModuleCache(options, logger); }) .then(() => { return startInstances(options, logger); }) .then(done) .catch((message, error) => { grunt.log.writeln(''); grunt.log.error(JSON.stringify(message, null, 4)); grunt.fatal('One or more files could not be uploaded.'); done(); }); }); }
javascript
function gruntYakTask(grunt) { 'use strict'; /** * @type {!Array<string>} */ let filesToUpload = []; /** * @type {RequestSender} */ let requestSender; /** * Register task for grunt. */ grunt.registerMultiTask('yakjs', 'A grunt task to update the YAKjs via rest API.', function task() { /** * This tasks sends several http request asynchronous. * So let's get the done callback from the task runner. */ let done = this.async(); /** * @type {!TaskOptions} */ let options = this.options(new TaskOptions()); filesToUpload = []; this.files.forEach(file => { filesToUpload = filesToUpload.concat(file.src); }); let logger = { log: grunt.log.writeln, error: grunt.log.error }; uploadFiles(filesToUpload, options, logger) .then(() => { grunt.log.writeln(''); grunt.log.ok('All files uploaded.'); }) .then(() => { return clearModuleCache(options, logger); }) .then(() => { return startInstances(options, logger); }) .then(done) .catch((message, error) => { grunt.log.writeln(''); grunt.log.error(JSON.stringify(message, null, 4)); grunt.fatal('One or more files could not be uploaded.'); done(); }); }); }
[ "function", "gruntYakTask", "(", "grunt", ")", "{", "'use strict'", ";", "/**\n * @type {!Array<string>}\n */", "let", "filesToUpload", "=", "[", "]", ";", "/**\n * @type {RequestSender}\n */", "let", "requestSender", ";", "/**\n * Register task for grunt.\n */", "grunt", ".", "registerMultiTask", "(", "'yakjs'", ",", "'A grunt task to update the YAKjs via rest API.'", ",", "function", "task", "(", ")", "{", "/**\n * This tasks sends several http request asynchronous.\n * So let's get the done callback from the task runner.\n */", "let", "done", "=", "this", ".", "async", "(", ")", ";", "/**\n * @type {!TaskOptions}\n */", "let", "options", "=", "this", ".", "options", "(", "new", "TaskOptions", "(", ")", ")", ";", "filesToUpload", "=", "[", "]", ";", "this", ".", "files", ".", "forEach", "(", "file", "=>", "{", "filesToUpload", "=", "filesToUpload", ".", "concat", "(", "file", ".", "src", ")", ";", "}", ")", ";", "let", "logger", "=", "{", "log", ":", "grunt", ".", "log", ".", "writeln", ",", "error", ":", "grunt", ".", "log", ".", "error", "}", ";", "uploadFiles", "(", "filesToUpload", ",", "options", ",", "logger", ")", ".", "then", "(", "(", ")", "=>", "{", "grunt", ".", "log", ".", "writeln", "(", "''", ")", ";", "grunt", ".", "log", ".", "ok", "(", "'All files uploaded.'", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "clearModuleCache", "(", "options", ",", "logger", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "startInstances", "(", "options", ",", "logger", ")", ";", "}", ")", ".", "then", "(", "done", ")", ".", "catch", "(", "(", "message", ",", "error", ")", "=>", "{", "grunt", ".", "log", ".", "writeln", "(", "''", ")", ";", "grunt", ".", "log", ".", "error", "(", "JSON", ".", "stringify", "(", "message", ",", "null", ",", "4", ")", ")", ";", "grunt", ".", "fatal", "(", "'One or more files could not be uploaded.'", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Registers tasks for grunt @param {?} grunt
[ "Registers", "tasks", "for", "grunt" ]
4e0c94220c1e8bb30a533ce204e70a57f41e1e43
https://github.com/cschuller/grunt-yakjs/blob/4e0c94220c1e8bb30a533ce204e70a57f41e1e43/grunt-yakjs.js#L12-L70
55,839
75lb/req-then
index.js
request
function request (reqOptions, data) { const t = require('typical') if (!reqOptions) return Promise.reject(Error('need a URL or request options object')) if (t.isString(reqOptions)) { const urlUtils = require('url') reqOptions = urlUtils.parse(reqOptions) } else { reqOptions = Object.assign({ headers: {} }, reqOptions) } let transport const protocol = reqOptions.protocol if (protocol === 'http:') { transport = require('http') } else if (protocol === 'https:') { transport = require('https') } else { return Promise.reject(Error('Protocol missing from request: ' + JSON.stringify(reqOptions, null, ' '))) } const defer = require('defer-promise') const deferred = defer() const req = transport.request(reqOptions, function (res) { const pick = require('lodash.pick') if (/text\/event-stream/.test(res.headers['content-type'])) { const util = require('util') res[util.inspect.custom] = function (depth, options) { return options.stylize('[ SSE event-stream ]', 'special') } deferred.resolve({ data: res, res: pick(res, [ 'headers', 'method', 'statusCode', 'statusMessage', 'url' ]), req: reqOptions }) } else { const streamReadAll = require('stream-read-all') streamReadAll(res).then(data => { /* statusCode will be zero if the request was disconnected, so don't resolve */ if (res.statusCode !== 0) { deferred.resolve({ data: data, res: pick(res, [ 'headers', 'method', 'statusCode', 'statusMessage', 'url' ]), req: reqOptions }) } }) } }) req.on('error', function reqOnError (err) { /* failed to connect */ err.name = 'request-fail' err.request = req deferred.reject(err) }) req.end(data) if (reqOptions.controller) { reqOptions.controller.abort = function () { req.abort() const err = new Error('Aborted') err.name = 'aborted' deferred.reject(err) } } return deferred.promise }
javascript
function request (reqOptions, data) { const t = require('typical') if (!reqOptions) return Promise.reject(Error('need a URL or request options object')) if (t.isString(reqOptions)) { const urlUtils = require('url') reqOptions = urlUtils.parse(reqOptions) } else { reqOptions = Object.assign({ headers: {} }, reqOptions) } let transport const protocol = reqOptions.protocol if (protocol === 'http:') { transport = require('http') } else if (protocol === 'https:') { transport = require('https') } else { return Promise.reject(Error('Protocol missing from request: ' + JSON.stringify(reqOptions, null, ' '))) } const defer = require('defer-promise') const deferred = defer() const req = transport.request(reqOptions, function (res) { const pick = require('lodash.pick') if (/text\/event-stream/.test(res.headers['content-type'])) { const util = require('util') res[util.inspect.custom] = function (depth, options) { return options.stylize('[ SSE event-stream ]', 'special') } deferred.resolve({ data: res, res: pick(res, [ 'headers', 'method', 'statusCode', 'statusMessage', 'url' ]), req: reqOptions }) } else { const streamReadAll = require('stream-read-all') streamReadAll(res).then(data => { /* statusCode will be zero if the request was disconnected, so don't resolve */ if (res.statusCode !== 0) { deferred.resolve({ data: data, res: pick(res, [ 'headers', 'method', 'statusCode', 'statusMessage', 'url' ]), req: reqOptions }) } }) } }) req.on('error', function reqOnError (err) { /* failed to connect */ err.name = 'request-fail' err.request = req deferred.reject(err) }) req.end(data) if (reqOptions.controller) { reqOptions.controller.abort = function () { req.abort() const err = new Error('Aborted') err.name = 'aborted' deferred.reject(err) } } return deferred.promise }
[ "function", "request", "(", "reqOptions", ",", "data", ")", "{", "const", "t", "=", "require", "(", "'typical'", ")", "if", "(", "!", "reqOptions", ")", "return", "Promise", ".", "reject", "(", "Error", "(", "'need a URL or request options object'", ")", ")", "if", "(", "t", ".", "isString", "(", "reqOptions", ")", ")", "{", "const", "urlUtils", "=", "require", "(", "'url'", ")", "reqOptions", "=", "urlUtils", ".", "parse", "(", "reqOptions", ")", "}", "else", "{", "reqOptions", "=", "Object", ".", "assign", "(", "{", "headers", ":", "{", "}", "}", ",", "reqOptions", ")", "}", "let", "transport", "const", "protocol", "=", "reqOptions", ".", "protocol", "if", "(", "protocol", "===", "'http:'", ")", "{", "transport", "=", "require", "(", "'http'", ")", "}", "else", "if", "(", "protocol", "===", "'https:'", ")", "{", "transport", "=", "require", "(", "'https'", ")", "}", "else", "{", "return", "Promise", ".", "reject", "(", "Error", "(", "'Protocol missing from request: '", "+", "JSON", ".", "stringify", "(", "reqOptions", ",", "null", ",", "' '", ")", ")", ")", "}", "const", "defer", "=", "require", "(", "'defer-promise'", ")", "const", "deferred", "=", "defer", "(", ")", "const", "req", "=", "transport", ".", "request", "(", "reqOptions", ",", "function", "(", "res", ")", "{", "const", "pick", "=", "require", "(", "'lodash.pick'", ")", "if", "(", "/", "text\\/event-stream", "/", ".", "test", "(", "res", ".", "headers", "[", "'content-type'", "]", ")", ")", "{", "const", "util", "=", "require", "(", "'util'", ")", "res", "[", "util", ".", "inspect", ".", "custom", "]", "=", "function", "(", "depth", ",", "options", ")", "{", "return", "options", ".", "stylize", "(", "'[ SSE event-stream ]'", ",", "'special'", ")", "}", "deferred", ".", "resolve", "(", "{", "data", ":", "res", ",", "res", ":", "pick", "(", "res", ",", "[", "'headers'", ",", "'method'", ",", "'statusCode'", ",", "'statusMessage'", ",", "'url'", "]", ")", ",", "req", ":", "reqOptions", "}", ")", "}", "else", "{", "const", "streamReadAll", "=", "require", "(", "'stream-read-all'", ")", "streamReadAll", "(", "res", ")", ".", "then", "(", "data", "=>", "{", "/* statusCode will be zero if the request was disconnected, so don't resolve */", "if", "(", "res", ".", "statusCode", "!==", "0", ")", "{", "deferred", ".", "resolve", "(", "{", "data", ":", "data", ",", "res", ":", "pick", "(", "res", ",", "[", "'headers'", ",", "'method'", ",", "'statusCode'", ",", "'statusMessage'", ",", "'url'", "]", ")", ",", "req", ":", "reqOptions", "}", ")", "}", "}", ")", "}", "}", ")", "req", ".", "on", "(", "'error'", ",", "function", "reqOnError", "(", "err", ")", "{", "/* failed to connect */", "err", ".", "name", "=", "'request-fail'", "err", ".", "request", "=", "req", "deferred", ".", "reject", "(", "err", ")", "}", ")", "req", ".", "end", "(", "data", ")", "if", "(", "reqOptions", ".", "controller", ")", "{", "reqOptions", ".", "controller", ".", "abort", "=", "function", "(", ")", "{", "req", ".", "abort", "(", ")", "const", "err", "=", "new", "Error", "(", "'Aborted'", ")", "err", ".", "name", "=", "'aborted'", "deferred", ".", "reject", "(", "err", ")", "}", "}", "return", "deferred", ".", "promise", "}" ]
Returns a promise for the response. @param {string|object} - Target url string or a standard node.js http request options object. @param [reqOptions.controller] {object} - If supplied, an `.abort()` method will be created on it which, if invoked, will cancel the request. Cancelling will cause the returned promise to reject with an `'aborted'` error. @param [data] {*} - Data to send with the request. @returns {external:Promise} @resolve {object} - `res` will be the node response object, `data` will be the data, `req` the original request. @reject {Error} - If aborted, the `name` property of the error will be `aborted`. @alias module:req-then
[ "Returns", "a", "promise", "for", "the", "response", "." ]
1d7997054d6634702b5046e4eaf9e8e703705367
https://github.com/75lb/req-then/blob/1d7997054d6634702b5046e4eaf9e8e703705367/index.js#L47-L115
55,840
patience-tema-baron/ember-createjs
vendor/createjs/cordova-audio-plugin.js
Loader
function Loader(loadItem) { this.AbstractLoader_constructor(loadItem, true, createjs.AbstractLoader.SOUND); /** * A Media object used to determine if src exists and to get duration * @property _media * @type {Media} * @protected */ this._media = null; /** * A time counter that triggers timeout if loading takes too long * @property _loadTime * @type {number} * @protected */ this._loadTime = 0; /** * The frequency to fire the loading timer until duration can be retrieved * @property _TIMER_FREQUENCY * @type {number} * @protected */ this._TIMER_FREQUENCY = 100; }
javascript
function Loader(loadItem) { this.AbstractLoader_constructor(loadItem, true, createjs.AbstractLoader.SOUND); /** * A Media object used to determine if src exists and to get duration * @property _media * @type {Media} * @protected */ this._media = null; /** * A time counter that triggers timeout if loading takes too long * @property _loadTime * @type {number} * @protected */ this._loadTime = 0; /** * The frequency to fire the loading timer until duration can be retrieved * @property _TIMER_FREQUENCY * @type {number} * @protected */ this._TIMER_FREQUENCY = 100; }
[ "function", "Loader", "(", "loadItem", ")", "{", "this", ".", "AbstractLoader_constructor", "(", "loadItem", ",", "true", ",", "createjs", ".", "AbstractLoader", ".", "SOUND", ")", ";", "/**\n\t\t * A Media object used to determine if src exists and to get duration\n\t\t * @property _media\n\t\t * @type {Media}\n\t\t * @protected\n\t\t */", "this", ".", "_media", "=", "null", ";", "/**\n\t\t * A time counter that triggers timeout if loading takes too long\n\t\t * @property _loadTime\n\t\t * @type {number}\n\t\t * @protected\n\t\t */", "this", ".", "_loadTime", "=", "0", ";", "/**\n\t\t * The frequency to fire the loading timer until duration can be retrieved\n\t\t * @property _TIMER_FREQUENCY\n\t\t * @type {number}\n\t\t * @protected\n\t\t */", "this", ".", "_TIMER_FREQUENCY", "=", "100", ";", "}" ]
Loader provides a mechanism to preload Cordova audio content via PreloadJS or internally. Instances are returned to the preloader, and the load method is called when the asset needs to be requested. Currently files are assumed to be local and no loading actually takes place. This class exists to more easily support the existing architecture. @class CordovaAudioLoader @param {String} loadItem The item to be loaded @extends XHRRequest @protected
[ "Loader", "provides", "a", "mechanism", "to", "preload", "Cordova", "audio", "content", "via", "PreloadJS", "or", "internally", ".", "Instances", "are", "returned", "to", "the", "preloader", "and", "the", "load", "method", "is", "called", "when", "the", "asset", "needs", "to", "be", "requested", ".", "Currently", "files", "are", "assumed", "to", "be", "local", "and", "no", "loading", "actually", "takes", "place", ".", "This", "class", "exists", "to", "more", "easily", "support", "the", "existing", "architecture", "." ]
4647611b4b7540a736ae63a641f1febbbd36145d
https://github.com/patience-tema-baron/ember-createjs/blob/4647611b4b7540a736ae63a641f1febbbd36145d/vendor/createjs/cordova-audio-plugin.js#L50-L76
55,841
rranauro/boxspringjs
utils.js
function (f) { var separator , temp = []; [ '/', '-', ' '].forEach(function(sep) { if (temp.length < 2) { separator = sep; temp = f.split(separator); } }); return separator; }
javascript
function (f) { var separator , temp = []; [ '/', '-', ' '].forEach(function(sep) { if (temp.length < 2) { separator = sep; temp = f.split(separator); } }); return separator; }
[ "function", "(", "f", ")", "{", "var", "separator", ",", "temp", "=", "[", "]", ";", "[", "'/'", ",", "'-'", ",", "' '", "]", ".", "forEach", "(", "function", "(", "sep", ")", "{", "if", "(", "temp", ".", "length", "<", "2", ")", "{", "separator", "=", "sep", ";", "temp", "=", "f", ".", "split", "(", "separator", ")", ";", "}", "}", ")", ";", "return", "separator", ";", "}" ]
get the separator for the date format
[ "get", "the", "separator", "for", "the", "date", "format" ]
43fd13ae45ba5b16ba9144084b96748a1cd8c0ea
https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/utils.js#L368-L378
55,842
ryedog/stallion
src/stallion.js
function(username, password) { var restler_defaults = { baseURL: config.baseUrl }; var RestlerService = restler.service(default_init, restler_defaults, api); return new RestlerService(username, password); }
javascript
function(username, password) { var restler_defaults = { baseURL: config.baseUrl }; var RestlerService = restler.service(default_init, restler_defaults, api); return new RestlerService(username, password); }
[ "function", "(", "username", ",", "password", ")", "{", "var", "restler_defaults", "=", "{", "baseURL", ":", "config", ".", "baseUrl", "}", ";", "var", "RestlerService", "=", "restler", ".", "service", "(", "default_init", ",", "restler_defaults", ",", "api", ")", ";", "return", "new", "RestlerService", "(", "username", ",", "password", ")", ";", "}" ]
Can't use multilple instances of Reslter services Because each instance shares the defaults and the only way to set the username & password is to use the defaults each instance will actually be the same So instead when we create another instance of a Stallion service we'll actually create a seperate instance of a Restler service
[ "Can", "t", "use", "multilple", "instances", "of", "Reslter", "services", "Because", "each", "instance", "shares", "the", "defaults", "and", "the", "only", "way", "to", "set", "the", "username", "&", "password", "is", "to", "use", "the", "defaults", "each", "instance", "will", "actually", "be", "the", "same", "So", "instead", "when", "we", "create", "another", "instance", "of", "a", "Stallion", "service", "we", "ll", "actually", "create", "a", "seperate", "instance", "of", "a", "Restler", "service" ]
08d200aeea5b0ed2fbfd7d4b757ab9a7ba85c30a
https://github.com/ryedog/stallion/blob/08d200aeea5b0ed2fbfd7d4b757ab9a7ba85c30a/src/stallion.js#L50-L55
55,843
ryedog/stallion
src/stallion.js
get_id
function get_id(val) { if ( typeof val === 'string' || typeof val === 'number' ) return val; if ( typeof val === 'object' && val.id ) return val.id; return false; }
javascript
function get_id(val) { if ( typeof val === 'string' || typeof val === 'number' ) return val; if ( typeof val === 'object' && val.id ) return val.id; return false; }
[ "function", "get_id", "(", "val", ")", "{", "if", "(", "typeof", "val", "===", "'string'", "||", "typeof", "val", "===", "'number'", ")", "return", "val", ";", "if", "(", "typeof", "val", "===", "'object'", "&&", "val", ".", "id", ")", "return", "val", ".", "id", ";", "return", "false", ";", "}" ]
Whether the value can be used in the REST endpoint @param {Mixed} val @return {Boolean} TRUE if value can be inserted into the endpoint
[ "Whether", "the", "value", "can", "be", "used", "in", "the", "REST", "endpoint" ]
08d200aeea5b0ed2fbfd7d4b757ab9a7ba85c30a
https://github.com/ryedog/stallion/blob/08d200aeea5b0ed2fbfd7d4b757ab9a7ba85c30a/src/stallion.js#L246-L254
55,844
ryedog/stallion
src/stallion.js
default_init
function default_init(user, password) { this.defaults.username = user; this.defaults.password = password; this.defaults.headers = { Accept: 'application/json' }; this.defaults.headers['Content-Type'] = 'application/json'; }
javascript
function default_init(user, password) { this.defaults.username = user; this.defaults.password = password; this.defaults.headers = { Accept: 'application/json' }; this.defaults.headers['Content-Type'] = 'application/json'; }
[ "function", "default_init", "(", "user", ",", "password", ")", "{", "this", ".", "defaults", ".", "username", "=", "user", ";", "this", ".", "defaults", ".", "password", "=", "password", ";", "this", ".", "defaults", ".", "headers", "=", "{", "Accept", ":", "'application/json'", "}", ";", "this", ".", "defaults", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", ";", "}" ]
Default Restler service function @param {String} user @param {String} password
[ "Default", "Restler", "service", "function" ]
08d200aeea5b0ed2fbfd7d4b757ab9a7ba85c30a
https://github.com/ryedog/stallion/blob/08d200aeea5b0ed2fbfd7d4b757ab9a7ba85c30a/src/stallion.js#L261-L269
55,845
gmalysa/flux-link
lib/environment.js
LocalEnvironment
function LocalEnvironment(env, id) { Environment.call(this, {}, env._fm.$log); this._env = env; this._thread_id = id; }
javascript
function LocalEnvironment(env, id) { Environment.call(this, {}, env._fm.$log); this._env = env; this._thread_id = id; }
[ "function", "LocalEnvironment", "(", "env", ",", "id", ")", "{", "Environment", ".", "call", "(", "this", ",", "{", "}", ",", "env", ".", "_fm", ".", "$log", ")", ";", "this", ".", "_env", "=", "env", ";", "this", ".", "_thread_id", "=", "id", ";", "}" ]
The LocalEnvironment class, which is the same as an environment class, except that it is unique to each "thread" in parallel execution chains, similar to thread-local storage. It has a pointer to the shared state, so that it may still be accessed. @param env The environment variable to use as parent @param id The thread id, this is used to track when all threads complete
[ "The", "LocalEnvironment", "class", "which", "is", "the", "same", "as", "an", "environment", "class", "except", "that", "it", "is", "unique", "to", "each", "thread", "in", "parallel", "execution", "chains", "similar", "to", "thread", "-", "local", "storage", ".", "It", "has", "a", "pointer", "to", "the", "shared", "state", "so", "that", "it", "may", "still", "be", "accessed", "." ]
567ac39a1f4a74f85465a58fb6fd96d64b1b765f
https://github.com/gmalysa/flux-link/blob/567ac39a1f4a74f85465a58fb6fd96d64b1b765f/lib/environment.js#L192-L196
55,846
MiguelCastillo/spromise
src/promise.js
StateManager
function StateManager(options) { // Initial state is pending this.state = states.pending; // If a state is passed in, then we go ahead and initialize the state manager with it if (options && options.state) { this.transition(options.state, options.value, options.context); } }
javascript
function StateManager(options) { // Initial state is pending this.state = states.pending; // If a state is passed in, then we go ahead and initialize the state manager with it if (options && options.state) { this.transition(options.state, options.value, options.context); } }
[ "function", "StateManager", "(", "options", ")", "{", "// Initial state is pending", "this", ".", "state", "=", "states", ".", "pending", ";", "// If a state is passed in, then we go ahead and initialize the state manager with it", "if", "(", "options", "&&", "options", ".", "state", ")", "{", "this", ".", "transition", "(", "options", ".", "state", ",", "options", ".", "value", ",", "options", ".", "context", ")", ";", "}", "}" ]
Provides a set of interfaces to manage callback queues and the resolution state of the promises.
[ "Provides", "a", "set", "of", "interfaces", "to", "manage", "callback", "queues", "and", "the", "resolution", "state", "of", "the", "promises", "." ]
faef0a81e88a871095393980fccdd7980e7c3f89
https://github.com/MiguelCastillo/spromise/blob/faef0a81e88a871095393980fccdd7980e7c3f89/src/promise.js#L115-L123
55,847
limi58/ease-animate
src/ease-animate-dom.js
startDomAnimate
function startDomAnimate(selector, animationProps, interval, onDone){ let numberIndex = 0 const numbersLength = animationProps[0].numbers.length this.isDomRunning = true const tick = setInterval(() => { animationProps.forEach(prop => { setStyle(selector, prop.attr, prop.numbers[numberIndex], prop.unit) }) numberIndex ++ if(numberIndex >= numbersLength) { clearInterval(tick) this.isDomRunning = false if (onDone) onDone() } }, interval) }
javascript
function startDomAnimate(selector, animationProps, interval, onDone){ let numberIndex = 0 const numbersLength = animationProps[0].numbers.length this.isDomRunning = true const tick = setInterval(() => { animationProps.forEach(prop => { setStyle(selector, prop.attr, prop.numbers[numberIndex], prop.unit) }) numberIndex ++ if(numberIndex >= numbersLength) { clearInterval(tick) this.isDomRunning = false if (onDone) onDone() } }, interval) }
[ "function", "startDomAnimate", "(", "selector", ",", "animationProps", ",", "interval", ",", "onDone", ")", "{", "let", "numberIndex", "=", "0", "const", "numbersLength", "=", "animationProps", "[", "0", "]", ".", "numbers", ".", "length", "this", ".", "isDomRunning", "=", "true", "const", "tick", "=", "setInterval", "(", "(", ")", "=>", "{", "animationProps", ".", "forEach", "(", "prop", "=>", "{", "setStyle", "(", "selector", ",", "prop", ".", "attr", ",", "prop", ".", "numbers", "[", "numberIndex", "]", ",", "prop", ".", "unit", ")", "}", ")", "numberIndex", "++", "if", "(", "numberIndex", ">=", "numbersLength", ")", "{", "clearInterval", "(", "tick", ")", "this", ".", "isDomRunning", "=", "false", "if", "(", "onDone", ")", "onDone", "(", ")", "}", "}", ",", "interval", ")", "}" ]
let dom animate
[ "let", "dom", "animate" ]
5072ef7798749228febcf1b778cca17461592982
https://github.com/limi58/ease-animate/blob/5072ef7798749228febcf1b778cca17461592982/src/ease-animate-dom.js#L15-L30
55,848
powmedia/pow-mongoose-plugins
lib/authenticator.js
encryptPassword
function encryptPassword(password, callback) { bcrypt.gen_salt(workFactor, function(err, salt) { if (err) callback(err); bcrypt.encrypt(password, salt, function(err, hashedPassword) { if (err) callback(err); callback(null, hashedPassword); }); }); }
javascript
function encryptPassword(password, callback) { bcrypt.gen_salt(workFactor, function(err, salt) { if (err) callback(err); bcrypt.encrypt(password, salt, function(err, hashedPassword) { if (err) callback(err); callback(null, hashedPassword); }); }); }
[ "function", "encryptPassword", "(", "password", ",", "callback", ")", "{", "bcrypt", ".", "gen_salt", "(", "workFactor", ",", "function", "(", "err", ",", "salt", ")", "{", "if", "(", "err", ")", "callback", "(", "err", ")", ";", "bcrypt", ".", "encrypt", "(", "password", ",", "salt", ",", "function", "(", "err", ",", "hashedPassword", ")", "{", "if", "(", "err", ")", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "hashedPassword", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Encrypts a password @param {String} Password @param {Function} Callback (receives: err, hashedPassword)
[ "Encrypts", "a", "password" ]
4dff978adb012136eb773741ae1e9e2efb0224ca
https://github.com/powmedia/pow-mongoose-plugins/blob/4dff978adb012136eb773741ae1e9e2efb0224ca/lib/authenticator.js#L49-L59
55,849
dominictarr/npmd-tree
index.js
ls
function ls (dir, cb) { if(!cb) cb = dir, dir = null dir = dir || process.cwd() pull( pfs.ancestors(dir), pfs.resolve('node_modules'), pfs.star(), pull.filter(Boolean), paramap(maybe(readPackage)), filter(), pull.unique('name'), pull.reduce(function (obj, val) { if(!obj[val.name]) obj[val.name] = val return obj }, {}, function (err, obj) { cb(err, obj) }) ) }
javascript
function ls (dir, cb) { if(!cb) cb = dir, dir = null dir = dir || process.cwd() pull( pfs.ancestors(dir), pfs.resolve('node_modules'), pfs.star(), pull.filter(Boolean), paramap(maybe(readPackage)), filter(), pull.unique('name'), pull.reduce(function (obj, val) { if(!obj[val.name]) obj[val.name] = val return obj }, {}, function (err, obj) { cb(err, obj) }) ) }
[ "function", "ls", "(", "dir", ",", "cb", ")", "{", "if", "(", "!", "cb", ")", "cb", "=", "dir", ",", "dir", "=", "null", "dir", "=", "dir", "||", "process", ".", "cwd", "(", ")", "pull", "(", "pfs", ".", "ancestors", "(", "dir", ")", ",", "pfs", ".", "resolve", "(", "'node_modules'", ")", ",", "pfs", ".", "star", "(", ")", ",", "pull", ".", "filter", "(", "Boolean", ")", ",", "paramap", "(", "maybe", "(", "readPackage", ")", ")", ",", "filter", "(", ")", ",", "pull", ".", "unique", "(", "'name'", ")", ",", "pull", ".", "reduce", "(", "function", "(", "obj", ",", "val", ")", "{", "if", "(", "!", "obj", "[", "val", ".", "name", "]", ")", "obj", "[", "val", ".", "name", "]", "=", "val", "return", "obj", "}", ",", "{", "}", ",", "function", "(", "err", ",", "obj", ")", "{", "cb", "(", "err", ",", "obj", ")", "}", ")", ")", "}" ]
retrive the current files,
[ "retrive", "the", "current", "files" ]
97d56a4414520266b736d7d6442a05b82cb43ebb
https://github.com/dominictarr/npmd-tree/blob/97d56a4414520266b736d7d6442a05b82cb43ebb/index.js#L89-L110
55,850
dominictarr/npmd-tree
index.js
tree
function tree (dir, opts, cb) { var i = 0 findPackage(dir, function (err, pkg) { pull( pull.depthFirst(pkg, function (pkg) { pkg.tree = {} return pull( pfs.readdir(path.resolve(pkg.path, 'node_modules')), paramap(maybe(readPackage)), pull.filter(function (_pkg) { if(!_pkg) return _pkg.parent = pkg pkg.tree[_pkg.name] = _pkg return pkg }) ) }), opts.post ? paramap(function (data, cb) { //run a post install-style hook. opts.post(data, cb) }) : pull.through(), pull.drain(null, function (err) { cb(err === true ? null : err, clean(pkg)) }) ) }) }
javascript
function tree (dir, opts, cb) { var i = 0 findPackage(dir, function (err, pkg) { pull( pull.depthFirst(pkg, function (pkg) { pkg.tree = {} return pull( pfs.readdir(path.resolve(pkg.path, 'node_modules')), paramap(maybe(readPackage)), pull.filter(function (_pkg) { if(!_pkg) return _pkg.parent = pkg pkg.tree[_pkg.name] = _pkg return pkg }) ) }), opts.post ? paramap(function (data, cb) { //run a post install-style hook. opts.post(data, cb) }) : pull.through(), pull.drain(null, function (err) { cb(err === true ? null : err, clean(pkg)) }) ) }) }
[ "function", "tree", "(", "dir", ",", "opts", ",", "cb", ")", "{", "var", "i", "=", "0", "findPackage", "(", "dir", ",", "function", "(", "err", ",", "pkg", ")", "{", "pull", "(", "pull", ".", "depthFirst", "(", "pkg", ",", "function", "(", "pkg", ")", "{", "pkg", ".", "tree", "=", "{", "}", "return", "pull", "(", "pfs", ".", "readdir", "(", "path", ".", "resolve", "(", "pkg", ".", "path", ",", "'node_modules'", ")", ")", ",", "paramap", "(", "maybe", "(", "readPackage", ")", ")", ",", "pull", ".", "filter", "(", "function", "(", "_pkg", ")", "{", "if", "(", "!", "_pkg", ")", "return", "_pkg", ".", "parent", "=", "pkg", "pkg", ".", "tree", "[", "_pkg", ".", "name", "]", "=", "_pkg", "return", "pkg", "}", ")", ")", "}", ")", ",", "opts", ".", "post", "?", "paramap", "(", "function", "(", "data", ",", "cb", ")", "{", "//run a post install-style hook.", "opts", ".", "post", "(", "data", ",", "cb", ")", "}", ")", ":", "pull", ".", "through", "(", ")", ",", "pull", ".", "drain", "(", "null", ",", "function", "(", "err", ")", "{", "cb", "(", "err", "===", "true", "?", "null", ":", "err", ",", "clean", "(", "pkg", ")", ")", "}", ")", ")", "}", ")", "}" ]
creates the same datastructure as resolve, selecting all dependencies...
[ "creates", "the", "same", "datastructure", "as", "resolve", "selecting", "all", "dependencies", "..." ]
97d56a4414520266b736d7d6442a05b82cb43ebb
https://github.com/dominictarr/npmd-tree/blob/97d56a4414520266b736d7d6442a05b82cb43ebb/index.js#L115-L142
55,851
JBZoo/JS-Utils
src/helper.js
function () { var args = arguments, argc = arguments.length; if (argc === 1) { if (args[0] === undefined || args[0] === null) { return undefined; } return args[0]; } else if (argc === 2) { if (args[0] === undefined || args[0] === null) { return args[1]; } return args[0]; } else { if (args[0][args[1]] === undefined || args[0][args[1]] === null) { return args[2]; } return args[0][args[1]]; } }
javascript
function () { var args = arguments, argc = arguments.length; if (argc === 1) { if (args[0] === undefined || args[0] === null) { return undefined; } return args[0]; } else if (argc === 2) { if (args[0] === undefined || args[0] === null) { return args[1]; } return args[0]; } else { if (args[0][args[1]] === undefined || args[0][args[1]] === null) { return args[2]; } return args[0][args[1]]; } }
[ "function", "(", ")", "{", "var", "args", "=", "arguments", ",", "argc", "=", "arguments", ".", "length", ";", "if", "(", "argc", "===", "1", ")", "{", "if", "(", "args", "[", "0", "]", "===", "undefined", "||", "args", "[", "0", "]", "===", "null", ")", "{", "return", "undefined", ";", "}", "return", "args", "[", "0", "]", ";", "}", "else", "if", "(", "argc", "===", "2", ")", "{", "if", "(", "args", "[", "0", "]", "===", "undefined", "||", "args", "[", "0", "]", "===", "null", ")", "{", "return", "args", "[", "1", "]", ";", "}", "return", "args", "[", "0", "]", ";", "}", "else", "{", "if", "(", "args", "[", "0", "]", "[", "args", "[", "1", "]", "]", "===", "undefined", "||", "args", "[", "0", "]", "[", "args", "[", "1", "]", "]", "===", "null", ")", "{", "return", "args", "[", "2", "]", ";", "}", "return", "args", "[", "0", "]", "[", "args", "[", "1", "]", "]", ";", "}", "}" ]
Check and get variable @returns {*}
[ "Check", "and", "get", "variable" ]
7b188893c4e2da81279e00e07e65b930685d05d3
https://github.com/JBZoo/JS-Utils/blob/7b188893c4e2da81279e00e07e65b930685d05d3/src/helper.js#L150-L178
55,852
JBZoo/JS-Utils
src/helper.js
function (variable, isRecursive) { var property, result = 0; isRecursive = (typeof isRecursive !== "undefined" && isRecursive) ? true : false; if (variable === false || variable === null || typeof variable === "undefined" ) { return 0; } else if (variable.constructor !== Array && variable.constructor !== Object) { return 1; } for (property in variable) { if (variable.hasOwnProperty(property) && !$this.isFunc(variable[property])) { result++; if (isRecursive && variable[property] && ( variable[property].constructor === Array || variable[property].constructor === Object ) ) { result += this.count(variable[property], true); } } } return result; }
javascript
function (variable, isRecursive) { var property, result = 0; isRecursive = (typeof isRecursive !== "undefined" && isRecursive) ? true : false; if (variable === false || variable === null || typeof variable === "undefined" ) { return 0; } else if (variable.constructor !== Array && variable.constructor !== Object) { return 1; } for (property in variable) { if (variable.hasOwnProperty(property) && !$this.isFunc(variable[property])) { result++; if (isRecursive && variable[property] && ( variable[property].constructor === Array || variable[property].constructor === Object ) ) { result += this.count(variable[property], true); } } } return result; }
[ "function", "(", "variable", ",", "isRecursive", ")", "{", "var", "property", ",", "result", "=", "0", ";", "isRecursive", "=", "(", "typeof", "isRecursive", "!==", "\"undefined\"", "&&", "isRecursive", ")", "?", "true", ":", "false", ";", "if", "(", "variable", "===", "false", "||", "variable", "===", "null", "||", "typeof", "variable", "===", "\"undefined\"", ")", "{", "return", "0", ";", "}", "else", "if", "(", "variable", ".", "constructor", "!==", "Array", "&&", "variable", ".", "constructor", "!==", "Object", ")", "{", "return", "1", ";", "}", "for", "(", "property", "in", "variable", ")", "{", "if", "(", "variable", ".", "hasOwnProperty", "(", "property", ")", "&&", "!", "$this", ".", "isFunc", "(", "variable", "[", "property", "]", ")", ")", "{", "result", "++", ";", "if", "(", "isRecursive", "&&", "variable", "[", "property", "]", "&&", "(", "variable", "[", "property", "]", ".", "constructor", "===", "Array", "||", "variable", "[", "property", "]", ".", "constructor", "===", "Object", ")", ")", "{", "result", "+=", "this", ".", "count", "(", "variable", "[", "property", "]", ",", "true", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Count all elements in an array, or something in an object @link http://php.net/manual/en/function.count.php @link http://phpjs.org/functions/count/ @param variable @param isRecursive bool @returns {number}
[ "Count", "all", "elements", "in", "an", "array", "or", "something", "in", "an", "object" ]
7b188893c4e2da81279e00e07e65b930685d05d3
https://github.com/JBZoo/JS-Utils/blob/7b188893c4e2da81279e00e07e65b930685d05d3/src/helper.js#L228-L261
55,853
JBZoo/JS-Utils
src/helper.js
function (needle, haystack, strict) { var found = false; strict = !!strict; $this.each(haystack, function (key) { /* jshint -W116 */ if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) { found = true; return false; } /* jshint +W116 */ }); return found; }
javascript
function (needle, haystack, strict) { var found = false; strict = !!strict; $this.each(haystack, function (key) { /* jshint -W116 */ if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) { found = true; return false; } /* jshint +W116 */ }); return found; }
[ "function", "(", "needle", ",", "haystack", ",", "strict", ")", "{", "var", "found", "=", "false", ";", "strict", "=", "!", "!", "strict", ";", "$this", ".", "each", "(", "haystack", ",", "function", "(", "key", ")", "{", "/* jshint -W116 */", "if", "(", "(", "strict", "&&", "haystack", "[", "key", "]", "===", "needle", ")", "||", "(", "!", "strict", "&&", "haystack", "[", "key", "]", "==", "needle", ")", ")", "{", "found", "=", "true", ";", "return", "false", ";", "}", "/* jshint +W116 */", "}", ")", ";", "return", "found", ";", "}" ]
Finds whether a variable is a number or a numeric string @link http://php.net/manual/ru/function.in-array.php @link http://phpjs.org/functions/in_array/ @param needle @param haystack @param strict @return {Boolean}
[ "Finds", "whether", "a", "variable", "is", "a", "number", "or", "a", "numeric", "string" ]
7b188893c4e2da81279e00e07e65b930685d05d3
https://github.com/JBZoo/JS-Utils/blob/7b188893c4e2da81279e00e07e65b930685d05d3/src/helper.js#L274-L290
55,854
JBZoo/JS-Utils
src/helper.js
function (value, precision, mode) { /* jshint -W016 */ /* jshint -W018 */ // Helper variables var base, floorNum, isHalf, sign; // Making sure precision is integer precision |= 0; base = Math.pow(10, precision); value *= base; // Sign of the number sign = (value > 0) | -(value < 0); isHalf = value % 1 === 0.5 * sign; floorNum = Math.floor(value); if (isHalf) { mode = mode ? mode.toUpperCase() : "DEFAULT"; switch (mode) { case "DOWN": // Rounds .5 toward zero value = floorNum + (sign < 0); break; case "EVEN": // Rouds .5 towards the next even integer value = floorNum + (floorNum % 2 * sign); break; case "ODD": // Rounds .5 towards the next odd integer value = floorNum + !(floorNum % 2); break; default: // Rounds .5 away from zero value = floorNum + (sign > 0); } } return (isHalf ? value : Math.round(value)) / base; /* jshint +W016 */ /* jshint +W018 */ }
javascript
function (value, precision, mode) { /* jshint -W016 */ /* jshint -W018 */ // Helper variables var base, floorNum, isHalf, sign; // Making sure precision is integer precision |= 0; base = Math.pow(10, precision); value *= base; // Sign of the number sign = (value > 0) | -(value < 0); isHalf = value % 1 === 0.5 * sign; floorNum = Math.floor(value); if (isHalf) { mode = mode ? mode.toUpperCase() : "DEFAULT"; switch (mode) { case "DOWN": // Rounds .5 toward zero value = floorNum + (sign < 0); break; case "EVEN": // Rouds .5 towards the next even integer value = floorNum + (floorNum % 2 * sign); break; case "ODD": // Rounds .5 towards the next odd integer value = floorNum + !(floorNum % 2); break; default: // Rounds .5 away from zero value = floorNum + (sign > 0); } } return (isHalf ? value : Math.round(value)) / base; /* jshint +W016 */ /* jshint +W018 */ }
[ "function", "(", "value", ",", "precision", ",", "mode", ")", "{", "/* jshint -W016 */", "/* jshint -W018 */", "// Helper variables", "var", "base", ",", "floorNum", ",", "isHalf", ",", "sign", ";", "// Making sure precision is integer", "precision", "|=", "0", ";", "base", "=", "Math", ".", "pow", "(", "10", ",", "precision", ")", ";", "value", "*=", "base", ";", "// Sign of the number", "sign", "=", "(", "value", ">", "0", ")", "|", "-", "(", "value", "<", "0", ")", ";", "isHalf", "=", "value", "%", "1", "===", "0.5", "*", "sign", ";", "floorNum", "=", "Math", ".", "floor", "(", "value", ")", ";", "if", "(", "isHalf", ")", "{", "mode", "=", "mode", "?", "mode", ".", "toUpperCase", "(", ")", ":", "\"DEFAULT\"", ";", "switch", "(", "mode", ")", "{", "case", "\"DOWN\"", ":", "// Rounds .5 toward zero", "value", "=", "floorNum", "+", "(", "sign", "<", "0", ")", ";", "break", ";", "case", "\"EVEN\"", ":", "// Rouds .5 towards the next even integer", "value", "=", "floorNum", "+", "(", "floorNum", "%", "2", "*", "sign", ")", ";", "break", ";", "case", "\"ODD\"", ":", "// Rounds .5 towards the next odd integer", "value", "=", "floorNum", "+", "!", "(", "floorNum", "%", "2", ")", ";", "break", ";", "default", ":", "// Rounds .5 away from zero", "value", "=", "floorNum", "+", "(", "sign", ">", "0", ")", ";", "}", "}", "return", "(", "isHalf", "?", "value", ":", "Math", ".", "round", "(", "value", ")", ")", "/", "base", ";", "/* jshint +W016 */", "/* jshint +W018 */", "}" ]
Rounds a float @link http://php.net/manual/en/function.round.php @link http://phpjs.org/functions/round/ @param value @param precision @param mode @returns {number}
[ "Rounds", "a", "float" ]
7b188893c4e2da81279e00e07e65b930685d05d3
https://github.com/JBZoo/JS-Utils/blob/7b188893c4e2da81279e00e07e65b930685d05d3/src/helper.js#L385-L426
55,855
JBZoo/JS-Utils
src/helper.js
function (glue, pieces) { var retVal = "", tGlue = ""; if (arguments.length === 1) { pieces = glue; glue = ""; } if (typeof pieces === "object") { if ($this.type(pieces) === "array") { return pieces.join(glue); } $this.each(pieces, function (i) { retVal += tGlue + pieces[i]; tGlue = glue; }); return retVal; } }
javascript
function (glue, pieces) { var retVal = "", tGlue = ""; if (arguments.length === 1) { pieces = glue; glue = ""; } if (typeof pieces === "object") { if ($this.type(pieces) === "array") { return pieces.join(glue); } $this.each(pieces, function (i) { retVal += tGlue + pieces[i]; tGlue = glue; }); return retVal; } }
[ "function", "(", "glue", ",", "pieces", ")", "{", "var", "retVal", "=", "\"\"", ",", "tGlue", "=", "\"\"", ";", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "pieces", "=", "glue", ";", "glue", "=", "\"\"", ";", "}", "if", "(", "typeof", "pieces", "===", "\"object\"", ")", "{", "if", "(", "$this", ".", "type", "(", "pieces", ")", "===", "\"array\"", ")", "{", "return", "pieces", ".", "join", "(", "glue", ")", ";", "}", "$this", ".", "each", "(", "pieces", ",", "function", "(", "i", ")", "{", "retVal", "+=", "tGlue", "+", "pieces", "[", "i", "]", ";", "tGlue", "=", "glue", ";", "}", ")", ";", "return", "retVal", ";", "}", "}" ]
Join array elements with a string @link http://php.net/manual/en/function.implode.php @link http://phpjs.org/functions/implode/ @param glue @param pieces @returns {*}
[ "Join", "array", "elements", "with", "a", "string" ]
7b188893c4e2da81279e00e07e65b930685d05d3
https://github.com/JBZoo/JS-Utils/blob/7b188893c4e2da81279e00e07e65b930685d05d3/src/helper.js#L466-L488
55,856
JBZoo/JS-Utils
src/helper.js
function (delimiter, string, limit) { if (arguments.length < 2 || typeof delimiter === "undefined" || typeof string === "undefined" ) { return null; } if (delimiter === "" || delimiter === false || delimiter === null ) { return false; } if (delimiter === true) { delimiter = "1"; } // Here we go... delimiter += ""; string += ""; var splited = string.split(delimiter); if (typeof limit === "undefined") { return splited; } // Support for limit if (limit === 0) { limit = 1; } // Positive limit if (limit > 0) { if (limit >= splited.length) { return splited; } return splited.slice(0, limit - 1) .concat([splited.slice(limit - 1) .join(delimiter) ]); } // Negative limit if (-limit >= splited.length) { return []; } splited.splice(splited.length + limit); return splited; }
javascript
function (delimiter, string, limit) { if (arguments.length < 2 || typeof delimiter === "undefined" || typeof string === "undefined" ) { return null; } if (delimiter === "" || delimiter === false || delimiter === null ) { return false; } if (delimiter === true) { delimiter = "1"; } // Here we go... delimiter += ""; string += ""; var splited = string.split(delimiter); if (typeof limit === "undefined") { return splited; } // Support for limit if (limit === 0) { limit = 1; } // Positive limit if (limit > 0) { if (limit >= splited.length) { return splited; } return splited.slice(0, limit - 1) .concat([splited.slice(limit - 1) .join(delimiter) ]); } // Negative limit if (-limit >= splited.length) { return []; } splited.splice(splited.length + limit); return splited; }
[ "function", "(", "delimiter", ",", "string", ",", "limit", ")", "{", "if", "(", "arguments", ".", "length", "<", "2", "||", "typeof", "delimiter", "===", "\"undefined\"", "||", "typeof", "string", "===", "\"undefined\"", ")", "{", "return", "null", ";", "}", "if", "(", "delimiter", "===", "\"\"", "||", "delimiter", "===", "false", "||", "delimiter", "===", "null", ")", "{", "return", "false", ";", "}", "if", "(", "delimiter", "===", "true", ")", "{", "delimiter", "=", "\"1\"", ";", "}", "// Here we go...", "delimiter", "+=", "\"\"", ";", "string", "+=", "\"\"", ";", "var", "splited", "=", "string", ".", "split", "(", "delimiter", ")", ";", "if", "(", "typeof", "limit", "===", "\"undefined\"", ")", "{", "return", "splited", ";", "}", "// Support for limit", "if", "(", "limit", "===", "0", ")", "{", "limit", "=", "1", ";", "}", "// Positive limit", "if", "(", "limit", ">", "0", ")", "{", "if", "(", "limit", ">=", "splited", ".", "length", ")", "{", "return", "splited", ";", "}", "return", "splited", ".", "slice", "(", "0", ",", "limit", "-", "1", ")", ".", "concat", "(", "[", "splited", ".", "slice", "(", "limit", "-", "1", ")", ".", "join", "(", "delimiter", ")", "]", ")", ";", "}", "// Negative limit", "if", "(", "-", "limit", ">=", "splited", ".", "length", ")", "{", "return", "[", "]", ";", "}", "splited", ".", "splice", "(", "splited", ".", "length", "+", "limit", ")", ";", "return", "splited", ";", "}" ]
Split a string by string @link http://phpjs.org/functions/explode/ @link http://php.net/manual/en/function.explode.php @param delimiter @param string @param limit @returns {*}
[ "Split", "a", "string", "by", "string" ]
7b188893c4e2da81279e00e07e65b930685d05d3
https://github.com/JBZoo/JS-Utils/blob/7b188893c4e2da81279e00e07e65b930685d05d3/src/helper.js#L501-L556
55,857
webinverters/robust-auth
src/robust-auth.js
authDetectionMiddleware
function authDetectionMiddleware(req, res, next) { logger.debug('Running Auth Detection Middleware...', req.body); if (req.headers['token']) { try { req.user = encryption.decode(req.headers['token'], config.secret); req.session = { user: req.user }; } catch (ex) { logger.logError('Unexpectedly could not decode a token.', ex); res.status(401).send(); // ensure no user is authenticated. req.user = null; req.session = { user: null }; } if (!req.user.id) throw 'AUTH FAILED:USER HAS NO MEMBER: id'; if (!req.user.tokenExpiry || req.user.tokenExpiry <= new Date().getTime()) { logger.log('Expired Token:', req.user); res.status(401).send({errorCode: 'expired token'}); } else { logger.log('Authenticated User:', req.user.id); next(); } } else { //logger.debug('Checking permissions to ', req.path); //if (config.routesNotRequiringAuthentication[req.path]) next(); //else if (m.isPublicRoute(req.path)) next(); //else { // logger.debug('Disallowing request to:', req.path); // res.status(401).send(); //} if (config.authenticatedRoutes[req.path] || !m.isPublicRoute(req.path)) res.status(401).send(); else next(); } }
javascript
function authDetectionMiddleware(req, res, next) { logger.debug('Running Auth Detection Middleware...', req.body); if (req.headers['token']) { try { req.user = encryption.decode(req.headers['token'], config.secret); req.session = { user: req.user }; } catch (ex) { logger.logError('Unexpectedly could not decode a token.', ex); res.status(401).send(); // ensure no user is authenticated. req.user = null; req.session = { user: null }; } if (!req.user.id) throw 'AUTH FAILED:USER HAS NO MEMBER: id'; if (!req.user.tokenExpiry || req.user.tokenExpiry <= new Date().getTime()) { logger.log('Expired Token:', req.user); res.status(401).send({errorCode: 'expired token'}); } else { logger.log('Authenticated User:', req.user.id); next(); } } else { //logger.debug('Checking permissions to ', req.path); //if (config.routesNotRequiringAuthentication[req.path]) next(); //else if (m.isPublicRoute(req.path)) next(); //else { // logger.debug('Disallowing request to:', req.path); // res.status(401).send(); //} if (config.authenticatedRoutes[req.path] || !m.isPublicRoute(req.path)) res.status(401).send(); else next(); } }
[ "function", "authDetectionMiddleware", "(", "req", ",", "res", ",", "next", ")", "{", "logger", ".", "debug", "(", "'Running Auth Detection Middleware...'", ",", "req", ".", "body", ")", ";", "if", "(", "req", ".", "headers", "[", "'token'", "]", ")", "{", "try", "{", "req", ".", "user", "=", "encryption", ".", "decode", "(", "req", ".", "headers", "[", "'token'", "]", ",", "config", ".", "secret", ")", ";", "req", ".", "session", "=", "{", "user", ":", "req", ".", "user", "}", ";", "}", "catch", "(", "ex", ")", "{", "logger", ".", "logError", "(", "'Unexpectedly could not decode a token.'", ",", "ex", ")", ";", "res", ".", "status", "(", "401", ")", ".", "send", "(", ")", ";", "// ensure no user is authenticated.", "req", ".", "user", "=", "null", ";", "req", ".", "session", "=", "{", "user", ":", "null", "}", ";", "}", "if", "(", "!", "req", ".", "user", ".", "id", ")", "throw", "'AUTH FAILED:USER HAS NO MEMBER: id'", ";", "if", "(", "!", "req", ".", "user", ".", "tokenExpiry", "||", "req", ".", "user", ".", "tokenExpiry", "<=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", "{", "logger", ".", "log", "(", "'Expired Token:'", ",", "req", ".", "user", ")", ";", "res", ".", "status", "(", "401", ")", ".", "send", "(", "{", "errorCode", ":", "'expired token'", "}", ")", ";", "}", "else", "{", "logger", ".", "log", "(", "'Authenticated User:'", ",", "req", ".", "user", ".", "id", ")", ";", "next", "(", ")", ";", "}", "}", "else", "{", "//logger.debug('Checking permissions to ', req.path);", "//if (config.routesNotRequiringAuthentication[req.path]) next();", "//else if (m.isPublicRoute(req.path)) next();", "//else {", "// logger.debug('Disallowing request to:', req.path);", "// res.status(401).send();", "//}", "if", "(", "config", ".", "authenticatedRoutes", "[", "req", ".", "path", "]", "||", "!", "m", ".", "isPublicRoute", "(", "req", ".", "path", ")", ")", "res", ".", "status", "(", "401", ")", ".", "send", "(", ")", ";", "else", "next", "(", ")", ";", "}", "}" ]
Detects if the user is sending an authenticated request. If it is, it will set req.user and req.session.user details. @param req @param res @param next
[ "Detects", "if", "the", "user", "is", "sending", "an", "authenticated", "request", ".", "If", "it", "is", "it", "will", "set", "req", ".", "user", "and", "req", ".", "session", ".", "user", "details", "." ]
ec2058d34837f97da48129998d8af72fef87018a
https://github.com/webinverters/robust-auth/blob/ec2058d34837f97da48129998d8af72fef87018a/src/robust-auth.js#L203-L239
55,858
Zingle/http-later-storage
http-later-storage.js
createStorage
function createStorage(defaults, queue, unqueue, log) { if (typeof defaults !== "object") { log = unqueue; unqueue = queue; queue = defaults; defaults = {}; } /** * @constructor * @param {object} [opts] */ function Storage(opts) { mixin(mixin(this, opts), defaults); } /** * @name Storage#queue * @method * @param {object} task * @param {queueTaskCallback} [done] */ Storage.prototype.queue = function(task, done) { switch (arguments.length) { case 0: throw new TypeError("expected task"); case 1: arguments[1] = function() {}; } queue.apply(this, arguments); }; /** * @name Storage#unqueue * @method * @param {unqueueTaskCallback} [done] */ Storage.prototype.unqueue = function(done) { switch (arguments.length) { case 0: arguments[0] = function() {}; } unqueue.apply(this, arguments); }; /** * @name Storage#log * @method * @param {string} key * @param {object} result * @param {functon} [done] */ Storage.prototype.log = function(key, result, done) { switch (arguments.length) { case 0: throw new TypeError("expected key"); case 1: throw new TypeError("expected results"); case 2: arguments[2] = function() {}; } log.apply(this, arguments); }; // return new Storage class return Storage; }
javascript
function createStorage(defaults, queue, unqueue, log) { if (typeof defaults !== "object") { log = unqueue; unqueue = queue; queue = defaults; defaults = {}; } /** * @constructor * @param {object} [opts] */ function Storage(opts) { mixin(mixin(this, opts), defaults); } /** * @name Storage#queue * @method * @param {object} task * @param {queueTaskCallback} [done] */ Storage.prototype.queue = function(task, done) { switch (arguments.length) { case 0: throw new TypeError("expected task"); case 1: arguments[1] = function() {}; } queue.apply(this, arguments); }; /** * @name Storage#unqueue * @method * @param {unqueueTaskCallback} [done] */ Storage.prototype.unqueue = function(done) { switch (arguments.length) { case 0: arguments[0] = function() {}; } unqueue.apply(this, arguments); }; /** * @name Storage#log * @method * @param {string} key * @param {object} result * @param {functon} [done] */ Storage.prototype.log = function(key, result, done) { switch (arguments.length) { case 0: throw new TypeError("expected key"); case 1: throw new TypeError("expected results"); case 2: arguments[2] = function() {}; } log.apply(this, arguments); }; // return new Storage class return Storage; }
[ "function", "createStorage", "(", "defaults", ",", "queue", ",", "unqueue", ",", "log", ")", "{", "if", "(", "typeof", "defaults", "!==", "\"object\"", ")", "{", "log", "=", "unqueue", ";", "unqueue", "=", "queue", ";", "queue", "=", "defaults", ";", "defaults", "=", "{", "}", ";", "}", "/**\n * @constructor\n * @param {object} [opts]\n */", "function", "Storage", "(", "opts", ")", "{", "mixin", "(", "mixin", "(", "this", ",", "opts", ")", ",", "defaults", ")", ";", "}", "/**\n * @name Storage#queue\n * @method\n * @param {object} task\n * @param {queueTaskCallback} [done]\n */", "Storage", ".", "prototype", ".", "queue", "=", "function", "(", "task", ",", "done", ")", "{", "switch", "(", "arguments", ".", "length", ")", "{", "case", "0", ":", "throw", "new", "TypeError", "(", "\"expected task\"", ")", ";", "case", "1", ":", "arguments", "[", "1", "]", "=", "function", "(", ")", "{", "}", ";", "}", "queue", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "/**\n * @name Storage#unqueue\n * @method\n * @param {unqueueTaskCallback} [done]\n */", "Storage", ".", "prototype", ".", "unqueue", "=", "function", "(", "done", ")", "{", "switch", "(", "arguments", ".", "length", ")", "{", "case", "0", ":", "arguments", "[", "0", "]", "=", "function", "(", ")", "{", "}", ";", "}", "unqueue", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "/**\n * @name Storage#log\n * @method\n * @param {string} key\n * @param {object} result\n * @param {functon} [done]\n */", "Storage", ".", "prototype", ".", "log", "=", "function", "(", "key", ",", "result", ",", "done", ")", "{", "switch", "(", "arguments", ".", "length", ")", "{", "case", "0", ":", "throw", "new", "TypeError", "(", "\"expected key\"", ")", ";", "case", "1", ":", "throw", "new", "TypeError", "(", "\"expected results\"", ")", ";", "case", "2", ":", "arguments", "[", "2", "]", "=", "function", "(", ")", "{", "}", ";", "}", "log", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "// return new Storage class", "return", "Storage", ";", "}" ]
Log task result @callback logResult @param {string} key @param {object} result @param {doneCallback} done Create http-later storage driver. @param {object} [defaults] @param {queueTask} queue @param {unqueueTask} unqueue @param {logResult} log @returns {function}
[ "Log", "task", "result" ]
df555a8720a77aa52a37fdcca2d5c01d326b5e3a
https://github.com/Zingle/http-later-storage/blob/df555a8720a77aa52a37fdcca2d5c01d326b5e3a/http-later-storage.js#L55-L119
55,859
crcn/beet
lib/group.js
function(callback) { var self = this; this.beet.client.getAllProcessInfo(function(err, processes) { if(processes) for(var i = processes.length; i--;) { var proc = processes[i], nameParts = proc.name.split('_'); if(nameParts[0] != self.name) { processes.splice(i, 1); } else { proc.group = nameParts[0]; proc.name = nameParts[1]; } } callback(err, processes); }); }
javascript
function(callback) { var self = this; this.beet.client.getAllProcessInfo(function(err, processes) { if(processes) for(var i = processes.length; i--;) { var proc = processes[i], nameParts = proc.name.split('_'); if(nameParts[0] != self.name) { processes.splice(i, 1); } else { proc.group = nameParts[0]; proc.name = nameParts[1]; } } callback(err, processes); }); }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "this", ".", "beet", ".", "client", ".", "getAllProcessInfo", "(", "function", "(", "err", ",", "processes", ")", "{", "if", "(", "processes", ")", "for", "(", "var", "i", "=", "processes", ".", "length", ";", "i", "--", ";", ")", "{", "var", "proc", "=", "processes", "[", "i", "]", ",", "nameParts", "=", "proc", ".", "name", ".", "split", "(", "'_'", ")", ";", "if", "(", "nameParts", "[", "0", "]", "!=", "self", ".", "name", ")", "{", "processes", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "else", "{", "proc", ".", "group", "=", "nameParts", "[", "0", "]", ";", "proc", ".", "name", "=", "nameParts", "[", "1", "]", ";", "}", "}", "callback", "(", "err", ",", "processes", ")", ";", "}", ")", ";", "}" ]
Lists all the processes under the given group
[ "Lists", "all", "the", "processes", "under", "the", "given", "group" ]
e8622c5c48592bddcf9507a388022aea1f571f01
https://github.com/crcn/beet/blob/e8622c5c48592bddcf9507a388022aea1f571f01/lib/group.js#L32-L54
55,860
crcn/beet
lib/group.js
function(ops, callback) { if(!callback) callback = function() { }; //name of the script to run for supervisord if(!ops.name) ops.name = 'undefined'; var supervisordName = this._name(ops.name); //script exists? split it apart if(ops.script) { ops.directory = ops.script.split('.').length == 1 ? ops.script :path.dirname(ops.script); try { var package = JSON.parse(fs.readFileSync(ops.directory + '/package.json')); if(!package.main && package.bin) { for(var binName in package.bin) { ops.command = ops.directory + '/' + package.bin[binName]; } } } catch(e) { } if(!ops.command) ops.command = 'node ' + ops.script +' '+ (ops.args || []).join(' '); } var envStr; if(ops.environment) { var envBuffer = []; for(var property in ops.environment) { envBuffer.push(property + '=' + ops.environment[property]); } envStr = envBuffer.join(','); } //directory to script - chdir for supervisord //if(!ops.directory) return callback('directory is not provided'); //the command to use for running supervisord if(!ops.command) return callback('command not provided'); if(!ops.name) return callback('Name not provided'); var self = this; var update = this._query({ supervisordName: supervisordName, name: ops.name, directory: ops.directory, command: ops.command, environment: envStr, stdout_logfile: this.logsDir + '/' + supervisordName + '.log', stderr_logfile: this.logsDir + '/' + supervisordName + '-err.log' }); //insert into the beet db this._collection.update({ _id: this._id(supervisordName) }, { $set: update }, { upsert: true }, function(err, result){ if(callback) callback(err, result); }); }
javascript
function(ops, callback) { if(!callback) callback = function() { }; //name of the script to run for supervisord if(!ops.name) ops.name = 'undefined'; var supervisordName = this._name(ops.name); //script exists? split it apart if(ops.script) { ops.directory = ops.script.split('.').length == 1 ? ops.script :path.dirname(ops.script); try { var package = JSON.parse(fs.readFileSync(ops.directory + '/package.json')); if(!package.main && package.bin) { for(var binName in package.bin) { ops.command = ops.directory + '/' + package.bin[binName]; } } } catch(e) { } if(!ops.command) ops.command = 'node ' + ops.script +' '+ (ops.args || []).join(' '); } var envStr; if(ops.environment) { var envBuffer = []; for(var property in ops.environment) { envBuffer.push(property + '=' + ops.environment[property]); } envStr = envBuffer.join(','); } //directory to script - chdir for supervisord //if(!ops.directory) return callback('directory is not provided'); //the command to use for running supervisord if(!ops.command) return callback('command not provided'); if(!ops.name) return callback('Name not provided'); var self = this; var update = this._query({ supervisordName: supervisordName, name: ops.name, directory: ops.directory, command: ops.command, environment: envStr, stdout_logfile: this.logsDir + '/' + supervisordName + '.log', stderr_logfile: this.logsDir + '/' + supervisordName + '-err.log' }); //insert into the beet db this._collection.update({ _id: this._id(supervisordName) }, { $set: update }, { upsert: true }, function(err, result){ if(callback) callback(err, result); }); }
[ "function", "(", "ops", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "callback", "=", "function", "(", ")", "{", "}", ";", "//name of the script to run for supervisord", "if", "(", "!", "ops", ".", "name", ")", "ops", ".", "name", "=", "'undefined'", ";", "var", "supervisordName", "=", "this", ".", "_name", "(", "ops", ".", "name", ")", ";", "//script exists? split it apart", "if", "(", "ops", ".", "script", ")", "{", "ops", ".", "directory", "=", "ops", ".", "script", ".", "split", "(", "'.'", ")", ".", "length", "==", "1", "?", "ops", ".", "script", ":", "path", ".", "dirname", "(", "ops", ".", "script", ")", ";", "try", "{", "var", "package", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "ops", ".", "directory", "+", "'/package.json'", ")", ")", ";", "if", "(", "!", "package", ".", "main", "&&", "package", ".", "bin", ")", "{", "for", "(", "var", "binName", "in", "package", ".", "bin", ")", "{", "ops", ".", "command", "=", "ops", ".", "directory", "+", "'/'", "+", "package", ".", "bin", "[", "binName", "]", ";", "}", "}", "}", "catch", "(", "e", ")", "{", "}", "if", "(", "!", "ops", ".", "command", ")", "ops", ".", "command", "=", "'node '", "+", "ops", ".", "script", "+", "' '", "+", "(", "ops", ".", "args", "||", "[", "]", ")", ".", "join", "(", "' '", ")", ";", "}", "var", "envStr", ";", "if", "(", "ops", ".", "environment", ")", "{", "var", "envBuffer", "=", "[", "]", ";", "for", "(", "var", "property", "in", "ops", ".", "environment", ")", "{", "envBuffer", ".", "push", "(", "property", "+", "'='", "+", "ops", ".", "environment", "[", "property", "]", ")", ";", "}", "envStr", "=", "envBuffer", ".", "join", "(", "','", ")", ";", "}", "//directory to script - chdir for supervisord", "//if(!ops.directory) return callback('directory is not provided');", "//the command to use for running supervisord", "if", "(", "!", "ops", ".", "command", ")", "return", "callback", "(", "'command not provided'", ")", ";", "if", "(", "!", "ops", ".", "name", ")", "return", "callback", "(", "'Name not provided'", ")", ";", "var", "self", "=", "this", ";", "var", "update", "=", "this", ".", "_query", "(", "{", "supervisordName", ":", "supervisordName", ",", "name", ":", "ops", ".", "name", ",", "directory", ":", "ops", ".", "directory", ",", "command", ":", "ops", ".", "command", ",", "environment", ":", "envStr", ",", "stdout_logfile", ":", "this", ".", "logsDir", "+", "'/'", "+", "supervisordName", "+", "'.log'", ",", "stderr_logfile", ":", "this", ".", "logsDir", "+", "'/'", "+", "supervisordName", "+", "'-err.log'", "}", ")", ";", "//insert into the beet db ", "this", ".", "_collection", ".", "update", "(", "{", "_id", ":", "this", ".", "_id", "(", "supervisordName", ")", "}", ",", "{", "$set", ":", "update", "}", ",", "{", "upsert", ":", "true", "}", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "callback", ")", "callback", "(", "err", ",", "result", ")", ";", "}", ")", ";", "}" ]
addes a process to a given group
[ "addes", "a", "process", "to", "a", "given", "group" ]
e8622c5c48592bddcf9507a388022aea1f571f01
https://github.com/crcn/beet/blob/e8622c5c48592bddcf9507a388022aea1f571f01/lib/group.js#L153-L218
55,861
crcn/beet
lib/group.js
function(ops, callback) { var search = typeof ops == 'string' ? { name: ops } : ops, query = this._query(search), self = this; //stop the app in case... self.stop(search.name, function(err, result) { if(callback) callback(err, result); }); //remove the app self._collection.remove(query, function(err, result){ }); }
javascript
function(ops, callback) { var search = typeof ops == 'string' ? { name: ops } : ops, query = this._query(search), self = this; //stop the app in case... self.stop(search.name, function(err, result) { if(callback) callback(err, result); }); //remove the app self._collection.remove(query, function(err, result){ }); }
[ "function", "(", "ops", ",", "callback", ")", "{", "var", "search", "=", "typeof", "ops", "==", "'string'", "?", "{", "name", ":", "ops", "}", ":", "ops", ",", "query", "=", "this", ".", "_query", "(", "search", ")", ",", "self", "=", "this", ";", "//stop the app in case...", "self", ".", "stop", "(", "search", ".", "name", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "callback", ")", "callback", "(", "err", ",", "result", ")", ";", "}", ")", ";", "//remove the app", "self", ".", "_collection", ".", "remove", "(", "query", ",", "function", "(", "err", ",", "result", ")", "{", "}", ")", ";", "}" ]
Removes a script from supervisord
[ "Removes", "a", "script", "from", "supervisord" ]
e8622c5c48592bddcf9507a388022aea1f571f01
https://github.com/crcn/beet/blob/e8622c5c48592bddcf9507a388022aea1f571f01/lib/group.js#L224-L236
55,862
themouette/screenstory
lib/reporter.js
ForwardMochaReporter
function ForwardMochaReporter(mochaRunner, options) { Base.call(this, mochaRunner, options); forwardEvent(mochaRunner, runner, 'start'); forwardEvent(mochaRunner, runner, 'suite'); forwardEvent(mochaRunner, runner, 'suite end'); forwardEvent(mochaRunner, runner, 'pending'); forwardEvent(mochaRunner, runner, 'pass'); forwardEvent(mochaRunner, runner, 'fail'); // when runner output should be captured, it is done for the end event only. mochaRunner.on('end', function () { try { if (outputFile) { console.log(outputFile); captureStdout(outputFile); } var args = Array.prototype.slice.call(arguments, 0); runner.emit.apply(runner, ['end'].concat(args)); releaseStdout(); } catch (e) { releaseStdout(); } }); }
javascript
function ForwardMochaReporter(mochaRunner, options) { Base.call(this, mochaRunner, options); forwardEvent(mochaRunner, runner, 'start'); forwardEvent(mochaRunner, runner, 'suite'); forwardEvent(mochaRunner, runner, 'suite end'); forwardEvent(mochaRunner, runner, 'pending'); forwardEvent(mochaRunner, runner, 'pass'); forwardEvent(mochaRunner, runner, 'fail'); // when runner output should be captured, it is done for the end event only. mochaRunner.on('end', function () { try { if (outputFile) { console.log(outputFile); captureStdout(outputFile); } var args = Array.prototype.slice.call(arguments, 0); runner.emit.apply(runner, ['end'].concat(args)); releaseStdout(); } catch (e) { releaseStdout(); } }); }
[ "function", "ForwardMochaReporter", "(", "mochaRunner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "mochaRunner", ",", "options", ")", ";", "forwardEvent", "(", "mochaRunner", ",", "runner", ",", "'start'", ")", ";", "forwardEvent", "(", "mochaRunner", ",", "runner", ",", "'suite'", ")", ";", "forwardEvent", "(", "mochaRunner", ",", "runner", ",", "'suite end'", ")", ";", "forwardEvent", "(", "mochaRunner", ",", "runner", ",", "'pending'", ")", ";", "forwardEvent", "(", "mochaRunner", ",", "runner", ",", "'pass'", ")", ";", "forwardEvent", "(", "mochaRunner", ",", "runner", ",", "'fail'", ")", ";", "// when runner output should be captured, it is done for the end event only.", "mochaRunner", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "try", "{", "if", "(", "outputFile", ")", "{", "console", ".", "log", "(", "outputFile", ")", ";", "captureStdout", "(", "outputFile", ")", ";", "}", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "runner", ".", "emit", ".", "apply", "(", "runner", ",", "[", "'end'", "]", ".", "concat", "(", "args", ")", ")", ";", "releaseStdout", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "releaseStdout", "(", ")", ";", "}", "}", ")", ";", "}" ]
Initialize a new `ProxyReporter` reporter. @param {Runner} runner @api public
[ "Initialize", "a", "new", "ProxyReporter", "reporter", "." ]
0c847f5514a55e7c2f59728565591d4bb5788915
https://github.com/themouette/screenstory/blob/0c847f5514a55e7c2f59728565591d4bb5788915/lib/reporter.js#L22-L44
55,863
redisjs/jsr-log
lib/logtime.js
logtime
function logtime() { var d = new Date() , space = ' ' , delimiter = ':' , str = d.toString() , month = str.split(' ')[1]; return d.getDate() + space + month + space + d.getHours() + delimiter + pad(d.getMinutes()) + delimiter + pad(d.getSeconds()) + '.' + pad(d.getMilliseconds(), 3); }
javascript
function logtime() { var d = new Date() , space = ' ' , delimiter = ':' , str = d.toString() , month = str.split(' ')[1]; return d.getDate() + space + month + space + d.getHours() + delimiter + pad(d.getMinutes()) + delimiter + pad(d.getSeconds()) + '.' + pad(d.getMilliseconds(), 3); }
[ "function", "logtime", "(", ")", "{", "var", "d", "=", "new", "Date", "(", ")", ",", "space", "=", "' '", ",", "delimiter", "=", "':'", ",", "str", "=", "d", ".", "toString", "(", ")", ",", "month", "=", "str", ".", "split", "(", "' '", ")", "[", "1", "]", ";", "return", "d", ".", "getDate", "(", ")", "+", "space", "+", "month", "+", "space", "+", "d", ".", "getHours", "(", ")", "+", "delimiter", "+", "pad", "(", "d", ".", "getMinutes", "(", ")", ")", "+", "delimiter", "+", "pad", "(", "d", ".", "getSeconds", "(", ")", ")", "+", "'.'", "+", "pad", "(", "d", ".", "getMilliseconds", "(", ")", ",", "3", ")", ";", "}" ]
Utility to get a time format.
[ "Utility", "to", "get", "a", "time", "format", "." ]
a67a34285449b0d731493def58d8a5212aad5526
https://github.com/redisjs/jsr-log/blob/a67a34285449b0d731493def58d8a5212aad5526/lib/logtime.js#L6-L19
55,864
fazo96/LC2.js
peripherals/console.js
Console
function Console (lc2, position, debug) { this.lc2 = lc2 this.position = position this.debug = debug || false this.name = 'Console' this.lastReadKey = 0 this.inputBuffer = 0 this.outputKey = 0 this.displayReady = 1 }
javascript
function Console (lc2, position, debug) { this.lc2 = lc2 this.position = position this.debug = debug || false this.name = 'Console' this.lastReadKey = 0 this.inputBuffer = 0 this.outputKey = 0 this.displayReady = 1 }
[ "function", "Console", "(", "lc2", ",", "position", ",", "debug", ")", "{", "this", ".", "lc2", "=", "lc2", "this", ".", "position", "=", "position", "this", ".", "debug", "=", "debug", "||", "false", "this", ".", "name", "=", "'Console'", "this", ".", "lastReadKey", "=", "0", "this", ".", "inputBuffer", "=", "0", "this", ".", "outputKey", "=", "0", "this", ".", "displayReady", "=", "1", "}" ]
Creates a new Console. Of course it needs a reference to a `lc2` CPU, the `position` in memory that will map to the Console registers, and wether or not debug mode might be activated.
[ "Creates", "a", "new", "Console", ".", "Of", "course", "it", "needs", "a", "reference", "to", "a", "lc2", "CPU", "the", "position", "in", "memory", "that", "will", "map", "to", "the", "Console", "registers", "and", "wether", "or", "not", "debug", "mode", "might", "be", "activated", "." ]
33b1d1e84d5da7c0df16290fc1289628ba65b430
https://github.com/fazo96/LC2.js/blob/33b1d1e84d5da7c0df16290fc1289628ba65b430/peripherals/console.js#L183-L192
55,865
lorenwest/monitor-min
lib/probes/FileProbe.js
function() { FS.readFile(path, options.encoding, function(err, text) { if (err) { // Forward the error return callback(err); } // Success callback(null, text.toString()); }); }
javascript
function() { FS.readFile(path, options.encoding, function(err, text) { if (err) { // Forward the error return callback(err); } // Success callback(null, text.toString()); }); }
[ "function", "(", ")", "{", "FS", ".", "readFile", "(", "path", ",", "options", ".", "encoding", ",", "function", "(", "err", ",", "text", ")", "{", "if", "(", "err", ")", "{", "// Forward the error", "return", "callback", "(", "err", ")", ";", "}", "// Success", "callback", "(", "null", ",", "text", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "}" ]
Build the function to call when the file changes
[ "Build", "the", "function", "to", "call", "when", "the", "file", "changes" ]
859ba34a121498dc1cb98577ae24abd825407fca
https://github.com/lorenwest/monitor-min/blob/859ba34a121498dc1cb98577ae24abd825407fca/lib/probes/FileProbe.js#L254-L263
55,866
bibig/rander
libs/rander.js
pickup
function pickup (/*len, dict || dict */) { var str = '', pos; var len, dict; if (arguments.length === 1) { dict = arguments[0]; len = 1; } else if (arguments.length === 2) { len = arguments[0]; dict = arguments[1]; } else { return string(); } for (var i=0; i< len; i++) { pos = dice(dict.length - 1); str += dict.substring(pos, pos + 1); } return str; }
javascript
function pickup (/*len, dict || dict */) { var str = '', pos; var len, dict; if (arguments.length === 1) { dict = arguments[0]; len = 1; } else if (arguments.length === 2) { len = arguments[0]; dict = arguments[1]; } else { return string(); } for (var i=0; i< len; i++) { pos = dice(dict.length - 1); str += dict.substring(pos, pos + 1); } return str; }
[ "function", "pickup", "(", "/*len, dict || dict */", ")", "{", "var", "str", "=", "''", ",", "pos", ";", "var", "len", ",", "dict", ";", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "dict", "=", "arguments", "[", "0", "]", ";", "len", "=", "1", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "len", "=", "arguments", "[", "0", "]", ";", "dict", "=", "arguments", "[", "1", "]", ";", "}", "else", "{", "return", "string", "(", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "pos", "=", "dice", "(", "dict", ".", "length", "-", "1", ")", ";", "str", "+=", "dict", ".", "substring", "(", "pos", ",", "pos", "+", "1", ")", ";", "}", "return", "str", ";", "}" ]
dict is a string
[ "dict", "is", "a", "string" ]
8f4d4d807994d9b11e57ea979e9a7597d8c983eb
https://github.com/bibig/rander/blob/8f4d4d807994d9b11e57ea979e9a7597d8c983eb/libs/rander.js#L21-L41
55,867
JoshuaToenyes/browserify-testability
src/prelude.js
function(x, reload){ // Get the numeric ID for the module to load. var id = modules[name][1][x]; // If there's a matching module in the testability cache, return it. if (_testability_cache_[x]) return _testability_cache_[x]; // Return recursively... the module's export will be in the cache // after this. return newRequire(id ? id : x, undefined, reload); }
javascript
function(x, reload){ // Get the numeric ID for the module to load. var id = modules[name][1][x]; // If there's a matching module in the testability cache, return it. if (_testability_cache_[x]) return _testability_cache_[x]; // Return recursively... the module's export will be in the cache // after this. return newRequire(id ? id : x, undefined, reload); }
[ "function", "(", "x", ",", "reload", ")", "{", "// Get the numeric ID for the module to load.", "var", "id", "=", "modules", "[", "name", "]", "[", "1", "]", "[", "x", "]", ";", "// If there's a matching module in the testability cache, return it.", "if", "(", "_testability_cache_", "[", "x", "]", ")", "return", "_testability_cache_", "[", "x", "]", ";", "// Return recursively... the module's export will be in the cache ", "// after this.", "return", "newRequire", "(", "id", "?", "id", ":", "x", ",", "undefined", ",", "reload", ")", ";", "}" ]
Create the require function for this module.
[ "Create", "the", "require", "function", "for", "this", "module", "." ]
a8966b3dc49b84e68198e87a7d1ec61b2bddfe23
https://github.com/JoshuaToenyes/browserify-testability/blob/a8966b3dc49b84e68198e87a7d1ec61b2bddfe23/src/prelude.js#L42-L53
55,868
transomjs/transom-mongoose-localuser
lib/localUserMiddleware.js
groupMembershipMiddleware
function groupMembershipMiddleware(groups) { if (typeof groups === 'string') { groups = [groups]; } return function hasGroupMembership(req, res, next) { if (req.locals.user) { const userGroups = req.locals.user.groups || []; for (let group of groups) { if (userGroups.indexOf(group) !== -1) { debug(`User has the '${group}' Group.`); return next(); } } } debug(`User is not a member of one of [${groups.join(',')}] Group(s).`); next(new restifyErrors.ForbiddenError('No execute permissions on endpoint')); } }
javascript
function groupMembershipMiddleware(groups) { if (typeof groups === 'string') { groups = [groups]; } return function hasGroupMembership(req, res, next) { if (req.locals.user) { const userGroups = req.locals.user.groups || []; for (let group of groups) { if (userGroups.indexOf(group) !== -1) { debug(`User has the '${group}' Group.`); return next(); } } } debug(`User is not a member of one of [${groups.join(',')}] Group(s).`); next(new restifyErrors.ForbiddenError('No execute permissions on endpoint')); } }
[ "function", "groupMembershipMiddleware", "(", "groups", ")", "{", "if", "(", "typeof", "groups", "===", "'string'", ")", "{", "groups", "=", "[", "groups", "]", ";", "}", "return", "function", "hasGroupMembership", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "locals", ".", "user", ")", "{", "const", "userGroups", "=", "req", ".", "locals", ".", "user", ".", "groups", "||", "[", "]", ";", "for", "(", "let", "group", "of", "groups", ")", "{", "if", "(", "userGroups", ".", "indexOf", "(", "group", ")", "!==", "-", "1", ")", "{", "debug", "(", "`", "${", "group", "}", "`", ")", ";", "return", "next", "(", ")", ";", "}", "}", "}", "debug", "(", "`", "${", "groups", ".", "join", "(", "','", ")", "}", "`", ")", ";", "next", "(", "new", "restifyErrors", ".", "ForbiddenError", "(", "'No execute permissions on endpoint'", ")", ")", ";", "}", "}" ]
api configs Create a middleware that confirms whether a logged in user has one of the specified Groups. @param {string or Array} groups one or more Group codes that are required for this route.
[ "api", "configs", "Create", "a", "middleware", "that", "confirms", "whether", "a", "logged", "in", "user", "has", "one", "of", "the", "specified", "Groups", "." ]
e610ba9e08c5a117f71a8aac33997f0549df06fe
https://github.com/transomjs/transom-mongoose-localuser/blob/e610ba9e08c5a117f71a8aac33997f0549df06fe/lib/localUserMiddleware.js#L17-L34
55,869
transomjs/transom-mongoose-localuser
lib/localUserMiddleware.js
isLoggedInMiddleware
function isLoggedInMiddleware() { return function isLoggedIn(req, res, next) { const AclUser = mongoose.model("TransomAclUser"); if ((req.headers && req.headers.authorization) || (req.body && req.body.access_token) || (req.query && req.query.access_token)) { // Verify the authorization token or fail. passport.authenticate('bearer', { session: false }, function (err, user, info) { if (err) { return next(err); } if (!user || (info && info.indexOf("invalid_token") >= 0)) { // Something didn't work out. Token Expired / Denied. debug("NOT LoggedIn - Invalid"); return next(new restifyErrors.InvalidCredentialsError("Incorrect or expired credentials")); } else { // Properly authenticated! return next(); } })(req, res, next); } else { // debug("No Authorization header or query access_token. Trying Anonymous."); if (localuser.anonymous !== false) { // Attempt anonymous login, if possible; AclUser.findOne({ 'username': 'anonymous', 'active': true }, function (err, user) { if (err) { return next(err); } if (user) { req.locals = req.locals || {}; req.locals.user = user; return next(); } // Oh no, not authenticated debug("No bearer token provided or query access_token. No Anonymous user available."); return next(new restifyErrors.InvalidCredentialsError("No bearer token provided or query access_token. No Anonymous user available.")); }); } else { debug("No bearer token provided or query access_token."); return next(new restifyErrors.InvalidCredentialsError("No bearer token provided or query access_token.")); } } } }
javascript
function isLoggedInMiddleware() { return function isLoggedIn(req, res, next) { const AclUser = mongoose.model("TransomAclUser"); if ((req.headers && req.headers.authorization) || (req.body && req.body.access_token) || (req.query && req.query.access_token)) { // Verify the authorization token or fail. passport.authenticate('bearer', { session: false }, function (err, user, info) { if (err) { return next(err); } if (!user || (info && info.indexOf("invalid_token") >= 0)) { // Something didn't work out. Token Expired / Denied. debug("NOT LoggedIn - Invalid"); return next(new restifyErrors.InvalidCredentialsError("Incorrect or expired credentials")); } else { // Properly authenticated! return next(); } })(req, res, next); } else { // debug("No Authorization header or query access_token. Trying Anonymous."); if (localuser.anonymous !== false) { // Attempt anonymous login, if possible; AclUser.findOne({ 'username': 'anonymous', 'active': true }, function (err, user) { if (err) { return next(err); } if (user) { req.locals = req.locals || {}; req.locals.user = user; return next(); } // Oh no, not authenticated debug("No bearer token provided or query access_token. No Anonymous user available."); return next(new restifyErrors.InvalidCredentialsError("No bearer token provided or query access_token. No Anonymous user available.")); }); } else { debug("No bearer token provided or query access_token."); return next(new restifyErrors.InvalidCredentialsError("No bearer token provided or query access_token.")); } } } }
[ "function", "isLoggedInMiddleware", "(", ")", "{", "return", "function", "isLoggedIn", "(", "req", ",", "res", ",", "next", ")", "{", "const", "AclUser", "=", "mongoose", ".", "model", "(", "\"TransomAclUser\"", ")", ";", "if", "(", "(", "req", ".", "headers", "&&", "req", ".", "headers", ".", "authorization", ")", "||", "(", "req", ".", "body", "&&", "req", ".", "body", ".", "access_token", ")", "||", "(", "req", ".", "query", "&&", "req", ".", "query", ".", "access_token", ")", ")", "{", "// Verify the authorization token or fail.", "passport", ".", "authenticate", "(", "'bearer'", ",", "{", "session", ":", "false", "}", ",", "function", "(", "err", ",", "user", ",", "info", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "if", "(", "!", "user", "||", "(", "info", "&&", "info", ".", "indexOf", "(", "\"invalid_token\"", ")", ">=", "0", ")", ")", "{", "// Something didn't work out. Token Expired / Denied.", "debug", "(", "\"NOT LoggedIn - Invalid\"", ")", ";", "return", "next", "(", "new", "restifyErrors", ".", "InvalidCredentialsError", "(", "\"Incorrect or expired credentials\"", ")", ")", ";", "}", "else", "{", "// Properly authenticated!", "return", "next", "(", ")", ";", "}", "}", ")", "(", "req", ",", "res", ",", "next", ")", ";", "}", "else", "{", "// debug(\"No Authorization header or query access_token. Trying Anonymous.\");", "if", "(", "localuser", ".", "anonymous", "!==", "false", ")", "{", "// Attempt anonymous login, if possible;", "AclUser", ".", "findOne", "(", "{", "'username'", ":", "'anonymous'", ",", "'active'", ":", "true", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "if", "(", "user", ")", "{", "req", ".", "locals", "=", "req", ".", "locals", "||", "{", "}", ";", "req", ".", "locals", ".", "user", "=", "user", ";", "return", "next", "(", ")", ";", "}", "// Oh no, not authenticated", "debug", "(", "\"No bearer token provided or query access_token. No Anonymous user available.\"", ")", ";", "return", "next", "(", "new", "restifyErrors", ".", "InvalidCredentialsError", "(", "\"No bearer token provided or query access_token. No Anonymous user available.\"", ")", ")", ";", "}", ")", ";", "}", "else", "{", "debug", "(", "\"No bearer token provided or query access_token.\"", ")", ";", "return", "next", "(", "new", "restifyErrors", ".", "InvalidCredentialsError", "(", "\"No bearer token provided or query access_token.\"", ")", ")", ";", "}", "}", "}", "}" ]
Create middleware that requires a valid Bearer token.
[ "Create", "middleware", "that", "requires", "a", "valid", "Bearer", "token", "." ]
e610ba9e08c5a117f71a8aac33997f0549df06fe
https://github.com/transomjs/transom-mongoose-localuser/blob/e610ba9e08c5a117f71a8aac33997f0549df06fe/lib/localUserMiddleware.js#L39-L86
55,870
themouette/screenstory
lib/runner/runMocha.js
prepareContext
function prepareContext(screenstoryRunner, options, context, file, mochaRunner) { debug('prepare context for %s', file); var wdOptions = { desiredCapabilities: options.wdCapabilities, host: options.wdHost, port: options.wdPort, user: options.wdUsername, key: options.wdKey, logLevel: options.wdLogLevel }; context.url = options.url; // @return webdriverio context.newClient = function () { // init client var client = webdriverio.remote(wdOptions) .init(); // fix resolution if (options.resolution) { client .setViewportSize(options.resolution, true); } // add extensions screenstoryRunner.extensions.forEach(function (extension) { Object.keys(extension).forEach(function (key) { debug('+ Add command "%s"', key); client.addCommand(key, extension[key]); }); }); screenstoryRunner.emitAsync('new client', client, function (err) { if (err) { debug('While executing "new client" event, following error occured'); debug(err); console.log(err); } }); return client; }; // add globals options.global.forEach(function (globalName) { addGlobal(context, globalName); }); }
javascript
function prepareContext(screenstoryRunner, options, context, file, mochaRunner) { debug('prepare context for %s', file); var wdOptions = { desiredCapabilities: options.wdCapabilities, host: options.wdHost, port: options.wdPort, user: options.wdUsername, key: options.wdKey, logLevel: options.wdLogLevel }; context.url = options.url; // @return webdriverio context.newClient = function () { // init client var client = webdriverio.remote(wdOptions) .init(); // fix resolution if (options.resolution) { client .setViewportSize(options.resolution, true); } // add extensions screenstoryRunner.extensions.forEach(function (extension) { Object.keys(extension).forEach(function (key) { debug('+ Add command "%s"', key); client.addCommand(key, extension[key]); }); }); screenstoryRunner.emitAsync('new client', client, function (err) { if (err) { debug('While executing "new client" event, following error occured'); debug(err); console.log(err); } }); return client; }; // add globals options.global.forEach(function (globalName) { addGlobal(context, globalName); }); }
[ "function", "prepareContext", "(", "screenstoryRunner", ",", "options", ",", "context", ",", "file", ",", "mochaRunner", ")", "{", "debug", "(", "'prepare context for %s'", ",", "file", ")", ";", "var", "wdOptions", "=", "{", "desiredCapabilities", ":", "options", ".", "wdCapabilities", ",", "host", ":", "options", ".", "wdHost", ",", "port", ":", "options", ".", "wdPort", ",", "user", ":", "options", ".", "wdUsername", ",", "key", ":", "options", ".", "wdKey", ",", "logLevel", ":", "options", ".", "wdLogLevel", "}", ";", "context", ".", "url", "=", "options", ".", "url", ";", "// @return webdriverio", "context", ".", "newClient", "=", "function", "(", ")", "{", "// init client", "var", "client", "=", "webdriverio", ".", "remote", "(", "wdOptions", ")", ".", "init", "(", ")", ";", "// fix resolution", "if", "(", "options", ".", "resolution", ")", "{", "client", ".", "setViewportSize", "(", "options", ".", "resolution", ",", "true", ")", ";", "}", "// add extensions", "screenstoryRunner", ".", "extensions", ".", "forEach", "(", "function", "(", "extension", ")", "{", "Object", ".", "keys", "(", "extension", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "debug", "(", "'+ Add command \"%s\"'", ",", "key", ")", ";", "client", ".", "addCommand", "(", "key", ",", "extension", "[", "key", "]", ")", ";", "}", ")", ";", "}", ")", ";", "screenstoryRunner", ".", "emitAsync", "(", "'new client'", ",", "client", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "'While executing \"new client\" event, following error occured'", ")", ";", "debug", "(", "err", ")", ";", "console", ".", "log", "(", "err", ")", ";", "}", "}", ")", ";", "return", "client", ";", "}", ";", "// add globals", "options", ".", "global", ".", "forEach", "(", "function", "(", "globalName", ")", "{", "addGlobal", "(", "context", ",", "globalName", ")", ";", "}", ")", ";", "}" ]
prepare context before given file runs see mocha runner `pre-require` event
[ "prepare", "context", "before", "given", "file", "runs", "see", "mocha", "runner", "pre", "-", "require", "event" ]
0c847f5514a55e7c2f59728565591d4bb5788915
https://github.com/themouette/screenstory/blob/0c847f5514a55e7c2f59728565591d4bb5788915/lib/runner/runMocha.js#L64-L111
55,871
airbrite/muni
router.js
function(req, requiredParams) { // Find all missing parameters var missingParams = []; _.forEach(requiredParams, function(requiredParam) { if ( Mixins.isNullOrUndefined(req.params && req.params[requiredParam]) && Mixins.isNullOrUndefined(req.query && req.query[requiredParam]) && Mixins.isNullOrUndefined(req.body && req.body[requiredParam]) ) { missingParams.push(requiredParam); } }); return missingParams; }
javascript
function(req, requiredParams) { // Find all missing parameters var missingParams = []; _.forEach(requiredParams, function(requiredParam) { if ( Mixins.isNullOrUndefined(req.params && req.params[requiredParam]) && Mixins.isNullOrUndefined(req.query && req.query[requiredParam]) && Mixins.isNullOrUndefined(req.body && req.body[requiredParam]) ) { missingParams.push(requiredParam); } }); return missingParams; }
[ "function", "(", "req", ",", "requiredParams", ")", "{", "// Find all missing parameters", "var", "missingParams", "=", "[", "]", ";", "_", ".", "forEach", "(", "requiredParams", ",", "function", "(", "requiredParam", ")", "{", "if", "(", "Mixins", ".", "isNullOrUndefined", "(", "req", ".", "params", "&&", "req", ".", "params", "[", "requiredParam", "]", ")", "&&", "Mixins", ".", "isNullOrUndefined", "(", "req", ".", "query", "&&", "req", ".", "query", "[", "requiredParam", "]", ")", "&&", "Mixins", ".", "isNullOrUndefined", "(", "req", ".", "body", "&&", "req", ".", "body", "[", "requiredParam", "]", ")", ")", "{", "missingParams", ".", "push", "(", "requiredParam", ")", ";", "}", "}", ")", ";", "return", "missingParams", ";", "}" ]
Return a list of missing parameters that were required @param {Object} req @param {Array} requiredParams @return {Array}
[ "Return", "a", "list", "of", "missing", "parameters", "that", "were", "required" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/router.js#L43-L56
55,872
airbrite/muni
router.js
function(missingParams) { var errParts = []; missingParams = _.map(missingParams, function(missingParam) { return '`' + missingParam + '`'; }); errParts.push("Missing"); errParts.push(missingParams.join(', ')); errParts.push("parameter(s)."); return new MuniError(errParts.join(' '), 400); }
javascript
function(missingParams) { var errParts = []; missingParams = _.map(missingParams, function(missingParam) { return '`' + missingParam + '`'; }); errParts.push("Missing"); errParts.push(missingParams.join(', ')); errParts.push("parameter(s)."); return new MuniError(errParts.join(' '), 400); }
[ "function", "(", "missingParams", ")", "{", "var", "errParts", "=", "[", "]", ";", "missingParams", "=", "_", ".", "map", "(", "missingParams", ",", "function", "(", "missingParam", ")", "{", "return", "'`'", "+", "missingParam", "+", "'`'", ";", "}", ")", ";", "errParts", ".", "push", "(", "\"Missing\"", ")", ";", "errParts", ".", "push", "(", "missingParams", ".", "join", "(", "', '", ")", ")", ";", "errParts", ".", "push", "(", "\"parameter(s).\"", ")", ";", "return", "new", "MuniError", "(", "errParts", ".", "join", "(", "' '", ")", ",", "400", ")", ";", "}" ]
Return an Error containing missing parameters that were required @param {Array} missingParams @return {MuniError}
[ "Return", "an", "Error", "containing", "missing", "parameters", "that", "were", "required" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/router.js#L65-L74
55,873
airbrite/muni
router.js
function() { // Used for de-duping var paths = {}; // Each controller has a `routes` object // Connect all routes defined in controllers _.forEach(router.controllers, function(controller) { _.forEach(controller.routes, function(route, method) { _.forEach(route, function(routeOptions, path) { // If path/method has already been defined, skip if (paths[path] === method) { debug.warn('Skipping duplicate route: [%s] %s', method, path); return; } // If no route action is defined, skip if (!routeOptions.action) { debug.warn('No action defined for route: [%s] %s', method, path); return; } // Setup controller scoped middleware // These apply to all routes in the controller var pre = _.invokeMap(controller.pre, 'bind', controller) || []; var before = _.invokeMap(controller.before, 'bind', controller) || []; var after = _.invokeMap(controller.after, 'bind', controller) || []; // Setup route scoped middleware // These apply only to this route var middleware = routeOptions.middleware || []; // Build the route handler (callback) var handler = router._buildHandler(controller, routeOptions); // Connect the route router[method](path, pre, middleware, before, handler, after); // Add route to set of connected routes router.routes.push({ url: router.url, method: method, path: path }); // Use for de-duping paths[path] = method; }); }); }); // Debug logging _.forEach(router.routes, function(route) { debug.info('Route [%s] %s', route.method, route.url + route.path); }); }
javascript
function() { // Used for de-duping var paths = {}; // Each controller has a `routes` object // Connect all routes defined in controllers _.forEach(router.controllers, function(controller) { _.forEach(controller.routes, function(route, method) { _.forEach(route, function(routeOptions, path) { // If path/method has already been defined, skip if (paths[path] === method) { debug.warn('Skipping duplicate route: [%s] %s', method, path); return; } // If no route action is defined, skip if (!routeOptions.action) { debug.warn('No action defined for route: [%s] %s', method, path); return; } // Setup controller scoped middleware // These apply to all routes in the controller var pre = _.invokeMap(controller.pre, 'bind', controller) || []; var before = _.invokeMap(controller.before, 'bind', controller) || []; var after = _.invokeMap(controller.after, 'bind', controller) || []; // Setup route scoped middleware // These apply only to this route var middleware = routeOptions.middleware || []; // Build the route handler (callback) var handler = router._buildHandler(controller, routeOptions); // Connect the route router[method](path, pre, middleware, before, handler, after); // Add route to set of connected routes router.routes.push({ url: router.url, method: method, path: path }); // Use for de-duping paths[path] = method; }); }); }); // Debug logging _.forEach(router.routes, function(route) { debug.info('Route [%s] %s', route.method, route.url + route.path); }); }
[ "function", "(", ")", "{", "// Used for de-duping", "var", "paths", "=", "{", "}", ";", "// Each controller has a `routes` object", "// Connect all routes defined in controllers", "_", ".", "forEach", "(", "router", ".", "controllers", ",", "function", "(", "controller", ")", "{", "_", ".", "forEach", "(", "controller", ".", "routes", ",", "function", "(", "route", ",", "method", ")", "{", "_", ".", "forEach", "(", "route", ",", "function", "(", "routeOptions", ",", "path", ")", "{", "// If path/method has already been defined, skip", "if", "(", "paths", "[", "path", "]", "===", "method", ")", "{", "debug", ".", "warn", "(", "'Skipping duplicate route: [%s] %s'", ",", "method", ",", "path", ")", ";", "return", ";", "}", "// If no route action is defined, skip", "if", "(", "!", "routeOptions", ".", "action", ")", "{", "debug", ".", "warn", "(", "'No action defined for route: [%s] %s'", ",", "method", ",", "path", ")", ";", "return", ";", "}", "// Setup controller scoped middleware", "// These apply to all routes in the controller", "var", "pre", "=", "_", ".", "invokeMap", "(", "controller", ".", "pre", ",", "'bind'", ",", "controller", ")", "||", "[", "]", ";", "var", "before", "=", "_", ".", "invokeMap", "(", "controller", ".", "before", ",", "'bind'", ",", "controller", ")", "||", "[", "]", ";", "var", "after", "=", "_", ".", "invokeMap", "(", "controller", ".", "after", ",", "'bind'", ",", "controller", ")", "||", "[", "]", ";", "// Setup route scoped middleware", "// These apply only to this route", "var", "middleware", "=", "routeOptions", ".", "middleware", "||", "[", "]", ";", "// Build the route handler (callback)", "var", "handler", "=", "router", ".", "_buildHandler", "(", "controller", ",", "routeOptions", ")", ";", "// Connect the route", "router", "[", "method", "]", "(", "path", ",", "pre", ",", "middleware", ",", "before", ",", "handler", ",", "after", ")", ";", "// Add route to set of connected routes", "router", ".", "routes", ".", "push", "(", "{", "url", ":", "router", ".", "url", ",", "method", ":", "method", ",", "path", ":", "path", "}", ")", ";", "// Use for de-duping", "paths", "[", "path", "]", "=", "method", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "// Debug logging", "_", ".", "forEach", "(", "router", ".", "routes", ",", "function", "(", "route", ")", "{", "debug", ".", "info", "(", "'Route [%s] %s'", ",", "route", ".", "method", ",", "route", ".", "url", "+", "route", ".", "path", ")", ";", "}", ")", ";", "}" ]
Iterates over all controllers and connects any routes defined
[ "Iterates", "over", "all", "controllers", "and", "connects", "any", "routes", "defined" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/router.js#L115-L169
55,874
mrduncan/ranger
lib/ranger/client.js
toRooms
function toRooms(data) { var i, rooms; rooms = []; for (i = 0; i < data.rooms.length; i++) { rooms.push(new Room(connection, data.rooms[i])); } return rooms; }
javascript
function toRooms(data) { var i, rooms; rooms = []; for (i = 0; i < data.rooms.length; i++) { rooms.push(new Room(connection, data.rooms[i])); } return rooms; }
[ "function", "toRooms", "(", "data", ")", "{", "var", "i", ",", "rooms", ";", "rooms", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "data", ".", "rooms", ".", "length", ";", "i", "++", ")", "{", "rooms", ".", "push", "(", "new", "Room", "(", "connection", ",", "data", ".", "rooms", "[", "i", "]", ")", ")", ";", "}", "return", "rooms", ";", "}" ]
Convert the specified response data into an array of Rooms. @param {Object} data The server response data. @return {Array.<Room>} An array of Rooms.
[ "Convert", "the", "specified", "response", "data", "into", "an", "array", "of", "Rooms", "." ]
6fed6e8353512e9b4985f6080aa6f2cc1363e840
https://github.com/mrduncan/ranger/blob/6fed6e8353512e9b4985f6080aa6f2cc1363e840/lib/ranger/client.js#L19-L28
55,875
SideCatt/SideCat
src/js/lib/react.js
parseActiveChildren
function parseActiveChildren(values, active) { let activeChild = false; const activeValues = values.map(function (val) { const childrenTraversed = (val.children && parseActiveChildren(val.children, active)); const isActive = val.value === active || Boolean(childrenTraversed && childrenTraversed.hasActiveChild); if (isActive) { activeChild = true; } const activatedChild = Object.assign({}, val, { active: isActive }); if (val.children) { activatedChild.children = childrenTraversed.children; } return activatedChild; }); return { children: activeValues, hasActiveChild: activeChild }; }
javascript
function parseActiveChildren(values, active) { let activeChild = false; const activeValues = values.map(function (val) { const childrenTraversed = (val.children && parseActiveChildren(val.children, active)); const isActive = val.value === active || Boolean(childrenTraversed && childrenTraversed.hasActiveChild); if (isActive) { activeChild = true; } const activatedChild = Object.assign({}, val, { active: isActive }); if (val.children) { activatedChild.children = childrenTraversed.children; } return activatedChild; }); return { children: activeValues, hasActiveChild: activeChild }; }
[ "function", "parseActiveChildren", "(", "values", ",", "active", ")", "{", "let", "activeChild", "=", "false", ";", "const", "activeValues", "=", "values", ".", "map", "(", "function", "(", "val", ")", "{", "const", "childrenTraversed", "=", "(", "val", ".", "children", "&&", "parseActiveChildren", "(", "val", ".", "children", ",", "active", ")", ")", ";", "const", "isActive", "=", "val", ".", "value", "===", "active", "||", "Boolean", "(", "childrenTraversed", "&&", "childrenTraversed", ".", "hasActiveChild", ")", ";", "if", "(", "isActive", ")", "{", "activeChild", "=", "true", ";", "}", "const", "activatedChild", "=", "Object", ".", "assign", "(", "{", "}", ",", "val", ",", "{", "active", ":", "isActive", "}", ")", ";", "if", "(", "val", ".", "children", ")", "{", "activatedChild", ".", "children", "=", "childrenTraversed", ".", "children", ";", "}", "return", "activatedChild", ";", "}", ")", ";", "return", "{", "children", ":", "activeValues", ",", "hasActiveChild", ":", "activeChild", "}", ";", "}" ]
Class handles boilerplate javascript to attribute active state to a data array. This does not handle array of active values. Recursively searches children. @param {array} values Array of data for iteratively rendered child components @param {string} active Active element of child components @returns {object} Returns hasActiveChild and children properties
[ "Class", "handles", "boilerplate", "javascript", "to", "attribute", "active", "state", "to", "a", "data", "array", ".", "This", "does", "not", "handle", "array", "of", "active", "values", ".", "Recursively", "searches", "children", "." ]
40ecf15eb9a26a3ad94cc771c235508e654b51c0
https://github.com/SideCatt/SideCat/blob/40ecf15eb9a26a3ad94cc771c235508e654b51c0/src/js/lib/react.js#L9-L35
55,876
douglasduteil/gesalakacula
lib/gesalakacula.js
queueLauncherKey
function queueLauncherKey(asKey, subprocess) { return function processTarget(targets) { return Object .keys(targets) .map(function (targetName) { return subprocess(targets[targetName]) .map(function (launcher) { launcher[asKey] = targetName; return launcher; }); }) .reduce(function (a, b) { // flatten return a.concat(b); }, []); }; }
javascript
function queueLauncherKey(asKey, subprocess) { return function processTarget(targets) { return Object .keys(targets) .map(function (targetName) { return subprocess(targets[targetName]) .map(function (launcher) { launcher[asKey] = targetName; return launcher; }); }) .reduce(function (a, b) { // flatten return a.concat(b); }, []); }; }
[ "function", "queueLauncherKey", "(", "asKey", ",", "subprocess", ")", "{", "return", "function", "processTarget", "(", "targets", ")", "{", "return", "Object", ".", "keys", "(", "targets", ")", ".", "map", "(", "function", "(", "targetName", ")", "{", "return", "subprocess", "(", "targets", "[", "targetName", "]", ")", ".", "map", "(", "function", "(", "launcher", ")", "{", "launcher", "[", "asKey", "]", "=", "targetName", ";", "return", "launcher", ";", "}", ")", ";", "}", ")", ".", "reduce", "(", "function", "(", "a", ",", "b", ")", "{", "// flatten", "return", "a", ".", "concat", "(", "b", ")", ";", "}", ",", "[", "]", ")", ";", "}", ";", "}" ]
Generic in queue key assignment. @description This will assign the in the result fo a sub process. @param {String} asKey the name to use in the launcher environment for the current key in the target. @param {Function} subprocess process to use as launcher environment @returns {Function} A target processor.
[ "Generic", "in", "queue", "key", "assignment", "." ]
86e117807a2ab86b1e72972c3371ec92f14c9353
https://github.com/douglasduteil/gesalakacula/blob/86e117807a2ab86b1e72972c3371ec92f14c9353/lib/gesalakacula.js#L71-L87
55,877
douglasduteil/gesalakacula
lib/gesalakacula.js
generateSauceLabsKarmaCustomLaunchers
function generateSauceLabsKarmaCustomLaunchers(config) { return processPlatform(config) .reduce(function (memo, launcher) { var launcherName = [ SAUCELABS_PREFIX, shorty(launcher.platform), shorty(launcher.browserName), launcher.version ].join('_'); memo[launcherName] = launcher; return memo; }, {}); //// function shorty(str) { return str.indexOf(' ') === -1 ? // capitaliseFirstLetter str.charAt(0).toUpperCase() + str.slice(1) : // abbr str.match(/\b(\w)/g).join('').toUpperCase(); } }
javascript
function generateSauceLabsKarmaCustomLaunchers(config) { return processPlatform(config) .reduce(function (memo, launcher) { var launcherName = [ SAUCELABS_PREFIX, shorty(launcher.platform), shorty(launcher.browserName), launcher.version ].join('_'); memo[launcherName] = launcher; return memo; }, {}); //// function shorty(str) { return str.indexOf(' ') === -1 ? // capitaliseFirstLetter str.charAt(0).toUpperCase() + str.slice(1) : // abbr str.match(/\b(\w)/g).join('').toUpperCase(); } }
[ "function", "generateSauceLabsKarmaCustomLaunchers", "(", "config", ")", "{", "return", "processPlatform", "(", "config", ")", ".", "reduce", "(", "function", "(", "memo", ",", "launcher", ")", "{", "var", "launcherName", "=", "[", "SAUCELABS_PREFIX", ",", "shorty", "(", "launcher", ".", "platform", ")", ",", "shorty", "(", "launcher", ".", "browserName", ")", ",", "launcher", ".", "version", "]", ".", "join", "(", "'_'", ")", ";", "memo", "[", "launcherName", "]", "=", "launcher", ";", "return", "memo", ";", "}", ",", "{", "}", ")", ";", "////", "function", "shorty", "(", "str", ")", "{", "return", "str", ".", "indexOf", "(", "' '", ")", "===", "-", "1", "?", "// capitaliseFirstLetter", "str", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "str", ".", "slice", "(", "1", ")", ":", "// abbr", "str", ".", "match", "(", "/", "\\b(\\w)", "/", "g", ")", ".", "join", "(", "''", ")", ".", "toUpperCase", "(", ")", ";", "}", "}" ]
Generate SauceLabs Karma "customLaunchers". @param {Object} config The abstract full config to process @returns {Object} The karma ready "customLaunchers" object.
[ "Generate", "SauceLabs", "Karma", "customLaunchers", "." ]
86e117807a2ab86b1e72972c3371ec92f14c9353
https://github.com/douglasduteil/gesalakacula/blob/86e117807a2ab86b1e72972c3371ec92f14c9353/lib/gesalakacula.js#L94-L116
55,878
electrovir/arff-toolkit
arffToolkit.js
separateMultiClassArffData
function separateMultiClassArffData(arffData, outputAttributes) { if (!Array.isArray(outputAttributes) || outputAttributes.length === 0) { outputAttributes = [arffData.attributes[arffData.attributes.length - 1]]; } outputAttributes.forEach((attribute) => { if (arffData.types[attribute].hasOwnProperty('oneof') && arffData.types[attribute].oneof.length > 2) { arffData.attributes.splice(arffData.attributes.indexOf(attribute), 1); outputAttributes.splice(arffData.attributes.indexOf(attribute), 1); arffData.types[attribute].oneof.forEach((oneofValue, oneofIndex) => { const newAttributeName = attribute + '__' + oneofValue; outputAttributes.push(newAttributeName); arffData.attributes.push(newAttributeName); arffData.types[newAttributeName] = {type: 'nominal', oneof: ['n', 'y']}; arffData.data.forEach((entry) => { if (entry[attribute] == oneofIndex) { entry[newAttributeName] = 1; } else { entry[newAttributeName] = 0; } }); }); } }); return outputAttributes; }
javascript
function separateMultiClassArffData(arffData, outputAttributes) { if (!Array.isArray(outputAttributes) || outputAttributes.length === 0) { outputAttributes = [arffData.attributes[arffData.attributes.length - 1]]; } outputAttributes.forEach((attribute) => { if (arffData.types[attribute].hasOwnProperty('oneof') && arffData.types[attribute].oneof.length > 2) { arffData.attributes.splice(arffData.attributes.indexOf(attribute), 1); outputAttributes.splice(arffData.attributes.indexOf(attribute), 1); arffData.types[attribute].oneof.forEach((oneofValue, oneofIndex) => { const newAttributeName = attribute + '__' + oneofValue; outputAttributes.push(newAttributeName); arffData.attributes.push(newAttributeName); arffData.types[newAttributeName] = {type: 'nominal', oneof: ['n', 'y']}; arffData.data.forEach((entry) => { if (entry[attribute] == oneofIndex) { entry[newAttributeName] = 1; } else { entry[newAttributeName] = 0; } }); }); } }); return outputAttributes; }
[ "function", "separateMultiClassArffData", "(", "arffData", ",", "outputAttributes", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "outputAttributes", ")", "||", "outputAttributes", ".", "length", "===", "0", ")", "{", "outputAttributes", "=", "[", "arffData", ".", "attributes", "[", "arffData", ".", "attributes", ".", "length", "-", "1", "]", "]", ";", "}", "outputAttributes", ".", "forEach", "(", "(", "attribute", ")", "=>", "{", "if", "(", "arffData", ".", "types", "[", "attribute", "]", ".", "hasOwnProperty", "(", "'oneof'", ")", "&&", "arffData", ".", "types", "[", "attribute", "]", ".", "oneof", ".", "length", ">", "2", ")", "{", "arffData", ".", "attributes", ".", "splice", "(", "arffData", ".", "attributes", ".", "indexOf", "(", "attribute", ")", ",", "1", ")", ";", "outputAttributes", ".", "splice", "(", "arffData", ".", "attributes", ".", "indexOf", "(", "attribute", ")", ",", "1", ")", ";", "arffData", ".", "types", "[", "attribute", "]", ".", "oneof", ".", "forEach", "(", "(", "oneofValue", ",", "oneofIndex", ")", "=>", "{", "const", "newAttributeName", "=", "attribute", "+", "'__'", "+", "oneofValue", ";", "outputAttributes", ".", "push", "(", "newAttributeName", ")", ";", "arffData", ".", "attributes", ".", "push", "(", "newAttributeName", ")", ";", "arffData", ".", "types", "[", "newAttributeName", "]", "=", "{", "type", ":", "'nominal'", ",", "oneof", ":", "[", "'n'", ",", "'y'", "]", "}", ";", "arffData", ".", "data", ".", "forEach", "(", "(", "entry", ")", "=>", "{", "if", "(", "entry", "[", "attribute", "]", "==", "oneofIndex", ")", "{", "entry", "[", "newAttributeName", "]", "=", "1", ";", "}", "else", "{", "entry", "[", "newAttributeName", "]", "=", "0", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "outputAttributes", ";", "}" ]
this mutates arffData
[ "this", "mutates", "arffData" ]
82edbacf84cc8acf347256c7d65f12688f91e439
https://github.com/electrovir/arff-toolkit/blob/82edbacf84cc8acf347256c7d65f12688f91e439/arffToolkit.js#L34-L67
55,879
electrovir/arff-toolkit
arffToolkit.js
loadArff
function loadArff(fileName, callback) { ARFF.load(fileName, (error, data) => { if (error) { throw new Error(filename + error); } callback(data); }); return 'THIS IS ASYNCHRONOUS'; }
javascript
function loadArff(fileName, callback) { ARFF.load(fileName, (error, data) => { if (error) { throw new Error(filename + error); } callback(data); }); return 'THIS IS ASYNCHRONOUS'; }
[ "function", "loadArff", "(", "fileName", ",", "callback", ")", "{", "ARFF", ".", "load", "(", "fileName", ",", "(", "error", ",", "data", ")", "=>", "{", "if", "(", "error", ")", "{", "throw", "new", "Error", "(", "filename", "+", "error", ")", ";", "}", "callback", "(", "data", ")", ";", "}", ")", ";", "return", "'THIS IS ASYNCHRONOUS'", ";", "}" ]
just a wrapper to make it easier to read ARFF files
[ "just", "a", "wrapper", "to", "make", "it", "easier", "to", "read", "ARFF", "files" ]
82edbacf84cc8acf347256c7d65f12688f91e439
https://github.com/electrovir/arff-toolkit/blob/82edbacf84cc8acf347256c7d65f12688f91e439/arffToolkit.js#L166-L175
55,880
dizmo/functions-random
dist/lib/index.js
random
function random() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var range = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 36; return String.random(length, range); }
javascript
function random() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var range = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 36; return String.random(length, range); }
[ "function", "random", "(", ")", "{", "var", "length", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "0", ";", "var", "range", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "36", ";", "return", "String", ".", "random", "(", "length", ",", "range", ")", ";", "}" ]
Returns a random string for the provided length and range. @param length of returned string in [0..8] @param range of characters in [2..36] @returns a random string
[ "Returns", "a", "random", "string", "for", "the", "provided", "length", "and", "range", "." ]
480c9ff22622842ecaa4c034c61f342a6ae14fc6
https://github.com/dizmo/functions-random/blob/480c9ff22622842ecaa4c034c61f342a6ae14fc6/dist/lib/index.js#L13-L18
55,881
sackio/pa1d
lib/providers/braintree.js
function(obj, name, callback){ if (!obj) return Belt.noop; var s = _.pick(obj, B._api_objects[name + 's']); var stream = B._gateway[name].search(function(search){ _.each(s, function(v, k){ if (_.isObject(v)) return search[k].call(search)[v.op](v.val, v.val2); return search[k].call(search).is(v); }); }) , results = [] , err; stream.on('data', function(r){ return results.push(r); }); stream.on('error', function(e){ return err = e; }); return stream.on('end', function(){ return callback(err, results); }); }
javascript
function(obj, name, callback){ if (!obj) return Belt.noop; var s = _.pick(obj, B._api_objects[name + 's']); var stream = B._gateway[name].search(function(search){ _.each(s, function(v, k){ if (_.isObject(v)) return search[k].call(search)[v.op](v.val, v.val2); return search[k].call(search).is(v); }); }) , results = [] , err; stream.on('data', function(r){ return results.push(r); }); stream.on('error', function(e){ return err = e; }); return stream.on('end', function(){ return callback(err, results); }); }
[ "function", "(", "obj", ",", "name", ",", "callback", ")", "{", "if", "(", "!", "obj", ")", "return", "Belt", ".", "noop", ";", "var", "s", "=", "_", ".", "pick", "(", "obj", ",", "B", ".", "_api_objects", "[", "name", "+", "'s'", "]", ")", ";", "var", "stream", "=", "B", ".", "_gateway", "[", "name", "]", ".", "search", "(", "function", "(", "search", ")", "{", "_", ".", "each", "(", "s", ",", "function", "(", "v", ",", "k", ")", "{", "if", "(", "_", ".", "isObject", "(", "v", ")", ")", "return", "search", "[", "k", "]", ".", "call", "(", "search", ")", "[", "v", ".", "op", "]", "(", "v", ".", "val", ",", "v", ".", "val2", ")", ";", "return", "search", "[", "k", "]", ".", "call", "(", "search", ")", ".", "is", "(", "v", ")", ";", "}", ")", ";", "}", ")", ",", "results", "=", "[", "]", ",", "err", ";", "stream", ".", "on", "(", "'data'", ",", "function", "(", "r", ")", "{", "return", "results", ".", "push", "(", "r", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "return", "err", "=", "e", ";", "}", ")", ";", "return", "stream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "return", "callback", "(", "err", ",", "results", ")", ";", "}", ")", ";", "}" ]
return function with searching criteria
[ "return", "function", "with", "searching", "criteria" ]
fc981f086434045d8eed50f631645558ef212507
https://github.com/sackio/pa1d/blob/fc981f086434045d8eed50f631645558ef212507/lib/providers/braintree.js#L84-L108
55,882
victorherraiz/xcatalog
index.js
xcatalog
function xcatalog(id) { const definition = definitions.get(id); if (!definition) { throw new TypeError("No definition for: " + id); } if (!definition.fac) { definition.fac = build(definition, definition.dep.map(xcatalog)); } return definition.fac(); }
javascript
function xcatalog(id) { const definition = definitions.get(id); if (!definition) { throw new TypeError("No definition for: " + id); } if (!definition.fac) { definition.fac = build(definition, definition.dep.map(xcatalog)); } return definition.fac(); }
[ "function", "xcatalog", "(", "id", ")", "{", "const", "definition", "=", "definitions", ".", "get", "(", "id", ")", ";", "if", "(", "!", "definition", ")", "{", "throw", "new", "TypeError", "(", "\"No definition for: \"", "+", "id", ")", ";", "}", "if", "(", "!", "definition", ".", "fac", ")", "{", "definition", ".", "fac", "=", "build", "(", "definition", ",", "definition", ".", "dep", ".", "map", "(", "xcatalog", ")", ")", ";", "}", "return", "definition", ".", "fac", "(", ")", ";", "}" ]
Retrieves a stored reference @param {string} id - xcatalog id item
[ "Retrieves", "a", "stored", "reference" ]
1b91bf6f75ce57bf1abbc9f15c56d53f3dc8e966
https://github.com/victorherraiz/xcatalog/blob/1b91bf6f75ce57bf1abbc9f15c56d53f3dc8e966/index.js#L28-L37
55,883
antonycourtney/tabli-core
lib/js/components/browserConstants.js
initBrowser
function initBrowser() { if (window.chrome) { Object.assign(module.exports, chromeConstants); } else { Object.assign(module.exports, braveConstants); } }
javascript
function initBrowser() { if (window.chrome) { Object.assign(module.exports, chromeConstants); } else { Object.assign(module.exports, braveConstants); } }
[ "function", "initBrowser", "(", ")", "{", "if", "(", "window", ".", "chrome", ")", "{", "Object", ".", "assign", "(", "module", ".", "exports", ",", "chromeConstants", ")", ";", "}", "else", "{", "Object", ".", "assign", "(", "module", ".", "exports", ",", "braveConstants", ")", ";", "}", "}" ]
do browser detection and assign constants to exported bindings. Should only happen once.
[ "do", "browser", "detection", "and", "assign", "constants", "to", "exported", "bindings", "." ]
76cc540891421bc6c8bdcf00f277ebb6e716fdd9
https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/components/browserConstants.js#L11-L17
55,884
AmrEldib/agol-data-faker
build-doc.js
generateCodeDocs
function generateCodeDocs() { config.codeFiles.forEach(function (jsFile) { var jf = [jsFile]; documentation(jf, {}, function (err, result) { documentation.formats.md(result, {}, function (err, md) { // Write to file fs.writeFile(path.resolve(__dirname, config.docFolder + "/" + jsFile + ".md"), md); }); }); }); }
javascript
function generateCodeDocs() { config.codeFiles.forEach(function (jsFile) { var jf = [jsFile]; documentation(jf, {}, function (err, result) { documentation.formats.md(result, {}, function (err, md) { // Write to file fs.writeFile(path.resolve(__dirname, config.docFolder + "/" + jsFile + ".md"), md); }); }); }); }
[ "function", "generateCodeDocs", "(", ")", "{", "config", ".", "codeFiles", ".", "forEach", "(", "function", "(", "jsFile", ")", "{", "var", "jf", "=", "[", "jsFile", "]", ";", "documentation", "(", "jf", ",", "{", "}", ",", "function", "(", "err", ",", "result", ")", "{", "documentation", ".", "formats", ".", "md", "(", "result", ",", "{", "}", ",", "function", "(", "err", ",", "md", ")", "{", "// Write to file", "fs", ".", "writeFile", "(", "path", ".", "resolve", "(", "__dirname", ",", "config", ".", "docFolder", "+", "\"/\"", "+", "jsFile", "+", "\".md\"", ")", ",", "md", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Generate documentation for code files. It reads the JSDoc comments and generate markdown files for them. One markdown file is generated for each code file.
[ "Generate", "documentation", "for", "code", "files", ".", "It", "reads", "the", "JSDoc", "comments", "and", "generate", "markdown", "files", "for", "them", ".", "One", "markdown", "file", "is", "generated", "for", "each", "code", "file", "." ]
9bb7e29698a34effd98afe135d053256050a072e
https://github.com/AmrEldib/agol-data-faker/blob/9bb7e29698a34effd98afe135d053256050a072e/build-doc.js#L9-L19
55,885
ro-ka/stylesheet.js
lib/stylesheet.js
Stylesheet
function Stylesheet() { var styleElement = document.createElement('style'), head = document.getElementsByTagName('head')[0]; head.appendChild(styleElement); // Safari does not see the new stylesheet unless you append something. // However! IE will blow chunks, so ... filter it thusly: if (!window.createPopup) { styleElement.appendChild(document.createTextNode('')); } this.sheet = document.styleSheets[document.styleSheets.length - 1]; }
javascript
function Stylesheet() { var styleElement = document.createElement('style'), head = document.getElementsByTagName('head')[0]; head.appendChild(styleElement); // Safari does not see the new stylesheet unless you append something. // However! IE will blow chunks, so ... filter it thusly: if (!window.createPopup) { styleElement.appendChild(document.createTextNode('')); } this.sheet = document.styleSheets[document.styleSheets.length - 1]; }
[ "function", "Stylesheet", "(", ")", "{", "var", "styleElement", "=", "document", ".", "createElement", "(", "'style'", ")", ",", "head", "=", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ";", "head", ".", "appendChild", "(", "styleElement", ")", ";", "// Safari does not see the new stylesheet unless you append something.", "// However! IE will blow chunks, so ... filter it thusly:", "if", "(", "!", "window", ".", "createPopup", ")", "{", "styleElement", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "''", ")", ")", ";", "}", "this", ".", "sheet", "=", "document", ".", "styleSheets", "[", "document", ".", "styleSheets", ".", "length", "-", "1", "]", ";", "}" ]
Create a new stylesheet
[ "Create", "a", "new", "stylesheet" ]
4f02289b62da5d49d7f001e6934371342e07d4a7
https://github.com/ro-ka/stylesheet.js/blob/4f02289b62da5d49d7f001e6934371342e07d4a7/lib/stylesheet.js#L4-L17
55,886
aliaksandr-master/node-verifier-schema
lib/schema.js
function (validations) { if (!validations) { return this; } if (!this.validations) { this.validations = []; } var that = this; _.isArray(validations) || (validations = [ validations ]); _.each(validations, function (validation) { that.validations.push(validation); }); return this; }
javascript
function (validations) { if (!validations) { return this; } if (!this.validations) { this.validations = []; } var that = this; _.isArray(validations) || (validations = [ validations ]); _.each(validations, function (validation) { that.validations.push(validation); }); return this; }
[ "function", "(", "validations", ")", "{", "if", "(", "!", "validations", ")", "{", "return", "this", ";", "}", "if", "(", "!", "this", ".", "validations", ")", "{", "this", ".", "validations", "=", "[", "]", ";", "}", "var", "that", "=", "this", ";", "_", ".", "isArray", "(", "validations", ")", "||", "(", "validations", "=", "[", "validations", "]", ")", ";", "_", ".", "each", "(", "validations", ",", "function", "(", "validation", ")", "{", "that", ".", "validations", ".", "push", "(", "validation", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
set validate options. can be called several times @method @this {Schema} @param {*} validations - validation options. @returns {Schema} @this
[ "set", "validate", "options", ".", "can", "be", "called", "several", "times" ]
dc49df3c4703928bcfd7447a59cdd70bafac21b0
https://github.com/aliaksandr-master/node-verifier-schema/blob/dc49df3c4703928bcfd7447a59cdd70bafac21b0/lib/schema.js#L102-L120
55,887
aliaksandr-master/node-verifier-schema
lib/schema.js
function (flagOrBuilder) { if (_.isFunction(flagOrBuilder)) { this.object(flagOrBuilder); } if (flagOrBuilder == null || flagOrBuilder) { this.isArray = true; } else { delete this.isArray; } return this; }
javascript
function (flagOrBuilder) { if (_.isFunction(flagOrBuilder)) { this.object(flagOrBuilder); } if (flagOrBuilder == null || flagOrBuilder) { this.isArray = true; } else { delete this.isArray; } return this; }
[ "function", "(", "flagOrBuilder", ")", "{", "if", "(", "_", ".", "isFunction", "(", "flagOrBuilder", ")", ")", "{", "this", ".", "object", "(", "flagOrBuilder", ")", ";", "}", "if", "(", "flagOrBuilder", "==", "null", "||", "flagOrBuilder", ")", "{", "this", ".", "isArray", "=", "true", ";", "}", "else", "{", "delete", "this", ".", "isArray", ";", "}", "return", "this", ";", "}" ]
set nested fields builder with type array @method @this {Schema} @param {?Boolean} [flagOrBuilder] @throws {TypeError} If nested is not a function if specified @returns {Schema} @this
[ "set", "nested", "fields", "builder", "with", "type", "array" ]
dc49df3c4703928bcfd7447a59cdd70bafac21b0
https://github.com/aliaksandr-master/node-verifier-schema/blob/dc49df3c4703928bcfd7447a59cdd70bafac21b0/lib/schema.js#L146-L158
55,888
aliaksandr-master/node-verifier-schema
lib/schema.js
function (schema, process) { var that = this; if (!(schema instanceof Schema)) { throw new Error('first argument must be instance of Schema'); } if (process) { var r = process.call(this, schema); if (r != null && !r) { return this; } } _.each(schema.fields, function (fieldSchema, fieldName) { that.field(fieldName).like(fieldSchema, process); }); if (process) { return this; } _.each(schema, function (value, key) { if (/^(_.*|fields)$/.test(key)) { return; } that[key] = _.cloneDeep(value); }); return this; }
javascript
function (schema, process) { var that = this; if (!(schema instanceof Schema)) { throw new Error('first argument must be instance of Schema'); } if (process) { var r = process.call(this, schema); if (r != null && !r) { return this; } } _.each(schema.fields, function (fieldSchema, fieldName) { that.field(fieldName).like(fieldSchema, process); }); if (process) { return this; } _.each(schema, function (value, key) { if (/^(_.*|fields)$/.test(key)) { return; } that[key] = _.cloneDeep(value); }); return this; }
[ "function", "(", "schema", ",", "process", ")", "{", "var", "that", "=", "this", ";", "if", "(", "!", "(", "schema", "instanceof", "Schema", ")", ")", "{", "throw", "new", "Error", "(", "'first argument must be instance of Schema'", ")", ";", "}", "if", "(", "process", ")", "{", "var", "r", "=", "process", ".", "call", "(", "this", ",", "schema", ")", ";", "if", "(", "r", "!=", "null", "&&", "!", "r", ")", "{", "return", "this", ";", "}", "}", "_", ".", "each", "(", "schema", ".", "fields", ",", "function", "(", "fieldSchema", ",", "fieldName", ")", "{", "that", ".", "field", "(", "fieldName", ")", ".", "like", "(", "fieldSchema", ",", "process", ")", ";", "}", ")", ";", "if", "(", "process", ")", "{", "return", "this", ";", "}", "_", ".", "each", "(", "schema", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "/", "^(_.*|fields)$", "/", ".", "test", "(", "key", ")", ")", "{", "return", ";", "}", "that", "[", "key", "]", "=", "_", ".", "cloneDeep", "(", "value", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
clone schema to this schema object @method @this {Schema} @param {Schema} schema @param {processFunction} [process] @returns {Schema} new object (clone)
[ "clone", "schema", "to", "this", "schema", "object" ]
dc49df3c4703928bcfd7447a59cdd70bafac21b0
https://github.com/aliaksandr-master/node-verifier-schema/blob/dc49df3c4703928bcfd7447a59cdd70bafac21b0/lib/schema.js#L214-L246
55,889
aliaksandr-master/node-verifier-schema
lib/schema.js
function (name, validation) { if (name == null && validation == null) { delete this.isRequired; return this; } return this.field(name).validate(validation); }
javascript
function (name, validation) { if (name == null && validation == null) { delete this.isRequired; return this; } return this.field(name).validate(validation); }
[ "function", "(", "name", ",", "validation", ")", "{", "if", "(", "name", "==", "null", "&&", "validation", "==", "null", ")", "{", "delete", "this", ".", "isRequired", ";", "return", "this", ";", "}", "return", "this", ".", "field", "(", "name", ")", ".", "validate", "(", "validation", ")", ";", "}" ]
add new required nested schema by construct @method @this {Schema} @param {?String} [name] - field name. @param {?*} [validation] - validation options. @returns {Schema}
[ "add", "new", "required", "nested", "schema", "by", "construct" ]
dc49df3c4703928bcfd7447a59cdd70bafac21b0
https://github.com/aliaksandr-master/node-verifier-schema/blob/dc49df3c4703928bcfd7447a59cdd70bafac21b0/lib/schema.js#L277-L284
55,890
aliaksandr-master/node-verifier-schema
lib/schema.js
function (name, validation) { if (name == null && validation == null) { this.isRequired = false; return this; } return this.field(name).validate(validation).optional(); }
javascript
function (name, validation) { if (name == null && validation == null) { this.isRequired = false; return this; } return this.field(name).validate(validation).optional(); }
[ "function", "(", "name", ",", "validation", ")", "{", "if", "(", "name", "==", "null", "&&", "validation", "==", "null", ")", "{", "this", ".", "isRequired", "=", "false", ";", "return", "this", ";", "}", "return", "this", ".", "field", "(", "name", ")", ".", "validate", "(", "validation", ")", ".", "optional", "(", ")", ";", "}" ]
add new optional nested schema by construct @method @this {Schema} @param {?String} [name] - field name. @param {?*} [validation] - validation options. @returns {Schema}
[ "add", "new", "optional", "nested", "schema", "by", "construct" ]
dc49df3c4703928bcfd7447a59cdd70bafac21b0
https://github.com/aliaksandr-master/node-verifier-schema/blob/dc49df3c4703928bcfd7447a59cdd70bafac21b0/lib/schema.js#L297-L304
55,891
thomasdobber/grunt-remfallback
tasks/remfallback.js
preciseRound
function preciseRound(num) { var decimals = options.round ? 0 : 1; return Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals); }
javascript
function preciseRound(num) { var decimals = options.round ? 0 : 1; return Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals); }
[ "function", "preciseRound", "(", "num", ")", "{", "var", "decimals", "=", "options", ".", "round", "?", "0", ":", "1", ";", "return", "Math", ".", "round", "(", "num", "*", "Math", ".", "pow", "(", "10", ",", "decimals", ")", ")", "/", "Math", ".", "pow", "(", "10", ",", "decimals", ")", ";", "}" ]
round floating numbers
[ "round", "floating", "numbers" ]
4c1559e214720dbc3b8899f4affdf5564bb9ebc5
https://github.com/thomasdobber/grunt-remfallback/blob/4c1559e214720dbc3b8899f4affdf5564bb9ebc5/tasks/remfallback.js#L53-L56
55,892
thomasdobber/grunt-remfallback
tasks/remfallback.js
remToPx
function remToPx(remArray) { var pxArray = remArray.map(function(v) { if (regexCalc.test(v)) { return v; } else if (regexRem.test(v)) { // this one is needed to split properties like '2rem/1.5' var restValue = ''; if (/\//.test(v)) { restValue = v.match(/\/.*/); } // replace 'rem' and anything that comes after it, we'll repair this later var unitlessValue = v.replace(/rem.*/, ''); var pxValue = preciseRound(unitlessValue * rootSize) + 'px'; var newValue = restValue ? pxValue + restValue : pxValue; remFound++; return newValue; } return v; }).join(' '); return pxArray; }
javascript
function remToPx(remArray) { var pxArray = remArray.map(function(v) { if (regexCalc.test(v)) { return v; } else if (regexRem.test(v)) { // this one is needed to split properties like '2rem/1.5' var restValue = ''; if (/\//.test(v)) { restValue = v.match(/\/.*/); } // replace 'rem' and anything that comes after it, we'll repair this later var unitlessValue = v.replace(/rem.*/, ''); var pxValue = preciseRound(unitlessValue * rootSize) + 'px'; var newValue = restValue ? pxValue + restValue : pxValue; remFound++; return newValue; } return v; }).join(' '); return pxArray; }
[ "function", "remToPx", "(", "remArray", ")", "{", "var", "pxArray", "=", "remArray", ".", "map", "(", "function", "(", "v", ")", "{", "if", "(", "regexCalc", ".", "test", "(", "v", ")", ")", "{", "return", "v", ";", "}", "else", "if", "(", "regexRem", ".", "test", "(", "v", ")", ")", "{", "// this one is needed to split properties like '2rem/1.5'", "var", "restValue", "=", "''", ";", "if", "(", "/", "\\/", "/", ".", "test", "(", "v", ")", ")", "{", "restValue", "=", "v", ".", "match", "(", "/", "\\/.*", "/", ")", ";", "}", "// replace 'rem' and anything that comes after it, we'll repair this later", "var", "unitlessValue", "=", "v", ".", "replace", "(", "/", "rem.*", "/", ",", "''", ")", ";", "var", "pxValue", "=", "preciseRound", "(", "unitlessValue", "*", "rootSize", ")", "+", "'px'", ";", "var", "newValue", "=", "restValue", "?", "pxValue", "+", "restValue", ":", "pxValue", ";", "remFound", "++", ";", "return", "newValue", ";", "}", "return", "v", ";", "}", ")", ".", "join", "(", "' '", ")", ";", "return", "pxArray", ";", "}" ]
convert rem to px
[ "convert", "rem", "to", "px" ]
4c1559e214720dbc3b8899f4affdf5564bb9ebc5
https://github.com/thomasdobber/grunt-remfallback/blob/4c1559e214720dbc3b8899f4affdf5564bb9ebc5/tasks/remfallback.js#L72-L97
55,893
thomasdobber/grunt-remfallback
tasks/remfallback.js
createBaseSize
function createBaseSize(value) { if (/px/.test(value)) { return value.replace(/px/, ''); } if (/em|rem/.test(value)) { return value.replace(/em|rem/, '') * 16; } if (/%/.test(value)) { return value.replace(/%/, '')/100 * 16; } }
javascript
function createBaseSize(value) { if (/px/.test(value)) { return value.replace(/px/, ''); } if (/em|rem/.test(value)) { return value.replace(/em|rem/, '') * 16; } if (/%/.test(value)) { return value.replace(/%/, '')/100 * 16; } }
[ "function", "createBaseSize", "(", "value", ")", "{", "if", "(", "/", "px", "/", ".", "test", "(", "value", ")", ")", "{", "return", "value", ".", "replace", "(", "/", "px", "/", ",", "''", ")", ";", "}", "if", "(", "/", "em|rem", "/", ".", "test", "(", "value", ")", ")", "{", "return", "value", ".", "replace", "(", "/", "em|rem", "/", ",", "''", ")", "*", "16", ";", "}", "if", "(", "/", "%", "/", ".", "test", "(", "value", ")", ")", "{", "return", "value", ".", "replace", "(", "/", "%", "/", ",", "''", ")", "/", "100", "*", "16", ";", "}", "}" ]
create a base value from px,em,rem or percentage
[ "create", "a", "base", "value", "from", "px", "em", "rem", "or", "percentage" ]
4c1559e214720dbc3b8899f4affdf5564bb9ebc5
https://github.com/thomasdobber/grunt-remfallback/blob/4c1559e214720dbc3b8899f4affdf5564bb9ebc5/tasks/remfallback.js#L111-L123
55,894
thomasdobber/grunt-remfallback
tasks/remfallback.js
findRoot
function findRoot(r) { r.selectors.forEach(function(s) { // look for 'html' selectors if (regexHtml.test(s)) { r.declarations.forEach(function(d) { var foundSize = false; // look for the 'font' property if (d.property === 'font' && regexFont.test(d.value)) { foundSize = d.value.match(regexFont)[1]; } // look for the 'font-size' property else if (d.property === 'font-size') { foundSize = d.value; } // update root size if new one is found if (foundSize) { rootSize = createBaseSize(foundSize); } }); } }); }
javascript
function findRoot(r) { r.selectors.forEach(function(s) { // look for 'html' selectors if (regexHtml.test(s)) { r.declarations.forEach(function(d) { var foundSize = false; // look for the 'font' property if (d.property === 'font' && regexFont.test(d.value)) { foundSize = d.value.match(regexFont)[1]; } // look for the 'font-size' property else if (d.property === 'font-size') { foundSize = d.value; } // update root size if new one is found if (foundSize) { rootSize = createBaseSize(foundSize); } }); } }); }
[ "function", "findRoot", "(", "r", ")", "{", "r", ".", "selectors", ".", "forEach", "(", "function", "(", "s", ")", "{", "// look for 'html' selectors", "if", "(", "regexHtml", ".", "test", "(", "s", ")", ")", "{", "r", ".", "declarations", ".", "forEach", "(", "function", "(", "d", ")", "{", "var", "foundSize", "=", "false", ";", "// look for the 'font' property", "if", "(", "d", ".", "property", "===", "'font'", "&&", "regexFont", ".", "test", "(", "d", ".", "value", ")", ")", "{", "foundSize", "=", "d", ".", "value", ".", "match", "(", "regexFont", ")", "[", "1", "]", ";", "}", "// look for the 'font-size' property", "else", "if", "(", "d", ".", "property", "===", "'font-size'", ")", "{", "foundSize", "=", "d", ".", "value", ";", "}", "// update root size if new one is found", "if", "(", "foundSize", ")", "{", "rootSize", "=", "createBaseSize", "(", "foundSize", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
find root font-size declarations
[ "find", "root", "font", "-", "size", "declarations" ]
4c1559e214720dbc3b8899f4affdf5564bb9ebc5
https://github.com/thomasdobber/grunt-remfallback/blob/4c1559e214720dbc3b8899f4affdf5564bb9ebc5/tasks/remfallback.js#L126-L152
55,895
thomasdobber/grunt-remfallback
tasks/remfallback.js
findRems
function findRems(rule) { for (var i = 0; i < rule.declarations.length; i++) { var declaration = rule.declarations[i]; // grab values that contain 'rem' if (declaration.type === 'declaration' && isSupported(declaration) && regexRem.test(declaration.value)) { var pxValues = remToPx(declaration.value.split(/\s(?![^\(\)]*\))/)); if (options.replace) { declaration.value = pxValues; } else { var fallback = clone(declaration); fallback.value = pxValues; rule.declarations.splice(i, 0, fallback); } } } }
javascript
function findRems(rule) { for (var i = 0; i < rule.declarations.length; i++) { var declaration = rule.declarations[i]; // grab values that contain 'rem' if (declaration.type === 'declaration' && isSupported(declaration) && regexRem.test(declaration.value)) { var pxValues = remToPx(declaration.value.split(/\s(?![^\(\)]*\))/)); if (options.replace) { declaration.value = pxValues; } else { var fallback = clone(declaration); fallback.value = pxValues; rule.declarations.splice(i, 0, fallback); } } } }
[ "function", "findRems", "(", "rule", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rule", ".", "declarations", ".", "length", ";", "i", "++", ")", "{", "var", "declaration", "=", "rule", ".", "declarations", "[", "i", "]", ";", "// grab values that contain 'rem'", "if", "(", "declaration", ".", "type", "===", "'declaration'", "&&", "isSupported", "(", "declaration", ")", "&&", "regexRem", ".", "test", "(", "declaration", ".", "value", ")", ")", "{", "var", "pxValues", "=", "remToPx", "(", "declaration", ".", "value", ".", "split", "(", "/", "\\s(?![^\\(\\)]*\\))", "/", ")", ")", ";", "if", "(", "options", ".", "replace", ")", "{", "declaration", ".", "value", "=", "pxValues", ";", "}", "else", "{", "var", "fallback", "=", "clone", "(", "declaration", ")", ";", "fallback", ".", "value", "=", "pxValues", ";", "rule", ".", "declarations", ".", "splice", "(", "i", ",", "0", ",", "fallback", ")", ";", "}", "}", "}", "}" ]
look for rem values
[ "look", "for", "rem", "values" ]
4c1559e214720dbc3b8899f4affdf5564bb9ebc5
https://github.com/thomasdobber/grunt-remfallback/blob/4c1559e214720dbc3b8899f4affdf5564bb9ebc5/tasks/remfallback.js#L155-L175
55,896
char1e5/ot-webdriverjs
lib/webdriver/promise.js
propagateError
function propagateError(error) { flow.pendingRejections_ += 1; return flow.timer.setTimeout(function() { flow.pendingRejections_ -= 1; flow.abortFrame_(error); }, 0); }
javascript
function propagateError(error) { flow.pendingRejections_ += 1; return flow.timer.setTimeout(function() { flow.pendingRejections_ -= 1; flow.abortFrame_(error); }, 0); }
[ "function", "propagateError", "(", "error", ")", "{", "flow", ".", "pendingRejections_", "+=", "1", ";", "return", "flow", ".", "timer", ".", "setTimeout", "(", "function", "(", ")", "{", "flow", ".", "pendingRejections_", "-=", "1", ";", "flow", ".", "abortFrame_", "(", "error", ")", ";", "}", ",", "0", ")", ";", "}" ]
Propagates an unhandled rejection to the parent ControlFlow in a future turn of the JavaScript event loop. @param {*} error The error value to report. @return {number} The key for the registered timeout.
[ "Propagates", "an", "unhandled", "rejection", "to", "the", "parent", "ControlFlow", "in", "a", "future", "turn", "of", "the", "JavaScript", "event", "loop", "." ]
5fc8cabcb481602673f1d47cdf544d681c35f784
https://github.com/char1e5/ot-webdriverjs/blob/5fc8cabcb481602673f1d47cdf544d681c35f784/lib/webdriver/promise.js#L345-L351
55,897
char1e5/ot-webdriverjs
lib/webdriver/promise.js
then
function then(opt_callback, opt_errback) { // Avoid unnecessary allocations if we weren't given any callback functions. if (!opt_callback && !opt_errback) { return promise; } // The moment a listener is registered, we consider this deferred to be // handled; the callback must handle any rejection errors. handled = true; if (pendingRejectionKey) { flow.pendingRejections_ -= 1; flow.timer.clearTimeout(pendingRejectionKey); } var deferred = new webdriver.promise.Deferred(cancel, flow); var listener = { callback: opt_callback, errback: opt_errback, fulfill: deferred.fulfill, reject: deferred.reject }; if (state == webdriver.promise.Deferred.State_.PENDING || state == webdriver.promise.Deferred.State_.BLOCKED) { listeners.push(listener); } else { notify(listener); } return deferred.promise; }
javascript
function then(opt_callback, opt_errback) { // Avoid unnecessary allocations if we weren't given any callback functions. if (!opt_callback && !opt_errback) { return promise; } // The moment a listener is registered, we consider this deferred to be // handled; the callback must handle any rejection errors. handled = true; if (pendingRejectionKey) { flow.pendingRejections_ -= 1; flow.timer.clearTimeout(pendingRejectionKey); } var deferred = new webdriver.promise.Deferred(cancel, flow); var listener = { callback: opt_callback, errback: opt_errback, fulfill: deferred.fulfill, reject: deferred.reject }; if (state == webdriver.promise.Deferred.State_.PENDING || state == webdriver.promise.Deferred.State_.BLOCKED) { listeners.push(listener); } else { notify(listener); } return deferred.promise; }
[ "function", "then", "(", "opt_callback", ",", "opt_errback", ")", "{", "// Avoid unnecessary allocations if we weren't given any callback functions.", "if", "(", "!", "opt_callback", "&&", "!", "opt_errback", ")", "{", "return", "promise", ";", "}", "// The moment a listener is registered, we consider this deferred to be", "// handled; the callback must handle any rejection errors.", "handled", "=", "true", ";", "if", "(", "pendingRejectionKey", ")", "{", "flow", ".", "pendingRejections_", "-=", "1", ";", "flow", ".", "timer", ".", "clearTimeout", "(", "pendingRejectionKey", ")", ";", "}", "var", "deferred", "=", "new", "webdriver", ".", "promise", ".", "Deferred", "(", "cancel", ",", "flow", ")", ";", "var", "listener", "=", "{", "callback", ":", "opt_callback", ",", "errback", ":", "opt_errback", ",", "fulfill", ":", "deferred", ".", "fulfill", ",", "reject", ":", "deferred", ".", "reject", "}", ";", "if", "(", "state", "==", "webdriver", ".", "promise", ".", "Deferred", ".", "State_", ".", "PENDING", "||", "state", "==", "webdriver", ".", "promise", ".", "Deferred", ".", "State_", ".", "BLOCKED", ")", "{", "listeners", ".", "push", "(", "listener", ")", ";", "}", "else", "{", "notify", "(", "listener", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Registers a callback on this Deferred. @param {?(function(T): (R|webdriver.promise.Promise.<R>))=} opt_callback . @param {?(function(*): (R|webdriver.promise.Promise.<R>))=} opt_errback . @return {!webdriver.promise.Promise.<R>} A new promise representing the result of the callback. @template R @see webdriver.promise.Promise#then
[ "Registers", "a", "callback", "on", "this", "Deferred", "." ]
5fc8cabcb481602673f1d47cdf544d681c35f784
https://github.com/char1e5/ot-webdriverjs/blob/5fc8cabcb481602673f1d47cdf544d681c35f784/lib/webdriver/promise.js#L388-L418
55,898
davemedema/grunt-funky-tag
tasks/tag.js
function() { var highestTag = '0.0.0'; var tags = exec('git tag'); if (tags.code !== 0) return highestTag; tags = tags.output.split('\n'); tags.forEach(function(tag) { tag = semver.valid(tag); if (tag && (!highestTag || semver.gt(tag, highestTag))) { highestTag = tag; } }); return highestTag; }
javascript
function() { var highestTag = '0.0.0'; var tags = exec('git tag'); if (tags.code !== 0) return highestTag; tags = tags.output.split('\n'); tags.forEach(function(tag) { tag = semver.valid(tag); if (tag && (!highestTag || semver.gt(tag, highestTag))) { highestTag = tag; } }); return highestTag; }
[ "function", "(", ")", "{", "var", "highestTag", "=", "'0.0.0'", ";", "var", "tags", "=", "exec", "(", "'git tag'", ")", ";", "if", "(", "tags", ".", "code", "!==", "0", ")", "return", "highestTag", ";", "tags", "=", "tags", ".", "output", ".", "split", "(", "'\\n'", ")", ";", "tags", ".", "forEach", "(", "function", "(", "tag", ")", "{", "tag", "=", "semver", ".", "valid", "(", "tag", ")", ";", "if", "(", "tag", "&&", "(", "!", "highestTag", "||", "semver", ".", "gt", "(", "tag", ",", "highestTag", ")", ")", ")", "{", "highestTag", "=", "tag", ";", "}", "}", ")", ";", "return", "highestTag", ";", "}" ]
Returns the highest tag in the repo. @return {String}
[ "Returns", "the", "highest", "tag", "in", "the", "repo", "." ]
a930fd8054246494d4c1298f41f12a530158957b
https://github.com/davemedema/grunt-funky-tag/blob/a930fd8054246494d4c1298f41f12a530158957b/tasks/tag.js#L39-L54
55,899
joekarl/fastsync
fastsync.js
makeChainedWaterfallCallback
function makeChainedWaterfallCallback(i, fns, cb) { return function() { var args = Array.prototype.slice.call(arguments); if (args[0]) { //ie. we had an error return cb(args[0]); } if (fns[i + 1]) { //remove error arg args.shift(); args.push(makeChainedWaterfallCallback(i + 1, fns, cb)); return fns[i + 1].apply(null, args); } else { return cb.apply(null, args); } }; }
javascript
function makeChainedWaterfallCallback(i, fns, cb) { return function() { var args = Array.prototype.slice.call(arguments); if (args[0]) { //ie. we had an error return cb(args[0]); } if (fns[i + 1]) { //remove error arg args.shift(); args.push(makeChainedWaterfallCallback(i + 1, fns, cb)); return fns[i + 1].apply(null, args); } else { return cb.apply(null, args); } }; }
[ "function", "makeChainedWaterfallCallback", "(", "i", ",", "fns", ",", "cb", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "if", "(", "args", "[", "0", "]", ")", "{", "//ie. we had an error", "return", "cb", "(", "args", "[", "0", "]", ")", ";", "}", "if", "(", "fns", "[", "i", "+", "1", "]", ")", "{", "//remove error arg", "args", ".", "shift", "(", ")", ";", "args", ".", "push", "(", "makeChainedWaterfallCallback", "(", "i", "+", "1", ",", "fns", ",", "cb", ")", ")", ";", "return", "fns", "[", "i", "+", "1", "]", ".", "apply", "(", "null", ",", "args", ")", ";", "}", "else", "{", "return", "cb", ".", "apply", "(", "null", ",", "args", ")", ";", "}", "}", ";", "}" ]
Create a function that will call the next function in a chain with the results of the original function until the chain is finished
[ "Create", "a", "function", "that", "will", "call", "the", "next", "function", "in", "a", "chain", "with", "the", "results", "of", "the", "original", "function", "until", "the", "chain", "is", "finished" ]
b2a81cb5990e15c3f8bfab6efd7856ae4d51b9d4
https://github.com/joekarl/fastsync/blob/b2a81cb5990e15c3f8bfab6efd7856ae4d51b9d4/fastsync.js#L120-L136