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
19,400
riot/compiler
src/generators/template/utils.js
updateNodeScope
function updateNodeScope(path) { if (!isGlobal(path)) { replacePathScope(path, path.node) return false } this.traverse(path) }
javascript
function updateNodeScope(path) { if (!isGlobal(path)) { replacePathScope(path, path.node) return false } this.traverse(path) }
[ "function", "updateNodeScope", "(", "path", ")", "{", "if", "(", "!", "isGlobal", "(", "path", ")", ")", "{", "replacePathScope", "(", "path", ",", "path", ".", "node", ")", "return", "false", "}", "this", ".", "traverse", "(", "path", ")", "}" ]
Change the nodes scope adding the `scope` prefix @param { types.NodePath } path - containing the current node visited @returns { boolean } return false if we want to stop the tree traversal @context { types.visit }
[ "Change", "the", "nodes", "scope", "adding", "the", "scope", "prefix" ]
fa9cea9cf6b8a369e057c966c4e2698940a3fafc
https://github.com/riot/compiler/blob/fa9cea9cf6b8a369e057c966c4e2698940a3fafc/src/generators/template/utils.js#L86-L94
19,401
riot/compiler
src/generators/template/utils.js
visitMemberExpression
function visitMemberExpression(path) { if (!isGlobal({ node: path.node.object, scope: path.scope })) { replacePathScope(path, isThisExpression(path.node.object) ? path.node.property : path.node) } return false }
javascript
function visitMemberExpression(path) { if (!isGlobal({ node: path.node.object, scope: path.scope })) { replacePathScope(path, isThisExpression(path.node.object) ? path.node.property : path.node) } return false }
[ "function", "visitMemberExpression", "(", "path", ")", "{", "if", "(", "!", "isGlobal", "(", "{", "node", ":", "path", ".", "node", ".", "object", ",", "scope", ":", "path", ".", "scope", "}", ")", ")", "{", "replacePathScope", "(", "path", ",", "isThisExpression", "(", "path", ".", "node", ".", "object", ")", "?", "path", ".", "node", ".", "property", ":", "path", ".", "node", ")", "}", "return", "false", "}" ]
Change the scope of the member expressions @param { types.NodePath } path - containing the current node visited @returns { boolean } return always false because we want to check only the first node object
[ "Change", "the", "scope", "of", "the", "member", "expressions" ]
fa9cea9cf6b8a369e057c966c4e2698940a3fafc
https://github.com/riot/compiler/blob/fa9cea9cf6b8a369e057c966c4e2698940a3fafc/src/generators/template/utils.js#L101-L107
19,402
riot/compiler
src/generators/template/utils.js
visitProperty
function visitProperty(path) { const value = path.node.value if (isIdentifier(value)) { updateNodeScope(path.get('value')) } else { this.traverse(path.get('value')) } return false }
javascript
function visitProperty(path) { const value = path.node.value if (isIdentifier(value)) { updateNodeScope(path.get('value')) } else { this.traverse(path.get('value')) } return false }
[ "function", "visitProperty", "(", "path", ")", "{", "const", "value", "=", "path", ".", "node", ".", "value", "if", "(", "isIdentifier", "(", "value", ")", ")", "{", "updateNodeScope", "(", "path", ".", "get", "(", "'value'", ")", ")", "}", "else", "{", "this", ".", "traverse", "(", "path", ".", "get", "(", "'value'", ")", ")", "}", "return", "false", "}" ]
Objects properties should be handled a bit differently from the Identifier @param { types.NodePath } path - containing the current node visited @returns { boolean } return false if we want to stop the tree traversal
[ "Objects", "properties", "should", "be", "handled", "a", "bit", "differently", "from", "the", "Identifier" ]
fa9cea9cf6b8a369e057c966c4e2698940a3fafc
https://github.com/riot/compiler/blob/fa9cea9cf6b8a369e057c966c4e2698940a3fafc/src/generators/template/utils.js#L115-L125
19,403
riot/compiler
src/index.js
createMeta
function createMeta(source, options) { return { tagName: null, fragments: null, options: { ...DEFAULT_OPTIONS, ...options }, source } }
javascript
function createMeta(source, options) { return { tagName: null, fragments: null, options: { ...DEFAULT_OPTIONS, ...options }, source } }
[ "function", "createMeta", "(", "source", ",", "options", ")", "{", "return", "{", "tagName", ":", "null", ",", "fragments", ":", "null", ",", "options", ":", "{", "...", "DEFAULT_OPTIONS", ",", "...", "options", "}", ",", "source", "}", "}" ]
Create the compilation meta object @param { string } source - source code of the tag we will need to compile @param { string } options - compiling options @returns {Object} meta object
[ "Create", "the", "compilation", "meta", "object" ]
fa9cea9cf6b8a369e057c966c4e2698940a3fafc
https://github.com/riot/compiler/blob/fa9cea9cf6b8a369e057c966c4e2698940a3fafc/src/index.js#L80-L90
19,404
riot/compiler
src/index.js
hookGenerator
function hookGenerator(transformer, sourceNode, source, meta) { if ( // filter missing nodes !sourceNode || // filter nodes without children (sourceNode.nodes && !sourceNode.nodes.length) || // filter empty javascript and css nodes (!sourceNode.nodes && !sourceNode.text)) { return result => result } return curry(transformer)(sourceNode, source, meta) }
javascript
function hookGenerator(transformer, sourceNode, source, meta) { if ( // filter missing nodes !sourceNode || // filter nodes without children (sourceNode.nodes && !sourceNode.nodes.length) || // filter empty javascript and css nodes (!sourceNode.nodes && !sourceNode.text)) { return result => result } return curry(transformer)(sourceNode, source, meta) }
[ "function", "hookGenerator", "(", "transformer", ",", "sourceNode", ",", "source", ",", "meta", ")", "{", "if", "(", "// filter missing nodes", "!", "sourceNode", "||", "// filter nodes without children", "(", "sourceNode", ".", "nodes", "&&", "!", "sourceNode", ".", "nodes", ".", "length", ")", "||", "// filter empty javascript and css nodes", "(", "!", "sourceNode", ".", "nodes", "&&", "!", "sourceNode", ".", "text", ")", ")", "{", "return", "result", "=>", "result", "}", "return", "curry", "(", "transformer", ")", "(", "sourceNode", ",", "source", ",", "meta", ")", "}" ]
Prepare the riot parser node transformers @param { Function } transformer - transformer function @param { Object } sourceNode - riot parser node @param { string } source - component source code @param { Object } meta - compilation meta information @returns { Promise<Output> } object containing output code and source map
[ "Prepare", "the", "riot", "parser", "node", "transformers" ]
fa9cea9cf6b8a369e057c966c4e2698940a3fafc
https://github.com/riot/compiler/blob/fa9cea9cf6b8a369e057c966c4e2698940a3fafc/src/index.js#L142-L154
19,405
rbtech/css-purge
lib/css-purge.js
processHTML
function processHTML(cssSelectors = [], htmlDataIn = null, htmlOptionsIn = null) { //read html files if (OPTIONS.html !== '' && OPTIONS.html !== undefined && OPTIONS.special_reduce_with_html) { var htmlFiles = OPTIONS.html; tmpHTMLPaths = []; //check for file or files switch (typeof htmlFiles) { case 'object': case 'array': for (i = 0; i < htmlFiles.length; ++i) { getFilePaths(htmlFiles[i], ['.html','.htm']); } if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } break; case 'string': //formats htmlFiles = htmlFiles.replace(/ /g, ''); // comma delimited list - filename1.html, filename2.html if (htmlFiles.indexOf(',') > -1) { htmlFiles = htmlFiles.replace(/^\s+|\s+$/g,'').split(','); tmpStr = ''; for (i = 0; i < htmlFiles.length; ++i) { getFilePaths(htmlFiles[i], ['.html','.htm']); } //end of for if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } } else { //string path getFilePaths(htmlFiles, ['.html','.htm']); if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } } break; } //end of switch htmlFileLocation = (htmlFiles)?htmlFiles.toString():htmlFiles; readHTMLFile(htmlFiles); CPEVENTS.on('HTML_READ_AGAIN', function(){ //process selectors processHTMLSelectors(cssSelectors, htmlDataIn, htmlOptionsIn); //read next file dataHTMLIn = []; readHTMLFile(htmlFiles); }); CPEVENTS.on('HTML_READ_END', function(){ //process selectors processHTMLSelectors(cssSelectors, htmlDataIn, htmlOptionsIn); dataHTMLIn = []; CPEVENTS.emit('HTML_RESULTS_END', cssSelectors); }); } //end of html files check }
javascript
function processHTML(cssSelectors = [], htmlDataIn = null, htmlOptionsIn = null) { //read html files if (OPTIONS.html !== '' && OPTIONS.html !== undefined && OPTIONS.special_reduce_with_html) { var htmlFiles = OPTIONS.html; tmpHTMLPaths = []; //check for file or files switch (typeof htmlFiles) { case 'object': case 'array': for (i = 0; i < htmlFiles.length; ++i) { getFilePaths(htmlFiles[i], ['.html','.htm']); } if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } break; case 'string': //formats htmlFiles = htmlFiles.replace(/ /g, ''); // comma delimited list - filename1.html, filename2.html if (htmlFiles.indexOf(',') > -1) { htmlFiles = htmlFiles.replace(/^\s+|\s+$/g,'').split(','); tmpStr = ''; for (i = 0; i < htmlFiles.length; ++i) { getFilePaths(htmlFiles[i], ['.html','.htm']); } //end of for if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } } else { //string path getFilePaths(htmlFiles, ['.html','.htm']); if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } } break; } //end of switch htmlFileLocation = (htmlFiles)?htmlFiles.toString():htmlFiles; readHTMLFile(htmlFiles); CPEVENTS.on('HTML_READ_AGAIN', function(){ //process selectors processHTMLSelectors(cssSelectors, htmlDataIn, htmlOptionsIn); //read next file dataHTMLIn = []; readHTMLFile(htmlFiles); }); CPEVENTS.on('HTML_READ_END', function(){ //process selectors processHTMLSelectors(cssSelectors, htmlDataIn, htmlOptionsIn); dataHTMLIn = []; CPEVENTS.emit('HTML_RESULTS_END', cssSelectors); }); } //end of html files check }
[ "function", "processHTML", "(", "cssSelectors", "=", "[", "]", ",", "htmlDataIn", "=", "null", ",", "htmlOptionsIn", "=", "null", ")", "{", "//read html files", "if", "(", "OPTIONS", ".", "html", "!==", "''", "&&", "OPTIONS", ".", "html", "!==", "undefined", "&&", "OPTIONS", ".", "special_reduce_with_html", ")", "{", "var", "htmlFiles", "=", "OPTIONS", ".", "html", ";", "tmpHTMLPaths", "=", "[", "]", ";", "//check for file or files", "switch", "(", "typeof", "htmlFiles", ")", "{", "case", "'object'", ":", "case", "'array'", ":", "for", "(", "i", "=", "0", ";", "i", "<", "htmlFiles", ".", "length", ";", "++", "i", ")", "{", "getFilePaths", "(", "htmlFiles", "[", "i", "]", ",", "[", "'.html'", ",", "'.htm'", "]", ")", ";", "}", "if", "(", "tmpHTMLPaths", ".", "length", ")", "{", "htmlFiles", "=", "tmpHTMLPaths", ";", "}", "break", ";", "case", "'string'", ":", "//formats", "htmlFiles", "=", "htmlFiles", ".", "replace", "(", "/", " ", "/", "g", ",", "''", ")", ";", "// comma delimited list - filename1.html, filename2.html", "if", "(", "htmlFiles", ".", "indexOf", "(", "','", ")", ">", "-", "1", ")", "{", "htmlFiles", "=", "htmlFiles", ".", "replace", "(", "/", "^\\s+|\\s+$", "/", "g", ",", "''", ")", ".", "split", "(", "','", ")", ";", "tmpStr", "=", "''", ";", "for", "(", "i", "=", "0", ";", "i", "<", "htmlFiles", ".", "length", ";", "++", "i", ")", "{", "getFilePaths", "(", "htmlFiles", "[", "i", "]", ",", "[", "'.html'", ",", "'.htm'", "]", ")", ";", "}", "//end of for", "if", "(", "tmpHTMLPaths", ".", "length", ")", "{", "htmlFiles", "=", "tmpHTMLPaths", ";", "}", "}", "else", "{", "//string path", "getFilePaths", "(", "htmlFiles", ",", "[", "'.html'", ",", "'.htm'", "]", ")", ";", "if", "(", "tmpHTMLPaths", ".", "length", ")", "{", "htmlFiles", "=", "tmpHTMLPaths", ";", "}", "}", "break", ";", "}", "//end of switch", "htmlFileLocation", "=", "(", "htmlFiles", ")", "?", "htmlFiles", ".", "toString", "(", ")", ":", "htmlFiles", ";", "readHTMLFile", "(", "htmlFiles", ")", ";", "CPEVENTS", ".", "on", "(", "'HTML_READ_AGAIN'", ",", "function", "(", ")", "{", "//process selectors", "processHTMLSelectors", "(", "cssSelectors", ",", "htmlDataIn", ",", "htmlOptionsIn", ")", ";", "//read next file", "dataHTMLIn", "=", "[", "]", ";", "readHTMLFile", "(", "htmlFiles", ")", ";", "}", ")", ";", "CPEVENTS", ".", "on", "(", "'HTML_READ_END'", ",", "function", "(", ")", "{", "//process selectors", "processHTMLSelectors", "(", "cssSelectors", ",", "htmlDataIn", ",", "htmlOptionsIn", ")", ";", "dataHTMLIn", "=", "[", "]", ";", "CPEVENTS", ".", "emit", "(", "'HTML_RESULTS_END'", ",", "cssSelectors", ")", ";", "}", ")", ";", "}", "//end of html files check", "}" ]
end of processHTMLSelectors
[ "end", "of", "processHTMLSelectors" ]
4c23ea9cd86056a79bb63117a79ef139ad9b0f2c
https://github.com/rbtech/css-purge/blob/4c23ea9cd86056a79bb63117a79ef139ad9b0f2c/lib/css-purge.js#L1361-L1446
19,406
rbtech/css-purge
lib/css-purge.js
getFilePaths
function getFilePaths(strPath = '', exts = ['.css']) { if (validUrl.isUri(strPath)){ switch(exts[0]) { case '.css': tmpCSSPaths.push(strPath); break; case '.html': case '.htm': tmpHTMLPaths.push(strPath); break; case '.js': tmpJSPaths.push(strPath); break; } } else { try { // Query the entry fileStats = fs.lstatSync(strPath); // directory given if (fileStats.isDirectory()) { var dir = strPath; //traverse directory for .ext strPath try { fs.readdirSync(dir).forEach(filenameRead => { fileFound = false; for (m = 0, count = exts.length; m < count; ++m) { if (path.extname(filenameRead) == exts[m]) { fileFound = true; } } if (fileFound) { switch(exts[0]) { case '.css': tmpCSSPaths.push(dir + '/' + filenameRead); break; case '.html': case '.htm': tmpHTMLPaths.push(dir + '/' + filenameRead); break; case '.js': tmpJSPaths.push(dir + '/' + filenameRead); break; } } else if (path.extname(filenameRead) == '') { switch(exts[0]) { case '.css': getFilePaths(strPath+'/'+filenameRead, ['.css']); break; case '.html': case '.htm': getFilePaths(strPath+'/'+filenameRead, ['.html','.htm']); break; case '.js': getFilePaths(strPath+'/'+filenameRead, ['.js']); break; } } }); } catch (e) { console.log(error("Directory read error: Something went wrong while reading the directory, check your [html] in " + configFileLocation + " and please try again.")); console.log(e); process.exit(1); } } else if (fileStats.isFile()) { //filepath given if (exts.join(",").indexOf(strPath.substr(strPath.lastIndexOf('.') + 1)) != -1) { switch(exts[0]) { case '.css': tmpCSSPaths.push(strPath); break; case '.html': case '.htm': tmpHTMLPaths.push(strPath); break; case '.js': tmpJSPaths.push(strPath); break; } } } } catch (e) { console.log(error("CSS File read error: Something went wrong while reading the file(s), check your [html] in " + configFileLocation + " and please try again.")); console.log(e); process.exit(1); } } //end of url check }
javascript
function getFilePaths(strPath = '', exts = ['.css']) { if (validUrl.isUri(strPath)){ switch(exts[0]) { case '.css': tmpCSSPaths.push(strPath); break; case '.html': case '.htm': tmpHTMLPaths.push(strPath); break; case '.js': tmpJSPaths.push(strPath); break; } } else { try { // Query the entry fileStats = fs.lstatSync(strPath); // directory given if (fileStats.isDirectory()) { var dir = strPath; //traverse directory for .ext strPath try { fs.readdirSync(dir).forEach(filenameRead => { fileFound = false; for (m = 0, count = exts.length; m < count; ++m) { if (path.extname(filenameRead) == exts[m]) { fileFound = true; } } if (fileFound) { switch(exts[0]) { case '.css': tmpCSSPaths.push(dir + '/' + filenameRead); break; case '.html': case '.htm': tmpHTMLPaths.push(dir + '/' + filenameRead); break; case '.js': tmpJSPaths.push(dir + '/' + filenameRead); break; } } else if (path.extname(filenameRead) == '') { switch(exts[0]) { case '.css': getFilePaths(strPath+'/'+filenameRead, ['.css']); break; case '.html': case '.htm': getFilePaths(strPath+'/'+filenameRead, ['.html','.htm']); break; case '.js': getFilePaths(strPath+'/'+filenameRead, ['.js']); break; } } }); } catch (e) { console.log(error("Directory read error: Something went wrong while reading the directory, check your [html] in " + configFileLocation + " and please try again.")); console.log(e); process.exit(1); } } else if (fileStats.isFile()) { //filepath given if (exts.join(",").indexOf(strPath.substr(strPath.lastIndexOf('.') + 1)) != -1) { switch(exts[0]) { case '.css': tmpCSSPaths.push(strPath); break; case '.html': case '.htm': tmpHTMLPaths.push(strPath); break; case '.js': tmpJSPaths.push(strPath); break; } } } } catch (e) { console.log(error("CSS File read error: Something went wrong while reading the file(s), check your [html] in " + configFileLocation + " and please try again.")); console.log(e); process.exit(1); } } //end of url check }
[ "function", "getFilePaths", "(", "strPath", "=", "''", ",", "exts", "=", "[", "'.css'", "]", ")", "{", "if", "(", "validUrl", ".", "isUri", "(", "strPath", ")", ")", "{", "switch", "(", "exts", "[", "0", "]", ")", "{", "case", "'.css'", ":", "tmpCSSPaths", ".", "push", "(", "strPath", ")", ";", "break", ";", "case", "'.html'", ":", "case", "'.htm'", ":", "tmpHTMLPaths", ".", "push", "(", "strPath", ")", ";", "break", ";", "case", "'.js'", ":", "tmpJSPaths", ".", "push", "(", "strPath", ")", ";", "break", ";", "}", "}", "else", "{", "try", "{", "// Query the entry", "fileStats", "=", "fs", ".", "lstatSync", "(", "strPath", ")", ";", "// directory given", "if", "(", "fileStats", ".", "isDirectory", "(", ")", ")", "{", "var", "dir", "=", "strPath", ";", "//traverse directory for .ext strPath", "try", "{", "fs", ".", "readdirSync", "(", "dir", ")", ".", "forEach", "(", "filenameRead", "=>", "{", "fileFound", "=", "false", ";", "for", "(", "m", "=", "0", ",", "count", "=", "exts", ".", "length", ";", "m", "<", "count", ";", "++", "m", ")", "{", "if", "(", "path", ".", "extname", "(", "filenameRead", ")", "==", "exts", "[", "m", "]", ")", "{", "fileFound", "=", "true", ";", "}", "}", "if", "(", "fileFound", ")", "{", "switch", "(", "exts", "[", "0", "]", ")", "{", "case", "'.css'", ":", "tmpCSSPaths", ".", "push", "(", "dir", "+", "'/'", "+", "filenameRead", ")", ";", "break", ";", "case", "'.html'", ":", "case", "'.htm'", ":", "tmpHTMLPaths", ".", "push", "(", "dir", "+", "'/'", "+", "filenameRead", ")", ";", "break", ";", "case", "'.js'", ":", "tmpJSPaths", ".", "push", "(", "dir", "+", "'/'", "+", "filenameRead", ")", ";", "break", ";", "}", "}", "else", "if", "(", "path", ".", "extname", "(", "filenameRead", ")", "==", "''", ")", "{", "switch", "(", "exts", "[", "0", "]", ")", "{", "case", "'.css'", ":", "getFilePaths", "(", "strPath", "+", "'/'", "+", "filenameRead", ",", "[", "'.css'", "]", ")", ";", "break", ";", "case", "'.html'", ":", "case", "'.htm'", ":", "getFilePaths", "(", "strPath", "+", "'/'", "+", "filenameRead", ",", "[", "'.html'", ",", "'.htm'", "]", ")", ";", "break", ";", "case", "'.js'", ":", "getFilePaths", "(", "strPath", "+", "'/'", "+", "filenameRead", ",", "[", "'.js'", "]", ")", ";", "break", ";", "}", "}", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "error", "(", "\"Directory read error: Something went wrong while reading the directory, check your [html] in \"", "+", "configFileLocation", "+", "\" and please try again.\"", ")", ")", ";", "console", ".", "log", "(", "e", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}", "else", "if", "(", "fileStats", ".", "isFile", "(", ")", ")", "{", "//filepath given", "if", "(", "exts", ".", "join", "(", "\",\"", ")", ".", "indexOf", "(", "strPath", ".", "substr", "(", "strPath", ".", "lastIndexOf", "(", "'.'", ")", "+", "1", ")", ")", "!=", "-", "1", ")", "{", "switch", "(", "exts", "[", "0", "]", ")", "{", "case", "'.css'", ":", "tmpCSSPaths", ".", "push", "(", "strPath", ")", ";", "break", ";", "case", "'.html'", ":", "case", "'.htm'", ":", "tmpHTMLPaths", ".", "push", "(", "strPath", ")", ";", "break", ";", "case", "'.js'", ":", "tmpJSPaths", ".", "push", "(", "strPath", ")", ";", "break", ";", "}", "}", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "error", "(", "\"CSS File read error: Something went wrong while reading the file(s), check your [html] in \"", "+", "configFileLocation", "+", "\" and please try again.\"", ")", ")", ";", "console", ".", "log", "(", "e", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}", "//end of url check", "}" ]
end of processCSSFiles
[ "end", "of", "processCSSFiles" ]
4c23ea9cd86056a79bb63117a79ef139ad9b0f2c
https://github.com/rbtech/css-purge/blob/4c23ea9cd86056a79bb63117a79ef139ad9b0f2c/lib/css-purge.js#L1992-L2101
19,407
rbtech/css-purge
lib/css-purge.js
processRulesReset
function processRulesReset() { declarationsNameCounts = null; declarationsValueCounts = null; valKey = null; key = null; declarationsValueCountsCount = null; amountRemoved = 1; duplicate_ids = null; selectorPropertiesList = null; }
javascript
function processRulesReset() { declarationsNameCounts = null; declarationsValueCounts = null; valKey = null; key = null; declarationsValueCountsCount = null; amountRemoved = 1; duplicate_ids = null; selectorPropertiesList = null; }
[ "function", "processRulesReset", "(", ")", "{", "declarationsNameCounts", "=", "null", ";", "declarationsValueCounts", "=", "null", ";", "valKey", "=", "null", ";", "key", "=", "null", ";", "declarationsValueCountsCount", "=", "null", ";", "amountRemoved", "=", "1", ";", "duplicate_ids", "=", "null", ";", "selectorPropertiesList", "=", "null", ";", "}" ]
end of processRules
[ "end", "of", "processRules" ]
4c23ea9cd86056a79bb63117a79ef139ad9b0f2c
https://github.com/rbtech/css-purge/blob/4c23ea9cd86056a79bb63117a79ef139ad9b0f2c/lib/css-purge.js#L5765-L5775
19,408
zalmoxisus/remotedev
examples/reflux/js/store.js
function(list){ localStorage.setItem(localStorageKey, JSON.stringify(list)); // if we used a real database, we would likely do the below in a callback this.list = list; this.trigger(list); // sends the updated list to all listening components (TodoApp) }
javascript
function(list){ localStorage.setItem(localStorageKey, JSON.stringify(list)); // if we used a real database, we would likely do the below in a callback this.list = list; this.trigger(list); // sends the updated list to all listening components (TodoApp) }
[ "function", "(", "list", ")", "{", "localStorage", ".", "setItem", "(", "localStorageKey", ",", "JSON", ".", "stringify", "(", "list", ")", ")", ";", "// if we used a real database, we would likely do the below in a callback", "this", ".", "list", "=", "list", ";", "this", ".", "trigger", "(", "list", ")", ";", "// sends the updated list to all listening components (TodoApp)", "}" ]
called whenever we change a list. normally this would mean a database API call
[ "called", "whenever", "we", "change", "a", "list", ".", "normally", "this", "would", "mean", "a", "database", "API", "call" ]
f8256d934316b37a94cd24870fc1d3efcbe7d0b9
https://github.com/zalmoxisus/remotedev/blob/f8256d934316b37a94cd24870fc1d3efcbe7d0b9/examples/reflux/js/store.js#L63-L68
19,409
zalmoxisus/remotedev
examples/reflux/js/store.js
function() { var loadedList = localStorage.getItem(localStorageKey); if (!loadedList) { // If no list is in localstorage, start out with a default one this.list = [{ key: todoCounter++, created: new Date(), isComplete: false, label: 'Rule the web' }]; } else { this.list = _.map(JSON.parse(loadedList), function(item) { // just resetting the key property for each todo item item.key = todoCounter++; return item; }); } // Subscribe to RemoteDev RemoteDev.subscribe(state => { this.updateList(state); }); RemoteDev.init(this.list); return this.list; }
javascript
function() { var loadedList = localStorage.getItem(localStorageKey); if (!loadedList) { // If no list is in localstorage, start out with a default one this.list = [{ key: todoCounter++, created: new Date(), isComplete: false, label: 'Rule the web' }]; } else { this.list = _.map(JSON.parse(loadedList), function(item) { // just resetting the key property for each todo item item.key = todoCounter++; return item; }); } // Subscribe to RemoteDev RemoteDev.subscribe(state => { this.updateList(state); }); RemoteDev.init(this.list); return this.list; }
[ "function", "(", ")", "{", "var", "loadedList", "=", "localStorage", ".", "getItem", "(", "localStorageKey", ")", ";", "if", "(", "!", "loadedList", ")", "{", "// If no list is in localstorage, start out with a default one", "this", ".", "list", "=", "[", "{", "key", ":", "todoCounter", "++", ",", "created", ":", "new", "Date", "(", ")", ",", "isComplete", ":", "false", ",", "label", ":", "'Rule the web'", "}", "]", ";", "}", "else", "{", "this", ".", "list", "=", "_", ".", "map", "(", "JSON", ".", "parse", "(", "loadedList", ")", ",", "function", "(", "item", ")", "{", "// just resetting the key property for each todo item", "item", ".", "key", "=", "todoCounter", "++", ";", "return", "item", ";", "}", ")", ";", "}", "// Subscribe to RemoteDev", "RemoteDev", ".", "subscribe", "(", "state", "=>", "{", "this", ".", "updateList", "(", "state", ")", ";", "}", ")", ";", "RemoteDev", ".", "init", "(", "this", ".", "list", ")", ";", "return", "this", ".", "list", ";", "}" ]
this will be called by all listening components as they register their listeners
[ "this", "will", "be", "called", "by", "all", "listening", "components", "as", "they", "register", "their", "listeners" ]
f8256d934316b37a94cd24870fc1d3efcbe7d0b9
https://github.com/zalmoxisus/remotedev/blob/f8256d934316b37a94cd24870fc1d3efcbe7d0b9/examples/reflux/js/store.js#L70-L93
19,410
DaftMonk/angular-tour
src/tour/tour.js
getTargetScope
function getTargetScope() { var targetElement = scope.ttElement ? angular.element(scope.ttElement) : element; var targetScope = scope; if (targetElement !== element && !scope.ttSourceScope) targetScope = targetElement.scope(); return targetScope; }
javascript
function getTargetScope() { var targetElement = scope.ttElement ? angular.element(scope.ttElement) : element; var targetScope = scope; if (targetElement !== element && !scope.ttSourceScope) targetScope = targetElement.scope(); return targetScope; }
[ "function", "getTargetScope", "(", ")", "{", "var", "targetElement", "=", "scope", ".", "ttElement", "?", "angular", ".", "element", "(", "scope", ".", "ttElement", ")", ":", "element", ";", "var", "targetScope", "=", "scope", ";", "if", "(", "targetElement", "!==", "element", "&&", "!", "scope", ".", "ttSourceScope", ")", "targetScope", "=", "targetElement", ".", "scope", "(", ")", ";", "return", "targetScope", ";", "}" ]
determining target scope. It's used only when using virtual steps and there is some action performed like on-show or on-progress. Without virtual steps action would performed on element's scope and that would work just fine however, when using virtual steps, whose steps can be placed in different controller, so it affects scope, which will be used to run this action against.
[ "determining", "target", "scope", ".", "It", "s", "used", "only", "when", "using", "virtual", "steps", "and", "there", "is", "some", "action", "performed", "like", "on", "-", "show", "or", "on", "-", "progress", ".", "Without", "virtual", "steps", "action", "would", "performed", "on", "element", "s", "scope", "and", "that", "would", "work", "just", "fine", "however", "when", "using", "virtual", "steps", "whose", "steps", "can", "be", "placed", "in", "different", "controller", "so", "it", "affects", "scope", "which", "will", "be", "used", "to", "run", "this", "action", "against", "." ]
07433ccef7cfb632dfd1b379835c7d126968cf0c
https://github.com/DaftMonk/angular-tour/blob/07433ccef7cfb632dfd1b379835c7d126968cf0c/src/tour/tour.js#L270-L278
19,411
SU-SWS/decanter
webpack.config.js
recursiveIssuer
function recursiveIssuer(module) { if (module.issuer) { return recursiveIssuer(module.issuer); } else if (module.name) { return module.name; } else { return false; } }
javascript
function recursiveIssuer(module) { if (module.issuer) { return recursiveIssuer(module.issuer); } else if (module.name) { return module.name; } else { return false; } }
[ "function", "recursiveIssuer", "(", "module", ")", "{", "if", "(", "module", ".", "issuer", ")", "{", "return", "recursiveIssuer", "(", "module", ".", "issuer", ")", ";", "}", "else", "if", "(", "module", ".", "name", ")", "{", "return", "module", ".", "name", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
For MiniCssExtractPlugin Loops through the module variable that is nested looking for a name.
[ "For", "MiniCssExtractPlugin", "Loops", "through", "the", "module", "variable", "that", "is", "nested", "looking", "for", "a", "name", "." ]
2a00f03066f4abc07032308597a60fff4744cc06
https://github.com/SU-SWS/decanter/blob/2a00f03066f4abc07032308597a60fff4744cc06/webpack.config.js#L30-L40
19,412
sidorares/node-tick
lib/tickprocessor.js
readFile
function readFile(fileName) { try { return read(fileName); } catch (e) { print(fileName + ': ' + (e.message || e)); throw e; } }
javascript
function readFile(fileName) { try { return read(fileName); } catch (e) { print(fileName + ': ' + (e.message || e)); throw e; } }
[ "function", "readFile", "(", "fileName", ")", "{", "try", "{", "return", "read", "(", "fileName", ")", ";", "}", "catch", "(", "e", ")", "{", "print", "(", "fileName", "+", "': '", "+", "(", "e", ".", "message", "||", "e", ")", ")", ";", "throw", "e", ";", "}", "}" ]
A thin wrapper around shell's 'read' function showing a file name on error.
[ "A", "thin", "wrapper", "around", "shell", "s", "read", "function", "showing", "a", "file", "name", "on", "error", "." ]
350c64c5a12588e25be9e8e6acc861e40315eeaa
https://github.com/sidorares/node-tick/blob/350c64c5a12588e25be9e8e6acc861e40315eeaa/lib/tickprocessor.js#L70-L77
19,413
sidorares/node-tick
lib/tickprocessor.js
parseState
function parseState(s) { switch (s) { case "": return Profile.CodeState.COMPILED; case "~": return Profile.CodeState.OPTIMIZABLE; case "*": return Profile.CodeState.OPTIMIZED; } throw new Error("unknown code state: " + s); }
javascript
function parseState(s) { switch (s) { case "": return Profile.CodeState.COMPILED; case "~": return Profile.CodeState.OPTIMIZABLE; case "*": return Profile.CodeState.OPTIMIZED; } throw new Error("unknown code state: " + s); }
[ "function", "parseState", "(", "s", ")", "{", "switch", "(", "s", ")", "{", "case", "\"\"", ":", "return", "Profile", ".", "CodeState", ".", "COMPILED", ";", "case", "\"~\"", ":", "return", "Profile", ".", "CodeState", ".", "OPTIMIZABLE", ";", "case", "\"*\"", ":", "return", "Profile", ".", "CodeState", ".", "OPTIMIZED", ";", "}", "throw", "new", "Error", "(", "\"unknown code state: \"", "+", "s", ")", ";", "}" ]
Parser for dynamic code optimization state.
[ "Parser", "for", "dynamic", "code", "optimization", "state", "." ]
350c64c5a12588e25be9e8e6acc861e40315eeaa
https://github.com/sidorares/node-tick/blob/350c64c5a12588e25be9e8e6acc861e40315eeaa/lib/tickprocessor.js#L83-L90
19,414
Azure/azure-documentdb-node-q
documentclientwrapper.js
function () { var deferred = Q.defer(); var that = this; this._innerQueryIterator.nextItem(function (error, item, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({ resource: item, headers: responseHeaders }); } }); return deferred.promise; }
javascript
function () { var deferred = Q.defer(); var that = this; this._innerQueryIterator.nextItem(function (error, item, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({ resource: item, headers: responseHeaders }); } }); return deferred.promise; }
[ "function", "(", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "that", "=", "this", ";", "this", ".", "_innerQueryIterator", ".", "nextItem", "(", "function", "(", "error", ",", "item", ",", "responseHeaders", ")", "{", "if", "(", "error", ")", "{", "addOrMergeHeadersForError", "(", "error", ",", "responseHeaders", ")", ";", "deferred", ".", "reject", "(", "error", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", "{", "resource", ":", "item", ",", "headers", ":", "responseHeaders", "}", ")", ";", "}", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Gets the next element in the QueryIterator. @memberof QueryIteratorWrapper @instance @Returns {Object} A promise object for the request completion. The onFulfilled callback is of type {@link ResourceResponse} and onError callback is of type {@link ResponseError}
[ "Gets", "the", "next", "element", "in", "the", "QueryIterator", "." ]
ffd0ad09b52942f5c1e167cc54f795553929234d
https://github.com/Azure/azure-documentdb-node-q/blob/ffd0ad09b52942f5c1e167cc54f795553929234d/documentclientwrapper.js#L209-L222
19,415
Azure/azure-documentdb-node-q
documentclientwrapper.js
function () { var deferred = Q.defer(); var that = this; this._innerQueryIterator.executeNext(function (error, resources, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({ feed: resources, headers: responseHeaders }); } }); return deferred.promise; }
javascript
function () { var deferred = Q.defer(); var that = this; this._innerQueryIterator.executeNext(function (error, resources, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({ feed: resources, headers: responseHeaders }); } }); return deferred.promise; }
[ "function", "(", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "that", "=", "this", ";", "this", ".", "_innerQueryIterator", ".", "executeNext", "(", "function", "(", "error", ",", "resources", ",", "responseHeaders", ")", "{", "if", "(", "error", ")", "{", "addOrMergeHeadersForError", "(", "error", ",", "responseHeaders", ")", ";", "deferred", ".", "reject", "(", "error", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", "{", "feed", ":", "resources", ",", "headers", ":", "responseHeaders", "}", ")", ";", "}", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Retrieve the next batch of the feed and pass them as an array to a function @memberof QueryIteratorWrapper @instance @Returns {Object} A promise object for the request completion. the onFulfilled callback is of type {@link FeedResponse} and onError callback is of type {@link ResponseError}
[ "Retrieve", "the", "next", "batch", "of", "the", "feed", "and", "pass", "them", "as", "an", "array", "to", "a", "function" ]
ffd0ad09b52942f5c1e167cc54f795553929234d
https://github.com/Azure/azure-documentdb-node-q/blob/ffd0ad09b52942f5c1e167cc54f795553929234d/documentclientwrapper.js#L230-L243
19,416
Azure/azure-documentdb-node-q
documentclientwrapper.js
function(sprocLink, params, options) { var deferred = Q.defer(); this._innerDocumentclient.executeStoredProcedure(sprocLink, params, options, function (error, result, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({result: result, headers: responseHeaders}); } }); return deferred.promise; }
javascript
function(sprocLink, params, options) { var deferred = Q.defer(); this._innerDocumentclient.executeStoredProcedure(sprocLink, params, options, function (error, result, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({result: result, headers: responseHeaders}); } }); return deferred.promise; }
[ "function", "(", "sprocLink", ",", "params", ",", "options", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "this", ".", "_innerDocumentclient", ".", "executeStoredProcedure", "(", "sprocLink", ",", "params", ",", "options", ",", "function", "(", "error", ",", "result", ",", "responseHeaders", ")", "{", "if", "(", "error", ")", "{", "addOrMergeHeadersForError", "(", "error", ",", "responseHeaders", ")", ";", "deferred", ".", "reject", "(", "error", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", "{", "result", ":", "result", ",", "headers", ":", "responseHeaders", "}", ")", ";", "}", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Execute the StoredProcedure represented by the object. @memberof DocumentClientWrapper @instance @param {string} sprocLink - The self-link of the stored procedure. @param {Array} [params] - Represent the parameters of the stored procedure. @param {Object} [options] - options for executing the stored procedure @param {Object} [options.partitionKey] - partition key value if executing against a partitioned collection @Returns {Object} <p>A promise object for the request completion. <br> The onFulfilled callback takes a parameter of type {@link Response} and the OnError callback takes a parameter of type {@link ResponseError}</p>
[ "Execute", "the", "StoredProcedure", "represented", "by", "the", "object", "." ]
ffd0ad09b52942f5c1e167cc54f795553929234d
https://github.com/Azure/azure-documentdb-node-q/blob/ffd0ad09b52942f5c1e167cc54f795553929234d/documentclientwrapper.js#L1261-L1272
19,417
edx/ux-pattern-library
pldoc/static/js/ui.js
function() { var target; $('a[href^="#"]').not('.pldoc-tab-wrapper .pldoc-link').on('click', function(event) { event.preventDefault(); target = $(event.currentTarget).attr('href'); $('html, body').stop().animate({ scrollTop: $(target).offset().top }, 1000, 'swing', function() { Ui.sendFocus(target); }); }); }
javascript
function() { var target; $('a[href^="#"]').not('.pldoc-tab-wrapper .pldoc-link').on('click', function(event) { event.preventDefault(); target = $(event.currentTarget).attr('href'); $('html, body').stop().animate({ scrollTop: $(target).offset().top }, 1000, 'swing', function() { Ui.sendFocus(target); }); }); }
[ "function", "(", ")", "{", "var", "target", ";", "$", "(", "'a[href^=\"#\"]'", ")", ".", "not", "(", "'.pldoc-tab-wrapper .pldoc-link'", ")", ".", "on", "(", "'click'", ",", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "target", "=", "$", "(", "event", ".", "currentTarget", ")", ".", "attr", "(", "'href'", ")", ";", "$", "(", "'html, body'", ")", ".", "stop", "(", ")", ".", "animate", "(", "{", "scrollTop", ":", "$", "(", "target", ")", ".", "offset", "(", ")", ".", "top", "}", ",", "1000", ",", "'swing'", ",", "function", "(", ")", "{", "Ui", ".", "sendFocus", "(", "target", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
smoothscroll to target links
[ "smoothscroll", "to", "target", "links" ]
ca09258db3805e8315c5347d404a4f343d7700d5
https://github.com/edx/ux-pattern-library/blob/ca09258db3805e8315c5347d404a4f343d7700d5/pldoc/static/js/ui.js#L48-L61
19,418
KissKissBankBank/kitten
src/components/navigation/pagination.js
range
function range(start, end) { return Array(end - start + 1).fill().map(function (_, index) { return start + index; }); }
javascript
function range(start, end) { return Array(end - start + 1).fill().map(function (_, index) { return start + index; }); }
[ "function", "range", "(", "start", ",", "end", ")", "{", "return", "Array", "(", "end", "-", "start", "+", "1", ")", ".", "fill", "(", ")", ".", "map", "(", "function", "(", "_", ",", "index", ")", "{", "return", "start", "+", "index", ";", "}", ")", ";", "}" ]
Returns an array with the given bounds
[ "Returns", "an", "array", "with", "the", "given", "bounds" ]
b002b08d71dfa09719bdd90cf51c902910dd5293
https://github.com/KissKissBankBank/kitten/blob/b002b08d71dfa09719bdd90cf51c902910dd5293/src/components/navigation/pagination.js#L50-L54
19,419
williamkapke/bson-objectid
objectid.js
ObjectID
function ObjectID(arg) { if(!(this instanceof ObjectID)) return new ObjectID(arg); if(arg && ((arg instanceof ObjectID) || arg._bsontype==="ObjectID")) return arg; var buf; if(isBuffer(arg) || (Array.isArray(arg) && arg.length===12)) { buf = Array.prototype.slice.call(arg); } else if(typeof arg === "string") { if(arg.length!==12 && !ObjectID.isValid(arg)) throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); buf = buffer(arg); } else if(/number|undefined/.test(typeof arg)) { buf = buffer(generate(arg)); } Object.defineProperty(this, "id", { enumerable: true, get: function() { return String.fromCharCode.apply(this, buf); } }); Object.defineProperty(this, "str", { get: function() { return buf.map(hex.bind(this, 2)).join(''); } }); }
javascript
function ObjectID(arg) { if(!(this instanceof ObjectID)) return new ObjectID(arg); if(arg && ((arg instanceof ObjectID) || arg._bsontype==="ObjectID")) return arg; var buf; if(isBuffer(arg) || (Array.isArray(arg) && arg.length===12)) { buf = Array.prototype.slice.call(arg); } else if(typeof arg === "string") { if(arg.length!==12 && !ObjectID.isValid(arg)) throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); buf = buffer(arg); } else if(/number|undefined/.test(typeof arg)) { buf = buffer(generate(arg)); } Object.defineProperty(this, "id", { enumerable: true, get: function() { return String.fromCharCode.apply(this, buf); } }); Object.defineProperty(this, "str", { get: function() { return buf.map(hex.bind(this, 2)).join(''); } }); }
[ "function", "ObjectID", "(", "arg", ")", "{", "if", "(", "!", "(", "this", "instanceof", "ObjectID", ")", ")", "return", "new", "ObjectID", "(", "arg", ")", ";", "if", "(", "arg", "&&", "(", "(", "arg", "instanceof", "ObjectID", ")", "||", "arg", ".", "_bsontype", "===", "\"ObjectID\"", ")", ")", "return", "arg", ";", "var", "buf", ";", "if", "(", "isBuffer", "(", "arg", ")", "||", "(", "Array", ".", "isArray", "(", "arg", ")", "&&", "arg", ".", "length", "===", "12", ")", ")", "{", "buf", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arg", ")", ";", "}", "else", "if", "(", "typeof", "arg", "===", "\"string\"", ")", "{", "if", "(", "arg", ".", "length", "!==", "12", "&&", "!", "ObjectID", ".", "isValid", "(", "arg", ")", ")", "throw", "new", "Error", "(", "\"Argument passed in must be a single String of 12 bytes or a string of 24 hex characters\"", ")", ";", "buf", "=", "buffer", "(", "arg", ")", ";", "}", "else", "if", "(", "/", "number|undefined", "/", ".", "test", "(", "typeof", "arg", ")", ")", "{", "buf", "=", "buffer", "(", "generate", "(", "arg", ")", ")", ";", "}", "Object", ".", "defineProperty", "(", "this", ",", "\"id\"", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "String", ".", "fromCharCode", ".", "apply", "(", "this", ",", "buf", ")", ";", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "\"str\"", ",", "{", "get", ":", "function", "(", ")", "{", "return", "buf", ".", "map", "(", "hex", ".", "bind", "(", "this", ",", "2", ")", ")", ".", "join", "(", "''", ")", ";", "}", "}", ")", ";", "}" ]
Create a new immutable ObjectID instance @class Represents the BSON ObjectID type @param {String|Number} arg Can be a 24 byte hex string, 12 byte binary string or a Number. @return {Object} instance of ObjectID.
[ "Create", "a", "new", "immutable", "ObjectID", "instance" ]
df4eada0816a423dc4447411f356c7931808353c
https://github.com/williamkapke/bson-objectid/blob/df4eada0816a423dc4447411f356c7931808353c/objectid.js#L29-L56
19,420
stevenbenner/jquery-powertip
src/core.js
apiShowTip
function apiShowTip(element, event) { // if we were given a mouse event then run the hover intent testing, // otherwise, simply show the tooltip asap if (isMouseEvent(event)) { trackMouse(event); session.previousX = event.pageX; session.previousY = event.pageY; $(element).data(DATA_DISPLAYCONTROLLER).show(); } else { $(element).first().data(DATA_DISPLAYCONTROLLER).show(true, true); } return element; }
javascript
function apiShowTip(element, event) { // if we were given a mouse event then run the hover intent testing, // otherwise, simply show the tooltip asap if (isMouseEvent(event)) { trackMouse(event); session.previousX = event.pageX; session.previousY = event.pageY; $(element).data(DATA_DISPLAYCONTROLLER).show(); } else { $(element).first().data(DATA_DISPLAYCONTROLLER).show(true, true); } return element; }
[ "function", "apiShowTip", "(", "element", ",", "event", ")", "{", "// if we were given a mouse event then run the hover intent testing,", "// otherwise, simply show the tooltip asap", "if", "(", "isMouseEvent", "(", "event", ")", ")", "{", "trackMouse", "(", "event", ")", ";", "session", ".", "previousX", "=", "event", ".", "pageX", ";", "session", ".", "previousY", "=", "event", ".", "pageY", ";", "$", "(", "element", ")", ".", "data", "(", "DATA_DISPLAYCONTROLLER", ")", ".", "show", "(", ")", ";", "}", "else", "{", "$", "(", "element", ")", ".", "first", "(", ")", ".", "data", "(", "DATA_DISPLAYCONTROLLER", ")", ".", "show", "(", "true", ",", "true", ")", ";", "}", "return", "element", ";", "}" ]
Attempts to show the tooltip for the specified element. @param {jQuery|Element} element The element to open the tooltip for. @param {jQuery.Event=} event jQuery event for hover intent and mouse tracking (optional). @return {jQuery|Element} The original jQuery object or DOM Element.
[ "Attempts", "to", "show", "the", "tooltip", "for", "the", "specified", "element", "." ]
58a576d409e2452673d90695f4520b9378ba7c48
https://github.com/stevenbenner/jquery-powertip/blob/58a576d409e2452673d90695f4520b9378ba7c48/src/core.js#L231-L243
19,421
stevenbenner/jquery-powertip
src/core.js
apiCloseTip
function apiCloseTip(element, immediate) { var displayController; // set immediate to true when no element is specified immediate = element ? immediate : true; // find the relevant display controller if (element) { displayController = $(element).first().data(DATA_DISPLAYCONTROLLER); } else if (session.activeHover) { displayController = session.activeHover.data(DATA_DISPLAYCONTROLLER); } // if found, hide the tip if (displayController) { displayController.hide(immediate); } return element; }
javascript
function apiCloseTip(element, immediate) { var displayController; // set immediate to true when no element is specified immediate = element ? immediate : true; // find the relevant display controller if (element) { displayController = $(element).first().data(DATA_DISPLAYCONTROLLER); } else if (session.activeHover) { displayController = session.activeHover.data(DATA_DISPLAYCONTROLLER); } // if found, hide the tip if (displayController) { displayController.hide(immediate); } return element; }
[ "function", "apiCloseTip", "(", "element", ",", "immediate", ")", "{", "var", "displayController", ";", "// set immediate to true when no element is specified", "immediate", "=", "element", "?", "immediate", ":", "true", ";", "// find the relevant display controller", "if", "(", "element", ")", "{", "displayController", "=", "$", "(", "element", ")", ".", "first", "(", ")", ".", "data", "(", "DATA_DISPLAYCONTROLLER", ")", ";", "}", "else", "if", "(", "session", ".", "activeHover", ")", "{", "displayController", "=", "session", ".", "activeHover", ".", "data", "(", "DATA_DISPLAYCONTROLLER", ")", ";", "}", "// if found, hide the tip", "if", "(", "displayController", ")", "{", "displayController", ".", "hide", "(", "immediate", ")", ";", "}", "return", "element", ";", "}" ]
Attempts to close any open tooltips. @param {(jQuery|Element)=} element The element with the tooltip that should be closed (optional). @param {boolean=} immediate Disable close delay (optional). @return {jQuery|Element|undefined} The original jQuery object or DOM Element, if one was specified.
[ "Attempts", "to", "close", "any", "open", "tooltips", "." ]
58a576d409e2452673d90695f4520b9378ba7c48
https://github.com/stevenbenner/jquery-powertip/blob/58a576d409e2452673d90695f4520b9378ba7c48/src/core.js#L263-L282
19,422
stevenbenner/jquery-powertip
src/core.js
apiToggle
function apiToggle(element, event) { if (session.activeHover && session.activeHover.is(element)) { // tooltip for element is active, so close it $.powerTip.hide(element, !isMouseEvent(event)); } else { // tooltip for element is not active, so open it $.powerTip.show(element, event); } return element; }
javascript
function apiToggle(element, event) { if (session.activeHover && session.activeHover.is(element)) { // tooltip for element is active, so close it $.powerTip.hide(element, !isMouseEvent(event)); } else { // tooltip for element is not active, so open it $.powerTip.show(element, event); } return element; }
[ "function", "apiToggle", "(", "element", ",", "event", ")", "{", "if", "(", "session", ".", "activeHover", "&&", "session", ".", "activeHover", ".", "is", "(", "element", ")", ")", "{", "// tooltip for element is active, so close it", "$", ".", "powerTip", ".", "hide", "(", "element", ",", "!", "isMouseEvent", "(", "event", ")", ")", ";", "}", "else", "{", "// tooltip for element is not active, so open it", "$", ".", "powerTip", ".", "show", "(", "element", ",", "event", ")", ";", "}", "return", "element", ";", "}" ]
Toggles the tooltip for the specified element. This will open a closed tooltip, or close an open tooltip. @param {jQuery|Element} element The element with the tooltip that should be toggled. @param {jQuery.Event=} event jQuery event for hover intent and mouse tracking (optional). @return {jQuery|Element} The original jQuery object or DOM Element.
[ "Toggles", "the", "tooltip", "for", "the", "specified", "element", ".", "This", "will", "open", "a", "closed", "tooltip", "or", "close", "an", "open", "tooltip", "." ]
58a576d409e2452673d90695f4520b9378ba7c48
https://github.com/stevenbenner/jquery-powertip/blob/58a576d409e2452673d90695f4520b9378ba7c48/src/core.js#L293-L302
19,423
fernandojsg/aframe-teleport-controls
index.js
function () { var collisionEntities; var data = this.data; var el = this.el; if (!data.collisionEntities) { this.collisionEntities = []; return; } collisionEntities = [].slice.call(el.sceneEl.querySelectorAll(data.collisionEntities)); this.collisionEntities = collisionEntities; // Update entity list on attach. this.childAttachHandler = function childAttachHandler (evt) { if (!evt.detail.el.matches(data.collisionEntities)) { return; } collisionEntities.push(evt.detail.el); }; el.sceneEl.addEventListener('child-attached', this.childAttachHandler); // Update entity list on detach. this.childDetachHandler = function childDetachHandler (evt) { var index; if (!evt.detail.el.matches(data.collisionEntities)) { return; } index = collisionEntities.indexOf(evt.detail.el); if (index === -1) { return; } collisionEntities.splice(index, 1); }; el.sceneEl.addEventListener('child-detached', this.childDetachHandler); }
javascript
function () { var collisionEntities; var data = this.data; var el = this.el; if (!data.collisionEntities) { this.collisionEntities = []; return; } collisionEntities = [].slice.call(el.sceneEl.querySelectorAll(data.collisionEntities)); this.collisionEntities = collisionEntities; // Update entity list on attach. this.childAttachHandler = function childAttachHandler (evt) { if (!evt.detail.el.matches(data.collisionEntities)) { return; } collisionEntities.push(evt.detail.el); }; el.sceneEl.addEventListener('child-attached', this.childAttachHandler); // Update entity list on detach. this.childDetachHandler = function childDetachHandler (evt) { var index; if (!evt.detail.el.matches(data.collisionEntities)) { return; } index = collisionEntities.indexOf(evt.detail.el); if (index === -1) { return; } collisionEntities.splice(index, 1); }; el.sceneEl.addEventListener('child-detached', this.childDetachHandler); }
[ "function", "(", ")", "{", "var", "collisionEntities", ";", "var", "data", "=", "this", ".", "data", ";", "var", "el", "=", "this", ".", "el", ";", "if", "(", "!", "data", ".", "collisionEntities", ")", "{", "this", ".", "collisionEntities", "=", "[", "]", ";", "return", ";", "}", "collisionEntities", "=", "[", "]", ".", "slice", ".", "call", "(", "el", ".", "sceneEl", ".", "querySelectorAll", "(", "data", ".", "collisionEntities", ")", ")", ";", "this", ".", "collisionEntities", "=", "collisionEntities", ";", "// Update entity list on attach.", "this", ".", "childAttachHandler", "=", "function", "childAttachHandler", "(", "evt", ")", "{", "if", "(", "!", "evt", ".", "detail", ".", "el", ".", "matches", "(", "data", ".", "collisionEntities", ")", ")", "{", "return", ";", "}", "collisionEntities", ".", "push", "(", "evt", ".", "detail", ".", "el", ")", ";", "}", ";", "el", ".", "sceneEl", ".", "addEventListener", "(", "'child-attached'", ",", "this", ".", "childAttachHandler", ")", ";", "// Update entity list on detach.", "this", ".", "childDetachHandler", "=", "function", "childDetachHandler", "(", "evt", ")", "{", "var", "index", ";", "if", "(", "!", "evt", ".", "detail", ".", "el", ".", "matches", "(", "data", ".", "collisionEntities", ")", ")", "{", "return", ";", "}", "index", "=", "collisionEntities", ".", "indexOf", "(", "evt", ".", "detail", ".", "el", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "return", ";", "}", "collisionEntities", ".", "splice", "(", "index", ",", "1", ")", ";", "}", ";", "el", ".", "sceneEl", ".", "addEventListener", "(", "'child-detached'", ",", "this", ".", "childDetachHandler", ")", ";", "}" ]
Run `querySelectorAll` for `collisionEntities` and maintain it with `child-attached` and `child-detached` events.
[ "Run", "querySelectorAll", "for", "collisionEntities", "and", "maintain", "it", "with", "child", "-", "attached", "and", "child", "-", "detached", "events", "." ]
d5ed39291c0bb99183fdd71a5071dafbb4cd259c
https://github.com/fernandojsg/aframe-teleport-controls/blob/d5ed39291c0bb99183fdd71a5071dafbb4cd259c/index.js#L248-L277
19,424
fernandojsg/aframe-teleport-controls
index.js
function (i, next) { // @todo We should add a property to define if the collisionEntity is dynamic or static // If static we should do the map just once, otherwise we're recreating the array in every // loop when aiming. var meshes; if (!this.data.collisionEntities) { meshes = this.defaultCollisionMeshes; } else { meshes = this.collisionEntities.map(function (entity) { return entity.getObject3D('mesh'); }).filter(function (n) { return n; }); meshes = meshes.length ? meshes : this.defaultCollisionMeshes; } var intersects = this.raycaster.intersectObjects(meshes, true); if (intersects.length > 0 && !this.hit && this.isValidNormalsAngle(intersects[0].face.normal)) { var point = intersects[0].point; this.line.material.color.set(this.curveHitColor); this.line.material.opacity = this.data.hitOpacity; this.line.material.transparent= this.data.hitOpacity < 1; this.hitEntity.setAttribute('position', point); this.hitEntity.setAttribute('visible', true); this.hit = true; this.hitPoint.copy(intersects[0].point); // If hit, just fill the rest of the points with the hit point and break the loop for (var j = i; j < this.line.numPoints; j++) { this.line.setPoint(j, this.hitPoint); } return true; } else { this.line.setPoint(i, next); return false; } }
javascript
function (i, next) { // @todo We should add a property to define if the collisionEntity is dynamic or static // If static we should do the map just once, otherwise we're recreating the array in every // loop when aiming. var meshes; if (!this.data.collisionEntities) { meshes = this.defaultCollisionMeshes; } else { meshes = this.collisionEntities.map(function (entity) { return entity.getObject3D('mesh'); }).filter(function (n) { return n; }); meshes = meshes.length ? meshes : this.defaultCollisionMeshes; } var intersects = this.raycaster.intersectObjects(meshes, true); if (intersects.length > 0 && !this.hit && this.isValidNormalsAngle(intersects[0].face.normal)) { var point = intersects[0].point; this.line.material.color.set(this.curveHitColor); this.line.material.opacity = this.data.hitOpacity; this.line.material.transparent= this.data.hitOpacity < 1; this.hitEntity.setAttribute('position', point); this.hitEntity.setAttribute('visible', true); this.hit = true; this.hitPoint.copy(intersects[0].point); // If hit, just fill the rest of the points with the hit point and break the loop for (var j = i; j < this.line.numPoints; j++) { this.line.setPoint(j, this.hitPoint); } return true; } else { this.line.setPoint(i, next); return false; } }
[ "function", "(", "i", ",", "next", ")", "{", "// @todo We should add a property to define if the collisionEntity is dynamic or static", "// If static we should do the map just once, otherwise we're recreating the array in every", "// loop when aiming.", "var", "meshes", ";", "if", "(", "!", "this", ".", "data", ".", "collisionEntities", ")", "{", "meshes", "=", "this", ".", "defaultCollisionMeshes", ";", "}", "else", "{", "meshes", "=", "this", ".", "collisionEntities", ".", "map", "(", "function", "(", "entity", ")", "{", "return", "entity", ".", "getObject3D", "(", "'mesh'", ")", ";", "}", ")", ".", "filter", "(", "function", "(", "n", ")", "{", "return", "n", ";", "}", ")", ";", "meshes", "=", "meshes", ".", "length", "?", "meshes", ":", "this", ".", "defaultCollisionMeshes", ";", "}", "var", "intersects", "=", "this", ".", "raycaster", ".", "intersectObjects", "(", "meshes", ",", "true", ")", ";", "if", "(", "intersects", ".", "length", ">", "0", "&&", "!", "this", ".", "hit", "&&", "this", ".", "isValidNormalsAngle", "(", "intersects", "[", "0", "]", ".", "face", ".", "normal", ")", ")", "{", "var", "point", "=", "intersects", "[", "0", "]", ".", "point", ";", "this", ".", "line", ".", "material", ".", "color", ".", "set", "(", "this", ".", "curveHitColor", ")", ";", "this", ".", "line", ".", "material", ".", "opacity", "=", "this", ".", "data", ".", "hitOpacity", ";", "this", ".", "line", ".", "material", ".", "transparent", "=", "this", ".", "data", ".", "hitOpacity", "<", "1", ";", "this", ".", "hitEntity", ".", "setAttribute", "(", "'position'", ",", "point", ")", ";", "this", ".", "hitEntity", ".", "setAttribute", "(", "'visible'", ",", "true", ")", ";", "this", ".", "hit", "=", "true", ";", "this", ".", "hitPoint", ".", "copy", "(", "intersects", "[", "0", "]", ".", "point", ")", ";", "// If hit, just fill the rest of the points with the hit point and break the loop", "for", "(", "var", "j", "=", "i", ";", "j", "<", "this", ".", "line", ".", "numPoints", ";", "j", "++", ")", "{", "this", ".", "line", ".", "setPoint", "(", "j", ",", "this", ".", "hitPoint", ")", ";", "}", "return", "true", ";", "}", "else", "{", "this", ".", "line", ".", "setPoint", "(", "i", ",", "next", ")", ";", "return", "false", ";", "}", "}" ]
Check for raycaster intersection. @param {number} Line fragment point index. @param {number} Next line fragment point index. @returns {boolean} true if there's an intersection.
[ "Check", "for", "raycaster", "intersection", "." ]
d5ed39291c0bb99183fdd71a5071dafbb4cd259c
https://github.com/fernandojsg/aframe-teleport-controls/blob/d5ed39291c0bb99183fdd71a5071dafbb4cd259c/index.js#L352-L389
19,425
fernandojsg/aframe-teleport-controls
index.js
createHitEntity
function createHitEntity (data) { var cylinder; var hitEntity; var torus; // Parent. hitEntity = document.createElement('a-entity'); hitEntity.className = 'hitEntity'; // Torus. torus = document.createElement('a-entity'); torus.setAttribute('geometry', { primitive: 'torus', radius: data.hitCylinderRadius, radiusTubular: 0.01 }); torus.setAttribute('rotation', {x: 90, y: 0, z: 0}); torus.setAttribute('material', { shader: 'flat', color: data.hitCylinderColor, side: 'double', depthTest: false }); hitEntity.appendChild(torus); // Cylinder. cylinder = document.createElement('a-entity'); cylinder.setAttribute('position', {x: 0, y: data.hitCylinderHeight / 2, z: 0}); cylinder.setAttribute('geometry', { primitive: 'cylinder', segmentsHeight: 1, radius: data.hitCylinderRadius, height: data.hitCylinderHeight, openEnded: true }); cylinder.setAttribute('material', { shader: 'flat', color: data.hitCylinderColor, side: 'double', src: cylinderTexture, transparent: true, depthTest: false }); hitEntity.appendChild(cylinder); return hitEntity; }
javascript
function createHitEntity (data) { var cylinder; var hitEntity; var torus; // Parent. hitEntity = document.createElement('a-entity'); hitEntity.className = 'hitEntity'; // Torus. torus = document.createElement('a-entity'); torus.setAttribute('geometry', { primitive: 'torus', radius: data.hitCylinderRadius, radiusTubular: 0.01 }); torus.setAttribute('rotation', {x: 90, y: 0, z: 0}); torus.setAttribute('material', { shader: 'flat', color: data.hitCylinderColor, side: 'double', depthTest: false }); hitEntity.appendChild(torus); // Cylinder. cylinder = document.createElement('a-entity'); cylinder.setAttribute('position', {x: 0, y: data.hitCylinderHeight / 2, z: 0}); cylinder.setAttribute('geometry', { primitive: 'cylinder', segmentsHeight: 1, radius: data.hitCylinderRadius, height: data.hitCylinderHeight, openEnded: true }); cylinder.setAttribute('material', { shader: 'flat', color: data.hitCylinderColor, side: 'double', src: cylinderTexture, transparent: true, depthTest: false }); hitEntity.appendChild(cylinder); return hitEntity; }
[ "function", "createHitEntity", "(", "data", ")", "{", "var", "cylinder", ";", "var", "hitEntity", ";", "var", "torus", ";", "// Parent.", "hitEntity", "=", "document", ".", "createElement", "(", "'a-entity'", ")", ";", "hitEntity", ".", "className", "=", "'hitEntity'", ";", "// Torus.", "torus", "=", "document", ".", "createElement", "(", "'a-entity'", ")", ";", "torus", ".", "setAttribute", "(", "'geometry'", ",", "{", "primitive", ":", "'torus'", ",", "radius", ":", "data", ".", "hitCylinderRadius", ",", "radiusTubular", ":", "0.01", "}", ")", ";", "torus", ".", "setAttribute", "(", "'rotation'", ",", "{", "x", ":", "90", ",", "y", ":", "0", ",", "z", ":", "0", "}", ")", ";", "torus", ".", "setAttribute", "(", "'material'", ",", "{", "shader", ":", "'flat'", ",", "color", ":", "data", ".", "hitCylinderColor", ",", "side", ":", "'double'", ",", "depthTest", ":", "false", "}", ")", ";", "hitEntity", ".", "appendChild", "(", "torus", ")", ";", "// Cylinder.", "cylinder", "=", "document", ".", "createElement", "(", "'a-entity'", ")", ";", "cylinder", ".", "setAttribute", "(", "'position'", ",", "{", "x", ":", "0", ",", "y", ":", "data", ".", "hitCylinderHeight", "/", "2", ",", "z", ":", "0", "}", ")", ";", "cylinder", ".", "setAttribute", "(", "'geometry'", ",", "{", "primitive", ":", "'cylinder'", ",", "segmentsHeight", ":", "1", ",", "radius", ":", "data", ".", "hitCylinderRadius", ",", "height", ":", "data", ".", "hitCylinderHeight", ",", "openEnded", ":", "true", "}", ")", ";", "cylinder", ".", "setAttribute", "(", "'material'", ",", "{", "shader", ":", "'flat'", ",", "color", ":", "data", ".", "hitCylinderColor", ",", "side", ":", "'double'", ",", "src", ":", "cylinderTexture", ",", "transparent", ":", "true", ",", "depthTest", ":", "false", "}", ")", ";", "hitEntity", ".", "appendChild", "(", "cylinder", ")", ";", "return", "hitEntity", ";", "}" ]
Create mesh to represent the area of intersection. Default to a combination of torus and cylinder.
[ "Create", "mesh", "to", "represent", "the", "area", "of", "intersection", ".", "Default", "to", "a", "combination", "of", "torus", "and", "cylinder", "." ]
d5ed39291c0bb99183fdd71a5071dafbb4cd259c
https://github.com/fernandojsg/aframe-teleport-controls/blob/d5ed39291c0bb99183fdd71a5071dafbb4cd259c/index.js#L407-L453
19,426
natefaubion/sparkler
src/utils.js
cloneSyntax
function cloneSyntax(stx) { function F(){} F.prototype = stx.__proto__; var s = new F(); extend(s, stx); s.token = extend({}, s.token); return s; }
javascript
function cloneSyntax(stx) { function F(){} F.prototype = stx.__proto__; var s = new F(); extend(s, stx); s.token = extend({}, s.token); return s; }
[ "function", "cloneSyntax", "(", "stx", ")", "{", "function", "F", "(", ")", "{", "}", "F", ".", "prototype", "=", "stx", ".", "__proto__", ";", "var", "s", "=", "new", "F", "(", ")", ";", "extend", "(", "s", ",", "stx", ")", ";", "s", ".", "token", "=", "extend", "(", "{", "}", ",", "s", ".", "token", ")", ";", "return", "s", ";", "}" ]
HACK! Sweet.js needs to expose syntax cloning to macros
[ "HACK!", "Sweet", ".", "js", "needs", "to", "expose", "syntax", "cloning", "to", "macros" ]
c8ab2c14787b5b0256f93c03d2dd11a732356fb3
https://github.com/natefaubion/sparkler/blob/c8ab2c14787b5b0256f93c03d2dd11a732356fb3/src/utils.js#L220-L227
19,427
chr15m/bugout
index.js
attach
function attach(bugout, identifier, wire, addr) { debug("saw wire", wire.peerId, identifier); wire.use(extension(bugout, identifier, wire)); wire.on("close", partial(detach, bugout, identifier, wire)); }
javascript
function attach(bugout, identifier, wire, addr) { debug("saw wire", wire.peerId, identifier); wire.use(extension(bugout, identifier, wire)); wire.on("close", partial(detach, bugout, identifier, wire)); }
[ "function", "attach", "(", "bugout", ",", "identifier", ",", "wire", ",", "addr", ")", "{", "debug", "(", "\"saw wire\"", ",", "wire", ".", "peerId", ",", "identifier", ")", ";", "wire", ".", "use", "(", "extension", "(", "bugout", ",", "identifier", ",", "wire", ")", ")", ";", "wire", ".", "on", "(", "\"close\"", ",", "partial", "(", "detach", ",", "bugout", ",", "identifier", ",", "wire", ")", ")", ";", "}" ]
extension protocol plumbing
[ "extension", "protocol", "plumbing" ]
0795437ff7d674d17d2b8cd0463c7c2386d5b478
https://github.com/chr15m/bugout/blob/0795437ff7d674d17d2b8cd0463c7c2386d5b478/index.js#L415-L419
19,428
not-an-aardvark/eslint-plugin-eslint-plugin
lib/rules/report-message-format.js
processMessageNode
function processMessageNode (message) { if ( (message.type === 'Literal' && typeof message.value === 'string' && !pattern.test(message.value)) || (message.type === 'TemplateLiteral' && message.quasis.length === 1 && !pattern.test(message.quasis[0].value.cooked)) ) { context.report({ node: message, message: "Report message does not match the pattern '{{pattern}}'.", data: { pattern: context.options[0] || '' }, }); } }
javascript
function processMessageNode (message) { if ( (message.type === 'Literal' && typeof message.value === 'string' && !pattern.test(message.value)) || (message.type === 'TemplateLiteral' && message.quasis.length === 1 && !pattern.test(message.quasis[0].value.cooked)) ) { context.report({ node: message, message: "Report message does not match the pattern '{{pattern}}'.", data: { pattern: context.options[0] || '' }, }); } }
[ "function", "processMessageNode", "(", "message", ")", "{", "if", "(", "(", "message", ".", "type", "===", "'Literal'", "&&", "typeof", "message", ".", "value", "===", "'string'", "&&", "!", "pattern", ".", "test", "(", "message", ".", "value", ")", ")", "||", "(", "message", ".", "type", "===", "'TemplateLiteral'", "&&", "message", ".", "quasis", ".", "length", "===", "1", "&&", "!", "pattern", ".", "test", "(", "message", ".", "quasis", "[", "0", "]", ".", "value", ".", "cooked", ")", ")", ")", "{", "context", ".", "report", "(", "{", "node", ":", "message", ",", "message", ":", "\"Report message does not match the pattern '{{pattern}}'.\"", ",", "data", ":", "{", "pattern", ":", "context", ".", "options", "[", "0", "]", "||", "''", "}", ",", "}", ")", ";", "}", "}" ]
Report a message node if it doesn't match the given formatting @param {ASTNode} message The message AST node @returns {void}
[ "Report", "a", "message", "node", "if", "it", "doesn", "t", "match", "the", "given", "formatting" ]
660074eaaa342f6c25128c1bfc541663388921ef
https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/660074eaaa342f6c25128c1bfc541663388921ef/lib/rules/report-message-format.js#L37-L48
19,429
not-an-aardvark/eslint-plugin-eslint-plugin
lib/rules/require-meta-docs-url.js
isExpectedUrl
function isExpectedUrl (node) { return Boolean( node && node.type === 'Literal' && typeof node.value === 'string' && ( expectedUrl === undefined || node.value === expectedUrl ) ); }
javascript
function isExpectedUrl (node) { return Boolean( node && node.type === 'Literal' && typeof node.value === 'string' && ( expectedUrl === undefined || node.value === expectedUrl ) ); }
[ "function", "isExpectedUrl", "(", "node", ")", "{", "return", "Boolean", "(", "node", "&&", "node", ".", "type", "===", "'Literal'", "&&", "typeof", "node", ".", "value", "===", "'string'", "&&", "(", "expectedUrl", "===", "undefined", "||", "node", ".", "value", "===", "expectedUrl", ")", ")", ";", "}" ]
Check whether a given node is the expected URL. @param {Node} node The node of property value to check. @returns {boolean} `true` if the node is the expected URL.
[ "Check", "whether", "a", "given", "node", "is", "the", "expected", "URL", "." ]
660074eaaa342f6c25128c1bfc541663388921ef
https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/660074eaaa342f6c25128c1bfc541663388921ef/lib/rules/require-meta-docs-url.js#L55-L65
19,430
not-an-aardvark/eslint-plugin-eslint-plugin
lib/rules/require-meta-docs-url.js
insertProperty
function insertProperty (fixer, node, propertyText) { if (node.properties.length === 0) { return fixer.replaceText(node, `{\n${propertyText}\n}`); } return fixer.insertTextAfter( sourceCode.getLastToken(node.properties[node.properties.length - 1]), `,\n${propertyText}` ); }
javascript
function insertProperty (fixer, node, propertyText) { if (node.properties.length === 0) { return fixer.replaceText(node, `{\n${propertyText}\n}`); } return fixer.insertTextAfter( sourceCode.getLastToken(node.properties[node.properties.length - 1]), `,\n${propertyText}` ); }
[ "function", "insertProperty", "(", "fixer", ",", "node", ",", "propertyText", ")", "{", "if", "(", "node", ".", "properties", ".", "length", "===", "0", ")", "{", "return", "fixer", ".", "replaceText", "(", "node", ",", "`", "\\n", "${", "propertyText", "}", "\\n", "`", ")", ";", "}", "return", "fixer", ".", "insertTextAfter", "(", "sourceCode", ".", "getLastToken", "(", "node", ".", "properties", "[", "node", ".", "properties", ".", "length", "-", "1", "]", ")", ",", "`", "\\n", "${", "propertyText", "}", "`", ")", ";", "}" ]
Insert a given property into a given object literal. @param {SourceCodeFixer} fixer The fixer. @param {Node} node The ObjectExpression node to insert a property. @param {string} propertyText The property code to insert. @returns {void}
[ "Insert", "a", "given", "property", "into", "a", "given", "object", "literal", "." ]
660074eaaa342f6c25128c1bfc541663388921ef
https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/660074eaaa342f6c25128c1bfc541663388921ef/lib/rules/require-meta-docs-url.js#L74-L82
19,431
not-an-aardvark/eslint-plugin-eslint-plugin
lib/rules/no-useless-token-range.js
isRangeAccess
function isRangeAccess (node) { return node.type === 'MemberExpression' && node.property.type === 'Identifier' && node.property.name === 'range'; }
javascript
function isRangeAccess (node) { return node.type === 'MemberExpression' && node.property.type === 'Identifier' && node.property.name === 'range'; }
[ "function", "isRangeAccess", "(", "node", ")", "{", "return", "node", ".", "type", "===", "'MemberExpression'", "&&", "node", ".", "property", ".", "type", "===", "'Identifier'", "&&", "node", ".", "property", ".", "name", "===", "'range'", ";", "}" ]
Determines whether a node is a MemberExpression that accesses the `range` property @param {ASTNode} node The node @returns {boolean} `true` if the node is a MemberExpression that accesses the `range` property
[ "Determines", "whether", "a", "node", "is", "a", "MemberExpression", "that", "accesses", "the", "range", "property" ]
660074eaaa342f6c25128c1bfc541663388921ef
https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/660074eaaa342f6c25128c1bfc541663388921ef/lib/rules/no-useless-token-range.js#L58-L60
19,432
ceejbot/fivebeans
lib/client.js
argHashToArray
function argHashToArray(hash) { var keys = Object.keys(hash); var result = []; for (var i = 0; i < keys.length; i++) { result[parseInt(keys[i], 10)] = hash[keys[i]]; } return result; }
javascript
function argHashToArray(hash) { var keys = Object.keys(hash); var result = []; for (var i = 0; i < keys.length; i++) { result[parseInt(keys[i], 10)] = hash[keys[i]]; } return result; }
[ "function", "argHashToArray", "(", "hash", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "hash", ")", ";", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "result", "[", "parseInt", "(", "keys", "[", "i", "]", ",", "10", ")", "]", "=", "hash", "[", "keys", "[", "i", "]", "]", ";", "}", "return", "result", ";", "}" ]
utilities Turn a function argument hash into an array for slicing.
[ "utilities", "Turn", "a", "function", "argument", "hash", "into", "an", "array", "for", "slicing", "." ]
1849d0286b5bea6a1de7582da9b910a567f8ed4f
https://github.com/ceejbot/fivebeans/blob/1849d0286b5bea6a1de7582da9b910a567f8ed4f/lib/client.js#L15-L24
19,433
ceejbot/fivebeans
lib/client.js
makeBeanstalkCommand
function makeBeanstalkCommand(command, expectedResponse, sendsData) { // Commands are called as client.COMMAND(arg1, arg2, ... data, callback); // They're sent to beanstalkd as: COMMAND arg1 arg2 ... // followed by data. // So we slice the callback & data from the passed-in arguments, prepend // the command, then send the arglist otherwise intact. // We then push a handler for the expected response onto our handler stack. // Some commands have no args, just a callback (stats, stats-tube, etc); // That's the case handled when args < 2. return function() { var data, buffer, args = argHashToArray(arguments), callback = args.pop(); args.unshift(command); if (sendsData) { data = args.pop(); if (!Buffer.isBuffer(data)) data = new Buffer(data); args.push(data.length); } this.handlers.push([new ResponseHandler(expectedResponse), callback]); if (data) { buffer = Buffer.concat([new Buffer(args.join(' ')), CRLF, data, CRLF]); } else { buffer = Buffer.concat([new Buffer(args.join(' ')), CRLF]); } this.stream.write(buffer); }; }
javascript
function makeBeanstalkCommand(command, expectedResponse, sendsData) { // Commands are called as client.COMMAND(arg1, arg2, ... data, callback); // They're sent to beanstalkd as: COMMAND arg1 arg2 ... // followed by data. // So we slice the callback & data from the passed-in arguments, prepend // the command, then send the arglist otherwise intact. // We then push a handler for the expected response onto our handler stack. // Some commands have no args, just a callback (stats, stats-tube, etc); // That's the case handled when args < 2. return function() { var data, buffer, args = argHashToArray(arguments), callback = args.pop(); args.unshift(command); if (sendsData) { data = args.pop(); if (!Buffer.isBuffer(data)) data = new Buffer(data); args.push(data.length); } this.handlers.push([new ResponseHandler(expectedResponse), callback]); if (data) { buffer = Buffer.concat([new Buffer(args.join(' ')), CRLF, data, CRLF]); } else { buffer = Buffer.concat([new Buffer(args.join(' ')), CRLF]); } this.stream.write(buffer); }; }
[ "function", "makeBeanstalkCommand", "(", "command", ",", "expectedResponse", ",", "sendsData", ")", "{", "// Commands are called as client.COMMAND(arg1, arg2, ... data, callback);", "// They're sent to beanstalkd as: COMMAND arg1 arg2 ...", "// followed by data.", "// So we slice the callback & data from the passed-in arguments, prepend", "// the command, then send the arglist otherwise intact.", "// We then push a handler for the expected response onto our handler stack.", "// Some commands have no args, just a callback (stats, stats-tube, etc);", "// That's the case handled when args < 2.", "return", "function", "(", ")", "{", "var", "data", ",", "buffer", ",", "args", "=", "argHashToArray", "(", "arguments", ")", ",", "callback", "=", "args", ".", "pop", "(", ")", ";", "args", ".", "unshift", "(", "command", ")", ";", "if", "(", "sendsData", ")", "{", "data", "=", "args", ".", "pop", "(", ")", ";", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "data", "=", "new", "Buffer", "(", "data", ")", ";", "args", ".", "push", "(", "data", ".", "length", ")", ";", "}", "this", ".", "handlers", ".", "push", "(", "[", "new", "ResponseHandler", "(", "expectedResponse", ")", ",", "callback", "]", ")", ";", "if", "(", "data", ")", "{", "buffer", "=", "Buffer", ".", "concat", "(", "[", "new", "Buffer", "(", "args", ".", "join", "(", "' '", ")", ")", ",", "CRLF", ",", "data", ",", "CRLF", "]", ")", ";", "}", "else", "{", "buffer", "=", "Buffer", ".", "concat", "(", "[", "new", "Buffer", "(", "args", ".", "join", "(", "' '", ")", ")", ",", "CRLF", "]", ")", ";", "}", "this", ".", "stream", ".", "write", "(", "buffer", ")", ";", "}", ";", "}" ]
Implementing the beanstalkd interface.
[ "Implementing", "the", "beanstalkd", "interface", "." ]
1849d0286b5bea6a1de7582da9b910a567f8ed4f
https://github.com/ceejbot/fivebeans/blob/1849d0286b5bea6a1de7582da9b910a567f8ed4f/lib/client.js#L266-L305
19,434
Leanplum/Leanplum-JavaScript-SDK
dist/sw/sw.js
pushListener
function pushListener(event) { var jsonString = event.data && event.data.text() ? event.data.text() : null; if (!jsonString) { console.log('Leanplum: Push received without payload, skipping display.'); return; } // noinspection JSCheckFunctionSignatures var options = JSON.parse(jsonString); /** @namespace options.title The title of the push notification. **/ /** @namespace options.tag The id of the push notification **/ if (!options || !options.title || !options.tag) { console.log('Leanplum: No options, title or tag/id received, skipping ' + 'display.'); return; } // Extract open action url. We only support open url action for now. /** @namespace options.data.openAction The openAction of the push notification. **/ if (options.data && options.data.openAction && options.data.openAction.hasOwnProperty(ACTION_NAME_KEY) && options.data.openAction[ACTION_NAME_KEY] === OPEN_URL_ACTION && options.data.openAction.hasOwnProperty(ARG_URL)) { openActions[options.tag] = options.data.openAction[ARG_URL]; } // Extract title and delete from options. var title = options.title; Reflect.deleteProperty(options, 'title'); /** @namespace self.registration **/ /** @namespace self.registration.showNotification **/ event.waitUntil(self.registration.showNotification(title, options)); }
javascript
function pushListener(event) { var jsonString = event.data && event.data.text() ? event.data.text() : null; if (!jsonString) { console.log('Leanplum: Push received without payload, skipping display.'); return; } // noinspection JSCheckFunctionSignatures var options = JSON.parse(jsonString); /** @namespace options.title The title of the push notification. **/ /** @namespace options.tag The id of the push notification **/ if (!options || !options.title || !options.tag) { console.log('Leanplum: No options, title or tag/id received, skipping ' + 'display.'); return; } // Extract open action url. We only support open url action for now. /** @namespace options.data.openAction The openAction of the push notification. **/ if (options.data && options.data.openAction && options.data.openAction.hasOwnProperty(ACTION_NAME_KEY) && options.data.openAction[ACTION_NAME_KEY] === OPEN_URL_ACTION && options.data.openAction.hasOwnProperty(ARG_URL)) { openActions[options.tag] = options.data.openAction[ARG_URL]; } // Extract title and delete from options. var title = options.title; Reflect.deleteProperty(options, 'title'); /** @namespace self.registration **/ /** @namespace self.registration.showNotification **/ event.waitUntil(self.registration.showNotification(title, options)); }
[ "function", "pushListener", "(", "event", ")", "{", "var", "jsonString", "=", "event", ".", "data", "&&", "event", ".", "data", ".", "text", "(", ")", "?", "event", ".", "data", ".", "text", "(", ")", ":", "null", ";", "if", "(", "!", "jsonString", ")", "{", "console", ".", "log", "(", "'Leanplum: Push received without payload, skipping display.'", ")", ";", "return", ";", "}", "// noinspection JSCheckFunctionSignatures", "var", "options", "=", "JSON", ".", "parse", "(", "jsonString", ")", ";", "/** @namespace options.title The title of the push notification. **/", "/** @namespace options.tag The id of the push notification **/", "if", "(", "!", "options", "||", "!", "options", ".", "title", "||", "!", "options", ".", "tag", ")", "{", "console", ".", "log", "(", "'Leanplum: No options, title or tag/id received, skipping '", "+", "'display.'", ")", ";", "return", ";", "}", "// Extract open action url. We only support open url action for now.", "/** @namespace options.data.openAction The openAction of the push notification. **/", "if", "(", "options", ".", "data", "&&", "options", ".", "data", ".", "openAction", "&&", "options", ".", "data", ".", "openAction", ".", "hasOwnProperty", "(", "ACTION_NAME_KEY", ")", "&&", "options", ".", "data", ".", "openAction", "[", "ACTION_NAME_KEY", "]", "===", "OPEN_URL_ACTION", "&&", "options", ".", "data", ".", "openAction", ".", "hasOwnProperty", "(", "ARG_URL", ")", ")", "{", "openActions", "[", "options", ".", "tag", "]", "=", "options", ".", "data", ".", "openAction", "[", "ARG_URL", "]", ";", "}", "// Extract title and delete from options.", "var", "title", "=", "options", ".", "title", ";", "Reflect", ".", "deleteProperty", "(", "options", ",", "'title'", ")", ";", "/** @namespace self.registration **/", "/** @namespace self.registration.showNotification **/", "event", ".", "waitUntil", "(", "self", ".", "registration", ".", "showNotification", "(", "title", ",", "options", ")", ")", ";", "}" ]
Triggered on push message received. @param {object} event The push payload that the browser received.
[ "Triggered", "on", "push", "message", "received", "." ]
a9fc6c6feba3fc9a9f500b80b797a350db3c0caa
https://github.com/Leanplum/Leanplum-JavaScript-SDK/blob/a9fc6c6feba3fc9a9f500b80b797a350db3c0caa/dist/sw/sw.js#L64-L94
19,435
Leanplum/Leanplum-JavaScript-SDK
dist/sw/sw.js
notificationClickListener
function notificationClickListener(event) { console.log('Leanplum: [Service Worker] Notification click received.'); event.notification.close(); if (!event.notification || !event.notification.tag) { console.log('Leanplum: No notification or tag/id received, skipping open action.'); return; } var notificationId = event.notification.tag; var openActionUrl = openActions[notificationId]; if (!openActionUrl) { console.log('Leanplum: [Service Worker] No action defined, doing nothing.'); return; } Reflect.deleteProperty(openActions, 'notificationId'); /** @namespace clients.openWindow **/ event.waitUntil(clients.openWindow(openActionUrl)); }
javascript
function notificationClickListener(event) { console.log('Leanplum: [Service Worker] Notification click received.'); event.notification.close(); if (!event.notification || !event.notification.tag) { console.log('Leanplum: No notification or tag/id received, skipping open action.'); return; } var notificationId = event.notification.tag; var openActionUrl = openActions[notificationId]; if (!openActionUrl) { console.log('Leanplum: [Service Worker] No action defined, doing nothing.'); return; } Reflect.deleteProperty(openActions, 'notificationId'); /** @namespace clients.openWindow **/ event.waitUntil(clients.openWindow(openActionUrl)); }
[ "function", "notificationClickListener", "(", "event", ")", "{", "console", ".", "log", "(", "'Leanplum: [Service Worker] Notification click received.'", ")", ";", "event", ".", "notification", ".", "close", "(", ")", ";", "if", "(", "!", "event", ".", "notification", "||", "!", "event", ".", "notification", ".", "tag", ")", "{", "console", ".", "log", "(", "'Leanplum: No notification or tag/id received, skipping open action.'", ")", ";", "return", ";", "}", "var", "notificationId", "=", "event", ".", "notification", ".", "tag", ";", "var", "openActionUrl", "=", "openActions", "[", "notificationId", "]", ";", "if", "(", "!", "openActionUrl", ")", "{", "console", ".", "log", "(", "'Leanplum: [Service Worker] No action defined, doing nothing.'", ")", ";", "return", ";", "}", "Reflect", ".", "deleteProperty", "(", "openActions", ",", "'notificationId'", ")", ";", "/** @namespace clients.openWindow **/", "event", ".", "waitUntil", "(", "clients", ".", "openWindow", "(", "openActionUrl", ")", ")", ";", "}" ]
Callback that handles clicks on the notification. @param {object} event The notification event object. @param {object} event.notification The notification object. @param {function} event.waitUntil The browser will keep the service worker running until the promise you passed in has settled.
[ "Callback", "that", "handles", "clicks", "on", "the", "notification", "." ]
a9fc6c6feba3fc9a9f500b80b797a350db3c0caa
https://github.com/Leanplum/Leanplum-JavaScript-SDK/blob/a9fc6c6feba3fc9a9f500b80b797a350db3c0caa/dist/sw/sw.js#L103-L124
19,436
rochars/wavefile
dist/wavefile.js
bitDepth
function bitDepth(input, original, target, output) { validateBitDepth_(original); validateBitDepth_(target); /** @type {!Function} */ let toFunction = getBitDepthFunction_(original, target); /** @type {!Object<string, number>} */ let options = { oldMin: Math.pow(2, parseInt(original, 10)) / 2, newMin: Math.pow(2, parseInt(target, 10)) / 2, oldMax: (Math.pow(2, parseInt(original, 10)) / 2) - 1, newMax: (Math.pow(2, parseInt(target, 10)) / 2) - 1, }; /** @type {number} */ const len = input.length; // sign the samples if original is 8-bit if (original == "8") { for (let i=0; i<len; i++) { output[i] = input[i] -= 128; } } // change the resolution of the samples for (let i=0; i<len; i++) { output[i] = toFunction(input[i], options); } // unsign the samples if target is 8-bit if (target == "8") { for (let i=0; i<len; i++) { output[i] = output[i] += 128; } } }
javascript
function bitDepth(input, original, target, output) { validateBitDepth_(original); validateBitDepth_(target); /** @type {!Function} */ let toFunction = getBitDepthFunction_(original, target); /** @type {!Object<string, number>} */ let options = { oldMin: Math.pow(2, parseInt(original, 10)) / 2, newMin: Math.pow(2, parseInt(target, 10)) / 2, oldMax: (Math.pow(2, parseInt(original, 10)) / 2) - 1, newMax: (Math.pow(2, parseInt(target, 10)) / 2) - 1, }; /** @type {number} */ const len = input.length; // sign the samples if original is 8-bit if (original == "8") { for (let i=0; i<len; i++) { output[i] = input[i] -= 128; } } // change the resolution of the samples for (let i=0; i<len; i++) { output[i] = toFunction(input[i], options); } // unsign the samples if target is 8-bit if (target == "8") { for (let i=0; i<len; i++) { output[i] = output[i] += 128; } } }
[ "function", "bitDepth", "(", "input", ",", "original", ",", "target", ",", "output", ")", "{", "validateBitDepth_", "(", "original", ")", ";", "validateBitDepth_", "(", "target", ")", ";", "/** @type {!Function} */", "let", "toFunction", "=", "getBitDepthFunction_", "(", "original", ",", "target", ")", ";", "/** @type {!Object<string, number>} */", "let", "options", "=", "{", "oldMin", ":", "Math", ".", "pow", "(", "2", ",", "parseInt", "(", "original", ",", "10", ")", ")", "/", "2", ",", "newMin", ":", "Math", ".", "pow", "(", "2", ",", "parseInt", "(", "target", ",", "10", ")", ")", "/", "2", ",", "oldMax", ":", "(", "Math", ".", "pow", "(", "2", ",", "parseInt", "(", "original", ",", "10", ")", ")", "/", "2", ")", "-", "1", ",", "newMax", ":", "(", "Math", ".", "pow", "(", "2", ",", "parseInt", "(", "target", ",", "10", ")", ")", "/", "2", ")", "-", "1", ",", "}", ";", "/** @type {number} */", "const", "len", "=", "input", ".", "length", ";", "// sign the samples if original is 8-bit", "if", "(", "original", "==", "\"8\"", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "output", "[", "i", "]", "=", "input", "[", "i", "]", "-=", "128", ";", "}", "}", "// change the resolution of the samples", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "output", "[", "i", "]", "=", "toFunction", "(", "input", "[", "i", "]", ",", "options", ")", ";", "}", "// unsign the samples if target is 8-bit", "if", "(", "target", "==", "\"8\"", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "output", "[", "i", "]", "=", "output", "[", "i", "]", "+=", "128", ";", "}", "}", "}" ]
Change the bit depth of samples. The input array. @param {!TypedArray} input The samples. @param {string} original The original bit depth of the data. One of "8" ... "53", "32f", "64" @param {string} target The desired bit depth for the data. One of "8" ... "53", "32f", "64" @param {!TypedArray} output The output array.
[ "Change", "the", "bit", "depth", "of", "samples", ".", "The", "input", "array", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L46-L76
19,437
rochars/wavefile
dist/wavefile.js
intToInt_
function intToInt_(sample, args) { if (sample > 0) { sample = parseInt((sample / args.oldMax) * args.newMax, 10); } else { sample = parseInt((sample / args.oldMin) * args.newMin, 10); } return sample; }
javascript
function intToInt_(sample, args) { if (sample > 0) { sample = parseInt((sample / args.oldMax) * args.newMax, 10); } else { sample = parseInt((sample / args.oldMin) * args.newMin, 10); } return sample; }
[ "function", "intToInt_", "(", "sample", ",", "args", ")", "{", "if", "(", "sample", ">", "0", ")", "{", "sample", "=", "parseInt", "(", "(", "sample", "/", "args", ".", "oldMax", ")", "*", "args", ".", "newMax", ",", "10", ")", ";", "}", "else", "{", "sample", "=", "parseInt", "(", "(", "sample", "/", "args", ".", "oldMin", ")", "*", "args", ".", "newMin", ",", "10", ")", ";", "}", "return", "sample", ";", "}" ]
Change the bit depth from int to int. @param {number} sample The sample. @param {!Object<string, number>} args Data about the original and target bit depths. @return {number} @private
[ "Change", "the", "bit", "depth", "from", "int", "to", "int", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L85-L92
19,438
rochars/wavefile
dist/wavefile.js
floatToInt_
function floatToInt_(sample, args) { return parseInt( sample > 0 ? sample * args.newMax : sample * args.newMin, 10); }
javascript
function floatToInt_(sample, args) { return parseInt( sample > 0 ? sample * args.newMax : sample * args.newMin, 10); }
[ "function", "floatToInt_", "(", "sample", ",", "args", ")", "{", "return", "parseInt", "(", "sample", ">", "0", "?", "sample", "*", "args", ".", "newMax", ":", "sample", "*", "args", ".", "newMin", ",", "10", ")", ";", "}" ]
Change the bit depth from float to int. @param {number} sample The sample. @param {!Object<string, number>} args Data about the original and target bit depths. @return {number} @private
[ "Change", "the", "bit", "depth", "from", "float", "to", "int", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L101-L104
19,439
rochars/wavefile
dist/wavefile.js
getBitDepthFunction_
function getBitDepthFunction_(original, target) { /** @type {!Function} */ let func = function(x) {return x;}; if (original != target) { if (["32f", "64"].includes(original)) { if (["32f", "64"].includes(target)) { func = floatToFloat_; } else { func = floatToInt_; } } else { if (["32f", "64"].includes(target)) { func = intToFloat_; } else { func = intToInt_; } } } return func; }
javascript
function getBitDepthFunction_(original, target) { /** @type {!Function} */ let func = function(x) {return x;}; if (original != target) { if (["32f", "64"].includes(original)) { if (["32f", "64"].includes(target)) { func = floatToFloat_; } else { func = floatToInt_; } } else { if (["32f", "64"].includes(target)) { func = intToFloat_; } else { func = intToInt_; } } } return func; }
[ "function", "getBitDepthFunction_", "(", "original", ",", "target", ")", "{", "/** @type {!Function} */", "let", "func", "=", "function", "(", "x", ")", "{", "return", "x", ";", "}", ";", "if", "(", "original", "!=", "target", ")", "{", "if", "(", "[", "\"32f\"", ",", "\"64\"", "]", ".", "includes", "(", "original", ")", ")", "{", "if", "(", "[", "\"32f\"", ",", "\"64\"", "]", ".", "includes", "(", "target", ")", ")", "{", "func", "=", "floatToFloat_", ";", "}", "else", "{", "func", "=", "floatToInt_", ";", "}", "}", "else", "{", "if", "(", "[", "\"32f\"", ",", "\"64\"", "]", ".", "includes", "(", "target", ")", ")", "{", "func", "=", "intToFloat_", ";", "}", "else", "{", "func", "=", "intToInt_", ";", "}", "}", "}", "return", "func", ";", "}" ]
Return the function to change the bit depth of a sample. @param {string} original The original bit depth of the data. One of "8" ... "53", "32f", "64" @param {string} target The new bit depth of the data. One of "8" ... "53", "32f", "64" @return {!Function} @private
[ "Return", "the", "function", "to", "change", "the", "bit", "depth", "of", "a", "sample", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L137-L156
19,440
rochars/wavefile
dist/wavefile.js
decode
function decode(adpcmSamples, blockAlign=256) { /** @type {!Int16Array} */ let samples = new Int16Array(adpcmSamples.length * 2); /** @type {!Array<number>} */ let block = []; /** @type {number} */ let fileIndex = 0; for (let i=0; i<adpcmSamples.length; i++) { if (i % blockAlign == 0 && i != 0) { samples.set(decodeBlock(block), fileIndex); fileIndex += blockAlign * 2; block = []; } block.push(adpcmSamples[i]); } return samples; }
javascript
function decode(adpcmSamples, blockAlign=256) { /** @type {!Int16Array} */ let samples = new Int16Array(adpcmSamples.length * 2); /** @type {!Array<number>} */ let block = []; /** @type {number} */ let fileIndex = 0; for (let i=0; i<adpcmSamples.length; i++) { if (i % blockAlign == 0 && i != 0) { samples.set(decodeBlock(block), fileIndex); fileIndex += blockAlign * 2; block = []; } block.push(adpcmSamples[i]); } return samples; }
[ "function", "decode", "(", "adpcmSamples", ",", "blockAlign", "=", "256", ")", "{", "/** @type {!Int16Array} */", "let", "samples", "=", "new", "Int16Array", "(", "adpcmSamples", ".", "length", "*", "2", ")", ";", "/** @type {!Array<number>} */", "let", "block", "=", "[", "]", ";", "/** @type {number} */", "let", "fileIndex", "=", "0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "adpcmSamples", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "%", "blockAlign", "==", "0", "&&", "i", "!=", "0", ")", "{", "samples", ".", "set", "(", "decodeBlock", "(", "block", ")", ",", "fileIndex", ")", ";", "fileIndex", "+=", "blockAlign", "*", "2", ";", "block", "=", "[", "]", ";", "}", "block", ".", "push", "(", "adpcmSamples", "[", "i", "]", ")", ";", "}", "return", "samples", ";", "}" ]
Decode IMA ADPCM samples into 16-bit PCM samples. @param {!Uint8Array} adpcmSamples A array of ADPCM samples. @param {number} blockAlign The block size. @return {!Int16Array}
[ "Decode", "IMA", "ADPCM", "samples", "into", "16", "-", "bit", "PCM", "samples", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L284-L300
19,441
rochars/wavefile
dist/wavefile.js
encodeBlock
function encodeBlock(block) { /** @type {!Array<number>} */ let adpcmSamples = blockHead_(block[0]); for (let i=3; i<block.length; i+=2) { /** @type {number} */ let sample2 = encodeSample_(block[i]); /** @type {number} */ let sample = encodeSample_(block[i + 1]); adpcmSamples.push((sample << 4) | sample2); } while (adpcmSamples.length < 256) { adpcmSamples.push(0); } return adpcmSamples; }
javascript
function encodeBlock(block) { /** @type {!Array<number>} */ let adpcmSamples = blockHead_(block[0]); for (let i=3; i<block.length; i+=2) { /** @type {number} */ let sample2 = encodeSample_(block[i]); /** @type {number} */ let sample = encodeSample_(block[i + 1]); adpcmSamples.push((sample << 4) | sample2); } while (adpcmSamples.length < 256) { adpcmSamples.push(0); } return adpcmSamples; }
[ "function", "encodeBlock", "(", "block", ")", "{", "/** @type {!Array<number>} */", "let", "adpcmSamples", "=", "blockHead_", "(", "block", "[", "0", "]", ")", ";", "for", "(", "let", "i", "=", "3", ";", "i", "<", "block", ".", "length", ";", "i", "+=", "2", ")", "{", "/** @type {number} */", "let", "sample2", "=", "encodeSample_", "(", "block", "[", "i", "]", ")", ";", "/** @type {number} */", "let", "sample", "=", "encodeSample_", "(", "block", "[", "i", "+", "1", "]", ")", ";", "adpcmSamples", ".", "push", "(", "(", "sample", "<<", "4", ")", "|", "sample2", ")", ";", "}", "while", "(", "adpcmSamples", ".", "length", "<", "256", ")", "{", "adpcmSamples", ".", "push", "(", "0", ")", ";", "}", "return", "adpcmSamples", ";", "}" ]
Encode a block of 505 16-bit samples as 4-bit ADPCM samples. @param {!Array<number>} block A sample block of 505 samples. @return {!Array<number>}
[ "Encode", "a", "block", "of", "505", "16", "-", "bit", "samples", "as", "4", "-", "bit", "ADPCM", "samples", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L307-L321
19,442
rochars/wavefile
dist/wavefile.js
decodeBlock
function decodeBlock(block) { decoderPredicted_ = sign_((block[1] << 8) | block[0]); decoderIndex_ = block[2]; decoderStep_ = STEP_TABLE[decoderIndex_]; /** @type {!Array<number>} */ let result = [ decoderPredicted_, sign_((block[3] << 8) | block[2]) ]; for (let i=4; i<block.length; i++) { /** @type {number} */ let original_sample = block[i]; /** @type {number} */ let second_sample = original_sample >> 4; /** @type {number} */ let first_sample = (second_sample << 4) ^ original_sample; result.push(decodeSample_(first_sample)); result.push(decodeSample_(second_sample)); } return result; }
javascript
function decodeBlock(block) { decoderPredicted_ = sign_((block[1] << 8) | block[0]); decoderIndex_ = block[2]; decoderStep_ = STEP_TABLE[decoderIndex_]; /** @type {!Array<number>} */ let result = [ decoderPredicted_, sign_((block[3] << 8) | block[2]) ]; for (let i=4; i<block.length; i++) { /** @type {number} */ let original_sample = block[i]; /** @type {number} */ let second_sample = original_sample >> 4; /** @type {number} */ let first_sample = (second_sample << 4) ^ original_sample; result.push(decodeSample_(first_sample)); result.push(decodeSample_(second_sample)); } return result; }
[ "function", "decodeBlock", "(", "block", ")", "{", "decoderPredicted_", "=", "sign_", "(", "(", "block", "[", "1", "]", "<<", "8", ")", "|", "block", "[", "0", "]", ")", ";", "decoderIndex_", "=", "block", "[", "2", "]", ";", "decoderStep_", "=", "STEP_TABLE", "[", "decoderIndex_", "]", ";", "/** @type {!Array<number>} */", "let", "result", "=", "[", "decoderPredicted_", ",", "sign_", "(", "(", "block", "[", "3", "]", "<<", "8", ")", "|", "block", "[", "2", "]", ")", "]", ";", "for", "(", "let", "i", "=", "4", ";", "i", "<", "block", ".", "length", ";", "i", "++", ")", "{", "/** @type {number} */", "let", "original_sample", "=", "block", "[", "i", "]", ";", "/** @type {number} */", "let", "second_sample", "=", "original_sample", ">>", "4", ";", "/** @type {number} */", "let", "first_sample", "=", "(", "second_sample", "<<", "4", ")", "^", "original_sample", ";", "result", ".", "push", "(", "decodeSample_", "(", "first_sample", ")", ")", ";", "result", ".", "push", "(", "decodeSample_", "(", "second_sample", ")", ")", ";", "}", "return", "result", ";", "}" ]
Decode a block of ADPCM samples into 16-bit PCM samples. @param {!Array<number>} block A adpcm sample block. @return {!Array<number>}
[ "Decode", "a", "block", "of", "ADPCM", "samples", "into", "16", "-", "bit", "PCM", "samples", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L328-L348
19,443
rochars/wavefile
dist/wavefile.js
encodeSample_
function encodeSample_(sample) { /** @type {number} */ let delta = sample - encoderPredicted_; /** @type {number} */ let value = 0; if (delta >= 0) { value = 0; } else { value = 8; delta = -delta; } /** @type {number} */ let step = STEP_TABLE[encoderIndex_]; /** @type {number} */ let diff = step >> 3; if (delta > step) { value |= 4; delta -= step; diff += step; } step >>= 1; if (delta > step) { value |= 2; delta -= step; diff += step; } step >>= 1; if (delta > step) { value |= 1; diff += step; } updateEncoder_(value, diff); return value; }
javascript
function encodeSample_(sample) { /** @type {number} */ let delta = sample - encoderPredicted_; /** @type {number} */ let value = 0; if (delta >= 0) { value = 0; } else { value = 8; delta = -delta; } /** @type {number} */ let step = STEP_TABLE[encoderIndex_]; /** @type {number} */ let diff = step >> 3; if (delta > step) { value |= 4; delta -= step; diff += step; } step >>= 1; if (delta > step) { value |= 2; delta -= step; diff += step; } step >>= 1; if (delta > step) { value |= 1; diff += step; } updateEncoder_(value, diff); return value; }
[ "function", "encodeSample_", "(", "sample", ")", "{", "/** @type {number} */", "let", "delta", "=", "sample", "-", "encoderPredicted_", ";", "/** @type {number} */", "let", "value", "=", "0", ";", "if", "(", "delta", ">=", "0", ")", "{", "value", "=", "0", ";", "}", "else", "{", "value", "=", "8", ";", "delta", "=", "-", "delta", ";", "}", "/** @type {number} */", "let", "step", "=", "STEP_TABLE", "[", "encoderIndex_", "]", ";", "/** @type {number} */", "let", "diff", "=", "step", ">>", "3", ";", "if", "(", "delta", ">", "step", ")", "{", "value", "|=", "4", ";", "delta", "-=", "step", ";", "diff", "+=", "step", ";", "}", "step", ">>=", "1", ";", "if", "(", "delta", ">", "step", ")", "{", "value", "|=", "2", ";", "delta", "-=", "step", ";", "diff", "+=", "step", ";", "}", "step", ">>=", "1", ";", "if", "(", "delta", ">", "step", ")", "{", "value", "|=", "1", ";", "diff", "+=", "step", ";", "}", "updateEncoder_", "(", "value", ",", "diff", ")", ";", "return", "value", ";", "}" ]
Compress a 16-bit PCM sample into a 4-bit ADPCM sample. @param {number} sample The sample. @return {number} @private
[ "Compress", "a", "16", "-", "bit", "PCM", "sample", "into", "a", "4", "-", "bit", "ADPCM", "sample", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L366-L399
19,444
rochars/wavefile
dist/wavefile.js
decodeSample_
function decodeSample_(nibble) { /** @type {number} */ let difference = 0; if (nibble & 4) { difference += decoderStep_; } if (nibble & 2) { difference += decoderStep_ >> 1; } if (nibble & 1) { difference += decoderStep_ >> 2; } difference += decoderStep_ >> 3; if (nibble & 8) { difference = -difference; } decoderPredicted_ += difference; if (decoderPredicted_ > 32767) { decoderPredicted_ = 32767; } else if (decoderPredicted_ < -32767) { decoderPredicted_ = -32767; } updateDecoder_(nibble); return decoderPredicted_; }
javascript
function decodeSample_(nibble) { /** @type {number} */ let difference = 0; if (nibble & 4) { difference += decoderStep_; } if (nibble & 2) { difference += decoderStep_ >> 1; } if (nibble & 1) { difference += decoderStep_ >> 2; } difference += decoderStep_ >> 3; if (nibble & 8) { difference = -difference; } decoderPredicted_ += difference; if (decoderPredicted_ > 32767) { decoderPredicted_ = 32767; } else if (decoderPredicted_ < -32767) { decoderPredicted_ = -32767; } updateDecoder_(nibble); return decoderPredicted_; }
[ "function", "decodeSample_", "(", "nibble", ")", "{", "/** @type {number} */", "let", "difference", "=", "0", ";", "if", "(", "nibble", "&", "4", ")", "{", "difference", "+=", "decoderStep_", ";", "}", "if", "(", "nibble", "&", "2", ")", "{", "difference", "+=", "decoderStep_", ">>", "1", ";", "}", "if", "(", "nibble", "&", "1", ")", "{", "difference", "+=", "decoderStep_", ">>", "2", ";", "}", "difference", "+=", "decoderStep_", ">>", "3", ";", "if", "(", "nibble", "&", "8", ")", "{", "difference", "=", "-", "difference", ";", "}", "decoderPredicted_", "+=", "difference", ";", "if", "(", "decoderPredicted_", ">", "32767", ")", "{", "decoderPredicted_", "=", "32767", ";", "}", "else", "if", "(", "decoderPredicted_", "<", "-", "32767", ")", "{", "decoderPredicted_", "=", "-", "32767", ";", "}", "updateDecoder_", "(", "nibble", ")", ";", "return", "decoderPredicted_", ";", "}" ]
Decode a 4-bit ADPCM sample into a 16-bit PCM sample. @param {number} nibble A 4-bit adpcm sample. @return {number} @private
[ "Decode", "a", "4", "-", "bit", "ADPCM", "sample", "into", "a", "16", "-", "bit", "PCM", "sample", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L433-L457
19,445
rochars/wavefile
dist/wavefile.js
blockHead_
function blockHead_(sample) { encodeSample_(sample); /** @type {!Array<number>} */ let adpcmSamples = []; adpcmSamples.push(sample & 0xFF); adpcmSamples.push((sample >> 8) & 0xFF); adpcmSamples.push(encoderIndex_); adpcmSamples.push(0); return adpcmSamples; }
javascript
function blockHead_(sample) { encodeSample_(sample); /** @type {!Array<number>} */ let adpcmSamples = []; adpcmSamples.push(sample & 0xFF); adpcmSamples.push((sample >> 8) & 0xFF); adpcmSamples.push(encoderIndex_); adpcmSamples.push(0); return adpcmSamples; }
[ "function", "blockHead_", "(", "sample", ")", "{", "encodeSample_", "(", "sample", ")", ";", "/** @type {!Array<number>} */", "let", "adpcmSamples", "=", "[", "]", ";", "adpcmSamples", ".", "push", "(", "sample", "&", "0xFF", ")", ";", "adpcmSamples", ".", "push", "(", "(", "sample", ">>", "8", ")", "&", "0xFF", ")", ";", "adpcmSamples", ".", "push", "(", "encoderIndex_", ")", ";", "adpcmSamples", ".", "push", "(", "0", ")", ";", "return", "adpcmSamples", ";", "}" ]
Return the head of a ADPCM sample block. @param {number} sample The first sample of the block. @return {!Array<number>} @private
[ "Return", "the", "head", "of", "a", "ADPCM", "sample", "block", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L480-L489
19,446
rochars/wavefile
dist/wavefile.js
encodeSample
function encodeSample(sample) { /** @type {number} */ let compandedValue; sample = (sample ==-32768) ? -32767 : sample; /** @type {number} */ let sign = ((~sample) >> 8) & 0x80; if (!sign) { sample = sample * -1; } if (sample > 32635) { sample = 32635; } if (sample >= 256) { /** @type {number} */ let exponent = LOG_TABLE[(sample >> 8) & 0x7F]; /** @type {number} */ let mantissa = (sample >> (exponent + 3) ) & 0x0F; compandedValue = ((exponent << 4) | mantissa); } else { compandedValue = sample >> 4; } return compandedValue ^ (sign ^ 0x55); }
javascript
function encodeSample(sample) { /** @type {number} */ let compandedValue; sample = (sample ==-32768) ? -32767 : sample; /** @type {number} */ let sign = ((~sample) >> 8) & 0x80; if (!sign) { sample = sample * -1; } if (sample > 32635) { sample = 32635; } if (sample >= 256) { /** @type {number} */ let exponent = LOG_TABLE[(sample >> 8) & 0x7F]; /** @type {number} */ let mantissa = (sample >> (exponent + 3) ) & 0x0F; compandedValue = ((exponent << 4) | mantissa); } else { compandedValue = sample >> 4; } return compandedValue ^ (sign ^ 0x55); }
[ "function", "encodeSample", "(", "sample", ")", "{", "/** @type {number} */", "let", "compandedValue", ";", "sample", "=", "(", "sample", "==", "-", "32768", ")", "?", "-", "32767", ":", "sample", ";", "/** @type {number} */", "let", "sign", "=", "(", "(", "~", "sample", ")", ">>", "8", ")", "&", "0x80", ";", "if", "(", "!", "sign", ")", "{", "sample", "=", "sample", "*", "-", "1", ";", "}", "if", "(", "sample", ">", "32635", ")", "{", "sample", "=", "32635", ";", "}", "if", "(", "sample", ">=", "256", ")", "{", "/** @type {number} */", "let", "exponent", "=", "LOG_TABLE", "[", "(", "sample", ">>", "8", ")", "&", "0x7F", "]", ";", "/** @type {number} */", "let", "mantissa", "=", "(", "sample", ">>", "(", "exponent", "+", "3", ")", ")", "&", "0x0F", ";", "compandedValue", "=", "(", "(", "exponent", "<<", "4", ")", "|", "mantissa", ")", ";", "}", "else", "{", "compandedValue", "=", "sample", ">>", "4", ";", "}", "return", "compandedValue", "^", "(", "sign", "^", "0x55", ")", ";", "}" ]
Encode a 16-bit linear PCM sample as 8-bit A-Law. @param {number} sample A 16-bit PCM sample @return {number}
[ "Encode", "a", "16", "-", "bit", "linear", "PCM", "sample", "as", "8", "-", "bit", "A", "-", "Law", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L537-L559
19,447
rochars/wavefile
dist/wavefile.js
decodeSample
function decodeSample(aLawSample) { /** @type {number} */ let sign = 0; aLawSample ^= 0x55; if (aLawSample & 0x80) { aLawSample &= ~(1 << 7); sign = -1; } /** @type {number} */ let position = ((aLawSample & 0xF0) >> 4) + 4; /** @type {number} */ let decoded = 0; if (position != 4) { decoded = ((1 << position) | ((aLawSample & 0x0F) << (position - 4)) | (1 << (position - 5))); } else { decoded = (aLawSample << 1)|1; } decoded = (sign === 0) ? (decoded) : (-decoded); return (decoded * 8) * -1; }
javascript
function decodeSample(aLawSample) { /** @type {number} */ let sign = 0; aLawSample ^= 0x55; if (aLawSample & 0x80) { aLawSample &= ~(1 << 7); sign = -1; } /** @type {number} */ let position = ((aLawSample & 0xF0) >> 4) + 4; /** @type {number} */ let decoded = 0; if (position != 4) { decoded = ((1 << position) | ((aLawSample & 0x0F) << (position - 4)) | (1 << (position - 5))); } else { decoded = (aLawSample << 1)|1; } decoded = (sign === 0) ? (decoded) : (-decoded); return (decoded * 8) * -1; }
[ "function", "decodeSample", "(", "aLawSample", ")", "{", "/** @type {number} */", "let", "sign", "=", "0", ";", "aLawSample", "^=", "0x55", ";", "if", "(", "aLawSample", "&", "0x80", ")", "{", "aLawSample", "&=", "~", "(", "1", "<<", "7", ")", ";", "sign", "=", "-", "1", ";", "}", "/** @type {number} */", "let", "position", "=", "(", "(", "aLawSample", "&", "0xF0", ")", ">>", "4", ")", "+", "4", ";", "/** @type {number} */", "let", "decoded", "=", "0", ";", "if", "(", "position", "!=", "4", ")", "{", "decoded", "=", "(", "(", "1", "<<", "position", ")", "|", "(", "(", "aLawSample", "&", "0x0F", ")", "<<", "(", "position", "-", "4", ")", ")", "|", "(", "1", "<<", "(", "position", "-", "5", ")", ")", ")", ";", "}", "else", "{", "decoded", "=", "(", "aLawSample", "<<", "1", ")", "|", "1", ";", "}", "decoded", "=", "(", "sign", "===", "0", ")", "?", "(", "decoded", ")", ":", "(", "-", "decoded", ")", ";", "return", "(", "decoded", "*", "8", ")", "*", "-", "1", ";", "}" ]
Decode a 8-bit A-Law sample as 16-bit PCM. @param {number} aLawSample The 8-bit A-Law sample @return {number}
[ "Decode", "a", "8", "-", "bit", "A", "-", "Law", "sample", "as", "16", "-", "bit", "PCM", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L566-L587
19,448
rochars/wavefile
dist/wavefile.js
decode$1
function decode$1(samples) { /** @type {!Int16Array} */ let pcmSamples = new Int16Array(samples.length); for (let i=0; i<samples.length; i++) { pcmSamples[i] = decodeSample(samples[i]); } return pcmSamples; }
javascript
function decode$1(samples) { /** @type {!Int16Array} */ let pcmSamples = new Int16Array(samples.length); for (let i=0; i<samples.length; i++) { pcmSamples[i] = decodeSample(samples[i]); } return pcmSamples; }
[ "function", "decode$1", "(", "samples", ")", "{", "/** @type {!Int16Array} */", "let", "pcmSamples", "=", "new", "Int16Array", "(", "samples", ".", "length", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "samples", ".", "length", ";", "i", "++", ")", "{", "pcmSamples", "[", "i", "]", "=", "decodeSample", "(", "samples", "[", "i", "]", ")", ";", "}", "return", "pcmSamples", ";", "}" ]
Decode 8-bit A-Law samples into 16-bit linear PCM samples. @param {!Uint8Array} samples A array of 8-bit A-Law samples. @return {!Int16Array}
[ "Decode", "8", "-", "bit", "A", "-", "Law", "samples", "into", "16", "-", "bit", "linear", "PCM", "samples", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L608-L615
19,449
rochars/wavefile
dist/wavefile.js
encodeSample$1
function encodeSample$1(sample) { /** @type {number} */ let sign; /** @type {number} */ let exponent; /** @type {number} */ let mantissa; /** @type {number} */ let muLawSample; /** get the sample into sign-magnitude **/ sign = (sample >> 8) & 0x80; if (sign != 0) sample = -sample; if (sample > CLIP) sample = CLIP; /** convert from 16 bit linear to ulaw **/ sample = sample + BIAS; exponent = encodeTable[(sample>>7) & 0xFF]; mantissa = (sample >> (exponent+3)) & 0x0F; muLawSample = ~(sign | (exponent << 4) | mantissa); /** return the result **/ return muLawSample; }
javascript
function encodeSample$1(sample) { /** @type {number} */ let sign; /** @type {number} */ let exponent; /** @type {number} */ let mantissa; /** @type {number} */ let muLawSample; /** get the sample into sign-magnitude **/ sign = (sample >> 8) & 0x80; if (sign != 0) sample = -sample; if (sample > CLIP) sample = CLIP; /** convert from 16 bit linear to ulaw **/ sample = sample + BIAS; exponent = encodeTable[(sample>>7) & 0xFF]; mantissa = (sample >> (exponent+3)) & 0x0F; muLawSample = ~(sign | (exponent << 4) | mantissa); /** return the result **/ return muLawSample; }
[ "function", "encodeSample$1", "(", "sample", ")", "{", "/** @type {number} */", "let", "sign", ";", "/** @type {number} */", "let", "exponent", ";", "/** @type {number} */", "let", "mantissa", ";", "/** @type {number} */", "let", "muLawSample", ";", "/** get the sample into sign-magnitude **/", "sign", "=", "(", "sample", ">>", "8", ")", "&", "0x80", ";", "if", "(", "sign", "!=", "0", ")", "sample", "=", "-", "sample", ";", "if", "(", "sample", ">", "CLIP", ")", "sample", "=", "CLIP", ";", "/** convert from 16 bit linear to ulaw **/", "sample", "=", "sample", "+", "BIAS", ";", "exponent", "=", "encodeTable", "[", "(", "sample", ">>", "7", ")", "&", "0xFF", "]", ";", "mantissa", "=", "(", "sample", ">>", "(", "exponent", "+", "3", ")", ")", "&", "0x0F", ";", "muLawSample", "=", "~", "(", "sign", "|", "(", "exponent", "<<", "4", ")", "|", "mantissa", ")", ";", "/** return the result **/", "return", "muLawSample", ";", "}" ]
Encode a 16-bit linear PCM sample as 8-bit mu-Law. @param {number} sample A 16-bit PCM sample @return {number}
[ "Encode", "a", "16", "-", "bit", "linear", "PCM", "sample", "as", "8", "-", "bit", "mu", "-", "Law", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L692-L712
19,450
rochars/wavefile
dist/wavefile.js
decodeSample$1
function decodeSample$1(muLawSample) { /** @type {number} */ let sign; /** @type {number} */ let exponent; /** @type {number} */ let mantissa; /** @type {number} */ let sample; muLawSample = ~muLawSample; sign = (muLawSample & 0x80); exponent = (muLawSample >> 4) & 0x07; mantissa = muLawSample & 0x0F; sample = decodeTable[exponent] + (mantissa << (exponent+3)); if (sign != 0) sample = -sample; return sample; }
javascript
function decodeSample$1(muLawSample) { /** @type {number} */ let sign; /** @type {number} */ let exponent; /** @type {number} */ let mantissa; /** @type {number} */ let sample; muLawSample = ~muLawSample; sign = (muLawSample & 0x80); exponent = (muLawSample >> 4) & 0x07; mantissa = muLawSample & 0x0F; sample = decodeTable[exponent] + (mantissa << (exponent+3)); if (sign != 0) sample = -sample; return sample; }
[ "function", "decodeSample$1", "(", "muLawSample", ")", "{", "/** @type {number} */", "let", "sign", ";", "/** @type {number} */", "let", "exponent", ";", "/** @type {number} */", "let", "mantissa", ";", "/** @type {number} */", "let", "sample", ";", "muLawSample", "=", "~", "muLawSample", ";", "sign", "=", "(", "muLawSample", "&", "0x80", ")", ";", "exponent", "=", "(", "muLawSample", ">>", "4", ")", "&", "0x07", ";", "mantissa", "=", "muLawSample", "&", "0x0F", ";", "sample", "=", "decodeTable", "[", "exponent", "]", "+", "(", "mantissa", "<<", "(", "exponent", "+", "3", ")", ")", ";", "if", "(", "sign", "!=", "0", ")", "sample", "=", "-", "sample", ";", "return", "sample", ";", "}" ]
Decode a 8-bit mu-Law sample as 16-bit PCM. @param {number} muLawSample The 8-bit mu-Law sample @return {number}
[ "Decode", "a", "8", "-", "bit", "mu", "-", "Law", "sample", "as", "16", "-", "bit", "PCM", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L719-L735
19,451
rochars/wavefile
dist/wavefile.js
swap
function swap(bytes, offset, index) { offset--; for(let x = 0; x < offset; x++) { /** @type {*} */ let theByte = bytes[index + x]; bytes[index + x] = bytes[index + offset]; bytes[index + offset] = theByte; offset--; } }
javascript
function swap(bytes, offset, index) { offset--; for(let x = 0; x < offset; x++) { /** @type {*} */ let theByte = bytes[index + x]; bytes[index + x] = bytes[index + offset]; bytes[index + offset] = theByte; offset--; } }
[ "function", "swap", "(", "bytes", ",", "offset", ",", "index", ")", "{", "offset", "--", ";", "for", "(", "let", "x", "=", "0", ";", "x", "<", "offset", ";", "x", "++", ")", "{", "/** @type {*} */", "let", "theByte", "=", "bytes", "[", "index", "+", "x", "]", ";", "bytes", "[", "index", "+", "x", "]", "=", "bytes", "[", "index", "+", "offset", "]", ";", "bytes", "[", "index", "+", "offset", "]", "=", "theByte", ";", "offset", "--", ";", "}", "}" ]
Swap the byte order of a value in a buffer. The buffer is modified in place. @param {!Array|!Uint8Array} bytes The bytes. @param {number} offset The byte offset. @param {number} index The start index. @private
[ "Swap", "the", "byte", "order", "of", "a", "value", "in", "a", "buffer", ".", "The", "buffer", "is", "modified", "in", "place", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L915-L924
19,452
rochars/wavefile
dist/wavefile.js
pack
function pack(str, buffer, index=0) { for (let i = 0, len = str.length; i < len; i++) { /** @type {number} */ let codePoint = str.codePointAt(i); if (codePoint < 128) { buffer[index] = codePoint; index++; } else { /** @type {number} */ let count = 0; /** @type {number} */ let offset = 0; if (codePoint <= 0x07FF) { count = 1; offset = 0xC0; } else if(codePoint <= 0xFFFF) { count = 2; offset = 0xE0; } else if(codePoint <= 0x10FFFF) { count = 3; offset = 0xF0; i++; } buffer[index] = (codePoint >> (6 * count)) + offset; index++; while (count > 0) { buffer[index] = 0x80 | (codePoint >> (6 * (count - 1)) & 0x3F); index++; count--; } } } return index; }
javascript
function pack(str, buffer, index=0) { for (let i = 0, len = str.length; i < len; i++) { /** @type {number} */ let codePoint = str.codePointAt(i); if (codePoint < 128) { buffer[index] = codePoint; index++; } else { /** @type {number} */ let count = 0; /** @type {number} */ let offset = 0; if (codePoint <= 0x07FF) { count = 1; offset = 0xC0; } else if(codePoint <= 0xFFFF) { count = 2; offset = 0xE0; } else if(codePoint <= 0x10FFFF) { count = 3; offset = 0xF0; i++; } buffer[index] = (codePoint >> (6 * count)) + offset; index++; while (count > 0) { buffer[index] = 0x80 | (codePoint >> (6 * (count - 1)) & 0x3F); index++; count--; } } } return index; }
[ "function", "pack", "(", "str", ",", "buffer", ",", "index", "=", "0", ")", "{", "for", "(", "let", "i", "=", "0", ",", "len", "=", "str", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "/** @type {number} */", "let", "codePoint", "=", "str", ".", "codePointAt", "(", "i", ")", ";", "if", "(", "codePoint", "<", "128", ")", "{", "buffer", "[", "index", "]", "=", "codePoint", ";", "index", "++", ";", "}", "else", "{", "/** @type {number} */", "let", "count", "=", "0", ";", "/** @type {number} */", "let", "offset", "=", "0", ";", "if", "(", "codePoint", "<=", "0x07FF", ")", "{", "count", "=", "1", ";", "offset", "=", "0xC0", ";", "}", "else", "if", "(", "codePoint", "<=", "0xFFFF", ")", "{", "count", "=", "2", ";", "offset", "=", "0xE0", ";", "}", "else", "if", "(", "codePoint", "<=", "0x10FFFF", ")", "{", "count", "=", "3", ";", "offset", "=", "0xF0", ";", "i", "++", ";", "}", "buffer", "[", "index", "]", "=", "(", "codePoint", ">>", "(", "6", "*", "count", ")", ")", "+", "offset", ";", "index", "++", ";", "while", "(", "count", ">", "0", ")", "{", "buffer", "[", "index", "]", "=", "0x80", "|", "(", "codePoint", ">>", "(", "6", "*", "(", "count", "-", "1", ")", ")", "&", "0x3F", ")", ";", "index", "++", ";", "count", "--", ";", "}", "}", "}", "return", "index", ";", "}" ]
Write a string of UTF-8 characters to a byte buffer. @see https://encoding.spec.whatwg.org/#utf-8-encoder @param {string} str The string to pack. @param {!Uint8Array|!Array<number>} buffer The buffer to pack the string to. @param {number=} index The buffer index to start writing. @return {number} The next index to write in the buffer.
[ "Write", "a", "string", "of", "UTF", "-", "8", "characters", "to", "a", "byte", "buffer", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L1040-L1073
19,453
rochars/wavefile
dist/wavefile.js
unpackString
function unpackString(buffer, index=0, end=buffer.length) { return unpack(buffer, index, end); }
javascript
function unpackString(buffer, index=0, end=buffer.length) { return unpack(buffer, index, end); }
[ "function", "unpackString", "(", "buffer", ",", "index", "=", "0", ",", "end", "=", "buffer", ".", "length", ")", "{", "return", "unpack", "(", "buffer", ",", "index", ",", "end", ")", ";", "}" ]
Read a string of UTF-8 characters from a byte buffer. @param {!Uint8Array|!Array<number>} buffer A byte buffer. @param {number=} index The buffer index to start reading. @param {number=} end The buffer index to stop reading, non inclusive. Assumes buffer length if undefined. @return {string}
[ "Read", "a", "string", "of", "UTF", "-", "8", "characters", "from", "a", "byte", "buffer", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L1742-L1744
19,454
rochars/wavefile
dist/wavefile.js
unpackArrayTo
function unpackArrayTo( buffer, theType, output, start=0, end=buffer.length, safe=false) { theType = theType || {}; /** @type {NumberBuffer} */ let packer = new NumberBuffer(theType.bits, theType.fp, theType.signed); /** @type {number} */ let offset = packer.offset; // getUnpackLen_ will either fix the length of the input buffer // according to the byte offset of the type (on unsafe mode) or // throw a Error if the input buffer has a bad length (on safe mode) end = getUnpackLen_(buffer, start, end, offset, safe); /** @type {number} */ let index = 0; let j = start; try { if (theType.be) { endianness(buffer, offset, start, end); } for (; j < end; j += offset, index++) { output[index] = packer.unpack(buffer, j); } if (theType.be) { endianness(buffer, offset, start, end); } } catch (e) { throwValueError_(e, buffer.slice(j, j + offset), j, theType.fp); } }
javascript
function unpackArrayTo( buffer, theType, output, start=0, end=buffer.length, safe=false) { theType = theType || {}; /** @type {NumberBuffer} */ let packer = new NumberBuffer(theType.bits, theType.fp, theType.signed); /** @type {number} */ let offset = packer.offset; // getUnpackLen_ will either fix the length of the input buffer // according to the byte offset of the type (on unsafe mode) or // throw a Error if the input buffer has a bad length (on safe mode) end = getUnpackLen_(buffer, start, end, offset, safe); /** @type {number} */ let index = 0; let j = start; try { if (theType.be) { endianness(buffer, offset, start, end); } for (; j < end; j += offset, index++) { output[index] = packer.unpack(buffer, j); } if (theType.be) { endianness(buffer, offset, start, end); } } catch (e) { throwValueError_(e, buffer.slice(j, j + offset), j, theType.fp); } }
[ "function", "unpackArrayTo", "(", "buffer", ",", "theType", ",", "output", ",", "start", "=", "0", ",", "end", "=", "buffer", ".", "length", ",", "safe", "=", "false", ")", "{", "theType", "=", "theType", "||", "{", "}", ";", "/** @type {NumberBuffer} */", "let", "packer", "=", "new", "NumberBuffer", "(", "theType", ".", "bits", ",", "theType", ".", "fp", ",", "theType", ".", "signed", ")", ";", "/** @type {number} */", "let", "offset", "=", "packer", ".", "offset", ";", "// getUnpackLen_ will either fix the length of the input buffer", "// according to the byte offset of the type (on unsafe mode) or", "// throw a Error if the input buffer has a bad length (on safe mode)", "end", "=", "getUnpackLen_", "(", "buffer", ",", "start", ",", "end", ",", "offset", ",", "safe", ")", ";", "/** @type {number} */", "let", "index", "=", "0", ";", "let", "j", "=", "start", ";", "try", "{", "if", "(", "theType", ".", "be", ")", "{", "endianness", "(", "buffer", ",", "offset", ",", "start", ",", "end", ")", ";", "}", "for", "(", ";", "j", "<", "end", ";", "j", "+=", "offset", ",", "index", "++", ")", "{", "output", "[", "index", "]", "=", "packer", ".", "unpack", "(", "buffer", ",", "j", ")", ";", "}", "if", "(", "theType", ".", "be", ")", "{", "endianness", "(", "buffer", ",", "offset", ",", "start", ",", "end", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "throwValueError_", "(", "e", ",", "buffer", ".", "slice", "(", "j", ",", "j", "+", "offset", ")", ",", "j", ",", "theType", ".", "fp", ")", ";", "}", "}" ]
Unpack a array of numbers to a typed array. All other unpacking functions are interfaces to this function. @param {!Uint8Array|!Array<number>} buffer The byte buffer. @param {!Object} theType The type definition. @param {!TypedArray|!Array<number>} output The output array. @param {number=} start The buffer index to start reading. Assumes zero if undefined. @param {number=} end The buffer index to stop reading. Assumes the buffer length if undefined. @param {boolean=} safe If set to false, extra bytes in the end of the array are ignored and input buffers with insufficient bytes will write nothing to the output array. If safe is set to true the function will throw a 'Bad buffer length' error. Defaults to false. @throws {Error} If the type definition is not valid @throws {Error} On overflow
[ "Unpack", "a", "array", "of", "numbers", "to", "a", "typed", "array", ".", "All", "other", "unpacking", "functions", "are", "interfaces", "to", "this", "function", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L1822-L1849
19,455
rochars/wavefile
dist/wavefile.js
packTo
function packTo(value, theType, buffer, index=0) { return packArrayTo([value], theType, buffer, index); }
javascript
function packTo(value, theType, buffer, index=0) { return packArrayTo([value], theType, buffer, index); }
[ "function", "packTo", "(", "value", ",", "theType", ",", "buffer", ",", "index", "=", "0", ")", "{", "return", "packArrayTo", "(", "[", "value", "]", ",", "theType", ",", "buffer", ",", "index", ")", ";", "}" ]
Pack a number to a byte buffer. @param {number} value The value. @param {!Object} theType The type definition. @param {!Uint8Array|!Array<number>} buffer The output buffer. @param {number=} index The buffer index to write. Assumes 0 if undefined. @return {number} The next index to write. @throws {Error} If the type definition is not valid. @throws {Error} If the value is not valid.
[ "Pack", "a", "number", "to", "a", "byte", "buffer", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L1861-L1863
19,456
rochars/wavefile
dist/wavefile.js
unpackArray
function unpackArray( buffer, theType, start=0, end=buffer.length, safe=false) { /** @type {!Array<number>} */ let output = []; unpackArrayTo(buffer, theType, output, start, end, safe); return output; }
javascript
function unpackArray( buffer, theType, start=0, end=buffer.length, safe=false) { /** @type {!Array<number>} */ let output = []; unpackArrayTo(buffer, theType, output, start, end, safe); return output; }
[ "function", "unpackArray", "(", "buffer", ",", "theType", ",", "start", "=", "0", ",", "end", "=", "buffer", ".", "length", ",", "safe", "=", "false", ")", "{", "/** @type {!Array<number>} */", "let", "output", "=", "[", "]", ";", "unpackArrayTo", "(", "buffer", ",", "theType", ",", "output", ",", "start", ",", "end", ",", "safe", ")", ";", "return", "output", ";", "}" ]
Unpack an array of numbers from a byte buffer. @param {!Uint8Array|!Array<number>} buffer The byte buffer. @param {!Object} theType The type definition. @param {number=} start The buffer index to start reading. Assumes zero if undefined. @param {number=} end The buffer index to stop reading. Assumes the buffer length if undefined. @param {boolean=} safe If set to false, extra bytes in the end of the array are ignored and input buffers with insufficient bytes will output a empty array. If safe is set to true the function will throw a 'Bad buffer length' error. Defaults to false. @return {!Array<number>} @throws {Error} If the type definition is not valid @throws {Error} On overflow
[ "Unpack", "an", "array", "of", "numbers", "from", "a", "byte", "buffer", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L1896-L1902
19,457
rochars/wavefile
dist/wavefile.js
unpack$1
function unpack$1(buffer, theType, index=0) { return unpackArray( buffer, theType, index, index + Math.ceil(theType.bits / 8), true)[0]; }
javascript
function unpack$1(buffer, theType, index=0) { return unpackArray( buffer, theType, index, index + Math.ceil(theType.bits / 8), true)[0]; }
[ "function", "unpack$1", "(", "buffer", ",", "theType", ",", "index", "=", "0", ")", "{", "return", "unpackArray", "(", "buffer", ",", "theType", ",", "index", ",", "index", "+", "Math", ".", "ceil", "(", "theType", ".", "bits", "/", "8", ")", ",", "true", ")", "[", "0", "]", ";", "}" ]
Unpack a number from a byte buffer. @param {!Uint8Array|!Array<number>} buffer The byte buffer. @param {!Object} theType The type definition. @param {number=} index The buffer index to read. Assumes zero if undefined. @return {number} @throws {Error} If the type definition is not valid @throws {Error} On bad buffer length. @throws {Error} On overflow
[ "Unpack", "a", "number", "from", "a", "byte", "buffer", "." ]
fb9d9c7adb38f6a046857cef24e3651e8a849102
https://github.com/rochars/wavefile/blob/fb9d9c7adb38f6a046857cef24e3651e8a849102/dist/wavefile.js#L1914-L1917
19,458
yatskevich/grunt-bower-task
tasks/lib/layouts_manager.js
function(layout, fail) { if (_.isFunction(layout)) { return layout; } if (!_.isString(layout)) { fail('Layout should be specified by name or as a function'); } if (_(defaultLayouts).has(layout)) { return defaultLayouts[layout]; } fail('The following named layouts are supported: ' + _.keys(defaultLayouts).join(', ')); }
javascript
function(layout, fail) { if (_.isFunction(layout)) { return layout; } if (!_.isString(layout)) { fail('Layout should be specified by name or as a function'); } if (_(defaultLayouts).has(layout)) { return defaultLayouts[layout]; } fail('The following named layouts are supported: ' + _.keys(defaultLayouts).join(', ')); }
[ "function", "(", "layout", ",", "fail", ")", "{", "if", "(", "_", ".", "isFunction", "(", "layout", ")", ")", "{", "return", "layout", ";", "}", "if", "(", "!", "_", ".", "isString", "(", "layout", ")", ")", "{", "fail", "(", "'Layout should be specified by name or as a function'", ")", ";", "}", "if", "(", "_", "(", "defaultLayouts", ")", ".", "has", "(", "layout", ")", ")", "{", "return", "defaultLayouts", "[", "layout", "]", ";", "}", "fail", "(", "'The following named layouts are supported: '", "+", "_", ".", "keys", "(", "defaultLayouts", ")", ".", "join", "(", "', '", ")", ")", ";", "}" ]
Resolves named layouts, returns functions as is @param {string | Function} layout name or layout function @param { Function } fail handler @returns {Function} layout function
[ "Resolves", "named", "layouts", "returns", "functions", "as", "is" ]
76525ba9e45f097f9a07845b06c03ae5c8eb79cb
https://github.com/yatskevich/grunt-bower-task/blob/76525ba9e45f097f9a07845b06c03ae5c8eb79cb/tasks/lib/layouts_manager.js#L32-L46
19,459
dollarshaveclub/ember-uni-form
addon/utils/pathify.js
pathifyModel
function pathifyModel (model, store, prefix) { let result = [] if (prefix) result.push(prefix) if (get(model, '_internalModel.modelName') === 'uni-form') { const propPath = propertyPath('payload', prefix) if (model.get('payload') instanceof DS.Model) { return result.concat(pathifyModel(model.get('payload'), store, propPath)) } return result.concat(pathifyObject(model.get('payload'), store, propPath)) } // Pathify serializer output const payload = model.serialize() const { attributes, data } = payload if (attributes) result = result.concat(pathifyObject(attributes, store, prefix)) // JSONAPI else if (data) result = result.concat(pathifyObject(data, store, prefix)) // JSONAPI else result = result.concat(pathifyObject(payload, store, prefix)) // Not JSONAPI // Pathify model attributes and child models which will be serialized const serializer = store.serializerFor(get(model, '_internalModel.modelName')) model.eachAttribute(name => result.push(propertyPath(name, prefix))) model.eachRelationship((name, { kind, type }) => { if (kind === 'hasMany') return // not supported const childPath = propertyPath(name, prefix) const willSerialize = get(serializer, `attrs.${name}.serialize`) === 'records' || get(serializer, `attrs.${name}.embedded`) === 'always' if (!willSerialize) { result.push(childPath) } else { const instance = store.createRecord(type) result = result.concat(pathifyModel(instance, store, childPath)) store.deleteRecord(instance) } }) return result.uniq() }
javascript
function pathifyModel (model, store, prefix) { let result = [] if (prefix) result.push(prefix) if (get(model, '_internalModel.modelName') === 'uni-form') { const propPath = propertyPath('payload', prefix) if (model.get('payload') instanceof DS.Model) { return result.concat(pathifyModel(model.get('payload'), store, propPath)) } return result.concat(pathifyObject(model.get('payload'), store, propPath)) } // Pathify serializer output const payload = model.serialize() const { attributes, data } = payload if (attributes) result = result.concat(pathifyObject(attributes, store, prefix)) // JSONAPI else if (data) result = result.concat(pathifyObject(data, store, prefix)) // JSONAPI else result = result.concat(pathifyObject(payload, store, prefix)) // Not JSONAPI // Pathify model attributes and child models which will be serialized const serializer = store.serializerFor(get(model, '_internalModel.modelName')) model.eachAttribute(name => result.push(propertyPath(name, prefix))) model.eachRelationship((name, { kind, type }) => { if (kind === 'hasMany') return // not supported const childPath = propertyPath(name, prefix) const willSerialize = get(serializer, `attrs.${name}.serialize`) === 'records' || get(serializer, `attrs.${name}.embedded`) === 'always' if (!willSerialize) { result.push(childPath) } else { const instance = store.createRecord(type) result = result.concat(pathifyModel(instance, store, childPath)) store.deleteRecord(instance) } }) return result.uniq() }
[ "function", "pathifyModel", "(", "model", ",", "store", ",", "prefix", ")", "{", "let", "result", "=", "[", "]", "if", "(", "prefix", ")", "result", ".", "push", "(", "prefix", ")", "if", "(", "get", "(", "model", ",", "'_internalModel.modelName'", ")", "===", "'uni-form'", ")", "{", "const", "propPath", "=", "propertyPath", "(", "'payload'", ",", "prefix", ")", "if", "(", "model", ".", "get", "(", "'payload'", ")", "instanceof", "DS", ".", "Model", ")", "{", "return", "result", ".", "concat", "(", "pathifyModel", "(", "model", ".", "get", "(", "'payload'", ")", ",", "store", ",", "propPath", ")", ")", "}", "return", "result", ".", "concat", "(", "pathifyObject", "(", "model", ".", "get", "(", "'payload'", ")", ",", "store", ",", "propPath", ")", ")", "}", "// Pathify serializer output", "const", "payload", "=", "model", ".", "serialize", "(", ")", "const", "{", "attributes", ",", "data", "}", "=", "payload", "if", "(", "attributes", ")", "result", "=", "result", ".", "concat", "(", "pathifyObject", "(", "attributes", ",", "store", ",", "prefix", ")", ")", "// JSONAPI", "else", "if", "(", "data", ")", "result", "=", "result", ".", "concat", "(", "pathifyObject", "(", "data", ",", "store", ",", "prefix", ")", ")", "// JSONAPI", "else", "result", "=", "result", ".", "concat", "(", "pathifyObject", "(", "payload", ",", "store", ",", "prefix", ")", ")", "// Not JSONAPI", "// Pathify model attributes and child models which will be serialized", "const", "serializer", "=", "store", ".", "serializerFor", "(", "get", "(", "model", ",", "'_internalModel.modelName'", ")", ")", "model", ".", "eachAttribute", "(", "name", "=>", "result", ".", "push", "(", "propertyPath", "(", "name", ",", "prefix", ")", ")", ")", "model", ".", "eachRelationship", "(", "(", "name", ",", "{", "kind", ",", "type", "}", ")", "=>", "{", "if", "(", "kind", "===", "'hasMany'", ")", "return", "// not supported", "const", "childPath", "=", "propertyPath", "(", "name", ",", "prefix", ")", "const", "willSerialize", "=", "get", "(", "serializer", ",", "`", "${", "name", "}", "`", ")", "===", "'records'", "||", "get", "(", "serializer", ",", "`", "${", "name", "}", "`", ")", "===", "'always'", "if", "(", "!", "willSerialize", ")", "{", "result", ".", "push", "(", "childPath", ")", "}", "else", "{", "const", "instance", "=", "store", ".", "createRecord", "(", "type", ")", "result", "=", "result", ".", "concat", "(", "pathifyModel", "(", "instance", ",", "store", ",", "childPath", ")", ")", "store", ".", "deleteRecord", "(", "instance", ")", "}", "}", ")", "return", "result", ".", "uniq", "(", ")", "}" ]
Belt-and-suspenders approach gets field paths from both the ultimate payload and the model data structure in memory.
[ "Belt", "-", "and", "-", "suspenders", "approach", "gets", "field", "paths", "from", "both", "the", "ultimate", "payload", "and", "the", "model", "data", "structure", "in", "memory", "." ]
47ae76aa0bddb250fb41f572caf2ca351a87a4f3
https://github.com/dollarshaveclub/ember-uni-form/blob/47ae76aa0bddb250fb41f572caf2ca351a87a4f3/addon/utils/pathify.js#L36-L75
19,460
zalando/dress-code
docs/demo/assets/scripts/fabricator.js
function () { options.menu = !fabricator.dom.root.classList.contains('f-menu-active'); fabricator.dom.root.classList.toggle('f-menu-active'); if (fabricator.test.sessionStorage) { sessionStorage.setItem('fabricator', JSON.stringify(options)); } }
javascript
function () { options.menu = !fabricator.dom.root.classList.contains('f-menu-active'); fabricator.dom.root.classList.toggle('f-menu-active'); if (fabricator.test.sessionStorage) { sessionStorage.setItem('fabricator', JSON.stringify(options)); } }
[ "function", "(", ")", "{", "options", ".", "menu", "=", "!", "fabricator", ".", "dom", ".", "root", ".", "classList", ".", "contains", "(", "'f-menu-active'", ")", ";", "fabricator", ".", "dom", ".", "root", ".", "classList", ".", "toggle", "(", "'f-menu-active'", ")", ";", "if", "(", "fabricator", ".", "test", ".", "sessionStorage", ")", "{", "sessionStorage", ".", "setItem", "(", "'fabricator'", ",", "JSON", ".", "stringify", "(", "options", ")", ")", ";", "}", "}" ]
toggle classes on certain elements
[ "toggle", "classes", "on", "certain", "elements" ]
041f6c4bf26a1ee630d2ef6bdef09e7c581b452c
https://github.com/zalando/dress-code/blob/041f6c4bf26a1ee630d2ef6bdef09e7c581b452c/docs/demo/assets/scripts/fabricator.js#L179-L186
19,461
zalando/dress-code
docs/demo/assets/scripts/fabricator.js
function (list) { if (!list.matches) { root.classList.remove('f-menu-active'); } else { if (fabricator.getOptions().menu) { root.classList.add('f-menu-active'); } else { root.classList.remove('f-menu-active'); } } }
javascript
function (list) { if (!list.matches) { root.classList.remove('f-menu-active'); } else { if (fabricator.getOptions().menu) { root.classList.add('f-menu-active'); } else { root.classList.remove('f-menu-active'); } } }
[ "function", "(", "list", ")", "{", "if", "(", "!", "list", ".", "matches", ")", "{", "root", ".", "classList", ".", "remove", "(", "'f-menu-active'", ")", ";", "}", "else", "{", "if", "(", "fabricator", ".", "getOptions", "(", ")", ".", "menu", ")", "{", "root", ".", "classList", ".", "add", "(", "'f-menu-active'", ")", ";", "}", "else", "{", "root", ".", "classList", ".", "remove", "(", "'f-menu-active'", ")", ";", "}", "}", "}" ]
if small screen
[ "if", "small", "screen" ]
041f6c4bf26a1ee630d2ef6bdef09e7c581b452c
https://github.com/zalando/dress-code/blob/041f6c4bf26a1ee630d2ef6bdef09e7c581b452c/docs/demo/assets/scripts/fabricator.js#L343-L353
19,462
zalando/dress-code
gulp/util/sassdoc.js
getColors
function getColors(rawData) { // Regular expression matching colors variables naming pattern var REGEX = /^dc-(.*?)[0-9]+$/; var content = rawData .filter((item) => { var group = item.group[0]; return group === 'colors' && item.context.type === 'variable' && item.context.name.match(REGEX); }) .map((item) => { // extract color name (eg. `dc-magenta10 -> magenta`) item.color = item.context.name.replace(REGEX, '$1'); item.color = _.capitalize(item.color); return item; }); // transform colors array in a object, shaped as the view layer expect content = _.groupBy(content, (c) => c.color ); Object.keys(content).forEach((color) => { content[color] = content[color].reduce((acc, c) => { acc['$' + c.context.name] = c.context.value; return acc; }, {}); }); return content; }
javascript
function getColors(rawData) { // Regular expression matching colors variables naming pattern var REGEX = /^dc-(.*?)[0-9]+$/; var content = rawData .filter((item) => { var group = item.group[0]; return group === 'colors' && item.context.type === 'variable' && item.context.name.match(REGEX); }) .map((item) => { // extract color name (eg. `dc-magenta10 -> magenta`) item.color = item.context.name.replace(REGEX, '$1'); item.color = _.capitalize(item.color); return item; }); // transform colors array in a object, shaped as the view layer expect content = _.groupBy(content, (c) => c.color ); Object.keys(content).forEach((color) => { content[color] = content[color].reduce((acc, c) => { acc['$' + c.context.name] = c.context.value; return acc; }, {}); }); return content; }
[ "function", "getColors", "(", "rawData", ")", "{", "// Regular expression matching colors variables naming pattern", "var", "REGEX", "=", "/", "^dc-(.*?)[0-9]+$", "/", ";", "var", "content", "=", "rawData", ".", "filter", "(", "(", "item", ")", "=>", "{", "var", "group", "=", "item", ".", "group", "[", "0", "]", ";", "return", "group", "===", "'colors'", "&&", "item", ".", "context", ".", "type", "===", "'variable'", "&&", "item", ".", "context", ".", "name", ".", "match", "(", "REGEX", ")", ";", "}", ")", ".", "map", "(", "(", "item", ")", "=>", "{", "// extract color name (eg. `dc-magenta10 -> magenta`)", "item", ".", "color", "=", "item", ".", "context", ".", "name", ".", "replace", "(", "REGEX", ",", "'$1'", ")", ";", "item", ".", "color", "=", "_", ".", "capitalize", "(", "item", ".", "color", ")", ";", "return", "item", ";", "}", ")", ";", "// transform colors array in a object, shaped as the view layer expect", "content", "=", "_", ".", "groupBy", "(", "content", ",", "(", "c", ")", "=>", "c", ".", "color", ")", ";", "Object", ".", "keys", "(", "content", ")", ".", "forEach", "(", "(", "color", ")", "=>", "{", "content", "[", "color", "]", "=", "content", "[", "color", "]", ".", "reduce", "(", "(", "acc", ",", "c", ")", "=>", "{", "acc", "[", "'$'", "+", "c", ".", "context", ".", "name", "]", "=", "c", ".", "context", ".", "value", ";", "return", "acc", ";", "}", ",", "{", "}", ")", ";", "}", ")", ";", "return", "content", ";", "}" ]
Get colors view model from sassdoc raw data @param {Array} rawData - sassdoc items @return {Object}
[ "Get", "colors", "view", "model", "from", "sassdoc", "raw", "data" ]
041f6c4bf26a1ee630d2ef6bdef09e7c581b452c
https://github.com/zalando/dress-code/blob/041f6c4bf26a1ee630d2ef6bdef09e7c581b452c/gulp/util/sassdoc.js#L9-L37
19,463
zalando/dress-code
gulp/util/sassdoc.js
getSassReference
function getSassReference(rawData) { // group sassdoc items (variables, mixins, functions, etc.) by @group var content = _.groupBy(rawData, (item) => item.group[0]); Object.keys(content).forEach((group) => { content[group] = content[group].map((item) => { // boolean flag for deprecated item.deprecated = typeof item.deprecated !== 'undefined' return item; }); // group every sassdoc item by type content[group] = _.groupBy(content[group], (item) => item.context.type + 's'); }); return content; }
javascript
function getSassReference(rawData) { // group sassdoc items (variables, mixins, functions, etc.) by @group var content = _.groupBy(rawData, (item) => item.group[0]); Object.keys(content).forEach((group) => { content[group] = content[group].map((item) => { // boolean flag for deprecated item.deprecated = typeof item.deprecated !== 'undefined' return item; }); // group every sassdoc item by type content[group] = _.groupBy(content[group], (item) => item.context.type + 's'); }); return content; }
[ "function", "getSassReference", "(", "rawData", ")", "{", "// group sassdoc items (variables, mixins, functions, etc.) by @group", "var", "content", "=", "_", ".", "groupBy", "(", "rawData", ",", "(", "item", ")", "=>", "item", ".", "group", "[", "0", "]", ")", ";", "Object", ".", "keys", "(", "content", ")", ".", "forEach", "(", "(", "group", ")", "=>", "{", "content", "[", "group", "]", "=", "content", "[", "group", "]", ".", "map", "(", "(", "item", ")", "=>", "{", "// boolean flag for deprecated", "item", ".", "deprecated", "=", "typeof", "item", ".", "deprecated", "!==", "'undefined'", "return", "item", ";", "}", ")", ";", "// group every sassdoc item by type", "content", "[", "group", "]", "=", "_", ".", "groupBy", "(", "content", "[", "group", "]", ",", "(", "item", ")", "=>", "item", ".", "context", ".", "type", "+", "'s'", ")", ";", "}", ")", ";", "return", "content", ";", "}" ]
Get sass reference view model from sassdoc raw data @param {Array} rawData - sassdoc items @return {Object}
[ "Get", "sass", "reference", "view", "model", "from", "sassdoc", "raw", "data" ]
041f6c4bf26a1ee630d2ef6bdef09e7c581b452c
https://github.com/zalando/dress-code/blob/041f6c4bf26a1ee630d2ef6bdef09e7c581b452c/gulp/util/sassdoc.js#L45-L61
19,464
apache/cordova-serve
src/browser.js
getErrorMessage
function getErrorMessage (err, target, defaultMsg) { var errMessage; if (err) { errMessage = err.toString(); } else { errMessage = defaultMsg; } return errMessage.replace('%target%', target); }
javascript
function getErrorMessage (err, target, defaultMsg) { var errMessage; if (err) { errMessage = err.toString(); } else { errMessage = defaultMsg; } return errMessage.replace('%target%', target); }
[ "function", "getErrorMessage", "(", "err", ",", "target", ",", "defaultMsg", ")", "{", "var", "errMessage", ";", "if", "(", "err", ")", "{", "errMessage", "=", "err", ".", "toString", "(", ")", ";", "}", "else", "{", "errMessage", "=", "defaultMsg", ";", "}", "return", "errMessage", ".", "replace", "(", "'%target%'", ",", "target", ")", ";", "}" ]
err might be null, in which case defaultMsg is used. target MUST be defined or an error is thrown.
[ "err", "might", "be", "null", "in", "which", "case", "defaultMsg", "is", "used", ".", "target", "MUST", "be", "defined", "or", "an", "error", "is", "thrown", "." ]
18ace76f16667ebf2ec5bc2125c100a199fb8f44
https://github.com/apache/cordova-serve/blob/18ace76f16667ebf2ec5bc2125c100a199fb8f44/src/browser.js#L145-L153
19,465
bitcoinjs/merkle-lib
index.js
merkle
function merkle (values, digestFn) { if (!Array.isArray(values)) throw TypeError('Expected values Array') if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') if (values.length === 1) return values.concat() var levels = [values] var level = values do { level = _derive(level, digestFn) levels.push(level) } while (level.length > 1) return [].concat.apply([], levels) }
javascript
function merkle (values, digestFn) { if (!Array.isArray(values)) throw TypeError('Expected values Array') if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') if (values.length === 1) return values.concat() var levels = [values] var level = values do { level = _derive(level, digestFn) levels.push(level) } while (level.length > 1) return [].concat.apply([], levels) }
[ "function", "merkle", "(", "values", ",", "digestFn", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "values", ")", ")", "throw", "TypeError", "(", "'Expected values Array'", ")", "if", "(", "typeof", "digestFn", "!==", "'function'", ")", "throw", "TypeError", "(", "'Expected digest Function'", ")", "if", "(", "values", ".", "length", "===", "1", ")", "return", "values", ".", "concat", "(", ")", "var", "levels", "=", "[", "values", "]", "var", "level", "=", "values", "do", "{", "level", "=", "_derive", "(", "level", ",", "digestFn", ")", "levels", ".", "push", "(", "level", ")", "}", "while", "(", "level", ".", "length", ">", "1", ")", "return", "[", "]", ".", "concat", ".", "apply", "(", "[", "]", ",", "levels", ")", "}" ]
returns the merkle tree
[ "returns", "the", "merkle", "tree" ]
e233148537006fc45daeacebcfc5fd0bdcc1625f
https://github.com/bitcoinjs/merkle-lib/blob/e233148537006fc45daeacebcfc5fd0bdcc1625f/index.js#L18-L32
19,466
almost/through2-concurrent
through2-concurrent.js
callOnFinish
function callOnFinish (original) { return function (callback) { if (concurrent === 0) { original.call(this, callback); } else { pendingFinish = original.bind(this, callback); } } }
javascript
function callOnFinish (original) { return function (callback) { if (concurrent === 0) { original.call(this, callback); } else { pendingFinish = original.bind(this, callback); } } }
[ "function", "callOnFinish", "(", "original", ")", "{", "return", "function", "(", "callback", ")", "{", "if", "(", "concurrent", "===", "0", ")", "{", "original", ".", "call", "(", "this", ",", "callback", ")", ";", "}", "else", "{", "pendingFinish", "=", "original", ".", "bind", "(", "this", ",", "callback", ")", ";", "}", "}", "}" ]
Flush is always called only after Final has finished to ensure that data from Final gets processed, so we only need one pending callback at a time
[ "Flush", "is", "always", "called", "only", "after", "Final", "has", "finished", "to", "ensure", "that", "data", "from", "Final", "gets", "processed", "so", "we", "only", "need", "one", "pending", "callback", "at", "a", "time" ]
ce8b0dc6c00e2a5c12b82e280f5e1972ed0c6e4e
https://github.com/almost/through2-concurrent/blob/ce8b0dc6c00e2a5c12b82e280f5e1972ed0c6e4e/through2-concurrent.js#L75-L83
19,467
jasonbellamy/git-label
dist/lib/package.js
findPackages
function findPackages(path) { return new Promise(function (resolve, reject) { (0, _glob.glob)(path, function (err, res) { if (err) { reject(err); } resolve(res.filter(function (file) { return file.endsWith('.json'); })); }); }); }
javascript
function findPackages(path) { return new Promise(function (resolve, reject) { (0, _glob.glob)(path, function (err, res) { if (err) { reject(err); } resolve(res.filter(function (file) { return file.endsWith('.json'); })); }); }); }
[ "function", "findPackages", "(", "path", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "(", "0", ",", "_glob", ".", "glob", ")", "(", "path", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "resolve", "(", "res", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "file", ".", "endsWith", "(", "'.json'", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Takes a glob and returns a list of label package files @name findPackages @function @param {String} path a globbing pattern @return {Promise} array containing any found label packages
[ "Takes", "a", "glob", "and", "returns", "a", "list", "of", "label", "package", "files" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/package.js#L22-L33
19,468
jasonbellamy/git-label
dist/lib/package.js
readPackages
function readPackages() { var packages = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; return Promise.all(packages.map(readPackage)).then(function (labels) { return labels.reduce(function (prev, curr) { return prev.concat(curr); }); }); }
javascript
function readPackages() { var packages = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; return Promise.all(packages.map(readPackage)).then(function (labels) { return labels.reduce(function (prev, curr) { return prev.concat(curr); }); }); }
[ "function", "readPackages", "(", ")", "{", "var", "packages", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "[", "]", ":", "arguments", "[", "0", "]", ";", "return", "Promise", ".", "all", "(", "packages", ".", "map", "(", "readPackage", ")", ")", ".", "then", "(", "function", "(", "labels", ")", "{", "return", "labels", ".", "reduce", "(", "function", "(", "prev", ",", "curr", ")", "{", "return", "prev", ".", "concat", "(", "curr", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Processes a list of packages and concatenates their contents into a single object. @name readPackages @function @param {Array} packages array of paths to package files @return {Promise}
[ "Processes", "a", "list", "of", "packages", "and", "concatenates", "their", "contents", "into", "a", "single", "object", "." ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/package.js#L43-L51
19,469
jasonbellamy/git-label
dist/lib/request.js
requestPromisfied
function requestPromisfied(options) { return new Promise(function (resolve, reject) { (0, _request2.default)(options, function (err, res) { if (err) { reject(err); } resolve(res.body); }); }); }
javascript
function requestPromisfied(options) { return new Promise(function (resolve, reject) { (0, _request2.default)(options, function (err, res) { if (err) { reject(err); } resolve(res.body); }); }); }
[ "function", "requestPromisfied", "(", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "(", "0", ",", "_request2", ".", "default", ")", "(", "options", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "resolve", "(", "res", ".", "body", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates a "Promisfied" HTTPRequest object @name requestPromisfied @function @param {Object} options request options: https://github.com/request/request) @return {Promise}
[ "Creates", "a", "Promisfied", "HTTPRequest", "object" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/request.js#L22-L31
19,470
jasonbellamy/git-label
dist/lib/config.js
configure
function configure(_ref) { var api = _ref.api; var token = _ref.token; var repo = _ref.repo; return { api: api, repo: "repos/" + repo, token: token }; }
javascript
function configure(_ref) { var api = _ref.api; var token = _ref.token; var repo = _ref.repo; return { api: api, repo: "repos/" + repo, token: token }; }
[ "function", "configure", "(", "_ref", ")", "{", "var", "api", "=", "_ref", ".", "api", ";", "var", "token", "=", "_ref", ".", "token", ";", "var", "repo", "=", "_ref", ".", "repo", ";", "return", "{", "api", ":", "api", ",", "repo", ":", "\"repos/\"", "+", "repo", ",", "token", ":", "token", "}", ";", "}" ]
Configures and returns an object with the git server settings @name configure @function @param {Object} server the server configuration object @param {String} server.api the api endpoint to connect to @param {String} server.token the api token to use @param {String} server.repo the git repo to manipulate @return {Object} structured server configuration object
[ "Configures", "and", "returns", "an", "object", "with", "the", "git", "server", "settings" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/config.js#L18-L28
19,471
jasonbellamy/git-label
dist/index.js
add
function add(server, labels) { return (0, _label.createLabels)((0, _config.configure)(server), labels).then(_handlers.createSuccessHandler).catch(_handlers.errorHandler); }
javascript
function add(server, labels) { return (0, _label.createLabels)((0, _config.configure)(server), labels).then(_handlers.createSuccessHandler).catch(_handlers.errorHandler); }
[ "function", "add", "(", "server", ",", "labels", ")", "{", "return", "(", "0", ",", "_label", ".", "createLabels", ")", "(", "(", "0", ",", "_config", ".", "configure", ")", "(", "server", ")", ",", "labels", ")", ".", "then", "(", "_handlers", ".", "createSuccessHandler", ")", ".", "catch", "(", "_handlers", ".", "errorHandler", ")", ";", "}" ]
Automates and simplifies the creation of labels for GitHub repositories @name add @function @param {Object} server the server configuration object @param {String} server.api the api endpoint to connect to @param {String} server.token the api token to use @param {String} server.repo the git repo to manipulate @param {Array} labels array of label objects @return {Promise}
[ "Automates", "and", "simplifies", "the", "creation", "of", "labels", "for", "GitHub", "repositories" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/index.js#L30-L32
19,472
jasonbellamy/git-label
dist/index.js
remove
function remove(server, labels) { return (0, _label.deleteLabels)((0, _config.configure)(server), labels).then(_handlers.deleteSuccessHandler).catch(_handlers.errorHandler); }
javascript
function remove(server, labels) { return (0, _label.deleteLabels)((0, _config.configure)(server), labels).then(_handlers.deleteSuccessHandler).catch(_handlers.errorHandler); }
[ "function", "remove", "(", "server", ",", "labels", ")", "{", "return", "(", "0", ",", "_label", ".", "deleteLabels", ")", "(", "(", "0", ",", "_config", ".", "configure", ")", "(", "server", ")", ",", "labels", ")", ".", "then", "(", "_handlers", ".", "deleteSuccessHandler", ")", ".", "catch", "(", "_handlers", ".", "errorHandler", ")", ";", "}" ]
Removes all of the specified labels associated with the GitHub repo @name remove @function @param {Object} server the server configuration object @param {String} server.api the api endpoint to connect to @param {String} server.token the api token to use @param {String} server.repo the git repo to manipulate @param {Array} labels array of label objects @return {Promise}
[ "Removes", "all", "of", "the", "specified", "labels", "associated", "with", "the", "GitHub", "repo" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/index.js#L46-L48
19,473
jasonbellamy/git-label
dist/lib/label.js
createLabel
function createLabel(_ref, name, color) { var api = _ref.api; var token = _ref.token; var repo = _ref.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels', form: JSON.stringify({ name: name, color: color }), method: 'POST', json: true }); }
javascript
function createLabel(_ref, name, color) { var api = _ref.api; var token = _ref.token; var repo = _ref.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels', form: JSON.stringify({ name: name, color: color }), method: 'POST', json: true }); }
[ "function", "createLabel", "(", "_ref", ",", "name", ",", "color", ")", "{", "var", "api", "=", "_ref", ".", "api", ";", "var", "token", "=", "_ref", ".", "token", ";", "var", "repo", "=", "_ref", ".", "repo", ";", "return", "(", "0", ",", "_request2", ".", "default", ")", "(", "{", "headers", ":", "{", "'User-Agent'", ":", "'request'", ",", "'Authorization'", ":", "'token '", "+", "token", "}", ",", "url", ":", "api", "+", "'/'", "+", "repo", "+", "'/labels'", ",", "form", ":", "JSON", ".", "stringify", "(", "{", "name", ":", "name", ",", "color", ":", "color", "}", ")", ",", "method", ":", "'POST'", ",", "json", ":", "true", "}", ")", ";", "}" ]
Sends a request to GitHub to create a label @name createLabel @function @param {Object} server the server configuration object @param {String} server.api the api endpoint to connect to @param {String} server.token the api token to use @param {String} server.repo the git repo to manipulate @param {String} name the name of the label @param {String} color the hexidecimal color of the label @return {Promise}
[ "Sends", "a", "request", "to", "GitHub", "to", "create", "a", "label" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/label.js#L32-L44
19,474
jasonbellamy/git-label
dist/lib/label.js
deleteLabel
function deleteLabel(_ref2, name) { var api = _ref2.api; var token = _ref2.token; var repo = _ref2.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels/' + name, method: 'DELETE', json: true }); }
javascript
function deleteLabel(_ref2, name) { var api = _ref2.api; var token = _ref2.token; var repo = _ref2.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels/' + name, method: 'DELETE', json: true }); }
[ "function", "deleteLabel", "(", "_ref2", ",", "name", ")", "{", "var", "api", "=", "_ref2", ".", "api", ";", "var", "token", "=", "_ref2", ".", "token", ";", "var", "repo", "=", "_ref2", ".", "repo", ";", "return", "(", "0", ",", "_request2", ".", "default", ")", "(", "{", "headers", ":", "{", "'User-Agent'", ":", "'request'", ",", "'Authorization'", ":", "'token '", "+", "token", "}", ",", "url", ":", "api", "+", "'/'", "+", "repo", "+", "'/labels/'", "+", "name", ",", "method", ":", "'DELETE'", ",", "json", ":", "true", "}", ")", ";", "}" ]
Sends a request to GitHub to delete a label @name deleteLabel @function @param {Object} server the server configuration object @param {String} server.api the api endpoint to connect to @param {String} server.token the api token to use @param {String} server.repo the git repo to manipulate @param {String} name the name of the label to delete @return {Promise}
[ "Sends", "a", "request", "to", "GitHub", "to", "delete", "a", "label" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/label.js#L58-L69
19,475
jasonbellamy/git-label
dist/lib/label.js
getLabels
function getLabels(_ref3) { var api = _ref3.api; var token = _ref3.token; var repo = _ref3.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels', method: 'GET', json: true }); }
javascript
function getLabels(_ref3) { var api = _ref3.api; var token = _ref3.token; var repo = _ref3.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels', method: 'GET', json: true }); }
[ "function", "getLabels", "(", "_ref3", ")", "{", "var", "api", "=", "_ref3", ".", "api", ";", "var", "token", "=", "_ref3", ".", "token", ";", "var", "repo", "=", "_ref3", ".", "repo", ";", "return", "(", "0", ",", "_request2", ".", "default", ")", "(", "{", "headers", ":", "{", "'User-Agent'", ":", "'request'", ",", "'Authorization'", ":", "'token '", "+", "token", "}", ",", "url", ":", "api", "+", "'/'", "+", "repo", "+", "'/labels'", ",", "method", ":", "'GET'", ",", "json", ":", "true", "}", ")", ";", "}" ]
Retrieves a list of labels from Github @name getLabels @function @param {Object} server the server configuration object @param {String} server.api the api endpoint to connect to @param {String} server.token the api token to use @param {String} server.repo the git repo to manipulate @return {Promise}
[ "Retrieves", "a", "list", "of", "labels", "from", "Github" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/label.js#L82-L93
19,476
jasonbellamy/git-label
dist/lib/label.js
formatLabel
function formatLabel(_ref4) { var name = _ref4.name; var color = _ref4.color; return { name: name, color: color.replace('#', '') }; }
javascript
function formatLabel(_ref4) { var name = _ref4.name; var color = _ref4.color; return { name: name, color: color.replace('#', '') }; }
[ "function", "formatLabel", "(", "_ref4", ")", "{", "var", "name", "=", "_ref4", ".", "name", ";", "var", "color", "=", "_ref4", ".", "color", ";", "return", "{", "name", ":", "name", ",", "color", ":", "color", ".", "replace", "(", "'#'", ",", "''", ")", "}", ";", "}" ]
Properly formats an object for a label for a GitHub request @name formatLabel @function @param {String} name the name of the label @param {String} color the hexidecimal color of the label @return {Object} a properly formated label object that can be sent to GitHub
[ "Properly", "formats", "an", "object", "for", "a", "label", "for", "a", "GitHub", "request" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/label.js#L104-L109
19,477
jasonbellamy/git-label
dist/lib/label.js
createLabels
function createLabels(server, labels) { return Promise.all(labels.map(formatLabel).map(function (_ref5) { var name = _ref5.name; var color = _ref5.color; return createLabel(server, name, color); })); }
javascript
function createLabels(server, labels) { return Promise.all(labels.map(formatLabel).map(function (_ref5) { var name = _ref5.name; var color = _ref5.color; return createLabel(server, name, color); })); }
[ "function", "createLabels", "(", "server", ",", "labels", ")", "{", "return", "Promise", ".", "all", "(", "labels", ".", "map", "(", "formatLabel", ")", ".", "map", "(", "function", "(", "_ref5", ")", "{", "var", "name", "=", "_ref5", ".", "name", ";", "var", "color", "=", "_ref5", ".", "color", ";", "return", "createLabel", "(", "server", ",", "name", ",", "color", ")", ";", "}", ")", ")", ";", "}" ]
Prepares and sends a request to GitHub to create multiple labels @name createLabels @function @param {Object} server the server configuration object @param {String} server.api the api endpoint to connect to @param {String} server.token the api token to use @param {String} server.repo the git repo to manipulate @param {array} labels an array of objects containing data to be formatted and sent to GitHub @return {Promise}
[ "Prepares", "and", "sends", "a", "request", "to", "GitHub", "to", "create", "multiple", "labels" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/label.js#L123-L129
19,478
jasonbellamy/git-label
dist/lib/label.js
deleteLabels
function deleteLabels(server, labels) { return Promise.all(labels.map(formatLabel).map(function (_ref6) { var name = _ref6.name; var color = _ref6.color; return deleteLabel(server, name); })); }
javascript
function deleteLabels(server, labels) { return Promise.all(labels.map(formatLabel).map(function (_ref6) { var name = _ref6.name; var color = _ref6.color; return deleteLabel(server, name); })); }
[ "function", "deleteLabels", "(", "server", ",", "labels", ")", "{", "return", "Promise", ".", "all", "(", "labels", ".", "map", "(", "formatLabel", ")", ".", "map", "(", "function", "(", "_ref6", ")", "{", "var", "name", "=", "_ref6", ".", "name", ";", "var", "color", "=", "_ref6", ".", "color", ";", "return", "deleteLabel", "(", "server", ",", "name", ")", ";", "}", ")", ")", ";", "}" ]
Deletes all of the current labels associated with the GitHub repo @name deleteLabels @function @param {Object} server the server configuration object @param {String} server.api the api endpoint to connect to @param {String} server.token the api token to use @param {String} server.repo the git repo to manipulate @return {Promise}
[ "Deletes", "all", "of", "the", "current", "labels", "associated", "with", "the", "GitHub", "repo" ]
ad33c23a1805cf99beb04e07039d9879fa632d2b
https://github.com/jasonbellamy/git-label/blob/ad33c23a1805cf99beb04e07039d9879fa632d2b/dist/lib/label.js#L142-L148
19,479
taozhi8833998/node-sql-parser
lib/util.js
replaceParams
function replaceParams(ast, keys) { Object.keys(ast) .filter(key => { const value = ast[key] return Array.isArray(value) || (typeof value === 'object' && value !== null) }) .forEach(key => { const expr = ast[key] if (!(typeof expr === 'object' && expr.type === 'param')) return replaceParams(expr, keys) if (typeof keys[expr.value] === 'undefined') throw new Error(`no value for parameter :${expr.value} found`) ast[key] = createValueExpr(keys[expr.value]) return null }) return ast }
javascript
function replaceParams(ast, keys) { Object.keys(ast) .filter(key => { const value = ast[key] return Array.isArray(value) || (typeof value === 'object' && value !== null) }) .forEach(key => { const expr = ast[key] if (!(typeof expr === 'object' && expr.type === 'param')) return replaceParams(expr, keys) if (typeof keys[expr.value] === 'undefined') throw new Error(`no value for parameter :${expr.value} found`) ast[key] = createValueExpr(keys[expr.value]) return null }) return ast }
[ "function", "replaceParams", "(", "ast", ",", "keys", ")", "{", "Object", ".", "keys", "(", "ast", ")", ".", "filter", "(", "key", "=>", "{", "const", "value", "=", "ast", "[", "key", "]", "return", "Array", ".", "isArray", "(", "value", ")", "||", "(", "typeof", "value", "===", "'object'", "&&", "value", "!==", "null", ")", "}", ")", ".", "forEach", "(", "key", "=>", "{", "const", "expr", "=", "ast", "[", "key", "]", "if", "(", "!", "(", "typeof", "expr", "===", "'object'", "&&", "expr", ".", "type", "===", "'param'", ")", ")", "return", "replaceParams", "(", "expr", ",", "keys", ")", "if", "(", "typeof", "keys", "[", "expr", ".", "value", "]", "===", "'undefined'", ")", "throw", "new", "Error", "(", "`", "${", "expr", ".", "value", "}", "`", ")", "ast", "[", "key", "]", "=", "createValueExpr", "(", "keys", "[", "expr", ".", "value", "]", ")", "return", "null", "}", ")", "return", "ast", "}" ]
Replace param expressions @param {Object} ast - AST object @param {Object} keys - Keys = parameter names, values = parameter values @return {Object} - Newly created AST object
[ "Replace", "param", "expressions" ]
762944764e08018f9b432e56e3532cfd1b8eb58b
https://github.com/taozhi8833998/node-sql-parser/blob/762944764e08018f9b432e56e3532cfd1b8eb58b/lib/util.js#L51-L68
19,480
mage/mage
lib/mage/Mage.js
Mage
function Mage(mageRootModule) { EventEmitter.call(this); this.workerId = require('./worker').getId(); this.MageError = require('./MageError'); this.task = null; this._runState = 'init'; this._modulesList = []; this._modulePaths = [ applicationModulesPath ]; this._setupQueue = []; this._teardownQueue = []; // Set up the core object that holds some crucial Mage libraries this.core = { modules: {} }; // Register the Mage version var magePath = path.join(path.dirname(__dirname), '..'); var magePackagePath = path.join(magePath, 'package.json'); var rootPackagePath = path.join(rootPath, 'package.json'); var magePackage = require(magePackagePath); var rootPackage; try { rootPackage = require(rootPackagePath); } catch (error) { console.warn('Could not load your project\'s "package.json"', error); } var appName = rootPackage && rootPackage.name || path.basename(rootPath); var appVersion = rootPackage && rootPackage.version; this.version = magePackage.version; this.magePackage = { name: 'mage', version: magePackage.version, path: magePath, package: magePackage }; this.rootPackage = { name: appName, version: appVersion, path: rootPath, package: rootPackage }; // test the supported node version of mage itself as soon as possible testEngineVersion(this.magePackage.package, magePackagePath, this); testEngineVersion(this.rootPackage.package, rootPackagePath, this); require('codependency').register(mageRootModule); }
javascript
function Mage(mageRootModule) { EventEmitter.call(this); this.workerId = require('./worker').getId(); this.MageError = require('./MageError'); this.task = null; this._runState = 'init'; this._modulesList = []; this._modulePaths = [ applicationModulesPath ]; this._setupQueue = []; this._teardownQueue = []; // Set up the core object that holds some crucial Mage libraries this.core = { modules: {} }; // Register the Mage version var magePath = path.join(path.dirname(__dirname), '..'); var magePackagePath = path.join(magePath, 'package.json'); var rootPackagePath = path.join(rootPath, 'package.json'); var magePackage = require(magePackagePath); var rootPackage; try { rootPackage = require(rootPackagePath); } catch (error) { console.warn('Could not load your project\'s "package.json"', error); } var appName = rootPackage && rootPackage.name || path.basename(rootPath); var appVersion = rootPackage && rootPackage.version; this.version = magePackage.version; this.magePackage = { name: 'mage', version: magePackage.version, path: magePath, package: magePackage }; this.rootPackage = { name: appName, version: appVersion, path: rootPath, package: rootPackage }; // test the supported node version of mage itself as soon as possible testEngineVersion(this.magePackage.package, magePackagePath, this); testEngineVersion(this.rootPackage.package, rootPackagePath, this); require('codependency').register(mageRootModule); }
[ "function", "Mage", "(", "mageRootModule", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "workerId", "=", "require", "(", "'./worker'", ")", ".", "getId", "(", ")", ";", "this", ".", "MageError", "=", "require", "(", "'./MageError'", ")", ";", "this", ".", "task", "=", "null", ";", "this", ".", "_runState", "=", "'init'", ";", "this", ".", "_modulesList", "=", "[", "]", ";", "this", ".", "_modulePaths", "=", "[", "applicationModulesPath", "]", ";", "this", ".", "_setupQueue", "=", "[", "]", ";", "this", ".", "_teardownQueue", "=", "[", "]", ";", "// Set up the core object that holds some crucial Mage libraries", "this", ".", "core", "=", "{", "modules", ":", "{", "}", "}", ";", "// Register the Mage version", "var", "magePath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "__dirname", ")", ",", "'..'", ")", ";", "var", "magePackagePath", "=", "path", ".", "join", "(", "magePath", ",", "'package.json'", ")", ";", "var", "rootPackagePath", "=", "path", ".", "join", "(", "rootPath", ",", "'package.json'", ")", ";", "var", "magePackage", "=", "require", "(", "magePackagePath", ")", ";", "var", "rootPackage", ";", "try", "{", "rootPackage", "=", "require", "(", "rootPackagePath", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "warn", "(", "'Could not load your project\\'s \"package.json\"'", ",", "error", ")", ";", "}", "var", "appName", "=", "rootPackage", "&&", "rootPackage", ".", "name", "||", "path", ".", "basename", "(", "rootPath", ")", ";", "var", "appVersion", "=", "rootPackage", "&&", "rootPackage", ".", "version", ";", "this", ".", "version", "=", "magePackage", ".", "version", ";", "this", ".", "magePackage", "=", "{", "name", ":", "'mage'", ",", "version", ":", "magePackage", ".", "version", ",", "path", ":", "magePath", ",", "package", ":", "magePackage", "}", ";", "this", ".", "rootPackage", "=", "{", "name", ":", "appName", ",", "version", ":", "appVersion", ",", "path", ":", "rootPath", ",", "package", ":", "rootPackage", "}", ";", "// test the supported node version of mage itself as soon as possible", "testEngineVersion", "(", "this", ".", "magePackage", ".", "package", ",", "magePackagePath", ",", "this", ")", ";", "testEngineVersion", "(", "this", ".", "rootPackage", ".", "package", ",", "rootPackagePath", ",", "this", ")", ";", "require", "(", "'codependency'", ")", ".", "register", "(", "mageRootModule", ")", ";", "}" ]
The mage class. @constructor @extends EventEmitter
[ "The", "mage", "class", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/mage/Mage.js#L41-L101
19,481
mage/mage
lib/archivist/vaults/file/directories.js
recursiveFileList
function recursiveFileList(rootPath, cb) { var fileList = []; var errorList = []; var q = async.queue(function (filename, callback) { var filePath = path.join(rootPath, filename); fs.stat(filePath, function (error, stat) { if (error) { errorList.push(error); return callback(error); } // If not a directory then push onto list and continue if (!stat.isDirectory()) { fileList.push(filename); return callback(); } // Otherwise recurse fs.readdir(filePath, function (error, files) { if (error) { errorList.push(error); return callback(error); } // Append list of child file onto our file list for (var i = 0; i < files.length; i += 1) { q.push(path.join(filename, files[i])); } callback(); }); }); }, MAX_PARALLEL); q.drain = function () { if (errorList.length) { return cb(errorList); } cb(null, fileList); }; fs.readdir(rootPath, function (error, files) { if (error) { return cb(error); } if (!files.length) { return q.drain(); } for (var i = 0; i < files.length; i += 1) { q.push(files[i]); } }); }
javascript
function recursiveFileList(rootPath, cb) { var fileList = []; var errorList = []; var q = async.queue(function (filename, callback) { var filePath = path.join(rootPath, filename); fs.stat(filePath, function (error, stat) { if (error) { errorList.push(error); return callback(error); } // If not a directory then push onto list and continue if (!stat.isDirectory()) { fileList.push(filename); return callback(); } // Otherwise recurse fs.readdir(filePath, function (error, files) { if (error) { errorList.push(error); return callback(error); } // Append list of child file onto our file list for (var i = 0; i < files.length; i += 1) { q.push(path.join(filename, files[i])); } callback(); }); }); }, MAX_PARALLEL); q.drain = function () { if (errorList.length) { return cb(errorList); } cb(null, fileList); }; fs.readdir(rootPath, function (error, files) { if (error) { return cb(error); } if (!files.length) { return q.drain(); } for (var i = 0; i < files.length; i += 1) { q.push(files[i]); } }); }
[ "function", "recursiveFileList", "(", "rootPath", ",", "cb", ")", "{", "var", "fileList", "=", "[", "]", ";", "var", "errorList", "=", "[", "]", ";", "var", "q", "=", "async", ".", "queue", "(", "function", "(", "filename", ",", "callback", ")", "{", "var", "filePath", "=", "path", ".", "join", "(", "rootPath", ",", "filename", ")", ";", "fs", ".", "stat", "(", "filePath", ",", "function", "(", "error", ",", "stat", ")", "{", "if", "(", "error", ")", "{", "errorList", ".", "push", "(", "error", ")", ";", "return", "callback", "(", "error", ")", ";", "}", "// If not a directory then push onto list and continue", "if", "(", "!", "stat", ".", "isDirectory", "(", ")", ")", "{", "fileList", ".", "push", "(", "filename", ")", ";", "return", "callback", "(", ")", ";", "}", "// Otherwise recurse", "fs", ".", "readdir", "(", "filePath", ",", "function", "(", "error", ",", "files", ")", "{", "if", "(", "error", ")", "{", "errorList", ".", "push", "(", "error", ")", ";", "return", "callback", "(", "error", ")", ";", "}", "// Append list of child file onto our file list", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "+=", "1", ")", "{", "q", ".", "push", "(", "path", ".", "join", "(", "filename", ",", "files", "[", "i", "]", ")", ")", ";", "}", "callback", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "MAX_PARALLEL", ")", ";", "q", ".", "drain", "=", "function", "(", ")", "{", "if", "(", "errorList", ".", "length", ")", "{", "return", "cb", "(", "errorList", ")", ";", "}", "cb", "(", "null", ",", "fileList", ")", ";", "}", ";", "fs", ".", "readdir", "(", "rootPath", ",", "function", "(", "error", ",", "files", ")", "{", "if", "(", "error", ")", "{", "return", "cb", "(", "error", ")", ";", "}", "if", "(", "!", "files", ".", "length", ")", "{", "return", "q", ".", "drain", "(", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "+=", "1", ")", "{", "q", ".", "push", "(", "files", "[", "i", "]", ")", ";", "}", "}", ")", ";", "}" ]
Recursively scans a directory for all files. This will then yield an array of all filenames relative to the give rootPath or an error. @param {String} rootPath @param {Function} cb
[ "Recursively", "scans", "a", "directory", "for", "all", "files", ".", "This", "will", "then", "yield", "an", "array", "of", "all", "filenames", "relative", "to", "the", "give", "rootPath", "or", "an", "error", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/file/directories.js#L14-L71
19,482
mage/mage
lib/archivist/vaults/file/directories.js
purgeEmptyParentFolders
function purgeEmptyParentFolders(rootPath, subfolderPath, logger, cb) { var fullPath = path.join(rootPath, subfolderPath); // Don't delete if we have reached the base if (!subfolderPath || subfolderPath === '.') { return cb(); } fs.rmdir(fullPath, function (error) { if (error) { return cb(error); } logger.verbose('Purged empty subfolder:', fullPath); return purgeEmptyParentFolders(rootPath, path.dirname(subfolderPath), logger, cb); }); }
javascript
function purgeEmptyParentFolders(rootPath, subfolderPath, logger, cb) { var fullPath = path.join(rootPath, subfolderPath); // Don't delete if we have reached the base if (!subfolderPath || subfolderPath === '.') { return cb(); } fs.rmdir(fullPath, function (error) { if (error) { return cb(error); } logger.verbose('Purged empty subfolder:', fullPath); return purgeEmptyParentFolders(rootPath, path.dirname(subfolderPath), logger, cb); }); }
[ "function", "purgeEmptyParentFolders", "(", "rootPath", ",", "subfolderPath", ",", "logger", ",", "cb", ")", "{", "var", "fullPath", "=", "path", ".", "join", "(", "rootPath", ",", "subfolderPath", ")", ";", "// Don't delete if we have reached the base", "if", "(", "!", "subfolderPath", "||", "subfolderPath", "===", "'.'", ")", "{", "return", "cb", "(", ")", ";", "}", "fs", ".", "rmdir", "(", "fullPath", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "return", "cb", "(", "error", ")", ";", "}", "logger", ".", "verbose", "(", "'Purged empty subfolder:'", ",", "fullPath", ")", ";", "return", "purgeEmptyParentFolders", "(", "rootPath", ",", "path", ".", "dirname", "(", "subfolderPath", ")", ",", "logger", ",", "cb", ")", ";", "}", ")", ";", "}" ]
Recursively purges empty folders from subfolderPath and working its way through its parents until reaching rootPath. @param {String} rootPath - root path to which the given subfolder belongs @param {String} subfolderPath - subfolder path relative to the root path @param {Object} logger @param {Function} cb
[ "Recursively", "purges", "empty", "folders", "from", "subfolderPath", "and", "working", "its", "way", "through", "its", "parents", "until", "reaching", "rootPath", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/file/directories.js#L85-L102
19,483
mage/mage
lib/archivist/vaults/file/directories.js
purgeEmptySubFolders
function purgeEmptySubFolders(rootPath, subfolderPath, logger, cb) { subfolderPath = subfolderPath || ''; var fullPath = path.join(rootPath, subfolderPath); fs.readdir(fullPath, function (error, files) { if (error) { return cb(); } async.eachLimit(files, MAX_PARALLEL, function (file, callback) { var filepath = path.join(fullPath, file); fs.stat(filepath, function (error, stat) { if (error || !stat.isDirectory()) { return callback(); } // Recurse inwards purgeEmptySubFolders(rootPath, path.join(subfolderPath, file), logger, callback); }); }, function () { // Do nothing if root path if (!subfolderPath) { return cb(); } // Otherwise attempt to remove directory fs.rmdir(fullPath, function (error) { if (error) { return cb(); } logger.verbose('Purged empty subfolder:', fullPath); return cb(); }); }); }); }
javascript
function purgeEmptySubFolders(rootPath, subfolderPath, logger, cb) { subfolderPath = subfolderPath || ''; var fullPath = path.join(rootPath, subfolderPath); fs.readdir(fullPath, function (error, files) { if (error) { return cb(); } async.eachLimit(files, MAX_PARALLEL, function (file, callback) { var filepath = path.join(fullPath, file); fs.stat(filepath, function (error, stat) { if (error || !stat.isDirectory()) { return callback(); } // Recurse inwards purgeEmptySubFolders(rootPath, path.join(subfolderPath, file), logger, callback); }); }, function () { // Do nothing if root path if (!subfolderPath) { return cb(); } // Otherwise attempt to remove directory fs.rmdir(fullPath, function (error) { if (error) { return cb(); } logger.verbose('Purged empty subfolder:', fullPath); return cb(); }); }); }); }
[ "function", "purgeEmptySubFolders", "(", "rootPath", ",", "subfolderPath", ",", "logger", ",", "cb", ")", "{", "subfolderPath", "=", "subfolderPath", "||", "''", ";", "var", "fullPath", "=", "path", ".", "join", "(", "rootPath", ",", "subfolderPath", ")", ";", "fs", ".", "readdir", "(", "fullPath", ",", "function", "(", "error", ",", "files", ")", "{", "if", "(", "error", ")", "{", "return", "cb", "(", ")", ";", "}", "async", ".", "eachLimit", "(", "files", ",", "MAX_PARALLEL", ",", "function", "(", "file", ",", "callback", ")", "{", "var", "filepath", "=", "path", ".", "join", "(", "fullPath", ",", "file", ")", ";", "fs", ".", "stat", "(", "filepath", ",", "function", "(", "error", ",", "stat", ")", "{", "if", "(", "error", "||", "!", "stat", ".", "isDirectory", "(", ")", ")", "{", "return", "callback", "(", ")", ";", "}", "// Recurse inwards", "purgeEmptySubFolders", "(", "rootPath", ",", "path", ".", "join", "(", "subfolderPath", ",", "file", ")", ",", "logger", ",", "callback", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "// Do nothing if root path", "if", "(", "!", "subfolderPath", ")", "{", "return", "cb", "(", ")", ";", "}", "// Otherwise attempt to remove directory", "fs", ".", "rmdir", "(", "fullPath", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "return", "cb", "(", ")", ";", "}", "logger", ".", "verbose", "(", "'Purged empty subfolder:'", ",", "fullPath", ")", ";", "return", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Scans all subdirectories for a given root path and attempts to delete any empty subfolders. It will traverse to the deepest child of each branch and work backwards deleting any empty folders. If there is an error during directory removal, we just ignore it and call the callback. @param {String} rootPath - root path for given subfolder path @param {String} subfolderPath - internal recursion string (pass in null) @param {Object} logger @param {Function} cb
[ "Scans", "all", "subdirectories", "for", "a", "given", "root", "path", "and", "attempts", "to", "delete", "any", "empty", "subfolders", ".", "It", "will", "traverse", "to", "the", "deepest", "child", "of", "each", "branch", "and", "work", "backwards", "deleting", "any", "empty", "folders", ".", "If", "there", "is", "an", "error", "during", "directory", "removal", "we", "just", "ignore", "it", "and", "call", "the", "callback", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/file/directories.js#L116-L153
19,484
mage/mage
lib/archivist/migration.js
getAvailableMigrations
function getAvailableMigrations(vaultName, cb) { var path = configuration.getMigrationsPath(vaultName); fs.readdir(path, function (error, files) { if (error) { if (error.code === 'ENOENT') { logger.warning('No migration folder found for vault', vaultName, '(skipping).'); return cb(null, []); } return cb(error); } var result = []; for (var i = 0; i < files.length; i++) { var file = files[i]; var ext = extname(file); if (mage.isCodeFileExtension(ext)) { result.push(basename(file, ext)); } } cb(null, result); }); }
javascript
function getAvailableMigrations(vaultName, cb) { var path = configuration.getMigrationsPath(vaultName); fs.readdir(path, function (error, files) { if (error) { if (error.code === 'ENOENT') { logger.warning('No migration folder found for vault', vaultName, '(skipping).'); return cb(null, []); } return cb(error); } var result = []; for (var i = 0; i < files.length; i++) { var file = files[i]; var ext = extname(file); if (mage.isCodeFileExtension(ext)) { result.push(basename(file, ext)); } } cb(null, result); }); }
[ "function", "getAvailableMigrations", "(", "vaultName", ",", "cb", ")", "{", "var", "path", "=", "configuration", ".", "getMigrationsPath", "(", "vaultName", ")", ";", "fs", ".", "readdir", "(", "path", ",", "function", "(", "error", ",", "files", ")", "{", "if", "(", "error", ")", "{", "if", "(", "error", ".", "code", "===", "'ENOENT'", ")", "{", "logger", ".", "warning", "(", "'No migration folder found for vault'", ",", "vaultName", ",", "'(skipping).'", ")", ";", "return", "cb", "(", "null", ",", "[", "]", ")", ";", "}", "return", "cb", "(", "error", ")", ";", "}", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "var", "file", "=", "files", "[", "i", "]", ";", "var", "ext", "=", "extname", "(", "file", ")", ";", "if", "(", "mage", ".", "isCodeFileExtension", "(", "ext", ")", ")", "{", "result", ".", "push", "(", "basename", "(", "file", ",", "ext", ")", ")", ";", "}", "}", "cb", "(", "null", ",", "result", ")", ";", "}", ")", ";", "}" ]
Scans the hard disk for available migration files for this vault and returns the version names. @param {string} vaultName The vault name for which to migrate. @param {Function} cb Callback that receives the found version numbers that can be migrated to or from.
[ "Scans", "the", "hard", "disk", "for", "available", "migration", "files", "for", "this", "vault", "and", "returns", "the", "version", "names", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/migration.js#L116-L141
19,485
mage/mage
lib/archivist/migration.js
migrateVaultToVersion
function migrateVaultToVersion(vault, targetVersion, cb) { var preventMigrate = mage.core.config.get(['archivist', 'vaults', vault.name, 'config', 'preventMigrate'], false); if (preventMigrate) { logger.warning(`Vault ${vault.name} has disabled migrate operation (skipping)`); return cb(); } if (typeof vault.getMigrations !== 'function') { logger.warning('Cannot migrate on vault', vault.name, '(skipping).'); return cb(); } // load applied versions vault.getMigrations(function (error, appliedVersions) { if (error) { return cb(error); } getAvailableMigrations(vault.name, function (error, available) { if (error) { return cb(error); } logger.debug('Available versions with migration paths:', available); var migration = calculateMigration(targetVersion, available, appliedVersions); logger.debug('Calculated migration path:', migration); if (migration.versions.length === 0) { logger.notice('No migrations to apply on vault', vault.name); return cb(); } if (migration.direction === 'down') { migrateDown(vault, migration.versions, cb); } else { migrateUp(vault, migration.versions, cb); } }); }); }
javascript
function migrateVaultToVersion(vault, targetVersion, cb) { var preventMigrate = mage.core.config.get(['archivist', 'vaults', vault.name, 'config', 'preventMigrate'], false); if (preventMigrate) { logger.warning(`Vault ${vault.name} has disabled migrate operation (skipping)`); return cb(); } if (typeof vault.getMigrations !== 'function') { logger.warning('Cannot migrate on vault', vault.name, '(skipping).'); return cb(); } // load applied versions vault.getMigrations(function (error, appliedVersions) { if (error) { return cb(error); } getAvailableMigrations(vault.name, function (error, available) { if (error) { return cb(error); } logger.debug('Available versions with migration paths:', available); var migration = calculateMigration(targetVersion, available, appliedVersions); logger.debug('Calculated migration path:', migration); if (migration.versions.length === 0) { logger.notice('No migrations to apply on vault', vault.name); return cb(); } if (migration.direction === 'down') { migrateDown(vault, migration.versions, cb); } else { migrateUp(vault, migration.versions, cb); } }); }); }
[ "function", "migrateVaultToVersion", "(", "vault", ",", "targetVersion", ",", "cb", ")", "{", "var", "preventMigrate", "=", "mage", ".", "core", ".", "config", ".", "get", "(", "[", "'archivist'", ",", "'vaults'", ",", "vault", ".", "name", ",", "'config'", ",", "'preventMigrate'", "]", ",", "false", ")", ";", "if", "(", "preventMigrate", ")", "{", "logger", ".", "warning", "(", "`", "${", "vault", ".", "name", "}", "`", ")", ";", "return", "cb", "(", ")", ";", "}", "if", "(", "typeof", "vault", ".", "getMigrations", "!==", "'function'", ")", "{", "logger", ".", "warning", "(", "'Cannot migrate on vault'", ",", "vault", ".", "name", ",", "'(skipping).'", ")", ";", "return", "cb", "(", ")", ";", "}", "// load applied versions", "vault", ".", "getMigrations", "(", "function", "(", "error", ",", "appliedVersions", ")", "{", "if", "(", "error", ")", "{", "return", "cb", "(", "error", ")", ";", "}", "getAvailableMigrations", "(", "vault", ".", "name", ",", "function", "(", "error", ",", "available", ")", "{", "if", "(", "error", ")", "{", "return", "cb", "(", "error", ")", ";", "}", "logger", ".", "debug", "(", "'Available versions with migration paths:'", ",", "available", ")", ";", "var", "migration", "=", "calculateMigration", "(", "targetVersion", ",", "available", ",", "appliedVersions", ")", ";", "logger", ".", "debug", "(", "'Calculated migration path:'", ",", "migration", ")", ";", "if", "(", "migration", ".", "versions", ".", "length", "===", "0", ")", "{", "logger", ".", "notice", "(", "'No migrations to apply on vault'", ",", "vault", ".", "name", ")", ";", "return", "cb", "(", ")", ";", "}", "if", "(", "migration", ".", "direction", "===", "'down'", ")", "{", "migrateDown", "(", "vault", ",", "migration", ".", "versions", ",", "cb", ")", ";", "}", "else", "{", "migrateUp", "(", "vault", ",", "migration", ".", "versions", ",", "cb", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
This analyzes the strategy for migrating a single vault to a given version. Then executes that strategy. @param {Object} vault The vault to migrate @param {string} targetVersion The version to migrate to @param {Function} cb A callback to be called after migration of this vault completes
[ "This", "analyzes", "the", "strategy", "for", "migrating", "a", "single", "vault", "to", "a", "given", "version", ".", "Then", "executes", "that", "strategy", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/migration.js#L220-L262
19,486
mage/mage
scripts/create.js
copy
function copy(from, to) { var mode = fs.statSync(from).mode; var src = fs.readFileSync(from, 'utf8'); var re = /%([0-9A-Z\_]+)%/g; function replacer(_, match) { // We support the %PERIOD% variable to allow .gitignore to be created. The reason: // npm "kindly" ignores .gitignore files, so we have to use this workaround. // More info: https://github.com/isaacs/npm/issues/2958 if (match === 'PERIOD') { return '.'; } return templateRules.replace(match); } try { to = to.replace(re, replacer); src = src.replace(re, replacer); } catch (error) { pretty.warning(error + ' in: ' + from); // skip this file return; } var fd = fs.openSync(to, 'w', mode); fs.writeSync(fd, src); fs.closeSync(fd); }
javascript
function copy(from, to) { var mode = fs.statSync(from).mode; var src = fs.readFileSync(from, 'utf8'); var re = /%([0-9A-Z\_]+)%/g; function replacer(_, match) { // We support the %PERIOD% variable to allow .gitignore to be created. The reason: // npm "kindly" ignores .gitignore files, so we have to use this workaround. // More info: https://github.com/isaacs/npm/issues/2958 if (match === 'PERIOD') { return '.'; } return templateRules.replace(match); } try { to = to.replace(re, replacer); src = src.replace(re, replacer); } catch (error) { pretty.warning(error + ' in: ' + from); // skip this file return; } var fd = fs.openSync(to, 'w', mode); fs.writeSync(fd, src); fs.closeSync(fd); }
[ "function", "copy", "(", "from", ",", "to", ")", "{", "var", "mode", "=", "fs", ".", "statSync", "(", "from", ")", ".", "mode", ";", "var", "src", "=", "fs", ".", "readFileSync", "(", "from", ",", "'utf8'", ")", ";", "var", "re", "=", "/", "%([0-9A-Z\\_]+)%", "/", "g", ";", "function", "replacer", "(", "_", ",", "match", ")", "{", "// We support the %PERIOD% variable to allow .gitignore to be created. The reason:", "// npm \"kindly\" ignores .gitignore files, so we have to use this workaround.", "// More info: https://github.com/isaacs/npm/issues/2958", "if", "(", "match", "===", "'PERIOD'", ")", "{", "return", "'.'", ";", "}", "return", "templateRules", ".", "replace", "(", "match", ")", ";", "}", "try", "{", "to", "=", "to", ".", "replace", "(", "re", ",", "replacer", ")", ";", "src", "=", "src", ".", "replace", "(", "re", ",", "replacer", ")", ";", "}", "catch", "(", "error", ")", "{", "pretty", ".", "warning", "(", "error", "+", "' in: '", "+", "from", ")", ";", "// skip this file", "return", ";", "}", "var", "fd", "=", "fs", ".", "openSync", "(", "to", ",", "'w'", ",", "mode", ")", ";", "fs", ".", "writeSync", "(", "fd", ",", "src", ")", ";", "fs", ".", "closeSync", "(", "fd", ")", ";", "}" ]
Copies a file from "from" to "to", and replaces template vars in filenames and file content. @param {String} from from-path @param {String} to to-path
[ "Copies", "a", "file", "from", "from", "to", "to", "and", "replaces", "template", "vars", "in", "filenames", "and", "file", "content", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/scripts/create.js#L121-L152
19,487
mage/mage
lib/archivist/vaults/couchbase/defaultTopicApi.js
flagsToStr
function flagsToStr(flags) { if (!flags) { return; } var buff = new Buffer(4); buff.writeUInt32BE(flags, 0); // return a 0-byte terminated or 4-byte string switch (0) { case buff[0]: return; case buff[1]: return buff.toString('utf8', 0, 1); case buff[2]: return buff.toString('utf8', 0, 2); case buff[3]: return buff.toString('utf8', 0, 3); default: return buff.toString(); } }
javascript
function flagsToStr(flags) { if (!flags) { return; } var buff = new Buffer(4); buff.writeUInt32BE(flags, 0); // return a 0-byte terminated or 4-byte string switch (0) { case buff[0]: return; case buff[1]: return buff.toString('utf8', 0, 1); case buff[2]: return buff.toString('utf8', 0, 2); case buff[3]: return buff.toString('utf8', 0, 3); default: return buff.toString(); } }
[ "function", "flagsToStr", "(", "flags", ")", "{", "if", "(", "!", "flags", ")", "{", "return", ";", "}", "var", "buff", "=", "new", "Buffer", "(", "4", ")", ";", "buff", ".", "writeUInt32BE", "(", "flags", ",", "0", ")", ";", "// return a 0-byte terminated or 4-byte string", "switch", "(", "0", ")", "{", "case", "buff", "[", "0", "]", ":", "return", ";", "case", "buff", "[", "1", "]", ":", "return", "buff", ".", "toString", "(", "'utf8'", ",", "0", ",", "1", ")", ";", "case", "buff", "[", "2", "]", ":", "return", "buff", ".", "toString", "(", "'utf8'", ",", "0", ",", "2", ")", ";", "case", "buff", "[", "3", "]", ":", "return", "buff", ".", "toString", "(", "'utf8'", ",", "0", ",", "3", ")", ";", "default", ":", "return", "buff", ".", "toString", "(", ")", ";", "}", "}" ]
Turns uint32 into a max 4 char string. The node.js Buffer class provides a good uint32 conversion algorithm that we want to use. @param {number} flags @returns {string}
[ "Turns", "uint32", "into", "a", "max", "4", "char", "string", ".", "The", "node", ".", "js", "Buffer", "class", "provides", "a", "good", "uint32", "conversion", "algorithm", "that", "we", "want", "to", "use", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/couchbase/defaultTopicApi.js#L28-L50
19,488
mage/mage
lib/archivist/vaults/couchbase/defaultTopicApi.js
strToFlags
function strToFlags(str) { if (!str) { return; } var buff = new Buffer([0, 0, 0, 0]); buff.write(str, 0, 4, 'ascii'); return buff.readUInt32BE(0); }
javascript
function strToFlags(str) { if (!str) { return; } var buff = new Buffer([0, 0, 0, 0]); buff.write(str, 0, 4, 'ascii'); return buff.readUInt32BE(0); }
[ "function", "strToFlags", "(", "str", ")", "{", "if", "(", "!", "str", ")", "{", "return", ";", "}", "var", "buff", "=", "new", "Buffer", "(", "[", "0", ",", "0", ",", "0", ",", "0", "]", ")", ";", "buff", ".", "write", "(", "str", ",", "0", ",", "4", ",", "'ascii'", ")", ";", "return", "buff", ".", "readUInt32BE", "(", "0", ")", ";", "}" ]
Turns a max 4 char string into a uint32. The node.js Buffer class provides a good uint32 conversion algorithm that we want to use. @param {string} str @returns {number}
[ "Turns", "a", "max", "4", "char", "string", "into", "a", "uint32", ".", "The", "node", ".", "js", "Buffer", "class", "provides", "a", "good", "uint32", "conversion", "algorithm", "that", "we", "want", "to", "use", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/couchbase/defaultTopicApi.js#L61-L69
19,489
mage/mage
lib/config/Matryoshka/index.js
getRawRecursive
function getRawRecursive(matryoshka) { if (matryoshka.type !== 'object') { return matryoshka.value; } const returnObj = {}; for (const key of Object.keys(matryoshka.value)) { returnObj[key] = getRawRecursive(matryoshka.value[key]); } return returnObj; }
javascript
function getRawRecursive(matryoshka) { if (matryoshka.type !== 'object') { return matryoshka.value; } const returnObj = {}; for (const key of Object.keys(matryoshka.value)) { returnObj[key] = getRawRecursive(matryoshka.value[key]); } return returnObj; }
[ "function", "getRawRecursive", "(", "matryoshka", ")", "{", "if", "(", "matryoshka", ".", "type", "!==", "'object'", ")", "{", "return", "matryoshka", ".", "value", ";", "}", "const", "returnObj", "=", "{", "}", ";", "for", "(", "const", "key", "of", "Object", ".", "keys", "(", "matryoshka", ".", "value", ")", ")", "{", "returnObj", "[", "key", "]", "=", "getRawRecursive", "(", "matryoshka", ".", "value", "[", "key", "]", ")", ";", "}", "return", "returnObj", ";", "}" ]
Recursively unpeel a matryoshka to recover the raw data. @param {Matryoshka} matryoshka The matryoshka to unwrap. @return {*} The raw representation of the data contained in the matryoshka. @private
[ "Recursively", "unpeel", "a", "matryoshka", "to", "recover", "the", "raw", "data", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/config/Matryoshka/index.js#L251-L263
19,490
mage/mage
lib/config/Matryoshka/index.js
merge
function merge(a, b) { // If a is not a matryoshka, then return a copy of b (override). if (!(a instanceof Matryoshka)) { return b.copy(); } // If b is not a matryoshka, then just keep a. if (!(b instanceof Matryoshka)) { return a.copy(); } // If we reached here, both a and b are matryoshkas. // Types are 'object' (not including array or null) and 'scalar' (everything else). // If a field is empty, merge with the other object // Ex: // logging: // server: // || // \/ // logging: { // server: null // } if (a.value === null) { return b.copy(); } if (b.value === null) { return a.copy(); } // Different types means that no merge is required, and we can just copy b. if (a.type !== b.type) { return b.copy(); } // Scalar types are shallow, so a merge is really just an override. if (b.type === 'scalar') { return b.copy(); } // If we reached here, then both a and b contain objects to be compared key-by-key. // First assemble a list of keys in one or both objects. const aKeys = Object.keys(a.value); const bKeys = Object.keys(b.value); const uniqueKeys = new Set(aKeys.concat(bKeys)); const merged = {}; // Merge key-by-key. for (const key of uniqueKeys) { merged[key] = merge(a.value[key], b.value[key]); } // Wrap the merged object in a Matryoshka. return new Matryoshka(merged, a.source, true); }
javascript
function merge(a, b) { // If a is not a matryoshka, then return a copy of b (override). if (!(a instanceof Matryoshka)) { return b.copy(); } // If b is not a matryoshka, then just keep a. if (!(b instanceof Matryoshka)) { return a.copy(); } // If we reached here, both a and b are matryoshkas. // Types are 'object' (not including array or null) and 'scalar' (everything else). // If a field is empty, merge with the other object // Ex: // logging: // server: // || // \/ // logging: { // server: null // } if (a.value === null) { return b.copy(); } if (b.value === null) { return a.copy(); } // Different types means that no merge is required, and we can just copy b. if (a.type !== b.type) { return b.copy(); } // Scalar types are shallow, so a merge is really just an override. if (b.type === 'scalar') { return b.copy(); } // If we reached here, then both a and b contain objects to be compared key-by-key. // First assemble a list of keys in one or both objects. const aKeys = Object.keys(a.value); const bKeys = Object.keys(b.value); const uniqueKeys = new Set(aKeys.concat(bKeys)); const merged = {}; // Merge key-by-key. for (const key of uniqueKeys) { merged[key] = merge(a.value[key], b.value[key]); } // Wrap the merged object in a Matryoshka. return new Matryoshka(merged, a.source, true); }
[ "function", "merge", "(", "a", ",", "b", ")", "{", "// If a is not a matryoshka, then return a copy of b (override).", "if", "(", "!", "(", "a", "instanceof", "Matryoshka", ")", ")", "{", "return", "b", ".", "copy", "(", ")", ";", "}", "// If b is not a matryoshka, then just keep a.", "if", "(", "!", "(", "b", "instanceof", "Matryoshka", ")", ")", "{", "return", "a", ".", "copy", "(", ")", ";", "}", "// If we reached here, both a and b are matryoshkas.", "// Types are 'object' (not including array or null) and 'scalar' (everything else).", "// If a field is empty, merge with the other object", "// Ex:", "//\t\tlogging:", "//\t\t\tserver:", "//\t\t\t||", "//\t\t\t\\/", "//\t\tlogging: {", "//\t\t\tserver: null", "//\t\t}", "if", "(", "a", ".", "value", "===", "null", ")", "{", "return", "b", ".", "copy", "(", ")", ";", "}", "if", "(", "b", ".", "value", "===", "null", ")", "{", "return", "a", ".", "copy", "(", ")", ";", "}", "// Different types means that no merge is required, and we can just copy b.", "if", "(", "a", ".", "type", "!==", "b", ".", "type", ")", "{", "return", "b", ".", "copy", "(", ")", ";", "}", "// Scalar types are shallow, so a merge is really just an override.", "if", "(", "b", ".", "type", "===", "'scalar'", ")", "{", "return", "b", ".", "copy", "(", ")", ";", "}", "// If we reached here, then both a and b contain objects to be compared key-by-key.", "// First assemble a list of keys in one or both objects.", "const", "aKeys", "=", "Object", ".", "keys", "(", "a", ".", "value", ")", ";", "const", "bKeys", "=", "Object", ".", "keys", "(", "b", ".", "value", ")", ";", "const", "uniqueKeys", "=", "new", "Set", "(", "aKeys", ".", "concat", "(", "bKeys", ")", ")", ";", "const", "merged", "=", "{", "}", ";", "// Merge key-by-key.", "for", "(", "const", "key", "of", "uniqueKeys", ")", "{", "merged", "[", "key", "]", "=", "merge", "(", "a", ".", "value", "[", "key", "]", ",", "b", ".", "value", "[", "key", "]", ")", ";", "}", "// Wrap the merged object in a Matryoshka.", "return", "new", "Matryoshka", "(", "merged", ",", "a", ".", "source", ",", "true", ")", ";", "}" ]
Merges a and b together into a new Matryoshka. Does not affect the state of a or b, and b overrides a. At least one is guaranteed to be a Matryoshka. @param {Matryoshka} a Matryoshka of lesser importance. @param {Matryoshka} b Matryoshka of greater importance. @return {Matryoshka} Resultant merge of a and b.
[ "Merges", "a", "and", "b", "together", "into", "a", "new", "Matryoshka", ".", "Does", "not", "affect", "the", "state", "of", "a", "or", "b", "and", "b", "overrides", "a", ".", "At", "least", "one", "is", "guaranteed", "to", "be", "a", "Matryoshka", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/config/Matryoshka/index.js#L274-L333
19,491
mage/mage
lib/commandCenter/commandCenter.js
serializeCommandResult
function serializeCommandResult(result) { const out = []; out.push(result.errorCode || 'null'); out.push(result.response || 'null'); if (result.myEvents && result.myEvents.length) { out.push('[' + result.myEvents.join(',') + ']'); } return '[' + out.join(',') + ']'; }
javascript
function serializeCommandResult(result) { const out = []; out.push(result.errorCode || 'null'); out.push(result.response || 'null'); if (result.myEvents && result.myEvents.length) { out.push('[' + result.myEvents.join(',') + ']'); } return '[' + out.join(',') + ']'; }
[ "function", "serializeCommandResult", "(", "result", ")", "{", "const", "out", "=", "[", "]", ";", "out", ".", "push", "(", "result", ".", "errorCode", "||", "'null'", ")", ";", "out", ".", "push", "(", "result", ".", "response", "||", "'null'", ")", ";", "if", "(", "result", ".", "myEvents", "&&", "result", ".", "myEvents", ".", "length", ")", "{", "out", ".", "push", "(", "'['", "+", "result", ".", "myEvents", ".", "join", "(", "','", ")", "+", "']'", ")", ";", "}", "return", "'['", "+", "out", ".", "join", "(", "','", ")", "+", "']'", ";", "}" ]
Serializes a single command response into a string. @param {Object} result The result of the user command, including pre-serialized arguments @param {string} [result.errorCode] JSON serialized error code @param {string} [result.response] JSON serialized response value @param {string[]} [result.myEvents] Array of JSON serialized events for the executing user @returns {string} The serialized response.
[ "Serializes", "a", "single", "command", "response", "into", "a", "string", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/commandCenter.js#L353-L364
19,492
mage/mage
lib/commandCenter/commandCenter.js
generateCommandPromise
function generateCommandPromise(cmdInfo, state, paramList) { const mod = cmdInfo.mod; const execute = () => mod.execute.apply(mod, paramList); if (cmdInfo.isAsync) { // Async user commands will need to take the response value, and feed it // to `state.respond` const isJson = mod.serialize === false; return execute() .then((response) => state.respond(response, isJson)); } else { // Callback-based user commands are expected to call `state.respond` // on their own; all we need to do is promisify return new Promise((resolve) => paramList.push(resolve) && execute()); } }
javascript
function generateCommandPromise(cmdInfo, state, paramList) { const mod = cmdInfo.mod; const execute = () => mod.execute.apply(mod, paramList); if (cmdInfo.isAsync) { // Async user commands will need to take the response value, and feed it // to `state.respond` const isJson = mod.serialize === false; return execute() .then((response) => state.respond(response, isJson)); } else { // Callback-based user commands are expected to call `state.respond` // on their own; all we need to do is promisify return new Promise((resolve) => paramList.push(resolve) && execute()); } }
[ "function", "generateCommandPromise", "(", "cmdInfo", ",", "state", ",", "paramList", ")", "{", "const", "mod", "=", "cmdInfo", ".", "mod", ";", "const", "execute", "=", "(", ")", "=>", "mod", ".", "execute", ".", "apply", "(", "mod", ",", "paramList", ")", ";", "if", "(", "cmdInfo", ".", "isAsync", ")", "{", "// Async user commands will need to take the response value, and feed it", "// to `state.respond`", "const", "isJson", "=", "mod", ".", "serialize", "===", "false", ";", "return", "execute", "(", ")", ".", "then", "(", "(", "response", ")", "=>", "state", ".", "respond", "(", "response", ",", "isJson", ")", ")", ";", "}", "else", "{", "// Callback-based user commands are expected to call `state.respond`", "// on their own; all we need to do is promisify", "return", "new", "Promise", "(", "(", "resolve", ")", "=>", "paramList", ".", "push", "(", "resolve", ")", "&&", "execute", "(", ")", ")", ";", "}", "}" ]
Promisify the user command execute method, or ensure its return value is passed to state.respond Once callback-based user commands are removed from MAGE, you will be able to remove this method. @param {*} cmdInfo @param {State} state @param {*} paramList
[ "Promisify", "the", "user", "command", "execute", "method", "or", "ensure", "its", "return", "value", "is", "passed", "to", "state", ".", "respond" ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/commandCenter.js#L417-L433
19,493
mage/mage
lib/commandCenter/commandCenter.js
createTimerPromise
function createTimerPromise(commandName, timeout) { let timer; const promise = new Promise((resolve, reject) => { if (timeout) { timer = setTimeout(() => reject(new UserCommandExecutionTimeout(commandName)), timeout); } }); promise.clear = () => clearTimeout(timer); return promise; }
javascript
function createTimerPromise(commandName, timeout) { let timer; const promise = new Promise((resolve, reject) => { if (timeout) { timer = setTimeout(() => reject(new UserCommandExecutionTimeout(commandName)), timeout); } }); promise.clear = () => clearTimeout(timer); return promise; }
[ "function", "createTimerPromise", "(", "commandName", ",", "timeout", ")", "{", "let", "timer", ";", "const", "promise", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "timeout", ")", "{", "timer", "=", "setTimeout", "(", "(", ")", "=>", "reject", "(", "new", "UserCommandExecutionTimeout", "(", "commandName", ")", ")", ",", "timeout", ")", ";", "}", "}", ")", ";", "promise", ".", "clear", "=", "(", ")", "=>", "clearTimeout", "(", "timer", ")", ";", "return", "promise", ";", "}" ]
Create a promise timer Useful when using Promise.race. @param {number} timeout
[ "Create", "a", "promise", "timer" ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/commandCenter.js#L442-L454
19,494
mage/mage
lib/commandCenter/commandCenter.js
processBatchHeader
function processBatchHeader(state, batch, cb) { if (messageHooks.length === 0) { return cb(); } var hookData = {}; for (var i = 0; i < batch.header.length; i += 1) { var header = batch.header[i]; if (header.name) { hookData[header.name] = header; } } async.eachSeries( messageHooks, function (hook, cb) { var data = hookData[hook.name]; if (!data) { // if the hook wasn't mentioned in the RPC call, and it's not required to be executed, ignore it if (!hook.required) { return cb(); } data = { name: hook.name }; } hook.fn(state, data, batch, cb); }, function (error) { if (error) { // error while handling hooks (probably parse errors) return cb(error); } // some hooks may have caused mutations (eg: session touch), so distribute these first state.archivist.distribute(cb); } ); }
javascript
function processBatchHeader(state, batch, cb) { if (messageHooks.length === 0) { return cb(); } var hookData = {}; for (var i = 0; i < batch.header.length; i += 1) { var header = batch.header[i]; if (header.name) { hookData[header.name] = header; } } async.eachSeries( messageHooks, function (hook, cb) { var data = hookData[hook.name]; if (!data) { // if the hook wasn't mentioned in the RPC call, and it's not required to be executed, ignore it if (!hook.required) { return cb(); } data = { name: hook.name }; } hook.fn(state, data, batch, cb); }, function (error) { if (error) { // error while handling hooks (probably parse errors) return cb(error); } // some hooks may have caused mutations (eg: session touch), so distribute these first state.archivist.distribute(cb); } ); }
[ "function", "processBatchHeader", "(", "state", ",", "batch", ",", "cb", ")", "{", "if", "(", "messageHooks", ".", "length", "===", "0", ")", "{", "return", "cb", "(", ")", ";", "}", "var", "hookData", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "batch", ".", "header", ".", "length", ";", "i", "+=", "1", ")", "{", "var", "header", "=", "batch", ".", "header", "[", "i", "]", ";", "if", "(", "header", ".", "name", ")", "{", "hookData", "[", "header", ".", "name", "]", "=", "header", ";", "}", "}", "async", ".", "eachSeries", "(", "messageHooks", ",", "function", "(", "hook", ",", "cb", ")", "{", "var", "data", "=", "hookData", "[", "hook", ".", "name", "]", ";", "if", "(", "!", "data", ")", "{", "// if the hook wasn't mentioned in the RPC call, and it's not required to be executed, ignore it", "if", "(", "!", "hook", ".", "required", ")", "{", "return", "cb", "(", ")", ";", "}", "data", "=", "{", "name", ":", "hook", ".", "name", "}", ";", "}", "hook", ".", "fn", "(", "state", ",", "data", ",", "batch", ",", "cb", ")", ";", "}", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "// error while handling hooks (probably parse errors)", "return", "cb", "(", "error", ")", ";", "}", "// some hooks may have caused mutations (eg: session touch), so distribute these first", "state", ".", "archivist", ".", "distribute", "(", "cb", ")", ";", "}", ")", ";", "}" ]
Calls all message hooks required for a batch. @param {State} state MAGE state object. @param {Object} batch Command batch object. @param {Object} batch.app The app object that this batch is for (hooks can filter on app.name). @param {string} batch.rawData The raw request data (may be useful for hashing). @param {Object[]} batch.header Array of header objects that will be passed to message hook functions. @param {Object[]} batch.commands Array of command objects { name: str, params: Object } @param {string[]} batch.commandNames Array of all command names in the batch, in order. @param {Function} cb Callback on completion.
[ "Calls", "all", "message", "hooks", "required", "for", "a", "batch", "." ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/commandCenter.js#L665-L706
19,495
mage/mage
lib/commandCenter/commandCenter.js
respond
function respond(options, content, cache) { // cache the response var cached = that.responseCache.set(state, queryId, options, cache); // send the response back to the client cb(null, content, options); // log the execution time var msg = cached ? 'Executed and cached user command batch' : 'Executed user command batch (could not cache)'; logger.debug .data({ batch: batch.commandNames, queryId: queryId, durationMsec: duration(), options: options, dataSize: content.length }) .log(msg); }
javascript
function respond(options, content, cache) { // cache the response var cached = that.responseCache.set(state, queryId, options, cache); // send the response back to the client cb(null, content, options); // log the execution time var msg = cached ? 'Executed and cached user command batch' : 'Executed user command batch (could not cache)'; logger.debug .data({ batch: batch.commandNames, queryId: queryId, durationMsec: duration(), options: options, dataSize: content.length }) .log(msg); }
[ "function", "respond", "(", "options", ",", "content", ",", "cache", ")", "{", "// cache the response", "var", "cached", "=", "that", ".", "responseCache", ".", "set", "(", "state", ",", "queryId", ",", "options", ",", "cache", ")", ";", "// send the response back to the client", "cb", "(", "null", ",", "content", ",", "options", ")", ";", "// log the execution time", "var", "msg", "=", "cached", "?", "'Executed and cached user command batch'", ":", "'Executed user command batch (could not cache)'", ";", "logger", ".", "debug", ".", "data", "(", "{", "batch", ":", "batch", ".", "commandNames", ",", "queryId", ":", "queryId", ",", "durationMsec", ":", "duration", "(", ")", ",", "options", ":", "options", ",", "dataSize", ":", "content", ".", "length", "}", ")", ".", "log", "(", "msg", ")", ";", "}" ]
start executing commands and build a serialized output response
[ "start", "executing", "commands", "and", "build", "a", "serialized", "output", "response" ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/commandCenter.js#L781-L805
19,496
mage/mage
lib/commandCenter/commandCenter.js
runCommand
function runCommand(output, cache, cmdIndex) { var cmd = batch.commands[cmdIndex]; if (cmd) { if (cacheContent.length !== 0 && isCachedCommand(cmd)) { logger.warning .data({ cmd: cmd.cmdName }) .log('Re-sending cached command response'); output += (output ? ',' : '[') + cacheContent.shift(); return setImmediate(runCommand, output, cache, cmdIndex + 1); } return that.executeCommand(cmd, session, metaData, function (error, response) { if (error) { // should never happen return cb(error); } if (headerEvents && headerEvents.length) { response.myEvents = response.myEvents || []; response.myEvents = headerEvents.concat(response.myEvents); headerEvents = null; } const serializedResponse = serializeCommandResult(response); output += (output ? ',' : '[') + serializedResponse; if (isCachedCommand(cmd)) { cache += (cache ? ',' : '[') + JSON.stringify(serializedResponse); } setImmediate(runCommand, output, cache, cmdIndex + 1); }); } // close the output JSON array output += ']'; if (cache === '') { cache = '[]'; } else { cache += ']'; } // turn results array into a reportable response (possibly gzipped) var options = { mimetype: CONTENT_TYPE_JSON }; if (!shouldCompress(output, acceptedEncodings)) { return respond(options, output, cache); } return compress(output, function (error, compressed) { if (error) { // error during compression, send the original respond(options, output, cache); } else { options.encoding = 'gzip'; respond(options, compressed, cache); } }); }
javascript
function runCommand(output, cache, cmdIndex) { var cmd = batch.commands[cmdIndex]; if (cmd) { if (cacheContent.length !== 0 && isCachedCommand(cmd)) { logger.warning .data({ cmd: cmd.cmdName }) .log('Re-sending cached command response'); output += (output ? ',' : '[') + cacheContent.shift(); return setImmediate(runCommand, output, cache, cmdIndex + 1); } return that.executeCommand(cmd, session, metaData, function (error, response) { if (error) { // should never happen return cb(error); } if (headerEvents && headerEvents.length) { response.myEvents = response.myEvents || []; response.myEvents = headerEvents.concat(response.myEvents); headerEvents = null; } const serializedResponse = serializeCommandResult(response); output += (output ? ',' : '[') + serializedResponse; if (isCachedCommand(cmd)) { cache += (cache ? ',' : '[') + JSON.stringify(serializedResponse); } setImmediate(runCommand, output, cache, cmdIndex + 1); }); } // close the output JSON array output += ']'; if (cache === '') { cache = '[]'; } else { cache += ']'; } // turn results array into a reportable response (possibly gzipped) var options = { mimetype: CONTENT_TYPE_JSON }; if (!shouldCompress(output, acceptedEncodings)) { return respond(options, output, cache); } return compress(output, function (error, compressed) { if (error) { // error during compression, send the original respond(options, output, cache); } else { options.encoding = 'gzip'; respond(options, compressed, cache); } }); }
[ "function", "runCommand", "(", "output", ",", "cache", ",", "cmdIndex", ")", "{", "var", "cmd", "=", "batch", ".", "commands", "[", "cmdIndex", "]", ";", "if", "(", "cmd", ")", "{", "if", "(", "cacheContent", ".", "length", "!==", "0", "&&", "isCachedCommand", "(", "cmd", ")", ")", "{", "logger", ".", "warning", ".", "data", "(", "{", "cmd", ":", "cmd", ".", "cmdName", "}", ")", ".", "log", "(", "'Re-sending cached command response'", ")", ";", "output", "+=", "(", "output", "?", "','", ":", "'['", ")", "+", "cacheContent", ".", "shift", "(", ")", ";", "return", "setImmediate", "(", "runCommand", ",", "output", ",", "cache", ",", "cmdIndex", "+", "1", ")", ";", "}", "return", "that", ".", "executeCommand", "(", "cmd", ",", "session", ",", "metaData", ",", "function", "(", "error", ",", "response", ")", "{", "if", "(", "error", ")", "{", "// should never happen", "return", "cb", "(", "error", ")", ";", "}", "if", "(", "headerEvents", "&&", "headerEvents", ".", "length", ")", "{", "response", ".", "myEvents", "=", "response", ".", "myEvents", "||", "[", "]", ";", "response", ".", "myEvents", "=", "headerEvents", ".", "concat", "(", "response", ".", "myEvents", ")", ";", "headerEvents", "=", "null", ";", "}", "const", "serializedResponse", "=", "serializeCommandResult", "(", "response", ")", ";", "output", "+=", "(", "output", "?", "','", ":", "'['", ")", "+", "serializedResponse", ";", "if", "(", "isCachedCommand", "(", "cmd", ")", ")", "{", "cache", "+=", "(", "cache", "?", "','", ":", "'['", ")", "+", "JSON", ".", "stringify", "(", "serializedResponse", ")", ";", "}", "setImmediate", "(", "runCommand", ",", "output", ",", "cache", ",", "cmdIndex", "+", "1", ")", ";", "}", ")", ";", "}", "// close the output JSON array", "output", "+=", "']'", ";", "if", "(", "cache", "===", "''", ")", "{", "cache", "=", "'[]'", ";", "}", "else", "{", "cache", "+=", "']'", ";", "}", "// turn results array into a reportable response (possibly gzipped)", "var", "options", "=", "{", "mimetype", ":", "CONTENT_TYPE_JSON", "}", ";", "if", "(", "!", "shouldCompress", "(", "output", ",", "acceptedEncodings", ")", ")", "{", "return", "respond", "(", "options", ",", "output", ",", "cache", ")", ";", "}", "return", "compress", "(", "output", ",", "function", "(", "error", ",", "compressed", ")", "{", "if", "(", "error", ")", "{", "// error during compression, send the original", "respond", "(", "options", ",", "output", ",", "cache", ")", ";", "}", "else", "{", "options", ".", "encoding", "=", "'gzip'", ";", "respond", "(", "options", ",", "compressed", ",", "cache", ")", ";", "}", "}", ")", ";", "}" ]
recursively runs each command, until done, then calls respond
[ "recursively", "runs", "each", "command", "until", "done", "then", "calls", "respond" ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/commandCenter.js#L809-L874
19,497
mage/mage
lib/archivist/vaults/mysql/index.js
MysqlVault
function MysqlVault(name, logger) { var that = this; // required exposed properties this.name = name; // the unique vault name this.archive = new Archive(this); // archivist bindings // internals this.mysql = null; // node-mysql library this.config = null; // the URI that connections will be established to this.pool = null; // node-mysql connection pool this.logger = logger; /* jshint camelcase:false */ // connection is here for backward compat, please use pool from now on this.__defineGetter__('connection', function () { logger.debug('Accessing the "connection" property on the mysql vault is deprecated, please' + ' use the "pool" property'); return that.pool; }); }
javascript
function MysqlVault(name, logger) { var that = this; // required exposed properties this.name = name; // the unique vault name this.archive = new Archive(this); // archivist bindings // internals this.mysql = null; // node-mysql library this.config = null; // the URI that connections will be established to this.pool = null; // node-mysql connection pool this.logger = logger; /* jshint camelcase:false */ // connection is here for backward compat, please use pool from now on this.__defineGetter__('connection', function () { logger.debug('Accessing the "connection" property on the mysql vault is deprecated, please' + ' use the "pool" property'); return that.pool; }); }
[ "function", "MysqlVault", "(", "name", ",", "logger", ")", "{", "var", "that", "=", "this", ";", "// required exposed properties", "this", ".", "name", "=", "name", ";", "// the unique vault name", "this", ".", "archive", "=", "new", "Archive", "(", "this", ")", ";", "// archivist bindings", "// internals", "this", ".", "mysql", "=", "null", ";", "// node-mysql library", "this", ".", "config", "=", "null", ";", "// the URI that connections will be established to", "this", ".", "pool", "=", "null", ";", "// node-mysql connection pool", "this", ".", "logger", "=", "logger", ";", "/* jshint camelcase:false */", "// connection is here for backward compat, please use pool from now on", "this", ".", "__defineGetter__", "(", "'connection'", ",", "function", "(", ")", "{", "logger", ".", "debug", "(", "'Accessing the \"connection\" property on the mysql vault is deprecated, please'", "+", "' use the \"pool\" property'", ")", ";", "return", "that", ".", "pool", ";", "}", ")", ";", "}" ]
Vault wrapper around node-mysql
[ "Vault", "wrapper", "around", "node", "-", "mysql" ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/mysql/index.js#L38-L60
19,498
mage/mage
lib/tasks/serve.js
setupModules
function setupModules(callback) { if (mage.core.processManager.isMaster) { return callback(); } mage.setupModules(callback); }
javascript
function setupModules(callback) { if (mage.core.processManager.isMaster) { return callback(); } mage.setupModules(callback); }
[ "function", "setupModules", "(", "callback", ")", "{", "if", "(", "mage", ".", "core", ".", "processManager", ".", "isMaster", ")", "{", "return", "callback", "(", ")", ";", "}", "mage", ".", "setupModules", "(", "callback", ")", ";", "}" ]
Set up the modules
[ "Set", "up", "the", "modules" ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/tasks/serve.js#L48-L54
19,499
mage/mage
lib/tasks/serve.js
createApps
function createApps(callback) { if (mage.core.processManager.isMaster) { return callback(); } try { mage.core.app.createApps(); } catch (error) { return callback(error); } return callback(); }
javascript
function createApps(callback) { if (mage.core.processManager.isMaster) { return callback(); } try { mage.core.app.createApps(); } catch (error) { return callback(error); } return callback(); }
[ "function", "createApps", "(", "callback", ")", "{", "if", "(", "mage", ".", "core", ".", "processManager", ".", "isMaster", ")", "{", "return", "callback", "(", ")", ";", "}", "try", "{", "mage", ".", "core", ".", "app", ".", "createApps", "(", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "return", "callback", "(", ")", ";", "}" ]
Create the apps
[ "Create", "the", "apps" ]
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/tasks/serve.js#L58-L70