id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
45,000
bonesoul/node-hpool-web
public/js/plugins/input-mask/jquery.inputmask.js
shiftL
function shiftL(start, end, c, maskJumps) { var buffer = getActiveBuffer(); if (maskJumps !== false) //jumping over nonmask position while (!isMask(start) && start - 1 >= 0) start--; for (var i = start; i < end && i < getMaskLength() ; i++) { if (isMask(i)) { setReTargetPlaceHolder(buffer, i); var j = seekNext(i); var p = getBufferElement(buffer, j); if (p != getPlaceHolder(j)) { if (j < getMaskLength() && isValid(i, p, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) { setBufferElement(buffer, i, p, true); } else { if (isMask(i)) break; } } } else { setReTargetPlaceHolder(buffer, i); } } if (c != undefined) setBufferElement(buffer, seekPrevious(end), c); if (getActiveMaskSet()["greedy"] == false) { var trbuffer = truncateInput(buffer.join('')).split(''); buffer.length = trbuffer.length; for (var i = 0, bl = buffer.length; i < bl; i++) { buffer[i] = trbuffer[i]; } if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice(); } return start; //return the used start position }
javascript
function shiftL(start, end, c, maskJumps) { var buffer = getActiveBuffer(); if (maskJumps !== false) //jumping over nonmask position while (!isMask(start) && start - 1 >= 0) start--; for (var i = start; i < end && i < getMaskLength() ; i++) { if (isMask(i)) { setReTargetPlaceHolder(buffer, i); var j = seekNext(i); var p = getBufferElement(buffer, j); if (p != getPlaceHolder(j)) { if (j < getMaskLength() && isValid(i, p, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) { setBufferElement(buffer, i, p, true); } else { if (isMask(i)) break; } } } else { setReTargetPlaceHolder(buffer, i); } } if (c != undefined) setBufferElement(buffer, seekPrevious(end), c); if (getActiveMaskSet()["greedy"] == false) { var trbuffer = truncateInput(buffer.join('')).split(''); buffer.length = trbuffer.length; for (var i = 0, bl = buffer.length; i < bl; i++) { buffer[i] = trbuffer[i]; } if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice(); } return start; //return the used start position }
[ "function", "shiftL", "(", "start", ",", "end", ",", "c", ",", "maskJumps", ")", "{", "var", "buffer", "=", "getActiveBuffer", "(", ")", ";", "if", "(", "maskJumps", "!==", "false", ")", "//jumping over nonmask position", "while", "(", "!", "isMask", "(", "start", ")", "&&", "start", "-", "1", ">=", "0", ")", "start", "--", ";", "for", "(", "var", "i", "=", "start", ";", "i", "<", "end", "&&", "i", "<", "getMaskLength", "(", ")", ";", "i", "++", ")", "{", "if", "(", "isMask", "(", "i", ")", ")", "{", "setReTargetPlaceHolder", "(", "buffer", ",", "i", ")", ";", "var", "j", "=", "seekNext", "(", "i", ")", ";", "var", "p", "=", "getBufferElement", "(", "buffer", ",", "j", ")", ";", "if", "(", "p", "!=", "getPlaceHolder", "(", "j", ")", ")", "{", "if", "(", "j", "<", "getMaskLength", "(", ")", "&&", "isValid", "(", "i", ",", "p", ",", "true", ")", "!==", "false", "&&", "getActiveTests", "(", ")", "[", "determineTestPosition", "(", "i", ")", "]", ".", "def", "==", "getActiveTests", "(", ")", "[", "determineTestPosition", "(", "j", ")", "]", ".", "def", ")", "{", "setBufferElement", "(", "buffer", ",", "i", ",", "p", ",", "true", ")", ";", "}", "else", "{", "if", "(", "isMask", "(", "i", ")", ")", "break", ";", "}", "}", "}", "else", "{", "setReTargetPlaceHolder", "(", "buffer", ",", "i", ")", ";", "}", "}", "if", "(", "c", "!=", "undefined", ")", "setBufferElement", "(", "buffer", ",", "seekPrevious", "(", "end", ")", ",", "c", ")", ";", "if", "(", "getActiveMaskSet", "(", ")", "[", "\"greedy\"", "]", "==", "false", ")", "{", "var", "trbuffer", "=", "truncateInput", "(", "buffer", ".", "join", "(", "''", ")", ")", ".", "split", "(", "''", ")", ";", "buffer", ".", "length", "=", "trbuffer", ".", "length", ";", "for", "(", "var", "i", "=", "0", ",", "bl", "=", "buffer", ".", "length", ";", "i", "<", "bl", ";", "i", "++", ")", "{", "buffer", "[", "i", "]", "=", "trbuffer", "[", "i", "]", ";", "}", "if", "(", "buffer", ".", "length", "==", "0", ")", "getActiveMaskSet", "(", ")", "[", "\"buffer\"", "]", "=", "getActiveBufferTemplate", "(", ")", ".", "slice", "(", ")", ";", "}", "return", "start", ";", "//return the used start position", "}" ]
shift chars to left from start to end and put c at end position if defined
[ "shift", "chars", "to", "left", "from", "start", "to", "end", "and", "put", "c", "at", "end", "position", "if", "defined" ]
3d7749b2bcff8b59243939b5b3da19396c4878ff
https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/input-mask/jquery.inputmask.js#L791-L824
45,001
onecommons/base
lib/createmodel.js
function(){ baseSchema.constructor.apply(this, arguments); //copy base schema var This = this; baseSchema.eachPath(function(key, val) { if (key != '__t') This.paths[key] = val; }); }
javascript
function(){ baseSchema.constructor.apply(this, arguments); //copy base schema var This = this; baseSchema.eachPath(function(key, val) { if (key != '__t') This.paths[key] = val; }); }
[ "function", "(", ")", "{", "baseSchema", ".", "constructor", ".", "apply", "(", "this", ",", "arguments", ")", ";", "//copy base schema", "var", "This", "=", "this", ";", "baseSchema", ".", "eachPath", "(", "function", "(", "key", ",", "val", ")", "{", "if", "(", "key", "!=", "'__t'", ")", "This", ".", "paths", "[", "key", "]", "=", "val", ";", "}", ")", ";", "}" ]
schema is just the definition create a new schema class derived from the base class
[ "schema", "is", "just", "the", "definition", "create", "a", "new", "schema", "class", "derived", "from", "the", "base", "class" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/lib/createmodel.js#L195-L203
45,002
Whitebolt/require-extra
gulpfile.js
tree
function tree(root) { var structure = {}; var _files = fs.readdirSync(root); for(var i=0; i<_files.length; i++) { if ((_files[i] !== '.') && (_files[i] !== '..')) { var stats = fs.statSync(root + '/' + _files[i]); if (stats.isDirectory()) { structure[_files[i]] = tree(root + '/' + _files[i]); } else if (stats.isFile() && xIsJsFile.test(_files[i])) { try { structure[_files[i]] = require(root + '/' + _files[i]); } catch(err) { console.log('Could not load task in: ' + _files[i]); console.error(err); } } } } return structure; }
javascript
function tree(root) { var structure = {}; var _files = fs.readdirSync(root); for(var i=0; i<_files.length; i++) { if ((_files[i] !== '.') && (_files[i] !== '..')) { var stats = fs.statSync(root + '/' + _files[i]); if (stats.isDirectory()) { structure[_files[i]] = tree(root + '/' + _files[i]); } else if (stats.isFile() && xIsJsFile.test(_files[i])) { try { structure[_files[i]] = require(root + '/' + _files[i]); } catch(err) { console.log('Could not load task in: ' + _files[i]); console.error(err); } } } } return structure; }
[ "function", "tree", "(", "root", ")", "{", "var", "structure", "=", "{", "}", ";", "var", "_files", "=", "fs", ".", "readdirSync", "(", "root", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "_files", ".", "length", ";", "i", "++", ")", "{", "if", "(", "(", "_files", "[", "i", "]", "!==", "'.'", ")", "&&", "(", "_files", "[", "i", "]", "!==", "'..'", ")", ")", "{", "var", "stats", "=", "fs", ".", "statSync", "(", "root", "+", "'/'", "+", "_files", "[", "i", "]", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "structure", "[", "_files", "[", "i", "]", "]", "=", "tree", "(", "root", "+", "'/'", "+", "_files", "[", "i", "]", ")", ";", "}", "else", "if", "(", "stats", ".", "isFile", "(", ")", "&&", "xIsJsFile", ".", "test", "(", "_files", "[", "i", "]", ")", ")", "{", "try", "{", "structure", "[", "_files", "[", "i", "]", "]", "=", "require", "(", "root", "+", "'/'", "+", "_files", "[", "i", "]", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "'Could not load task in: '", "+", "_files", "[", "i", "]", ")", ";", "console", ".", "error", "(", "err", ")", ";", "}", "}", "}", "}", "return", "structure", ";", "}" ]
Get a tree structure from a directory with given root. Returns required files if files is .js. @param {string} root The starting directory. @returns {Object} The structure.
[ "Get", "a", "tree", "structure", "from", "a", "directory", "with", "given", "root", ".", "Returns", "required", "files", "if", "files", "is", ".", "js", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/gulpfile.js#L21-L42
45,003
Whitebolt/require-extra
gulpfile.js
_createTasks
function _createTasks(tree, parent, tasks) { parent = parent || ""; tasks = tasks || {}; for (var id in tree) { if (tree[id].deps && tree[id].fn) { tasks[parentId(parent, id)] = tree[id]; } else { _createTasks(tree[id], parentId(parent, id) + ':', tasks) } } return tasks; }
javascript
function _createTasks(tree, parent, tasks) { parent = parent || ""; tasks = tasks || {}; for (var id in tree) { if (tree[id].deps && tree[id].fn) { tasks[parentId(parent, id)] = tree[id]; } else { _createTasks(tree[id], parentId(parent, id) + ':', tasks) } } return tasks; }
[ "function", "_createTasks", "(", "tree", ",", "parent", ",", "tasks", ")", "{", "parent", "=", "parent", "||", "\"\"", ";", "tasks", "=", "tasks", "||", "{", "}", ";", "for", "(", "var", "id", "in", "tree", ")", "{", "if", "(", "tree", "[", "id", "]", ".", "deps", "&&", "tree", "[", "id", "]", ".", "fn", ")", "{", "tasks", "[", "parentId", "(", "parent", ",", "id", ")", "]", "=", "tree", "[", "id", "]", ";", "}", "else", "{", "_createTasks", "(", "tree", "[", "id", "]", ",", "parentId", "(", "parent", ",", "id", ")", "+", "':'", ",", "tasks", ")", "}", "}", "return", "tasks", ";", "}" ]
Given a tree structure, create an object of tasks-ids against task objects. @param {Object} tree The directory tree from tree(). @param {string} [parent=""] The current parent id. @param {Object} [tasks={}] The task object. @returns {Object} The flat object, tasks.
[ "Given", "a", "tree", "structure", "create", "an", "object", "of", "tasks", "-", "ids", "against", "task", "objects", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/gulpfile.js#L63-L76
45,004
Whitebolt/require-extra
gulpfile.js
createTask
function createTask(taskId) { return function (done) { var stream = tasks[taskId].fn(gulp, done); if (stream) { if (stream.on) stream.on('end', done); if (stream.then) stream.then(done); } }; }
javascript
function createTask(taskId) { return function (done) { var stream = tasks[taskId].fn(gulp, done); if (stream) { if (stream.on) stream.on('end', done); if (stream.then) stream.then(done); } }; }
[ "function", "createTask", "(", "taskId", ")", "{", "return", "function", "(", "done", ")", "{", "var", "stream", "=", "tasks", "[", "taskId", "]", ".", "fn", "(", "gulp", ",", "done", ")", ";", "if", "(", "stream", ")", "{", "if", "(", "stream", ".", "on", ")", "stream", ".", "on", "(", "'end'", ",", "done", ")", ";", "if", "(", "stream", ".", "then", ")", "stream", ".", "then", "(", "done", ")", ";", "}", "}", ";", "}" ]
Create a gulp task for the given id. @param {string} taskId Task id to lookup in tasks and assign. @returns {Function} The gulp function.
[ "Create", "a", "gulp", "task", "for", "the", "given", "id", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/gulpfile.js#L94-L102
45,005
EightMedia/collect-components
lib/parser.js
getComponents
function getComponents(templateSrc, filename, options){ var $ = cheerio.load('<div>' + templateSrc + '</div>'); var components = []; var nodeIndex = 0; $('*').contents().map(function(index, $el) { if ($el.type === 'comment') { var src = $el.data.trim(); // keyword check if(isComponentComment(src, options.keyword)){ src = src.substring(options.keyword.length); var meta = YAML.safeLoad(src) || {}; var nodes = getComponentHtml($, $el, $.html($($el).nextAll()), options.keyword, meta); var html = nodes.filter(function(node) { return (node.trim() !== ''); }).join('\n'); var output = render(html, meta, options.block); var component = { meta: meta, file: filename, output: output.trim() }; // push comment return components.push(component); } } }.bind(this)); return components; }
javascript
function getComponents(templateSrc, filename, options){ var $ = cheerio.load('<div>' + templateSrc + '</div>'); var components = []; var nodeIndex = 0; $('*').contents().map(function(index, $el) { if ($el.type === 'comment') { var src = $el.data.trim(); // keyword check if(isComponentComment(src, options.keyword)){ src = src.substring(options.keyword.length); var meta = YAML.safeLoad(src) || {}; var nodes = getComponentHtml($, $el, $.html($($el).nextAll()), options.keyword, meta); var html = nodes.filter(function(node) { return (node.trim() !== ''); }).join('\n'); var output = render(html, meta, options.block); var component = { meta: meta, file: filename, output: output.trim() }; // push comment return components.push(component); } } }.bind(this)); return components; }
[ "function", "getComponents", "(", "templateSrc", ",", "filename", ",", "options", ")", "{", "var", "$", "=", "cheerio", ".", "load", "(", "'<div>'", "+", "templateSrc", "+", "'</div>'", ")", ";", "var", "components", "=", "[", "]", ";", "var", "nodeIndex", "=", "0", ";", "$", "(", "'*'", ")", ".", "contents", "(", ")", ".", "map", "(", "function", "(", "index", ",", "$el", ")", "{", "if", "(", "$el", ".", "type", "===", "'comment'", ")", "{", "var", "src", "=", "$el", ".", "data", ".", "trim", "(", ")", ";", "// keyword check", "if", "(", "isComponentComment", "(", "src", ",", "options", ".", "keyword", ")", ")", "{", "src", "=", "src", ".", "substring", "(", "options", ".", "keyword", ".", "length", ")", ";", "var", "meta", "=", "YAML", ".", "safeLoad", "(", "src", ")", "||", "{", "}", ";", "var", "nodes", "=", "getComponentHtml", "(", "$", ",", "$el", ",", "$", ".", "html", "(", "$", "(", "$el", ")", ".", "nextAll", "(", ")", ")", ",", "options", ".", "keyword", ",", "meta", ")", ";", "var", "html", "=", "nodes", ".", "filter", "(", "function", "(", "node", ")", "{", "return", "(", "node", ".", "trim", "(", ")", "!==", "''", ")", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "var", "output", "=", "render", "(", "html", ",", "meta", ",", "options", ".", "block", ")", ";", "var", "component", "=", "{", "meta", ":", "meta", ",", "file", ":", "filename", ",", "output", ":", "output", ".", "trim", "(", ")", "}", ";", "// push comment", "return", "components", ".", "push", "(", "component", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "components", ";", "}" ]
Returns all components for the given code
[ "Returns", "all", "components", "for", "the", "given", "code" ]
b83f7b3d771ef9393e5cf6ed4807f4caca6bbfa4
https://github.com/EightMedia/collect-components/blob/b83f7b3d771ef9393e5cf6ed4807f4caca6bbfa4/lib/parser.js#L35-L71
45,006
EightMedia/collect-components
lib/parser.js
getComponentHtml
function getComponentHtml($, $el, $siblings, keyword, meta) { var capture = meta.capture; // default to single node if (typeof capture === 'undefined') { capture = 1; } // capture fixed number of nodes if (Number.isInteger(capture) || typeof capture === 'undefined') { return captureNumber($, $siblings, capture); } // capture all if (capture === CAPTURE_ALL) { return captureAll($, $siblings); } // capture section if (capture === CAPTURE_SECTION) { return captureSection($, $el, keyword, meta); } }
javascript
function getComponentHtml($, $el, $siblings, keyword, meta) { var capture = meta.capture; // default to single node if (typeof capture === 'undefined') { capture = 1; } // capture fixed number of nodes if (Number.isInteger(capture) || typeof capture === 'undefined') { return captureNumber($, $siblings, capture); } // capture all if (capture === CAPTURE_ALL) { return captureAll($, $siblings); } // capture section if (capture === CAPTURE_SECTION) { return captureSection($, $el, keyword, meta); } }
[ "function", "getComponentHtml", "(", "$", ",", "$el", ",", "$siblings", ",", "keyword", ",", "meta", ")", "{", "var", "capture", "=", "meta", ".", "capture", ";", "// default to single node", "if", "(", "typeof", "capture", "===", "'undefined'", ")", "{", "capture", "=", "1", ";", "}", "// capture fixed number of nodes", "if", "(", "Number", ".", "isInteger", "(", "capture", ")", "||", "typeof", "capture", "===", "'undefined'", ")", "{", "return", "captureNumber", "(", "$", ",", "$siblings", ",", "capture", ")", ";", "}", "// capture all", "if", "(", "capture", "===", "CAPTURE_ALL", ")", "{", "return", "captureAll", "(", "$", ",", "$siblings", ")", ";", "}", "// capture section", "if", "(", "capture", "===", "CAPTURE_SECTION", ")", "{", "return", "captureSection", "(", "$", ",", "$el", ",", "keyword", ",", "meta", ")", ";", "}", "}" ]
Get html component
[ "Get", "html", "component" ]
b83f7b3d771ef9393e5cf6ed4807f4caca6bbfa4
https://github.com/EightMedia/collect-components/blob/b83f7b3d771ef9393e5cf6ed4807f4caca6bbfa4/lib/parser.js#L78-L101
45,007
EightMedia/collect-components
lib/parser.js
captureNumber
function captureNumber($, $siblings, capture) { var nodes = []; if (typeof capture === 'undefined') { capture = 1; } $($siblings).each(function(n, $node) { if (n < capture) { nodes.push($.html($node)) } }); return nodes; }
javascript
function captureNumber($, $siblings, capture) { var nodes = []; if (typeof capture === 'undefined') { capture = 1; } $($siblings).each(function(n, $node) { if (n < capture) { nodes.push($.html($node)) } }); return nodes; }
[ "function", "captureNumber", "(", "$", ",", "$siblings", ",", "capture", ")", "{", "var", "nodes", "=", "[", "]", ";", "if", "(", "typeof", "capture", "===", "'undefined'", ")", "{", "capture", "=", "1", ";", "}", "$", "(", "$siblings", ")", ".", "each", "(", "function", "(", "n", ",", "$node", ")", "{", "if", "(", "n", "<", "capture", ")", "{", "nodes", ".", "push", "(", "$", ".", "html", "(", "$node", ")", ")", "}", "}", ")", ";", "return", "nodes", ";", "}" ]
Capture fixed number of nodes
[ "Capture", "fixed", "number", "of", "nodes" ]
b83f7b3d771ef9393e5cf6ed4807f4caca6bbfa4
https://github.com/EightMedia/collect-components/blob/b83f7b3d771ef9393e5cf6ed4807f4caca6bbfa4/lib/parser.js#L108-L122
45,008
EightMedia/collect-components
lib/parser.js
getExamples
function getExamples(meta){ var examples = []; if(meta.example){ examples = examples.concat(meta.example); } if(meta.examples){ examples = examples.concat(meta.examples); } return examples; }
javascript
function getExamples(meta){ var examples = []; if(meta.example){ examples = examples.concat(meta.example); } if(meta.examples){ examples = examples.concat(meta.examples); } return examples; }
[ "function", "getExamples", "(", "meta", ")", "{", "var", "examples", "=", "[", "]", ";", "if", "(", "meta", ".", "example", ")", "{", "examples", "=", "examples", ".", "concat", "(", "meta", ".", "example", ")", ";", "}", "if", "(", "meta", ".", "examples", ")", "{", "examples", "=", "examples", ".", "concat", "(", "meta", ".", "examples", ")", ";", "}", "return", "examples", ";", "}" ]
get all examples from the meta object either one or both of meta.example and meta.examples can be given
[ "get", "all", "examples", "from", "the", "meta", "object", "either", "one", "or", "both", "of", "meta", ".", "example", "and", "meta", ".", "examples", "can", "be", "given" ]
b83f7b3d771ef9393e5cf6ed4807f4caca6bbfa4
https://github.com/EightMedia/collect-components/blob/b83f7b3d771ef9393e5cf6ed4807f4caca6bbfa4/lib/parser.js#L210-L219
45,009
haraldrudell/nodegod
lib/masterlink.js
write
function write(data) { if (typeof process.send == 'function') process.send(data) else console.log(emitter.id, 'ipc not available') }
javascript
function write(data) { if (typeof process.send == 'function') process.send(data) else console.log(emitter.id, 'ipc not available') }
[ "function", "write", "(", "data", ")", "{", "if", "(", "typeof", "process", ".", "send", "==", "'function'", ")", "process", ".", "send", "(", "data", ")", "else", "console", ".", "log", "(", "emitter", ".", "id", ",", "'ipc not available'", ")", "}" ]
messages to master process
[ "messages", "to", "master", "process" ]
3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21
https://github.com/haraldrudell/nodegod/blob/3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21/lib/masterlink.js#L32-L35
45,010
odogono/elsinore-js
src/entity_set/async_view.js
createUpdateStream
function createUpdateStream(origin, target, options, completeCb) { // console.log('[EntitySetAsyncView][createUpdateStream]', 'from', origin.cid, 'to', target.cid ); // let source = origin.source(options); // let sink = target.sink({}, completeCb); options = { ...options, emitEntities: true }; let args = [origin.source(options)]; if (options.debug) { args.push( PullMap(val => { let [data, dataOptions] = val; console.log('[EntitySetAsyncView][>]', origin.cid, target.cid, stringify(data)); return val; }) ); } if (options.query) { args.push(QueryFilter(options.query, options)); } args.push(target.sink({ source: origin }, completeCb)); return Pull.apply(null, args); }
javascript
function createUpdateStream(origin, target, options, completeCb) { // console.log('[EntitySetAsyncView][createUpdateStream]', 'from', origin.cid, 'to', target.cid ); // let source = origin.source(options); // let sink = target.sink({}, completeCb); options = { ...options, emitEntities: true }; let args = [origin.source(options)]; if (options.debug) { args.push( PullMap(val => { let [data, dataOptions] = val; console.log('[EntitySetAsyncView][>]', origin.cid, target.cid, stringify(data)); return val; }) ); } if (options.query) { args.push(QueryFilter(options.query, options)); } args.push(target.sink({ source: origin }, completeCb)); return Pull.apply(null, args); }
[ "function", "createUpdateStream", "(", "origin", ",", "target", ",", "options", ",", "completeCb", ")", "{", "// console.log('[EntitySetAsyncView][createUpdateStream]', 'from', origin.cid, 'to', target.cid );", "// let source = origin.source(options);", "// let sink = target.sink({}, completeCb);", "options", "=", "{", "...", "options", ",", "emitEntities", ":", "true", "}", ";", "let", "args", "=", "[", "origin", ".", "source", "(", "options", ")", "]", ";", "if", "(", "options", ".", "debug", ")", "{", "args", ".", "push", "(", "PullMap", "(", "val", "=>", "{", "let", "[", "data", ",", "dataOptions", "]", "=", "val", ";", "console", ".", "log", "(", "'[EntitySetAsyncView][>]'", ",", "origin", ".", "cid", ",", "target", ".", "cid", ",", "stringify", "(", "data", ")", ")", ";", "return", "val", ";", "}", ")", ")", ";", "}", "if", "(", "options", ".", "query", ")", "{", "args", ".", "push", "(", "QueryFilter", "(", "options", ".", "query", ",", "options", ")", ")", ";", "}", "args", ".", "push", "(", "target", ".", "sink", "(", "{", "source", ":", "origin", "}", ",", "completeCb", ")", ")", ";", "return", "Pull", ".", "apply", "(", "null", ",", "args", ")", ";", "}" ]
Creates a pull-stream from the source to the destination @param {*} entitySet @param {*} view
[ "Creates", "a", "pull", "-", "stream", "from", "the", "source", "to", "the", "destination" ]
1ecce67ad0022646419a740def029b1ba92dd558
https://github.com/odogono/elsinore-js/blob/1ecce67ad0022646419a740def029b1ba92dd558/src/entity_set/async_view.js#L89-L114
45,011
vid/SenseBase
util/entrez-esearch.js
search
function search(options, callback) { var queryURI = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=' + options.terms + '&retmode=json&retmax=' + (options.count || 10); utils.retrieve(queryURI, callback); }
javascript
function search(options, callback) { var queryURI = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=' + options.terms + '&retmode=json&retmax=' + (options.count || 10); utils.retrieve(queryURI, callback); }
[ "function", "search", "(", "options", ",", "callback", ")", "{", "var", "queryURI", "=", "'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term='", "+", "options", ".", "terms", "+", "'&retmode=json&retmax='", "+", "(", "options", ".", "count", "||", "10", ")", ";", "utils", ".", "retrieve", "(", "queryURI", ",", "callback", ")", ";", "}" ]
Do the actual search.
[ "Do", "the", "actual", "search", "." ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/util/entrez-esearch.js#L38-L41
45,012
linyngfly/omelo-scheduler
lib/simpleTrigger.js
function(trigger, job){ this.nextTime = (!!trigger.start)?trigger.start:Date.now(); //The rec this.period = (!!trigger.period)?trigger.period:-1; //The running count of the job, -1 means no limit this.count = (!!trigger.count)?trigger.count:-1; this.job = job; }
javascript
function(trigger, job){ this.nextTime = (!!trigger.start)?trigger.start:Date.now(); //The rec this.period = (!!trigger.period)?trigger.period:-1; //The running count of the job, -1 means no limit this.count = (!!trigger.count)?trigger.count:-1; this.job = job; }
[ "function", "(", "trigger", ",", "job", ")", "{", "this", ".", "nextTime", "=", "(", "!", "!", "trigger", ".", "start", ")", "?", "trigger", ".", "start", ":", "Date", ".", "now", "(", ")", ";", "//The rec", "this", ".", "period", "=", "(", "!", "!", "trigger", ".", "period", ")", "?", "trigger", ".", "period", ":", "-", "1", ";", "//The running count of the job, -1 means no limit", "this", ".", "count", "=", "(", "!", "!", "trigger", ".", "count", ")", "?", "trigger", ".", "count", ":", "-", "1", ";", "this", ".", "job", "=", "job", ";", "}" ]
The constructor of simple trigger
[ "The", "constructor", "of", "simple", "trigger" ]
aa7775eb2b8b31160669c8fedccd84e2108797eb
https://github.com/linyngfly/omelo-scheduler/blob/aa7775eb2b8b31160669c8fedccd84e2108797eb/lib/simpleTrigger.js#L9-L19
45,013
gavagai-corp/gavagai-node
lib/RestClient.js
RestClient
function RestClient(apikey, options) { //Required client config if (!apikey) { if (process.env.GAVAGAI_APIKEY) { this.apikey = process.env.GAVAGAI_APIKEY; } else { throw new Error('RestClient requires an apikey set explicitly or via the GAVAGAI_APIKEY environment variable'); } } else { this.apikey = apikey.trim(); } //Optional client config options = options || {}; this.host = options.host || defaultHost; this.apiVersion = options.apiVersion || defaultApiVersion; this.timeout = options.timeout || defaultTimeOut; // Resources this.stories = require('./stories')(this); this.tonality = require('./tonality')(this); this.topics = require('./topics')(this); this.keywords = require('./keywords')(this); this.lexicon = require('./lexicon')(this); }
javascript
function RestClient(apikey, options) { //Required client config if (!apikey) { if (process.env.GAVAGAI_APIKEY) { this.apikey = process.env.GAVAGAI_APIKEY; } else { throw new Error('RestClient requires an apikey set explicitly or via the GAVAGAI_APIKEY environment variable'); } } else { this.apikey = apikey.trim(); } //Optional client config options = options || {}; this.host = options.host || defaultHost; this.apiVersion = options.apiVersion || defaultApiVersion; this.timeout = options.timeout || defaultTimeOut; // Resources this.stories = require('./stories')(this); this.tonality = require('./tonality')(this); this.topics = require('./topics')(this); this.keywords = require('./keywords')(this); this.lexicon = require('./lexicon')(this); }
[ "function", "RestClient", "(", "apikey", ",", "options", ")", "{", "//Required client config", "if", "(", "!", "apikey", ")", "{", "if", "(", "process", ".", "env", ".", "GAVAGAI_APIKEY", ")", "{", "this", ".", "apikey", "=", "process", ".", "env", ".", "GAVAGAI_APIKEY", ";", "}", "else", "{", "throw", "new", "Error", "(", "'RestClient requires an apikey set explicitly or via the GAVAGAI_APIKEY environment variable'", ")", ";", "}", "}", "else", "{", "this", ".", "apikey", "=", "apikey", ".", "trim", "(", ")", ";", "}", "//Optional client config", "options", "=", "options", "||", "{", "}", ";", "this", ".", "host", "=", "options", ".", "host", "||", "defaultHost", ";", "this", ".", "apiVersion", "=", "options", ".", "apiVersion", "||", "defaultApiVersion", ";", "this", ".", "timeout", "=", "options", ".", "timeout", "||", "defaultTimeOut", ";", "// Resources", "this", ".", "stories", "=", "require", "(", "'./stories'", ")", "(", "this", ")", ";", "this", ".", "tonality", "=", "require", "(", "'./tonality'", ")", "(", "this", ")", ";", "this", ".", "topics", "=", "require", "(", "'./topics'", ")", "(", "this", ")", ";", "this", ".", "keywords", "=", "require", "(", "'./keywords'", ")", "(", "this", ")", ";", "this", ".", "lexicon", "=", "require", "(", "'./lexicon'", ")", "(", "this", ")", ";", "}" ]
The Gavagai REST API client @constructor @param {string} apikey - The apikey obtained from Gavagai developer portal @param {object} options (optional) - optional config for the REST client - @member {string} host - host for the Gavagai REST API (default: api.gavagai.se) - @member {string} apiVersion - the Gavagai REST API version to use for requests (default: v3)
[ "The", "Gavagai", "REST", "API", "client" ]
d3f5e3f59f25d9c3ebbf6fd3a3ecb70b3a4047eb
https://github.com/gavagai-corp/gavagai-node/blob/d3f5e3f59f25d9c3ebbf6fd3a3ecb70b3a4047eb/lib/RestClient.js#L23-L50
45,014
VizArtJS/vizart-core
src/color/kmeans/index.js
makeMatrix
function makeMatrix(columns, rows) { let matrix = []; for (let i = 0; i < columns; i++) { let column = []; for (let j = 0; j < rows; j++) { column.push(0); } matrix.push(column); } return matrix; }
javascript
function makeMatrix(columns, rows) { let matrix = []; for (let i = 0; i < columns; i++) { let column = []; for (let j = 0; j < rows; j++) { column.push(0); } matrix.push(column); } return matrix; }
[ "function", "makeMatrix", "(", "columns", ",", "rows", ")", "{", "let", "matrix", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "columns", ";", "i", "++", ")", "{", "let", "column", "=", "[", "]", ";", "for", "(", "let", "j", "=", "0", ";", "j", "<", "rows", ";", "j", "++", ")", "{", "column", ".", "push", "(", "0", ")", ";", "}", "matrix", ".", "push", "(", "column", ")", ";", "}", "return", "matrix", ";", "}" ]
Create a new column x row matrix. @private @param {number} columns @param {number} rows @return {Array<Array<number>>} matrix @example makeMatrix(10, 10);
[ "Create", "a", "new", "column", "x", "row", "matrix", "." ]
ac1d050d2ccaca75bf223439cd6e856b4eb2d69c
https://github.com/VizArtJS/vizart-core/blob/ac1d050d2ccaca75bf223439cd6e856b4eb2d69c/src/color/kmeans/index.js#L15-L25
45,015
VizArtJS/vizart-core
src/color/kmeans/index.js
ssq
function ssq(j, i, sums, sumsOfSquares) { let sji; // s(j, i) if (j > 0) { let muji = (sums[i] - sums[j - 1]) / (i - j + 1); // mu(j, i) sji = sumsOfSquares[i] - sumsOfSquares[j - 1] - (i - j + 1) * muji * muji; } else { sji = sumsOfSquares[i] - sums[i] * sums[i] / (i + 1); } if (sji < 0) { return 0; } return sji; }
javascript
function ssq(j, i, sums, sumsOfSquares) { let sji; // s(j, i) if (j > 0) { let muji = (sums[i] - sums[j - 1]) / (i - j + 1); // mu(j, i) sji = sumsOfSquares[i] - sumsOfSquares[j - 1] - (i - j + 1) * muji * muji; } else { sji = sumsOfSquares[i] - sums[i] * sums[i] / (i + 1); } if (sji < 0) { return 0; } return sji; }
[ "function", "ssq", "(", "j", ",", "i", ",", "sums", ",", "sumsOfSquares", ")", "{", "let", "sji", ";", "// s(j, i)", "if", "(", "j", ">", "0", ")", "{", "let", "muji", "=", "(", "sums", "[", "i", "]", "-", "sums", "[", "j", "-", "1", "]", ")", "/", "(", "i", "-", "j", "+", "1", ")", ";", "// mu(j, i)", "sji", "=", "sumsOfSquares", "[", "i", "]", "-", "sumsOfSquares", "[", "j", "-", "1", "]", "-", "(", "i", "-", "j", "+", "1", ")", "*", "muji", "*", "muji", ";", "}", "else", "{", "sji", "=", "sumsOfSquares", "[", "i", "]", "-", "sums", "[", "i", "]", "*", "sums", "[", "i", "]", "/", "(", "i", "+", "1", ")", ";", "}", "if", "(", "sji", "<", "0", ")", "{", "return", "0", ";", "}", "return", "sji", ";", "}" ]
Generates incrementally computed values based on the sums and sums of squares for the data array @private @param {number} j @param {number} i @param {Array<number>} sums @param {Array<number>} sumsOfSquares @return {number} @example ssq(0, 1, [-1, 0, 2], [1, 1, 5]);
[ "Generates", "incrementally", "computed", "values", "based", "on", "the", "sums", "and", "sums", "of", "squares", "for", "the", "data", "array" ]
ac1d050d2ccaca75bf223439cd6e856b4eb2d69c
https://github.com/VizArtJS/vizart-core/blob/ac1d050d2ccaca75bf223439cd6e856b4eb2d69c/src/color/kmeans/index.js#L40-L52
45,016
VizArtJS/vizart-core
src/color/kmeans/index.js
fillMatrixColumn
function fillMatrixColumn( iMin, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ) { if (iMin > iMax) { return; } // Start at midpoint between iMin and iMax let i = Math.floor((iMin + iMax) / 2); matrix[cluster][i] = matrix[cluster - 1][i - 1]; backtrackMatrix[cluster][i] = i; let jlow = cluster; // the lower end for j if (iMin > cluster) { jlow = Math.max(jlow, backtrackMatrix[cluster][iMin - 1] || 0); } jlow = Math.max(jlow, backtrackMatrix[cluster - 1][i] || 0); let jhigh = i - 1; // the upper end for j if (iMax < matrix.length - 1) { jhigh = Math.min(jhigh, backtrackMatrix[cluster][iMax + 1] || 0); } let sji; let sjlowi; let ssqjlow; let ssqj; for (let j = jhigh; j >= jlow; --j) { sji = ssq(j, i, sums, sumsOfSquares); if (sji + matrix[cluster - 1][jlow - 1] >= matrix[cluster][i]) { break; } // Examine the lower bound of the cluster border sjlowi = ssq(jlow, i, sums, sumsOfSquares); ssqjlow = sjlowi + matrix[cluster - 1][jlow - 1]; if (ssqjlow < matrix[cluster][i]) { // Shrink the lower bound matrix[cluster][i] = ssqjlow; backtrackMatrix[cluster][i] = jlow; } jlow++; ssqj = sji + matrix[cluster - 1][j - 1]; if (ssqj < matrix[cluster][i]) { matrix[cluster][i] = ssqj; backtrackMatrix[cluster][i] = j; } } fillMatrixColumn( iMin, i - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); fillMatrixColumn( i + 1, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); }
javascript
function fillMatrixColumn( iMin, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ) { if (iMin > iMax) { return; } // Start at midpoint between iMin and iMax let i = Math.floor((iMin + iMax) / 2); matrix[cluster][i] = matrix[cluster - 1][i - 1]; backtrackMatrix[cluster][i] = i; let jlow = cluster; // the lower end for j if (iMin > cluster) { jlow = Math.max(jlow, backtrackMatrix[cluster][iMin - 1] || 0); } jlow = Math.max(jlow, backtrackMatrix[cluster - 1][i] || 0); let jhigh = i - 1; // the upper end for j if (iMax < matrix.length - 1) { jhigh = Math.min(jhigh, backtrackMatrix[cluster][iMax + 1] || 0); } let sji; let sjlowi; let ssqjlow; let ssqj; for (let j = jhigh; j >= jlow; --j) { sji = ssq(j, i, sums, sumsOfSquares); if (sji + matrix[cluster - 1][jlow - 1] >= matrix[cluster][i]) { break; } // Examine the lower bound of the cluster border sjlowi = ssq(jlow, i, sums, sumsOfSquares); ssqjlow = sjlowi + matrix[cluster - 1][jlow - 1]; if (ssqjlow < matrix[cluster][i]) { // Shrink the lower bound matrix[cluster][i] = ssqjlow; backtrackMatrix[cluster][i] = jlow; } jlow++; ssqj = sji + matrix[cluster - 1][j - 1]; if (ssqj < matrix[cluster][i]) { matrix[cluster][i] = ssqj; backtrackMatrix[cluster][i] = j; } } fillMatrixColumn( iMin, i - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); fillMatrixColumn( i + 1, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); }
[ "function", "fillMatrixColumn", "(", "iMin", ",", "iMax", ",", "cluster", ",", "matrix", ",", "backtrackMatrix", ",", "sums", ",", "sumsOfSquares", ")", "{", "if", "(", "iMin", ">", "iMax", ")", "{", "return", ";", "}", "// Start at midpoint between iMin and iMax", "let", "i", "=", "Math", ".", "floor", "(", "(", "iMin", "+", "iMax", ")", "/", "2", ")", ";", "matrix", "[", "cluster", "]", "[", "i", "]", "=", "matrix", "[", "cluster", "-", "1", "]", "[", "i", "-", "1", "]", ";", "backtrackMatrix", "[", "cluster", "]", "[", "i", "]", "=", "i", ";", "let", "jlow", "=", "cluster", ";", "// the lower end for j", "if", "(", "iMin", ">", "cluster", ")", "{", "jlow", "=", "Math", ".", "max", "(", "jlow", ",", "backtrackMatrix", "[", "cluster", "]", "[", "iMin", "-", "1", "]", "||", "0", ")", ";", "}", "jlow", "=", "Math", ".", "max", "(", "jlow", ",", "backtrackMatrix", "[", "cluster", "-", "1", "]", "[", "i", "]", "||", "0", ")", ";", "let", "jhigh", "=", "i", "-", "1", ";", "// the upper end for j", "if", "(", "iMax", "<", "matrix", ".", "length", "-", "1", ")", "{", "jhigh", "=", "Math", ".", "min", "(", "jhigh", ",", "backtrackMatrix", "[", "cluster", "]", "[", "iMax", "+", "1", "]", "||", "0", ")", ";", "}", "let", "sji", ";", "let", "sjlowi", ";", "let", "ssqjlow", ";", "let", "ssqj", ";", "for", "(", "let", "j", "=", "jhigh", ";", "j", ">=", "jlow", ";", "--", "j", ")", "{", "sji", "=", "ssq", "(", "j", ",", "i", ",", "sums", ",", "sumsOfSquares", ")", ";", "if", "(", "sji", "+", "matrix", "[", "cluster", "-", "1", "]", "[", "jlow", "-", "1", "]", ">=", "matrix", "[", "cluster", "]", "[", "i", "]", ")", "{", "break", ";", "}", "// Examine the lower bound of the cluster border", "sjlowi", "=", "ssq", "(", "jlow", ",", "i", ",", "sums", ",", "sumsOfSquares", ")", ";", "ssqjlow", "=", "sjlowi", "+", "matrix", "[", "cluster", "-", "1", "]", "[", "jlow", "-", "1", "]", ";", "if", "(", "ssqjlow", "<", "matrix", "[", "cluster", "]", "[", "i", "]", ")", "{", "// Shrink the lower bound", "matrix", "[", "cluster", "]", "[", "i", "]", "=", "ssqjlow", ";", "backtrackMatrix", "[", "cluster", "]", "[", "i", "]", "=", "jlow", ";", "}", "jlow", "++", ";", "ssqj", "=", "sji", "+", "matrix", "[", "cluster", "-", "1", "]", "[", "j", "-", "1", "]", ";", "if", "(", "ssqj", "<", "matrix", "[", "cluster", "]", "[", "i", "]", ")", "{", "matrix", "[", "cluster", "]", "[", "i", "]", "=", "ssqj", ";", "backtrackMatrix", "[", "cluster", "]", "[", "i", "]", "=", "j", ";", "}", "}", "fillMatrixColumn", "(", "iMin", ",", "i", "-", "1", ",", "cluster", ",", "matrix", ",", "backtrackMatrix", ",", "sums", ",", "sumsOfSquares", ")", ";", "fillMatrixColumn", "(", "i", "+", "1", ",", "iMax", ",", "cluster", ",", "matrix", ",", "backtrackMatrix", ",", "sums", ",", "sumsOfSquares", ")", ";", "}" ]
Function that recursively divides and conquers computations for cluster j @private @param {number} iMin Minimum index in cluster to be computed @param {number} iMax Maximum index in cluster to be computed @param {number} cluster Index of the cluster currently being computed @param {Array<Array<number>>} matrix @param {Array<Array<number>>} backtrackMatrix @param {Array<number>} sums @param {Array<number>} sumsOfSquares
[ "Function", "that", "recursively", "divides", "and", "conquers", "computations", "for", "cluster", "j" ]
ac1d050d2ccaca75bf223439cd6e856b4eb2d69c
https://github.com/VizArtJS/vizart-core/blob/ac1d050d2ccaca75bf223439cd6e856b4eb2d69c/src/color/kmeans/index.js#L67-L146
45,017
VizArtJS/vizart-core
src/color/kmeans/index.js
fillMatrices
function fillMatrices(data, matrix, backtrackMatrix) { let nValues = matrix[0].length; // Shift values by the median to improve numeric stability let shift = data[Math.floor(nValues / 2)]; // Cumulative sum and cumulative sum of squares for all values in data array let sums = []; let sumsOfSquares = []; // Initialize first column in matrix & backtrackMatrix for (let i = 0, shiftedValue; i < nValues; ++i) { shiftedValue = data[i] - shift; if (i === 0) { sums.push(shiftedValue); sumsOfSquares.push(shiftedValue * shiftedValue); } else { sums.push(sums[i - 1] + shiftedValue); sumsOfSquares.push(sumsOfSquares[i - 1] + shiftedValue * shiftedValue); } // Initialize for cluster = 0 matrix[0][i] = ssq(0, i, sums, sumsOfSquares); backtrackMatrix[0][i] = 0; } // Initialize the rest of the columns let iMin; for (let cluster = 1; cluster < matrix.length; ++cluster) { if (cluster < matrix.length - 1) { iMin = cluster; } else { // No need to compute matrix[K-1][0] ... matrix[K-1][N-2] iMin = nValues - 1; } fillMatrixColumn( iMin, nValues - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); } }
javascript
function fillMatrices(data, matrix, backtrackMatrix) { let nValues = matrix[0].length; // Shift values by the median to improve numeric stability let shift = data[Math.floor(nValues / 2)]; // Cumulative sum and cumulative sum of squares for all values in data array let sums = []; let sumsOfSquares = []; // Initialize first column in matrix & backtrackMatrix for (let i = 0, shiftedValue; i < nValues; ++i) { shiftedValue = data[i] - shift; if (i === 0) { sums.push(shiftedValue); sumsOfSquares.push(shiftedValue * shiftedValue); } else { sums.push(sums[i - 1] + shiftedValue); sumsOfSquares.push(sumsOfSquares[i - 1] + shiftedValue * shiftedValue); } // Initialize for cluster = 0 matrix[0][i] = ssq(0, i, sums, sumsOfSquares); backtrackMatrix[0][i] = 0; } // Initialize the rest of the columns let iMin; for (let cluster = 1; cluster < matrix.length; ++cluster) { if (cluster < matrix.length - 1) { iMin = cluster; } else { // No need to compute matrix[K-1][0] ... matrix[K-1][N-2] iMin = nValues - 1; } fillMatrixColumn( iMin, nValues - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); } }
[ "function", "fillMatrices", "(", "data", ",", "matrix", ",", "backtrackMatrix", ")", "{", "let", "nValues", "=", "matrix", "[", "0", "]", ".", "length", ";", "// Shift values by the median to improve numeric stability", "let", "shift", "=", "data", "[", "Math", ".", "floor", "(", "nValues", "/", "2", ")", "]", ";", "// Cumulative sum and cumulative sum of squares for all values in data array", "let", "sums", "=", "[", "]", ";", "let", "sumsOfSquares", "=", "[", "]", ";", "// Initialize first column in matrix & backtrackMatrix", "for", "(", "let", "i", "=", "0", ",", "shiftedValue", ";", "i", "<", "nValues", ";", "++", "i", ")", "{", "shiftedValue", "=", "data", "[", "i", "]", "-", "shift", ";", "if", "(", "i", "===", "0", ")", "{", "sums", ".", "push", "(", "shiftedValue", ")", ";", "sumsOfSquares", ".", "push", "(", "shiftedValue", "*", "shiftedValue", ")", ";", "}", "else", "{", "sums", ".", "push", "(", "sums", "[", "i", "-", "1", "]", "+", "shiftedValue", ")", ";", "sumsOfSquares", ".", "push", "(", "sumsOfSquares", "[", "i", "-", "1", "]", "+", "shiftedValue", "*", "shiftedValue", ")", ";", "}", "// Initialize for cluster = 0", "matrix", "[", "0", "]", "[", "i", "]", "=", "ssq", "(", "0", ",", "i", ",", "sums", ",", "sumsOfSquares", ")", ";", "backtrackMatrix", "[", "0", "]", "[", "i", "]", "=", "0", ";", "}", "// Initialize the rest of the columns", "let", "iMin", ";", "for", "(", "let", "cluster", "=", "1", ";", "cluster", "<", "matrix", ".", "length", ";", "++", "cluster", ")", "{", "if", "(", "cluster", "<", "matrix", ".", "length", "-", "1", ")", "{", "iMin", "=", "cluster", ";", "}", "else", "{", "// No need to compute matrix[K-1][0] ... matrix[K-1][N-2]", "iMin", "=", "nValues", "-", "1", ";", "}", "fillMatrixColumn", "(", "iMin", ",", "nValues", "-", "1", ",", "cluster", ",", "matrix", ",", "backtrackMatrix", ",", "sums", ",", "sumsOfSquares", ")", ";", "}", "}" ]
Initializes the main matrices used in Ckmeans and kicks off the divide and conquer cluster computation strategy @private @param {Array<number>} data sorted array of values @param {Array<Array<number>>} matrix @param {Array<Array<number>>} backtrackMatrix
[ "Initializes", "the", "main", "matrices", "used", "in", "Ckmeans", "and", "kicks", "off", "the", "divide", "and", "conquer", "cluster", "computation", "strategy" ]
ac1d050d2ccaca75bf223439cd6e856b4eb2d69c
https://github.com/VizArtJS/vizart-core/blob/ac1d050d2ccaca75bf223439cd6e856b4eb2d69c/src/color/kmeans/index.js#L157-L203
45,018
ayebear/picoes
src/utilities.js
invoke
function invoke(object, method, ...args) { if (object && typeof object[method] === 'function') { return object[method].call(object, ...args) } }
javascript
function invoke(object, method, ...args) { if (object && typeof object[method] === 'function') { return object[method].call(object, ...args) } }
[ "function", "invoke", "(", "object", ",", "method", ",", "...", "args", ")", "{", "if", "(", "object", "&&", "typeof", "object", "[", "method", "]", "===", "'function'", ")", "{", "return", "object", "[", "method", "]", ".", "call", "(", "object", ",", "...", "args", ")", "}", "}" ]
Utility function for invoking methods inside objects, binding "this" to the object. @ignore @param {Object} object - The object @param {Function} method - The method @param {Array} args - The arguments @return {Object} Returns what the called method returns
[ "Utility", "function", "for", "invoking", "methods", "inside", "objects", "binding", "this", "to", "the", "object", "." ]
2f3055172ed28047ae9ba0ade802a286a9bf6649
https://github.com/ayebear/picoes/blob/2f3055172ed28047ae9ba0ade802a286a9bf6649/src/utilities.js#L12-L16
45,019
simonsmith/grunt-suitcss
tasks/grunt-suitcss.js
buildComponentAndCheckConformance
function buildComponentAndCheckConformance(filepath) { var componentDir = path.join(process.cwd(), path.dirname(filepath)); var deferred = Q.defer(); resolve(componentDir, options.resolveOpts, function(err, tree) { if (err) { return deferred.reject(err); } var build = Build(flatten(tree)); build.stylePlugins = function(build) { build.use('styles', function(file, done) { file.read(function(err, string) { if (err) { return deferred.reject(err); } if (options.conform) { try { file.string = conform(string); } catch (e) { return deferred.reject(e); } } done(); }); }); }; build.styles(function(err, builtCSS) { if (err) { return deferred.reject(err); } deferred.resolve(builtCSS); }); }); return deferred.promise; }
javascript
function buildComponentAndCheckConformance(filepath) { var componentDir = path.join(process.cwd(), path.dirname(filepath)); var deferred = Q.defer(); resolve(componentDir, options.resolveOpts, function(err, tree) { if (err) { return deferred.reject(err); } var build = Build(flatten(tree)); build.stylePlugins = function(build) { build.use('styles', function(file, done) { file.read(function(err, string) { if (err) { return deferred.reject(err); } if (options.conform) { try { file.string = conform(string); } catch (e) { return deferred.reject(e); } } done(); }); }); }; build.styles(function(err, builtCSS) { if (err) { return deferred.reject(err); } deferred.resolve(builtCSS); }); }); return deferred.promise; }
[ "function", "buildComponentAndCheckConformance", "(", "filepath", ")", "{", "var", "componentDir", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "path", ".", "dirname", "(", "filepath", ")", ")", ";", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "resolve", "(", "componentDir", ",", "options", ".", "resolveOpts", ",", "function", "(", "err", ",", "tree", ")", "{", "if", "(", "err", ")", "{", "return", "deferred", ".", "reject", "(", "err", ")", ";", "}", "var", "build", "=", "Build", "(", "flatten", "(", "tree", ")", ")", ";", "build", ".", "stylePlugins", "=", "function", "(", "build", ")", "{", "build", ".", "use", "(", "'styles'", ",", "function", "(", "file", ",", "done", ")", "{", "file", ".", "read", "(", "function", "(", "err", ",", "string", ")", "{", "if", "(", "err", ")", "{", "return", "deferred", ".", "reject", "(", "err", ")", ";", "}", "if", "(", "options", ".", "conform", ")", "{", "try", "{", "file", ".", "string", "=", "conform", "(", "string", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "deferred", ".", "reject", "(", "e", ")", ";", "}", "}", "done", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "build", ".", "styles", "(", "function", "(", "err", ",", "builtCSS", ")", "{", "if", "(", "err", ")", "{", "return", "deferred", ".", "reject", "(", "err", ")", ";", "}", "deferred", ".", "resolve", "(", "builtCSS", ")", ";", "}", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Builds a component package based on a component.json file. Will install packages if they don't exist locally. Validate each component before returning built files
[ "Builds", "a", "component", "package", "based", "on", "a", "component", ".", "json", "file", ".", "Will", "install", "packages", "if", "they", "don", "t", "exist", "locally", ".", "Validate", "each", "component", "before", "returning", "built", "files" ]
132018dcfc8f08fc4bbcba198b77c3e230cc5e75
https://github.com/simonsmith/grunt-suitcss/blob/132018dcfc8f08fc4bbcba198b77c3e230cc5e75/tasks/grunt-suitcss.js#L75-L116
45,020
simonsmith/grunt-suitcss
tasks/grunt-suitcss.js
checkConformance
function checkConformance(filepath) { var file = grunt.file.read(filepath); var deferred = Q.defer(); if (options.conform) { try { conform(file); } catch (e) { deferred.reject(e); return deferred.promise; } } deferred.resolve(file); return deferred.promise; }
javascript
function checkConformance(filepath) { var file = grunt.file.read(filepath); var deferred = Q.defer(); if (options.conform) { try { conform(file); } catch (e) { deferred.reject(e); return deferred.promise; } } deferred.resolve(file); return deferred.promise; }
[ "function", "checkConformance", "(", "filepath", ")", "{", "var", "file", "=", "grunt", ".", "file", ".", "read", "(", "filepath", ")", ";", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "if", "(", "options", ".", "conform", ")", "{", "try", "{", "conform", "(", "file", ")", ";", "}", "catch", "(", "e", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "return", "deferred", ".", "promise", ";", "}", "}", "deferred", ".", "resolve", "(", "file", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Run on individual components
[ "Run", "on", "individual", "components" ]
132018dcfc8f08fc4bbcba198b77c3e230cc5e75
https://github.com/simonsmith/grunt-suitcss/blob/132018dcfc8f08fc4bbcba198b77c3e230cc5e75/tasks/grunt-suitcss.js#L121-L136
45,021
feedhenry/fh-mbaas-client
lib/admin/appdata/import.js
startJob
function startJob(params, cb) { var resourcePath = config.addURIParams(constants.APPDATA_BASE_PATH + "/import", params); var method = "POST"; params.resourcePath = resourcePath; params.method = method; params.data = { filename: params.filename, filesize: params.filesize }; mbaasRequest.admin(params, cb); }
javascript
function startJob(params, cb) { var resourcePath = config.addURIParams(constants.APPDATA_BASE_PATH + "/import", params); var method = "POST"; params.resourcePath = resourcePath; params.method = method; params.data = { filename: params.filename, filesize: params.filesize }; mbaasRequest.admin(params, cb); }
[ "function", "startJob", "(", "params", ",", "cb", ")", "{", "var", "resourcePath", "=", "config", ".", "addURIParams", "(", "constants", ".", "APPDATA_BASE_PATH", "+", "\"/import\"", ",", "params", ")", ";", "var", "method", "=", "\"POST\"", ";", "params", ".", "resourcePath", "=", "resourcePath", ";", "params", ".", "method", "=", "method", ";", "params", ".", "data", "=", "{", "filename", ":", "params", ".", "filename", ",", "filesize", ":", "params", ".", "filesize", "}", ";", "mbaasRequest", ".", "admin", "(", "params", ",", "cb", ")", ";", "}" ]
Start a new appdata import job given domain, environment and app id @param params Object containing environment, appid and domain
[ "Start", "a", "new", "appdata", "import", "job", "given", "domain", "environment", "and", "app", "id" ]
2d5a9cbb32e1b2464d71ffa18513358fea388859
https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/admin/appdata/import.js#L30-L42
45,022
DScheglov/merest
lib/controllers/create.js
create
function create(req, res, next) { res.__apiMethod = 'create'; const self = this; const readonly = this.option('create', 'readonly'); const method = this.option('create', 'method'); let data = (method !== 'get') ? req.body : req.query; if (readonly) { try { data = helpers.validateReadonly( helpers.flat(data), readonly ); } catch(e) { return next(e) } } const obj = new (this.model)(data); obj.save(function (err) { if (err) { if (err.name && err.name == "ValidationError") { return next(new ModelAPIError(422, err)); } return next(err); } req.params.id = obj._id; res.status(201); return findById.call(self, 'create', req, res, next); }); }
javascript
function create(req, res, next) { res.__apiMethod = 'create'; const self = this; const readonly = this.option('create', 'readonly'); const method = this.option('create', 'method'); let data = (method !== 'get') ? req.body : req.query; if (readonly) { try { data = helpers.validateReadonly( helpers.flat(data), readonly ); } catch(e) { return next(e) } } const obj = new (this.model)(data); obj.save(function (err) { if (err) { if (err.name && err.name == "ValidationError") { return next(new ModelAPIError(422, err)); } return next(err); } req.params.id = obj._id; res.status(201); return findById.call(self, 'create', req, res, next); }); }
[ "function", "create", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "__apiMethod", "=", "'create'", ";", "const", "self", "=", "this", ";", "const", "readonly", "=", "this", ".", "option", "(", "'create'", ",", "'readonly'", ")", ";", "const", "method", "=", "this", ".", "option", "(", "'create'", ",", "'method'", ")", ";", "let", "data", "=", "(", "method", "!==", "'get'", ")", "?", "req", ".", "body", ":", "req", ".", "query", ";", "if", "(", "readonly", ")", "{", "try", "{", "data", "=", "helpers", ".", "validateReadonly", "(", "helpers", ".", "flat", "(", "data", ")", ",", "readonly", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "next", "(", "e", ")", "}", "}", "const", "obj", "=", "new", "(", "this", ".", "model", ")", "(", "data", ")", ";", "obj", ".", "save", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "name", "&&", "err", ".", "name", "==", "\"ValidationError\"", ")", "{", "return", "next", "(", "new", "ModelAPIError", "(", "422", ",", "err", ")", ")", ";", "}", "return", "next", "(", "err", ")", ";", "}", "req", ".", "params", ".", "id", "=", "obj", ".", "_id", ";", "res", ".", "status", "(", "201", ")", ";", "return", "findById", ".", "call", "(", "self", ",", "'create'", ",", "req", ",", "res", ",", "next", ")", ";", "}", ")", ";", "}" ]
create - the controller that creates a model instance if instance is creared successfully this controller calls findById controller @param {express.Request} req the http(s) request @param {express.Response} res the http(s) response @param {Function} next the callback should be called if controller fails @throws ModelAPIError(406, '...') @throws ModelAPIError(422, '...') @memberof ModelAPIRouter
[ "create", "-", "the", "controller", "that", "creates", "a", "model", "instance", "if", "instance", "is", "creared", "successfully", "this", "controller", "calls", "findById", "controller" ]
d39e7ef0d56236247773467e9bfe83cb128ebc01
https://github.com/DScheglov/merest/blob/d39e7ef0d56236247773467e9bfe83cb128ebc01/lib/controllers/create.js#L20-L48
45,023
Whitebolt/require-extra
src/importSettings.js
loadConfig
function loadConfig(id, copyProps, defaultPropValues) { var cwd = path.normalize(__dirname + '/../'); /** * Get the package file without error-ing on fail, * * @param {string} [filename='package.json'] Package source name. * @returns {Object} The package file. */ function getPackageData(filename) { filename = filename || 'package.json'; try { return require(cwd + './' + filename); } catch(err) { return {}; } } /** * A local version of Object.assign() for old node versions. * * @param {Array} [...=[{}]] Objects to assign (in order). * @returns {Object} */ function assign() { arguments[0] = arguments[0] || {}; for (var n=1; n<arguments.length; n++) { for (var key in arguments[n]) { if (arguments[n].hasOwnProperty(key)) arguments[0][key] = arguments[n][key]; } } return arguments[0]; } /** * Pick the given properties from the given object, returning a new object. * * @param {Object} from Object to take from. * @param {Array} [picks=[]] Properties to pick. * @param {Object} [defaults={}] Defaults to apply. * @returns {Object} */ function pick(from, picks, defaults) { picks = picks || []; defaults = defaults || {}; var obj = {}; for (var n=0; n<picks.length; n++) obj[picks[n]] = from[picks[n]] || defaults[picks[n]]; return obj; } var packageData = getPackageData(); var local = getPackageData('local.json'); var exported = assign( packageData[id], pick(packageData, copyProps, defaultPropValues), {nodeVersion: parseFloat(process.versions.node.split('.').slice(0, 2).join('.'))}, local, {cwd: cwd} ); return exported; }
javascript
function loadConfig(id, copyProps, defaultPropValues) { var cwd = path.normalize(__dirname + '/../'); /** * Get the package file without error-ing on fail, * * @param {string} [filename='package.json'] Package source name. * @returns {Object} The package file. */ function getPackageData(filename) { filename = filename || 'package.json'; try { return require(cwd + './' + filename); } catch(err) { return {}; } } /** * A local version of Object.assign() for old node versions. * * @param {Array} [...=[{}]] Objects to assign (in order). * @returns {Object} */ function assign() { arguments[0] = arguments[0] || {}; for (var n=1; n<arguments.length; n++) { for (var key in arguments[n]) { if (arguments[n].hasOwnProperty(key)) arguments[0][key] = arguments[n][key]; } } return arguments[0]; } /** * Pick the given properties from the given object, returning a new object. * * @param {Object} from Object to take from. * @param {Array} [picks=[]] Properties to pick. * @param {Object} [defaults={}] Defaults to apply. * @returns {Object} */ function pick(from, picks, defaults) { picks = picks || []; defaults = defaults || {}; var obj = {}; for (var n=0; n<picks.length; n++) obj[picks[n]] = from[picks[n]] || defaults[picks[n]]; return obj; } var packageData = getPackageData(); var local = getPackageData('local.json'); var exported = assign( packageData[id], pick(packageData, copyProps, defaultPropValues), {nodeVersion: parseFloat(process.versions.node.split('.').slice(0, 2).join('.'))}, local, {cwd: cwd} ); return exported; }
[ "function", "loadConfig", "(", "id", ",", "copyProps", ",", "defaultPropValues", ")", "{", "var", "cwd", "=", "path", ".", "normalize", "(", "__dirname", "+", "'/../'", ")", ";", "/**\n * Get the package file without error-ing on fail,\n *\n * @param {string} [filename='package.json'] Package source name.\n * @returns {Object} The package file.\n */", "function", "getPackageData", "(", "filename", ")", "{", "filename", "=", "filename", "||", "'package.json'", ";", "try", "{", "return", "require", "(", "cwd", "+", "'./'", "+", "filename", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "{", "}", ";", "}", "}", "/**\n * A local version of Object.assign() for old node versions.\n *\n * @param {Array} [...=[{}]] Objects to assign (in order).\n * @returns {Object}\n */", "function", "assign", "(", ")", "{", "arguments", "[", "0", "]", "=", "arguments", "[", "0", "]", "||", "{", "}", ";", "for", "(", "var", "n", "=", "1", ";", "n", "<", "arguments", ".", "length", ";", "n", "++", ")", "{", "for", "(", "var", "key", "in", "arguments", "[", "n", "]", ")", "{", "if", "(", "arguments", "[", "n", "]", ".", "hasOwnProperty", "(", "key", ")", ")", "arguments", "[", "0", "]", "[", "key", "]", "=", "arguments", "[", "n", "]", "[", "key", "]", ";", "}", "}", "return", "arguments", "[", "0", "]", ";", "}", "/**\n * Pick the given properties from the given object, returning a new object.\n *\n * @param {Object} from Object to take from.\n * @param {Array} [picks=[]] Properties to pick.\n * @param {Object} [defaults={}] Defaults to apply.\n * @returns {Object}\n */", "function", "pick", "(", "from", ",", "picks", ",", "defaults", ")", "{", "picks", "=", "picks", "||", "[", "]", ";", "defaults", "=", "defaults", "||", "{", "}", ";", "var", "obj", "=", "{", "}", ";", "for", "(", "var", "n", "=", "0", ";", "n", "<", "picks", ".", "length", ";", "n", "++", ")", "obj", "[", "picks", "[", "n", "]", "]", "=", "from", "[", "picks", "[", "n", "]", "]", "||", "defaults", "[", "picks", "[", "n", "]", "]", ";", "return", "obj", ";", "}", "var", "packageData", "=", "getPackageData", "(", ")", ";", "var", "local", "=", "getPackageData", "(", "'local.json'", ")", ";", "var", "exported", "=", "assign", "(", "packageData", "[", "id", "]", ",", "pick", "(", "packageData", ",", "copyProps", ",", "defaultPropValues", ")", ",", "{", "nodeVersion", ":", "parseFloat", "(", "process", ".", "versions", ".", "node", ".", "split", "(", "'.'", ")", ".", "slice", "(", "0", ",", "2", ")", ".", "join", "(", "'.'", ")", ")", "}", ",", "local", ",", "{", "cwd", ":", "cwd", "}", ")", ";", "return", "exported", ";", "}" ]
Load config properties from package.json of module. @param {string} id Id in package.json to grab from. @param {Array} copyProps Properties to get. @param {Object} defaultPropValues Default values to apply. @returns {Object} The config.
[ "Load", "config", "properties", "from", "package", ".", "json", "of", "module", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/importSettings.js#L15-L79
45,024
Whitebolt/require-extra
src/importSettings.js
pick
function pick(from, picks, defaults) { picks = picks || []; defaults = defaults || {}; var obj = {}; for (var n=0; n<picks.length; n++) obj[picks[n]] = from[picks[n]] || defaults[picks[n]]; return obj; }
javascript
function pick(from, picks, defaults) { picks = picks || []; defaults = defaults || {}; var obj = {}; for (var n=0; n<picks.length; n++) obj[picks[n]] = from[picks[n]] || defaults[picks[n]]; return obj; }
[ "function", "pick", "(", "from", ",", "picks", ",", "defaults", ")", "{", "picks", "=", "picks", "||", "[", "]", ";", "defaults", "=", "defaults", "||", "{", "}", ";", "var", "obj", "=", "{", "}", ";", "for", "(", "var", "n", "=", "0", ";", "n", "<", "picks", ".", "length", ";", "n", "++", ")", "obj", "[", "picks", "[", "n", "]", "]", "=", "from", "[", "picks", "[", "n", "]", "]", "||", "defaults", "[", "picks", "[", "n", "]", "]", ";", "return", "obj", ";", "}" ]
Pick the given properties from the given object, returning a new object. @param {Object} from Object to take from. @param {Array} [picks=[]] Properties to pick. @param {Object} [defaults={}] Defaults to apply. @returns {Object}
[ "Pick", "the", "given", "properties", "from", "the", "given", "object", "returning", "a", "new", "object", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/importSettings.js#L58-L65
45,025
cfpb/AtomicComponent
src/components/AtomicComponent.js
function() { if ( !this.modifiers ) { return; } this.modifiers.forEach( function( modifier ) { if ( classList.contains( this.element, modifier.ui.base ) ) { if ( modifier.initialize ) { this.initializers.push( modifier.initialize ); delete modifier.initialize; } assign( this, modifier ); } }, this ); }
javascript
function() { if ( !this.modifiers ) { return; } this.modifiers.forEach( function( modifier ) { if ( classList.contains( this.element, modifier.ui.base ) ) { if ( modifier.initialize ) { this.initializers.push( modifier.initialize ); delete modifier.initialize; } assign( this, modifier ); } }, this ); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "modifiers", ")", "{", "return", ";", "}", "this", ".", "modifiers", ".", "forEach", "(", "function", "(", "modifier", ")", "{", "if", "(", "classList", ".", "contains", "(", "this", ".", "element", ",", "modifier", ".", "ui", ".", "base", ")", ")", "{", "if", "(", "modifier", ".", "initialize", ")", "{", "this", ".", "initializers", ".", "push", "(", "modifier", ".", "initialize", ")", ";", "delete", "modifier", ".", "initialize", ";", "}", "assign", "(", "this", ",", "modifier", ")", ";", "}", "}", ",", "this", ")", ";", "}" ]
Function used to process class modifiers. These should correspond with BEM modifiers. @param {Object} attributes - Hash of attributes to set on base element. @param {Object} atomicComponent - Base component.
[ "Function", "used", "to", "process", "class", "modifiers", ".", "These", "should", "correspond", "with", "BEM", "modifiers", "." ]
f45d7ded6687672c8b701c9910ddfe90c7ede742
https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/components/AtomicComponent.js#L58-L72
45,026
tmorin/ceb
dist/systemjs/helper/objects.js
result
function result(object, propName) { var value = object[propName]; return isFunction(value) ? value() : value; }
javascript
function result(object, propName) { var value = object[propName]; return isFunction(value) ? value() : value; }
[ "function", "result", "(", "object", ",", "propName", ")", "{", "var", "value", "=", "object", "[", "propName", "]", ";", "return", "isFunction", "(", "value", ")", "?", "value", "(", ")", ":", "value", ";", "}" ]
Resolve the value of propName into object. If the value is a function, it will be executed. @param {!Object} object the object @param {!string} propName the property name @return the resolved value.
[ "Resolve", "the", "value", "of", "propName", "into", "object", ".", "If", "the", "value", "is", "a", "function", "it", "will", "be", "executed", "." ]
7cc0904b482aa99e5123302c5de4401f7a80af02
https://github.com/tmorin/ceb/blob/7cc0904b482aa99e5123302c5de4401f7a80af02/dist/systemjs/helper/objects.js#L16-L19
45,027
z-open/zlog
lib/zlog.js
getLoggers
function getLoggers() { return _.sortBy( loggers.map(function (logger) { return { name: logger.name, level: logger.getLevel(), parent: logger.getParent() ? logger.getParent().name : '' }; }), function (logger) { return logger.name.toUpperCase(); }); }
javascript
function getLoggers() { return _.sortBy( loggers.map(function (logger) { return { name: logger.name, level: logger.getLevel(), parent: logger.getParent() ? logger.getParent().name : '' }; }), function (logger) { return logger.name.toUpperCase(); }); }
[ "function", "getLoggers", "(", ")", "{", "return", "_", ".", "sortBy", "(", "loggers", ".", "map", "(", "function", "(", "logger", ")", "{", "return", "{", "name", ":", "logger", ".", "name", ",", "level", ":", "logger", ".", "getLevel", "(", ")", ",", "parent", ":", "logger", ".", "getParent", "(", ")", "?", "logger", ".", "getParent", "(", ")", ".", "name", ":", "''", "}", ";", "}", ")", ",", "function", "(", "logger", ")", "{", "return", "logger", ".", "name", ".", "toUpperCase", "(", ")", ";", "}", ")", ";", "}" ]
provide available loggers and their current level
[ "provide", "available", "loggers", "and", "their", "current", "level" ]
756f3d1f9e79e3159c5be87ce65da80b4b71f12b
https://github.com/z-open/zlog/blob/756f3d1f9e79e3159c5be87ce65da80b4b71f12b/lib/zlog.js#L66-L78
45,028
z-open/zlog
lib/zlog.js
print
function print() { getLoggers().forEach(function (logger) { consoleAppender.log(formatText('Logger %b: %b, parent:%b', logger.name, logger.level, logger.parent)); }); }
javascript
function print() { getLoggers().forEach(function (logger) { consoleAppender.log(formatText('Logger %b: %b, parent:%b', logger.name, logger.level, logger.parent)); }); }
[ "function", "print", "(", ")", "{", "getLoggers", "(", ")", ".", "forEach", "(", "function", "(", "logger", ")", "{", "consoleAppender", ".", "log", "(", "formatText", "(", "'Logger %b: %b, parent:%b'", ",", "logger", ".", "name", ",", "logger", ".", "level", ",", "logger", ".", "parent", ")", ")", ";", "}", ")", ";", "}" ]
print to the console the logger statuses
[ "print", "to", "the", "console", "the", "logger", "statuses" ]
756f3d1f9e79e3159c5be87ce65da80b4b71f12b
https://github.com/z-open/zlog/blob/756f3d1f9e79e3159c5be87ce65da80b4b71f12b/lib/zlog.js#L84-L88
45,029
z-open/zlog
lib/zlog.js
setLogger
function setLogger(name, level, appenderNames) { try { var logger = getLogger(name); logger.setLevel(level); if (appenderNames) { logger.clearAppenders(); appenderNames.forEach(function (name) { logger.addAppender(name); }); } return logger; } catch (err) { err.message += formatText(' - Logger %b definition error', name); throw err; } }
javascript
function setLogger(name, level, appenderNames) { try { var logger = getLogger(name); logger.setLevel(level); if (appenderNames) { logger.clearAppenders(); appenderNames.forEach(function (name) { logger.addAppender(name); }); } return logger; } catch (err) { err.message += formatText(' - Logger %b definition error', name); throw err; } }
[ "function", "setLogger", "(", "name", ",", "level", ",", "appenderNames", ")", "{", "try", "{", "var", "logger", "=", "getLogger", "(", "name", ")", ";", "logger", ".", "setLevel", "(", "level", ")", ";", "if", "(", "appenderNames", ")", "{", "logger", ".", "clearAppenders", "(", ")", ";", "appenderNames", ".", "forEach", "(", "function", "(", "name", ")", "{", "logger", ".", "addAppender", "(", "name", ")", ";", "}", ")", ";", "}", "return", "logger", ";", "}", "catch", "(", "err", ")", "{", "err", ".", "message", "+=", "formatText", "(", "' - Logger %b definition error'", ",", "name", ")", ";", "throw", "err", ";", "}", "}" ]
if appenderNames are not provided, the rootLogger appender will be used.
[ "if", "appenderNames", "are", "not", "provided", "the", "rootLogger", "appender", "will", "be", "used", "." ]
756f3d1f9e79e3159c5be87ce65da80b4b71f12b
https://github.com/z-open/zlog/blob/756f3d1f9e79e3159c5be87ce65da80b4b71f12b/lib/zlog.js#L157-L173
45,030
z-open/zlog
lib/zlog.js
writeLog
function writeLog(logLevel, writeArgs) { var logName = loggerName || 'ROOT'; var levelAppenders = []; var logger; // child level always overwrite parent levels // if the child does not allow, no appender even parents' ones won't show if (getLevelNumber(thisLogger.getLevel()) <= getLevelNumber(logLevel)) { logger = thisLogger; while (logger) { levelAppenders = _.concat(levelAppenders, logger.getAppenders()); logger = logger.getParent(); } } // write the message to each appender no more than once! _.uniq(levelAppenders).forEach(function (appender) { var fmt = appender.pattern.format(logName, logLevel, writeArgs[0], _.slice(writeArgs, 1)); var args = _.concat(logName, logLevel, fmt.message); // any more arguments ? if (fmt.otherArgs) { args = _.concat(args, fmt.otherArgs); } appender.writeLog.apply(this, args); }); }
javascript
function writeLog(logLevel, writeArgs) { var logName = loggerName || 'ROOT'; var levelAppenders = []; var logger; // child level always overwrite parent levels // if the child does not allow, no appender even parents' ones won't show if (getLevelNumber(thisLogger.getLevel()) <= getLevelNumber(logLevel)) { logger = thisLogger; while (logger) { levelAppenders = _.concat(levelAppenders, logger.getAppenders()); logger = logger.getParent(); } } // write the message to each appender no more than once! _.uniq(levelAppenders).forEach(function (appender) { var fmt = appender.pattern.format(logName, logLevel, writeArgs[0], _.slice(writeArgs, 1)); var args = _.concat(logName, logLevel, fmt.message); // any more arguments ? if (fmt.otherArgs) { args = _.concat(args, fmt.otherArgs); } appender.writeLog.apply(this, args); }); }
[ "function", "writeLog", "(", "logLevel", ",", "writeArgs", ")", "{", "var", "logName", "=", "loggerName", "||", "'ROOT'", ";", "var", "levelAppenders", "=", "[", "]", ";", "var", "logger", ";", "// child level always overwrite parent levels", "// if the child does not allow, no appender even parents' ones won't show", "if", "(", "getLevelNumber", "(", "thisLogger", ".", "getLevel", "(", ")", ")", "<=", "getLevelNumber", "(", "logLevel", ")", ")", "{", "logger", "=", "thisLogger", ";", "while", "(", "logger", ")", "{", "levelAppenders", "=", "_", ".", "concat", "(", "levelAppenders", ",", "logger", ".", "getAppenders", "(", ")", ")", ";", "logger", "=", "logger", ".", "getParent", "(", ")", ";", "}", "}", "// write the message to each appender no more than once!", "_", ".", "uniq", "(", "levelAppenders", ")", ".", "forEach", "(", "function", "(", "appender", ")", "{", "var", "fmt", "=", "appender", ".", "pattern", ".", "format", "(", "logName", ",", "logLevel", ",", "writeArgs", "[", "0", "]", ",", "_", ".", "slice", "(", "writeArgs", ",", "1", ")", ")", ";", "var", "args", "=", "_", ".", "concat", "(", "logName", ",", "logLevel", ",", "fmt", ".", "message", ")", ";", "// any more arguments ?", "if", "(", "fmt", ".", "otherArgs", ")", "{", "args", "=", "_", ".", "concat", "(", "args", ",", "fmt", ".", "otherArgs", ")", ";", "}", "appender", ".", "writeLog", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ")", ";", "}" ]
write a log entry to all appenders. All parent loggers will be checked to see if their appenders - if any - should write the log. Up to the rootLogger.
[ "write", "a", "log", "entry", "to", "all", "appenders", "." ]
756f3d1f9e79e3159c5be87ce65da80b4b71f12b
https://github.com/z-open/zlog/blob/756f3d1f9e79e3159c5be87ce65da80b4b71f12b/lib/zlog.js#L301-L328
45,031
z-open/zlog
lib/zlog.js
findLoggerParent
function findLoggerParent(logger) { if (rootLogger === logger) { return null; } var deep = true; var hierachy = getHierarchy(logger.name); var parent; for (var n = hierachy.length - 1; n >= 0 && !parent; n--) { parent = _.find(loggers, { name: hierachy[n] }) } return parent || rootLogger; }
javascript
function findLoggerParent(logger) { if (rootLogger === logger) { return null; } var deep = true; var hierachy = getHierarchy(logger.name); var parent; for (var n = hierachy.length - 1; n >= 0 && !parent; n--) { parent = _.find(loggers, { name: hierachy[n] }) } return parent || rootLogger; }
[ "function", "findLoggerParent", "(", "logger", ")", "{", "if", "(", "rootLogger", "===", "logger", ")", "{", "return", "null", ";", "}", "var", "deep", "=", "true", ";", "var", "hierachy", "=", "getHierarchy", "(", "logger", ".", "name", ")", ";", "var", "parent", ";", "for", "(", "var", "n", "=", "hierachy", ".", "length", "-", "1", ";", "n", ">=", "0", "&&", "!", "parent", ";", "n", "--", ")", "{", "parent", "=", "_", ".", "find", "(", "loggers", ",", "{", "name", ":", "hierachy", "[", "n", "]", "}", ")", "}", "return", "parent", "||", "rootLogger", ";", "}" ]
Check the logger name and find out if there is any defined parent loggers
[ "Check", "the", "logger", "name", "and", "find", "out", "if", "there", "is", "any", "defined", "parent", "loggers" ]
756f3d1f9e79e3159c5be87ce65da80b4b71f12b
https://github.com/z-open/zlog/blob/756f3d1f9e79e3159c5be87ce65da80b4b71f12b/lib/zlog.js#L339-L352
45,032
thinkkoa/think_lib
index.js
define
function define(obj, property, value, setter = false) { if (setter) { return Object.defineProperty(obj, property, { value: value, writable: true, configurable: false, enumerable: true }); } else { return Object.defineProperty(obj, property, { get: function () { return value; }, configurable: false, enumerable: true }); } }
javascript
function define(obj, property, value, setter = false) { if (setter) { return Object.defineProperty(obj, property, { value: value, writable: true, configurable: false, enumerable: true }); } else { return Object.defineProperty(obj, property, { get: function () { return value; }, configurable: false, enumerable: true }); } }
[ "function", "define", "(", "obj", ",", "property", ",", "value", ",", "setter", "=", "false", ")", "{", "if", "(", "setter", ")", "{", "return", "Object", ".", "defineProperty", "(", "obj", ",", "property", ",", "{", "value", ":", "value", ",", "writable", ":", "true", ",", "configurable", ":", "false", ",", "enumerable", ":", "true", "}", ")", ";", "}", "else", "{", "return", "Object", ".", "defineProperty", "(", "obj", ",", "property", ",", "{", "get", ":", "function", "(", ")", "{", "return", "value", ";", "}", ",", "configurable", ":", "false", ",", "enumerable", ":", "true", "}", ")", ";", "}", "}" ]
Short for Object.defineProperty, the property is getter when setter is false @param {any} obj @param {any} property @param {any} value @param {boolean} [setter=false] @returns {void}
[ "Short", "for", "Object", ".", "defineProperty", "the", "property", "is", "getter", "when", "setter", "is", "false" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L52-L69
45,033
thinkkoa/think_lib
index.js
isNumberString
function isNumberString(value) { let numberReg = /^((-?\d*\.?\d*(?:e[+-]?\d*(?:\d?\.?|\.?\d?)\d*)?)|(0[0-7]+)|(0x[0-9a-f]+))$/i; return lodash.isString(value) && !isEmpty(value) && numberReg.test(value); }
javascript
function isNumberString(value) { let numberReg = /^((-?\d*\.?\d*(?:e[+-]?\d*(?:\d?\.?|\.?\d?)\d*)?)|(0[0-7]+)|(0x[0-9a-f]+))$/i; return lodash.isString(value) && !isEmpty(value) && numberReg.test(value); }
[ "function", "isNumberString", "(", "value", ")", "{", "let", "numberReg", "=", "/", "^((-?\\d*\\.?\\d*(?:e[+-]?\\d*(?:\\d?\\.?|\\.?\\d?)\\d*)?)|(0[0-7]+)|(0x[0-9a-f]+))$", "/", "i", ";", "return", "lodash", ".", "isString", "(", "value", ")", "&&", "!", "isEmpty", "(", "value", ")", "&&", "numberReg", ".", "test", "(", "value", ")", ";", "}" ]
Checks if value is a string that contains only numbers @param {any} value @returns {boolean}
[ "Checks", "if", "value", "is", "a", "string", "that", "contains", "only", "numbers" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L77-L80
45,034
thinkkoa/think_lib
index.js
isJSONStr
function isJSONStr(value) { if (!lodash.isString(value)) { return false; } try { return isJSONObj(JSON.parse(value)); } catch (e) { return false; } }
javascript
function isJSONStr(value) { if (!lodash.isString(value)) { return false; } try { return isJSONObj(JSON.parse(value)); } catch (e) { return false; } }
[ "function", "isJSONStr", "(", "value", ")", "{", "if", "(", "!", "lodash", ".", "isString", "(", "value", ")", ")", "{", "return", "false", ";", "}", "try", "{", "return", "isJSONObj", "(", "JSON", ".", "parse", "(", "value", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Checks if value is a standard JSON string, must be a string, and can be deserialized as an plain object or array @param {any} value @returns {boolean}
[ "Checks", "if", "value", "is", "a", "standard", "JSON", "string", "must", "be", "a", "string", "and", "can", "be", "deserialized", "as", "an", "plain", "object", "or", "array" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L97-L106
45,035
thinkkoa/think_lib
index.js
isTrueEmpty
function isTrueEmpty(value) { if (value === undefined || value === null || value === '') { return true; } if (lodash.isNumber(value)) { return isNaN(value); } return false; }
javascript
function isTrueEmpty(value) { if (value === undefined || value === null || value === '') { return true; } if (lodash.isNumber(value)) { return isNaN(value); } return false; }
[ "function", "isTrueEmpty", "(", "value", ")", "{", "if", "(", "value", "===", "undefined", "||", "value", "===", "null", "||", "value", "===", "''", ")", "{", "return", "true", ";", "}", "if", "(", "lodash", ".", "isNumber", "(", "value", ")", ")", "{", "return", "isNaN", "(", "value", ")", ";", "}", "return", "false", ";", "}" ]
Checks value is empty, do not consider empty objects, empty arrays, spaces, tabs, form breaks, etc. @param {any} value @returns {boolean}
[ "Checks", "value", "is", "empty", "do", "not", "consider", "empty", "objects", "empty", "arrays", "spaces", "tabs", "form", "breaks", "etc", "." ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L114-L122
45,036
thinkkoa/think_lib
index.js
ucFirst
function ucFirst(value) { value = lodash.toString(value || ''); return value.slice(0, 1).toUpperCase() + value.slice(1).toLowerCase(); }
javascript
function ucFirst(value) { value = lodash.toString(value || ''); return value.slice(0, 1).toUpperCase() + value.slice(1).toLowerCase(); }
[ "function", "ucFirst", "(", "value", ")", "{", "value", "=", "lodash", ".", "toString", "(", "value", "||", "''", ")", ";", "return", "value", ".", "slice", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "value", ".", "slice", "(", "1", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Convert the first letter in the value to uppercase @param {string} value @returns {string}
[ "Convert", "the", "first", "letter", "in", "the", "value", "to", "uppercase" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L193-L196
45,037
thinkkoa/think_lib
index.js
md5
function md5(value) { let ins = crypto.createHash('md5'); ins.update(value); return ins.digest('hex'); }
javascript
function md5(value) { let ins = crypto.createHash('md5'); ins.update(value); return ins.digest('hex'); }
[ "function", "md5", "(", "value", ")", "{", "let", "ins", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "ins", ".", "update", "(", "value", ")", ";", "return", "ins", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Calculate the MD5 hash of value @param {string} value @returns {string}
[ "Calculate", "the", "MD5", "hash", "of", "value" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L204-L208
45,038
thinkkoa/think_lib
index.js
md5Salt
function md5Salt(value, salt = 'abcdefghijklmnopqrstuvwxyz1234567890') { let ins = crypto.createHash('md5'); value = value + salt.slice(value.length % salt.length, salt.length); ins.update(value); return ins.digest('hex'); }
javascript
function md5Salt(value, salt = 'abcdefghijklmnopqrstuvwxyz1234567890') { let ins = crypto.createHash('md5'); value = value + salt.slice(value.length % salt.length, salt.length); ins.update(value); return ins.digest('hex'); }
[ "function", "md5Salt", "(", "value", ",", "salt", "=", "'abcdefghijklmnopqrstuvwxyz1234567890'", ")", "{", "let", "ins", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "value", "=", "value", "+", "salt", ".", "slice", "(", "value", ".", "length", "%", "salt", ".", "length", ",", "salt", ".", "length", ")", ";", "ins", ".", "update", "(", "value", ")", ";", "return", "ins", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Calculate the value of MD5 hash value, including simple salt @param {string} value @param {string} [salt='abcdefghijklmnopqrstuvwxyz1234567890'] @returns
[ "Calculate", "the", "value", "of", "MD5", "hash", "value", "including", "simple", "salt" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L217-L222
45,039
thinkkoa/think_lib
index.js
inArray
function inArray(value, arr) { let len = arr.length; for (let i = 0; i < len; i++) { if (arr[i] == value) { return true; } } return false; }
javascript
function inArray(value, arr) { let len = arr.length; for (let i = 0; i < len; i++) { if (arr[i] == value) { return true; } } return false; }
[ "function", "inArray", "(", "value", ",", "arr", ")", "{", "let", "len", "=", "arr", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "arr", "[", "i", "]", "==", "value", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determines whether value is an element of array arr, only determine the same value with the element, do not determine the type @param {any} value @param {any[]} arr @returns {boolean}
[ "Determines", "whether", "value", "is", "an", "element", "of", "array", "arr", "only", "determine", "the", "same", "value", "with", "the", "element", "do", "not", "determine", "the", "type" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L288-L296
45,040
thinkkoa/think_lib
index.js
arrRemove
function arrRemove(arr, index) { return lodash.remove(arr, function (n, i) { return i !== index; }); }
javascript
function arrRemove(arr, index) { return lodash.remove(arr, function (n, i) { return i !== index; }); }
[ "function", "arrRemove", "(", "arr", ",", "index", ")", "{", "return", "lodash", ".", "remove", "(", "arr", ",", "function", "(", "n", ",", "i", ")", "{", "return", "i", "!==", "index", ";", "}", ")", ";", "}" ]
Removes the specified index element from the array @param {any[]} arr @param {number} index @returns {any[]}
[ "Removes", "the", "specified", "index", "element", "from", "the", "array" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L305-L309
45,041
thinkkoa/think_lib
index.js
isFile
function isFile(p) { if (!fs.existsSync(p)) { return false; } try { let stats = fs.statSync(p); return stats.isFile(); } catch (e) { return false; } }
javascript
function isFile(p) { if (!fs.existsSync(p)) { return false; } try { let stats = fs.statSync(p); return stats.isFile(); } catch (e) { return false; } }
[ "function", "isFile", "(", "p", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "p", ")", ")", "{", "return", "false", ";", "}", "try", "{", "let", "stats", "=", "fs", ".", "statSync", "(", "p", ")", ";", "return", "stats", ".", "isFile", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Checks if p is a file @param {string} p @returns {boolean}
[ "Checks", "if", "p", "is", "a", "file" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L317-L327
45,042
thinkkoa/think_lib
index.js
isDir
function isDir(p) { if (!fs.existsSync(p)) { return false; } try { let stats = fs.statSync(p); return stats.isDirectory(); } catch (e) { return false; } }
javascript
function isDir(p) { if (!fs.existsSync(p)) { return false; } try { let stats = fs.statSync(p); return stats.isDirectory(); } catch (e) { return false; } }
[ "function", "isDir", "(", "p", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "p", ")", ")", "{", "return", "false", ";", "}", "try", "{", "let", "stats", "=", "fs", ".", "statSync", "(", "p", ")", ";", "return", "stats", ".", "isDirectory", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Checks if p is a dir @param {string} p @returns {boolean}
[ "Checks", "if", "p", "is", "a", "dir" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L335-L345
45,043
thinkkoa/think_lib
index.js
isWritable
function isWritable(p) { if (!fs.existsSync(p)) { return false; } let stats = fs.statSync(p); let mode = stats.mode; let uid = process.getuid ? process.getuid() : 0; let gid = process.getgid ? process.getgid() : 0; let owner = uid === stats.uid; let group = gid === stats.gid; return !!(owner && (mode & parseInt('00200', 8)) || group && (mode & parseInt('00020', 8)) || (mode & parseInt('00002', 8))); }
javascript
function isWritable(p) { if (!fs.existsSync(p)) { return false; } let stats = fs.statSync(p); let mode = stats.mode; let uid = process.getuid ? process.getuid() : 0; let gid = process.getgid ? process.getgid() : 0; let owner = uid === stats.uid; let group = gid === stats.gid; return !!(owner && (mode & parseInt('00200', 8)) || group && (mode & parseInt('00020', 8)) || (mode & parseInt('00002', 8))); }
[ "function", "isWritable", "(", "p", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "p", ")", ")", "{", "return", "false", ";", "}", "let", "stats", "=", "fs", ".", "statSync", "(", "p", ")", ";", "let", "mode", "=", "stats", ".", "mode", ";", "let", "uid", "=", "process", ".", "getuid", "?", "process", ".", "getuid", "(", ")", ":", "0", ";", "let", "gid", "=", "process", ".", "getgid", "?", "process", ".", "getgid", "(", ")", ":", "0", ";", "let", "owner", "=", "uid", "===", "stats", ".", "uid", ";", "let", "group", "=", "gid", "===", "stats", ".", "gid", ";", "return", "!", "!", "(", "owner", "&&", "(", "mode", "&", "parseInt", "(", "'00200'", ",", "8", ")", ")", "||", "group", "&&", "(", "mode", "&", "parseInt", "(", "'00020'", ",", "8", ")", ")", "||", "(", "mode", "&", "parseInt", "(", "'00002'", ",", "8", ")", ")", ")", ";", "}" ]
Checks if the file or folder p is writable @param {string} p @returns {boolean}
[ "Checks", "if", "the", "file", "or", "folder", "p", "is", "writable" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L353-L366
45,044
thinkkoa/think_lib
index.js
chmod
function chmod(p, mode) { mode = mode || 0777; if (!fs.existsSync(p)) { return true; } return fs.chmodSync(p, mode); }
javascript
function chmod(p, mode) { mode = mode || 0777; if (!fs.existsSync(p)) { return true; } return fs.chmodSync(p, mode); }
[ "function", "chmod", "(", "p", ",", "mode", ")", "{", "mode", "=", "mode", "||", "0777", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "p", ")", ")", "{", "return", "true", ";", "}", "return", "fs", ".", "chmodSync", "(", "p", ",", "mode", ")", ";", "}" ]
Modify the permissions of the file or folder p. Synchronous mode @param {string} p @param {number} mode @returns {*}
[ "Modify", "the", "permissions", "of", "the", "file", "or", "folder", "p", ".", "Synchronous", "mode" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L375-L381
45,045
thinkkoa/think_lib
index.js
readFile
function readFile(filename, enc) { return new Promise(function (fulfill, reject) { fs.readFile(filename, enc || 'utf8', function (err, res) { return err ? reject(err) : fulfill(res); }); }); }
javascript
function readFile(filename, enc) { return new Promise(function (fulfill, reject) { fs.readFile(filename, enc || 'utf8', function (err, res) { return err ? reject(err) : fulfill(res); }); }); }
[ "function", "readFile", "(", "filename", ",", "enc", ")", "{", "return", "new", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "filename", ",", "enc", "||", "'utf8'", ",", "function", "(", "err", ",", "res", ")", "{", "return", "err", "?", "reject", "(", "err", ")", ":", "fulfill", "(", "res", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Read the contents of the file filename. Asynchronous mode @param {string} filename 文件物理路径 @param {undefined | string} enc 为空返回Buffer类型,'utf8'返回String类型 @returns {promise}
[ "Read", "the", "contents", "of", "the", "file", "filename", ".", "Asynchronous", "mode" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L390-L396
45,046
thinkkoa/think_lib
index.js
writeFile
function writeFile(filename, data) { return new Promise(function (fulfill, reject) { fs.writeFile(filename, data, function (err, res) { return err ? reject(err) : fulfill(res); }); }); }
javascript
function writeFile(filename, data) { return new Promise(function (fulfill, reject) { fs.writeFile(filename, data, function (err, res) { return err ? reject(err) : fulfill(res); }); }); }
[ "function", "writeFile", "(", "filename", ",", "data", ")", "{", "return", "new", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "fs", ".", "writeFile", "(", "filename", ",", "data", ",", "function", "(", "err", ",", "res", ")", "{", "return", "err", "?", "reject", "(", "err", ")", ":", "fulfill", "(", "res", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Write the string data to file. Asynchronous mode @param {string} filename @param {string} data @returns {promise}
[ "Write", "the", "string", "data", "to", "file", ".", "Asynchronous", "mode" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L405-L411
45,047
thinkkoa/think_lib
index.js
reFile
function reFile(filename, nfilename) { return new Promise(function (fulfill, reject) { fs.rename(filename, nfilename, function (err) { return err ? reject(err) : fulfill(); }); }); }
javascript
function reFile(filename, nfilename) { return new Promise(function (fulfill, reject) { fs.rename(filename, nfilename, function (err) { return err ? reject(err) : fulfill(); }); }); }
[ "function", "reFile", "(", "filename", ",", "nfilename", ")", "{", "return", "new", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "fs", ".", "rename", "(", "filename", ",", "nfilename", ",", "function", "(", "err", ")", "{", "return", "err", "?", "reject", "(", "err", ")", ":", "fulfill", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Rename the filename to nfilename. If nfilename and filename are not in the same physical path, the move file action will be triggered. Asynchronous mode @param {string} filename @param {string} nfilename @returns {*}
[ "Rename", "the", "filename", "to", "nfilename", ".", "If", "nfilename", "and", "filename", "are", "not", "in", "the", "same", "physical", "path", "the", "move", "file", "action", "will", "be", "triggered", ".", "Asynchronous", "mode" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L420-L426
45,048
thinkkoa/think_lib
index.js
mkDir
function mkDir(p, mode = 0777) { if (fs.existsSync(p)) { chmod(p, mode); return true; } else { if (mkDir(path.dirname(p))) { fs.mkdirSync(p, mode); return true; } } }
javascript
function mkDir(p, mode = 0777) { if (fs.existsSync(p)) { chmod(p, mode); return true; } else { if (mkDir(path.dirname(p))) { fs.mkdirSync(p, mode); return true; } } }
[ "function", "mkDir", "(", "p", ",", "mode", "=", "0777", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "p", ")", ")", "{", "chmod", "(", "p", ",", "mode", ")", ";", "return", "true", ";", "}", "else", "{", "if", "(", "mkDir", "(", "path", ".", "dirname", "(", "p", ")", ")", ")", "{", "fs", ".", "mkdirSync", "(", "p", ",", "mode", ")", ";", "return", "true", ";", "}", "}", "}" ]
According to the path p to create a folder, p contains multi-level new path will be automatically recursively created. Synchronous mode @param {string} p @param {number} mode @returns {*}
[ "According", "to", "the", "path", "p", "to", "create", "a", "folder", "p", "contains", "multi", "-", "level", "new", "path", "will", "be", "automatically", "recursively", "created", ".", "Synchronous", "mode" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L449-L459
45,049
thinkkoa/think_lib
index.js
readDir
function readDir(p, filter, files, prefix) { prefix = prefix || ''; files = files || []; filter = filter || function (x) { return x[0] !== '.'; }; let dir = path.join(p, prefix); if (!fs.existsSync(dir)) { return files; } if (fs.statSync(dir).isDirectory()) { fs.readdirSync(dir).filter(filter).forEach(function (name) { readDir(p, filter, files, path.join(prefix, name)); }); } else { files.push(prefix); } return files; }
javascript
function readDir(p, filter, files, prefix) { prefix = prefix || ''; files = files || []; filter = filter || function (x) { return x[0] !== '.'; }; let dir = path.join(p, prefix); if (!fs.existsSync(dir)) { return files; } if (fs.statSync(dir).isDirectory()) { fs.readdirSync(dir).filter(filter).forEach(function (name) { readDir(p, filter, files, path.join(prefix, name)); }); } else { files.push(prefix); } return files; }
[ "function", "readDir", "(", "p", ",", "filter", ",", "files", ",", "prefix", ")", "{", "prefix", "=", "prefix", "||", "''", ";", "files", "=", "files", "||", "[", "]", ";", "filter", "=", "filter", "||", "function", "(", "x", ")", "{", "return", "x", "[", "0", "]", "!==", "'.'", ";", "}", ";", "let", "dir", "=", "path", ".", "join", "(", "p", ",", "prefix", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "dir", ")", ")", "{", "return", "files", ";", "}", "if", "(", "fs", ".", "statSync", "(", "dir", ")", ".", "isDirectory", "(", ")", ")", "{", "fs", ".", "readdirSync", "(", "dir", ")", ".", "filter", "(", "filter", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "readDir", "(", "p", ",", "filter", ",", "files", ",", "path", ".", "join", "(", "prefix", ",", "name", ")", ")", ";", "}", ")", ";", "}", "else", "{", "files", ".", "push", "(", "prefix", ")", ";", "}", "return", "files", ";", "}" ]
Recursively read the path under the p folder. Synchronous mode @param {any} p @param {any} filter @param {any} files @param {any} prefix @returns {*}
[ "Recursively", "read", "the", "path", "under", "the", "p", "folder", ".", "Synchronous", "mode" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L470-L489
45,050
thinkkoa/think_lib
index.js
rmDir
function rmDir(p, reserve) { if (!isDir(p)) { return Promise.resolve(null); } let deferred = getDefer(); fs.readdir(p, function (err, files) { if (err) { return deferred.reject(err); } let spromise = Promise.resolve(null); if (files.length > 0) { let promises = files.map(function (item) { let filePath = path.normalize(`${p}${path.sep}${item}`); if (isDir(filePath)) { return rmDir(filePath, false); } else { let defer = getDefer(); fs.unlink(filePath, function (er) { return er ? defer.reject(er) : defer.resolve(); }); return defer.promise; } }); spromise = Promise.all(promises); } return spromise.then(function () { if (!reserve) { let deferr = getDefer(); fs.rmdir(p, function (e) { return e ? deferr.reject(e) : deferr.resolve(); }); return deferr.promise; } return Promise.resolve(); }).then(function () { deferred.resolve(); }).catch(function (e) { deferred.reject(e); }); }); return deferred.promise; }
javascript
function rmDir(p, reserve) { if (!isDir(p)) { return Promise.resolve(null); } let deferred = getDefer(); fs.readdir(p, function (err, files) { if (err) { return deferred.reject(err); } let spromise = Promise.resolve(null); if (files.length > 0) { let promises = files.map(function (item) { let filePath = path.normalize(`${p}${path.sep}${item}`); if (isDir(filePath)) { return rmDir(filePath, false); } else { let defer = getDefer(); fs.unlink(filePath, function (er) { return er ? defer.reject(er) : defer.resolve(); }); return defer.promise; } }); spromise = Promise.all(promises); } return spromise.then(function () { if (!reserve) { let deferr = getDefer(); fs.rmdir(p, function (e) { return e ? deferr.reject(e) : deferr.resolve(); }); return deferr.promise; } return Promise.resolve(); }).then(function () { deferred.resolve(); }).catch(function (e) { deferred.reject(e); }); }); return deferred.promise; }
[ "function", "rmDir", "(", "p", ",", "reserve", ")", "{", "if", "(", "!", "isDir", "(", "p", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "null", ")", ";", "}", "let", "deferred", "=", "getDefer", "(", ")", ";", "fs", ".", "readdir", "(", "p", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "return", "deferred", ".", "reject", "(", "err", ")", ";", "}", "let", "spromise", "=", "Promise", ".", "resolve", "(", "null", ")", ";", "if", "(", "files", ".", "length", ">", "0", ")", "{", "let", "promises", "=", "files", ".", "map", "(", "function", "(", "item", ")", "{", "let", "filePath", "=", "path", ".", "normalize", "(", "`", "${", "p", "}", "${", "path", ".", "sep", "}", "${", "item", "}", "`", ")", ";", "if", "(", "isDir", "(", "filePath", ")", ")", "{", "return", "rmDir", "(", "filePath", ",", "false", ")", ";", "}", "else", "{", "let", "defer", "=", "getDefer", "(", ")", ";", "fs", ".", "unlink", "(", "filePath", ",", "function", "(", "er", ")", "{", "return", "er", "?", "defer", ".", "reject", "(", "er", ")", ":", "defer", ".", "resolve", "(", ")", ";", "}", ")", ";", "return", "defer", ".", "promise", ";", "}", "}", ")", ";", "spromise", "=", "Promise", ".", "all", "(", "promises", ")", ";", "}", "return", "spromise", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "reserve", ")", "{", "let", "deferr", "=", "getDefer", "(", ")", ";", "fs", ".", "rmdir", "(", "p", ",", "function", "(", "e", ")", "{", "return", "e", "?", "deferr", ".", "reject", "(", "e", ")", ":", "deferr", ".", "resolve", "(", ")", ";", "}", ")", ";", "return", "deferr", ".", "promise", ";", "}", "return", "Promise", ".", "resolve", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "deferred", ".", "resolve", "(", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "deferred", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Subfolders of path p are recursively deleted. When reserve is true, the top-level folder is deleted Asynchronous mode @template T @param {string} p @param {boolean} reserve @returns {*}
[ "Subfolders", "of", "path", "p", "are", "recursively", "deleted", ".", "When", "reserve", "is", "true", "the", "top", "-", "level", "folder", "is", "deleted", "Asynchronous", "mode" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L499-L541
45,051
thinkkoa/think_lib
index.js
generatorToPromise
function generatorToPromise(fn) { if (typeof fn !== 'function') { throw Error('fn is not a function'); } if (!isGenerator(fn)) { // assume it's Promise-based return fn; } return co.wrap(fn); }
javascript
function generatorToPromise(fn) { if (typeof fn !== 'function') { throw Error('fn is not a function'); } if (!isGenerator(fn)) { // assume it's Promise-based return fn; } return co.wrap(fn); }
[ "function", "generatorToPromise", "(", "fn", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "throw", "Error", "(", "'fn is not a function'", ")", ";", "}", "if", "(", "!", "isGenerator", "(", "fn", ")", ")", "{", "// assume it's Promise-based", "return", "fn", ";", "}", "return", "co", ".", "wrap", "(", "fn", ")", ";", "}" ]
Convert GeneratorFunction fn to Promise @param {Function} fn @returns {Promise}
[ "Convert", "GeneratorFunction", "fn", "to", "Promise" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L597-L606
45,052
thinkkoa/think_lib
index.js
clone
function clone(source, deep) { if (deep) { return lodash.cloneDeep(source); } else { return lodash.clone(source); } }
javascript
function clone(source, deep) { if (deep) { return lodash.cloneDeep(source); } else { return lodash.clone(source); } }
[ "function", "clone", "(", "source", ",", "deep", ")", "{", "if", "(", "deep", ")", "{", "return", "lodash", ".", "cloneDeep", "(", "source", ")", ";", "}", "else", "{", "return", "lodash", ".", "clone", "(", "source", ")", ";", "}", "}" ]
Copy the source, deep deep to true depth copy @param {any} source @param {any} deep @returns {*}
[ "Copy", "the", "source", "deep", "deep", "to", "true", "depth", "copy" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L649-L655
45,053
thinkkoa/think_lib
index.js
extend
function extend(source, target, deep) { if (deep) { return lodash.merge(lodash.cloneDeep(source), target); } else { return lodash.assignIn(source, target); } }
javascript
function extend(source, target, deep) { if (deep) { return lodash.merge(lodash.cloneDeep(source), target); } else { return lodash.assignIn(source, target); } }
[ "function", "extend", "(", "source", ",", "target", ",", "deep", ")", "{", "if", "(", "deep", ")", "{", "return", "lodash", ".", "merge", "(", "lodash", ".", "cloneDeep", "(", "source", ")", ",", "target", ")", ";", "}", "else", "{", "return", "lodash", ".", "assignIn", "(", "source", ",", "target", ")", ";", "}", "}" ]
So that the target object inherits the source, deep depth is true depth inheritance @param {any} source @param {any} target @param {any} deep @returns {*}
[ "So", "that", "the", "target", "object", "inherits", "the", "source", "deep", "depth", "is", "true", "depth", "inheritance" ]
1934e363fb931820c1cca746f34a7306084fa342
https://github.com/thinkkoa/think_lib/blob/1934e363fb931820c1cca746f34a7306084fa342/index.js#L665-L671
45,054
odogono/elsinore-js
src/entity_set/source.js
pushComponent
function pushComponent(pushable, component, cdefMap, isAnonymous = false, options) { // if( cdefMap ){ let json = component.toJSON({ cdefMap }); if (isAnonymous) { delete json[ENTITY_ID]; delete json[COMPONENT_ID]; } return pushable.push([json, options]); // } // pushable.push( component ); }
javascript
function pushComponent(pushable, component, cdefMap, isAnonymous = false, options) { // if( cdefMap ){ let json = component.toJSON({ cdefMap }); if (isAnonymous) { delete json[ENTITY_ID]; delete json[COMPONENT_ID]; } return pushable.push([json, options]); // } // pushable.push( component ); }
[ "function", "pushComponent", "(", "pushable", ",", "component", ",", "cdefMap", ",", "isAnonymous", "=", "false", ",", "options", ")", "{", "// if( cdefMap ){", "let", "json", "=", "component", ".", "toJSON", "(", "{", "cdefMap", "}", ")", ";", "if", "(", "isAnonymous", ")", "{", "delete", "json", "[", "ENTITY_ID", "]", ";", "delete", "json", "[", "COMPONENT_ID", "]", ";", "}", "return", "pushable", ".", "push", "(", "[", "json", ",", "options", "]", ")", ";", "// }", "// pushable.push( component );", "}" ]
Push details of the component to the Pushable stream @param {*} pushable @param {*} component @param {*} cdefMap @param {*} isAnonymous
[ "Push", "details", "of", "the", "component", "to", "the", "Pushable", "stream" ]
1ecce67ad0022646419a740def029b1ba92dd558
https://github.com/odogono/elsinore-js/blob/1ecce67ad0022646419a740def029b1ba92dd558/src/entity_set/source.js#L196-L207
45,055
nodejitsu/contour
pagelets/share.js
define
function define() { var defaults = this.defaults , data = this.data , load = data.load || defaults.load , href = this.href , def = []; // // Check what social media to load, if none provided load defaults in `load`. // Object.keys(load).forEach(function checkLoad(key) { if (!load[key] || !(key in href)) return; def.push(href[key]); }); this.queue.enlist('loader', { plain: def }); return this; }
javascript
function define() { var defaults = this.defaults , data = this.data , load = data.load || defaults.load , href = this.href , def = []; // // Check what social media to load, if none provided load defaults in `load`. // Object.keys(load).forEach(function checkLoad(key) { if (!load[key] || !(key in href)) return; def.push(href[key]); }); this.queue.enlist('loader', { plain: def }); return this; }
[ "function", "define", "(", ")", "{", "var", "defaults", "=", "this", ".", "defaults", ",", "data", "=", "this", ".", "data", ",", "load", "=", "data", ".", "load", "||", "defaults", ".", "load", ",", "href", "=", "this", ".", "href", ",", "def", "=", "[", "]", ";", "//", "// Check what social media to load, if none provided load defaults in `load`.", "//", "Object", ".", "keys", "(", "load", ")", ".", "forEach", "(", "function", "checkLoad", "(", "key", ")", "{", "if", "(", "!", "load", "[", "key", "]", "||", "!", "(", "key", "in", "href", ")", ")", "return", ";", "def", ".", "push", "(", "href", "[", "key", "]", ")", ";", "}", ")", ";", "this", ".", "queue", ".", "enlist", "(", "'loader'", ",", "{", "plain", ":", "def", "}", ")", ";", "return", "this", ";", "}" ]
Define what external JS script should be loaded. @return {Pagelet} @api private
[ "Define", "what", "external", "JS", "script", "should", "be", "loaded", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/share.js#L52-L69
45,056
boneskull/node-fogbugz
index.js
_extractEmptyResponse
function _extractEmptyResponse(xml, dfrd) { var parser = new xml2js.Parser(); parser.parseString(xml, function(err, res) { if (err) { dfrd.reject(); return MODULE_ERRORS.xmlParseError; } if (res.response.error) { dfrd.reject(res.response.error); } }); }
javascript
function _extractEmptyResponse(xml, dfrd) { var parser = new xml2js.Parser(); parser.parseString(xml, function(err, res) { if (err) { dfrd.reject(); return MODULE_ERRORS.xmlParseError; } if (res.response.error) { dfrd.reject(res.response.error); } }); }
[ "function", "_extractEmptyResponse", "(", "xml", ",", "dfrd", ")", "{", "var", "parser", "=", "new", "xml2js", ".", "Parser", "(", ")", ";", "parser", ".", "parseString", "(", "xml", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "dfrd", ".", "reject", "(", ")", ";", "return", "MODULE_ERRORS", ".", "xmlParseError", ";", "}", "if", "(", "res", ".", "response", ".", "error", ")", "{", "dfrd", ".", "reject", "(", "res", ".", "response", ".", "error", ")", ";", "}", "}", ")", ";", "}" ]
Basically just asserts an empty response has no errors in it. @param {string} xml XML to parse @param {Q.defer} dfrd Q deferred object
[ "Basically", "just", "asserts", "an", "empty", "response", "has", "no", "errors", "in", "it", "." ]
7e5001b5e5b4383348a2713c5ddc943bc8e6fe0a
https://github.com/boneskull/node-fogbugz/blob/7e5001b5e5b4383348a2713c5ddc943bc8e6fe0a/index.js#L159-L170
45,057
boneskull/node-fogbugz
index.js
logoff
function logoff() { var token = cache.get('token'); var dfrd = Q.defer(); if (!token) { dfrd.reject(MODULE_ERRORS.undefinedToken); } else { request(format(URLs.logoff, PROTOCOL, conf.host, token), function(err) { if (err) { dfrd.reject(err); } else { dfrd.resolve(true); } }); } return dfrd.promise; }
javascript
function logoff() { var token = cache.get('token'); var dfrd = Q.defer(); if (!token) { dfrd.reject(MODULE_ERRORS.undefinedToken); } else { request(format(URLs.logoff, PROTOCOL, conf.host, token), function(err) { if (err) { dfrd.reject(err); } else { dfrd.resolve(true); } }); } return dfrd.promise; }
[ "function", "logoff", "(", ")", "{", "var", "token", "=", "cache", ".", "get", "(", "'token'", ")", ";", "var", "dfrd", "=", "Q", ".", "defer", "(", ")", ";", "if", "(", "!", "token", ")", "{", "dfrd", ".", "reject", "(", "MODULE_ERRORS", ".", "undefinedToken", ")", ";", "}", "else", "{", "request", "(", "format", "(", "URLs", ".", "logoff", ",", "PROTOCOL", ",", "conf", ".", "host", ",", "token", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "dfrd", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "dfrd", ".", "resolve", "(", "true", ")", ";", "}", "}", ")", ";", "}", "return", "dfrd", ".", "promise", ";", "}" ]
Assuming you are logged in and have a cached token, this will log you out. @method logoff @returns {Function|promise|Q.promise} Promise
[ "Assuming", "you", "are", "logged", "in", "and", "have", "a", "cached", "token", "this", "will", "log", "you", "out", "." ]
7e5001b5e5b4383348a2713c5ddc943bc8e6fe0a
https://github.com/boneskull/node-fogbugz/blob/7e5001b5e5b4383348a2713c5ddc943bc8e6fe0a/index.js#L198-L214
45,058
boneskull/node-fogbugz
index.js
logon
function logon() { var dfrd = Q.defer(); var token = cache.get('token'); function extractToken(xml) { var r = _parse(xml, dfrd); if (r) { return r.response.token[0]; } } if (token) { dfrd.resolve({ token: token, cached: true }); } request(format(URLs.logon, PROTOCOL, conf.host, conf.username, conf.password), function(err, res, body) { var newToken; if (err) { dfrd.reject(err); } else { newToken = extractToken(body); if (!newToken) { dfrd.reject(MODULE_ERRORS.unknown); } else { cache.put('token', newToken); dfrd.resolve({ token: newToken, cached: false }); } } }); return dfrd.promise; }
javascript
function logon() { var dfrd = Q.defer(); var token = cache.get('token'); function extractToken(xml) { var r = _parse(xml, dfrd); if (r) { return r.response.token[0]; } } if (token) { dfrd.resolve({ token: token, cached: true }); } request(format(URLs.logon, PROTOCOL, conf.host, conf.username, conf.password), function(err, res, body) { var newToken; if (err) { dfrd.reject(err); } else { newToken = extractToken(body); if (!newToken) { dfrd.reject(MODULE_ERRORS.unknown); } else { cache.put('token', newToken); dfrd.resolve({ token: newToken, cached: false }); } } }); return dfrd.promise; }
[ "function", "logon", "(", ")", "{", "var", "dfrd", "=", "Q", ".", "defer", "(", ")", ";", "var", "token", "=", "cache", ".", "get", "(", "'token'", ")", ";", "function", "extractToken", "(", "xml", ")", "{", "var", "r", "=", "_parse", "(", "xml", ",", "dfrd", ")", ";", "if", "(", "r", ")", "{", "return", "r", ".", "response", ".", "token", "[", "0", "]", ";", "}", "}", "if", "(", "token", ")", "{", "dfrd", ".", "resolve", "(", "{", "token", ":", "token", ",", "cached", ":", "true", "}", ")", ";", "}", "request", "(", "format", "(", "URLs", ".", "logon", ",", "PROTOCOL", ",", "conf", ".", "host", ",", "conf", ".", "username", ",", "conf", ".", "password", ")", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "var", "newToken", ";", "if", "(", "err", ")", "{", "dfrd", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "newToken", "=", "extractToken", "(", "body", ")", ";", "if", "(", "!", "newToken", ")", "{", "dfrd", ".", "reject", "(", "MODULE_ERRORS", ".", "unknown", ")", ";", "}", "else", "{", "cache", ".", "put", "(", "'token'", ",", "newToken", ")", ";", "dfrd", ".", "resolve", "(", "{", "token", ":", "newToken", ",", "cached", ":", "false", "}", ")", ";", "}", "}", "}", ")", ";", "return", "dfrd", ".", "promise", ";", "}" ]
Logs you into FogBugz based on contents of `fogbugz.conf.json`. @method logon @returns {Function|promise|Q.promise} Promise
[ "Logs", "you", "into", "FogBugz", "based", "on", "contents", "of", "fogbugz", ".", "conf", ".", "json", "." ]
7e5001b5e5b4383348a2713c5ddc943bc8e6fe0a
https://github.com/boneskull/node-fogbugz/blob/7e5001b5e5b4383348a2713c5ddc943bc8e6fe0a/index.js#L221-L259
45,059
boneskull/node-fogbugz
index.js
setCurrentFilter
function setCurrentFilter(filter) { var token = cache.get('token'); var dfrd = Q.defer(); var id; if (!token) { dfrd.reject(MODULE_ERRORS.undefinedToken); } else { id = typeof filter === 'string' ? filter : filter.id; request(format(URLs.setCurrentFilter, PROTOCOL, conf.host, id, token), function(err, res, body) { if (err) { dfrd.reject(err); } else { _extractEmptyResponse(body, dfrd); dfrd.resolve(true); } }); } return dfrd.promise; }
javascript
function setCurrentFilter(filter) { var token = cache.get('token'); var dfrd = Q.defer(); var id; if (!token) { dfrd.reject(MODULE_ERRORS.undefinedToken); } else { id = typeof filter === 'string' ? filter : filter.id; request(format(URLs.setCurrentFilter, PROTOCOL, conf.host, id, token), function(err, res, body) { if (err) { dfrd.reject(err); } else { _extractEmptyResponse(body, dfrd); dfrd.resolve(true); } }); } return dfrd.promise; }
[ "function", "setCurrentFilter", "(", "filter", ")", "{", "var", "token", "=", "cache", ".", "get", "(", "'token'", ")", ";", "var", "dfrd", "=", "Q", ".", "defer", "(", ")", ";", "var", "id", ";", "if", "(", "!", "token", ")", "{", "dfrd", ".", "reject", "(", "MODULE_ERRORS", ".", "undefinedToken", ")", ";", "}", "else", "{", "id", "=", "typeof", "filter", "===", "'string'", "?", "filter", ":", "filter", ".", "id", ";", "request", "(", "format", "(", "URLs", ".", "setCurrentFilter", ",", "PROTOCOL", ",", "conf", ".", "host", ",", "id", ",", "token", ")", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "err", ")", "{", "dfrd", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "_extractEmptyResponse", "(", "body", ",", "dfrd", ")", ";", "dfrd", ".", "resolve", "(", "true", ")", ";", "}", "}", ")", ";", "}", "return", "dfrd", ".", "promise", ";", "}" ]
Sets the current Filter. I'm not sure what this does exactly. @method setCurrentFilter @param {Filter|string} filter Filter object or string ID @see class fogbugz.Filter @returns {Promise.<boolean>} True if success
[ "Sets", "the", "current", "Filter", ".", "I", "m", "not", "sure", "what", "this", "does", "exactly", "." ]
7e5001b5e5b4383348a2713c5ddc943bc8e6fe0a
https://github.com/boneskull/node-fogbugz/blob/7e5001b5e5b4383348a2713c5ddc943bc8e6fe0a/index.js#L322-L341
45,060
AlexanderMoskovkin/qunit-harness
vendor/qunit-1.20.0.js
priorityFill
function priorityFill( callback ) { var queue, prioritizedQueue; queue = config.queue.slice( priorityFill.pos ); prioritizedQueue = config.queue.slice( 0, -config.queue.length + priorityFill.pos ); queue.unshift( callback ); queue.unshift.apply( queue, prioritizedQueue ); config.queue = queue; priorityFill.pos += 1; }
javascript
function priorityFill( callback ) { var queue, prioritizedQueue; queue = config.queue.slice( priorityFill.pos ); prioritizedQueue = config.queue.slice( 0, -config.queue.length + priorityFill.pos ); queue.unshift( callback ); queue.unshift.apply( queue, prioritizedQueue ); config.queue = queue; priorityFill.pos += 1; }
[ "function", "priorityFill", "(", "callback", ")", "{", "var", "queue", ",", "prioritizedQueue", ";", "queue", "=", "config", ".", "queue", ".", "slice", "(", "priorityFill", ".", "pos", ")", ";", "prioritizedQueue", "=", "config", ".", "queue", ".", "slice", "(", "0", ",", "-", "config", ".", "queue", ".", "length", "+", "priorityFill", ".", "pos", ")", ";", "queue", ".", "unshift", "(", "callback", ")", ";", "queue", ".", "unshift", ".", "apply", "(", "queue", ",", "prioritizedQueue", ")", ";", "config", ".", "queue", "=", "queue", ";", "priorityFill", ".", "pos", "+=", "1", ";", "}" ]
Place previously failed tests on a queue priority line, respecting the order they get assigned.
[ "Place", "previously", "failed", "tests", "on", "a", "queue", "priority", "line", "respecting", "the", "order", "they", "get", "assigned", "." ]
fde6210031e9d7fb6759f7124e689d0dbe70e747
https://github.com/AlexanderMoskovkin/qunit-harness/blob/fde6210031e9d7fb6759f7124e689d0dbe70e747/vendor/qunit-1.20.0.js#L1265-L1277
45,061
AlexanderMoskovkin/qunit-harness
vendor/qunit-1.20.0.js
function( count ) { var test = this.test, popped = false, acceptCallCount = count; if ( typeof acceptCallCount === "undefined" ) { acceptCallCount = 1; } test.semaphore += 1; test.usedAsync = true; pauseProcessing(); return function done() { if ( popped ) { test.pushFailure( "Too many calls to the `assert.async` callback", sourceFromStacktrace( 2 ) ); return; } acceptCallCount -= 1; if ( acceptCallCount > 0 ) { return; } test.semaphore -= 1; popped = true; resumeProcessing(); }; }
javascript
function( count ) { var test = this.test, popped = false, acceptCallCount = count; if ( typeof acceptCallCount === "undefined" ) { acceptCallCount = 1; } test.semaphore += 1; test.usedAsync = true; pauseProcessing(); return function done() { if ( popped ) { test.pushFailure( "Too many calls to the `assert.async` callback", sourceFromStacktrace( 2 ) ); return; } acceptCallCount -= 1; if ( acceptCallCount > 0 ) { return; } test.semaphore -= 1; popped = true; resumeProcessing(); }; }
[ "function", "(", "count", ")", "{", "var", "test", "=", "this", ".", "test", ",", "popped", "=", "false", ",", "acceptCallCount", "=", "count", ";", "if", "(", "typeof", "acceptCallCount", "===", "\"undefined\"", ")", "{", "acceptCallCount", "=", "1", ";", "}", "test", ".", "semaphore", "+=", "1", ";", "test", ".", "usedAsync", "=", "true", ";", "pauseProcessing", "(", ")", ";", "return", "function", "done", "(", ")", "{", "if", "(", "popped", ")", "{", "test", ".", "pushFailure", "(", "\"Too many calls to the `assert.async` callback\"", ",", "sourceFromStacktrace", "(", "2", ")", ")", ";", "return", ";", "}", "acceptCallCount", "-=", "1", ";", "if", "(", "acceptCallCount", ">", "0", ")", "{", "return", ";", "}", "test", ".", "semaphore", "-=", "1", ";", "popped", "=", "true", ";", "resumeProcessing", "(", ")", ";", "}", ";", "}" ]
Increment this Test's semaphore counter, then return a function that decrements that counter a maximum of once.
[ "Increment", "this", "Test", "s", "semaphore", "counter", "then", "return", "a", "function", "that", "decrements", "that", "counter", "a", "maximum", "of", "once", "." ]
fde6210031e9d7fb6759f7124e689d0dbe70e747
https://github.com/AlexanderMoskovkin/qunit-harness/blob/fde6210031e9d7fb6759f7124e689d0dbe70e747/vendor/qunit-1.20.0.js#L1401-L1430
45,062
CodeboxIDE/large-watcher
find.js
find
function find(dirname, args, cb) { var spawned = execFile( '/usr/bin/find', ['./'].concat(args), { maxBuffer: 4000*1024, cwd: dirname, }, execHandler(cb) ); // Handle error spawned.once('error', cb); }
javascript
function find(dirname, args, cb) { var spawned = execFile( '/usr/bin/find', ['./'].concat(args), { maxBuffer: 4000*1024, cwd: dirname, }, execHandler(cb) ); // Handle error spawned.once('error', cb); }
[ "function", "find", "(", "dirname", ",", "args", ",", "cb", ")", "{", "var", "spawned", "=", "execFile", "(", "'/usr/bin/find'", ",", "[", "'./'", "]", ".", "concat", "(", "args", ")", ",", "{", "maxBuffer", ":", "4000", "*", "1024", ",", "cwd", ":", "dirname", ",", "}", ",", "execHandler", "(", "cb", ")", ")", ";", "// Handle error", "spawned", ".", "once", "(", "'error'", ",", "cb", ")", ";", "}" ]
Wrapper of find command
[ "Wrapper", "of", "find", "command" ]
876af5d8964b73348d5bcaaecff9b4d3fb7f8d03
https://github.com/CodeboxIDE/large-watcher/blob/876af5d8964b73348d5bcaaecff9b4d3fb7f8d03/find.js#L26-L39
45,063
CodeboxIDE/large-watcher
find.js
modifiedSince
function modifiedSince(dirname, time, shouldPrune, cb) { // Make sure time is in seconds var timestr = Math.ceil(time + 1).toString(); var args = [ '-type', 'f', // Modified less than time seconds ago '-newermt', timestr+' seconds ago', ]; if(shouldPrune) { args = EXCLUDED_ARGS.concat(args); } // Run the command find(dirname, args, cb); }
javascript
function modifiedSince(dirname, time, shouldPrune, cb) { // Make sure time is in seconds var timestr = Math.ceil(time + 1).toString(); var args = [ '-type', 'f', // Modified less than time seconds ago '-newermt', timestr+' seconds ago', ]; if(shouldPrune) { args = EXCLUDED_ARGS.concat(args); } // Run the command find(dirname, args, cb); }
[ "function", "modifiedSince", "(", "dirname", ",", "time", ",", "shouldPrune", ",", "cb", ")", "{", "// Make sure time is in seconds", "var", "timestr", "=", "Math", ".", "ceil", "(", "time", "+", "1", ")", ".", "toString", "(", ")", ";", "var", "args", "=", "[", "'-type'", ",", "'f'", ",", "// Modified less than time seconds ago", "'-newermt'", ",", "timestr", "+", "' seconds ago'", ",", "]", ";", "if", "(", "shouldPrune", ")", "{", "args", "=", "EXCLUDED_ARGS", ".", "concat", "(", "args", ")", ";", "}", "// Run the command", "find", "(", "dirname", ",", "args", ",", "cb", ")", ";", "}" ]
Get all modified files since "time" seconds ago
[ "Get", "all", "modified", "files", "since", "time", "seconds", "ago" ]
876af5d8964b73348d5bcaaecff9b4d3fb7f8d03
https://github.com/CodeboxIDE/large-watcher/blob/876af5d8964b73348d5bcaaecff9b4d3fb7f8d03/find.js#L42-L58
45,064
CodeboxIDE/large-watcher
find.js
dumpTree
function dumpTree(dirname, shouldPrune, cb) { var args = ['-type', 'f']; if(shouldPrune) { args = EXCLUDED_ARGS.concat(args); } find(dirname, args, cb); }
javascript
function dumpTree(dirname, shouldPrune, cb) { var args = ['-type', 'f']; if(shouldPrune) { args = EXCLUDED_ARGS.concat(args); } find(dirname, args, cb); }
[ "function", "dumpTree", "(", "dirname", ",", "shouldPrune", ",", "cb", ")", "{", "var", "args", "=", "[", "'-type'", ",", "'f'", "]", ";", "if", "(", "shouldPrune", ")", "{", "args", "=", "EXCLUDED_ARGS", ".", "concat", "(", "args", ")", ";", "}", "find", "(", "dirname", ",", "args", ",", "cb", ")", ";", "}" ]
Get filetree of a folder
[ "Get", "filetree", "of", "a", "folder" ]
876af5d8964b73348d5bcaaecff9b4d3fb7f8d03
https://github.com/CodeboxIDE/large-watcher/blob/876af5d8964b73348d5bcaaecff9b4d3fb7f8d03/find.js#L61-L68
45,065
evanlucas/lintit
rules/indent.js
validateTokenIndent
function validateTokenIndent(token, desiredIndentLevel) { const indentation = tokenInfo.getTokenIndent(token); const expectedChar = indentType === "space" ? " " : "\t"; return indentation === expectedChar.repeat(desiredIndentLevel * indentSize) || // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs. indentation.includes(" ") && indentation.includes("\t"); }
javascript
function validateTokenIndent(token, desiredIndentLevel) { const indentation = tokenInfo.getTokenIndent(token); const expectedChar = indentType === "space" ? " " : "\t"; return indentation === expectedChar.repeat(desiredIndentLevel * indentSize) || // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs. indentation.includes(" ") && indentation.includes("\t"); }
[ "function", "validateTokenIndent", "(", "token", ",", "desiredIndentLevel", ")", "{", "const", "indentation", "=", "tokenInfo", ".", "getTokenIndent", "(", "token", ")", ";", "const", "expectedChar", "=", "indentType", "===", "\"space\"", "?", "\" \"", ":", "\"\\t\"", ";", "return", "indentation", "===", "expectedChar", ".", "repeat", "(", "desiredIndentLevel", "*", "indentSize", ")", "||", "// To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.", "indentation", ".", "includes", "(", "\" \"", ")", "&&", "indentation", ".", "includes", "(", "\"\\t\"", ")", ";", "}" ]
Checks if a token's indentation is correct @param {Token} token Token to examine @param {int} desiredIndentLevel needed indent level @returns {boolean} `true` if the token's indentation is correct
[ "Checks", "if", "a", "token", "s", "indentation", "is", "correct" ]
7ae771e973a618eeb533184cdd8bec051cb7cd33
https://github.com/evanlucas/lintit/blob/7ae771e973a618eeb533184cdd8bec051cb7cd33/rules/indent.js#L728-L736
45,066
evanlucas/lintit
rules/indent.js
getFirstToken
function getFirstToken(element) { let token = sourceCode.getTokenBefore(element); while (astUtils.isOpeningParenToken(token) && token !== startToken) { token = sourceCode.getTokenBefore(token); } return sourceCode.getTokenAfter(token); }
javascript
function getFirstToken(element) { let token = sourceCode.getTokenBefore(element); while (astUtils.isOpeningParenToken(token) && token !== startToken) { token = sourceCode.getTokenBefore(token); } return sourceCode.getTokenAfter(token); }
[ "function", "getFirstToken", "(", "element", ")", "{", "let", "token", "=", "sourceCode", ".", "getTokenBefore", "(", "element", ")", ";", "while", "(", "astUtils", ".", "isOpeningParenToken", "(", "token", ")", "&&", "token", "!==", "startToken", ")", "{", "token", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ")", ";", "}", "return", "sourceCode", ".", "getTokenAfter", "(", "token", ")", ";", "}" ]
Gets the first token of a given element, including surrounding parentheses. @param {ASTNode} element A node in the `elements` list @returns {Token} The first token of this element
[ "Gets", "the", "first", "token", "of", "a", "given", "element", "including", "surrounding", "parentheses", "." ]
7ae771e973a618eeb533184cdd8bec051cb7cd33
https://github.com/evanlucas/lintit/blob/7ae771e973a618eeb533184cdd8bec051cb7cd33/rules/indent.js#L787-L794
45,067
evanlucas/lintit
rules/indent.js
addBlocklessNodeIndent
function addBlocklessNodeIndent(node) { if (node.type !== "BlockStatement") { const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken); let firstBodyToken = sourceCode.getFirstToken(node); let lastBodyToken = sourceCode.getLastToken(node); while ( astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) && astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken)) ) { firstBodyToken = sourceCode.getTokenBefore(firstBodyToken); lastBodyToken = sourceCode.getTokenAfter(lastBodyToken); } offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1); /* * For blockless nodes with semicolon-first style, don't indent the semicolon. * e.g. * if (foo) bar() * ; [1, 2, 3].map(foo) */ const lastToken = sourceCode.getLastToken(node); if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) { offsets.setDesiredOffset(lastToken, lastParentToken, 0); } } }
javascript
function addBlocklessNodeIndent(node) { if (node.type !== "BlockStatement") { const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken); let firstBodyToken = sourceCode.getFirstToken(node); let lastBodyToken = sourceCode.getLastToken(node); while ( astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) && astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken)) ) { firstBodyToken = sourceCode.getTokenBefore(firstBodyToken); lastBodyToken = sourceCode.getTokenAfter(lastBodyToken); } offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1); /* * For blockless nodes with semicolon-first style, don't indent the semicolon. * e.g. * if (foo) bar() * ; [1, 2, 3].map(foo) */ const lastToken = sourceCode.getLastToken(node); if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) { offsets.setDesiredOffset(lastToken, lastParentToken, 0); } } }
[ "function", "addBlocklessNodeIndent", "(", "node", ")", "{", "if", "(", "node", ".", "type", "!==", "\"BlockStatement\"", ")", "{", "const", "lastParentToken", "=", "sourceCode", ".", "getTokenBefore", "(", "node", ",", "astUtils", ".", "isNotOpeningParenToken", ")", ";", "let", "firstBodyToken", "=", "sourceCode", ".", "getFirstToken", "(", "node", ")", ";", "let", "lastBodyToken", "=", "sourceCode", ".", "getLastToken", "(", "node", ")", ";", "while", "(", "astUtils", ".", "isOpeningParenToken", "(", "sourceCode", ".", "getTokenBefore", "(", "firstBodyToken", ")", ")", "&&", "astUtils", ".", "isClosingParenToken", "(", "sourceCode", ".", "getTokenAfter", "(", "lastBodyToken", ")", ")", ")", "{", "firstBodyToken", "=", "sourceCode", ".", "getTokenBefore", "(", "firstBodyToken", ")", ";", "lastBodyToken", "=", "sourceCode", ".", "getTokenAfter", "(", "lastBodyToken", ")", ";", "}", "offsets", ".", "setDesiredOffsets", "(", "[", "firstBodyToken", ".", "range", "[", "0", "]", ",", "lastBodyToken", ".", "range", "[", "1", "]", "]", ",", "lastParentToken", ",", "1", ")", ";", "/*\n * For blockless nodes with semicolon-first style, don't indent the semicolon.\n * e.g.\n * if (foo) bar()\n * ; [1, 2, 3].map(foo)\n */", "const", "lastToken", "=", "sourceCode", ".", "getLastToken", "(", "node", ")", ";", "if", "(", "node", ".", "type", "!==", "\"EmptyStatement\"", "&&", "astUtils", ".", "isSemicolonToken", "(", "lastToken", ")", ")", "{", "offsets", ".", "setDesiredOffset", "(", "lastToken", ",", "lastParentToken", ",", "0", ")", ";", "}", "}", "}" ]
Check and decide whether to check for indentation for blockless nodes Scenarios are for or while statements without braces around them @param {ASTNode} node node to examine @returns {void}
[ "Check", "and", "decide", "whether", "to", "check", "for", "indentation", "for", "blockless", "nodes", "Scenarios", "are", "for", "or", "while", "statements", "without", "braces", "around", "them" ]
7ae771e973a618eeb533184cdd8bec051cb7cd33
https://github.com/evanlucas/lintit/blob/7ae771e973a618eeb533184cdd8bec051cb7cd33/rules/indent.js#L834-L863
45,068
evanlucas/lintit
rules/indent.js
addParensIndent
function addParensIndent(tokens) { const parenStack = []; const parenPairs = []; tokens.forEach(nextToken => { // Accumulate a list of parenthesis pairs if (astUtils.isOpeningParenToken(nextToken)) { parenStack.push(nextToken); } else if (astUtils.isClosingParenToken(nextToken)) { parenPairs.unshift({ left: parenStack.pop(), right: nextToken }); } }); parenPairs.forEach(pair => { const leftParen = pair.left; const rightParen = pair.right; // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments. if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) { const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen)); parenthesizedTokens.forEach(token => { if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) { offsets.setDesiredOffset(token, leftParen, 1); } }); } offsets.setDesiredOffset(rightParen, leftParen, 0); }); }
javascript
function addParensIndent(tokens) { const parenStack = []; const parenPairs = []; tokens.forEach(nextToken => { // Accumulate a list of parenthesis pairs if (astUtils.isOpeningParenToken(nextToken)) { parenStack.push(nextToken); } else if (astUtils.isClosingParenToken(nextToken)) { parenPairs.unshift({ left: parenStack.pop(), right: nextToken }); } }); parenPairs.forEach(pair => { const leftParen = pair.left; const rightParen = pair.right; // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments. if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) { const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen)); parenthesizedTokens.forEach(token => { if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) { offsets.setDesiredOffset(token, leftParen, 1); } }); } offsets.setDesiredOffset(rightParen, leftParen, 0); }); }
[ "function", "addParensIndent", "(", "tokens", ")", "{", "const", "parenStack", "=", "[", "]", ";", "const", "parenPairs", "=", "[", "]", ";", "tokens", ".", "forEach", "(", "nextToken", "=>", "{", "// Accumulate a list of parenthesis pairs", "if", "(", "astUtils", ".", "isOpeningParenToken", "(", "nextToken", ")", ")", "{", "parenStack", ".", "push", "(", "nextToken", ")", ";", "}", "else", "if", "(", "astUtils", ".", "isClosingParenToken", "(", "nextToken", ")", ")", "{", "parenPairs", ".", "unshift", "(", "{", "left", ":", "parenStack", ".", "pop", "(", ")", ",", "right", ":", "nextToken", "}", ")", ";", "}", "}", ")", ";", "parenPairs", ".", "forEach", "(", "pair", "=>", "{", "const", "leftParen", "=", "pair", ".", "left", ";", "const", "rightParen", "=", "pair", ".", "right", ";", "// We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.", "if", "(", "!", "parameterParens", ".", "has", "(", "leftParen", ")", "&&", "!", "parameterParens", ".", "has", "(", "rightParen", ")", ")", "{", "const", "parenthesizedTokens", "=", "new", "Set", "(", "sourceCode", ".", "getTokensBetween", "(", "leftParen", ",", "rightParen", ")", ")", ";", "parenthesizedTokens", ".", "forEach", "(", "token", "=>", "{", "if", "(", "!", "parenthesizedTokens", ".", "has", "(", "offsets", ".", "getFirstDependency", "(", "token", ")", ")", ")", "{", "offsets", ".", "setDesiredOffset", "(", "token", ",", "leftParen", ",", "1", ")", ";", "}", "}", ")", ";", "}", "offsets", ".", "setDesiredOffset", "(", "rightParen", ",", "leftParen", ",", "0", ")", ";", "}", ")", ";", "}" ]
Checks the indentation of parenthesized values, given a list of tokens in a program @param {Token[]} tokens A list of tokens @returns {void}
[ "Checks", "the", "indentation", "of", "parenthesized", "values", "given", "a", "list", "of", "tokens", "in", "a", "program" ]
7ae771e973a618eeb533184cdd8bec051cb7cd33
https://github.com/evanlucas/lintit/blob/7ae771e973a618eeb533184cdd8bec051cb7cd33/rules/indent.js#L892-L923
45,069
evanlucas/lintit
rules/indent.js
ignoreNode
function ignoreNode(node) { const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true })); unknownNodeTokens.forEach(token => { if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) { const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token); if (token === firstTokenOfLine) { offsets.ignoreToken(token); } else { offsets.setDesiredOffset(token, firstTokenOfLine, 0); } } }); }
javascript
function ignoreNode(node) { const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true })); unknownNodeTokens.forEach(token => { if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) { const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token); if (token === firstTokenOfLine) { offsets.ignoreToken(token); } else { offsets.setDesiredOffset(token, firstTokenOfLine, 0); } } }); }
[ "function", "ignoreNode", "(", "node", ")", "{", "const", "unknownNodeTokens", "=", "new", "Set", "(", "sourceCode", ".", "getTokens", "(", "node", ",", "{", "includeComments", ":", "true", "}", ")", ")", ";", "unknownNodeTokens", ".", "forEach", "(", "token", "=>", "{", "if", "(", "!", "unknownNodeTokens", ".", "has", "(", "offsets", ".", "getFirstDependency", "(", "token", ")", ")", ")", "{", "const", "firstTokenOfLine", "=", "tokenInfo", ".", "getFirstTokenOfLine", "(", "token", ")", ";", "if", "(", "token", "===", "firstTokenOfLine", ")", "{", "offsets", ".", "ignoreToken", "(", "token", ")", ";", "}", "else", "{", "offsets", ".", "setDesiredOffset", "(", "token", ",", "firstTokenOfLine", ",", "0", ")", ";", "}", "}", "}", ")", ";", "}" ]
Ignore all tokens within an unknown node whose offset do not depend on another token's offset within the unknown node @param {ASTNode} node Unknown Node @returns {void}
[ "Ignore", "all", "tokens", "within", "an", "unknown", "node", "whose", "offset", "do", "not", "depend", "on", "another", "token", "s", "offset", "within", "the", "unknown", "node" ]
7ae771e973a618eeb533184cdd8bec051cb7cd33
https://github.com/evanlucas/lintit/blob/7ae771e973a618eeb533184cdd8bec051cb7cd33/rules/indent.js#L931-L945
45,070
evanlucas/lintit
rules/indent.js
isFirstTokenOfStatement
function isFirstTokenOfStatement(token, leafNode) { let node = leafNode; while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) { node = node.parent; } node = node.parent; return !node || node.range[0] === token.range[0]; }
javascript
function isFirstTokenOfStatement(token, leafNode) { let node = leafNode; while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) { node = node.parent; } node = node.parent; return !node || node.range[0] === token.range[0]; }
[ "function", "isFirstTokenOfStatement", "(", "token", ",", "leafNode", ")", "{", "let", "node", "=", "leafNode", ";", "while", "(", "node", ".", "parent", "&&", "!", "node", ".", "parent", ".", "type", ".", "endsWith", "(", "\"Statement\"", ")", "&&", "!", "node", ".", "parent", ".", "type", ".", "endsWith", "(", "\"Declaration\"", ")", ")", "{", "node", "=", "node", ".", "parent", ";", "}", "node", "=", "node", ".", "parent", ";", "return", "!", "node", "||", "node", ".", "range", "[", "0", "]", "===", "token", ".", "range", "[", "0", "]", ";", "}" ]
Check whether the given token is the first token of a statement. @param {Token} token The token to check. @param {ASTNode} leafNode The expression node that the token belongs directly. @returns {boolean} `true` if the token is the first token of a statement.
[ "Check", "whether", "the", "given", "token", "is", "the", "first", "token", "of", "a", "statement", "." ]
7ae771e973a618eeb533184cdd8bec051cb7cd33
https://github.com/evanlucas/lintit/blob/7ae771e973a618eeb533184cdd8bec051cb7cd33/rules/indent.js#L953-L962
45,071
flogvit/textify
lib/textify.js
prototypeString
function prototypeString(method) { for(var func in funcs) { if (method !== undefined && func != method) { continue; } var mod = funcs[func]; var pcount = mods[mod].funcs[func]; if (!String.prototype.hasOwnProperty(func)) { var proto = "Object.defineProperty(String.prototype, " +"'"+func+"'," +"{value: function(params){ return mods['"+mod+"']."+func+"(this.toString(), params);}," +"enumerable: false})"; eval(proto); } } }
javascript
function prototypeString(method) { for(var func in funcs) { if (method !== undefined && func != method) { continue; } var mod = funcs[func]; var pcount = mods[mod].funcs[func]; if (!String.prototype.hasOwnProperty(func)) { var proto = "Object.defineProperty(String.prototype, " +"'"+func+"'," +"{value: function(params){ return mods['"+mod+"']."+func+"(this.toString(), params);}," +"enumerable: false})"; eval(proto); } } }
[ "function", "prototypeString", "(", "method", ")", "{", "for", "(", "var", "func", "in", "funcs", ")", "{", "if", "(", "method", "!==", "undefined", "&&", "func", "!=", "method", ")", "{", "continue", ";", "}", "var", "mod", "=", "funcs", "[", "func", "]", ";", "var", "pcount", "=", "mods", "[", "mod", "]", ".", "funcs", "[", "func", "]", ";", "if", "(", "!", "String", ".", "prototype", ".", "hasOwnProperty", "(", "func", ")", ")", "{", "var", "proto", "=", "\"Object.defineProperty(String.prototype, \"", "+", "\"'\"", "+", "func", "+", "\"',\"", "+", "\"{value: function(params){ return mods['\"", "+", "mod", "+", "\"'].\"", "+", "func", "+", "\"(this.toString(), params);},\"", "+", "\"enumerable: false})\"", ";", "eval", "(", "proto", ")", ";", "}", "}", "}" ]
Add methods to String prototype Examples: textify.prototypeString(); // prototype all methods textify.prototypeString("texturize"); // prototype texturize method 'test'.texturize(); @param {String} method @return {null}
[ "Add", "methods", "to", "String", "prototype" ]
c8510ac4d5b9f9f86339141a5ae5fa4e1f2db339
https://github.com/flogvit/textify/blob/c8510ac4d5b9f9f86339141a5ae5fa4e1f2db339/lib/textify.js#L30-L45
45,072
jonschlinkert/option-cache
index.js
Options
function Options(options) { if (!(this instanceof Options)) { return new Options(options); } this.defaults = this.defaults || {}; this.options = this.options || {}; if (options) { this.option(options); } }
javascript
function Options(options) { if (!(this instanceof Options)) { return new Options(options); } this.defaults = this.defaults || {}; this.options = this.options || {}; if (options) { this.option(options); } }
[ "function", "Options", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Options", ")", ")", "{", "return", "new", "Options", "(", "options", ")", ";", "}", "this", ".", "defaults", "=", "this", ".", "defaults", "||", "{", "}", ";", "this", ".", "options", "=", "this", ".", "options", "||", "{", "}", ";", "if", "(", "options", ")", "{", "this", ".", "option", "(", "options", ")", ";", "}", "}" ]
Create a new instance of `Options`. ```js var app = new Options(); ``` @param {Object} `options` Initialize with default options. @api public
[ "Create", "a", "new", "instance", "of", "Options", "." ]
f7f390b3b083f7885a63f2b15926ea5d88ecedfd
https://github.com/jonschlinkert/option-cache/blob/f7f390b3b083f7885a63f2b15926ea5d88ecedfd/index.js#L24-L33
45,073
jonschlinkert/option-cache
index.js
function(key, value) { switch (utils.typeOf(key)) { case 'object': this.visit('default', key); break; case 'string': if (typeof value === 'undefined') { return utils.get(this.defaults, key); } utils.set(this.defaults, key, value); break; default: { throw new TypeError('expected a string or object'); } } return this; }
javascript
function(key, value) { switch (utils.typeOf(key)) { case 'object': this.visit('default', key); break; case 'string': if (typeof value === 'undefined') { return utils.get(this.defaults, key); } utils.set(this.defaults, key, value); break; default: { throw new TypeError('expected a string or object'); } } return this; }
[ "function", "(", "key", ",", "value", ")", "{", "switch", "(", "utils", ".", "typeOf", "(", "key", ")", ")", "{", "case", "'object'", ":", "this", ".", "visit", "(", "'default'", ",", "key", ")", ";", "break", ";", "case", "'string'", ":", "if", "(", "typeof", "value", "===", "'undefined'", ")", "{", "return", "utils", ".", "get", "(", "this", ".", "defaults", ",", "key", ")", ";", "}", "utils", ".", "set", "(", "this", ".", "defaults", ",", "key", ",", "value", ")", ";", "break", ";", "default", ":", "{", "throw", "new", "TypeError", "(", "'expected a string or object'", ")", ";", "}", "}", "return", "this", ";", "}" ]
Set or get a default value. Defaults are cached on the `.defaults` object. ```js app.default('admin', false); app.default('admin'); //=> false app.option('admin'); //=> false app.option('admin', true); app.option('admin'); //=> true ``` @name .option @param {String} `key` The option name. @param {*} `value` The value to set. @return {*} Returns a `value` when only `key` is defined. @api public
[ "Set", "or", "get", "a", "default", "value", ".", "Defaults", "are", "cached", "on", "the", ".", "defaults", "object", "." ]
f7f390b3b083f7885a63f2b15926ea5d88ecedfd
https://github.com/jonschlinkert/option-cache/blob/f7f390b3b083f7885a63f2b15926ea5d88ecedfd/index.js#L65-L81
45,074
jonschlinkert/option-cache
index.js
function(key, value, type) { var val = utils.get(this.options, key); if (typeof val === 'undefined' || (type && utils.typeOf(val) !== type)) { return value; } return val; }
javascript
function(key, value, type) { var val = utils.get(this.options, key); if (typeof val === 'undefined' || (type && utils.typeOf(val) !== type)) { return value; } return val; }
[ "function", "(", "key", ",", "value", ",", "type", ")", "{", "var", "val", "=", "utils", ".", "get", "(", "this", ".", "options", ",", "key", ")", ";", "if", "(", "typeof", "val", "===", "'undefined'", "||", "(", "type", "&&", "utils", ".", "typeOf", "(", "val", ")", "!==", "type", ")", ")", "{", "return", "value", ";", "}", "return", "val", ";", "}" ]
Returns the value of `key` or `value`, Or, if `type` is passed and the value of `key` is not the same javascript native type as `type`, then `value` is returned. ```js app.option('admin', true); console.log(app.either('admin', false)); //=> true console.log(app.either('collaborator', false)); //=> false ``` @param {String} `key` @param {any} `value` @param {String} `type` Javascript native type (optional) @return {Object} @api public
[ "Returns", "the", "value", "of", "key", "or", "value", "Or", "if", "type", "is", "passed", "and", "the", "value", "of", "key", "is", "not", "the", "same", "javascript", "native", "type", "as", "type", "then", "value", "is", "returned", "." ]
f7f390b3b083f7885a63f2b15926ea5d88ecedfd
https://github.com/jonschlinkert/option-cache/blob/f7f390b3b083f7885a63f2b15926ea5d88ecedfd/index.js#L138-L144
45,075
jrmerz/node-ckan
lib/ckan-exporter.js
getPackageSet
function getPackageSet(index, callback) { var page = { limit : 100, offset : index*100 } ckan.exec('current_package_list_with_resources', page, function(err, resp){ checkError(err, resp); for( var i = 0; i < resp.result.length; i++ ) { data.packages[resp.result[i].id] = resp.result[i]; } if( resp.result.length == 0 ) { if( callback ) callback(); } else { if( options.debug ) console.log("CKAN EXPORT: Package data loaded ("+(index*100)+" to "+((index+1)*100)+")"); index++; getPackageSet(index, callback); } }); }
javascript
function getPackageSet(index, callback) { var page = { limit : 100, offset : index*100 } ckan.exec('current_package_list_with_resources', page, function(err, resp){ checkError(err, resp); for( var i = 0; i < resp.result.length; i++ ) { data.packages[resp.result[i].id] = resp.result[i]; } if( resp.result.length == 0 ) { if( callback ) callback(); } else { if( options.debug ) console.log("CKAN EXPORT: Package data loaded ("+(index*100)+" to "+((index+1)*100)+")"); index++; getPackageSet(index, callback); } }); }
[ "function", "getPackageSet", "(", "index", ",", "callback", ")", "{", "var", "page", "=", "{", "limit", ":", "100", ",", "offset", ":", "index", "*", "100", "}", "ckan", ".", "exec", "(", "'current_package_list_with_resources'", ",", "page", ",", "function", "(", "err", ",", "resp", ")", "{", "checkError", "(", "err", ",", "resp", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "resp", ".", "result", ".", "length", ";", "i", "++", ")", "{", "data", ".", "packages", "[", "resp", ".", "result", "[", "i", "]", ".", "id", "]", "=", "resp", ".", "result", "[", "i", "]", ";", "}", "if", "(", "resp", ".", "result", ".", "length", "==", "0", ")", "{", "if", "(", "callback", ")", "callback", "(", ")", ";", "}", "else", "{", "if", "(", "options", ".", "debug", ")", "console", ".", "log", "(", "\"CKAN EXPORT: Package data loaded (\"", "+", "(", "index", "*", "100", ")", "+", "\" to \"", "+", "(", "(", "index", "+", "1", ")", "*", "100", ")", "+", "\")\"", ")", ";", "index", "++", ";", "getPackageSet", "(", "index", ",", "callback", ")", ";", "}", "}", ")", ";", "}" ]
get 100 packages at a time
[ "get", "100", "packages", "at", "a", "time" ]
55f6bb1ece7f57ccd5ba57be7888e4d3941bc659
https://github.com/jrmerz/node-ckan/blob/55f6bb1ece7f57ccd5ba57be7888e4d3941bc659/lib/ckan-exporter.js#L54-L75
45,076
jperezov/vargate
src/models/util.js
function (message, important) { /** @type {string} */ const prefix = 'VarGate SG1 Log:'; /** @type {Array} */ let args = []; if (window['DEBUG_MODE']) { if (typeof message !== 'string' && message.length) { args = message; } else { args.push(message); } args.unshift(prefix); try { switch (window['DEBUG_MODE']) { case 'verbose': console['warn'].apply(console, args); break; case 'static': console['warn'].apply(console, JSON.parse(JSON.stringify(args))); break; case 'minimal': if (important) console['warn'].apply(console, args); break; default: // do nothing } } catch (e) { // Looks like we can't log anything } } }
javascript
function (message, important) { /** @type {string} */ const prefix = 'VarGate SG1 Log:'; /** @type {Array} */ let args = []; if (window['DEBUG_MODE']) { if (typeof message !== 'string' && message.length) { args = message; } else { args.push(message); } args.unshift(prefix); try { switch (window['DEBUG_MODE']) { case 'verbose': console['warn'].apply(console, args); break; case 'static': console['warn'].apply(console, JSON.parse(JSON.stringify(args))); break; case 'minimal': if (important) console['warn'].apply(console, args); break; default: // do nothing } } catch (e) { // Looks like we can't log anything } } }
[ "function", "(", "message", ",", "important", ")", "{", "/** @type {string} */", "const", "prefix", "=", "'VarGate SG1 Log:'", ";", "/** @type {Array} */", "let", "args", "=", "[", "]", ";", "if", "(", "window", "[", "'DEBUG_MODE'", "]", ")", "{", "if", "(", "typeof", "message", "!==", "'string'", "&&", "message", ".", "length", ")", "{", "args", "=", "message", ";", "}", "else", "{", "args", ".", "push", "(", "message", ")", ";", "}", "args", ".", "unshift", "(", "prefix", ")", ";", "try", "{", "switch", "(", "window", "[", "'DEBUG_MODE'", "]", ")", "{", "case", "'verbose'", ":", "console", "[", "'warn'", "]", ".", "apply", "(", "console", ",", "args", ")", ";", "break", ";", "case", "'static'", ":", "console", "[", "'warn'", "]", ".", "apply", "(", "console", ",", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "args", ")", ")", ")", ";", "break", ";", "case", "'minimal'", ":", "if", "(", "important", ")", "console", "[", "'warn'", "]", ".", "apply", "(", "console", ",", "args", ")", ";", "break", ";", "default", ":", "// do nothing", "}", "}", "catch", "(", "e", ")", "{", "// Looks like we can't log anything", "}", "}", "}" ]
Conditionally logs messages to help debug based on the value of DEBUG_MODE @param {Array|string} message @param {boolean=} important
[ "Conditionally", "logs", "messages", "to", "help", "debug", "based", "on", "the", "value", "of", "DEBUG_MODE" ]
97993224d59639cec9eda935694cdb0394d72082
https://github.com/jperezov/vargate/blob/97993224d59639cec9eda935694cdb0394d72082/src/models/util.js#L38-L68
45,077
blakeembrey/popsicle-server
popsicle-server.js
popsicleServer
function popsicleServer (app) { var server = serverAddress(app) return function (req, next) { server.listen() req.url = server.url(req.url) return promiseFinally(next(), function () { server.close() }) } }
javascript
function popsicleServer (app) { var server = serverAddress(app) return function (req, next) { server.listen() req.url = server.url(req.url) return promiseFinally(next(), function () { server.close() }) } }
[ "function", "popsicleServer", "(", "app", ")", "{", "var", "server", "=", "serverAddress", "(", "app", ")", "return", "function", "(", "req", ",", "next", ")", "{", "server", ".", "listen", "(", ")", "req", ".", "url", "=", "server", ".", "url", "(", "req", ".", "url", ")", "return", "promiseFinally", "(", "next", "(", ")", ",", "function", "(", ")", "{", "server", ".", "close", "(", ")", "}", ")", "}", "}" ]
Create a request interceptor that listens and disconnects automatically. @param {Function} app @return {Function}
[ "Create", "a", "request", "interceptor", "that", "listens", "and", "disconnects", "automatically", "." ]
a245a4a6071099445e317d341376ba39f551e191
https://github.com/blakeembrey/popsicle-server/blob/a245a4a6071099445e317d341376ba39f551e191/popsicle-server.js#L15-L27
45,078
onecommons/base
public/js/jquery.downCount.js
function () { // get client's current date var date = new Date(); // turn date to utc var utc = date.getTime() + (date.getTimezoneOffset() * 60000); // set new Date object var new_date = new Date(utc + (3600000*settings.offset)) return new_date; }
javascript
function () { // get client's current date var date = new Date(); // turn date to utc var utc = date.getTime() + (date.getTimezoneOffset() * 60000); // set new Date object var new_date = new Date(utc + (3600000*settings.offset)) return new_date; }
[ "function", "(", ")", "{", "// get client's current date", "var", "date", "=", "new", "Date", "(", ")", ";", "// turn date to utc", "var", "utc", "=", "date", ".", "getTime", "(", ")", "+", "(", "date", ".", "getTimezoneOffset", "(", ")", "*", "60000", ")", ";", "// set new Date object", "var", "new_date", "=", "new", "Date", "(", "utc", "+", "(", "3600000", "*", "settings", ".", "offset", ")", ")", "return", "new_date", ";", "}" ]
Change client's local date to match offset timezone @return {Object} Fixed Date object.
[ "Change", "client", "s", "local", "date", "to", "match", "offset", "timezone" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/public/js/jquery.downCount.js#L31-L42
45,079
onecommons/base
public/js/jquery.downCount.js
countdown
function countdown () { var target_date = new Date(settings.date), // set target date current_date = currentDate(); // get fixed current date // difference of dates var difference = target_date - current_date; // if difference is negative than it's pass the target date if (difference < 0) { // stop timer clearInterval(interval); if (callback && typeof callback === 'function') callback(); return; } // basic math variables var _second = 1000, _minute = _second * 60, _hour = _minute * 60, _day = _hour * 24; // calculate dates var days = Math.floor(difference / _day), hours = Math.floor((difference % _day) / _hour), minutes = Math.floor((difference % _hour) / _minute), seconds = Math.floor((difference % _minute) / _second); // fix dates so that it will show two digets days = (String(days).length >= 2) ? days : '0' + days; hours = (String(hours).length >= 2) ? hours : '0' + hours; minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes; seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds; // based on the date change the refrence wording var ref_days = (days === 1) ? 'day' : 'days', ref_hours = (hours === 1) ? 'hour' : 'hours', ref_minutes = (minutes === 1) ? 'minute' : 'minutes', ref_seconds = (seconds === 1) ? 'second' : 'seconds'; // set to DOM container.find('.days').text(days); container.find('.hours').text(hours); container.find('.minutes').text(minutes); container.find('.seconds').text(seconds); container.find('.days_ref').text(ref_days); container.find('.hours_ref').text(ref_hours); container.find('.minutes_ref').text(ref_minutes); container.find('.seconds_ref').text(ref_seconds); }
javascript
function countdown () { var target_date = new Date(settings.date), // set target date current_date = currentDate(); // get fixed current date // difference of dates var difference = target_date - current_date; // if difference is negative than it's pass the target date if (difference < 0) { // stop timer clearInterval(interval); if (callback && typeof callback === 'function') callback(); return; } // basic math variables var _second = 1000, _minute = _second * 60, _hour = _minute * 60, _day = _hour * 24; // calculate dates var days = Math.floor(difference / _day), hours = Math.floor((difference % _day) / _hour), minutes = Math.floor((difference % _hour) / _minute), seconds = Math.floor((difference % _minute) / _second); // fix dates so that it will show two digets days = (String(days).length >= 2) ? days : '0' + days; hours = (String(hours).length >= 2) ? hours : '0' + hours; minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes; seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds; // based on the date change the refrence wording var ref_days = (days === 1) ? 'day' : 'days', ref_hours = (hours === 1) ? 'hour' : 'hours', ref_minutes = (minutes === 1) ? 'minute' : 'minutes', ref_seconds = (seconds === 1) ? 'second' : 'seconds'; // set to DOM container.find('.days').text(days); container.find('.hours').text(hours); container.find('.minutes').text(minutes); container.find('.seconds').text(seconds); container.find('.days_ref').text(ref_days); container.find('.hours_ref').text(ref_hours); container.find('.minutes_ref').text(ref_minutes); container.find('.seconds_ref').text(ref_seconds); }
[ "function", "countdown", "(", ")", "{", "var", "target_date", "=", "new", "Date", "(", "settings", ".", "date", ")", ",", "// set target date", "current_date", "=", "currentDate", "(", ")", ";", "// get fixed current date", "// difference of dates", "var", "difference", "=", "target_date", "-", "current_date", ";", "// if difference is negative than it's pass the target date", "if", "(", "difference", "<", "0", ")", "{", "// stop timer", "clearInterval", "(", "interval", ")", ";", "if", "(", "callback", "&&", "typeof", "callback", "===", "'function'", ")", "callback", "(", ")", ";", "return", ";", "}", "// basic math variables", "var", "_second", "=", "1000", ",", "_minute", "=", "_second", "*", "60", ",", "_hour", "=", "_minute", "*", "60", ",", "_day", "=", "_hour", "*", "24", ";", "// calculate dates", "var", "days", "=", "Math", ".", "floor", "(", "difference", "/", "_day", ")", ",", "hours", "=", "Math", ".", "floor", "(", "(", "difference", "%", "_day", ")", "/", "_hour", ")", ",", "minutes", "=", "Math", ".", "floor", "(", "(", "difference", "%", "_hour", ")", "/", "_minute", ")", ",", "seconds", "=", "Math", ".", "floor", "(", "(", "difference", "%", "_minute", ")", "/", "_second", ")", ";", "// fix dates so that it will show two digets", "days", "=", "(", "String", "(", "days", ")", ".", "length", ">=", "2", ")", "?", "days", ":", "'0'", "+", "days", ";", "hours", "=", "(", "String", "(", "hours", ")", ".", "length", ">=", "2", ")", "?", "hours", ":", "'0'", "+", "hours", ";", "minutes", "=", "(", "String", "(", "minutes", ")", ".", "length", ">=", "2", ")", "?", "minutes", ":", "'0'", "+", "minutes", ";", "seconds", "=", "(", "String", "(", "seconds", ")", ".", "length", ">=", "2", ")", "?", "seconds", ":", "'0'", "+", "seconds", ";", "// based on the date change the refrence wording", "var", "ref_days", "=", "(", "days", "===", "1", ")", "?", "'day'", ":", "'days'", ",", "ref_hours", "=", "(", "hours", "===", "1", ")", "?", "'hour'", ":", "'hours'", ",", "ref_minutes", "=", "(", "minutes", "===", "1", ")", "?", "'minute'", ":", "'minutes'", ",", "ref_seconds", "=", "(", "seconds", "===", "1", ")", "?", "'second'", ":", "'seconds'", ";", "// set to DOM", "container", ".", "find", "(", "'.days'", ")", ".", "text", "(", "days", ")", ";", "container", ".", "find", "(", "'.hours'", ")", ".", "text", "(", "hours", ")", ";", "container", ".", "find", "(", "'.minutes'", ")", ".", "text", "(", "minutes", ")", ";", "container", ".", "find", "(", "'.seconds'", ")", ".", "text", "(", "seconds", ")", ";", "container", ".", "find", "(", "'.days_ref'", ")", ".", "text", "(", "ref_days", ")", ";", "container", ".", "find", "(", "'.hours_ref'", ")", ".", "text", "(", "ref_hours", ")", ";", "container", ".", "find", "(", "'.minutes_ref'", ")", ".", "text", "(", "ref_minutes", ")", ";", "container", ".", "find", "(", "'.seconds_ref'", ")", ".", "text", "(", "ref_seconds", ")", ";", "}" ]
Main downCount function that calculates everything
[ "Main", "downCount", "function", "that", "calculates", "everything" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/public/js/jquery.downCount.js#L47-L98
45,080
websiteflash/grunt-ftp-upload
tasks/ftp_upload.js
ftpCwd
function ftpCwd(inPath, cb) { ftp.raw.cwd(inPath, function(err) { if (err) { ftp.raw.mkd(inPath, function(err) { if (err) { log.error('Error creating new remote folder ' + inPath + ' --> ' + err); cb(err); } else { log.ok('New remote folder created ' + inPath.yellow); ftpCwd(inPath, cb); } }); } else { cb(null); } }); }
javascript
function ftpCwd(inPath, cb) { ftp.raw.cwd(inPath, function(err) { if (err) { ftp.raw.mkd(inPath, function(err) { if (err) { log.error('Error creating new remote folder ' + inPath + ' --> ' + err); cb(err); } else { log.ok('New remote folder created ' + inPath.yellow); ftpCwd(inPath, cb); } }); } else { cb(null); } }); }
[ "function", "ftpCwd", "(", "inPath", ",", "cb", ")", "{", "ftp", ".", "raw", ".", "cwd", "(", "inPath", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "ftp", ".", "raw", ".", "mkd", "(", "inPath", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "log", ".", "error", "(", "'Error creating new remote folder '", "+", "inPath", "+", "' --> '", "+", "err", ")", ";", "cb", "(", "err", ")", ";", "}", "else", "{", "log", ".", "ok", "(", "'New remote folder created '", "+", "inPath", ".", "yellow", ")", ";", "ftpCwd", "(", "inPath", ",", "cb", ")", ";", "}", "}", ")", ";", "}", "else", "{", "cb", "(", "null", ")", ";", "}", "}", ")", ";", "}" ]
A method for changing the remote working directory and creating one if it doesn't already exist
[ "A", "method", "for", "changing", "the", "remote", "working", "directory", "and", "creating", "one", "if", "it", "doesn", "t", "already", "exist" ]
12b955779ba831c6849a2211061d3f72548d96c1
https://github.com/websiteflash/grunt-ftp-upload/blob/12b955779ba831c6849a2211061d3f72548d96c1/tasks/ftp_upload.js#L109-L125
45,081
PsychoLlama/mytosis
workspaces/mytosis-leveldb/src/index.js
streamToGenerator
async function* streamToGenerator(stream) { let promise; stream.on('data', data => promise.resolve(data)); stream.once('end', () => promise.resolve(null)); stream.on('error', error => { stream.removeAllListeners(); promise.reject(error); }); while (true) { promise = defer(); yield promise; } }
javascript
async function* streamToGenerator(stream) { let promise; stream.on('data', data => promise.resolve(data)); stream.once('end', () => promise.resolve(null)); stream.on('error', error => { stream.removeAllListeners(); promise.reject(error); }); while (true) { promise = defer(); yield promise; } }
[ "async", "function", "*", "streamToGenerator", "(", "stream", ")", "{", "let", "promise", ";", "stream", ".", "on", "(", "'data'", ",", "data", "=>", "promise", ".", "resolve", "(", "data", ")", ")", ";", "stream", ".", "once", "(", "'end'", ",", "(", ")", "=>", "promise", ".", "resolve", "(", "null", ")", ")", ";", "stream", ".", "on", "(", "'error'", ",", "error", "=>", "{", "stream", ".", "removeAllListeners", "(", ")", ";", "promise", ".", "reject", "(", "error", ")", ";", "}", ")", ";", "while", "(", "true", ")", "{", "promise", "=", "defer", "(", ")", ";", "yield", "promise", ";", "}", "}" ]
Reads values from a object mode readable stream as an async iterator. @param {Stream.Readable} stream - A value stream from levelup. @return {Promise<Object>} - Resolves with each node.
[ "Reads", "values", "from", "a", "object", "mode", "readable", "stream", "as", "an", "async", "iterator", "." ]
4ebe5acb090b1d97d2369e4436a065bd8ec7fbdb
https://github.com/PsychoLlama/mytosis/blob/4ebe5acb090b1d97d2369e4436a065bd8ec7fbdb/workspaces/mytosis-leveldb/src/index.js#L62-L78
45,082
pwambach/mini-mock-api
lib/mini-mock-api.js
function(filePath){ var parts = filePath.split('/'); if(parts.length > 0){ var id = parts.pop(); return { id: id, path: parts.join('/') } } else { return false; } }
javascript
function(filePath){ var parts = filePath.split('/'); if(parts.length > 0){ var id = parts.pop(); return { id: id, path: parts.join('/') } } else { return false; } }
[ "function", "(", "filePath", ")", "{", "var", "parts", "=", "filePath", ".", "split", "(", "'/'", ")", ";", "if", "(", "parts", ".", "length", ">", "0", ")", "{", "var", "id", "=", "parts", ".", "pop", "(", ")", ";", "return", "{", "id", ":", "id", ",", "path", ":", "parts", ".", "join", "(", "'/'", ")", "}", "}", "else", "{", "return", "false", ";", "}", "}" ]
split path in subpath and uuid
[ "split", "path", "in", "subpath", "and", "uuid" ]
1db889af3b61757c7020177e44d9fbc64edb5f06
https://github.com/pwambach/mini-mock-api/blob/1db889af3b61757c7020177e44d9fbc64edb5f06/lib/mini-mock-api.js#L159-L170
45,083
vid/SenseBase
lib/search.js
getQueuedLink
function getQueuedLink(callback, seconds) { var dateField = 'queued.lastAttempt'; seconds = seconds || DELAY_SECONDS; // function to process the link var process = function(err, res) { var queuedLink = null; if (res && res.hits && res.hits.hits.length) { var hit = res.hits.hits[0]._source; var queued = hit.queued; queuedLink = { uri: hit.uri, queued: queued, total: res.hits.total }; queued.lastAttempt = new Date().toISOString(); queued.attempts = queued.attempts + 1; hit.queued = queued; // update accesses contentLib.indexContentItem(hit, {state: 'queued', member: queued.member}, function(err, res) { // process the link if (!err) { callback(null, queuedLink); } else { utils.passingError(err); } }); } else { callback(err, null); } }; // call query with the function GLOBAL.svc.indexer.formQuery({query: { terms: dateField + ':<now-' + seconds + 's AND state:queued AND queued.attempts:<' + MAX_ATTEMPTS }, sort: dateField, sourceFields : ['uri', 'title', 'queued.*'], size : 1 }, process); }
javascript
function getQueuedLink(callback, seconds) { var dateField = 'queued.lastAttempt'; seconds = seconds || DELAY_SECONDS; // function to process the link var process = function(err, res) { var queuedLink = null; if (res && res.hits && res.hits.hits.length) { var hit = res.hits.hits[0]._source; var queued = hit.queued; queuedLink = { uri: hit.uri, queued: queued, total: res.hits.total }; queued.lastAttempt = new Date().toISOString(); queued.attempts = queued.attempts + 1; hit.queued = queued; // update accesses contentLib.indexContentItem(hit, {state: 'queued', member: queued.member}, function(err, res) { // process the link if (!err) { callback(null, queuedLink); } else { utils.passingError(err); } }); } else { callback(err, null); } }; // call query with the function GLOBAL.svc.indexer.formQuery({query: { terms: dateField + ':<now-' + seconds + 's AND state:queued AND queued.attempts:<' + MAX_ATTEMPTS }, sort: dateField, sourceFields : ['uri', 'title', 'queued.*'], size : 1 }, process); }
[ "function", "getQueuedLink", "(", "callback", ",", "seconds", ")", "{", "var", "dateField", "=", "'queued.lastAttempt'", ";", "seconds", "=", "seconds", "||", "DELAY_SECONDS", ";", "// function to process the link", "var", "process", "=", "function", "(", "err", ",", "res", ")", "{", "var", "queuedLink", "=", "null", ";", "if", "(", "res", "&&", "res", ".", "hits", "&&", "res", ".", "hits", ".", "hits", ".", "length", ")", "{", "var", "hit", "=", "res", ".", "hits", ".", "hits", "[", "0", "]", ".", "_source", ";", "var", "queued", "=", "hit", ".", "queued", ";", "queuedLink", "=", "{", "uri", ":", "hit", ".", "uri", ",", "queued", ":", "queued", ",", "total", ":", "res", ".", "hits", ".", "total", "}", ";", "queued", ".", "lastAttempt", "=", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ";", "queued", ".", "attempts", "=", "queued", ".", "attempts", "+", "1", ";", "hit", ".", "queued", "=", "queued", ";", "// update accesses", "contentLib", ".", "indexContentItem", "(", "hit", ",", "{", "state", ":", "'queued'", ",", "member", ":", "queued", ".", "member", "}", ",", "function", "(", "err", ",", "res", ")", "{", "// process the link", "if", "(", "!", "err", ")", "{", "callback", "(", "null", ",", "queuedLink", ")", ";", "}", "else", "{", "utils", ".", "passingError", "(", "err", ")", ";", "}", "}", ")", ";", "}", "else", "{", "callback", "(", "err", ",", "null", ")", ";", "}", "}", ";", "// call query with the function", "GLOBAL", ".", "svc", ".", "indexer", ".", "formQuery", "(", "{", "query", ":", "{", "terms", ":", "dateField", "+", "':<now-'", "+", "seconds", "+", "'s AND state:queued AND queued.attempts:<'", "+", "MAX_ATTEMPTS", "}", ",", "sort", ":", "dateField", ",", "sourceFields", ":", "[", "'uri'", ",", "'title'", ",", "'queued.*'", "]", ",", "size", ":", "1", "}", ",", "process", ")", ";", "}" ]
Get a queued link that hasn't been attempted recently. Callback is usually `getLinkContents`.
[ "Get", "a", "queued", "link", "that", "hasn", "t", "been", "attempted", "recently", ".", "Callback", "is", "usually", "getLinkContents", "." ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/search.js#L23-L55
45,084
vid/SenseBase
lib/search.js
function(err, res) { var queuedLink = null; if (res && res.hits && res.hits.hits.length) { var hit = res.hits.hits[0]._source; var queued = hit.queued; queuedLink = { uri: hit.uri, queued: queued, total: res.hits.total }; queued.lastAttempt = new Date().toISOString(); queued.attempts = queued.attempts + 1; hit.queued = queued; // update accesses contentLib.indexContentItem(hit, {state: 'queued', member: queued.member}, function(err, res) { // process the link if (!err) { callback(null, queuedLink); } else { utils.passingError(err); } }); } else { callback(err, null); } }
javascript
function(err, res) { var queuedLink = null; if (res && res.hits && res.hits.hits.length) { var hit = res.hits.hits[0]._source; var queued = hit.queued; queuedLink = { uri: hit.uri, queued: queued, total: res.hits.total }; queued.lastAttempt = new Date().toISOString(); queued.attempts = queued.attempts + 1; hit.queued = queued; // update accesses contentLib.indexContentItem(hit, {state: 'queued', member: queued.member}, function(err, res) { // process the link if (!err) { callback(null, queuedLink); } else { utils.passingError(err); } }); } else { callback(err, null); } }
[ "function", "(", "err", ",", "res", ")", "{", "var", "queuedLink", "=", "null", ";", "if", "(", "res", "&&", "res", ".", "hits", "&&", "res", ".", "hits", ".", "hits", ".", "length", ")", "{", "var", "hit", "=", "res", ".", "hits", ".", "hits", "[", "0", "]", ".", "_source", ";", "var", "queued", "=", "hit", ".", "queued", ";", "queuedLink", "=", "{", "uri", ":", "hit", ".", "uri", ",", "queued", ":", "queued", ",", "total", ":", "res", ".", "hits", ".", "total", "}", ";", "queued", ".", "lastAttempt", "=", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ";", "queued", ".", "attempts", "=", "queued", ".", "attempts", "+", "1", ";", "hit", ".", "queued", "=", "queued", ";", "// update accesses", "contentLib", ".", "indexContentItem", "(", "hit", ",", "{", "state", ":", "'queued'", ",", "member", ":", "queued", ".", "member", "}", ",", "function", "(", "err", ",", "res", ")", "{", "// process the link", "if", "(", "!", "err", ")", "{", "callback", "(", "null", ",", "queuedLink", ")", ";", "}", "else", "{", "utils", ".", "passingError", "(", "err", ")", ";", "}", "}", ")", ";", "}", "else", "{", "callback", "(", "err", ",", "null", ")", ";", "}", "}" ]
function to process the link
[ "function", "to", "process", "the", "link" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/search.js#L27-L49
45,085
vid/SenseBase
lib/search.js
getLinkContents
function getLinkContents(err, queuedLink) { // no link found if (!queuedLink) { return; } // retrieve https directly var method = (queuedLink.uri.toString().indexOf('https') === 0) ? utils.retrieveHTTPS : utils.retrieve; method(queuedLink.uri, function(err, data) { contentLib.indexContentItem({ uri: ''+queuedLink.uri, content: data}, {isHTML: true, member: queuedLink.queued.member}, function(err, res, cItem) { if (err || !cItem) { GLOBAL.error('getLinkContents failed', err, res); return; } // if it recently gained content queue links if (cItem.state !== utils.states.content.queued && cItem.previousState === utils.states.content.queued) { GLOBAL.info('queueing links', cItem.uri, 'relevance', cItem.queued.relevance); queueLinks(cItem); } GLOBAL.debug('scraped', err, data ? data.length : 'no content'); }); }); }
javascript
function getLinkContents(err, queuedLink) { // no link found if (!queuedLink) { return; } // retrieve https directly var method = (queuedLink.uri.toString().indexOf('https') === 0) ? utils.retrieveHTTPS : utils.retrieve; method(queuedLink.uri, function(err, data) { contentLib.indexContentItem({ uri: ''+queuedLink.uri, content: data}, {isHTML: true, member: queuedLink.queued.member}, function(err, res, cItem) { if (err || !cItem) { GLOBAL.error('getLinkContents failed', err, res); return; } // if it recently gained content queue links if (cItem.state !== utils.states.content.queued && cItem.previousState === utils.states.content.queued) { GLOBAL.info('queueing links', cItem.uri, 'relevance', cItem.queued.relevance); queueLinks(cItem); } GLOBAL.debug('scraped', err, data ? data.length : 'no content'); }); }); }
[ "function", "getLinkContents", "(", "err", ",", "queuedLink", ")", "{", "// no link found", "if", "(", "!", "queuedLink", ")", "{", "return", ";", "}", "// retrieve https directly", "var", "method", "=", "(", "queuedLink", ".", "uri", ".", "toString", "(", ")", ".", "indexOf", "(", "'https'", ")", "===", "0", ")", "?", "utils", ".", "retrieveHTTPS", ":", "utils", ".", "retrieve", ";", "method", "(", "queuedLink", ".", "uri", ",", "function", "(", "err", ",", "data", ")", "{", "contentLib", ".", "indexContentItem", "(", "{", "uri", ":", "''", "+", "queuedLink", ".", "uri", ",", "content", ":", "data", "}", ",", "{", "isHTML", ":", "true", ",", "member", ":", "queuedLink", ".", "queued", ".", "member", "}", ",", "function", "(", "err", ",", "res", ",", "cItem", ")", "{", "if", "(", "err", "||", "!", "cItem", ")", "{", "GLOBAL", ".", "error", "(", "'getLinkContents failed'", ",", "err", ",", "res", ")", ";", "return", ";", "}", "// if it recently gained content queue links", "if", "(", "cItem", ".", "state", "!==", "utils", ".", "states", ".", "content", ".", "queued", "&&", "cItem", ".", "previousState", "===", "utils", ".", "states", ".", "content", ".", "queued", ")", "{", "GLOBAL", ".", "info", "(", "'queueing links'", ",", "cItem", ".", "uri", ",", "'relevance'", ",", "cItem", ".", "queued", ".", "relevance", ")", ";", "queueLinks", "(", "cItem", ")", ";", "}", "GLOBAL", ".", "debug", "(", "'scraped'", ",", "err", ",", "data", "?", "data", ".", "length", ":", "'no content'", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
retrieve and process any queued link
[ "retrieve", "and", "process", "any", "queued", "link" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/search.js#L58-L80
45,086
vid/SenseBase
lib/search.js
queueLinks
function queueLinks(cItem) { if (!cItem.queued || !cItem.queued.categories) { GLOBAL.error('missing queued || queued.categories', cItem.uri, cItem.queued); return; } var relevance = cItem.queued.relevance; if (relevance > 0) { relevance--; var links = contentLib.getRecognizedLinks(cItem); var categories = cItem.queued.categories; // FIXME: add callback for (var type in links) { var typeLinks = links[type], referers = [cItem.uri], state = utils.states.annotations.validated; // FIXME add referers typeLinks.forEach(function(uri) { queueLink(uri, { relevance: relevance, categories: categories, referers: referers, member: cItem.queued.member, state: state}); }); } return links; } }
javascript
function queueLinks(cItem) { if (!cItem.queued || !cItem.queued.categories) { GLOBAL.error('missing queued || queued.categories', cItem.uri, cItem.queued); return; } var relevance = cItem.queued.relevance; if (relevance > 0) { relevance--; var links = contentLib.getRecognizedLinks(cItem); var categories = cItem.queued.categories; // FIXME: add callback for (var type in links) { var typeLinks = links[type], referers = [cItem.uri], state = utils.states.annotations.validated; // FIXME add referers typeLinks.forEach(function(uri) { queueLink(uri, { relevance: relevance, categories: categories, referers: referers, member: cItem.queued.member, state: state}); }); } return links; } }
[ "function", "queueLinks", "(", "cItem", ")", "{", "if", "(", "!", "cItem", ".", "queued", "||", "!", "cItem", ".", "queued", ".", "categories", ")", "{", "GLOBAL", ".", "error", "(", "'missing queued || queued.categories'", ",", "cItem", ".", "uri", ",", "cItem", ".", "queued", ")", ";", "return", ";", "}", "var", "relevance", "=", "cItem", ".", "queued", ".", "relevance", ";", "if", "(", "relevance", ">", "0", ")", "{", "relevance", "--", ";", "var", "links", "=", "contentLib", ".", "getRecognizedLinks", "(", "cItem", ")", ";", "var", "categories", "=", "cItem", ".", "queued", ".", "categories", ";", "// FIXME: add callback", "for", "(", "var", "type", "in", "links", ")", "{", "var", "typeLinks", "=", "links", "[", "type", "]", ",", "referers", "=", "[", "cItem", ".", "uri", "]", ",", "state", "=", "utils", ".", "states", ".", "annotations", ".", "validated", ";", "// FIXME add referers", "typeLinks", ".", "forEach", "(", "function", "(", "uri", ")", "{", "queueLink", "(", "uri", ",", "{", "relevance", ":", "relevance", ",", "categories", ":", "categories", ",", "referers", ":", "referers", ",", "member", ":", "cItem", ".", "queued", ".", "member", ",", "state", ":", "state", "}", ")", ";", "}", ")", ";", "}", "return", "links", ";", "}", "}" ]
add relevant links from cItem
[ "add", "relevant", "links", "from", "cItem" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/search.js#L84-L104
45,087
vid/SenseBase
lib/search.js
queueLink
function queueLink(uri, context) { var queuedDetails = { queueOnly: true, member: context.member, categories: context.categories, relevance: context.relevance, attempts: 0, lastAttempt: new Date().toISOString(), team: context.team }; var toQueue = { title: 'Queued ' + context.categories, uri: uri, state: utils.states.content.queued, queued: queuedDetails}; contentLib.indexContentItem(toQueue, context, utils.passingError); }
javascript
function queueLink(uri, context) { var queuedDetails = { queueOnly: true, member: context.member, categories: context.categories, relevance: context.relevance, attempts: 0, lastAttempt: new Date().toISOString(), team: context.team }; var toQueue = { title: 'Queued ' + context.categories, uri: uri, state: utils.states.content.queued, queued: queuedDetails}; contentLib.indexContentItem(toQueue, context, utils.passingError); }
[ "function", "queueLink", "(", "uri", ",", "context", ")", "{", "var", "queuedDetails", "=", "{", "queueOnly", ":", "true", ",", "member", ":", "context", ".", "member", ",", "categories", ":", "context", ".", "categories", ",", "relevance", ":", "context", ".", "relevance", ",", "attempts", ":", "0", ",", "lastAttempt", ":", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "team", ":", "context", ".", "team", "}", ";", "var", "toQueue", "=", "{", "title", ":", "'Queued '", "+", "context", ".", "categories", ",", "uri", ":", "uri", ",", "state", ":", "utils", ".", "states", ".", "content", ".", "queued", ",", "queued", ":", "queuedDetails", "}", ";", "contentLib", ".", "indexContentItem", "(", "toQueue", ",", "context", ",", "utils", ".", "passingError", ")", ";", "}" ]
queue an individual link
[ "queue", "an", "individual", "link" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/search.js#L107-L111
45,088
vid/SenseBase
lib/search.js
queueSearcher
function queueSearcher(data, cb) { // validate if (data.team && data.team.length > 0 && data.input && data.member && data.categories && data.categories.length > 0) { // log the search GLOBAL.svc.indexer.saveSearchLog({searchID: GLOBAL.svc.indexer.searchID(data), searchDate: new Date()}, utils.passingError); // process it by each member data.team.forEach(function(m) { var user = auth.getUserByUsername(m), context = { member: user.username, input: data.input, relevance: data.relevance, team: data.team, categories: data.categories}; // user not found if (!user) { console.log('queueSearch: user not found', m); } else { console.log('execing', data, 'user', user); // it's a searcher, add links if (user.type === 'Searcher') { if (user.api) { // use query template or just the term context.query = (user.template || '$SBQUERY').replace('$SBQUERY', data.input); context.targetResults = data.targetResults || 10; // one callback per uri searchAPIs.exec(user.api, context, function(err, uri, resultContext) { console.log('got a link', uri); var status; if (err) { utils.passingError(err); } else { status = { uri: uri, source: resultContext.referers }; queueLink(uri, resultContext); } if (cb) { cb(err, status); } }); // scrape style location } else if (user.locations) { user.locations.split('\n').forEach(function(l) { l = l.replace('$SBQUERY', data.input); GLOBAL.info(' /queueSearch', l); queueLink(l, context); }); } else { GLOBAL.error('unknown searcher type', user); } // an annotator or individual } else { GLOBAL.info(' /queueSearch', data.uri); queueLink(data.uri, context); } } }); } else { console.log('missing data', data); } }
javascript
function queueSearcher(data, cb) { // validate if (data.team && data.team.length > 0 && data.input && data.member && data.categories && data.categories.length > 0) { // log the search GLOBAL.svc.indexer.saveSearchLog({searchID: GLOBAL.svc.indexer.searchID(data), searchDate: new Date()}, utils.passingError); // process it by each member data.team.forEach(function(m) { var user = auth.getUserByUsername(m), context = { member: user.username, input: data.input, relevance: data.relevance, team: data.team, categories: data.categories}; // user not found if (!user) { console.log('queueSearch: user not found', m); } else { console.log('execing', data, 'user', user); // it's a searcher, add links if (user.type === 'Searcher') { if (user.api) { // use query template or just the term context.query = (user.template || '$SBQUERY').replace('$SBQUERY', data.input); context.targetResults = data.targetResults || 10; // one callback per uri searchAPIs.exec(user.api, context, function(err, uri, resultContext) { console.log('got a link', uri); var status; if (err) { utils.passingError(err); } else { status = { uri: uri, source: resultContext.referers }; queueLink(uri, resultContext); } if (cb) { cb(err, status); } }); // scrape style location } else if (user.locations) { user.locations.split('\n').forEach(function(l) { l = l.replace('$SBQUERY', data.input); GLOBAL.info(' /queueSearch', l); queueLink(l, context); }); } else { GLOBAL.error('unknown searcher type', user); } // an annotator or individual } else { GLOBAL.info(' /queueSearch', data.uri); queueLink(data.uri, context); } } }); } else { console.log('missing data', data); } }
[ "function", "queueSearcher", "(", "data", ",", "cb", ")", "{", "// validate", "if", "(", "data", ".", "team", "&&", "data", ".", "team", ".", "length", ">", "0", "&&", "data", ".", "input", "&&", "data", ".", "member", "&&", "data", ".", "categories", "&&", "data", ".", "categories", ".", "length", ">", "0", ")", "{", "// log the search", "GLOBAL", ".", "svc", ".", "indexer", ".", "saveSearchLog", "(", "{", "searchID", ":", "GLOBAL", ".", "svc", ".", "indexer", ".", "searchID", "(", "data", ")", ",", "searchDate", ":", "new", "Date", "(", ")", "}", ",", "utils", ".", "passingError", ")", ";", "// process it by each member", "data", ".", "team", ".", "forEach", "(", "function", "(", "m", ")", "{", "var", "user", "=", "auth", ".", "getUserByUsername", "(", "m", ")", ",", "context", "=", "{", "member", ":", "user", ".", "username", ",", "input", ":", "data", ".", "input", ",", "relevance", ":", "data", ".", "relevance", ",", "team", ":", "data", ".", "team", ",", "categories", ":", "data", ".", "categories", "}", ";", "// user not found", "if", "(", "!", "user", ")", "{", "console", ".", "log", "(", "'queueSearch: user not found'", ",", "m", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'execing'", ",", "data", ",", "'user'", ",", "user", ")", ";", "// it's a searcher, add links", "if", "(", "user", ".", "type", "===", "'Searcher'", ")", "{", "if", "(", "user", ".", "api", ")", "{", "// use query template or just the term", "context", ".", "query", "=", "(", "user", ".", "template", "||", "'$SBQUERY'", ")", ".", "replace", "(", "'$SBQUERY'", ",", "data", ".", "input", ")", ";", "context", ".", "targetResults", "=", "data", ".", "targetResults", "||", "10", ";", "// one callback per uri", "searchAPIs", ".", "exec", "(", "user", ".", "api", ",", "context", ",", "function", "(", "err", ",", "uri", ",", "resultContext", ")", "{", "console", ".", "log", "(", "'got a link'", ",", "uri", ")", ";", "var", "status", ";", "if", "(", "err", ")", "{", "utils", ".", "passingError", "(", "err", ")", ";", "}", "else", "{", "status", "=", "{", "uri", ":", "uri", ",", "source", ":", "resultContext", ".", "referers", "}", ";", "queueLink", "(", "uri", ",", "resultContext", ")", ";", "}", "if", "(", "cb", ")", "{", "cb", "(", "err", ",", "status", ")", ";", "}", "}", ")", ";", "// scrape style location", "}", "else", "if", "(", "user", ".", "locations", ")", "{", "user", ".", "locations", ".", "split", "(", "'\\n'", ")", ".", "forEach", "(", "function", "(", "l", ")", "{", "l", "=", "l", ".", "replace", "(", "'$SBQUERY'", ",", "data", ".", "input", ")", ";", "GLOBAL", ".", "info", "(", "' /queueSearch'", ",", "l", ")", ";", "queueLink", "(", "l", ",", "context", ")", ";", "}", ")", ";", "}", "else", "{", "GLOBAL", ".", "error", "(", "'unknown searcher type'", ",", "user", ")", ";", "}", "// an annotator or individual", "}", "else", "{", "GLOBAL", ".", "info", "(", "' /queueSearch'", ",", "data", ".", "uri", ")", ";", "queueLink", "(", "data", ".", "uri", ",", "context", ")", ";", "}", "}", "}", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'missing data'", ",", "data", ")", ";", "}", "}" ]
Process queued searches by members. receives form data, validates it passes links via queueLink for Searchers, queues up found links use cb to send updates
[ "Process", "queued", "searches", "by", "members", ".", "receives", "form", "data", "validates", "it", "passes", "links", "via", "queueLink", "for", "Searchers", "queues", "up", "found", "links", "use", "cb", "to", "send", "updates" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/search.js#L119-L173
45,089
vid/SenseBase
web/lib/annoTree.js
function(o) { this._id++; o.__id = this._id; // FIXME collusion with tree state o._state = o.state; this.mapped[this._id] = o; return this._id; }
javascript
function(o) { this._id++; o.__id = this._id; // FIXME collusion with tree state o._state = o.state; this.mapped[this._id] = o; return this._id; }
[ "function", "(", "o", ")", "{", "this", ".", "_id", "++", ";", "o", ".", "__id", "=", "this", ".", "_id", ";", "// FIXME collusion with tree state", "o", ".", "_state", "=", "o", ".", "state", ";", "this", ".", "mapped", "[", "this", ".", "_id", "]", "=", "o", ";", "return", "this", ".", "_id", ";", "}" ]
get an id
[ "get", "an", "id" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/lib/annoTree.js#L25-L32
45,090
jperezov/vargate
vargate.js
checkDefined
function checkDefined(key) { //noinspection JSPotentiallyInvalidUsageOfThis if (! data[`${this.moduleName}.${key}`] && typeof parent.get(key) !== 'undefined' && ! util.squelch()) { // Not allowing sub-modules to name variables already defined in the parent (unless using override). // Things get weird when expecting a variable defined in two places. //noinspection JSPotentiallyInvalidUsageOfThis util.throw(`In "${this.moduleName}" variable "${key}" defined in module "${parent.moduleName}". Choose a different name.`); } }
javascript
function checkDefined(key) { //noinspection JSPotentiallyInvalidUsageOfThis if (! data[`${this.moduleName}.${key}`] && typeof parent.get(key) !== 'undefined' && ! util.squelch()) { // Not allowing sub-modules to name variables already defined in the parent (unless using override). // Things get weird when expecting a variable defined in two places. //noinspection JSPotentiallyInvalidUsageOfThis util.throw(`In "${this.moduleName}" variable "${key}" defined in module "${parent.moduleName}". Choose a different name.`); } }
[ "function", "checkDefined", "(", "key", ")", "{", "//noinspection JSPotentiallyInvalidUsageOfThis", "if", "(", "!", "data", "[", "`", "${", "this", ".", "moduleName", "}", "${", "key", "}", "`", "]", "&&", "typeof", "parent", ".", "get", "(", "key", ")", "!==", "'undefined'", "&&", "!", "util", ".", "squelch", "(", ")", ")", "{", "// Not allowing sub-modules to name variables already defined in the parent (unless using override).", "// Things get weird when expecting a variable defined in two places.", "//noinspection JSPotentiallyInvalidUsageOfThis", "util", ".", "throw", "(", "`", "${", "this", ".", "moduleName", "}", "${", "key", "}", "${", "parent", ".", "moduleName", "}", "`", ")", ";", "}", "}" ]
Used to prevent users from overriding a key without using a function meant to explicitly do so. Only works when `window.DEV_MODE` is 'strict' or 'warn' @param {string} key
[ "Used", "to", "prevent", "users", "from", "overriding", "a", "key", "without", "using", "a", "function", "meant", "to", "explicitly", "do", "so", ".", "Only", "works", "when", "window", ".", "DEV_MODE", "is", "strict", "or", "warn" ]
97993224d59639cec9eda935694cdb0394d72082
https://github.com/jperezov/vargate/blob/97993224d59639cec9eda935694cdb0394d72082/vargate.js#L480-L488
45,091
jperezov/vargate
vargate.js
assignNestedPropertyListener
function assignNestedPropertyListener(object, key, fullKey, context) { /** @type {Array} */ const pathArray = key.split('.'); if (pathArray.length === 1 && typeof key === 'string') { // Sanitize `key` key = key.replace(/[^\w$]/g, ''); if (object[key] === undefined) { // Create a watch on the property, and run once it's been set Object.defineProperty(object, key, { /** @type {boolean} */ 'configurable': true, /** @param {*} val */ 'set': function(val) { delete object[key]; object[key] = val; context.set(fullKey, object); } }); } else { // The property's already been defined. Trigger it. context.set(fullKey, object); } } else { assignNestedPropertyListener(object[pathArray[0]], pathArray.splice(1).join('.'), fullKey, context); } }
javascript
function assignNestedPropertyListener(object, key, fullKey, context) { /** @type {Array} */ const pathArray = key.split('.'); if (pathArray.length === 1 && typeof key === 'string') { // Sanitize `key` key = key.replace(/[^\w$]/g, ''); if (object[key] === undefined) { // Create a watch on the property, and run once it's been set Object.defineProperty(object, key, { /** @type {boolean} */ 'configurable': true, /** @param {*} val */ 'set': function(val) { delete object[key]; object[key] = val; context.set(fullKey, object); } }); } else { // The property's already been defined. Trigger it. context.set(fullKey, object); } } else { assignNestedPropertyListener(object[pathArray[0]], pathArray.splice(1).join('.'), fullKey, context); } }
[ "function", "assignNestedPropertyListener", "(", "object", ",", "key", ",", "fullKey", ",", "context", ")", "{", "/** @type {Array} */", "const", "pathArray", "=", "key", ".", "split", "(", "'.'", ")", ";", "if", "(", "pathArray", ".", "length", "===", "1", "&&", "typeof", "key", "===", "'string'", ")", "{", "// Sanitize `key`", "key", "=", "key", ".", "replace", "(", "/", "[^\\w$]", "/", "g", ",", "''", ")", ";", "if", "(", "object", "[", "key", "]", "===", "undefined", ")", "{", "// Create a watch on the property, and run once it's been set", "Object", ".", "defineProperty", "(", "object", ",", "key", ",", "{", "/** @type {boolean} */", "'configurable'", ":", "true", ",", "/** @param {*} val */", "'set'", ":", "function", "(", "val", ")", "{", "delete", "object", "[", "key", "]", ";", "object", "[", "key", "]", "=", "val", ";", "context", ".", "set", "(", "fullKey", ",", "object", ")", ";", "}", "}", ")", ";", "}", "else", "{", "// The property's already been defined. Trigger it.", "context", ".", "set", "(", "fullKey", ",", "object", ")", ";", "}", "}", "else", "{", "assignNestedPropertyListener", "(", "object", "[", "pathArray", "[", "0", "]", "]", ",", "pathArray", ".", "splice", "(", "1", ")", ".", "join", "(", "'.'", ")", ",", "fullKey", ",", "context", ")", ";", "}", "}" ]
Listens and marks when a property is available @param {Object} object @param {string} key @param {string} fullKey @param {VarGate} context
[ "Listens", "and", "marks", "when", "a", "property", "is", "available" ]
97993224d59639cec9eda935694cdb0394d72082
https://github.com/jperezov/vargate/blob/97993224d59639cec9eda935694cdb0394d72082/vargate.js#L496-L521
45,092
ucscXena/ehmutable
js/index.js
arrAssoc
function arrAssoc(x, k, v) { var y; if (k < 0 || k > x.length) { throw new Error('Index ' + k + ' out of bounds [0,' + x.length + ']'); } y = [].concat(x); y[k] = v; return y; }
javascript
function arrAssoc(x, k, v) { var y; if (k < 0 || k > x.length) { throw new Error('Index ' + k + ' out of bounds [0,' + x.length + ']'); } y = [].concat(x); y[k] = v; return y; }
[ "function", "arrAssoc", "(", "x", ",", "k", ",", "v", ")", "{", "var", "y", ";", "if", "(", "k", "<", "0", "||", "k", ">", "x", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Index '", "+", "k", "+", "' out of bounds [0,'", "+", "x", ".", "length", "+", "']'", ")", ";", "}", "y", "=", "[", "]", ".", "concat", "(", "x", ")", ";", "y", "[", "k", "]", "=", "v", ";", "return", "y", ";", "}" ]
Immutable collection operations, based on doing a naive path copy. Should be performant for objects that are not too large, and nesting not too deep.
[ "Immutable", "collection", "operations", "based", "on", "doing", "a", "naive", "path", "copy", ".", "Should", "be", "performant", "for", "objects", "that", "are", "not", "too", "large", "and", "nesting", "not", "too", "deep", "." ]
5dfb342588944620adbdc33547904e074e2ed372
https://github.com/ucscXena/ehmutable/blob/5dfb342588944620adbdc33547904e074e2ed372/js/index.js#L23-L31
45,093
gusenov/web-store-js
tree.js
WebTreeStore
function WebTreeStore(storageObject, storageId, dataChanged) { this.storage = storageObject; this.id = storageId; this._setItem(this.id + "-tree", true); this.dataChanged = dataChanged; }
javascript
function WebTreeStore(storageObject, storageId, dataChanged) { this.storage = storageObject; this.id = storageId; this._setItem(this.id + "-tree", true); this.dataChanged = dataChanged; }
[ "function", "WebTreeStore", "(", "storageObject", ",", "storageId", ",", "dataChanged", ")", "{", "this", ".", "storage", "=", "storageObject", ";", "this", ".", "id", "=", "storageId", ";", "this", ".", "_setItem", "(", "this", ".", "id", "+", "\"-tree\"", ",", "true", ")", ";", "this", ".", "dataChanged", "=", "dataChanged", ";", "}" ]
Creates a new instance of class WebTreeStore. @access public @augments WebStore @constructs WebTreeStore
[ "Creates", "a", "new", "instance", "of", "class", "WebTreeStore", "." ]
efc80715a601f657340b171c690dc0164e12386b
https://github.com/gusenov/web-store-js/blob/efc80715a601f657340b171c690dc0164e12386b/tree.js#L22-L27
45,094
chapmanu/hb
lib/services/twitter/stream.js
function(service, credentials, accounts, keywords) { Stream.call(this, service, credentials, accounts, keywords); this._twit = new Twit(credentials); this.responder = new Responder(); this._changes = []; this._interval = setInterval(this.intervalMethod.bind(this), QUEUE_PERIOD_DEFAULT); }
javascript
function(service, credentials, accounts, keywords) { Stream.call(this, service, credentials, accounts, keywords); this._twit = new Twit(credentials); this.responder = new Responder(); this._changes = []; this._interval = setInterval(this.intervalMethod.bind(this), QUEUE_PERIOD_DEFAULT); }
[ "function", "(", "service", ",", "credentials", ",", "accounts", ",", "keywords", ")", "{", "Stream", ".", "call", "(", "this", ",", "service", ",", "credentials", ",", "accounts", ",", "keywords", ")", ";", "this", ".", "_twit", "=", "new", "Twit", "(", "credentials", ")", ";", "this", ".", "responder", "=", "new", "Responder", "(", ")", ";", "this", ".", "_changes", "=", "[", "]", ";", "this", ".", "_interval", "=", "setInterval", "(", "this", ".", "intervalMethod", ".", "bind", "(", "this", ")", ",", "QUEUE_PERIOD_DEFAULT", ")", ";", "}" ]
Manages the streaming connection to Twitter @constructor @extends Stream
[ "Manages", "the", "streaming", "connection", "to", "Twitter" ]
5edd8de89c7c5fdffc3df0c627513889220f7d51
https://github.com/chapmanu/hb/blob/5edd8de89c7c5fdffc3df0c627513889220f7d51/lib/services/twitter/stream.js#L18-L25
45,095
coreh-deprecated/ferret
ferret.js
function(ferret, fn) { if (ferret._ready) { return fn(null) } else if (ferret._error) { return fn(new Error('Not connected to the database')) } else { ferret._readyQueue.push(fn) } }
javascript
function(ferret, fn) { if (ferret._ready) { return fn(null) } else if (ferret._error) { return fn(new Error('Not connected to the database')) } else { ferret._readyQueue.push(fn) } }
[ "function", "(", "ferret", ",", "fn", ")", "{", "if", "(", "ferret", ".", "_ready", ")", "{", "return", "fn", "(", "null", ")", "}", "else", "if", "(", "ferret", ".", "_error", ")", "{", "return", "fn", "(", "new", "Error", "(", "'Not connected to the database'", ")", ")", "}", "else", "{", "ferret", ".", "_readyQueue", ".", "push", "(", "fn", ")", "}", "}" ]
Run a function right now if ready, or queue it for later
[ "Run", "a", "function", "right", "now", "if", "ready", "or", "queue", "it", "for", "later" ]
951803a107f9e5366323fca12b139f8de2de53d8
https://github.com/coreh-deprecated/ferret/blob/951803a107f9e5366323fca12b139f8de2de53d8/ferret.js#L84-L92
45,096
coreh-deprecated/ferret
ferret.js
function(ferret, collection_name, callback) { _ready(ferret, function(err) { if (err) { process.nextTick(function() { callback(err) }) } else { if (ferret._collections[collection_name]) { process.nextTick(function() { callback(null, ferret._collections[collection_name]) }) } else { ferret._db.collection(collection_name, function(err, collection){ if (!err) { ferret._collections[collection_name] = collection } callback(err, collection) }) } } }) }
javascript
function(ferret, collection_name, callback) { _ready(ferret, function(err) { if (err) { process.nextTick(function() { callback(err) }) } else { if (ferret._collections[collection_name]) { process.nextTick(function() { callback(null, ferret._collections[collection_name]) }) } else { ferret._db.collection(collection_name, function(err, collection){ if (!err) { ferret._collections[collection_name] = collection } callback(err, collection) }) } } }) }
[ "function", "(", "ferret", ",", "collection_name", ",", "callback", ")", "{", "_ready", "(", "ferret", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "callback", "(", "err", ")", "}", ")", "}", "else", "{", "if", "(", "ferret", ".", "_collections", "[", "collection_name", "]", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "callback", "(", "null", ",", "ferret", ".", "_collections", "[", "collection_name", "]", ")", "}", ")", "}", "else", "{", "ferret", ".", "_db", ".", "collection", "(", "collection_name", ",", "function", "(", "err", ",", "collection", ")", "{", "if", "(", "!", "err", ")", "{", "ferret", ".", "_collections", "[", "collection_name", "]", "=", "collection", "}", "callback", "(", "err", ",", "collection", ")", "}", ")", "}", "}", "}", ")", "}" ]
Try loading a collection from the cache. If that fails, get it from the driver
[ "Try", "loading", "a", "collection", "from", "the", "cache", ".", "If", "that", "fails", "get", "it", "from", "the", "driver" ]
951803a107f9e5366323fca12b139f8de2de53d8
https://github.com/coreh-deprecated/ferret/blob/951803a107f9e5366323fca12b139f8de2de53d8/ferret.js#L95-L114
45,097
henrytseng/angular-state-router
src/utils/url.js
function() { var pairs = _self.querystring().split('&'); var params = {}; for(var i=0; i<pairs.length; i++) { if(pairs[i] === '') continue; var nameValue = pairs[i].split('='); params[nameValue[0]] = (typeof nameValue[1] === 'undefined' || nameValue[1] === '') ? true : decodeURIComponent(nameValue[1]); } return params; }
javascript
function() { var pairs = _self.querystring().split('&'); var params = {}; for(var i=0; i<pairs.length; i++) { if(pairs[i] === '') continue; var nameValue = pairs[i].split('='); params[nameValue[0]] = (typeof nameValue[1] === 'undefined' || nameValue[1] === '') ? true : decodeURIComponent(nameValue[1]); } return params; }
[ "function", "(", ")", "{", "var", "pairs", "=", "_self", ".", "querystring", "(", ")", ".", "split", "(", "'&'", ")", ";", "var", "params", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pairs", ".", "length", ";", "i", "++", ")", "{", "if", "(", "pairs", "[", "i", "]", "===", "''", ")", "continue", ";", "var", "nameValue", "=", "pairs", "[", "i", "]", ".", "split", "(", "'='", ")", ";", "params", "[", "nameValue", "[", "0", "]", "]", "=", "(", "typeof", "nameValue", "[", "1", "]", "===", "'undefined'", "||", "nameValue", "[", "1", "]", "===", "''", ")", "?", "true", ":", "decodeURIComponent", "(", "nameValue", "[", "1", "]", ")", ";", "}", "return", "params", ";", "}" ]
Get the querystring of a URL parameters as a hash @return {String} A querystring from URL
[ "Get", "the", "querystring", "of", "a", "URL", "parameters", "as", "a", "hash" ]
5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b
https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/utils/url.js#L32-L43
45,098
evsheffield/node-donedone-api
lib/donedone-api.js
function(subdomain, username, passwordOrAPIToken, methodURL, requestMethod, callback, data, attachments) { var baseUrl = subdomain + '.mydonedone.com' , path = '/issuetracker/api/v2/' + methodURL , auth = new Buffer(username + ':' + passwordOrAPIToken).toString('base64') , options = { hostname: baseUrl, path: path, method: requestMethod, headers: { Authorization: 'Basic ' + auth } } , respData = ''; if(data) { data = querystring.stringify(data); options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; options.headers['Content-Length'] = Buffer.byteLength(data); } var req = https.request(options, function(res) { res.setEncoding('utf8'); // Collect response chunks res.on('data', function(chunk) { respData += chunk; }); // Process the response once all data has come in res.on('end', function() { var respJson = JSON.parse(respData); // Non-200 responses are API errors. Execute the callback with the error message. if(200 !== res.statusCode) { var errMsg = 'HTTP Error ' + res.statusCode + ', Message: ' + respJson.Message; if(callback) { callback(errMsg); } } else { if(callback) { callback(null, respJson); } } }); }); // Write the POST data if(data) { req.write(data); } req.end(); req.on('error', function(e) { callback(e); }); }
javascript
function(subdomain, username, passwordOrAPIToken, methodURL, requestMethod, callback, data, attachments) { var baseUrl = subdomain + '.mydonedone.com' , path = '/issuetracker/api/v2/' + methodURL , auth = new Buffer(username + ':' + passwordOrAPIToken).toString('base64') , options = { hostname: baseUrl, path: path, method: requestMethod, headers: { Authorization: 'Basic ' + auth } } , respData = ''; if(data) { data = querystring.stringify(data); options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; options.headers['Content-Length'] = Buffer.byteLength(data); } var req = https.request(options, function(res) { res.setEncoding('utf8'); // Collect response chunks res.on('data', function(chunk) { respData += chunk; }); // Process the response once all data has come in res.on('end', function() { var respJson = JSON.parse(respData); // Non-200 responses are API errors. Execute the callback with the error message. if(200 !== res.statusCode) { var errMsg = 'HTTP Error ' + res.statusCode + ', Message: ' + respJson.Message; if(callback) { callback(errMsg); } } else { if(callback) { callback(null, respJson); } } }); }); // Write the POST data if(data) { req.write(data); } req.end(); req.on('error', function(e) { callback(e); }); }
[ "function", "(", "subdomain", ",", "username", ",", "passwordOrAPIToken", ",", "methodURL", ",", "requestMethod", ",", "callback", ",", "data", ",", "attachments", ")", "{", "var", "baseUrl", "=", "subdomain", "+", "'.mydonedone.com'", ",", "path", "=", "'/issuetracker/api/v2/'", "+", "methodURL", ",", "auth", "=", "new", "Buffer", "(", "username", "+", "':'", "+", "passwordOrAPIToken", ")", ".", "toString", "(", "'base64'", ")", ",", "options", "=", "{", "hostname", ":", "baseUrl", ",", "path", ":", "path", ",", "method", ":", "requestMethod", ",", "headers", ":", "{", "Authorization", ":", "'Basic '", "+", "auth", "}", "}", ",", "respData", "=", "''", ";", "if", "(", "data", ")", "{", "data", "=", "querystring", ".", "stringify", "(", "data", ")", ";", "options", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded'", ";", "options", ".", "headers", "[", "'Content-Length'", "]", "=", "Buffer", ".", "byteLength", "(", "data", ")", ";", "}", "var", "req", "=", "https", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "res", ".", "setEncoding", "(", "'utf8'", ")", ";", "// Collect response chunks", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "respData", "+=", "chunk", ";", "}", ")", ";", "// Process the response once all data has come in", "res", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "var", "respJson", "=", "JSON", ".", "parse", "(", "respData", ")", ";", "// Non-200 responses are API errors. Execute the callback with the error message.", "if", "(", "200", "!==", "res", ".", "statusCode", ")", "{", "var", "errMsg", "=", "'HTTP Error '", "+", "res", ".", "statusCode", "+", "', Message: '", "+", "respJson", ".", "Message", ";", "if", "(", "callback", ")", "{", "callback", "(", "errMsg", ")", ";", "}", "}", "else", "{", "if", "(", "callback", ")", "{", "callback", "(", "null", ",", "respJson", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "// Write the POST data", "if", "(", "data", ")", "{", "req", ".", "write", "(", "data", ")", ";", "}", "req", ".", "end", "(", ")", ";", "req", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "callback", "(", "e", ")", ";", "}", ")", ";", "}" ]
A wrapper for performing all API calls. @param {string} subdomain The DoneDone subdomain, e.g. 'foobar' in 'foobar.mydonedone.com' @param {string} username DoneDone username @param {string} passwordOrAPIToken DoneDone password or API token @param {string} methodURL The URL for the API action @param {string} requestMethod HTTP verb, e.g. 'GET' or 'POST' @param {Function} callback Callback function with two arguments `(err, data)` @param {array} data Generic data (optional) @param {array} attachments List of file paths (optional)
[ "A", "wrapper", "for", "performing", "all", "API", "calls", "." ]
9b1d8ddb86c4fe654509e9191fc7d666334c4a03
https://github.com/evsheffield/node-donedone-api/blob/9b1d8ddb86c4fe654509e9191fc7d666334c4a03/lib/donedone-api.js#L28-L84
45,099
evsheffield/node-donedone-api
lib/donedone-api.js
function(cb) { exports.getReleaseBuildInfo(subdomain, username, passwordOrAPIToken, id, function(err, respData) { cb(err, respData); }); }
javascript
function(cb) { exports.getReleaseBuildInfo(subdomain, username, passwordOrAPIToken, id, function(err, respData) { cb(err, respData); }); }
[ "function", "(", "cb", ")", "{", "exports", ".", "getReleaseBuildInfo", "(", "subdomain", ",", "username", ",", "passwordOrAPIToken", ",", "id", ",", "function", "(", "err", ",", "respData", ")", "{", "cb", "(", "err", ",", "respData", ")", ";", "}", ")", ";", "}" ]
Get release build information
[ "Get", "release", "build", "information" ]
9b1d8ddb86c4fe654509e9191fc7d666334c4a03
https://github.com/evsheffield/node-donedone-api/blob/9b1d8ddb86c4fe654509e9191fc7d666334c4a03/lib/donedone-api.js#L305-L309