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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
jeanamarante/catena | tasks/dev/watch.js | renameFile | function renameFile (oldFile, newFile) {
if (!isFileRegistered(oldFile) || isFileRegistered(newFile)) { return undefined; }
let item = fileRegistry[oldFile];
item.file = newFile;
fileRegistry[newFile] = item;
delete fileRegistry[oldFile];
} | javascript | function renameFile (oldFile, newFile) {
if (!isFileRegistered(oldFile) || isFileRegistered(newFile)) { return undefined; }
let item = fileRegistry[oldFile];
item.file = newFile;
fileRegistry[newFile] = item;
delete fileRegistry[oldFile];
} | [
"function",
"renameFile",
"(",
"oldFile",
",",
"newFile",
")",
"{",
"if",
"(",
"!",
"isFileRegistered",
"(",
"oldFile",
")",
"||",
"isFileRegistered",
"(",
"newFile",
")",
")",
"{",
"return",
"undefined",
";",
"}",
"let",
"item",
"=",
"fileRegistry",
"[",
... | Unregister old file and register new one.
@function renameFile
@param {String} oldFile
@param {String} newFile
@api private | [
"Unregister",
"old",
"file",
"and",
"register",
"new",
"one",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/dev/watch.js#L116-L126 | train |
jeanamarante/catena | tasks/dev/watch.js | onEvent | function onEvent (watcher) {
// Wait for write stream to end if write has been delayed.
if (writeDelayed) { return undefined; }
// If any watch events occur while writing to dest then restart
// write stream with new changes.
if (stream.isWriting()) {
writeDelayed = true;
stream.en... | javascript | function onEvent (watcher) {
// Wait for write stream to end if write has been delayed.
if (writeDelayed) { return undefined; }
// If any watch events occur while writing to dest then restart
// write stream with new changes.
if (stream.isWriting()) {
writeDelayed = true;
stream.en... | [
"function",
"onEvent",
"(",
"watcher",
")",
"{",
"// Wait for write stream to end if write has been delayed.",
"if",
"(",
"writeDelayed",
")",
"{",
"return",
"undefined",
";",
"}",
"// If any watch events occur while writing to dest then restart",
"// write stream with new changes.... | Write files whenever a watch event happens.
@function onEvent
@param {Watcher} watcher
@api private | [
"Write",
"files",
"whenever",
"a",
"watch",
"event",
"happens",
"."
] | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/dev/watch.js#L176-L192 | train |
alexindigo/executioner | index.js | executioner | function executioner(commands, params, options, callback)
{
var keys, execOptions, collector = [];
// optional options :)
if (typeof options == 'function')
{
callback = options;
options = {};
}
// clone params, to mess with them without side effects
params = extend(params);
// copy options an... | javascript | function executioner(commands, params, options, callback)
{
var keys, execOptions, collector = [];
// optional options :)
if (typeof options == 'function')
{
callback = options;
options = {};
}
// clone params, to mess with them without side effects
params = extend(params);
// copy options an... | [
"function",
"executioner",
"(",
"commands",
",",
"params",
",",
"options",
",",
"callback",
")",
"{",
"var",
"keys",
",",
"execOptions",
",",
"collector",
"=",
"[",
"]",
";",
"// optional options :)",
"if",
"(",
"typeof",
"options",
"==",
"'function'",
")",
... | Executes provided command with supplied arguments
@param {string|array|object} commands - command to execute, optionally with parameter placeholders
@param {object} params - parameters to pass to the command
@param {object} [options] - command execution options like `cwd`
@param {function} callback - `callback... | [
"Executes",
"provided",
"command",
"with",
"supplied",
"arguments"
] | 582f92897f47c13f4531e0b692aebb4a9f134eec | https://github.com/alexindigo/executioner/blob/582f92897f47c13f4531e0b692aebb4a9f134eec/index.js#L24-L59 | train |
viRingbells/easy-babel | lib/parse.js | parse | function parse (targets) {
debug('Parse: start parsing');
targets = prepare.targets(targets);
prepare_babelrc();
parse_targets(targets);
} | javascript | function parse (targets) {
debug('Parse: start parsing');
targets = prepare.targets(targets);
prepare_babelrc();
parse_targets(targets);
} | [
"function",
"parse",
"(",
"targets",
")",
"{",
"debug",
"(",
"'Parse: start parsing'",
")",
";",
"targets",
"=",
"prepare",
".",
"targets",
"(",
"targets",
")",
";",
"prepare_babelrc",
"(",
")",
";",
"parse_targets",
"(",
"targets",
")",
";",
"}"
] | Parse targets with babel.
@param {string|Array} targets
@return {undefined} no return | [
"Parse",
"targets",
"with",
"babel",
"."
] | 2cb332affc404304cfb01924aaefeac864c002bc | https://github.com/viRingbells/easy-babel/blob/2cb332affc404304cfb01924aaefeac864c002bc/lib/parse.js#L29-L34 | train |
viRingbells/easy-babel | lib/parse.js | parse_targets | function parse_targets (targets) {
debug('Parse: parse targets');
for (let i = 0; i < targets.length; i++) {
const target = targets[i];
const name = path.basename(target);
if (is_special(name)) {
special_targets.push(target);
continue;
}
parse_ta... | javascript | function parse_targets (targets) {
debug('Parse: parse targets');
for (let i = 0; i < targets.length; i++) {
const target = targets[i];
const name = path.basename(target);
if (is_special(name)) {
special_targets.push(target);
continue;
}
parse_ta... | [
"function",
"parse_targets",
"(",
"targets",
")",
"{",
"debug",
"(",
"'Parse: parse targets'",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"targets",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"target",
"=",
"targets",
"[",
"i",... | parse the target | [
"parse",
"the",
"target"
] | 2cb332affc404304cfb01924aaefeac864c002bc | https://github.com/viRingbells/easy-babel/blob/2cb332affc404304cfb01924aaefeac864c002bc/lib/parse.js#L104-L115 | train |
yneves/grunt-html-generator | tasks/html_generator.js | expand | function expand(file, root){
var items = file.orig.src;
var category = file.dest;
_debug("Expanding "+category+": ",items,"\n");
var expanded;
switch(category){
case 'meta': //bypass expanding that would break
expanded = items;
break;
case 'head':
case 'body':
... | javascript | function expand(file, root){
var items = file.orig.src;
var category = file.dest;
_debug("Expanding "+category+": ",items,"\n");
var expanded;
switch(category){
case 'meta': //bypass expanding that would break
expanded = items;
break;
case 'head':
case 'body':
... | [
"function",
"expand",
"(",
"file",
",",
"root",
")",
"{",
"var",
"items",
"=",
"file",
".",
"orig",
".",
"src",
";",
"var",
"category",
"=",
"file",
".",
"dest",
";",
"_debug",
"(",
"\"Expanding \"",
"+",
"category",
"+",
"\": \"",
",",
"items",
",",... | Expand file, by converting in an array of strings
@param file Object as returned by task.files
@param root String root directory where paths refer to
@return Array of strings | [
"Expand",
"file",
"by",
"converting",
"in",
"an",
"array",
"of",
"strings"
] | 325553623706660886bc3e1c85e07a7582950a91 | https://github.com/yneves/grunt-html-generator/blob/325553623706660886bc3e1c85e07a7582950a91/tasks/html_generator.js#L172-L204 | train |
ceddl/ceddl-aditional-inputs | src/performance-timing.js | getPerformanceTimingData | function getPerformanceTimingData() {
var PerformanceObj = {
'redirecting': performance.timing.fetchStart - performance.timing.navigationStart,
'dnsconnect': performance.timing.requestStart - performance.timing.fetchStart,
'request': performance.timing.responseStart - perform... | javascript | function getPerformanceTimingData() {
var PerformanceObj = {
'redirecting': performance.timing.fetchStart - performance.timing.navigationStart,
'dnsconnect': performance.timing.requestStart - performance.timing.fetchStart,
'request': performance.timing.responseStart - perform... | [
"function",
"getPerformanceTimingData",
"(",
")",
"{",
"var",
"PerformanceObj",
"=",
"{",
"'redirecting'",
":",
"performance",
".",
"timing",
".",
"fetchStart",
"-",
"performance",
".",
"timing",
".",
"navigationStart",
",",
"'dnsconnect'",
":",
"performance",
"."... | Calculating steps in the page loading pipeline.
@return {Object} PerformanceObj containg performance metrics | [
"Calculating",
"steps",
"in",
"the",
"page",
"loading",
"pipeline",
"."
] | 0e018d463107a0b631c317d7bf372aa9e194b7da | https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/performance-timing.js#L24-L51 | train |
fatalxiao/js-markdown | src/lib/utils/Str.js | at | function at(index) {
if (!this) {
throw TypeError();
}
const str = '' + this,
len = str.length;
if (index >= len) {
return;
}
if (index < 0) {
index = len - index;
}
let i = 0;
for (let item of str) {
if (i === index) {
return i... | javascript | function at(index) {
if (!this) {
throw TypeError();
}
const str = '' + this,
len = str.length;
if (index >= len) {
return;
}
if (index < 0) {
index = len - index;
}
let i = 0;
for (let item of str) {
if (i === index) {
return i... | [
"function",
"at",
"(",
"index",
")",
"{",
"if",
"(",
"!",
"this",
")",
"{",
"throw",
"TypeError",
"(",
")",
";",
"}",
"const",
"str",
"=",
"''",
"+",
"this",
",",
"len",
"=",
"str",
".",
"length",
";",
"if",
"(",
"index",
">=",
"len",
")",
"{... | String.at polyfill
@param index
@returns {*} | [
"String",
".",
"at",
"polyfill"
] | dffa23be561f50282e5ccc2f1595a51d18a81246 | https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/utils/Str.js#L10-L35 | train |
fatalxiao/js-markdown | src/lib/utils/Str.js | trimHandle | function trimHandle(str, chars = ' ', position) {
if (typeof str !== 'string') {
return;
}
let cs = chars;
if (Valid.isArray(chars)) {
cs = chars.join('');
}
const startReg = new RegExp(`^[${cs}]*`, 'g'),
endReg = new RegExp(`[${cs}]*$`, 'g');
if (position === 's... | javascript | function trimHandle(str, chars = ' ', position) {
if (typeof str !== 'string') {
return;
}
let cs = chars;
if (Valid.isArray(chars)) {
cs = chars.join('');
}
const startReg = new RegExp(`^[${cs}]*`, 'g'),
endReg = new RegExp(`[${cs}]*$`, 'g');
if (position === 's... | [
"function",
"trimHandle",
"(",
"str",
",",
"chars",
"=",
"' '",
",",
"position",
")",
"{",
"if",
"(",
"typeof",
"str",
"!==",
"'string'",
")",
"{",
"return",
";",
"}",
"let",
"cs",
"=",
"chars",
";",
"if",
"(",
"Valid",
".",
"isArray",
"(",
"chars"... | string trim handle method
@param str
@param chars
@param position | [
"string",
"trim",
"handle",
"method"
] | dffa23be561f50282e5ccc2f1595a51d18a81246 | https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/utils/Str.js#L43-L66 | train |
clauswitt/affirm | lib/affirm.js | function(a, length, msg) {
return assert((this.assertIsArray(a, msg) && a.length <= length), msg);
} | javascript | function(a, length, msg) {
return assert((this.assertIsArray(a, msg) && a.length <= length), msg);
} | [
"function",
"(",
"a",
",",
"length",
",",
"msg",
")",
"{",
"return",
"assert",
"(",
"(",
"this",
".",
"assertIsArray",
"(",
"a",
",",
"msg",
")",
"&&",
"a",
".",
"length",
"<=",
"length",
")",
",",
"msg",
")",
";",
"}"
] | Assert that the array length is less than or equal to length | [
"Assert",
"that",
"the",
"array",
"length",
"is",
"less",
"than",
"or",
"equal",
"to",
"length"
] | 5eb49ec115896ce195c888bbcf6cf5a5bb17713b | https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L60-L62 | train | |
clauswitt/affirm | lib/affirm.js | function(a, length, allowNumbers, msg) {
allowNumbers = allowNumbers || true;
return assert((this.assertIsString(a, allowNumbers) && a.length <= length), msg);
} | javascript | function(a, length, allowNumbers, msg) {
allowNumbers = allowNumbers || true;
return assert((this.assertIsString(a, allowNumbers) && a.length <= length), msg);
} | [
"function",
"(",
"a",
",",
"length",
",",
"allowNumbers",
",",
"msg",
")",
"{",
"allowNumbers",
"=",
"allowNumbers",
"||",
"true",
";",
"return",
"assert",
"(",
"(",
"this",
".",
"assertIsString",
"(",
"a",
",",
"allowNumbers",
")",
"&&",
"a",
".",
"le... | Assert that the string length is less than or equal to max | [
"Assert",
"that",
"the",
"string",
"length",
"is",
"less",
"than",
"or",
"equal",
"to",
"max"
] | 5eb49ec115896ce195c888bbcf6cf5a5bb17713b | https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L79-L82 | train | |
clauswitt/affirm | lib/affirm.js | function(a, min, max, allowNumbers, msg) {
return assert((this.assertStringMinLength(a, min, allowNumbers, msg)&&this.assertStringMaxLength(a, max, allowNumbers, msg)), msg);
} | javascript | function(a, min, max, allowNumbers, msg) {
return assert((this.assertStringMinLength(a, min, allowNumbers, msg)&&this.assertStringMaxLength(a, max, allowNumbers, msg)), msg);
} | [
"function",
"(",
"a",
",",
"min",
",",
"max",
",",
"allowNumbers",
",",
"msg",
")",
"{",
"return",
"assert",
"(",
"(",
"this",
".",
"assertStringMinLength",
"(",
"a",
",",
"min",
",",
"allowNumbers",
",",
"msg",
")",
"&&",
"this",
".",
"assertStringMax... | Assert that the string length is within the range | [
"Assert",
"that",
"the",
"string",
"length",
"is",
"within",
"the",
"range"
] | 5eb49ec115896ce195c888bbcf6cf5a5bb17713b | https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L91-L93 | train | |
clauswitt/affirm | lib/affirm.js | function(a, start, msg) {
return assert((this.assertIsString(a, msg) && a.indexOf(start)===0), msg);
} | javascript | function(a, start, msg) {
return assert((this.assertIsString(a, msg) && a.indexOf(start)===0), msg);
} | [
"function",
"(",
"a",
",",
"start",
",",
"msg",
")",
"{",
"return",
"assert",
"(",
"(",
"this",
".",
"assertIsString",
"(",
"a",
",",
"msg",
")",
"&&",
"a",
".",
"indexOf",
"(",
"start",
")",
"===",
"0",
")",
",",
"msg",
")",
";",
"}"
] | Assert that the string string starts with the substring | [
"Assert",
"that",
"the",
"string",
"string",
"starts",
"with",
"the",
"substring"
] | 5eb49ec115896ce195c888bbcf6cf5a5bb17713b | https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L96-L98 | train | |
clauswitt/affirm | lib/affirm.js | function(a, end, msg) {
return assert((this.assertIsString(a, msg) && a.indexOf(end, a.length - end.length) !== -1), msg);
} | javascript | function(a, end, msg) {
return assert((this.assertIsString(a, msg) && a.indexOf(end, a.length - end.length) !== -1), msg);
} | [
"function",
"(",
"a",
",",
"end",
",",
"msg",
")",
"{",
"return",
"assert",
"(",
"(",
"this",
".",
"assertIsString",
"(",
"a",
",",
"msg",
")",
"&&",
"a",
".",
"indexOf",
"(",
"end",
",",
"a",
".",
"length",
"-",
"end",
".",
"length",
")",
"!==... | Assert that the string string ends with the substring | [
"Assert",
"that",
"the",
"string",
"string",
"ends",
"with",
"the",
"substring"
] | 5eb49ec115896ce195c888bbcf6cf5a5bb17713b | https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L101-L103 | train | |
clauswitt/affirm | lib/affirm.js | function(value, assertionObject) {
for(var name in assertionObject) {
if (assertionObject.hasOwnProperty(name)) {
args = [value];
args = args.concat(assertionObject[name]);
this[name].apply(this, args);
}
}
} | javascript | function(value, assertionObject) {
for(var name in assertionObject) {
if (assertionObject.hasOwnProperty(name)) {
args = [value];
args = args.concat(assertionObject[name]);
this[name].apply(this, args);
}
}
} | [
"function",
"(",
"value",
",",
"assertionObject",
")",
"{",
"for",
"(",
"var",
"name",
"in",
"assertionObject",
")",
"{",
"if",
"(",
"assertionObject",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"args",
"=",
"[",
"value",
"]",
";",
"args",
"=",... | Run a series of assertions | [
"Run",
"a",
"series",
"of",
"assertions"
] | 5eb49ec115896ce195c888bbcf6cf5a5bb17713b | https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L116-L124 | train | |
deliciousinsights/fb-flo-brunch | index.js | FbFloBrunch | function FbFloBrunch(config) {
this.setOptions(config);
// This plugin only makes sense if we're in watcher mode
// (`config.persistent`). Also, we honor the plugin-specific `enabled`
// setting, so users don't need to strip the plugin or its config to
// disable it: just set `enabled` to `false`.
if (!co... | javascript | function FbFloBrunch(config) {
this.setOptions(config);
// This plugin only makes sense if we're in watcher mode
// (`config.persistent`). Also, we honor the plugin-specific `enabled`
// setting, so users don't need to strip the plugin or its config to
// disable it: just set `enabled` to `false`.
if (!co... | [
"function",
"FbFloBrunch",
"(",
"config",
")",
"{",
"this",
".",
"setOptions",
"(",
"config",
")",
";",
"// This plugin only makes sense if we're in watcher mode",
"// (`config.persistent`). Also, we honor the plugin-specific `enabled`",
"// setting, so users don't need to strip the p... | Plugin constructor. Takes Brunch's complete config as argument. | [
"Plugin",
"constructor",
".",
"Takes",
"Brunch",
"s",
"complete",
"config",
"as",
"argument",
"."
] | 88249d1b1c40fd2df69714ab01a77ab26a010581 | https://github.com/deliciousinsights/fb-flo-brunch/blob/88249d1b1c40fd2df69714ab01a77ab26a010581/index.js#L19-L32 | train |
deliciousinsights/fb-flo-brunch | index.js | resolver | function resolver(filePath, callback) {
var fullPath = path.join(this.config.publicPath, filePath);
var options = {
resourceURL: filePath,
contents: fs.readFileSync(fullPath).toString()
};
// If we defined a custom browser-side message system, use it.
if (this.update) {
options.up... | javascript | function resolver(filePath, callback) {
var fullPath = path.join(this.config.publicPath, filePath);
var options = {
resourceURL: filePath,
contents: fs.readFileSync(fullPath).toString()
};
// If we defined a custom browser-side message system, use it.
if (this.update) {
options.up... | [
"function",
"resolver",
"(",
"filePath",
",",
"callback",
")",
"{",
"var",
"fullPath",
"=",
"path",
".",
"join",
"(",
"this",
".",
"config",
".",
"publicPath",
",",
"filePath",
")",
";",
"var",
"options",
"=",
"{",
"resourceURL",
":",
"filePath",
",",
... | The fb-flo resolver, triggered everytime fb-flo wants to send a change notification to connected browser extensions. | [
"The",
"fb",
"-",
"flo",
"resolver",
"triggered",
"everytime",
"fb",
"-",
"flo",
"wants",
"to",
"send",
"a",
"change",
"notification",
"to",
"connected",
"browser",
"extensions",
"."
] | 88249d1b1c40fd2df69714ab01a77ab26a010581 | https://github.com/deliciousinsights/fb-flo-brunch/blob/88249d1b1c40fd2df69714ab01a77ab26a010581/index.js#L62-L85 | train |
deliciousinsights/fb-flo-brunch | index.js | startServer | function startServer() {
this._flo = flo(
// The path to watch (see `setOptions(…)`).
this.config.publicPath,
// The config-provided fb-flo options + a generic watch glob
// (all JS/CSS, at any depth) inside the watched path.
extend(
pick(this.config, FB_FLO_OPTIONS),
{... | javascript | function startServer() {
this._flo = flo(
// The path to watch (see `setOptions(…)`).
this.config.publicPath,
// The config-provided fb-flo options + a generic watch glob
// (all JS/CSS, at any depth) inside the watched path.
extend(
pick(this.config, FB_FLO_OPTIONS),
{... | [
"function",
"startServer",
"(",
")",
"{",
"this",
".",
"_flo",
"=",
"flo",
"(",
"// The path to watch (see `setOptions(…)`).",
"this",
".",
"config",
".",
"publicPath",
",",
"// The config-provided fb-flo options + a generic watch glob",
"// (all JS/CSS, at any depth) inside th... | Starts the fb-flo server. Launched from the constructor unless the plugin is disabled. | [
"Starts",
"the",
"fb",
"-",
"flo",
"server",
".",
"Launched",
"from",
"the",
"constructor",
"unless",
"the",
"plugin",
"is",
"disabled",
"."
] | 88249d1b1c40fd2df69714ab01a77ab26a010581 | https://github.com/deliciousinsights/fb-flo-brunch/blob/88249d1b1c40fd2df69714ab01a77ab26a010581/index.js#L137-L150 | train |
yashprit/is-float | index.js | isFloat | function isFloat (n, shouldCoerce) {
if (shouldCoerce) {
if (typeof n === "string") {
n = parseFloat(n);
}
}
return n === +n && n !== (n|0);
} | javascript | function isFloat (n, shouldCoerce) {
if (shouldCoerce) {
if (typeof n === "string") {
n = parseFloat(n);
}
}
return n === +n && n !== (n|0);
} | [
"function",
"isFloat",
"(",
"n",
",",
"shouldCoerce",
")",
"{",
"if",
"(",
"shouldCoerce",
")",
"{",
"if",
"(",
"typeof",
"n",
"===",
"\"string\"",
")",
"{",
"n",
"=",
"parseFloat",
"(",
"n",
")",
";",
"}",
"}",
"return",
"n",
"===",
"+",
"n",
"&... | Check argument is float or not
@param {number} n
@param {Boolean} shouldCoerce
@return {Boolean} true if it's a float | [
"Check",
"argument",
"is",
"float",
"or",
"not"
] | 8e22fbeaa4913dae87918064b6f03eafdd36eff8 | https://github.com/yashprit/is-float/blob/8e22fbeaa4913dae87918064b6f03eafdd36eff8/index.js#L9-L17 | train |
jeanamarante/catena | tasks/deploy/minify.js | writeExterns | function writeExterns (grunt, fileData, options) {
let content = '';
// Default externs.
content += 'var require = function () {};';
for (let i = 0, max = options.externs.length; i < max; i++) {
content += `var ${options.externs[i]} = {};`;
}
grunt.file.write(fileData.tmpExterns, cont... | javascript | function writeExterns (grunt, fileData, options) {
let content = '';
// Default externs.
content += 'var require = function () {};';
for (let i = 0, max = options.externs.length; i < max; i++) {
content += `var ${options.externs[i]} = {};`;
}
grunt.file.write(fileData.tmpExterns, cont... | [
"function",
"writeExterns",
"(",
"grunt",
",",
"fileData",
",",
"options",
")",
"{",
"let",
"content",
"=",
"''",
";",
"// Default externs.",
"content",
"+=",
"'var require = function () {};'",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"max",
"=",
"options... | Concatenate each extern as a variable declaration that points to an empty object.
Externs are used to prevent the closure compiler from complaining about undeclared
variables and renaming those variables.
@function writeExterns
@param {Object} grunt
@param {Object} fileData
@param {Object} options
@api private | [
"Concatenate",
"each",
"extern",
"as",
"a",
"variable",
"declaration",
"that",
"points",
"to",
"an",
"empty",
"object",
".",
"Externs",
"are",
"used",
"to",
"prevent",
"the",
"closure",
"compiler",
"from",
"complaining",
"about",
"undeclared",
"variables",
"and"... | c7762332f71c0fd7cfafba8d1e3cd66053529954 | https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/deploy/minify.js#L21-L32 | train |
Chris911/mocha-http-detect | src/index.js | printHostnames | function printHostnames() {
console.log(chalk.yellow.bold(`${indent(2)} Hostnames requested: `));
if (Object.keys(hostnames).length === 0) {
console.log(chalk.yellow(`${indent(4)}none`));
return;
}
for (const key in hostnames) {
if (!hostnames[key]) return;
console.log(chalk.yellow(`${indent(4... | javascript | function printHostnames() {
console.log(chalk.yellow.bold(`${indent(2)} Hostnames requested: `));
if (Object.keys(hostnames).length === 0) {
console.log(chalk.yellow(`${indent(4)}none`));
return;
}
for (const key in hostnames) {
if (!hostnames[key]) return;
console.log(chalk.yellow(`${indent(4... | [
"function",
"printHostnames",
"(",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
".",
"bold",
"(",
"`",
"${",
"indent",
"(",
"2",
")",
"}",
"`",
")",
")",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"hostnames",
")",
".",
"length"... | Print requested hostnames summary. | [
"Print",
"requested",
"hostnames",
"summary",
"."
] | 61e90d5d9478255844452bef0fe1a957cd2abdab | https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L39-L51 | train |
Chris911/mocha-http-detect | src/index.js | patchMocha | function patchMocha() {
const _testRun = Mocha.Test.prototype.run;
Mocha.Test.prototype.run = function (fn) {
function done(ctx) {
fn.call(this, ctx);
if (testRequests.length) {
printTestRequest(testRequests);
testRequests = [];
}
}
return _testRun.call(this, done);
... | javascript | function patchMocha() {
const _testRun = Mocha.Test.prototype.run;
Mocha.Test.prototype.run = function (fn) {
function done(ctx) {
fn.call(this, ctx);
if (testRequests.length) {
printTestRequest(testRequests);
testRequests = [];
}
}
return _testRun.call(this, done);
... | [
"function",
"patchMocha",
"(",
")",
"{",
"const",
"_testRun",
"=",
"Mocha",
".",
"Test",
".",
"prototype",
".",
"run",
";",
"Mocha",
".",
"Test",
".",
"prototype",
".",
"run",
"=",
"function",
"(",
"fn",
")",
"{",
"function",
"done",
"(",
"ctx",
")",... | Patch mocha to display recording requests during individual tests and at
the end of the test suite. | [
"Patch",
"mocha",
"to",
"display",
"recording",
"requests",
"during",
"individual",
"tests",
"and",
"at",
"the",
"end",
"of",
"the",
"test",
"suite",
"."
] | 61e90d5d9478255844452bef0fe1a957cd2abdab | https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L57-L83 | train |
Chris911/mocha-http-detect | src/index.js | getHostname | function getHostname(httpOptions) {
if (httpOptions.uri && httpOptions.uri.hostname) {
return httpOptions.uri.hostname;
} else if (httpOptions.hostname) {
return httpOptions.hostname;
} else if (httpOptions.host) {
return httpOptions.host;
}
return 'Unknown';
} | javascript | function getHostname(httpOptions) {
if (httpOptions.uri && httpOptions.uri.hostname) {
return httpOptions.uri.hostname;
} else if (httpOptions.hostname) {
return httpOptions.hostname;
} else if (httpOptions.host) {
return httpOptions.host;
}
return 'Unknown';
} | [
"function",
"getHostname",
"(",
"httpOptions",
")",
"{",
"if",
"(",
"httpOptions",
".",
"uri",
"&&",
"httpOptions",
".",
"uri",
".",
"hostname",
")",
"{",
"return",
"httpOptions",
".",
"uri",
".",
"hostname",
";",
"}",
"else",
"if",
"(",
"httpOptions",
"... | Get the hostname from an HTTP options object.
Supports multiple types of options.
@param {object} httpOptions
@return {string} the hostname or "Unknown" if not found. | [
"Get",
"the",
"hostname",
"from",
"an",
"HTTP",
"options",
"object",
".",
"Supports",
"multiple",
"types",
"of",
"options",
"."
] | 61e90d5d9478255844452bef0fe1a957cd2abdab | https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L91-L100 | train |
Chris911/mocha-http-detect | src/index.js | getHref | function getHref(httpOptions) {
if (httpOptions.uri && httpOptions.uri.href) {
return httpOptions.uri.href;
} else if (httpOptions.hostname && httpOptions.path) {
return httpOptions.hostname + httpOptions.path;
} else if (httpOptions.host && httpOptions.path) {
return httpOptions.host + httpOptions.pa... | javascript | function getHref(httpOptions) {
if (httpOptions.uri && httpOptions.uri.href) {
return httpOptions.uri.href;
} else if (httpOptions.hostname && httpOptions.path) {
return httpOptions.hostname + httpOptions.path;
} else if (httpOptions.host && httpOptions.path) {
return httpOptions.host + httpOptions.pa... | [
"function",
"getHref",
"(",
"httpOptions",
")",
"{",
"if",
"(",
"httpOptions",
".",
"uri",
"&&",
"httpOptions",
".",
"uri",
".",
"href",
")",
"{",
"return",
"httpOptions",
".",
"uri",
".",
"href",
";",
"}",
"else",
"if",
"(",
"httpOptions",
".",
"hostn... | Get the href from an HTTP options objet.
Supports multiple types of options.
@param {object} httpOptions
@return {string} the hostname or "Unknown" if not found. | [
"Get",
"the",
"href",
"from",
"an",
"HTTP",
"options",
"objet",
".",
"Supports",
"multiple",
"types",
"of",
"options",
"."
] | 61e90d5d9478255844452bef0fe1a957cd2abdab | https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L108-L117 | train |
Chris911/mocha-http-detect | src/index.js | patchHttpClient | function patchHttpClient() {
const _ClientRequest = http.ClientRequest;
function patchedHttpClient(options, done) {
if (http.OutgoingMessage) http.OutgoingMessage.call(this);
const hostname = getHostname(options);
// Ignore localhost requests
if (hostname.indexOf('127.0.0.1') === -1 && hostname.i... | javascript | function patchHttpClient() {
const _ClientRequest = http.ClientRequest;
function patchedHttpClient(options, done) {
if (http.OutgoingMessage) http.OutgoingMessage.call(this);
const hostname = getHostname(options);
// Ignore localhost requests
if (hostname.indexOf('127.0.0.1') === -1 && hostname.i... | [
"function",
"patchHttpClient",
"(",
")",
"{",
"const",
"_ClientRequest",
"=",
"http",
".",
"ClientRequest",
";",
"function",
"patchedHttpClient",
"(",
"options",
",",
"done",
")",
"{",
"if",
"(",
"http",
".",
"OutgoingMessage",
")",
"http",
".",
"OutgoingMessa... | Patch Node's HTTP client to record external HTTP calls.
- All hostnames are stored in `hostname` with their count for the whole
test suite.
- Full request URLs are stores in `testRequests` and used to display
recorded requests for individual tests.
- Requests to localhost are ignored. | [
"Patch",
"Node",
"s",
"HTTP",
"client",
"to",
"record",
"external",
"HTTP",
"calls",
".",
"-",
"All",
"hostnames",
"are",
"stored",
"in",
"hostname",
"with",
"their",
"count",
"for",
"the",
"whole",
"test",
"suite",
".",
"-",
"Full",
"request",
"URLs",
"... | 61e90d5d9478255844452bef0fe1a957cd2abdab | https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L127-L160 | train |
anseki/pre-proc | lib/pre-proc.js | isTargetPath | function isTargetPath(srcPath, pathTest) {
return !srcPath ||
(Array.isArray(pathTest) ? pathTest : [pathTest]).some(function(test) {
return test && (test instanceof RegExp ? test.test(srcPath) : srcPath.indexOf(test) === 0);
});
} | javascript | function isTargetPath(srcPath, pathTest) {
return !srcPath ||
(Array.isArray(pathTest) ? pathTest : [pathTest]).some(function(test) {
return test && (test instanceof RegExp ? test.test(srcPath) : srcPath.indexOf(test) === 0);
});
} | [
"function",
"isTargetPath",
"(",
"srcPath",
",",
"pathTest",
")",
"{",
"return",
"!",
"srcPath",
"||",
"(",
"Array",
".",
"isArray",
"(",
"pathTest",
")",
"?",
"pathTest",
":",
"[",
"pathTest",
"]",
")",
".",
"some",
"(",
"function",
"(",
"test",
")",
... | Test whether a path is target.
@param {string} [srcPath] - A full path.
@param {(string|RegExp|Array)} [pathTest] - A string which must be at the start, a RegExp which tests or an array.
@returns {boolean} `true` if the `srcPath` is target, or `srcPath` is omitted. | [
"Test",
"whether",
"a",
"path",
"is",
"target",
"."
] | 7b6814bd50df64cce98048736cba2eade755fad5 | https://github.com/anseki/pre-proc/blob/7b6814bd50df64cce98048736cba2eade755fad5/lib/pre-proc.js#L17-L22 | train |
bernardodiasc/filestojson | examples/config.js | posts | function posts (content, contentType) {
let output = {}
const allFiles = content.filter(each => each.dir.includes(`/${contentType}`))
const index = allFiles.filter(each => each.base === 'index.md')[0]
index.attr.forEach(each => {
allFiles.forEach(file => {
if (file.name === each) {
output[each... | javascript | function posts (content, contentType) {
let output = {}
const allFiles = content.filter(each => each.dir.includes(`/${contentType}`))
const index = allFiles.filter(each => each.base === 'index.md')[0]
index.attr.forEach(each => {
allFiles.forEach(file => {
if (file.name === each) {
output[each... | [
"function",
"posts",
"(",
"content",
",",
"contentType",
")",
"{",
"let",
"output",
"=",
"{",
"}",
"const",
"allFiles",
"=",
"content",
".",
"filter",
"(",
"each",
"=>",
"each",
".",
"dir",
".",
"includes",
"(",
"`",
"${",
"contentType",
"}",
"`",
")... | Posts content type translation
@param {Array} content List of files
@param {String} contentType Content type name
@return {Object} The posts content type data object | [
"Posts",
"content",
"type",
"translation"
] | 4ccd4454d1fe0408001b1f9f57ed89d19e38256e | https://github.com/bernardodiasc/filestojson/blob/4ccd4454d1fe0408001b1f9f57ed89d19e38256e/examples/config.js#L9-L21 | train |
bernardodiasc/filestojson | examples/config.js | gallery | function gallery (content, contentType) {
let output = {}
const allFiles = content.filter(each => each.dir.includes(`/${contentType}`))
const index = allFiles.filter(each => each.base === 'index.md')[0]
index.attr.forEach(each => {
Object.keys(each).forEach(key => {
output[key] = Object.assign({ title... | javascript | function gallery (content, contentType) {
let output = {}
const allFiles = content.filter(each => each.dir.includes(`/${contentType}`))
const index = allFiles.filter(each => each.base === 'index.md')[0]
index.attr.forEach(each => {
Object.keys(each).forEach(key => {
output[key] = Object.assign({ title... | [
"function",
"gallery",
"(",
"content",
",",
"contentType",
")",
"{",
"let",
"output",
"=",
"{",
"}",
"const",
"allFiles",
"=",
"content",
".",
"filter",
"(",
"each",
"=>",
"each",
".",
"dir",
".",
"includes",
"(",
"`",
"${",
"contentType",
"}",
"`",
... | Gallery content type translation
@param {Array} content List of files
@param {String} contentType Content type name
@return {Object} The gallery content type data object | [
"Gallery",
"content",
"type",
"translation"
] | 4ccd4454d1fe0408001b1f9f57ed89d19e38256e | https://github.com/bernardodiasc/filestojson/blob/4ccd4454d1fe0408001b1f9f57ed89d19e38256e/examples/config.js#L29-L39 | train |
tianjianchn/javascript-packages | packages/frm/src/builder.js | activateField | function activateField(model, fields) {
let activeFields = [];
if (fields === true) { // activate all
return Object.keys(model.def.fields);
} else if (Array.isArray(fields)) {
activeFields = fields;
} else if (typeof fields === 'string') {
if (fields.indexOf('*') >= 0) { // activate all
active... | javascript | function activateField(model, fields) {
let activeFields = [];
if (fields === true) { // activate all
return Object.keys(model.def.fields);
} else if (Array.isArray(fields)) {
activeFields = fields;
} else if (typeof fields === 'string') {
if (fields.indexOf('*') >= 0) { // activate all
active... | [
"function",
"activateField",
"(",
"model",
",",
"fields",
")",
"{",
"let",
"activeFields",
"=",
"[",
"]",
";",
"if",
"(",
"fields",
"===",
"true",
")",
"{",
"// activate all",
"return",
"Object",
".",
"keys",
"(",
"model",
".",
"def",
".",
"fields",
")... | parse the active fields, which will be used as select field list in sql statement | [
"parse",
"the",
"active",
"fields",
"which",
"will",
"be",
"used",
"as",
"select",
"field",
"list",
"in",
"sql",
"statement"
] | 3abe85edbfe323939c84c1d02128d74d6374bcde | https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/frm/src/builder.js#L217-L234 | train |
tianjianchn/javascript-packages | packages/frm/src/builder.js | cfv | function cfv(model, set) {
const cvs = {};// column values
for (const fieldName in set) {
const field = model.def.fields[fieldName];
if (!field || field.props.category !== 'entity') continue;
const value = set[fieldName];
cvs[field.props.column] = value;
}
return cvs;
} | javascript | function cfv(model, set) {
const cvs = {};// column values
for (const fieldName in set) {
const field = model.def.fields[fieldName];
if (!field || field.props.category !== 'entity') continue;
const value = set[fieldName];
cvs[field.props.column] = value;
}
return cvs;
} | [
"function",
"cfv",
"(",
"model",
",",
"set",
")",
"{",
"const",
"cvs",
"=",
"{",
"}",
";",
"// column values",
"for",
"(",
"const",
"fieldName",
"in",
"set",
")",
"{",
"const",
"field",
"=",
"model",
".",
"def",
".",
"fields",
"[",
"fieldName",
"]",
... | convert the field to table column | [
"convert",
"the",
"field",
"to",
"table",
"column"
] | 3abe85edbfe323939c84c1d02128d74d6374bcde | https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/frm/src/builder.js#L460-L470 | train |
krzystof/possible-states | lib/index.js | zip | function zip(keys, values) {
if (keys.length !== values.length) {
throw Error(`Incorrect number of arguments, expected: ${keys.length}, arguments received: ${values.join(', ')}`)
}
return keys.reduce((all, key, idx) => ({...all, [key]: values[idx]}), {})
} | javascript | function zip(keys, values) {
if (keys.length !== values.length) {
throw Error(`Incorrect number of arguments, expected: ${keys.length}, arguments received: ${values.join(', ')}`)
}
return keys.reduce((all, key, idx) => ({...all, [key]: values[idx]}), {})
} | [
"function",
"zip",
"(",
"keys",
",",
"values",
")",
"{",
"if",
"(",
"keys",
".",
"length",
"!==",
"values",
".",
"length",
")",
"{",
"throw",
"Error",
"(",
"`",
"${",
"keys",
".",
"length",
"}",
"${",
"values",
".",
"join",
"(",
"', '",
")",
"}",... | Zip two arrays together, combining the keys of the
first with the values of the second one. | [
"Zip",
"two",
"arrays",
"together",
"combining",
"the",
"keys",
"of",
"the",
"first",
"with",
"the",
"values",
"of",
"the",
"second",
"one",
"."
] | f7248da30dbec056447f11c2e9c5bc36526afaac | https://github.com/krzystof/possible-states/blob/f7248da30dbec056447f11c2e9c5bc36526afaac/lib/index.js#L5-L11 | train |
krzystof/possible-states | lib/index.js | PossibleStatesContainer | function PossibleStatesContainer({current, allStates, data}) {
return {
caseOf(clauses) {
const casesCovered = Object.keys(clauses)
const notCovered = allStates.map(({name}) => name).filter(state => !casesCovered.includes(state))
if (notCovered.length > 0 && !casesCovered.includes('_')) {
... | javascript | function PossibleStatesContainer({current, allStates, data}) {
return {
caseOf(clauses) {
const casesCovered = Object.keys(clauses)
const notCovered = allStates.map(({name}) => name).filter(state => !casesCovered.includes(state))
if (notCovered.length > 0 && !casesCovered.includes('_')) {
... | [
"function",
"PossibleStatesContainer",
"(",
"{",
"current",
",",
"allStates",
",",
"data",
"}",
")",
"{",
"return",
"{",
"caseOf",
"(",
"clauses",
")",
"{",
"const",
"casesCovered",
"=",
"Object",
".",
"keys",
"(",
"clauses",
")",
"const",
"notCovered",
"=... | The main data structure passed to the clients. | [
"The",
"main",
"data",
"structure",
"passed",
"to",
"the",
"clients",
"."
] | f7248da30dbec056447f11c2e9c5bc36526afaac | https://github.com/krzystof/possible-states/blob/f7248da30dbec056447f11c2e9c5bc36526afaac/lib/index.js#L68-L94 | train |
krzystof/possible-states | lib/index.js | PossibleStates | function PossibleStates(...allStates) {
if (!allStates.length === 0) {
throw Error('No values passed when constructing a new PossibleStates')
}
const containsData = typeDefinition => typeDefinition.match(/<.*>/)
if (allStates[0].match(/<.*>/)) {
throw Error('The initial state cannot contain data')
}... | javascript | function PossibleStates(...allStates) {
if (!allStates.length === 0) {
throw Error('No values passed when constructing a new PossibleStates')
}
const containsData = typeDefinition => typeDefinition.match(/<.*>/)
if (allStates[0].match(/<.*>/)) {
throw Error('The initial state cannot contain data')
}... | [
"function",
"PossibleStates",
"(",
"...",
"allStates",
")",
"{",
"if",
"(",
"!",
"allStates",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"Error",
"(",
"'No values passed when constructing a new PossibleStates'",
")",
"}",
"const",
"containsData",
"=",
"typeDefi... | A function to parse the users definition and create
the corresponding Container.
The only exposed function to users. | [
"A",
"function",
"to",
"parse",
"the",
"users",
"definition",
"and",
"create",
"the",
"corresponding",
"Container",
".",
"The",
"only",
"exposed",
"function",
"to",
"users",
"."
] | f7248da30dbec056447f11c2e9c5bc36526afaac | https://github.com/krzystof/possible-states/blob/f7248da30dbec056447f11c2e9c5bc36526afaac/lib/index.js#L101-L123 | train |
adekom/decitectural | index.js | function(architectural, units, precision) {
if (typeof architectural !== "string" && !(architectural instanceof String))
return false;
if(architectural.match(/^(([0-9]+)\')?([-\s])*((([0-9]+\")([-\s])*|([0-9]*)([-\s]*)([0-9]+)(\/{1})([0-9]+\")))?$/g) === null)
return false;
if(["1", "1/10", "1/100", "1/1000... | javascript | function(architectural, units, precision) {
if (typeof architectural !== "string" && !(architectural instanceof String))
return false;
if(architectural.match(/^(([0-9]+)\')?([-\s])*((([0-9]+\")([-\s])*|([0-9]*)([-\s]*)([0-9]+)(\/{1})([0-9]+\")))?$/g) === null)
return false;
if(["1", "1/10", "1/100", "1/1000... | [
"function",
"(",
"architectural",
",",
"units",
",",
"precision",
")",
"{",
"if",
"(",
"typeof",
"architectural",
"!==",
"\"string\"",
"&&",
"!",
"(",
"architectural",
"instanceof",
"String",
")",
")",
"return",
"false",
";",
"if",
"(",
"architectural",
".",... | Convert architectural measurement to decimal notation.
@param {String} architectural
@param {String} units
@param {String} precision
@return {Number} | [
"Convert",
"architectural",
"measurement",
"to",
"decimal",
"notation",
"."
] | 3aa94c2c09bc23dd76ea2238021ede750b3e123e | https://github.com/adekom/decitectural/blob/3aa94c2c09bc23dd76ea2238021ede750b3e123e/index.js#L11-L49 | train | |
adekom/decitectural | index.js | function(decimal, units, precision) {
if(typeof decimal !== "number" || isNaN(decimal) || !isFinite(decimal))
return false;
if(["inches", "feet"].indexOf(units) < 0)
return false;
if(["1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/128", "1/256"].indexOf(precision) < 0)
return false;
var architectur... | javascript | function(decimal, units, precision) {
if(typeof decimal !== "number" || isNaN(decimal) || !isFinite(decimal))
return false;
if(["inches", "feet"].indexOf(units) < 0)
return false;
if(["1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/128", "1/256"].indexOf(precision) < 0)
return false;
var architectur... | [
"function",
"(",
"decimal",
",",
"units",
",",
"precision",
")",
"{",
"if",
"(",
"typeof",
"decimal",
"!==",
"\"number\"",
"||",
"isNaN",
"(",
"decimal",
")",
"||",
"!",
"isFinite",
"(",
"decimal",
")",
")",
"return",
"false",
";",
"if",
"(",
"[",
"\... | Convert decimal measurement to architectural notation.
@param {Number} decimal
@param {String} units
@param {String} precision
@return {String} | [
"Convert",
"decimal",
"measurement",
"to",
"architectural",
"notation",
"."
] | 3aa94c2c09bc23dd76ea2238021ede750b3e123e | https://github.com/adekom/decitectural/blob/3aa94c2c09bc23dd76ea2238021ede750b3e123e/index.js#L60-L91 | train | |
seeden/maglev | src/models/user.js | createByFacebook | function createByFacebook(profile, callback) {
if (!profile.id) {
return callback(new Error('Profile id is undefined'));
}
this.findByFacebookID(profile.id, ok(callback, (user) => {
if (user) {
return updateUserByFacebookProfile(user, profile, callback);
}
this.create({
username: pro... | javascript | function createByFacebook(profile, callback) {
if (!profile.id) {
return callback(new Error('Profile id is undefined'));
}
this.findByFacebookID(profile.id, ok(callback, (user) => {
if (user) {
return updateUserByFacebookProfile(user, profile, callback);
}
this.create({
username: pro... | [
"function",
"createByFacebook",
"(",
"profile",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"profile",
".",
"id",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Profile id is undefined'",
")",
")",
";",
"}",
"this",
".",
"findByFacebookID",
"("... | Create user by user profile from facebook
@param {Object} profile Profile from facebook
@param {Function} callback Callback with created user | [
"Create",
"user",
"by",
"user",
"profile",
"from",
"facebook"
] | e291675fed963ccf5d50bab24ec9d9bf745ad5a3 | https://github.com/seeden/maglev/blob/e291675fed963ccf5d50bab24ec9d9bf745ad5a3/src/models/user.js#L96-L119 | train |
seeden/maglev | src/models/user.js | createByTwitter | function createByTwitter(profile, callback) {
if (!profile.id) {
return callback(new Error('Profile id is undefined'));
}
this.findByTwitterID(profile.id, ok(callback, (user) => {
if (user) {
return callback(null, user);
}
this.create({
username: profile.username || null,
name:... | javascript | function createByTwitter(profile, callback) {
if (!profile.id) {
return callback(new Error('Profile id is undefined'));
}
this.findByTwitterID(profile.id, ok(callback, (user) => {
if (user) {
return callback(null, user);
}
this.create({
username: profile.username || null,
name:... | [
"function",
"createByTwitter",
"(",
"profile",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"profile",
".",
"id",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Profile id is undefined'",
")",
")",
";",
"}",
"this",
".",
"findByTwitterID",
"(",
... | Create user by user profile from twitter
@param {Object} profile Profile from twitter
@param {Function} callback Callback with created user | [
"Create",
"user",
"by",
"user",
"profile",
"from",
"twitter"
] | e291675fed963ccf5d50bab24ec9d9bf745ad5a3 | https://github.com/seeden/maglev/blob/e291675fed963ccf5d50bab24ec9d9bf745ad5a3/src/models/user.js#L126-L145 | train |
seeden/maglev | src/models/user.js | generateBearerToken | function generateBearerToken(tokenSecret, expiresInMinutes = 60 * 24 * 14, scope = []) {
if (!tokenSecret) {
throw new Error('Token secret is undefined');
}
const data = {
user: this._id.toString(),
};
if (scope.length) {
data.scope = scope;
}
const token = jwt.sign(data, tokenSecret, {
... | javascript | function generateBearerToken(tokenSecret, expiresInMinutes = 60 * 24 * 14, scope = []) {
if (!tokenSecret) {
throw new Error('Token secret is undefined');
}
const data = {
user: this._id.toString(),
};
if (scope.length) {
data.scope = scope;
}
const token = jwt.sign(data, tokenSecret, {
... | [
"function",
"generateBearerToken",
"(",
"tokenSecret",
",",
"expiresInMinutes",
"=",
"60",
"*",
"24",
"*",
"14",
",",
"scope",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"tokenSecret",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Token secret is undefined'",
")... | Generate access token for actual user
@param {String} Secret for generating of token
@param {[Number]} expiresInMinutes
@param {[Array]} scope List of scopes
@return {Object} Access token of user | [
"Generate",
"access",
"token",
"for",
"actual",
"user"
] | e291675fed963ccf5d50bab24ec9d9bf745ad5a3 | https://github.com/seeden/maglev/blob/e291675fed963ccf5d50bab24ec9d9bf745ad5a3/src/models/user.js#L154-L175 | train |
seeden/maglev | src/models/user.js | comparePassword | function comparePassword(candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
if (err) {
return callback(err);
}
callback(null, isMatch);
});
} | javascript | function comparePassword(candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
if (err) {
return callback(err);
}
callback(null, isMatch);
});
} | [
"function",
"comparePassword",
"(",
"candidatePassword",
",",
"callback",
")",
"{",
"bcrypt",
".",
"compare",
"(",
"candidatePassword",
",",
"this",
".",
"password",
",",
"(",
"err",
",",
"isMatch",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"... | Compare user entered password with stored user's password
@param {String} candidatePassword
@param {Function} callback | [
"Compare",
"user",
"entered",
"password",
"with",
"stored",
"user",
"s",
"password"
] | e291675fed963ccf5d50bab24ec9d9bf745ad5a3 | https://github.com/seeden/maglev/blob/e291675fed963ccf5d50bab24ec9d9bf745ad5a3/src/models/user.js#L318-L326 | train |
switer/chainjs | chain.js | pushNode | function pushNode( /*handler1, handler2, ..., handlerN*/ ) {
var node = {
items: utils.slice(arguments),
state: {}
}
var id = this.props._nodes.add(node)
node.id = id
return node
} | javascript | function pushNode( /*handler1, handler2, ..., handlerN*/ ) {
var node = {
items: utils.slice(arguments),
state: {}
}
var id = this.props._nodes.add(node)
node.id = id
return node
} | [
"function",
"pushNode",
"(",
"/*handler1, handler2, ..., handlerN*/",
")",
"{",
"var",
"node",
"=",
"{",
"items",
":",
"utils",
".",
"slice",
"(",
"arguments",
")",
",",
"state",
":",
"{",
"}",
"}",
"var",
"id",
"=",
"this",
".",
"props",
".",
"_nodes",
... | Push a step node to LinkNodes | [
"Push",
"a",
"step",
"node",
"to",
"LinkNodes"
] | 7b5c0ceb55135df7b7a621a891cf59f49cc67d6c | https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/chain.js#L263-L271 | train |
switer/chainjs | chain.js | pushHandlers | function pushHandlers (chain, args) {
return pushNode.apply(chain, utils.type(args[0]) == 'array' ? args[0]:args)
} | javascript | function pushHandlers (chain, args) {
return pushNode.apply(chain, utils.type(args[0]) == 'array' ? args[0]:args)
} | [
"function",
"pushHandlers",
"(",
"chain",
",",
"args",
")",
"{",
"return",
"pushNode",
".",
"apply",
"(",
"chain",
",",
"utils",
".",
"type",
"(",
"args",
"[",
"0",
"]",
")",
"==",
"'array'",
"?",
"args",
"[",
"0",
"]",
":",
"args",
")",
"}"
] | Push functions to step node | [
"Push",
"functions",
"to",
"step",
"node"
] | 7b5c0ceb55135df7b7a621a891cf59f49cc67d6c | https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/chain.js#L275-L277 | train |
switer/chainjs | chain.js | setAlltoNoop | function setAlltoNoop (obj, methods) {
utils.each(methods, function (method) {
obj[method] = noop
})
} | javascript | function setAlltoNoop (obj, methods) {
utils.each(methods, function (method) {
obj[method] = noop
})
} | [
"function",
"setAlltoNoop",
"(",
"obj",
",",
"methods",
")",
"{",
"utils",
".",
"each",
"(",
"methods",
",",
"function",
"(",
"method",
")",
"{",
"obj",
"[",
"method",
"]",
"=",
"noop",
"}",
")",
"}"
] | Call by destroy step | [
"Call",
"by",
"destroy",
"step"
] | 7b5c0ceb55135df7b7a621a891cf59f49cc67d6c | https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/chain.js#L283-L287 | train |
arendjr/laces.js | laces.local.js | LacesLocalModel | function LacesLocalModel(key) {
var data = localStorage.getItem(key);
var object = data && JSON.parse(data) || {};
Laces.Model.call(this, object);
this.bind("change", function() { localStorage.setItem(key, JSON.stringify(this)); });
} | javascript | function LacesLocalModel(key) {
var data = localStorage.getItem(key);
var object = data && JSON.parse(data) || {};
Laces.Model.call(this, object);
this.bind("change", function() { localStorage.setItem(key, JSON.stringify(this)); });
} | [
"function",
"LacesLocalModel",
"(",
"key",
")",
"{",
"var",
"data",
"=",
"localStorage",
".",
"getItem",
"(",
"key",
")",
";",
"var",
"object",
"=",
"data",
"&&",
"JSON",
".",
"parse",
"(",
"data",
")",
"||",
"{",
"}",
";",
"Laces",
".",
"Model",
"... | Laces Local Model constructor. A Laces Local Model is a Model that automatically syncs itself to LocalStorage. key - The key to use for storing the LocalStorage data. | [
"Laces",
"Local",
"Model",
"constructor",
".",
"A",
"Laces",
"Local",
"Model",
"is",
"a",
"Model",
"that",
"automatically",
"syncs",
"itself",
"to",
"LocalStorage",
".",
"key",
"-",
"The",
"key",
"to",
"use",
"for",
"storing",
"the",
"LocalStorage",
"data",
... | e04fd060a4668abe58064267b1405e6a40f8a6f2 | https://github.com/arendjr/laces.js/blob/e04fd060a4668abe58064267b1405e6a40f8a6f2/laces.local.js#L14-L22 | train |
arendjr/laces.js | laces.local.js | LacesLocalArray | function LacesLocalArray(key) {
var data = localStorage.getItem(key);
var elements = data && JSON.parse(data) || [];
var array = Laces.Array.call(this);
for (var i = 0, length = elements.length; i < length; i++) {
array.push(elements[i]);
}
array.bind("change", function() { localStora... | javascript | function LacesLocalArray(key) {
var data = localStorage.getItem(key);
var elements = data && JSON.parse(data) || [];
var array = Laces.Array.call(this);
for (var i = 0, length = elements.length; i < length; i++) {
array.push(elements[i]);
}
array.bind("change", function() { localStora... | [
"function",
"LacesLocalArray",
"(",
"key",
")",
"{",
"var",
"data",
"=",
"localStorage",
".",
"getItem",
"(",
"key",
")",
";",
"var",
"elements",
"=",
"data",
"&&",
"JSON",
".",
"parse",
"(",
"data",
")",
"||",
"[",
"]",
";",
"var",
"array",
"=",
"... | Laces Local Array constructor. A Laces Local Array is a Laces Array that automatically syncs itself to LocalStorage. key - The key to use for storing the LocalStorage data. | [
"Laces",
"Local",
"Array",
"constructor",
".",
"A",
"Laces",
"Local",
"Array",
"is",
"a",
"Laces",
"Array",
"that",
"automatically",
"syncs",
"itself",
"to",
"LocalStorage",
".",
"key",
"-",
"The",
"key",
"to",
"use",
"for",
"storing",
"the",
"LocalStorage",... | e04fd060a4668abe58064267b1405e6a40f8a6f2 | https://github.com/arendjr/laces.js/blob/e04fd060a4668abe58064267b1405e6a40f8a6f2/laces.local.js#L35-L48 | train |
ceddl/ceddl-aditional-inputs | src/page-ready.js | createCompleteCallback | function createCompleteCallback(name) {
return function(data) {
_store[name] = data;
var allCallbacksComplete = Object.keys(_store).reduce(isStoreValid, true);
if (allCallbacksComplete) {
clearTimeout(pageReadyWarning);
ceddl.emitEvent('pagere... | javascript | function createCompleteCallback(name) {
return function(data) {
_store[name] = data;
var allCallbacksComplete = Object.keys(_store).reduce(isStoreValid, true);
if (allCallbacksComplete) {
clearTimeout(pageReadyWarning);
ceddl.emitEvent('pagere... | [
"function",
"createCompleteCallback",
"(",
"name",
")",
"{",
"return",
"function",
"(",
"data",
")",
"{",
"_store",
"[",
"name",
"]",
"=",
"data",
";",
"var",
"allCallbacksComplete",
"=",
"Object",
".",
"keys",
"(",
"_store",
")",
".",
"reduce",
"(",
"is... | Helper function that creates event callbacks which set the event as
completed on execution, as well as checking whether all keys in the
store are true, and dispatch the pageready event should that be the
case.
@param {String} name Event name to mark as completed on execution.
@returns {Function} | [
"Helper",
"function",
"that",
"creates",
"event",
"callbacks",
"which",
"set",
"the",
"event",
"as",
"completed",
"on",
"execution",
"as",
"well",
"as",
"checking",
"whether",
"all",
"keys",
"in",
"the",
"store",
"are",
"true",
"and",
"dispatch",
"the",
"pag... | 0e018d463107a0b631c317d7bf372aa9e194b7da | https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/page-ready.js#L42-L52 | train |
ceddl/ceddl-aditional-inputs | src/page-ready.js | pageReadySetListeners | function pageReadySetListeners(eventNames) {
// Reset the previous state
_store = {};
_listeners.forEach(function(eventCallback) {
ceddl.eventbus.off(eventCallback.name, eventCallback.markComplete);
});
_listeners = [];
// If there is no need to wait for anyt... | javascript | function pageReadySetListeners(eventNames) {
// Reset the previous state
_store = {};
_listeners.forEach(function(eventCallback) {
ceddl.eventbus.off(eventCallback.name, eventCallback.markComplete);
});
_listeners = [];
// If there is no need to wait for anyt... | [
"function",
"pageReadySetListeners",
"(",
"eventNames",
")",
"{",
"// Reset the previous state",
"_store",
"=",
"{",
"}",
";",
"_listeners",
".",
"forEach",
"(",
"function",
"(",
"eventCallback",
")",
"{",
"ceddl",
".",
"eventbus",
".",
"off",
"(",
"eventCallbac... | Method to indicate when to fire the pageready event. It takes a collection
of event names and waits until all of them have fired at least once before
dispatching the pageready event. | [
"Method",
"to",
"indicate",
"when",
"to",
"fire",
"the",
"pageready",
"event",
".",
"It",
"takes",
"a",
"collection",
"of",
"event",
"names",
"and",
"waits",
"until",
"all",
"of",
"them",
"have",
"fired",
"at",
"least",
"once",
"before",
"dispatching",
"th... | 0e018d463107a0b631c317d7bf372aa9e194b7da | https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/page-ready.js#L83-L117 | train |
leesei/node-comics-feed | lib/main.js | _initFeed | function _initFeed(meta) {
// create out feed
feed = new RSS({
title: meta.title.replace(/^GoComics.com - /, ''),
description: meta.description,
generator: 'node-comics-scrape',
feed_url: meta.xmlUrl,
site_url: meta.link,
pubDate: meta.pubDate,
ttl: ONE_DAY_MINUTES
});
} | javascript | function _initFeed(meta) {
// create out feed
feed = new RSS({
title: meta.title.replace(/^GoComics.com - /, ''),
description: meta.description,
generator: 'node-comics-scrape',
feed_url: meta.xmlUrl,
site_url: meta.link,
pubDate: meta.pubDate,
ttl: ONE_DAY_MINUTES
});
} | [
"function",
"_initFeed",
"(",
"meta",
")",
"{",
"// create out feed",
"feed",
"=",
"new",
"RSS",
"(",
"{",
"title",
":",
"meta",
".",
"title",
".",
"replace",
"(",
"/",
"^GoComics.com - ",
"/",
",",
"''",
")",
",",
"description",
":",
"meta",
".",
"des... | out-feed | [
"out",
"-",
"feed"
] | 269161d83c10381b70f0d423cc8d212ddff543d7 | https://github.com/leesei/node-comics-feed/blob/269161d83c10381b70f0d423cc8d212ddff543d7/lib/main.js#L27-L38 | train |
anvaka/ngraph.merge | index.js | merge | function merge(target, options) {
var key;
if (!target) { target = {}; }
if (options) {
for (key in options) {
if (options.hasOwnProperty(key)) {
var targetHasIt = target.hasOwnProperty(key),
optionsValueType = typeof options[key],
shouldReplace = !targetHasIt || (typeof ... | javascript | function merge(target, options) {
var key;
if (!target) { target = {}; }
if (options) {
for (key in options) {
if (options.hasOwnProperty(key)) {
var targetHasIt = target.hasOwnProperty(key),
optionsValueType = typeof options[key],
shouldReplace = !targetHasIt || (typeof ... | [
"function",
"merge",
"(",
"target",
",",
"options",
")",
"{",
"var",
"key",
";",
"if",
"(",
"!",
"target",
")",
"{",
"target",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"options",
")",
"{",
"for",
"(",
"key",
"in",
"options",
")",
"{",
"if",
"(",
"... | Augments `target` with properties in `options`. Does not override
target's properties if they are defined and matches expected type in
options
@returns {Object} merged object | [
"Augments",
"target",
"with",
"properties",
"in",
"options",
".",
"Does",
"not",
"override",
"target",
"s",
"properties",
"if",
"they",
"are",
"defined",
"and",
"matches",
"expected",
"type",
"in",
"options"
] | 38721e27ea39d97b425934f983b4fc998fe285ad | https://github.com/anvaka/ngraph.merge/blob/38721e27ea39d97b425934f983b4fc998fe285ad/index.js#L10-L31 | train |
clux/trials | trials.js | function (ary) {
var shuffled = [];
ary.reduce(function (acc, v) {
var r = range(0, acc);
shuffled[acc] = shuffled[r];
shuffled[r] = v;
return acc + 1;
}, 0);
return shuffled;
} | javascript | function (ary) {
var shuffled = [];
ary.reduce(function (acc, v) {
var r = range(0, acc);
shuffled[acc] = shuffled[r];
shuffled[r] = v;
return acc + 1;
}, 0);
return shuffled;
} | [
"function",
"(",
"ary",
")",
"{",
"var",
"shuffled",
"=",
"[",
"]",
";",
"ary",
".",
"reduce",
"(",
"function",
"(",
"acc",
",",
"v",
")",
"{",
"var",
"r",
"=",
"range",
"(",
"0",
",",
"acc",
")",
";",
"shuffled",
"[",
"acc",
"]",
"=",
"shuff... | fisher-yates shuffle - does not modify ary | [
"fisher",
"-",
"yates",
"shuffle",
"-",
"does",
"not",
"modify",
"ary"
] | 591f5a966b10f96bb849c9ecf423e2cbbb356344 | https://github.com/clux/trials/blob/591f5a966b10f96bb849c9ecf423e2cbbb356344/trials.js#L57-L66 | train | |
roeldev-deprecated-stuff/log-interceptor | lib/utils.js | function($str, $checkColors)
{
var $regex = new RegExp(REGEXP_PLAIN, 'gm');
var $match = $str.match($regex);
if (!!$match)
{
$str = $str.substr($match[0].length);
$match = true;
}
else if ($checkColors !== false)
{
$regex... | javascript | function($str, $checkColors)
{
var $regex = new RegExp(REGEXP_PLAIN, 'gm');
var $match = $str.match($regex);
if (!!$match)
{
$str = $str.substr($match[0].length);
$match = true;
}
else if ($checkColors !== false)
{
$regex... | [
"function",
"(",
"$str",
",",
"$checkColors",
")",
"{",
"var",
"$regex",
"=",
"new",
"RegExp",
"(",
"REGEXP_PLAIN",
",",
"'gm'",
")",
";",
"var",
"$match",
"=",
"$str",
".",
"match",
"(",
"$regex",
")",
";",
"if",
"(",
"!",
"!",
"$match",
")",
"{",... | Trim a timestamp from the beginning of the string. First checks for the
timestamp without color coding. When none found and the `checkColors`
arg equals `true`, the function searches for color coded timestamps.
@param {string} $str
@param {boolean} $checkColors [true]
@return {string} | [
"Trim",
"a",
"timestamp",
"from",
"the",
"beginning",
"of",
"the",
"string",
".",
"First",
"checks",
"for",
"the",
"timestamp",
"without",
"color",
"coding",
".",
"When",
"none",
"found",
"and",
"the",
"checkColors",
"arg",
"equals",
"true",
"the",
"function... | ccc958e47de73dffdf7d4c0d62766e6d85e5b066 | https://github.com/roeldev-deprecated-stuff/log-interceptor/blob/ccc958e47de73dffdf7d4c0d62766e6d85e5b066/lib/utils.js#L35-L64 | train | |
tianjianchn/javascript-packages | packages/promise-addition/src/static-members.js | run | function run(index) {
if (index >= len || error) return Promise.resolve();
next += 1;
try {
return Promise.resolve(iterator(arr[index], index)).then((ret) => {
result[index] = ret;
return run(next);
}, (err) => {
error = err;
r... | javascript | function run(index) {
if (index >= len || error) return Promise.resolve();
next += 1;
try {
return Promise.resolve(iterator(arr[index], index)).then((ret) => {
result[index] = ret;
return run(next);
}, (err) => {
error = err;
r... | [
"function",
"run",
"(",
"index",
")",
"{",
"if",
"(",
"index",
">=",
"len",
"||",
"error",
")",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"next",
"+=",
"1",
";",
"try",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"iterator",
"(",
"arr"... | if an error occured, all remain ones will not be run | [
"if",
"an",
"error",
"occured",
"all",
"remain",
"ones",
"will",
"not",
"be",
"run"
] | 3abe85edbfe323939c84c1d02128d74d6374bcde | https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/promise-addition/src/static-members.js#L71-L86 | train |
fresheneesz/deadunit | deadunit.browser.js | updateCountSuccess | function updateCountSuccess(that) {
if(that.expected !== undefined) {
var countSuccess = that.count === that.expected
that.countBlock.state.set("success", countSuccess)
if(that.groupEnded) that.countBlock.results.state.set("late", true)
if(countSuccess) {
that.mainGroup.... | javascript | function updateCountSuccess(that) {
if(that.expected !== undefined) {
var countSuccess = that.count === that.expected
that.countBlock.state.set("success", countSuccess)
if(that.groupEnded) that.countBlock.results.state.set("late", true)
if(countSuccess) {
that.mainGroup.... | [
"function",
"updateCountSuccess",
"(",
"that",
")",
"{",
"if",
"(",
"that",
".",
"expected",
"!==",
"undefined",
")",
"{",
"var",
"countSuccess",
"=",
"that",
".",
"count",
"===",
"that",
".",
"expected",
"that",
".",
"countBlock",
".",
"state",
".",
"se... | figure out if count succeeded and update the main group and the countblock state | [
"figure",
"out",
"if",
"count",
"succeeded",
"and",
"update",
"the",
"main",
"group",
"and",
"the",
"countblock",
"state"
] | c2bf1f6dc7e53a85b85bc2fb8607f1ad9c6cf516 | https://github.com/fresheneesz/deadunit/blob/c2bf1f6dc7e53a85b85bc2fb8607f1ad9c6cf516/deadunit.browser.js#L426-L447 | train |
kuno/neco | deps/npm/lib/utils/completion/contains-single-match.js | containsSingleMatch | function containsSingleMatch(str, arr) {
var filtered = arr.filter(function(e) { return e.indexOf(str) === 0 })
return filtered.length === 1
} | javascript | function containsSingleMatch(str, arr) {
var filtered = arr.filter(function(e) { return e.indexOf(str) === 0 })
return filtered.length === 1
} | [
"function",
"containsSingleMatch",
"(",
"str",
",",
"arr",
")",
"{",
"var",
"filtered",
"=",
"arr",
".",
"filter",
"(",
"function",
"(",
"e",
")",
"{",
"return",
"e",
".",
"indexOf",
"(",
"str",
")",
"===",
"0",
"}",
")",
"return",
"filtered",
".",
... | True if arr contains only one element starting with str. | [
"True",
"if",
"arr",
"contains",
"only",
"one",
"element",
"starting",
"with",
"str",
"."
] | cf6361c1fcb9466c6b2ab3b127b5d0160ca50735 | https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/utils/completion/contains-single-match.js#L5-L8 | train |
kuno/neco | deps/npm/lib/utils/ini-parser.js | objectEach | function objectEach(obj, fn, thisObj) {
var keys = Object.keys(obj).sort(function (a,b) {
a = a.toLowerCase()
b = b.toLowerCase()
return a === b ? 0 : a < b ? -1 : 1
})
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i]
fn.call(thisObj, obj[key], key, obj)
}
} | javascript | function objectEach(obj, fn, thisObj) {
var keys = Object.keys(obj).sort(function (a,b) {
a = a.toLowerCase()
b = b.toLowerCase()
return a === b ? 0 : a < b ? -1 : 1
})
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i]
fn.call(thisObj, obj[key], key, obj)
}
} | [
"function",
"objectEach",
"(",
"obj",
",",
"fn",
",",
"thisObj",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"a",
"=",
"a",
".",
"toLowerCase",
"(",
")",
"b",... | ForEaches over an object. The only thing faster is to inline this function. | [
"ForEaches",
"over",
"an",
"object",
".",
"The",
"only",
"thing",
"faster",
"is",
"to",
"inline",
"this",
"function",
"."
] | cf6361c1fcb9466c6b2ab3b127b5d0160ca50735 | https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/utils/ini-parser.js#L31-L41 | train |
TotallyRadRichard/jumbotron | public/js/reveal/jumbotron.reveal.js | function($frag) {
if(typeof $frag.parent().attr('jt-code-blur') !== 'string') {
return;
}
if(typeof $frag.attr('jt-clear-blur') === 'string') {
return $frag.parent().find('code').removeClass('blurred');
}
if($frag.is('code') && $frag.hasClass('fragment')) {
$frag.parent()
... | javascript | function($frag) {
if(typeof $frag.parent().attr('jt-code-blur') !== 'string') {
return;
}
if(typeof $frag.attr('jt-clear-blur') === 'string') {
return $frag.parent().find('code').removeClass('blurred');
}
if($frag.is('code') && $frag.hasClass('fragment')) {
$frag.parent()
... | [
"function",
"(",
"$frag",
")",
"{",
"if",
"(",
"typeof",
"$frag",
".",
"parent",
"(",
")",
".",
"attr",
"(",
"'jt-code-blur'",
")",
"!==",
"'string'",
")",
"{",
"return",
";",
"}",
"if",
"(",
"typeof",
"$frag",
".",
"attr",
"(",
"'jt-clear-blur'",
")... | set up fragment highlighting | [
"set",
"up",
"fragment",
"highlighting"
] | 64d5e605d51d5cb3c588258b5738128ca56634bf | https://github.com/TotallyRadRichard/jumbotron/blob/64d5e605d51d5cb3c588258b5738128ca56634bf/public/js/reveal/jumbotron.reveal.js#L86-L100 | train | |
necolas/dom-insert | index.js | normalizeContent | function normalizeContent(content) {
var fragment = document.createDocumentFragment();
var i, len;
if (isNode(content)) {
return content;
} else {
len = content.length;
for (i = 0; i < len; i++) { fragment.appendChild(content[i]); }
return fragment;
}
} | javascript | function normalizeContent(content) {
var fragment = document.createDocumentFragment();
var i, len;
if (isNode(content)) {
return content;
} else {
len = content.length;
for (i = 0; i < len; i++) { fragment.appendChild(content[i]); }
return fragment;
}
} | [
"function",
"normalizeContent",
"(",
"content",
")",
"{",
"var",
"fragment",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
";",
"var",
"i",
",",
"len",
";",
"if",
"(",
"isNode",
"(",
"content",
")",
")",
"{",
"return",
"content",
";",
"}",
... | Normalize a DOM Node or a collection of DOM Nodes. Returns a
documentFragment if the input is a collection.
@param {Node|NodeList|Array<Node>} content - the content to normalize
@return {Node} | [
"Normalize",
"a",
"DOM",
"Node",
"or",
"a",
"collection",
"of",
"DOM",
"Nodes",
".",
"Returns",
"a",
"documentFragment",
"if",
"the",
"input",
"is",
"a",
"collection",
"."
] | dc59e09f9a12790e050e0411f2f4a4645c9ba2e0 | https://github.com/necolas/dom-insert/blob/dc59e09f9a12790e050e0411f2f4a4645c9ba2e0/index.js#L93-L104 | train |
sagiegurari/js-project-commons | lib/grunt/apidoc2readme.js | function (doc) {
[
'Returns',
'Emits',
'Access',
'Kind'
].forEach(function removeLine(preTag) {
preTag = '**' + preTag;
var start = doc.indexOf(preTag);
if (start !== -1) {
var end = doc.indexOf('\n', st... | javascript | function (doc) {
[
'Returns',
'Emits',
'Access',
'Kind'
].forEach(function removeLine(preTag) {
preTag = '**' + preTag;
var start = doc.indexOf(preTag);
if (start !== -1) {
var end = doc.indexOf('\n', st... | [
"function",
"(",
"doc",
")",
"{",
"[",
"'Returns'",
",",
"'Emits'",
",",
"'Access'",
",",
"'Kind'",
"]",
".",
"forEach",
"(",
"function",
"removeLine",
"(",
"preTag",
")",
"{",
"preTag",
"=",
"'**'",
"+",
"preTag",
";",
"var",
"start",
"=",
"doc",
".... | Returns the doc without specific api doc tags.
@function
@memberof! GruntApiDocs2ReadmeTaskHelper
@private
@param {String} doc - The document text
@returns {String} The doc without specific api doc tags | [
"Returns",
"the",
"doc",
"without",
"specific",
"api",
"doc",
"tags",
"."
] | 42dd07a8a3b2c49db71f489e08b94ac7279007a3 | https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/apidoc2readme.js#L22-L40 | train | |
sagiegurari/js-project-commons | lib/grunt/apidoc2readme.js | function (doc, skipSignature, postHook) {
var index = doc.indexOf('\n');
var functionLine = '';
if (!skipSignature) {
functionLine = doc.substring(0, index).substring(4); //get first line and remove initial ###
//wrap with "'", replace object#function to object.function,... | javascript | function (doc, skipSignature, postHook) {
var index = doc.indexOf('\n');
var functionLine = '';
if (!skipSignature) {
functionLine = doc.substring(0, index).substring(4); //get first line and remove initial ###
//wrap with "'", replace object#function to object.function,... | [
"function",
"(",
"doc",
",",
"skipSignature",
",",
"postHook",
")",
"{",
"var",
"index",
"=",
"doc",
".",
"indexOf",
"(",
"'\\n'",
")",
";",
"var",
"functionLine",
"=",
"''",
";",
"if",
"(",
"!",
"skipSignature",
")",
"{",
"functionLine",
"=",
"doc",
... | Returns the doc with updated signature line.
@function
@memberof! GruntApiDocs2ReadmeTaskHelper
@private
@param {String} doc - The document text
@param {Boolean} [skipSignature] - True to not create a signature line, just remove it
@param {function} [postHook] - Will be invoked after the signature was modified
@return... | [
"Returns",
"the",
"doc",
"with",
"updated",
"signature",
"line",
"."
] | 42dd07a8a3b2c49db71f489e08b94ac7279007a3 | https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/apidoc2readme.js#L52-L90 | train | |
sagiegurari/js-project-commons | lib/grunt/apidoc2readme.js | function (grunt, apiDocs, apiDocLink, occurrence) {
occurrence = occurrence || 1;
var linkString = '<a name="' + apiDocLink + '"></a>';
var index = -1;
var occurrenceIndex;
for (occurrenceIndex = 0; occurrenceIndex < occurrence; occurrenceIndex++) {
index = apiDocs.i... | javascript | function (grunt, apiDocs, apiDocLink, occurrence) {
occurrence = occurrence || 1;
var linkString = '<a name="' + apiDocLink + '"></a>';
var index = -1;
var occurrenceIndex;
for (occurrenceIndex = 0; occurrenceIndex < occurrence; occurrenceIndex++) {
index = apiDocs.i... | [
"function",
"(",
"grunt",
",",
"apiDocs",
",",
"apiDocLink",
",",
"occurrence",
")",
"{",
"occurrence",
"=",
"occurrence",
"||",
"1",
";",
"var",
"linkString",
"=",
"'<a name=\"'",
"+",
"apiDocLink",
"+",
"'\"></a>'",
";",
"var",
"index",
"=",
"-",
"1",
... | Returns the link location in the docs.
@function
@memberof! GruntApiDocs2ReadmeTaskHelper
@private
@param {Object} grunt - The grunt instance
@param {String} apiDocs - The document text
@param {String} apiDocLink - The link to search for
@param {Number} [occurrence] - The occurrence number
@returns {Number} The locati... | [
"Returns",
"the",
"link",
"location",
"in",
"the",
"docs",
"."
] | 42dd07a8a3b2c49db71f489e08b94ac7279007a3 | https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/apidoc2readme.js#L103-L118 | train | |
jeresig/node-enamdict | enamdict.js | function(callback) {
dataIndex = {};
var pos = 0;
enamdictData.split("\n").forEach(function(line) {
var parts = line.split("|");
var cleanName = parts[0];
var romaji = parts[1];
if (!(cleanName in dataIndex)) {
dataIndex[cleanNam... | javascript | function(callback) {
dataIndex = {};
var pos = 0;
enamdictData.split("\n").forEach(function(line) {
var parts = line.split("|");
var cleanName = parts[0];
var romaji = parts[1];
if (!(cleanName in dataIndex)) {
dataIndex[cleanNam... | [
"function",
"(",
"callback",
")",
"{",
"dataIndex",
"=",
"{",
"}",
";",
"var",
"pos",
"=",
"0",
";",
"enamdictData",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"forEach",
"(",
"function",
"(",
"line",
")",
"{",
"var",
"parts",
"=",
"line",
".",
"split... | Build an index to improve name lookup performance. | [
"Build",
"an",
"index",
"to",
"improve",
"name",
"lookup",
"performance",
"."
] | a95a2b85be3f07c2ecdbe2eb3bbe8108beda56e6 | https://github.com/jeresig/node-enamdict/blob/a95a2b85be3f07c2ecdbe2eb3bbe8108beda56e6/enamdict.js#L106-L129 | train | |
tianjianchn/javascript-packages | packages/wx-abc/lib/cs.js | sendCsMessage | function sendCsMessage(csMessage){
var token = this.instance.getAccessToken();
var url = 'https://api.WeiXin.qq.com/cgi-bin/message/custom/send?access_token='+token;
var fiber = fibext();
hr.post(url, {json: csMessage}, util.processResponse(function(err, body){
fiber.resume(err, body);
}));
retur... | javascript | function sendCsMessage(csMessage){
var token = this.instance.getAccessToken();
var url = 'https://api.WeiXin.qq.com/cgi-bin/message/custom/send?access_token='+token;
var fiber = fibext();
hr.post(url, {json: csMessage}, util.processResponse(function(err, body){
fiber.resume(err, body);
}));
retur... | [
"function",
"sendCsMessage",
"(",
"csMessage",
")",
"{",
"var",
"token",
"=",
"this",
".",
"instance",
".",
"getAccessToken",
"(",
")",
";",
"var",
"url",
"=",
"'https://api.WeiXin.qq.com/cgi-bin/message/custom/send?access_token='",
"+",
"token",
";",
"var",
"fiber"... | send custom service message, always async | [
"send",
"custom",
"service",
"message",
"always",
"async"
] | 3abe85edbfe323939c84c1d02128d74d6374bcde | https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/wx-abc/lib/cs.js#L140-L148 | train |
Raathigesh/AtmoExpressES5Generator | src/index.js | generate | function generate(spec) {
createProjectDirectory();
spec = addHttpEndpointNames(spec);
spec = addSocketEndpointFlag(spec);
spec = addSocketEmitTypeFlag(spec);
spec = isProxyEndpointAvailable(spec);
writeFileSync('server.mustache', spec, 'server.js');
writeFileSync('package.mustache', spec, 'package.json')... | javascript | function generate(spec) {
createProjectDirectory();
spec = addHttpEndpointNames(spec);
spec = addSocketEndpointFlag(spec);
spec = addSocketEmitTypeFlag(spec);
spec = isProxyEndpointAvailable(spec);
writeFileSync('server.mustache', spec, 'server.js');
writeFileSync('package.mustache', spec, 'package.json')... | [
"function",
"generate",
"(",
"spec",
")",
"{",
"createProjectDirectory",
"(",
")",
";",
"spec",
"=",
"addHttpEndpointNames",
"(",
"spec",
")",
";",
"spec",
"=",
"addSocketEndpointFlag",
"(",
"spec",
")",
";",
"spec",
"=",
"addSocketEmitTypeFlag",
"(",
"spec",
... | Generates the project files | [
"Generates",
"the",
"project",
"files"
] | e74b63811675c9a033e02f58604f270fac388dde | https://github.com/Raathigesh/AtmoExpressES5Generator/blob/e74b63811675c9a033e02f58604f270fac388dde/src/index.js#L9-L17 | train |
Raathigesh/AtmoExpressES5Generator | src/index.js | addHttpEndpointNames | function addHttpEndpointNames(spec) {
for(var i = 0; i < spec.endpoints.length; i++) {
var endpoint = spec.endpoints[i];
if (endpoint.response.contentType.contentType.toLowerCase() === 'javascript') {
endpoint.response.contentType.contentType = 'application/json';
endpoint.response.contentType.eva... | javascript | function addHttpEndpointNames(spec) {
for(var i = 0; i < spec.endpoints.length; i++) {
var endpoint = spec.endpoints[i];
if (endpoint.response.contentType.contentType.toLowerCase() === 'javascript') {
endpoint.response.contentType.contentType = 'application/json';
endpoint.response.contentType.eva... | [
"function",
"addHttpEndpointNames",
"(",
"spec",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"spec",
".",
"endpoints",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"endpoint",
"=",
"spec",
".",
"endpoints",
"[",
"i",
"]",
";",
"... | Makes the http method names to express friendly name | [
"Makes",
"the",
"http",
"method",
"names",
"to",
"express",
"friendly",
"name"
] | e74b63811675c9a033e02f58604f270fac388dde | https://github.com/Raathigesh/AtmoExpressES5Generator/blob/e74b63811675c9a033e02f58604f270fac388dde/src/index.js#L31-L43 | train |
Raathigesh/AtmoExpressES5Generator | src/index.js | addSocketEmitTypeFlag | function addSocketEmitTypeFlag(spec) {
for(var i = 0; i < spec.socketEndpoints.length; i++) {
var endpoint = spec.socketEndpoints[i];
endpoint.isEmitSelf = endpoint.emitType === "self";
endpoint.isEmitAll = endpoint.emitType === "all";
endpoint.isEmitBroadcast = endpoint.emitType === "broadcast";
... | javascript | function addSocketEmitTypeFlag(spec) {
for(var i = 0; i < spec.socketEndpoints.length; i++) {
var endpoint = spec.socketEndpoints[i];
endpoint.isEmitSelf = endpoint.emitType === "self";
endpoint.isEmitAll = endpoint.emitType === "all";
endpoint.isEmitBroadcast = endpoint.emitType === "broadcast";
... | [
"function",
"addSocketEmitTypeFlag",
"(",
"spec",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"spec",
".",
"socketEndpoints",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"endpoint",
"=",
"spec",
".",
"socketEndpoints",
"[",
"i",
"]... | Adds flags depending on the socket emit type | [
"Adds",
"flags",
"depending",
"on",
"the",
"socket",
"emit",
"type"
] | e74b63811675c9a033e02f58604f270fac388dde | https://github.com/Raathigesh/AtmoExpressES5Generator/blob/e74b63811675c9a033e02f58604f270fac388dde/src/index.js#L59-L68 | train |
Raathigesh/AtmoExpressES5Generator | src/index.js | writeFileSync | function writeFileSync(templateName, templateOption, filename) {
var templateString = fs.readFileSync(path.join(__dirname, '/templates/' + templateName), 'utf8');
fs.writeFileSync(path.join(projectDirectory, filename), Mustache.render(templateString, templateOption));
} | javascript | function writeFileSync(templateName, templateOption, filename) {
var templateString = fs.readFileSync(path.join(__dirname, '/templates/' + templateName), 'utf8');
fs.writeFileSync(path.join(projectDirectory, filename), Mustache.render(templateString, templateOption));
} | [
"function",
"writeFileSync",
"(",
"templateName",
",",
"templateOption",
",",
"filename",
")",
"{",
"var",
"templateString",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'/templates/'",
"+",
"templateName",
")",
",",
"'utf8... | Writes the file to the output folder | [
"Writes",
"the",
"file",
"to",
"the",
"output",
"folder"
] | e74b63811675c9a033e02f58604f270fac388dde | https://github.com/Raathigesh/AtmoExpressES5Generator/blob/e74b63811675c9a033e02f58604f270fac388dde/src/index.js#L83-L86 | train |
3axap4eHko/yyf | src/event.js | getEvent | function getEvent(context, eventName) {
if (!eventsMap.has(context)) {
eventsMap.set(context, {});
}
const events = eventsMap.get(context);
if (!events[eventName]) {
events[eventName] = {
listeners: [],
meta: new WeakMap()
};
}
return events[eventName];
} | javascript | function getEvent(context, eventName) {
if (!eventsMap.has(context)) {
eventsMap.set(context, {});
}
const events = eventsMap.get(context);
if (!events[eventName]) {
events[eventName] = {
listeners: [],
meta: new WeakMap()
};
}
return events[eventName];
} | [
"function",
"getEvent",
"(",
"context",
",",
"eventName",
")",
"{",
"if",
"(",
"!",
"eventsMap",
".",
"has",
"(",
"context",
")",
")",
"{",
"eventsMap",
".",
"set",
"(",
"context",
",",
"{",
"}",
")",
";",
"}",
"const",
"events",
"=",
"eventsMap",
... | Returns event's listeners
@param {Object} context
@param {string} eventName
@returns {Object} | [
"Returns",
"event",
"s",
"listeners"
] | 0eddc236a3a5052b682ecc31dbb459772e653c14 | https://github.com/3axap4eHko/yyf/blob/0eddc236a3a5052b682ecc31dbb459772e653c14/src/event.js#L14-L26 | train |
3axap4eHko/yyf | src/event.js | addListener | function addListener(event, callback, meta) {
event.listeners.push(callback);
event.meta.set(callback, meta);
} | javascript | function addListener(event, callback, meta) {
event.listeners.push(callback);
event.meta.set(callback, meta);
} | [
"function",
"addListener",
"(",
"event",
",",
"callback",
",",
"meta",
")",
"{",
"event",
".",
"listeners",
".",
"push",
"(",
"callback",
")",
";",
"event",
".",
"meta",
".",
"set",
"(",
"callback",
",",
"meta",
")",
";",
"}"
] | Adds listener to event
@param {Object} event
@param {Function} callback
@param {Object} meta | [
"Adds",
"listener",
"to",
"event"
] | 0eddc236a3a5052b682ecc31dbb459772e653c14 | https://github.com/3axap4eHko/yyf/blob/0eddc236a3a5052b682ecc31dbb459772e653c14/src/event.js#L34-L37 | train |
3axap4eHko/yyf | src/event.js | deleteListener | function deleteListener(event, callback, idx) {
if ((idx = event.listeners.indexOf(callback)) >= 0) {
event.listeners.splice(idx, 1);
event.meta.delete(callback);
return true;
}
return false;
} | javascript | function deleteListener(event, callback, idx) {
if ((idx = event.listeners.indexOf(callback)) >= 0) {
event.listeners.splice(idx, 1);
event.meta.delete(callback);
return true;
}
return false;
} | [
"function",
"deleteListener",
"(",
"event",
",",
"callback",
",",
"idx",
")",
"{",
"if",
"(",
"(",
"idx",
"=",
"event",
".",
"listeners",
".",
"indexOf",
"(",
"callback",
")",
")",
">=",
"0",
")",
"{",
"event",
".",
"listeners",
".",
"splice",
"(",
... | Delete event listener returns true on success
@param {Object} event
@param {Function} callback
@param {number} [idx]
@returns {boolean} | [
"Delete",
"event",
"listener",
"returns",
"true",
"on",
"success"
] | 0eddc236a3a5052b682ecc31dbb459772e653c14 | https://github.com/3axap4eHko/yyf/blob/0eddc236a3a5052b682ecc31dbb459772e653c14/src/event.js#L74-L81 | train |
straits/babel | index.js | generateStraitsFunctions | function generateStraitsFunctions( {template}, path ) {
// testTraitSet( traitSet )
// it makes sure that all the `use traits * from` statements have a valid object as expression
const testTraitBuilder = template(`
function TEST_TRAIT_SET( traitSet ) {
if( ! traitSet || typeof traitSet === 'boolean' || typeof trait... | javascript | function generateStraitsFunctions( {template}, path ) {
// testTraitSet( traitSet )
// it makes sure that all the `use traits * from` statements have a valid object as expression
const testTraitBuilder = template(`
function TEST_TRAIT_SET( traitSet ) {
if( ! traitSet || typeof traitSet === 'boolean' || typeof trait... | [
"function",
"generateStraitsFunctions",
"(",
"{",
"template",
"}",
",",
"path",
")",
"{",
"// testTraitSet( traitSet )",
"// it makes sure that all the `use traits * from` statements have a valid object as expression",
"const",
"testTraitBuilder",
"=",
"template",
"(",
"`",
"\\`"... | prepend to `path` the functions we need to use traits | [
"prepend",
"to",
"path",
"the",
"functions",
"we",
"need",
"to",
"use",
"traits"
] | dbd2ee618520ccce30fc8d5621c833352e7fc6b3 | https://github.com/straits/babel/blob/dbd2ee618520ccce30fc8d5621c833352e7fc6b3/index.js#L16-L70 | train |
samuelbrian/node-dot-argv | dot-argv.js | overwrite | function overwrite(obj, defaults) {
var res = {};
var dFlat = collapse(defaults);
var oFlat = collapse(obj);
for (var key in dFlat) {
val(res, key, dFlat[key]);
}
for (var key in oFlat) {
val(res, key, oFlat[key]);
}
return res;
} | javascript | function overwrite(obj, defaults) {
var res = {};
var dFlat = collapse(defaults);
var oFlat = collapse(obj);
for (var key in dFlat) {
val(res, key, dFlat[key]);
}
for (var key in oFlat) {
val(res, key, oFlat[key]);
}
return res;
} | [
"function",
"overwrite",
"(",
"obj",
",",
"defaults",
")",
"{",
"var",
"res",
"=",
"{",
"}",
";",
"var",
"dFlat",
"=",
"collapse",
"(",
"defaults",
")",
";",
"var",
"oFlat",
"=",
"collapse",
"(",
"obj",
")",
";",
"for",
"(",
"var",
"key",
"in",
"... | Returns a new object with 'defaults' overwritten by entries in 'obj' | [
"Returns",
"a",
"new",
"object",
"with",
"defaults",
"overwritten",
"by",
"entries",
"in",
"obj"
] | 6c20962f747493c8ba99afd9f226c83a891b4be8 | https://github.com/samuelbrian/node-dot-argv/blob/6c20962f747493c8ba99afd9f226c83a891b4be8/dot-argv.js#L189-L200 | train |
jackspaniel/yukon | demo/homePage/homePage.js | function(req, res) {
this.debug('preProcessor called');
// MAGIC ALERT: if no templateName is specified the framework looks for [module name].[template extension] (default=.jade)
// example of specifying nodule properties at request time
if (req.path.indexOf('special') > -1) {
this.api... | javascript | function(req, res) {
this.debug('preProcessor called');
// MAGIC ALERT: if no templateName is specified the framework looks for [module name].[template extension] (default=.jade)
// example of specifying nodule properties at request time
if (req.path.indexOf('special') > -1) {
this.api... | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"this",
".",
"debug",
"(",
"'preProcessor called'",
")",
";",
"// MAGIC ALERT: if no templateName is specified the framework looks for [module name].[template extension] (default=.jade)",
"// example of specifying nodule properties at reque... | business logic before API calls are made | [
"business",
"logic",
"before",
"API",
"calls",
"are",
"made"
] | 7e5259126751dc5b604c6156d470f0a9ca9e3966 | https://github.com/jackspaniel/yukon/blob/7e5259126751dc5b604c6156d470f0a9ca9e3966/demo/homePage/homePage.js#L27-L37 | train | |
jackspaniel/yukon | demo/homePage/homePage.js | function(req, res) {
this.debug('postProcessor called');
// example of post API business logic
var clientMsg = res.yukon.data2.specialMsg || res.yukon.data2.msg;
// MAGIC ALERT: if no res.yukon.renderData isn't specified, the framework uses res.yukon.data1
// res.yukon.renderData is the... | javascript | function(req, res) {
this.debug('postProcessor called');
// example of post API business logic
var clientMsg = res.yukon.data2.specialMsg || res.yukon.data2.msg;
// MAGIC ALERT: if no res.yukon.renderData isn't specified, the framework uses res.yukon.data1
// res.yukon.renderData is the... | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"this",
".",
"debug",
"(",
"'postProcessor called'",
")",
";",
"// example of post API business logic",
"var",
"clientMsg",
"=",
"res",
".",
"yukon",
".",
"data2",
".",
"specialMsg",
"||",
"res",
".",
"yukon",
".... | business logic after all API calls return | [
"business",
"logic",
"after",
"all",
"API",
"calls",
"return"
] | 7e5259126751dc5b604c6156d470f0a9ca9e3966 | https://github.com/jackspaniel/yukon/blob/7e5259126751dc5b604c6156d470f0a9ca9e3966/demo/homePage/homePage.js#L40-L55 | train | |
trupin/crawlable | lib/processor.js | function (context, next) {
this._cache.read(context.cached._id, function (err, doc) {
if (err || !doc)
return next(err || new Error('Critical failure! A cache entry has mysteriously disappeared...'));
context.cached = doc;
// this should happen only for intern... | javascript | function (context, next) {
this._cache.read(context.cached._id, function (err, doc) {
if (err || !doc)
return next(err || new Error('Critical failure! A cache entry has mysteriously disappeared...'));
context.cached = doc;
// this should happen only for intern... | [
"function",
"(",
"context",
",",
"next",
")",
"{",
"this",
".",
"_cache",
".",
"read",
"(",
"context",
".",
"cached",
".",
"_id",
",",
"function",
"(",
"err",
",",
"doc",
")",
"{",
"if",
"(",
"err",
"||",
"!",
"doc",
")",
"return",
"next",
"(",
... | Read the cache entry.
It should exists, so if it doesn't, the cache has a critical failure.
@param {object} context
@param {function} next | [
"Read",
"the",
"cache",
"entry",
".",
"It",
"should",
"exists",
"so",
"if",
"it",
"doesn",
"t",
"the",
"cache",
"has",
"a",
"critical",
"failure",
"."
] | ef8c5b17a160d2d6ef35c3d70598fd42e89d47b9 | https://github.com/trupin/crawlable/blob/ef8c5b17a160d2d6ef35c3d70598fd42e89d47b9/lib/processor.js#L142-L155 | train | |
trupin/crawlable | lib/processor.js | function (context, next) {
if (context.options.force || !context.cached.template) {
this._tasksQueue.push(Processor._models.task(
context.cached._id, context.pathname, context.cached, !context.options.wait ? null :
function (err, cached) {
... | javascript | function (context, next) {
if (context.options.force || !context.cached.template) {
this._tasksQueue.push(Processor._models.task(
context.cached._id, context.pathname, context.cached, !context.options.wait ? null :
function (err, cached) {
... | [
"function",
"(",
"context",
",",
"next",
")",
"{",
"if",
"(",
"context",
".",
"options",
".",
"force",
"||",
"!",
"context",
".",
"cached",
".",
"template",
")",
"{",
"this",
".",
"_tasksQueue",
".",
"push",
"(",
"Processor",
".",
"_models",
".",
"ta... | Pushes a task in the queue, so it can be processed as soon as possible.
@param {object} context
@param {function} next | [
"Pushes",
"a",
"task",
"in",
"the",
"queue",
"so",
"it",
"can",
"be",
"processed",
"as",
"soon",
"as",
"possible",
"."
] | ef8c5b17a160d2d6ef35c3d70598fd42e89d47b9 | https://github.com/trupin/crawlable/blob/ef8c5b17a160d2d6ef35c3d70598fd42e89d47b9/lib/processor.js#L161-L175 | train | |
trupin/crawlable | lib/processor.js | function (context, next) {
if (context.cached.error)
return next(context.cached.error);
if (!context.cached.template)
return next(new errors.Internal("For unknowns reasons, the template couldn't have been processed."));
var opts = {
requests: context.cached.r... | javascript | function (context, next) {
if (context.cached.error)
return next(context.cached.error);
if (!context.cached.template)
return next(new errors.Internal("For unknowns reasons, the template couldn't have been processed."));
var opts = {
requests: context.cached.r... | [
"function",
"(",
"context",
",",
"next",
")",
"{",
"if",
"(",
"context",
".",
"cached",
".",
"error",
")",
"return",
"next",
"(",
"context",
".",
"cached",
".",
"error",
")",
";",
"if",
"(",
"!",
"context",
".",
"cached",
".",
"template",
")",
"ret... | The page has been rendered, so we check for errors and finalize the template.
@param {object} context
@param {function} next | [
"The",
"page",
"has",
"been",
"rendered",
"so",
"we",
"check",
"for",
"errors",
"and",
"finalize",
"the",
"template",
"."
] | ef8c5b17a160d2d6ef35c3d70598fd42e89d47b9 | https://github.com/trupin/crawlable/blob/ef8c5b17a160d2d6ef35c3d70598fd42e89d47b9/lib/processor.js#L181-L202 | train | |
redarrowlabs/strongback | bin/date/instant-date-view.js | InstantDateView | function InstantDateView(props) {
var empty = React.createElement("time", null, "-");
if (!props.date) {
return empty;
}
var isoDate = props.date.substring(0, 20);
if (!isoDate) {
return empty;
}
//Control characters:
//https://github.com/js-joda/js-joda/blob/e728951a850d... | javascript | function InstantDateView(props) {
var empty = React.createElement("time", null, "-");
if (!props.date) {
return empty;
}
var isoDate = props.date.substring(0, 20);
if (!isoDate) {
return empty;
}
//Control characters:
//https://github.com/js-joda/js-joda/blob/e728951a850d... | [
"function",
"InstantDateView",
"(",
"props",
")",
"{",
"var",
"empty",
"=",
"React",
".",
"createElement",
"(",
"\"time\"",
",",
"null",
",",
"\"-\"",
")",
";",
"if",
"(",
"!",
"props",
".",
"date",
")",
"{",
"return",
"empty",
";",
"}",
"var",
"isoD... | Displays the date of an instant, relative to the viewer. | [
"Displays",
"the",
"date",
"of",
"an",
"instant",
"relative",
"to",
"the",
"viewer",
"."
] | cdc8e0431a7fdf4faeb4016ba498b9146fc166aa | https://github.com/redarrowlabs/strongback/blob/cdc8e0431a7fdf4faeb4016ba498b9146fc166aa/bin/date/instant-date-view.js#L10-L34 | train |
tether/morph-stream | index.js | morph | function morph (value, input) {
const result = input || readable()
const cb = map[type(value)] || end
cb(result, value)
return new Proxy(result, {
get(target, key, receiver) {
if (key !== 'pipe') return target[key]
return function (dest) {
pump(result, dest)
return dest
}
... | javascript | function morph (value, input) {
const result = input || readable()
const cb = map[type(value)] || end
cb(result, value)
return new Proxy(result, {
get(target, key, receiver) {
if (key !== 'pipe') return target[key]
return function (dest) {
pump(result, dest)
return dest
}
... | [
"function",
"morph",
"(",
"value",
",",
"input",
")",
"{",
"const",
"result",
"=",
"input",
"||",
"readable",
"(",
")",
"const",
"cb",
"=",
"map",
"[",
"type",
"(",
"value",
")",
"]",
"||",
"end",
"cb",
"(",
"result",
",",
"value",
")",
"return",
... | Transform any value into a readable stream.
@param {String | Number | Boolean | Promises} value
@param {Boolean?} objectMode
@param {Stream?} readable
@return {Stream}
@api public | [
"Transform",
"any",
"value",
"into",
"a",
"readable",
"stream",
"."
] | 3f137a7449d276d05a4b0eb3fe1367fd02815c4f | https://github.com/tether/morph-stream/blob/3f137a7449d276d05a4b0eb3fe1367fd02815c4f/index.js#L43-L56 | train |
tether/morph-stream | index.js | type | function type (value) {
const proto = toString.call(value)
return proto.substring(8, proto.length - 1)
} | javascript | function type (value) {
const proto = toString.call(value)
return proto.substring(8, proto.length - 1)
} | [
"function",
"type",
"(",
"value",
")",
"{",
"const",
"proto",
"=",
"toString",
".",
"call",
"(",
"value",
")",
"return",
"proto",
".",
"substring",
"(",
"8",
",",
"proto",
".",
"length",
"-",
"1",
")",
"}"
] | Parse value type.
@param {Any} value
@return {String}
@api private | [
"Parse",
"value",
"type",
"."
] | 3f137a7449d276d05a4b0eb3fe1367fd02815c4f | https://github.com/tether/morph-stream/blob/3f137a7449d276d05a4b0eb3fe1367fd02815c4f/index.js#L81-L84 | train |
tether/morph-stream | index.js | end | function end (input, value) {
if (value != null) input.push(String(value))
input.push(null)
} | javascript | function end (input, value) {
if (value != null) input.push(String(value))
input.push(null)
} | [
"function",
"end",
"(",
"input",
",",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"input",
".",
"push",
"(",
"String",
"(",
"value",
")",
")",
"input",
".",
"push",
"(",
"null",
")",
"}"
] | End input stream with given value.
@param {Stream} input
@param {Any} value
@api private | [
"End",
"input",
"stream",
"with",
"given",
"value",
"."
] | 3f137a7449d276d05a4b0eb3fe1367fd02815c4f | https://github.com/tether/morph-stream/blob/3f137a7449d276d05a4b0eb3fe1367fd02815c4f/index.js#L95-L98 | train |
tether/morph-stream | index.js | object | function object (input, value) {
if (value instanceof Stream) stream(input, value)
else stringify(input, value)
} | javascript | function object (input, value) {
if (value instanceof Stream) stream(input, value)
else stringify(input, value)
} | [
"function",
"object",
"(",
"input",
",",
"value",
")",
"{",
"if",
"(",
"value",
"instanceof",
"Stream",
")",
"stream",
"(",
"input",
",",
"value",
")",
"else",
"stringify",
"(",
"input",
",",
"value",
")",
"}"
] | End input stream with given object.
@param {Stream} input
@param {Object} value
@api private | [
"End",
"input",
"stream",
"with",
"given",
"object",
"."
] | 3f137a7449d276d05a4b0eb3fe1367fd02815c4f | https://github.com/tether/morph-stream/blob/3f137a7449d276d05a4b0eb3fe1367fd02815c4f/index.js#L109-L112 | train |
tether/morph-stream | index.js | stringify | function stringify (input, value) {
input.push(JSON.stringify(value))
input.push(null)
} | javascript | function stringify (input, value) {
input.push(JSON.stringify(value))
input.push(null)
} | [
"function",
"stringify",
"(",
"input",
",",
"value",
")",
"{",
"input",
".",
"push",
"(",
"JSON",
".",
"stringify",
"(",
"value",
")",
")",
"input",
".",
"push",
"(",
"null",
")",
"}"
] | Stringify object and push down the pipe.
@param {Stream} input
@param {Object} value
@api private | [
"Stringify",
"object",
"and",
"push",
"down",
"the",
"pipe",
"."
] | 3f137a7449d276d05a4b0eb3fe1367fd02815c4f | https://github.com/tether/morph-stream/blob/3f137a7449d276d05a4b0eb3fe1367fd02815c4f/index.js#L123-L126 | train |
tether/morph-stream | index.js | stream | function stream (input, value) {
value.on('data', data => input.push(data))
value.on('error', err => error(input, err))
value.on('end', () => input.push(null))
} | javascript | function stream (input, value) {
value.on('data', data => input.push(data))
value.on('error', err => error(input, err))
value.on('end', () => input.push(null))
} | [
"function",
"stream",
"(",
"input",
",",
"value",
")",
"{",
"value",
".",
"on",
"(",
"'data'",
",",
"data",
"=>",
"input",
".",
"push",
"(",
"data",
")",
")",
"value",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"error",
"(",
"input",
",",
"err"... | End input stream with given stream.
@param {Stream} input
@param {Stream} value
@api private | [
"End",
"input",
"stream",
"with",
"given",
"stream",
"."
] | 3f137a7449d276d05a4b0eb3fe1367fd02815c4f | https://github.com/tether/morph-stream/blob/3f137a7449d276d05a4b0eb3fe1367fd02815c4f/index.js#L136-L140 | train |
tether/morph-stream | index.js | promise | function promise (input, value) {
value.then(val => {
morph(val, input)
}, reason => {
input.emit('error', reason)
})
} | javascript | function promise (input, value) {
value.then(val => {
morph(val, input)
}, reason => {
input.emit('error', reason)
})
} | [
"function",
"promise",
"(",
"input",
",",
"value",
")",
"{",
"value",
".",
"then",
"(",
"val",
"=>",
"{",
"morph",
"(",
"val",
",",
"input",
")",
"}",
",",
"reason",
"=>",
"{",
"input",
".",
"emit",
"(",
"'error'",
",",
"reason",
")",
"}",
")",
... | End input stream with given promise.
@param {Stream} input
@param {Promise} value
@api private | [
"End",
"input",
"stream",
"with",
"given",
"promise",
"."
] | 3f137a7449d276d05a4b0eb3fe1367fd02815c4f | https://github.com/tether/morph-stream/blob/3f137a7449d276d05a4b0eb3fe1367fd02815c4f/index.js#L151-L157 | train |
nodys/polymerize | lib/polymerize.js | polymerize | function polymerize(src, filepath) {
// Parse web-component source (extract dependency, optimize source, etc.)
var result = parseSource(src, filepath);
// Generate commonjs module source:
var src = [];
// Require imported web-components
result.imports.forEach(function(imp) {
src.push('require("'+imp+... | javascript | function polymerize(src, filepath) {
// Parse web-component source (extract dependency, optimize source, etc.)
var result = parseSource(src, filepath);
// Generate commonjs module source:
var src = [];
// Require imported web-components
result.imports.forEach(function(imp) {
src.push('require("'+imp+... | [
"function",
"polymerize",
"(",
"src",
",",
"filepath",
")",
"{",
"// Parse web-component source (extract dependency, optimize source, etc.)",
"var",
"result",
"=",
"parseSource",
"(",
"src",
",",
"filepath",
")",
";",
"// Generate commonjs module source:",
"var",
"src",
"... | Polymer vulcanization for browserify
@param {String} src
Web component html source
@param {String} filepath
Source filepath
@return {String}
CommonJS source with external import module and stylesheet
as `require()` calls | [
"Polymer",
"vulcanization",
"for",
"browserify"
] | 3f525ff5144c084ba4d501ab174828844f5a53dd | https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/polymerize.js#L34-L77 | train |
nodys/polymerize | lib/polymerize.js | parseSource | function parseSource(src, filepath) {
var result = {};
// Use whacko (cheerio) to parse html source
var $ = whacko.load(src);
// Extract sources and remove tags
result.imports = extractImports($);
result.scripts = extractScripts($);
result.inline = extractInline($)
// Inline external styleshe... | javascript | function parseSource(src, filepath) {
var result = {};
// Use whacko (cheerio) to parse html source
var $ = whacko.load(src);
// Extract sources and remove tags
result.imports = extractImports($);
result.scripts = extractScripts($);
result.inline = extractInline($)
// Inline external styleshe... | [
"function",
"parseSource",
"(",
"src",
",",
"filepath",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"// Use whacko (cheerio) to parse html source",
"var",
"$",
"=",
"whacko",
".",
"load",
"(",
"src",
")",
";",
"// Extract sources and remove tags",
"result",
"... | Parse a polymer component and return a parse result object
@param {String} src
Web-component html source
@param {String} filepath
Web-component filepath
@return {Object}
Parse result object:
- `imports` {Array}: Relative path to other components to require as commonjs module
- `scripts` {Array}: Relative path to oth... | [
"Parse",
"a",
"polymer",
"component",
"and",
"return",
"a",
"parse",
"result",
"object"
] | 3f525ff5144c084ba4d501ab174828844f5a53dd | https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/polymerize.js#L96-L118 | train |
nodys/polymerize | lib/polymerize.js | extractImports | function extractImports($) {
var imports = [];
$('link[rel=import][href]').each(function() {
var el = $(this);
var href = el.attr('href');
if(ABS.test(href)) return;
imports.push(/^\./.test(href) ? href : './' + href);
el.remove();
})
return imports;
} | javascript | function extractImports($) {
var imports = [];
$('link[rel=import][href]').each(function() {
var el = $(this);
var href = el.attr('href');
if(ABS.test(href)) return;
imports.push(/^\./.test(href) ? href : './' + href);
el.remove();
})
return imports;
} | [
"function",
"extractImports",
"(",
"$",
")",
"{",
"var",
"imports",
"=",
"[",
"]",
";",
"$",
"(",
"'link[rel=import][href]'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"el",
"=",
"$",
"(",
"this",
")",
";",
"var",
"href",
"=",
"el",
... | Extract relative path to other web-component sources
@param {Object} $
Whacko document
@return {Array} | [
"Extract",
"relative",
"path",
"to",
"other",
"web",
"-",
"component",
"sources"
] | 3f525ff5144c084ba4d501ab174828844f5a53dd | https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/polymerize.js#L128-L138 | train |
nodys/polymerize | lib/polymerize.js | extractScripts | function extractScripts($) {
var scripts = [];
$('script[src]').each(function() {
var el = $(this);
var src = el.attr('src');
if(ABS.test(src)) return;
scripts.push(/^\./.test(src) ? src : './' + src);
el.remove();
})
return scripts;
} | javascript | function extractScripts($) {
var scripts = [];
$('script[src]').each(function() {
var el = $(this);
var src = el.attr('src');
if(ABS.test(src)) return;
scripts.push(/^\./.test(src) ? src : './' + src);
el.remove();
})
return scripts;
} | [
"function",
"extractScripts",
"(",
"$",
")",
"{",
"var",
"scripts",
"=",
"[",
"]",
";",
"$",
"(",
"'script[src]'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"el",
"=",
"$",
"(",
"this",
")",
";",
"var",
"src",
"=",
"el",
".",
"at... | Extract relative path to other javascript sources
@param {Object} $
Whacko document
@return {Array} | [
"Extract",
"relative",
"path",
"to",
"other",
"javascript",
"sources"
] | 3f525ff5144c084ba4d501ab174828844f5a53dd | https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/polymerize.js#L149-L159 | train |
nodys/polymerize | lib/polymerize.js | extractInline | function extractInline($) {
var scripts = [];
$('script:not([src])').each(function() {
var el = $(this);
var src = el.text();
var closestPolymerElement = el.closest('polymer-element');
if(closestPolymerElement.length) {
src = fixPolymerInvocation(src, $(closestPolymerElement).attr('name'))
... | javascript | function extractInline($) {
var scripts = [];
$('script:not([src])').each(function() {
var el = $(this);
var src = el.text();
var closestPolymerElement = el.closest('polymer-element');
if(closestPolymerElement.length) {
src = fixPolymerInvocation(src, $(closestPolymerElement).attr('name'))
... | [
"function",
"extractInline",
"(",
"$",
")",
"{",
"var",
"scripts",
"=",
"[",
"]",
";",
"$",
"(",
"'script:not([src])'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"el",
"=",
"$",
"(",
"this",
")",
";",
"var",
"src",
"=",
"el",
".",
... | Extract inline javascript sources
@param {Object} $
Whacko document
@return {Array} | [
"Extract",
"inline",
"javascript",
"sources"
] | 3f525ff5144c084ba4d501ab174828844f5a53dd | https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/polymerize.js#L169-L182 | train |
nodys/polymerize | lib/polymerize.js | inlineStylesheet | function inlineStylesheet($, filepath) {
$('link[rel=stylesheet][href]').each(function() {
var el = $(this);
var href = el.attr('href');
if(ABS.test(href)) return;
var relpath = /^\./.test(href) ? href : './' + href;
var srcpath = resolve.sync(relpath, {
basedir : dirname(filepath... | javascript | function inlineStylesheet($, filepath) {
$('link[rel=stylesheet][href]').each(function() {
var el = $(this);
var href = el.attr('href');
if(ABS.test(href)) return;
var relpath = /^\./.test(href) ? href : './' + href;
var srcpath = resolve.sync(relpath, {
basedir : dirname(filepath... | [
"function",
"inlineStylesheet",
"(",
"$",
",",
"filepath",
")",
"{",
"$",
"(",
"'link[rel=stylesheet][href]'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"el",
"=",
"$",
"(",
"this",
")",
";",
"var",
"href",
"=",
"el",
".",
"attr",
"(",... | Inline external css sources
@param {Object} $
Whacko document
@return {Array} | [
"Inline",
"external",
"css",
"sources"
] | 3f525ff5144c084ba4d501ab174828844f5a53dd | https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/polymerize.js#L192-L209 | train |
nodys/polymerize | lib/polymerize.js | minifyHtml | function minifyHtml($) {
$('style:not([type]), style[type="text/css"]').each(function() {
var el = $(this);
el.text( new cleancss({noAdvanced: true}).minify(el.text()) )
});
$('*').contents().filter(function(_, node) {
if (node.type === 'comment'){
return true;
} else if (node.type === ... | javascript | function minifyHtml($) {
$('style:not([type]), style[type="text/css"]').each(function() {
var el = $(this);
el.text( new cleancss({noAdvanced: true}).minify(el.text()) )
});
$('*').contents().filter(function(_, node) {
if (node.type === 'comment'){
return true;
} else if (node.type === ... | [
"function",
"minifyHtml",
"(",
"$",
")",
"{",
"$",
"(",
"'style:not([type]), style[type=\"text/css\"]'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"el",
"=",
"$",
"(",
"this",
")",
";",
"el",
".",
"text",
"(",
"new",
"cleancss",
"(",
"{"... | Optimize html source
Inspired by https://github.com/Polymer/vulcanize
@param {Object} $
Whacko document | [
"Optimize",
"html",
"source"
] | 3f525ff5144c084ba4d501ab174828844f5a53dd | https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/polymerize.js#L255-L268 | train |
openpermissions/offer-generator | src/template.js | toJS | function toJS(entity) {
let data = {};
Object.keys(entity).forEach(key => {
if (_.some(customObjects, obj => entity[key] instanceof obj)) {
data[key] = toJS(entity[key])
} else {
data[key] = entity[key]
}
});
return data
} | javascript | function toJS(entity) {
let data = {};
Object.keys(entity).forEach(key => {
if (_.some(customObjects, obj => entity[key] instanceof obj)) {
data[key] = toJS(entity[key])
} else {
data[key] = entity[key]
}
});
return data
} | [
"function",
"toJS",
"(",
"entity",
")",
"{",
"let",
"data",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"entity",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"if",
"(",
"_",
".",
"some",
"(",
"customObjects",
",",
"obj",
"=>",
"entity",
"[",
... | Convert contents of entity into generic JS object that can be parsed by immutable
@param entity
@returns object | [
"Convert",
"contents",
"of",
"entity",
"into",
"generic",
"JS",
"object",
"that",
"can",
"be",
"parsed",
"by",
"immutable"
] | 94aa576996f1ce584974fbe250a4e316584570c0 | https://github.com/openpermissions/offer-generator/blob/94aa576996f1ce584974fbe250a4e316584570c0/src/template.js#L48-L58 | train |
pulseshift/ui5-lib-util | index.js | ui5Download | function ui5Download(sDownloadURL, sDownloadPath, sUI5Version, oOptions = {}) {
// check params
if (!sDownloadURL) {
return Promise.reject('No download URL provided')
}
if (!sDownloadPath) {
return Promise.reject('No download path provided')
}
if (!sUI5Version) {
return Promise.reject('No UI5 ve... | javascript | function ui5Download(sDownloadURL, sDownloadPath, sUI5Version, oOptions = {}) {
// check params
if (!sDownloadURL) {
return Promise.reject('No download URL provided')
}
if (!sDownloadPath) {
return Promise.reject('No download path provided')
}
if (!sUI5Version) {
return Promise.reject('No UI5 ve... | [
"function",
"ui5Download",
"(",
"sDownloadURL",
",",
"sDownloadPath",
",",
"sUI5Version",
",",
"oOptions",
"=",
"{",
"}",
")",
"{",
"// check params",
"if",
"(",
"!",
"sDownloadURL",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"'No download URL provided'"... | Download OpenUI5 repository from external URL and unzip.
@param {string} [sDownloadURL] Download URL of required archive.
@param {string} [sDownloadPath] Destination path for the download archive and extracted files.
@param {string} [sUI5Version] Version number of UI5 to create at <code>sDownloadPath</code> a subdirec... | [
"Download",
"OpenUI5",
"repository",
"from",
"external",
"URL",
"and",
"unzip",
"."
] | d257d57e80515adc9638bfeb80992997cf5357d4 | https://github.com/pulseshift/ui5-lib-util/blob/d257d57e80515adc9638bfeb80992997cf5357d4/index.js#L41-L135 | train |
pulseshift/ui5-lib-util | index.js | ui5CompileLessLib | function ui5CompileLessLib(oFile) {
const sDestDir = path.dirname(oFile.path)
const sFileName = oFile.path.split(path.sep).pop()
const sLessFileContent = oFile.contents.toString('utf8')
// options for less-openui5
const oOptions = {
lessInput: sLessFileContent,
rootPaths: [sDestDir],
rtl: true,
... | javascript | function ui5CompileLessLib(oFile) {
const sDestDir = path.dirname(oFile.path)
const sFileName = oFile.path.split(path.sep).pop()
const sLessFileContent = oFile.contents.toString('utf8')
// options for less-openui5
const oOptions = {
lessInput: sLessFileContent,
rootPaths: [sDestDir],
rtl: true,
... | [
"function",
"ui5CompileLessLib",
"(",
"oFile",
")",
"{",
"const",
"sDestDir",
"=",
"path",
".",
"dirname",
"(",
"oFile",
".",
"path",
")",
"const",
"sFileName",
"=",
"oFile",
".",
"path",
".",
"split",
"(",
"path",
".",
"sep",
")",
".",
"pop",
"(",
"... | Compile library.source.less and dependencies to library.css.
@param {Vinyl} [oFile] Vinyl file object of library.source.less.
@returns {Promise} Promise. | [
"Compile",
"library",
".",
"source",
".",
"less",
"and",
"dependencies",
"to",
"library",
".",
"css",
"."
] | d257d57e80515adc9638bfeb80992997cf5357d4 | https://github.com/pulseshift/ui5-lib-util/blob/d257d57e80515adc9638bfeb80992997cf5357d4/index.js#L683-L779 | train |
pulseshift/ui5-lib-util | index.js | transformPreloadJSON | function transformPreloadJSON(oFile) {
const oJSONRaw = oFile.contents.toString('utf8')
const sPrelaodJSON = `jQuery.sap.registerPreloadedModules(${oJSONRaw});`
oFile.contents = new Buffer(sPrelaodJSON)
return oFile
} | javascript | function transformPreloadJSON(oFile) {
const oJSONRaw = oFile.contents.toString('utf8')
const sPrelaodJSON = `jQuery.sap.registerPreloadedModules(${oJSONRaw});`
oFile.contents = new Buffer(sPrelaodJSON)
return oFile
} | [
"function",
"transformPreloadJSON",
"(",
"oFile",
")",
"{",
"const",
"oJSONRaw",
"=",
"oFile",
".",
"contents",
".",
"toString",
"(",
"'utf8'",
")",
"const",
"sPrelaodJSON",
"=",
"`",
"${",
"oJSONRaw",
"}",
"`",
"oFile",
".",
"contents",
"=",
"new",
"Buffe... | Transform library-preload.json content.
@param {Vinyl} [oFile] Vinyl file object of library-preload.json.
@returns {Vinyl} Transformed library-preload.json. | [
"Transform",
"library",
"-",
"preload",
".",
"json",
"content",
"."
] | d257d57e80515adc9638bfeb80992997cf5357d4 | https://github.com/pulseshift/ui5-lib-util/blob/d257d57e80515adc9638bfeb80992997cf5357d4/index.js#L787-L792 | train |
pulseshift/ui5-lib-util | index.js | replaceFilePlaceholders | function replaceFilePlaceholders(oFile, aReplacementRules) {
// parse file
const sRaw = oFile.contents.toString('utf8')
const sUpdatedFile = aReplacementRules.reduce((oResult, oRule) => {
return oResult.replace(oRule.identifier, oRule.content)
}, sRaw)
// update new raw content
oFile.contents = new Buf... | javascript | function replaceFilePlaceholders(oFile, aReplacementRules) {
// parse file
const sRaw = oFile.contents.toString('utf8')
const sUpdatedFile = aReplacementRules.reduce((oResult, oRule) => {
return oResult.replace(oRule.identifier, oRule.content)
}, sRaw)
// update new raw content
oFile.contents = new Buf... | [
"function",
"replaceFilePlaceholders",
"(",
"oFile",
",",
"aReplacementRules",
")",
"{",
"// parse file",
"const",
"sRaw",
"=",
"oFile",
".",
"contents",
".",
"toString",
"(",
"'utf8'",
")",
"const",
"sUpdatedFile",
"=",
"aReplacementRules",
".",
"reduce",
"(",
... | replace a list of placeholders with a list of string contents | [
"replace",
"a",
"list",
"of",
"placeholders",
"with",
"a",
"list",
"of",
"string",
"contents"
] | d257d57e80515adc9638bfeb80992997cf5357d4 | https://github.com/pulseshift/ui5-lib-util/blob/d257d57e80515adc9638bfeb80992997cf5357d4/index.js#L795-L807 | train |
ianmcgregor/boid | src/boid.js | arrive | function arrive(targetVec) {
const desiredVelocity = targetVec.clone().subtract(position);
desiredVelocity.normalize();
const distanceSq = position.distanceSq(targetVec);
if (distanceSq > arriveThresholdSq) {
desiredVelocity.scaleBy(maxSpeed);
} else {
co... | javascript | function arrive(targetVec) {
const desiredVelocity = targetVec.clone().subtract(position);
desiredVelocity.normalize();
const distanceSq = position.distanceSq(targetVec);
if (distanceSq > arriveThresholdSq) {
desiredVelocity.scaleBy(maxSpeed);
} else {
co... | [
"function",
"arrive",
"(",
"targetVec",
")",
"{",
"const",
"desiredVelocity",
"=",
"targetVec",
".",
"clone",
"(",
")",
".",
"subtract",
"(",
"position",
")",
";",
"desiredVelocity",
".",
"normalize",
"(",
")",
";",
"const",
"distanceSq",
"=",
"position",
... | seek until within arriveThreshold | [
"seek",
"until",
"within",
"arriveThreshold"
] | cef69760c5777898a389707905fc1ca387441bcd | https://github.com/ianmcgregor/boid/blob/cef69760c5777898a389707905fc1ca387441bcd/src/boid.js#L145-L161 | train |
ianmcgregor/boid | src/boid.js | wander | function wander() {
const center = velocity.clone().normalize().scaleBy(wanderDistance);
const offset = Vec2.get();
offset.set(wanderAngle, wanderRadius);
// offset.length = wanderRadius;
// offset.angle = wanderAngle;
wanderAngle += Math.random() * wanderRange - wanderR... | javascript | function wander() {
const center = velocity.clone().normalize().scaleBy(wanderDistance);
const offset = Vec2.get();
offset.set(wanderAngle, wanderRadius);
// offset.length = wanderRadius;
// offset.angle = wanderAngle;
wanderAngle += Math.random() * wanderRange - wanderR... | [
"function",
"wander",
"(",
")",
"{",
"const",
"center",
"=",
"velocity",
".",
"clone",
"(",
")",
".",
"normalize",
"(",
")",
".",
"scaleBy",
"(",
"wanderDistance",
")",
";",
"const",
"offset",
"=",
"Vec2",
".",
"get",
"(",
")",
";",
"offset",
".",
... | wander around, changing angle by a limited amount each tick | [
"wander",
"around",
"changing",
"angle",
"by",
"a",
"limited",
"amount",
"each",
"tick"
] | cef69760c5777898a389707905fc1ca387441bcd | https://github.com/ianmcgregor/boid/blob/cef69760c5777898a389707905fc1ca387441bcd/src/boid.js#L194-L210 | train |
ianmcgregor/boid | src/boid.js | avoid | function avoid(obstacles) {
for (let i = 0; i < obstacles.length; i++) {
const obstacle = obstacles[i];
const heading = velocity.clone().normalize();
// vec between obstacle and boid
const difference = obstacle.position.clone().subtract(position);
con... | javascript | function avoid(obstacles) {
for (let i = 0; i < obstacles.length; i++) {
const obstacle = obstacles[i];
const heading = velocity.clone().normalize();
// vec between obstacle and boid
const difference = obstacle.position.clone().subtract(position);
con... | [
"function",
"avoid",
"(",
"obstacles",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"obstacles",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"obstacle",
"=",
"obstacles",
"[",
"i",
"]",
";",
"const",
"heading",
"=",
"velocity",
... | gets a bit rough used in combination with seeking as the boid attempts to seek straight through an object while simultaneously trying to avoid it | [
"gets",
"a",
"bit",
"rough",
"used",
"in",
"combination",
"with",
"seeking",
"as",
"the",
"boid",
"attempts",
"to",
"seek",
"straight",
"through",
"an",
"object",
"while",
"simultaneously",
"trying",
"to",
"avoid",
"it"
] | cef69760c5777898a389707905fc1ca387441bcd | https://github.com/ianmcgregor/boid/blob/cef69760c5777898a389707905fc1ca387441bcd/src/boid.js#L214-L256 | train |
ianmcgregor/boid | src/boid.js | followPath | function followPath(path, loop) {
loop = !!loop;
const wayPoint = path[pathIndex];
if (!wayPoint) {
pathIndex = 0;
return boid;
}
if (position.distanceSq(wayPoint) < pathThresholdSq) {
if (pathIndex >= path.length - 1) {
if (lo... | javascript | function followPath(path, loop) {
loop = !!loop;
const wayPoint = path[pathIndex];
if (!wayPoint) {
pathIndex = 0;
return boid;
}
if (position.distanceSq(wayPoint) < pathThresholdSq) {
if (pathIndex >= path.length - 1) {
if (lo... | [
"function",
"followPath",
"(",
"path",
",",
"loop",
")",
"{",
"loop",
"=",
"!",
"!",
"loop",
";",
"const",
"wayPoint",
"=",
"path",
"[",
"pathIndex",
"]",
";",
"if",
"(",
"!",
"wayPoint",
")",
"{",
"pathIndex",
"=",
"0",
";",
"return",
"boid",
";",... | follow a path made up of an array or vectors | [
"follow",
"a",
"path",
"made",
"up",
"of",
"an",
"array",
"or",
"vectors"
] | cef69760c5777898a389707905fc1ca387441bcd | https://github.com/ianmcgregor/boid/blob/cef69760c5777898a389707905fc1ca387441bcd/src/boid.js#L259-L282 | train |
ianmcgregor/boid | src/boid.js | inSight | function inSight(b) {
if (position.distanceSq(b.position) > maxDistanceSq) {
return false;
}
const heading = velocity.clone().normalize();
const difference = b.position.clone().subtract(position);
const dotProd = difference.dotProduct(heading);
heading.dispos... | javascript | function inSight(b) {
if (position.distanceSq(b.position) > maxDistanceSq) {
return false;
}
const heading = velocity.clone().normalize();
const difference = b.position.clone().subtract(position);
const dotProd = difference.dotProduct(heading);
heading.dispos... | [
"function",
"inSight",
"(",
"b",
")",
"{",
"if",
"(",
"position",
".",
"distanceSq",
"(",
"b",
".",
"position",
")",
">",
"maxDistanceSq",
")",
"{",
"return",
"false",
";",
"}",
"const",
"heading",
"=",
"velocity",
".",
"clone",
"(",
")",
".",
"norma... | is boid close enough to be in sight and facing | [
"is",
"boid",
"close",
"enough",
"to",
"be",
"in",
"sight",
"and",
"facing"
] | cef69760c5777898a389707905fc1ca387441bcd | https://github.com/ianmcgregor/boid/blob/cef69760c5777898a389707905fc1ca387441bcd/src/boid.js#L285-L297 | train |
Subsets and Splits
SQL Console for semeru/code-text-javascript
Retrieves 20,000 non-null code samples labeled as JavaScript, providing a basic overview of the dataset.