id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
48,600 | emreavsar/unjar-from-url | index.js | function (nodeModulesDir, unzipDirectory, url) {
const download = require('download');
const fs = require('fs');
const zlib = require('zlib');
var exec = require('child_process').exec,
child;
var path = require("path");
// extracting filename from url
var filename = path.basename(url);
var fileDirectory = nodeModulesDir + "/" + unzipDirectory;
console.log("nodeModules directory = ", nodeModulesDir);
console.log("downloading file from url=", url);
console.log("unzipping to directory=", unzipDirectory);
console.log("fileDriectory=", fileDirectory);
console.log("filename = ", filename);
// makes programming easier (create the directory anyway)
if (!fs.existsSync(fileDirectory)) {
// mkdir -p fileDirectory
fileDirectory.split('/').forEach((dir, index, splits) => {
const parent = splits.slice(0, index).join('/');
const dirPath = path.resolve(parent, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
});
}
// delete directory with file in it, and after that download the file into newly created folder
exec('rm -r ' + fileDirectory, function (err, stdout, stderr) {
fs.mkdirSync(fileDirectory);
// fs.writeFileSync(fileDirectory + "/download.jar", content);
// download process
download(url, fileDirectory).then(() => {
console.log("downloaded file successful. unzipping...");
var DecompressZip = require('decompress-zip');
console.log("file to decompress: " + fileDirectory + "/" + filename);
var unzipper = new DecompressZip(fileDirectory + "/" + filename);
unzipper.on('error', function (err) {
console.log('Caught an error', err);
});
unzipper.on('extract', function (log) {
console.log('Finished extracting');
});
unzipper.on('progress', function (fileIndex, fileCount) {
console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
});
unzipper.extract({
path: fileDirectory,
filter: function (file) {
return file.type !== "SymbolicLink";
}
});
});
});
} | javascript | function (nodeModulesDir, unzipDirectory, url) {
const download = require('download');
const fs = require('fs');
const zlib = require('zlib');
var exec = require('child_process').exec,
child;
var path = require("path");
// extracting filename from url
var filename = path.basename(url);
var fileDirectory = nodeModulesDir + "/" + unzipDirectory;
console.log("nodeModules directory = ", nodeModulesDir);
console.log("downloading file from url=", url);
console.log("unzipping to directory=", unzipDirectory);
console.log("fileDriectory=", fileDirectory);
console.log("filename = ", filename);
// makes programming easier (create the directory anyway)
if (!fs.existsSync(fileDirectory)) {
// mkdir -p fileDirectory
fileDirectory.split('/').forEach((dir, index, splits) => {
const parent = splits.slice(0, index).join('/');
const dirPath = path.resolve(parent, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
});
}
// delete directory with file in it, and after that download the file into newly created folder
exec('rm -r ' + fileDirectory, function (err, stdout, stderr) {
fs.mkdirSync(fileDirectory);
// fs.writeFileSync(fileDirectory + "/download.jar", content);
// download process
download(url, fileDirectory).then(() => {
console.log("downloaded file successful. unzipping...");
var DecompressZip = require('decompress-zip');
console.log("file to decompress: " + fileDirectory + "/" + filename);
var unzipper = new DecompressZip(fileDirectory + "/" + filename);
unzipper.on('error', function (err) {
console.log('Caught an error', err);
});
unzipper.on('extract', function (log) {
console.log('Finished extracting');
});
unzipper.on('progress', function (fileIndex, fileCount) {
console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
});
unzipper.extract({
path: fileDirectory,
filter: function (file) {
return file.type !== "SymbolicLink";
}
});
});
});
} | [
"function",
"(",
"nodeModulesDir",
",",
"unzipDirectory",
",",
"url",
")",
"{",
"const",
"download",
"=",
"require",
"(",
"'download'",
")",
";",
"const",
"fs",
"=",
"require",
"(",
"'fs'",
")",
";",
"const",
"zlib",
"=",
"require",
"(",
"'zlib'",
")",
";",
"var",
"exec",
"=",
"require",
"(",
"'child_process'",
")",
".",
"exec",
",",
"child",
";",
"var",
"path",
"=",
"require",
"(",
"\"path\"",
")",
";",
"// extracting filename from url",
"var",
"filename",
"=",
"path",
".",
"basename",
"(",
"url",
")",
";",
"var",
"fileDirectory",
"=",
"nodeModulesDir",
"+",
"\"/\"",
"+",
"unzipDirectory",
";",
"console",
".",
"log",
"(",
"\"nodeModules directory = \"",
",",
"nodeModulesDir",
")",
";",
"console",
".",
"log",
"(",
"\"downloading file from url=\"",
",",
"url",
")",
";",
"console",
".",
"log",
"(",
"\"unzipping to directory=\"",
",",
"unzipDirectory",
")",
";",
"console",
".",
"log",
"(",
"\"fileDriectory=\"",
",",
"fileDirectory",
")",
";",
"console",
".",
"log",
"(",
"\"filename = \"",
",",
"filename",
")",
";",
"// makes programming easier (create the directory anyway)",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"fileDirectory",
")",
")",
"{",
"// mkdir -p fileDirectory",
"fileDirectory",
".",
"split",
"(",
"'/'",
")",
".",
"forEach",
"(",
"(",
"dir",
",",
"index",
",",
"splits",
")",
"=>",
"{",
"const",
"parent",
"=",
"splits",
".",
"slice",
"(",
"0",
",",
"index",
")",
".",
"join",
"(",
"'/'",
")",
";",
"const",
"dirPath",
"=",
"path",
".",
"resolve",
"(",
"parent",
",",
"dir",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dirPath",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"dirPath",
")",
";",
"}",
"}",
")",
";",
"}",
"// delete directory with file in it, and after that download the file into newly created folder",
"exec",
"(",
"'rm -r '",
"+",
"fileDirectory",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"fileDirectory",
")",
";",
"// fs.writeFileSync(fileDirectory + \"/download.jar\", content);",
"// download process",
"download",
"(",
"url",
",",
"fileDirectory",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"\"downloaded file successful. unzipping...\"",
")",
";",
"var",
"DecompressZip",
"=",
"require",
"(",
"'decompress-zip'",
")",
";",
"console",
".",
"log",
"(",
"\"file to decompress: \"",
"+",
"fileDirectory",
"+",
"\"/\"",
"+",
"filename",
")",
";",
"var",
"unzipper",
"=",
"new",
"DecompressZip",
"(",
"fileDirectory",
"+",
"\"/\"",
"+",
"filename",
")",
";",
"unzipper",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'Caught an error'",
",",
"err",
")",
";",
"}",
")",
";",
"unzipper",
".",
"on",
"(",
"'extract'",
",",
"function",
"(",
"log",
")",
"{",
"console",
".",
"log",
"(",
"'Finished extracting'",
")",
";",
"}",
")",
";",
"unzipper",
".",
"on",
"(",
"'progress'",
",",
"function",
"(",
"fileIndex",
",",
"fileCount",
")",
"{",
"console",
".",
"log",
"(",
"'Extracted file '",
"+",
"(",
"fileIndex",
"+",
"1",
")",
"+",
"' of '",
"+",
"fileCount",
")",
";",
"}",
")",
";",
"unzipper",
".",
"extract",
"(",
"{",
"path",
":",
"fileDirectory",
",",
"filter",
":",
"function",
"(",
"file",
")",
"{",
"return",
"file",
".",
"type",
"!==",
"\"SymbolicLink\"",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Downloads and uncompresses a jar from given url into node_modules directory.
@param {string} nodeModulesDir absolute path to node_modules directory where a directory gets created where the jar gets uncompressed
@param {string} unzipDirectory name of the directory where the jar file gets uncompressed in
@param {string} url to jar to download | [
"Downloads",
"and",
"uncompresses",
"a",
"jar",
"from",
"given",
"url",
"into",
"node_modules",
"directory",
"."
] | 998b45d0c67a6f21a552ac6780900549d6fb0026 | https://github.com/emreavsar/unjar-from-url/blob/998b45d0c67a6f21a552ac6780900549d6fb0026/index.js#L166-L229 |
|
48,601 | Ensighten/Builder | dist/Builder.require.jquery.keys.js | Builder | function Builder(tmpl, data) {
// Generate a this context for data
var that = {'tmpl': tmpl, 'data': data};
// Run the beforeFns on tmpl
tmpl = pre.call(that, tmpl);
// Convert the template into content
var content = template.call(that, tmpl, data);
// Pass the template through the dom engine
var $content = domify.call(that, content);
// Run the afterFns on $content
$content = post.call(that, $content);
// Return the $content
return $content;
} | javascript | function Builder(tmpl, data) {
// Generate a this context for data
var that = {'tmpl': tmpl, 'data': data};
// Run the beforeFns on tmpl
tmpl = pre.call(that, tmpl);
// Convert the template into content
var content = template.call(that, tmpl, data);
// Pass the template through the dom engine
var $content = domify.call(that, content);
// Run the afterFns on $content
$content = post.call(that, $content);
// Return the $content
return $content;
} | [
"function",
"Builder",
"(",
"tmpl",
",",
"data",
")",
"{",
"// Generate a this context for data",
"var",
"that",
"=",
"{",
"'tmpl'",
":",
"tmpl",
",",
"'data'",
":",
"data",
"}",
";",
"// Run the beforeFns on tmpl",
"tmpl",
"=",
"pre",
".",
"call",
"(",
"that",
",",
"tmpl",
")",
";",
"// Convert the template into content",
"var",
"content",
"=",
"template",
".",
"call",
"(",
"that",
",",
"tmpl",
",",
"data",
")",
";",
"// Pass the template through the dom engine",
"var",
"$content",
"=",
"domify",
".",
"call",
"(",
"that",
",",
"content",
")",
";",
"// Run the afterFns on $content",
"$content",
"=",
"post",
".",
"call",
"(",
"that",
",",
"$content",
")",
";",
"// Return the $content",
"return",
"$content",
";",
"}"
] | Build chain for client side views. before -> template -> domify -> after -> return
@param {String} tmpl Template to process through template engine
@param {Object} [data] Data to pass through to template engine
@returns {Mixed} Output from before -> template -> domify -> after -> return | [
"Build",
"chain",
"for",
"client",
"side",
"views",
".",
"before",
"-",
">",
"template",
"-",
">",
"domify",
"-",
">",
"after",
"-",
">",
"return"
] | eb1cf781f229588a3898fd2c0d7365feb29fb06b | https://github.com/Ensighten/Builder/blob/eb1cf781f229588a3898fd2c0d7365feb29fb06b/dist/Builder.require.jquery.keys.js#L27-L45 |
48,602 | Ensighten/Builder | dist/Builder.require.jquery.keys.js | pre | function pre(tmpl) {
// Iterate over the beforeFns
var i = 0,
len = beforeFns.length;
for (; i < len; i++) {
tmpl = beforeFns[i].call(this, tmpl) || tmpl;
}
// Return tmpl
return tmpl;
} | javascript | function pre(tmpl) {
// Iterate over the beforeFns
var i = 0,
len = beforeFns.length;
for (; i < len; i++) {
tmpl = beforeFns[i].call(this, tmpl) || tmpl;
}
// Return tmpl
return tmpl;
} | [
"function",
"pre",
"(",
"tmpl",
")",
"{",
"// Iterate over the beforeFns",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"beforeFns",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"tmpl",
"=",
"beforeFns",
"[",
"i",
"]",
".",
"call",
"(",
"this",
",",
"tmpl",
")",
"||",
"tmpl",
";",
"}",
"// Return tmpl",
"return",
"tmpl",
";",
"}"
] | Modify tmpl via beforeFns
@param {String} tmpl Template string to modify
@returns {String} Modified tmpl | [
"Modify",
"tmpl",
"via",
"beforeFns"
] | eb1cf781f229588a3898fd2c0d7365feb29fb06b | https://github.com/Ensighten/Builder/blob/eb1cf781f229588a3898fd2c0d7365feb29fb06b/dist/Builder.require.jquery.keys.js#L52-L62 |
48,603 | Ensighten/Builder | dist/Builder.require.jquery.keys.js | template | function template(tmpl, data) {
// Grab the template engine
var engine = settings['template engine'];
// Process the template through the template engine
var content = engine.call(this, tmpl, data);
// Return the content
return content;
} | javascript | function template(tmpl, data) {
// Grab the template engine
var engine = settings['template engine'];
// Process the template through the template engine
var content = engine.call(this, tmpl, data);
// Return the content
return content;
} | [
"function",
"template",
"(",
"tmpl",
",",
"data",
")",
"{",
"// Grab the template engine",
"var",
"engine",
"=",
"settings",
"[",
"'template engine'",
"]",
";",
"// Process the template through the template engine",
"var",
"content",
"=",
"engine",
".",
"call",
"(",
"this",
",",
"tmpl",
",",
"data",
")",
";",
"// Return the content",
"return",
"content",
";",
"}"
] | Parse template through its engine
@param {String} tmpl Template to process through template engine
@param {Object} [data] Data to pass through to template engine | [
"Parse",
"template",
"through",
"its",
"engine"
] | eb1cf781f229588a3898fd2c0d7365feb29fb06b | https://github.com/Ensighten/Builder/blob/eb1cf781f229588a3898fd2c0d7365feb29fb06b/dist/Builder.require.jquery.keys.js#L71-L80 |
48,604 | Ensighten/Builder | dist/Builder.require.jquery.keys.js | set | function set(name, val) {
// If the name is an object
var key;
if (typeof name === 'object') {
// Iterate over its properties
for (key in name) {
if (name.hasOwnProperty(key)) {
// Set each one
set(key, name[key]);
}
}
} else {
// Otherwise, save to settings
settings[name] = val;
}
} | javascript | function set(name, val) {
// If the name is an object
var key;
if (typeof name === 'object') {
// Iterate over its properties
for (key in name) {
if (name.hasOwnProperty(key)) {
// Set each one
set(key, name[key]);
}
}
} else {
// Otherwise, save to settings
settings[name] = val;
}
} | [
"function",
"set",
"(",
"name",
",",
"val",
")",
"{",
"// If the name is an object",
"var",
"key",
";",
"if",
"(",
"typeof",
"name",
"===",
"'object'",
")",
"{",
"// Iterate over its properties",
"for",
"(",
"key",
"in",
"name",
")",
"{",
"if",
"(",
"name",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"// Set each one",
"set",
"(",
"key",
",",
"name",
"[",
"key",
"]",
")",
";",
"}",
"}",
"}",
"else",
"{",
"// Otherwise, save to settings",
"settings",
"[",
"name",
"]",
"=",
"val",
";",
"}",
"}"
] | Settings helper for Builder
@param {String|Object} name If object, interpret as key-value pairs of settings. If string, save val under settings key.
@param {Mixed} [val] Value to save under name | [
"Settings",
"helper",
"for",
"Builder"
] | eb1cf781f229588a3898fd2c0d7365feb29fb06b | https://github.com/Ensighten/Builder/blob/eb1cf781f229588a3898fd2c0d7365feb29fb06b/dist/Builder.require.jquery.keys.js#L123-L138 |
48,605 | Ensighten/Builder | dist/Builder.require.jquery.keys.js | addPlugin | function addPlugin(params) {
// If the params are a string, upcast it to an object
if (typeof params === 'string') {
params = {
'plugin': params
};
}
// Grab and fallback plugin and selector
var plugin = params.plugin,
selector = params.selector || '.' + plugin;
// Generate an after function for binding
var afterFn = function pluginAfterFn($content) {
// Filter and find any jQuery module that has the corresponding class
var $items = $().add($content.filter(selector)).add($content.find(selector));
// Iterate over the items and initialize the plugin
$items.each(function () {
$(this)[plugin]();
});
};
// Bind the after function
after(afterFn);
} | javascript | function addPlugin(params) {
// If the params are a string, upcast it to an object
if (typeof params === 'string') {
params = {
'plugin': params
};
}
// Grab and fallback plugin and selector
var plugin = params.plugin,
selector = params.selector || '.' + plugin;
// Generate an after function for binding
var afterFn = function pluginAfterFn($content) {
// Filter and find any jQuery module that has the corresponding class
var $items = $().add($content.filter(selector)).add($content.find(selector));
// Iterate over the items and initialize the plugin
$items.each(function () {
$(this)[plugin]();
});
};
// Bind the after function
after(afterFn);
} | [
"function",
"addPlugin",
"(",
"params",
")",
"{",
"// If the params are a string, upcast it to an object",
"if",
"(",
"typeof",
"params",
"===",
"'string'",
")",
"{",
"params",
"=",
"{",
"'plugin'",
":",
"params",
"}",
";",
"}",
"// Grab and fallback plugin and selector",
"var",
"plugin",
"=",
"params",
".",
"plugin",
",",
"selector",
"=",
"params",
".",
"selector",
"||",
"'.'",
"+",
"plugin",
";",
"// Generate an after function for binding",
"var",
"afterFn",
"=",
"function",
"pluginAfterFn",
"(",
"$content",
")",
"{",
"// Filter and find any jQuery module that has the corresponding class",
"var",
"$items",
"=",
"$",
"(",
")",
".",
"add",
"(",
"$content",
".",
"filter",
"(",
"selector",
")",
")",
".",
"add",
"(",
"$content",
".",
"find",
"(",
"selector",
")",
")",
";",
"// Iterate over the items and initialize the plugin",
"$items",
".",
"each",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
"[",
"plugin",
"]",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"// Bind the after function",
"after",
"(",
"afterFn",
")",
";",
"}"
] | Initialize jQuery plugins after rendering
@param {String|Object} params If a string, it will be used for params.plugin and we will search elements which use it as a class
@param {String} params.plugin jQuery plugin to instantiate
@param {Mixed} params.selector Selector to use within $content.filter and $content.find | [
"Initialize",
"jQuery",
"plugins",
"after",
"rendering"
] | eb1cf781f229588a3898fd2c0d7365feb29fb06b | https://github.com/Ensighten/Builder/blob/eb1cf781f229588a3898fd2c0d7365feb29fb06b/dist/Builder.require.jquery.keys.js#L166-L191 |
48,606 | soldair/pinoccio-server | troop.js | handle | function handle(js,line){
// handle message from board.
//stream.log("handle",stream.token,line);
var hasToken = stream.token;
if(js.type == "token") {
// send in event stream.
stream.queue(js);
stream.token = js.token;
if(!hasToken) {
readycb(false,stream);
clearTimeout(readyTimeout);
}
return;
}
if(!stream.token) return stream.log('data from socket before auth/id token.',js);
if(js.type == 'reply'){
o = stream.callbacks[js.id]||{};
if(o.id === undefined) return stream.log('got reply with no id mapping! ',js);
var output = js.output||js.reply||"";
var ret = js.return;// not set yet.
if(!o.output) o.output = "";
// handle chunked responses. they come in order.
o.output += output;
// soon the firmware will support returning the return int value of the scout script function/expression. it willbe the property return.
if(ret) {
o.return = ret;
}
js._cid = js.id;
js.id = o.id;
if(js.err || js.end) {
delete stream.callbacks[js._cid];
js.reply = js.output = o.output;
js.return = o.return;
o.cb(js.err,js)
}
} else if(js.type == "report" && line == stream._lastreport){
// duplicate reports are not really useful to propagate as events because nothing changed.
return;// stream.log('duplicate report ',line);
} else if (js.type == "report") {
stream._lastreport = line;
stream.queue(js);// send report in stream.
} else {
stream.log('unknown message type',js);
}
} | javascript | function handle(js,line){
// handle message from board.
//stream.log("handle",stream.token,line);
var hasToken = stream.token;
if(js.type == "token") {
// send in event stream.
stream.queue(js);
stream.token = js.token;
if(!hasToken) {
readycb(false,stream);
clearTimeout(readyTimeout);
}
return;
}
if(!stream.token) return stream.log('data from socket before auth/id token.',js);
if(js.type == 'reply'){
o = stream.callbacks[js.id]||{};
if(o.id === undefined) return stream.log('got reply with no id mapping! ',js);
var output = js.output||js.reply||"";
var ret = js.return;// not set yet.
if(!o.output) o.output = "";
// handle chunked responses. they come in order.
o.output += output;
// soon the firmware will support returning the return int value of the scout script function/expression. it willbe the property return.
if(ret) {
o.return = ret;
}
js._cid = js.id;
js.id = o.id;
if(js.err || js.end) {
delete stream.callbacks[js._cid];
js.reply = js.output = o.output;
js.return = o.return;
o.cb(js.err,js)
}
} else if(js.type == "report" && line == stream._lastreport){
// duplicate reports are not really useful to propagate as events because nothing changed.
return;// stream.log('duplicate report ',line);
} else if (js.type == "report") {
stream._lastreport = line;
stream.queue(js);// send report in stream.
} else {
stream.log('unknown message type',js);
}
} | [
"function",
"handle",
"(",
"js",
",",
"line",
")",
"{",
"// handle message from board.",
"//stream.log(\"handle\",stream.token,line);",
"var",
"hasToken",
"=",
"stream",
".",
"token",
";",
"if",
"(",
"js",
".",
"type",
"==",
"\"token\"",
")",
"{",
"// send in event stream.",
"stream",
".",
"queue",
"(",
"js",
")",
";",
"stream",
".",
"token",
"=",
"js",
".",
"token",
";",
"if",
"(",
"!",
"hasToken",
")",
"{",
"readycb",
"(",
"false",
",",
"stream",
")",
";",
"clearTimeout",
"(",
"readyTimeout",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"!",
"stream",
".",
"token",
")",
"return",
"stream",
".",
"log",
"(",
"'data from socket before auth/id token.'",
",",
"js",
")",
";",
"if",
"(",
"js",
".",
"type",
"==",
"'reply'",
")",
"{",
"o",
"=",
"stream",
".",
"callbacks",
"[",
"js",
".",
"id",
"]",
"||",
"{",
"}",
";",
"if",
"(",
"o",
".",
"id",
"===",
"undefined",
")",
"return",
"stream",
".",
"log",
"(",
"'got reply with no id mapping! '",
",",
"js",
")",
";",
"var",
"output",
"=",
"js",
".",
"output",
"||",
"js",
".",
"reply",
"||",
"\"\"",
";",
"var",
"ret",
"=",
"js",
".",
"return",
";",
"// not set yet.",
"if",
"(",
"!",
"o",
".",
"output",
")",
"o",
".",
"output",
"=",
"\"\"",
";",
"// handle chunked responses. they come in order.",
"o",
".",
"output",
"+=",
"output",
";",
"// soon the firmware will support returning the return int value of the scout script function/expression. it willbe the property return.",
"if",
"(",
"ret",
")",
"{",
"o",
".",
"return",
"=",
"ret",
";",
"}",
"js",
".",
"_cid",
"=",
"js",
".",
"id",
";",
"js",
".",
"id",
"=",
"o",
".",
"id",
";",
"if",
"(",
"js",
".",
"err",
"||",
"js",
".",
"end",
")",
"{",
"delete",
"stream",
".",
"callbacks",
"[",
"js",
".",
"_cid",
"]",
";",
"js",
".",
"reply",
"=",
"js",
".",
"output",
"=",
"o",
".",
"output",
";",
"js",
".",
"return",
"=",
"o",
".",
"return",
";",
"o",
".",
"cb",
"(",
"js",
".",
"err",
",",
"js",
")",
"}",
"}",
"else",
"if",
"(",
"js",
".",
"type",
"==",
"\"report\"",
"&&",
"line",
"==",
"stream",
".",
"_lastreport",
")",
"{",
"// duplicate reports are not really useful to propagate as events because nothing changed.",
"return",
";",
"// stream.log('duplicate report ',line);",
"}",
"else",
"if",
"(",
"js",
".",
"type",
"==",
"\"report\"",
")",
"{",
"stream",
".",
"_lastreport",
"=",
"line",
";",
"stream",
".",
"queue",
"(",
"js",
")",
";",
"// send report in stream.",
"}",
"else",
"{",
"stream",
".",
"log",
"(",
"'unknown message type'",
",",
"js",
")",
";",
"}",
"}"
] | cannot send commands to boards that have not provided a token. | [
"cannot",
"send",
"commands",
"to",
"boards",
"that",
"have",
"not",
"provided",
"a",
"token",
"."
] | 5be3196d1ec8f340aaa3ca96282f871a243943df | https://github.com/soldair/pinoccio-server/blob/5be3196d1ec8f340aaa3ca96282f871a243943df/troop.js#L97-L156 |
48,607 | kchapelier/in-browser-download | index.js | getElement | function getElement () {
if (element === null) {
element = document.createElement('a');
element.innerText = 'Download';
element.style.position = 'absolute';
element.style.top = '-100px';
element.style.left = '0px';
}
return element;
} | javascript | function getElement () {
if (element === null) {
element = document.createElement('a');
element.innerText = 'Download';
element.style.position = 'absolute';
element.style.top = '-100px';
element.style.left = '0px';
}
return element;
} | [
"function",
"getElement",
"(",
")",
"{",
"if",
"(",
"element",
"===",
"null",
")",
"{",
"element",
"=",
"document",
".",
"createElement",
"(",
"'a'",
")",
";",
"element",
".",
"innerText",
"=",
"'Download'",
";",
"element",
".",
"style",
".",
"position",
"=",
"'absolute'",
";",
"element",
".",
"style",
".",
"top",
"=",
"'-100px'",
";",
"element",
".",
"style",
".",
"left",
"=",
"'0px'",
";",
"}",
"return",
"element",
";",
"}"
] | Get an anchor element.
@returns {HTMLElement} | [
"Get",
"an",
"anchor",
"element",
"."
] | 84cad967f85e8bd897c9587b5e87a1b0d9159c3a | https://github.com/kchapelier/in-browser-download/blob/84cad967f85e8bd897c9587b5e87a1b0d9159c3a/index.js#L11-L21 |
48,608 | kchapelier/in-browser-download | index.js | getObjectUrl | function getObjectUrl (data) {
let blob;
if (typeof data === 'object' && data.constructor.name === 'Blob') {
blob = data;
} else if (typeof data === 'string') {
blob = new Blob([getTextEncoder().encode(data).buffer], {
type: 'application/octet-stream'
});
} else if (typeof data === 'object' && data.constructor && data.constructor.name === 'ArrayBuffer') {
blob = new Blob([data], {
type: 'application/octet-stream'
});
} else {
throw new Error('in-browser-download: Data must either be a Blob, a string or an ArrayBuffer');
}
return URL.createObjectURL(blob);
} | javascript | function getObjectUrl (data) {
let blob;
if (typeof data === 'object' && data.constructor.name === 'Blob') {
blob = data;
} else if (typeof data === 'string') {
blob = new Blob([getTextEncoder().encode(data).buffer], {
type: 'application/octet-stream'
});
} else if (typeof data === 'object' && data.constructor && data.constructor.name === 'ArrayBuffer') {
blob = new Blob([data], {
type: 'application/octet-stream'
});
} else {
throw new Error('in-browser-download: Data must either be a Blob, a string or an ArrayBuffer');
}
return URL.createObjectURL(blob);
} | [
"function",
"getObjectUrl",
"(",
"data",
")",
"{",
"let",
"blob",
";",
"if",
"(",
"typeof",
"data",
"===",
"'object'",
"&&",
"data",
".",
"constructor",
".",
"name",
"===",
"'Blob'",
")",
"{",
"blob",
"=",
"data",
";",
"}",
"else",
"if",
"(",
"typeof",
"data",
"===",
"'string'",
")",
"{",
"blob",
"=",
"new",
"Blob",
"(",
"[",
"getTextEncoder",
"(",
")",
".",
"encode",
"(",
"data",
")",
".",
"buffer",
"]",
",",
"{",
"type",
":",
"'application/octet-stream'",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"data",
"===",
"'object'",
"&&",
"data",
".",
"constructor",
"&&",
"data",
".",
"constructor",
".",
"name",
"===",
"'ArrayBuffer'",
")",
"{",
"blob",
"=",
"new",
"Blob",
"(",
"[",
"data",
"]",
",",
"{",
"type",
":",
"'application/octet-stream'",
"}",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'in-browser-download: Data must either be a Blob, a string or an ArrayBuffer'",
")",
";",
"}",
"return",
"URL",
".",
"createObjectURL",
"(",
"blob",
")",
";",
"}"
] | Return an object URL based on the given data.
@param {string|Blob|ArrayBuffer} data
@returns {*} | [
"Return",
"an",
"object",
"URL",
"based",
"on",
"the",
"given",
"data",
"."
] | 84cad967f85e8bd897c9587b5e87a1b0d9159c3a | https://github.com/kchapelier/in-browser-download/blob/84cad967f85e8bd897c9587b5e87a1b0d9159c3a/index.js#L43-L61 |
48,609 | kchapelier/in-browser-download | index.js | download | function download (data, filename) {
const element = getElement();
const url = getObjectUrl(data);
element.setAttribute('href', url);
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
setTimeout(function () {
URL.revokeObjectURL(url);
}, 100);
} | javascript | function download (data, filename) {
const element = getElement();
const url = getObjectUrl(data);
element.setAttribute('href', url);
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
setTimeout(function () {
URL.revokeObjectURL(url);
}, 100);
} | [
"function",
"download",
"(",
"data",
",",
"filename",
")",
"{",
"const",
"element",
"=",
"getElement",
"(",
")",
";",
"const",
"url",
"=",
"getObjectUrl",
"(",
"data",
")",
";",
"element",
".",
"setAttribute",
"(",
"'href'",
",",
"url",
")",
";",
"element",
".",
"setAttribute",
"(",
"'download'",
",",
"filename",
")",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"element",
")",
";",
"element",
".",
"click",
"(",
")",
";",
"document",
".",
"body",
".",
"removeChild",
"(",
"element",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"URL",
".",
"revokeObjectURL",
"(",
"url",
")",
";",
"}",
",",
"100",
")",
";",
"}"
] | Download a Blob, a string or an ArrayBuffer as a file in the browser
@param {string|ArrayBuffer} data The content of the file to download.
@param {string} [filename] The name of the file to download. | [
"Download",
"a",
"Blob",
"a",
"string",
"or",
"an",
"ArrayBuffer",
"as",
"a",
"file",
"in",
"the",
"browser"
] | 84cad967f85e8bd897c9587b5e87a1b0d9159c3a | https://github.com/kchapelier/in-browser-download/blob/84cad967f85e8bd897c9587b5e87a1b0d9159c3a/index.js#L69-L82 |
48,610 | seek-oss/nodejs-consumer-pact-verifier | verifier.js | makeObjectKeysLC | function makeObjectKeysLC (o){
var keys = Object.keys(o);
var lcObject = {};
keys.forEach(function(k){
lcObject[k.toLowerCase()] = o[k];
});
return lcObject;
} | javascript | function makeObjectKeysLC (o){
var keys = Object.keys(o);
var lcObject = {};
keys.forEach(function(k){
lcObject[k.toLowerCase()] = o[k];
});
return lcObject;
} | [
"function",
"makeObjectKeysLC",
"(",
"o",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"o",
")",
";",
"var",
"lcObject",
"=",
"{",
"}",
";",
"keys",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"lcObject",
"[",
"k",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"o",
"[",
"k",
"]",
";",
"}",
")",
";",
"return",
"lcObject",
";",
"}"
] | Private API
Takes an object and lower-cases its' keys
@param {Object} o Expected to be a set of headers
@return {Object} New object with lowercase keys | [
"Private",
"API",
"Takes",
"an",
"object",
"and",
"lower",
"-",
"cases",
"its",
"keys"
] | b7685a3283a8b51bd55d3e35f8918480b486df8e | https://github.com/seek-oss/nodejs-consumer-pact-verifier/blob/b7685a3283a8b51bd55d3e35f8918480b486df8e/verifier.js#L14-L21 |
48,611 | arendjr/laces.js | laces.js | LacesObject | function LacesObject(options) {
Object.defineProperty(this, "_bindings", { "value": [], "writable": true });
Object.defineProperty(this, "_eventListeners", { "value": {}, "writable": true });
Object.defineProperty(this, "_heldEvents", { "value": null, "writable": true });
Object.defineProperty(this, "_gotLaces", { "value": true });
Object.defineProperty(this, "_options", { "value": options || {} });
} | javascript | function LacesObject(options) {
Object.defineProperty(this, "_bindings", { "value": [], "writable": true });
Object.defineProperty(this, "_eventListeners", { "value": {}, "writable": true });
Object.defineProperty(this, "_heldEvents", { "value": null, "writable": true });
Object.defineProperty(this, "_gotLaces", { "value": true });
Object.defineProperty(this, "_options", { "value": options || {} });
} | [
"function",
"LacesObject",
"(",
"options",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"_bindings\"",
",",
"{",
"\"value\"",
":",
"[",
"]",
",",
"\"writable\"",
":",
"true",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"_eventListeners\"",
",",
"{",
"\"value\"",
":",
"{",
"}",
",",
"\"writable\"",
":",
"true",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"_heldEvents\"",
",",
"{",
"\"value\"",
":",
"null",
",",
"\"writable\"",
":",
"true",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"_gotLaces\"",
",",
"{",
"\"value\"",
":",
"true",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"_options\"",
",",
"{",
"\"value\"",
":",
"options",
"||",
"{",
"}",
"}",
")",
";",
"}"
] | Laces Object constructor. This is the base class for the other laces object types. You should not instantiate this class directly. Instead, use LacesArray, LacesMap or LacesModel. The methods defined here are available on all said object types. | [
"Laces",
"Object",
"constructor",
".",
"This",
"is",
"the",
"base",
"class",
"for",
"the",
"other",
"laces",
"object",
"types",
".",
"You",
"should",
"not",
"instantiate",
"this",
"class",
"directly",
".",
"Instead",
"use",
"LacesArray",
"LacesMap",
"or",
"LacesModel",
".",
"The",
"methods",
"defined",
"here",
"are",
"available",
"on",
"all",
"said",
"object",
"types",
"."
] | e04fd060a4668abe58064267b1405e6a40f8a6f2 | https://github.com/arendjr/laces.js/blob/e04fd060a4668abe58064267b1405e6a40f8a6f2/laces.js#L10-L17 |
48,612 | MartinKolarik/ractive-render | lib/template.js | load | function load(file, options) {
if (options.cache && rr.cache['tpl!' + file]) {
return Promise.resolve(rr.cache['tpl!' + file]);
}
return fs.readFileAsync(file, 'utf8').then(function (template) {
return utils.wrap(Ractive.parse(template, options), options);
}).then(function (template) {
var basePath = path.relative(options.settings.views, path.dirname(file));
var cOptions = utils.buildOptions(options, null, true);
cOptions.template = template;
return Promise.join(utils.buildComponentsRegistry(cOptions), utils.buildPartialsRegistry(basePath, cOptions), function (components, partials) {
cOptions.components = components;
cOptions.partials = partials;
options.components = {};
options.partials = {};
var Component = Ractive.extend(cOptions);
if (options.cache) {
rr.cache['tpl!' + file] = Component;
}
return Component;
});
});
} | javascript | function load(file, options) {
if (options.cache && rr.cache['tpl!' + file]) {
return Promise.resolve(rr.cache['tpl!' + file]);
}
return fs.readFileAsync(file, 'utf8').then(function (template) {
return utils.wrap(Ractive.parse(template, options), options);
}).then(function (template) {
var basePath = path.relative(options.settings.views, path.dirname(file));
var cOptions = utils.buildOptions(options, null, true);
cOptions.template = template;
return Promise.join(utils.buildComponentsRegistry(cOptions), utils.buildPartialsRegistry(basePath, cOptions), function (components, partials) {
cOptions.components = components;
cOptions.partials = partials;
options.components = {};
options.partials = {};
var Component = Ractive.extend(cOptions);
if (options.cache) {
rr.cache['tpl!' + file] = Component;
}
return Component;
});
});
} | [
"function",
"load",
"(",
"file",
",",
"options",
")",
"{",
"if",
"(",
"options",
".",
"cache",
"&&",
"rr",
".",
"cache",
"[",
"'tpl!'",
"+",
"file",
"]",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"rr",
".",
"cache",
"[",
"'tpl!'",
"+",
"file",
"]",
")",
";",
"}",
"return",
"fs",
".",
"readFileAsync",
"(",
"file",
",",
"'utf8'",
")",
".",
"then",
"(",
"function",
"(",
"template",
")",
"{",
"return",
"utils",
".",
"wrap",
"(",
"Ractive",
".",
"parse",
"(",
"template",
",",
"options",
")",
",",
"options",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"template",
")",
"{",
"var",
"basePath",
"=",
"path",
".",
"relative",
"(",
"options",
".",
"settings",
".",
"views",
",",
"path",
".",
"dirname",
"(",
"file",
")",
")",
";",
"var",
"cOptions",
"=",
"utils",
".",
"buildOptions",
"(",
"options",
",",
"null",
",",
"true",
")",
";",
"cOptions",
".",
"template",
"=",
"template",
";",
"return",
"Promise",
".",
"join",
"(",
"utils",
".",
"buildComponentsRegistry",
"(",
"cOptions",
")",
",",
"utils",
".",
"buildPartialsRegistry",
"(",
"basePath",
",",
"cOptions",
")",
",",
"function",
"(",
"components",
",",
"partials",
")",
"{",
"cOptions",
".",
"components",
"=",
"components",
";",
"cOptions",
".",
"partials",
"=",
"partials",
";",
"options",
".",
"components",
"=",
"{",
"}",
";",
"options",
".",
"partials",
"=",
"{",
"}",
";",
"var",
"Component",
"=",
"Ractive",
".",
"extend",
"(",
"cOptions",
")",
";",
"if",
"(",
"options",
".",
"cache",
")",
"{",
"rr",
".",
"cache",
"[",
"'tpl!'",
"+",
"file",
"]",
"=",
"Component",
";",
"}",
"return",
"Component",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Create a component from the given file
@param {String} file
@param {Object} options
@returns {Promise}
@public | [
"Create",
"a",
"component",
"from",
"the",
"given",
"file"
] | 417a97c42de4b1ea6c1ab13803f5470b3cc6f75a | https://github.com/MartinKolarik/ractive-render/blob/417a97c42de4b1ea6c1ab13803f5470b3cc6f75a/lib/template.js#L21-L48 |
48,613 | fatalxiao/js-markdown | src/lib/syntax/block/Table.js | generateTableTree | function generateTableTree(head, separator) {
return {
type: 'Table',
children: [{
type: 'TableHead',
children: [{
type: 'TableRow',
children: head.map((rawValue, index) => ({
type: 'TableHeadCell',
align: separator[index],
rawValue
}))
}]
}]
};
} | javascript | function generateTableTree(head, separator) {
return {
type: 'Table',
children: [{
type: 'TableHead',
children: [{
type: 'TableRow',
children: head.map((rawValue, index) => ({
type: 'TableHeadCell',
align: separator[index],
rawValue
}))
}]
}]
};
} | [
"function",
"generateTableTree",
"(",
"head",
",",
"separator",
")",
"{",
"return",
"{",
"type",
":",
"'Table'",
",",
"children",
":",
"[",
"{",
"type",
":",
"'TableHead'",
",",
"children",
":",
"[",
"{",
"type",
":",
"'TableRow'",
",",
"children",
":",
"head",
".",
"map",
"(",
"(",
"rawValue",
",",
"index",
")",
"=>",
"(",
"{",
"type",
":",
"'TableHeadCell'",
",",
"align",
":",
"separator",
"[",
"index",
"]",
",",
"rawValue",
"}",
")",
")",
"}",
"]",
"}",
"]",
"}",
";",
"}"
] | get the initial table render tree that includes headers
@param head
@param separator
@returns {{type: string, children: [*]}} | [
"get",
"the",
"initial",
"table",
"render",
"tree",
"that",
"includes",
"headers"
] | dffa23be561f50282e5ccc2f1595a51d18a81246 | https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/syntax/block/Table.js#L36-L51 |
48,614 | fatalxiao/js-markdown | src/lib/syntax/block/Table.js | generateTableRowNode | function generateTableRowNode(line, separator) {
const tableRow = {
type: 'TableRow',
children: separator.map(align => ({
type: 'TableDataCell',
align
}))
};
for (let i = 0, data = calRow(line), len = data.length; i < len; i++) {
tableRow.children[i].rawValue = data[i];
}
return tableRow;
} | javascript | function generateTableRowNode(line, separator) {
const tableRow = {
type: 'TableRow',
children: separator.map(align => ({
type: 'TableDataCell',
align
}))
};
for (let i = 0, data = calRow(line), len = data.length; i < len; i++) {
tableRow.children[i].rawValue = data[i];
}
return tableRow;
} | [
"function",
"generateTableRowNode",
"(",
"line",
",",
"separator",
")",
"{",
"const",
"tableRow",
"=",
"{",
"type",
":",
"'TableRow'",
",",
"children",
":",
"separator",
".",
"map",
"(",
"align",
"=>",
"(",
"{",
"type",
":",
"'TableDataCell'",
",",
"align",
"}",
")",
")",
"}",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"data",
"=",
"calRow",
"(",
"line",
")",
",",
"len",
"=",
"data",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"tableRow",
".",
"children",
"[",
"i",
"]",
".",
"rawValue",
"=",
"data",
"[",
"i",
"]",
";",
"}",
"return",
"tableRow",
";",
"}"
] | return a table row that includes table data cells
@param line
@param separator
@returns {{type: string, children}} | [
"return",
"a",
"table",
"row",
"that",
"includes",
"table",
"data",
"cells"
] | dffa23be561f50282e5ccc2f1595a51d18a81246 | https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/syntax/block/Table.js#L83-L99 |
48,615 | fatalxiao/js-markdown | src/lib/syntax/block/Table.js | calSeparator | function calSeparator(str) {
return calRow(str).map(item => {
if (item.startsWith(':') && item.endsWith(':')) {
return 'center';
} else if (item.startsWith(':')) {
return 'left';
} else if (item.endsWith(':')) {
return 'right';
} else if (item.endsWith(':')) {
return '';
}
});
} | javascript | function calSeparator(str) {
return calRow(str).map(item => {
if (item.startsWith(':') && item.endsWith(':')) {
return 'center';
} else if (item.startsWith(':')) {
return 'left';
} else if (item.endsWith(':')) {
return 'right';
} else if (item.endsWith(':')) {
return '';
}
});
} | [
"function",
"calSeparator",
"(",
"str",
")",
"{",
"return",
"calRow",
"(",
"str",
")",
".",
"map",
"(",
"item",
"=>",
"{",
"if",
"(",
"item",
".",
"startsWith",
"(",
"':'",
")",
"&&",
"item",
".",
"endsWith",
"(",
"':'",
")",
")",
"{",
"return",
"'center'",
";",
"}",
"else",
"if",
"(",
"item",
".",
"startsWith",
"(",
"':'",
")",
")",
"{",
"return",
"'left'",
";",
"}",
"else",
"if",
"(",
"item",
".",
"endsWith",
"(",
"':'",
")",
")",
"{",
"return",
"'right'",
";",
"}",
"else",
"if",
"(",
"item",
".",
"endsWith",
"(",
"':'",
")",
")",
"{",
"return",
"''",
";",
"}",
"}",
")",
";",
"}"
] | parse the separator line, and return a align info
@param str
@returns {Array} | [
"parse",
"the",
"separator",
"line",
"and",
"return",
"a",
"align",
"info"
] | dffa23be561f50282e5ccc2f1595a51d18a81246 | https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/syntax/block/Table.js#L106-L118 |
48,616 | mhdawson/google-auth-wrapper | lib/googleAuthWrapper.js | createOauthClient | function createOauthClient(storagePath, clientSecrets) {
var secrets = fs.readFileSync(path.join(storagePath, clientSecrets + '.json'));
if (secrets === undefined) {
throw new Error('failed to read secrets file');
}
secrets = JSON.parse(secrets);
var gAuth = new googleAuth();
var oauthClient = new gAuth.OAuth2(secrets.installed.client_id,
secrets.installed.client_secret,
secrets.installed.redirect_uris[0]);
return oauthClient;
} | javascript | function createOauthClient(storagePath, clientSecrets) {
var secrets = fs.readFileSync(path.join(storagePath, clientSecrets + '.json'));
if (secrets === undefined) {
throw new Error('failed to read secrets file');
}
secrets = JSON.parse(secrets);
var gAuth = new googleAuth();
var oauthClient = new gAuth.OAuth2(secrets.installed.client_id,
secrets.installed.client_secret,
secrets.installed.redirect_uris[0]);
return oauthClient;
} | [
"function",
"createOauthClient",
"(",
"storagePath",
",",
"clientSecrets",
")",
"{",
"var",
"secrets",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"storagePath",
",",
"clientSecrets",
"+",
"'.json'",
")",
")",
";",
"if",
"(",
"secrets",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"'failed to read secrets file'",
")",
";",
"}",
"secrets",
"=",
"JSON",
".",
"parse",
"(",
"secrets",
")",
";",
"var",
"gAuth",
"=",
"new",
"googleAuth",
"(",
")",
";",
"var",
"oauthClient",
"=",
"new",
"gAuth",
".",
"OAuth2",
"(",
"secrets",
".",
"installed",
".",
"client_id",
",",
"secrets",
".",
"installed",
".",
"client_secret",
",",
"secrets",
".",
"installed",
".",
"redirect_uris",
"[",
"0",
"]",
")",
";",
"return",
"oauthClient",
";",
"}"
] | common parts of oauth client creation | [
"common",
"parts",
"of",
"oauth",
"client",
"creation"
] | 7052af71889b4c72904be784b1fdde955782ec15 | https://github.com/mhdawson/google-auth-wrapper/blob/7052af71889b4c72904be784b1fdde955782ec15/lib/googleAuthWrapper.js#L81-L93 |
48,617 | meetings/gearsloth | lib/controllers/retry.js | Retry | function Retry(conf) {
component.Component.call(this, 'controller', conf);
this.registerGearman(conf.servers, {
client: true,
worker: {
func_name: 'retryController',
func: _.bind( function(json_string, worker) {
try {
// TODO: this parsing and meta parameter storing should be encapsulated into a Task class
var task = JSON.parse( json_string.toString() );
task._task_json_string = json_string;
task._task_worker = worker;
this.execute_task( task );
}
catch ( e ) {
_err( 'Error executing retryController with following payload:', json_string );
}
}, this )
}
});
} | javascript | function Retry(conf) {
component.Component.call(this, 'controller', conf);
this.registerGearman(conf.servers, {
client: true,
worker: {
func_name: 'retryController',
func: _.bind( function(json_string, worker) {
try {
// TODO: this parsing and meta parameter storing should be encapsulated into a Task class
var task = JSON.parse( json_string.toString() );
task._task_json_string = json_string;
task._task_worker = worker;
this.execute_task( task );
}
catch ( e ) {
_err( 'Error executing retryController with following payload:', json_string );
}
}, this )
}
});
} | [
"function",
"Retry",
"(",
"conf",
")",
"{",
"component",
".",
"Component",
".",
"call",
"(",
"this",
",",
"'controller'",
",",
"conf",
")",
";",
"this",
".",
"registerGearman",
"(",
"conf",
".",
"servers",
",",
"{",
"client",
":",
"true",
",",
"worker",
":",
"{",
"func_name",
":",
"'retryController'",
",",
"func",
":",
"_",
".",
"bind",
"(",
"function",
"(",
"json_string",
",",
"worker",
")",
"{",
"try",
"{",
"// TODO: this parsing and meta parameter storing should be encapsulated into a Task class",
"var",
"task",
"=",
"JSON",
".",
"parse",
"(",
"json_string",
".",
"toString",
"(",
")",
")",
";",
"task",
".",
"_task_json_string",
"=",
"json_string",
";",
"task",
".",
"_task_worker",
"=",
"worker",
";",
"this",
".",
"execute_task",
"(",
"task",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"_err",
"(",
"'Error executing retryController with following payload:'",
",",
"json_string",
")",
";",
"}",
"}",
",",
"this",
")",
"}",
"}",
")",
";",
"}"
] | Retry component. Emits 'connect' when at least one server for both
worker and client roles are connected to. | [
"Retry",
"component",
".",
"Emits",
"connect",
"when",
"at",
"least",
"one",
"server",
"for",
"both",
"worker",
"and",
"client",
"roles",
"are",
"connected",
"to",
"."
] | 21d07729d6197bdbea515f32922896e3ae485d46 | https://github.com/meetings/gearsloth/blob/21d07729d6197bdbea515f32922896e3ae485d46/lib/controllers/retry.js#L10-L31 |
48,618 | wilmoore/string-split.js | index.js | split | function split (splitBy, string) {
return (typeof splitBy === 'function')
? predicate(splitBy, string)
: string.split(splitBy)
} | javascript | function split (splitBy, string) {
return (typeof splitBy === 'function')
? predicate(splitBy, string)
: string.split(splitBy)
} | [
"function",
"split",
"(",
"splitBy",
",",
"string",
")",
"{",
"return",
"(",
"typeof",
"splitBy",
"===",
"'function'",
")",
"?",
"predicate",
"(",
"splitBy",
",",
"string",
")",
":",
"string",
".",
"split",
"(",
"splitBy",
")",
"}"
] | A curried `String.prototype.split` with support
for splitting by String, RegExp, or Function.
@param {String|RegExp|Function} splitBy
String, RegExp, or Function to split by.
@param {String} string
String to split.
@return {Array}
List of split string parts. | [
"A",
"curried",
"String",
".",
"prototype",
".",
"split",
"with",
"support",
"for",
"splitting",
"by",
"String",
"RegExp",
"or",
"Function",
"."
] | 3584c106212c45c7a26c9f9b4f2b70e3b3b07d07 | https://github.com/wilmoore/string-split.js/blob/3584c106212c45c7a26c9f9b4f2b70e3b3b07d07/index.js#L29-L33 |
48,619 | wilmoore/string-split.js | index.js | predicate | function predicate (fn, string) {
var idx = -1
var end = string.length
var out = []
var buf = ''
while (++idx < end) {
if (fn(string[idx], idx) === true) {
if (buf) out.push(buf)
buf = ''
} else {
buf += string[idx]
}
}
if (buf) out.push(buf)
return out
} | javascript | function predicate (fn, string) {
var idx = -1
var end = string.length
var out = []
var buf = ''
while (++idx < end) {
if (fn(string[idx], idx) === true) {
if (buf) out.push(buf)
buf = ''
} else {
buf += string[idx]
}
}
if (buf) out.push(buf)
return out
} | [
"function",
"predicate",
"(",
"fn",
",",
"string",
")",
"{",
"var",
"idx",
"=",
"-",
"1",
"var",
"end",
"=",
"string",
".",
"length",
"var",
"out",
"=",
"[",
"]",
"var",
"buf",
"=",
"''",
"while",
"(",
"++",
"idx",
"<",
"end",
")",
"{",
"if",
"(",
"fn",
"(",
"string",
"[",
"idx",
"]",
",",
"idx",
")",
"===",
"true",
")",
"{",
"if",
"(",
"buf",
")",
"out",
".",
"push",
"(",
"buf",
")",
"buf",
"=",
"''",
"}",
"else",
"{",
"buf",
"+=",
"string",
"[",
"idx",
"]",
"}",
"}",
"if",
"(",
"buf",
")",
"out",
".",
"push",
"(",
"buf",
")",
"return",
"out",
"}"
] | Split via predicate function.
@param {Function} fn
Predicate function.
@param {String} string
String to split.
@return {Array}
List of split string parts. | [
"Split",
"via",
"predicate",
"function",
"."
] | 3584c106212c45c7a26c9f9b4f2b70e3b3b07d07 | https://github.com/wilmoore/string-split.js/blob/3584c106212c45c7a26c9f9b4f2b70e3b3b07d07/index.js#L48-L65 |
48,620 | syarul/passwordless-nedb | lib/nedb.js | NedbStore | function NedbStore(datastore, documentsName) {
if(arguments.length === 0 || typeof datastore !== 'object') {
throw new Error('Valid datastore parameter have to be provided')
}
if (arguments[1]) {
if (typeof arguments[1] !== 'string') {
throw new Error('documentsName must be a valid string')
}
}
TokenStore.call(this)
this._documentsName = documentsName || 'passwordless-token'
this._db = datastore
} | javascript | function NedbStore(datastore, documentsName) {
if(arguments.length === 0 || typeof datastore !== 'object') {
throw new Error('Valid datastore parameter have to be provided')
}
if (arguments[1]) {
if (typeof arguments[1] !== 'string') {
throw new Error('documentsName must be a valid string')
}
}
TokenStore.call(this)
this._documentsName = documentsName || 'passwordless-token'
this._db = datastore
} | [
"function",
"NedbStore",
"(",
"datastore",
",",
"documentsName",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
"||",
"typeof",
"datastore",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Valid datastore parameter have to be provided'",
")",
"}",
"if",
"(",
"arguments",
"[",
"1",
"]",
")",
"{",
"if",
"(",
"typeof",
"arguments",
"[",
"1",
"]",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'documentsName must be a valid string'",
")",
"}",
"}",
"TokenStore",
".",
"call",
"(",
"this",
")",
"this",
".",
"_documentsName",
"=",
"documentsName",
"||",
"'passwordless-token'",
"this",
".",
"_db",
"=",
"datastore",
"}"
] | Constructor of NedbStore
@param {Object} [datastore] the data storage declared upon creation/loading
as defined by the NeDB specification. Please check the documentation for
details: https://github.com/louischatriot/nedb
@param {String} [documentsName] A valid string identifier. All created
documents within database has value { _lib: passwordless-token } as the
default reference, this will override the default name. Usefull for easy
indexing and search when you want to integrate the database with other
documents as well
@constructor | [
"Constructor",
"of",
"NedbStore"
] | 249a96111d240f74e091ef250225f9d8c863a75a | https://github.com/syarul/passwordless-nedb/blob/249a96111d240f74e091ef250225f9d8c863a75a/lib/nedb.js#L19-L34 |
48,621 | eventsauce/eventsauce | lib/overload.js | compatible | function compatible(value, descriptor) {
if (!value) {
// If we're a null, then we can't validate.
return false;
} else if (!descriptor) {
return true;
}
const descriptorType = typeof descriptor;
if (descriptorType === 'string') {
return typeof value === descriptor;
} else if (descriptorType === 'function') {
return descriptor(value);
} else if (descriptorType === 'object') {
let matched = true;
Object.keys(descriptor).forEach((key) => {
const fromValue = value[key];
const fromDescriptor = descriptor[key];
if (!compatible(fromValue, fromDescriptor)) {
matched = false;
}
});
return matched;
}
throw new Error('Unknown descriptor type: ' + descriptorType);
} | javascript | function compatible(value, descriptor) {
if (!value) {
// If we're a null, then we can't validate.
return false;
} else if (!descriptor) {
return true;
}
const descriptorType = typeof descriptor;
if (descriptorType === 'string') {
return typeof value === descriptor;
} else if (descriptorType === 'function') {
return descriptor(value);
} else if (descriptorType === 'object') {
let matched = true;
Object.keys(descriptor).forEach((key) => {
const fromValue = value[key];
const fromDescriptor = descriptor[key];
if (!compatible(fromValue, fromDescriptor)) {
matched = false;
}
});
return matched;
}
throw new Error('Unknown descriptor type: ' + descriptorType);
} | [
"function",
"compatible",
"(",
"value",
",",
"descriptor",
")",
"{",
"if",
"(",
"!",
"value",
")",
"{",
"// If we're a null, then we can't validate.",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"!",
"descriptor",
")",
"{",
"return",
"true",
";",
"}",
"const",
"descriptorType",
"=",
"typeof",
"descriptor",
";",
"if",
"(",
"descriptorType",
"===",
"'string'",
")",
"{",
"return",
"typeof",
"value",
"===",
"descriptor",
";",
"}",
"else",
"if",
"(",
"descriptorType",
"===",
"'function'",
")",
"{",
"return",
"descriptor",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"descriptorType",
"===",
"'object'",
")",
"{",
"let",
"matched",
"=",
"true",
";",
"Object",
".",
"keys",
"(",
"descriptor",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"const",
"fromValue",
"=",
"value",
"[",
"key",
"]",
";",
"const",
"fromDescriptor",
"=",
"descriptor",
"[",
"key",
"]",
";",
"if",
"(",
"!",
"compatible",
"(",
"fromValue",
",",
"fromDescriptor",
")",
")",
"{",
"matched",
"=",
"false",
";",
"}",
"}",
")",
";",
"return",
"matched",
";",
"}",
"throw",
"new",
"Error",
"(",
"'Unknown descriptor type: '",
"+",
"descriptorType",
")",
";",
"}"
] | Is the specified value equivelent to the descriptor?
@param {object} value - Value to check.
@param {object} descriptor - Descriptor to compare to.
@returns {Boolean} - True if equivelent. | [
"Is",
"the",
"specified",
"value",
"equivelent",
"to",
"the",
"descriptor?"
] | 934fb22134e0408861e3d2a5338c4ecc07ad4843 | https://github.com/eventsauce/eventsauce/blob/934fb22134e0408861e3d2a5338c4ecc07ad4843/lib/overload.js#L15-L41 |
48,622 | eventsauce/eventsauce | lib/overload.js | match | function match(args, typeMap) {
// No arguments, no win.
if (!args || !args.length) {
throw new Error('Cannot perform overload.match: args must be non-null array');
} else if (!typeMap || !typeMap.length) {
// We always satisfy a null or empty typeMap
return true;
}
// Validate the arguments one by one
for (let index = 0; index < args.length; index++) {
if (!compatible(args[index], typeMap[index])) {
return false;
}
}
// If not incompatible, sucess
return true;
} | javascript | function match(args, typeMap) {
// No arguments, no win.
if (!args || !args.length) {
throw new Error('Cannot perform overload.match: args must be non-null array');
} else if (!typeMap || !typeMap.length) {
// We always satisfy a null or empty typeMap
return true;
}
// Validate the arguments one by one
for (let index = 0; index < args.length; index++) {
if (!compatible(args[index], typeMap[index])) {
return false;
}
}
// If not incompatible, sucess
return true;
} | [
"function",
"match",
"(",
"args",
",",
"typeMap",
")",
"{",
"// No arguments, no win.",
"if",
"(",
"!",
"args",
"||",
"!",
"args",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot perform overload.match: args must be non-null array'",
")",
";",
"}",
"else",
"if",
"(",
"!",
"typeMap",
"||",
"!",
"typeMap",
".",
"length",
")",
"{",
"// We always satisfy a null or empty typeMap",
"return",
"true",
";",
"}",
"// Validate the arguments one by one",
"for",
"(",
"let",
"index",
"=",
"0",
";",
"index",
"<",
"args",
".",
"length",
";",
"index",
"++",
")",
"{",
"if",
"(",
"!",
"compatible",
"(",
"args",
"[",
"index",
"]",
",",
"typeMap",
"[",
"index",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"// If not incompatible, sucess",
"return",
"true",
";",
"}"
] | Does the specified method match the overload requirements for the method?
@param {Array} args - Method arguments
@param {Array} typeMap - Type map
@returns {Boolean} - True if matches, false otherwise. | [
"Does",
"the",
"specified",
"method",
"match",
"the",
"overload",
"requirements",
"for",
"the",
"method?"
] | 934fb22134e0408861e3d2a5338c4ecc07ad4843 | https://github.com/eventsauce/eventsauce/blob/934fb22134e0408861e3d2a5338c4ecc07ad4843/lib/overload.js#L49-L67 |
48,623 | meetings/gearsloth | lib/daemon/runner.js | Runner | function Runner(conf) {
component.Component.call(this, 'runner', conf);
var that = this;
this._default_controller = defaults.controllerfuncname(conf);
this._dbconn = conf.dbconn;
this.registerGearman(conf.servers, { client: true });
this.on('connect', function() {
that.startPolling();
});
this.on('disconnect', function() {
if (that.db_poll_stop)
that.db_poll_stop();
});
} | javascript | function Runner(conf) {
component.Component.call(this, 'runner', conf);
var that = this;
this._default_controller = defaults.controllerfuncname(conf);
this._dbconn = conf.dbconn;
this.registerGearman(conf.servers, { client: true });
this.on('connect', function() {
that.startPolling();
});
this.on('disconnect', function() {
if (that.db_poll_stop)
that.db_poll_stop();
});
} | [
"function",
"Runner",
"(",
"conf",
")",
"{",
"component",
".",
"Component",
".",
"call",
"(",
"this",
",",
"'runner'",
",",
"conf",
")",
";",
"var",
"that",
"=",
"this",
";",
"this",
".",
"_default_controller",
"=",
"defaults",
".",
"controllerfuncname",
"(",
"conf",
")",
";",
"this",
".",
"_dbconn",
"=",
"conf",
".",
"dbconn",
";",
"this",
".",
"registerGearman",
"(",
"conf",
".",
"servers",
",",
"{",
"client",
":",
"true",
"}",
")",
";",
"this",
".",
"on",
"(",
"'connect'",
",",
"function",
"(",
")",
"{",
"that",
".",
"startPolling",
"(",
")",
";",
"}",
")",
";",
"this",
".",
"on",
"(",
"'disconnect'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"that",
".",
"db_poll_stop",
")",
"that",
".",
"db_poll_stop",
"(",
")",
";",
"}",
")",
";",
"}"
] | Runner component. Emits 'connect' when at least one server is connected. | [
"Runner",
"component",
".",
"Emits",
"connect",
"when",
"at",
"least",
"one",
"server",
"is",
"connected",
"."
] | 21d07729d6197bdbea515f32922896e3ae485d46 | https://github.com/meetings/gearsloth/blob/21d07729d6197bdbea515f32922896e3ae485d46/lib/daemon/runner.js#L8-L21 |
48,624 | naugtur/secure-dependencies | index.js | promiseCommand | function promiseCommand(command) {
const opts = {
env: process.env
};
console.log('>>>>', command)
return spawnShell(command, opts).exitPromise
.then((exitCode) => {
if (exitCode === 0) {
return;
} else {
throw Error("Exit " + exitCode)
}
})
} | javascript | function promiseCommand(command) {
const opts = {
env: process.env
};
console.log('>>>>', command)
return spawnShell(command, opts).exitPromise
.then((exitCode) => {
if (exitCode === 0) {
return;
} else {
throw Error("Exit " + exitCode)
}
})
} | [
"function",
"promiseCommand",
"(",
"command",
")",
"{",
"const",
"opts",
"=",
"{",
"env",
":",
"process",
".",
"env",
"}",
";",
"console",
".",
"log",
"(",
"'>>>>'",
",",
"command",
")",
"return",
"spawnShell",
"(",
"command",
",",
"opts",
")",
".",
"exitPromise",
".",
"then",
"(",
"(",
"exitCode",
")",
"=>",
"{",
"if",
"(",
"exitCode",
"===",
"0",
")",
"{",
"return",
";",
"}",
"else",
"{",
"throw",
"Error",
"(",
"\"Exit \"",
"+",
"exitCode",
")",
"}",
"}",
")",
"}"
] | The main purpose of this is to reject the promise based on exit code | [
"The",
"main",
"purpose",
"of",
"this",
"is",
"to",
"reject",
"the",
"promise",
"based",
"on",
"exit",
"code"
] | 6ccfe4078df31372f6f25011574291eba5d21832 | https://github.com/naugtur/secure-dependencies/blob/6ccfe4078df31372f6f25011574291eba5d21832/index.js#L60-L73 |
48,625 | thlorenz/resolve-jit-symbols | index.js | JITResolver | function JITResolver(map) {
if (!(this instanceof JITResolver)) return new JITResolver(map);
var lines = Array.isArray(map) ? map : map.split('\n')
this._addresses = lines
.reduce(processLine, [])
.sort(byDecimalAddress)
this._len = this._addresses.length;
} | javascript | function JITResolver(map) {
if (!(this instanceof JITResolver)) return new JITResolver(map);
var lines = Array.isArray(map) ? map : map.split('\n')
this._addresses = lines
.reduce(processLine, [])
.sort(byDecimalAddress)
this._len = this._addresses.length;
} | [
"function",
"JITResolver",
"(",
"map",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"JITResolver",
")",
")",
"return",
"new",
"JITResolver",
"(",
"map",
")",
";",
"var",
"lines",
"=",
"Array",
".",
"isArray",
"(",
"map",
")",
"?",
"map",
":",
"map",
".",
"split",
"(",
"'\\n'",
")",
"this",
".",
"_addresses",
"=",
"lines",
".",
"reduce",
"(",
"processLine",
",",
"[",
"]",
")",
".",
"sort",
"(",
"byDecimalAddress",
")",
"this",
".",
"_len",
"=",
"this",
".",
"_addresses",
".",
"length",
";",
"}"
] | Instantiates a JIT resolver for the given map.
@name JITResolver
@function
@param {String|Array.<String>} map either a string or lines with space separated HexAddress, Size, Symbol on each line
@return {Object} the initialized JIT resolver | [
"Instantiates",
"a",
"JIT",
"resolver",
"for",
"the",
"given",
"map",
"."
] | 465e9a8d5b923e22b30ae909b336e7943de2221d | https://github.com/thlorenz/resolve-jit-symbols/blob/465e9a8d5b923e22b30ae909b336e7943de2221d/index.js#L42-L51 |
48,626 | roeldev-deprecated-stuff/log-interceptor | lib/level.js | function($str)
{
if (!this.hasFormatOptions)
{
this.addToLog($str);
return false;
}
// strip colors from the string. this is ok with multilines
if (this.options.stripColor)
{
$str = Utils.stripColor($str);
}
var $result = [];
if (this.options.splitOnLinebreak)
{
var $split = Utils.splitOnLinebreak($str,
this.options.trimLinebreak);
for (var $i = 0, $iL = $split.length; $i < $iL; $i++)
{
$str = $split[$i];
if (this.options.trimTimestamp)
{
$str = Utils.trimTimestamp($str, !this.options.stripColor);
}
this.addToLog($str);
$result.push($str);
}
}
else
{
if (this.options.trimTimestamp)
{
$str = Utils.trimTimestamp($str, !this.options.stripColor);
}
if (this.options.trimLinebreak)
{
$str = Utils.trimLinebreak($str);
}
this.addToLog($str);
$result.push($str);
}
return $result;
} | javascript | function($str)
{
if (!this.hasFormatOptions)
{
this.addToLog($str);
return false;
}
// strip colors from the string. this is ok with multilines
if (this.options.stripColor)
{
$str = Utils.stripColor($str);
}
var $result = [];
if (this.options.splitOnLinebreak)
{
var $split = Utils.splitOnLinebreak($str,
this.options.trimLinebreak);
for (var $i = 0, $iL = $split.length; $i < $iL; $i++)
{
$str = $split[$i];
if (this.options.trimTimestamp)
{
$str = Utils.trimTimestamp($str, !this.options.stripColor);
}
this.addToLog($str);
$result.push($str);
}
}
else
{
if (this.options.trimTimestamp)
{
$str = Utils.trimTimestamp($str, !this.options.stripColor);
}
if (this.options.trimLinebreak)
{
$str = Utils.trimLinebreak($str);
}
this.addToLog($str);
$result.push($str);
}
return $result;
} | [
"function",
"(",
"$str",
")",
"{",
"if",
"(",
"!",
"this",
".",
"hasFormatOptions",
")",
"{",
"this",
".",
"addToLog",
"(",
"$str",
")",
";",
"return",
"false",
";",
"}",
"// strip colors from the string. this is ok with multilines",
"if",
"(",
"this",
".",
"options",
".",
"stripColor",
")",
"{",
"$str",
"=",
"Utils",
".",
"stripColor",
"(",
"$str",
")",
";",
"}",
"var",
"$result",
"=",
"[",
"]",
";",
"if",
"(",
"this",
".",
"options",
".",
"splitOnLinebreak",
")",
"{",
"var",
"$split",
"=",
"Utils",
".",
"splitOnLinebreak",
"(",
"$str",
",",
"this",
".",
"options",
".",
"trimLinebreak",
")",
";",
"for",
"(",
"var",
"$i",
"=",
"0",
",",
"$iL",
"=",
"$split",
".",
"length",
";",
"$i",
"<",
"$iL",
";",
"$i",
"++",
")",
"{",
"$str",
"=",
"$split",
"[",
"$i",
"]",
";",
"if",
"(",
"this",
".",
"options",
".",
"trimTimestamp",
")",
"{",
"$str",
"=",
"Utils",
".",
"trimTimestamp",
"(",
"$str",
",",
"!",
"this",
".",
"options",
".",
"stripColor",
")",
";",
"}",
"this",
".",
"addToLog",
"(",
"$str",
")",
";",
"$result",
".",
"push",
"(",
"$str",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"options",
".",
"trimTimestamp",
")",
"{",
"$str",
"=",
"Utils",
".",
"trimTimestamp",
"(",
"$str",
",",
"!",
"this",
".",
"options",
".",
"stripColor",
")",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"trimLinebreak",
")",
"{",
"$str",
"=",
"Utils",
".",
"trimLinebreak",
"(",
"$str",
")",
";",
"}",
"this",
".",
"addToLog",
"(",
"$str",
")",
";",
"$result",
".",
"push",
"(",
"$str",
")",
";",
"}",
"return",
"$result",
";",
"}"
] | Will format and log the intercepted string and return an array with the
formatted result, or `false` when no format options are enabled.
@param {string} $str
@return {boolean|array} | [
"Will",
"format",
"and",
"log",
"the",
"intercepted",
"string",
"and",
"return",
"an",
"array",
"with",
"the",
"formatted",
"result",
"or",
"false",
"when",
"no",
"format",
"options",
"are",
"enabled",
"."
] | ccc958e47de73dffdf7d4c0d62766e6d85e5b066 | https://github.com/roeldev-deprecated-stuff/log-interceptor/blob/ccc958e47de73dffdf7d4c0d62766e6d85e5b066/lib/level.js#L78-L127 |
|
48,627 | Hexagon/abstractor | lib/log.js | function (fn, module, data, verbose) {
let complete = module.toUpperCase() + " > ";
// Only provide verbose log if logLevel > 5
verbose = config.logLevel >= 5 ? (verbose || undefined) : undefined;
// When writing to console
if ( config.destination === console) {
// Compose message
complete = " [ " + new Date().toLocaleString() + " ] " + complete + data;
if ( fn == "error" )
complete = complete.bgRed.white;
else if ( fn == "warning" )
complete = complete.bgYellow.black
// ... when writing to a custom log function
} else {
complete += fn + ': ' + data;
}
// Check that destination.fn exists, fallback to destination.log
let logger = (config.destination[fn] || config.destination.log).bind(config.destination);
if ( verbose !== undefined ) {
logger(complete, verbose);
} else {
logger(complete);
}
} | javascript | function (fn, module, data, verbose) {
let complete = module.toUpperCase() + " > ";
// Only provide verbose log if logLevel > 5
verbose = config.logLevel >= 5 ? (verbose || undefined) : undefined;
// When writing to console
if ( config.destination === console) {
// Compose message
complete = " [ " + new Date().toLocaleString() + " ] " + complete + data;
if ( fn == "error" )
complete = complete.bgRed.white;
else if ( fn == "warning" )
complete = complete.bgYellow.black
// ... when writing to a custom log function
} else {
complete += fn + ': ' + data;
}
// Check that destination.fn exists, fallback to destination.log
let logger = (config.destination[fn] || config.destination.log).bind(config.destination);
if ( verbose !== undefined ) {
logger(complete, verbose);
} else {
logger(complete);
}
} | [
"function",
"(",
"fn",
",",
"module",
",",
"data",
",",
"verbose",
")",
"{",
"let",
"complete",
"=",
"module",
".",
"toUpperCase",
"(",
")",
"+",
"\" > \"",
";",
"// Only provide verbose log if logLevel > 5",
"verbose",
"=",
"config",
".",
"logLevel",
">=",
"5",
"?",
"(",
"verbose",
"||",
"undefined",
")",
":",
"undefined",
";",
"// When writing to console",
"if",
"(",
"config",
".",
"destination",
"===",
"console",
")",
"{",
"// Compose message",
"complete",
"=",
"\" [ \"",
"+",
"new",
"Date",
"(",
")",
".",
"toLocaleString",
"(",
")",
"+",
"\" ] \"",
"+",
"complete",
"+",
"data",
";",
"if",
"(",
"fn",
"==",
"\"error\"",
")",
"complete",
"=",
"complete",
".",
"bgRed",
".",
"white",
";",
"else",
"if",
"(",
"fn",
"==",
"\"warning\"",
")",
"complete",
"=",
"complete",
".",
"bgYellow",
".",
"black",
"// ... when writing to a custom log function",
"}",
"else",
"{",
"complete",
"+=",
"fn",
"+",
"': '",
"+",
"data",
";",
"}",
"// Check that destination.fn exists, fallback to destination.log",
"let",
"logger",
"=",
"(",
"config",
".",
"destination",
"[",
"fn",
"]",
"||",
"config",
".",
"destination",
".",
"log",
")",
".",
"bind",
"(",
"config",
".",
"destination",
")",
";",
"if",
"(",
"verbose",
"!==",
"undefined",
")",
"{",
"logger",
"(",
"complete",
",",
"verbose",
")",
";",
"}",
"else",
"{",
"logger",
"(",
"complete",
")",
";",
"}",
"}"
] | Log levels 0 = silent 1 = error 2 = warning 3 = log 4 = notice 5 = verbose Private | [
"Log",
"levels",
"0",
"=",
"silent",
"1",
"=",
"error",
"2",
"=",
"warning",
"3",
"=",
"log",
"4",
"=",
"notice",
"5",
"=",
"verbose",
"Private"
] | e4ab34e9404060998b4af1ad41544be5f436bffb | https://github.com/Hexagon/abstractor/blob/e4ab34e9404060998b4af1ad41544be5f436bffb/lib/log.js#L50-L84 |
|
48,628 | cusspvz/method-throttle | src/method-throttle.js | throttle | function throttle ( fn, time, context ) {
var lock, args, asyncKey, destroyed
var later = function () {
// reset lock and call if queued
lock = false
if ( args ) {
throttled.apply( context, args )
args = false
}
}
var checkDestroyed = function () {
if ( destroyed ) {
throw new Error( "Method was already destroyed" )
}
}
var throttled = function () {
checkDestroyed()
if ( lock ) {
// called too soon, queue to call later
args = arguments
return
}
// call and lock until later
fn.apply( context, arguments )
asyncKey = setTimeout( later, time )
lock = true
}
throttled.destroy = function () {
checkDestroyed()
if ( asyncKey ) {
clearTimeout( asyncKey )
}
destroyed = true
}
return throttled
} | javascript | function throttle ( fn, time, context ) {
var lock, args, asyncKey, destroyed
var later = function () {
// reset lock and call if queued
lock = false
if ( args ) {
throttled.apply( context, args )
args = false
}
}
var checkDestroyed = function () {
if ( destroyed ) {
throw new Error( "Method was already destroyed" )
}
}
var throttled = function () {
checkDestroyed()
if ( lock ) {
// called too soon, queue to call later
args = arguments
return
}
// call and lock until later
fn.apply( context, arguments )
asyncKey = setTimeout( later, time )
lock = true
}
throttled.destroy = function () {
checkDestroyed()
if ( asyncKey ) {
clearTimeout( asyncKey )
}
destroyed = true
}
return throttled
} | [
"function",
"throttle",
"(",
"fn",
",",
"time",
",",
"context",
")",
"{",
"var",
"lock",
",",
"args",
",",
"asyncKey",
",",
"destroyed",
"var",
"later",
"=",
"function",
"(",
")",
"{",
"// reset lock and call if queued",
"lock",
"=",
"false",
"if",
"(",
"args",
")",
"{",
"throttled",
".",
"apply",
"(",
"context",
",",
"args",
")",
"args",
"=",
"false",
"}",
"}",
"var",
"checkDestroyed",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"destroyed",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Method was already destroyed\"",
")",
"}",
"}",
"var",
"throttled",
"=",
"function",
"(",
")",
"{",
"checkDestroyed",
"(",
")",
"if",
"(",
"lock",
")",
"{",
"// called too soon, queue to call later",
"args",
"=",
"arguments",
"return",
"}",
"// call and lock until later",
"fn",
".",
"apply",
"(",
"context",
",",
"arguments",
")",
"asyncKey",
"=",
"setTimeout",
"(",
"later",
",",
"time",
")",
"lock",
"=",
"true",
"}",
"throttled",
".",
"destroy",
"=",
"function",
"(",
")",
"{",
"checkDestroyed",
"(",
")",
"if",
"(",
"asyncKey",
")",
"{",
"clearTimeout",
"(",
"asyncKey",
")",
"}",
"destroyed",
"=",
"true",
"}",
"return",
"throttled",
"}"
] | throttle - throttles provided fn for a specific time
@param {Function} fn method that you wish to throttle
@param {Integer} time amount of time that you want to ignore calls
@param {mixed} context object that will context into provided fn
@return {Function} returned method will check if it can recall your
first method | [
"throttle",
"-",
"throttles",
"provided",
"fn",
"for",
"a",
"specific",
"time"
] | 6eeef472d026c6902addb34c6a6a1138a7ba4402 | https://github.com/cusspvz/method-throttle/blob/6eeef472d026c6902addb34c6a6a1138a7ba4402/src/method-throttle.js#L11-L55 |
48,629 | ceddl/ceddl-aditional-inputs | src/page-metadata.js | hasCookies | function hasCookies() {
if (navigator.cookieEnabled) {
return true;
}
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") != -1;
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
return ret;
} | javascript | function hasCookies() {
if (navigator.cookieEnabled) {
return true;
}
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") != -1;
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
return ret;
} | [
"function",
"hasCookies",
"(",
")",
"{",
"if",
"(",
"navigator",
".",
"cookieEnabled",
")",
"{",
"return",
"true",
";",
"}",
"document",
".",
"cookie",
"=",
"\"cookietest=1\"",
";",
"var",
"ret",
"=",
"document",
".",
"cookie",
".",
"indexOf",
"(",
"\"cookietest=\"",
")",
"!=",
"-",
"1",
";",
"document",
".",
"cookie",
"=",
"\"cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT\"",
";",
"return",
"ret",
";",
"}"
] | detects if the browser has Cookies enabled.
@return {Boolean} ret | [
"detects",
"if",
"the",
"browser",
"has",
"Cookies",
"enabled",
"."
] | 0e018d463107a0b631c317d7bf372aa9e194b7da | https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/page-metadata.js#L24-L33 |
48,630 | ceddl/ceddl-aditional-inputs | src/page-metadata.js | getPageMeta | function getPageMeta() {
var data = detectFeatures();
data.title = document.title;
data.url = window.location.href;
data.path = document.location.pathname;
data.referrer = document.referrer;
data.url_section = window.location.pathname.split('/').filter(function(part){
return part.length !== 0;
}).map(function(part){
return part.replace(/\.[^/.]+$/, "");
});
data.hash = window.location.hash;
data.query_string = window.location.search;
return data;
} | javascript | function getPageMeta() {
var data = detectFeatures();
data.title = document.title;
data.url = window.location.href;
data.path = document.location.pathname;
data.referrer = document.referrer;
data.url_section = window.location.pathname.split('/').filter(function(part){
return part.length !== 0;
}).map(function(part){
return part.replace(/\.[^/.]+$/, "");
});
data.hash = window.location.hash;
data.query_string = window.location.search;
return data;
} | [
"function",
"getPageMeta",
"(",
")",
"{",
"var",
"data",
"=",
"detectFeatures",
"(",
")",
";",
"data",
".",
"title",
"=",
"document",
".",
"title",
";",
"data",
".",
"url",
"=",
"window",
".",
"location",
".",
"href",
";",
"data",
".",
"path",
"=",
"document",
".",
"location",
".",
"pathname",
";",
"data",
".",
"referrer",
"=",
"document",
".",
"referrer",
";",
"data",
".",
"url_section",
"=",
"window",
".",
"location",
".",
"pathname",
".",
"split",
"(",
"'/'",
")",
".",
"filter",
"(",
"function",
"(",
"part",
")",
"{",
"return",
"part",
".",
"length",
"!==",
"0",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"part",
")",
"{",
"return",
"part",
".",
"replace",
"(",
"/",
"\\.[^/.]+$",
"/",
",",
"\"\"",
")",
";",
"}",
")",
";",
"data",
".",
"hash",
"=",
"window",
".",
"location",
".",
"hash",
";",
"data",
".",
"query_string",
"=",
"window",
".",
"location",
".",
"search",
";",
"return",
"data",
";",
"}"
] | getPageState is a helper function to collect all the browser and custom element data
converting it into the page data object. | [
"getPageState",
"is",
"a",
"helper",
"function",
"to",
"collect",
"all",
"the",
"browser",
"and",
"custom",
"element",
"data",
"converting",
"it",
"into",
"the",
"page",
"data",
"object",
"."
] | 0e018d463107a0b631c317d7bf372aa9e194b7da | https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/page-metadata.js#L138-L154 |
48,631 | phun-ky/grunt-minified | tasks/minified.js | function(file){
// Sandboxed variables
var filePath = '';
// Read file source
var src = grunt.file.read(file);
// Get file name
var filename = path.basename(file);
// set file extention
if(_opts.ext) {
filename = filename.replace('.js', _opts.ext);
}
if(_opts.sourcemap){
uglifyOpts.outSourceMap = filename + '.map';
mapDest = _destPath + uglifyOpts.outSourceMap;
}
// Minify file source
var result = uglify.minify(file, uglifyOpts);
if(_opts.sourcemap){
// Write source map to file
grunt.file.write( mapDest, result.map );
}
var minSrc = result.code;
// Verbose output by default for now
if(_opts.verbose){
grunt.log.ok(filename.yellow + ': original size: ' + String(src.length).cyan + ' bytes' + ', minified size: ' + String(minSrc.length).cyan + ' bytes.');
if(_opts.sourcemap){
grunt.log.ok('sourcemap generated to ' + uglifyOpts.outSourceMap.yellow);
}
} else {
var _non_verbose_output = filename.yellow + ' minified';
if(_opts.sourcemap){
_non_verbose_output += ', and sourcemapped to ' + uglifyOpts.outSourceMap.yellow;
}
grunt.log.ok(_non_verbose_output);
}
// Set destination
filePath = (_isMirrorSource) ? changeFilePath(file) : _destPath;
minDest = filePath + filename;
// Write minified sorce to destination file
grunt.file.write( minDest, minSrc );
} | javascript | function(file){
// Sandboxed variables
var filePath = '';
// Read file source
var src = grunt.file.read(file);
// Get file name
var filename = path.basename(file);
// set file extention
if(_opts.ext) {
filename = filename.replace('.js', _opts.ext);
}
if(_opts.sourcemap){
uglifyOpts.outSourceMap = filename + '.map';
mapDest = _destPath + uglifyOpts.outSourceMap;
}
// Minify file source
var result = uglify.minify(file, uglifyOpts);
if(_opts.sourcemap){
// Write source map to file
grunt.file.write( mapDest, result.map );
}
var minSrc = result.code;
// Verbose output by default for now
if(_opts.verbose){
grunt.log.ok(filename.yellow + ': original size: ' + String(src.length).cyan + ' bytes' + ', minified size: ' + String(minSrc.length).cyan + ' bytes.');
if(_opts.sourcemap){
grunt.log.ok('sourcemap generated to ' + uglifyOpts.outSourceMap.yellow);
}
} else {
var _non_verbose_output = filename.yellow + ' minified';
if(_opts.sourcemap){
_non_verbose_output += ', and sourcemapped to ' + uglifyOpts.outSourceMap.yellow;
}
grunt.log.ok(_non_verbose_output);
}
// Set destination
filePath = (_isMirrorSource) ? changeFilePath(file) : _destPath;
minDest = filePath + filename;
// Write minified sorce to destination file
grunt.file.write( minDest, minSrc );
} | [
"function",
"(",
"file",
")",
"{",
"// Sandboxed variables",
"var",
"filePath",
"=",
"''",
";",
"// Read file source",
"var",
"src",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"file",
")",
";",
"// Get file name",
"var",
"filename",
"=",
"path",
".",
"basename",
"(",
"file",
")",
";",
"// set file extention",
"if",
"(",
"_opts",
".",
"ext",
")",
"{",
"filename",
"=",
"filename",
".",
"replace",
"(",
"'.js'",
",",
"_opts",
".",
"ext",
")",
";",
"}",
"if",
"(",
"_opts",
".",
"sourcemap",
")",
"{",
"uglifyOpts",
".",
"outSourceMap",
"=",
"filename",
"+",
"'.map'",
";",
"mapDest",
"=",
"_destPath",
"+",
"uglifyOpts",
".",
"outSourceMap",
";",
"}",
"// Minify file source",
"var",
"result",
"=",
"uglify",
".",
"minify",
"(",
"file",
",",
"uglifyOpts",
")",
";",
"if",
"(",
"_opts",
".",
"sourcemap",
")",
"{",
"// Write source map to file",
"grunt",
".",
"file",
".",
"write",
"(",
"mapDest",
",",
"result",
".",
"map",
")",
";",
"}",
"var",
"minSrc",
"=",
"result",
".",
"code",
";",
"// Verbose output by default for now",
"if",
"(",
"_opts",
".",
"verbose",
")",
"{",
"grunt",
".",
"log",
".",
"ok",
"(",
"filename",
".",
"yellow",
"+",
"': original size: '",
"+",
"String",
"(",
"src",
".",
"length",
")",
".",
"cyan",
"+",
"' bytes'",
"+",
"', minified size: '",
"+",
"String",
"(",
"minSrc",
".",
"length",
")",
".",
"cyan",
"+",
"' bytes.'",
")",
";",
"if",
"(",
"_opts",
".",
"sourcemap",
")",
"{",
"grunt",
".",
"log",
".",
"ok",
"(",
"'sourcemap generated to '",
"+",
"uglifyOpts",
".",
"outSourceMap",
".",
"yellow",
")",
";",
"}",
"}",
"else",
"{",
"var",
"_non_verbose_output",
"=",
"filename",
".",
"yellow",
"+",
"' minified'",
";",
"if",
"(",
"_opts",
".",
"sourcemap",
")",
"{",
"_non_verbose_output",
"+=",
"', and sourcemapped to '",
"+",
"uglifyOpts",
".",
"outSourceMap",
".",
"yellow",
";",
"}",
"grunt",
".",
"log",
".",
"ok",
"(",
"_non_verbose_output",
")",
";",
"}",
"// Set destination",
"filePath",
"=",
"(",
"_isMirrorSource",
")",
"?",
"changeFilePath",
"(",
"file",
")",
":",
"_destPath",
";",
"minDest",
"=",
"filePath",
"+",
"filename",
";",
"// Write minified sorce to destination file",
"grunt",
".",
"file",
".",
"write",
"(",
"minDest",
",",
"minSrc",
")",
";",
"}"
] | Set up callback function for file iteration | [
"Set",
"up",
"callback",
"function",
"for",
"file",
"iteration"
] | ba9a3896af6e1248087beb006fe82f354815730f | https://github.com/phun-ky/grunt-minified/blob/ba9a3896af6e1248087beb006fe82f354815730f/tasks/minified.js#L40-L96 |
|
48,632 | IjzerenHein/famous-refresh-loader | RefreshLoader.js | _translateBehind | function _translateBehind() {
if (this._zNode) {
this._zNode = this._zNode.add(new Modifier({
transform: Transform.behind
}));
}
else {
this._zNode = this.add(new Modifier({
transform: Transform.behind
}));
}
return this._zNode;
} | javascript | function _translateBehind() {
if (this._zNode) {
this._zNode = this._zNode.add(new Modifier({
transform: Transform.behind
}));
}
else {
this._zNode = this.add(new Modifier({
transform: Transform.behind
}));
}
return this._zNode;
} | [
"function",
"_translateBehind",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_zNode",
")",
"{",
"this",
".",
"_zNode",
"=",
"this",
".",
"_zNode",
".",
"add",
"(",
"new",
"Modifier",
"(",
"{",
"transform",
":",
"Transform",
".",
"behind",
"}",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"_zNode",
"=",
"this",
".",
"add",
"(",
"new",
"Modifier",
"(",
"{",
"transform",
":",
"Transform",
".",
"behind",
"}",
")",
")",
";",
"}",
"return",
"this",
".",
"_zNode",
";",
"}"
] | Helper function for giving all surfaces the correct z-index. | [
"Helper",
"function",
"for",
"giving",
"all",
"surfaces",
"the",
"correct",
"z",
"-",
"index",
"."
] | 4df7aa51d5f17d510915311e46c5ee6745498d86 | https://github.com/IjzerenHein/famous-refresh-loader/blob/4df7aa51d5f17d510915311e46c5ee6745498d86/RefreshLoader.js#L62-L74 |
48,633 | IjzerenHein/famous-refresh-loader | RefreshLoader.js | _createParticles | function _createParticles(node, count) {
this._particles = [];
var options = {
size: [this.options.particleSize, this.options.particleSize],
properties: {
backgroundColor: this.options.color,
borderRadius: '50%'
}
};
for (var i = 0; i < count; i++) {
var particle = {
surface: new Surface(options),
mod: new Modifier({})
};
this._particles.push(particle);
node.add(particle.mod).add(particle.surface);
}
} | javascript | function _createParticles(node, count) {
this._particles = [];
var options = {
size: [this.options.particleSize, this.options.particleSize],
properties: {
backgroundColor: this.options.color,
borderRadius: '50%'
}
};
for (var i = 0; i < count; i++) {
var particle = {
surface: new Surface(options),
mod: new Modifier({})
};
this._particles.push(particle);
node.add(particle.mod).add(particle.surface);
}
} | [
"function",
"_createParticles",
"(",
"node",
",",
"count",
")",
"{",
"this",
".",
"_particles",
"=",
"[",
"]",
";",
"var",
"options",
"=",
"{",
"size",
":",
"[",
"this",
".",
"options",
".",
"particleSize",
",",
"this",
".",
"options",
".",
"particleSize",
"]",
",",
"properties",
":",
"{",
"backgroundColor",
":",
"this",
".",
"options",
".",
"color",
",",
"borderRadius",
":",
"'50%'",
"}",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
")",
"{",
"var",
"particle",
"=",
"{",
"surface",
":",
"new",
"Surface",
"(",
"options",
")",
",",
"mod",
":",
"new",
"Modifier",
"(",
"{",
"}",
")",
"}",
";",
"this",
".",
"_particles",
".",
"push",
"(",
"particle",
")",
";",
"node",
".",
"add",
"(",
"particle",
".",
"mod",
")",
".",
"add",
"(",
"particle",
".",
"surface",
")",
";",
"}",
"}"
] | Creates the particles | [
"Creates",
"the",
"particles"
] | 4df7aa51d5f17d510915311e46c5ee6745498d86 | https://github.com/IjzerenHein/famous-refresh-loader/blob/4df7aa51d5f17d510915311e46c5ee6745498d86/RefreshLoader.js#L79-L96 |
48,634 | IjzerenHein/famous-refresh-loader | RefreshLoader.js | _createForeground | function _createForeground(node) {
this._foreground = {
surface: new Surface({
size: this.options.size,
properties: {
backgroundColor: this.options.pullToRefreshBackgroundColor
}
}),
mod: new Modifier({})
};
node.add(this._foreground.mod).add(this._foreground.surface);
} | javascript | function _createForeground(node) {
this._foreground = {
surface: new Surface({
size: this.options.size,
properties: {
backgroundColor: this.options.pullToRefreshBackgroundColor
}
}),
mod: new Modifier({})
};
node.add(this._foreground.mod).add(this._foreground.surface);
} | [
"function",
"_createForeground",
"(",
"node",
")",
"{",
"this",
".",
"_foreground",
"=",
"{",
"surface",
":",
"new",
"Surface",
"(",
"{",
"size",
":",
"this",
".",
"options",
".",
"size",
",",
"properties",
":",
"{",
"backgroundColor",
":",
"this",
".",
"options",
".",
"pullToRefreshBackgroundColor",
"}",
"}",
")",
",",
"mod",
":",
"new",
"Modifier",
"(",
"{",
"}",
")",
"}",
";",
"node",
".",
"add",
"(",
"this",
".",
"_foreground",
".",
"mod",
")",
".",
"add",
"(",
"this",
".",
"_foreground",
".",
"surface",
")",
";",
"}"
] | Creates the foreground behind which the particles can hide in case of pull to refresh. | [
"Creates",
"the",
"foreground",
"behind",
"which",
"the",
"particles",
"can",
"hide",
"in",
"case",
"of",
"pull",
"to",
"refresh",
"."
] | 4df7aa51d5f17d510915311e46c5ee6745498d86 | https://github.com/IjzerenHein/famous-refresh-loader/blob/4df7aa51d5f17d510915311e46c5ee6745498d86/RefreshLoader.js#L101-L112 |
48,635 | IjzerenHein/famous-refresh-loader | RefreshLoader.js | _positionForeground | function _positionForeground(renderSize) {
if (this._pullToRefreshDirection) {
this._foreground.mod.transformFrom(Transform.translate(0, renderSize[1], 0));
}
else {
this._foreground.mod.transformFrom(Transform.translate(renderSize[0], 0, 0));
}
} | javascript | function _positionForeground(renderSize) {
if (this._pullToRefreshDirection) {
this._foreground.mod.transformFrom(Transform.translate(0, renderSize[1], 0));
}
else {
this._foreground.mod.transformFrom(Transform.translate(renderSize[0], 0, 0));
}
} | [
"function",
"_positionForeground",
"(",
"renderSize",
")",
"{",
"if",
"(",
"this",
".",
"_pullToRefreshDirection",
")",
"{",
"this",
".",
"_foreground",
".",
"mod",
".",
"transformFrom",
"(",
"Transform",
".",
"translate",
"(",
"0",
",",
"renderSize",
"[",
"1",
"]",
",",
"0",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"_foreground",
".",
"mod",
".",
"transformFrom",
"(",
"Transform",
".",
"translate",
"(",
"renderSize",
"[",
"0",
"]",
",",
"0",
",",
"0",
")",
")",
";",
"}",
"}"
] | Positions the foreground in front of the particles. | [
"Positions",
"the",
"foreground",
"in",
"front",
"of",
"the",
"particles",
"."
] | 4df7aa51d5f17d510915311e46c5ee6745498d86 | https://github.com/IjzerenHein/famous-refresh-loader/blob/4df7aa51d5f17d510915311e46c5ee6745498d86/RefreshLoader.js#L169-L176 |
48,636 | stefan-dimitrov/i18n-compile | index.js | function (filePatterns, destination, options) {
try {
var fse = require('fs-extra')
} catch (e) {
console.error('This method can only be used in server applications.\n' +
'Consider using the alternative method "i18nCompile.fromString()" instead.')
}
options = options || {};
var matchedFiles = _.map(filePatterns, function (pattern) {
return glob.sync(pattern);
});
var files = _.uniq(_.flatten(matchedFiles));
var srcList = files.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
try {
fse.accessSync(filepath);
return true;
} catch (e) {
console.warn('Source file "' + filepath + '" not found.');
return false;
}
}).map(function (filepath) {
// Read YAML file.
var content = yaml.safeLoad(fse.readFileSync(filepath, 'utf8'), {
filename: filepath,
schema: yaml.JSON_SCHEMA
});
return new SrcItem(filepath, content);
});
var compiled = compileTranslations(srcList);
// Handle options.
if (options.merge) {
// Write the destination file(with all languages merged in the same file).
fse.outputFileSync(destination, JSON.stringify(compiled));
// Print a success message.
console.log('File "' + destination + '" created.');
return;
}
// Write the destination files.
for (var lang in compiled) {
var fileDest = langFileDest(destination, lang, options.langPlace);
fse.outputFileSync(fileDest, JSON.stringify(compiled[lang]));
// Print a success message.
console.log('File "' + fileDest + '" created.');
}
} | javascript | function (filePatterns, destination, options) {
try {
var fse = require('fs-extra')
} catch (e) {
console.error('This method can only be used in server applications.\n' +
'Consider using the alternative method "i18nCompile.fromString()" instead.')
}
options = options || {};
var matchedFiles = _.map(filePatterns, function (pattern) {
return glob.sync(pattern);
});
var files = _.uniq(_.flatten(matchedFiles));
var srcList = files.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
try {
fse.accessSync(filepath);
return true;
} catch (e) {
console.warn('Source file "' + filepath + '" not found.');
return false;
}
}).map(function (filepath) {
// Read YAML file.
var content = yaml.safeLoad(fse.readFileSync(filepath, 'utf8'), {
filename: filepath,
schema: yaml.JSON_SCHEMA
});
return new SrcItem(filepath, content);
});
var compiled = compileTranslations(srcList);
// Handle options.
if (options.merge) {
// Write the destination file(with all languages merged in the same file).
fse.outputFileSync(destination, JSON.stringify(compiled));
// Print a success message.
console.log('File "' + destination + '" created.');
return;
}
// Write the destination files.
for (var lang in compiled) {
var fileDest = langFileDest(destination, lang, options.langPlace);
fse.outputFileSync(fileDest, JSON.stringify(compiled[lang]));
// Print a success message.
console.log('File "' + fileDest + '" created.');
}
} | [
"function",
"(",
"filePatterns",
",",
"destination",
",",
"options",
")",
"{",
"try",
"{",
"var",
"fse",
"=",
"require",
"(",
"'fs-extra'",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"'This method can only be used in server applications.\\n'",
"+",
"'Consider using the alternative method \"i18nCompile.fromString()\" instead.'",
")",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"matchedFiles",
"=",
"_",
".",
"map",
"(",
"filePatterns",
",",
"function",
"(",
"pattern",
")",
"{",
"return",
"glob",
".",
"sync",
"(",
"pattern",
")",
";",
"}",
")",
";",
"var",
"files",
"=",
"_",
".",
"uniq",
"(",
"_",
".",
"flatten",
"(",
"matchedFiles",
")",
")",
";",
"var",
"srcList",
"=",
"files",
".",
"filter",
"(",
"function",
"(",
"filepath",
")",
"{",
"// Warn on and remove invalid source files (if nonull was set).",
"try",
"{",
"fse",
".",
"accessSync",
"(",
"filepath",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"warn",
"(",
"'Source file \"'",
"+",
"filepath",
"+",
"'\" not found.'",
")",
";",
"return",
"false",
";",
"}",
"}",
")",
".",
"map",
"(",
"function",
"(",
"filepath",
")",
"{",
"// Read YAML file.",
"var",
"content",
"=",
"yaml",
".",
"safeLoad",
"(",
"fse",
".",
"readFileSync",
"(",
"filepath",
",",
"'utf8'",
")",
",",
"{",
"filename",
":",
"filepath",
",",
"schema",
":",
"yaml",
".",
"JSON_SCHEMA",
"}",
")",
";",
"return",
"new",
"SrcItem",
"(",
"filepath",
",",
"content",
")",
";",
"}",
")",
";",
"var",
"compiled",
"=",
"compileTranslations",
"(",
"srcList",
")",
";",
"// Handle options.",
"if",
"(",
"options",
".",
"merge",
")",
"{",
"// Write the destination file(with all languages merged in the same file).",
"fse",
".",
"outputFileSync",
"(",
"destination",
",",
"JSON",
".",
"stringify",
"(",
"compiled",
")",
")",
";",
"// Print a success message.",
"console",
".",
"log",
"(",
"'File \"'",
"+",
"destination",
"+",
"'\" created.'",
")",
";",
"return",
";",
"}",
"// Write the destination files.",
"for",
"(",
"var",
"lang",
"in",
"compiled",
")",
"{",
"var",
"fileDest",
"=",
"langFileDest",
"(",
"destination",
",",
"lang",
",",
"options",
".",
"langPlace",
")",
";",
"fse",
".",
"outputFileSync",
"(",
"fileDest",
",",
"JSON",
".",
"stringify",
"(",
"compiled",
"[",
"lang",
"]",
")",
")",
";",
"// Print a success message.",
"console",
".",
"log",
"(",
"'File \"'",
"+",
"fileDest",
"+",
"'\" created.'",
")",
";",
"}",
"}"
] | Compile files to json.
@param {String[]} filePatterns - files to compile. Glob patterns can be used to match many files
@param {String} destination - where to write the compiled results
@param {*} [options] - compiling options | [
"Compile",
"files",
"to",
"json",
"."
] | bb3133e0d60ac1eafd53510ecfbe101a103d203f | https://github.com/stefan-dimitrov/i18n-compile/blob/bb3133e0d60ac1eafd53510ecfbe101a103d203f/index.js#L14-L69 |
|
48,637 | stewart/apod.js | index.js | randomDate | function randomDate() {
var start = new Date(1995, 5, 16),
end = new Date(),
current = start,
dates = [];
while (current < end) {
dates.push([
current.getFullYear(),
current.getMonth() + 1,
current.getDate()
].join("-"));
current.setDate(current.getDate() + 1);
}
return dates[Math.floor(Math.random() * dates.length)];
} | javascript | function randomDate() {
var start = new Date(1995, 5, 16),
end = new Date(),
current = start,
dates = [];
while (current < end) {
dates.push([
current.getFullYear(),
current.getMonth() + 1,
current.getDate()
].join("-"));
current.setDate(current.getDate() + 1);
}
return dates[Math.floor(Math.random() * dates.length)];
} | [
"function",
"randomDate",
"(",
")",
"{",
"var",
"start",
"=",
"new",
"Date",
"(",
"1995",
",",
"5",
",",
"16",
")",
",",
"end",
"=",
"new",
"Date",
"(",
")",
",",
"current",
"=",
"start",
",",
"dates",
"=",
"[",
"]",
";",
"while",
"(",
"current",
"<",
"end",
")",
"{",
"dates",
".",
"push",
"(",
"[",
"current",
".",
"getFullYear",
"(",
")",
",",
"current",
".",
"getMonth",
"(",
")",
"+",
"1",
",",
"current",
".",
"getDate",
"(",
")",
"]",
".",
"join",
"(",
"\"-\"",
")",
")",
";",
"current",
".",
"setDate",
"(",
"current",
".",
"getDate",
"(",
")",
"+",
"1",
")",
";",
"}",
"return",
"dates",
"[",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"dates",
".",
"length",
")",
"]",
";",
"}"
] | anytime between start of APOD and now | [
"anytime",
"between",
"start",
"of",
"APOD",
"and",
"now"
] | 84bea181ac69c3e23ac3659cb4ba3d871d89258f | https://github.com/stewart/apod.js/blob/84bea181ac69c3e23ac3659cb4ba3d871d89258f/index.js#L32-L49 |
48,638 | rootslab/geco | lib/comb-set.js | function ( n, k ) {
if ( ! n || ( n < k ) )
throw new RangeError( 'check input values' )
;
// buffer for generating combinations
const buff = balloc( n, 0 )
// colex recursive generator
, colex_gen = function *( n, k ) {
if ( n === 0 ) yield buff;
else {
if ( k < n ) {
buff[ n - 1 ] = 0;
yield* colex_gen( n - 1, k );
}
if ( k > 0 ) {
buff[ n - 1 ] = 1;
yield* colex_gen( n - 1, k - 1 );
}
}
}
// generating colex order for k <= n/2.
, colex_gen_2 = function *( n, k ) {
if ( k === 0 ) yield buff;
else {
if ( k < n ) {
buff[ n - 1 ] = 0;
yield* colex_gen_2( n - 1, k );
}
buff[ n - 1 ] = 1;
yield* colex_gen_2( n - 1, k - 1);
buff[ n - 1 ] = 0;
}
}
;
return ( k > n / 2 ) ?
colex_gen( n , k ) :
colex_gen_2( n, k )
;
} | javascript | function ( n, k ) {
if ( ! n || ( n < k ) )
throw new RangeError( 'check input values' )
;
// buffer for generating combinations
const buff = balloc( n, 0 )
// colex recursive generator
, colex_gen = function *( n, k ) {
if ( n === 0 ) yield buff;
else {
if ( k < n ) {
buff[ n - 1 ] = 0;
yield* colex_gen( n - 1, k );
}
if ( k > 0 ) {
buff[ n - 1 ] = 1;
yield* colex_gen( n - 1, k - 1 );
}
}
}
// generating colex order for k <= n/2.
, colex_gen_2 = function *( n, k ) {
if ( k === 0 ) yield buff;
else {
if ( k < n ) {
buff[ n - 1 ] = 0;
yield* colex_gen_2( n - 1, k );
}
buff[ n - 1 ] = 1;
yield* colex_gen_2( n - 1, k - 1);
buff[ n - 1 ] = 0;
}
}
;
return ( k > n / 2 ) ?
colex_gen( n , k ) :
colex_gen_2( n, k )
;
} | [
"function",
"(",
"n",
",",
"k",
")",
"{",
"if",
"(",
"!",
"n",
"||",
"(",
"n",
"<",
"k",
")",
")",
"throw",
"new",
"RangeError",
"(",
"'check input values'",
")",
";",
"// buffer for generating combinations",
"const",
"buff",
"=",
"balloc",
"(",
"n",
",",
"0",
")",
"// colex recursive generator",
",",
"colex_gen",
"=",
"function",
"*",
"(",
"n",
",",
"k",
")",
"{",
"if",
"(",
"n",
"===",
"0",
")",
"yield",
"buff",
";",
"else",
"{",
"if",
"(",
"k",
"<",
"n",
")",
"{",
"buff",
"[",
"n",
"-",
"1",
"]",
"=",
"0",
";",
"yield",
"*",
"colex_gen",
"(",
"n",
"-",
"1",
",",
"k",
")",
";",
"}",
"if",
"(",
"k",
">",
"0",
")",
"{",
"buff",
"[",
"n",
"-",
"1",
"]",
"=",
"1",
";",
"yield",
"*",
"colex_gen",
"(",
"n",
"-",
"1",
",",
"k",
"-",
"1",
")",
";",
"}",
"}",
"}",
"// generating colex order for k <= n/2.",
",",
"colex_gen_2",
"=",
"function",
"*",
"(",
"n",
",",
"k",
")",
"{",
"if",
"(",
"k",
"===",
"0",
")",
"yield",
"buff",
";",
"else",
"{",
"if",
"(",
"k",
"<",
"n",
")",
"{",
"buff",
"[",
"n",
"-",
"1",
"]",
"=",
"0",
";",
"yield",
"*",
"colex_gen_2",
"(",
"n",
"-",
"1",
",",
"k",
")",
";",
"}",
"buff",
"[",
"n",
"-",
"1",
"]",
"=",
"1",
";",
"yield",
"*",
"colex_gen_2",
"(",
"n",
"-",
"1",
",",
"k",
"-",
"1",
")",
";",
"buff",
"[",
"n",
"-",
"1",
"]",
"=",
"0",
";",
"}",
"}",
";",
"return",
"(",
"k",
">",
"n",
"/",
"2",
")",
"?",
"colex_gen",
"(",
"n",
",",
"k",
")",
":",
"colex_gen_2",
"(",
"n",
",",
"k",
")",
";",
"}"
] | CAT generator for combinations without replacement | [
"CAT",
"generator",
"for",
"combinations",
"without",
"replacement"
] | b19fb4820eccfecd903e8691d62783757fbd2817 | https://github.com/rootslab/geco/blob/b19fb4820eccfecd903e8691d62783757fbd2817/lib/comb-set.js#L19-L57 |
|
48,639 | kuno/neco | deps/npm/lib/build.js | build | function build (args, cb) {
readAll(args, function (er, args) {
if (er) return cb(er)
// do all preinstalls, then check deps, then install all, then finish up.
chain
( [asyncMap, args, function (a, cb) {
return lifecycle(a, "preinstall", cb)
}]
, [asyncMap, args, function (a, cb) {
return resolveDependencies(a, cb)
}]
, [ asyncMap
, args
, function (pkg, cb) {
linkModules(pkg, path.join(npm.root, pkg.name+"@"+pkg.version), cb)
}
, linkBins
, linkMans
]
// must rebuild bundles serially, because it messes with configs.
, [chain].concat(args.map(function (a) { return [rebuildBundle, a] }))
, [linkDependencies, args]
, [finishBuild, args]
, cb
)
})
} | javascript | function build (args, cb) {
readAll(args, function (er, args) {
if (er) return cb(er)
// do all preinstalls, then check deps, then install all, then finish up.
chain
( [asyncMap, args, function (a, cb) {
return lifecycle(a, "preinstall", cb)
}]
, [asyncMap, args, function (a, cb) {
return resolveDependencies(a, cb)
}]
, [ asyncMap
, args
, function (pkg, cb) {
linkModules(pkg, path.join(npm.root, pkg.name+"@"+pkg.version), cb)
}
, linkBins
, linkMans
]
// must rebuild bundles serially, because it messes with configs.
, [chain].concat(args.map(function (a) { return [rebuildBundle, a] }))
, [linkDependencies, args]
, [finishBuild, args]
, cb
)
})
} | [
"function",
"build",
"(",
"args",
",",
"cb",
")",
"{",
"readAll",
"(",
"args",
",",
"function",
"(",
"er",
",",
"args",
")",
"{",
"if",
"(",
"er",
")",
"return",
"cb",
"(",
"er",
")",
"// do all preinstalls, then check deps, then install all, then finish up.",
"chain",
"(",
"[",
"asyncMap",
",",
"args",
",",
"function",
"(",
"a",
",",
"cb",
")",
"{",
"return",
"lifecycle",
"(",
"a",
",",
"\"preinstall\"",
",",
"cb",
")",
"}",
"]",
",",
"[",
"asyncMap",
",",
"args",
",",
"function",
"(",
"a",
",",
"cb",
")",
"{",
"return",
"resolveDependencies",
"(",
"a",
",",
"cb",
")",
"}",
"]",
",",
"[",
"asyncMap",
",",
"args",
",",
"function",
"(",
"pkg",
",",
"cb",
")",
"{",
"linkModules",
"(",
"pkg",
",",
"path",
".",
"join",
"(",
"npm",
".",
"root",
",",
"pkg",
".",
"name",
"+",
"\"@\"",
"+",
"pkg",
".",
"version",
")",
",",
"cb",
")",
"}",
",",
"linkBins",
",",
"linkMans",
"]",
"// must rebuild bundles serially, because it messes with configs.",
",",
"[",
"chain",
"]",
".",
"concat",
"(",
"args",
".",
"map",
"(",
"function",
"(",
"a",
")",
"{",
"return",
"[",
"rebuildBundle",
",",
"a",
"]",
"}",
")",
")",
",",
"[",
"linkDependencies",
",",
"args",
"]",
",",
"[",
"finishBuild",
",",
"args",
"]",
",",
"cb",
")",
"}",
")",
"}"
] | pkg is either a "package" folder, or a package.json data obj, or an object that has the package.json data on the _data member. | [
"pkg",
"is",
"either",
"a",
"package",
"folder",
"or",
"a",
"package",
".",
"json",
"data",
"obj",
"or",
"an",
"object",
"that",
"has",
"the",
"package",
".",
"json",
"data",
"on",
"the",
"_data",
"member",
"."
] | cf6361c1fcb9466c6b2ab3b127b5d0160ca50735 | https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/build.js#L40-L66 |
48,640 | kuno/neco | deps/npm/lib/build.js | resolveDependencies | function resolveDependencies (pkg, cb) {
if (!pkg) return topCb(new Error(
"Package not found to resolve dependencies"))
// link foo-1.0.3 to ROOT/.npm/{pkg}/{version}/node_modules/foo
// see if it's bundled already
var bundleDir = path.join( npm.dir, pkg.name, pkg.version
, "package", "node_modules" )
, deps = pkg.dependencies && Object.keys(pkg.dependencies) || []
log.verbose([pkg, deps], "deps being resolved")
fs.readdir(bundleDir, function (er, bundledDeps) {
if (er) bundledDeps = []
bundledDeps.forEach(function (bd) {
var i = deps.indexOf(bd)
if (i !== -1) deps.splice(i, 1)
})
asyncMap(deps, function (i, cb) {
var req = { name:i, version:pkg.dependencies[i] }
log.verbose(req.name+"@"+req.version, "required")
// see if we have this thing installed.
fs.readdir(path.join(npm.dir, req.name), function (er, versions) {
if (er) return cb(new Error(
"Required package: "+req.name+"("+req.version+") not found."+
"\n(required by: "+pkg._id+")"))
// TODO: Get the "stable" version if there is one.
// Look that up from the registry.
var satis = semver.maxSatisfying(versions, req.version)
if (satis) return cb(null, {name:req.name, version:satis})
return cb(new Error(
"Required package: "+req.name+"("+req.version+") not found. "+
"(Found: "+JSON.stringify(versions)+")"+
"\n(required by: "+pkg._id+")"))
})
}, function (er, found) {
// save the resolved dependencies on the pkg data for later
pkg._resolvedDeps = found
cb(er, found)
})
})
} | javascript | function resolveDependencies (pkg, cb) {
if (!pkg) return topCb(new Error(
"Package not found to resolve dependencies"))
// link foo-1.0.3 to ROOT/.npm/{pkg}/{version}/node_modules/foo
// see if it's bundled already
var bundleDir = path.join( npm.dir, pkg.name, pkg.version
, "package", "node_modules" )
, deps = pkg.dependencies && Object.keys(pkg.dependencies) || []
log.verbose([pkg, deps], "deps being resolved")
fs.readdir(bundleDir, function (er, bundledDeps) {
if (er) bundledDeps = []
bundledDeps.forEach(function (bd) {
var i = deps.indexOf(bd)
if (i !== -1) deps.splice(i, 1)
})
asyncMap(deps, function (i, cb) {
var req = { name:i, version:pkg.dependencies[i] }
log.verbose(req.name+"@"+req.version, "required")
// see if we have this thing installed.
fs.readdir(path.join(npm.dir, req.name), function (er, versions) {
if (er) return cb(new Error(
"Required package: "+req.name+"("+req.version+") not found."+
"\n(required by: "+pkg._id+")"))
// TODO: Get the "stable" version if there is one.
// Look that up from the registry.
var satis = semver.maxSatisfying(versions, req.version)
if (satis) return cb(null, {name:req.name, version:satis})
return cb(new Error(
"Required package: "+req.name+"("+req.version+") not found. "+
"(Found: "+JSON.stringify(versions)+")"+
"\n(required by: "+pkg._id+")"))
})
}, function (er, found) {
// save the resolved dependencies on the pkg data for later
pkg._resolvedDeps = found
cb(er, found)
})
})
} | [
"function",
"resolveDependencies",
"(",
"pkg",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"pkg",
")",
"return",
"topCb",
"(",
"new",
"Error",
"(",
"\"Package not found to resolve dependencies\"",
")",
")",
"// link foo-1.0.3 to ROOT/.npm/{pkg}/{version}/node_modules/foo",
"// see if it's bundled already",
"var",
"bundleDir",
"=",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"pkg",
".",
"name",
",",
"pkg",
".",
"version",
",",
"\"package\"",
",",
"\"node_modules\"",
")",
",",
"deps",
"=",
"pkg",
".",
"dependencies",
"&&",
"Object",
".",
"keys",
"(",
"pkg",
".",
"dependencies",
")",
"||",
"[",
"]",
"log",
".",
"verbose",
"(",
"[",
"pkg",
",",
"deps",
"]",
",",
"\"deps being resolved\"",
")",
"fs",
".",
"readdir",
"(",
"bundleDir",
",",
"function",
"(",
"er",
",",
"bundledDeps",
")",
"{",
"if",
"(",
"er",
")",
"bundledDeps",
"=",
"[",
"]",
"bundledDeps",
".",
"forEach",
"(",
"function",
"(",
"bd",
")",
"{",
"var",
"i",
"=",
"deps",
".",
"indexOf",
"(",
"bd",
")",
"if",
"(",
"i",
"!==",
"-",
"1",
")",
"deps",
".",
"splice",
"(",
"i",
",",
"1",
")",
"}",
")",
"asyncMap",
"(",
"deps",
",",
"function",
"(",
"i",
",",
"cb",
")",
"{",
"var",
"req",
"=",
"{",
"name",
":",
"i",
",",
"version",
":",
"pkg",
".",
"dependencies",
"[",
"i",
"]",
"}",
"log",
".",
"verbose",
"(",
"req",
".",
"name",
"+",
"\"@\"",
"+",
"req",
".",
"version",
",",
"\"required\"",
")",
"// see if we have this thing installed.",
"fs",
".",
"readdir",
"(",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"req",
".",
"name",
")",
",",
"function",
"(",
"er",
",",
"versions",
")",
"{",
"if",
"(",
"er",
")",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"Required package: \"",
"+",
"req",
".",
"name",
"+",
"\"(\"",
"+",
"req",
".",
"version",
"+",
"\") not found.\"",
"+",
"\"\\n(required by: \"",
"+",
"pkg",
".",
"_id",
"+",
"\")\"",
")",
")",
"// TODO: Get the \"stable\" version if there is one.",
"// Look that up from the registry.",
"var",
"satis",
"=",
"semver",
".",
"maxSatisfying",
"(",
"versions",
",",
"req",
".",
"version",
")",
"if",
"(",
"satis",
")",
"return",
"cb",
"(",
"null",
",",
"{",
"name",
":",
"req",
".",
"name",
",",
"version",
":",
"satis",
"}",
")",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"Required package: \"",
"+",
"req",
".",
"name",
"+",
"\"(\"",
"+",
"req",
".",
"version",
"+",
"\") not found. \"",
"+",
"\"(Found: \"",
"+",
"JSON",
".",
"stringify",
"(",
"versions",
")",
"+",
"\")\"",
"+",
"\"\\n(required by: \"",
"+",
"pkg",
".",
"_id",
"+",
"\")\"",
")",
")",
"}",
")",
"}",
",",
"function",
"(",
"er",
",",
"found",
")",
"{",
"// save the resolved dependencies on the pkg data for later",
"pkg",
".",
"_resolvedDeps",
"=",
"found",
"cb",
"(",
"er",
",",
"found",
")",
"}",
")",
"}",
")",
"}"
] | make sure that all the dependencies have been installed. | [
"make",
"sure",
"that",
"all",
"the",
"dependencies",
"have",
"been",
"installed",
"."
] | cf6361c1fcb9466c6b2ab3b127b5d0160ca50735 | https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/build.js#L162-L203 |
48,641 | kuno/neco | deps/npm/lib/build.js | dependentLink | function dependentLink (pkg, cb) {
asyncMap(pkg._resolvedDeps, function (dep, cb) {
var dependents = path.join(npm.dir, dep.name, dep.version, "dependents")
, to = path.join(dependents, pkg.name + "@" + pkg.version)
, from = path.join(npm.dir, pkg.name, pkg.version)
link(from, to, cb)
}, cb)
} | javascript | function dependentLink (pkg, cb) {
asyncMap(pkg._resolvedDeps, function (dep, cb) {
var dependents = path.join(npm.dir, dep.name, dep.version, "dependents")
, to = path.join(dependents, pkg.name + "@" + pkg.version)
, from = path.join(npm.dir, pkg.name, pkg.version)
link(from, to, cb)
}, cb)
} | [
"function",
"dependentLink",
"(",
"pkg",
",",
"cb",
")",
"{",
"asyncMap",
"(",
"pkg",
".",
"_resolvedDeps",
",",
"function",
"(",
"dep",
",",
"cb",
")",
"{",
"var",
"dependents",
"=",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"dep",
".",
"name",
",",
"dep",
".",
"version",
",",
"\"dependents\"",
")",
",",
"to",
"=",
"path",
".",
"join",
"(",
"dependents",
",",
"pkg",
".",
"name",
"+",
"\"@\"",
"+",
"pkg",
".",
"version",
")",
",",
"from",
"=",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"pkg",
".",
"name",
",",
"pkg",
".",
"version",
")",
"link",
"(",
"from",
",",
"to",
",",
"cb",
")",
"}",
",",
"cb",
")",
"}"
] | for each dependency, link this pkg into the proper "dependent" folder | [
"for",
"each",
"dependency",
"link",
"this",
"pkg",
"into",
"the",
"proper",
"dependent",
"folder"
] | cf6361c1fcb9466c6b2ab3b127b5d0160ca50735 | https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/build.js#L216-L223 |
48,642 | kuno/neco | deps/npm/lib/build.js | dependencyLink | function dependencyLink (pkg, cb) {
var dependencies = path.join(npm.dir, pkg.name, pkg.version, "node_modules")
, depBin = path.join(npm.dir, pkg.name, pkg.version, "dep-bin")
asyncMap(pkg._resolvedDeps, function (dep, cb) {
log.silly(dep, "dependency")
var fromRoot = path.join(npm.dir, dep.name, dep.version)
, dependsOn = path.join( npm.dir, pkg.name, pkg.version
, "dependson", dep.name + "@" + dep.version
)
link(fromRoot, dependsOn, cb)
}, function (dep, cb) {
var depDir = path.join(npm.dir, dep.name, dep.version, "package")
readJson(path.join(depDir, "package.json"), function (er, dep) {
if (er) return cb(er)
loadPackageDefaults(dep, function (er, dep) {
if (er) return cb(er)
asyncMap([dep], function (dep) {
var toLib = path.join(dependencies, dep.name)
linkModules(dep, toLib, cb)
}, function (dep, cb) {
// link the bins to this pkg's "dep-bin" folder.
linkBins(dep, depBin, false, cb)
}, cb)
})
})
}, cb)
} | javascript | function dependencyLink (pkg, cb) {
var dependencies = path.join(npm.dir, pkg.name, pkg.version, "node_modules")
, depBin = path.join(npm.dir, pkg.name, pkg.version, "dep-bin")
asyncMap(pkg._resolvedDeps, function (dep, cb) {
log.silly(dep, "dependency")
var fromRoot = path.join(npm.dir, dep.name, dep.version)
, dependsOn = path.join( npm.dir, pkg.name, pkg.version
, "dependson", dep.name + "@" + dep.version
)
link(fromRoot, dependsOn, cb)
}, function (dep, cb) {
var depDir = path.join(npm.dir, dep.name, dep.version, "package")
readJson(path.join(depDir, "package.json"), function (er, dep) {
if (er) return cb(er)
loadPackageDefaults(dep, function (er, dep) {
if (er) return cb(er)
asyncMap([dep], function (dep) {
var toLib = path.join(dependencies, dep.name)
linkModules(dep, toLib, cb)
}, function (dep, cb) {
// link the bins to this pkg's "dep-bin" folder.
linkBins(dep, depBin, false, cb)
}, cb)
})
})
}, cb)
} | [
"function",
"dependencyLink",
"(",
"pkg",
",",
"cb",
")",
"{",
"var",
"dependencies",
"=",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"pkg",
".",
"name",
",",
"pkg",
".",
"version",
",",
"\"node_modules\"",
")",
",",
"depBin",
"=",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"pkg",
".",
"name",
",",
"pkg",
".",
"version",
",",
"\"dep-bin\"",
")",
"asyncMap",
"(",
"pkg",
".",
"_resolvedDeps",
",",
"function",
"(",
"dep",
",",
"cb",
")",
"{",
"log",
".",
"silly",
"(",
"dep",
",",
"\"dependency\"",
")",
"var",
"fromRoot",
"=",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"dep",
".",
"name",
",",
"dep",
".",
"version",
")",
",",
"dependsOn",
"=",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"pkg",
".",
"name",
",",
"pkg",
".",
"version",
",",
"\"dependson\"",
",",
"dep",
".",
"name",
"+",
"\"@\"",
"+",
"dep",
".",
"version",
")",
"link",
"(",
"fromRoot",
",",
"dependsOn",
",",
"cb",
")",
"}",
",",
"function",
"(",
"dep",
",",
"cb",
")",
"{",
"var",
"depDir",
"=",
"path",
".",
"join",
"(",
"npm",
".",
"dir",
",",
"dep",
".",
"name",
",",
"dep",
".",
"version",
",",
"\"package\"",
")",
"readJson",
"(",
"path",
".",
"join",
"(",
"depDir",
",",
"\"package.json\"",
")",
",",
"function",
"(",
"er",
",",
"dep",
")",
"{",
"if",
"(",
"er",
")",
"return",
"cb",
"(",
"er",
")",
"loadPackageDefaults",
"(",
"dep",
",",
"function",
"(",
"er",
",",
"dep",
")",
"{",
"if",
"(",
"er",
")",
"return",
"cb",
"(",
"er",
")",
"asyncMap",
"(",
"[",
"dep",
"]",
",",
"function",
"(",
"dep",
")",
"{",
"var",
"toLib",
"=",
"path",
".",
"join",
"(",
"dependencies",
",",
"dep",
".",
"name",
")",
"linkModules",
"(",
"dep",
",",
"toLib",
",",
"cb",
")",
"}",
",",
"function",
"(",
"dep",
",",
"cb",
")",
"{",
"// link the bins to this pkg's \"dep-bin\" folder.",
"linkBins",
"(",
"dep",
",",
"depBin",
",",
"false",
",",
"cb",
")",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"}",
",",
"cb",
")",
"}"
] | link each dep into this pkg's "node_modules" folder | [
"link",
"each",
"dep",
"into",
"this",
"pkg",
"s",
"node_modules",
"folder"
] | cf6361c1fcb9466c6b2ab3b127b5d0160ca50735 | https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/build.js#L227-L253 |
48,643 | fatalxiao/js-markdown | src/lib/syntax/block/Paragraph.js | getPrev | function getPrev(renderTree) {
if (!renderTree || !renderTree.children || renderTree.children.length < 1
|| !renderTree.children[renderTree.children.length - 1]) {
return;
}
return renderTree.children[renderTree.children.length - 1];
} | javascript | function getPrev(renderTree) {
if (!renderTree || !renderTree.children || renderTree.children.length < 1
|| !renderTree.children[renderTree.children.length - 1]) {
return;
}
return renderTree.children[renderTree.children.length - 1];
} | [
"function",
"getPrev",
"(",
"renderTree",
")",
"{",
"if",
"(",
"!",
"renderTree",
"||",
"!",
"renderTree",
".",
"children",
"||",
"renderTree",
".",
"children",
".",
"length",
"<",
"1",
"||",
"!",
"renderTree",
".",
"children",
"[",
"renderTree",
".",
"children",
".",
"length",
"-",
"1",
"]",
")",
"{",
"return",
";",
"}",
"return",
"renderTree",
".",
"children",
"[",
"renderTree",
".",
"children",
".",
"length",
"-",
"1",
"]",
";",
"}"
] | get prev node in render tree | [
"get",
"prev",
"node",
"in",
"render",
"tree"
] | dffa23be561f50282e5ccc2f1595a51d18a81246 | https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/syntax/block/Paragraph.js#L17-L26 |
48,644 | jeanamarante/catena | tasks/deploy/parse.js | shuffleArray | function shuffleArray (options, arr) {
if (!options.minify) { return undefined; }
for (let i = 0, max = arr.length; i < max; i++) {
let j = randomInt(max);
if (arr[j] !== arr[i]) {
let source = arr[i];
arr[i] = arr[j];
arr[j] = source;
}
}
} | javascript | function shuffleArray (options, arr) {
if (!options.minify) { return undefined; }
for (let i = 0, max = arr.length; i < max; i++) {
let j = randomInt(max);
if (arr[j] !== arr[i]) {
let source = arr[i];
arr[i] = arr[j];
arr[j] = source;
}
}
} | [
"function",
"shuffleArray",
"(",
"options",
",",
"arr",
")",
"{",
"if",
"(",
"!",
"options",
".",
"minify",
")",
"{",
"return",
"undefined",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"max",
"=",
"arr",
".",
"length",
";",
"i",
"<",
"max",
";",
"i",
"++",
")",
"{",
"let",
"j",
"=",
"randomInt",
"(",
"max",
")",
";",
"if",
"(",
"arr",
"[",
"j",
"]",
"!==",
"arr",
"[",
"i",
"]",
")",
"{",
"let",
"source",
"=",
"arr",
"[",
"i",
"]",
";",
"arr",
"[",
"i",
"]",
"=",
"arr",
"[",
"j",
"]",
";",
"arr",
"[",
"j",
"]",
"=",
"source",
";",
"}",
"}",
"}"
] | Fisher-Yates "inside-out" shuffle. Randomize order of modules and
their properties when minifying.
@function shuffleArray
@param {Object} options
@param {Array} arr
@api private | [
"Fisher",
"-",
"Yates",
"inside",
"-",
"out",
"shuffle",
".",
"Randomize",
"order",
"of",
"modules",
"and",
"their",
"properties",
"when",
"minifying",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/deploy/parse.js#L107-L120 |
48,645 | jeanamarante/catena | tasks/deploy/parse.js | parseExtend | function parseExtend (ast) {
for (let i = 0, max = ast.body.length; i < max; i++) {
let node = ast.body[i];
// Search for extend('Parent', 'Child');
if (isExpressionStatement(node) && isCallExpression(node.expression) && node.expression.callee.name === 'extend') {
node = node.expression;
let parent = node.arguments[0].value;
let child = node.arguments[1].value;
createHierarchyNode(parent);
createHierarchyNode(child);
// Link child to parent.
hierarchy[parent].children.push(child);
// Link parent to child.
hierarchy[child].parent = parent;
return true;
}
}
return false;
} | javascript | function parseExtend (ast) {
for (let i = 0, max = ast.body.length; i < max; i++) {
let node = ast.body[i];
// Search for extend('Parent', 'Child');
if (isExpressionStatement(node) && isCallExpression(node.expression) && node.expression.callee.name === 'extend') {
node = node.expression;
let parent = node.arguments[0].value;
let child = node.arguments[1].value;
createHierarchyNode(parent);
createHierarchyNode(child);
// Link child to parent.
hierarchy[parent].children.push(child);
// Link parent to child.
hierarchy[child].parent = parent;
return true;
}
}
return false;
} | [
"function",
"parseExtend",
"(",
"ast",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"max",
"=",
"ast",
".",
"body",
".",
"length",
";",
"i",
"<",
"max",
";",
"i",
"++",
")",
"{",
"let",
"node",
"=",
"ast",
".",
"body",
"[",
"i",
"]",
";",
"// Search for extend('Parent', 'Child');",
"if",
"(",
"isExpressionStatement",
"(",
"node",
")",
"&&",
"isCallExpression",
"(",
"node",
".",
"expression",
")",
"&&",
"node",
".",
"expression",
".",
"callee",
".",
"name",
"===",
"'extend'",
")",
"{",
"node",
"=",
"node",
".",
"expression",
";",
"let",
"parent",
"=",
"node",
".",
"arguments",
"[",
"0",
"]",
".",
"value",
";",
"let",
"child",
"=",
"node",
".",
"arguments",
"[",
"1",
"]",
".",
"value",
";",
"createHierarchyNode",
"(",
"parent",
")",
";",
"createHierarchyNode",
"(",
"child",
")",
";",
"// Link child to parent.",
"hierarchy",
"[",
"parent",
"]",
".",
"children",
".",
"push",
"(",
"child",
")",
";",
"// Link parent to child.",
"hierarchy",
"[",
"child",
"]",
".",
"parent",
"=",
"parent",
";",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Search for top level extend invocation and store parent and child
modules as hierarchical nodes.
@function parseExtend
@param {Object} ast
@return {Boolean}
@api private | [
"Search",
"for",
"top",
"level",
"extend",
"invocation",
"and",
"store",
"parent",
"and",
"child",
"modules",
"as",
"hierarchical",
"nodes",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/deploy/parse.js#L257-L282 |
48,646 | jeanamarante/catena | tasks/deploy/parse.js | parseClass | function parseClass (ast, content) {
let appendNode = null;
let appendName = '';
let constructorNode = null;
let constructorName = '';
for (let i = 0, max = ast.body.length; i < max; i++) {
let node = ast.body[i];
if (!isExpressionStatement(node) || !isAssignmentExpression(node.expression)) { continue; }
node = node.expression;
// Search for constructor -> CLASS.Module = function () {};
if (isIdentifier(node.left.object) && isIdentifier(node.left.property) && node.left.object.name === 'CLASS') {
constructorNode = node;
constructorName = node.left.property.name;
// Search for append -> CLASS.Module.append = {};
} else if (isMemberExpression(node.left.object)) {
let subNode = node.left;
if (isIdentifier(subNode.object.object) && isIdentifier(subNode.object.property)) {
if (subNode.object.object.name !== 'CLASS' || subNode.property.name !== 'append') { continue; }
appendNode = node;
appendName = subNode.object.property.name;
}
}
}
// If no constructor or append node is found or if the constructor and
// append name do not match then don't create the hierarchy node.
if (constructorNode === null || appendNode === null) {
return false;
} else if (constructorName !== appendName) {
return false;
}
createHierarchyNode(constructorName);
let hierarchyNode = hierarchy[constructorName];
hierarchyNode.content = content;
hierarchyNode.appendNode = appendNode;
hierarchyNode.constructorNode = constructorNode;
return true;
} | javascript | function parseClass (ast, content) {
let appendNode = null;
let appendName = '';
let constructorNode = null;
let constructorName = '';
for (let i = 0, max = ast.body.length; i < max; i++) {
let node = ast.body[i];
if (!isExpressionStatement(node) || !isAssignmentExpression(node.expression)) { continue; }
node = node.expression;
// Search for constructor -> CLASS.Module = function () {};
if (isIdentifier(node.left.object) && isIdentifier(node.left.property) && node.left.object.name === 'CLASS') {
constructorNode = node;
constructorName = node.left.property.name;
// Search for append -> CLASS.Module.append = {};
} else if (isMemberExpression(node.left.object)) {
let subNode = node.left;
if (isIdentifier(subNode.object.object) && isIdentifier(subNode.object.property)) {
if (subNode.object.object.name !== 'CLASS' || subNode.property.name !== 'append') { continue; }
appendNode = node;
appendName = subNode.object.property.name;
}
}
}
// If no constructor or append node is found or if the constructor and
// append name do not match then don't create the hierarchy node.
if (constructorNode === null || appendNode === null) {
return false;
} else if (constructorName !== appendName) {
return false;
}
createHierarchyNode(constructorName);
let hierarchyNode = hierarchy[constructorName];
hierarchyNode.content = content;
hierarchyNode.appendNode = appendNode;
hierarchyNode.constructorNode = constructorNode;
return true;
} | [
"function",
"parseClass",
"(",
"ast",
",",
"content",
")",
"{",
"let",
"appendNode",
"=",
"null",
";",
"let",
"appendName",
"=",
"''",
";",
"let",
"constructorNode",
"=",
"null",
";",
"let",
"constructorName",
"=",
"''",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"max",
"=",
"ast",
".",
"body",
".",
"length",
";",
"i",
"<",
"max",
";",
"i",
"++",
")",
"{",
"let",
"node",
"=",
"ast",
".",
"body",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"isExpressionStatement",
"(",
"node",
")",
"||",
"!",
"isAssignmentExpression",
"(",
"node",
".",
"expression",
")",
")",
"{",
"continue",
";",
"}",
"node",
"=",
"node",
".",
"expression",
";",
"// Search for constructor -> CLASS.Module = function () {};",
"if",
"(",
"isIdentifier",
"(",
"node",
".",
"left",
".",
"object",
")",
"&&",
"isIdentifier",
"(",
"node",
".",
"left",
".",
"property",
")",
"&&",
"node",
".",
"left",
".",
"object",
".",
"name",
"===",
"'CLASS'",
")",
"{",
"constructorNode",
"=",
"node",
";",
"constructorName",
"=",
"node",
".",
"left",
".",
"property",
".",
"name",
";",
"// Search for append -> CLASS.Module.append = {};",
"}",
"else",
"if",
"(",
"isMemberExpression",
"(",
"node",
".",
"left",
".",
"object",
")",
")",
"{",
"let",
"subNode",
"=",
"node",
".",
"left",
";",
"if",
"(",
"isIdentifier",
"(",
"subNode",
".",
"object",
".",
"object",
")",
"&&",
"isIdentifier",
"(",
"subNode",
".",
"object",
".",
"property",
")",
")",
"{",
"if",
"(",
"subNode",
".",
"object",
".",
"object",
".",
"name",
"!==",
"'CLASS'",
"||",
"subNode",
".",
"property",
".",
"name",
"!==",
"'append'",
")",
"{",
"continue",
";",
"}",
"appendNode",
"=",
"node",
";",
"appendName",
"=",
"subNode",
".",
"object",
".",
"property",
".",
"name",
";",
"}",
"}",
"}",
"// If no constructor or append node is found or if the constructor and",
"// append name do not match then don't create the hierarchy node.",
"if",
"(",
"constructorNode",
"===",
"null",
"||",
"appendNode",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"constructorName",
"!==",
"appendName",
")",
"{",
"return",
"false",
";",
"}",
"createHierarchyNode",
"(",
"constructorName",
")",
";",
"let",
"hierarchyNode",
"=",
"hierarchy",
"[",
"constructorName",
"]",
";",
"hierarchyNode",
".",
"content",
"=",
"content",
";",
"hierarchyNode",
".",
"appendNode",
"=",
"appendNode",
";",
"hierarchyNode",
".",
"constructorNode",
"=",
"constructorNode",
";",
"return",
"true",
";",
"}"
] | Search for top level CLASS constructor and append assignment expressions.
@function parseClass
@param {Object} ast
@param {String} content
@return {Boolean}
@api private | [
"Search",
"for",
"top",
"level",
"CLASS",
"constructor",
"and",
"append",
"assignment",
"expressions",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/deploy/parse.js#L294-L342 |
48,647 | jeanamarante/catena | tasks/deploy/parse.js | processClass | function processClass (options, name, node) {
processClassConstructor(options, name, node);
processClassAppend(options, name, node);
shuffleArray(options, node.children);
for (let i = 0, max = node.children.length; i < max; i++) {
let child = node.children[i];
processClass(options, child, hierarchy[child]);
}
} | javascript | function processClass (options, name, node) {
processClassConstructor(options, name, node);
processClassAppend(options, name, node);
shuffleArray(options, node.children);
for (let i = 0, max = node.children.length; i < max; i++) {
let child = node.children[i];
processClass(options, child, hierarchy[child]);
}
} | [
"function",
"processClass",
"(",
"options",
",",
"name",
",",
"node",
")",
"{",
"processClassConstructor",
"(",
"options",
",",
"name",
",",
"node",
")",
";",
"processClassAppend",
"(",
"options",
",",
"name",
",",
"node",
")",
";",
"shuffleArray",
"(",
"options",
",",
"node",
".",
"children",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"max",
"=",
"node",
".",
"children",
".",
"length",
";",
"i",
"<",
"max",
";",
"i",
"++",
")",
"{",
"let",
"child",
"=",
"node",
".",
"children",
"[",
"i",
"]",
";",
"processClass",
"(",
"options",
",",
"child",
",",
"hierarchy",
"[",
"child",
"]",
")",
";",
"}",
"}"
] | Recursively process the content of class modules into writeArray.
@function processClass
@param {Object} options
@param {String} name
@param {Object} node
@return {Boolean}
@api private | [
"Recursively",
"process",
"the",
"content",
"of",
"class",
"modules",
"into",
"writeArray",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/deploy/parse.js#L355-L366 |
48,648 | kuno/neco | deps/npm/lib/config.js | config | function config (args, cb) {
var action = args.shift()
switch (action) {
case "set": return set(args[0], args[1], cb)
case "get": return get(args[0], cb)
case "delete": case "rm": case "del": return del(args[0], cb)
case "list": case "ls": return list(cb)
case "edit": return edit(cb)
default: return unknown(action, cb)
}
} | javascript | function config (args, cb) {
var action = args.shift()
switch (action) {
case "set": return set(args[0], args[1], cb)
case "get": return get(args[0], cb)
case "delete": case "rm": case "del": return del(args[0], cb)
case "list": case "ls": return list(cb)
case "edit": return edit(cb)
default: return unknown(action, cb)
}
} | [
"function",
"config",
"(",
"args",
",",
"cb",
")",
"{",
"var",
"action",
"=",
"args",
".",
"shift",
"(",
")",
"switch",
"(",
"action",
")",
"{",
"case",
"\"set\"",
":",
"return",
"set",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
",",
"cb",
")",
"case",
"\"get\"",
":",
"return",
"get",
"(",
"args",
"[",
"0",
"]",
",",
"cb",
")",
"case",
"\"delete\"",
":",
"case",
"\"rm\"",
":",
"case",
"\"del\"",
":",
"return",
"del",
"(",
"args",
"[",
"0",
"]",
",",
"cb",
")",
"case",
"\"list\"",
":",
"case",
"\"ls\"",
":",
"return",
"list",
"(",
"cb",
")",
"case",
"\"edit\"",
":",
"return",
"edit",
"(",
"cb",
")",
"default",
":",
"return",
"unknown",
"(",
"action",
",",
"cb",
")",
"}",
"}"
] | npm config set key value npm config get key npm config list | [
"npm",
"config",
"set",
"key",
"value",
"npm",
"config",
"get",
"key",
"npm",
"config",
"list"
] | cf6361c1fcb9466c6b2ab3b127b5d0160ca50735 | https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/config.js#L36-L46 |
48,649 | lteacher/mysql-query-wrapper | lib/wrapper.js | init | function init(input) {
// Use provided pool
if(typeof input == 'function') db.pool = input;
else {
// Create the pool with any options merged with the below defaults
db.pool = mysql.createPool(Object.assign({
user: 'root',
password: 'root',
database: 'test'
},input));
}
// Set the local _pool(just for convenience)
_pool = db.pool;
return db;
} | javascript | function init(input) {
// Use provided pool
if(typeof input == 'function') db.pool = input;
else {
// Create the pool with any options merged with the below defaults
db.pool = mysql.createPool(Object.assign({
user: 'root',
password: 'root',
database: 'test'
},input));
}
// Set the local _pool(just for convenience)
_pool = db.pool;
return db;
} | [
"function",
"init",
"(",
"input",
")",
"{",
"// Use provided pool",
"if",
"(",
"typeof",
"input",
"==",
"'function'",
")",
"db",
".",
"pool",
"=",
"input",
";",
"else",
"{",
"// Create the pool with any options merged with the below defaults",
"db",
".",
"pool",
"=",
"mysql",
".",
"createPool",
"(",
"Object",
".",
"assign",
"(",
"{",
"user",
":",
"'root'",
",",
"password",
":",
"'root'",
",",
"database",
":",
"'test'",
"}",
",",
"input",
")",
")",
";",
"}",
"// Set the local _pool(just for convenience)",
"_pool",
"=",
"db",
".",
"pool",
";",
"return",
"db",
";",
"}"
] | The db function is the initialiser for setting a pool if provided on require
@param {Pool|Object} [input] - Either a mysql.Pool OR a config options object
@return {Function} Returns the db function so we can attach additional exports | [
"The",
"db",
"function",
"is",
"the",
"initialiser",
"for",
"setting",
"a",
"pool",
"if",
"provided",
"on",
"require"
] | 09211b08ef1f8ce429957f42de83cba533df56d5 | https://github.com/lteacher/mysql-query-wrapper/blob/09211b08ef1f8ce429957f42de83cba533df56d5/lib/wrapper.js#L12-L29 |
48,650 | lteacher/mysql-query-wrapper | lib/wrapper.js | _checkConnection | function _checkConnection(conn) {
// Return Promise for getConnection callback wrapping
return new Promise((resolve, reject) => {
if (conn) {
resolve(conn);
} else {
_pool.getConnection((err, conn) => {
if (err) reject(err); // Reject this error
else resolve(conn); // Resolve the connection
})
}
});
} | javascript | function _checkConnection(conn) {
// Return Promise for getConnection callback wrapping
return new Promise((resolve, reject) => {
if (conn) {
resolve(conn);
} else {
_pool.getConnection((err, conn) => {
if (err) reject(err); // Reject this error
else resolve(conn); // Resolve the connection
})
}
});
} | [
"function",
"_checkConnection",
"(",
"conn",
")",
"{",
"// Return Promise for getConnection callback wrapping",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"conn",
")",
"{",
"resolve",
"(",
"conn",
")",
";",
"}",
"else",
"{",
"_pool",
".",
"getConnection",
"(",
"(",
"err",
",",
"conn",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"reject",
"(",
"err",
")",
";",
"// Reject this error",
"else",
"resolve",
"(",
"conn",
")",
";",
"// Resolve the connection",
"}",
")",
"}",
"}",
")",
";",
"}"
] | Check and return a connection, or get new connection from the pool | [
"Check",
"and",
"return",
"a",
"connection",
"or",
"get",
"new",
"connection",
"from",
"the",
"pool"
] | 09211b08ef1f8ce429957f42de83cba533df56d5 | https://github.com/lteacher/mysql-query-wrapper/blob/09211b08ef1f8ce429957f42de83cba533df56d5/lib/wrapper.js#L141-L153 |
48,651 | lteacher/mysql-query-wrapper | lib/wrapper.js | function(sql, val, callback) {
let qry = (typeof sql === 'object') ? sql : mysql.format(sql, val);
if (!callback && typeof val === 'function') callback = val; // Handle 2 parm scenario
_pool.getConnection((err, conn) => {
_pool.query(qry, (err, items, fields) => {
if (err) return callback(err);
conn.release();
callback(err, items);
});
});
} | javascript | function(sql, val, callback) {
let qry = (typeof sql === 'object') ? sql : mysql.format(sql, val);
if (!callback && typeof val === 'function') callback = val; // Handle 2 parm scenario
_pool.getConnection((err, conn) => {
_pool.query(qry, (err, items, fields) => {
if (err) return callback(err);
conn.release();
callback(err, items);
});
});
} | [
"function",
"(",
"sql",
",",
"val",
",",
"callback",
")",
"{",
"let",
"qry",
"=",
"(",
"typeof",
"sql",
"===",
"'object'",
")",
"?",
"sql",
":",
"mysql",
".",
"format",
"(",
"sql",
",",
"val",
")",
";",
"if",
"(",
"!",
"callback",
"&&",
"typeof",
"val",
"===",
"'function'",
")",
"callback",
"=",
"val",
";",
"// Handle 2 parm scenario",
"_pool",
".",
"getConnection",
"(",
"(",
"err",
",",
"conn",
")",
"=>",
"{",
"_pool",
".",
"query",
"(",
"qry",
",",
"(",
"err",
",",
"items",
",",
"fields",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"conn",
".",
"release",
"(",
")",
";",
"callback",
"(",
"err",
",",
"items",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Exposes the basic query without promise | [
"Exposes",
"the",
"basic",
"query",
"without",
"promise"
] | 09211b08ef1f8ce429957f42de83cba533df56d5 | https://github.com/lteacher/mysql-query-wrapper/blob/09211b08ef1f8ce429957f42de83cba533df56d5/lib/wrapper.js#L156-L169 |
|
48,652 | morungos/log4js-knex | lib/log4js-knex.js | knexAppender | function knexAppender(config, layouts) {
if (! config.knex) {
throw new Error('knex.js connection parameters are missing');
}
let layout = null;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
} else {
layout = layouts.messagePassThroughLayout;
}
let tableName = config.table || 'log';
let additionalFields = config.additionalFields || {};
let knex = typeof config.knex === 'object' ? Knex(config.knex) : config.knex;
function writeEvent(loggingEvent) {
// Build a record to insert
const record = Object.assign({}, {
time: loggingEvent.startTime.valueOf(),
data: layout(loggingEvent),
rank: loggingEvent.level.level,
level: loggingEvent.level.levelStr,
category: loggingEvent.categoryName
}, additionalFields);
// Insert it, inside a transaction
return knex.transaction((trx) => trx(tableName).insert(record).then(() => null));
};
return writeEvent;
} | javascript | function knexAppender(config, layouts) {
if (! config.knex) {
throw new Error('knex.js connection parameters are missing');
}
let layout = null;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
} else {
layout = layouts.messagePassThroughLayout;
}
let tableName = config.table || 'log';
let additionalFields = config.additionalFields || {};
let knex = typeof config.knex === 'object' ? Knex(config.knex) : config.knex;
function writeEvent(loggingEvent) {
// Build a record to insert
const record = Object.assign({}, {
time: loggingEvent.startTime.valueOf(),
data: layout(loggingEvent),
rank: loggingEvent.level.level,
level: loggingEvent.level.levelStr,
category: loggingEvent.categoryName
}, additionalFields);
// Insert it, inside a transaction
return knex.transaction((trx) => trx(tableName).insert(record).then(() => null));
};
return writeEvent;
} | [
"function",
"knexAppender",
"(",
"config",
",",
"layouts",
")",
"{",
"if",
"(",
"!",
"config",
".",
"knex",
")",
"{",
"throw",
"new",
"Error",
"(",
"'knex.js connection parameters are missing'",
")",
";",
"}",
"let",
"layout",
"=",
"null",
";",
"if",
"(",
"config",
".",
"layout",
")",
"{",
"layout",
"=",
"layouts",
".",
"layout",
"(",
"config",
".",
"layout",
".",
"type",
",",
"config",
".",
"layout",
")",
";",
"}",
"else",
"{",
"layout",
"=",
"layouts",
".",
"messagePassThroughLayout",
";",
"}",
"let",
"tableName",
"=",
"config",
".",
"table",
"||",
"'log'",
";",
"let",
"additionalFields",
"=",
"config",
".",
"additionalFields",
"||",
"{",
"}",
";",
"let",
"knex",
"=",
"typeof",
"config",
".",
"knex",
"===",
"'object'",
"?",
"Knex",
"(",
"config",
".",
"knex",
")",
":",
"config",
".",
"knex",
";",
"function",
"writeEvent",
"(",
"loggingEvent",
")",
"{",
"// Build a record to insert",
"const",
"record",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"{",
"time",
":",
"loggingEvent",
".",
"startTime",
".",
"valueOf",
"(",
")",
",",
"data",
":",
"layout",
"(",
"loggingEvent",
")",
",",
"rank",
":",
"loggingEvent",
".",
"level",
".",
"level",
",",
"level",
":",
"loggingEvent",
".",
"level",
".",
"levelStr",
",",
"category",
":",
"loggingEvent",
".",
"categoryName",
"}",
",",
"additionalFields",
")",
";",
"// Insert it, inside a transaction",
"return",
"knex",
".",
"transaction",
"(",
"(",
"trx",
")",
"=>",
"trx",
"(",
"tableName",
")",
".",
"insert",
"(",
"record",
")",
".",
"then",
"(",
"(",
")",
"=>",
"null",
")",
")",
";",
"}",
";",
"return",
"writeEvent",
";",
"}"
] | Returns a function to log data in knex.
@param {Object} config The configuration object.
@param {string} config.connectionString The connection string to the mongo db.
@param {string=} config.layout The log4js layout.
@param {string=} config.write The write mode.
@returns {Function} | [
"Returns",
"a",
"function",
"to",
"log",
"data",
"in",
"knex",
"."
] | 973d7072136d1b67624cdd821b59c019798f3349 | https://github.com/morungos/log4js-knex/blob/973d7072136d1b67624cdd821b59c019798f3349/lib/log4js-knex.js#L15-L48 |
48,653 | bholloway/browserify-debug-tools | lib/match.js | match | function match(regex, callback) {
return inspect(onComplete);
function onComplete(filename, contents, done) {
callback(filename, contents.match(regex), done);
if (callback.length < 3) {
done();
}
}
} | javascript | function match(regex, callback) {
return inspect(onComplete);
function onComplete(filename, contents, done) {
callback(filename, contents.match(regex), done);
if (callback.length < 3) {
done();
}
}
} | [
"function",
"match",
"(",
"regex",
",",
"callback",
")",
"{",
"return",
"inspect",
"(",
"onComplete",
")",
";",
"function",
"onComplete",
"(",
"filename",
",",
"contents",
",",
"done",
")",
"{",
"callback",
"(",
"filename",
",",
"contents",
".",
"match",
"(",
"regex",
")",
",",
"done",
")",
";",
"if",
"(",
"callback",
".",
"length",
"<",
"3",
")",
"{",
"done",
"(",
")",
";",
"}",
"}",
"}"
] | Match a regular expression in the transformed file's contents and call the given method for each file.
@param {RegExp} regex A regular expression to test the file contents
@param {function} callback A method to call with the filename and matches for each file | [
"Match",
"a",
"regular",
"expression",
"in",
"the",
"transformed",
"file",
"s",
"contents",
"and",
"call",
"the",
"given",
"method",
"for",
"each",
"file",
"."
] | 47aa05164d73ec7512bdd4a18db0e12fa6b96209 | https://github.com/bholloway/browserify-debug-tools/blob/47aa05164d73ec7512bdd4a18db0e12fa6b96209/lib/match.js#L10-L19 |
48,654 | avoidwork/mpass | src/random.js | random | function random (arg, used) {
var n;
do {
n = Math.floor(Math.random() * arg);
} while (used[n]);
used[n] = 1;
return n;
} | javascript | function random (arg, used) {
var n;
do {
n = Math.floor(Math.random() * arg);
} while (used[n]);
used[n] = 1;
return n;
} | [
"function",
"random",
"(",
"arg",
",",
"used",
")",
"{",
"var",
"n",
";",
"do",
"{",
"n",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"arg",
")",
";",
"}",
"while",
"(",
"used",
"[",
"n",
"]",
")",
";",
"used",
"[",
"n",
"]",
"=",
"1",
";",
"return",
"n",
";",
"}"
] | Generates a random number between 0 & ceiling
@method random
@param {Number} arg Ceiling
@param {Object} used Hash of used indices
@return {Number} Random number between 0 and ceiling | [
"Generates",
"a",
"random",
"number",
"between",
"0",
"&",
"ceiling"
] | 3881af71808c1eba55a9f0525c919f0491e949cb | https://github.com/avoidwork/mpass/blob/3881af71808c1eba55a9f0525c919f0491e949cb/src/random.js#L9-L19 |
48,655 | chrisJohn404/LabJack-nodejs | lib/device.js | function(err, res) {
if(err) {
return onError('Weird Error open', err);
}
//Check for no errors
if(res === 0) {
//Save the handle & other information to the
// device class
self.handle = refDeviceHandle.readInt32LE(0);
self.deviceType = deviceType;
self.connectionType = connectionType;
self.identifier = identifier;
self.isHandleValid = true;
return onSuccess();
} else {
//Make sure that the handle, deviceType
// & connectionType are still null
self.handle = null;
self.deviceType = null;
self.connectionType = null;
self.identifier = null;
return onError(res);
}
} | javascript | function(err, res) {
if(err) {
return onError('Weird Error open', err);
}
//Check for no errors
if(res === 0) {
//Save the handle & other information to the
// device class
self.handle = refDeviceHandle.readInt32LE(0);
self.deviceType = deviceType;
self.connectionType = connectionType;
self.identifier = identifier;
self.isHandleValid = true;
return onSuccess();
} else {
//Make sure that the handle, deviceType
// & connectionType are still null
self.handle = null;
self.deviceType = null;
self.connectionType = null;
self.identifier = null;
return onError(res);
}
} | [
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"onError",
"(",
"'Weird Error open'",
",",
"err",
")",
";",
"}",
"//Check for no errors",
"if",
"(",
"res",
"===",
"0",
")",
"{",
"//Save the handle & other information to the ",
"//\tdevice class",
"self",
".",
"handle",
"=",
"refDeviceHandle",
".",
"readInt32LE",
"(",
"0",
")",
";",
"self",
".",
"deviceType",
"=",
"deviceType",
";",
"self",
".",
"connectionType",
"=",
"connectionType",
";",
"self",
".",
"identifier",
"=",
"identifier",
";",
"self",
".",
"isHandleValid",
"=",
"true",
";",
"return",
"onSuccess",
"(",
")",
";",
"}",
"else",
"{",
"//Make sure that the handle, deviceType ",
"//\t\t& connectionType are still null",
"self",
".",
"handle",
"=",
"null",
";",
"self",
".",
"deviceType",
"=",
"null",
";",
"self",
".",
"connectionType",
"=",
"null",
";",
"self",
".",
"identifier",
"=",
"null",
";",
"return",
"onError",
"(",
"res",
")",
";",
"}",
"}"
] | Function for handling the ffi callback | [
"Function",
"for",
"handling",
"the",
"ffi",
"callback"
] | 6f638eb039f3e1619e46ba5aac20d827fecafc29 | https://github.com/chrisJohn404/LabJack-nodejs/blob/6f638eb039f3e1619e46ba5aac20d827fecafc29/lib/device.js#L207-L230 |
|
48,656 | chrisJohn404/LabJack-nodejs | lib/device.js | function(address, writeData) {
var writeInfo = {
'isValid': false,
'message': 'Unknown Reason',
// Data to be written
'address': undefined,
'type': undefined,
'numValues': undefined,
'aValues': undefined,
'errorAddress': undefined,
};
var info = self.constants.getAddressInfo(address, 'W');
var isDirectionValid = info.directionValid == 1;
var isBufferRegister = false;
if(info.data) {
if(info.data.isBuffer) {
isBufferRegister = true;
}
}
if (isDirectionValid && isBufferRegister) {
writeInfo.isValid = true;
// Save info
writeInfo.address = info.address;
writeInfo.type = info.type;
var errorVal = new ref.alloc('int',1);
errorVal.fill(0);
writeInfo.errorAddress = errorVal;
// Variable declarations:
var aValues, offset, i;
// Check to see if the input-data is of the type "buffer"
if(Buffer.isBuffer(writeData)) {
writeInfo.isValid = false;
writeInfo.message = 'Buffer type is not supported';
} else if(Array.isArray(writeData)) {
writeInfo.numValues = writeData.length;
aValues = new Buffer(writeData.length * ARCH_DOUBLE_NUM_BYTES);
aValues.fill(0);
offset = 0;
for(i = 0; i < writeData.length; i++) {
aValues.writeDoubleLE(writeData[i], offset);
offset += ARCH_DOUBLE_NUM_BYTES;
}
writeInfo.aValues = aValues;
} else if((typeof(writeData) === 'string') || (writeData instanceof String)) {
writeInfo.numValues = writeData.length;
aValues = new Buffer(writeData.length * ARCH_DOUBLE_NUM_BYTES);
aValues.fill(0);
offset = 0;
for(i = 0; i < writeData.length; i++) {
aValues.writeDoubleLE(writeData.charCodeAt(i), offset);
offset += ARCH_DOUBLE_NUM_BYTES;
}
writeInfo.aValues = aValues;
} else {
// Un-supported type
writeInfo.isValid = false;
writeInfo.message = 'Invalid data type being written: ' + typeof(writeData) + '.';
}
writeInfo.numValues = writeData.length;
} else {
writeInfo.isValid = false;
if (info.type == -1) {
writeInfo.message = 'Invalid Address';
} else if (info.directionValid === 0) {
writeInfo.message = 'Invalid Read Attempt';
} else if (!isBufferRegister) {
writeInfo.message = 'Tried to read an array from a register that is not a buffer';
}
}
return writeInfo;
} | javascript | function(address, writeData) {
var writeInfo = {
'isValid': false,
'message': 'Unknown Reason',
// Data to be written
'address': undefined,
'type': undefined,
'numValues': undefined,
'aValues': undefined,
'errorAddress': undefined,
};
var info = self.constants.getAddressInfo(address, 'W');
var isDirectionValid = info.directionValid == 1;
var isBufferRegister = false;
if(info.data) {
if(info.data.isBuffer) {
isBufferRegister = true;
}
}
if (isDirectionValid && isBufferRegister) {
writeInfo.isValid = true;
// Save info
writeInfo.address = info.address;
writeInfo.type = info.type;
var errorVal = new ref.alloc('int',1);
errorVal.fill(0);
writeInfo.errorAddress = errorVal;
// Variable declarations:
var aValues, offset, i;
// Check to see if the input-data is of the type "buffer"
if(Buffer.isBuffer(writeData)) {
writeInfo.isValid = false;
writeInfo.message = 'Buffer type is not supported';
} else if(Array.isArray(writeData)) {
writeInfo.numValues = writeData.length;
aValues = new Buffer(writeData.length * ARCH_DOUBLE_NUM_BYTES);
aValues.fill(0);
offset = 0;
for(i = 0; i < writeData.length; i++) {
aValues.writeDoubleLE(writeData[i], offset);
offset += ARCH_DOUBLE_NUM_BYTES;
}
writeInfo.aValues = aValues;
} else if((typeof(writeData) === 'string') || (writeData instanceof String)) {
writeInfo.numValues = writeData.length;
aValues = new Buffer(writeData.length * ARCH_DOUBLE_NUM_BYTES);
aValues.fill(0);
offset = 0;
for(i = 0; i < writeData.length; i++) {
aValues.writeDoubleLE(writeData.charCodeAt(i), offset);
offset += ARCH_DOUBLE_NUM_BYTES;
}
writeInfo.aValues = aValues;
} else {
// Un-supported type
writeInfo.isValid = false;
writeInfo.message = 'Invalid data type being written: ' + typeof(writeData) + '.';
}
writeInfo.numValues = writeData.length;
} else {
writeInfo.isValid = false;
if (info.type == -1) {
writeInfo.message = 'Invalid Address';
} else if (info.directionValid === 0) {
writeInfo.message = 'Invalid Read Attempt';
} else if (!isBufferRegister) {
writeInfo.message = 'Tried to read an array from a register that is not a buffer';
}
}
return writeInfo;
} | [
"function",
"(",
"address",
",",
"writeData",
")",
"{",
"var",
"writeInfo",
"=",
"{",
"'isValid'",
":",
"false",
",",
"'message'",
":",
"'Unknown Reason'",
",",
"// Data to be written",
"'address'",
":",
"undefined",
",",
"'type'",
":",
"undefined",
",",
"'numValues'",
":",
"undefined",
",",
"'aValues'",
":",
"undefined",
",",
"'errorAddress'",
":",
"undefined",
",",
"}",
";",
"var",
"info",
"=",
"self",
".",
"constants",
".",
"getAddressInfo",
"(",
"address",
",",
"'W'",
")",
";",
"var",
"isDirectionValid",
"=",
"info",
".",
"directionValid",
"==",
"1",
";",
"var",
"isBufferRegister",
"=",
"false",
";",
"if",
"(",
"info",
".",
"data",
")",
"{",
"if",
"(",
"info",
".",
"data",
".",
"isBuffer",
")",
"{",
"isBufferRegister",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"isDirectionValid",
"&&",
"isBufferRegister",
")",
"{",
"writeInfo",
".",
"isValid",
"=",
"true",
";",
"// Save info",
"writeInfo",
".",
"address",
"=",
"info",
".",
"address",
";",
"writeInfo",
".",
"type",
"=",
"info",
".",
"type",
";",
"var",
"errorVal",
"=",
"new",
"ref",
".",
"alloc",
"(",
"'int'",
",",
"1",
")",
";",
"errorVal",
".",
"fill",
"(",
"0",
")",
";",
"writeInfo",
".",
"errorAddress",
"=",
"errorVal",
";",
"// Variable declarations:",
"var",
"aValues",
",",
"offset",
",",
"i",
";",
"// Check to see if the input-data is of the type \"buffer\"",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"writeData",
")",
")",
"{",
"writeInfo",
".",
"isValid",
"=",
"false",
";",
"writeInfo",
".",
"message",
"=",
"'Buffer type is not supported'",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"writeData",
")",
")",
"{",
"writeInfo",
".",
"numValues",
"=",
"writeData",
".",
"length",
";",
"aValues",
"=",
"new",
"Buffer",
"(",
"writeData",
".",
"length",
"*",
"ARCH_DOUBLE_NUM_BYTES",
")",
";",
"aValues",
".",
"fill",
"(",
"0",
")",
";",
"offset",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"writeData",
".",
"length",
";",
"i",
"++",
")",
"{",
"aValues",
".",
"writeDoubleLE",
"(",
"writeData",
"[",
"i",
"]",
",",
"offset",
")",
";",
"offset",
"+=",
"ARCH_DOUBLE_NUM_BYTES",
";",
"}",
"writeInfo",
".",
"aValues",
"=",
"aValues",
";",
"}",
"else",
"if",
"(",
"(",
"typeof",
"(",
"writeData",
")",
"===",
"'string'",
")",
"||",
"(",
"writeData",
"instanceof",
"String",
")",
")",
"{",
"writeInfo",
".",
"numValues",
"=",
"writeData",
".",
"length",
";",
"aValues",
"=",
"new",
"Buffer",
"(",
"writeData",
".",
"length",
"*",
"ARCH_DOUBLE_NUM_BYTES",
")",
";",
"aValues",
".",
"fill",
"(",
"0",
")",
";",
"offset",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"writeData",
".",
"length",
";",
"i",
"++",
")",
"{",
"aValues",
".",
"writeDoubleLE",
"(",
"writeData",
".",
"charCodeAt",
"(",
"i",
")",
",",
"offset",
")",
";",
"offset",
"+=",
"ARCH_DOUBLE_NUM_BYTES",
";",
"}",
"writeInfo",
".",
"aValues",
"=",
"aValues",
";",
"}",
"else",
"{",
"// Un-supported type",
"writeInfo",
".",
"isValid",
"=",
"false",
";",
"writeInfo",
".",
"message",
"=",
"'Invalid data type being written: '",
"+",
"typeof",
"(",
"writeData",
")",
"+",
"'.'",
";",
"}",
"writeInfo",
".",
"numValues",
"=",
"writeData",
".",
"length",
";",
"}",
"else",
"{",
"writeInfo",
".",
"isValid",
"=",
"false",
";",
"if",
"(",
"info",
".",
"type",
"==",
"-",
"1",
")",
"{",
"writeInfo",
".",
"message",
"=",
"'Invalid Address'",
";",
"}",
"else",
"if",
"(",
"info",
".",
"directionValid",
"===",
"0",
")",
"{",
"writeInfo",
".",
"message",
"=",
"'Invalid Read Attempt'",
";",
"}",
"else",
"if",
"(",
"!",
"isBufferRegister",
")",
"{",
"writeInfo",
".",
"message",
"=",
"'Tried to read an array from a register that is not a buffer'",
";",
"}",
"}",
"return",
"writeInfo",
";",
"}"
] | A helper function for the writeArray and writeArraySync function to parse
or interpret the data to be written. | [
"A",
"helper",
"function",
"for",
"the",
"writeArray",
"and",
"writeArraySync",
"function",
"to",
"parse",
"or",
"interpret",
"the",
"data",
"to",
"be",
"written",
"."
] | 6f638eb039f3e1619e46ba5aac20d827fecafc29 | https://github.com/chrisJohn404/LabJack-nodejs/blob/6f638eb039f3e1619e46ba5aac20d827fecafc29/lib/device.js#L1590-L1668 |
|
48,657 | oleynikd/gulp-wp-file-header | index.js | function(manifest) {
var out = "/*\n";
_.forEach(fields, function(n, key) {
if (typeof manifest[key] != "undefined") {
out += pad(n+":", 20) + manifest[key] + "\n";
}
});
out += "*/\n";
return out;
} | javascript | function(manifest) {
var out = "/*\n";
_.forEach(fields, function(n, key) {
if (typeof manifest[key] != "undefined") {
out += pad(n+":", 20) + manifest[key] + "\n";
}
});
out += "*/\n";
return out;
} | [
"function",
"(",
"manifest",
")",
"{",
"var",
"out",
"=",
"\"/*\\n\"",
";",
"_",
".",
"forEach",
"(",
"fields",
",",
"function",
"(",
"n",
",",
"key",
")",
"{",
"if",
"(",
"typeof",
"manifest",
"[",
"key",
"]",
"!=",
"\"undefined\"",
")",
"{",
"out",
"+=",
"pad",
"(",
"n",
"+",
"\":\"",
",",
"20",
")",
"+",
"manifest",
"[",
"key",
"]",
"+",
"\"\\n\"",
";",
"}",
"}",
")",
";",
"out",
"+=",
"\"*/\\n\"",
";",
"return",
"out",
";",
"}"
] | Creates style.css header content.
@param {Object} manifest
@return {string}
TODO: add Author URI
TODO: add license info | [
"Creates",
"style",
".",
"css",
"header",
"content",
"."
] | 6834e1a83208f6875bf6010de021c7bc5a28efe5 | https://github.com/oleynikd/gulp-wp-file-header/blob/6834e1a83208f6875bf6010de021c7bc5a28efe5/index.js#L89-L99 |
|
48,658 | jeanamarante/catena | tasks/catena.js | streamWrappers | function streamWrappers (grunt, fileData, options) {
stream.createWriteStream(fileData.tmpWrapStart, () => {
streamWrapperEnd(grunt, fileData, options);
});
if (options.license) {
streamLicense(grunt, fileData, options);
} else {
streamWrapperStart(grunt, fileData, options);
}
} | javascript | function streamWrappers (grunt, fileData, options) {
stream.createWriteStream(fileData.tmpWrapStart, () => {
streamWrapperEnd(grunt, fileData, options);
});
if (options.license) {
streamLicense(grunt, fileData, options);
} else {
streamWrapperStart(grunt, fileData, options);
}
} | [
"function",
"streamWrappers",
"(",
"grunt",
",",
"fileData",
",",
"options",
")",
"{",
"stream",
".",
"createWriteStream",
"(",
"fileData",
".",
"tmpWrapStart",
",",
"(",
")",
"=>",
"{",
"streamWrapperEnd",
"(",
"grunt",
",",
"fileData",
",",
"options",
")",
";",
"}",
")",
";",
"if",
"(",
"options",
".",
"license",
")",
"{",
"streamLicense",
"(",
"grunt",
",",
"fileData",
",",
"options",
")",
";",
"}",
"else",
"{",
"streamWrapperStart",
"(",
"grunt",
",",
"fileData",
",",
"options",
")",
";",
"}",
"}"
] | Create files that will be used to wrap all the matched Javascript files.
@function streamWrappers
@param {Object} grunt
@param {Object} fileData
@param {Object} options
@api private | [
"Create",
"files",
"that",
"will",
"be",
"used",
"to",
"wrap",
"all",
"the",
"matched",
"Javascript",
"files",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/catena.js#L151-L161 |
48,659 | jeanamarante/catena | tasks/catena.js | streamLicense | function streamLicense (grunt, fileData, options) {
let content = grunt.file.read(options.license);
// Use JSDoc license tag to preserve file content as
// comment when minifying.
if (options.deploy && options.minify) {
content = `/**@license ${content}*/`;
} else {
content = `/*\x0A${content}*/\x0A\x0A`;
}
stream.write(content, () => {
streamWrapperStart(grunt, fileData, options);
});
} | javascript | function streamLicense (grunt, fileData, options) {
let content = grunt.file.read(options.license);
// Use JSDoc license tag to preserve file content as
// comment when minifying.
if (options.deploy && options.minify) {
content = `/**@license ${content}*/`;
} else {
content = `/*\x0A${content}*/\x0A\x0A`;
}
stream.write(content, () => {
streamWrapperStart(grunt, fileData, options);
});
} | [
"function",
"streamLicense",
"(",
"grunt",
",",
"fileData",
",",
"options",
")",
"{",
"let",
"content",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"options",
".",
"license",
")",
";",
"// Use JSDoc license tag to preserve file content as",
"// comment when minifying.",
"if",
"(",
"options",
".",
"deploy",
"&&",
"options",
".",
"minify",
")",
"{",
"content",
"=",
"`",
"${",
"content",
"}",
"`",
";",
"}",
"else",
"{",
"content",
"=",
"`",
"\\x0A",
"${",
"content",
"}",
"\\x0A",
"\\x0A",
"`",
";",
"}",
"stream",
".",
"write",
"(",
"content",
",",
"(",
")",
"=>",
"{",
"streamWrapperStart",
"(",
"grunt",
",",
"fileData",
",",
"options",
")",
";",
"}",
")",
";",
"}"
] | Prepend license in the starting wrapper.
@function streamLicense
@param {Object} grunt
@param {Object} fileData
@param {Object} options
@api private | [
"Prepend",
"license",
"in",
"the",
"starting",
"wrapper",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/catena.js#L173-L187 |
48,660 | jeanamarante/catena | tasks/catena.js | recurseSrcDirectories | function recurseSrcDirectories (grunt, fileData, options) {
let promises = [];
// Ignore everything except directories and Javascript files.
// Store function in array for recursive-readdir module.
let ignoreCallback = [(file, stats) => !(stats.isDirectory() || path.extname(file) === '.js')];
for (let i = 0, max = fileData.src.length; i < max; i++) {
promises.push(readDir(fileData.src[i], ignoreCallback).then((value) => value, (err) => err));
}
Promise.all(promises)
.then((values) => {
streamMatches(grunt, fileData, options, values, values.flat());
}, throwAsyncError);
} | javascript | function recurseSrcDirectories (grunt, fileData, options) {
let promises = [];
// Ignore everything except directories and Javascript files.
// Store function in array for recursive-readdir module.
let ignoreCallback = [(file, stats) => !(stats.isDirectory() || path.extname(file) === '.js')];
for (let i = 0, max = fileData.src.length; i < max; i++) {
promises.push(readDir(fileData.src[i], ignoreCallback).then((value) => value, (err) => err));
}
Promise.all(promises)
.then((values) => {
streamMatches(grunt, fileData, options, values, values.flat());
}, throwAsyncError);
} | [
"function",
"recurseSrcDirectories",
"(",
"grunt",
",",
"fileData",
",",
"options",
")",
"{",
"let",
"promises",
"=",
"[",
"]",
";",
"// Ignore everything except directories and Javascript files.",
"// Store function in array for recursive-readdir module.",
"let",
"ignoreCallback",
"=",
"[",
"(",
"file",
",",
"stats",
")",
"=>",
"!",
"(",
"stats",
".",
"isDirectory",
"(",
")",
"||",
"path",
".",
"extname",
"(",
"file",
")",
"===",
"'.js'",
")",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"max",
"=",
"fileData",
".",
"src",
".",
"length",
";",
"i",
"<",
"max",
";",
"i",
"++",
")",
"{",
"promises",
".",
"push",
"(",
"readDir",
"(",
"fileData",
".",
"src",
"[",
"i",
"]",
",",
"ignoreCallback",
")",
".",
"then",
"(",
"(",
"value",
")",
"=>",
"value",
",",
"(",
"err",
")",
"=>",
"err",
")",
")",
";",
"}",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"(",
"values",
")",
"=>",
"{",
"streamMatches",
"(",
"grunt",
",",
"fileData",
",",
"options",
",",
"values",
",",
"values",
".",
"flat",
"(",
")",
")",
";",
"}",
",",
"throwAsyncError",
")",
";",
"}"
] | Find all Javascript files in src directories.
@function recurseSrcDirectories
@param {Object} grunt
@param {Object} fileData
@param {Object} options
@api private | [
"Find",
"all",
"Javascript",
"files",
"in",
"src",
"directories",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/catena.js#L236-L251 |
48,661 | jeanamarante/catena | tasks/catena.js | streamMatches | function streamMatches (grunt, fileData, options, matches, flattenedMatches) {
// Run optional tasks after we stream matches to dest.
stream.createWriteStream(fileData.dest, () => {
require('./dev/test')(grunt, fileData, options, throwAsyncError).performTests();
if (options.deploy) {
require('./deploy/parse')(grunt, fileData, options, asyncDone, throwAsyncError, flattenedMatches);
} else {
// Never end task if watch option is true and there are src directories to watch.
if (options.watch && fileData.src.length > 0) {
require('./dev/watch')(grunt, fileData, options, throwAsyncError, matches, flattenedMatches);
} else {
asyncDone(true);
}
}
});
// Place the flattened matches between the start wrapper and the end
// wrapper into a single dimensional array.
stream.pipeFileArray([fileData.tmpWrapStart, flattenedMatches, fileData.tmpWrapEnd].flat());
} | javascript | function streamMatches (grunt, fileData, options, matches, flattenedMatches) {
// Run optional tasks after we stream matches to dest.
stream.createWriteStream(fileData.dest, () => {
require('./dev/test')(grunt, fileData, options, throwAsyncError).performTests();
if (options.deploy) {
require('./deploy/parse')(grunt, fileData, options, asyncDone, throwAsyncError, flattenedMatches);
} else {
// Never end task if watch option is true and there are src directories to watch.
if (options.watch && fileData.src.length > 0) {
require('./dev/watch')(grunt, fileData, options, throwAsyncError, matches, flattenedMatches);
} else {
asyncDone(true);
}
}
});
// Place the flattened matches between the start wrapper and the end
// wrapper into a single dimensional array.
stream.pipeFileArray([fileData.tmpWrapStart, flattenedMatches, fileData.tmpWrapEnd].flat());
} | [
"function",
"streamMatches",
"(",
"grunt",
",",
"fileData",
",",
"options",
",",
"matches",
",",
"flattenedMatches",
")",
"{",
"// Run optional tasks after we stream matches to dest.",
"stream",
".",
"createWriteStream",
"(",
"fileData",
".",
"dest",
",",
"(",
")",
"=>",
"{",
"require",
"(",
"'./dev/test'",
")",
"(",
"grunt",
",",
"fileData",
",",
"options",
",",
"throwAsyncError",
")",
".",
"performTests",
"(",
")",
";",
"if",
"(",
"options",
".",
"deploy",
")",
"{",
"require",
"(",
"'./deploy/parse'",
")",
"(",
"grunt",
",",
"fileData",
",",
"options",
",",
"asyncDone",
",",
"throwAsyncError",
",",
"flattenedMatches",
")",
";",
"}",
"else",
"{",
"// Never end task if watch option is true and there are src directories to watch.",
"if",
"(",
"options",
".",
"watch",
"&&",
"fileData",
".",
"src",
".",
"length",
">",
"0",
")",
"{",
"require",
"(",
"'./dev/watch'",
")",
"(",
"grunt",
",",
"fileData",
",",
"options",
",",
"throwAsyncError",
",",
"matches",
",",
"flattenedMatches",
")",
";",
"}",
"else",
"{",
"asyncDone",
"(",
"true",
")",
";",
"}",
"}",
"}",
")",
";",
"// Place the flattened matches between the start wrapper and the end",
"// wrapper into a single dimensional array.",
"stream",
".",
"pipeFileArray",
"(",
"[",
"fileData",
".",
"tmpWrapStart",
",",
"flattenedMatches",
",",
"fileData",
".",
"tmpWrapEnd",
"]",
".",
"flat",
"(",
")",
")",
";",
"}"
] | Iterate all matches and stream them into the dest file.
@function streamMatches
@param {Object} grunt
@param {Object} fileData
@param {Object} options
@param {Array} matches
@param {Array} flattenedMatches
@api private | [
"Iterate",
"all",
"matches",
"and",
"stream",
"them",
"into",
"the",
"dest",
"file",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/catena.js#L265-L285 |
48,662 | sagiegurari/js-project-commons | lib/grunt/helper.js | function (buildConfig) {
var configFile;
var suffix = 'karma';
if (buildConfig.nodeProject) {
suffix = 'mocha';
}
configFile = path.join(currentDirectory, '../lint/eslint/eslintrc-' + suffix + '.js');
return configFile;
} | javascript | function (buildConfig) {
var configFile;
var suffix = 'karma';
if (buildConfig.nodeProject) {
suffix = 'mocha';
}
configFile = path.join(currentDirectory, '../lint/eslint/eslintrc-' + suffix + '.js');
return configFile;
} | [
"function",
"(",
"buildConfig",
")",
"{",
"var",
"configFile",
";",
"var",
"suffix",
"=",
"'karma'",
";",
"if",
"(",
"buildConfig",
".",
"nodeProject",
")",
"{",
"suffix",
"=",
"'mocha'",
";",
"}",
"configFile",
"=",
"path",
".",
"join",
"(",
"currentDirectory",
",",
"'../lint/eslint/eslintrc-'",
"+",
"suffix",
"+",
"'.js'",
")",
";",
"return",
"configFile",
";",
"}"
] | Returns the eslint test sources config file location.
@function
@memberof! GruntTaskHelper
@private
@param {Object} buildConfig - The grunt buildConfig data
@returns {String} The eslint test sources config file location | [
"Returns",
"the",
"eslint",
"test",
"sources",
"config",
"file",
"location",
"."
] | 42dd07a8a3b2c49db71f489e08b94ac7279007a3 | https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/helper.js#L75-L85 |
|
48,663 | sagiegurari/js-project-commons | lib/grunt/helper.js | function (buildConfig, config) {
var testConfig = extend(true, {}, config || {}, {
nomen: true,
unparam: true,
predef: [
'it',
'describe'
]
});
if (!buildConfig.nodeProject) {
testConfig.predef.push('angular');
}
return testConfig;
} | javascript | function (buildConfig, config) {
var testConfig = extend(true, {}, config || {}, {
nomen: true,
unparam: true,
predef: [
'it',
'describe'
]
});
if (!buildConfig.nodeProject) {
testConfig.predef.push('angular');
}
return testConfig;
} | [
"function",
"(",
"buildConfig",
",",
"config",
")",
"{",
"var",
"testConfig",
"=",
"extend",
"(",
"true",
",",
"{",
"}",
",",
"config",
"||",
"{",
"}",
",",
"{",
"nomen",
":",
"true",
",",
"unparam",
":",
"true",
",",
"predef",
":",
"[",
"'it'",
",",
"'describe'",
"]",
"}",
")",
";",
"if",
"(",
"!",
"buildConfig",
".",
"nodeProject",
")",
"{",
"testConfig",
".",
"predef",
".",
"push",
"(",
"'angular'",
")",
";",
"}",
"return",
"testConfig",
";",
"}"
] | Returns the jslint test config.
@function
@memberof! GruntTaskHelper
@private
@param {Object} buildConfig - The grunt buildConfig data
@param {Object} config - The JSLint config used for non test files
@returns {Object} The JSLint config | [
"Returns",
"the",
"jslint",
"test",
"config",
"."
] | 42dd07a8a3b2c49db71f489e08b94ac7279007a3 | https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/helper.js#L127-L142 |
|
48,664 | sagiegurari/js-project-commons | lib/grunt/helper.js | function (buildConfig, options) {
options = options || {};
var includeLib = options.includeLib;
if (includeLib === undefined) {
includeLib = true;
}
var src = [];
if (includeLib) {
if (buildConfig.nodeProject) {
src = src.concat([
'*.js',
'<%=buildConfig.libDirectory%>/**/*.js'
]);
} else if (buildConfig.bowerJSON && buildConfig.bowerJSON.main) {
src.push(buildConfig.bowerJSON.main);
}
}
if (options.includeBuild) {
src.push('project/**/*.js');
}
if (options.includeTest) {
src.push('<%=buildConfig.testDirectory%>/**/*spec.js');
}
return src;
} | javascript | function (buildConfig, options) {
options = options || {};
var includeLib = options.includeLib;
if (includeLib === undefined) {
includeLib = true;
}
var src = [];
if (includeLib) {
if (buildConfig.nodeProject) {
src = src.concat([
'*.js',
'<%=buildConfig.libDirectory%>/**/*.js'
]);
} else if (buildConfig.bowerJSON && buildConfig.bowerJSON.main) {
src.push(buildConfig.bowerJSON.main);
}
}
if (options.includeBuild) {
src.push('project/**/*.js');
}
if (options.includeTest) {
src.push('<%=buildConfig.testDirectory%>/**/*spec.js');
}
return src;
} | [
"function",
"(",
"buildConfig",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"includeLib",
"=",
"options",
".",
"includeLib",
";",
"if",
"(",
"includeLib",
"===",
"undefined",
")",
"{",
"includeLib",
"=",
"true",
";",
"}",
"var",
"src",
"=",
"[",
"]",
";",
"if",
"(",
"includeLib",
")",
"{",
"if",
"(",
"buildConfig",
".",
"nodeProject",
")",
"{",
"src",
"=",
"src",
".",
"concat",
"(",
"[",
"'*.js'",
",",
"'<%=buildConfig.libDirectory%>/**/*.js'",
"]",
")",
";",
"}",
"else",
"if",
"(",
"buildConfig",
".",
"bowerJSON",
"&&",
"buildConfig",
".",
"bowerJSON",
".",
"main",
")",
"{",
"src",
".",
"push",
"(",
"buildConfig",
".",
"bowerJSON",
".",
"main",
")",
";",
"}",
"}",
"if",
"(",
"options",
".",
"includeBuild",
")",
"{",
"src",
".",
"push",
"(",
"'project/**/*.js'",
")",
";",
"}",
"if",
"(",
"options",
".",
"includeTest",
")",
"{",
"src",
".",
"push",
"(",
"'<%=buildConfig.testDirectory%>/**/*spec.js'",
")",
";",
"}",
"return",
"src",
";",
"}"
] | Returns the project sources paths.
@function
@memberof! GruntTaskHelper
@private
@param {Object} buildConfig - The grunt buildConfig data
@param {Object} [options] - Any optional options
@param {Boolean} [options.includeLib=false] - True if to include the main library files
@param {Boolean} [options.includeBuild=false] - True if to include build files
@param {Boolean} [options.includeTest=false] - True if to include test files
@returns {Array} The project sources paths | [
"Returns",
"the",
"project",
"sources",
"paths",
"."
] | 42dd07a8a3b2c49db71f489e08b94ac7279007a3 | https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/helper.js#L156-L185 |
|
48,665 | tianjianchn/javascript-packages | packages/wx-abc/lib/pay.js | xml2json | function xml2json(method, body){
body = util.xml2json(body);
if(body.return_code!=='SUCCESS'){
throw new Error(util.format('api error to call %s: %s', method, body.return_msg));
}
if(body.result_code!=='SUCCESS'){
throw new Error(util.format('business error to call %s: %s %s', method, body.err_code, body.err_code_des));
}
return body;
} | javascript | function xml2json(method, body){
body = util.xml2json(body);
if(body.return_code!=='SUCCESS'){
throw new Error(util.format('api error to call %s: %s', method, body.return_msg));
}
if(body.result_code!=='SUCCESS'){
throw new Error(util.format('business error to call %s: %s %s', method, body.err_code, body.err_code_des));
}
return body;
} | [
"function",
"xml2json",
"(",
"method",
",",
"body",
")",
"{",
"body",
"=",
"util",
".",
"xml2json",
"(",
"body",
")",
";",
"if",
"(",
"body",
".",
"return_code",
"!==",
"'SUCCESS'",
")",
"{",
"throw",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"'api error to call %s: %s'",
",",
"method",
",",
"body",
".",
"return_msg",
")",
")",
";",
"}",
"if",
"(",
"body",
".",
"result_code",
"!==",
"'SUCCESS'",
")",
"{",
"throw",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"'business error to call %s: %s %s'",
",",
"method",
",",
"body",
".",
"err_code",
",",
"body",
".",
"err_code_des",
")",
")",
";",
"}",
"return",
"body",
";",
"}"
] | convert response xml to json | [
"convert",
"response",
"xml",
"to",
"json"
] | 3abe85edbfe323939c84c1d02128d74d6374bcde | https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/wx-abc/lib/pay.js#L134-L144 |
48,666 | jeanamarante/catena | tasks/client-side/class-properties.js | referenceParentNode | function referenceParentNode () {
// If nodeName is an empty string, then reference the parent of the root child.
if (isEmptyString(nodeName)) {
nodeName = this.$parentName;
// Even though super might be invoked in different constructors,
// the same instance will always be referenced. rootName is used
// to know if the chain has been broken.
rootName = this.$name;
// Prevent instance from having parent properties applied more than once.
if (this.$applied) {
throwError(`Cannot invoke super more than once for ${this.$name} instance.`, 'SUPER');
} else {
descriptor.value = true;
Object.defineProperty(this, '$applied', descriptor);
}
// Otherwise just move to next parent.
} else {
// Error out if chain is broken.
if (this.$name !== rootName) {
throwError(`Chain started by ${rootName} instance is being broken by ${this.$name} instance.`, 'SUPER');
}
nodeName = CLASS[nodeName].prototype.$parentName;
}
} | javascript | function referenceParentNode () {
// If nodeName is an empty string, then reference the parent of the root child.
if (isEmptyString(nodeName)) {
nodeName = this.$parentName;
// Even though super might be invoked in different constructors,
// the same instance will always be referenced. rootName is used
// to know if the chain has been broken.
rootName = this.$name;
// Prevent instance from having parent properties applied more than once.
if (this.$applied) {
throwError(`Cannot invoke super more than once for ${this.$name} instance.`, 'SUPER');
} else {
descriptor.value = true;
Object.defineProperty(this, '$applied', descriptor);
}
// Otherwise just move to next parent.
} else {
// Error out if chain is broken.
if (this.$name !== rootName) {
throwError(`Chain started by ${rootName} instance is being broken by ${this.$name} instance.`, 'SUPER');
}
nodeName = CLASS[nodeName].prototype.$parentName;
}
} | [
"function",
"referenceParentNode",
"(",
")",
"{",
"// If nodeName is an empty string, then reference the parent of the root child.",
"if",
"(",
"isEmptyString",
"(",
"nodeName",
")",
")",
"{",
"nodeName",
"=",
"this",
".",
"$parentName",
";",
"// Even though super might be invoked in different constructors,",
"// the same instance will always be referenced. rootName is used",
"// to know if the chain has been broken.",
"rootName",
"=",
"this",
".",
"$name",
";",
"// Prevent instance from having parent properties applied more than once.",
"if",
"(",
"this",
".",
"$applied",
")",
"{",
"throwError",
"(",
"`",
"${",
"this",
".",
"$name",
"}",
"`",
",",
"'SUPER'",
")",
";",
"}",
"else",
"{",
"descriptor",
".",
"value",
"=",
"true",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'$applied'",
",",
"descriptor",
")",
";",
"}",
"// Otherwise just move to next parent.",
"}",
"else",
"{",
"// Error out if chain is broken.",
"if",
"(",
"this",
".",
"$name",
"!==",
"rootName",
")",
"{",
"throwError",
"(",
"`",
"${",
"rootName",
"}",
"${",
"this",
".",
"$name",
"}",
"`",
",",
"'SUPER'",
")",
";",
"}",
"nodeName",
"=",
"CLASS",
"[",
"nodeName",
"]",
".",
"prototype",
".",
"$parentName",
";",
"}",
"}"
] | Check in which node the super chain is at.
@function referenceParentNode
@api private | [
"Check",
"in",
"which",
"node",
"the",
"super",
"chain",
"is",
"at",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/client-side/class-properties.js#L41-L69 |
48,667 | jeanamarante/catena | tasks/client-side/class-properties.js | applyParentNode | function applyParentNode (args) {
if (isEmptyString(nodeName)) { return undefined; }
let nextParentName = CLASS[nodeName].prototype.$parentName;
// Keep reference of the node's name just in case the chain gets reset.
let tmpName = nodeName;
// If there are no more parent nodes then reset the chain.
if (isEmptyString(nextParentName)) {
resetNames();
}
CLASS[tmpName].apply(this, args);
} | javascript | function applyParentNode (args) {
if (isEmptyString(nodeName)) { return undefined; }
let nextParentName = CLASS[nodeName].prototype.$parentName;
// Keep reference of the node's name just in case the chain gets reset.
let tmpName = nodeName;
// If there are no more parent nodes then reset the chain.
if (isEmptyString(nextParentName)) {
resetNames();
}
CLASS[tmpName].apply(this, args);
} | [
"function",
"applyParentNode",
"(",
"args",
")",
"{",
"if",
"(",
"isEmptyString",
"(",
"nodeName",
")",
")",
"{",
"return",
"undefined",
";",
"}",
"let",
"nextParentName",
"=",
"CLASS",
"[",
"nodeName",
"]",
".",
"prototype",
".",
"$parentName",
";",
"// Keep reference of the node's name just in case the chain gets reset.",
"let",
"tmpName",
"=",
"nodeName",
";",
"// If there are no more parent nodes then reset the chain.",
"if",
"(",
"isEmptyString",
"(",
"nextParentName",
")",
")",
"{",
"resetNames",
"(",
")",
";",
"}",
"CLASS",
"[",
"tmpName",
"]",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}"
] | If the current node has parent, apply current node to
parent's constructor.
@function applyParentNode
@param {Array} args
@api private | [
"If",
"the",
"current",
"node",
"has",
"parent",
"apply",
"current",
"node",
"to",
"parent",
"s",
"constructor",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/client-side/class-properties.js#L80-L94 |
48,668 | abukurov/morph-expressions | src/abstract-syntax-tree.js | get | function get(resource, path) {
const [head, ...tail] = path.split('.');
return resource && head ? get(resource[head], tail.join('.')) : resource;
} | javascript | function get(resource, path) {
const [head, ...tail] = path.split('.');
return resource && head ? get(resource[head], tail.join('.')) : resource;
} | [
"function",
"get",
"(",
"resource",
",",
"path",
")",
"{",
"const",
"[",
"head",
",",
"...",
"tail",
"]",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
";",
"return",
"resource",
"&&",
"head",
"?",
"get",
"(",
"resource",
"[",
"head",
"]",
",",
"tail",
".",
"join",
"(",
"'.'",
")",
")",
":",
"resource",
";",
"}"
] | Get object deep propery
@return {Function} compiled node
@private | [
"Get",
"object",
"deep",
"propery"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L8-L12 |
48,669 | abukurov/morph-expressions | src/abstract-syntax-tree.js | createIdentifierNode | function createIdentifierNode(name) {
return (scope, opts) => {
const property = get(opts.properties, name);
return property ? property(scope) : get(scope, name);
};
} | javascript | function createIdentifierNode(name) {
return (scope, opts) => {
const property = get(opts.properties, name);
return property ? property(scope) : get(scope, name);
};
} | [
"function",
"createIdentifierNode",
"(",
"name",
")",
"{",
"return",
"(",
"scope",
",",
"opts",
")",
"=>",
"{",
"const",
"property",
"=",
"get",
"(",
"opts",
".",
"properties",
",",
"name",
")",
";",
"return",
"property",
"?",
"property",
"(",
"scope",
")",
":",
"get",
"(",
"scope",
",",
"name",
")",
";",
"}",
";",
"}"
] | Create identifier tree node
@return {Function} compiled node
@private | [
"Create",
"identifier",
"tree",
"node"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L28-L34 |
48,670 | abukurov/morph-expressions | src/abstract-syntax-tree.js | createOperatorNode | function createOperatorNode(operand, nodes = []) {
return (scope, opts) => {
const args = nodes.map(node => node(scope, opts));
if (typeof operand === 'function') {
return operand(...args);
}
const operator = get(opts.functions, operand);
if (!operator) {
throw new ReferenceError(`Function '${operand}' isn't declared`);
}
return operator(...args);
};
} | javascript | function createOperatorNode(operand, nodes = []) {
return (scope, opts) => {
const args = nodes.map(node => node(scope, opts));
if (typeof operand === 'function') {
return operand(...args);
}
const operator = get(opts.functions, operand);
if (!operator) {
throw new ReferenceError(`Function '${operand}' isn't declared`);
}
return operator(...args);
};
} | [
"function",
"createOperatorNode",
"(",
"operand",
",",
"nodes",
"=",
"[",
"]",
")",
"{",
"return",
"(",
"scope",
",",
"opts",
")",
"=>",
"{",
"const",
"args",
"=",
"nodes",
".",
"map",
"(",
"node",
"=>",
"node",
"(",
"scope",
",",
"opts",
")",
")",
";",
"if",
"(",
"typeof",
"operand",
"===",
"'function'",
")",
"{",
"return",
"operand",
"(",
"...",
"args",
")",
";",
"}",
"const",
"operator",
"=",
"get",
"(",
"opts",
".",
"functions",
",",
"operand",
")",
";",
"if",
"(",
"!",
"operator",
")",
"{",
"throw",
"new",
"ReferenceError",
"(",
"`",
"${",
"operand",
"}",
"`",
")",
";",
"}",
"return",
"operator",
"(",
"...",
"args",
")",
";",
"}",
";",
"}"
] | Create operator tree node
@return {Function} compiled node
@private | [
"Create",
"operator",
"tree",
"node"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L41-L57 |
48,671 | abukurov/morph-expressions | src/abstract-syntax-tree.js | processLogicalOr | function processLogicalOr(tokenizer, scope) {
let node = processLogicalAnd(tokenizer, scope);
while (tokenizer.token.match(types.LOGICAL_OR)) {
node = createOperatorNode(tokenizer.token.value, [node, processLogicalAnd(tokenizer.skipToken(), scope)]);
}
return node;
} | javascript | function processLogicalOr(tokenizer, scope) {
let node = processLogicalAnd(tokenizer, scope);
while (tokenizer.token.match(types.LOGICAL_OR)) {
node = createOperatorNode(tokenizer.token.value, [node, processLogicalAnd(tokenizer.skipToken(), scope)]);
}
return node;
} | [
"function",
"processLogicalOr",
"(",
"tokenizer",
",",
"scope",
")",
"{",
"let",
"node",
"=",
"processLogicalAnd",
"(",
"tokenizer",
",",
"scope",
")",
";",
"while",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"LOGICAL_OR",
")",
")",
"{",
"node",
"=",
"createOperatorNode",
"(",
"tokenizer",
".",
"token",
".",
"value",
",",
"[",
"node",
",",
"processLogicalAnd",
"(",
"tokenizer",
".",
"skipToken",
"(",
")",
",",
"scope",
")",
"]",
")",
";",
"}",
"return",
"node",
";",
"}"
] | Process logical OR operator
@return {Function} compiled node
@private | [
"Process",
"logical",
"OR",
"operator"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L64-L72 |
48,672 | abukurov/morph-expressions | src/abstract-syntax-tree.js | processLogicalAnd | function processLogicalAnd(tokenizer, scope) {
let node = processLogicalEquality(tokenizer, scope);
while (tokenizer.token.match(types.LOGICAL_AND)) {
node = createOperatorNode(tokenizer.token.value, [node, processLogicalEquality(tokenizer.skipToken(), scope)]);
}
return node;
} | javascript | function processLogicalAnd(tokenizer, scope) {
let node = processLogicalEquality(tokenizer, scope);
while (tokenizer.token.match(types.LOGICAL_AND)) {
node = createOperatorNode(tokenizer.token.value, [node, processLogicalEquality(tokenizer.skipToken(), scope)]);
}
return node;
} | [
"function",
"processLogicalAnd",
"(",
"tokenizer",
",",
"scope",
")",
"{",
"let",
"node",
"=",
"processLogicalEquality",
"(",
"tokenizer",
",",
"scope",
")",
";",
"while",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"LOGICAL_AND",
")",
")",
"{",
"node",
"=",
"createOperatorNode",
"(",
"tokenizer",
".",
"token",
".",
"value",
",",
"[",
"node",
",",
"processLogicalEquality",
"(",
"tokenizer",
".",
"skipToken",
"(",
")",
",",
"scope",
")",
"]",
")",
";",
"}",
"return",
"node",
";",
"}"
] | Process logical AND operator
@return {Function} compiled node
@private | [
"Process",
"logical",
"AND",
"operator"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L79-L87 |
48,673 | abukurov/morph-expressions | src/abstract-syntax-tree.js | processAddSubtract | function processAddSubtract(tokenizer, scope) {
let node = processMultiplyDivide(tokenizer, scope);
while (tokenizer.token.match(types.ADD_SUBTRACT)) {
node = createOperatorNode(tokenizer.token.value, [node, processMultiplyDivide(tokenizer.skipToken(), scope)]);
}
return node;
} | javascript | function processAddSubtract(tokenizer, scope) {
let node = processMultiplyDivide(tokenizer, scope);
while (tokenizer.token.match(types.ADD_SUBTRACT)) {
node = createOperatorNode(tokenizer.token.value, [node, processMultiplyDivide(tokenizer.skipToken(), scope)]);
}
return node;
} | [
"function",
"processAddSubtract",
"(",
"tokenizer",
",",
"scope",
")",
"{",
"let",
"node",
"=",
"processMultiplyDivide",
"(",
"tokenizer",
",",
"scope",
")",
";",
"while",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"ADD_SUBTRACT",
")",
")",
"{",
"node",
"=",
"createOperatorNode",
"(",
"tokenizer",
".",
"token",
".",
"value",
",",
"[",
"node",
",",
"processMultiplyDivide",
"(",
"tokenizer",
".",
"skipToken",
"(",
")",
",",
"scope",
")",
"]",
")",
";",
"}",
"return",
"node",
";",
"}"
] | Process math Add or Subtract operators
@return {Function} compiled node
@private | [
"Process",
"math",
"Add",
"or",
"Subtract",
"operators"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L124-L132 |
48,674 | abukurov/morph-expressions | src/abstract-syntax-tree.js | processMultiplyDivide | function processMultiplyDivide(tokenizer, scope) {
let node = processUnary(tokenizer, scope);
while (tokenizer.token.match(types.MULTIPLY_DIVIDE)) {
node = createOperatorNode(tokenizer.token.value, [node, processUnary(tokenizer.skipToken(), scope)]);
}
return node;
} | javascript | function processMultiplyDivide(tokenizer, scope) {
let node = processUnary(tokenizer, scope);
while (tokenizer.token.match(types.MULTIPLY_DIVIDE)) {
node = createOperatorNode(tokenizer.token.value, [node, processUnary(tokenizer.skipToken(), scope)]);
}
return node;
} | [
"function",
"processMultiplyDivide",
"(",
"tokenizer",
",",
"scope",
")",
"{",
"let",
"node",
"=",
"processUnary",
"(",
"tokenizer",
",",
"scope",
")",
";",
"while",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"MULTIPLY_DIVIDE",
")",
")",
"{",
"node",
"=",
"createOperatorNode",
"(",
"tokenizer",
".",
"token",
".",
"value",
",",
"[",
"node",
",",
"processUnary",
"(",
"tokenizer",
".",
"skipToken",
"(",
")",
",",
"scope",
")",
"]",
")",
";",
"}",
"return",
"node",
";",
"}"
] | Process math Multiply, Divide or Modulus operators
@return {Function} compiled node
@privateR | [
"Process",
"math",
"Multiply",
"Divide",
"or",
"Modulus",
"operators"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L139-L147 |
48,675 | abukurov/morph-expressions | src/abstract-syntax-tree.js | processUnary | function processUnary(tokenizer, scope) {
const unaryAddSubtract = {
'-': value => -value,
'+': value => value
};
if (tokenizer.token.match(types.ADD_SUBTRACT)) {
return createOperatorNode(unaryAddSubtract[tokenizer.token.lexeme], [processUnary(tokenizer.skipToken(), scope)]);
}
if (tokenizer.token.match(types.INCREASE_DECREASE) || tokenizer.token.match(types.LOGICAL_NEGATION)) {
return createOperatorNode(tokenizer.token.value, [processUnary(tokenizer.skipToken(), scope)]);
}
return processIdentifiers(tokenizer, scope);
} | javascript | function processUnary(tokenizer, scope) {
const unaryAddSubtract = {
'-': value => -value,
'+': value => value
};
if (tokenizer.token.match(types.ADD_SUBTRACT)) {
return createOperatorNode(unaryAddSubtract[tokenizer.token.lexeme], [processUnary(tokenizer.skipToken(), scope)]);
}
if (tokenizer.token.match(types.INCREASE_DECREASE) || tokenizer.token.match(types.LOGICAL_NEGATION)) {
return createOperatorNode(tokenizer.token.value, [processUnary(tokenizer.skipToken(), scope)]);
}
return processIdentifiers(tokenizer, scope);
} | [
"function",
"processUnary",
"(",
"tokenizer",
",",
"scope",
")",
"{",
"const",
"unaryAddSubtract",
"=",
"{",
"'-'",
":",
"value",
"=>",
"-",
"value",
",",
"'+'",
":",
"value",
"=>",
"value",
"}",
";",
"if",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"ADD_SUBTRACT",
")",
")",
"{",
"return",
"createOperatorNode",
"(",
"unaryAddSubtract",
"[",
"tokenizer",
".",
"token",
".",
"lexeme",
"]",
",",
"[",
"processUnary",
"(",
"tokenizer",
".",
"skipToken",
"(",
")",
",",
"scope",
")",
"]",
")",
";",
"}",
"if",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"INCREASE_DECREASE",
")",
"||",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"LOGICAL_NEGATION",
")",
")",
"{",
"return",
"createOperatorNode",
"(",
"tokenizer",
".",
"token",
".",
"value",
",",
"[",
"processUnary",
"(",
"tokenizer",
".",
"skipToken",
"(",
")",
",",
"scope",
")",
"]",
")",
";",
"}",
"return",
"processIdentifiers",
"(",
"tokenizer",
",",
"scope",
")",
";",
"}"
] | Process Unary plus and minus, and negation operators
@return {Function} compiled node
@private | [
"Process",
"Unary",
"plus",
"and",
"minus",
"and",
"negation",
"operators"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L154-L169 |
48,676 | abukurov/morph-expressions | src/abstract-syntax-tree.js | processIdentifiers | function processIdentifiers(tokenizer, scope) {
let params = [];
if (tokenizer.token.match(types.IDENTIFIER)) {
const keys = [tokenizer.token.value];
tokenizer.skipToken();
while (tokenizer.token.match(types.DOT, types.OPEN_SQUARE_BRACKET)) {
const token = tokenizer.token;
tokenizer.skipToken();
const isValidKey = token.match(types.OPEN_SQUARE_BRACKET) ?
tokenizer.token.match(types.CONSTANT) :
(
(tokenizer.token.match(types.CONSTANT) && (typeof tokenizer.token.value === 'number')) ||
tokenizer.token.match(types.IDENTIFIER)
);
if (!isValidKey) {
throw new SyntaxError('Unexpected object key notation');
}
keys.push(tokenizer.token.value);
tokenizer.skipToken();
if (token.match(types.OPEN_SQUARE_BRACKET)) {
if (!tokenizer.token.match(types.CLOSE_SQUARE_BRACKET)) {
throw new SyntaxError('Closing square bracket expected');
}
tokenizer.skipToken();
}
}
const identifier = keys.join('.');
if (!tokenizer.token.match(types.OPEN_PARENTHESES)) {
scope.identifiers.push(identifier);
return createIdentifierNode(identifier);
}
params = [];
tokenizer.skipToken();
if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) {
params.push(processLogicalOr(tokenizer, scope));
while (tokenizer.token.match(types.DELIMITER)) {
params.push(processLogicalOr(tokenizer.skipToken(), scope));
}
}
if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) {
throw new SyntaxError('Unexpected end of expression');
}
tokenizer.skipToken();
return createOperatorNode(identifier, params);
}
return processConstants(tokenizer, scope);
} | javascript | function processIdentifiers(tokenizer, scope) {
let params = [];
if (tokenizer.token.match(types.IDENTIFIER)) {
const keys = [tokenizer.token.value];
tokenizer.skipToken();
while (tokenizer.token.match(types.DOT, types.OPEN_SQUARE_BRACKET)) {
const token = tokenizer.token;
tokenizer.skipToken();
const isValidKey = token.match(types.OPEN_SQUARE_BRACKET) ?
tokenizer.token.match(types.CONSTANT) :
(
(tokenizer.token.match(types.CONSTANT) && (typeof tokenizer.token.value === 'number')) ||
tokenizer.token.match(types.IDENTIFIER)
);
if (!isValidKey) {
throw new SyntaxError('Unexpected object key notation');
}
keys.push(tokenizer.token.value);
tokenizer.skipToken();
if (token.match(types.OPEN_SQUARE_BRACKET)) {
if (!tokenizer.token.match(types.CLOSE_SQUARE_BRACKET)) {
throw new SyntaxError('Closing square bracket expected');
}
tokenizer.skipToken();
}
}
const identifier = keys.join('.');
if (!tokenizer.token.match(types.OPEN_PARENTHESES)) {
scope.identifiers.push(identifier);
return createIdentifierNode(identifier);
}
params = [];
tokenizer.skipToken();
if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) {
params.push(processLogicalOr(tokenizer, scope));
while (tokenizer.token.match(types.DELIMITER)) {
params.push(processLogicalOr(tokenizer.skipToken(), scope));
}
}
if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) {
throw new SyntaxError('Unexpected end of expression');
}
tokenizer.skipToken();
return createOperatorNode(identifier, params);
}
return processConstants(tokenizer, scope);
} | [
"function",
"processIdentifiers",
"(",
"tokenizer",
",",
"scope",
")",
"{",
"let",
"params",
"=",
"[",
"]",
";",
"if",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"IDENTIFIER",
")",
")",
"{",
"const",
"keys",
"=",
"[",
"tokenizer",
".",
"token",
".",
"value",
"]",
";",
"tokenizer",
".",
"skipToken",
"(",
")",
";",
"while",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"DOT",
",",
"types",
".",
"OPEN_SQUARE_BRACKET",
")",
")",
"{",
"const",
"token",
"=",
"tokenizer",
".",
"token",
";",
"tokenizer",
".",
"skipToken",
"(",
")",
";",
"const",
"isValidKey",
"=",
"token",
".",
"match",
"(",
"types",
".",
"OPEN_SQUARE_BRACKET",
")",
"?",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"CONSTANT",
")",
":",
"(",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"CONSTANT",
")",
"&&",
"(",
"typeof",
"tokenizer",
".",
"token",
".",
"value",
"===",
"'number'",
")",
")",
"||",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"IDENTIFIER",
")",
")",
";",
"if",
"(",
"!",
"isValidKey",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Unexpected object key notation'",
")",
";",
"}",
"keys",
".",
"push",
"(",
"tokenizer",
".",
"token",
".",
"value",
")",
";",
"tokenizer",
".",
"skipToken",
"(",
")",
";",
"if",
"(",
"token",
".",
"match",
"(",
"types",
".",
"OPEN_SQUARE_BRACKET",
")",
")",
"{",
"if",
"(",
"!",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"CLOSE_SQUARE_BRACKET",
")",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Closing square bracket expected'",
")",
";",
"}",
"tokenizer",
".",
"skipToken",
"(",
")",
";",
"}",
"}",
"const",
"identifier",
"=",
"keys",
".",
"join",
"(",
"'.'",
")",
";",
"if",
"(",
"!",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"OPEN_PARENTHESES",
")",
")",
"{",
"scope",
".",
"identifiers",
".",
"push",
"(",
"identifier",
")",
";",
"return",
"createIdentifierNode",
"(",
"identifier",
")",
";",
"}",
"params",
"=",
"[",
"]",
";",
"tokenizer",
".",
"skipToken",
"(",
")",
";",
"if",
"(",
"!",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"CLOSE_PARENTHESES",
")",
")",
"{",
"params",
".",
"push",
"(",
"processLogicalOr",
"(",
"tokenizer",
",",
"scope",
")",
")",
";",
"while",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"DELIMITER",
")",
")",
"{",
"params",
".",
"push",
"(",
"processLogicalOr",
"(",
"tokenizer",
".",
"skipToken",
"(",
")",
",",
"scope",
")",
")",
";",
"}",
"}",
"if",
"(",
"!",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"CLOSE_PARENTHESES",
")",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Unexpected end of expression'",
")",
";",
"}",
"tokenizer",
".",
"skipToken",
"(",
")",
";",
"return",
"createOperatorNode",
"(",
"identifier",
",",
"params",
")",
";",
"}",
"return",
"processConstants",
"(",
"tokenizer",
",",
"scope",
")",
";",
"}"
] | Process custom identifiers and functions
@return {Function} compiled node
@private | [
"Process",
"custom",
"identifiers",
"and",
"functions"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L176-L239 |
48,677 | abukurov/morph-expressions | src/abstract-syntax-tree.js | processConstants | function processConstants(tokenizer, scope) {
if (tokenizer.token.match(types.CONSTANT)) {
const node = createConstantNode(tokenizer.token.value);
tokenizer.skipToken();
return node;
}
return processParentheses(tokenizer, scope);
} | javascript | function processConstants(tokenizer, scope) {
if (tokenizer.token.match(types.CONSTANT)) {
const node = createConstantNode(tokenizer.token.value);
tokenizer.skipToken();
return node;
}
return processParentheses(tokenizer, scope);
} | [
"function",
"processConstants",
"(",
"tokenizer",
",",
"scope",
")",
"{",
"if",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"CONSTANT",
")",
")",
"{",
"const",
"node",
"=",
"createConstantNode",
"(",
"tokenizer",
".",
"token",
".",
"value",
")",
";",
"tokenizer",
".",
"skipToken",
"(",
")",
";",
"return",
"node",
";",
"}",
"return",
"processParentheses",
"(",
"tokenizer",
",",
"scope",
")",
";",
"}"
] | Process numeric, and string, and predefined constants
@return {Function} compiled node
@private | [
"Process",
"numeric",
"and",
"string",
"and",
"predefined",
"constants"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L246-L256 |
48,678 | abukurov/morph-expressions | src/abstract-syntax-tree.js | processParentheses | function processParentheses(tokenizer, scope) {
if (tokenizer.token.match(types.CLOSE_PARENTHESES)) {
throw new SyntaxError('Unexpected end of expression');
}
if (tokenizer.token.match(types.OPEN_PARENTHESES)) {
const node = processLogicalOr(tokenizer.skipToken(), scope);
if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) {
throw new SyntaxError('Unexpected end of expression');
}
tokenizer.skipToken();
return node;
}
throw new SyntaxError('Unexpected end of expression');
} | javascript | function processParentheses(tokenizer, scope) {
if (tokenizer.token.match(types.CLOSE_PARENTHESES)) {
throw new SyntaxError('Unexpected end of expression');
}
if (tokenizer.token.match(types.OPEN_PARENTHESES)) {
const node = processLogicalOr(tokenizer.skipToken(), scope);
if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) {
throw new SyntaxError('Unexpected end of expression');
}
tokenizer.skipToken();
return node;
}
throw new SyntaxError('Unexpected end of expression');
} | [
"function",
"processParentheses",
"(",
"tokenizer",
",",
"scope",
")",
"{",
"if",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"CLOSE_PARENTHESES",
")",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Unexpected end of expression'",
")",
";",
"}",
"if",
"(",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"OPEN_PARENTHESES",
")",
")",
"{",
"const",
"node",
"=",
"processLogicalOr",
"(",
"tokenizer",
".",
"skipToken",
"(",
")",
",",
"scope",
")",
";",
"if",
"(",
"!",
"tokenizer",
".",
"token",
".",
"match",
"(",
"types",
".",
"CLOSE_PARENTHESES",
")",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Unexpected end of expression'",
")",
";",
"}",
"tokenizer",
".",
"skipToken",
"(",
")",
";",
"return",
"node",
";",
"}",
"throw",
"new",
"SyntaxError",
"(",
"'Unexpected end of expression'",
")",
";",
"}"
] | Process parentheses expressions
@return {Function} compiled node
@private | [
"Process",
"parentheses",
"expressions"
] | e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca | https://github.com/abukurov/morph-expressions/blob/e8b96e50c1ba9d97ca22ee2bb6d9af6de466f9ca/src/abstract-syntax-tree.js#L263-L280 |
48,679 | kadamwhite/mbtapi | api.js | makeMBTAPI | function makeMBTAPI( config ) {
if ( ! config.apiKey || typeof config.apiKey !== 'string' ) {
throw new Error( 'An MBTA API key must be provided' );
}
config.apiRoot = config.apiRoot || 'http://realtime.mbta.com/developer/api/v2/';
return _.mapValues( methods, function( args, key ) {
// makeQueryHandler's third argument is a config object: add it when applying
return makeQueryHandler.apply( null, args.concat( config ) );
});
} | javascript | function makeMBTAPI( config ) {
if ( ! config.apiKey || typeof config.apiKey !== 'string' ) {
throw new Error( 'An MBTA API key must be provided' );
}
config.apiRoot = config.apiRoot || 'http://realtime.mbta.com/developer/api/v2/';
return _.mapValues( methods, function( args, key ) {
// makeQueryHandler's third argument is a config object: add it when applying
return makeQueryHandler.apply( null, args.concat( config ) );
});
} | [
"function",
"makeMBTAPI",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"config",
".",
"apiKey",
"||",
"typeof",
"config",
".",
"apiKey",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'An MBTA API key must be provided'",
")",
";",
"}",
"config",
".",
"apiRoot",
"=",
"config",
".",
"apiRoot",
"||",
"'http://realtime.mbta.com/developer/api/v2/'",
";",
"return",
"_",
".",
"mapValues",
"(",
"methods",
",",
"function",
"(",
"args",
",",
"key",
")",
"{",
"// makeQueryHandler's third argument is a config object: add it when applying",
"return",
"makeQueryHandler",
".",
"apply",
"(",
"null",
",",
"args",
".",
"concat",
"(",
"config",
")",
")",
";",
"}",
")",
";",
"}"
] | Create and return an MBTAPI interface object
@method create
@param {Object} config Configuration object
@param {String} config.apiKey A developer.mbta.com API key
@param {String} [config.apiRoot] An alternative API endpoint to query
@return {MBTAPI} A configured MBTAPI instance | [
"Create",
"and",
"return",
"an",
"MBTAPI",
"interface",
"object"
] | 9abb3966dad5db4117ba84966ecc98321c717428 | https://github.com/kadamwhite/mbtapi/blob/9abb3966dad5db4117ba84966ecc98321c717428/api.js#L21-L31 |
48,680 | jkroso/serialize-svg-path | index.js | serialize | function serialize(path){
return path.reduce(function(str, seg){
return str + seg[0] + seg.slice(1).join(',')
}, '')
} | javascript | function serialize(path){
return path.reduce(function(str, seg){
return str + seg[0] + seg.slice(1).join(',')
}, '')
} | [
"function",
"serialize",
"(",
"path",
")",
"{",
"return",
"path",
".",
"reduce",
"(",
"function",
"(",
"str",
",",
"seg",
")",
"{",
"return",
"str",
"+",
"seg",
"[",
"0",
"]",
"+",
"seg",
".",
"slice",
"(",
"1",
")",
".",
"join",
"(",
"','",
")",
"}",
",",
"''",
")",
"}"
] | convert `path` to a string
@param {Array} path
@return {String} | [
"convert",
"path",
"to",
"a",
"string"
] | be1f9d1b83828be1520cd4e26666f37f2a6e3da5 | https://github.com/jkroso/serialize-svg-path/blob/be1f9d1b83828be1520cd4e26666f37f2a6e3da5/index.js#L11-L15 |
48,681 | Lokiedu/grapheme-utils | index.js | slice | function slice(str, beginSlice, endSlice) {
return GraphemeBreaker.break(str)
.slice(beginSlice, endSlice)
.join('');
} | javascript | function slice(str, beginSlice, endSlice) {
return GraphemeBreaker.break(str)
.slice(beginSlice, endSlice)
.join('');
} | [
"function",
"slice",
"(",
"str",
",",
"beginSlice",
",",
"endSlice",
")",
"{",
"return",
"GraphemeBreaker",
".",
"break",
"(",
"str",
")",
".",
"slice",
"(",
"beginSlice",
",",
"endSlice",
")",
".",
"join",
"(",
"''",
")",
";",
"}"
] | Extracts a section of a string and returns a new string. | [
"Extracts",
"a",
"section",
"of",
"a",
"string",
"and",
"returns",
"a",
"new",
"string",
"."
] | 66ca45a0a094507eb319ba594c9a4030128dc776 | https://github.com/Lokiedu/grapheme-utils/blob/66ca45a0a094507eb319ba594c9a4030128dc776/index.js#L7-L11 |
48,682 | ThatDevCompany/that-build-library | src/utils/private.js | zipFolder | function zipFolder(zip, ffs, root, dir) {
dir = dir || '';
let files = ffs.readdirSync(root + (dir ? '/' + dir : ''));
files.forEach(file => {
if (['.ts', '.js.map'].some(e => file.endsWith(e))) {
return;
}
let stat = ffs.statSync(root + (dir ? '/' + dir : '') + '/' + file);
if (stat.isFile()) {
zipFile(zip, ffs, root, dir, file);
}
else if (stat.isDirectory()) {
zipFolder(zip, ffs, root, dir ? dir + '/' + file : file);
}
});
} | javascript | function zipFolder(zip, ffs, root, dir) {
dir = dir || '';
let files = ffs.readdirSync(root + (dir ? '/' + dir : ''));
files.forEach(file => {
if (['.ts', '.js.map'].some(e => file.endsWith(e))) {
return;
}
let stat = ffs.statSync(root + (dir ? '/' + dir : '') + '/' + file);
if (stat.isFile()) {
zipFile(zip, ffs, root, dir, file);
}
else if (stat.isDirectory()) {
zipFolder(zip, ffs, root, dir ? dir + '/' + file : file);
}
});
} | [
"function",
"zipFolder",
"(",
"zip",
",",
"ffs",
",",
"root",
",",
"dir",
")",
"{",
"dir",
"=",
"dir",
"||",
"''",
";",
"let",
"files",
"=",
"ffs",
".",
"readdirSync",
"(",
"root",
"+",
"(",
"dir",
"?",
"'/'",
"+",
"dir",
":",
"''",
")",
")",
";",
"files",
".",
"forEach",
"(",
"file",
"=>",
"{",
"if",
"(",
"[",
"'.ts'",
",",
"'.js.map'",
"]",
".",
"some",
"(",
"e",
"=>",
"file",
".",
"endsWith",
"(",
"e",
")",
")",
")",
"{",
"return",
";",
"}",
"let",
"stat",
"=",
"ffs",
".",
"statSync",
"(",
"root",
"+",
"(",
"dir",
"?",
"'/'",
"+",
"dir",
":",
"''",
")",
"+",
"'/'",
"+",
"file",
")",
";",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"zipFile",
"(",
"zip",
",",
"ffs",
",",
"root",
",",
"dir",
",",
"file",
")",
";",
"}",
"else",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"zipFolder",
"(",
"zip",
",",
"ffs",
",",
"root",
",",
"dir",
"?",
"dir",
"+",
"'/'",
"+",
"file",
":",
"file",
")",
";",
"}",
"}",
")",
";",
"}"
] | PRIVATE Zip Folder | [
"PRIVATE",
"Zip",
"Folder"
] | 865aaac49531fa9793a055a4df8e9b1b41e71753 | https://github.com/ThatDevCompany/that-build-library/blob/865aaac49531fa9793a055a4df8e9b1b41e71753/src/utils/private.js#L6-L21 |
48,683 | ThatDevCompany/that-build-library | src/utils/private.js | zipFile | function zipFile(zip, ffs, root, dir, file) {
dir = dir || '';
let zipfolder = dir ? zip.folder(dir) : zip;
const data = ffs.readFileSync(root + (dir ? '/' + dir : '') + '/' + file);
zipfolder.file(file, data);
} | javascript | function zipFile(zip, ffs, root, dir, file) {
dir = dir || '';
let zipfolder = dir ? zip.folder(dir) : zip;
const data = ffs.readFileSync(root + (dir ? '/' + dir : '') + '/' + file);
zipfolder.file(file, data);
} | [
"function",
"zipFile",
"(",
"zip",
",",
"ffs",
",",
"root",
",",
"dir",
",",
"file",
")",
"{",
"dir",
"=",
"dir",
"||",
"''",
";",
"let",
"zipfolder",
"=",
"dir",
"?",
"zip",
".",
"folder",
"(",
"dir",
")",
":",
"zip",
";",
"const",
"data",
"=",
"ffs",
".",
"readFileSync",
"(",
"root",
"+",
"(",
"dir",
"?",
"'/'",
"+",
"dir",
":",
"''",
")",
"+",
"'/'",
"+",
"file",
")",
";",
"zipfolder",
".",
"file",
"(",
"file",
",",
"data",
")",
";",
"}"
] | PRIVATE Zip File | [
"PRIVATE",
"Zip",
"File"
] | 865aaac49531fa9793a055a4df8e9b1b41e71753 | https://github.com/ThatDevCompany/that-build-library/blob/865aaac49531fa9793a055a4df8e9b1b41e71753/src/utils/private.js#L26-L31 |
48,684 | ThatDevCompany/that-build-library | src/utils/private.js | checkFolder | function checkFolder(ffs, fld) {
let fldBits = fld.split('/'), mkfld = '';
fldBits.forEach(toBit => {
mkfld = mkfld ? mkfld + '/' + toBit : toBit;
if (mkfld && !ffs.existsSync(mkfld)) {
ffs.mkdirSync(mkfld);
}
});
} | javascript | function checkFolder(ffs, fld) {
let fldBits = fld.split('/'), mkfld = '';
fldBits.forEach(toBit => {
mkfld = mkfld ? mkfld + '/' + toBit : toBit;
if (mkfld && !ffs.existsSync(mkfld)) {
ffs.mkdirSync(mkfld);
}
});
} | [
"function",
"checkFolder",
"(",
"ffs",
",",
"fld",
")",
"{",
"let",
"fldBits",
"=",
"fld",
".",
"split",
"(",
"'/'",
")",
",",
"mkfld",
"=",
"''",
";",
"fldBits",
".",
"forEach",
"(",
"toBit",
"=>",
"{",
"mkfld",
"=",
"mkfld",
"?",
"mkfld",
"+",
"'/'",
"+",
"toBit",
":",
"toBit",
";",
"if",
"(",
"mkfld",
"&&",
"!",
"ffs",
".",
"existsSync",
"(",
"mkfld",
")",
")",
"{",
"ffs",
".",
"mkdirSync",
"(",
"mkfld",
")",
";",
"}",
"}",
")",
";",
"}"
] | PRIVATE Check Folder | [
"PRIVATE",
"Check",
"Folder"
] | 865aaac49531fa9793a055a4df8e9b1b41e71753 | https://github.com/ThatDevCompany/that-build-library/blob/865aaac49531fa9793a055a4df8e9b1b41e71753/src/utils/private.js#L36-L44 |
48,685 | ThatDevCompany/that-build-library | src/utils/private.js | copyFolder | function copyFolder(ffs, from, to) {
checkFolder(ffs, to);
let tasks = [];
ffs.readdirSync(from).forEach(child => {
if (ffs.statSync(from + '/' + child).isDirectory()) {
copyFolder(ffs, from + '/' + child, to + '/' + child);
}
else {
copyFile(ffs, from + '/' + child, to + '/' + child);
}
});
} | javascript | function copyFolder(ffs, from, to) {
checkFolder(ffs, to);
let tasks = [];
ffs.readdirSync(from).forEach(child => {
if (ffs.statSync(from + '/' + child).isDirectory()) {
copyFolder(ffs, from + '/' + child, to + '/' + child);
}
else {
copyFile(ffs, from + '/' + child, to + '/' + child);
}
});
} | [
"function",
"copyFolder",
"(",
"ffs",
",",
"from",
",",
"to",
")",
"{",
"checkFolder",
"(",
"ffs",
",",
"to",
")",
";",
"let",
"tasks",
"=",
"[",
"]",
";",
"ffs",
".",
"readdirSync",
"(",
"from",
")",
".",
"forEach",
"(",
"child",
"=>",
"{",
"if",
"(",
"ffs",
".",
"statSync",
"(",
"from",
"+",
"'/'",
"+",
"child",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"copyFolder",
"(",
"ffs",
",",
"from",
"+",
"'/'",
"+",
"child",
",",
"to",
"+",
"'/'",
"+",
"child",
")",
";",
"}",
"else",
"{",
"copyFile",
"(",
"ffs",
",",
"from",
"+",
"'/'",
"+",
"child",
",",
"to",
"+",
"'/'",
"+",
"child",
")",
";",
"}",
"}",
")",
";",
"}"
] | PRIVATE Copy Folder | [
"PRIVATE",
"Copy",
"Folder"
] | 865aaac49531fa9793a055a4df8e9b1b41e71753 | https://github.com/ThatDevCompany/that-build-library/blob/865aaac49531fa9793a055a4df8e9b1b41e71753/src/utils/private.js#L49-L60 |
48,686 | cliffano/ae86 | lib/engine.js | _process | function _process(templates, params, cb) {
var _templates = _.extend(templates, {}), // process template copies, not the originals
tasks = {};
_.keys(_templates).forEach(function (key) {
tasks[key] = function (cb) {
_templates[key].process(params, function (data) {
cb(null, data);
});
};
});
async.parallel(tasks, function (err, results) {
cb(results);
});
} | javascript | function _process(templates, params, cb) {
var _templates = _.extend(templates, {}), // process template copies, not the originals
tasks = {};
_.keys(_templates).forEach(function (key) {
tasks[key] = function (cb) {
_templates[key].process(params, function (data) {
cb(null, data);
});
};
});
async.parallel(tasks, function (err, results) {
cb(results);
});
} | [
"function",
"_process",
"(",
"templates",
",",
"params",
",",
"cb",
")",
"{",
"var",
"_templates",
"=",
"_",
".",
"extend",
"(",
"templates",
",",
"{",
"}",
")",
",",
"// process template copies, not the originals",
"tasks",
"=",
"{",
"}",
";",
"_",
".",
"keys",
"(",
"_templates",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"tasks",
"[",
"key",
"]",
"=",
"function",
"(",
"cb",
")",
"{",
"_templates",
"[",
"key",
"]",
".",
"process",
"(",
"params",
",",
"function",
"(",
"data",
")",
"{",
"cb",
"(",
"null",
",",
"data",
")",
";",
"}",
")",
";",
"}",
";",
"}",
")",
";",
"async",
".",
"parallel",
"(",
"tasks",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"cb",
"(",
"results",
")",
";",
"}",
")",
";",
"}"
] | merge a set of params to a set of templates | [
"merge",
"a",
"set",
"of",
"params",
"to",
"a",
"set",
"of",
"templates"
] | 7687e438a93638231bf7d2bebe1e8b062082a9a3 | https://github.com/cliffano/ae86/blob/7687e438a93638231bf7d2bebe1e8b062082a9a3/lib/engine.js#L73-L88 |
48,687 | deathcap/cjs2es6export | cjs2es6export.js | function(node) {
if (node.type !== 'AssignmentExpression') return false;
return node.left.type === 'MemberExpression' &&
node.left.object.type === 'Identifier' && node.left.object.name === 'module' &&
node.left.property.type === 'Identifier' && node.left.property.name === 'exports';
// TODO: detect module.exports.foo = (or exports.foo =) property assignments, non-default exports
} | javascript | function(node) {
if (node.type !== 'AssignmentExpression') return false;
return node.left.type === 'MemberExpression' &&
node.left.object.type === 'Identifier' && node.left.object.name === 'module' &&
node.left.property.type === 'Identifier' && node.left.property.name === 'exports';
// TODO: detect module.exports.foo = (or exports.foo =) property assignments, non-default exports
} | [
"function",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"!==",
"'AssignmentExpression'",
")",
"return",
"false",
";",
"return",
"node",
".",
"left",
".",
"type",
"===",
"'MemberExpression'",
"&&",
"node",
".",
"left",
".",
"object",
".",
"type",
"===",
"'Identifier'",
"&&",
"node",
".",
"left",
".",
"object",
".",
"name",
"===",
"'module'",
"&&",
"node",
".",
"left",
".",
"property",
".",
"type",
"===",
"'Identifier'",
"&&",
"node",
".",
"left",
".",
"property",
".",
"name",
"===",
"'exports'",
";",
"// TODO: detect module.exports.foo = (or exports.foo =) property assignments, non-default exports",
"}"
] | module.exports = | [
"module",
".",
"exports",
"="
] | 4a13b039f58ed4fbe2f823bdab5f25675832cb72 | https://github.com/deathcap/cjs2es6export/blob/4a13b039f58ed4fbe2f823bdab5f25675832cb72/cjs2es6export.js#L17-L24 |
|
48,688 | jdborowy/grunt-remove-logging-calls | tasks/lib/removeloggingcalls.js | function(rootNode) {
// queue to compute de breadth first search
var queue = [rootNode];
var nodes = [rootNode];
while (queue.length !== 0) {
// fetch child nodes of the first node of the queue
var currentNode = queue.shift();
for (var property in currentNode) {
// compute only non-inherited properties
if (currentNode.hasOwnProperty(property)) {
if (Array.isArray(currentNode[property])) {
var nodeArray = currentNode[property];
for (var i = 0, ii = nodeArray.length; i < ii; ++i) {
// enqueue only if it is a Node instance
if (nodeArray[i] instanceof rootNode.constructor) {
queue.push(nodeArray[i]);
nodes.push(nodeArray[i]);
}
}
} else
// enqueue only if it is a Node instance
if (currentNode[property] instanceof rootNode.constructor) {
queue.push(currentNode[property]);
nodes.push(currentNode[property]);
}
}
}
}
return nodes;
} | javascript | function(rootNode) {
// queue to compute de breadth first search
var queue = [rootNode];
var nodes = [rootNode];
while (queue.length !== 0) {
// fetch child nodes of the first node of the queue
var currentNode = queue.shift();
for (var property in currentNode) {
// compute only non-inherited properties
if (currentNode.hasOwnProperty(property)) {
if (Array.isArray(currentNode[property])) {
var nodeArray = currentNode[property];
for (var i = 0, ii = nodeArray.length; i < ii; ++i) {
// enqueue only if it is a Node instance
if (nodeArray[i] instanceof rootNode.constructor) {
queue.push(nodeArray[i]);
nodes.push(nodeArray[i]);
}
}
} else
// enqueue only if it is a Node instance
if (currentNode[property] instanceof rootNode.constructor) {
queue.push(currentNode[property]);
nodes.push(currentNode[property]);
}
}
}
}
return nodes;
} | [
"function",
"(",
"rootNode",
")",
"{",
"// queue to compute de breadth first search",
"var",
"queue",
"=",
"[",
"rootNode",
"]",
";",
"var",
"nodes",
"=",
"[",
"rootNode",
"]",
";",
"while",
"(",
"queue",
".",
"length",
"!==",
"0",
")",
"{",
"// fetch child nodes of the first node of the queue",
"var",
"currentNode",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"for",
"(",
"var",
"property",
"in",
"currentNode",
")",
"{",
"// compute only non-inherited properties",
"if",
"(",
"currentNode",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"currentNode",
"[",
"property",
"]",
")",
")",
"{",
"var",
"nodeArray",
"=",
"currentNode",
"[",
"property",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ii",
"=",
"nodeArray",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"// enqueue only if it is a Node instance",
"if",
"(",
"nodeArray",
"[",
"i",
"]",
"instanceof",
"rootNode",
".",
"constructor",
")",
"{",
"queue",
".",
"push",
"(",
"nodeArray",
"[",
"i",
"]",
")",
";",
"nodes",
".",
"push",
"(",
"nodeArray",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}",
"else",
"// enqueue only if it is a Node instance",
"if",
"(",
"currentNode",
"[",
"property",
"]",
"instanceof",
"rootNode",
".",
"constructor",
")",
"{",
"queue",
".",
"push",
"(",
"currentNode",
"[",
"property",
"]",
")",
";",
"nodes",
".",
"push",
"(",
"currentNode",
"[",
"property",
"]",
")",
";",
"}",
"}",
"}",
"}",
"return",
"nodes",
";",
"}"
] | Compute the breadth first search on syntax tree to get the list of nodes
@param {Node} rootNode the root node of the tree
@return {Node[]} the list of all the tree nodes | [
"Compute",
"the",
"breadth",
"first",
"search",
"on",
"syntax",
"tree",
"to",
"get",
"the",
"list",
"of",
"nodes"
] | bf6ae6fbb778cede015dc96dbba0a18a6e0a90e4 | https://github.com/jdborowy/grunt-remove-logging-calls/blob/bf6ae6fbb778cede015dc96dbba0a18a6e0a90e4/tasks/lib/removeloggingcalls.js#L19-L49 |
|
48,689 | jdborowy/grunt-remove-logging-calls | tasks/lib/removeloggingcalls.js | function(nodes, methods) {
var segmentsToBlank = [];
for (var i = 0, ii = nodes.length; i < ii; ++i) {
// checks if the statement is a CallExpression
if (nodes[i].type === 'CallExpression' &&
nodes[i].callee.type === 'MemberExpression') {
var nodeExpression = nodes[i];
// checks if the called function is a property of console or window.console
if (nodeExpression.callee.object.name === 'console' || (
nodeExpression.callee.object.property !== undefined &&
nodeExpression.callee.object.object !== undefined &&
nodeExpression.callee.object.property.name === 'console' &&
nodeExpression.callee.object.object.name === 'window'
)) {
// push the node if the current function is within the methods array
if (methods.indexOf(nodeExpression.callee.property.name) > -1) {
segmentsToBlank.push(nodeExpression.range);
}
}
}
}
// sort the range segments list
segmentsToBlank.sort(function(a, b) {
return a[0] - b[0];
});
// handle the case of nested segments : "console.log(console.log('foo'))"
removeNestedSegments(segmentsToBlank);
return segmentsToBlank;
} | javascript | function(nodes, methods) {
var segmentsToBlank = [];
for (var i = 0, ii = nodes.length; i < ii; ++i) {
// checks if the statement is a CallExpression
if (nodes[i].type === 'CallExpression' &&
nodes[i].callee.type === 'MemberExpression') {
var nodeExpression = nodes[i];
// checks if the called function is a property of console or window.console
if (nodeExpression.callee.object.name === 'console' || (
nodeExpression.callee.object.property !== undefined &&
nodeExpression.callee.object.object !== undefined &&
nodeExpression.callee.object.property.name === 'console' &&
nodeExpression.callee.object.object.name === 'window'
)) {
// push the node if the current function is within the methods array
if (methods.indexOf(nodeExpression.callee.property.name) > -1) {
segmentsToBlank.push(nodeExpression.range);
}
}
}
}
// sort the range segments list
segmentsToBlank.sort(function(a, b) {
return a[0] - b[0];
});
// handle the case of nested segments : "console.log(console.log('foo'))"
removeNestedSegments(segmentsToBlank);
return segmentsToBlank;
} | [
"function",
"(",
"nodes",
",",
"methods",
")",
"{",
"var",
"segmentsToBlank",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ii",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"// checks if the statement is a CallExpression",
"if",
"(",
"nodes",
"[",
"i",
"]",
".",
"type",
"===",
"'CallExpression'",
"&&",
"nodes",
"[",
"i",
"]",
".",
"callee",
".",
"type",
"===",
"'MemberExpression'",
")",
"{",
"var",
"nodeExpression",
"=",
"nodes",
"[",
"i",
"]",
";",
"// checks if the called function is a property of console or window.console",
"if",
"(",
"nodeExpression",
".",
"callee",
".",
"object",
".",
"name",
"===",
"'console'",
"||",
"(",
"nodeExpression",
".",
"callee",
".",
"object",
".",
"property",
"!==",
"undefined",
"&&",
"nodeExpression",
".",
"callee",
".",
"object",
".",
"object",
"!==",
"undefined",
"&&",
"nodeExpression",
".",
"callee",
".",
"object",
".",
"property",
".",
"name",
"===",
"'console'",
"&&",
"nodeExpression",
".",
"callee",
".",
"object",
".",
"object",
".",
"name",
"===",
"'window'",
")",
")",
"{",
"// push the node if the current function is within the methods array",
"if",
"(",
"methods",
".",
"indexOf",
"(",
"nodeExpression",
".",
"callee",
".",
"property",
".",
"name",
")",
">",
"-",
"1",
")",
"{",
"segmentsToBlank",
".",
"push",
"(",
"nodeExpression",
".",
"range",
")",
";",
"}",
"}",
"}",
"}",
"// sort the range segments list",
"segmentsToBlank",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
"[",
"0",
"]",
"-",
"b",
"[",
"0",
"]",
";",
"}",
")",
";",
"// handle the case of nested segments : \"console.log(console.log('foo'))\"",
"removeNestedSegments",
"(",
"segmentsToBlank",
")",
";",
"return",
"segmentsToBlank",
";",
"}"
] | Identify nodes that relate to console statements
@param {Node[]} nodes the list of nodes
@param {Node[]} methods the methods to identify
@param {String[]} methods the properties (functions) to catch for blanking | [
"Identify",
"nodes",
"that",
"relate",
"to",
"console",
"statements"
] | bf6ae6fbb778cede015dc96dbba0a18a6e0a90e4 | https://github.com/jdborowy/grunt-remove-logging-calls/blob/bf6ae6fbb778cede015dc96dbba0a18a6e0a90e4/tasks/lib/removeloggingcalls.js#L57-L86 |
|
48,690 | jdborowy/grunt-remove-logging-calls | tasks/lib/removeloggingcalls.js | function(segments) {
var previousSegment = [-1, -1];
var segmentIndicesToRemove = [];
var cleanedSegmentArray = [];
var i, ii;
for (i = 0, ii = segments.length; i < ii; ++i) {
if (!(previousSegment[0] <= segments[i][0] &&
previousSegment[1] >= segments[i][1])) {
cleanedSegmentArray.push(segments[i]);
}
previousSegment = segments[i];
}
segments.length = 0;
for (i = 0, ii = cleanedSegmentArray.length; i < ii; ++i) {
segments.push(cleanedSegmentArray[i]);
}
} | javascript | function(segments) {
var previousSegment = [-1, -1];
var segmentIndicesToRemove = [];
var cleanedSegmentArray = [];
var i, ii;
for (i = 0, ii = segments.length; i < ii; ++i) {
if (!(previousSegment[0] <= segments[i][0] &&
previousSegment[1] >= segments[i][1])) {
cleanedSegmentArray.push(segments[i]);
}
previousSegment = segments[i];
}
segments.length = 0;
for (i = 0, ii = cleanedSegmentArray.length; i < ii; ++i) {
segments.push(cleanedSegmentArray[i]);
}
} | [
"function",
"(",
"segments",
")",
"{",
"var",
"previousSegment",
"=",
"[",
"-",
"1",
",",
"-",
"1",
"]",
";",
"var",
"segmentIndicesToRemove",
"=",
"[",
"]",
";",
"var",
"cleanedSegmentArray",
"=",
"[",
"]",
";",
"var",
"i",
",",
"ii",
";",
"for",
"(",
"i",
"=",
"0",
",",
"ii",
"=",
"segments",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"if",
"(",
"!",
"(",
"previousSegment",
"[",
"0",
"]",
"<=",
"segments",
"[",
"i",
"]",
"[",
"0",
"]",
"&&",
"previousSegment",
"[",
"1",
"]",
">=",
"segments",
"[",
"i",
"]",
"[",
"1",
"]",
")",
")",
"{",
"cleanedSegmentArray",
".",
"push",
"(",
"segments",
"[",
"i",
"]",
")",
";",
"}",
"previousSegment",
"=",
"segments",
"[",
"i",
"]",
";",
"}",
"segments",
".",
"length",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
",",
"ii",
"=",
"cleanedSegmentArray",
".",
"length",
";",
"i",
"<",
"ii",
";",
"++",
"i",
")",
"{",
"segments",
".",
"push",
"(",
"cleanedSegmentArray",
"[",
"i",
"]",
")",
";",
"}",
"}"
] | Remove segments that are nested in other
@param {Node[]} node the console calls nodes | [
"Remove",
"segments",
"that",
"are",
"nested",
"in",
"other"
] | bf6ae6fbb778cede015dc96dbba0a18a6e0a90e4 | https://github.com/jdborowy/grunt-remove-logging-calls/blob/bf6ae6fbb778cede015dc96dbba0a18a6e0a90e4/tasks/lib/removeloggingcalls.js#L92-L109 |
|
48,691 | bodenr/expose | lib/expose.js | importModule | function importModule(module, scope, fn) {
debug("Importing module: " + module);
var imports = require(module),
name = path.basename(module, path.extname(module));
if (isPlainObject(imports)) {
var keys = Object.keys(imports), key, len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (imports.hasOwnProperty(key)) {
scope[key] = imports[key];
if (fn) {
fn(name, key, imports[key]);
}
}
}
} else {
scope[name] = imports;
if (fn) {
fn(name, null, imports);
}
}
} | javascript | function importModule(module, scope, fn) {
debug("Importing module: " + module);
var imports = require(module),
name = path.basename(module, path.extname(module));
if (isPlainObject(imports)) {
var keys = Object.keys(imports), key, len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (imports.hasOwnProperty(key)) {
scope[key] = imports[key];
if (fn) {
fn(name, key, imports[key]);
}
}
}
} else {
scope[name] = imports;
if (fn) {
fn(name, null, imports);
}
}
} | [
"function",
"importModule",
"(",
"module",
",",
"scope",
",",
"fn",
")",
"{",
"debug",
"(",
"\"Importing module: \"",
"+",
"module",
")",
";",
"var",
"imports",
"=",
"require",
"(",
"module",
")",
",",
"name",
"=",
"path",
".",
"basename",
"(",
"module",
",",
"path",
".",
"extname",
"(",
"module",
")",
")",
";",
"if",
"(",
"isPlainObject",
"(",
"imports",
")",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"imports",
")",
",",
"key",
",",
"len",
"=",
"keys",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"imports",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"scope",
"[",
"key",
"]",
"=",
"imports",
"[",
"key",
"]",
";",
"if",
"(",
"fn",
")",
"{",
"fn",
"(",
"name",
",",
"key",
",",
"imports",
"[",
"key",
"]",
")",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"scope",
"[",
"name",
"]",
"=",
"imports",
";",
"if",
"(",
"fn",
")",
"{",
"fn",
"(",
"name",
",",
"null",
",",
"imports",
")",
";",
"}",
"}",
"}"
] | Import a module into the given scope there by
`require`ing the module and copying its exports
into the given scope object.
@param {String} module The path to the module to require.
@param {Object} scope The namespace to import the modules exports into.
@param {Function} fn The optional callback function to invoke for each imported property.
@api private | [
"Import",
"a",
"module",
"into",
"the",
"given",
"scope",
"there",
"by",
"require",
"ing",
"the",
"module",
"and",
"copying",
"its",
"exports",
"into",
"the",
"given",
"scope",
"object",
"."
] | 7801e2fdbca8fd6445e76365ef7011bcac1b6cfa | https://github.com/bodenr/expose/blob/7801e2fdbca8fd6445e76365ef7011bcac1b6cfa/lib/expose.js#L156-L179 |
48,692 | bodenr/expose | lib/expose.js | load | function load(target, opts) {
target = path.resolve(target);
debug("Load enter: " + target);
if (fs.statSync(target).isDirectory()) {
var files = fs.readdirSync(target), len = files.length, file;
for (var i = 0; i < len; i++) {
file = files[i];
var fullPath = target + sep + file;
if (fs.statSync(fullPath).isDirectory() && opts.recurse) {
load(fullPath, opts);
} else if (test(fullPath, opts.grep, opts.ungrep)) {
importModule(fullPath, opts.scope, opts.fn);
}
}
} else if (test(target, opts.grep, opts.ungrep)) {
importModule(target, opts.scope, opts.fn);
}
} | javascript | function load(target, opts) {
target = path.resolve(target);
debug("Load enter: " + target);
if (fs.statSync(target).isDirectory()) {
var files = fs.readdirSync(target), len = files.length, file;
for (var i = 0; i < len; i++) {
file = files[i];
var fullPath = target + sep + file;
if (fs.statSync(fullPath).isDirectory() && opts.recurse) {
load(fullPath, opts);
} else if (test(fullPath, opts.grep, opts.ungrep)) {
importModule(fullPath, opts.scope, opts.fn);
}
}
} else if (test(target, opts.grep, opts.ungrep)) {
importModule(target, opts.scope, opts.fn);
}
} | [
"function",
"load",
"(",
"target",
",",
"opts",
")",
"{",
"target",
"=",
"path",
".",
"resolve",
"(",
"target",
")",
";",
"debug",
"(",
"\"Load enter: \"",
"+",
"target",
")",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"target",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"var",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"target",
")",
",",
"len",
"=",
"files",
".",
"length",
",",
"file",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"var",
"fullPath",
"=",
"target",
"+",
"sep",
"+",
"file",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"fullPath",
")",
".",
"isDirectory",
"(",
")",
"&&",
"opts",
".",
"recurse",
")",
"{",
"load",
"(",
"fullPath",
",",
"opts",
")",
";",
"}",
"else",
"if",
"(",
"test",
"(",
"fullPath",
",",
"opts",
".",
"grep",
",",
"opts",
".",
"ungrep",
")",
")",
"{",
"importModule",
"(",
"fullPath",
",",
"opts",
".",
"scope",
",",
"opts",
".",
"fn",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"test",
"(",
"target",
",",
"opts",
".",
"grep",
",",
"opts",
".",
"ungrep",
")",
")",
"{",
"importModule",
"(",
"target",
",",
"opts",
".",
"scope",
",",
"opts",
".",
"fn",
")",
";",
"}",
"}"
] | Perform importing on the given target based on the
given options. The target can be a directory to
walk or it can be a file.
The `opts` passed in should be the same format
as those built with `defaultOpts`.
@param {String} target The file or dir to target.
@param {Object} opts The options to use for importing.
@api private | [
"Perform",
"importing",
"on",
"the",
"given",
"target",
"based",
"on",
"the",
"given",
"options",
".",
"The",
"target",
"can",
"be",
"a",
"directory",
"to",
"walk",
"or",
"it",
"can",
"be",
"a",
"file",
"."
] | 7801e2fdbca8fd6445e76365ef7011bcac1b6cfa | https://github.com/bodenr/expose/blob/7801e2fdbca8fd6445e76365ef7011bcac1b6cfa/lib/expose.js#L205-L225 |
48,693 | bodenr/expose | lib/expose.js | asRegExps | function asRegExps(array) {
var array = asArray(array), len = array.length;
for (var i = 0; i < len; i++) {
if (!(array[i] instanceof RegExp)) {
array[i] = new RegExp(array[i]);
}
}
return array;
} | javascript | function asRegExps(array) {
var array = asArray(array), len = array.length;
for (var i = 0; i < len; i++) {
if (!(array[i] instanceof RegExp)) {
array[i] = new RegExp(array[i]);
}
}
return array;
} | [
"function",
"asRegExps",
"(",
"array",
")",
"{",
"var",
"array",
"=",
"asArray",
"(",
"array",
")",
",",
"len",
"=",
"array",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"(",
"array",
"[",
"i",
"]",
"instanceof",
"RegExp",
")",
")",
"{",
"array",
"[",
"i",
"]",
"=",
"new",
"RegExp",
"(",
"array",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"array",
";",
"}"
] | Validates each item in the array is a `RegExp` instance
and if not it creates a new `RegExp` for the item and
stores it in the array index.
@param array
@returns
@api private | [
"Validates",
"each",
"item",
"in",
"the",
"array",
"is",
"a",
"RegExp",
"instance",
"and",
"if",
"not",
"it",
"creates",
"a",
"new",
"RegExp",
"for",
"the",
"item",
"and",
"stores",
"it",
"in",
"the",
"array",
"index",
"."
] | 7801e2fdbca8fd6445e76365ef7011bcac1b6cfa | https://github.com/bodenr/expose/blob/7801e2fdbca8fd6445e76365ef7011bcac1b6cfa/lib/expose.js#L292-L300 |
48,694 | bodenr/expose | lib/expose.js | defaultOpts | function defaultOpts(opts, parentId) {
var targets = opts.targets && opts.targets.length
? asArray(opts.targets)
: [defaultTarget(parentId)];
return mixin({targets: targets,
grep: [/\.js$/],
ungrep: opts.ungrep && opts.ungrep.length
? asArray(opts.ungrep)
: defaultUngrep(targets),
scope: {},
recurse: true},
opts, true);
} | javascript | function defaultOpts(opts, parentId) {
var targets = opts.targets && opts.targets.length
? asArray(opts.targets)
: [defaultTarget(parentId)];
return mixin({targets: targets,
grep: [/\.js$/],
ungrep: opts.ungrep && opts.ungrep.length
? asArray(opts.ungrep)
: defaultUngrep(targets),
scope: {},
recurse: true},
opts, true);
} | [
"function",
"defaultOpts",
"(",
"opts",
",",
"parentId",
")",
"{",
"var",
"targets",
"=",
"opts",
".",
"targets",
"&&",
"opts",
".",
"targets",
".",
"length",
"?",
"asArray",
"(",
"opts",
".",
"targets",
")",
":",
"[",
"defaultTarget",
"(",
"parentId",
")",
"]",
";",
"return",
"mixin",
"(",
"{",
"targets",
":",
"targets",
",",
"grep",
":",
"[",
"/",
"\\.js$",
"/",
"]",
",",
"ungrep",
":",
"opts",
".",
"ungrep",
"&&",
"opts",
".",
"ungrep",
".",
"length",
"?",
"asArray",
"(",
"opts",
".",
"ungrep",
")",
":",
"defaultUngrep",
"(",
"targets",
")",
",",
"scope",
":",
"{",
"}",
",",
"recurse",
":",
"true",
"}",
",",
"opts",
",",
"true",
")",
";",
"}"
] | Returns the default options for this module merged
with the given options passed to this function.
The defaults are as follows:
- grep: any file ending in `.js`
- ungrep: any path including `node_modules`
- scope: an empty object
- recurse: true
- targets: return value from `defaultTargets()`
@param {Object} opts The options to merge the defaults into.
@param {String} parentId The path of the requiring module.
@returns {Object} The merged options.
@api private | [
"Returns",
"the",
"default",
"options",
"for",
"this",
"module",
"merged",
"with",
"the",
"given",
"options",
"passed",
"to",
"this",
"function",
"."
] | 7801e2fdbca8fd6445e76365ef7011bcac1b6cfa | https://github.com/bodenr/expose/blob/7801e2fdbca8fd6445e76365ef7011bcac1b6cfa/lib/expose.js#L319-L332 |
48,695 | bodenr/expose | lib/expose.js | defaultUngrep | function defaultUngrep(targets) {
if (targets && targets.length) {
var ungreps = [], target, len = targets.length;
for (var i = 0; i < len; i++) {
target = targets[i];
target = '(?:^' + path.dirname(target) + sep + '){1}';
target += '(?:/?.*/?)*' + NM_SEG;
ungreps.push(new RegExp(escape(target)));
}
return ungreps;
}
return [new RegExp(escape(NM_SEG))];
} | javascript | function defaultUngrep(targets) {
if (targets && targets.length) {
var ungreps = [], target, len = targets.length;
for (var i = 0; i < len; i++) {
target = targets[i];
target = '(?:^' + path.dirname(target) + sep + '){1}';
target += '(?:/?.*/?)*' + NM_SEG;
ungreps.push(new RegExp(escape(target)));
}
return ungreps;
}
return [new RegExp(escape(NM_SEG))];
} | [
"function",
"defaultUngrep",
"(",
"targets",
")",
"{",
"if",
"(",
"targets",
"&&",
"targets",
".",
"length",
")",
"{",
"var",
"ungreps",
"=",
"[",
"]",
",",
"target",
",",
"len",
"=",
"targets",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"target",
"=",
"targets",
"[",
"i",
"]",
";",
"target",
"=",
"'(?:^'",
"+",
"path",
".",
"dirname",
"(",
"target",
")",
"+",
"sep",
"+",
"'){1}'",
";",
"target",
"+=",
"'(?:/?.*/?)*'",
"+",
"NM_SEG",
";",
"ungreps",
".",
"push",
"(",
"new",
"RegExp",
"(",
"escape",
"(",
"target",
")",
")",
")",
";",
"}",
"return",
"ungreps",
";",
"}",
"return",
"[",
"new",
"RegExp",
"(",
"escape",
"(",
"NM_SEG",
")",
")",
"]",
";",
"}"
] | Build default ungrep pattern based on targets.
@param {Array} targets
@returns {Array} The default ungrep regex in an array.
@api private | [
"Build",
"default",
"ungrep",
"pattern",
"based",
"on",
"targets",
"."
] | 7801e2fdbca8fd6445e76365ef7011bcac1b6cfa | https://github.com/bodenr/expose/blob/7801e2fdbca8fd6445e76365ef7011bcac1b6cfa/lib/expose.js#L365-L378 |
48,696 | amida-tech/blue-button-pim | lib/candidates.js | compare | function compare(data, candidates, shim, at, mt) {
var results = [];
var i;
for (i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
if (shim) {
candidate = shim(candidate);
}
//compare candidate with patient
var s = score(data, candidate);
var m = evaluate(s, at, mt);
// all candidates are returned, with score
// and matching status
var result = {};
result.pat_key = candidate.pat_key;
result.match = m;
result.score = s;
results.push(result);
}
return results;
} | javascript | function compare(data, candidates, shim, at, mt) {
var results = [];
var i;
for (i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
if (shim) {
candidate = shim(candidate);
}
//compare candidate with patient
var s = score(data, candidate);
var m = evaluate(s, at, mt);
// all candidates are returned, with score
// and matching status
var result = {};
result.pat_key = candidate.pat_key;
result.match = m;
result.score = s;
results.push(result);
}
return results;
} | [
"function",
"compare",
"(",
"data",
",",
"candidates",
",",
"shim",
",",
"at",
",",
"mt",
")",
"{",
"var",
"results",
"=",
"[",
"]",
";",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"candidates",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"candidate",
"=",
"candidates",
"[",
"i",
"]",
";",
"if",
"(",
"shim",
")",
"{",
"candidate",
"=",
"shim",
"(",
"candidate",
")",
";",
"}",
"//compare candidate with patient",
"var",
"s",
"=",
"score",
"(",
"data",
",",
"candidate",
")",
";",
"var",
"m",
"=",
"evaluate",
"(",
"s",
",",
"at",
",",
"mt",
")",
";",
"// all candidates are returned, with score",
"// and matching status",
"var",
"result",
"=",
"{",
"}",
";",
"result",
".",
"pat_key",
"=",
"candidate",
".",
"pat_key",
";",
"result",
".",
"match",
"=",
"m",
";",
"result",
".",
"score",
"=",
"s",
";",
"results",
".",
"push",
"(",
"result",
")",
";",
"}",
"return",
"results",
";",
"}"
] | runs through array of candidates and compare them with patient's data returns list of matches and flagged candidates | [
"runs",
"through",
"array",
"of",
"candidates",
"and",
"compare",
"them",
"with",
"patient",
"s",
"data",
"returns",
"list",
"of",
"matches",
"and",
"flagged",
"candidates"
] | 329dcc5fa5f3d877c2b675e8e0d689a8ef25a895 | https://github.com/amida-tech/blue-button-pim/blob/329dcc5fa5f3d877c2b675e8e0d689a8ef25a895/lib/candidates.js#L11-L36 |
48,697 | aaronabramov/esfmt | package/newlines.js | newLineAfterCompositeExpressions | function newLineAfterCompositeExpressions(previous) {
if (previous.type === 'ExpressionStatement') {
var expression = previous.expression;
switch (expression.type) {
case 'AssignmentExpression':
case 'BinaryExpression':
return NEED_EXTRA_NEWLINE_AFTER[expression.right.type];}}} | javascript | function newLineAfterCompositeExpressions(previous) {
if (previous.type === 'ExpressionStatement') {
var expression = previous.expression;
switch (expression.type) {
case 'AssignmentExpression':
case 'BinaryExpression':
return NEED_EXTRA_NEWLINE_AFTER[expression.right.type];}}} | [
"function",
"newLineAfterCompositeExpressions",
"(",
"previous",
")",
"{",
"if",
"(",
"previous",
".",
"type",
"===",
"'ExpressionStatement'",
")",
"{",
"var",
"expression",
"=",
"previous",
".",
"expression",
";",
"switch",
"(",
"expression",
".",
"type",
")",
"{",
"case",
"'AssignmentExpression'",
":",
"case",
"'BinaryExpression'",
":",
"return",
"NEED_EXTRA_NEWLINE_AFTER",
"[",
"expression",
".",
"right",
".",
"type",
"]",
";",
"}",
"}",
"}"
] | Returns true if newline is needed after the composite expression
Examples:
1. Assignment expression
a.b.c = function() {
return 4;
}
2. a + function() {
return 2;
} | [
"Returns",
"true",
"if",
"newline",
"is",
"needed",
"after",
"the",
"composite",
"expression"
] | 8e05fa01d777d504f965ba484c287139a00b5b00 | https://github.com/aaronabramov/esfmt/blob/8e05fa01d777d504f965ba484c287139a00b5b00/package/newlines.js#L98-L105 |
48,698 | tianjianchn/javascript-packages | packages/frm/src/record/construct.js | getPrototype | function getPrototype(model) {
if (model.__recordPrototype) return model.__recordPrototype;
const mrProto = Object.assign({}, proto);// eslint-disable-line no-use-before-define
const extraProperties = {};
Object.keys(model.def.fields).forEach((fieldName) => {
extraProperties[fieldName] = {
enumerable: true,
get() {
const value = getf.call(this, fieldName);
return value;
},
set(value) {
return setf.call(this, fieldName, value);
},
};
});
Object.defineProperties(mrProto, extraProperties);
model.__recordPrototype = mrProto;
return mrProto;
} | javascript | function getPrototype(model) {
if (model.__recordPrototype) return model.__recordPrototype;
const mrProto = Object.assign({}, proto);// eslint-disable-line no-use-before-define
const extraProperties = {};
Object.keys(model.def.fields).forEach((fieldName) => {
extraProperties[fieldName] = {
enumerable: true,
get() {
const value = getf.call(this, fieldName);
return value;
},
set(value) {
return setf.call(this, fieldName, value);
},
};
});
Object.defineProperties(mrProto, extraProperties);
model.__recordPrototype = mrProto;
return mrProto;
} | [
"function",
"getPrototype",
"(",
"model",
")",
"{",
"if",
"(",
"model",
".",
"__recordPrototype",
")",
"return",
"model",
".",
"__recordPrototype",
";",
"const",
"mrProto",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"proto",
")",
";",
"// eslint-disable-line no-use-before-define",
"const",
"extraProperties",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"model",
".",
"def",
".",
"fields",
")",
".",
"forEach",
"(",
"(",
"fieldName",
")",
"=>",
"{",
"extraProperties",
"[",
"fieldName",
"]",
"=",
"{",
"enumerable",
":",
"true",
",",
"get",
"(",
")",
"{",
"const",
"value",
"=",
"getf",
".",
"call",
"(",
"this",
",",
"fieldName",
")",
";",
"return",
"value",
";",
"}",
",",
"set",
"(",
"value",
")",
"{",
"return",
"setf",
".",
"call",
"(",
"this",
",",
"fieldName",
",",
"value",
")",
";",
"}",
",",
"}",
";",
"}",
")",
";",
"Object",
".",
"defineProperties",
"(",
"mrProto",
",",
"extraProperties",
")",
";",
"model",
".",
"__recordPrototype",
"=",
"mrProto",
";",
"return",
"mrProto",
";",
"}"
] | get model specified record prototype | [
"get",
"model",
"specified",
"record",
"prototype"
] | 3abe85edbfe323939c84c1d02128d74d6374bcde | https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/frm/src/record/construct.js#L47-L67 |
48,699 | ciberch/node-express-boilerplate | lib/authentication.js | normalizeUserData | function normalizeUserData() {
function handler(req, res, next) {
if (req.session && !req.session.user && req.session.auth && req.session.auth.loggedIn) {
var user = {};
if (req.session.auth.github) {
user.image = 'http://1.gravatar.com/avatar/'+req.session.auth.github.user.gravatar_id+'?s=48';
user.name = req.session.auth.github.user.name;
user.id = 'github-'+req.session.auth.github.user.id;
}
if (req.session.auth.twitter) {
user.image = req.session.auth.twitter.user.profile_image_url;
user.name = req.session.auth.twitter.user.name;
user.id = 'twitter-'+req.session.auth.twitter.user.id_str;
}
if (req.session.auth.facebook) {
user.image = req.session.auth.facebook.user.picture;
user.name = req.session.auth.facebook.user.name;
user.id = 'facebook-'+req.session.auth.facebook.user.id;
// Need to fetch the users image...
https.get({
'host': 'graph.facebook.com'
, 'path': '/me/picture?access_token='+req.session.auth.facebook.accessToken
}, function(response) {
user.image = response.headers.location;
req.session.user = user;
next();
}).on('error', function(e) {
req.session.user = user;
next();
});
return;
}
req.session.user = user;
}
next();
}
return handler;
} | javascript | function normalizeUserData() {
function handler(req, res, next) {
if (req.session && !req.session.user && req.session.auth && req.session.auth.loggedIn) {
var user = {};
if (req.session.auth.github) {
user.image = 'http://1.gravatar.com/avatar/'+req.session.auth.github.user.gravatar_id+'?s=48';
user.name = req.session.auth.github.user.name;
user.id = 'github-'+req.session.auth.github.user.id;
}
if (req.session.auth.twitter) {
user.image = req.session.auth.twitter.user.profile_image_url;
user.name = req.session.auth.twitter.user.name;
user.id = 'twitter-'+req.session.auth.twitter.user.id_str;
}
if (req.session.auth.facebook) {
user.image = req.session.auth.facebook.user.picture;
user.name = req.session.auth.facebook.user.name;
user.id = 'facebook-'+req.session.auth.facebook.user.id;
// Need to fetch the users image...
https.get({
'host': 'graph.facebook.com'
, 'path': '/me/picture?access_token='+req.session.auth.facebook.accessToken
}, function(response) {
user.image = response.headers.location;
req.session.user = user;
next();
}).on('error', function(e) {
req.session.user = user;
next();
});
return;
}
req.session.user = user;
}
next();
}
return handler;
} | [
"function",
"normalizeUserData",
"(",
")",
"{",
"function",
"handler",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"session",
"&&",
"!",
"req",
".",
"session",
".",
"user",
"&&",
"req",
".",
"session",
".",
"auth",
"&&",
"req",
".",
"session",
".",
"auth",
".",
"loggedIn",
")",
"{",
"var",
"user",
"=",
"{",
"}",
";",
"if",
"(",
"req",
".",
"session",
".",
"auth",
".",
"github",
")",
"{",
"user",
".",
"image",
"=",
"'http://1.gravatar.com/avatar/'",
"+",
"req",
".",
"session",
".",
"auth",
".",
"github",
".",
"user",
".",
"gravatar_id",
"+",
"'?s=48'",
";",
"user",
".",
"name",
"=",
"req",
".",
"session",
".",
"auth",
".",
"github",
".",
"user",
".",
"name",
";",
"user",
".",
"id",
"=",
"'github-'",
"+",
"req",
".",
"session",
".",
"auth",
".",
"github",
".",
"user",
".",
"id",
";",
"}",
"if",
"(",
"req",
".",
"session",
".",
"auth",
".",
"twitter",
")",
"{",
"user",
".",
"image",
"=",
"req",
".",
"session",
".",
"auth",
".",
"twitter",
".",
"user",
".",
"profile_image_url",
";",
"user",
".",
"name",
"=",
"req",
".",
"session",
".",
"auth",
".",
"twitter",
".",
"user",
".",
"name",
";",
"user",
".",
"id",
"=",
"'twitter-'",
"+",
"req",
".",
"session",
".",
"auth",
".",
"twitter",
".",
"user",
".",
"id_str",
";",
"}",
"if",
"(",
"req",
".",
"session",
".",
"auth",
".",
"facebook",
")",
"{",
"user",
".",
"image",
"=",
"req",
".",
"session",
".",
"auth",
".",
"facebook",
".",
"user",
".",
"picture",
";",
"user",
".",
"name",
"=",
"req",
".",
"session",
".",
"auth",
".",
"facebook",
".",
"user",
".",
"name",
";",
"user",
".",
"id",
"=",
"'facebook-'",
"+",
"req",
".",
"session",
".",
"auth",
".",
"facebook",
".",
"user",
".",
"id",
";",
"// Need to fetch the users image...",
"https",
".",
"get",
"(",
"{",
"'host'",
":",
"'graph.facebook.com'",
",",
"'path'",
":",
"'/me/picture?access_token='",
"+",
"req",
".",
"session",
".",
"auth",
".",
"facebook",
".",
"accessToken",
"}",
",",
"function",
"(",
"response",
")",
"{",
"user",
".",
"image",
"=",
"response",
".",
"headers",
".",
"location",
";",
"req",
".",
"session",
".",
"user",
"=",
"user",
";",
"next",
"(",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"e",
")",
"{",
"req",
".",
"session",
".",
"user",
"=",
"user",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"req",
".",
"session",
".",
"user",
"=",
"user",
";",
"}",
"next",
"(",
")",
";",
"}",
"return",
"handler",
";",
"}"
] | Fetch and format data so we have an easy object with user data to work with. | [
"Fetch",
"and",
"format",
"data",
"so",
"we",
"have",
"an",
"easy",
"object",
"with",
"user",
"data",
"to",
"work",
"with",
"."
] | 0f617063e56a5b1041f6eca374f1ff009b9747cf | https://github.com/ciberch/node-express-boilerplate/blob/0f617063e56a5b1041f6eca374f1ff009b9747cf/lib/authentication.js#L45-L83 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.