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
48,900
observing/fossa
lib/predefine.js
after
function after(results, next) { item.trigger('after:' + method, function done(error) { next(error, results); }); }
javascript
function after(results, next) { item.trigger('after:' + method, function done(error) { next(error, results); }); }
[ "function", "after", "(", "results", ",", "next", ")", "{", "item", ".", "trigger", "(", "'after:'", "+", "method", ",", "function", "done", "(", "error", ")", "{", "next", "(", "error", ",", "results", ")", ";", "}", ")", ";", "}" ]
Trigger execution of after hooks, pass results from the peristence to keep it consistent with the callback of persistance if no after hooks are provided. @param {Object} results of persistence @param {Function} next callback @api private
[ "Trigger", "execution", "of", "after", "hooks", "pass", "results", "from", "the", "peristence", "to", "keep", "it", "consistent", "with", "the", "callback", "of", "persistance", "if", "no", "after", "hooks", "are", "provided", "." ]
29b3717ee10a13fb607f5bbddcb8b003faf008c6
https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/lib/predefine.js#L423-L427
48,901
tianjianchn/javascript-packages
packages/frm/src/record/create.js
createRecord
function createRecord(fvs, options) { options || (options = {}); const model = this; const row = {}; if (fvs) { for (const kk in fvs) { row[kk] = fvs[kk]; } } const r = constructRecord(model, row, Object.keys(model.def.fields), true); getDefaultOnCreate(r, null, options.createdBy); return r; }
javascript
function createRecord(fvs, options) { options || (options = {}); const model = this; const row = {}; if (fvs) { for (const kk in fvs) { row[kk] = fvs[kk]; } } const r = constructRecord(model, row, Object.keys(model.def.fields), true); getDefaultOnCreate(r, null, options.createdBy); return r; }
[ "function", "createRecord", "(", "fvs", ",", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "const", "model", "=", "this", ";", "const", "row", "=", "{", "}", ";", "if", "(", "fvs", ")", "{", "for", "(", "const", "kk", "in", "fvs", ")", "{", "row", "[", "kk", "]", "=", "fvs", "[", "kk", "]", ";", "}", "}", "const", "r", "=", "constructRecord", "(", "model", ",", "row", ",", "Object", ".", "keys", "(", "model", ".", "def", ".", "fields", ")", ",", "true", ")", ";", "getDefaultOnCreate", "(", "r", ",", "null", ",", "options", ".", "createdBy", ")", ";", "return", "r", ";", "}" ]
this = model
[ "this", "=", "model" ]
3abe85edbfe323939c84c1d02128d74d6374bcde
https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/frm/src/record/create.js#L11-L24
48,902
bernardodiasc/filestojson
src/index.js
readDirSync
function readDirSync (dir, allFiles = []) { const files = fs.readdirSync(dir).map(f => join(dir, f)) allFiles.push(...files) files.forEach(f => { fs.statSync(f).isDirectory() && readDirSync(f, allFiles) }) return allFiles }
javascript
function readDirSync (dir, allFiles = []) { const files = fs.readdirSync(dir).map(f => join(dir, f)) allFiles.push(...files) files.forEach(f => { fs.statSync(f).isDirectory() && readDirSync(f, allFiles) }) return allFiles }
[ "function", "readDirSync", "(", "dir", ",", "allFiles", "=", "[", "]", ")", "{", "const", "files", "=", "fs", ".", "readdirSync", "(", "dir", ")", ".", "map", "(", "f", "=>", "join", "(", "dir", ",", "f", ")", ")", "allFiles", ".", "push", "(", "...", "files", ")", "files", ".", "forEach", "(", "f", "=>", "{", "fs", ".", "statSync", "(", "f", ")", ".", "isDirectory", "(", ")", "&&", "readDirSync", "(", "f", ",", "allFiles", ")", "}", ")", "return", "allFiles", "}" ]
Reads content directory and return all files @param {String} dir Content path @param {Array} allFiles Partial list of files and directories @return {Array} List of files and directories
[ "Reads", "content", "directory", "and", "return", "all", "files" ]
4ccd4454d1fe0408001b1f9f57ed89d19e38256e
https://github.com/bernardodiasc/filestojson/blob/4ccd4454d1fe0408001b1f9f57ed89d19e38256e/src/index.js#L29-L36
48,903
bernardodiasc/filestojson
src/index.js
getData
function getData (allFiles = [], config) { const files = allFiles.reduce((memo, iteratee) => { const filePath = path.parse(iteratee) if (config.include.includes(filePath.ext) && !config.exclude.includes(filePath.base)) { const newFile = { file: iteratee.replace(config.content, ''), dir: filePath.dir.replace(config.content, ''), name: filePath.name, base: filePath.base, ext: filePath.ext, } if (filePath.ext === '.md') { const file = fs.readFileSync(iteratee, { encoding: 'utf8' }) const frontMatter = fm(file) newFile.attr = frontMatter.attributes newFile.body = frontMatter.body } else if (filePath.ext === '.png') { const image = new PNG.load(iteratee) newFile.width = image.width newFile.height = image.height } memo.push(newFile) } return memo }, []) return files }
javascript
function getData (allFiles = [], config) { const files = allFiles.reduce((memo, iteratee) => { const filePath = path.parse(iteratee) if (config.include.includes(filePath.ext) && !config.exclude.includes(filePath.base)) { const newFile = { file: iteratee.replace(config.content, ''), dir: filePath.dir.replace(config.content, ''), name: filePath.name, base: filePath.base, ext: filePath.ext, } if (filePath.ext === '.md') { const file = fs.readFileSync(iteratee, { encoding: 'utf8' }) const frontMatter = fm(file) newFile.attr = frontMatter.attributes newFile.body = frontMatter.body } else if (filePath.ext === '.png') { const image = new PNG.load(iteratee) newFile.width = image.width newFile.height = image.height } memo.push(newFile) } return memo }, []) return files }
[ "function", "getData", "(", "allFiles", "=", "[", "]", ",", "config", ")", "{", "const", "files", "=", "allFiles", ".", "reduce", "(", "(", "memo", ",", "iteratee", ")", "=>", "{", "const", "filePath", "=", "path", ".", "parse", "(", "iteratee", ")", "if", "(", "config", ".", "include", ".", "includes", "(", "filePath", ".", "ext", ")", "&&", "!", "config", ".", "exclude", ".", "includes", "(", "filePath", ".", "base", ")", ")", "{", "const", "newFile", "=", "{", "file", ":", "iteratee", ".", "replace", "(", "config", ".", "content", ",", "''", ")", ",", "dir", ":", "filePath", ".", "dir", ".", "replace", "(", "config", ".", "content", ",", "''", ")", ",", "name", ":", "filePath", ".", "name", ",", "base", ":", "filePath", ".", "base", ",", "ext", ":", "filePath", ".", "ext", ",", "}", "if", "(", "filePath", ".", "ext", "===", "'.md'", ")", "{", "const", "file", "=", "fs", ".", "readFileSync", "(", "iteratee", ",", "{", "encoding", ":", "'utf8'", "}", ")", "const", "frontMatter", "=", "fm", "(", "file", ")", "newFile", ".", "attr", "=", "frontMatter", ".", "attributes", "newFile", ".", "body", "=", "frontMatter", ".", "body", "}", "else", "if", "(", "filePath", ".", "ext", "===", "'.png'", ")", "{", "const", "image", "=", "new", "PNG", ".", "load", "(", "iteratee", ")", "newFile", ".", "width", "=", "image", ".", "width", "newFile", ".", "height", "=", "image", ".", "height", "}", "memo", ".", "push", "(", "newFile", ")", "}", "return", "memo", "}", ",", "[", "]", ")", "return", "files", "}" ]
Get data from list of files filtered based on options @param {Array} allFiles List of files and directories @return {Array} Updated list of files with content
[ "Get", "data", "from", "list", "of", "files", "filtered", "based", "on", "options" ]
4ccd4454d1fe0408001b1f9f57ed89d19e38256e
https://github.com/bernardodiasc/filestojson/blob/4ccd4454d1fe0408001b1f9f57ed89d19e38256e/src/index.js#L43-L69
48,904
bernardodiasc/filestojson
src/index.js
translate
function translate (content, contentTypes) { let output = {} content.forEach(each => { const base = path.parse(each.file).base if (base === 'index.md') { const type = each.dir.split('/').pop() const contentTypeTranslation = contentTypes.find(contentType => contentType[type]) if (contentTypeTranslation && contentTypeTranslation[type]) { output[type] = contentTypeTranslation[type](content, type) } } }) return output }
javascript
function translate (content, contentTypes) { let output = {} content.forEach(each => { const base = path.parse(each.file).base if (base === 'index.md') { const type = each.dir.split('/').pop() const contentTypeTranslation = contentTypes.find(contentType => contentType[type]) if (contentTypeTranslation && contentTypeTranslation[type]) { output[type] = contentTypeTranslation[type](content, type) } } }) return output }
[ "function", "translate", "(", "content", ",", "contentTypes", ")", "{", "let", "output", "=", "{", "}", "content", ".", "forEach", "(", "each", "=>", "{", "const", "base", "=", "path", ".", "parse", "(", "each", ".", "file", ")", ".", "base", "if", "(", "base", "===", "'index.md'", ")", "{", "const", "type", "=", "each", ".", "dir", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", "const", "contentTypeTranslation", "=", "contentTypes", ".", "find", "(", "contentType", "=>", "contentType", "[", "type", "]", ")", "if", "(", "contentTypeTranslation", "&&", "contentTypeTranslation", "[", "type", "]", ")", "{", "output", "[", "type", "]", "=", "contentTypeTranslation", "[", "type", "]", "(", "content", ",", "type", ")", "}", "}", "}", ")", "return", "output", "}" ]
Translate data based on content types @param {Array} file List of contents @return {Array} Updated list of contents
[ "Translate", "data", "based", "on", "content", "types" ]
4ccd4454d1fe0408001b1f9f57ed89d19e38256e
https://github.com/bernardodiasc/filestojson/blob/4ccd4454d1fe0408001b1f9f57ed89d19e38256e/src/index.js#L76-L89
48,905
bernardodiasc/filestojson
src/index.js
write
function write (filename, content) { const json = JSON.stringify(content, (key, value) => value === undefined ? null : value) fs.writeFileSync(filename, json) return json }
javascript
function write (filename, content) { const json = JSON.stringify(content, (key, value) => value === undefined ? null : value) fs.writeFileSync(filename, json) return json }
[ "function", "write", "(", "filename", ",", "content", ")", "{", "const", "json", "=", "JSON", ".", "stringify", "(", "content", ",", "(", "key", ",", "value", ")", "=>", "value", "===", "undefined", "?", "null", ":", "value", ")", "fs", ".", "writeFileSync", "(", "filename", ",", "json", ")", "return", "json", "}" ]
Write output data in file system @param {String} filename Output file name @param {Array} content List of contents @return {String} Stringified list of contents
[ "Write", "output", "data", "in", "file", "system" ]
4ccd4454d1fe0408001b1f9f57ed89d19e38256e
https://github.com/bernardodiasc/filestojson/blob/4ccd4454d1fe0408001b1f9f57ed89d19e38256e/src/index.js#L97-L101
48,906
tianjianchn/javascript-packages
packages/jstr/index.js
parse
function parse(html, script, filePath){ var m, index = 0;//the index in the html string while(m = reDelim.exec(html)) { addLiteral(script, html.slice(index, m.index));//string addCode(script, m, filePath); index = m.index + m[0].length; } addLiteral(script, html.slice(index)); script.push('\n}return __r.join("");'); script = script.join(''); return script; }
javascript
function parse(html, script, filePath){ var m, index = 0;//the index in the html string while(m = reDelim.exec(html)) { addLiteral(script, html.slice(index, m.index));//string addCode(script, m, filePath); index = m.index + m[0].length; } addLiteral(script, html.slice(index)); script.push('\n}return __r.join("");'); script = script.join(''); return script; }
[ "function", "parse", "(", "html", ",", "script", ",", "filePath", ")", "{", "var", "m", ",", "index", "=", "0", ";", "//the index in the html string\r", "while", "(", "m", "=", "reDelim", ".", "exec", "(", "html", ")", ")", "{", "addLiteral", "(", "script", ",", "html", ".", "slice", "(", "index", ",", "m", ".", "index", ")", ")", ";", "//string\r", "addCode", "(", "script", ",", "m", ",", "filePath", ")", ";", "index", "=", "m", ".", "index", "+", "m", "[", "0", "]", ".", "length", ";", "}", "addLiteral", "(", "script", ",", "html", ".", "slice", "(", "index", ")", ")", ";", "script", ".", "push", "(", "'\\n}return __r.join(\"\");'", ")", ";", "script", "=", "script", ".", "join", "(", "''", ")", ";", "return", "script", ";", "}" ]
parse the html string to js script
[ "parse", "the", "html", "string", "to", "js", "script" ]
3abe85edbfe323939c84c1d02128d74d6374bcde
https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/jstr/index.js#L112-L123
48,907
tianjianchn/javascript-packages
packages/jstr/index.js
addLiteral
function addLiteral(script, str){ if(!str) return; str = str.replace(/\\|'/g, '\\$&');// escape ' var m, index = 0; while(m = reNewline.exec(str)){ var nl = m[0]; var es = nl==='\r\n'? '\\r\\n':'\\n'; script.push("__p('" + str.slice(index, m.index) + es + "');\n"); index = m.index + nl.length; } var last = str.slice(index); if(last) script.push("__p('" + last + "');"); }
javascript
function addLiteral(script, str){ if(!str) return; str = str.replace(/\\|'/g, '\\$&');// escape ' var m, index = 0; while(m = reNewline.exec(str)){ var nl = m[0]; var es = nl==='\r\n'? '\\r\\n':'\\n'; script.push("__p('" + str.slice(index, m.index) + es + "');\n"); index = m.index + nl.length; } var last = str.slice(index); if(last) script.push("__p('" + last + "');"); }
[ "function", "addLiteral", "(", "script", ",", "str", ")", "{", "if", "(", "!", "str", ")", "return", ";", "str", "=", "str", ".", "replace", "(", "/", "\\\\|'", "/", "g", ",", "'\\\\$&'", ")", ";", "// escape '\r", "var", "m", ",", "index", "=", "0", ";", "while", "(", "m", "=", "reNewline", ".", "exec", "(", "str", ")", ")", "{", "var", "nl", "=", "m", "[", "0", "]", ";", "var", "es", "=", "nl", "===", "'\\r\\n'", "?", "'\\\\r\\\\n'", ":", "'\\\\n'", ";", "script", ".", "push", "(", "\"__p('\"", "+", "str", ".", "slice", "(", "index", ",", "m", ".", "index", ")", "+", "es", "+", "\"');\\n\"", ")", ";", "index", "=", "m", ".", "index", "+", "nl", ".", "length", ";", "}", "var", "last", "=", "str", ".", "slice", "(", "index", ")", ";", "if", "(", "last", ")", "script", ".", "push", "(", "\"__p('\"", "+", "last", "+", "\"');\"", ")", ";", "}" ]
the literal, which is out of delimiters, like @>literal here<@
[ "the", "literal", "which", "is", "out", "of", "delimiters", "like" ]
3abe85edbfe323939c84c1d02128d74d6374bcde
https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/jstr/index.js#L126-L139
48,908
tianjianchn/javascript-packages
packages/jstr/index.js
addCode
function addCode(script, match, filePath) { var leftDeli = match[1], code = match[2]; if(leftDeli==='<@' || leftDeli==='<!--@='){ script.push('__p(escape(' + code + '));'); } else if(leftDeli==='<@|' || leftDeli==='<!--@|'){//no escape script.push('__p(' + code + ');'); } else{//<!--@ --> script.push(code); //possible single-line comment check var lastLine = code.split('\n').slice(-1)[0]; if(lastLine.indexOf('//')>=0){ /*eslint-disable no-console*/ if(!filePath) console.warn('detect a possible single-line comment: %s', lastLine); else console.warn('detect a possible single-line comment in file %s: %s', filePath, lastLine); /*eslint-enable no-console*/ } if(code.slice(-1)!==';') script.push(';'); } }
javascript
function addCode(script, match, filePath) { var leftDeli = match[1], code = match[2]; if(leftDeli==='<@' || leftDeli==='<!--@='){ script.push('__p(escape(' + code + '));'); } else if(leftDeli==='<@|' || leftDeli==='<!--@|'){//no escape script.push('__p(' + code + ');'); } else{//<!--@ --> script.push(code); //possible single-line comment check var lastLine = code.split('\n').slice(-1)[0]; if(lastLine.indexOf('//')>=0){ /*eslint-disable no-console*/ if(!filePath) console.warn('detect a possible single-line comment: %s', lastLine); else console.warn('detect a possible single-line comment in file %s: %s', filePath, lastLine); /*eslint-enable no-console*/ } if(code.slice(-1)!==';') script.push(';'); } }
[ "function", "addCode", "(", "script", ",", "match", ",", "filePath", ")", "{", "var", "leftDeli", "=", "match", "[", "1", "]", ",", "code", "=", "match", "[", "2", "]", ";", "if", "(", "leftDeli", "===", "'<@'", "||", "leftDeli", "===", "'<!--@='", ")", "{", "script", ".", "push", "(", "'__p(escape('", "+", "code", "+", "'));'", ")", ";", "}", "else", "if", "(", "leftDeli", "===", "'<@|'", "||", "leftDeli", "===", "'<!--@|'", ")", "{", "//no escape\r", "script", ".", "push", "(", "'__p('", "+", "code", "+", "');'", ")", ";", "}", "else", "{", "//<!--@ -->\r", "script", ".", "push", "(", "code", ")", ";", "//possible single-line comment check\r", "var", "lastLine", "=", "code", ".", "split", "(", "'\\n'", ")", ".", "slice", "(", "-", "1", ")", "[", "0", "]", ";", "if", "(", "lastLine", ".", "indexOf", "(", "'//'", ")", ">=", "0", ")", "{", "/*eslint-disable no-console*/", "if", "(", "!", "filePath", ")", "console", ".", "warn", "(", "'detect a possible single-line comment: %s'", ",", "lastLine", ")", ";", "else", "console", ".", "warn", "(", "'detect a possible single-line comment in file %s: %s'", ",", "filePath", ",", "lastLine", ")", ";", "/*eslint-enable no-console*/", "}", "if", "(", "code", ".", "slice", "(", "-", "1", ")", "!==", "';'", ")", "script", ".", "push", "(", "';'", ")", ";", "}", "}" ]
the code, which is in the delimiters
[ "the", "code", "which", "is", "in", "the", "delimiters" ]
3abe85edbfe323939c84c1d02128d74d6374bcde
https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/jstr/index.js#L142-L163
48,909
kuno/neco
deps/npm/lib/init.js
defaultName
function defaultName (folder, data) { if (data.name) return data.name return path.basename(folder).replace(/^node[_-]?|[-\.]?js$/g, '') }
javascript
function defaultName (folder, data) { if (data.name) return data.name return path.basename(folder).replace(/^node[_-]?|[-\.]?js$/g, '') }
[ "function", "defaultName", "(", "folder", ",", "data", ")", "{", "if", "(", "data", ".", "name", ")", "return", "data", ".", "name", "return", "path", ".", "basename", "(", "folder", ")", ".", "replace", "(", "/", "^node[_-]?|[-\\.]?js$", "/", "g", ",", "''", ")", "}" ]
sync - no io
[ "sync", "-", "no", "io" ]
cf6361c1fcb9466c6b2ab3b127b5d0160ca50735
https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/init.js#L209-L212
48,910
chrisJohn404/LabJack-nodejs
lib/driver.js
DriverOperationError
function DriverOperationError(code,description) { this.code = code; this.description = description; console.log('in DriverOperationError',code,description); }
javascript
function DriverOperationError(code,description) { this.code = code; this.description = description; console.log('in DriverOperationError',code,description); }
[ "function", "DriverOperationError", "(", "code", ",", "description", ")", "{", "this", ".", "code", "=", "code", ";", "this", ".", "description", "=", "description", ";", "console", ".", "log", "(", "'in DriverOperationError'", ",", "code", ",", "description", ")", ";", "}" ]
For problems encountered while in driver DLL
[ "For", "problems", "encountered", "while", "in", "driver", "DLL" ]
6f638eb039f3e1619e46ba5aac20d827fecafc29
https://github.com/chrisJohn404/LabJack-nodejs/blob/6f638eb039f3e1619e46ba5aac20d827fecafc29/lib/driver.js#L23-L27
48,911
chrisJohn404/LabJack-nodejs
lib/driver.js
function(me, deviceType, connectionType) { if (!self.hasOpenAll) { throw new DriverInterfaceError( 'openAll is not loaded. Use ListAll and Open functions instead.' ); } if (deviceType === undefined || connectionType === undefined) { throw 'Insufficient parameters for OpenAll - DeviceType and ConnectionType required'; } me.numOpened = new ref.alloc('int', 0); me.aHandles = new Buffer(ARCH_INT_NUM_BYTES * LJM_LIST_ALL_SIZE); me.aHandles.fill(0); me.numErrors = new ref.alloc('int', 0); me.errorHandle = new ref.alloc('int', 0); me.errors = new Buffer(ARCH_POINTER_SIZE); me.errors.fill(0); me.devType = driver_const.deviceTypes[deviceType]; me.deviceType = deviceType; me.connType = driver_const.connectionTypes[connectionType]; me.connectionType = connectionType; }
javascript
function(me, deviceType, connectionType) { if (!self.hasOpenAll) { throw new DriverInterfaceError( 'openAll is not loaded. Use ListAll and Open functions instead.' ); } if (deviceType === undefined || connectionType === undefined) { throw 'Insufficient parameters for OpenAll - DeviceType and ConnectionType required'; } me.numOpened = new ref.alloc('int', 0); me.aHandles = new Buffer(ARCH_INT_NUM_BYTES * LJM_LIST_ALL_SIZE); me.aHandles.fill(0); me.numErrors = new ref.alloc('int', 0); me.errorHandle = new ref.alloc('int', 0); me.errors = new Buffer(ARCH_POINTER_SIZE); me.errors.fill(0); me.devType = driver_const.deviceTypes[deviceType]; me.deviceType = deviceType; me.connType = driver_const.connectionTypes[connectionType]; me.connectionType = connectionType; }
[ "function", "(", "me", ",", "deviceType", ",", "connectionType", ")", "{", "if", "(", "!", "self", ".", "hasOpenAll", ")", "{", "throw", "new", "DriverInterfaceError", "(", "'openAll is not loaded. Use ListAll and Open functions instead.'", ")", ";", "}", "if", "(", "deviceType", "===", "undefined", "||", "connectionType", "===", "undefined", ")", "{", "throw", "'Insufficient parameters for OpenAll - DeviceType and ConnectionType required'", ";", "}", "me", ".", "numOpened", "=", "new", "ref", ".", "alloc", "(", "'int'", ",", "0", ")", ";", "me", ".", "aHandles", "=", "new", "Buffer", "(", "ARCH_INT_NUM_BYTES", "*", "LJM_LIST_ALL_SIZE", ")", ";", "me", ".", "aHandles", ".", "fill", "(", "0", ")", ";", "me", ".", "numErrors", "=", "new", "ref", ".", "alloc", "(", "'int'", ",", "0", ")", ";", "me", ".", "errorHandle", "=", "new", "ref", ".", "alloc", "(", "'int'", ",", "0", ")", ";", "me", ".", "errors", "=", "new", "Buffer", "(", "ARCH_POINTER_SIZE", ")", ";", "me", ".", "errors", ".", "fill", "(", "0", ")", ";", "me", ".", "devType", "=", "driver_const", ".", "deviceTypes", "[", "deviceType", "]", ";", "me", ".", "deviceType", "=", "deviceType", ";", "me", ".", "connType", "=", "driver_const", ".", "connectionTypes", "[", "connectionType", "]", ";", "me", ".", "connectionType", "=", "connectionType", ";", "}" ]
Internal helper function to prepare the arguments for an OpenAll call.
[ "Internal", "helper", "function", "to", "prepare", "the", "arguments", "for", "an", "OpenAll", "call", "." ]
6f638eb039f3e1619e46ba5aac20d827fecafc29
https://github.com/chrisJohn404/LabJack-nodejs/blob/6f638eb039f3e1619e46ba5aac20d827fecafc29/lib/driver.js#L674-L697
48,912
rkusa/swac
lib/routing.js
done
function done() { // get the next route from the stack route = stack.pop() var callback // if the stack is not empty yet, i.e., if this is not // the last route part, the callback standard callback is provided if (stack.length) { callback = done } // otherwise a slightly modified callback is provided else { callback = function() { done.end() } callback.redirect = done.redirect callback.render = function() { res.render.apply(res, [req.app._currentRoute].concat(Array.prototype.slice.call(arguments), finalize)) } } // exectue the route part route.execute(req.app, req, res, callback) }
javascript
function done() { // get the next route from the stack route = stack.pop() var callback // if the stack is not empty yet, i.e., if this is not // the last route part, the callback standard callback is provided if (stack.length) { callback = done } // otherwise a slightly modified callback is provided else { callback = function() { done.end() } callback.redirect = done.redirect callback.render = function() { res.render.apply(res, [req.app._currentRoute].concat(Array.prototype.slice.call(arguments), finalize)) } } // exectue the route part route.execute(req.app, req, res, callback) }
[ "function", "done", "(", ")", "{", "// get the next route from the stack", "route", "=", "stack", ".", "pop", "(", ")", "var", "callback", "// if the stack is not empty yet, i.e., if this is not", "// the last route part, the callback standard callback is provided", "if", "(", "stack", ".", "length", ")", "{", "callback", "=", "done", "}", "// otherwise a slightly modified callback is provided", "else", "{", "callback", "=", "function", "(", ")", "{", "done", ".", "end", "(", ")", "}", "callback", ".", "redirect", "=", "done", ".", "redirect", "callback", ".", "render", "=", "function", "(", ")", "{", "res", ".", "render", ".", "apply", "(", "res", ",", "[", "req", ".", "app", ".", "_currentRoute", "]", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ",", "finalize", ")", ")", "}", "}", "// exectue the route part", "route", ".", "execute", "(", "req", ".", "app", ",", "req", ",", "res", ",", "callback", ")", "}" ]
the callback method that is provided to each route node
[ "the", "callback", "method", "that", "is", "provided", "to", "each", "route", "node" ]
930c5618bc257fd8bceade6875f126a742b45828
https://github.com/rkusa/swac/blob/930c5618bc257fd8bceade6875f126a742b45828/lib/routing.js#L214-L237
48,913
meetings/gearsloth
lib/daemon/ejector.js
Ejector
function Ejector(conf) { component.Component.call(this, 'ejector', conf); var that = this; this._dbconn = conf.dbconn; this.registerGearman(conf.servers, { worker: { func_name: 'delayedJobDone', func: function(payload, worker) { var task = JSON.parse(payload.toString()); that._info('Received a task with id:', task.id); that.eject(task, worker); } } }); }
javascript
function Ejector(conf) { component.Component.call(this, 'ejector', conf); var that = this; this._dbconn = conf.dbconn; this.registerGearman(conf.servers, { worker: { func_name: 'delayedJobDone', func: function(payload, worker) { var task = JSON.parse(payload.toString()); that._info('Received a task with id:', task.id); that.eject(task, worker); } } }); }
[ "function", "Ejector", "(", "conf", ")", "{", "component", ".", "Component", ".", "call", "(", "this", ",", "'ejector'", ",", "conf", ")", ";", "var", "that", "=", "this", ";", "this", ".", "_dbconn", "=", "conf", ".", "dbconn", ";", "this", ".", "registerGearman", "(", "conf", ".", "servers", ",", "{", "worker", ":", "{", "func_name", ":", "'delayedJobDone'", ",", "func", ":", "function", "(", "payload", ",", "worker", ")", "{", "var", "task", "=", "JSON", ".", "parse", "(", "payload", ".", "toString", "(", ")", ")", ";", "that", ".", "_info", "(", "'Received a task with id:'", ",", "task", ".", "id", ")", ";", "that", ".", "eject", "(", "task", ",", "worker", ")", ";", "}", "}", "}", ")", ";", "}" ]
Ejector component. Emits 'connect' when at least one server is connected.
[ "Ejector", "component", ".", "Emits", "connect", "when", "at", "least", "one", "server", "is", "connected", "." ]
21d07729d6197bdbea515f32922896e3ae485d46
https://github.com/meetings/gearsloth/blob/21d07729d6197bdbea515f32922896e3ae485d46/lib/daemon/ejector.js#L8-L22
48,914
angeloocana/ptz-math
dist-esnext/index.js
getRandomItem
function getRandomItem(list) { if (!list) return null; if (list.length === 0) return list[0]; const randomIndex = random(1, list.length) - 1; return list[randomIndex]; }
javascript
function getRandomItem(list) { if (!list) return null; if (list.length === 0) return list[0]; const randomIndex = random(1, list.length) - 1; return list[randomIndex]; }
[ "function", "getRandomItem", "(", "list", ")", "{", "if", "(", "!", "list", ")", "return", "null", ";", "if", "(", "list", ".", "length", "===", "0", ")", "return", "list", "[", "0", "]", ";", "const", "randomIndex", "=", "random", "(", "1", ",", "list", ".", "length", ")", "-", "1", ";", "return", "list", "[", "randomIndex", "]", ";", "}" ]
Gets some random item from the given array. @param list
[ "Gets", "some", "random", "item", "from", "the", "given", "array", "." ]
25f17ec0fb9b62b4459d6bc43074c349811f682d
https://github.com/angeloocana/ptz-math/blob/25f17ec0fb9b62b4459d6bc43074c349811f682d/dist-esnext/index.js#L10-L17
48,915
cludden/app-container
lib/container.js
_loadRecursive
function _loadRecursive(container, map, accum = {}) { return Bluebird.reduce(Object.keys(map), (memo, key) => { const path = map[key]; if (typeof path === 'string') { return container._load(path) .then((mod) => { set(memo, key, mod); return memo; }); } return _loadRecursive(container, path) .then((mods) => { set(memo, key, mods); return memo; }); }, accum); }
javascript
function _loadRecursive(container, map, accum = {}) { return Bluebird.reduce(Object.keys(map), (memo, key) => { const path = map[key]; if (typeof path === 'string') { return container._load(path) .then((mod) => { set(memo, key, mod); return memo; }); } return _loadRecursive(container, path) .then((mods) => { set(memo, key, mods); return memo; }); }, accum); }
[ "function", "_loadRecursive", "(", "container", ",", "map", ",", "accum", "=", "{", "}", ")", "{", "return", "Bluebird", ".", "reduce", "(", "Object", ".", "keys", "(", "map", ")", ",", "(", "memo", ",", "key", ")", "=>", "{", "const", "path", "=", "map", "[", "key", "]", ";", "if", "(", "typeof", "path", "===", "'string'", ")", "{", "return", "container", ".", "_load", "(", "path", ")", ".", "then", "(", "(", "mod", ")", "=>", "{", "set", "(", "memo", ",", "key", ",", "mod", ")", ";", "return", "memo", ";", "}", ")", ";", "}", "return", "_loadRecursive", "(", "container", ",", "path", ")", ".", "then", "(", "(", "mods", ")", "=>", "{", "set", "(", "memo", ",", "key", ",", "mods", ")", ";", "return", "memo", ";", "}", ")", ";", "}", ",", "accum", ")", ";", "}" ]
Recursively load a component map @param {Container} container @param {Object} map @param {Object} [accum={}] @return {Bluebird} @private
[ "Recursively", "load", "a", "component", "map" ]
cdae445179eaf240f414a004f1b28653b49f8549
https://github.com/cludden/app-container/blob/cdae445179eaf240f414a004f1b28653b49f8549/lib/container.js#L296-L312
48,916
cludden/app-container
lib/container.js
_recursiveDeps
function _recursiveDeps(graph, name, deps) { return Object.keys(deps).forEach((key) => { const dep = deps[key]; if (PLUGIN.test(dep)) { return; } if (typeof dep === 'string') { if (!graph.hasNode(dep)) { graph.addNode(dep); } graph.addDependency(name, dep); } else if (typeof dep === 'object') { _recursiveDeps(graph, name, deps[key]); } }); }
javascript
function _recursiveDeps(graph, name, deps) { return Object.keys(deps).forEach((key) => { const dep = deps[key]; if (PLUGIN.test(dep)) { return; } if (typeof dep === 'string') { if (!graph.hasNode(dep)) { graph.addNode(dep); } graph.addDependency(name, dep); } else if (typeof dep === 'object') { _recursiveDeps(graph, name, deps[key]); } }); }
[ "function", "_recursiveDeps", "(", "graph", ",", "name", ",", "deps", ")", "{", "return", "Object", ".", "keys", "(", "deps", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "const", "dep", "=", "deps", "[", "key", "]", ";", "if", "(", "PLUGIN", ".", "test", "(", "dep", ")", ")", "{", "return", ";", "}", "if", "(", "typeof", "dep", "===", "'string'", ")", "{", "if", "(", "!", "graph", ".", "hasNode", "(", "dep", ")", ")", "{", "graph", ".", "addNode", "(", "dep", ")", ";", "}", "graph", ".", "addDependency", "(", "name", ",", "dep", ")", ";", "}", "else", "if", "(", "typeof", "dep", "===", "'object'", ")", "{", "_recursiveDeps", "(", "graph", ",", "name", ",", "deps", "[", "key", "]", ")", ";", "}", "}", ")", ";", "}" ]
Add recursive dependencies to dependency graph @param {DepGraph} graph @param {String} name - current node name @param {Object} deps - dependency map @private
[ "Add", "recursive", "dependencies", "to", "dependency", "graph" ]
cdae445179eaf240f414a004f1b28653b49f8549
https://github.com/cludden/app-container/blob/cdae445179eaf240f414a004f1b28653b49f8549/lib/container.js#L321-L336
48,917
bholloway/browserify-debug-tools
lib/profile.js
profile
function profile(excludeRegex) { var categories = []; return { forCategory: forCategory, toArray : toArray, toString : toString }; function toArray() { return categories; } function toString() { return categories .map(String) .filter(Boolean) .join('\n'); } /** * Create a category for analysis. * @param {string} [label] Optional category label * @param {{forCategory:function, start:function, stop:function, report:function, toString:function}} A new instance */ function forCategory(label) { var eventsByFilename = {}, isUsed = false, self = { forCategory: forCategory, start : start, stop : stop, report : report, toString : toString }; label = label || ('category-' + String.fromCharCode(65 + categories.length)); categories.push(self); return self; /** * Start a segment delineated by the given key. * @param {string} key A key to delineate a segment * @returns {function} A transform that causes a start event when the file is completed streaming */ function start(key) { return createEventTransform(key); } /** * Stop the currently delineated segment. * @returns {function} A transform that causes a stop event when the file is completed streaming */ function stop() { return createEventTransform(null); } /** * Create a transform that pushes time-stamped events data to the current filename. * @param {*} data The event data * @returns {function} A browserify transform that captures events on file contents complete */ function createEventTransform(data) { return inspect(onComplete); function onComplete(filename) { isUsed = true; var now = Date.now(); var events = eventsByFilename[filename] = eventsByFilename[filename] || []; events.push(now, data); } } /** * Create a json report of time verses key verses filename. */ function report() { return Object.keys(eventsByFilename) .filter(testIncluded) .reduce(reduceFilenames, {}); function testIncluded(filename) { return !excludeRegex || !excludeRegex.test(filename); } function reduceFilenames(reduced, filename) { var totalsByKey = {}, list = eventsByFilename[filename], lastKey = null, lastTime = NaN; // events consist of time,key pairs for (var i = 0; i < list.length; i += 2) { var time = list[i], key = list[i + 1]; if (lastKey) { var initial = totalsByKey[key] || 0, delta = ((time - lastTime) / 1000) || 0; totalsByKey[lastKey] = initial + delta; } lastKey = key; lastTime = time; } // total at the end to guarantee consistency var total = 0; for (var key in totalsByKey) { total += totalsByKey[key]; } totalsByKey.total = total; // store by the short filename var short = path.relative(process.cwd(), filename); reduced[short] = totalsByKey; return reduced; } } /** * A string representation of the report, sorted by longest time. */ function toString() { var json = report(), filenames = Object.keys(json), longestFilename = filenames.reduce(reduceFilenamesToLength, 0), columnOrder = orderColumns(), headerRow = [label].concat(columnOrder).map(leftJustify).join(' '), delimiter = (new Array(headerRow.length + 1)).join('-'); if (isUsed) { return [delimiter, headerRow, delimiter] .concat(rows()) .concat(delimiter) .filter(Boolean) .join('\n'); } else { return ''; } /** * Establish the column names, in order, left justified (for the maximum length). */ function orderColumns() { var keyTotals = filenames.reduce(reduceFilenamesToKeyTotal, {}); return sort(keyTotals); function reduceFilenamesToKeyTotal(reduced, filename) { var item = json[filename]; return Object.keys(item) .reduce(reducePropToLength.bind(item), reduced); } } /** * Map each filename to a data row, in decreasing time order. */ function rows() { var fileTotals = filenames.reduce(reducePropToLength.bind(json), {}), fileOrder = sort(fileTotals); return fileOrder.map(rowForFile); function rowForFile(filename) { var data = json[filename]; // console.log(JSON.stringify(data, null, 2)); return [filename] .concat(columnOrder .map(dataForColumn) .map(formatFloat)) .map(leftJustify) .join(' '); function dataForColumn(column) { return data[column]; } function formatFloat(number) { var padding = '000', warning = ((number > 99) ? '>' : ' '), integer = (padding + Math.min(99, Math.floor(number))).slice(-2), fraction = (padding + Math.round(1000 * number)).slice(-3); return warning + integer + '.' + fraction; } } } function reduceFilenamesToLength(reduced, filename) { return Math.max(filename.length, reduced); } function leftJustify(name, i) { var length = i ? Math.max(7, columnOrder[i - 1].length) : longestFilename; var padding = (new Array(length + 1)).join(' '); return (name + padding).slice(0, length); } function reducePropToLength(reduced, key) { var value = (typeof this[key] === 'object') ? this[key].total : this[key]; reduced[key] = (reduced[key] || 0) + value; return reduced; } function sort(object) { return Object.keys(object) .reduce(createObjects.bind(object), []) .sort(sortTimeDescending) .map(getColumnName); function createObjects(reduced, field) { reduced.push({ name: field, time: Math.round(this[field] * 1000) / 1000 // millisecond precision }); return reduced; } function sortTimeDescending(a, b) { return b.time - a.time; } function getColumnName(object) { return object.name; } } } } }
javascript
function profile(excludeRegex) { var categories = []; return { forCategory: forCategory, toArray : toArray, toString : toString }; function toArray() { return categories; } function toString() { return categories .map(String) .filter(Boolean) .join('\n'); } /** * Create a category for analysis. * @param {string} [label] Optional category label * @param {{forCategory:function, start:function, stop:function, report:function, toString:function}} A new instance */ function forCategory(label) { var eventsByFilename = {}, isUsed = false, self = { forCategory: forCategory, start : start, stop : stop, report : report, toString : toString }; label = label || ('category-' + String.fromCharCode(65 + categories.length)); categories.push(self); return self; /** * Start a segment delineated by the given key. * @param {string} key A key to delineate a segment * @returns {function} A transform that causes a start event when the file is completed streaming */ function start(key) { return createEventTransform(key); } /** * Stop the currently delineated segment. * @returns {function} A transform that causes a stop event when the file is completed streaming */ function stop() { return createEventTransform(null); } /** * Create a transform that pushes time-stamped events data to the current filename. * @param {*} data The event data * @returns {function} A browserify transform that captures events on file contents complete */ function createEventTransform(data) { return inspect(onComplete); function onComplete(filename) { isUsed = true; var now = Date.now(); var events = eventsByFilename[filename] = eventsByFilename[filename] || []; events.push(now, data); } } /** * Create a json report of time verses key verses filename. */ function report() { return Object.keys(eventsByFilename) .filter(testIncluded) .reduce(reduceFilenames, {}); function testIncluded(filename) { return !excludeRegex || !excludeRegex.test(filename); } function reduceFilenames(reduced, filename) { var totalsByKey = {}, list = eventsByFilename[filename], lastKey = null, lastTime = NaN; // events consist of time,key pairs for (var i = 0; i < list.length; i += 2) { var time = list[i], key = list[i + 1]; if (lastKey) { var initial = totalsByKey[key] || 0, delta = ((time - lastTime) / 1000) || 0; totalsByKey[lastKey] = initial + delta; } lastKey = key; lastTime = time; } // total at the end to guarantee consistency var total = 0; for (var key in totalsByKey) { total += totalsByKey[key]; } totalsByKey.total = total; // store by the short filename var short = path.relative(process.cwd(), filename); reduced[short] = totalsByKey; return reduced; } } /** * A string representation of the report, sorted by longest time. */ function toString() { var json = report(), filenames = Object.keys(json), longestFilename = filenames.reduce(reduceFilenamesToLength, 0), columnOrder = orderColumns(), headerRow = [label].concat(columnOrder).map(leftJustify).join(' '), delimiter = (new Array(headerRow.length + 1)).join('-'); if (isUsed) { return [delimiter, headerRow, delimiter] .concat(rows()) .concat(delimiter) .filter(Boolean) .join('\n'); } else { return ''; } /** * Establish the column names, in order, left justified (for the maximum length). */ function orderColumns() { var keyTotals = filenames.reduce(reduceFilenamesToKeyTotal, {}); return sort(keyTotals); function reduceFilenamesToKeyTotal(reduced, filename) { var item = json[filename]; return Object.keys(item) .reduce(reducePropToLength.bind(item), reduced); } } /** * Map each filename to a data row, in decreasing time order. */ function rows() { var fileTotals = filenames.reduce(reducePropToLength.bind(json), {}), fileOrder = sort(fileTotals); return fileOrder.map(rowForFile); function rowForFile(filename) { var data = json[filename]; // console.log(JSON.stringify(data, null, 2)); return [filename] .concat(columnOrder .map(dataForColumn) .map(formatFloat)) .map(leftJustify) .join(' '); function dataForColumn(column) { return data[column]; } function formatFloat(number) { var padding = '000', warning = ((number > 99) ? '>' : ' '), integer = (padding + Math.min(99, Math.floor(number))).slice(-2), fraction = (padding + Math.round(1000 * number)).slice(-3); return warning + integer + '.' + fraction; } } } function reduceFilenamesToLength(reduced, filename) { return Math.max(filename.length, reduced); } function leftJustify(name, i) { var length = i ? Math.max(7, columnOrder[i - 1].length) : longestFilename; var padding = (new Array(length + 1)).join(' '); return (name + padding).slice(0, length); } function reducePropToLength(reduced, key) { var value = (typeof this[key] === 'object') ? this[key].total : this[key]; reduced[key] = (reduced[key] || 0) + value; return reduced; } function sort(object) { return Object.keys(object) .reduce(createObjects.bind(object), []) .sort(sortTimeDescending) .map(getColumnName); function createObjects(reduced, field) { reduced.push({ name: field, time: Math.round(this[field] * 1000) / 1000 // millisecond precision }); return reduced; } function sortTimeDescending(a, b) { return b.time - a.time; } function getColumnName(object) { return object.name; } } } } }
[ "function", "profile", "(", "excludeRegex", ")", "{", "var", "categories", "=", "[", "]", ";", "return", "{", "forCategory", ":", "forCategory", ",", "toArray", ":", "toArray", ",", "toString", ":", "toString", "}", ";", "function", "toArray", "(", ")", "{", "return", "categories", ";", "}", "function", "toString", "(", ")", "{", "return", "categories", ".", "map", "(", "String", ")", ".", "filter", "(", "Boolean", ")", ".", "join", "(", "'\\n'", ")", ";", "}", "/**\n * Create a category for analysis.\n * @param {string} [label] Optional category label\n * @param {{forCategory:function, start:function, stop:function, report:function, toString:function}} A new instance\n */", "function", "forCategory", "(", "label", ")", "{", "var", "eventsByFilename", "=", "{", "}", ",", "isUsed", "=", "false", ",", "self", "=", "{", "forCategory", ":", "forCategory", ",", "start", ":", "start", ",", "stop", ":", "stop", ",", "report", ":", "report", ",", "toString", ":", "toString", "}", ";", "label", "=", "label", "||", "(", "'category-'", "+", "String", ".", "fromCharCode", "(", "65", "+", "categories", ".", "length", ")", ")", ";", "categories", ".", "push", "(", "self", ")", ";", "return", "self", ";", "/**\n * Start a segment delineated by the given key.\n * @param {string} key A key to delineate a segment\n * @returns {function} A transform that causes a start event when the file is completed streaming\n */", "function", "start", "(", "key", ")", "{", "return", "createEventTransform", "(", "key", ")", ";", "}", "/**\n * Stop the currently delineated segment.\n * @returns {function} A transform that causes a stop event when the file is completed streaming\n */", "function", "stop", "(", ")", "{", "return", "createEventTransform", "(", "null", ")", ";", "}", "/**\n * Create a transform that pushes time-stamped events data to the current filename.\n * @param {*} data The event data\n * @returns {function} A browserify transform that captures events on file contents complete\n */", "function", "createEventTransform", "(", "data", ")", "{", "return", "inspect", "(", "onComplete", ")", ";", "function", "onComplete", "(", "filename", ")", "{", "isUsed", "=", "true", ";", "var", "now", "=", "Date", ".", "now", "(", ")", ";", "var", "events", "=", "eventsByFilename", "[", "filename", "]", "=", "eventsByFilename", "[", "filename", "]", "||", "[", "]", ";", "events", ".", "push", "(", "now", ",", "data", ")", ";", "}", "}", "/**\n * Create a json report of time verses key verses filename.\n */", "function", "report", "(", ")", "{", "return", "Object", ".", "keys", "(", "eventsByFilename", ")", ".", "filter", "(", "testIncluded", ")", ".", "reduce", "(", "reduceFilenames", ",", "{", "}", ")", ";", "function", "testIncluded", "(", "filename", ")", "{", "return", "!", "excludeRegex", "||", "!", "excludeRegex", ".", "test", "(", "filename", ")", ";", "}", "function", "reduceFilenames", "(", "reduced", ",", "filename", ")", "{", "var", "totalsByKey", "=", "{", "}", ",", "list", "=", "eventsByFilename", "[", "filename", "]", ",", "lastKey", "=", "null", ",", "lastTime", "=", "NaN", ";", "// events consist of time,key pairs", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "+=", "2", ")", "{", "var", "time", "=", "list", "[", "i", "]", ",", "key", "=", "list", "[", "i", "+", "1", "]", ";", "if", "(", "lastKey", ")", "{", "var", "initial", "=", "totalsByKey", "[", "key", "]", "||", "0", ",", "delta", "=", "(", "(", "time", "-", "lastTime", ")", "/", "1000", ")", "||", "0", ";", "totalsByKey", "[", "lastKey", "]", "=", "initial", "+", "delta", ";", "}", "lastKey", "=", "key", ";", "lastTime", "=", "time", ";", "}", "// total at the end to guarantee consistency", "var", "total", "=", "0", ";", "for", "(", "var", "key", "in", "totalsByKey", ")", "{", "total", "+=", "totalsByKey", "[", "key", "]", ";", "}", "totalsByKey", ".", "total", "=", "total", ";", "// store by the short filename", "var", "short", "=", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "filename", ")", ";", "reduced", "[", "short", "]", "=", "totalsByKey", ";", "return", "reduced", ";", "}", "}", "/**\n * A string representation of the report, sorted by longest time.\n */", "function", "toString", "(", ")", "{", "var", "json", "=", "report", "(", ")", ",", "filenames", "=", "Object", ".", "keys", "(", "json", ")", ",", "longestFilename", "=", "filenames", ".", "reduce", "(", "reduceFilenamesToLength", ",", "0", ")", ",", "columnOrder", "=", "orderColumns", "(", ")", ",", "headerRow", "=", "[", "label", "]", ".", "concat", "(", "columnOrder", ")", ".", "map", "(", "leftJustify", ")", ".", "join", "(", "' '", ")", ",", "delimiter", "=", "(", "new", "Array", "(", "headerRow", ".", "length", "+", "1", ")", ")", ".", "join", "(", "'-'", ")", ";", "if", "(", "isUsed", ")", "{", "return", "[", "delimiter", ",", "headerRow", ",", "delimiter", "]", ".", "concat", "(", "rows", "(", ")", ")", ".", "concat", "(", "delimiter", ")", ".", "filter", "(", "Boolean", ")", ".", "join", "(", "'\\n'", ")", ";", "}", "else", "{", "return", "''", ";", "}", "/**\n * Establish the column names, in order, left justified (for the maximum length).\n */", "function", "orderColumns", "(", ")", "{", "var", "keyTotals", "=", "filenames", ".", "reduce", "(", "reduceFilenamesToKeyTotal", ",", "{", "}", ")", ";", "return", "sort", "(", "keyTotals", ")", ";", "function", "reduceFilenamesToKeyTotal", "(", "reduced", ",", "filename", ")", "{", "var", "item", "=", "json", "[", "filename", "]", ";", "return", "Object", ".", "keys", "(", "item", ")", ".", "reduce", "(", "reducePropToLength", ".", "bind", "(", "item", ")", ",", "reduced", ")", ";", "}", "}", "/**\n * Map each filename to a data row, in decreasing time order.\n */", "function", "rows", "(", ")", "{", "var", "fileTotals", "=", "filenames", ".", "reduce", "(", "reducePropToLength", ".", "bind", "(", "json", ")", ",", "{", "}", ")", ",", "fileOrder", "=", "sort", "(", "fileTotals", ")", ";", "return", "fileOrder", ".", "map", "(", "rowForFile", ")", ";", "function", "rowForFile", "(", "filename", ")", "{", "var", "data", "=", "json", "[", "filename", "]", ";", "// console.log(JSON.stringify(data, null, 2));", "return", "[", "filename", "]", ".", "concat", "(", "columnOrder", ".", "map", "(", "dataForColumn", ")", ".", "map", "(", "formatFloat", ")", ")", ".", "map", "(", "leftJustify", ")", ".", "join", "(", "' '", ")", ";", "function", "dataForColumn", "(", "column", ")", "{", "return", "data", "[", "column", "]", ";", "}", "function", "formatFloat", "(", "number", ")", "{", "var", "padding", "=", "'000'", ",", "warning", "=", "(", "(", "number", ">", "99", ")", "?", "'>'", ":", "' '", ")", ",", "integer", "=", "(", "padding", "+", "Math", ".", "min", "(", "99", ",", "Math", ".", "floor", "(", "number", ")", ")", ")", ".", "slice", "(", "-", "2", ")", ",", "fraction", "=", "(", "padding", "+", "Math", ".", "round", "(", "1000", "*", "number", ")", ")", ".", "slice", "(", "-", "3", ")", ";", "return", "warning", "+", "integer", "+", "'.'", "+", "fraction", ";", "}", "}", "}", "function", "reduceFilenamesToLength", "(", "reduced", ",", "filename", ")", "{", "return", "Math", ".", "max", "(", "filename", ".", "length", ",", "reduced", ")", ";", "}", "function", "leftJustify", "(", "name", ",", "i", ")", "{", "var", "length", "=", "i", "?", "Math", ".", "max", "(", "7", ",", "columnOrder", "[", "i", "-", "1", "]", ".", "length", ")", ":", "longestFilename", ";", "var", "padding", "=", "(", "new", "Array", "(", "length", "+", "1", ")", ")", ".", "join", "(", "' '", ")", ";", "return", "(", "name", "+", "padding", ")", ".", "slice", "(", "0", ",", "length", ")", ";", "}", "function", "reducePropToLength", "(", "reduced", ",", "key", ")", "{", "var", "value", "=", "(", "typeof", "this", "[", "key", "]", "===", "'object'", ")", "?", "this", "[", "key", "]", ".", "total", ":", "this", "[", "key", "]", ";", "reduced", "[", "key", "]", "=", "(", "reduced", "[", "key", "]", "||", "0", ")", "+", "value", ";", "return", "reduced", ";", "}", "function", "sort", "(", "object", ")", "{", "return", "Object", ".", "keys", "(", "object", ")", ".", "reduce", "(", "createObjects", ".", "bind", "(", "object", ")", ",", "[", "]", ")", ".", "sort", "(", "sortTimeDescending", ")", ".", "map", "(", "getColumnName", ")", ";", "function", "createObjects", "(", "reduced", ",", "field", ")", "{", "reduced", ".", "push", "(", "{", "name", ":", "field", ",", "time", ":", "Math", ".", "round", "(", "this", "[", "field", "]", "*", "1000", ")", "/", "1000", "// millisecond precision", "}", ")", ";", "return", "reduced", ";", "}", "function", "sortTimeDescending", "(", "a", ",", "b", ")", "{", "return", "b", ".", "time", "-", "a", ".", "time", ";", "}", "function", "getColumnName", "(", "object", ")", "{", "return", "object", ".", "name", ";", "}", "}", "}", "}", "}" ]
Analyse one or more transforms which perform a bulk action on stream flush. @param {RegExp} [excludeRegex] Optionally exclude files @returns {{forCategory:function, toArray:function, toString:function}} A new instance
[ "Analyse", "one", "or", "more", "transforms", "which", "perform", "a", "bulk", "action", "on", "stream", "flush", "." ]
47aa05164d73ec7512bdd4a18db0e12fa6b96209
https://github.com/bholloway/browserify-debug-tools/blob/47aa05164d73ec7512bdd4a18db0e12fa6b96209/lib/profile.js#L12-L236
48,918
bholloway/browserify-debug-tools
lib/profile.js
createEventTransform
function createEventTransform(data) { return inspect(onComplete); function onComplete(filename) { isUsed = true; var now = Date.now(); var events = eventsByFilename[filename] = eventsByFilename[filename] || []; events.push(now, data); } }
javascript
function createEventTransform(data) { return inspect(onComplete); function onComplete(filename) { isUsed = true; var now = Date.now(); var events = eventsByFilename[filename] = eventsByFilename[filename] || []; events.push(now, data); } }
[ "function", "createEventTransform", "(", "data", ")", "{", "return", "inspect", "(", "onComplete", ")", ";", "function", "onComplete", "(", "filename", ")", "{", "isUsed", "=", "true", ";", "var", "now", "=", "Date", ".", "now", "(", ")", ";", "var", "events", "=", "eventsByFilename", "[", "filename", "]", "=", "eventsByFilename", "[", "filename", "]", "||", "[", "]", ";", "events", ".", "push", "(", "now", ",", "data", ")", ";", "}", "}" ]
Create a transform that pushes time-stamped events data to the current filename. @param {*} data The event data @returns {function} A browserify transform that captures events on file contents complete
[ "Create", "a", "transform", "that", "pushes", "time", "-", "stamped", "events", "data", "to", "the", "current", "filename", "." ]
47aa05164d73ec7512bdd4a18db0e12fa6b96209
https://github.com/bholloway/browserify-debug-tools/blob/47aa05164d73ec7512bdd4a18db0e12fa6b96209/lib/profile.js#L73-L82
48,919
bholloway/browserify-debug-tools
lib/profile.js
report
function report() { return Object.keys(eventsByFilename) .filter(testIncluded) .reduce(reduceFilenames, {}); function testIncluded(filename) { return !excludeRegex || !excludeRegex.test(filename); } function reduceFilenames(reduced, filename) { var totalsByKey = {}, list = eventsByFilename[filename], lastKey = null, lastTime = NaN; // events consist of time,key pairs for (var i = 0; i < list.length; i += 2) { var time = list[i], key = list[i + 1]; if (lastKey) { var initial = totalsByKey[key] || 0, delta = ((time - lastTime) / 1000) || 0; totalsByKey[lastKey] = initial + delta; } lastKey = key; lastTime = time; } // total at the end to guarantee consistency var total = 0; for (var key in totalsByKey) { total += totalsByKey[key]; } totalsByKey.total = total; // store by the short filename var short = path.relative(process.cwd(), filename); reduced[short] = totalsByKey; return reduced; } }
javascript
function report() { return Object.keys(eventsByFilename) .filter(testIncluded) .reduce(reduceFilenames, {}); function testIncluded(filename) { return !excludeRegex || !excludeRegex.test(filename); } function reduceFilenames(reduced, filename) { var totalsByKey = {}, list = eventsByFilename[filename], lastKey = null, lastTime = NaN; // events consist of time,key pairs for (var i = 0; i < list.length; i += 2) { var time = list[i], key = list[i + 1]; if (lastKey) { var initial = totalsByKey[key] || 0, delta = ((time - lastTime) / 1000) || 0; totalsByKey[lastKey] = initial + delta; } lastKey = key; lastTime = time; } // total at the end to guarantee consistency var total = 0; for (var key in totalsByKey) { total += totalsByKey[key]; } totalsByKey.total = total; // store by the short filename var short = path.relative(process.cwd(), filename); reduced[short] = totalsByKey; return reduced; } }
[ "function", "report", "(", ")", "{", "return", "Object", ".", "keys", "(", "eventsByFilename", ")", ".", "filter", "(", "testIncluded", ")", ".", "reduce", "(", "reduceFilenames", ",", "{", "}", ")", ";", "function", "testIncluded", "(", "filename", ")", "{", "return", "!", "excludeRegex", "||", "!", "excludeRegex", ".", "test", "(", "filename", ")", ";", "}", "function", "reduceFilenames", "(", "reduced", ",", "filename", ")", "{", "var", "totalsByKey", "=", "{", "}", ",", "list", "=", "eventsByFilename", "[", "filename", "]", ",", "lastKey", "=", "null", ",", "lastTime", "=", "NaN", ";", "// events consist of time,key pairs", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "+=", "2", ")", "{", "var", "time", "=", "list", "[", "i", "]", ",", "key", "=", "list", "[", "i", "+", "1", "]", ";", "if", "(", "lastKey", ")", "{", "var", "initial", "=", "totalsByKey", "[", "key", "]", "||", "0", ",", "delta", "=", "(", "(", "time", "-", "lastTime", ")", "/", "1000", ")", "||", "0", ";", "totalsByKey", "[", "lastKey", "]", "=", "initial", "+", "delta", ";", "}", "lastKey", "=", "key", ";", "lastTime", "=", "time", ";", "}", "// total at the end to guarantee consistency", "var", "total", "=", "0", ";", "for", "(", "var", "key", "in", "totalsByKey", ")", "{", "total", "+=", "totalsByKey", "[", "key", "]", ";", "}", "totalsByKey", ".", "total", "=", "total", ";", "// store by the short filename", "var", "short", "=", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "filename", ")", ";", "reduced", "[", "short", "]", "=", "totalsByKey", ";", "return", "reduced", ";", "}", "}" ]
Create a json report of time verses key verses filename.
[ "Create", "a", "json", "report", "of", "time", "verses", "key", "verses", "filename", "." ]
47aa05164d73ec7512bdd4a18db0e12fa6b96209
https://github.com/bholloway/browserify-debug-tools/blob/47aa05164d73ec7512bdd4a18db0e12fa6b96209/lib/profile.js#L87-L127
48,920
bholloway/browserify-debug-tools
lib/profile.js
rows
function rows() { var fileTotals = filenames.reduce(reducePropToLength.bind(json), {}), fileOrder = sort(fileTotals); return fileOrder.map(rowForFile); function rowForFile(filename) { var data = json[filename]; // console.log(JSON.stringify(data, null, 2)); return [filename] .concat(columnOrder .map(dataForColumn) .map(formatFloat)) .map(leftJustify) .join(' '); function dataForColumn(column) { return data[column]; } function formatFloat(number) { var padding = '000', warning = ((number > 99) ? '>' : ' '), integer = (padding + Math.min(99, Math.floor(number))).slice(-2), fraction = (padding + Math.round(1000 * number)).slice(-3); return warning + integer + '.' + fraction; } } }
javascript
function rows() { var fileTotals = filenames.reduce(reducePropToLength.bind(json), {}), fileOrder = sort(fileTotals); return fileOrder.map(rowForFile); function rowForFile(filename) { var data = json[filename]; // console.log(JSON.stringify(data, null, 2)); return [filename] .concat(columnOrder .map(dataForColumn) .map(formatFloat)) .map(leftJustify) .join(' '); function dataForColumn(column) { return data[column]; } function formatFloat(number) { var padding = '000', warning = ((number > 99) ? '>' : ' '), integer = (padding + Math.min(99, Math.floor(number))).slice(-2), fraction = (padding + Math.round(1000 * number)).slice(-3); return warning + integer + '.' + fraction; } } }
[ "function", "rows", "(", ")", "{", "var", "fileTotals", "=", "filenames", ".", "reduce", "(", "reducePropToLength", ".", "bind", "(", "json", ")", ",", "{", "}", ")", ",", "fileOrder", "=", "sort", "(", "fileTotals", ")", ";", "return", "fileOrder", ".", "map", "(", "rowForFile", ")", ";", "function", "rowForFile", "(", "filename", ")", "{", "var", "data", "=", "json", "[", "filename", "]", ";", "// console.log(JSON.stringify(data, null, 2));", "return", "[", "filename", "]", ".", "concat", "(", "columnOrder", ".", "map", "(", "dataForColumn", ")", ".", "map", "(", "formatFloat", ")", ")", ".", "map", "(", "leftJustify", ")", ".", "join", "(", "' '", ")", ";", "function", "dataForColumn", "(", "column", ")", "{", "return", "data", "[", "column", "]", ";", "}", "function", "formatFloat", "(", "number", ")", "{", "var", "padding", "=", "'000'", ",", "warning", "=", "(", "(", "number", ">", "99", ")", "?", "'>'", ":", "' '", ")", ",", "integer", "=", "(", "padding", "+", "Math", ".", "min", "(", "99", ",", "Math", ".", "floor", "(", "number", ")", ")", ")", ".", "slice", "(", "-", "2", ")", ",", "fraction", "=", "(", "padding", "+", "Math", ".", "round", "(", "1000", "*", "number", ")", ")", ".", "slice", "(", "-", "3", ")", ";", "return", "warning", "+", "integer", "+", "'.'", "+", "fraction", ";", "}", "}", "}" ]
Map each filename to a data row, in decreasing time order.
[ "Map", "each", "filename", "to", "a", "data", "row", "in", "decreasing", "time", "order", "." ]
47aa05164d73ec7512bdd4a18db0e12fa6b96209
https://github.com/bholloway/browserify-debug-tools/blob/47aa05164d73ec7512bdd4a18db0e12fa6b96209/lib/profile.js#L167-L194
48,921
tdukai/bimo
dist/bimo.js
function (data) { // Add property to hold internal values Object.defineProperty(this, '_', { enumerable: false, configurable: false, writable: false, value: { dt: this._clone(data), ev: {}, df: {}, sp: false, ct: 0 } }); // Assign keys for (var key in this._.dt) { this._addProperty(key); } }
javascript
function (data) { // Add property to hold internal values Object.defineProperty(this, '_', { enumerable: false, configurable: false, writable: false, value: { dt: this._clone(data), ev: {}, df: {}, sp: false, ct: 0 } }); // Assign keys for (var key in this._.dt) { this._addProperty(key); } }
[ "function", "(", "data", ")", "{", "// Add property to hold internal values", "Object", ".", "defineProperty", "(", "this", ",", "'_'", ",", "{", "enumerable", ":", "false", ",", "configurable", ":", "false", ",", "writable", ":", "false", ",", "value", ":", "{", "dt", ":", "this", ".", "_clone", "(", "data", ")", ",", "ev", ":", "{", "}", ",", "df", ":", "{", "}", ",", "sp", ":", "false", ",", "ct", ":", "0", "}", "}", ")", ";", "// Assign keys", "for", "(", "var", "key", "in", "this", ".", "_", ".", "dt", ")", "{", "this", ".", "_addProperty", "(", "key", ")", ";", "}", "}" ]
Model base class @class Model @param {object} content in simple javascript object format @constructor
[ "Model", "base", "class" ]
55c1ae3cabdd6ef0b0a710240692e30e81ec83c9
https://github.com/tdukai/bimo/blob/55c1ae3cabdd6ef0b0a710240692e30e81ec83c9/dist/bimo.js#L10-L28
48,922
opendxl/opendxl-bootstrap-javascript
lib/application.js
Application
function Application (configDir, appConfigFileName) { /** * The DXL client to use for communication with the fabric. * @private * @type {external.DxlClient} * @name Application#_dxlClient */ this._dxlClient = null /** * The directory containing the application configuration files. * @private * @type {String} * @name Application#_configDir */ this._configDir = configDir /** * Full path to the file used to configure the DXL client. * @private * @type {String} * @name Application#_dxlClientConfigPath */ this._dxlClientConfigPath = path.join(configDir, DXL_CLIENT_CONFIG_FILE) /** * Full path to the application-specifie configuration file. * @private * @type {String} * @name Application#_appConfigPath */ this._appConfigPath = path.join(configDir, appConfigFileName) /** * Whether or not the application is currently running. * @private * @type {boolean} * @name Application#_running */ this._running = false /** * Loads the configuration settings from the application-specific * configuration file * @private */ this._loadConfiguration = function () { var configData try { configData = fs.readFileSync(this._appConfigPath, 'utf-8') } catch (err) { throw new Error('Unable to read configuration file: ' + err.message) } var parsedConfig try { parsedConfig = ini.parse(configData) } catch (err) { throw new Error('Unable to parse config file: ' + err.message) } this.onLoadConfiguration(parsedConfig) } /** * Attempts to connect to the DXL fabric. * @private * @param {Function} [callback=null] - Callback function which should be * invoked after the client has been connected. */ this._dxlConnect = function (callback) { var that = this var config = Config.createDxlConfigFromFile(this._dxlClientConfigPath) this._dxlClient = new Client(config) this._dxlClient.connect(function () { that.onRegisterEventHandlers() that.onRegisterServices() that.onDxlConnect() if (callback) { callback() } }) } }
javascript
function Application (configDir, appConfigFileName) { /** * The DXL client to use for communication with the fabric. * @private * @type {external.DxlClient} * @name Application#_dxlClient */ this._dxlClient = null /** * The directory containing the application configuration files. * @private * @type {String} * @name Application#_configDir */ this._configDir = configDir /** * Full path to the file used to configure the DXL client. * @private * @type {String} * @name Application#_dxlClientConfigPath */ this._dxlClientConfigPath = path.join(configDir, DXL_CLIENT_CONFIG_FILE) /** * Full path to the application-specifie configuration file. * @private * @type {String} * @name Application#_appConfigPath */ this._appConfigPath = path.join(configDir, appConfigFileName) /** * Whether or not the application is currently running. * @private * @type {boolean} * @name Application#_running */ this._running = false /** * Loads the configuration settings from the application-specific * configuration file * @private */ this._loadConfiguration = function () { var configData try { configData = fs.readFileSync(this._appConfigPath, 'utf-8') } catch (err) { throw new Error('Unable to read configuration file: ' + err.message) } var parsedConfig try { parsedConfig = ini.parse(configData) } catch (err) { throw new Error('Unable to parse config file: ' + err.message) } this.onLoadConfiguration(parsedConfig) } /** * Attempts to connect to the DXL fabric. * @private * @param {Function} [callback=null] - Callback function which should be * invoked after the client has been connected. */ this._dxlConnect = function (callback) { var that = this var config = Config.createDxlConfigFromFile(this._dxlClientConfigPath) this._dxlClient = new Client(config) this._dxlClient.connect(function () { that.onRegisterEventHandlers() that.onRegisterServices() that.onDxlConnect() if (callback) { callback() } }) } }
[ "function", "Application", "(", "configDir", ",", "appConfigFileName", ")", "{", "/**\n * The DXL client to use for communication with the fabric.\n * @private\n * @type {external.DxlClient}\n * @name Application#_dxlClient\n */", "this", ".", "_dxlClient", "=", "null", "/**\n * The directory containing the application configuration files.\n * @private\n * @type {String}\n * @name Application#_configDir\n */", "this", ".", "_configDir", "=", "configDir", "/**\n * Full path to the file used to configure the DXL client.\n * @private\n * @type {String}\n * @name Application#_dxlClientConfigPath\n */", "this", ".", "_dxlClientConfigPath", "=", "path", ".", "join", "(", "configDir", ",", "DXL_CLIENT_CONFIG_FILE", ")", "/**\n * Full path to the application-specifie configuration file.\n * @private\n * @type {String}\n * @name Application#_appConfigPath\n */", "this", ".", "_appConfigPath", "=", "path", ".", "join", "(", "configDir", ",", "appConfigFileName", ")", "/**\n * Whether or not the application is currently running.\n * @private\n * @type {boolean}\n * @name Application#_running\n */", "this", ".", "_running", "=", "false", "/**\n * Loads the configuration settings from the application-specific\n * configuration file\n * @private\n */", "this", ".", "_loadConfiguration", "=", "function", "(", ")", "{", "var", "configData", "try", "{", "configData", "=", "fs", ".", "readFileSync", "(", "this", ".", "_appConfigPath", ",", "'utf-8'", ")", "}", "catch", "(", "err", ")", "{", "throw", "new", "Error", "(", "'Unable to read configuration file: '", "+", "err", ".", "message", ")", "}", "var", "parsedConfig", "try", "{", "parsedConfig", "=", "ini", ".", "parse", "(", "configData", ")", "}", "catch", "(", "err", ")", "{", "throw", "new", "Error", "(", "'Unable to parse config file: '", "+", "err", ".", "message", ")", "}", "this", ".", "onLoadConfiguration", "(", "parsedConfig", ")", "}", "/**\n * Attempts to connect to the DXL fabric.\n * @private\n * @param {Function} [callback=null] - Callback function which should be\n * invoked after the client has been connected.\n */", "this", ".", "_dxlConnect", "=", "function", "(", "callback", ")", "{", "var", "that", "=", "this", "var", "config", "=", "Config", ".", "createDxlConfigFromFile", "(", "this", ".", "_dxlClientConfigPath", ")", "this", ".", "_dxlClient", "=", "new", "Client", "(", "config", ")", "this", ".", "_dxlClient", ".", "connect", "(", "function", "(", ")", "{", "that", ".", "onRegisterEventHandlers", "(", ")", "that", ".", "onRegisterServices", "(", ")", "that", ".", "onDxlConnect", "(", ")", "if", "(", "callback", ")", "{", "callback", "(", ")", "}", "}", ")", "}", "}" ]
Service registration instances are used to register and expose services onto a DXL fabric. @external ServiceRegistrationInfo @see {@link https://opendxl.github.io/opendxl-client-javascript/jsdoc/ServiceRegistrationInfo.html} @classdesc Base class used for DXL applications. @param {String} configDir - The directory containing the application configuration files. @param {String} appConfigFileName - The name of the application-specific configuration file. @constructor
[ "Service", "registration", "instances", "are", "used", "to", "register", "and", "expose", "services", "onto", "a", "DXL", "fabric", "." ]
f369077f059b0da12c2f918de5ce41331e1d9b28
https://github.com/opendxl/opendxl-bootstrap-javascript/blob/f369077f059b0da12c2f918de5ce41331e1d9b28/lib/application.js#L34-L113
48,923
nodys/polymerize
lib/transform.js
transform
function transform(filepath, options) { // Normalize options options = extend({ match: /bower_components.*\.html$/ }, options || {}) if(!(options.match instanceof RegExp)) { options.match = RegExp.apply(null, Array.isArray(options.match) ? options.match : [options.match]) } // Shim polymer.js if(/polymer\/polymer\.js$/.test(filepath)) { return fixpolymer(); } // Transform only source that vulcanize can handle if(!options.match.test(filepath) || !/\.html$/.test(filepath)) { return through(); } // Bufferize and polymerize var src = ''; return through( function(chunk) { src += chunk.toString() }, function() { this.queue(polymerize(src, filepath, options)) this.queue(null) } ); }
javascript
function transform(filepath, options) { // Normalize options options = extend({ match: /bower_components.*\.html$/ }, options || {}) if(!(options.match instanceof RegExp)) { options.match = RegExp.apply(null, Array.isArray(options.match) ? options.match : [options.match]) } // Shim polymer.js if(/polymer\/polymer\.js$/.test(filepath)) { return fixpolymer(); } // Transform only source that vulcanize can handle if(!options.match.test(filepath) || !/\.html$/.test(filepath)) { return through(); } // Bufferize and polymerize var src = ''; return through( function(chunk) { src += chunk.toString() }, function() { this.queue(polymerize(src, filepath, options)) this.queue(null) } ); }
[ "function", "transform", "(", "filepath", ",", "options", ")", "{", "// Normalize options", "options", "=", "extend", "(", "{", "match", ":", "/", "bower_components.*\\.html$", "/", "}", ",", "options", "||", "{", "}", ")", "if", "(", "!", "(", "options", ".", "match", "instanceof", "RegExp", ")", ")", "{", "options", ".", "match", "=", "RegExp", ".", "apply", "(", "null", ",", "Array", ".", "isArray", "(", "options", ".", "match", ")", "?", "options", ".", "match", ":", "[", "options", ".", "match", "]", ")", "}", "// Shim polymer.js", "if", "(", "/", "polymer\\/polymer\\.js$", "/", ".", "test", "(", "filepath", ")", ")", "{", "return", "fixpolymer", "(", ")", ";", "}", "// Transform only source that vulcanize can handle", "if", "(", "!", "options", ".", "match", ".", "test", "(", "filepath", ")", "||", "!", "/", "\\.html$", "/", ".", "test", "(", "filepath", ")", ")", "{", "return", "through", "(", ")", ";", "}", "// Bufferize and polymerize", "var", "src", "=", "''", ";", "return", "through", "(", "function", "(", "chunk", ")", "{", "src", "+=", "chunk", ".", "toString", "(", ")", "}", ",", "function", "(", ")", "{", "this", ".", "queue", "(", "polymerize", "(", "src", ",", "filepath", ",", "options", ")", ")", "this", ".", "queue", "(", "null", ")", "}", ")", ";", "}" ]
Browserify's transform function for polymerize @param {String} filepath @param {Object} [options] @return {Stream}
[ "Browserify", "s", "transform", "function", "for", "polymerize" ]
3f525ff5144c084ba4d501ab174828844f5a53dd
https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/transform.js#L14-L44
48,924
cliffano/ae86
lib/functions.js
include
function include(partial, cb) { cb((params.partials && params.partials[partial]) ? params.partials[partial] : '[error] partial ' + partial + ' does not exist'); }
javascript
function include(partial, cb) { cb((params.partials && params.partials[partial]) ? params.partials[partial] : '[error] partial ' + partial + ' does not exist'); }
[ "function", "include", "(", "partial", ",", "cb", ")", "{", "cb", "(", "(", "params", ".", "partials", "&&", "params", ".", "partials", "[", "partial", "]", ")", "?", "params", ".", "partials", "[", "partial", "]", ":", "'[error] partial '", "+", "partial", "+", "' does not exist'", ")", ";", "}" ]
Include a partial template in the current page. An error message will be included when partial does not exist. @param {String} partial: partial template file to include @param {Function} cb: jazz cb(data) callback
[ "Include", "a", "partial", "template", "in", "the", "current", "page", ".", "An", "error", "message", "will", "be", "included", "when", "partial", "does", "not", "exist", "." ]
7687e438a93638231bf7d2bebe1e8b062082a9a3
https://github.com/cliffano/ae86/blob/7687e438a93638231bf7d2bebe1e8b062082a9a3/lib/functions.js#L32-L36
48,925
cliffano/ae86
lib/functions.js
title
function title(cb) { cb((params.sitemap && params.sitemap[page]) ? params.sitemap[page].title : '[error] page ' + page + ' does not have any sitemap title'); }
javascript
function title(cb) { cb((params.sitemap && params.sitemap[page]) ? params.sitemap[page].title : '[error] page ' + page + ' does not have any sitemap title'); }
[ "function", "title", "(", "cb", ")", "{", "cb", "(", "(", "params", ".", "sitemap", "&&", "params", ".", "sitemap", "[", "page", "]", ")", "?", "params", ".", "sitemap", "[", "page", "]", ".", "title", ":", "'[error] page '", "+", "page", "+", "' does not have any sitemap title'", ")", ";", "}" ]
Display current page's sitemap title. @param {Function} cb: jazz cb(data) callback
[ "Display", "current", "page", "s", "sitemap", "title", "." ]
7687e438a93638231bf7d2bebe1e8b062082a9a3
https://github.com/cliffano/ae86/blob/7687e438a93638231bf7d2bebe1e8b062082a9a3/lib/functions.js#L60-L64
48,926
opendxl/opendxl-bootstrap-javascript
lib/message-utils.js
function (value, encoding) { encoding = (typeof encoding === 'undefined') ? 'utf8' : encoding if (Buffer.isBuffer(value)) { value = value.toString(encoding) } return value }
javascript
function (value, encoding) { encoding = (typeof encoding === 'undefined') ? 'utf8' : encoding if (Buffer.isBuffer(value)) { value = value.toString(encoding) } return value }
[ "function", "(", "value", ",", "encoding", ")", "{", "encoding", "=", "(", "typeof", "encoding", "===", "'undefined'", ")", "?", "'utf8'", ":", "encoding", "if", "(", "Buffer", ".", "isBuffer", "(", "value", ")", ")", "{", "value", "=", "value", ".", "toString", "(", "encoding", ")", "}", "return", "value", "}" ]
Decodes the specified value and returns it. @param {Buffer|String} value - The value. @param {String} encoding - The encoding. @returns {String} The decoded value
[ "Decodes", "the", "specified", "value", "and", "returns", "it", "." ]
f369077f059b0da12c2f918de5ce41331e1d9b28
https://github.com/opendxl/opendxl-bootstrap-javascript/blob/f369077f059b0da12c2f918de5ce41331e1d9b28/lib/message-utils.js#L58-L64
48,927
opendxl/opendxl-bootstrap-javascript
lib/message-utils.js
function (message, encoding) { return module.exports.jsonToObject( module.exports.decodePayload(message, encoding)) }
javascript
function (message, encoding) { return module.exports.jsonToObject( module.exports.decodePayload(message, encoding)) }
[ "function", "(", "message", ",", "encoding", ")", "{", "return", "module", ".", "exports", ".", "jsonToObject", "(", "module", ".", "exports", ".", "decodePayload", "(", "message", ",", "encoding", ")", ")", "}" ]
Converts the specified message's payload from JSON to an object and returns it. @param {external:Message} message - The DXL message. @param {String} [encoding=utf8] - The encoding of the payload. @returns {Object} The object.
[ "Converts", "the", "specified", "message", "s", "payload", "from", "JSON", "to", "an", "object", "and", "returns", "it", "." ]
f369077f059b0da12c2f918de5ce41331e1d9b28
https://github.com/opendxl/opendxl-bootstrap-javascript/blob/f369077f059b0da12c2f918de5ce41331e1d9b28/lib/message-utils.js#L91-L94
48,928
opendxl/opendxl-bootstrap-javascript
lib/message-utils.js
function (value, encoding) { encoding = (typeof encoding === 'undefined') ? 'utf8' : encoding var returnValue = value if (!Buffer.isBuffer(returnValue)) { if (value === null) { returnValue = '' } else if (typeof value === 'object') { returnValue = module.exports.objectToJson(value) } else if (typeof value !== 'string') { returnValue = '' + value } returnValue = Buffer.from(returnValue, encoding) } return returnValue }
javascript
function (value, encoding) { encoding = (typeof encoding === 'undefined') ? 'utf8' : encoding var returnValue = value if (!Buffer.isBuffer(returnValue)) { if (value === null) { returnValue = '' } else if (typeof value === 'object') { returnValue = module.exports.objectToJson(value) } else if (typeof value !== 'string') { returnValue = '' + value } returnValue = Buffer.from(returnValue, encoding) } return returnValue }
[ "function", "(", "value", ",", "encoding", ")", "{", "encoding", "=", "(", "typeof", "encoding", "===", "'undefined'", ")", "?", "'utf8'", ":", "encoding", "var", "returnValue", "=", "value", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "returnValue", ")", ")", "{", "if", "(", "value", "===", "null", ")", "{", "returnValue", "=", "''", "}", "else", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "returnValue", "=", "module", ".", "exports", ".", "objectToJson", "(", "value", ")", "}", "else", "if", "(", "typeof", "value", "!==", "'string'", ")", "{", "returnValue", "=", "''", "+", "value", "}", "returnValue", "=", "Buffer", ".", "from", "(", "returnValue", ",", "encoding", ")", "}", "return", "returnValue", "}" ]
Encodes the specified value and returns it. @param value - The value. @param {String} [encoding=utf8] - The encoding of the payload. @returns {Buffer} The encoded value.
[ "Encodes", "the", "specified", "value", "and", "returns", "it", "." ]
f369077f059b0da12c2f918de5ce41331e1d9b28
https://github.com/opendxl/opendxl-bootstrap-javascript/blob/f369077f059b0da12c2f918de5ce41331e1d9b28/lib/message-utils.js#L101-L115
48,929
opendxl/opendxl-bootstrap-javascript
lib/message-utils.js
function (message, value, encoding) { message.payload = module.exports.encode(value, encoding) }
javascript
function (message, value, encoding) { message.payload = module.exports.encode(value, encoding) }
[ "function", "(", "message", ",", "value", ",", "encoding", ")", "{", "message", ".", "payload", "=", "module", ".", "exports", ".", "encode", "(", "value", ",", "encoding", ")", "}" ]
Encodes the specified value and places it in the DXL message's payload. @param {external:Message} message - The DXL message. @param value - The value. @param {String} [encoding=utf8] - The encoding of the payload.
[ "Encodes", "the", "specified", "value", "and", "places", "it", "in", "the", "DXL", "message", "s", "payload", "." ]
f369077f059b0da12c2f918de5ce41331e1d9b28
https://github.com/opendxl/opendxl-bootstrap-javascript/blob/f369077f059b0da12c2f918de5ce41331e1d9b28/lib/message-utils.js#L122-L124
48,930
opendxl/opendxl-bootstrap-javascript
lib/message-utils.js
function (obj, prettyPrint) { return prettyPrint ? JSON.stringify(obj, Object.keys(findUniqueKeys( obj, {}, [])).sort(), 4) : JSON.stringify(obj) }
javascript
function (obj, prettyPrint) { return prettyPrint ? JSON.stringify(obj, Object.keys(findUniqueKeys( obj, {}, [])).sort(), 4) : JSON.stringify(obj) }
[ "function", "(", "obj", ",", "prettyPrint", ")", "{", "return", "prettyPrint", "?", "JSON", ".", "stringify", "(", "obj", ",", "Object", ".", "keys", "(", "findUniqueKeys", "(", "obj", ",", "{", "}", ",", "[", "]", ")", ")", ".", "sort", "(", ")", ",", "4", ")", ":", "JSON", ".", "stringify", "(", "obj", ")", "}" ]
Converts the specified object to a JSON string and returns it. @param {Object} obj - The object. @param {Boolean} [prettyPrint=false] - Whether to pretty print the JSON. @returns {String} The JSON string.
[ "Converts", "the", "specified", "object", "to", "a", "JSON", "string", "and", "returns", "it", "." ]
f369077f059b0da12c2f918de5ce41331e1d9b28
https://github.com/opendxl/opendxl-bootstrap-javascript/blob/f369077f059b0da12c2f918de5ce41331e1d9b28/lib/message-utils.js#L131-L135
48,931
BBWeb/derby-ar
lib/rpc.js
plugin
function plugin(derby) { // Wrap createBackend in order to be able to listen to derby-ar RPC calls // But only do it once (e.g. if we have many apps, we need to ensure we only wrap it once since otherwise we'll destroy the wrapping) if(derby.__createBackend) return; derby.__createBackend = derby.createBackend; derby.createBackend = function () { // Create backend using regular createBackend method var backend = this.__createBackend.apply(this, arguments); backend.rpc.on('derby-ar', function (data, cb) { var path = data.path; var method = data.method; var args = data.args || []; var model = backend.createModel(); var $scoped = model.scope(data.path); args.push(cb); $scoped[method].apply($scoped, args); }); return backend; }; }
javascript
function plugin(derby) { // Wrap createBackend in order to be able to listen to derby-ar RPC calls // But only do it once (e.g. if we have many apps, we need to ensure we only wrap it once since otherwise we'll destroy the wrapping) if(derby.__createBackend) return; derby.__createBackend = derby.createBackend; derby.createBackend = function () { // Create backend using regular createBackend method var backend = this.__createBackend.apply(this, arguments); backend.rpc.on('derby-ar', function (data, cb) { var path = data.path; var method = data.method; var args = data.args || []; var model = backend.createModel(); var $scoped = model.scope(data.path); args.push(cb); $scoped[method].apply($scoped, args); }); return backend; }; }
[ "function", "plugin", "(", "derby", ")", "{", "// Wrap createBackend in order to be able to listen to derby-ar RPC calls", "// But only do it once (e.g. if we have many apps, we need to ensure we only wrap it once since otherwise we'll destroy the wrapping)", "if", "(", "derby", ".", "__createBackend", ")", "return", ";", "derby", ".", "__createBackend", "=", "derby", ".", "createBackend", ";", "derby", ".", "createBackend", "=", "function", "(", ")", "{", "// Create backend using regular createBackend method", "var", "backend", "=", "this", ".", "__createBackend", ".", "apply", "(", "this", ",", "arguments", ")", ";", "backend", ".", "rpc", ".", "on", "(", "'derby-ar'", ",", "function", "(", "data", ",", "cb", ")", "{", "var", "path", "=", "data", ".", "path", ";", "var", "method", "=", "data", ".", "method", ";", "var", "args", "=", "data", ".", "args", "||", "[", "]", ";", "var", "model", "=", "backend", ".", "createModel", "(", ")", ";", "var", "$scoped", "=", "model", ".", "scope", "(", "data", ".", "path", ")", ";", "args", ".", "push", "(", "cb", ")", ";", "$scoped", "[", "method", "]", ".", "apply", "(", "$scoped", ",", "args", ")", ";", "}", ")", ";", "return", "backend", ";", "}", ";", "}" ]
Add RPC support
[ "Add", "RPC", "support" ]
18a1a732481683427501e768fb1de3b4f995e7ca
https://github.com/BBWeb/derby-ar/blob/18a1a732481683427501e768fb1de3b4f995e7ca/lib/rpc.js#L37-L62
48,932
ThatDevCompany/that-build-library
src/utils/removeModuleAlias.js
removeModuleAlias
function removeModuleAlias(moduleName, folder, replacement = './') { return __awaiter(this, void 0, void 0, function* () { fs.readdirSync(folder).forEach(child => { if (fs.statSync(folder + '/' + child).isDirectory()) { removeModuleAlias(moduleName, folder + '/' + child, './.' + replacement); } else { fs.writeFileSync(folder + '/' + child, fs .readFileSync(folder + '/' + child, 'utf8') .split(`require("${moduleName}/`) .join(`require("${replacement}`) .split(`require("./../`) .join(`require("../`) .split(`require('${moduleName}/`) .join(`require('${replacement}`) .split(`require('./../`) .join(`require('../`) .split(`from '${moduleName}/`) .join(`from '${replacement}`) .split(`from './../`) .join(`from '../`) .split(`module":"${moduleName}/`) .join(`module":"${replacement}`) .split(`module":"./../`) .join(`module":"../`)); } }); return Promise.resolve(); }); }
javascript
function removeModuleAlias(moduleName, folder, replacement = './') { return __awaiter(this, void 0, void 0, function* () { fs.readdirSync(folder).forEach(child => { if (fs.statSync(folder + '/' + child).isDirectory()) { removeModuleAlias(moduleName, folder + '/' + child, './.' + replacement); } else { fs.writeFileSync(folder + '/' + child, fs .readFileSync(folder + '/' + child, 'utf8') .split(`require("${moduleName}/`) .join(`require("${replacement}`) .split(`require("./../`) .join(`require("../`) .split(`require('${moduleName}/`) .join(`require('${replacement}`) .split(`require('./../`) .join(`require('../`) .split(`from '${moduleName}/`) .join(`from '${replacement}`) .split(`from './../`) .join(`from '../`) .split(`module":"${moduleName}/`) .join(`module":"${replacement}`) .split(`module":"./../`) .join(`module":"../`)); } }); return Promise.resolve(); }); }
[ "function", "removeModuleAlias", "(", "moduleName", ",", "folder", ",", "replacement", "=", "'./'", ")", "{", "return", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "*", "(", ")", "{", "fs", ".", "readdirSync", "(", "folder", ")", ".", "forEach", "(", "child", "=>", "{", "if", "(", "fs", ".", "statSync", "(", "folder", "+", "'/'", "+", "child", ")", ".", "isDirectory", "(", ")", ")", "{", "removeModuleAlias", "(", "moduleName", ",", "folder", "+", "'/'", "+", "child", ",", "'./.'", "+", "replacement", ")", ";", "}", "else", "{", "fs", ".", "writeFileSync", "(", "folder", "+", "'/'", "+", "child", ",", "fs", ".", "readFileSync", "(", "folder", "+", "'/'", "+", "child", ",", "'utf8'", ")", ".", "split", "(", "`", "${", "moduleName", "}", "`", ")", ".", "join", "(", "`", "${", "replacement", "}", "`", ")", ".", "split", "(", "`", "`", ")", ".", "join", "(", "`", "`", ")", ".", "split", "(", "`", "${", "moduleName", "}", "`", ")", ".", "join", "(", "`", "${", "replacement", "}", "`", ")", ".", "split", "(", "`", "`", ")", ".", "join", "(", "`", "`", ")", ".", "split", "(", "`", "${", "moduleName", "}", "`", ")", ".", "join", "(", "`", "${", "replacement", "}", "`", ")", ".", "split", "(", "`", "`", ")", ".", "join", "(", "`", "`", ")", ".", "split", "(", "`", "${", "moduleName", "}", "`", ")", ".", "join", "(", "`", "${", "replacement", "}", "`", ")", ".", "split", "(", "`", "`", ")", ".", "join", "(", "`", "`", ")", ")", ";", "}", "}", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
Remove Module Alias
[ "Remove", "Module", "Alias" ]
865aaac49531fa9793a055a4df8e9b1b41e71753
https://github.com/ThatDevCompany/that-build-library/blob/865aaac49531fa9793a055a4df8e9b1b41e71753/src/utils/removeModuleAlias.js#L15-L44
48,933
hughsk/glsl-resolve
index.js
packageFilter
function packageFilter(pkg, root) { pkg.main = pkg.glslify || ( path.extname(pkg.main || '') !== '.js' && pkg.main ) || 'index.glsl' return pkg }
javascript
function packageFilter(pkg, root) { pkg.main = pkg.glslify || ( path.extname(pkg.main || '') !== '.js' && pkg.main ) || 'index.glsl' return pkg }
[ "function", "packageFilter", "(", "pkg", ",", "root", ")", "{", "pkg", ".", "main", "=", "pkg", ".", "glslify", "||", "(", "path", ".", "extname", "(", "pkg", ".", "main", "||", "''", ")", "!==", "'.js'", "&&", "pkg", ".", "main", ")", "||", "'index.glsl'", "return", "pkg", "}" ]
find the "glslify", "main", or assume main == "index.glsl" if main is a .js file then ignore it.
[ "find", "the", "glslify", "main", "or", "assume", "main", "==", "index", ".", "glsl", "if", "main", "is", "a", ".", "js", "file", "then", "ignore", "it", "." ]
2f94e44bf25c51a8bf1c0897b6cb159779ab0586
https://github.com/hughsk/glsl-resolve/blob/2f94e44bf25c51a8bf1c0897b6cb159779ab0586/index.js#L48-L55
48,934
jacoborus/curlymail
curlymail.js
function (obj) { var fns = {}, i; for (i in obj) { fns[i] = hogan.compile( obj[i] ); } return fns; }
javascript
function (obj) { var fns = {}, i; for (i in obj) { fns[i] = hogan.compile( obj[i] ); } return fns; }
[ "function", "(", "obj", ")", "{", "var", "fns", "=", "{", "}", ",", "i", ";", "for", "(", "i", "in", "obj", ")", "{", "fns", "[", "i", "]", "=", "hogan", ".", "compile", "(", "obj", "[", "i", "]", ")", ";", "}", "return", "fns", ";", "}" ]
compile templates in a object
[ "compile", "templates", "in", "a", "object" ]
05a01aa76a3716a6c9cb51d9e8d4ef4bee63d8fc
https://github.com/jacoborus/curlymail/blob/05a01aa76a3716a6c9cb51d9e8d4ef4bee63d8fc/curlymail.js#L19-L26
48,935
boylesoftware/x2node-patches
lib/differ.js
diffObjects
function diffObjects(container, pathPrefix, objOld, objNew, patchSpec) { // keep track of processed properties const unrecognizedPropNames = new Set(Object.keys(objNew)); // diff main properties diffObjectProps( container, pathPrefix, objOld, objNew, unrecognizedPropNames, patchSpec); // check if polymorphic object and check the subtype properties if (container.isPolymorphObject()) { // type property is recognized unrecognizedPropNames.delete(container.typePropertyName); // match the subtype const subtype = objOld[container.typePropertyName]; if (objNew[container.typePropertyName] !== subtype) throw new common.X2SyntaxError( 'Polymorphic object type does not match.'); // go over the subtype properties const subtypeDesc = container.getPropertyDesc(subtype); diffObjectProps( subtypeDesc.nestedProperties, `${pathPrefix}${subtype}:`, objOld, objNew, unrecognizedPropNames, patchSpec); } // any unrecognized properties? if (unrecognizedPropNames.size > 0) throw new common.X2SyntaxError( `Unrecognized properties for ${container.recordTypeName}` + ` at ${pathPrefix}:` + Array.from(unrecognizedPropNames).join(', ')); }
javascript
function diffObjects(container, pathPrefix, objOld, objNew, patchSpec) { // keep track of processed properties const unrecognizedPropNames = new Set(Object.keys(objNew)); // diff main properties diffObjectProps( container, pathPrefix, objOld, objNew, unrecognizedPropNames, patchSpec); // check if polymorphic object and check the subtype properties if (container.isPolymorphObject()) { // type property is recognized unrecognizedPropNames.delete(container.typePropertyName); // match the subtype const subtype = objOld[container.typePropertyName]; if (objNew[container.typePropertyName] !== subtype) throw new common.X2SyntaxError( 'Polymorphic object type does not match.'); // go over the subtype properties const subtypeDesc = container.getPropertyDesc(subtype); diffObjectProps( subtypeDesc.nestedProperties, `${pathPrefix}${subtype}:`, objOld, objNew, unrecognizedPropNames, patchSpec); } // any unrecognized properties? if (unrecognizedPropNames.size > 0) throw new common.X2SyntaxError( `Unrecognized properties for ${container.recordTypeName}` + ` at ${pathPrefix}:` + Array.from(unrecognizedPropNames).join(', ')); }
[ "function", "diffObjects", "(", "container", ",", "pathPrefix", ",", "objOld", ",", "objNew", ",", "patchSpec", ")", "{", "// keep track of processed properties", "const", "unrecognizedPropNames", "=", "new", "Set", "(", "Object", ".", "keys", "(", "objNew", ")", ")", ";", "// diff main properties", "diffObjectProps", "(", "container", ",", "pathPrefix", ",", "objOld", ",", "objNew", ",", "unrecognizedPropNames", ",", "patchSpec", ")", ";", "// check if polymorphic object and check the subtype properties", "if", "(", "container", ".", "isPolymorphObject", "(", ")", ")", "{", "// type property is recognized", "unrecognizedPropNames", ".", "delete", "(", "container", ".", "typePropertyName", ")", ";", "// match the subtype", "const", "subtype", "=", "objOld", "[", "container", ".", "typePropertyName", "]", ";", "if", "(", "objNew", "[", "container", ".", "typePropertyName", "]", "!==", "subtype", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "'Polymorphic object type does not match.'", ")", ";", "// go over the subtype properties", "const", "subtypeDesc", "=", "container", ".", "getPropertyDesc", "(", "subtype", ")", ";", "diffObjectProps", "(", "subtypeDesc", ".", "nestedProperties", ",", "`", "${", "pathPrefix", "}", "${", "subtype", "}", "`", ",", "objOld", ",", "objNew", ",", "unrecognizedPropNames", ",", "patchSpec", ")", ";", "}", "// any unrecognized properties?", "if", "(", "unrecognizedPropNames", ".", "size", ">", "0", ")", "throw", "new", "common", ".", "X2SyntaxError", "(", "`", "${", "container", ".", "recordTypeName", "}", "`", "+", "`", "${", "pathPrefix", "}", "`", "+", "Array", ".", "from", "(", "unrecognizedPropNames", ")", ".", "join", "(", "', '", ")", ")", ";", "}" ]
Recursively diff two objects and generate corresponding patch operations. @private @param {module:x2node-records~PropertiesContainer} container The container that describes the object (record or nested object property). @param {string} pathPrefix Prefix to add to contained property names to form corresponding JSON pointers. @param {Object} objOld Original object. @param {Object} objNew New object. @param {Array.<Object>} patchSpec The patch specification, to which to add generated operations.
[ "Recursively", "diff", "two", "objects", "and", "generate", "corresponding", "patch", "operations", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/differ.js#L74-L110
48,936
boylesoftware/x2node-patches
lib/differ.js
diffMaps
function diffMaps(propDesc, propPath, mapOld, mapNew, patchSpec) { const objects = (propDesc.scalarValueType === 'object'); const keysToRemove = new Set(Object.keys(mapOld)); for (let key of Object.keys(mapNew)) { const valOld = mapOld[key]; const valNew = mapNew[key]; if ((valNew === undefined) || (valNew === null)) { if ((valOld === undefined) || (valOld === null)) keysToRemove.delete(key); continue; } keysToRemove.delete(key); if ((valOld === undefined) || (valOld === null)) { patchSpec.push({ op: 'add', path: `${propPath}/${ptrSafe(key)}`, value: valNew }); } else if (objects) { diffObjects( propDesc.nestedProperties, `${propPath}/${ptrSafe(key)}/`, valOld, valNew, patchSpec); } else if (valNew !== valOld) { patchSpec.push({ op: 'replace', path: `${propPath}/${ptrSafe(key)}`, value: valNew }); } } for (let key of keysToRemove) patchSpec.push({ op: 'remove', path: `${propPath}/${ptrSafe(key)}` }); }
javascript
function diffMaps(propDesc, propPath, mapOld, mapNew, patchSpec) { const objects = (propDesc.scalarValueType === 'object'); const keysToRemove = new Set(Object.keys(mapOld)); for (let key of Object.keys(mapNew)) { const valOld = mapOld[key]; const valNew = mapNew[key]; if ((valNew === undefined) || (valNew === null)) { if ((valOld === undefined) || (valOld === null)) keysToRemove.delete(key); continue; } keysToRemove.delete(key); if ((valOld === undefined) || (valOld === null)) { patchSpec.push({ op: 'add', path: `${propPath}/${ptrSafe(key)}`, value: valNew }); } else if (objects) { diffObjects( propDesc.nestedProperties, `${propPath}/${ptrSafe(key)}/`, valOld, valNew, patchSpec); } else if (valNew !== valOld) { patchSpec.push({ op: 'replace', path: `${propPath}/${ptrSafe(key)}`, value: valNew }); } } for (let key of keysToRemove) patchSpec.push({ op: 'remove', path: `${propPath}/${ptrSafe(key)}` }); }
[ "function", "diffMaps", "(", "propDesc", ",", "propPath", ",", "mapOld", ",", "mapNew", ",", "patchSpec", ")", "{", "const", "objects", "=", "(", "propDesc", ".", "scalarValueType", "===", "'object'", ")", ";", "const", "keysToRemove", "=", "new", "Set", "(", "Object", ".", "keys", "(", "mapOld", ")", ")", ";", "for", "(", "let", "key", "of", "Object", ".", "keys", "(", "mapNew", ")", ")", "{", "const", "valOld", "=", "mapOld", "[", "key", "]", ";", "const", "valNew", "=", "mapNew", "[", "key", "]", ";", "if", "(", "(", "valNew", "===", "undefined", ")", "||", "(", "valNew", "===", "null", ")", ")", "{", "if", "(", "(", "valOld", "===", "undefined", ")", "||", "(", "valOld", "===", "null", ")", ")", "keysToRemove", ".", "delete", "(", "key", ")", ";", "continue", ";", "}", "keysToRemove", ".", "delete", "(", "key", ")", ";", "if", "(", "(", "valOld", "===", "undefined", ")", "||", "(", "valOld", "===", "null", ")", ")", "{", "patchSpec", ".", "push", "(", "{", "op", ":", "'add'", ",", "path", ":", "`", "${", "propPath", "}", "${", "ptrSafe", "(", "key", ")", "}", "`", ",", "value", ":", "valNew", "}", ")", ";", "}", "else", "if", "(", "objects", ")", "{", "diffObjects", "(", "propDesc", ".", "nestedProperties", ",", "`", "${", "propPath", "}", "${", "ptrSafe", "(", "key", ")", "}", "`", ",", "valOld", ",", "valNew", ",", "patchSpec", ")", ";", "}", "else", "if", "(", "valNew", "!==", "valOld", ")", "{", "patchSpec", ".", "push", "(", "{", "op", ":", "'replace'", ",", "path", ":", "`", "${", "propPath", "}", "${", "ptrSafe", "(", "key", ")", "}", "`", ",", "value", ":", "valNew", "}", ")", ";", "}", "}", "for", "(", "let", "key", "of", "keysToRemove", ")", "patchSpec", ".", "push", "(", "{", "op", ":", "'remove'", ",", "path", ":", "`", "${", "propPath", "}", "${", "ptrSafe", "(", "key", ")", "}", "`", "}", ")", ";", "}" ]
Recursively diff two maps and generate corresponding patch operations. @private @param {module:x2node-records~PropertyDescriptor} propDesc Descriptor of the map property. @param {string} propPath JSON pointer path of the map property. @param {Object.<string,*>} mapOld Original map. @param {Object.<string,*>} mapNew New map. @param {Array.<Object>} patchSpec The patch specification, to which to add generated operations.
[ "Recursively", "diff", "two", "maps", "and", "generate", "corresponding", "patch", "operations", "." ]
59debdb270c899bcca3f330217b68e2f746d9646
https://github.com/boylesoftware/x2node-patches/blob/59debdb270c899bcca3f330217b68e2f746d9646/lib/differ.js#L497-L540
48,937
weexteam/weex-transformer
bin/transformer.js
deserializeValue
function deserializeValue(value) { var num try { return value ? value == 'true' || value == true || (value == 'false' || value == false ? false : value == 'null' ? null : !/^0/.test(value) && !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? JSON.parse(value) : value) : value } catch (e) { return value } }
javascript
function deserializeValue(value) { var num try { return value ? value == 'true' || value == true || (value == 'false' || value == false ? false : value == 'null' ? null : !/^0/.test(value) && !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? JSON.parse(value) : value) : value } catch (e) { return value } }
[ "function", "deserializeValue", "(", "value", ")", "{", "var", "num", "try", "{", "return", "value", "?", "value", "==", "'true'", "||", "value", "==", "true", "||", "(", "value", "==", "'false'", "||", "value", "==", "false", "?", "false", ":", "value", "==", "'null'", "?", "null", ":", "!", "/", "^0", "/", ".", "test", "(", "value", ")", "&&", "!", "isNaN", "(", "num", "=", "Number", "(", "value", ")", ")", "?", "num", ":", "/", "^[\\[\\{]", "/", ".", "test", "(", "value", ")", "?", "JSON", ".", "parse", "(", "value", ")", ":", "value", ")", ":", "value", "}", "catch", "(", "e", ")", "{", "return", "value", "}", "}" ]
string to variables of proper type
[ "string", "to", "variables", "of", "proper", "type" ]
4c0dcc5450c58713647bd2665dbf937d86161ae0
https://github.com/weexteam/weex-transformer/blob/4c0dcc5450c58713647bd2665dbf937d86161ae0/bin/transformer.js#L12-L26
48,938
ftlabs/fruitmachine-fastdom
lib/helper.js
remove
function remove(item, list) { var i = list.indexOf(item); if (~i) list.splice(i, 1); }
javascript
function remove(item, list) { var i = list.indexOf(item); if (~i) list.splice(i, 1); }
[ "function", "remove", "(", "item", ",", "list", ")", "{", "var", "i", "=", "list", ".", "indexOf", "(", "item", ")", ";", "if", "(", "~", "i", ")", "list", ".", "splice", "(", "i", ",", "1", ")", ";", "}" ]
Removes an item from a list. @param {*} item @param {Array} list
[ "Removes", "an", "item", "from", "a", "list", "." ]
a90f33ea61e6196b0ff1aaf454f35fda0c063589
https://github.com/ftlabs/fruitmachine-fastdom/blob/a90f33ea61e6196b0ff1aaf454f35fda0c063589/lib/helper.js#L153-L156
48,939
wetfish/basic
src/transform.js
function(element, options) { // Make sure the transform property is an object if(typeof element.transform != "object") { element.transform = {}; } // If we have an object of options if(typeof options[0] == "object") { // Loop through object properties and save their values var keys = Object.keys(options[0]); keys.forEach(function(property) { element.transform[property] = options[0][property]; }); } // Otherwise, loop through all of the options to find values else { var property = options[0]; var args = []; for(var i = 1, l = options.length; i < l; i++) { args.push(options[i]); } element.transform[property] = args; } }
javascript
function(element, options) { // Make sure the transform property is an object if(typeof element.transform != "object") { element.transform = {}; } // If we have an object of options if(typeof options[0] == "object") { // Loop through object properties and save their values var keys = Object.keys(options[0]); keys.forEach(function(property) { element.transform[property] = options[0][property]; }); } // Otherwise, loop through all of the options to find values else { var property = options[0]; var args = []; for(var i = 1, l = options.length; i < l; i++) { args.push(options[i]); } element.transform[property] = args; } }
[ "function", "(", "element", ",", "options", ")", "{", "// Make sure the transform property is an object", "if", "(", "typeof", "element", ".", "transform", "!=", "\"object\"", ")", "{", "element", ".", "transform", "=", "{", "}", ";", "}", "// If we have an object of options", "if", "(", "typeof", "options", "[", "0", "]", "==", "\"object\"", ")", "{", "// Loop through object properties and save their values", "var", "keys", "=", "Object", ".", "keys", "(", "options", "[", "0", "]", ")", ";", "keys", ".", "forEach", "(", "function", "(", "property", ")", "{", "element", ".", "transform", "[", "property", "]", "=", "options", "[", "0", "]", "[", "property", "]", ";", "}", ")", ";", "}", "// Otherwise, loop through all of the options to find values", "else", "{", "var", "property", "=", "options", "[", "0", "]", ";", "var", "args", "=", "[", "]", ";", "for", "(", "var", "i", "=", "1", ",", "l", "=", "options", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "args", ".", "push", "(", "options", "[", "i", "]", ")", ";", "}", "element", ".", "transform", "[", "property", "]", "=", "args", ";", "}", "}" ]
Private function for saving new transform properties
[ "Private", "function", "for", "saving", "new", "transform", "properties" ]
cea1ad269ea9cd32b4cc73f6602aeab45bba9efa
https://github.com/wetfish/basic/blob/cea1ad269ea9cd32b4cc73f6602aeab45bba9efa/src/transform.js#L11-L44
48,940
wetfish/basic
src/transform.js
function(element) { // Loop through all saved transform functions to generate the style text var funcs = Object.keys(element.transform); var style = []; funcs.forEach(function(func) { var args = element.transform[func]; // If we have an array of arguments, join them with commas if(Array.isArray(args)) { args = args.join(', '); } style.push(func + "("+args+") "); }); // Update the element element.style['transform'] = style.join(" "); element.style['-webkit-transform'] = style.join(" "); }
javascript
function(element) { // Loop through all saved transform functions to generate the style text var funcs = Object.keys(element.transform); var style = []; funcs.forEach(function(func) { var args = element.transform[func]; // If we have an array of arguments, join them with commas if(Array.isArray(args)) { args = args.join(', '); } style.push(func + "("+args+") "); }); // Update the element element.style['transform'] = style.join(" "); element.style['-webkit-transform'] = style.join(" "); }
[ "function", "(", "element", ")", "{", "// Loop through all saved transform functions to generate the style text", "var", "funcs", "=", "Object", ".", "keys", "(", "element", ".", "transform", ")", ";", "var", "style", "=", "[", "]", ";", "funcs", ".", "forEach", "(", "function", "(", "func", ")", "{", "var", "args", "=", "element", ".", "transform", "[", "func", "]", ";", "// If we have an array of arguments, join them with commas", "if", "(", "Array", ".", "isArray", "(", "args", ")", ")", "{", "args", "=", "args", ".", "join", "(", "', '", ")", ";", "}", "style", ".", "push", "(", "func", "+", "\"(\"", "+", "args", "+", "\") \"", ")", ";", "}", ")", ";", "// Update the element", "element", ".", "style", "[", "'transform'", "]", "=", "style", ".", "join", "(", "\" \"", ")", ";", "element", ".", "style", "[", "'-webkit-transform'", "]", "=", "style", ".", "join", "(", "\" \"", ")", ";", "}" ]
Private function for updating an element on the page
[ "Private", "function", "for", "updating", "an", "element", "on", "the", "page" ]
cea1ad269ea9cd32b4cc73f6602aeab45bba9efa
https://github.com/wetfish/basic/blob/cea1ad269ea9cd32b4cc73f6602aeab45bba9efa/src/transform.js#L47-L69
48,941
QuietWind/find-imports
lib/file.js
findModulePath
function findModulePath(filename_rootfile, filename, options = DEFAULT_OPTIONS) { /** * . 相对路径 * . 绝对路径 */ const ext = path.extname(filename); if (ext && exports.extensions.indexOf(ext) === -1) { return null; } if (path.dirname(filename_rootfile) !== filename_rootfile) { filename_rootfile = path.dirname(filename_rootfile); } const storeKey = storePathKey(filename_rootfile, filename); const storeKeyVal = store.get(storeKey); const { baseUrl = DEFAULT_OPTIONS.baseUrl } = options; if (storeKeyVal) { return storeKeyVal === "null" ? null : storeKeyVal; } // save result path and return pathname const storeAndReturn = (rpath) => { store.set(storeKey, String(rpath)); return rpath; }; const roots = baseUrl.concat(filename_rootfile); let r = null; roots.some(baseRoot => { if (ext) { const namepath = genPath(baseRoot, filename); r = namepath; return !!namepath; } let namepath2 = null; exports.extensions.some(extname => { namepath2 = genPath(baseRoot, `${filename}${extname}`); if (!namepath2) { namepath2 = genPath(baseRoot, `${filename}/index${extname}`); } return !!namepath2; }); if (namepath2) { r = namepath2; return true; } return false; }); return storeAndReturn(r); }
javascript
function findModulePath(filename_rootfile, filename, options = DEFAULT_OPTIONS) { /** * . 相对路径 * . 绝对路径 */ const ext = path.extname(filename); if (ext && exports.extensions.indexOf(ext) === -1) { return null; } if (path.dirname(filename_rootfile) !== filename_rootfile) { filename_rootfile = path.dirname(filename_rootfile); } const storeKey = storePathKey(filename_rootfile, filename); const storeKeyVal = store.get(storeKey); const { baseUrl = DEFAULT_OPTIONS.baseUrl } = options; if (storeKeyVal) { return storeKeyVal === "null" ? null : storeKeyVal; } // save result path and return pathname const storeAndReturn = (rpath) => { store.set(storeKey, String(rpath)); return rpath; }; const roots = baseUrl.concat(filename_rootfile); let r = null; roots.some(baseRoot => { if (ext) { const namepath = genPath(baseRoot, filename); r = namepath; return !!namepath; } let namepath2 = null; exports.extensions.some(extname => { namepath2 = genPath(baseRoot, `${filename}${extname}`); if (!namepath2) { namepath2 = genPath(baseRoot, `${filename}/index${extname}`); } return !!namepath2; }); if (namepath2) { r = namepath2; return true; } return false; }); return storeAndReturn(r); }
[ "function", "findModulePath", "(", "filename_rootfile", ",", "filename", ",", "options", "=", "DEFAULT_OPTIONS", ")", "{", "/**\n * . 相对路径\n * . 绝对路径\n */", "const", "ext", "=", "path", ".", "extname", "(", "filename", ")", ";", "if", "(", "ext", "&&", "exports", ".", "extensions", ".", "indexOf", "(", "ext", ")", "===", "-", "1", ")", "{", "return", "null", ";", "}", "if", "(", "path", ".", "dirname", "(", "filename_rootfile", ")", "!==", "filename_rootfile", ")", "{", "filename_rootfile", "=", "path", ".", "dirname", "(", "filename_rootfile", ")", ";", "}", "const", "storeKey", "=", "storePathKey", "(", "filename_rootfile", ",", "filename", ")", ";", "const", "storeKeyVal", "=", "store", ".", "get", "(", "storeKey", ")", ";", "const", "{", "baseUrl", "=", "DEFAULT_OPTIONS", ".", "baseUrl", "}", "=", "options", ";", "if", "(", "storeKeyVal", ")", "{", "return", "storeKeyVal", "===", "\"null\"", "?", "null", ":", "storeKeyVal", ";", "}", "// save result path and return pathname", "const", "storeAndReturn", "=", "(", "rpath", ")", "=>", "{", "store", ".", "set", "(", "storeKey", ",", "String", "(", "rpath", ")", ")", ";", "return", "rpath", ";", "}", ";", "const", "roots", "=", "baseUrl", ".", "concat", "(", "filename_rootfile", ")", ";", "let", "r", "=", "null", ";", "roots", ".", "some", "(", "baseRoot", "=>", "{", "if", "(", "ext", ")", "{", "const", "namepath", "=", "genPath", "(", "baseRoot", ",", "filename", ")", ";", "r", "=", "namepath", ";", "return", "!", "!", "namepath", ";", "}", "let", "namepath2", "=", "null", ";", "exports", ".", "extensions", ".", "some", "(", "extname", "=>", "{", "namepath2", "=", "genPath", "(", "baseRoot", ",", "`", "${", "filename", "}", "${", "extname", "}", "`", ")", ";", "if", "(", "!", "namepath2", ")", "{", "namepath2", "=", "genPath", "(", "baseRoot", ",", "`", "${", "filename", "}", "${", "extname", "}", "`", ")", ";", "}", "return", "!", "!", "namepath2", ";", "}", ")", ";", "if", "(", "namepath2", ")", "{", "r", "=", "namepath2", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "return", "storeAndReturn", "(", "r", ")", ";", "}" ]
node_modules do not thinks @param filename_rootfile @param filename @param options
[ "node_modules", "do", "not", "thinks" ]
f0ecef2ff8025abfe59fcb19539965717ecd08ab
https://github.com/QuietWind/find-imports/blob/f0ecef2ff8025abfe59fcb19539965717ecd08ab/lib/file.js#L38-L84
48,942
meetings/gearsloth
lib/gearman/multiserver-client.js
MultiserverClient
function MultiserverClient(servers, options) { options = options || {}; Multiserver.call(this, servers, function(server) { return new gearman.Client({ host: server.host, port: server.port, debug: options.debug || false }); }, Multiserver.component_prefix(options.component_name) + 'client'); this._rr_index = -1; // round robin index }
javascript
function MultiserverClient(servers, options) { options = options || {}; Multiserver.call(this, servers, function(server) { return new gearman.Client({ host: server.host, port: server.port, debug: options.debug || false }); }, Multiserver.component_prefix(options.component_name) + 'client'); this._rr_index = -1; // round robin index }
[ "function", "MultiserverClient", "(", "servers", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "Multiserver", ".", "call", "(", "this", ",", "servers", ",", "function", "(", "server", ")", "{", "return", "new", "gearman", ".", "Client", "(", "{", "host", ":", "server", ".", "host", ",", "port", ":", "server", ".", "port", ",", "debug", ":", "options", ".", "debug", "||", "false", "}", ")", ";", "}", ",", "Multiserver", ".", "component_prefix", "(", "options", ".", "component_name", ")", "+", "'client'", ")", ";", "this", ".", "_rr_index", "=", "-", "1", ";", "// round robin index", "}" ]
A gearman client that supports multiple servers. Contains multiple gearman-coffee clients that are each connected to a different server. The client which submits a job is selected with round robin. Servers are provided in an array of json-objects, possible fields are: `.host`: a string that identifies a gearman job server host `.port`: an integer that identifies a geaerman job server port `._debug`: a boolean that tells whether debug mode should be used @param {[Object]} servers @param {Object} options @return {Object}
[ "A", "gearman", "client", "that", "supports", "multiple", "servers", ".", "Contains", "multiple", "gearman", "-", "coffee", "clients", "that", "are", "each", "connected", "to", "a", "different", "server", ".", "The", "client", "which", "submits", "a", "job", "is", "selected", "with", "round", "robin", "." ]
21d07729d6197bdbea515f32922896e3ae485d46
https://github.com/meetings/gearsloth/blob/21d07729d6197bdbea515f32922896e3ae485d46/lib/gearman/multiserver-client.js#L23-L33
48,943
kuzzleio/dumpme
index.js
dump
function dump(gcore, coredump) { gcore = gcore || 'gcore'; coredump = coredump || `${process.cwd()}/core.${process.pid}`; return DumpProcess.dumpProcess(gcore, coredump); }
javascript
function dump(gcore, coredump) { gcore = gcore || 'gcore'; coredump = coredump || `${process.cwd()}/core.${process.pid}`; return DumpProcess.dumpProcess(gcore, coredump); }
[ "function", "dump", "(", "gcore", ",", "coredump", ")", "{", "gcore", "=", "gcore", "||", "'gcore'", ";", "coredump", "=", "coredump", "||", "`", "${", "process", ".", "cwd", "(", ")", "}", "${", "process", ".", "pid", "}", "`", ";", "return", "DumpProcess", ".", "dumpProcess", "(", "gcore", ",", "coredump", ")", ";", "}" ]
Dumps the current process @param {string} [gcore] - path and filename of the gcore binary @param {string} [coredump] - path and filename of the target coredump file @return {Boolean}
[ "Dumps", "the", "current", "process" ]
1b70a9f91e82345bf50d0b36c85dffd61ca857bf
https://github.com/kuzzleio/dumpme/blob/1b70a9f91e82345bf50d0b36c85dffd61ca857bf/index.js#L12-L17
48,944
Flaque/react-mutate
packages/mutate-loader/src/index.js
installMutations
function installMutations(modules, enclosingFolder) { makeFolderLibraryIfNotExist(enclosingFolder); if (modules.length === 0) { return new Promise(resolve => resolve({})); } return npm.install(modules, { cwd: pathToMutations(enclosingFolder), save: true }); }
javascript
function installMutations(modules, enclosingFolder) { makeFolderLibraryIfNotExist(enclosingFolder); if (modules.length === 0) { return new Promise(resolve => resolve({})); } return npm.install(modules, { cwd: pathToMutations(enclosingFolder), save: true }); }
[ "function", "installMutations", "(", "modules", ",", "enclosingFolder", ")", "{", "makeFolderLibraryIfNotExist", "(", "enclosingFolder", ")", ";", "if", "(", "modules", ".", "length", "===", "0", ")", "{", "return", "new", "Promise", "(", "resolve", "=>", "resolve", "(", "{", "}", ")", ")", ";", "}", "return", "npm", ".", "install", "(", "modules", ",", "{", "cwd", ":", "pathToMutations", "(", "enclosingFolder", ")", ",", "save", ":", "true", "}", ")", ";", "}" ]
Installs a list of npm modules as "mutations" in a folder called "mutations" using `npm`. @param {Array} modules @param {String} enclosingFolder @return {Promise}
[ "Installs", "a", "list", "of", "npm", "modules", "as", "mutations", "in", "a", "folder", "called", "mutations", "using", "npm", "." ]
c2a1f6f9bf8af72f812000dc96f80b55d6ceaaa3
https://github.com/Flaque/react-mutate/blob/c2a1f6f9bf8af72f812000dc96f80b55d6ceaaa3/packages/mutate-loader/src/index.js#L25-L35
48,945
Flaque/react-mutate
packages/mutate-loader/src/index.js
loadMutations
function loadMutations(enclosingFolder) { const here = jetpack.cwd(pathToMutations(enclosingFolder)); const pkg = here.read(PACKAGE_JSON, "json"); errorIf( !pkg, `There doesn't seem to be a package.json file. Did you create one at the enclosing folder? FYI: installMutations creates one for you if you don't have one. ` ); const node_modules_path = here.dir(NODE_MODULES).cwd(); return new Promise((resolve, reject) => { // Load in mutations from dependencies const mutations = loadMutationsFromDependencies( pkg.dependencies, node_modules_path ); resolve(mutations); }); }
javascript
function loadMutations(enclosingFolder) { const here = jetpack.cwd(pathToMutations(enclosingFolder)); const pkg = here.read(PACKAGE_JSON, "json"); errorIf( !pkg, `There doesn't seem to be a package.json file. Did you create one at the enclosing folder? FYI: installMutations creates one for you if you don't have one. ` ); const node_modules_path = here.dir(NODE_MODULES).cwd(); return new Promise((resolve, reject) => { // Load in mutations from dependencies const mutations = loadMutationsFromDependencies( pkg.dependencies, node_modules_path ); resolve(mutations); }); }
[ "function", "loadMutations", "(", "enclosingFolder", ")", "{", "const", "here", "=", "jetpack", ".", "cwd", "(", "pathToMutations", "(", "enclosingFolder", ")", ")", ";", "const", "pkg", "=", "here", ".", "read", "(", "PACKAGE_JSON", ",", "\"json\"", ")", ";", "errorIf", "(", "!", "pkg", ",", "`", "`", ")", ";", "const", "node_modules_path", "=", "here", ".", "dir", "(", "NODE_MODULES", ")", ".", "cwd", "(", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "// Load in mutations from dependencies", "const", "mutations", "=", "loadMutationsFromDependencies", "(", "pkg", ".", "dependencies", ",", "node_modules_path", ")", ";", "resolve", "(", "mutations", ")", ";", "}", ")", ";", "}" ]
Loads mutations from a folder inside the `enclosingFolder` called "mutations". @param {String} enclosingFolder @return {JSON} a map of the mutation name to the mutation's export.
[ "Loads", "mutations", "from", "a", "folder", "inside", "the", "enclosingFolder", "called", "mutations", "." ]
c2a1f6f9bf8af72f812000dc96f80b55d6ceaaa3
https://github.com/Flaque/react-mutate/blob/c2a1f6f9bf8af72f812000dc96f80b55d6ceaaa3/packages/mutate-loader/src/index.js#L42-L63
48,946
mrdaniellewis/node-promise-utilities
lib/promise-queue.js
next
function next() { var fns = activeQueue.shift(); if ( !fns ) { return; } ret = ret.then( typeof fns[0] === 'function' ? fns[0].bind(self) : fns[0], typeof fns[1] === 'function' ? fns[1].bind(self) : fns[1] ); next(); }
javascript
function next() { var fns = activeQueue.shift(); if ( !fns ) { return; } ret = ret.then( typeof fns[0] === 'function' ? fns[0].bind(self) : fns[0], typeof fns[1] === 'function' ? fns[1].bind(self) : fns[1] ); next(); }
[ "function", "next", "(", ")", "{", "var", "fns", "=", "activeQueue", ".", "shift", "(", ")", ";", "if", "(", "!", "fns", ")", "{", "return", ";", "}", "ret", "=", "ret", ".", "then", "(", "typeof", "fns", "[", "0", "]", "===", "'function'", "?", "fns", "[", "0", "]", ".", "bind", "(", "self", ")", ":", "fns", "[", "0", "]", ",", "typeof", "fns", "[", "1", "]", "===", "'function'", "?", "fns", "[", "1", "]", ".", "bind", "(", "self", ")", ":", "fns", "[", "1", "]", ")", ";", "next", "(", ")", ";", "}" ]
Recursive function adds promise actions
[ "Recursive", "function", "adds", "promise", "actions" ]
53188b6b52e8807cfd8f446ae034626f9a2aecf4
https://github.com/mrdaniellewis/node-promise-utilities/blob/53188b6b52e8807cfd8f446ae034626f9a2aecf4/lib/promise-queue.js#L53-L67
48,947
sudo-suhas/eslint-config-chatur
lib/util.js
isInstalled
function isInstalled(dep) { if (_.has(exceptions, dep)) return exceptions[dep]; return installedDeps.has(dep); }
javascript
function isInstalled(dep) { if (_.has(exceptions, dep)) return exceptions[dep]; return installedDeps.has(dep); }
[ "function", "isInstalled", "(", "dep", ")", "{", "if", "(", "_", ".", "has", "(", "exceptions", ",", "dep", ")", ")", "return", "exceptions", "[", "dep", "]", ";", "return", "installedDeps", ".", "has", "(", "dep", ")", ";", "}" ]
Check if the given dependency is installed. Checks against `dependencies`, `devDependencies` in project `package.json`. @param {string} dep Name of the dependency @returns {boolean} `true` if installed, `false` if not
[ "Check", "if", "the", "given", "dependency", "is", "installed", ".", "Checks", "against", "dependencies", "devDependencies", "in", "project", "package", ".", "json", "." ]
fc3d6ece77512d9651da4e9ec29d641a9279519b
https://github.com/sudo-suhas/eslint-config-chatur/blob/fc3d6ece77512d9651da4e9ec29d641a9279519b/lib/util.js#L36-L39
48,948
sudo-suhas/eslint-config-chatur
lib/util.js
resolveDependencyPlugins
function resolveDependencyPlugins(deps) { return deps .filter(dep => isInstalled(dep) && isInstalled(`eslint-plugin-${dep}`)) .map(dep => `./lib/plugin-conf/${dep}.js`); }
javascript
function resolveDependencyPlugins(deps) { return deps .filter(dep => isInstalled(dep) && isInstalled(`eslint-plugin-${dep}`)) .map(dep => `./lib/plugin-conf/${dep}.js`); }
[ "function", "resolveDependencyPlugins", "(", "deps", ")", "{", "return", "deps", ".", "filter", "(", "dep", "=>", "isInstalled", "(", "dep", ")", "&&", "isInstalled", "(", "`", "${", "dep", "}", "`", ")", ")", ".", "map", "(", "dep", "=>", "`", "${", "dep", "}", "`", ")", ";", "}" ]
Resolve installed dependencies and return the eslint config paths which can be used for extending an eslint config. @param {Array<string>} deps Dependencies list @returns {Array<string>} Array of eslint config file paths for plugins
[ "Resolve", "installed", "dependencies", "and", "return", "the", "eslint", "config", "paths", "which", "can", "be", "used", "for", "extending", "an", "eslint", "config", "." ]
fc3d6ece77512d9651da4e9ec29d641a9279519b
https://github.com/sudo-suhas/eslint-config-chatur/blob/fc3d6ece77512d9651da4e9ec29d641a9279519b/lib/util.js#L59-L63
48,949
Flaque/react-mutate
packages/mutate-core/src/mutate.js
mutate
function mutate(Component, title, api = {}) { class Mutated extends React.Component { constructor(props, context) { super(props); this.ToRender = Component; const mutations = context.mutations; if (!mutations || !mutations[title]) { return; } // Convert old style mutations to new style mutations if (!Array.isArray(mutations[title])) { mutations[title] = [mutations[title]]; } // Apply all mutations to the component for (let mut of mutations[title]) { this.ToRender = mut(this.ToRender, api); } } render() { const ToRender = this.ToRender; return <ToRender {...this.props} />; } } Mutated.contextTypes = { mutations: PropTypes.object }; return Mutated; }
javascript
function mutate(Component, title, api = {}) { class Mutated extends React.Component { constructor(props, context) { super(props); this.ToRender = Component; const mutations = context.mutations; if (!mutations || !mutations[title]) { return; } // Convert old style mutations to new style mutations if (!Array.isArray(mutations[title])) { mutations[title] = [mutations[title]]; } // Apply all mutations to the component for (let mut of mutations[title]) { this.ToRender = mut(this.ToRender, api); } } render() { const ToRender = this.ToRender; return <ToRender {...this.props} />; } } Mutated.contextTypes = { mutations: PropTypes.object }; return Mutated; }
[ "function", "mutate", "(", "Component", ",", "title", ",", "api", "=", "{", "}", ")", "{", "class", "Mutated", "extends", "React", ".", "Component", "{", "constructor", "(", "props", ",", "context", ")", "{", "super", "(", "props", ")", ";", "this", ".", "ToRender", "=", "Component", ";", "const", "mutations", "=", "context", ".", "mutations", ";", "if", "(", "!", "mutations", "||", "!", "mutations", "[", "title", "]", ")", "{", "return", ";", "}", "// Convert old style mutations to new style mutations", "if", "(", "!", "Array", ".", "isArray", "(", "mutations", "[", "title", "]", ")", ")", "{", "mutations", "[", "title", "]", "=", "[", "mutations", "[", "title", "]", "]", ";", "}", "// Apply all mutations to the component", "for", "(", "let", "mut", "of", "mutations", "[", "title", "]", ")", "{", "this", ".", "ToRender", "=", "mut", "(", "this", ".", "ToRender", ",", "api", ")", ";", "}", "}", "render", "(", ")", "{", "const", "ToRender", "=", "this", ".", "ToRender", ";", "return", "<", "ToRender", "{", "...", "this", ".", "props", "}", "/", ">", ";", "}", "}", "Mutated", ".", "contextTypes", "=", "{", "mutations", ":", "PropTypes", ".", "object", "}", ";", "return", "Mutated", ";", "}" ]
A React HOC that returns a component that the user can mutate. @param {React} Component is the component we will mutate @param {String} title is the name you want to associate with the mutation
[ "A", "React", "HOC", "that", "returns", "a", "component", "that", "the", "user", "can", "mutate", "." ]
c2a1f6f9bf8af72f812000dc96f80b55d6ceaaa3
https://github.com/Flaque/react-mutate/blob/c2a1f6f9bf8af72f812000dc96f80b55d6ceaaa3/packages/mutate-core/src/mutate.js#L11-L45
48,950
alexindigo/executioner
lib/run.js
run
function run(collector, commands, keys, params, options, callback) { // either keys is array or commands var prefix, key, cmd = (keys || commands).shift(); // done here if (!cmd) { return callback(null, collector); } // transform object into a command if (keys) { key = cmd; cmd = commands[key]; } // update placeholders cmd = parse(cmd, params); // if loop over parameters terminated early // do not proceed further if (!cmd) { callback(new Error('Parameters should be a primitive value.')); return; } // populate command prefix prefix = parse(options.cmdPrefix || '', params); if (prefix) { cmd = prefix + ' ' + cmd; } execute(collector, cmd, options, function(error, output) { // store the output, if present if (output) { collector.push((key ? key + ': ' : '') + output); } // do not proceed further if error if (error) { // do not pass collector back if it a regular error callback(error, error.terminated ? collector : undefined); return; } // rinse, repeat run(collector, commands, keys, params, options, callback); }); }
javascript
function run(collector, commands, keys, params, options, callback) { // either keys is array or commands var prefix, key, cmd = (keys || commands).shift(); // done here if (!cmd) { return callback(null, collector); } // transform object into a command if (keys) { key = cmd; cmd = commands[key]; } // update placeholders cmd = parse(cmd, params); // if loop over parameters terminated early // do not proceed further if (!cmd) { callback(new Error('Parameters should be a primitive value.')); return; } // populate command prefix prefix = parse(options.cmdPrefix || '', params); if (prefix) { cmd = prefix + ' ' + cmd; } execute(collector, cmd, options, function(error, output) { // store the output, if present if (output) { collector.push((key ? key + ': ' : '') + output); } // do not proceed further if error if (error) { // do not pass collector back if it a regular error callback(error, error.terminated ? collector : undefined); return; } // rinse, repeat run(collector, commands, keys, params, options, callback); }); }
[ "function", "run", "(", "collector", ",", "commands", ",", "keys", ",", "params", ",", "options", ",", "callback", ")", "{", "// either keys is array or commands", "var", "prefix", ",", "key", ",", "cmd", "=", "(", "keys", "||", "commands", ")", ".", "shift", "(", ")", ";", "// done here", "if", "(", "!", "cmd", ")", "{", "return", "callback", "(", "null", ",", "collector", ")", ";", "}", "// transform object into a command", "if", "(", "keys", ")", "{", "key", "=", "cmd", ";", "cmd", "=", "commands", "[", "key", "]", ";", "}", "// update placeholders", "cmd", "=", "parse", "(", "cmd", ",", "params", ")", ";", "// if loop over parameters terminated early", "// do not proceed further", "if", "(", "!", "cmd", ")", "{", "callback", "(", "new", "Error", "(", "'Parameters should be a primitive value.'", ")", ")", ";", "return", ";", "}", "// populate command prefix", "prefix", "=", "parse", "(", "options", ".", "cmdPrefix", "||", "''", ",", "params", ")", ";", "if", "(", "prefix", ")", "{", "cmd", "=", "prefix", "+", "' '", "+", "cmd", ";", "}", "execute", "(", "collector", ",", "cmd", ",", "options", ",", "function", "(", "error", ",", "output", ")", "{", "// store the output, if present", "if", "(", "output", ")", "{", "collector", ".", "push", "(", "(", "key", "?", "key", "+", "': '", ":", "''", ")", "+", "output", ")", ";", "}", "// do not proceed further if error", "if", "(", "error", ")", "{", "// do not pass collector back if it a regular error", "callback", "(", "error", ",", "error", ".", "terminated", "?", "collector", ":", "undefined", ")", ";", "return", ";", "}", "// rinse, repeat", "run", "(", "collector", ",", "commands", ",", "keys", ",", "params", ",", "options", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Runs specified command, replaces parameter placeholders. @param {array} collector - job control object, contains list of results @param {object|array} commands - list of commands to execute @param {array} keys - list of commands keys @param {object} params - parameters for each command @param {object} options - options for child_process.exec @param {function} callback - invoked when all commands have been processed @returns {void}
[ "Runs", "specified", "command", "replaces", "parameter", "placeholders", "." ]
582f92897f47c13f4531e0b692aebb4a9f134eec
https://github.com/alexindigo/executioner/blob/582f92897f47c13f4531e0b692aebb4a9f134eec/lib/run.js#L19-L75
48,951
observing/fossa
lib/model.js
constructor
function constructor(attributes, options) { var hooks = [] , local = {}; options = options || {}; // // Set the database name and/or urlRoot if provided in the options. // if (options.database) this.database = options.database; if (options.urlRoot) this.urlRoot = options.urlRoot; // // Copy attributes to a new object and provide a MongoDB OfbjectID. // attributes = attributes || {}; for (var key in attributes) local[key] = attributes[key]; // // If the provided `_id` is an ObjectID assume the model is stored. // If it is not an ObjectID, remove it from the provided data. // MongoDB will provide an ObjectID by default. // if ('_id' in local) try { local._id = new ObjectID(local._id); } catch (error) { delete local._id; } // // Define restricted non-enumerated properties. // predefine(this, fossa); // // Check for presence of before/after hooks and setup. // if (this.before) hooks.push('before'); if (this.after) hooks.push('after'); this.setup(hooks); // // Call original Backbone Model constructor. // backbone.Model.call(this, local, options); }
javascript
function constructor(attributes, options) { var hooks = [] , local = {}; options = options || {}; // // Set the database name and/or urlRoot if provided in the options. // if (options.database) this.database = options.database; if (options.urlRoot) this.urlRoot = options.urlRoot; // // Copy attributes to a new object and provide a MongoDB OfbjectID. // attributes = attributes || {}; for (var key in attributes) local[key] = attributes[key]; // // If the provided `_id` is an ObjectID assume the model is stored. // If it is not an ObjectID, remove it from the provided data. // MongoDB will provide an ObjectID by default. // if ('_id' in local) try { local._id = new ObjectID(local._id); } catch (error) { delete local._id; } // // Define restricted non-enumerated properties. // predefine(this, fossa); // // Check for presence of before/after hooks and setup. // if (this.before) hooks.push('before'); if (this.after) hooks.push('after'); this.setup(hooks); // // Call original Backbone Model constructor. // backbone.Model.call(this, local, options); }
[ "function", "constructor", "(", "attributes", ",", "options", ")", "{", "var", "hooks", "=", "[", "]", ",", "local", "=", "{", "}", ";", "options", "=", "options", "||", "{", "}", ";", "//", "// Set the database name and/or urlRoot if provided in the options.", "//", "if", "(", "options", ".", "database", ")", "this", ".", "database", "=", "options", ".", "database", ";", "if", "(", "options", ".", "urlRoot", ")", "this", ".", "urlRoot", "=", "options", ".", "urlRoot", ";", "//", "// Copy attributes to a new object and provide a MongoDB OfbjectID.", "//", "attributes", "=", "attributes", "||", "{", "}", ";", "for", "(", "var", "key", "in", "attributes", ")", "local", "[", "key", "]", "=", "attributes", "[", "key", "]", ";", "//", "// If the provided `_id` is an ObjectID assume the model is stored.", "// If it is not an ObjectID, remove it from the provided data.", "// MongoDB will provide an ObjectID by default.", "//", "if", "(", "'_id'", "in", "local", ")", "try", "{", "local", ".", "_id", "=", "new", "ObjectID", "(", "local", ".", "_id", ")", ";", "}", "catch", "(", "error", ")", "{", "delete", "local", ".", "_id", ";", "}", "//", "// Define restricted non-enumerated properties.", "//", "predefine", "(", "this", ",", "fossa", ")", ";", "//", "// Check for presence of before/after hooks and setup.", "//", "if", "(", "this", ".", "before", ")", "hooks", ".", "push", "(", "'before'", ")", ";", "if", "(", "this", ".", "after", ")", "hooks", ".", "push", "(", "'after'", ")", ";", "this", ".", "setup", "(", "hooks", ")", ";", "//", "// Call original Backbone Model constructor.", "//", "backbone", ".", "Model", ".", "call", "(", "this", ",", "local", ",", "options", ")", ";", "}" ]
Override default Model Constructor. @Constructor @param {Object} attributes @param {Object} options @api public
[ "Override", "default", "Model", "Constructor", "." ]
29b3717ee10a13fb607f5bbddcb8b003faf008c6
https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/lib/model.js#L33-L76
48,952
observing/fossa
lib/model.js
save
function save() { var defer = new Defer , xhr = backbone.Model.prototype.save.apply(this, arguments); if (xhr) return xhr; defer.next(new Error('Could not validate model')); return defer; }
javascript
function save() { var defer = new Defer , xhr = backbone.Model.prototype.save.apply(this, arguments); if (xhr) return xhr; defer.next(new Error('Could not validate model')); return defer; }
[ "function", "save", "(", ")", "{", "var", "defer", "=", "new", "Defer", ",", "xhr", "=", "backbone", ".", "Model", ".", "prototype", ".", "save", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "xhr", ")", "return", "xhr", ";", "defer", ".", "next", "(", "new", "Error", "(", "'Could not validate model'", ")", ")", ";", "return", "defer", ";", "}" ]
Overrule the default save. Normally `save` returns `false` when validation fails. However this does not match the Node.JS callback pattern. @return {Defer} Promise XHR object @api public
[ "Overrule", "the", "default", "save", ".", "Normally", "save", "returns", "false", "when", "validation", "fails", ".", "However", "this", "does", "not", "match", "the", "Node", ".", "JS", "callback", "pattern", "." ]
29b3717ee10a13fb607f5bbddcb8b003faf008c6
https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/lib/model.js#L153-L161
48,953
PixieEngine/Cornerstone
game.js
function(namespacedEvent, callback) { var event, namespace, _ref; _ref = namespacedEvent.split("."), event = _ref[0], namespace = _ref[1]; if (namespace) { callback.__PIXIE || (callback.__PIXIE = {}); callback.__PIXIE[namespace] = true; } eventCallbacks[event] || (eventCallbacks[event] = []); eventCallbacks[event].push(callback); return this; }
javascript
function(namespacedEvent, callback) { var event, namespace, _ref; _ref = namespacedEvent.split("."), event = _ref[0], namespace = _ref[1]; if (namespace) { callback.__PIXIE || (callback.__PIXIE = {}); callback.__PIXIE[namespace] = true; } eventCallbacks[event] || (eventCallbacks[event] = []); eventCallbacks[event].push(callback); return this; }
[ "function", "(", "namespacedEvent", ",", "callback", ")", "{", "var", "event", ",", "namespace", ",", "_ref", ";", "_ref", "=", "namespacedEvent", ".", "split", "(", "\".\"", ")", ",", "event", "=", "_ref", "[", "0", "]", ",", "namespace", "=", "_ref", "[", "1", "]", ";", "if", "(", "namespace", ")", "{", "callback", ".", "__PIXIE", "||", "(", "callback", ".", "__PIXIE", "=", "{", "}", ")", ";", "callback", ".", "__PIXIE", "[", "namespace", "]", "=", "true", ";", "}", "eventCallbacks", "[", "event", "]", "||", "(", "eventCallbacks", "[", "event", "]", "=", "[", "]", ")", ";", "eventCallbacks", "[", "event", "]", ".", "push", "(", "callback", ")", ";", "return", "this", ";", "}" ]
Adds a function as an event listener. # this will call coolEventHandler after # yourObject.trigger "someCustomEvent" is called. yourObject.on "someCustomEvent", coolEventHandler #or yourObject.on "anotherCustomEvent", -> doSomething() @name on @methodOf Bindable# @param {String} event The event to listen to. @param {Function} callback The function to be called when the specified event is triggered.
[ "Adds", "a", "function", "as", "an", "event", "listener", "." ]
4fd1e28e71db89385876efe46ca634a90d51672e
https://github.com/PixieEngine/Cornerstone/blob/4fd1e28e71db89385876efe46ca634a90d51672e/game.js#L877-L887
48,954
PixieEngine/Cornerstone
game.js
function(namespacedEvent, callback) { var callbacks, event, key, namespace, _ref; _ref = namespacedEvent.split("."), event = _ref[0], namespace = _ref[1]; if (event) { eventCallbacks[event] || (eventCallbacks[event] = []); if (namespace) { eventCallbacks[event] = eventCallbacks.select(function(callback) { var _ref2; return !(((_ref2 = callback.__PIXIE) != null ? _ref2[namespace] : void 0) != null); }); } else { if (callback) { eventCallbacks[event].remove(callback); } else { eventCallbacks[event] = []; } } } else if (namespace) { for (key in eventCallbacks) { callbacks = eventCallbacks[key]; eventCallbacks[key] = callbacks.select(function(callback) { var _ref2; return !(((_ref2 = callback.__PIXIE) != null ? _ref2[namespace] : void 0) != null); }); } } return this; }
javascript
function(namespacedEvent, callback) { var callbacks, event, key, namespace, _ref; _ref = namespacedEvent.split("."), event = _ref[0], namespace = _ref[1]; if (event) { eventCallbacks[event] || (eventCallbacks[event] = []); if (namespace) { eventCallbacks[event] = eventCallbacks.select(function(callback) { var _ref2; return !(((_ref2 = callback.__PIXIE) != null ? _ref2[namespace] : void 0) != null); }); } else { if (callback) { eventCallbacks[event].remove(callback); } else { eventCallbacks[event] = []; } } } else if (namespace) { for (key in eventCallbacks) { callbacks = eventCallbacks[key]; eventCallbacks[key] = callbacks.select(function(callback) { var _ref2; return !(((_ref2 = callback.__PIXIE) != null ? _ref2[namespace] : void 0) != null); }); } } return this; }
[ "function", "(", "namespacedEvent", ",", "callback", ")", "{", "var", "callbacks", ",", "event", ",", "key", ",", "namespace", ",", "_ref", ";", "_ref", "=", "namespacedEvent", ".", "split", "(", "\".\"", ")", ",", "event", "=", "_ref", "[", "0", "]", ",", "namespace", "=", "_ref", "[", "1", "]", ";", "if", "(", "event", ")", "{", "eventCallbacks", "[", "event", "]", "||", "(", "eventCallbacks", "[", "event", "]", "=", "[", "]", ")", ";", "if", "(", "namespace", ")", "{", "eventCallbacks", "[", "event", "]", "=", "eventCallbacks", ".", "select", "(", "function", "(", "callback", ")", "{", "var", "_ref2", ";", "return", "!", "(", "(", "(", "_ref2", "=", "callback", ".", "__PIXIE", ")", "!=", "null", "?", "_ref2", "[", "namespace", "]", ":", "void", "0", ")", "!=", "null", ")", ";", "}", ")", ";", "}", "else", "{", "if", "(", "callback", ")", "{", "eventCallbacks", "[", "event", "]", ".", "remove", "(", "callback", ")", ";", "}", "else", "{", "eventCallbacks", "[", "event", "]", "=", "[", "]", ";", "}", "}", "}", "else", "if", "(", "namespace", ")", "{", "for", "(", "key", "in", "eventCallbacks", ")", "{", "callbacks", "=", "eventCallbacks", "[", "key", "]", ";", "eventCallbacks", "[", "key", "]", "=", "callbacks", ".", "select", "(", "function", "(", "callback", ")", "{", "var", "_ref2", ";", "return", "!", "(", "(", "(", "_ref2", "=", "callback", ".", "__PIXIE", ")", "!=", "null", "?", "_ref2", "[", "namespace", "]", ":", "void", "0", ")", "!=", "null", ")", ";", "}", ")", ";", "}", "}", "return", "this", ";", "}" ]
Removes a specific event listener, or all event listeners if no specific listener is given. # removes the handler coolEventHandler from the event # "someCustomEvent" while leaving the other events intact. yourObject.off "someCustomEvent", coolEventHandler # removes all handlers attached to "anotherCustomEvent" yourObject.off "anotherCustomEvent" @name off @methodOf Bindable# @param {String} event The event to remove the listener from. @param {Function} [callback] The listener to remove.
[ "Removes", "a", "specific", "event", "listener", "or", "all", "event", "listeners", "if", "no", "specific", "listener", "is", "given", "." ]
4fd1e28e71db89385876efe46ca634a90d51672e
https://github.com/PixieEngine/Cornerstone/blob/4fd1e28e71db89385876efe46ca634a90d51672e/game.js#L904-L931
48,955
PixieEngine/Cornerstone
game.js
function() { var callbacks, event, parameters; event = arguments[0], parameters = 2 <= arguments.length ? __slice.call(arguments, 1) : []; callbacks = eventCallbacks[event]; if (callbacks && callbacks.length) { self = this; return callbacks.each(function(callback) { return callback.apply(self, parameters); }); } }
javascript
function() { var callbacks, event, parameters; event = arguments[0], parameters = 2 <= arguments.length ? __slice.call(arguments, 1) : []; callbacks = eventCallbacks[event]; if (callbacks && callbacks.length) { self = this; return callbacks.each(function(callback) { return callback.apply(self, parameters); }); } }
[ "function", "(", ")", "{", "var", "callbacks", ",", "event", ",", "parameters", ";", "event", "=", "arguments", "[", "0", "]", ",", "parameters", "=", "2", "<=", "arguments", ".", "length", "?", "__slice", ".", "call", "(", "arguments", ",", "1", ")", ":", "[", "]", ";", "callbacks", "=", "eventCallbacks", "[", "event", "]", ";", "if", "(", "callbacks", "&&", "callbacks", ".", "length", ")", "{", "self", "=", "this", ";", "return", "callbacks", ".", "each", "(", "function", "(", "callback", ")", "{", "return", "callback", ".", "apply", "(", "self", ",", "parameters", ")", ";", "}", ")", ";", "}", "}" ]
Calls all listeners attached to the specified event. # calls each event handler bound to "someCustomEvent" yourObject.trigger "someCustomEvent" @name trigger @methodOf Bindable# @param {String} event The event to trigger. @param {Array} [parameters] Additional parameters to pass to the event listener.
[ "Calls", "all", "listeners", "attached", "to", "the", "specified", "event", "." ]
4fd1e28e71db89385876efe46ca634a90d51672e
https://github.com/PixieEngine/Cornerstone/blob/4fd1e28e71db89385876efe46ca634a90d51672e/game.js#L943-L953
48,956
PixieEngine/Cornerstone
game.js
function() { var attrNames; attrNames = 1 <= arguments.length ? __slice.call(arguments, 0) : []; return attrNames.each(function(attrName) { return self[attrName] = function() { return I[attrName]; }; }); }
javascript
function() { var attrNames; attrNames = 1 <= arguments.length ? __slice.call(arguments, 0) : []; return attrNames.each(function(attrName) { return self[attrName] = function() { return I[attrName]; }; }); }
[ "function", "(", ")", "{", "var", "attrNames", ";", "attrNames", "=", "1", "<=", "arguments", ".", "length", "?", "__slice", ".", "call", "(", "arguments", ",", "0", ")", ":", "[", "]", ";", "return", "attrNames", ".", "each", "(", "function", "(", "attrName", ")", "{", "return", "self", "[", "attrName", "]", "=", "function", "(", ")", "{", "return", "I", "[", "attrName", "]", ";", "}", ";", "}", ")", ";", "}" ]
Generates a public jQuery style getter method for each String argument. myObject = Core r: 255 g: 0 b: 100 myObject.attrReader "r", "g", "b" myObject.r() => 255 myObject.g() => 0 myObject.b() => 100 @name attrReader @methodOf Core#
[ "Generates", "a", "public", "jQuery", "style", "getter", "method", "for", "each", "String", "argument", "." ]
4fd1e28e71db89385876efe46ca634a90d51672e
https://github.com/PixieEngine/Cornerstone/blob/4fd1e28e71db89385876efe46ca634a90d51672e/game.js#L1106-L1114
48,957
PixieEngine/Cornerstone
game.js
function() { var Module, key, moduleName, modules, value, _i, _len; modules = 1 <= arguments.length ? __slice.call(arguments, 0) : []; for (_i = 0, _len = modules.length; _i < _len; _i++) { Module = modules[_i]; if (typeof Module.isString === "function" ? Module.isString() : void 0) { moduleName = Module; Module = Module.constantize(); } else if (moduleName = Module._name) {} else { for (key in root) { value = root[key]; if (value === Module) Module._name = moduleName = key; } } if (moduleName) { if (!I.includedModules.include(moduleName)) { I.includedModules.push(moduleName); self.extend(Module(I, self)); } } else { warn("Unable to discover name for module: ", Module, "\nSerialization issues may occur."); self.extend(Module(I, self)); } } return self; }
javascript
function() { var Module, key, moduleName, modules, value, _i, _len; modules = 1 <= arguments.length ? __slice.call(arguments, 0) : []; for (_i = 0, _len = modules.length; _i < _len; _i++) { Module = modules[_i]; if (typeof Module.isString === "function" ? Module.isString() : void 0) { moduleName = Module; Module = Module.constantize(); } else if (moduleName = Module._name) {} else { for (key in root) { value = root[key]; if (value === Module) Module._name = moduleName = key; } } if (moduleName) { if (!I.includedModules.include(moduleName)) { I.includedModules.push(moduleName); self.extend(Module(I, self)); } } else { warn("Unable to discover name for module: ", Module, "\nSerialization issues may occur."); self.extend(Module(I, self)); } } return self; }
[ "function", "(", ")", "{", "var", "Module", ",", "key", ",", "moduleName", ",", "modules", ",", "value", ",", "_i", ",", "_len", ";", "modules", "=", "1", "<=", "arguments", ".", "length", "?", "__slice", ".", "call", "(", "arguments", ",", "0", ")", ":", "[", "]", ";", "for", "(", "_i", "=", "0", ",", "_len", "=", "modules", ".", "length", ";", "_i", "<", "_len", ";", "_i", "++", ")", "{", "Module", "=", "modules", "[", "_i", "]", ";", "if", "(", "typeof", "Module", ".", "isString", "===", "\"function\"", "?", "Module", ".", "isString", "(", ")", ":", "void", "0", ")", "{", "moduleName", "=", "Module", ";", "Module", "=", "Module", ".", "constantize", "(", ")", ";", "}", "else", "if", "(", "moduleName", "=", "Module", ".", "_name", ")", "{", "}", "else", "{", "for", "(", "key", "in", "root", ")", "{", "value", "=", "root", "[", "key", "]", ";", "if", "(", "value", "===", "Module", ")", "Module", ".", "_name", "=", "moduleName", "=", "key", ";", "}", "}", "if", "(", "moduleName", ")", "{", "if", "(", "!", "I", ".", "includedModules", ".", "include", "(", "moduleName", ")", ")", "{", "I", ".", "includedModules", ".", "push", "(", "moduleName", ")", ";", "self", ".", "extend", "(", "Module", "(", "I", ",", "self", ")", ")", ";", "}", "}", "else", "{", "warn", "(", "\"Unable to discover name for module: \"", ",", "Module", ",", "\"\\nSerialization issues may occur.\"", ")", ";", "self", ".", "extend", "(", "Module", "(", "I", ",", "self", ")", ")", ";", "}", "}", "return", "self", ";", "}" ]
Includes a module in this object. myObject = Core() myObject.include(Bindable) # now you can bind handlers to functions myObject.bind "someEvent", -> alert("wow. that was easy.") @name include @methodOf Core# @param {String} Module the module to include. A module is a constructor that takes two parameters, I and self, and returns an object containing the public methods to extend the including object with.
[ "Includes", "a", "module", "in", "this", "object", "." ]
4fd1e28e71db89385876efe46ca634a90d51672e
https://github.com/PixieEngine/Cornerstone/blob/4fd1e28e71db89385876efe46ca634a90d51672e/game.js#L1160-L1185
48,958
jacoborus/updox
updox.js
function (route, options) { var opts = options || {}; opts.dest = opts.dest || './docs'; opts.destname = opts.destname || false; route = route || './*.js'; mkdirp( opts.dest, function (err) { if (err) { console.error(err); } else { // options is optional glob( route, function (err, files) { var f; if (err) { throw err; } for (f in files) { renderFile( files[f], opts ); } }); } }); }
javascript
function (route, options) { var opts = options || {}; opts.dest = opts.dest || './docs'; opts.destname = opts.destname || false; route = route || './*.js'; mkdirp( opts.dest, function (err) { if (err) { console.error(err); } else { // options is optional glob( route, function (err, files) { var f; if (err) { throw err; } for (f in files) { renderFile( files[f], opts ); } }); } }); }
[ "function", "(", "route", ",", "options", ")", "{", "var", "opts", "=", "options", "||", "{", "}", ";", "opts", ".", "dest", "=", "opts", ".", "dest", "||", "'./docs'", ";", "opts", ".", "destname", "=", "opts", ".", "destname", "||", "false", ";", "route", "=", "route", "||", "'./*.js'", ";", "mkdirp", "(", "opts", ".", "dest", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "err", ")", ";", "}", "else", "{", "// options is optional", "glob", "(", "route", ",", "function", "(", "err", ",", "files", ")", "{", "var", "f", ";", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "for", "(", "f", "in", "files", ")", "{", "renderFile", "(", "files", "[", "f", "]", ",", "opts", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
Document files in glob route path Options: - `dest`: documentation folder ('./docs' by default) - `destname`: name of docfile (only when one file is documented) @param {String} route glob path of javascript files @param {Object} options destiny and out name file @return {Array} list of documented files
[ "Document", "files", "in", "glob", "route", "path" ]
a3886637baf3afb2a15732ad9230f8e553577560
https://github.com/jacoborus/updox/blob/a3886637baf3afb2a15732ad9230f8e553577560/updox.js#L66-L87
48,959
AndiDittrich/Node.Crypto-Toolkit
lib/Hash.js
hash
function hash(input, algo, type){ // string or buffer input ? => keep it if (typeof input !== 'string' && !(input instanceof Buffer)){ input = JSON.stringify(input); } // create hash algo var sum = _crypto.createHash(algo); // set content sum.update(input); // binary output ? if (type && type.toLowerCase().trim() == 'binary'){ // calculate hashsum return sum.digest(); // base 64 urlsafe ? }else if (type==='base64-urlsafe'){ return base64urlsafe(sum.digest('base64')); // string output }else{ // calculate hashsum return sum.digest(type); } }
javascript
function hash(input, algo, type){ // string or buffer input ? => keep it if (typeof input !== 'string' && !(input instanceof Buffer)){ input = JSON.stringify(input); } // create hash algo var sum = _crypto.createHash(algo); // set content sum.update(input); // binary output ? if (type && type.toLowerCase().trim() == 'binary'){ // calculate hashsum return sum.digest(); // base 64 urlsafe ? }else if (type==='base64-urlsafe'){ return base64urlsafe(sum.digest('base64')); // string output }else{ // calculate hashsum return sum.digest(type); } }
[ "function", "hash", "(", "input", ",", "algo", ",", "type", ")", "{", "// string or buffer input ? => keep it", "if", "(", "typeof", "input", "!==", "'string'", "&&", "!", "(", "input", "instanceof", "Buffer", ")", ")", "{", "input", "=", "JSON", ".", "stringify", "(", "input", ")", ";", "}", "// create hash algo", "var", "sum", "=", "_crypto", ".", "createHash", "(", "algo", ")", ";", "// set content", "sum", ".", "update", "(", "input", ")", ";", "// binary output ?", "if", "(", "type", "&&", "type", ".", "toLowerCase", "(", ")", ".", "trim", "(", ")", "==", "'binary'", ")", "{", "// calculate hashsum", "return", "sum", ".", "digest", "(", ")", ";", "// base 64 urlsafe ?", "}", "else", "if", "(", "type", "===", "'base64-urlsafe'", ")", "{", "return", "base64urlsafe", "(", "sum", ".", "digest", "(", "'base64'", ")", ")", ";", "// string output", "}", "else", "{", "// calculate hashsum", "return", "sum", ".", "digest", "(", "type", ")", ";", "}", "}" ]
generic string hashing
[ "generic", "string", "hashing" ]
cb3cd64bc69460bdc761f36b0dd4665727bf6bd4
https://github.com/AndiDittrich/Node.Crypto-Toolkit/blob/cb3cd64bc69460bdc761f36b0dd4665727bf6bd4/lib/Hash.js#L4-L30
48,960
arendjr/laces.js
demo-hogan-local-js/hogan.js
function(symbol, ctx, partials, indent) { var partial = this.ep(symbol, partials); if (!partial) { return ''; } return partial.ri(ctx, partials, indent); }
javascript
function(symbol, ctx, partials, indent) { var partial = this.ep(symbol, partials); if (!partial) { return ''; } return partial.ri(ctx, partials, indent); }
[ "function", "(", "symbol", ",", "ctx", ",", "partials", ",", "indent", ")", "{", "var", "partial", "=", "this", ".", "ep", "(", "symbol", ",", "partials", ")", ";", "if", "(", "!", "partial", ")", "{", "return", "''", ";", "}", "return", "partial", ".", "ri", "(", "ctx", ",", "partials", ",", "indent", ")", ";", "}" ]
tries to find a partial in the current scope and render it
[ "tries", "to", "find", "a", "partial", "in", "the", "current", "scope", "and", "render", "it" ]
e04fd060a4668abe58064267b1405e6a40f8a6f2
https://github.com/arendjr/laces.js/blob/e04fd060a4668abe58064267b1405e6a40f8a6f2/demo-hogan-local-js/hogan.js#L88-L95
48,961
arendjr/laces.js
demo-hogan-local-js/hogan.js
function(func, ctx, partials) { var cx = ctx[ctx.length - 1]; return func.call(cx); }
javascript
function(func, ctx, partials) { var cx = ctx[ctx.length - 1]; return func.call(cx); }
[ "function", "(", "func", ",", "ctx", ",", "partials", ")", "{", "var", "cx", "=", "ctx", "[", "ctx", ".", "length", "-", "1", "]", ";", "return", "func", ".", "call", "(", "cx", ")", ";", "}" ]
method replace section
[ "method", "replace", "section" ]
e04fd060a4668abe58064267b1405e6a40f8a6f2
https://github.com/arendjr/laces.js/blob/e04fd060a4668abe58064267b1405e6a40f8a6f2/demo-hogan-local-js/hogan.js#L226-L229
48,962
arendjr/laces.js
demo-hogan-local-js/hogan.js
findInScope
function findInScope(key, scope, doModelGet) { var val, checkVal; if (scope && typeof scope == 'object') { if (scope[key] != null) { val = scope[key]; // try lookup with get for backbone or similar model data } else if (doModelGet && scope.get && typeof scope.get == 'function') { val = scope.get(key); } } return val; }
javascript
function findInScope(key, scope, doModelGet) { var val, checkVal; if (scope && typeof scope == 'object') { if (scope[key] != null) { val = scope[key]; // try lookup with get for backbone or similar model data } else if (doModelGet && scope.get && typeof scope.get == 'function') { val = scope.get(key); } } return val; }
[ "function", "findInScope", "(", "key", ",", "scope", ",", "doModelGet", ")", "{", "var", "val", ",", "checkVal", ";", "if", "(", "scope", "&&", "typeof", "scope", "==", "'object'", ")", "{", "if", "(", "scope", "[", "key", "]", "!=", "null", ")", "{", "val", "=", "scope", "[", "key", "]", ";", "// try lookup with get for backbone or similar model data", "}", "else", "if", "(", "doModelGet", "&&", "scope", ".", "get", "&&", "typeof", "scope", ".", "get", "==", "'function'", ")", "{", "val", "=", "scope", ".", "get", "(", "key", ")", ";", "}", "}", "return", "val", ";", "}" ]
Find a key in an object
[ "Find", "a", "key", "in", "an", "object" ]
e04fd060a4668abe58064267b1405e6a40f8a6f2
https://github.com/arendjr/laces.js/blob/e04fd060a4668abe58064267b1405e6a40f8a6f2/demo-hogan-local-js/hogan.js#L249-L264
48,963
KTH/kth-node-mongo
index.js
_mergeOptions
function _mergeOptions () { var options = {} for (var i = 0; i < arguments.length; ++i) { let obj = arguments[i] for (var attr in obj) { options[attr] = obj[attr] } } return options }
javascript
function _mergeOptions () { var options = {} for (var i = 0; i < arguments.length; ++i) { let obj = arguments[i] for (var attr in obj) { options[attr] = obj[attr] } } return options }
[ "function", "_mergeOptions", "(", ")", "{", "var", "options", "=", "{", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "++", "i", ")", "{", "let", "obj", "=", "arguments", "[", "i", "]", "for", "(", "var", "attr", "in", "obj", ")", "{", "options", "[", "attr", "]", "=", "obj", "[", "attr", "]", "}", "}", "return", "options", "}" ]
merge all options objects front to back, i.e. later overriding earlier objects
[ "merge", "all", "options", "objects", "front", "to", "back", "i", ".", "e", ".", "later", "overriding", "earlier", "objects" ]
03810f92dc504cfe0740c3083ce01dac00ba5aa1
https://github.com/KTH/kth-node-mongo/blob/03810f92dc504cfe0740c3083ce01dac00ba5aa1/index.js#L88-L95
48,964
AriaMinaei/mocha-pretty-spec-reporter
lib/base.js
Base
function Base(runner) { var self = this , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } , failures = this.failures = []; if (!runner) return; this.runner = runner; runner.stats = stats; runner.on('start', function(){ stats.start = new Date; }); runner.on('suite', function(suite){ stats.suites = stats.suites || 0; suite.root || stats.suites++; }); runner.on('test end', function(test){ stats.tests = stats.tests || 0; stats.tests++; }); runner.on('pass', function(test){ stats.passes = stats.passes || 0; var medium = test.slow() / 2; test.speed = test.duration > test.slow() ? 'slow' : test.duration > medium ? 'medium' : 'fast'; stats.passes++; }); runner.on('fail', function(test, err){ stats.failures = stats.failures || 0; stats.failures++; test.err = err; failures.push(test); }); runner.on('end', function(){ stats.end = new Date; stats.duration = new Date - stats.start; }); runner.on('pending', function(){ stats.pending++; }); }
javascript
function Base(runner) { var self = this , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } , failures = this.failures = []; if (!runner) return; this.runner = runner; runner.stats = stats; runner.on('start', function(){ stats.start = new Date; }); runner.on('suite', function(suite){ stats.suites = stats.suites || 0; suite.root || stats.suites++; }); runner.on('test end', function(test){ stats.tests = stats.tests || 0; stats.tests++; }); runner.on('pass', function(test){ stats.passes = stats.passes || 0; var medium = test.slow() / 2; test.speed = test.duration > test.slow() ? 'slow' : test.duration > medium ? 'medium' : 'fast'; stats.passes++; }); runner.on('fail', function(test, err){ stats.failures = stats.failures || 0; stats.failures++; test.err = err; failures.push(test); }); runner.on('end', function(){ stats.end = new Date; stats.duration = new Date - stats.start; }); runner.on('pending', function(){ stats.pending++; }); }
[ "function", "Base", "(", "runner", ")", "{", "var", "self", "=", "this", ",", "stats", "=", "this", ".", "stats", "=", "{", "suites", ":", "0", ",", "tests", ":", "0", ",", "passes", ":", "0", ",", "pending", ":", "0", ",", "failures", ":", "0", "}", ",", "failures", "=", "this", ".", "failures", "=", "[", "]", ";", "if", "(", "!", "runner", ")", "return", ";", "this", ".", "runner", "=", "runner", ";", "runner", ".", "stats", "=", "stats", ";", "runner", ".", "on", "(", "'start'", ",", "function", "(", ")", "{", "stats", ".", "start", "=", "new", "Date", ";", "}", ")", ";", "runner", ".", "on", "(", "'suite'", ",", "function", "(", "suite", ")", "{", "stats", ".", "suites", "=", "stats", ".", "suites", "||", "0", ";", "suite", ".", "root", "||", "stats", ".", "suites", "++", ";", "}", ")", ";", "runner", ".", "on", "(", "'test end'", ",", "function", "(", "test", ")", "{", "stats", ".", "tests", "=", "stats", ".", "tests", "||", "0", ";", "stats", ".", "tests", "++", ";", "}", ")", ";", "runner", ".", "on", "(", "'pass'", ",", "function", "(", "test", ")", "{", "stats", ".", "passes", "=", "stats", ".", "passes", "||", "0", ";", "var", "medium", "=", "test", ".", "slow", "(", ")", "/", "2", ";", "test", ".", "speed", "=", "test", ".", "duration", ">", "test", ".", "slow", "(", ")", "?", "'slow'", ":", "test", ".", "duration", ">", "medium", "?", "'medium'", ":", "'fast'", ";", "stats", ".", "passes", "++", ";", "}", ")", ";", "runner", ".", "on", "(", "'fail'", ",", "function", "(", "test", ",", "err", ")", "{", "stats", ".", "failures", "=", "stats", ".", "failures", "||", "0", ";", "stats", ".", "failures", "++", ";", "test", ".", "err", "=", "err", ";", "failures", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "stats", ".", "end", "=", "new", "Date", ";", "stats", ".", "duration", "=", "new", "Date", "-", "stats", ".", "start", ";", "}", ")", ";", "runner", ".", "on", "(", "'pending'", ",", "function", "(", ")", "{", "stats", ".", "pending", "++", ";", "}", ")", ";", "}" ]
Initialize a new `Base` reporter. All other reporters generally inherit from this reporter, providing stats such as test duration, number of tests passed / failed etc. @param {Runner} runner @api public
[ "Initialize", "a", "new", "Base", "reporter", "." ]
3799a77d6bac1852f4c79912b552e23e3ffb3699
https://github.com/AriaMinaei/mocha-pretty-spec-reporter/blob/3799a77d6bac1852f4c79912b552e23e3ffb3699/lib/base.js#L242-L294
48,965
AriaMinaei/mocha-pretty-spec-reporter
lib/base.js
inlineDiff
function inlineDiff(err, escape) { var msg = errorDiff(err, 'WordsWithSpace', escape); // linenos var lines = msg.split('\n'); if (lines.length > 4) { var width = String(lines.length).length; msg = lines.map(function(str, i){ return pad(++i, width) + ' |' + ' ' + str; }).join('\n'); } // legend msg = '\n' + color('diff removed', 'actual') + ' ' + color('diff added', 'expected') + '\n\n' + msg + '\n'; // indent msg = msg.replace(/^/gm, ' '); return msg; }
javascript
function inlineDiff(err, escape) { var msg = errorDiff(err, 'WordsWithSpace', escape); // linenos var lines = msg.split('\n'); if (lines.length > 4) { var width = String(lines.length).length; msg = lines.map(function(str, i){ return pad(++i, width) + ' |' + ' ' + str; }).join('\n'); } // legend msg = '\n' + color('diff removed', 'actual') + ' ' + color('diff added', 'expected') + '\n\n' + msg + '\n'; // indent msg = msg.replace(/^/gm, ' '); return msg; }
[ "function", "inlineDiff", "(", "err", ",", "escape", ")", "{", "var", "msg", "=", "errorDiff", "(", "err", ",", "'WordsWithSpace'", ",", "escape", ")", ";", "// linenos", "var", "lines", "=", "msg", ".", "split", "(", "'\\n'", ")", ";", "if", "(", "lines", ".", "length", ">", "4", ")", "{", "var", "width", "=", "String", "(", "lines", ".", "length", ")", ".", "length", ";", "msg", "=", "lines", ".", "map", "(", "function", "(", "str", ",", "i", ")", "{", "return", "pad", "(", "++", "i", ",", "width", ")", "+", "' |'", "+", "' '", "+", "str", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "}", "// legend", "msg", "=", "'\\n'", "+", "color", "(", "'diff removed'", ",", "'actual'", ")", "+", "' '", "+", "color", "(", "'diff added'", ",", "'expected'", ")", "+", "'\\n\\n'", "+", "msg", "+", "'\\n'", ";", "// indent", "msg", "=", "msg", ".", "replace", "(", "/", "^", "/", "gm", ",", "' '", ")", ";", "return", "msg", ";", "}" ]
Returns an inline diff between 2 strings with coloured ANSI output @param {Error} Error with actual/expected @return {String} Diff @api private
[ "Returns", "an", "inline", "diff", "between", "2", "strings", "with", "coloured", "ANSI", "output" ]
3799a77d6bac1852f4c79912b552e23e3ffb3699
https://github.com/AriaMinaei/mocha-pretty-spec-reporter/blob/3799a77d6bac1852f4c79912b552e23e3ffb3699/lib/base.js#L364-L388
48,966
AriaMinaei/mocha-pretty-spec-reporter
lib/base.js
unifiedDiff
function unifiedDiff(err, escape) { var indent = ' '; function cleanUp(line) { if (escape) { line = escapeInvisibles(line); } if (line[0] === '+') return indent + colorLines('diff added', line); if (line[0] === '-') return indent + colorLines('diff removed', line); if (line.match(/\@\@/)) return null; if (line.match(/\\ No newline/)) return null; else return indent + line; } function notBlank(line) { return line != null; } msg = diff.createPatch('string', err.actual, err.expected); var lines = msg.split('\n').splice(4); return '\n ' + colorLines('diff added', '+ expected') + ' ' + colorLines('diff removed', '- actual') + '\n\n' + lines.map(cleanUp).filter(notBlank).join('\n'); }
javascript
function unifiedDiff(err, escape) { var indent = ' '; function cleanUp(line) { if (escape) { line = escapeInvisibles(line); } if (line[0] === '+') return indent + colorLines('diff added', line); if (line[0] === '-') return indent + colorLines('diff removed', line); if (line.match(/\@\@/)) return null; if (line.match(/\\ No newline/)) return null; else return indent + line; } function notBlank(line) { return line != null; } msg = diff.createPatch('string', err.actual, err.expected); var lines = msg.split('\n').splice(4); return '\n ' + colorLines('diff added', '+ expected') + ' ' + colorLines('diff removed', '- actual') + '\n\n' + lines.map(cleanUp).filter(notBlank).join('\n'); }
[ "function", "unifiedDiff", "(", "err", ",", "escape", ")", "{", "var", "indent", "=", "' '", ";", "function", "cleanUp", "(", "line", ")", "{", "if", "(", "escape", ")", "{", "line", "=", "escapeInvisibles", "(", "line", ")", ";", "}", "if", "(", "line", "[", "0", "]", "===", "'+'", ")", "return", "indent", "+", "colorLines", "(", "'diff added'", ",", "line", ")", ";", "if", "(", "line", "[", "0", "]", "===", "'-'", ")", "return", "indent", "+", "colorLines", "(", "'diff removed'", ",", "line", ")", ";", "if", "(", "line", ".", "match", "(", "/", "\\@\\@", "/", ")", ")", "return", "null", ";", "if", "(", "line", ".", "match", "(", "/", "\\\\ No newline", "/", ")", ")", "return", "null", ";", "else", "return", "indent", "+", "line", ";", "}", "function", "notBlank", "(", "line", ")", "{", "return", "line", "!=", "null", ";", "}", "msg", "=", "diff", ".", "createPatch", "(", "'string'", ",", "err", ".", "actual", ",", "err", ".", "expected", ")", ";", "var", "lines", "=", "msg", ".", "split", "(", "'\\n'", ")", ".", "splice", "(", "4", ")", ";", "return", "'\\n '", "+", "colorLines", "(", "'diff added'", ",", "'+ expected'", ")", "+", "' '", "+", "colorLines", "(", "'diff removed'", ",", "'- actual'", ")", "+", "'\\n\\n'", "+", "lines", ".", "map", "(", "cleanUp", ")", ".", "filter", "(", "notBlank", ")", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Returns a unified diff between 2 strings @param {Error} Error with actual/expected @return {String} Diff @api private
[ "Returns", "a", "unified", "diff", "between", "2", "strings" ]
3799a77d6bac1852f4c79912b552e23e3ffb3699
https://github.com/AriaMinaei/mocha-pretty-spec-reporter/blob/3799a77d6bac1852f4c79912b552e23e3ffb3699/lib/base.js#L398-L420
48,967
AriaMinaei/mocha-pretty-spec-reporter
lib/base.js
stringify
function stringify(obj) { if (obj instanceof RegExp) return obj.toString(); return JSON.stringify(obj, null, 2); }
javascript
function stringify(obj) { if (obj instanceof RegExp) return obj.toString(); return JSON.stringify(obj, null, 2); }
[ "function", "stringify", "(", "obj", ")", "{", "if", "(", "obj", "instanceof", "RegExp", ")", "return", "obj", ".", "toString", "(", ")", ";", "return", "JSON", ".", "stringify", "(", "obj", ",", "null", ",", "2", ")", ";", "}" ]
Stringify `obj`. @param {Object} obj @return {String} @api private
[ "Stringify", "obj", "." ]
3799a77d6bac1852f4c79912b552e23e3ffb3699
https://github.com/AriaMinaei/mocha-pretty-spec-reporter/blob/3799a77d6bac1852f4c79912b552e23e3ffb3699/lib/base.js#L476-L479
48,968
AriaMinaei/mocha-pretty-spec-reporter
lib/base.js
canonicalize
function canonicalize(obj, stack) { stack = stack || []; if (utils.indexOf(stack, obj) !== -1) return obj; var canonicalizedObj; if ('[object Array]' == {}.toString.call(obj)) { stack.push(obj); canonicalizedObj = utils.map(obj, function(item) { return canonicalize(item, stack); }); stack.pop(); } else if (typeof obj === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; utils.forEach(utils.keys(obj).sort(), function(key) { canonicalizedObj[key] = canonicalize(obj[key], stack); }); stack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; }
javascript
function canonicalize(obj, stack) { stack = stack || []; if (utils.indexOf(stack, obj) !== -1) return obj; var canonicalizedObj; if ('[object Array]' == {}.toString.call(obj)) { stack.push(obj); canonicalizedObj = utils.map(obj, function(item) { return canonicalize(item, stack); }); stack.pop(); } else if (typeof obj === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; utils.forEach(utils.keys(obj).sort(), function(key) { canonicalizedObj[key] = canonicalize(obj[key], stack); }); stack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; }
[ "function", "canonicalize", "(", "obj", ",", "stack", ")", "{", "stack", "=", "stack", "||", "[", "]", ";", "if", "(", "utils", ".", "indexOf", "(", "stack", ",", "obj", ")", "!==", "-", "1", ")", "return", "obj", ";", "var", "canonicalizedObj", ";", "if", "(", "'[object Array]'", "==", "{", "}", ".", "toString", ".", "call", "(", "obj", ")", ")", "{", "stack", ".", "push", "(", "obj", ")", ";", "canonicalizedObj", "=", "utils", ".", "map", "(", "obj", ",", "function", "(", "item", ")", "{", "return", "canonicalize", "(", "item", ",", "stack", ")", ";", "}", ")", ";", "stack", ".", "pop", "(", ")", ";", "}", "else", "if", "(", "typeof", "obj", "===", "'object'", "&&", "obj", "!==", "null", ")", "{", "stack", ".", "push", "(", "obj", ")", ";", "canonicalizedObj", "=", "{", "}", ";", "utils", ".", "forEach", "(", "utils", ".", "keys", "(", "obj", ")", ".", "sort", "(", ")", ",", "function", "(", "key", ")", "{", "canonicalizedObj", "[", "key", "]", "=", "canonicalize", "(", "obj", "[", "key", "]", ",", "stack", ")", ";", "}", ")", ";", "stack", ".", "pop", "(", ")", ";", "}", "else", "{", "canonicalizedObj", "=", "obj", ";", "}", "return", "canonicalizedObj", ";", "}" ]
Return a new object that has the keys in sorted order. @param {Object} obj @return {Object} @api private
[ "Return", "a", "new", "object", "that", "has", "the", "keys", "in", "sorted", "order", "." ]
3799a77d6bac1852f4c79912b552e23e3ffb3699
https://github.com/AriaMinaei/mocha-pretty-spec-reporter/blob/3799a77d6bac1852f4c79912b552e23e3ffb3699/lib/base.js#L488-L513
48,969
jridgewell/PJs
promise.js
RejectedPromise
function RejectedPromise(reason, unused, onRejected, deferred) { if (!onRejected) { deferredAdopt(deferred, RejectedPromise, reason); return this; } if (!deferred) { deferred = new Deferred(this.constructor); } defer(tryCatchDeferred(deferred, onRejected, reason)); return deferred.promise; }
javascript
function RejectedPromise(reason, unused, onRejected, deferred) { if (!onRejected) { deferredAdopt(deferred, RejectedPromise, reason); return this; } if (!deferred) { deferred = new Deferred(this.constructor); } defer(tryCatchDeferred(deferred, onRejected, reason)); return deferred.promise; }
[ "function", "RejectedPromise", "(", "reason", ",", "unused", ",", "onRejected", ",", "deferred", ")", "{", "if", "(", "!", "onRejected", ")", "{", "deferredAdopt", "(", "deferred", ",", "RejectedPromise", ",", "reason", ")", ";", "return", "this", ";", "}", "if", "(", "!", "deferred", ")", "{", "deferred", "=", "new", "Deferred", "(", "this", ".", "constructor", ")", ";", "}", "defer", "(", "tryCatchDeferred", "(", "deferred", ",", "onRejected", ",", "reason", ")", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
The Rejected Promise state. Calls onRejected with the resolved value of this promise, creating a new promise. If there is no onRejected, returns the current promise to avoid an promise instance. @this {!Promise} The current promise @param {*=} reason The current promise's rejection reason. @param {function(*=)=} unused @param {function(*=)=} onRejected @param {Deferred} deferred A deferred object that holds a promise and its resolve and reject functions. It IS NOT passed when called from Promise#then to save an object instance (since we may return the current promise). It IS passed in when adopting the Rejected state from the Pending state. @returns {!Promise}
[ "The", "Rejected", "Promise", "state", ".", "Calls", "onRejected", "with", "the", "resolved", "value", "of", "this", "promise", "creating", "a", "new", "promise", "." ]
2dc2185f174e3b79daa1d66638056d9f5e1f7792
https://github.com/jridgewell/PJs/blob/2dc2185f174e3b79daa1d66638056d9f5e1f7792/promise.js#L236-L246
48,970
jridgewell/PJs
promise.js
PendingPromise
function PendingPromise(queue, onFulfilled, onRejected, deferred) { if (!deferred) { if (!onFulfilled && !onRejected) { return this; } deferred = new Deferred(this.constructor); } queue.push({ deferred: deferred, onFulfilled: onFulfilled || deferred.resolve, onRejected: onRejected || deferred.reject }); return deferred.promise; }
javascript
function PendingPromise(queue, onFulfilled, onRejected, deferred) { if (!deferred) { if (!onFulfilled && !onRejected) { return this; } deferred = new Deferred(this.constructor); } queue.push({ deferred: deferred, onFulfilled: onFulfilled || deferred.resolve, onRejected: onRejected || deferred.reject }); return deferred.promise; }
[ "function", "PendingPromise", "(", "queue", ",", "onFulfilled", ",", "onRejected", ",", "deferred", ")", "{", "if", "(", "!", "deferred", ")", "{", "if", "(", "!", "onFulfilled", "&&", "!", "onRejected", ")", "{", "return", "this", ";", "}", "deferred", "=", "new", "Deferred", "(", "this", ".", "constructor", ")", ";", "}", "queue", ".", "push", "(", "{", "deferred", ":", "deferred", ",", "onFulfilled", ":", "onFulfilled", "||", "deferred", ".", "resolve", ",", "onRejected", ":", "onRejected", "||", "deferred", ".", "reject", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
The Pending Promise state. Eventually calls onFulfilled once the promise has resolved, or onRejected once the promise rejects. If there is no onFulfilled and no onRejected, returns the current promise to avoid an promise instance. @this {!Promise} The current promise @param {*=} queue The current promise's pending promises queue. @param {function(*=)=} onFulfilled @param {function(*=)=} onRejected @param {Deferred} deferred A deferred object that holds a promise and its resolve and reject functions. It IS NOT passed when called from Promise#then to save an object instance (since we may return the current promise). It IS passed in when adopting the Pending state from the Pending state of another promise. @returns {!Promise}
[ "The", "Pending", "Promise", "state", ".", "Eventually", "calls", "onFulfilled", "once", "the", "promise", "has", "resolved", "or", "onRejected", "once", "the", "promise", "rejects", "." ]
2dc2185f174e3b79daa1d66638056d9f5e1f7792
https://github.com/jridgewell/PJs/blob/2dc2185f174e3b79daa1d66638056d9f5e1f7792/promise.js#L266-L277
48,971
jridgewell/PJs
promise.js
adopt
function adopt(promise, state, value, adoptee) { var queue = promise._value; promise._state = state; promise._value = value; if (adoptee && state === PendingPromise) { adoptee._state(value, void 0, void 0, { promise: promise, resolve: void 0, reject: void 0 }); } for (var i = 0; i < queue.length; i++) { var next = queue[i]; promise._state( value, next.onFulfilled, next.onRejected, next.deferred ); } queue.length = 0; // Determine if this rejected promise will be "handled". if (state === RejectedPromise && promise._isChainEnd) { setTimeout(function() { if (promise._isChainEnd) { onPossiblyUnhandledRejection(value, promise); } }, 0); } }
javascript
function adopt(promise, state, value, adoptee) { var queue = promise._value; promise._state = state; promise._value = value; if (adoptee && state === PendingPromise) { adoptee._state(value, void 0, void 0, { promise: promise, resolve: void 0, reject: void 0 }); } for (var i = 0; i < queue.length; i++) { var next = queue[i]; promise._state( value, next.onFulfilled, next.onRejected, next.deferred ); } queue.length = 0; // Determine if this rejected promise will be "handled". if (state === RejectedPromise && promise._isChainEnd) { setTimeout(function() { if (promise._isChainEnd) { onPossiblyUnhandledRejection(value, promise); } }, 0); } }
[ "function", "adopt", "(", "promise", ",", "state", ",", "value", ",", "adoptee", ")", "{", "var", "queue", "=", "promise", ".", "_value", ";", "promise", ".", "_state", "=", "state", ";", "promise", ".", "_value", "=", "value", ";", "if", "(", "adoptee", "&&", "state", "===", "PendingPromise", ")", "{", "adoptee", ".", "_state", "(", "value", ",", "void", "0", ",", "void", "0", ",", "{", "promise", ":", "promise", ",", "resolve", ":", "void", "0", ",", "reject", ":", "void", "0", "}", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "queue", ".", "length", ";", "i", "++", ")", "{", "var", "next", "=", "queue", "[", "i", "]", ";", "promise", ".", "_state", "(", "value", ",", "next", ".", "onFulfilled", ",", "next", ".", "onRejected", ",", "next", ".", "deferred", ")", ";", "}", "queue", ".", "length", "=", "0", ";", "// Determine if this rejected promise will be \"handled\".", "if", "(", "state", "===", "RejectedPromise", "&&", "promise", ".", "_isChainEnd", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "promise", ".", "_isChainEnd", ")", "{", "onPossiblyUnhandledRejection", "(", "value", ",", "promise", ")", ";", "}", "}", ",", "0", ")", ";", "}", "}" ]
Transitions the state of promise to another state. This is only ever called on with a promise that is currently in the Pending state. @param {!Promise} promise @param {function(this:Promise,*=,function(*=),function(*=),Deferred):!Promise} state @param {*=} value
[ "Transitions", "the", "state", "of", "promise", "to", "another", "state", ".", "This", "is", "only", "ever", "called", "on", "with", "a", "promise", "that", "is", "currently", "in", "the", "Pending", "state", "." ]
2dc2185f174e3b79daa1d66638056d9f5e1f7792
https://github.com/jridgewell/PJs/blob/2dc2185f174e3b79daa1d66638056d9f5e1f7792/promise.js#L306-L338
48,972
jridgewell/PJs
promise.js
deferredAdopt
function deferredAdopt(deferred, state, value) { if (deferred) { var promise = deferred.promise; promise._state = state; promise._value = value; } }
javascript
function deferredAdopt(deferred, state, value) { if (deferred) { var promise = deferred.promise; promise._state = state; promise._value = value; } }
[ "function", "deferredAdopt", "(", "deferred", ",", "state", ",", "value", ")", "{", "if", "(", "deferred", ")", "{", "var", "promise", "=", "deferred", ".", "promise", ";", "promise", ".", "_state", "=", "state", ";", "promise", ".", "_value", "=", "value", ";", "}", "}" ]
Updates a deferred promises state. Necessary for updating an adopting promise's state when the adoptee resolves. @param {?Deferred} deferred @param {function(this:Promise,*=,function(*=),function(*=),Deferred):!Promise} state @param {*=} value
[ "Updates", "a", "deferred", "promises", "state", ".", "Necessary", "for", "updating", "an", "adopting", "promise", "s", "state", "when", "the", "adoptee", "resolves", "." ]
2dc2185f174e3b79daa1d66638056d9f5e1f7792
https://github.com/jridgewell/PJs/blob/2dc2185f174e3b79daa1d66638056d9f5e1f7792/promise.js#L361-L367
48,973
jridgewell/PJs
promise.js
each
function each(collection, iterator) { for (var i = 0; i < collection.length; i++) { iterator(collection[i], i); } }
javascript
function each(collection, iterator) { for (var i = 0; i < collection.length; i++) { iterator(collection[i], i); } }
[ "function", "each", "(", "collection", ",", "iterator", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "collection", ".", "length", ";", "i", "++", ")", "{", "iterator", "(", "collection", "[", "i", "]", ",", "i", ")", ";", "}", "}" ]
Iterates over each element of an array, calling the iterator with the element and its index. @param {!Array} collection @param {function(*=,number)} iterator
[ "Iterates", "over", "each", "element", "of", "an", "array", "calling", "the", "iterator", "with", "the", "element", "and", "its", "index", "." ]
2dc2185f174e3b79daa1d66638056d9f5e1f7792
https://github.com/jridgewell/PJs/blob/2dc2185f174e3b79daa1d66638056d9f5e1f7792/promise.js#L401-L405
48,974
jridgewell/PJs
promise.js
tryCatchDeferred
function tryCatchDeferred(deferred, fn, arg) { var promise = deferred.promise; var resolve = deferred.resolve; var reject = deferred.reject; return function() { try { var result = fn(arg); doResolve(promise, resolve, reject, result, result); } catch (e) { reject(e); } }; }
javascript
function tryCatchDeferred(deferred, fn, arg) { var promise = deferred.promise; var resolve = deferred.resolve; var reject = deferred.reject; return function() { try { var result = fn(arg); doResolve(promise, resolve, reject, result, result); } catch (e) { reject(e); } }; }
[ "function", "tryCatchDeferred", "(", "deferred", ",", "fn", ",", "arg", ")", "{", "var", "promise", "=", "deferred", ".", "promise", ";", "var", "resolve", "=", "deferred", ".", "resolve", ";", "var", "reject", "=", "deferred", ".", "reject", ";", "return", "function", "(", ")", "{", "try", "{", "var", "result", "=", "fn", "(", "arg", ")", ";", "doResolve", "(", "promise", ",", "resolve", ",", "reject", ",", "result", ",", "result", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ";", "}" ]
Creates a function that will attempt to resolve the deferred with the return of fn. If any error is raised, rejects instead. @param {!Deferred} deferred @param {function(*=)} fn @param {*} arg @returns {function()}
[ "Creates", "a", "function", "that", "will", "attempt", "to", "resolve", "the", "deferred", "with", "the", "return", "of", "fn", ".", "If", "any", "error", "is", "raised", "rejects", "instead", "." ]
2dc2185f174e3b79daa1d66638056d9f5e1f7792
https://github.com/jridgewell/PJs/blob/2dc2185f174e3b79daa1d66638056d9f5e1f7792/promise.js#L416-L428
48,975
avoidwork/mpass
src/password.js
password
function password (n, special) { n = n || 3; special = special === true; var result = "", i = -1, used = {}, hasSub = false, hasExtra = false, flip, lth, pos, rnd, word; function sub (x, idx) { if (!hasSub && word.indexOf(x) > -1) { word = word.replace(x, subs[idx]); hasSub = true; flip = false; } } if (!special) { while (++i < n) { result += words[random(nth, used)]; } } else { rnd = Math.floor(Math.random() * n); while (++i < n) { word = words[random(nth, used)]; // Capitalizing a letter in a word if (i === rnd) { lth = word.length; pos = Math.floor(Math.random() * lth); if (pos === 0) { word = word.charAt(0).toUpperCase() + word.slice(1); } else if (pos < lth - 1) { word = word.slice(0, pos) + word.charAt(pos).toUpperCase() + word.slice(pos + 1, lth); } else { word = word.slice(0, pos) + word.charAt(pos).toUpperCase(); } } // or specializing if in the second half else if (i >= ( n / 2 )) { // Simulating a coin flip flip = Math.random() >= 0.5 ? 1 : 0; // Substituting a character if (flip && !hasSub) { replace.forEach(sub); } // Adding a character if (flip && !hasExtra) { word += extra[Math.floor(Math.random() * eth)]; hasExtra = true; } } result += word; } if (!hasSub) { result += subs[Math.floor(Math.random() * rth)]; } if (!hasExtra) { result += extra[Math.floor(Math.random() * eth)]; } } return result; }
javascript
function password (n, special) { n = n || 3; special = special === true; var result = "", i = -1, used = {}, hasSub = false, hasExtra = false, flip, lth, pos, rnd, word; function sub (x, idx) { if (!hasSub && word.indexOf(x) > -1) { word = word.replace(x, subs[idx]); hasSub = true; flip = false; } } if (!special) { while (++i < n) { result += words[random(nth, used)]; } } else { rnd = Math.floor(Math.random() * n); while (++i < n) { word = words[random(nth, used)]; // Capitalizing a letter in a word if (i === rnd) { lth = word.length; pos = Math.floor(Math.random() * lth); if (pos === 0) { word = word.charAt(0).toUpperCase() + word.slice(1); } else if (pos < lth - 1) { word = word.slice(0, pos) + word.charAt(pos).toUpperCase() + word.slice(pos + 1, lth); } else { word = word.slice(0, pos) + word.charAt(pos).toUpperCase(); } } // or specializing if in the second half else if (i >= ( n / 2 )) { // Simulating a coin flip flip = Math.random() >= 0.5 ? 1 : 0; // Substituting a character if (flip && !hasSub) { replace.forEach(sub); } // Adding a character if (flip && !hasExtra) { word += extra[Math.floor(Math.random() * eth)]; hasExtra = true; } } result += word; } if (!hasSub) { result += subs[Math.floor(Math.random() * rth)]; } if (!hasExtra) { result += extra[Math.floor(Math.random() * eth)]; } } return result; }
[ "function", "password", "(", "n", ",", "special", ")", "{", "n", "=", "n", "||", "3", ";", "special", "=", "special", "===", "true", ";", "var", "result", "=", "\"\"", ",", "i", "=", "-", "1", ",", "used", "=", "{", "}", ",", "hasSub", "=", "false", ",", "hasExtra", "=", "false", ",", "flip", ",", "lth", ",", "pos", ",", "rnd", ",", "word", ";", "function", "sub", "(", "x", ",", "idx", ")", "{", "if", "(", "!", "hasSub", "&&", "word", ".", "indexOf", "(", "x", ")", ">", "-", "1", ")", "{", "word", "=", "word", ".", "replace", "(", "x", ",", "subs", "[", "idx", "]", ")", ";", "hasSub", "=", "true", ";", "flip", "=", "false", ";", "}", "}", "if", "(", "!", "special", ")", "{", "while", "(", "++", "i", "<", "n", ")", "{", "result", "+=", "words", "[", "random", "(", "nth", ",", "used", ")", "]", ";", "}", "}", "else", "{", "rnd", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "n", ")", ";", "while", "(", "++", "i", "<", "n", ")", "{", "word", "=", "words", "[", "random", "(", "nth", ",", "used", ")", "]", ";", "// Capitalizing a letter in a word", "if", "(", "i", "===", "rnd", ")", "{", "lth", "=", "word", ".", "length", ";", "pos", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "lth", ")", ";", "if", "(", "pos", "===", "0", ")", "{", "word", "=", "word", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "word", ".", "slice", "(", "1", ")", ";", "}", "else", "if", "(", "pos", "<", "lth", "-", "1", ")", "{", "word", "=", "word", ".", "slice", "(", "0", ",", "pos", ")", "+", "word", ".", "charAt", "(", "pos", ")", ".", "toUpperCase", "(", ")", "+", "word", ".", "slice", "(", "pos", "+", "1", ",", "lth", ")", ";", "}", "else", "{", "word", "=", "word", ".", "slice", "(", "0", ",", "pos", ")", "+", "word", ".", "charAt", "(", "pos", ")", ".", "toUpperCase", "(", ")", ";", "}", "}", "// or specializing if in the second half", "else", "if", "(", "i", ">=", "(", "n", "/", "2", ")", ")", "{", "// Simulating a coin flip", "flip", "=", "Math", ".", "random", "(", ")", ">=", "0.5", "?", "1", ":", "0", ";", "// Substituting a character", "if", "(", "flip", "&&", "!", "hasSub", ")", "{", "replace", ".", "forEach", "(", "sub", ")", ";", "}", "// Adding a character", "if", "(", "flip", "&&", "!", "hasExtra", ")", "{", "word", "+=", "extra", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "eth", ")", "]", ";", "hasExtra", "=", "true", ";", "}", "}", "result", "+=", "word", ";", "}", "if", "(", "!", "hasSub", ")", "{", "result", "+=", "subs", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "rth", ")", "]", ";", "}", "if", "(", "!", "hasExtra", ")", "{", "result", "+=", "extra", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "eth", ")", "]", ";", "}", "}", "return", "result", ";", "}" ]
Mnemonic password generator @method password @param {Number} n Number of words to use (3) @param {Boolean} special Use special characters (false) @return {String} Password
[ "Mnemonic", "password", "generator" ]
3881af71808c1eba55a9f0525c919f0491e949cb
https://github.com/avoidwork/mpass/blob/3881af71808c1eba55a9f0525c919f0491e949cb/src/password.js#L9-L80
48,976
yoshuawuyts/size-stream
index.js
CountStream
function CountStream (opts) { if (!(this instanceof CountStream)) return new CountStream(opts) stream.PassThrough.call(this, opts) this.destroyed = false this.size = 0 }
javascript
function CountStream (opts) { if (!(this instanceof CountStream)) return new CountStream(opts) stream.PassThrough.call(this, opts) this.destroyed = false this.size = 0 }
[ "function", "CountStream", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "CountStream", ")", ")", "return", "new", "CountStream", "(", "opts", ")", "stream", ".", "PassThrough", ".", "call", "(", "this", ",", "opts", ")", "this", ".", "destroyed", "=", "false", "this", ".", "size", "=", "0", "}" ]
create a new count stream obj? -> tstream
[ "create", "a", "new", "count", "stream", "obj?", "-", ">", "tstream" ]
ecd21e639e73e404c789201bd6dde4250fc7938a
https://github.com/yoshuawuyts/size-stream/blob/ecd21e639e73e404c789201bd6dde4250fc7938a/index.js#L8-L14
48,977
defunctzombie/node-superstack
index.js
function(stack) { if (exports.async_trace_limit <= 0) { return; } var count = exports.async_trace_limit - 1; var previous = stack; while (previous && count > 1) { previous = previous.__previous__; --count; } if (previous) { delete previous.__previous__; } }
javascript
function(stack) { if (exports.async_trace_limit <= 0) { return; } var count = exports.async_trace_limit - 1; var previous = stack; while (previous && count > 1) { previous = previous.__previous__; --count; } if (previous) { delete previous.__previous__; } }
[ "function", "(", "stack", ")", "{", "if", "(", "exports", ".", "async_trace_limit", "<=", "0", ")", "{", "return", ";", "}", "var", "count", "=", "exports", ".", "async_trace_limit", "-", "1", ";", "var", "previous", "=", "stack", ";", "while", "(", "previous", "&&", "count", ">", "1", ")", "{", "previous", "=", "previous", ".", "__previous__", ";", "--", "count", ";", "}", "if", "(", "previous", ")", "{", "delete", "previous", ".", "__previous__", ";", "}", "}" ]
truncate frames to async_trace_limit
[ "truncate", "frames", "to", "async_trace_limit" ]
9ae6996a10b2e97ac2327a3e1e484839689c11ec
https://github.com/defunctzombie/node-superstack/blob/9ae6996a10b2e97ac2327a3e1e484839689c11ec/index.js#L70-L86
48,978
defunctzombie/node-superstack
index.js
function(callback) { // capture current error location var trace_error = new Error(); trace_error.id = ERROR_ID++; trace_error.__previous__ = current_trace_error; trace_error.__trace_count__ = current_trace_error ? current_trace_error.__trace_count__ + 1 : 1; limit_frames(trace_error); var new_callback = function() { current_trace_error = trace_error; trace_error = null; var res = callback.apply(this, arguments); current_trace_error = null; return res; }; new_callback.__original_callback__ = callback; return new_callback; }
javascript
function(callback) { // capture current error location var trace_error = new Error(); trace_error.id = ERROR_ID++; trace_error.__previous__ = current_trace_error; trace_error.__trace_count__ = current_trace_error ? current_trace_error.__trace_count__ + 1 : 1; limit_frames(trace_error); var new_callback = function() { current_trace_error = trace_error; trace_error = null; var res = callback.apply(this, arguments); current_trace_error = null; return res; }; new_callback.__original_callback__ = callback; return new_callback; }
[ "function", "(", "callback", ")", "{", "// capture current error location", "var", "trace_error", "=", "new", "Error", "(", ")", ";", "trace_error", ".", "id", "=", "ERROR_ID", "++", ";", "trace_error", ".", "__previous__", "=", "current_trace_error", ";", "trace_error", ".", "__trace_count__", "=", "current_trace_error", "?", "current_trace_error", ".", "__trace_count__", "+", "1", ":", "1", ";", "limit_frames", "(", "trace_error", ")", ";", "var", "new_callback", "=", "function", "(", ")", "{", "current_trace_error", "=", "trace_error", ";", "trace_error", "=", "null", ";", "var", "res", "=", "callback", ".", "apply", "(", "this", ",", "arguments", ")", ";", "current_trace_error", "=", "null", ";", "return", "res", ";", "}", ";", "new_callback", ".", "__original_callback__", "=", "callback", ";", "return", "new_callback", ";", "}" ]
wrap a callback to capture any error or throw and thus the stacktrace
[ "wrap", "a", "callback", "to", "capture", "any", "error", "or", "throw", "and", "thus", "the", "stacktrace" ]
9ae6996a10b2e97ac2327a3e1e484839689c11ec
https://github.com/defunctzombie/node-superstack/blob/9ae6996a10b2e97ac2327a3e1e484839689c11ec/index.js#L89-L105
48,979
francois2metz/node-intervals
bin/cli.js
addTime
function addTime(options, client) { return function(next, project) { var dates = options.dates; delete options.dates; var join = futures.join(); join.add(dates.map(function(date) { var promise = futures.future(); // we must clone to prevent options.date override var opts = utils.clone(options); opts.date = date; var message = ('Save '+ opts.time + ' ' + (opts.billable ? 'billable' : 'non billable') + ' hours for '+ opts.date); intervals.addTime(project, opts, client, function (err, res) { var msg = 'OK'; if (err) { msg = 'ERROR'; console.error(err); } else if (res.status != 201) { msg = 'ERROR'; console.error('Unexpected status '+ res.status +' for addTime method'); }; console.log(message + ' ' + msg); promise.deliver(); }); return promise; })); join.when(function() { next(project); }); }; }
javascript
function addTime(options, client) { return function(next, project) { var dates = options.dates; delete options.dates; var join = futures.join(); join.add(dates.map(function(date) { var promise = futures.future(); // we must clone to prevent options.date override var opts = utils.clone(options); opts.date = date; var message = ('Save '+ opts.time + ' ' + (opts.billable ? 'billable' : 'non billable') + ' hours for '+ opts.date); intervals.addTime(project, opts, client, function (err, res) { var msg = 'OK'; if (err) { msg = 'ERROR'; console.error(err); } else if (res.status != 201) { msg = 'ERROR'; console.error('Unexpected status '+ res.status +' for addTime method'); }; console.log(message + ' ' + msg); promise.deliver(); }); return promise; })); join.when(function() { next(project); }); }; }
[ "function", "addTime", "(", "options", ",", "client", ")", "{", "return", "function", "(", "next", ",", "project", ")", "{", "var", "dates", "=", "options", ".", "dates", ";", "delete", "options", ".", "dates", ";", "var", "join", "=", "futures", ".", "join", "(", ")", ";", "join", ".", "add", "(", "dates", ".", "map", "(", "function", "(", "date", ")", "{", "var", "promise", "=", "futures", ".", "future", "(", ")", ";", "// we must clone to prevent options.date override", "var", "opts", "=", "utils", ".", "clone", "(", "options", ")", ";", "opts", ".", "date", "=", "date", ";", "var", "message", "=", "(", "'Save '", "+", "opts", ".", "time", "+", "' '", "+", "(", "opts", ".", "billable", "?", "'billable'", ":", "'non billable'", ")", "+", "' hours for '", "+", "opts", ".", "date", ")", ";", "intervals", ".", "addTime", "(", "project", ",", "opts", ",", "client", ",", "function", "(", "err", ",", "res", ")", "{", "var", "msg", "=", "'OK'", ";", "if", "(", "err", ")", "{", "msg", "=", "'ERROR'", ";", "console", ".", "error", "(", "err", ")", ";", "}", "else", "if", "(", "res", ".", "status", "!=", "201", ")", "{", "msg", "=", "'ERROR'", ";", "console", ".", "error", "(", "'Unexpected status '", "+", "res", ".", "status", "+", "' for addTime method'", ")", ";", "}", ";", "console", ".", "log", "(", "message", "+", "' '", "+", "msg", ")", ";", "promise", ".", "deliver", "(", ")", ";", "}", ")", ";", "return", "promise", ";", "}", ")", ")", ";", "join", ".", "when", "(", "function", "(", ")", "{", "next", "(", "project", ")", ";", "}", ")", ";", "}", ";", "}" ]
Add time for each dates specified
[ "Add", "time", "for", "each", "dates", "specified" ]
0633747156f02938ce4d8063e1fed8a33beab365
https://github.com/francois2metz/node-intervals/blob/0633747156f02938ce4d8063e1fed8a33beab365/bin/cli.js#L16-L42
48,980
francois2metz/node-intervals
bin/cli.js
askForSave
function askForSave(conf) { return function(next, project) { process.stdout.write('Do you yant to save this project combinaison: (y/N)'); utils.readInput(function(input) { if (input == 'y') { process.stdout.write('Name of this combinaison: '); utils.readInput(function(input) { conf.projects ? '': conf.projects = []; project.name = input; conf.projects.push(project); config.write(conf, function(err) { if (err) throw err; console.log('ok. You can add time to this combinaison with intervals --project '+ input); next(); }) }); } else { next(); } }); } }
javascript
function askForSave(conf) { return function(next, project) { process.stdout.write('Do you yant to save this project combinaison: (y/N)'); utils.readInput(function(input) { if (input == 'y') { process.stdout.write('Name of this combinaison: '); utils.readInput(function(input) { conf.projects ? '': conf.projects = []; project.name = input; conf.projects.push(project); config.write(conf, function(err) { if (err) throw err; console.log('ok. You can add time to this combinaison with intervals --project '+ input); next(); }) }); } else { next(); } }); } }
[ "function", "askForSave", "(", "conf", ")", "{", "return", "function", "(", "next", ",", "project", ")", "{", "process", ".", "stdout", ".", "write", "(", "'Do you yant to save this project combinaison: (y/N)'", ")", ";", "utils", ".", "readInput", "(", "function", "(", "input", ")", "{", "if", "(", "input", "==", "'y'", ")", "{", "process", ".", "stdout", ".", "write", "(", "'Name of this combinaison: '", ")", ";", "utils", ".", "readInput", "(", "function", "(", "input", ")", "{", "conf", ".", "projects", "?", "''", ":", "conf", ".", "projects", "=", "[", "]", ";", "project", ".", "name", "=", "input", ";", "conf", ".", "projects", ".", "push", "(", "project", ")", ";", "config", ".", "write", "(", "conf", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "console", ".", "log", "(", "'ok. You can add time to this combinaison with intervals --project '", "+", "input", ")", ";", "next", "(", ")", ";", "}", ")", "}", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
Ask user to save the project
[ "Ask", "user", "to", "save", "the", "project" ]
0633747156f02938ce4d8063e1fed8a33beab365
https://github.com/francois2metz/node-intervals/blob/0633747156f02938ce4d8063e1fed8a33beab365/bin/cli.js#L68-L89
48,981
francois2metz/node-intervals
bin/cli.js
optionsFrom
function optionsFrom(argv) { var date = argv.date, dates = utils.parseDate(date), options = { time: argv.hours, dates: dates, billable: argv.billable || argv.b, description: argv.description }; return options; }
javascript
function optionsFrom(argv) { var date = argv.date, dates = utils.parseDate(date), options = { time: argv.hours, dates: dates, billable: argv.billable || argv.b, description: argv.description }; return options; }
[ "function", "optionsFrom", "(", "argv", ")", "{", "var", "date", "=", "argv", ".", "date", ",", "dates", "=", "utils", ".", "parseDate", "(", "date", ")", ",", "options", "=", "{", "time", ":", "argv", ".", "hours", ",", "dates", ":", "dates", ",", "billable", ":", "argv", ".", "billable", "||", "argv", ".", "b", ",", "description", ":", "argv", ".", "description", "}", ";", "return", "options", ";", "}" ]
Extract options from argv
[ "Extract", "options", "from", "argv" ]
0633747156f02938ce4d8063e1fed8a33beab365
https://github.com/francois2metz/node-intervals/blob/0633747156f02938ce4d8063e1fed8a33beab365/bin/cli.js#L94-L102
48,982
singulargarden/firebase-scheduler
functions/index.js
reqURL
function reqURL(req, newPath) { return url.format({ protocol: 'https', //req.protocol, // by default this returns http which gets redirected host: req.get('host'), pathname: newPath }) }
javascript
function reqURL(req, newPath) { return url.format({ protocol: 'https', //req.protocol, // by default this returns http which gets redirected host: req.get('host'), pathname: newPath }) }
[ "function", "reqURL", "(", "req", ",", "newPath", ")", "{", "return", "url", ".", "format", "(", "{", "protocol", ":", "'https'", ",", "//req.protocol, // by default this returns http which gets redirected", "host", ":", "req", ".", "get", "(", "'host'", ")", ",", "pathname", ":", "newPath", "}", ")", "}" ]
Retrieve the URL for another endpoint running on the same server, on https. @param req The express/firebase function request object @param newPath The endpoint @returns {string} The URL
[ "Retrieve", "the", "URL", "for", "another", "endpoint", "running", "on", "the", "same", "server", "on", "https", "." ]
0b6e46b5987cac16289a747c4bca5bd748397ee8
https://github.com/singulargarden/firebase-scheduler/blob/0b6e46b5987cac16289a747c4bca5bd748397ee8/functions/index.js#L27-L33
48,983
rmdort/react-kitt
src/components/Tooltip/index.js
ToolTip
function ToolTip({ className, children, label, position, type }) { const classes = cx( tooltipClassName, `${tooltipClassName}--${position}`, `${tooltipClassName}--${type}`, className ) return ( <button role="tooltip" type="button" className={classes} aria-label={label}> {children} </button> ) }
javascript
function ToolTip({ className, children, label, position, type }) { const classes = cx( tooltipClassName, `${tooltipClassName}--${position}`, `${tooltipClassName}--${type}`, className ) return ( <button role="tooltip" type="button" className={classes} aria-label={label}> {children} </button> ) }
[ "function", "ToolTip", "(", "{", "className", ",", "children", ",", "label", ",", "position", ",", "type", "}", ")", "{", "const", "classes", "=", "cx", "(", "tooltipClassName", ",", "`", "${", "tooltipClassName", "}", "${", "position", "}", "`", ",", "`", "${", "tooltipClassName", "}", "${", "type", "}", "`", ",", "className", ")", "return", "(", "<", "button", "role", "=", "\"tooltip\"", "type", "=", "\"button\"", "className", "=", "{", "classes", "}", "aria-label", "=", "{", "label", "}", ">", "\n ", "{", "children", "}", "\n ", "<", "/", "button", ">", ")", "}" ]
Render tooltips using `hint.css` https://github.com/chinchang/hint.css/
[ "Render", "tooltips", "using", "hint", ".", "css" ]
a3dc0ef1451a84b8f7bed1f86dd0f3db26e8ff31
https://github.com/rmdort/react-kitt/blob/a3dc0ef1451a84b8f7bed1f86dd0f3db26e8ff31/src/components/Tooltip/index.js#L12-L24
48,984
aaronabramov/esfmt
package/block.js
format
function format(node, context, recur) { var blockComments = context.blockComments(node); for (var i = 0; i < node.body.length; i++) { var previous = node.body[i - 1]; var current = node.body[i]; var next = node.body[i + 1]; if (current.type === 'EmptyStatement') { continue;} if (newlines.extraNewLineBetween(previous, current)) { context.write('\n');} context.write(blockComments.printLeading(current, previous)); context.write(context.getIndent()); recur(current); context.write(utils.getLineTerminator(current)); context.write(blockComments.printTrailing(current, previous, next)); if (next) { context.write('\n');}}}
javascript
function format(node, context, recur) { var blockComments = context.blockComments(node); for (var i = 0; i < node.body.length; i++) { var previous = node.body[i - 1]; var current = node.body[i]; var next = node.body[i + 1]; if (current.type === 'EmptyStatement') { continue;} if (newlines.extraNewLineBetween(previous, current)) { context.write('\n');} context.write(blockComments.printLeading(current, previous)); context.write(context.getIndent()); recur(current); context.write(utils.getLineTerminator(current)); context.write(blockComments.printTrailing(current, previous, next)); if (next) { context.write('\n');}}}
[ "function", "format", "(", "node", ",", "context", ",", "recur", ")", "{", "var", "blockComments", "=", "context", ".", "blockComments", "(", "node", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "node", ".", "body", ".", "length", ";", "i", "++", ")", "{", "var", "previous", "=", "node", ".", "body", "[", "i", "-", "1", "]", ";", "var", "current", "=", "node", ".", "body", "[", "i", "]", ";", "var", "next", "=", "node", ".", "body", "[", "i", "+", "1", "]", ";", "if", "(", "current", ".", "type", "===", "'EmptyStatement'", ")", "{", "continue", ";", "}", "if", "(", "newlines", ".", "extraNewLineBetween", "(", "previous", ",", "current", ")", ")", "{", "context", ".", "write", "(", "'\\n'", ")", ";", "}", "context", ".", "write", "(", "blockComments", ".", "printLeading", "(", "current", ",", "previous", ")", ")", ";", "context", ".", "write", "(", "context", ".", "getIndent", "(", ")", ")", ";", "recur", "(", "current", ")", ";", "context", ".", "write", "(", "utils", ".", "getLineTerminator", "(", "current", ")", ")", ";", "context", ".", "write", "(", "blockComments", ".", "printTrailing", "(", "current", ",", "previous", ",", "next", ")", ")", ";", "if", "(", "next", ")", "{", "context", ".", "write", "(", "'\\n'", ")", ";", "}", "}", "}" ]
Shared block formatting function @param {Object} node Program or BlockStatement @param {Object} context @param {Function} recur
[ "Shared", "block", "formatting", "function" ]
8e05fa01d777d504f965ba484c287139a00b5b00
https://github.com/aaronabramov/esfmt/blob/8e05fa01d777d504f965ba484c287139a00b5b00/package/block.js#L11-L34
48,985
kuno/neco
deps/npm/lib/view.js
showFields
function showFields (data, version, fields) { var o = {} ;[data,version].forEach(function (s) { Object.keys(s).forEach(function (k) { o[k] = s[k] }) }) return search(o, fields.split("."), version._id, fields) }
javascript
function showFields (data, version, fields) { var o = {} ;[data,version].forEach(function (s) { Object.keys(s).forEach(function (k) { o[k] = s[k] }) }) return search(o, fields.split("."), version._id, fields) }
[ "function", "showFields", "(", "data", ",", "version", ",", "fields", ")", "{", "var", "o", "=", "{", "}", ";", "[", "data", ",", "version", "]", ".", "forEach", "(", "function", "(", "s", ")", "{", "Object", ".", "keys", "(", "s", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "o", "[", "k", "]", "=", "s", "[", "k", "]", "}", ")", "}", ")", "return", "search", "(", "o", ",", "fields", ".", "split", "(", "\".\"", ")", ",", "version", ".", "_id", ",", "fields", ")", "}" ]
return whatever was printed
[ "return", "whatever", "was", "printed" ]
cf6361c1fcb9466c6b2ab3b127b5d0160ca50735
https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/view.js#L85-L93
48,986
MartinKolarik/ractive-render
lib/utils.js
findPartials
function findPartials(fragment) { var found = []; walkRecursive(fragment.t, function(item) { if (item.t === 8) { found.push(item.r); } }); return _.uniq(found); }
javascript
function findPartials(fragment) { var found = []; walkRecursive(fragment.t, function(item) { if (item.t === 8) { found.push(item.r); } }); return _.uniq(found); }
[ "function", "findPartials", "(", "fragment", ")", "{", "var", "found", "=", "[", "]", ";", "walkRecursive", "(", "fragment", ".", "t", ",", "function", "(", "item", ")", "{", "if", "(", "item", ".", "t", "===", "8", ")", "{", "found", ".", "push", "(", "item", ".", "r", ")", ";", "}", "}", ")", ";", "return", "_", ".", "uniq", "(", "found", ")", ";", "}" ]
Return a list of all partials used in the given template @param {Array|Object} fragment @returns {Array|Object} @private
[ "Return", "a", "list", "of", "all", "partials", "used", "in", "the", "given", "template" ]
417a97c42de4b1ea6c1ab13803f5470b3cc6f75a
https://github.com/MartinKolarik/ractive-render/blob/417a97c42de4b1ea6c1ab13803f5470b3cc6f75a/lib/utils.js#L163-L173
48,987
Raynos/serve-browserify
index.js
function (location, opts, callback) { resolve(location, function (err, fileUri) { if (err) { return callback(err) } bundle(fileUri, opts, callback) }) }
javascript
function (location, opts, callback) { resolve(location, function (err, fileUri) { if (err) { return callback(err) } bundle(fileUri, opts, callback) }) }
[ "function", "(", "location", ",", "opts", ",", "callback", ")", "{", "resolve", "(", "location", ",", "function", "(", "err", ",", "fileUri", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", "}", "bundle", "(", "fileUri", ",", "opts", ",", "callback", ")", "}", ")", "}" ]
this is the function to compile the resource. the location is the value returned by findResource you should pass a String to the callback
[ "this", "is", "the", "function", "to", "compile", "the", "resource", ".", "the", "location", "is", "the", "value", "returned", "by", "findResource", "you", "should", "pass", "a", "String", "to", "the", "callback" ]
a57baf3524b8b366dd9f1e8cffcb4467c914fe3a
https://github.com/Raynos/serve-browserify/blob/a57baf3524b8b366dd9f1e8cffcb4467c914fe3a/index.js#L13-L21
48,988
Raynos/serve-browserify
index.js
sendError
function sendError(req, res, err) { return res.end("(" + function (err) { throw new Error(err) } + "(" + JSON.stringify(err.message) + "))") }
javascript
function sendError(req, res, err) { return res.end("(" + function (err) { throw new Error(err) } + "(" + JSON.stringify(err.message) + "))") }
[ "function", "sendError", "(", "req", ",", "res", ",", "err", ")", "{", "return", "res", ".", "end", "(", "\"(\"", "+", "function", "(", "err", ")", "{", "throw", "new", "Error", "(", "err", ")", "}", "+", "\"(\"", "+", "JSON", ".", "stringify", "(", "err", ".", "message", ")", "+", "\"))\"", ")", "}" ]
This is the logic of how to display errors to the user
[ "This", "is", "the", "logic", "of", "how", "to", "display", "errors", "to", "the", "user" ]
a57baf3524b8b366dd9f1e8cffcb4467c914fe3a
https://github.com/Raynos/serve-browserify/blob/a57baf3524b8b366dd9f1e8cffcb4467c914fe3a/index.js#L23-L27
48,989
ragingwind/eddystone-beacon-config
eddystone-characteristics.js
ByteCharateristic
function ByteCharateristic(opts) { ByteCharateristic.super_.call(this, opts); this.on('beforeWrite', function(data, res) { res(data.length == opts.sizeof ? Results.Success : Results.InvalidAttributeLength); }); this.toBuffer = byte2buf(opts.sizeof); this.fromBuffer = buf2byte(opts.sizeof); }
javascript
function ByteCharateristic(opts) { ByteCharateristic.super_.call(this, opts); this.on('beforeWrite', function(data, res) { res(data.length == opts.sizeof ? Results.Success : Results.InvalidAttributeLength); }); this.toBuffer = byte2buf(opts.sizeof); this.fromBuffer = buf2byte(opts.sizeof); }
[ "function", "ByteCharateristic", "(", "opts", ")", "{", "ByteCharateristic", ".", "super_", ".", "call", "(", "this", ",", "opts", ")", ";", "this", ".", "on", "(", "'beforeWrite'", ",", "function", "(", "data", ",", "res", ")", "{", "res", "(", "data", ".", "length", "==", "opts", ".", "sizeof", "?", "Results", ".", "Success", ":", "Results", ".", "InvalidAttributeLength", ")", ";", "}", ")", ";", "this", ".", "toBuffer", "=", "byte2buf", "(", "opts", ".", "sizeof", ")", ";", "this", ".", "fromBuffer", "=", "buf2byte", "(", "opts", ".", "sizeof", ")", ";", "}" ]
characteristics for byte data
[ "characteristics", "for", "byte", "data" ]
0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b
https://github.com/ragingwind/eddystone-beacon-config/blob/0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b/eddystone-characteristics.js#L114-L123
48,990
ragingwind/eddystone-beacon-config
eddystone-characteristics.js
LockStateCharateristic
function LockStateCharateristic(opts) { LockStateCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2081-8786-40ba-ab96-99b91ac981d8', properties: ['read'], sizeof: 1 }, opts)); }
javascript
function LockStateCharateristic(opts) { LockStateCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2081-8786-40ba-ab96-99b91ac981d8', properties: ['read'], sizeof: 1 }, opts)); }
[ "function", "LockStateCharateristic", "(", "opts", ")", "{", "LockStateCharateristic", ".", "super_", ".", "call", "(", "this", ",", "objectAssign", "(", "{", "uuid", ":", "'ee0c2081-8786-40ba-ab96-99b91ac981d8'", ",", "properties", ":", "[", "'read'", "]", ",", "sizeof", ":", "1", "}", ",", "opts", ")", ")", ";", "}" ]
lock state characteristic
[ "lock", "state", "characteristic" ]
0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b
https://github.com/ragingwind/eddystone-beacon-config/blob/0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b/eddystone-characteristics.js#L128-L134
48,991
ragingwind/eddystone-beacon-config
eddystone-characteristics.js
TxPowerLevelCharateristic
function TxPowerLevelCharateristic(opts) { TxPowerLevelCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2084-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], }, opts)); this.on('beforeWrite', function(data, res) { res(data.length == 4 ? Results.Success : Results.InvalidAttributeLength); }); this.toBuffer = arr2buf; this.fromBuffer = buf2arr; }
javascript
function TxPowerLevelCharateristic(opts) { TxPowerLevelCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2084-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], }, opts)); this.on('beforeWrite', function(data, res) { res(data.length == 4 ? Results.Success : Results.InvalidAttributeLength); }); this.toBuffer = arr2buf; this.fromBuffer = buf2arr; }
[ "function", "TxPowerLevelCharateristic", "(", "opts", ")", "{", "TxPowerLevelCharateristic", ".", "super_", ".", "call", "(", "this", ",", "objectAssign", "(", "{", "uuid", ":", "'ee0c2084-8786-40ba-ab96-99b91ac981d8'", ",", "properties", ":", "[", "'read'", ",", "'write'", "]", ",", "}", ",", "opts", ")", ")", ";", "this", ".", "on", "(", "'beforeWrite'", ",", "function", "(", "data", ",", "res", ")", "{", "res", "(", "data", ".", "length", "==", "4", "?", "Results", ".", "Success", ":", "Results", ".", "InvalidAttributeLength", ")", ";", "}", ")", ";", "this", ".", "toBuffer", "=", "arr2buf", ";", "this", ".", "fromBuffer", "=", "buf2arr", ";", "}" ]
tx power characteristic
[ "tx", "power", "characteristic" ]
0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b
https://github.com/ragingwind/eddystone-beacon-config/blob/0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b/eddystone-characteristics.js#L187-L199
48,992
ragingwind/eddystone-beacon-config
eddystone-characteristics.js
TxPowerModeCharateristic
function TxPowerModeCharateristic(opts) { TxPowerModeCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2087-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], sizeof: 1 }, opts)); this.removeAllListeners('beforeWrite'); this.on('beforeWrite', function(data, res) { var err = Results.Success; var value = this.fromBuffer(data); if (data.length !== 1) { err = Results.InvalidAttributeLength; } else if (value < TxPowerMode.Lowest || value > TxPowerMode.High) { err = Results.WriteNotPermitted; } res(err); }); }
javascript
function TxPowerModeCharateristic(opts) { TxPowerModeCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2087-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], sizeof: 1 }, opts)); this.removeAllListeners('beforeWrite'); this.on('beforeWrite', function(data, res) { var err = Results.Success; var value = this.fromBuffer(data); if (data.length !== 1) { err = Results.InvalidAttributeLength; } else if (value < TxPowerMode.Lowest || value > TxPowerMode.High) { err = Results.WriteNotPermitted; } res(err); }); }
[ "function", "TxPowerModeCharateristic", "(", "opts", ")", "{", "TxPowerModeCharateristic", ".", "super_", ".", "call", "(", "this", ",", "objectAssign", "(", "{", "uuid", ":", "'ee0c2087-8786-40ba-ab96-99b91ac981d8'", ",", "properties", ":", "[", "'read'", ",", "'write'", "]", ",", "sizeof", ":", "1", "}", ",", "opts", ")", ")", ";", "this", ".", "removeAllListeners", "(", "'beforeWrite'", ")", ";", "this", ".", "on", "(", "'beforeWrite'", ",", "function", "(", "data", ",", "res", ")", "{", "var", "err", "=", "Results", ".", "Success", ";", "var", "value", "=", "this", ".", "fromBuffer", "(", "data", ")", ";", "if", "(", "data", ".", "length", "!==", "1", ")", "{", "err", "=", "Results", ".", "InvalidAttributeLength", ";", "}", "else", "if", "(", "value", "<", "TxPowerMode", ".", "Lowest", "||", "value", ">", "TxPowerMode", ".", "High", ")", "{", "err", "=", "Results", ".", "WriteNotPermitted", ";", "}", "res", "(", "err", ")", ";", "}", ")", ";", "}" ]
tx power mode characteristic
[ "tx", "power", "mode", "characteristic" ]
0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b
https://github.com/ragingwind/eddystone-beacon-config/blob/0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b/eddystone-characteristics.js#L204-L224
48,993
ragingwind/eddystone-beacon-config
eddystone-characteristics.js
BeaconPeriodCharateristic
function BeaconPeriodCharateristic(opts) { BeaconPeriodCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2088-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], sizeof: 2 }, opts)); }
javascript
function BeaconPeriodCharateristic(opts) { BeaconPeriodCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2088-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], sizeof: 2 }, opts)); }
[ "function", "BeaconPeriodCharateristic", "(", "opts", ")", "{", "BeaconPeriodCharateristic", ".", "super_", ".", "call", "(", "this", ",", "objectAssign", "(", "{", "uuid", ":", "'ee0c2088-8786-40ba-ab96-99b91ac981d8'", ",", "properties", ":", "[", "'read'", ",", "'write'", "]", ",", "sizeof", ":", "2", "}", ",", "opts", ")", ")", ";", "}" ]
beacon period characteristic
[ "beacon", "period", "characteristic" ]
0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b
https://github.com/ragingwind/eddystone-beacon-config/blob/0ccc4ade7732f1cbe1740a591d50fb91c2cb6e2b/eddystone-characteristics.js#L229-L235
48,994
gummesson/get-browser-language
index.js
getBrowserLanguage
function getBrowserLanguage() { var first = window.navigator.languages ? window.navigator.languages[0] : null var lang = first || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage return lang }
javascript
function getBrowserLanguage() { var first = window.navigator.languages ? window.navigator.languages[0] : null var lang = first || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage return lang }
[ "function", "getBrowserLanguage", "(", ")", "{", "var", "first", "=", "window", ".", "navigator", ".", "languages", "?", "window", ".", "navigator", ".", "languages", "[", "0", "]", ":", "null", "var", "lang", "=", "first", "||", "window", ".", "navigator", ".", "language", "||", "window", ".", "navigator", ".", "browserLanguage", "||", "window", ".", "navigator", ".", "userLanguage", "return", "lang", "}" ]
Get browser language. @return {String}
[ "Get", "browser", "language", "." ]
4669bc5fa2c5abd00a701a01ed7ef0e9fc1464c5
https://github.com/gummesson/get-browser-language/blob/4669bc5fa2c5abd00a701a01ed7ef0e9fc1464c5/index.js#L13-L24
48,995
bikramjeet/sanitation
sanitation.js
isPositiveIntegerArray
function isPositiveIntegerArray(value) { var success = true; for(var i = 0; i < value.length; i++) { if(!config.checkIntegerValue.test(value[i]) || parseInt(value[i]) <= 0) { success = false; break; } } return success; }
javascript
function isPositiveIntegerArray(value) { var success = true; for(var i = 0; i < value.length; i++) { if(!config.checkIntegerValue.test(value[i]) || parseInt(value[i]) <= 0) { success = false; break; } } return success; }
[ "function", "isPositiveIntegerArray", "(", "value", ")", "{", "var", "success", "=", "true", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "value", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "config", ".", "checkIntegerValue", ".", "test", "(", "value", "[", "i", "]", ")", "||", "parseInt", "(", "value", "[", "i", "]", ")", "<=", "0", ")", "{", "success", "=", "false", ";", "break", ";", "}", "}", "return", "success", ";", "}" ]
Validates the non-zero positive integer value from the array of strings and returns true for success. @method isPositiveInteger @param {Array} value The values to be tested.
[ "Validates", "the", "non", "-", "zero", "positive", "integer", "value", "from", "the", "array", "of", "strings", "and", "returns", "true", "for", "success", "." ]
af362d99c689ad1eb15cbd4639b346f3eac6cfb5
https://github.com/bikramjeet/sanitation/blob/af362d99c689ad1eb15cbd4639b346f3eac6cfb5/sanitation.js#L120-L129
48,996
bikramjeet/sanitation
sanitation.js
isValidDate
function isValidDate(dateString, dateFormat, returnDateFormat) { if(moment(dateString, dateFormat).format(dateFormat) !== dateString) { return false; } if(!moment(dateString, dateFormat).isValid()) { return false; } if(returnDateFormat) { return moment(dateString, dateFormat).format(returnDateFormat); } return true; }
javascript
function isValidDate(dateString, dateFormat, returnDateFormat) { if(moment(dateString, dateFormat).format(dateFormat) !== dateString) { return false; } if(!moment(dateString, dateFormat).isValid()) { return false; } if(returnDateFormat) { return moment(dateString, dateFormat).format(returnDateFormat); } return true; }
[ "function", "isValidDate", "(", "dateString", ",", "dateFormat", ",", "returnDateFormat", ")", "{", "if", "(", "moment", "(", "dateString", ",", "dateFormat", ")", ".", "format", "(", "dateFormat", ")", "!==", "dateString", ")", "{", "return", "false", ";", "}", "if", "(", "!", "moment", "(", "dateString", ",", "dateFormat", ")", ".", "isValid", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "returnDateFormat", ")", "{", "return", "moment", "(", "dateString", ",", "dateFormat", ")", ".", "format", "(", "returnDateFormat", ")", ";", "}", "return", "true", ";", "}" ]
Checks the date format along with valid date and convert to the expected format. @method isValidDate @param {String} dateString The date value to validate. @param {String} dateFormat The expected format of the date value. @param {String} [returnDateFormat] The expected date format after conversion as the return value.
[ "Checks", "the", "date", "format", "along", "with", "valid", "date", "and", "convert", "to", "the", "expected", "format", "." ]
af362d99c689ad1eb15cbd4639b346f3eac6cfb5
https://github.com/bikramjeet/sanitation/blob/af362d99c689ad1eb15cbd4639b346f3eac6cfb5/sanitation.js#L156-L167
48,997
bikramjeet/sanitation
sanitation.js
objValByStr
function objValByStr(name, separator, context) { var func, i, n, ns, _i, _len; if (!name || !separator || !context) { return null; } ns = name.split(separator); func = context; try { for (i = _i = 0, _len = ns.length; _i < _len; i = ++_i) { n = ns[i]; func = func[n]; } return func; } catch (e) { return e; } }
javascript
function objValByStr(name, separator, context) { var func, i, n, ns, _i, _len; if (!name || !separator || !context) { return null; } ns = name.split(separator); func = context; try { for (i = _i = 0, _len = ns.length; _i < _len; i = ++_i) { n = ns[i]; func = func[n]; } return func; } catch (e) { return e; } }
[ "function", "objValByStr", "(", "name", ",", "separator", ",", "context", ")", "{", "var", "func", ",", "i", ",", "n", ",", "ns", ",", "_i", ",", "_len", ";", "if", "(", "!", "name", "||", "!", "separator", "||", "!", "context", ")", "{", "return", "null", ";", "}", "ns", "=", "name", ".", "split", "(", "separator", ")", ";", "func", "=", "context", ";", "try", "{", "for", "(", "i", "=", "_i", "=", "0", ",", "_len", "=", "ns", ".", "length", ";", "_i", "<", "_len", ";", "i", "=", "++", "_i", ")", "{", "n", "=", "ns", "[", "i", "]", ";", "func", "=", "func", "[", "n", "]", ";", "}", "return", "func", ";", "}", "catch", "(", "e", ")", "{", "return", "e", ";", "}", "}" ]
Returns the value of the nested object based on string path and the separator provided. @param {String} name The path of the nested object structure to fetch the value. @param {String} separator The identifier to split the string to iterate over the JSON object keys. @param {Object} context The original nested JSON object.
[ "Returns", "the", "value", "of", "the", "nested", "object", "based", "on", "string", "path", "and", "the", "separator", "provided", "." ]
af362d99c689ad1eb15cbd4639b346f3eac6cfb5
https://github.com/bikramjeet/sanitation/blob/af362d99c689ad1eb15cbd4639b346f3eac6cfb5/sanitation.js#L175-L191
48,998
QuietWind/find-imports
lib/index.js
function (arrArg) { return arrArg.filter(function (elem, pos, arr) { return arr.indexOf(elem) === pos; }); }
javascript
function (arrArg) { return arrArg.filter(function (elem, pos, arr) { return arr.indexOf(elem) === pos; }); }
[ "function", "(", "arrArg", ")", "{", "return", "arrArg", ".", "filter", "(", "function", "(", "elem", ",", "pos", ",", "arr", ")", "{", "return", "arr", ".", "indexOf", "(", "elem", ")", "===", "pos", ";", "}", ")", ";", "}" ]
clear memory data
[ "clear", "memory", "data" ]
f0ecef2ff8025abfe59fcb19539965717ecd08ab
https://github.com/QuietWind/find-imports/blob/f0ecef2ff8025abfe59fcb19539965717ecd08ab/lib/index.js#L16-L20
48,999
pwstegman/pw-csp
index.js
CSP
function CSP(class1, class2) { var cov1 = stat.cov(class1); var cov2 = stat.cov(class2); this.V = numeric.eig(math.multiply(math.inv(math.add(cov1, cov2)), cov1)).E.x; }
javascript
function CSP(class1, class2) { var cov1 = stat.cov(class1); var cov2 = stat.cov(class2); this.V = numeric.eig(math.multiply(math.inv(math.add(cov1, cov2)), cov1)).E.x; }
[ "function", "CSP", "(", "class1", ",", "class2", ")", "{", "var", "cov1", "=", "stat", ".", "cov", "(", "class1", ")", ";", "var", "cov2", "=", "stat", ".", "cov", "(", "class2", ")", ";", "this", ".", "V", "=", "numeric", ".", "eig", "(", "math", ".", "multiply", "(", "math", ".", "inv", "(", "math", ".", "add", "(", "cov1", ",", "cov2", ")", ")", ",", "cov1", ")", ")", ".", "E", ".", "x", ";", "}" ]
Creates a new CSP object @constructor @param {number[][]} class1 - Data samples for class 1. Rows should be samples, columns should be signals. @param {number[][]} class2 - Data samples for class 2. Rows should be samples, columns should be signals.
[ "Creates", "a", "new", "CSP", "object" ]
58b7a8bf7055c333fe02bb8e23443a55ddb084ca
https://github.com/pwstegman/pw-csp/blob/58b7a8bf7055c333fe02bb8e23443a55ddb084ca/index.js#L15-L19