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
40,000
jscheel/metalsmith-encode-html
lib/index.js
plugin
function plugin(options){ options = options || {}; var keys = options.keys || []; return function(files, metalsmith, done){ setImmediate(done); Object.keys(files).forEach(function(file){ debug('checking file: %s', file); if (!isHtml(file)) return; var data = files[file]; var dir = dirname(file); var html = basename(file, extname(file)) + '.html'; if ('.' != dir) html = dir + '/' + html; debug('Encoding html entities in file: %s', file); var reg = /\`\`\`([\s\S]+?)\`\`\`/gi; var rep = function(match, group) { if (group) { return he.encode(group, {useNamedReferences: true}); } else { return ""; } }; var encoded = data.contents.toString().replace(reg, rep); data.contents = new Buffer(encoded); keys.forEach(function(key) { data[key] = data[key].replace(reg, rep); }); delete files[file]; files[html] = data; }); }; }
javascript
function plugin(options){ options = options || {}; var keys = options.keys || []; return function(files, metalsmith, done){ setImmediate(done); Object.keys(files).forEach(function(file){ debug('checking file: %s', file); if (!isHtml(file)) return; var data = files[file]; var dir = dirname(file); var html = basename(file, extname(file)) + '.html'; if ('.' != dir) html = dir + '/' + html; debug('Encoding html entities in file: %s', file); var reg = /\`\`\`([\s\S]+?)\`\`\`/gi; var rep = function(match, group) { if (group) { return he.encode(group, {useNamedReferences: true}); } else { return ""; } }; var encoded = data.contents.toString().replace(reg, rep); data.contents = new Buffer(encoded); keys.forEach(function(key) { data[key] = data[key].replace(reg, rep); }); delete files[file]; files[html] = data; }); }; }
[ "function", "plugin", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "keys", "=", "options", ".", "keys", "||", "[", "]", ";", "return", "function", "(", "files", ",", "metalsmith", ",", "done", ")", "{", "setImmediate", "(", "done", ")", ";", "Object", ".", "keys", "(", "files", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "debug", "(", "'checking file: %s'", ",", "file", ")", ";", "if", "(", "!", "isHtml", "(", "file", ")", ")", "return", ";", "var", "data", "=", "files", "[", "file", "]", ";", "var", "dir", "=", "dirname", "(", "file", ")", ";", "var", "html", "=", "basename", "(", "file", ",", "extname", "(", "file", ")", ")", "+", "'.html'", ";", "if", "(", "'.'", "!=", "dir", ")", "html", "=", "dir", "+", "'/'", "+", "html", ";", "debug", "(", "'Encoding html entities in file: %s'", ",", "file", ")", ";", "var", "reg", "=", "/", "\\`\\`\\`([\\s\\S]+?)\\`\\`\\`", "/", "gi", ";", "var", "rep", "=", "function", "(", "match", ",", "group", ")", "{", "if", "(", "group", ")", "{", "return", "he", ".", "encode", "(", "group", ",", "{", "useNamedReferences", ":", "true", "}", ")", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}", ";", "var", "encoded", "=", "data", ".", "contents", ".", "toString", "(", ")", ".", "replace", "(", "reg", ",", "rep", ")", ";", "data", ".", "contents", "=", "new", "Buffer", "(", "encoded", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "data", "[", "key", "]", "=", "data", "[", "key", "]", ".", "replace", "(", "reg", ",", "rep", ")", ";", "}", ")", ";", "delete", "files", "[", "file", "]", ";", "files", "[", "html", "]", "=", "data", ";", "}", ")", ";", "}", ";", "}" ]
Metalsmith plugin to encode html entities in html files. @param {Object} options (optional) @property {Array} keys @return {Function}
[ "Metalsmith", "plugin", "to", "encode", "html", "entities", "in", "html", "files", "." ]
f3d728a776aef1702b0dcb9810908dbe7d19ce81
https://github.com/jscheel/metalsmith-encode-html/blob/f3d728a776aef1702b0dcb9810908dbe7d19ce81/lib/index.js#L22-L58
40,001
PAI-Tech/PAI-BOT-JS
src/pai-bot/src/module-ext/learn.js
npmInstall
function npmInstall(packageName) { return new Promise((resolve,reject) => { npm.load({ save:false, progress: false, force:true }, function (er) { if (er) { PAILogger.error(er); return reject(er); } npm.commands.install([packageName], function (er, data) { if (er) { PAILogger.error(er); return reject(er); } resolve(data); // command succeeded, and data might have some info }); }); }); }
javascript
function npmInstall(packageName) { return new Promise((resolve,reject) => { npm.load({ save:false, progress: false, force:true }, function (er) { if (er) { PAILogger.error(er); return reject(er); } npm.commands.install([packageName], function (er, data) { if (er) { PAILogger.error(er); return reject(er); } resolve(data); // command succeeded, and data might have some info }); }); }); }
[ "function", "npmInstall", "(", "packageName", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "npm", ".", "load", "(", "{", "save", ":", "false", ",", "progress", ":", "false", ",", "force", ":", "true", "}", ",", "function", "(", "er", ")", "{", "if", "(", "er", ")", "{", "PAILogger", ".", "error", "(", "er", ")", ";", "return", "reject", "(", "er", ")", ";", "}", "npm", ".", "commands", ".", "install", "(", "[", "packageName", "]", ",", "function", "(", "er", ",", "data", ")", "{", "if", "(", "er", ")", "{", "PAILogger", ".", "error", "(", "er", ")", ";", "return", "reject", "(", "er", ")", ";", "}", "resolve", "(", "data", ")", ";", "// command succeeded, and data might have some info", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Install new NPM package @param {String} packageName @return {Promise<any>}
[ "Install", "new", "NPM", "package" ]
7744e54f580e18264861e33f2c05aac58b5ad1d9
https://github.com/PAI-Tech/PAI-BOT-JS/blob/7744e54f580e18264861e33f2c05aac58b5ad1d9/src/pai-bot/src/module-ext/learn.js#L56-L83
40,002
bartve/dot-view
index.js
function(filePath, currentPath){ if(/^(?:\/|[a-zA-Z]:(?:\/|\\))/.test(filePath)){ // Is the path absolute? filePath = path.normalize(filePath); }else{ // Relative paths need to be resolved first filePath = path.resolve(currentPath, filePath); } return filePath; }
javascript
function(filePath, currentPath){ if(/^(?:\/|[a-zA-Z]:(?:\/|\\))/.test(filePath)){ // Is the path absolute? filePath = path.normalize(filePath); }else{ // Relative paths need to be resolved first filePath = path.resolve(currentPath, filePath); } return filePath; }
[ "function", "(", "filePath", ",", "currentPath", ")", "{", "if", "(", "/", "^(?:\\/|[a-zA-Z]:(?:\\/|\\\\))", "/", ".", "test", "(", "filePath", ")", ")", "{", "// Is the path absolute?", "filePath", "=", "path", ".", "normalize", "(", "filePath", ")", ";", "}", "else", "{", "// Relative paths need to be resolved first", "filePath", "=", "path", ".", "resolve", "(", "currentPath", ",", "filePath", ")", ";", "}", "return", "filePath", ";", "}" ]
Parse absolute and relative path strings to a full path @param {string} filePath @param {string} currentPath @returns {string}
[ "Parse", "absolute", "and", "relative", "path", "strings", "to", "a", "full", "path" ]
580af6937c179d5b9ae05e6f6cd9d61a886f4fc5
https://github.com/bartve/dot-view/blob/580af6937c179d5b9ae05e6f6cd9d61a886f4fc5/index.js#L16-L23
40,003
bartve/dot-view
index.js
View
function View(tplPath, tplFile, data){ this.data = data||{}; this.defines = {}; this.enabled = true; // Default settings this.settings = doT.templateSettings; this.settings.varname = 'it,helpers'; // Add the helpers as a second data param for the parser this.settings.cache = true; // Use memory cache for compiled template functions this.settings.layout = /\{\{##\s*(?:def\.)?_layout\s*(?:\:|=)\s*([\s\S]+?)\s*#\}\}/; // Layout regex if(tplPath){ this.path = tplPath; } if(tplFile){ this.file = tplFile; this.layout(); } }
javascript
function View(tplPath, tplFile, data){ this.data = data||{}; this.defines = {}; this.enabled = true; // Default settings this.settings = doT.templateSettings; this.settings.varname = 'it,helpers'; // Add the helpers as a second data param for the parser this.settings.cache = true; // Use memory cache for compiled template functions this.settings.layout = /\{\{##\s*(?:def\.)?_layout\s*(?:\:|=)\s*([\s\S]+?)\s*#\}\}/; // Layout regex if(tplPath){ this.path = tplPath; } if(tplFile){ this.file = tplFile; this.layout(); } }
[ "function", "View", "(", "tplPath", ",", "tplFile", ",", "data", ")", "{", "this", ".", "data", "=", "data", "||", "{", "}", ";", "this", ".", "defines", "=", "{", "}", ";", "this", ".", "enabled", "=", "true", ";", "// Default settings", "this", ".", "settings", "=", "doT", ".", "templateSettings", ";", "this", ".", "settings", ".", "varname", "=", "'it,helpers'", ";", "// Add the helpers as a second data param for the parser", "this", ".", "settings", ".", "cache", "=", "true", ";", "// Use memory cache for compiled template functions", "this", ".", "settings", ".", "layout", "=", "/", "\\{\\{##\\s*(?:def\\.)?_layout\\s*(?:\\:|=)\\s*([\\s\\S]+?)\\s*#\\}\\}", "/", ";", "// Layout regex", "if", "(", "tplPath", ")", "{", "this", ".", "path", "=", "tplPath", ";", "}", "if", "(", "tplFile", ")", "{", "this", ".", "file", "=", "tplFile", ";", "this", ".", "layout", "(", ")", ";", "}", "}" ]
Object constructor. For quick use, the most important properties can be set in the constructor. @constructor @param {string} [tplPath] - The path of the template file @param {string} [tplFile] - The filename of the template file @param {object} [data={}] - The template data @return {View}
[ "Object", "constructor", ".", "For", "quick", "use", "the", "most", "important", "properties", "can", "be", "set", "in", "the", "constructor", "." ]
580af6937c179d5b9ae05e6f6cd9d61a886f4fc5
https://github.com/bartve/dot-view/blob/580af6937c179d5b9ae05e6f6cd9d61a886f4fc5/index.js#L48-L62
40,004
Cerealkillerway/versionUpdater
lib/version.js
fullWidth
function fullWidth(text, param) { let cols = process.stdout.columns; let lines = text.split('\n'); for (i = 0; i < lines.length; i++) { let size = cols; if (i === 0) size = size - 15; if ((lines[i].indexOf('%') > 0) && (param !== undefined)) size = size - param.length + 2; while (lines[i].length < size) { lines[i] = lines[i] + ' '; } } text = lines.join('\n'); return text; }
javascript
function fullWidth(text, param) { let cols = process.stdout.columns; let lines = text.split('\n'); for (i = 0; i < lines.length; i++) { let size = cols; if (i === 0) size = size - 15; if ((lines[i].indexOf('%') > 0) && (param !== undefined)) size = size - param.length + 2; while (lines[i].length < size) { lines[i] = lines[i] + ' '; } } text = lines.join('\n'); return text; }
[ "function", "fullWidth", "(", "text", ",", "param", ")", "{", "let", "cols", "=", "process", ".", "stdout", ".", "columns", ";", "let", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "let", "size", "=", "cols", ";", "if", "(", "i", "===", "0", ")", "size", "=", "size", "-", "15", ";", "if", "(", "(", "lines", "[", "i", "]", ".", "indexOf", "(", "'%'", ")", ">", "0", ")", "&&", "(", "param", "!==", "undefined", ")", ")", "size", "=", "size", "-", "param", ".", "length", "+", "2", ";", "while", "(", "lines", "[", "i", "]", ".", "length", "<", "size", ")", "{", "lines", "[", "i", "]", "=", "lines", "[", "i", "]", "+", "' '", ";", "}", "}", "text", "=", "lines", ".", "join", "(", "'\\n'", ")", ";", "return", "text", ";", "}" ]
make all the lines of a text as long as terminal's width
[ "make", "all", "the", "lines", "of", "a", "text", "as", "long", "as", "terminal", "s", "width" ]
977ef78d990ad6dd9bfd716f860bd05790c442d2
https://github.com/Cerealkillerway/versionUpdater/blob/977ef78d990ad6dd9bfd716f860bd05790c442d2/lib/version.js#L101-L116
40,005
Cerealkillerway/versionUpdater
lib/version.js
revertInit
function revertInit(reinit, list, prefix, name, currentVersion) { exec('rm -Rf ./.versionFilesList.json', function(error, stdout, stderr) { if (error) sendProcessError(stdout, stderr); print('Deleted previous .versionFilesList.json', 'important', 'date'); if (reinit) init(list, prefix, name, currentVersion); }); }
javascript
function revertInit(reinit, list, prefix, name, currentVersion) { exec('rm -Rf ./.versionFilesList.json', function(error, stdout, stderr) { if (error) sendProcessError(stdout, stderr); print('Deleted previous .versionFilesList.json', 'important', 'date'); if (reinit) init(list, prefix, name, currentVersion); }); }
[ "function", "revertInit", "(", "reinit", ",", "list", ",", "prefix", ",", "name", ",", "currentVersion", ")", "{", "exec", "(", "'rm -Rf ./.versionFilesList.json'", ",", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "error", ")", "sendProcessError", "(", "stdout", ",", "stderr", ")", ";", "print", "(", "'Deleted previous .versionFilesList.json'", ",", "'important'", ",", "'date'", ")", ";", "if", "(", "reinit", ")", "init", "(", "list", ",", "prefix", ",", "name", ",", "currentVersion", ")", ";", "}", ")", ";", "}" ]
delete files list
[ "delete", "files", "list" ]
977ef78d990ad6dd9bfd716f860bd05790c442d2
https://github.com/Cerealkillerway/versionUpdater/blob/977ef78d990ad6dd9bfd716f860bd05790c442d2/lib/version.js#L200-L207
40,006
Cerealkillerway/versionUpdater
lib/version.js
loadConfiguration
function loadConfiguration() { let configuration; if (isInit()) { configuration = jsonReader('./.versionFilesList.json'); // check configuration file's integrity if (!configuration.name || !configuration.currentVersion || !configuration.filesList || !configuration.versionPrefix) { sendError('E002'); } // check .versionFilesList.json for missing informations if (configuration.name.length === 0 || configuration.currentVersion.length === 0) { sendError('E001'); } } return configuration; }
javascript
function loadConfiguration() { let configuration; if (isInit()) { configuration = jsonReader('./.versionFilesList.json'); // check configuration file's integrity if (!configuration.name || !configuration.currentVersion || !configuration.filesList || !configuration.versionPrefix) { sendError('E002'); } // check .versionFilesList.json for missing informations if (configuration.name.length === 0 || configuration.currentVersion.length === 0) { sendError('E001'); } } return configuration; }
[ "function", "loadConfiguration", "(", ")", "{", "let", "configuration", ";", "if", "(", "isInit", "(", ")", ")", "{", "configuration", "=", "jsonReader", "(", "'./.versionFilesList.json'", ")", ";", "// check configuration file's integrity", "if", "(", "!", "configuration", ".", "name", "||", "!", "configuration", ".", "currentVersion", "||", "!", "configuration", ".", "filesList", "||", "!", "configuration", ".", "versionPrefix", ")", "{", "sendError", "(", "'E002'", ")", ";", "}", "// check .versionFilesList.json for missing informations", "if", "(", "configuration", ".", "name", ".", "length", "===", "0", "||", "configuration", ".", "currentVersion", ".", "length", "===", "0", ")", "{", "sendError", "(", "'E001'", ")", ";", "}", "}", "return", "configuration", ";", "}" ]
load configuration file; fallback to global if is not an initialized folder
[ "load", "configuration", "file", ";", "fallback", "to", "global", "if", "is", "not", "an", "initialized", "folder" ]
977ef78d990ad6dd9bfd716f860bd05790c442d2
https://github.com/Cerealkillerway/versionUpdater/blob/977ef78d990ad6dd9bfd716f860bd05790c442d2/lib/version.js#L211-L228
40,007
Cerealkillerway/versionUpdater
lib/version.js
discoverVersion
function discoverVersion() { // try to understand package name and current version // from package.json or bower.json let packageFile; let packageFileExtension; let packageType; let results = { name: '', currentVersion: '' }; let possiblePackageFiles = ['package.json', 'bower.json', 'package.js']; for (possiblePackageFile of possiblePackageFiles) { if (fs.existsSync(possiblePackageFile)) { packageFile = possiblePackageFile; break; } } packageFileExtension = packageFile.substr(packageFile.lastIndexOf('.') + 1); if (packageFile) { let packageData; if (packageFileExtension === 'json') { packageData = jsonReader(packageFile); } if (packageFileExtension === 'js') { let tmpData = fs.readFileSync(packageFile).toString().split('\n'); let nameFound = false; let versionFound = false; packageData = {}; for (line of tmpData) { if (line.indexOf('name:') >= 0) { nameFound = true; packageData.name = line.split(' ').pop().replace(/'/g, '').replace(/,/g, ''); } if (line.indexOf('version:') >= 0) { versionFound = true; packageData.version = line.split(' ').pop().replace(/'/g, '').replace(/,/g, ''); } if (nameFound && versionFound) { break; } } } debugLog('Reading packageFile for init:'); debugLog('Discovered pacakge name: ' + packageData.name + ' - discovered package version ' + packageData.version); if (packageData.name) { results.name = packageData.name; } else { print('Can\'t discover package name automatically', 'msgWarning', 'spaced22'); } if (packageData.version) { results.currentVersion = packageData.version; } else { print('Can\'t discover package\'s currentVersion automatically', 'msgWarning', 'spaced22'); } } else { print('Can\'t discover package name and/or currentVersion automatically', 'msgWarning', 'spaced22'); print('Please fill .versionFilesList.json with the missing informations', 'msgWarning', 'spaced22'); } return results; }
javascript
function discoverVersion() { // try to understand package name and current version // from package.json or bower.json let packageFile; let packageFileExtension; let packageType; let results = { name: '', currentVersion: '' }; let possiblePackageFiles = ['package.json', 'bower.json', 'package.js']; for (possiblePackageFile of possiblePackageFiles) { if (fs.existsSync(possiblePackageFile)) { packageFile = possiblePackageFile; break; } } packageFileExtension = packageFile.substr(packageFile.lastIndexOf('.') + 1); if (packageFile) { let packageData; if (packageFileExtension === 'json') { packageData = jsonReader(packageFile); } if (packageFileExtension === 'js') { let tmpData = fs.readFileSync(packageFile).toString().split('\n'); let nameFound = false; let versionFound = false; packageData = {}; for (line of tmpData) { if (line.indexOf('name:') >= 0) { nameFound = true; packageData.name = line.split(' ').pop().replace(/'/g, '').replace(/,/g, ''); } if (line.indexOf('version:') >= 0) { versionFound = true; packageData.version = line.split(' ').pop().replace(/'/g, '').replace(/,/g, ''); } if (nameFound && versionFound) { break; } } } debugLog('Reading packageFile for init:'); debugLog('Discovered pacakge name: ' + packageData.name + ' - discovered package version ' + packageData.version); if (packageData.name) { results.name = packageData.name; } else { print('Can\'t discover package name automatically', 'msgWarning', 'spaced22'); } if (packageData.version) { results.currentVersion = packageData.version; } else { print('Can\'t discover package\'s currentVersion automatically', 'msgWarning', 'spaced22'); } } else { print('Can\'t discover package name and/or currentVersion automatically', 'msgWarning', 'spaced22'); print('Please fill .versionFilesList.json with the missing informations', 'msgWarning', 'spaced22'); } return results; }
[ "function", "discoverVersion", "(", ")", "{", "// try to understand package name and current version", "// from package.json or bower.json", "let", "packageFile", ";", "let", "packageFileExtension", ";", "let", "packageType", ";", "let", "results", "=", "{", "name", ":", "''", ",", "currentVersion", ":", "''", "}", ";", "let", "possiblePackageFiles", "=", "[", "'package.json'", ",", "'bower.json'", ",", "'package.js'", "]", ";", "for", "(", "possiblePackageFile", "of", "possiblePackageFiles", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "possiblePackageFile", ")", ")", "{", "packageFile", "=", "possiblePackageFile", ";", "break", ";", "}", "}", "packageFileExtension", "=", "packageFile", ".", "substr", "(", "packageFile", ".", "lastIndexOf", "(", "'.'", ")", "+", "1", ")", ";", "if", "(", "packageFile", ")", "{", "let", "packageData", ";", "if", "(", "packageFileExtension", "===", "'json'", ")", "{", "packageData", "=", "jsonReader", "(", "packageFile", ")", ";", "}", "if", "(", "packageFileExtension", "===", "'js'", ")", "{", "let", "tmpData", "=", "fs", ".", "readFileSync", "(", "packageFile", ")", ".", "toString", "(", ")", ".", "split", "(", "'\\n'", ")", ";", "let", "nameFound", "=", "false", ";", "let", "versionFound", "=", "false", ";", "packageData", "=", "{", "}", ";", "for", "(", "line", "of", "tmpData", ")", "{", "if", "(", "line", ".", "indexOf", "(", "'name:'", ")", ">=", "0", ")", "{", "nameFound", "=", "true", ";", "packageData", ".", "name", "=", "line", ".", "split", "(", "' '", ")", ".", "pop", "(", ")", ".", "replace", "(", "/", "'", "/", "g", ",", "''", ")", ".", "replace", "(", "/", ",", "/", "g", ",", "''", ")", ";", "}", "if", "(", "line", ".", "indexOf", "(", "'version:'", ")", ">=", "0", ")", "{", "versionFound", "=", "true", ";", "packageData", ".", "version", "=", "line", ".", "split", "(", "' '", ")", ".", "pop", "(", ")", ".", "replace", "(", "/", "'", "/", "g", ",", "''", ")", ".", "replace", "(", "/", ",", "/", "g", ",", "''", ")", ";", "}", "if", "(", "nameFound", "&&", "versionFound", ")", "{", "break", ";", "}", "}", "}", "debugLog", "(", "'Reading packageFile for init:'", ")", ";", "debugLog", "(", "'Discovered pacakge name: '", "+", "packageData", ".", "name", "+", "' - discovered package version '", "+", "packageData", ".", "version", ")", ";", "if", "(", "packageData", ".", "name", ")", "{", "results", ".", "name", "=", "packageData", ".", "name", ";", "}", "else", "{", "print", "(", "'Can\\'t discover package name automatically'", ",", "'msgWarning'", ",", "'spaced22'", ")", ";", "}", "if", "(", "packageData", ".", "version", ")", "{", "results", ".", "currentVersion", "=", "packageData", ".", "version", ";", "}", "else", "{", "print", "(", "'Can\\'t discover package\\'s currentVersion automatically'", ",", "'msgWarning'", ",", "'spaced22'", ")", ";", "}", "}", "else", "{", "print", "(", "'Can\\'t discover package name and/or currentVersion automatically'", ",", "'msgWarning'", ",", "'spaced22'", ")", ";", "print", "(", "'Please fill .versionFilesList.json with the missing informations'", ",", "'msgWarning'", ",", "'spaced22'", ")", ";", "}", "return", "results", ";", "}" ]
discover project version
[ "discover", "project", "version" ]
977ef78d990ad6dd9bfd716f860bd05790c442d2
https://github.com/Cerealkillerway/versionUpdater/blob/977ef78d990ad6dd9bfd716f860bd05790c442d2/lib/version.js#L278-L351
40,008
wooorm/retext-language
index.js
patch
function patch(node, languages) { var data = node.data || {}; var primary = languages[0][0]; data.language = primary === 'und' ? null : primary; data.languages = languages; node.data = data; }
javascript
function patch(node, languages) { var data = node.data || {}; var primary = languages[0][0]; data.language = primary === 'und' ? null : primary; data.languages = languages; node.data = data; }
[ "function", "patch", "(", "node", ",", "languages", ")", "{", "var", "data", "=", "node", ".", "data", "||", "{", "}", ";", "var", "primary", "=", "languages", "[", "0", "]", "[", "0", "]", ";", "data", ".", "language", "=", "primary", "===", "'und'", "?", "null", ":", "primary", ";", "data", ".", "languages", "=", "languages", ";", "node", ".", "data", "=", "data", ";", "}" ]
Patch a `language` and `languages` properties on `node`. @param {NLCSTNode} node - Node. @param {Array.<Array.<string, number>>} languages - Languages.
[ "Patch", "a", "language", "and", "languages", "properties", "on", "node", "." ]
bc2a5b36f7a8e17161f86f0ed78d5e9794942340
https://github.com/wooorm/retext-language/blob/bc2a5b36f7a8e17161f86f0ed78d5e9794942340/index.js#L25-L33
40,009
wooorm/retext-language
index.js
concatenateFactory
function concatenateFactory() { var queue = []; /** * Gather a parent if not already gathered. * * @param {NLCSTChildNode} node - Child. * @param {number} index - Position of `node` in * `parent`. * @param {NLCSTParentNode} parent - Parent of `child`. */ function concatenate(node, index, parent) { if ( parent && (parent.type === 'ParagraphNode' || parent.type === 'RootNode') && queue.indexOf(parent) === -1 ) { queue.push(parent); } } /** * Patch one parent. * * @param {NLCSTParentNode} node - Parent * @return {Array.<Array.<string, number>>} - Language * map. */ function one(node) { var children = node.children; var length = children.length; var index = -1; var languages; var child; var dictionary = {}; var tuple; while (++index < length) { child = children[index]; languages = child.data && child.data.languages; if (languages) { tuple = languages[0]; if (tuple[0] in dictionary) { dictionary[tuple[0]] += tuple[1]; } else { dictionary[tuple[0]] = tuple[1]; } } } return sortDistanceObject(dictionary); } /** * Patch all parents in reverse order: this means * that first the last and deepest parent is invoked * up to the first and highest parent. */ function done() { var index = queue.length; while (index--) { patch(queue[index], one(queue[index])); } } concatenate.done = done; return concatenate; }
javascript
function concatenateFactory() { var queue = []; /** * Gather a parent if not already gathered. * * @param {NLCSTChildNode} node - Child. * @param {number} index - Position of `node` in * `parent`. * @param {NLCSTParentNode} parent - Parent of `child`. */ function concatenate(node, index, parent) { if ( parent && (parent.type === 'ParagraphNode' || parent.type === 'RootNode') && queue.indexOf(parent) === -1 ) { queue.push(parent); } } /** * Patch one parent. * * @param {NLCSTParentNode} node - Parent * @return {Array.<Array.<string, number>>} - Language * map. */ function one(node) { var children = node.children; var length = children.length; var index = -1; var languages; var child; var dictionary = {}; var tuple; while (++index < length) { child = children[index]; languages = child.data && child.data.languages; if (languages) { tuple = languages[0]; if (tuple[0] in dictionary) { dictionary[tuple[0]] += tuple[1]; } else { dictionary[tuple[0]] = tuple[1]; } } } return sortDistanceObject(dictionary); } /** * Patch all parents in reverse order: this means * that first the last and deepest parent is invoked * up to the first and highest parent. */ function done() { var index = queue.length; while (index--) { patch(queue[index], one(queue[index])); } } concatenate.done = done; return concatenate; }
[ "function", "concatenateFactory", "(", ")", "{", "var", "queue", "=", "[", "]", ";", "/**\n * Gather a parent if not already gathered.\n *\n * @param {NLCSTChildNode} node - Child.\n * @param {number} index - Position of `node` in\n * `parent`.\n * @param {NLCSTParentNode} parent - Parent of `child`.\n */", "function", "concatenate", "(", "node", ",", "index", ",", "parent", ")", "{", "if", "(", "parent", "&&", "(", "parent", ".", "type", "===", "'ParagraphNode'", "||", "parent", ".", "type", "===", "'RootNode'", ")", "&&", "queue", ".", "indexOf", "(", "parent", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "parent", ")", ";", "}", "}", "/**\n * Patch one parent.\n *\n * @param {NLCSTParentNode} node - Parent\n * @return {Array.<Array.<string, number>>} - Language\n * map.\n */", "function", "one", "(", "node", ")", "{", "var", "children", "=", "node", ".", "children", ";", "var", "length", "=", "children", ".", "length", ";", "var", "index", "=", "-", "1", ";", "var", "languages", ";", "var", "child", ";", "var", "dictionary", "=", "{", "}", ";", "var", "tuple", ";", "while", "(", "++", "index", "<", "length", ")", "{", "child", "=", "children", "[", "index", "]", ";", "languages", "=", "child", ".", "data", "&&", "child", ".", "data", ".", "languages", ";", "if", "(", "languages", ")", "{", "tuple", "=", "languages", "[", "0", "]", ";", "if", "(", "tuple", "[", "0", "]", "in", "dictionary", ")", "{", "dictionary", "[", "tuple", "[", "0", "]", "]", "+=", "tuple", "[", "1", "]", ";", "}", "else", "{", "dictionary", "[", "tuple", "[", "0", "]", "]", "=", "tuple", "[", "1", "]", ";", "}", "}", "}", "return", "sortDistanceObject", "(", "dictionary", ")", ";", "}", "/**\n * Patch all parents in reverse order: this means\n * that first the last and deepest parent is invoked\n * up to the first and highest parent.\n */", "function", "done", "(", ")", "{", "var", "index", "=", "queue", ".", "length", ";", "while", "(", "index", "--", ")", "{", "patch", "(", "queue", "[", "index", "]", ",", "one", "(", "queue", "[", "index", "]", ")", ")", ";", "}", "}", "concatenate", ".", "done", "=", "done", ";", "return", "concatenate", ";", "}" ]
Factory to gather parents and patch them based on their childrens directionality. @return {function(node, index, parent)} - Can be passed to `visit`.
[ "Factory", "to", "gather", "parents", "and", "patch", "them", "based", "on", "their", "childrens", "directionality", "." ]
bc2a5b36f7a8e17161f86f0ed78d5e9794942340
https://github.com/wooorm/retext-language/blob/bc2a5b36f7a8e17161f86f0ed78d5e9794942340/index.js#L90-L161
40,010
wooorm/retext-language
index.js
concatenate
function concatenate(node, index, parent) { if ( parent && (parent.type === 'ParagraphNode' || parent.type === 'RootNode') && queue.indexOf(parent) === -1 ) { queue.push(parent); } }
javascript
function concatenate(node, index, parent) { if ( parent && (parent.type === 'ParagraphNode' || parent.type === 'RootNode') && queue.indexOf(parent) === -1 ) { queue.push(parent); } }
[ "function", "concatenate", "(", "node", ",", "index", ",", "parent", ")", "{", "if", "(", "parent", "&&", "(", "parent", ".", "type", "===", "'ParagraphNode'", "||", "parent", ".", "type", "===", "'RootNode'", ")", "&&", "queue", ".", "indexOf", "(", "parent", ")", "===", "-", "1", ")", "{", "queue", ".", "push", "(", "parent", ")", ";", "}", "}" ]
Gather a parent if not already gathered. @param {NLCSTChildNode} node - Child. @param {number} index - Position of `node` in `parent`. @param {NLCSTParentNode} parent - Parent of `child`.
[ "Gather", "a", "parent", "if", "not", "already", "gathered", "." ]
bc2a5b36f7a8e17161f86f0ed78d5e9794942340
https://github.com/wooorm/retext-language/blob/bc2a5b36f7a8e17161f86f0ed78d5e9794942340/index.js#L101-L109
40,011
wooorm/retext-language
index.js
one
function one(node) { var children = node.children; var length = children.length; var index = -1; var languages; var child; var dictionary = {}; var tuple; while (++index < length) { child = children[index]; languages = child.data && child.data.languages; if (languages) { tuple = languages[0]; if (tuple[0] in dictionary) { dictionary[tuple[0]] += tuple[1]; } else { dictionary[tuple[0]] = tuple[1]; } } } return sortDistanceObject(dictionary); }
javascript
function one(node) { var children = node.children; var length = children.length; var index = -1; var languages; var child; var dictionary = {}; var tuple; while (++index < length) { child = children[index]; languages = child.data && child.data.languages; if (languages) { tuple = languages[0]; if (tuple[0] in dictionary) { dictionary[tuple[0]] += tuple[1]; } else { dictionary[tuple[0]] = tuple[1]; } } } return sortDistanceObject(dictionary); }
[ "function", "one", "(", "node", ")", "{", "var", "children", "=", "node", ".", "children", ";", "var", "length", "=", "children", ".", "length", ";", "var", "index", "=", "-", "1", ";", "var", "languages", ";", "var", "child", ";", "var", "dictionary", "=", "{", "}", ";", "var", "tuple", ";", "while", "(", "++", "index", "<", "length", ")", "{", "child", "=", "children", "[", "index", "]", ";", "languages", "=", "child", ".", "data", "&&", "child", ".", "data", ".", "languages", ";", "if", "(", "languages", ")", "{", "tuple", "=", "languages", "[", "0", "]", ";", "if", "(", "tuple", "[", "0", "]", "in", "dictionary", ")", "{", "dictionary", "[", "tuple", "[", "0", "]", "]", "+=", "tuple", "[", "1", "]", ";", "}", "else", "{", "dictionary", "[", "tuple", "[", "0", "]", "]", "=", "tuple", "[", "1", "]", ";", "}", "}", "}", "return", "sortDistanceObject", "(", "dictionary", ")", ";", "}" ]
Patch one parent. @param {NLCSTParentNode} node - Parent @return {Array.<Array.<string, number>>} - Language map.
[ "Patch", "one", "parent", "." ]
bc2a5b36f7a8e17161f86f0ed78d5e9794942340
https://github.com/wooorm/retext-language/blob/bc2a5b36f7a8e17161f86f0ed78d5e9794942340/index.js#L118-L143
40,012
stezu/node-stream
lib/creators/fromCallback.js
fromCallback
function fromCallback(source) { var callCount = 0; // Throw an error if the source is not a function if (typeof source !== 'function') { throw new TypeError('Expected `source` to be a function.'); } return new Readable({ objectMode: true, read: function () { var self = this; // Increment the number of calls so we know when to push null callCount += 1; // Call the method and push results if this is the first call if (callCount === 1) { source(_.rest(function (err, parameters) { if (err) { process.nextTick(function () { self.emit('error', err); }); return; } // Push all parameters of the callback to the stream as an array self.push(parameters); })); return; } // End the stream self.push(null); } }); }
javascript
function fromCallback(source) { var callCount = 0; // Throw an error if the source is not a function if (typeof source !== 'function') { throw new TypeError('Expected `source` to be a function.'); } return new Readable({ objectMode: true, read: function () { var self = this; // Increment the number of calls so we know when to push null callCount += 1; // Call the method and push results if this is the first call if (callCount === 1) { source(_.rest(function (err, parameters) { if (err) { process.nextTick(function () { self.emit('error', err); }); return; } // Push all parameters of the callback to the stream as an array self.push(parameters); })); return; } // End the stream self.push(null); } }); }
[ "function", "fromCallback", "(", "source", ")", "{", "var", "callCount", "=", "0", ";", "// Throw an error if the source is not a function", "if", "(", "typeof", "source", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'Expected `source` to be a function.'", ")", ";", "}", "return", "new", "Readable", "(", "{", "objectMode", ":", "true", ",", "read", ":", "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Increment the number of calls so we know when to push null", "callCount", "+=", "1", ";", "// Call the method and push results if this is the first call", "if", "(", "callCount", "===", "1", ")", "{", "source", "(", "_", ".", "rest", "(", "function", "(", "err", ",", "parameters", ")", "{", "if", "(", "err", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "return", ";", "}", "// Push all parameters of the callback to the stream as an array", "self", ".", "push", "(", "parameters", ")", ";", "}", ")", ")", ";", "return", ";", "}", "// End the stream", "self", ".", "push", "(", "null", ")", ";", "}", "}", ")", ";", "}" ]
Creates a new readable stream from a function which accepts a node-style callback. This is primarily useful for piping into additional node-stream methods like map, reduce and filter. @static @since 1.6.0 @category Creators @param {Function} source - A function to call which accepts a node-style callback as the last argument. When that callback is called, this stream will emit all arguments as a single array. @returns {Stream.Readable} - Readable stream. @throws {TypeError} - If `source` is not a function. @example // Create a stream from a function callback which is then piped to another node-stream method nodeStream.fromCallback(fs.readdir.bind(this, path.resolve('.'))) .pipe(nodeStream.map(fs.readFile)); // => ['contents of file1.txt', 'contents of file2.js', 'contents of file3.pdf']
[ "Creates", "a", "new", "readable", "stream", "from", "a", "function", "which", "accepts", "a", "node", "-", "style", "callback", ".", "This", "is", "primarily", "useful", "for", "piping", "into", "additional", "node", "-", "stream", "methods", "like", "map", "reduce", "and", "filter", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/creators/fromCallback.js#L28-L67
40,013
kevoree/kevoree-js
libraries/group/ws/lib/ClientHandler.js
function() { Object.keys(this.name2Ws).forEach(function(name) { delete this.name2Ws[name]; }.bind(this)); Object.keys(this.ws2Name).forEach(function(wsId) { delete this.ws2Name[wsId]; }.bind(this)); }
javascript
function() { Object.keys(this.name2Ws).forEach(function(name) { delete this.name2Ws[name]; }.bind(this)); Object.keys(this.ws2Name).forEach(function(wsId) { delete this.ws2Name[wsId]; }.bind(this)); }
[ "function", "(", ")", "{", "Object", ".", "keys", "(", "this", ".", "name2Ws", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "delete", "this", ".", "name2Ws", "[", "name", "]", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "Object", ".", "keys", "(", "this", ".", "ws2Name", ")", ".", "forEach", "(", "function", "(", "wsId", ")", "{", "delete", "this", ".", "ws2Name", "[", "wsId", "]", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Clear server caches
[ "Clear", "server", "caches" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/libraries/group/ws/lib/ClientHandler.js#L197-L205
40,014
ivitivan/yandex-dictionary
lib/yandex-dictionary.js
function(text, lang, callback) { if (arguments.length == 4) { var options = callback; callback = arguments[arguments.length - 1]; } var uri = url.format({ pathname: url.resolve(baseAddress, 'lookup'), query: { key: dis.APIkey, lang: lang, text: text, ui: options ? options.ui : null, flags: options ? options.flags : null, } }); makeRequest(uri, callback); }
javascript
function(text, lang, callback) { if (arguments.length == 4) { var options = callback; callback = arguments[arguments.length - 1]; } var uri = url.format({ pathname: url.resolve(baseAddress, 'lookup'), query: { key: dis.APIkey, lang: lang, text: text, ui: options ? options.ui : null, flags: options ? options.flags : null, } }); makeRequest(uri, callback); }
[ "function", "(", "text", ",", "lang", ",", "callback", ")", "{", "if", "(", "arguments", ".", "length", "==", "4", ")", "{", "var", "options", "=", "callback", ";", "callback", "=", "arguments", "[", "arguments", ".", "length", "-", "1", "]", ";", "}", "var", "uri", "=", "url", ".", "format", "(", "{", "pathname", ":", "url", ".", "resolve", "(", "baseAddress", ",", "'lookup'", ")", ",", "query", ":", "{", "key", ":", "dis", ".", "APIkey", ",", "lang", ":", "lang", ",", "text", ":", "text", ",", "ui", ":", "options", "?", "options", ".", "ui", ":", "null", ",", "flags", ":", "options", "?", "options", ".", "flags", ":", "null", ",", "}", "}", ")", ";", "makeRequest", "(", "uri", ",", "callback", ")", ";", "}" ]
The first two parameters are text and lang, next pararameter, options, is optional; the last parameter is callback function
[ "The", "first", "two", "parameters", "are", "text", "and", "lang", "next", "pararameter", "options", "is", "optional", ";", "the", "last", "parameter", "is", "callback", "function" ]
9865dbc376ec566f67bb8f97c756ba31b2e60fd1
https://github.com/ivitivan/yandex-dictionary/blob/9865dbc376ec566f67bb8f97c756ba31b2e60fd1/lib/yandex-dictionary.js#L16-L35
40,015
kevoree/kevoree-js
tools/kevoree-kevscript/lib/util/model-helper.js
getPlatforms
function getPlatforms(tdef) { const platforms = []; if (tdef) { tdef.deployUnits.array.forEach((du) => { const platform = du.findFiltersByID('platform'); if (platform && platforms.indexOf(platform.value) === -1) { platforms.push(platform.value); } }); } return platforms; }
javascript
function getPlatforms(tdef) { const platforms = []; if (tdef) { tdef.deployUnits.array.forEach((du) => { const platform = du.findFiltersByID('platform'); if (platform && platforms.indexOf(platform.value) === -1) { platforms.push(platform.value); } }); } return platforms; }
[ "function", "getPlatforms", "(", "tdef", ")", "{", "const", "platforms", "=", "[", "]", ";", "if", "(", "tdef", ")", "{", "tdef", ".", "deployUnits", ".", "array", ".", "forEach", "(", "(", "du", ")", "=>", "{", "const", "platform", "=", "du", ".", "findFiltersByID", "(", "'platform'", ")", ";", "if", "(", "platform", "&&", "platforms", ".", "indexOf", "(", "platform", ".", "value", ")", "===", "-", "1", ")", "{", "platforms", ".", "push", "(", "platform", ".", "value", ")", ";", "}", "}", ")", ";", "}", "return", "platforms", ";", "}" ]
Returns the platforms related to that TypeDefinition @param tdef @returns {Array}
[ "Returns", "the", "platforms", "related", "to", "that", "TypeDefinition" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-kevscript/lib/util/model-helper.js#L38-L51
40,016
kevoree/kevoree-js
tools/kevoree-kevscript/lib/util/model-helper.js
isCompatible
function isCompatible(tdef, node) { if (tdef && node) { if (tdef.select('metaData[name=virtual]').array.length > 0) { // tdef is virtual, so it is compatible return true; } else { const nodePlatforms = getPlatforms(node.typeDefinition); for (let i = 0; i < nodePlatforms.length; i++) { if (tdef.select('deployUnits[name=*]/filters[name=platform,value=' + nodePlatforms[i] + ']').array.length > 0) { return true; } } } } return false; }
javascript
function isCompatible(tdef, node) { if (tdef && node) { if (tdef.select('metaData[name=virtual]').array.length > 0) { // tdef is virtual, so it is compatible return true; } else { const nodePlatforms = getPlatforms(node.typeDefinition); for (let i = 0; i < nodePlatforms.length; i++) { if (tdef.select('deployUnits[name=*]/filters[name=platform,value=' + nodePlatforms[i] + ']').array.length > 0) { return true; } } } } return false; }
[ "function", "isCompatible", "(", "tdef", ",", "node", ")", "{", "if", "(", "tdef", "&&", "node", ")", "{", "if", "(", "tdef", ".", "select", "(", "'metaData[name=virtual]'", ")", ".", "array", ".", "length", ">", "0", ")", "{", "// tdef is virtual, so it is compatible", "return", "true", ";", "}", "else", "{", "const", "nodePlatforms", "=", "getPlatforms", "(", "node", ".", "typeDefinition", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "nodePlatforms", ".", "length", ";", "i", "++", ")", "{", "if", "(", "tdef", ".", "select", "(", "'deployUnits[name=*]/filters[name=platform,value='", "+", "nodePlatforms", "[", "i", "]", "+", "']'", ")", ".", "array", ".", "length", ">", "0", ")", "{", "return", "true", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Returns whether or not the given "tdef" is compatible with the given "node" if the tdef has a platform compatible with the node type @param tdef @param node @returns {Boolean}
[ "Returns", "whether", "or", "not", "the", "given", "tdef", "is", "compatible", "with", "the", "given", "node", "if", "the", "tdef", "has", "a", "platform", "compatible", "with", "the", "node", "type" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-kevscript/lib/util/model-helper.js#L60-L77
40,017
kevoree/kevoree-js
tools/kevoree-kevscript/lib/util/model-helper.js
getFQN
function getFQN(tdef) { const hasPreRelease = tdef.deployUnits.array.some((du) => { return semver.prerelease(du.version) !== null; }); const duTag = hasPreRelease ? '/LATEST' : ''; let fqn = tdef.name + '/' + tdef.version + duTag; function walk(pkg) { if (pkg.eContainer()) { fqn = pkg.name + '.' + fqn; walk(pkg.eContainer()); } } walk(tdef.eContainer()); return fqn; }
javascript
function getFQN(tdef) { const hasPreRelease = tdef.deployUnits.array.some((du) => { return semver.prerelease(du.version) !== null; }); const duTag = hasPreRelease ? '/LATEST' : ''; let fqn = tdef.name + '/' + tdef.version + duTag; function walk(pkg) { if (pkg.eContainer()) { fqn = pkg.name + '.' + fqn; walk(pkg.eContainer()); } } walk(tdef.eContainer()); return fqn; }
[ "function", "getFQN", "(", "tdef", ")", "{", "const", "hasPreRelease", "=", "tdef", ".", "deployUnits", ".", "array", ".", "some", "(", "(", "du", ")", "=>", "{", "return", "semver", ".", "prerelease", "(", "du", ".", "version", ")", "!==", "null", ";", "}", ")", ";", "const", "duTag", "=", "hasPreRelease", "?", "'/LATEST'", ":", "''", ";", "let", "fqn", "=", "tdef", ".", "name", "+", "'/'", "+", "tdef", ".", "version", "+", "duTag", ";", "function", "walk", "(", "pkg", ")", "{", "if", "(", "pkg", ".", "eContainer", "(", ")", ")", "{", "fqn", "=", "pkg", ".", "name", "+", "'.'", "+", "fqn", ";", "walk", "(", "pkg", ".", "eContainer", "(", ")", ")", ";", "}", "}", "walk", "(", "tdef", ".", "eContainer", "(", ")", ")", ";", "return", "fqn", ";", "}" ]
Returns the FQN of the given TypeDefinition @param tdef @returns {String}
[ "Returns", "the", "FQN", "of", "the", "given", "TypeDefinition" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-kevscript/lib/util/model-helper.js#L84-L103
40,018
EikosPartners/scalejs
src/scalejs.base.log.js
formatException
function formatException (ex) { var stack = (ex.stack) ? String(ex.stack) : '', message = ex.message || ''; return 'Error: ' + message + '\nStack: ' + stack; }
javascript
function formatException (ex) { var stack = (ex.stack) ? String(ex.stack) : '', message = ex.message || ''; return 'Error: ' + message + '\nStack: ' + stack; }
[ "function", "formatException", "(", "ex", ")", "{", "var", "stack", "=", "(", "ex", ".", "stack", ")", "?", "String", "(", "ex", ".", "stack", ")", ":", "''", ",", "message", "=", "ex", ".", "message", "||", "''", ";", "return", "'Error: '", "+", "message", "+", "'\\nStack: '", "+", "stack", ";", "}" ]
Formats an exception for better output @param {Object} ex exception object @memberOf log @return {String} formatted exception
[ "Formats", "an", "exception", "for", "better", "output" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/src/scalejs.base.log.js#L79-L83
40,019
novacrazy/scriptor
bin/scriptor.js
onError
function onError( error ) { logger.error( error.stack || error ); process.exit( EXIT_FAILURE ); }
javascript
function onError( error ) { logger.error( error.stack || error ); process.exit( EXIT_FAILURE ); }
[ "function", "onError", "(", "error", ")", "{", "logger", ".", "error", "(", "error", ".", "stack", "||", "error", ")", ";", "process", ".", "exit", "(", "EXIT_FAILURE", ")", ";", "}" ]
Unhandled errors are printed and the process is killed
[ "Unhandled", "errors", "are", "printed", "and", "the", "process", "is", "killed" ]
eef8051c85e2b26cf41bafec0873874d3710d111
https://github.com/novacrazy/scriptor/blob/eef8051c85e2b26cf41bafec0873874d3710d111/bin/scriptor.js#L73-L76
40,020
datagovsg/datagovsg-plottable-charts
lib/datagovsg-charts.js
baseIsMatch
function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; }
javascript
function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; }
[ "function", "baseIsMatch", "(", "object", ",", "source", ",", "matchData", ",", "customizer", ")", "{", "var", "index", "=", "matchData", ".", "length", ",", "length", "=", "index", ",", "noCustomizer", "=", "!", "customizer", ";", "if", "(", "object", "==", "null", ")", "{", "return", "!", "length", ";", "}", "object", "=", "Object", "(", "object", ")", ";", "while", "(", "index", "--", ")", "{", "var", "data", "=", "matchData", "[", "index", "]", ";", "if", "(", "(", "noCustomizer", "&&", "data", "[", "2", "]", ")", "?", "data", "[", "1", "]", "!==", "object", "[", "data", "[", "0", "]", "]", ":", "!", "(", "data", "[", "0", "]", "in", "object", ")", ")", "{", "return", "false", ";", "}", "}", "while", "(", "++", "index", "<", "length", ")", "{", "data", "=", "matchData", "[", "index", "]", ";", "var", "key", "=", "data", "[", "0", "]", ",", "objValue", "=", "object", "[", "key", "]", ",", "srcValue", "=", "data", "[", "1", "]", ";", "if", "(", "noCustomizer", "&&", "data", "[", "2", "]", ")", "{", "if", "(", "objValue", "===", "undefined", "&&", "!", "(", "key", "in", "object", ")", ")", "{", "return", "false", ";", "}", "}", "else", "{", "var", "stack", "=", "new", "_Stack", ";", "if", "(", "customizer", ")", "{", "var", "result", "=", "customizer", "(", "objValue", ",", "srcValue", ",", "key", ",", "object", ",", "source", ",", "stack", ")", ";", "}", "if", "(", "!", "(", "result", "===", "undefined", "?", "_baseIsEqual", "(", "srcValue", ",", "objValue", ",", "COMPARE_PARTIAL_FLAG", "|", "COMPARE_UNORDERED_FLAG", ",", "customizer", ",", "stack", ")", ":", "result", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
The base implementation of `_.isMatch` without support for iteratee shorthands. @private @param {Object} object The object to inspect. @param {Object} source The object of property values to match. @param {Array} matchData The property names, values, and compare flags to match. @param {Function} [customizer] The function to customize comparisons. @returns {boolean} Returns `true` if `object` is a match, else `false`.
[ "The", "base", "implementation", "of", "_", ".", "isMatch", "without", "support", "for", "iteratee", "shorthands", "." ]
f08c65c50f4be32dacb984ba5fd916e23d11e9d2
https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/datagovsg-charts.js#L3101-L3143
40,021
datagovsg/datagovsg-plottable-charts
lib/datagovsg-charts.js
compareAscending
function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; }
javascript
function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; }
[ "function", "compareAscending", "(", "value", ",", "other", ")", "{", "if", "(", "value", "!==", "other", ")", "{", "var", "valIsDefined", "=", "value", "!==", "undefined", ",", "valIsNull", "=", "value", "===", "null", ",", "valIsReflexive", "=", "value", "===", "value", ",", "valIsSymbol", "=", "isSymbol_1", "(", "value", ")", ";", "var", "othIsDefined", "=", "other", "!==", "undefined", ",", "othIsNull", "=", "other", "===", "null", ",", "othIsReflexive", "=", "other", "===", "other", ",", "othIsSymbol", "=", "isSymbol_1", "(", "other", ")", ";", "if", "(", "(", "!", "othIsNull", "&&", "!", "othIsSymbol", "&&", "!", "valIsSymbol", "&&", "value", ">", "other", ")", "||", "(", "valIsSymbol", "&&", "othIsDefined", "&&", "othIsReflexive", "&&", "!", "othIsNull", "&&", "!", "othIsSymbol", ")", "||", "(", "valIsNull", "&&", "othIsDefined", "&&", "othIsReflexive", ")", "||", "(", "!", "valIsDefined", "&&", "othIsReflexive", ")", "||", "!", "valIsReflexive", ")", "{", "return", "1", ";", "}", "if", "(", "(", "!", "valIsNull", "&&", "!", "valIsSymbol", "&&", "!", "othIsSymbol", "&&", "value", "<", "other", ")", "||", "(", "othIsSymbol", "&&", "valIsDefined", "&&", "valIsReflexive", "&&", "!", "valIsNull", "&&", "!", "valIsSymbol", ")", "||", "(", "othIsNull", "&&", "valIsDefined", "&&", "valIsReflexive", ")", "||", "(", "!", "othIsDefined", "&&", "valIsReflexive", ")", "||", "!", "othIsReflexive", ")", "{", "return", "-", "1", ";", "}", "}", "return", "0", ";", "}" ]
Compares values to sort them in ascending order. @private @param {*} value The value to compare. @param {*} other The other value to compare. @returns {number} Returns the sort order indicator for `value`.
[ "Compares", "values", "to", "sort", "them", "in", "ascending", "order", "." ]
f08c65c50f4be32dacb984ba5fd916e23d11e9d2
https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/datagovsg-charts.js#L3884-L3912
40,022
datagovsg/datagovsg-plottable-charts
lib/datagovsg-charts.js
customizeTimeAxis
function customizeTimeAxis(component, type) { var axis = component.xAxis; if (axis instanceof Plottable.Axes.Time) { var customTimeAxisConfigs = getCustomTimeAxisConfigs(type); axis.axisConfigurations(customTimeAxisConfigs); if (type === 'year' || type === 'financial_year') { axis.tierLabelPositions(customTimeAxisConfigs.map(function (v) { return 'center'; })); } } }
javascript
function customizeTimeAxis(component, type) { var axis = component.xAxis; if (axis instanceof Plottable.Axes.Time) { var customTimeAxisConfigs = getCustomTimeAxisConfigs(type); axis.axisConfigurations(customTimeAxisConfigs); if (type === 'year' || type === 'financial_year') { axis.tierLabelPositions(customTimeAxisConfigs.map(function (v) { return 'center'; })); } } }
[ "function", "customizeTimeAxis", "(", "component", ",", "type", ")", "{", "var", "axis", "=", "component", ".", "xAxis", ";", "if", "(", "axis", "instanceof", "Plottable", ".", "Axes", ".", "Time", ")", "{", "var", "customTimeAxisConfigs", "=", "getCustomTimeAxisConfigs", "(", "type", ")", ";", "axis", ".", "axisConfigurations", "(", "customTimeAxisConfigs", ")", ";", "if", "(", "type", "===", "'year'", "||", "type", "===", "'financial_year'", ")", "{", "axis", ".", "tierLabelPositions", "(", "customTimeAxisConfigs", ".", "map", "(", "function", "(", "v", ")", "{", "return", "'center'", ";", "}", ")", ")", ";", "}", "}", "}" ]
type can be one of the following 'year' 'financial_year' 'half_year' 'financial_half_year' 'quarter' 'financial_quarter' 'month' 'week' 'date' 'datetime' 'time'
[ "type", "can", "be", "one", "of", "the", "following", "year", "financial_year", "half_year", "financial_half_year", "quarter", "financial_quarter", "month", "week", "date", "datetime", "time" ]
f08c65c50f4be32dacb984ba5fd916e23d11e9d2
https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/datagovsg-charts.js#L5715-L5726
40,023
datagovsg/datagovsg-plottable-charts
lib/datagovsg-charts.js
removeInnerPadding
function removeInnerPadding(component) { var _makeInnerScale = component.plot._makeInnerScale; component.plot._makeInnerScale = function () { return _makeInnerScale.call(this).innerPadding(0).outerPadding(0); }; }
javascript
function removeInnerPadding(component) { var _makeInnerScale = component.plot._makeInnerScale; component.plot._makeInnerScale = function () { return _makeInnerScale.call(this).innerPadding(0).outerPadding(0); }; }
[ "function", "removeInnerPadding", "(", "component", ")", "{", "var", "_makeInnerScale", "=", "component", ".", "plot", ".", "_makeInnerScale", ";", "component", ".", "plot", ".", "_makeInnerScale", "=", "function", "(", ")", "{", "return", "_makeInnerScale", ".", "call", "(", "this", ")", ".", "innerPadding", "(", "0", ")", ".", "outerPadding", "(", "0", ")", ";", "}", ";", "}" ]
FIXME Very very hackish stuff Might break when upgrading to Plottable 3.0
[ "FIXME", "Very", "very", "hackish", "stuff", "Might", "break", "when", "upgrading", "to", "Plottable", "3", ".", "0" ]
f08c65c50f4be32dacb984ba5fd916e23d11e9d2
https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/datagovsg-charts.js#L5734-L5739
40,024
kflorence/gulp-pretty-url
index.js
prettyUrl
function prettyUrl(file) { file.extname = ".html"; if (file.basename !== "index") { file.dirname = path.join(file.dirname, file.basename); file.basename = "index"; } return file; }
javascript
function prettyUrl(file) { file.extname = ".html"; if (file.basename !== "index") { file.dirname = path.join(file.dirname, file.basename); file.basename = "index"; } return file; }
[ "function", "prettyUrl", "(", "file", ")", "{", "file", ".", "extname", "=", "\".html\"", ";", "if", "(", "file", ".", "basename", "!==", "\"index\"", ")", "{", "file", ".", "dirname", "=", "path", ".", "join", "(", "file", ".", "dirname", ",", "file", ".", "basename", ")", ";", "file", ".", "basename", "=", "\"index\"", ";", "}", "return", "file", ";", "}" ]
Generate pretty URLs for files piped through this method. @see `gulp-rename` for more information @param {Object} file Object containing file path information @return Modified file path object
[ "Generate", "pretty", "URLs", "for", "files", "piped", "through", "this", "method", "." ]
ec7440ae2161d44c4f553d4ebe6644082344640c
https://github.com/kflorence/gulp-pretty-url/blob/ec7440ae2161d44c4f553d4ebe6644082344640c/index.js#L12-L21
40,025
dbowring/elm-forest
lib/forest.js
function (name) { if (name === undefined || name === 'stable') { return 0; } else if (name === 'alpha') { return Number.MAX_SAFE_INTEGER - 1; } else if (name == 'beta') { return Number.MAX_SAFE_INTEGER - 2; } else { // Possibly something like "RC", but for not officially supported return Number.MAX_SAFE_INTEGER - 3; } }
javascript
function (name) { if (name === undefined || name === 'stable') { return 0; } else if (name === 'alpha') { return Number.MAX_SAFE_INTEGER - 1; } else if (name == 'beta') { return Number.MAX_SAFE_INTEGER - 2; } else { // Possibly something like "RC", but for not officially supported return Number.MAX_SAFE_INTEGER - 3; } }
[ "function", "(", "name", ")", "{", "if", "(", "name", "===", "undefined", "||", "name", "===", "'stable'", ")", "{", "return", "0", ";", "}", "else", "if", "(", "name", "===", "'alpha'", ")", "{", "return", "Number", ".", "MAX_SAFE_INTEGER", "-", "1", ";", "}", "else", "if", "(", "name", "==", "'beta'", ")", "{", "return", "Number", ".", "MAX_SAFE_INTEGER", "-", "2", ";", "}", "else", "{", "// Possibly something like \"RC\", but for not officially supported", "return", "Number", ".", "MAX_SAFE_INTEGER", "-", "3", ";", "}", "}" ]
Convert a release stage into a number
[ "Convert", "a", "release", "stage", "into", "a", "number" ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L187-L201
40,026
dbowring/elm-forest
lib/forest.js
function (constraint) { let first = /((?:\d+(?:\.\d+){0,2}))\s+(\<=|\>=|\<|\>)\s+v/; let second = /v\s+(\<=|\>=|\<|\>)\s+((?:\d+(?:\.\d+){0,2}))/; let firstMatch = constraint.match(first); let secondMatch = constraint.match(second); ; let alwaysFail = (v) => false; let firstOp = { '<': (a) => (v) => a < v, '<=': (a) => (v) => a <= v, '>': (a) => (v) => a > v, '>=': (a) => (v) => a >= v, }; let secondOp = { '<': (a) => (v) => v < a, '<=': (a) => (v) => v <= a, '>': (a) => (v) => v > a, '>=': (a) => (v) => v >= a, }; if (firstMatch && secondMatch) { let firstVersion = parseVersionString(firstMatch[1]); let secondVersion = parseVersionString(secondMatch[2]); return [ firstVersion ? firstOp[firstMatch[2]](firstVersion) : alwaysFail, secondVersion ? secondOp[secondMatch[1]](secondVersion) : alwaysFail ]; } return null; }
javascript
function (constraint) { let first = /((?:\d+(?:\.\d+){0,2}))\s+(\<=|\>=|\<|\>)\s+v/; let second = /v\s+(\<=|\>=|\<|\>)\s+((?:\d+(?:\.\d+){0,2}))/; let firstMatch = constraint.match(first); let secondMatch = constraint.match(second); ; let alwaysFail = (v) => false; let firstOp = { '<': (a) => (v) => a < v, '<=': (a) => (v) => a <= v, '>': (a) => (v) => a > v, '>=': (a) => (v) => a >= v, }; let secondOp = { '<': (a) => (v) => v < a, '<=': (a) => (v) => v <= a, '>': (a) => (v) => v > a, '>=': (a) => (v) => v >= a, }; if (firstMatch && secondMatch) { let firstVersion = parseVersionString(firstMatch[1]); let secondVersion = parseVersionString(secondMatch[2]); return [ firstVersion ? firstOp[firstMatch[2]](firstVersion) : alwaysFail, secondVersion ? secondOp[secondMatch[1]](secondVersion) : alwaysFail ]; } return null; }
[ "function", "(", "constraint", ")", "{", "let", "first", "=", "/", "((?:\\d+(?:\\.\\d+){0,2}))\\s+(\\<=|\\>=|\\<|\\>)\\s+v", "/", ";", "let", "second", "=", "/", "v\\s+(\\<=|\\>=|\\<|\\>)\\s+((?:\\d+(?:\\.\\d+){0,2}))", "/", ";", "let", "firstMatch", "=", "constraint", ".", "match", "(", "first", ")", ";", "let", "secondMatch", "=", "constraint", ".", "match", "(", "second", ")", ";", ";", "let", "alwaysFail", "=", "(", "v", ")", "=>", "false", ";", "let", "firstOp", "=", "{", "'<'", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "a", "<", "v", ",", "'<='", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "a", "<=", "v", ",", "'>'", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "a", ">", "v", ",", "'>='", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "a", ">=", "v", ",", "}", ";", "let", "secondOp", "=", "{", "'<'", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "v", "<", "a", ",", "'<='", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "v", "<=", "a", ",", "'>'", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "v", ">", "a", ",", "'>='", ":", "(", "a", ")", "=>", "(", "v", ")", "=>", "v", ">=", "a", ",", "}", ";", "if", "(", "firstMatch", "&&", "secondMatch", ")", "{", "let", "firstVersion", "=", "parseVersionString", "(", "firstMatch", "[", "1", "]", ")", ";", "let", "secondVersion", "=", "parseVersionString", "(", "secondMatch", "[", "2", "]", ")", ";", "return", "[", "firstVersion", "?", "firstOp", "[", "firstMatch", "[", "2", "]", "]", "(", "firstVersion", ")", ":", "alwaysFail", ",", "secondVersion", "?", "secondOp", "[", "secondMatch", "[", "1", "]", "]", "(", "secondVersion", ")", ":", "alwaysFail", "]", ";", "}", "return", "null", ";", "}" ]
Parse a constarint such as `0.18.0 <= v < 0.19.0` into a list of functions to test against a `v` value The value of `v` itself should match the type returned by `parseVersionString`.
[ "Parse", "a", "constarint", "such", "as", "0", ".", "18", ".", "0", "<", "=", "v", "<", "0", ".", "19", ".", "0", "into", "a", "list", "of", "functions", "to", "test", "against", "a", "v", "value", "The", "value", "of", "v", "itself", "should", "match", "the", "type", "returned", "by", "parseVersionString", "." ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L208-L236
40,027
dbowring/elm-forest
lib/forest.js
function (dirname) { return new Promise((resolve, reject) => { fs.mkdir(dirname, (err) => { if (err) { reject(err); } else { resolve(dirname); } }); }); }
javascript
function (dirname) { return new Promise((resolve, reject) => { fs.mkdir(dirname, (err) => { if (err) { reject(err); } else { resolve(dirname); } }); }); }
[ "function", "(", "dirname", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "mkdir", "(", "dirname", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "dirname", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Non-Recursive mkdir
[ "Non", "-", "Recursive", "mkdir" ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L261-L272
40,028
dbowring/elm-forest
lib/forest.js
function () { let noop = function () { }; let log = { error: npmlog.error, warn: npmlog.warn, info: noop, verbose: noop, silly: noop, http: noop, pause: noop, resume: noop }; return new RegClient({ log: log }); }
javascript
function () { let noop = function () { }; let log = { error: npmlog.error, warn: npmlog.warn, info: noop, verbose: noop, silly: noop, http: noop, pause: noop, resume: noop }; return new RegClient({ log: log }); }
[ "function", "(", ")", "{", "let", "noop", "=", "function", "(", ")", "{", "}", ";", "let", "log", "=", "{", "error", ":", "npmlog", ".", "error", ",", "warn", ":", "npmlog", ".", "warn", ",", "info", ":", "noop", ",", "verbose", ":", "noop", ",", "silly", ":", "noop", ",", "http", ":", "noop", ",", "pause", ":", "noop", ",", "resume", ":", "noop", "}", ";", "return", "new", "RegClient", "(", "{", "log", ":", "log", "}", ")", ";", "}" ]
Get a NPM client that does minimal console spam NPM Erorrs and warnings will still be sent to the console.
[ "Get", "a", "NPM", "client", "that", "does", "minimal", "console", "spam", "NPM", "Erorrs", "and", "warnings", "will", "still", "be", "sent", "to", "the", "console", "." ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L313-L326
40,029
dbowring/elm-forest
lib/forest.js
function (version) { return __awaiter(this, void 0, void 0, function* () { let versions = yield ForestInternal.queryElmVersions(); let result = ForestInternal.findSuitable(version, versions); if (result === null) { throw new ForestError(Errors.NoMatchingVersion, `Unable to find an Elm version matching ${version} on NPM`); } return Promise.resolve(result); }); }
javascript
function (version) { return __awaiter(this, void 0, void 0, function* () { let versions = yield ForestInternal.queryElmVersions(); let result = ForestInternal.findSuitable(version, versions); if (result === null) { throw new ForestError(Errors.NoMatchingVersion, `Unable to find an Elm version matching ${version} on NPM`); } return Promise.resolve(result); }); }
[ "function", "(", "version", ")", "{", "return", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "*", "(", ")", "{", "let", "versions", "=", "yield", "ForestInternal", ".", "queryElmVersions", "(", ")", ";", "let", "result", "=", "ForestInternal", ".", "findSuitable", "(", "version", ",", "versions", ")", ";", "if", "(", "result", "===", "null", ")", "{", "throw", "new", "ForestError", "(", "Errors", ".", "NoMatchingVersion", ",", "`", "${", "version", "}", "`", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "result", ")", ";", "}", ")", ";", "}" ]
Expand a version by asking npm
[ "Expand", "a", "version", "by", "asking", "npm" ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L379-L388
40,030
dbowring/elm-forest
lib/forest.js
function (path) { return new Promise((resolve, reject) => { fs.access(path, fs.constants.F_OK, (err) => { if (err === null) { resolve(true); } else if (err.code === 'ENOENT') { resolve(false); } else { reject(err); } }); }); }
javascript
function (path) { return new Promise((resolve, reject) => { fs.access(path, fs.constants.F_OK, (err) => { if (err === null) { resolve(true); } else if (err.code === 'ENOENT') { resolve(false); } else { reject(err); } }); }); }
[ "function", "(", "path", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "access", "(", "path", ",", "fs", ".", "constants", ".", "F_OK", ",", "(", "err", ")", "=>", "{", "if", "(", "err", "===", "null", ")", "{", "resolve", "(", "true", ")", ";", "}", "else", "if", "(", "err", ".", "code", "===", "'ENOENT'", ")", "{", "resolve", "(", "false", ")", ";", "}", "else", "{", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Does `path` exist on the filesystem?
[ "Does", "path", "exist", "on", "the", "filesystem?" ]
4e3a8252e19317501e7448b576fda4575e3c601c
https://github.com/dbowring/elm-forest/blob/4e3a8252e19317501e7448b576fda4575e3c601c/lib/forest.js#L510-L524
40,031
facet/core
lib/router-manifest.js
function(){ this.manifest = { apiEventType: '', apiModelId: '', // this is the id for this module routeBase: '', // this can be overwritten routes: [ ], routeErrorMessages: { conditions: 'No query conditions were specified', query: 'Error querying for item(s): ', notFound: 'No item was found.', find: 'No item(s) matched your criteria.', findOne: 'No item matched your criteria.', update: 'No updates were specified.', updateMatch: 'No items were updated based on your criteria.', create: 'No data supplied for creating new item.', createMatch: 'No item was created based on your criteria.', remove: 'No data supplied for removing item.', removeMatch: 'No item was removed based on your criteria.' } }; // return this object return this; }
javascript
function(){ this.manifest = { apiEventType: '', apiModelId: '', // this is the id for this module routeBase: '', // this can be overwritten routes: [ ], routeErrorMessages: { conditions: 'No query conditions were specified', query: 'Error querying for item(s): ', notFound: 'No item was found.', find: 'No item(s) matched your criteria.', findOne: 'No item matched your criteria.', update: 'No updates were specified.', updateMatch: 'No items were updated based on your criteria.', create: 'No data supplied for creating new item.', createMatch: 'No item was created based on your criteria.', remove: 'No data supplied for removing item.', removeMatch: 'No item was removed based on your criteria.' } }; // return this object return this; }
[ "function", "(", ")", "{", "this", ".", "manifest", "=", "{", "apiEventType", ":", "''", ",", "apiModelId", ":", "''", ",", "// this is the id for this module ", "routeBase", ":", "''", ",", "// this can be overwritten", "routes", ":", "[", "]", ",", "routeErrorMessages", ":", "{", "conditions", ":", "'No query conditions were specified'", ",", "query", ":", "'Error querying for item(s): '", ",", "notFound", ":", "'No item was found.'", ",", "find", ":", "'No item(s) matched your criteria.'", ",", "findOne", ":", "'No item matched your criteria.'", ",", "update", ":", "'No updates were specified.'", ",", "updateMatch", ":", "'No items were updated based on your criteria.'", ",", "create", ":", "'No data supplied for creating new item.'", ",", "createMatch", ":", "'No item was created based on your criteria.'", ",", "remove", ":", "'No data supplied for removing item.'", ",", "removeMatch", ":", "'No item was removed based on your criteria.'", "}", "}", ";", "// return this object", "return", "this", ";", "}" ]
Router Manifest constructor @return {Object} The Router Manifest Object
[ "Router", "Manifest", "constructor" ]
8e74c1545956dfbfa298a0fa477506980eca362e
https://github.com/facet/core/blob/8e74c1545956dfbfa298a0fa477506980eca362e/lib/router-manifest.js#L11-L36
40,032
sourcegraph/jsg
symbol_id.js
cleanPath
function cleanPath(p) { p = JSON.stringify(p); return p.slice(1, p.length - 1); }
javascript
function cleanPath(p) { p = JSON.stringify(p); return p.slice(1, p.length - 1); }
[ "function", "cleanPath", "(", "p", ")", "{", "p", "=", "JSON", ".", "stringify", "(", "p", ")", ";", "return", "p", ".", "slice", "(", "1", ",", "p", ".", "length", "-", "1", ")", ";", "}" ]
cleanPath escapes unprintable chars in p.
[ "cleanPath", "escapes", "unprintable", "chars", "in", "p", "." ]
83526b95285bd4381be24b21c6aa47b9dab13bbe
https://github.com/sourcegraph/jsg/blob/83526b95285bd4381be24b21c6aa47b9dab13bbe/symbol_id.js#L17-L20
40,033
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js
isHelper
function isHelper(node) { if (t.isMemberExpression(node)) { return isHelper(node.object) || isHelper(node.property); } else if (t.isIdentifier(node)) { return node.name === "require" || node.name[0] === "_"; } else if (t.isCallExpression(node)) { return isHelper(node.callee); } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); } else { return false; } }
javascript
function isHelper(node) { if (t.isMemberExpression(node)) { return isHelper(node.object) || isHelper(node.property); } else if (t.isIdentifier(node)) { return node.name === "require" || node.name[0] === "_"; } else if (t.isCallExpression(node)) { return isHelper(node.callee); } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); } else { return false; } }
[ "function", "isHelper", "(", "node", ")", "{", "if", "(", "t", ".", "isMemberExpression", "(", "node", ")", ")", "{", "return", "isHelper", "(", "node", ".", "object", ")", "||", "isHelper", "(", "node", ".", "property", ")", ";", "}", "else", "if", "(", "t", ".", "isIdentifier", "(", "node", ")", ")", "{", "return", "node", ".", "name", "===", "\"require\"", "||", "node", ".", "name", "[", "0", "]", "===", "\"_\"", ";", "}", "else", "if", "(", "t", ".", "isCallExpression", "(", "node", ")", ")", "{", "return", "isHelper", "(", "node", ".", "callee", ")", ";", "}", "else", "if", "(", "t", ".", "isBinary", "(", "node", ")", "||", "t", ".", "isAssignmentExpression", "(", "node", ")", ")", "{", "return", "t", ".", "isIdentifier", "(", "node", ".", "left", ")", "&&", "isHelper", "(", "node", ".", "left", ")", "||", "isHelper", "(", "node", ".", "right", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Test if a node is or has a helper.
[ "Test", "if", "a", "node", "is", "or", "has", "a", "helper", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js#L62-L74
40,034
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js
AssignmentExpression
function AssignmentExpression(node) { var state = crawl(node.right); if (state.hasCall && state.hasHelper || state.hasFunction) { return { before: state.hasFunction, after: true }; } }
javascript
function AssignmentExpression(node) { var state = crawl(node.right); if (state.hasCall && state.hasHelper || state.hasFunction) { return { before: state.hasFunction, after: true }; } }
[ "function", "AssignmentExpression", "(", "node", ")", "{", "var", "state", "=", "crawl", "(", "node", ".", "right", ")", ";", "if", "(", "state", ".", "hasCall", "&&", "state", ".", "hasHelper", "||", "state", ".", "hasFunction", ")", "{", "return", "{", "before", ":", "state", ".", "hasFunction", ",", "after", ":", "true", "}", ";", "}", "}" ]
Test if AssignmentExpression needs whitespace.
[ "Test", "if", "AssignmentExpression", "needs", "whitespace", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js#L94-L102
40,035
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js
CallExpression
function CallExpression(node) { if (t.isFunction(node.callee) || isHelper(node)) { return { before: true, after: true }; } }
javascript
function CallExpression(node) { if (t.isFunction(node.callee) || isHelper(node)) { return { before: true, after: true }; } }
[ "function", "CallExpression", "(", "node", ")", "{", "if", "(", "t", ".", "isFunction", "(", "node", ".", "callee", ")", "||", "isHelper", "(", "node", ")", ")", "{", "return", "{", "before", ":", "true", ",", "after", ":", "true", "}", ";", "}", "}" ]
Test if CallExpression needs whitespace.
[ "Test", "if", "CallExpression", "needs", "whitespace", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js#L142-L149
40,036
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js
IfStatement
function IfStatement(node) { if (t.isBlockStatement(node.consequent)) { return { before: true, after: true }; } }
javascript
function IfStatement(node) { if (t.isBlockStatement(node.consequent)) { return { before: true, after: true }; } }
[ "function", "IfStatement", "(", "node", ")", "{", "if", "(", "t", ".", "isBlockStatement", "(", "node", ".", "consequent", ")", ")", "{", "return", "{", "before", ":", "true", ",", "after", ":", "true", "}", ";", "}", "}" ]
Test if IfStatement needs whitespace.
[ "Test", "if", "IfStatement", "needs", "whitespace", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/whitespace.js#L178-L185
40,037
brycebaril/multibuffer
index.js
encode
function encode(buffer, extra) { if (!extra) extra = 0 var blen = buffer.length var lenbytes = vencode(blen) var mb = new Buffer(extra + blen + lenbytes.length) for (var i = 0; i < lenbytes.length; i++) { mb.writeUInt8(lenbytes[i], extra + i) } buffer.copy(mb, lenbytes.length + extra, 0, blen) return mb }
javascript
function encode(buffer, extra) { if (!extra) extra = 0 var blen = buffer.length var lenbytes = vencode(blen) var mb = new Buffer(extra + blen + lenbytes.length) for (var i = 0; i < lenbytes.length; i++) { mb.writeUInt8(lenbytes[i], extra + i) } buffer.copy(mb, lenbytes.length + extra, 0, blen) return mb }
[ "function", "encode", "(", "buffer", ",", "extra", ")", "{", "if", "(", "!", "extra", ")", "extra", "=", "0", "var", "blen", "=", "buffer", ".", "length", "var", "lenbytes", "=", "vencode", "(", "blen", ")", "var", "mb", "=", "new", "Buffer", "(", "extra", "+", "blen", "+", "lenbytes", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lenbytes", ".", "length", ";", "i", "++", ")", "{", "mb", ".", "writeUInt8", "(", "lenbytes", "[", "i", "]", ",", "extra", "+", "i", ")", "}", "buffer", ".", "copy", "(", "mb", ",", "lenbytes", ".", "length", "+", "extra", ",", "0", ",", "blen", ")", "return", "mb", "}" ]
Encode a buffer with a varint prefix containing the buffer's length. @param {Buffer} buffer The buffer to encode @param {int} extra How many extra empty leading bytes to put in the buffer @return {Buffer} An encoded buffer longer than before.
[ "Encode", "a", "buffer", "with", "a", "varint", "prefix", "containing", "the", "buffer", "s", "length", "." ]
ededac93ab213c743b2ee81623532bee9b0d5195
https://github.com/brycebaril/multibuffer/blob/ededac93ab213c743b2ee81623532bee9b0d5195/index.js#L16-L26
40,038
brycebaril/multibuffer
index.js
pack
function pack(buffs, extra) { var lengths = [], lenbytes = [], len = buffs.length, extra = extra || 0, sum = 0, offset = 0, mb, i for (i = 0; i < len; i++) { lengths.push(buffs[i].length) lenbytes.push(vencode(lengths[i])) sum += lengths[i] + lenbytes[i].length + extra } mb = new Buffer(sum) for (i = 0; i < len; i++) { for (var j = 0; j < lenbytes[i].length; j++) { mb.writeUInt8(lenbytes[i][j], offset + extra) offset = offset + 1 + extra } buffs[i].copy(mb, offset, 0, lengths[i]) offset += lengths[i] } return mb }
javascript
function pack(buffs, extra) { var lengths = [], lenbytes = [], len = buffs.length, extra = extra || 0, sum = 0, offset = 0, mb, i for (i = 0; i < len; i++) { lengths.push(buffs[i].length) lenbytes.push(vencode(lengths[i])) sum += lengths[i] + lenbytes[i].length + extra } mb = new Buffer(sum) for (i = 0; i < len; i++) { for (var j = 0; j < lenbytes[i].length; j++) { mb.writeUInt8(lenbytes[i][j], offset + extra) offset = offset + 1 + extra } buffs[i].copy(mb, offset, 0, lengths[i]) offset += lengths[i] } return mb }
[ "function", "pack", "(", "buffs", ",", "extra", ")", "{", "var", "lengths", "=", "[", "]", ",", "lenbytes", "=", "[", "]", ",", "len", "=", "buffs", ".", "length", ",", "extra", "=", "extra", "||", "0", ",", "sum", "=", "0", ",", "offset", "=", "0", ",", "mb", ",", "i", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "lengths", ".", "push", "(", "buffs", "[", "i", "]", ".", "length", ")", "lenbytes", ".", "push", "(", "vencode", "(", "lengths", "[", "i", "]", ")", ")", "sum", "+=", "lengths", "[", "i", "]", "+", "lenbytes", "[", "i", "]", ".", "length", "+", "extra", "}", "mb", "=", "new", "Buffer", "(", "sum", ")", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "lenbytes", "[", "i", "]", ".", "length", ";", "j", "++", ")", "{", "mb", ".", "writeUInt8", "(", "lenbytes", "[", "i", "]", "[", "j", "]", ",", "offset", "+", "extra", ")", "offset", "=", "offset", "+", "1", "+", "extra", "}", "buffs", "[", "i", "]", ".", "copy", "(", "mb", ",", "offset", ",", "0", ",", "lengths", "[", "i", "]", ")", "offset", "+=", "lengths", "[", "i", "]", "}", "return", "mb", "}" ]
Combine an array of buffers into a single buffer encoded such that they can all be extracted again. @param {Array[Buffer]} buffs An array of Buffers @param {int} extra How many extra empty leading bytes to put in each buffer @return {Buffer} A single buffer that is an encoded concatentation of buffs
[ "Combine", "an", "array", "of", "buffers", "into", "a", "single", "buffer", "encoded", "such", "that", "they", "can", "all", "be", "extracted", "again", "." ]
ededac93ab213c743b2ee81623532bee9b0d5195
https://github.com/brycebaril/multibuffer/blob/ededac93ab213c743b2ee81623532bee9b0d5195/index.js#L34-L60
40,039
brycebaril/multibuffer
index.js
unpack
function unpack(multibuffer) { var buffs = [] var offset = 0 var length while (offset < multibuffer.length) { length = vdecode(multibuffer.slice(offset)) offset += vdecode.bytes buffs.push(multibuffer.slice(offset, offset + length)) offset += length } return buffs }
javascript
function unpack(multibuffer) { var buffs = [] var offset = 0 var length while (offset < multibuffer.length) { length = vdecode(multibuffer.slice(offset)) offset += vdecode.bytes buffs.push(multibuffer.slice(offset, offset + length)) offset += length } return buffs }
[ "function", "unpack", "(", "multibuffer", ")", "{", "var", "buffs", "=", "[", "]", "var", "offset", "=", "0", "var", "length", "while", "(", "offset", "<", "multibuffer", ".", "length", ")", "{", "length", "=", "vdecode", "(", "multibuffer", ".", "slice", "(", "offset", ")", ")", "offset", "+=", "vdecode", ".", "bytes", "buffs", ".", "push", "(", "multibuffer", ".", "slice", "(", "offset", ",", "offset", "+", "length", ")", ")", "offset", "+=", "length", "}", "return", "buffs", "}" ]
Split an encoded multibuffer into the original buffers @param {Buffer} multibuffer An encoded multibuffer @return {Array[Buffer]} The encoded Buffers
[ "Split", "an", "encoded", "multibuffer", "into", "the", "original", "buffers" ]
ededac93ab213c743b2ee81623532bee9b0d5195
https://github.com/brycebaril/multibuffer/blob/ededac93ab213c743b2ee81623532bee9b0d5195/index.js#L67-L80
40,040
brycebaril/multibuffer
index.js
readPartial
function readPartial(multibuffer) { var dataLength = vdecode(multibuffer) var read = vdecode.bytes if (multibuffer.length < read + dataLength) return [null, multibuffer] var first = multibuffer.slice(read, read + dataLength) var rest = multibuffer.slice(read + dataLength) if (rest.length === 0) rest = null return [first, rest] }
javascript
function readPartial(multibuffer) { var dataLength = vdecode(multibuffer) var read = vdecode.bytes if (multibuffer.length < read + dataLength) return [null, multibuffer] var first = multibuffer.slice(read, read + dataLength) var rest = multibuffer.slice(read + dataLength) if (rest.length === 0) rest = null return [first, rest] }
[ "function", "readPartial", "(", "multibuffer", ")", "{", "var", "dataLength", "=", "vdecode", "(", "multibuffer", ")", "var", "read", "=", "vdecode", ".", "bytes", "if", "(", "multibuffer", ".", "length", "<", "read", "+", "dataLength", ")", "return", "[", "null", ",", "multibuffer", "]", "var", "first", "=", "multibuffer", ".", "slice", "(", "read", ",", "read", "+", "dataLength", ")", "var", "rest", "=", "multibuffer", ".", "slice", "(", "read", "+", "dataLength", ")", "if", "(", "rest", ".", "length", "===", "0", ")", "rest", "=", "null", "return", "[", "first", ",", "rest", "]", "}" ]
Fetch the first encoded buffer from a multibuffer, and the rest of the multibuffer. @param {Buffer} multibuffer An encoded multibuffer. @return {Array} [Buffer, Buffer] where the first buffer is the first encoded buffer, and the second is the rest of the multibuffer.
[ "Fetch", "the", "first", "encoded", "buffer", "from", "a", "multibuffer", "and", "the", "rest", "of", "the", "multibuffer", "." ]
ededac93ab213c743b2ee81623532bee9b0d5195
https://github.com/brycebaril/multibuffer/blob/ededac93ab213c743b2ee81623532bee9b0d5195/index.js#L87-L95
40,041
stadt-bielefeld/mapfile2js
src/build/determineKeyValueSpaces.js
determineKeyValueSpaces
function determineKeyValueSpaces(obj, tabSize) { let lastDepth = 0; let spacesIndex = 0; let spaces = []; //iterate over all lines obj.forEach((line) => { if (lastDepth !== line.depth) { spacesIndex++; } //key found if (line.key) { //value found if (line.value) { //block line found if (line.isBlockLine) { line.keyValueSpaces = ' '; } else { if (!spaces[spacesIndex]) { spaces[spacesIndex] = { maxKeyLength: 1 }; } //determine maxKeyLength if (spaces[spacesIndex].maxKeyLength < line.key.length) { if (spaces[spacesIndex].maxKeyLength < line.key.length) { spaces[spacesIndex].maxKeyLength = line.key.length; } } } } } lastDepth = line.depth; }); // reset the counters lastDepth = 0; spacesIndex = 0; //iterate over all lines obj.forEach((line) => { if (lastDepth !== line.depth) { spacesIndex++; } //key found if (line.key) { //value found if (line.value) { //block line found if (!line.isBlockLine) { if(spaces[spacesIndex]){ let numSpaces = spaces[spacesIndex].maxKeyLength - line.key.length + tabSize; line.keyValueSpaces = ''; for (let i = 0; i < numSpaces; i++) { line.keyValueSpaces += ' '; } } } } } lastDepth = line.depth; }); console.log(obj); return obj; }
javascript
function determineKeyValueSpaces(obj, tabSize) { let lastDepth = 0; let spacesIndex = 0; let spaces = []; //iterate over all lines obj.forEach((line) => { if (lastDepth !== line.depth) { spacesIndex++; } //key found if (line.key) { //value found if (line.value) { //block line found if (line.isBlockLine) { line.keyValueSpaces = ' '; } else { if (!spaces[spacesIndex]) { spaces[spacesIndex] = { maxKeyLength: 1 }; } //determine maxKeyLength if (spaces[spacesIndex].maxKeyLength < line.key.length) { if (spaces[spacesIndex].maxKeyLength < line.key.length) { spaces[spacesIndex].maxKeyLength = line.key.length; } } } } } lastDepth = line.depth; }); // reset the counters lastDepth = 0; spacesIndex = 0; //iterate over all lines obj.forEach((line) => { if (lastDepth !== line.depth) { spacesIndex++; } //key found if (line.key) { //value found if (line.value) { //block line found if (!line.isBlockLine) { if(spaces[spacesIndex]){ let numSpaces = spaces[spacesIndex].maxKeyLength - line.key.length + tabSize; line.keyValueSpaces = ''; for (let i = 0; i < numSpaces; i++) { line.keyValueSpaces += ' '; } } } } } lastDepth = line.depth; }); console.log(obj); return obj; }
[ "function", "determineKeyValueSpaces", "(", "obj", ",", "tabSize", ")", "{", "let", "lastDepth", "=", "0", ";", "let", "spacesIndex", "=", "0", ";", "let", "spaces", "=", "[", "]", ";", "//iterate over all lines", "obj", ".", "forEach", "(", "(", "line", ")", "=>", "{", "if", "(", "lastDepth", "!==", "line", ".", "depth", ")", "{", "spacesIndex", "++", ";", "}", "//key found", "if", "(", "line", ".", "key", ")", "{", "//value found", "if", "(", "line", ".", "value", ")", "{", "//block line found", "if", "(", "line", ".", "isBlockLine", ")", "{", "line", ".", "keyValueSpaces", "=", "' '", ";", "}", "else", "{", "if", "(", "!", "spaces", "[", "spacesIndex", "]", ")", "{", "spaces", "[", "spacesIndex", "]", "=", "{", "maxKeyLength", ":", "1", "}", ";", "}", "//determine maxKeyLength", "if", "(", "spaces", "[", "spacesIndex", "]", ".", "maxKeyLength", "<", "line", ".", "key", ".", "length", ")", "{", "if", "(", "spaces", "[", "spacesIndex", "]", ".", "maxKeyLength", "<", "line", ".", "key", ".", "length", ")", "{", "spaces", "[", "spacesIndex", "]", ".", "maxKeyLength", "=", "line", ".", "key", ".", "length", ";", "}", "}", "}", "}", "}", "lastDepth", "=", "line", ".", "depth", ";", "}", ")", ";", "// reset the counters", "lastDepth", "=", "0", ";", "spacesIndex", "=", "0", ";", "//iterate over all lines", "obj", ".", "forEach", "(", "(", "line", ")", "=>", "{", "if", "(", "lastDepth", "!==", "line", ".", "depth", ")", "{", "spacesIndex", "++", ";", "}", "//key found", "if", "(", "line", ".", "key", ")", "{", "//value found", "if", "(", "line", ".", "value", ")", "{", "//block line found", "if", "(", "!", "line", ".", "isBlockLine", ")", "{", "if", "(", "spaces", "[", "spacesIndex", "]", ")", "{", "let", "numSpaces", "=", "spaces", "[", "spacesIndex", "]", ".", "maxKeyLength", "-", "line", ".", "key", ".", "length", "+", "tabSize", ";", "line", ".", "keyValueSpaces", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "numSpaces", ";", "i", "++", ")", "{", "line", ".", "keyValueSpaces", "+=", "' '", ";", "}", "}", "}", "}", "}", "lastDepth", "=", "line", ".", "depth", ";", "}", ")", ";", "console", ".", "log", "(", "obj", ")", ";", "return", "obj", ";", "}" ]
Determines the spaces between key and value @param {array} obj Array of line objects @param {number} tabSize Tab size in spaces
[ "Determines", "the", "spaces", "between", "key", "and", "value" ]
08497189503e8823d1c9f26b74ce4ad1025e59dd
https://github.com/stadt-bielefeld/mapfile2js/blob/08497189503e8823d1c9f26b74ce4ad1025e59dd/src/build/determineKeyValueSpaces.js#L7-L88
40,042
Floobits/dmp
lib/dmp.js
match_bitapScore_
function match_bitapScore_(e, x) { var accuracy = e / pattern.length; var proximity = Math.abs(loc - x); if (!self.Match_Distance) { // Dodge divide by zero error. return proximity ? 1.0 : accuracy; } return accuracy + (proximity / self.Match_Distance); }
javascript
function match_bitapScore_(e, x) { var accuracy = e / pattern.length; var proximity = Math.abs(loc - x); if (!self.Match_Distance) { // Dodge divide by zero error. return proximity ? 1.0 : accuracy; } return accuracy + (proximity / self.Match_Distance); }
[ "function", "match_bitapScore_", "(", "e", ",", "x", ")", "{", "var", "accuracy", "=", "e", "/", "pattern", ".", "length", ";", "var", "proximity", "=", "Math", ".", "abs", "(", "loc", "-", "x", ")", ";", "if", "(", "!", "self", ".", "Match_Distance", ")", "{", "// Dodge divide by zero error.", "return", "proximity", "?", "1.0", ":", "accuracy", ";", "}", "return", "accuracy", "+", "(", "proximity", "/", "self", ".", "Match_Distance", ")", ";", "}" ]
'this' becomes 'window' in a closure. Compute and return the score for a match with e errors and x location. Accesses loc and pattern through being a closure. @param {number} e Number of errors in match. @param {number} x Location of match. @return {number} Overall score for match (0.0 = good, 1.0 = bad). @private
[ "this", "becomes", "window", "in", "a", "closure", ".", "Compute", "and", "return", "the", "score", "for", "a", "match", "with", "e", "errors", "and", "x", "location", ".", "Accesses", "loc", "and", "pattern", "through", "being", "a", "closure", "." ]
8da90ab40e64d193802097c22506dd31f300d9c2
https://github.com/Floobits/dmp/blob/8da90ab40e64d193802097c22506dd31f300d9c2/lib/dmp.js#L1456-L1464
40,043
jschaefer-io/tasap
index.js
TpBuilderProcess
function TpBuilderProcess(str, options){ let init = str; if (typeof str === 'object') { init = init.map((item) => '{{@ ' + item + ' }}').join('\n'); } return new TpBuilder(init, options).parse(); }
javascript
function TpBuilderProcess(str, options){ let init = str; if (typeof str === 'object') { init = init.map((item) => '{{@ ' + item + ' }}').join('\n'); } return new TpBuilder(init, options).parse(); }
[ "function", "TpBuilderProcess", "(", "str", ",", "options", ")", "{", "let", "init", "=", "str", ";", "if", "(", "typeof", "str", "===", "'object'", ")", "{", "init", "=", "init", ".", "map", "(", "(", "item", ")", "=>", "'{{@ '", "+", "item", "+", "' }}'", ")", ".", "join", "(", "'\\n'", ")", ";", "}", "return", "new", "TpBuilder", "(", "init", ",", "options", ")", ".", "parse", "(", ")", ";", "}" ]
Main Process starting process @param {string|object} str content @param {array} options options array for tasap @returns TpBuilder
[ "Main", "Process", "starting", "process" ]
ba4982fcf36fd293aab8281c2291fa62de8a2f23
https://github.com/jschaefer-io/tasap/blob/ba4982fcf36fd293aab8281c2291fa62de8a2f23/index.js#L13-L19
40,044
Node-Ops/node-apt-get
index.js
function(options) { options = options || {}; var optionsArray = []; // Go through the available options, // set either the passed option // or the default for (var i in apt.options) { if (typeof options[i] !== 'undefined') { addOption(optionsArray, i, options[i]); } else { addOption(optionsArray, i, apt.options[i]); } } return optionsArray; }
javascript
function(options) { options = options || {}; var optionsArray = []; // Go through the available options, // set either the passed option // or the default for (var i in apt.options) { if (typeof options[i] !== 'undefined') { addOption(optionsArray, i, options[i]); } else { addOption(optionsArray, i, apt.options[i]); } } return optionsArray; }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "optionsArray", "=", "[", "]", ";", "// Go through the available options,", "// set either the passed option", "// or the default", "for", "(", "var", "i", "in", "apt", ".", "options", ")", "{", "if", "(", "typeof", "options", "[", "i", "]", "!==", "'undefined'", ")", "{", "addOption", "(", "optionsArray", ",", "i", ",", "options", "[", "i", "]", ")", ";", "}", "else", "{", "addOption", "(", "optionsArray", ",", "i", ",", "apt", ".", "options", "[", "i", "]", ")", ";", "}", "}", "return", "optionsArray", ";", "}" ]
Parses the options adding them to an options array which is returned
[ "Parses", "the", "options", "adding", "them", "to", "an", "options", "array", "which", "is", "returned" ]
db5bb8b763dd6f71f1356eadc5875aaf4a215875
https://github.com/Node-Ops/node-apt-get/blob/db5bb8b763dd6f71f1356eadc5875aaf4a215875/index.js#L54-L70
40,045
Node-Ops/node-apt-get
index.js
function(optsArr, name, value) { switch(typeof value) { case 'boolean': if (value) optsArr.push('--' + name); break; case 'string': optsArr.push('--' + name); optsArr.push(value); break; case 'function': optsArr.push(value()); break; }; }
javascript
function(optsArr, name, value) { switch(typeof value) { case 'boolean': if (value) optsArr.push('--' + name); break; case 'string': optsArr.push('--' + name); optsArr.push(value); break; case 'function': optsArr.push(value()); break; }; }
[ "function", "(", "optsArr", ",", "name", ",", "value", ")", "{", "switch", "(", "typeof", "value", ")", "{", "case", "'boolean'", ":", "if", "(", "value", ")", "optsArr", ".", "push", "(", "'--'", "+", "name", ")", ";", "break", ";", "case", "'string'", ":", "optsArr", ".", "push", "(", "'--'", "+", "name", ")", ";", "optsArr", ".", "push", "(", "value", ")", ";", "break", ";", "case", "'function'", ":", "optsArr", ".", "push", "(", "value", "(", ")", ")", ";", "break", ";", "}", ";", "}" ]
Adds to the options array based on the type of argument provided
[ "Adds", "to", "the", "options", "array", "based", "on", "the", "type", "of", "argument", "provided" ]
db5bb8b763dd6f71f1356eadc5875aaf4a215875
https://github.com/Node-Ops/node-apt-get/blob/db5bb8b763dd6f71f1356eadc5875aaf4a215875/index.js#L74-L87
40,046
Node-Ops/node-apt-get
index.js
function(command, options) { options = options || []; options.unshift(command); return childProcess.spawn(apt.command, options, apt.spawnOptions); }
javascript
function(command, options) { options = options || []; options.unshift(command); return childProcess.spawn(apt.command, options, apt.spawnOptions); }
[ "function", "(", "command", ",", "options", ")", "{", "options", "=", "options", "||", "[", "]", ";", "options", ".", "unshift", "(", "command", ")", ";", "return", "childProcess", ".", "spawn", "(", "apt", ".", "command", ",", "options", ",", "apt", ".", "spawnOptions", ")", ";", "}" ]
A spawn helper to spawn apt-get commands
[ "A", "spawn", "helper", "to", "spawn", "apt", "-", "get", "commands" ]
db5bb8b763dd6f71f1356eadc5875aaf4a215875
https://github.com/Node-Ops/node-apt-get/blob/db5bb8b763dd6f71f1356eadc5875aaf4a215875/index.js#L90-L94
40,047
Mapita/Canary
dist/src/util.js
getOrdinal
function getOrdinal(value) { const lastDigit = value % 10; if (lastDigit === 1) { return `${value}st`; } else if (lastDigit === 2) { return `${value}nd`; } else if (lastDigit === 3) { return `${value}rd`; } else { return `${value}th`; } }
javascript
function getOrdinal(value) { const lastDigit = value % 10; if (lastDigit === 1) { return `${value}st`; } else if (lastDigit === 2) { return `${value}nd`; } else if (lastDigit === 3) { return `${value}rd`; } else { return `${value}th`; } }
[ "function", "getOrdinal", "(", "value", ")", "{", "const", "lastDigit", "=", "value", "%", "10", ";", "if", "(", "lastDigit", "===", "1", ")", "{", "return", "`", "${", "value", "}", "`", ";", "}", "else", "if", "(", "lastDigit", "===", "2", ")", "{", "return", "`", "${", "value", "}", "`", ";", "}", "else", "if", "(", "lastDigit", "===", "3", ")", "{", "return", "`", "${", "value", "}", "`", ";", "}", "else", "{", "return", "`", "${", "value", "}", "`", ";", "}", "}" ]
Helper function to get an ordinal string like "1st", "2nd", "3rd"... Expects the input to be an integer. This is used to produce helpful names for tests and callbacks that weren't assigned more descriptive names by their developer.
[ "Helper", "function", "to", "get", "an", "ordinal", "string", "like", "1st", "2nd", "3rd", "...", "Expects", "the", "input", "to", "be", "an", "integer", ".", "This", "is", "used", "to", "produce", "helpful", "names", "for", "tests", "and", "callbacks", "that", "weren", "t", "assigned", "more", "descriptive", "names", "by", "their", "developer", "." ]
c12c97afc741ac3cbc4727cd28566efbcaf066d9
https://github.com/Mapita/Canary/blob/c12c97afc741ac3cbc4727cd28566efbcaf066d9/dist/src/util.js#L21-L35
40,048
Mapita/Canary
dist/src/util.js
getCallerLocation
function getCallerLocation() { const error = new Error(); if (error.stack) { const lines = error.stack.split("\n"); for (let i = 2; i < lines.length; i++) { if (i > 0 && lines[i] === " at <anonymous>") { const paren = lines[i - 1].indexOf("("); if (paren >= 0) { return lines[i - 1].slice(paren + 1, lines[i - 1].length - 1); } else { return ""; } } else if (!lines[i].startsWith(" at CanaryTest.") && !lines[i].startsWith(" at new CanaryTest")) { const paren = lines[i].indexOf("("); if (paren >= 0) { return lines[i].slice(paren + 1, lines[i].length - 1); } else { return lines[i].slice(7, lines[i].length); } } } } return ""; }
javascript
function getCallerLocation() { const error = new Error(); if (error.stack) { const lines = error.stack.split("\n"); for (let i = 2; i < lines.length; i++) { if (i > 0 && lines[i] === " at <anonymous>") { const paren = lines[i - 1].indexOf("("); if (paren >= 0) { return lines[i - 1].slice(paren + 1, lines[i - 1].length - 1); } else { return ""; } } else if (!lines[i].startsWith(" at CanaryTest.") && !lines[i].startsWith(" at new CanaryTest")) { const paren = lines[i].indexOf("("); if (paren >= 0) { return lines[i].slice(paren + 1, lines[i].length - 1); } else { return lines[i].slice(7, lines[i].length); } } } } return ""; }
[ "function", "getCallerLocation", "(", ")", "{", "const", "error", "=", "new", "Error", "(", ")", ";", "if", "(", "error", ".", "stack", ")", "{", "const", "lines", "=", "error", ".", "stack", ".", "split", "(", "\"\\n\"", ")", ";", "for", "(", "let", "i", "=", "2", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", ">", "0", "&&", "lines", "[", "i", "]", "===", "\" at <anonymous>\"", ")", "{", "const", "paren", "=", "lines", "[", "i", "-", "1", "]", ".", "indexOf", "(", "\"(\"", ")", ";", "if", "(", "paren", ">=", "0", ")", "{", "return", "lines", "[", "i", "-", "1", "]", ".", "slice", "(", "paren", "+", "1", ",", "lines", "[", "i", "-", "1", "]", ".", "length", "-", "1", ")", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}", "else", "if", "(", "!", "lines", "[", "i", "]", ".", "startsWith", "(", "\" at CanaryTest.\"", ")", "&&", "!", "lines", "[", "i", "]", ".", "startsWith", "(", "\" at new CanaryTest\"", ")", ")", "{", "const", "paren", "=", "lines", "[", "i", "]", ".", "indexOf", "(", "\"(\"", ")", ";", "if", "(", "paren", ">=", "0", ")", "{", "return", "lines", "[", "i", "]", ".", "slice", "(", "paren", "+", "1", ",", "lines", "[", "i", "]", ".", "length", "-", "1", ")", ";", "}", "else", "{", "return", "lines", "[", "i", "]", ".", "slice", "(", "7", ",", "lines", "[", "i", "]", ".", "length", ")", ";", "}", "}", "}", "}", "return", "\"\"", ";", "}" ]
Helper function to get the path to the file where a test was defined.
[ "Helper", "function", "to", "get", "the", "path", "to", "the", "file", "where", "a", "test", "was", "defined", "." ]
c12c97afc741ac3cbc4727cd28566efbcaf066d9
https://github.com/Mapita/Canary/blob/c12c97afc741ac3cbc4727cd28566efbcaf066d9/dist/src/util.js#L38-L65
40,049
Mapita/Canary
dist/src/util.js
normalizePath
function normalizePath(path) { // Separate the path into parts (delimited by slashes) let parts = [""]; for (let char of path) { if (char === "/" || char === "\\") { if (parts[parts.length - 1].length) { parts.push(""); } } else { parts[parts.length - 1] += char; } } // Special case for when the entire path was "." if (parts.length === 1 && parts[0] === ".") { return "."; } // Resolve "." and ".." let i = 0; while (i < parts.length) { if (parts[i] === ".") { parts.splice(i, 1); } else if (i > 0 && parts[i] === "..") { parts.splice(i - 1, 2); i--; } else { i++; } } // Build the resulting path let result = ""; for (let part of parts) { if (part && part.length) { if (result.length) { result += "/"; } result += part; } } // Retain a slash at the beginning of the string if (path[0] === "/" || path[0] === "\\") { result = "/" + result; } // All done! return result; }
javascript
function normalizePath(path) { // Separate the path into parts (delimited by slashes) let parts = [""]; for (let char of path) { if (char === "/" || char === "\\") { if (parts[parts.length - 1].length) { parts.push(""); } } else { parts[parts.length - 1] += char; } } // Special case for when the entire path was "." if (parts.length === 1 && parts[0] === ".") { return "."; } // Resolve "." and ".." let i = 0; while (i < parts.length) { if (parts[i] === ".") { parts.splice(i, 1); } else if (i > 0 && parts[i] === "..") { parts.splice(i - 1, 2); i--; } else { i++; } } // Build the resulting path let result = ""; for (let part of parts) { if (part && part.length) { if (result.length) { result += "/"; } result += part; } } // Retain a slash at the beginning of the string if (path[0] === "/" || path[0] === "\\") { result = "/" + result; } // All done! return result; }
[ "function", "normalizePath", "(", "path", ")", "{", "// Separate the path into parts (delimited by slashes)", "let", "parts", "=", "[", "\"\"", "]", ";", "for", "(", "let", "char", "of", "path", ")", "{", "if", "(", "char", "===", "\"/\"", "||", "char", "===", "\"\\\\\"", ")", "{", "if", "(", "parts", "[", "parts", ".", "length", "-", "1", "]", ".", "length", ")", "{", "parts", ".", "push", "(", "\"\"", ")", ";", "}", "}", "else", "{", "parts", "[", "parts", ".", "length", "-", "1", "]", "+=", "char", ";", "}", "}", "// Special case for when the entire path was \".\"", "if", "(", "parts", ".", "length", "===", "1", "&&", "parts", "[", "0", "]", "===", "\".\"", ")", "{", "return", "\".\"", ";", "}", "// Resolve \".\" and \"..\"", "let", "i", "=", "0", ";", "while", "(", "i", "<", "parts", ".", "length", ")", "{", "if", "(", "parts", "[", "i", "]", "===", "\".\"", ")", "{", "parts", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "else", "if", "(", "i", ">", "0", "&&", "parts", "[", "i", "]", "===", "\"..\"", ")", "{", "parts", ".", "splice", "(", "i", "-", "1", ",", "2", ")", ";", "i", "--", ";", "}", "else", "{", "i", "++", ";", "}", "}", "// Build the resulting path", "let", "result", "=", "\"\"", ";", "for", "(", "let", "part", "of", "parts", ")", "{", "if", "(", "part", "&&", "part", ".", "length", ")", "{", "if", "(", "result", ".", "length", ")", "{", "result", "+=", "\"/\"", ";", "}", "result", "+=", "part", ";", "}", "}", "// Retain a slash at the beginning of the string", "if", "(", "path", "[", "0", "]", "===", "\"/\"", "||", "path", "[", "0", "]", "===", "\"\\\\\"", ")", "{", "result", "=", "\"/\"", "+", "result", ";", "}", "// All done!", "return", "result", ";", "}" ]
Helper function to normalize a file path for comparison. Makes all slashes forward slashes, removes trailing and redundant slashes, and resolves "." and "..".
[ "Helper", "function", "to", "normalize", "a", "file", "path", "for", "comparison", ".", "Makes", "all", "slashes", "forward", "slashes", "removes", "trailing", "and", "redundant", "slashes", "and", "resolves", ".", "and", "..", "." ]
c12c97afc741ac3cbc4727cd28566efbcaf066d9
https://github.com/Mapita/Canary/blob/c12c97afc741ac3cbc4727cd28566efbcaf066d9/dist/src/util.js#L70-L117
40,050
strugee/node-smart-spawn
index.js
maybeFireCallback
function maybeFireCallback() { // This function is called in any place where we might have completed a task that allows us to fire if (callbackFired) return; // If everything is ready, we *should* fire the callback, and it hasn't already been fired, then do so if (stdoutReady && stderrReady && wantCallback && !callbackFired) { callbackFired = true; callback(callbackErr, stdout); } }
javascript
function maybeFireCallback() { // This function is called in any place where we might have completed a task that allows us to fire if (callbackFired) return; // If everything is ready, we *should* fire the callback, and it hasn't already been fired, then do so if (stdoutReady && stderrReady && wantCallback && !callbackFired) { callbackFired = true; callback(callbackErr, stdout); } }
[ "function", "maybeFireCallback", "(", ")", "{", "// This function is called in any place where we might have completed a task that allows us to fire", "if", "(", "callbackFired", ")", "return", ";", "// If everything is ready, we *should* fire the callback, and it hasn't already been fired, then do so", "if", "(", "stdoutReady", "&&", "stderrReady", "&&", "wantCallback", "&&", "!", "callbackFired", ")", "{", "callbackFired", "=", "true", ";", "callback", "(", "callbackErr", ",", "stdout", ")", ";", "}", "}" ]
Done here so it gets the right scope
[ "Done", "here", "so", "it", "gets", "the", "right", "scope" ]
b57710af42af8a48085756897683b9e175bb8324
https://github.com/strugee/node-smart-spawn/blob/b57710af42af8a48085756897683b9e175bb8324/index.js#L33-L43
40,051
PAI-Tech/PAI-BOT-JS
src/pai-bot/src/modules/bot-base-modules.js
loadModulesConfig
async function loadModulesConfig() { if(!modulesLoaded) { for (let i = 0; i < modules.length; i++) { await applyBotDataSource(modules[i]); } modulesLoaded = true; } }
javascript
async function loadModulesConfig() { if(!modulesLoaded) { for (let i = 0; i < modules.length; i++) { await applyBotDataSource(modules[i]); } modulesLoaded = true; } }
[ "async", "function", "loadModulesConfig", "(", ")", "{", "if", "(", "!", "modulesLoaded", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "modules", ".", "length", ";", "i", "++", ")", "{", "await", "applyBotDataSource", "(", "modules", "[", "i", "]", ")", ";", "}", "modulesLoaded", "=", "true", ";", "}", "}" ]
Load configuration for every module @return {Promise<void>}
[ "Load", "configuration", "for", "every", "module" ]
7744e54f580e18264861e33f2c05aac58b5ad1d9
https://github.com/PAI-Tech/PAI-BOT-JS/blob/7744e54f580e18264861e33f2c05aac58b5ad1d9/src/pai-bot/src/modules/bot-base-modules.js#L29-L39
40,052
fergiemcdowall/search-index-deleter
deleter.js
function (options, callback) { var Deleter = {} // Delete all docs with the IDs found in deleteBatch Deleter.deleteBatch = function (deleteBatch, APICallback) { tryDeleteBatch(options, deleteBatch, function (err) { return APICallback(err) }) } // Flush the db (delete all entries) Deleter.flush = function (APICallback) { flush(options, function (err) { return APICallback(err) }) } return callback(null, Deleter) }
javascript
function (options, callback) { var Deleter = {} // Delete all docs with the IDs found in deleteBatch Deleter.deleteBatch = function (deleteBatch, APICallback) { tryDeleteBatch(options, deleteBatch, function (err) { return APICallback(err) }) } // Flush the db (delete all entries) Deleter.flush = function (APICallback) { flush(options, function (err) { return APICallback(err) }) } return callback(null, Deleter) }
[ "function", "(", "options", ",", "callback", ")", "{", "var", "Deleter", "=", "{", "}", "// Delete all docs with the IDs found in deleteBatch", "Deleter", ".", "deleteBatch", "=", "function", "(", "deleteBatch", ",", "APICallback", ")", "{", "tryDeleteBatch", "(", "options", ",", "deleteBatch", ",", "function", "(", "err", ")", "{", "return", "APICallback", "(", "err", ")", "}", ")", "}", "// Flush the db (delete all entries)", "Deleter", ".", "flush", "=", "function", "(", "APICallback", ")", "{", "flush", "(", "options", ",", "function", "(", "err", ")", "{", "return", "APICallback", "(", "err", ")", "}", ")", "}", "return", "callback", "(", "null", ",", "Deleter", ")", "}" ]
Define API calls
[ "Define", "API", "calls" ]
a1e5c3d9b3e4202fb71ba479203cdb505990ed59
https://github.com/fergiemcdowall/search-index-deleter/blob/a1e5c3d9b3e4202fb71ba479203cdb505990ed59/deleter.js#L33-L48
40,053
thirdcoder/balanced-ternary
bt.js
bts2n
function bts2n(s) { var n = 0; for (var i = 0; i < s.length; ++i) { var ch = s.charAt(i); var digit = BT_DIGIT_TO_N[ch]; if (digit === undefined) throw new Error('bts2n('+s+'): invalid digit character: '+ch); //console.log(i,digit,3**i,n,s,ch); n += pow3(s.length - i - 1) * digit; } return n; }
javascript
function bts2n(s) { var n = 0; for (var i = 0; i < s.length; ++i) { var ch = s.charAt(i); var digit = BT_DIGIT_TO_N[ch]; if (digit === undefined) throw new Error('bts2n('+s+'): invalid digit character: '+ch); //console.log(i,digit,3**i,n,s,ch); n += pow3(s.length - i - 1) * digit; } return n; }
[ "function", "bts2n", "(", "s", ")", "{", "var", "n", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "s", ".", "length", ";", "++", "i", ")", "{", "var", "ch", "=", "s", ".", "charAt", "(", "i", ")", ";", "var", "digit", "=", "BT_DIGIT_TO_N", "[", "ch", "]", ";", "if", "(", "digit", "===", "undefined", ")", "throw", "new", "Error", "(", "'bts2n('", "+", "s", "+", "'): invalid digit character: '", "+", "ch", ")", ";", "//console.log(i,digit,3**i,n,s,ch);", "n", "+=", "pow3", "(", "s", ".", "length", "-", "i", "-", "1", ")", "*", "digit", ";", "}", "return", "n", ";", "}" ]
parse balanced ternary string to signed integer
[ "parse", "balanced", "ternary", "string", "to", "signed", "integer" ]
79be6619cc68c161171925b34c3a820d39f4b1e9
https://github.com/thirdcoder/balanced-ternary/blob/79be6619cc68c161171925b34c3a820d39f4b1e9/bt.js#L24-L34
40,054
thirdcoder/balanced-ternary
bt.js
n2bts
function n2bts(n_) { var neg = n_ < 0; var n = Math.abs(n_); var s = ''; do { var digit = n % 3; // balance the ternary http://stackoverflow.com/questions/26456597/how-to-convert-from-unbalanced-to-balanced-ternary if (digit === 2) { digit = -1; ++n; } //console.log('digit',digit,n,n_,s); // if number has negative sign, flip all digits if (neg) { digit = -digit; } s = N_TO_BT_DIGIT[digit] + s; n = ~~(n / 3); // truncate, not floor! negatives } while(n); //console.log('n2bts',n_,s); return s; }
javascript
function n2bts(n_) { var neg = n_ < 0; var n = Math.abs(n_); var s = ''; do { var digit = n % 3; // balance the ternary http://stackoverflow.com/questions/26456597/how-to-convert-from-unbalanced-to-balanced-ternary if (digit === 2) { digit = -1; ++n; } //console.log('digit',digit,n,n_,s); // if number has negative sign, flip all digits if (neg) { digit = -digit; } s = N_TO_BT_DIGIT[digit] + s; n = ~~(n / 3); // truncate, not floor! negatives } while(n); //console.log('n2bts',n_,s); return s; }
[ "function", "n2bts", "(", "n_", ")", "{", "var", "neg", "=", "n_", "<", "0", ";", "var", "n", "=", "Math", ".", "abs", "(", "n_", ")", ";", "var", "s", "=", "''", ";", "do", "{", "var", "digit", "=", "n", "%", "3", ";", "// balance the ternary http://stackoverflow.com/questions/26456597/how-to-convert-from-unbalanced-to-balanced-ternary", "if", "(", "digit", "===", "2", ")", "{", "digit", "=", "-", "1", ";", "++", "n", ";", "}", "//console.log('digit',digit,n,n_,s);", "// if number has negative sign, flip all digits", "if", "(", "neg", ")", "{", "digit", "=", "-", "digit", ";", "}", "s", "=", "N_TO_BT_DIGIT", "[", "digit", "]", "+", "s", ";", "n", "=", "~", "~", "(", "n", "/", "3", ")", ";", "// truncate, not floor! negatives", "}", "while", "(", "n", ")", ";", "//console.log('n2bts',n_,s);", "return", "s", ";", "}" ]
signed integer to balanced ternary string
[ "signed", "integer", "to", "balanced", "ternary", "string" ]
79be6619cc68c161171925b34c3a820d39f4b1e9
https://github.com/thirdcoder/balanced-ternary/blob/79be6619cc68c161171925b34c3a820d39f4b1e9/bt.js#L38-L64
40,055
kevoree/kevoree-js
libraries/group/ws/lib/Protocol.js
startsWith
function startsWith(src, target) { if (target && target.length > 0) { return (src.substr(0, target.length) === target); } else { return false; } }
javascript
function startsWith(src, target) { if (target && target.length > 0) { return (src.substr(0, target.length) === target); } else { return false; } }
[ "function", "startsWith", "(", "src", ",", "target", ")", "{", "if", "(", "target", "&&", "target", ".", "length", ">", "0", ")", "{", "return", "(", "src", ".", "substr", "(", "0", ",", "target", ".", "length", ")", "===", "target", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Checks whether or not 'src' string starts with 'target' string @param {String} src source string to look into @param {String} target string to find at the beginning @returns {boolean} true if 'src' has 'target' at his beginning
[ "Checks", "whether", "or", "not", "src", "string", "starts", "with", "target", "string" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/libraries/group/ws/lib/Protocol.js#L26-L32
40,056
mreinstein/substrate-build
index.js
resolveScriptPaths
function resolveScriptPaths (filePath, m) { const toParse = [ m ] const lookup = {} // key is module name, value is path while (toParse.length) { let node = toParse.pop() if (node.children) for (let n of node.children) toParse.push(n) if (!node.scripts) continue for (let entry of node.scripts) { let moduleName = camelcase(path.parse(entry.source).name) lookup[moduleName] = entry.source entry.module = moduleName } } return lookup }
javascript
function resolveScriptPaths (filePath, m) { const toParse = [ m ] const lookup = {} // key is module name, value is path while (toParse.length) { let node = toParse.pop() if (node.children) for (let n of node.children) toParse.push(n) if (!node.scripts) continue for (let entry of node.scripts) { let moduleName = camelcase(path.parse(entry.source).name) lookup[moduleName] = entry.source entry.module = moduleName } } return lookup }
[ "function", "resolveScriptPaths", "(", "filePath", ",", "m", ")", "{", "const", "toParse", "=", "[", "m", "]", "const", "lookup", "=", "{", "}", "// key is module name, value is path", "while", "(", "toParse", ".", "length", ")", "{", "let", "node", "=", "toParse", ".", "pop", "(", ")", "if", "(", "node", ".", "children", ")", "for", "(", "let", "n", "of", "node", ".", "children", ")", "toParse", ".", "push", "(", "n", ")", "if", "(", "!", "node", ".", "scripts", ")", "continue", "for", "(", "let", "entry", "of", "node", ".", "scripts", ")", "{", "let", "moduleName", "=", "camelcase", "(", "path", ".", "parse", "(", "entry", ".", "source", ")", ".", "name", ")", "lookup", "[", "moduleName", "]", "=", "entry", ".", "source", "entry", ".", "module", "=", "moduleName", "}", "}", "return", "lookup", "}" ]
iterate over a substrate model, resolving all script paths
[ "iterate", "over", "a", "substrate", "model", "resolving", "all", "script", "paths" ]
7cae41956a2926f5dfe8bd496a50a1a5094a59e3
https://github.com/mreinstein/substrate-build/blob/7cae41956a2926f5dfe8bd496a50a1a5094a59e3/index.js#L78-L100
40,057
mreinstein/substrate-build
index.js
compileModel
async function compileModel (projectPath, model) { await copyExternalScripts(projectPath, model) deInlineScripts(projectPath, model) const lookup = resolveScriptPaths(projectPath, model) let imports = '' for (let moduleName in lookup) { let p = path.isAbsolute(lookup[moduleName]) ? lookup[moduleName] : `./${path.normalize(lookup[moduleName])}` imports += `import ${moduleName} from '${p}'\n` } const pre = JSON.stringify(model, null, 2) let post = pre for (let moduleName in lookup) post = replaceAll(post, moduleName) return `import substrate from 'substrate' // imports generated by the compiler ${imports} const dom = document.createElement('div') dom.id = 'myapp' document.body.appendChild(dom) const model = ${post} const app = substrate({ dom, node: model.rootNode, registry: model.registry })` }
javascript
async function compileModel (projectPath, model) { await copyExternalScripts(projectPath, model) deInlineScripts(projectPath, model) const lookup = resolveScriptPaths(projectPath, model) let imports = '' for (let moduleName in lookup) { let p = path.isAbsolute(lookup[moduleName]) ? lookup[moduleName] : `./${path.normalize(lookup[moduleName])}` imports += `import ${moduleName} from '${p}'\n` } const pre = JSON.stringify(model, null, 2) let post = pre for (let moduleName in lookup) post = replaceAll(post, moduleName) return `import substrate from 'substrate' // imports generated by the compiler ${imports} const dom = document.createElement('div') dom.id = 'myapp' document.body.appendChild(dom) const model = ${post} const app = substrate({ dom, node: model.rootNode, registry: model.registry })` }
[ "async", "function", "compileModel", "(", "projectPath", ",", "model", ")", "{", "await", "copyExternalScripts", "(", "projectPath", ",", "model", ")", "deInlineScripts", "(", "projectPath", ",", "model", ")", "const", "lookup", "=", "resolveScriptPaths", "(", "projectPath", ",", "model", ")", "let", "imports", "=", "''", "for", "(", "let", "moduleName", "in", "lookup", ")", "{", "let", "p", "=", "path", ".", "isAbsolute", "(", "lookup", "[", "moduleName", "]", ")", "?", "lookup", "[", "moduleName", "]", ":", "`", "${", "path", ".", "normalize", "(", "lookup", "[", "moduleName", "]", ")", "}", "`", "imports", "+=", "`", "${", "moduleName", "}", "${", "p", "}", "\\n", "`", "}", "const", "pre", "=", "JSON", ".", "stringify", "(", "model", ",", "null", ",", "2", ")", "let", "post", "=", "pre", "for", "(", "let", "moduleName", "in", "lookup", ")", "post", "=", "replaceAll", "(", "post", ",", "moduleName", ")", "return", "`", "${", "imports", "}", "${", "post", "}", "`", "}" ]
generate a build suitable for bundling by staticly compiling an input json model
[ "generate", "a", "build", "suitable", "for", "bundling", "by", "staticly", "compiling", "an", "input", "json", "model" ]
7cae41956a2926f5dfe8bd496a50a1a5094a59e3
https://github.com/mreinstein/substrate-build/blob/7cae41956a2926f5dfe8bd496a50a1a5094a59e3/index.js#L130-L160
40,058
bicarbon8/PhantomFunctionalTest
dist/pft-module.js
function () { var s = null; if (PFT.tester._suites.length > 0) { s = PFT.tester._suites[PFT.tester._suites.length - 1]; } return s; }
javascript
function () { var s = null; if (PFT.tester._suites.length > 0) { s = PFT.tester._suites[PFT.tester._suites.length - 1]; } return s; }
[ "function", "(", ")", "{", "var", "s", "=", "null", ";", "if", "(", "PFT", ".", "tester", ".", "_suites", ".", "length", ">", "0", ")", "{", "s", "=", "PFT", ".", "tester", ".", "_suites", "[", "PFT", ".", "tester", ".", "_suites", ".", "length", "-", "1", "]", ";", "}", "return", "s", ";", "}" ]
function will get the current suite in use. this is primarily used for associating a suite with a test
[ "function", "will", "get", "the", "current", "suite", "in", "use", ".", "this", "is", "primarily", "used", "for", "associating", "a", "suite", "with", "a", "test" ]
dcfd01cabac30f05d2c380f06103c81eaf0594f9
https://github.com/bicarbon8/PhantomFunctionalTest/blob/dcfd01cabac30f05d2c380f06103c81eaf0594f9/dist/pft-module.js#L942-L948
40,059
bicarbon8/PhantomFunctionalTest
dist/pft-module.js
function () { var t = null; if (PFT.tester._tests.length > 0) { t = PFT.tester._tests[PFT.tester._tests.length - 1]; } return t; }
javascript
function () { var t = null; if (PFT.tester._tests.length > 0) { t = PFT.tester._tests[PFT.tester._tests.length - 1]; } return t; }
[ "function", "(", ")", "{", "var", "t", "=", "null", ";", "if", "(", "PFT", ".", "tester", ".", "_tests", ".", "length", ">", "0", ")", "{", "t", "=", "PFT", ".", "tester", ".", "_tests", "[", "PFT", ".", "tester", ".", "_tests", ".", "length", "-", "1", "]", ";", "}", "return", "t", ";", "}" ]
function will get the currently executing test
[ "function", "will", "get", "the", "currently", "executing", "test" ]
dcfd01cabac30f05d2c380f06103c81eaf0594f9
https://github.com/bicarbon8/PhantomFunctionalTest/blob/dcfd01cabac30f05d2c380f06103c81eaf0594f9/dist/pft-module.js#L953-L959
40,060
bicarbon8/PhantomFunctionalTest
dist/pft-module.js
function (testObj) { var duration = PFT.convertMsToHumanReadable(new Date().getTime() - testObj.startTime); testObj.duration = duration; var suite = ""; if (testObj.suite) { if (testObj.suite.name) { suite = testObj.suite.name + " - "; } } var msg = "Completed: '" + suite + testObj.name + "' in " + duration + " with " + testObj.passes + " passes, " + testObj.failures.length + " failures, " + testObj.errors.length + " errors."; PFT.logger.log(PFT.logger.TEST, msg); PFT.tester.onTestCompleted({ test: testObj }); try { testObj.page.close(); } catch (e) { PFT.warn(e); } PFT.tester.remainingCount--; PFT.tester.exitIfDoneTesting(); }
javascript
function (testObj) { var duration = PFT.convertMsToHumanReadable(new Date().getTime() - testObj.startTime); testObj.duration = duration; var suite = ""; if (testObj.suite) { if (testObj.suite.name) { suite = testObj.suite.name + " - "; } } var msg = "Completed: '" + suite + testObj.name + "' in " + duration + " with " + testObj.passes + " passes, " + testObj.failures.length + " failures, " + testObj.errors.length + " errors."; PFT.logger.log(PFT.logger.TEST, msg); PFT.tester.onTestCompleted({ test: testObj }); try { testObj.page.close(); } catch (e) { PFT.warn(e); } PFT.tester.remainingCount--; PFT.tester.exitIfDoneTesting(); }
[ "function", "(", "testObj", ")", "{", "var", "duration", "=", "PFT", ".", "convertMsToHumanReadable", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "testObj", ".", "startTime", ")", ";", "testObj", ".", "duration", "=", "duration", ";", "var", "suite", "=", "\"\"", ";", "if", "(", "testObj", ".", "suite", ")", "{", "if", "(", "testObj", ".", "suite", ".", "name", ")", "{", "suite", "=", "testObj", ".", "suite", ".", "name", "+", "\" - \"", ";", "}", "}", "var", "msg", "=", "\"Completed: '\"", "+", "suite", "+", "testObj", ".", "name", "+", "\"' in \"", "+", "duration", "+", "\" with \"", "+", "testObj", ".", "passes", "+", "\" passes, \"", "+", "testObj", ".", "failures", ".", "length", "+", "\" failures, \"", "+", "testObj", ".", "errors", ".", "length", "+", "\" errors.\"", ";", "PFT", ".", "logger", ".", "log", "(", "PFT", ".", "logger", ".", "TEST", ",", "msg", ")", ";", "PFT", ".", "tester", ".", "onTestCompleted", "(", "{", "test", ":", "testObj", "}", ")", ";", "try", "{", "testObj", ".", "page", ".", "close", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "PFT", ".", "warn", "(", "e", ")", ";", "}", "PFT", ".", "tester", ".", "remainingCount", "--", ";", "PFT", ".", "tester", ".", "exitIfDoneTesting", "(", ")", ";", "}" ]
function will close out the currently running test objects, but any async tasks will continue running.
[ "function", "will", "close", "out", "the", "currently", "running", "test", "objects", "but", "any", "async", "tasks", "will", "continue", "running", "." ]
dcfd01cabac30f05d2c380f06103c81eaf0594f9
https://github.com/bicarbon8/PhantomFunctionalTest/blob/dcfd01cabac30f05d2c380f06103c81eaf0594f9/dist/pft-module.js#L1059-L1079
40,061
bicarbon8/PhantomFunctionalTest
dist/pft-module.js
function (msg) { // restart MutexJs in case exception caused fatal javascript halt MutexJs.recover(); // unexpected exception so log in errors and move to next var t = PFT.tester.currentTest(); t.errors.push(msg); PFT.tester.onError({ test: t, message: msg }); PFT.tester.closeTest(t); // move to next test MutexJs.release(t.runUnlockId); }
javascript
function (msg) { // restart MutexJs in case exception caused fatal javascript halt MutexJs.recover(); // unexpected exception so log in errors and move to next var t = PFT.tester.currentTest(); t.errors.push(msg); PFT.tester.onError({ test: t, message: msg }); PFT.tester.closeTest(t); // move to next test MutexJs.release(t.runUnlockId); }
[ "function", "(", "msg", ")", "{", "// restart MutexJs in case exception caused fatal javascript halt", "MutexJs", ".", "recover", "(", ")", ";", "// unexpected exception so log in errors and move to next", "var", "t", "=", "PFT", ".", "tester", ".", "currentTest", "(", ")", ";", "t", ".", "errors", ".", "push", "(", "msg", ")", ";", "PFT", ".", "tester", ".", "onError", "(", "{", "test", ":", "t", ",", "message", ":", "msg", "}", ")", ";", "PFT", ".", "tester", ".", "closeTest", "(", "t", ")", ";", "// move to next test", "MutexJs", ".", "release", "(", "t", ".", "runUnlockId", ")", ";", "}" ]
function provides handling for expected exceptions thrown to halt the currently running script. typically this will be called from the phantom.onError function if tests are running. @ignore
[ "function", "provides", "handling", "for", "expected", "exceptions", "thrown", "to", "halt", "the", "currently", "running", "script", ".", "typically", "this", "will", "be", "called", "from", "the", "phantom", ".", "onError", "function", "if", "tests", "are", "running", "." ]
dcfd01cabac30f05d2c380f06103c81eaf0594f9
https://github.com/bicarbon8/PhantomFunctionalTest/blob/dcfd01cabac30f05d2c380f06103c81eaf0594f9/dist/pft-module.js#L1191-L1203
40,062
unicornjs/unicornjs
core-services/uBroker/index.js
uBrokersManager
function uBrokersManager(){ var listenClient = redis.createClient(config.redis[0].port, config.redis[0].server); listenClient.on("error", function (err) { console.log("Redis listen error " + err); }); listenClient.on('message', function(channel, message) { client.get('uBrokers', function(err, reply) { uBrokers = JSON.parse(reply); }); }); listenClient.subscribe('uBrokersChannel'); }
javascript
function uBrokersManager(){ var listenClient = redis.createClient(config.redis[0].port, config.redis[0].server); listenClient.on("error", function (err) { console.log("Redis listen error " + err); }); listenClient.on('message', function(channel, message) { client.get('uBrokers', function(err, reply) { uBrokers = JSON.parse(reply); }); }); listenClient.subscribe('uBrokersChannel'); }
[ "function", "uBrokersManager", "(", ")", "{", "var", "listenClient", "=", "redis", ".", "createClient", "(", "config", ".", "redis", "[", "0", "]", ".", "port", ",", "config", ".", "redis", "[", "0", "]", ".", "server", ")", ";", "listenClient", ".", "on", "(", "\"error\"", ",", "function", "(", "err", ")", "{", "console", ".", "log", "(", "\"Redis listen error \"", "+", "err", ")", ";", "}", ")", ";", "listenClient", ".", "on", "(", "'message'", ",", "function", "(", "channel", ",", "message", ")", "{", "client", ".", "get", "(", "'uBrokers'", ",", "function", "(", "err", ",", "reply", ")", "{", "uBrokers", "=", "JSON", ".", "parse", "(", "reply", ")", ";", "}", ")", ";", "}", ")", ";", "listenClient", ".", "subscribe", "(", "'uBrokersChannel'", ")", ";", "}" ]
uBroker Manager Handler the negotiation of messages between uBrokers
[ "uBroker", "Manager", "Handler", "the", "negotiation", "of", "messages", "between", "uBrokers" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/core-services/uBroker/index.js#L141-L155
40,063
unicornjs/unicornjs
core-services/uBroker/index.js
selectService
function selectService (service){ if(typeof(uServices[service]) !== 'undefined'){ if (uServices[service].length !== 0 ) { var uService = uServices[service], //array activeuService = uService[0]; // the first service should be active but if is not, should look for an active one if (activeuService.status == 0) { var foundOne = false; for ( var i = 0 ; i < uService.length ; i++ ){ if ( foundOne == false && uService[i].status == 1 ) { activeuService = uService[i]; foundOne = true; } } //if there is not active service just stay whith the first one } activeuService.status = 0; //change state to busy uService.shift(); //take the service out of the list uService.push(activeuService); // pushing the service at the end of the list uService[0].status = 1; //activate other service //save the new uServices uServices[service] = uService; // changing the variable on redis client.set('uServices', JSON.stringify(uServices)); // Publish that it did an update client.publish('uServicesChannel', 'UPDATE'); return activeuService; } else { //not services availables console.log('Not services %s available', service); //return error to broker return 'Not services '+service+' available' } } else { return "not services with name "+service; // return an error cause there are no services with that name } }
javascript
function selectService (service){ if(typeof(uServices[service]) !== 'undefined'){ if (uServices[service].length !== 0 ) { var uService = uServices[service], //array activeuService = uService[0]; // the first service should be active but if is not, should look for an active one if (activeuService.status == 0) { var foundOne = false; for ( var i = 0 ; i < uService.length ; i++ ){ if ( foundOne == false && uService[i].status == 1 ) { activeuService = uService[i]; foundOne = true; } } //if there is not active service just stay whith the first one } activeuService.status = 0; //change state to busy uService.shift(); //take the service out of the list uService.push(activeuService); // pushing the service at the end of the list uService[0].status = 1; //activate other service //save the new uServices uServices[service] = uService; // changing the variable on redis client.set('uServices', JSON.stringify(uServices)); // Publish that it did an update client.publish('uServicesChannel', 'UPDATE'); return activeuService; } else { //not services availables console.log('Not services %s available', service); //return error to broker return 'Not services '+service+' available' } } else { return "not services with name "+service; // return an error cause there are no services with that name } }
[ "function", "selectService", "(", "service", ")", "{", "if", "(", "typeof", "(", "uServices", "[", "service", "]", ")", "!==", "'undefined'", ")", "{", "if", "(", "uServices", "[", "service", "]", ".", "length", "!==", "0", ")", "{", "var", "uService", "=", "uServices", "[", "service", "]", ",", "//array", "activeuService", "=", "uService", "[", "0", "]", ";", "// the first service should be active but if is not, should look for an active one", "if", "(", "activeuService", ".", "status", "==", "0", ")", "{", "var", "foundOne", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "uService", ".", "length", ";", "i", "++", ")", "{", "if", "(", "foundOne", "==", "false", "&&", "uService", "[", "i", "]", ".", "status", "==", "1", ")", "{", "activeuService", "=", "uService", "[", "i", "]", ";", "foundOne", "=", "true", ";", "}", "}", "//if there is not active service just stay whith the first one", "}", "activeuService", ".", "status", "=", "0", ";", "//change state to busy", "uService", ".", "shift", "(", ")", ";", "//take the service out of the list", "uService", ".", "push", "(", "activeuService", ")", ";", "// pushing the service at the end of the list", "uService", "[", "0", "]", ".", "status", "=", "1", ";", "//activate other service", "//save the new uServices", "uServices", "[", "service", "]", "=", "uService", ";", "// changing the variable on redis", "client", ".", "set", "(", "'uServices'", ",", "JSON", ".", "stringify", "(", "uServices", ")", ")", ";", "// Publish that it did an update", "client", ".", "publish", "(", "'uServicesChannel'", ",", "'UPDATE'", ")", ";", "return", "activeuService", ";", "}", "else", "{", "//not services availables", "console", ".", "log", "(", "'Not services %s available'", ",", "service", ")", ";", "//return error to broker", "return", "'Not services '", "+", "service", "+", "' available'", "}", "}", "else", "{", "return", "\"not services with name \"", "+", "service", ";", "// return an error cause there are no services with that name", "}", "}" ]
Select a service to assign a job and activate the next service @param service @returns {*}
[ "Select", "a", "service", "to", "assign", "a", "job", "and", "activate", "the", "next", "service" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/core-services/uBroker/index.js#L162-L207
40,064
unicornjs/unicornjs
core-services/uBroker/index.js
addService
function addService(service, serviceObject){ client.get('uServices', function(err, reply) { if (reply == null){ //extend this object //add a key with service name and value service channel //this is the first service i should activate it var newObjectToPush = JSON.parse('{"' + service + '": []}');//found a fancy way to make this serviceObject.status = 1; newObjectToPush[service].push(serviceObject); extend(uServices, newObjectToPush); setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } else { uServices = JSON.parse(reply); if (typeof(uServices[service]) !== 'undefined') { var uService = uServices[service]; uService.push(serviceObject); //save the new uServices uServices[service] = uService; setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } else { //extend this object //add a key with service name and value service channel var stringObject = '{"' + service + '": []}'; //found a fancy way to make this var objectToPush = JSON.parse(stringObject); objectToPush[service].push(serviceObject); extend(uServices, objectToPush); setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } } }); }
javascript
function addService(service, serviceObject){ client.get('uServices', function(err, reply) { if (reply == null){ //extend this object //add a key with service name and value service channel //this is the first service i should activate it var newObjectToPush = JSON.parse('{"' + service + '": []}');//found a fancy way to make this serviceObject.status = 1; newObjectToPush[service].push(serviceObject); extend(uServices, newObjectToPush); setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } else { uServices = JSON.parse(reply); if (typeof(uServices[service]) !== 'undefined') { var uService = uServices[service]; uService.push(serviceObject); //save the new uServices uServices[service] = uService; setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } else { //extend this object //add a key with service name and value service channel var stringObject = '{"' + service + '": []}'; //found a fancy way to make this var objectToPush = JSON.parse(stringObject); objectToPush[service].push(serviceObject); extend(uServices, objectToPush); setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE') } } }); }
[ "function", "addService", "(", "service", ",", "serviceObject", ")", "{", "client", ".", "get", "(", "'uServices'", ",", "function", "(", "err", ",", "reply", ")", "{", "if", "(", "reply", "==", "null", ")", "{", "//extend this object", "//add a key with service name and value service channel", "//this is the first service i should activate it", "var", "newObjectToPush", "=", "JSON", ".", "parse", "(", "'{\"'", "+", "service", "+", "'\": []}'", ")", ";", "//found a fancy way to make this", "serviceObject", ".", "status", "=", "1", ";", "newObjectToPush", "[", "service", "]", ".", "push", "(", "serviceObject", ")", ";", "extend", "(", "uServices", ",", "newObjectToPush", ")", ";", "setAndPublish", "(", "'uServices'", ",", "uServices", ",", "'uServicesChannel'", ",", "'UPDATE'", ")", "}", "else", "{", "uServices", "=", "JSON", ".", "parse", "(", "reply", ")", ";", "if", "(", "typeof", "(", "uServices", "[", "service", "]", ")", "!==", "'undefined'", ")", "{", "var", "uService", "=", "uServices", "[", "service", "]", ";", "uService", ".", "push", "(", "serviceObject", ")", ";", "//save the new uServices", "uServices", "[", "service", "]", "=", "uService", ";", "setAndPublish", "(", "'uServices'", ",", "uServices", ",", "'uServicesChannel'", ",", "'UPDATE'", ")", "}", "else", "{", "//extend this object", "//add a key with service name and value service channel", "var", "stringObject", "=", "'{\"'", "+", "service", "+", "'\": []}'", ";", "//found a fancy way to make this", "var", "objectToPush", "=", "JSON", ".", "parse", "(", "stringObject", ")", ";", "objectToPush", "[", "service", "]", ".", "push", "(", "serviceObject", ")", ";", "extend", "(", "uServices", ",", "objectToPush", ")", ";", "setAndPublish", "(", "'uServices'", ",", "uServices", ",", "'uServicesChannel'", ",", "'UPDATE'", ")", "}", "}", "}", ")", ";", "}" ]
Receive a service name and an object and stored it redis @addService @param service {String} @param serviceObject {Object}
[ "Receive", "a", "service", "name", "and", "an", "object", "and", "stored", "it", "redis" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/core-services/uBroker/index.js#L215-L254
40,065
unicornjs/unicornjs
core-services/uBroker/index.js
setAndPublish
function setAndPublish(variableName, object, channel, option){ client.set(variableName, JSON.stringify(object)); // Publish that it did an update client.publish(channel, option); }
javascript
function setAndPublish(variableName, object, channel, option){ client.set(variableName, JSON.stringify(object)); // Publish that it did an update client.publish(channel, option); }
[ "function", "setAndPublish", "(", "variableName", ",", "object", ",", "channel", ",", "option", ")", "{", "client", ".", "set", "(", "variableName", ",", "JSON", ".", "stringify", "(", "object", ")", ")", ";", "// Publish that it did an update", "client", ".", "publish", "(", "channel", ",", "option", ")", ";", "}" ]
Set a variable on redis @param variableName @param object @param channel @param option
[ "Set", "a", "variable", "on", "redis" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/core-services/uBroker/index.js#L263-L268
40,066
Bill4Time/mongo-fast-join
Join.js
pushOrPut
function pushOrPut (currentBin, index) { var temp = currentBin; if (Array.isArray(currentBin)) { if (currentBin.indexOf(index) === -1) { currentBin.push(index);//only add if this is a unique index to prevent dup'ing indexes, and associations } } else { temp = [index]; } return temp; }
javascript
function pushOrPut (currentBin, index) { var temp = currentBin; if (Array.isArray(currentBin)) { if (currentBin.indexOf(index) === -1) { currentBin.push(index);//only add if this is a unique index to prevent dup'ing indexes, and associations } } else { temp = [index]; } return temp; }
[ "function", "pushOrPut", "(", "currentBin", ",", "index", ")", "{", "var", "temp", "=", "currentBin", ";", "if", "(", "Array", ".", "isArray", "(", "currentBin", ")", ")", "{", "if", "(", "currentBin", ".", "indexOf", "(", "index", ")", "===", "-", "1", ")", "{", "currentBin", ".", "push", "(", "index", ")", ";", "//only add if this is a unique index to prevent dup'ing indexes, and associations", "}", "}", "else", "{", "temp", "=", "[", "index", "]", ";", "}", "return", "temp", ";", "}" ]
Put a new index value into the array at the given bin, making a new array if there is none. @param currentBin The location in which to put the array @param index the index value to put in the array @returns the newly created array if there was one created. Must be assigned into the correct spot
[ "Put", "a", "new", "index", "value", "into", "the", "array", "at", "the", "given", "bin", "making", "a", "new", "array", "if", "there", "is", "none", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L111-L121
40,067
Bill4Time/mongo-fast-join
Join.js
buildHashTableIndices
function buildHashTableIndices (bin, leftValue, index, accessors, rightKeys) { var i, length = accessors.length, lastBin, val; for (i = 0; i < length; i += 1) { val = accessors[i](leftValue); if (typeof val === "undefined") { return; } if (i + 1 === length) { if (Array.isArray(val)) { //for each value in val, put that key in val.forEach(function (subValue) { var boot = putKeyInBin(bin, subValue); bin[subValue] = pushOrPut(boot, index); bin[subValue].$val = subValue; }); } else { bin[val] = pushOrPut(bin[val], index); bin[val].$val = val; } } else if (Array.isArray(val)) { lastBin = bin; val.forEach(function (subDocumentValue) {//sub vals are for basically supposed to be payment ids var rightKeySubset = rightKeys.slice(i + 1); if (isNullOrUndefined(bin[subDocumentValue])) { bin[subDocumentValue] = {$val: subDocumentValue};//Store $val to maintain the data type } buildHashTableIndices(bin[subDocumentValue], leftValue, index, accessors.slice(i + 1), rightKeySubset); }); return;//don't go through the rest of the accessors, this recursion will take care of those } else { bin = putKeyInBin(bin, val); } } }
javascript
function buildHashTableIndices (bin, leftValue, index, accessors, rightKeys) { var i, length = accessors.length, lastBin, val; for (i = 0; i < length; i += 1) { val = accessors[i](leftValue); if (typeof val === "undefined") { return; } if (i + 1 === length) { if (Array.isArray(val)) { //for each value in val, put that key in val.forEach(function (subValue) { var boot = putKeyInBin(bin, subValue); bin[subValue] = pushOrPut(boot, index); bin[subValue].$val = subValue; }); } else { bin[val] = pushOrPut(bin[val], index); bin[val].$val = val; } } else if (Array.isArray(val)) { lastBin = bin; val.forEach(function (subDocumentValue) {//sub vals are for basically supposed to be payment ids var rightKeySubset = rightKeys.slice(i + 1); if (isNullOrUndefined(bin[subDocumentValue])) { bin[subDocumentValue] = {$val: subDocumentValue};//Store $val to maintain the data type } buildHashTableIndices(bin[subDocumentValue], leftValue, index, accessors.slice(i + 1), rightKeySubset); }); return;//don't go through the rest of the accessors, this recursion will take care of those } else { bin = putKeyInBin(bin, val); } } }
[ "function", "buildHashTableIndices", "(", "bin", ",", "leftValue", ",", "index", ",", "accessors", ",", "rightKeys", ")", "{", "var", "i", ",", "length", "=", "accessors", ".", "length", ",", "lastBin", ",", "val", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "val", "=", "accessors", "[", "i", "]", "(", "leftValue", ")", ";", "if", "(", "typeof", "val", "===", "\"undefined\"", ")", "{", "return", ";", "}", "if", "(", "i", "+", "1", "===", "length", ")", "{", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "//for each value in val, put that key in", "val", ".", "forEach", "(", "function", "(", "subValue", ")", "{", "var", "boot", "=", "putKeyInBin", "(", "bin", ",", "subValue", ")", ";", "bin", "[", "subValue", "]", "=", "pushOrPut", "(", "boot", ",", "index", ")", ";", "bin", "[", "subValue", "]", ".", "$val", "=", "subValue", ";", "}", ")", ";", "}", "else", "{", "bin", "[", "val", "]", "=", "pushOrPut", "(", "bin", "[", "val", "]", ",", "index", ")", ";", "bin", "[", "val", "]", ".", "$val", "=", "val", ";", "}", "}", "else", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "lastBin", "=", "bin", ";", "val", ".", "forEach", "(", "function", "(", "subDocumentValue", ")", "{", "//sub vals are for basically supposed to be payment ids", "var", "rightKeySubset", "=", "rightKeys", ".", "slice", "(", "i", "+", "1", ")", ";", "if", "(", "isNullOrUndefined", "(", "bin", "[", "subDocumentValue", "]", ")", ")", "{", "bin", "[", "subDocumentValue", "]", "=", "{", "$val", ":", "subDocumentValue", "}", ";", "//Store $val to maintain the data type", "}", "buildHashTableIndices", "(", "bin", "[", "subDocumentValue", "]", ",", "leftValue", ",", "index", ",", "accessors", ".", "slice", "(", "i", "+", "1", ")", ",", "rightKeySubset", ")", ";", "}", ")", ";", "return", ";", "//don't go through the rest of the accessors, this recursion will take care of those", "}", "else", "{", "bin", "=", "putKeyInBin", "(", "bin", ",", "val", ")", ";", "}", "}", "}" ]
Create the hash table which maps unique left key combination to an array of numbers representing the indexes of the source data where those unique left key combinations were found. Use this map in the joining process to add join subdocuments to the source data. @param bin The bin object into which keys and indexes will be put @param leftValue the left document from which to retrieve key values @param index the index in the source data that the leftvalue lives at @param accessors The accessor functions which retrieve the value for each join key from the leftValue. @param rightKeys The keys in the right hand set which are being joined on
[ "Create", "the", "hash", "table", "which", "maps", "unique", "left", "key", "combination", "to", "an", "array", "of", "numbers", "representing", "the", "indexes", "of", "the", "source", "data", "where", "those", "unique", "left", "key", "combinations", "were", "found", ".", "Use", "this", "map", "in", "the", "joining", "process", "to", "add", "join", "subdocuments", "to", "the", "source", "data", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L135-L176
40,068
Bill4Time/mongo-fast-join
Join.js
buildQueriesFromHashBin
function buildQueriesFromHashBin (keyHashBin, rightKeys, level, valuePath, orQueries, inQueries) { var keys = Object.getOwnPropertyNames(keyHashBin), or; valuePath = valuePath || []; if (level === rightKeys.length) { or = {}; rightKeys.forEach(function (key, i) { inQueries[i].push(valuePath[i]); or[key] = valuePath[i]; }); orQueries.push(or); //start returning //take the value path and begin making objects out of it } else { keys.forEach(function (key) { if (key !== "$val") { var newPath = valuePath.slice(), value = keyHashBin[key].$val; newPath.push(value);//now have a copied array buildQueriesFromHashBin(keyHashBin[key], rightKeys, level + 1, newPath, orQueries, inQueries); } }); } }
javascript
function buildQueriesFromHashBin (keyHashBin, rightKeys, level, valuePath, orQueries, inQueries) { var keys = Object.getOwnPropertyNames(keyHashBin), or; valuePath = valuePath || []; if (level === rightKeys.length) { or = {}; rightKeys.forEach(function (key, i) { inQueries[i].push(valuePath[i]); or[key] = valuePath[i]; }); orQueries.push(or); //start returning //take the value path and begin making objects out of it } else { keys.forEach(function (key) { if (key !== "$val") { var newPath = valuePath.slice(), value = keyHashBin[key].$val; newPath.push(value);//now have a copied array buildQueriesFromHashBin(keyHashBin[key], rightKeys, level + 1, newPath, orQueries, inQueries); } }); } }
[ "function", "buildQueriesFromHashBin", "(", "keyHashBin", ",", "rightKeys", ",", "level", ",", "valuePath", ",", "orQueries", ",", "inQueries", ")", "{", "var", "keys", "=", "Object", ".", "getOwnPropertyNames", "(", "keyHashBin", ")", ",", "or", ";", "valuePath", "=", "valuePath", "||", "[", "]", ";", "if", "(", "level", "===", "rightKeys", ".", "length", ")", "{", "or", "=", "{", "}", ";", "rightKeys", ".", "forEach", "(", "function", "(", "key", ",", "i", ")", "{", "inQueries", "[", "i", "]", ".", "push", "(", "valuePath", "[", "i", "]", ")", ";", "or", "[", "key", "]", "=", "valuePath", "[", "i", "]", ";", "}", ")", ";", "orQueries", ".", "push", "(", "or", ")", ";", "//start returning", "//take the value path and begin making objects out of it", "}", "else", "{", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", "!==", "\"$val\"", ")", "{", "var", "newPath", "=", "valuePath", ".", "slice", "(", ")", ",", "value", "=", "keyHashBin", "[", "key", "]", ".", "$val", ";", "newPath", ".", "push", "(", "value", ")", ";", "//now have a copied array", "buildQueriesFromHashBin", "(", "keyHashBin", "[", "key", "]", ",", "rightKeys", ",", "level", "+", "1", ",", "newPath", ",", "orQueries", ",", "inQueries", ")", ";", "}", "}", ")", ";", "}", "}" ]
Build the in and or queries that will be used to query for the join documents. @param keyHashBin The bin to use to retrieve the query vals from @param rightKeys The keys which will exists in the join documents @param level The current level of recursion which will correspond to the accessor and the index of the right key @param valuePath The values that have been gathered so far. Ordinally corresponding to the right keys @param orQueries The total list of $or queries generated @param inQueries The total list of $in queries generated
[ "Build", "the", "in", "and", "or", "queries", "that", "will", "be", "used", "to", "query", "for", "the", "join", "documents", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L189-L216
40,069
Bill4Time/mongo-fast-join
Join.js
arrayJoin
function arrayJoin (results, args) { var srcDataArray = results,//use these results as the source of the join joinCollection = args.joinCollection,//This is the mongoDB.Collection to use to join on joinQuery = args.joinQuery, joinType = args.joinType || 'left', rightKeys = args.rightKeys || [args.rightKey],//Get the value of the key being joined upon newKey = args.newKey,//The new field onto which the joined document will be mapped callback = args.callback,//The callback to call at this level of the join length, i, subqueries, keyHashBin = {}, accessors = [], joinLookups = [], inQueries = [], leftKeys = args.leftKeys || [args.leftKey];//place to put incoming join results rightKeys.forEach(function () { inQueries.push([]); }); leftKeys.forEach(function (key) {//generate the accessors for each entry in the composite key accessors.push(getKeyValueAccessorFromKey(key)); }); length = results.length; //get the path first for (i = 0; i < length; i += 1) { buildHashTableIndices(keyHashBin, results[i], i, accessors, rightKeys, inQueries, joinLookups, {}); }//create the path buildQueriesFromHashBin(keyHashBin, rightKeys, 0, [], joinLookups, inQueries); if (!Array.isArray(srcDataArray)) { srcDataArray = [srcDataArray]; } subqueries = getSubqueries(inQueries, joinLookups, joinQuery, args.pageSize || 25, rightKeys);//example runSubqueries(subqueries, function (items) { var un; performJoining(srcDataArray, items, { rightKeyPropertyPaths: rightKeys, newKey: newKey, keyHashBin: keyHashBin }); if (joinType === "inner") { removeNonMatchesLeft(srcDataArray, newKey); } if (joinStack.length > 0) { arrayJoin(srcDataArray, joinStack.shift()); } else { callIfFunction(finalCallback, [un, srcDataArray]); } callIfFunction(callback, [un, srcDataArray]); }, joinCollection); }
javascript
function arrayJoin (results, args) { var srcDataArray = results,//use these results as the source of the join joinCollection = args.joinCollection,//This is the mongoDB.Collection to use to join on joinQuery = args.joinQuery, joinType = args.joinType || 'left', rightKeys = args.rightKeys || [args.rightKey],//Get the value of the key being joined upon newKey = args.newKey,//The new field onto which the joined document will be mapped callback = args.callback,//The callback to call at this level of the join length, i, subqueries, keyHashBin = {}, accessors = [], joinLookups = [], inQueries = [], leftKeys = args.leftKeys || [args.leftKey];//place to put incoming join results rightKeys.forEach(function () { inQueries.push([]); }); leftKeys.forEach(function (key) {//generate the accessors for each entry in the composite key accessors.push(getKeyValueAccessorFromKey(key)); }); length = results.length; //get the path first for (i = 0; i < length; i += 1) { buildHashTableIndices(keyHashBin, results[i], i, accessors, rightKeys, inQueries, joinLookups, {}); }//create the path buildQueriesFromHashBin(keyHashBin, rightKeys, 0, [], joinLookups, inQueries); if (!Array.isArray(srcDataArray)) { srcDataArray = [srcDataArray]; } subqueries = getSubqueries(inQueries, joinLookups, joinQuery, args.pageSize || 25, rightKeys);//example runSubqueries(subqueries, function (items) { var un; performJoining(srcDataArray, items, { rightKeyPropertyPaths: rightKeys, newKey: newKey, keyHashBin: keyHashBin }); if (joinType === "inner") { removeNonMatchesLeft(srcDataArray, newKey); } if (joinStack.length > 0) { arrayJoin(srcDataArray, joinStack.shift()); } else { callIfFunction(finalCallback, [un, srcDataArray]); } callIfFunction(callback, [un, srcDataArray]); }, joinCollection); }
[ "function", "arrayJoin", "(", "results", ",", "args", ")", "{", "var", "srcDataArray", "=", "results", ",", "//use these results as the source of the join", "joinCollection", "=", "args", ".", "joinCollection", ",", "//This is the mongoDB.Collection to use to join on", "joinQuery", "=", "args", ".", "joinQuery", ",", "joinType", "=", "args", ".", "joinType", "||", "'left'", ",", "rightKeys", "=", "args", ".", "rightKeys", "||", "[", "args", ".", "rightKey", "]", ",", "//Get the value of the key being joined upon", "newKey", "=", "args", ".", "newKey", ",", "//The new field onto which the joined document will be mapped", "callback", "=", "args", ".", "callback", ",", "//The callback to call at this level of the join", "length", ",", "i", ",", "subqueries", ",", "keyHashBin", "=", "{", "}", ",", "accessors", "=", "[", "]", ",", "joinLookups", "=", "[", "]", ",", "inQueries", "=", "[", "]", ",", "leftKeys", "=", "args", ".", "leftKeys", "||", "[", "args", ".", "leftKey", "]", ";", "//place to put incoming join results", "rightKeys", ".", "forEach", "(", "function", "(", ")", "{", "inQueries", ".", "push", "(", "[", "]", ")", ";", "}", ")", ";", "leftKeys", ".", "forEach", "(", "function", "(", "key", ")", "{", "//generate the accessors for each entry in the composite key", "accessors", ".", "push", "(", "getKeyValueAccessorFromKey", "(", "key", ")", ")", ";", "}", ")", ";", "length", "=", "results", ".", "length", ";", "//get the path first", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "buildHashTableIndices", "(", "keyHashBin", ",", "results", "[", "i", "]", ",", "i", ",", "accessors", ",", "rightKeys", ",", "inQueries", ",", "joinLookups", ",", "{", "}", ")", ";", "}", "//create the path", "buildQueriesFromHashBin", "(", "keyHashBin", ",", "rightKeys", ",", "0", ",", "[", "]", ",", "joinLookups", ",", "inQueries", ")", ";", "if", "(", "!", "Array", ".", "isArray", "(", "srcDataArray", ")", ")", "{", "srcDataArray", "=", "[", "srcDataArray", "]", ";", "}", "subqueries", "=", "getSubqueries", "(", "inQueries", ",", "joinLookups", ",", "joinQuery", ",", "args", ".", "pageSize", "||", "25", ",", "rightKeys", ")", ";", "//example", "runSubqueries", "(", "subqueries", ",", "function", "(", "items", ")", "{", "var", "un", ";", "performJoining", "(", "srcDataArray", ",", "items", ",", "{", "rightKeyPropertyPaths", ":", "rightKeys", ",", "newKey", ":", "newKey", ",", "keyHashBin", ":", "keyHashBin", "}", ")", ";", "if", "(", "joinType", "===", "\"inner\"", ")", "{", "removeNonMatchesLeft", "(", "srcDataArray", ",", "newKey", ")", ";", "}", "if", "(", "joinStack", ".", "length", ">", "0", ")", "{", "arrayJoin", "(", "srcDataArray", ",", "joinStack", ".", "shift", "(", ")", ")", ";", "}", "else", "{", "callIfFunction", "(", "finalCallback", ",", "[", "un", ",", "srcDataArray", "]", ")", ";", "}", "callIfFunction", "(", "callback", ",", "[", "un", ",", "srcDataArray", "]", ")", ";", "}", ",", "joinCollection", ")", ";", "}" ]
Begin the joining process by compiling some data and performing a query for the objects to be joined. @param results The results of the previous join or query @param args The user supplied arguments which will configure this join
[ "Begin", "the", "joining", "process", "by", "compiling", "some", "data", "and", "performing", "a", "query", "for", "the", "objects", "to", "be", "joined", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L225-L285
40,070
Bill4Time/mongo-fast-join
Join.js
getSubqueries
function getSubqueries (inQueries, orQueries, otherQuery, pageSize, rightKeys) { var subqueries = [], numberOfChunks, i, inQuery, orQuery, queryArray, from, to; // this is a stupid way to turn numbers into 1 numberOfChunks = (orQueries.length / pageSize) + (!!(orQueries.length % pageSize)); for (i = 0; i < numberOfChunks; i += 1) { inQuery = {}; from = i * pageSize; to = from + pageSize; rightKeys.forEach(function (key, index) { inQuery[rightKeys[index]] = {$in: inQueries[index].slice(from, to)}; }); orQuery = { $or: orQueries.slice(from, to)}; queryArray = [ { $match: inQuery }, { $match: orQuery } ]; if(otherQuery) { queryArray.push({ $match: otherQuery }); //Push this to the end on the assumption that the join properties will be indexed, and the arbitrary //filter properties won't be indexed. } subqueries.push(queryArray); } return subqueries; }
javascript
function getSubqueries (inQueries, orQueries, otherQuery, pageSize, rightKeys) { var subqueries = [], numberOfChunks, i, inQuery, orQuery, queryArray, from, to; // this is a stupid way to turn numbers into 1 numberOfChunks = (orQueries.length / pageSize) + (!!(orQueries.length % pageSize)); for (i = 0; i < numberOfChunks; i += 1) { inQuery = {}; from = i * pageSize; to = from + pageSize; rightKeys.forEach(function (key, index) { inQuery[rightKeys[index]] = {$in: inQueries[index].slice(from, to)}; }); orQuery = { $or: orQueries.slice(from, to)}; queryArray = [ { $match: inQuery }, { $match: orQuery } ]; if(otherQuery) { queryArray.push({ $match: otherQuery }); //Push this to the end on the assumption that the join properties will be indexed, and the arbitrary //filter properties won't be indexed. } subqueries.push(queryArray); } return subqueries; }
[ "function", "getSubqueries", "(", "inQueries", ",", "orQueries", ",", "otherQuery", ",", "pageSize", ",", "rightKeys", ")", "{", "var", "subqueries", "=", "[", "]", ",", "numberOfChunks", ",", "i", ",", "inQuery", ",", "orQuery", ",", "queryArray", ",", "from", ",", "to", ";", "// this is a stupid way to turn numbers into 1", "numberOfChunks", "=", "(", "orQueries", ".", "length", "/", "pageSize", ")", "+", "(", "!", "!", "(", "orQueries", ".", "length", "%", "pageSize", ")", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "numberOfChunks", ";", "i", "+=", "1", ")", "{", "inQuery", "=", "{", "}", ";", "from", "=", "i", "*", "pageSize", ";", "to", "=", "from", "+", "pageSize", ";", "rightKeys", ".", "forEach", "(", "function", "(", "key", ",", "index", ")", "{", "inQuery", "[", "rightKeys", "[", "index", "]", "]", "=", "{", "$in", ":", "inQueries", "[", "index", "]", ".", "slice", "(", "from", ",", "to", ")", "}", ";", "}", ")", ";", "orQuery", "=", "{", "$or", ":", "orQueries", ".", "slice", "(", "from", ",", "to", ")", "}", ";", "queryArray", "=", "[", "{", "$match", ":", "inQuery", "}", ",", "{", "$match", ":", "orQuery", "}", "]", ";", "if", "(", "otherQuery", ")", "{", "queryArray", ".", "push", "(", "{", "$match", ":", "otherQuery", "}", ")", ";", "//Push this to the end on the assumption that the join properties will be indexed, and the arbitrary ", "//filter properties won't be indexed.", "}", "subqueries", ".", "push", "(", "queryArray", ")", ";", "}", "return", "subqueries", ";", "}" ]
Get the paged subqueries
[ "Get", "the", "paged", "subqueries" ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L295-L328
40,071
Bill4Time/mongo-fast-join
Join.js
runSubqueries
function runSubqueries (subQueries, callback, collection) { var i, responsesReceived = 0, length = subQueries.length, joinedSet = [];//The array where the results are going to get stuffed if (subQueries.length > 0) { for (i = 0; i < subQueries.length; i += 1) { collection.aggregate(subQueries[i], function (err, results) { joinedSet = joinedSet.concat(results); responsesReceived += 1; if (responsesReceived === length) { callback(joinedSet); } }); } } else { callback([]); } return joinedSet; }
javascript
function runSubqueries (subQueries, callback, collection) { var i, responsesReceived = 0, length = subQueries.length, joinedSet = [];//The array where the results are going to get stuffed if (subQueries.length > 0) { for (i = 0; i < subQueries.length; i += 1) { collection.aggregate(subQueries[i], function (err, results) { joinedSet = joinedSet.concat(results); responsesReceived += 1; if (responsesReceived === length) { callback(joinedSet); } }); } } else { callback([]); } return joinedSet; }
[ "function", "runSubqueries", "(", "subQueries", ",", "callback", ",", "collection", ")", "{", "var", "i", ",", "responsesReceived", "=", "0", ",", "length", "=", "subQueries", ".", "length", ",", "joinedSet", "=", "[", "]", ";", "//The array where the results are going to get stuffed", "if", "(", "subQueries", ".", "length", ">", "0", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "subQueries", ".", "length", ";", "i", "+=", "1", ")", "{", "collection", ".", "aggregate", "(", "subQueries", "[", "i", "]", ",", "function", "(", "err", ",", "results", ")", "{", "joinedSet", "=", "joinedSet", ".", "concat", "(", "results", ")", ";", "responsesReceived", "+=", "1", ";", "if", "(", "responsesReceived", "===", "length", ")", "{", "callback", "(", "joinedSet", ")", ";", "}", "}", ")", ";", "}", "}", "else", "{", "callback", "(", "[", "]", ")", ";", "}", "return", "joinedSet", ";", "}" ]
Run the sub queries individually, leveraging concurrency on the server for better performance.
[ "Run", "the", "sub", "queries", "individually", "leveraging", "concurrency", "on", "the", "server", "for", "better", "performance", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L335-L358
40,072
Bill4Time/mongo-fast-join
Join.js
getKeyValueAccessorFromKey
function getKeyValueAccessorFromKey (lookupValue) { var accessorFunction; if (typeof lookupValue === "string") { accessorFunction = function (resultValue) { var args = [resultValue]; args = args.concat(lookupValue.split(".")); return safeObjectAccess.apply(this, args); }; } else if (typeof lookupValue === "function") { accessorFunction = lookupValue; } return accessorFunction; }
javascript
function getKeyValueAccessorFromKey (lookupValue) { var accessorFunction; if (typeof lookupValue === "string") { accessorFunction = function (resultValue) { var args = [resultValue]; args = args.concat(lookupValue.split(".")); return safeObjectAccess.apply(this, args); }; } else if (typeof lookupValue === "function") { accessorFunction = lookupValue; } return accessorFunction; }
[ "function", "getKeyValueAccessorFromKey", "(", "lookupValue", ")", "{", "var", "accessorFunction", ";", "if", "(", "typeof", "lookupValue", "===", "\"string\"", ")", "{", "accessorFunction", "=", "function", "(", "resultValue", ")", "{", "var", "args", "=", "[", "resultValue", "]", ";", "args", "=", "args", ".", "concat", "(", "lookupValue", ".", "split", "(", "\".\"", ")", ")", ";", "return", "safeObjectAccess", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ";", "}", "else", "if", "(", "typeof", "lookupValue", "===", "\"function\"", ")", "{", "accessorFunction", "=", "lookupValue", ";", "}", "return", "accessorFunction", ";", "}" ]
Use the lookup value type to build an accessor function for each join key. The lookup algorithm respects dot notation. Currently supports strings and functions. @param lookupValue The key being used to lookup the value. @returns {Function} used to lookup value from an object
[ "Use", "the", "lookup", "value", "type", "to", "build", "an", "accessor", "function", "for", "each", "join", "key", ".", "The", "lookup", "algorithm", "respects", "dot", "notation", ".", "Currently", "supports", "strings", "and", "functions", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L368-L383
40,073
Bill4Time/mongo-fast-join
Join.js
performJoining
function performJoining (sourceData, joinSet, joinArgs) { var length = joinSet.length, i, rightKeyAccessors = []; joinArgs.rightKeyPropertyPaths.forEach(function (keyValue) { rightKeyAccessors.push(getKeyValueAccessorFromKey(keyValue)); }); for (i = 0; i < length; i += 1) { var rightRecord = joinSet[i], currentBin = joinArgs.keyHashBin; if (isNullOrUndefined(rightRecord)) { continue;//move onto the next, can't join on records that don't exist } //for each entry in the join set add it to the source document at the correct index rightKeyAccessors.forEach(function (accessor) { currentBin = currentBin[accessor(rightRecord)]; }); currentBin.forEach(function (sourceDataIndex) { var theObject = sourceData[sourceDataIndex][joinArgs.newKey]; if (isNullOrUndefined(theObject)) {//Handle adding multiple matches to the same sub document sourceData[sourceDataIndex][joinArgs.newKey] = rightRecord; } else if (Array.isArray(theObject)) { theObject.push(rightRecord); } else { sourceData[sourceDataIndex][joinArgs.newKey] = [theObject, rightRecord]; } }); } }
javascript
function performJoining (sourceData, joinSet, joinArgs) { var length = joinSet.length, i, rightKeyAccessors = []; joinArgs.rightKeyPropertyPaths.forEach(function (keyValue) { rightKeyAccessors.push(getKeyValueAccessorFromKey(keyValue)); }); for (i = 0; i < length; i += 1) { var rightRecord = joinSet[i], currentBin = joinArgs.keyHashBin; if (isNullOrUndefined(rightRecord)) { continue;//move onto the next, can't join on records that don't exist } //for each entry in the join set add it to the source document at the correct index rightKeyAccessors.forEach(function (accessor) { currentBin = currentBin[accessor(rightRecord)]; }); currentBin.forEach(function (sourceDataIndex) { var theObject = sourceData[sourceDataIndex][joinArgs.newKey]; if (isNullOrUndefined(theObject)) {//Handle adding multiple matches to the same sub document sourceData[sourceDataIndex][joinArgs.newKey] = rightRecord; } else if (Array.isArray(theObject)) { theObject.push(rightRecord); } else { sourceData[sourceDataIndex][joinArgs.newKey] = [theObject, rightRecord]; } }); } }
[ "function", "performJoining", "(", "sourceData", ",", "joinSet", ",", "joinArgs", ")", "{", "var", "length", "=", "joinSet", ".", "length", ",", "i", ",", "rightKeyAccessors", "=", "[", "]", ";", "joinArgs", ".", "rightKeyPropertyPaths", ".", "forEach", "(", "function", "(", "keyValue", ")", "{", "rightKeyAccessors", ".", "push", "(", "getKeyValueAccessorFromKey", "(", "keyValue", ")", ")", ";", "}", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "var", "rightRecord", "=", "joinSet", "[", "i", "]", ",", "currentBin", "=", "joinArgs", ".", "keyHashBin", ";", "if", "(", "isNullOrUndefined", "(", "rightRecord", ")", ")", "{", "continue", ";", "//move onto the next, can't join on records that don't exist", "}", "//for each entry in the join set add it to the source document at the correct index", "rightKeyAccessors", ".", "forEach", "(", "function", "(", "accessor", ")", "{", "currentBin", "=", "currentBin", "[", "accessor", "(", "rightRecord", ")", "]", ";", "}", ")", ";", "currentBin", ".", "forEach", "(", "function", "(", "sourceDataIndex", ")", "{", "var", "theObject", "=", "sourceData", "[", "sourceDataIndex", "]", "[", "joinArgs", ".", "newKey", "]", ";", "if", "(", "isNullOrUndefined", "(", "theObject", ")", ")", "{", "//Handle adding multiple matches to the same sub document", "sourceData", "[", "sourceDataIndex", "]", "[", "joinArgs", ".", "newKey", "]", "=", "rightRecord", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "theObject", ")", ")", "{", "theObject", ".", "push", "(", "rightRecord", ")", ";", "}", "else", "{", "sourceData", "[", "sourceDataIndex", "]", "[", "joinArgs", ".", "newKey", "]", "=", "[", "theObject", ",", "rightRecord", "]", ";", "}", "}", ")", ";", "}", "}" ]
Join the join set with the original query results at the new key. @param sourceData The original result set @param joinSet The results returned from the join query @param joinArgs The arguments used to join the source to the join set
[ "Join", "the", "join", "set", "with", "the", "original", "query", "results", "at", "the", "new", "key", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L393-L427
40,074
Bill4Time/mongo-fast-join
Join.js
safeObjectAccess
function safeObjectAccess () { var object = arguments[0], length = arguments.length, args = arguments, i, results, temp; if (!isNullOrUndefined(object)) { for (i = 1; i < length; i += 1) { if (Array.isArray(object)) {//if it's an array find the values from those results results = []; object.forEach(function (subDocument) { temp = safeObjectAccess.apply( safeObjectAccess, [subDocument].concat(Array.prototype.slice.apply(args, [i, length])) ); if (Array.isArray(temp)) { results = results.concat(temp); } else { results.push(temp); } }); break; } if (typeof object !== "undefined") { object = object[arguments[i]]; } else { break; } } } return results || object }
javascript
function safeObjectAccess () { var object = arguments[0], length = arguments.length, args = arguments, i, results, temp; if (!isNullOrUndefined(object)) { for (i = 1; i < length; i += 1) { if (Array.isArray(object)) {//if it's an array find the values from those results results = []; object.forEach(function (subDocument) { temp = safeObjectAccess.apply( safeObjectAccess, [subDocument].concat(Array.prototype.slice.apply(args, [i, length])) ); if (Array.isArray(temp)) { results = results.concat(temp); } else { results.push(temp); } }); break; } if (typeof object !== "undefined") { object = object[arguments[i]]; } else { break; } } } return results || object }
[ "function", "safeObjectAccess", "(", ")", "{", "var", "object", "=", "arguments", "[", "0", "]", ",", "length", "=", "arguments", ".", "length", ",", "args", "=", "arguments", ",", "i", ",", "results", ",", "temp", ";", "if", "(", "!", "isNullOrUndefined", "(", "object", ")", ")", "{", "for", "(", "i", "=", "1", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "if", "(", "Array", ".", "isArray", "(", "object", ")", ")", "{", "//if it's an array find the values from those results", "results", "=", "[", "]", ";", "object", ".", "forEach", "(", "function", "(", "subDocument", ")", "{", "temp", "=", "safeObjectAccess", ".", "apply", "(", "safeObjectAccess", ",", "[", "subDocument", "]", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "apply", "(", "args", ",", "[", "i", ",", "length", "]", ")", ")", ")", ";", "if", "(", "Array", ".", "isArray", "(", "temp", ")", ")", "{", "results", "=", "results", ".", "concat", "(", "temp", ")", ";", "}", "else", "{", "results", ".", "push", "(", "temp", ")", ";", "}", "}", ")", ";", "break", ";", "}", "if", "(", "typeof", "object", "!==", "\"undefined\"", ")", "{", "object", "=", "object", "[", "arguments", "[", "i", "]", "]", ";", "}", "else", "{", "break", ";", "}", "}", "}", "return", "results", "||", "object", "}" ]
Access an object without having to worry about "cannot access property '' of undefined" errors. Some extra, necessary and ugly convenience built in is that, if we encounter an array on the lookup path, we recursively drill down into each array value, returning the values discovered in each of those paths. It's kind of a headache, but necessary. @returns The value you were looking for or undefined
[ "Access", "an", "object", "without", "having", "to", "worry", "about", "cannot", "access", "property", "of", "undefined", "errors", ".", "Some", "extra", "necessary", "and", "ugly", "convenience", "built", "in", "is", "that", "if", "we", "encounter", "an", "array", "on", "the", "lookup", "path", "we", "recursively", "drill", "down", "into", "each", "array", "value", "returning", "the", "values", "discovered", "in", "each", "of", "those", "paths", ".", "It", "s", "kind", "of", "a", "headache", "but", "necessary", "." ]
3f9399a5b6523348dfcd501a34bcca9df380be71
https://github.com/Bill4Time/mongo-fast-join/blob/3f9399a5b6523348dfcd501a34bcca9df380be71/Join.js#L444-L479
40,075
mikolalysenko/bitmap-triangulate
ortho.js
takeCurve
function takeCurve(pred) { for(var i=0, n=horizon.length; i<n; ++i) { var c = horizon[i] if(pred(c)) { horizon[i] = horizon[n-1] horizon.pop() return c } } return null }
javascript
function takeCurve(pred) { for(var i=0, n=horizon.length; i<n; ++i) { var c = horizon[i] if(pred(c)) { horizon[i] = horizon[n-1] horizon.pop() return c } } return null }
[ "function", "takeCurve", "(", "pred", ")", "{", "for", "(", "var", "i", "=", "0", ",", "n", "=", "horizon", ".", "length", ";", "i", "<", "n", ";", "++", "i", ")", "{", "var", "c", "=", "horizon", "[", "i", "]", "if", "(", "pred", "(", "c", ")", ")", "{", "horizon", "[", "i", "]", "=", "horizon", "[", "n", "-", "1", "]", "horizon", ".", "pop", "(", ")", "return", "c", "}", "}", "return", "null", "}" ]
Finds and remove the first curve in horizon matching predicate
[ "Finds", "and", "remove", "the", "first", "curve", "in", "horizon", "matching", "predicate" ]
bdeaf0d4c988c9b26ec050deb786cdbdbe42054b
https://github.com/mikolalysenko/bitmap-triangulate/blob/bdeaf0d4c988c9b26ec050deb786cdbdbe42054b/ortho.js#L27-L37
40,076
mikolalysenko/bitmap-triangulate
ortho.js
reflexLeft
function reflexLeft(left, p, i0, i1) { for(var i=i1; i>i0; --i) { var a = left[i-1] var b = left[i] if(orient(a, b, p) <= 0) { cells.push([a[2], b[2], p[2]]) } else { return i } } return i0 }
javascript
function reflexLeft(left, p, i0, i1) { for(var i=i1; i>i0; --i) { var a = left[i-1] var b = left[i] if(orient(a, b, p) <= 0) { cells.push([a[2], b[2], p[2]]) } else { return i } } return i0 }
[ "function", "reflexLeft", "(", "left", ",", "p", ",", "i0", ",", "i1", ")", "{", "for", "(", "var", "i", "=", "i1", ";", "i", ">", "i0", ";", "--", "i", ")", "{", "var", "a", "=", "left", "[", "i", "-", "1", "]", "var", "b", "=", "left", "[", "i", "]", "if", "(", "orient", "(", "a", ",", "b", ",", "p", ")", "<=", "0", ")", "{", "cells", ".", "push", "(", "[", "a", "[", "2", "]", ",", "b", "[", "2", "]", ",", "p", "[", "2", "]", "]", ")", "}", "else", "{", "return", "i", "}", "}", "return", "i0", "}" ]
Remove all left reflex vertices starting from p
[ "Remove", "all", "left", "reflex", "vertices", "starting", "from", "p" ]
bdeaf0d4c988c9b26ec050deb786cdbdbe42054b
https://github.com/mikolalysenko/bitmap-triangulate/blob/bdeaf0d4c988c9b26ec050deb786cdbdbe42054b/ortho.js#L40-L51
40,077
mikolalysenko/bitmap-triangulate
ortho.js
reflexRight
function reflexRight(right, p, i0, i1) { for(var i=i0; i<i1; ++i) { var a = right[i] var b = right[i+1] if(orient(p, a, b) <= 0) { cells.push([p[2], a[2], b[2]]) } else { return i } } return i1 }
javascript
function reflexRight(right, p, i0, i1) { for(var i=i0; i<i1; ++i) { var a = right[i] var b = right[i+1] if(orient(p, a, b) <= 0) { cells.push([p[2], a[2], b[2]]) } else { return i } } return i1 }
[ "function", "reflexRight", "(", "right", ",", "p", ",", "i0", ",", "i1", ")", "{", "for", "(", "var", "i", "=", "i0", ";", "i", "<", "i1", ";", "++", "i", ")", "{", "var", "a", "=", "right", "[", "i", "]", "var", "b", "=", "right", "[", "i", "+", "1", "]", "if", "(", "orient", "(", "p", ",", "a", ",", "b", ")", "<=", "0", ")", "{", "cells", ".", "push", "(", "[", "p", "[", "2", "]", ",", "a", "[", "2", "]", ",", "b", "[", "2", "]", "]", ")", "}", "else", "{", "return", "i", "}", "}", "return", "i1", "}" ]
Remove all right reflex vertices starting from p
[ "Remove", "all", "right", "reflex", "vertices", "starting", "from", "p" ]
bdeaf0d4c988c9b26ec050deb786cdbdbe42054b
https://github.com/mikolalysenko/bitmap-triangulate/blob/bdeaf0d4c988c9b26ec050deb786cdbdbe42054b/ortho.js#L54-L65
40,078
mikolalysenko/bitmap-triangulate
ortho.js
mergeSegment
function mergeSegment(row, x0, x1) { //Take left and right curves out of horizon var left = takeCurve(function(c) { return c[c.length-1][0] === x0 }) var right = takeCurve(function(c) { return c[0][0] === x1 }) //Create new vertices var p0 = [x0,row,vertices.length] var p1 = [x1,row,vertices.length+1] vertices.push([x0, row], [x1,row]) //Merge chains var ncurve = [] if(left) { var l1 = reflexLeft(left, p0, 0, left.length-1) for(var i=0; i<=l1; ++i) { ncurve.push(left[i]) } } ncurve.push(p0, p1) if(right) { var r0 = reflexRight(right, p1, 0, right.length-1) for(var i=r0; i<right.length; ++i) { ncurve.push(right[i]) } } //Append new chain to horizon horizon.push(ncurve) }
javascript
function mergeSegment(row, x0, x1) { //Take left and right curves out of horizon var left = takeCurve(function(c) { return c[c.length-1][0] === x0 }) var right = takeCurve(function(c) { return c[0][0] === x1 }) //Create new vertices var p0 = [x0,row,vertices.length] var p1 = [x1,row,vertices.length+1] vertices.push([x0, row], [x1,row]) //Merge chains var ncurve = [] if(left) { var l1 = reflexLeft(left, p0, 0, left.length-1) for(var i=0; i<=l1; ++i) { ncurve.push(left[i]) } } ncurve.push(p0, p1) if(right) { var r0 = reflexRight(right, p1, 0, right.length-1) for(var i=r0; i<right.length; ++i) { ncurve.push(right[i]) } } //Append new chain to horizon horizon.push(ncurve) }
[ "function", "mergeSegment", "(", "row", ",", "x0", ",", "x1", ")", "{", "//Take left and right curves out of horizon", "var", "left", "=", "takeCurve", "(", "function", "(", "c", ")", "{", "return", "c", "[", "c", ".", "length", "-", "1", "]", "[", "0", "]", "===", "x0", "}", ")", "var", "right", "=", "takeCurve", "(", "function", "(", "c", ")", "{", "return", "c", "[", "0", "]", "[", "0", "]", "===", "x1", "}", ")", "//Create new vertices", "var", "p0", "=", "[", "x0", ",", "row", ",", "vertices", ".", "length", "]", "var", "p1", "=", "[", "x1", ",", "row", ",", "vertices", ".", "length", "+", "1", "]", "vertices", ".", "push", "(", "[", "x0", ",", "row", "]", ",", "[", "x1", ",", "row", "]", ")", "//Merge chains", "var", "ncurve", "=", "[", "]", "if", "(", "left", ")", "{", "var", "l1", "=", "reflexLeft", "(", "left", ",", "p0", ",", "0", ",", "left", ".", "length", "-", "1", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "l1", ";", "++", "i", ")", "{", "ncurve", ".", "push", "(", "left", "[", "i", "]", ")", "}", "}", "ncurve", ".", "push", "(", "p0", ",", "p1", ")", "if", "(", "right", ")", "{", "var", "r0", "=", "reflexRight", "(", "right", ",", "p1", ",", "0", ",", "right", ".", "length", "-", "1", ")", "for", "(", "var", "i", "=", "r0", ";", "i", "<", "right", ".", "length", ";", "++", "i", ")", "{", "ncurve", ".", "push", "(", "right", "[", "i", "]", ")", "}", "}", "//Append new chain to horizon", "horizon", ".", "push", "(", "ncurve", ")", "}" ]
Insert new segment into horizon
[ "Insert", "new", "segment", "into", "horizon" ]
bdeaf0d4c988c9b26ec050deb786cdbdbe42054b
https://github.com/mikolalysenko/bitmap-triangulate/blob/bdeaf0d4c988c9b26ec050deb786cdbdbe42054b/ortho.js#L68-L100
40,079
kalinchernev/odp
lib/odp.js
_sendRequest
function _sendRequest (options) { return new Promise((resolve, reject) => { var query = querystring.stringify(options.query) var bodyData = JSON.stringify(options.body) request({ url: _baseUrl + `/${options.endpoint}?${query}`, headers: headers, method: options.method, body: bodyData }, (error, response, body) => { if (error) { reject(error) } resolve(body) }) }) }
javascript
function _sendRequest (options) { return new Promise((resolve, reject) => { var query = querystring.stringify(options.query) var bodyData = JSON.stringify(options.body) request({ url: _baseUrl + `/${options.endpoint}?${query}`, headers: headers, method: options.method, body: bodyData }, (error, response, body) => { if (error) { reject(error) } resolve(body) }) }) }
[ "function", "_sendRequest", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "query", "=", "querystring", ".", "stringify", "(", "options", ".", "query", ")", "var", "bodyData", "=", "JSON", ".", "stringify", "(", "options", ".", "body", ")", "request", "(", "{", "url", ":", "_baseUrl", "+", "`", "${", "options", ".", "endpoint", "}", "${", "query", "}", "`", ",", "headers", ":", "headers", ",", "method", ":", "options", ".", "method", ",", "body", ":", "bodyData", "}", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", "}", "resolve", "(", "body", ")", "}", ")", "}", ")", "}" ]
Calls the service and return the data in a promise, but with POST. @function @private @name _sendRequest @param {object} options - The request set of options. @param {string} options.endpoint - Resource endpoint, without any slashes. @param {object} options.query - The query parameters for the request. @param {object} options.body - The body if POST, PUT @param {string} options.method - The method to be used. @returns {Promise} The response in a promise.
[ "Calls", "the", "service", "and", "return", "the", "data", "in", "a", "promise", "but", "with", "POST", "." ]
8b92122e99bc143d8737401aa225acc17f2a9aa1
https://github.com/kalinchernev/odp/blob/8b92122e99bc143d8737401aa225acc17f2a9aa1/lib/odp.js#L29-L46
40,080
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/inference/index.js
getTypeAnnotation
function getTypeAnnotation() { if (this.typeAnnotation) return this.typeAnnotation; var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); if (t.isTypeAnnotation(type)) type = type.typeAnnotation; return this.typeAnnotation = type; }
javascript
function getTypeAnnotation() { if (this.typeAnnotation) return this.typeAnnotation; var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); if (t.isTypeAnnotation(type)) type = type.typeAnnotation; return this.typeAnnotation = type; }
[ "function", "getTypeAnnotation", "(", ")", "{", "if", "(", "this", ".", "typeAnnotation", ")", "return", "this", ".", "typeAnnotation", ";", "var", "type", "=", "this", ".", "_getTypeAnnotation", "(", ")", "||", "t", ".", "anyTypeAnnotation", "(", ")", ";", "if", "(", "t", ".", "isTypeAnnotation", "(", "type", ")", ")", "type", "=", "type", ".", "typeAnnotation", ";", "return", "this", ".", "typeAnnotation", "=", "type", ";", "}" ]
Infer the type of the current `NodePath`.
[ "Infer", "the", "type", "of", "the", "current", "NodePath", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/inference/index.js#L28-L34
40,081
skerit/protoblast
lib/string.js
getNormalizedTag
function getNormalizedTag(tag_buffer) { var match = NORMALIZE_TAG_REGEX.exec(tag_buffer); return match ? match[1].toLowerCase() : null; }
javascript
function getNormalizedTag(tag_buffer) { var match = NORMALIZE_TAG_REGEX.exec(tag_buffer); return match ? match[1].toLowerCase() : null; }
[ "function", "getNormalizedTag", "(", "tag_buffer", ")", "{", "var", "match", "=", "NORMALIZE_TAG_REGEX", ".", "exec", "(", "tag_buffer", ")", ";", "return", "match", "?", "match", "[", "1", "]", ".", "toLowerCase", "(", ")", ":", "null", ";", "}" ]
Get the tag name @author Jelle De Loecker <[email protected]> @since 0.6.3 @version 0.6.3 @param {String} tag_buffer @return {String} The lowercase tag name
[ "Get", "the", "tag", "name" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/string.js#L643-L646
40,082
stadt-bielefeld/mapfile2js
src/parse/determineDepth.js
determineDepth
function determineDepth(obj){ let depth = 0; obj.forEach((line)=>{ line.depth = depth; if(line.isBlockKey){ depth++; }else{ if(line.key){ if(line.key.toUpperCase() === 'END'){ depth--; line.depth = depth; } } } }); return obj; }
javascript
function determineDepth(obj){ let depth = 0; obj.forEach((line)=>{ line.depth = depth; if(line.isBlockKey){ depth++; }else{ if(line.key){ if(line.key.toUpperCase() === 'END'){ depth--; line.depth = depth; } } } }); return obj; }
[ "function", "determineDepth", "(", "obj", ")", "{", "let", "depth", "=", "0", ";", "obj", ".", "forEach", "(", "(", "line", ")", "=>", "{", "line", ".", "depth", "=", "depth", ";", "if", "(", "line", ".", "isBlockKey", ")", "{", "depth", "++", ";", "}", "else", "{", "if", "(", "line", ".", "key", ")", "{", "if", "(", "line", ".", "key", ".", "toUpperCase", "(", ")", "===", "'END'", ")", "{", "depth", "--", ";", "line", ".", "depth", "=", "depth", ";", "}", "}", "}", "}", ")", ";", "return", "obj", ";", "}" ]
Determines the depth of every line of mapfile. @param {array} obj Array of line objects
[ "Determines", "the", "depth", "of", "every", "line", "of", "mapfile", "." ]
08497189503e8823d1c9f26b74ce4ad1025e59dd
https://github.com/stadt-bielefeld/mapfile2js/blob/08497189503e8823d1c9f26b74ce4ad1025e59dd/src/parse/determineDepth.js#L6-L27
40,083
RangerMauve/hex-to-32
index.js
encode
function encode(hexString) { // Convert to array of bytes var bytes = Buffer.from(hexString, "hex"); var encoded = base32.stringify(bytes); // strip padding & lowercase return encoded.replace(/(=+)$/, '').toLowerCase(); }
javascript
function encode(hexString) { // Convert to array of bytes var bytes = Buffer.from(hexString, "hex"); var encoded = base32.stringify(bytes); // strip padding & lowercase return encoded.replace(/(=+)$/, '').toLowerCase(); }
[ "function", "encode", "(", "hexString", ")", "{", "// Convert to array of bytes", "var", "bytes", "=", "Buffer", ".", "from", "(", "hexString", ",", "\"hex\"", ")", ";", "var", "encoded", "=", "base32", ".", "stringify", "(", "bytes", ")", ";", "// strip padding & lowercase", "return", "encoded", ".", "replace", "(", "/", "(=+)$", "/", ",", "''", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Convert a string of hex characters to a base32 encoded string @param {String} hexString The hex string to encode
[ "Convert", "a", "string", "of", "hex", "characters", "to", "a", "base32", "encoded", "string" ]
68c6e4159bec5a8722ceeb41765417480b6d4468
https://github.com/RangerMauve/hex-to-32/blob/68c6e4159bec5a8722ceeb41765417480b6d4468/index.js#L12-L19
40,084
RangerMauve/hex-to-32
index.js
decode
function decode(base32String) { // Decode to Buffer var bytes = base32.parse(base32String, { out: Buffer.alloc, loose: true }); return bytes.toString("hex"); }
javascript
function decode(base32String) { // Decode to Buffer var bytes = base32.parse(base32String, { out: Buffer.alloc, loose: true }); return bytes.toString("hex"); }
[ "function", "decode", "(", "base32String", ")", "{", "// Decode to Buffer", "var", "bytes", "=", "base32", ".", "parse", "(", "base32String", ",", "{", "out", ":", "Buffer", ".", "alloc", ",", "loose", ":", "true", "}", ")", ";", "return", "bytes", ".", "toString", "(", "\"hex\"", ")", ";", "}" ]
Convert a base32 encoded string to a hex string @param {String} base32String The base32 encoded string
[ "Convert", "a", "base32", "encoded", "string", "to", "a", "hex", "string" ]
68c6e4159bec5a8722ceeb41765417480b6d4468
https://github.com/RangerMauve/hex-to-32/blob/68c6e4159bec5a8722ceeb41765417480b6d4468/index.js#L25-L33
40,085
andrehrf/horus-client
index.js
function(setArr, cb){ if(typeof setArr === "string") var postData = querystring.stringify([setArr]); else if(typeof setArr === "object" || typeof setArr === "array") var postData = querystring.stringify(setArr); var options = { host: urlArr.hostname, path: "/set", port: urlArr.port, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; var postRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error) { if(typeof cb === "function") cb(error); }); res.on('data', function (chunk) { result += chunk; }); res.on('end', function (chunk) { if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null; cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); postRequest.write(postData); postRequest.end(); }
javascript
function(setArr, cb){ if(typeof setArr === "string") var postData = querystring.stringify([setArr]); else if(typeof setArr === "object" || typeof setArr === "array") var postData = querystring.stringify(setArr); var options = { host: urlArr.hostname, path: "/set", port: urlArr.port, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; var postRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error) { if(typeof cb === "function") cb(error); }); res.on('data', function (chunk) { result += chunk; }); res.on('end', function (chunk) { if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null; cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); postRequest.write(postData); postRequest.end(); }
[ "function", "(", "setArr", ",", "cb", ")", "{", "if", "(", "typeof", "setArr", "===", "\"string\"", ")", "var", "postData", "=", "querystring", ".", "stringify", "(", "[", "setArr", "]", ")", ";", "else", "if", "(", "typeof", "setArr", "===", "\"object\"", "||", "typeof", "setArr", "===", "\"array\"", ")", "var", "postData", "=", "querystring", ".", "stringify", "(", "setArr", ")", ";", "var", "options", "=", "{", "host", ":", "urlArr", ".", "hostname", ",", "path", ":", "\"/set\"", ",", "port", ":", "urlArr", ".", "port", ",", "method", ":", "'POST'", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", ",", "'Content-Length'", ":", "Buffer", ".", "byteLength", "(", "postData", ")", "}", "}", ";", "var", "postRequest", "=", "protocol", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "var", "result", "=", "\"\"", ";", "if", "(", "res", ".", "statusCode", "===", "200", ")", "{", "res", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "error", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "result", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", "chunk", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "{", "var", "resultObj", "=", "JSON", ".", "parse", "(", "result", ")", ";", "var", "err", "=", "(", "resultObj", ".", "status", "===", "\"error\"", ")", "?", "resultObj", "[", "\"msg\"", "]", ":", "null", ";", "cb", "(", "err", ",", "resultObj", ")", ";", "}", "}", ")", ";", "}", "else", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "\"Request return HTTP \"", "+", "res", ".", "statusCode", ")", ";", "}", "}", ")", ";", "postRequest", ".", "write", "(", "postData", ")", ";", "postRequest", ".", "end", "(", ")", ";", "}" ]
Function do set links to watch @param array setArr @param function cb @return void
[ "Function", "do", "set", "links", "to", "watch" ]
a32bd3a91b7af93ad8640789315ddabfc5ee8931
https://github.com/andrehrf/horus-client/blob/a32bd3a91b7af93ad8640789315ddabfc5ee8931/index.js#L23-L69
40,086
andrehrf/horus-client
index.js
function(link, cb){ var options = { host: urlArr.hostname, port: urlArr.port, path: urlArr.path+"?link="+encodeURIComponent(link), method: 'GET' }; var getRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error) { if(typeof cb === "function") cb(error); }); res.on('data', function (chunk) { result += chunk; }); res.on('end', function (chunk) { if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); getRequest.end(); }
javascript
function(link, cb){ var options = { host: urlArr.hostname, port: urlArr.port, path: urlArr.path+"?link="+encodeURIComponent(link), method: 'GET' }; var getRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error) { if(typeof cb === "function") cb(error); }); res.on('data', function (chunk) { result += chunk; }); res.on('end', function (chunk) { if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); getRequest.end(); }
[ "function", "(", "link", ",", "cb", ")", "{", "var", "options", "=", "{", "host", ":", "urlArr", ".", "hostname", ",", "port", ":", "urlArr", ".", "port", ",", "path", ":", "urlArr", ".", "path", "+", "\"?link=\"", "+", "encodeURIComponent", "(", "link", ")", ",", "method", ":", "'GET'", "}", ";", "var", "getRequest", "=", "protocol", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "var", "result", "=", "\"\"", ";", "if", "(", "res", ".", "statusCode", "===", "200", ")", "{", "res", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "error", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "result", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", "chunk", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "{", "var", "resultObj", "=", "JSON", ".", "parse", "(", "result", ")", ";", "var", "err", "=", "(", "resultObj", ".", "status", "===", "\"error\"", ")", "?", "resultObj", "[", "\"msg\"", "]", ":", "null", "cb", "(", "err", ",", "resultObj", ")", ";", "}", "}", ")", ";", "}", "else", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "\"Request return HTTP \"", "+", "res", ".", "statusCode", ")", ";", "}", "}", ")", ";", "getRequest", ".", "end", "(", ")", ";", "}" ]
Function do get link status @param string link @param function cb @return void
[ "Function", "do", "get", "link", "status" ]
a32bd3a91b7af93ad8640789315ddabfc5ee8931
https://github.com/andrehrf/horus-client/blob/a32bd3a91b7af93ad8640789315ddabfc5ee8931/index.js#L78-L114
40,087
andrehrf/horus-client
index.js
function(link, cb){ var id = Math.abs(crc32.str(md5(link))); var options = { host: urlArr.hostname, port: urlArr.port, path: "/delete/"+id, method: 'DELETE', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; var deleteRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error){ if(typeof cb === "function") cb(error); }); res.on('data', function(chunk){ result += chunk; }); res.on('end', function(chunk){ if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); deleteRequest.end(); }
javascript
function(link, cb){ var id = Math.abs(crc32.str(md5(link))); var options = { host: urlArr.hostname, port: urlArr.port, path: "/delete/"+id, method: 'DELETE', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; var deleteRequest = protocol.request(options, function(res){ var result = ""; if(res.statusCode === 200){ res.on('error', function(error){ if(typeof cb === "function") cb(error); }); res.on('data', function(chunk){ result += chunk; }); res.on('end', function(chunk){ if(typeof cb === "function"){ var resultObj = JSON.parse(result); var err = (resultObj.status === "error") ? resultObj["msg"] : null cb(err, resultObj); } }); } else{ if(typeof cb === "function") cb("Request return HTTP "+res.statusCode); } }); deleteRequest.end(); }
[ "function", "(", "link", ",", "cb", ")", "{", "var", "id", "=", "Math", ".", "abs", "(", "crc32", ".", "str", "(", "md5", "(", "link", ")", ")", ")", ";", "var", "options", "=", "{", "host", ":", "urlArr", ".", "hostname", ",", "port", ":", "urlArr", ".", "port", ",", "path", ":", "\"/delete/\"", "+", "id", ",", "method", ":", "'DELETE'", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "}", ";", "var", "deleteRequest", "=", "protocol", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "var", "result", "=", "\"\"", ";", "if", "(", "res", ".", "statusCode", "===", "200", ")", "{", "res", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "error", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "result", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", "chunk", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "{", "var", "resultObj", "=", "JSON", ".", "parse", "(", "result", ")", ";", "var", "err", "=", "(", "resultObj", ".", "status", "===", "\"error\"", ")", "?", "resultObj", "[", "\"msg\"", "]", ":", "null", "cb", "(", "err", ",", "resultObj", ")", ";", "}", "}", ")", ";", "}", "else", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "cb", "(", "\"Request return HTTP \"", "+", "res", ".", "statusCode", ")", ";", "}", "}", ")", ";", "deleteRequest", ".", "end", "(", ")", ";", "}" ]
Function to remove link to waitch list @returns {undefined}
[ "Function", "to", "remove", "link", "to", "waitch", "list" ]
a32bd3a91b7af93ad8640789315ddabfc5ee8931
https://github.com/andrehrf/horus-client/blob/a32bd3a91b7af93ad8640789315ddabfc5ee8931/index.js#L121-L162
40,088
qmachine/qm-nodejs
lib/qm/service.js
function (request) { // This function is the default logging function. return { host: request.headers.host, method: request.method, timestamp: new Date(), url: request.url }; }
javascript
function (request) { // This function is the default logging function. return { host: request.headers.host, method: request.method, timestamp: new Date(), url: request.url }; }
[ "function", "(", "request", ")", "{", "// This function is the default logging function.", "return", "{", "host", ":", "request", ".", "headers", ".", "host", ",", "method", ":", "request", ".", "method", ",", "timestamp", ":", "new", "Date", "(", ")", ",", "url", ":", "request", ".", "url", "}", ";", "}" ]
- aka INADDR_ANY
[ "-", "aka", "INADDR_ANY" ]
755b55e04e6ca4716504a7c705804ca07df8360f
https://github.com/qmachine/qm-nodejs/blob/755b55e04e6ca4716504a7c705804ca07df8360f/lib/qm/service.js#L130-L138
40,089
solid/folder-pane
folderPane.js
function (newPaneOptions) { var kb = UI.store var newInstance = newPaneOptions.newInstance || kb.sym(newPaneOptions.newBase) var u = newInstance.uri if (u.endsWith('/')) { u = u.slice(0, -1) // chop off trailer }// { throw new Error('URI of new folder must end in "/" :' + u) } newPaneOptions.newInstance = kb.sym(u + '/') // @@@@ kludge until we can get the solid-client version working // Force the folder by saving a dummy file inside it return kb.fetcher.webOperation('PUT', newInstance.uri + '.dummy') .then(function () { console.log('New folder created: ' + newInstance.uri) return kb.fetcher.delete(newInstance.uri + '.dummy') }) .then(function () { console.log('Dummy file deleted : ' + newInstance.uri + '.dummy') /* return kb.fetcher.createContainer(parentURI, folderName) // Not BOTH ways }) .then(function () { */ console.log('New container created: ' + newInstance.uri) return newPaneOptions }) }
javascript
function (newPaneOptions) { var kb = UI.store var newInstance = newPaneOptions.newInstance || kb.sym(newPaneOptions.newBase) var u = newInstance.uri if (u.endsWith('/')) { u = u.slice(0, -1) // chop off trailer }// { throw new Error('URI of new folder must end in "/" :' + u) } newPaneOptions.newInstance = kb.sym(u + '/') // @@@@ kludge until we can get the solid-client version working // Force the folder by saving a dummy file inside it return kb.fetcher.webOperation('PUT', newInstance.uri + '.dummy') .then(function () { console.log('New folder created: ' + newInstance.uri) return kb.fetcher.delete(newInstance.uri + '.dummy') }) .then(function () { console.log('Dummy file deleted : ' + newInstance.uri + '.dummy') /* return kb.fetcher.createContainer(parentURI, folderName) // Not BOTH ways }) .then(function () { */ console.log('New container created: ' + newInstance.uri) return newPaneOptions }) }
[ "function", "(", "newPaneOptions", ")", "{", "var", "kb", "=", "UI", ".", "store", "var", "newInstance", "=", "newPaneOptions", ".", "newInstance", "||", "kb", ".", "sym", "(", "newPaneOptions", ".", "newBase", ")", "var", "u", "=", "newInstance", ".", "uri", "if", "(", "u", ".", "endsWith", "(", "'/'", ")", ")", "{", "u", "=", "u", ".", "slice", "(", "0", ",", "-", "1", ")", "// chop off trailer", "}", "// { throw new Error('URI of new folder must end in \"/\" :' + u) }", "newPaneOptions", ".", "newInstance", "=", "kb", ".", "sym", "(", "u", "+", "'/'", ")", "// @@@@ kludge until we can get the solid-client version working", "// Force the folder by saving a dummy file inside it", "return", "kb", ".", "fetcher", ".", "webOperation", "(", "'PUT'", ",", "newInstance", ".", "uri", "+", "'.dummy'", ")", ".", "then", "(", "function", "(", ")", "{", "console", ".", "log", "(", "'New folder created: '", "+", "newInstance", ".", "uri", ")", "return", "kb", ".", "fetcher", ".", "delete", "(", "newInstance", ".", "uri", "+", "'.dummy'", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "console", ".", "log", "(", "'Dummy file deleted : '", "+", "newInstance", ".", "uri", "+", "'.dummy'", ")", "/*\n return kb.fetcher.createContainer(parentURI, folderName) // Not BOTH ways\n })\n .then(function () {\n*/", "console", ".", "log", "(", "'New container created: '", "+", "newInstance", ".", "uri", ")", "return", "newPaneOptions", "}", ")", "}" ]
Create a new folder in a Solid system,
[ "Create", "a", "new", "folder", "in", "a", "Solid", "system" ]
ef48b49a7b5e7c7475ad8acb566e921078604b7b
https://github.com/solid/folder-pane/blob/ef48b49a7b5e7c7475ad8acb566e921078604b7b/folderPane.js#L17-L44
40,090
solid/folder-pane
folderPane.js
function (obj) { // @@ This hiddenness should actually be server defined var pathEnd = obj.uri.slice(obj.dir().uri.length) return !(pathEnd.startsWith('.') || pathEnd.endsWith('.acl') || pathEnd.endsWith('~')) }
javascript
function (obj) { // @@ This hiddenness should actually be server defined var pathEnd = obj.uri.slice(obj.dir().uri.length) return !(pathEnd.startsWith('.') || pathEnd.endsWith('.acl') || pathEnd.endsWith('~')) }
[ "function", "(", "obj", ")", "{", "// @@ This hiddenness should actually be server defined", "var", "pathEnd", "=", "obj", ".", "uri", ".", "slice", "(", "obj", ".", "dir", "(", ")", ".", "uri", ".", "length", ")", "return", "!", "(", "pathEnd", ".", "startsWith", "(", "'.'", ")", "||", "pathEnd", ".", "endsWith", "(", "'.acl'", ")", "||", "pathEnd", ".", "endsWith", "(", "'~'", ")", ")", "}" ]
If this is an LDP container just list the directory
[ "If", "this", "is", "an", "LDP", "container", "just", "list", "the", "directory" ]
ef48b49a7b5e7c7475ad8acb566e921078604b7b
https://github.com/solid/folder-pane/blob/ef48b49a7b5e7c7475ad8acb566e921078604b7b/folderPane.js#L79-L82
40,091
noderaider/repackage
jspm_packages/npm/[email protected]/lib/api/browser.js
runScripts
function runScripts() { var scripts = []; var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"]; var index = 0; /** * Transform and execute script. Ensures correct load order. */ var exec = function exec() { var param = scripts[index]; if (param instanceof Array) { transform.run.apply(transform, param); index++; exec(); } }; /** * Load, transform, and execute all scripts. */ var run = function run(script, i) { var opts = {}; if (script.src) { transform.load(script.src, function (param) { scripts[i] = param; exec(); }, opts, true); } else { opts.filename = "embedded"; scripts[i] = [script.innerHTML, opts]; } }; // Collect scripts with Babel `types`. var _scripts = global.document.getElementsByTagName("script"); for (var i = 0; i < _scripts.length; ++i) { var _script = _scripts[i]; if (types.indexOf(_script.type) >= 0) scripts.push(_script); } for (i in scripts) { run(scripts[i], i); } exec(); }
javascript
function runScripts() { var scripts = []; var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"]; var index = 0; /** * Transform and execute script. Ensures correct load order. */ var exec = function exec() { var param = scripts[index]; if (param instanceof Array) { transform.run.apply(transform, param); index++; exec(); } }; /** * Load, transform, and execute all scripts. */ var run = function run(script, i) { var opts = {}; if (script.src) { transform.load(script.src, function (param) { scripts[i] = param; exec(); }, opts, true); } else { opts.filename = "embedded"; scripts[i] = [script.innerHTML, opts]; } }; // Collect scripts with Babel `types`. var _scripts = global.document.getElementsByTagName("script"); for (var i = 0; i < _scripts.length; ++i) { var _script = _scripts[i]; if (types.indexOf(_script.type) >= 0) scripts.push(_script); } for (i in scripts) { run(scripts[i], i); } exec(); }
[ "function", "runScripts", "(", ")", "{", "var", "scripts", "=", "[", "]", ";", "var", "types", "=", "[", "\"text/ecmascript-6\"", ",", "\"text/6to5\"", ",", "\"text/babel\"", ",", "\"module\"", "]", ";", "var", "index", "=", "0", ";", "/**\n * Transform and execute script. Ensures correct load order.\n */", "var", "exec", "=", "function", "exec", "(", ")", "{", "var", "param", "=", "scripts", "[", "index", "]", ";", "if", "(", "param", "instanceof", "Array", ")", "{", "transform", ".", "run", ".", "apply", "(", "transform", ",", "param", ")", ";", "index", "++", ";", "exec", "(", ")", ";", "}", "}", ";", "/**\n * Load, transform, and execute all scripts.\n */", "var", "run", "=", "function", "run", "(", "script", ",", "i", ")", "{", "var", "opts", "=", "{", "}", ";", "if", "(", "script", ".", "src", ")", "{", "transform", ".", "load", "(", "script", ".", "src", ",", "function", "(", "param", ")", "{", "scripts", "[", "i", "]", "=", "param", ";", "exec", "(", ")", ";", "}", ",", "opts", ",", "true", ")", ";", "}", "else", "{", "opts", ".", "filename", "=", "\"embedded\"", ";", "scripts", "[", "i", "]", "=", "[", "script", ".", "innerHTML", ",", "opts", "]", ";", "}", "}", ";", "// Collect scripts with Babel `types`.", "var", "_scripts", "=", "global", ".", "document", ".", "getElementsByTagName", "(", "\"script\"", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "_scripts", ".", "length", ";", "++", "i", ")", "{", "var", "_script", "=", "_scripts", "[", "i", "]", ";", "if", "(", "types", ".", "indexOf", "(", "_script", ".", "type", ")", ">=", "0", ")", "scripts", ".", "push", "(", "_script", ")", ";", "}", "for", "(", "i", "in", "scripts", ")", "{", "run", "(", "scripts", "[", "i", "]", ",", "i", ")", ";", "}", "exec", "(", ")", ";", "}" ]
Load and transform all scripts of `types`. @example <script type="module"></script>
[ "Load", "and", "transform", "all", "scripts", "of", "types", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/api/browser.js#L74-L124
40,092
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/node/index.js
find
function find(obj, node, parent) { if (!obj) return; var result; var types = Object.keys(obj); for (var i = 0; i < types.length; i++) { var type = types[i]; if (t.is(type, node)) { var fn = obj[type]; result = fn(node, parent); if (result != null) break; } } return result; }
javascript
function find(obj, node, parent) { if (!obj) return; var result; var types = Object.keys(obj); for (var i = 0; i < types.length; i++) { var type = types[i]; if (t.is(type, node)) { var fn = obj[type]; result = fn(node, parent); if (result != null) break; } } return result; }
[ "function", "find", "(", "obj", ",", "node", ",", "parent", ")", "{", "if", "(", "!", "obj", ")", "return", ";", "var", "result", ";", "var", "types", "=", "Object", ".", "keys", "(", "obj", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "types", ".", "length", ";", "i", "++", ")", "{", "var", "type", "=", "types", "[", "i", "]", ";", "if", "(", "t", ".", "is", "(", "type", ",", "node", ")", ")", "{", "var", "fn", "=", "obj", "[", "type", "]", ";", "result", "=", "fn", "(", "node", ",", "parent", ")", ";", "if", "(", "result", "!=", "null", ")", "break", ";", "}", "}", "return", "result", ";", "}" ]
Test if node matches a set of type-matcher pairs. @example find({ VariableDeclaration(node, parent) { return true; } }, node, parent);
[ "Test", "if", "node", "matches", "a", "set", "of", "type", "-", "matcher", "pairs", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/node/index.js#L48-L64
40,093
carlwoodward/run-markdown
index.js
writeAndRunCodeBlocks
function writeAndRunCodeBlocks(codeBlocks) { var dir = '.runnable-markdown-' + rand.generateKey(7); return makeTempDir(dir) .then(function() { return new Promise(function(fulfill, reject) { async.mapSeries(codeBlocks, function(codeBlock, callback) { appendCodeBlockToFile(codeBlock, dir) .then(runCodeBlock) .then(function(codeBlock) { callback(null, codeBlock); }) .catch(function(err) { callback(err, null); }); }, convertAsyncResultToPromise(fulfill, reject)); }); }) .then(function(codeBlocks) { return removeOldDir(dir) .then(function() { return codeBlocks; }); }); }
javascript
function writeAndRunCodeBlocks(codeBlocks) { var dir = '.runnable-markdown-' + rand.generateKey(7); return makeTempDir(dir) .then(function() { return new Promise(function(fulfill, reject) { async.mapSeries(codeBlocks, function(codeBlock, callback) { appendCodeBlockToFile(codeBlock, dir) .then(runCodeBlock) .then(function(codeBlock) { callback(null, codeBlock); }) .catch(function(err) { callback(err, null); }); }, convertAsyncResultToPromise(fulfill, reject)); }); }) .then(function(codeBlocks) { return removeOldDir(dir) .then(function() { return codeBlocks; }); }); }
[ "function", "writeAndRunCodeBlocks", "(", "codeBlocks", ")", "{", "var", "dir", "=", "'.runnable-markdown-'", "+", "rand", ".", "generateKey", "(", "7", ")", ";", "return", "makeTempDir", "(", "dir", ")", ".", "then", "(", "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "async", ".", "mapSeries", "(", "codeBlocks", ",", "function", "(", "codeBlock", ",", "callback", ")", "{", "appendCodeBlockToFile", "(", "codeBlock", ",", "dir", ")", ".", "then", "(", "runCodeBlock", ")", ".", "then", "(", "function", "(", "codeBlock", ")", "{", "callback", "(", "null", ",", "codeBlock", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "}", ")", ";", "}", ",", "convertAsyncResultToPromise", "(", "fulfill", ",", "reject", ")", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "codeBlocks", ")", "{", "return", "removeOldDir", "(", "dir", ")", ".", "then", "(", "function", "(", ")", "{", "return", "codeBlocks", ";", "}", ")", ";", "}", ")", ";", "}" ]
Returns the same list of code blocks as what is passed in, but each filename includes the directory where it is stored.
[ "Returns", "the", "same", "list", "of", "code", "blocks", "as", "what", "is", "passed", "in", "but", "each", "filename", "includes", "the", "directory", "where", "it", "is", "stored", "." ]
22dd6270540f735608c1c5d562ee04675702beb7
https://github.com/carlwoodward/run-markdown/blob/22dd6270540f735608c1c5d562ee04675702beb7/index.js#L121-L144
40,094
carlwoodward/run-markdown
index.js
runCodeBlock
function runCodeBlock(codeBlock) { var dir = path.dirname(codeBlock.filename); return new Promise(function(fulfill, reject) { var filenameWithoutDir = codeBlock.filename.replace(dir + '/', ''); var command = runner(codeBlock, filenameWithoutDir); if (command === null) { fulfill(codeBlock); return; } exec(command, {cwd: dir}, function(error, stdout, stderr) { if (error) { console.error(error); reject(error); } else { if (stdout) { console.log(stdout); } if (stderr) { console.error(stderr); } fulfill(codeBlock); } }); }); }
javascript
function runCodeBlock(codeBlock) { var dir = path.dirname(codeBlock.filename); return new Promise(function(fulfill, reject) { var filenameWithoutDir = codeBlock.filename.replace(dir + '/', ''); var command = runner(codeBlock, filenameWithoutDir); if (command === null) { fulfill(codeBlock); return; } exec(command, {cwd: dir}, function(error, stdout, stderr) { if (error) { console.error(error); reject(error); } else { if (stdout) { console.log(stdout); } if (stderr) { console.error(stderr); } fulfill(codeBlock); } }); }); }
[ "function", "runCodeBlock", "(", "codeBlock", ")", "{", "var", "dir", "=", "path", ".", "dirname", "(", "codeBlock", ".", "filename", ")", ";", "return", "new", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "var", "filenameWithoutDir", "=", "codeBlock", ".", "filename", ".", "replace", "(", "dir", "+", "'/'", ",", "''", ")", ";", "var", "command", "=", "runner", "(", "codeBlock", ",", "filenameWithoutDir", ")", ";", "if", "(", "command", "===", "null", ")", "{", "fulfill", "(", "codeBlock", ")", ";", "return", ";", "}", "exec", "(", "command", ",", "{", "cwd", ":", "dir", "}", ",", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", ";", "reject", "(", "error", ")", ";", "}", "else", "{", "if", "(", "stdout", ")", "{", "console", ".", "log", "(", "stdout", ")", ";", "}", "if", "(", "stderr", ")", "{", "console", ".", "error", "(", "stderr", ")", ";", "}", "fulfill", "(", "codeBlock", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Runs a code block. Uses specially runners for files like Gemfile and package.json. Returns codeBlock.
[ "Runs", "a", "code", "block", ".", "Uses", "specially", "runners", "for", "files", "like", "Gemfile", "and", "package", ".", "json", ".", "Returns", "codeBlock", "." ]
22dd6270540f735608c1c5d562ee04675702beb7
https://github.com/carlwoodward/run-markdown/blob/22dd6270540f735608c1c5d562ee04675702beb7/index.js#L177-L201
40,095
jlas/quirky
game-client.js
countdownTimer
function countdownTimer() { $(COUNTDOWN).html("0m 0s"); var end_t = COUNTDOWNTIME; var start_t = (new Date()).getTime()/1000; function countdown() { var cur_t = (new Date()).getTime()/1000; var timeleft = (end_t - (cur_t - start_t)); if (timeleft >= 0) { var min = Math.floor(timeleft / 60); var sec = Math.floor(timeleft % 60); $(COUNTDOWN).html(min + "m " + sec + "s"); COUNTDOWNTID = setTimeout(countdown, 1000); } else { $.post("/games/" + enc($.cookie("game")) + "/players", {end_turn: true}, function() { getPlayers(); }); } } countdown(); }
javascript
function countdownTimer() { $(COUNTDOWN).html("0m 0s"); var end_t = COUNTDOWNTIME; var start_t = (new Date()).getTime()/1000; function countdown() { var cur_t = (new Date()).getTime()/1000; var timeleft = (end_t - (cur_t - start_t)); if (timeleft >= 0) { var min = Math.floor(timeleft / 60); var sec = Math.floor(timeleft % 60); $(COUNTDOWN).html(min + "m " + sec + "s"); COUNTDOWNTID = setTimeout(countdown, 1000); } else { $.post("/games/" + enc($.cookie("game")) + "/players", {end_turn: true}, function() { getPlayers(); }); } } countdown(); }
[ "function", "countdownTimer", "(", ")", "{", "$", "(", "COUNTDOWN", ")", ".", "html", "(", "\"0m 0s\"", ")", ";", "var", "end_t", "=", "COUNTDOWNTIME", ";", "var", "start_t", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "/", "1000", ";", "function", "countdown", "(", ")", "{", "var", "cur_t", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "/", "1000", ";", "var", "timeleft", "=", "(", "end_t", "-", "(", "cur_t", "-", "start_t", ")", ")", ";", "if", "(", "timeleft", ">=", "0", ")", "{", "var", "min", "=", "Math", ".", "floor", "(", "timeleft", "/", "60", ")", ";", "var", "sec", "=", "Math", ".", "floor", "(", "timeleft", "%", "60", ")", ";", "$", "(", "COUNTDOWN", ")", ".", "html", "(", "min", "+", "\"m \"", "+", "sec", "+", "\"s\"", ")", ";", "COUNTDOWNTID", "=", "setTimeout", "(", "countdown", ",", "1000", ")", ";", "}", "else", "{", "$", ".", "post", "(", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/players\"", ",", "{", "end_turn", ":", "true", "}", ",", "function", "(", ")", "{", "getPlayers", "(", ")", ";", "}", ")", ";", "}", "}", "countdown", "(", ")", ";", "}" ]
Countdown timer. Update onscreen timer and end turn if time gets too low.
[ "Countdown", "timer", ".", "Update", "onscreen", "timer", "and", "end", "turn", "if", "time", "gets", "too", "low", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L112-L132
40,096
jlas/quirky
game-client.js
drawTurnInfo
function drawTurnInfo(pdata) { var my_game = $.cookie("game"); var my_player = pdata[$.cookie("player")]; $(PIECES).empty(); $(ADDPIECE).show(); // allow player to end his turn if (my_player.has_turn) { $(ENDTURN).removeAttr('disabled'); $(TURN).html("It's your turn! You have " + "<span id='countdown'>0m 0s</span> left."); $(ENDTURN)[0].onclick = function() { $.post("/games/" + enc(my_game) + "/players", {end_turn: true}, function() { getPlayers(); /* Typically we let HAVETURN get updated from the server * in onGetPlayers(), but if there is only one player this * doesn't work very well (the player has to refresh manually). * So we force it to false here in this special case. */ if (Object.keys(pdata).length === 1) { HAVETURN = false; clearTimeout(COUNTDOWNTID); } }); }; } else { $(ENDTURN).attr('disabled', ''); $(TURN).html("It's not your turn."); } getPiecesLeft(); getBoard(); getMyPieces(my_player); }
javascript
function drawTurnInfo(pdata) { var my_game = $.cookie("game"); var my_player = pdata[$.cookie("player")]; $(PIECES).empty(); $(ADDPIECE).show(); // allow player to end his turn if (my_player.has_turn) { $(ENDTURN).removeAttr('disabled'); $(TURN).html("It's your turn! You have " + "<span id='countdown'>0m 0s</span> left."); $(ENDTURN)[0].onclick = function() { $.post("/games/" + enc(my_game) + "/players", {end_turn: true}, function() { getPlayers(); /* Typically we let HAVETURN get updated from the server * in onGetPlayers(), but if there is only one player this * doesn't work very well (the player has to refresh manually). * So we force it to false here in this special case. */ if (Object.keys(pdata).length === 1) { HAVETURN = false; clearTimeout(COUNTDOWNTID); } }); }; } else { $(ENDTURN).attr('disabled', ''); $(TURN).html("It's not your turn."); } getPiecesLeft(); getBoard(); getMyPieces(my_player); }
[ "function", "drawTurnInfo", "(", "pdata", ")", "{", "var", "my_game", "=", "$", ".", "cookie", "(", "\"game\"", ")", ";", "var", "my_player", "=", "pdata", "[", "$", ".", "cookie", "(", "\"player\"", ")", "]", ";", "$", "(", "PIECES", ")", ".", "empty", "(", ")", ";", "$", "(", "ADDPIECE", ")", ".", "show", "(", ")", ";", "// allow player to end his turn", "if", "(", "my_player", ".", "has_turn", ")", "{", "$", "(", "ENDTURN", ")", ".", "removeAttr", "(", "'disabled'", ")", ";", "$", "(", "TURN", ")", ".", "html", "(", "\"It's your turn! You have \"", "+", "\"<span id='countdown'>0m 0s</span> left.\"", ")", ";", "$", "(", "ENDTURN", ")", "[", "0", "]", ".", "onclick", "=", "function", "(", ")", "{", "$", ".", "post", "(", "\"/games/\"", "+", "enc", "(", "my_game", ")", "+", "\"/players\"", ",", "{", "end_turn", ":", "true", "}", ",", "function", "(", ")", "{", "getPlayers", "(", ")", ";", "/* Typically we let HAVETURN get updated from the server\n * in onGetPlayers(), but if there is only one player this\n * doesn't work very well (the player has to refresh manually).\n * So we force it to false here in this special case.\n */", "if", "(", "Object", ".", "keys", "(", "pdata", ")", ".", "length", "===", "1", ")", "{", "HAVETURN", "=", "false", ";", "clearTimeout", "(", "COUNTDOWNTID", ")", ";", "}", "}", ")", ";", "}", ";", "}", "else", "{", "$", "(", "ENDTURN", ")", ".", "attr", "(", "'disabled'", ",", "''", ")", ";", "$", "(", "TURN", ")", ".", "html", "(", "\"It's not your turn.\"", ")", ";", "}", "getPiecesLeft", "(", ")", ";", "getBoard", "(", ")", ";", "getMyPieces", "(", "my_player", ")", ";", "}" ]
Draw player's pieces and It's Your Turn info. @param {obj} pdata json data from the server
[ "Draw", "player", "s", "pieces", "and", "It", "s", "Your", "Turn", "info", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L181-L215
40,097
jlas/quirky
game-client.js
getMyPieces
function getMyPieces(player) { for (var i in player.pieces) { var piece = player.pieces[i]; $(PIECES).append('<div class="piece" style="color:'+ pastels[piece.color]+'">'+ushapes[piece.shape]+'</div>'); $(PIECECLS+":last-child").data("piece", piece); $(PIECES).append("<div style='float: left; margin: 3px'></div>"); } function setDimensions() { $(PIECECLS).width($(GRIDCLS).width()); $(PIECECLS).height($(GRIDCLS).height()); var fontsize = $(GRIDCLS).css("font-size"); $(PIECECLS).css("font-size", fontsize); $(PIECECLS).css("line-height", fontsize); } /* Style switching is flaky here, we're depending on the width that was set * in getBoard() and maybe that happens too fast sometimes. So we add a * setTimeout to try setting dimensions again in a short while. */ setDimensions(); setTimeout(setDimensions, 250); if (player.has_turn) $(PIECECLS).draggable({ containment: "#board", snap: ".snapgrid" }); }
javascript
function getMyPieces(player) { for (var i in player.pieces) { var piece = player.pieces[i]; $(PIECES).append('<div class="piece" style="color:'+ pastels[piece.color]+'">'+ushapes[piece.shape]+'</div>'); $(PIECECLS+":last-child").data("piece", piece); $(PIECES).append("<div style='float: left; margin: 3px'></div>"); } function setDimensions() { $(PIECECLS).width($(GRIDCLS).width()); $(PIECECLS).height($(GRIDCLS).height()); var fontsize = $(GRIDCLS).css("font-size"); $(PIECECLS).css("font-size", fontsize); $(PIECECLS).css("line-height", fontsize); } /* Style switching is flaky here, we're depending on the width that was set * in getBoard() and maybe that happens too fast sometimes. So we add a * setTimeout to try setting dimensions again in a short while. */ setDimensions(); setTimeout(setDimensions, 250); if (player.has_turn) $(PIECECLS).draggable({ containment: "#board", snap: ".snapgrid" }); }
[ "function", "getMyPieces", "(", "player", ")", "{", "for", "(", "var", "i", "in", "player", ".", "pieces", ")", "{", "var", "piece", "=", "player", ".", "pieces", "[", "i", "]", ";", "$", "(", "PIECES", ")", ".", "append", "(", "'<div class=\"piece\" style=\"color:'", "+", "pastels", "[", "piece", ".", "color", "]", "+", "'\">'", "+", "ushapes", "[", "piece", ".", "shape", "]", "+", "'</div>'", ")", ";", "$", "(", "PIECECLS", "+", "\":last-child\"", ")", ".", "data", "(", "\"piece\"", ",", "piece", ")", ";", "$", "(", "PIECES", ")", ".", "append", "(", "\"<div style='float: left; margin: 3px'></div>\"", ")", ";", "}", "function", "setDimensions", "(", ")", "{", "$", "(", "PIECECLS", ")", ".", "width", "(", "$", "(", "GRIDCLS", ")", ".", "width", "(", ")", ")", ";", "$", "(", "PIECECLS", ")", ".", "height", "(", "$", "(", "GRIDCLS", ")", ".", "height", "(", ")", ")", ";", "var", "fontsize", "=", "$", "(", "GRIDCLS", ")", ".", "css", "(", "\"font-size\"", ")", ";", "$", "(", "PIECECLS", ")", ".", "css", "(", "\"font-size\"", ",", "fontsize", ")", ";", "$", "(", "PIECECLS", ")", ".", "css", "(", "\"line-height\"", ",", "fontsize", ")", ";", "}", "/* Style switching is flaky here, we're depending on the width that was set\n * in getBoard() and maybe that happens too fast sometimes. So we add a\n * setTimeout to try setting dimensions again in a short while.\n */", "setDimensions", "(", ")", ";", "setTimeout", "(", "setDimensions", ",", "250", ")", ";", "if", "(", "player", ".", "has_turn", ")", "$", "(", "PIECECLS", ")", ".", "draggable", "(", "{", "containment", ":", "\"#board\"", ",", "snap", ":", "\".snapgrid\"", "}", ")", ";", "}" ]
Add player's pieces to his sideboard and make active if it's his turn. @param {obj} player
[ "Add", "player", "s", "pieces", "to", "his", "sideboard", "and", "make", "active", "if", "it", "s", "his", "turn", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L221-L249
40,098
jlas/quirky
game-client.js
getPiecesLeft
function getPiecesLeft() { $.getJSON("/games/" + enc($.cookie("game")) + "/pieces", function(data) { $(GAMEPIECES).empty(); var npieces = 0; for (var i in data) npieces += data[i].count; $(GAMEPIECES).html(npieces); }); }
javascript
function getPiecesLeft() { $.getJSON("/games/" + enc($.cookie("game")) + "/pieces", function(data) { $(GAMEPIECES).empty(); var npieces = 0; for (var i in data) npieces += data[i].count; $(GAMEPIECES).html(npieces); }); }
[ "function", "getPiecesLeft", "(", ")", "{", "$", ".", "getJSON", "(", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/pieces\"", ",", "function", "(", "data", ")", "{", "$", "(", "GAMEPIECES", ")", ".", "empty", "(", ")", ";", "var", "npieces", "=", "0", ";", "for", "(", "var", "i", "in", "data", ")", "npieces", "+=", "data", "[", "i", "]", ".", "count", ";", "$", "(", "GAMEPIECES", ")", ".", "html", "(", "npieces", ")", ";", "}", ")", ";", "}" ]
Publish the number of pieces left in the bag.
[ "Publish", "the", "number", "of", "pieces", "left", "in", "the", "bag", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L254-L263
40,099
jlas/quirky
game-client.js
onPieceDrop
function onPieceDrop(event, ui) { var col = $(this).data().col; var row = $(this).data().row; var piece = $(ui.draggable).data().piece; $.ajax({ type: 'POST', url: "/games/" + enc($.cookie("game")) + "/board", data: { shape: piece.shape, color: piece.color, row: row, column: col }, success: function() { $(ERRORS).empty(); }, error: function (jqXHR, textStatus, errorThrown) { $(ERRORS).empty(); $(ERRORS).append("<div class='error'>&#9888; "+jqXHR.responseText+"</div>"); }, complete: function() { $.getJSON("/games/" + enc($.cookie("game")) + "/players", drawTurnInfo); } }); }
javascript
function onPieceDrop(event, ui) { var col = $(this).data().col; var row = $(this).data().row; var piece = $(ui.draggable).data().piece; $.ajax({ type: 'POST', url: "/games/" + enc($.cookie("game")) + "/board", data: { shape: piece.shape, color: piece.color, row: row, column: col }, success: function() { $(ERRORS).empty(); }, error: function (jqXHR, textStatus, errorThrown) { $(ERRORS).empty(); $(ERRORS).append("<div class='error'>&#9888; "+jqXHR.responseText+"</div>"); }, complete: function() { $.getJSON("/games/" + enc($.cookie("game")) + "/players", drawTurnInfo); } }); }
[ "function", "onPieceDrop", "(", "event", ",", "ui", ")", "{", "var", "col", "=", "$", "(", "this", ")", ".", "data", "(", ")", ".", "col", ";", "var", "row", "=", "$", "(", "this", ")", ".", "data", "(", ")", ".", "row", ";", "var", "piece", "=", "$", "(", "ui", ".", "draggable", ")", ".", "data", "(", ")", ".", "piece", ";", "$", ".", "ajax", "(", "{", "type", ":", "'POST'", ",", "url", ":", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/board\"", ",", "data", ":", "{", "shape", ":", "piece", ".", "shape", ",", "color", ":", "piece", ".", "color", ",", "row", ":", "row", ",", "column", ":", "col", "}", ",", "success", ":", "function", "(", ")", "{", "$", "(", "ERRORS", ")", ".", "empty", "(", ")", ";", "}", ",", "error", ":", "function", "(", "jqXHR", ",", "textStatus", ",", "errorThrown", ")", "{", "$", "(", "ERRORS", ")", ".", "empty", "(", ")", ";", "$", "(", "ERRORS", ")", ".", "append", "(", "\"<div class='error'>&#9888; \"", "+", "jqXHR", ".", "responseText", "+", "\"</div>\"", ")", ";", "}", ",", "complete", ":", "function", "(", ")", "{", "$", ".", "getJSON", "(", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/players\"", ",", "drawTurnInfo", ")", ";", "}", "}", ")", ";", "}" ]
When piece is dropped, send a POST to the server to add to board. Either the piece will be added or we get an error back for invalid placements.
[ "When", "piece", "is", "dropped", "send", "a", "POST", "to", "the", "server", "to", "add", "to", "board", ".", "Either", "the", "piece", "will", "be", "added", "or", "we", "get", "an", "error", "back", "for", "invalid", "placements", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L269-L294