id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
48,800 | 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 |
48,801 | 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 |
48,802 | 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",
".",
"call",
"(",
"this",
",",
"object",
")",
";",
"this",
".",
"bind",
"(",
"\"change\"",
",",
"function",
"(",
")",
"{",
"localStorage",
".",
"setItem",
"(",
"key",
",",
"JSON",
".",
"stringify",
"(",
"this",
")",
")",
";",
"}",
")",
";",
"}"
] | 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 |
48,803 | 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() { localStorage.setItem(key, JSON.stringify(this)); });
return array;
} | 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() { localStorage.setItem(key, JSON.stringify(this)); });
return array;
} | [
"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",
"(",
")",
"{",
"localStorage",
".",
"setItem",
"(",
"key",
",",
"JSON",
".",
"stringify",
"(",
"this",
")",
")",
";",
"}",
")",
";",
"return",
"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",
"data",
"."
] | e04fd060a4668abe58064267b1405e6a40f8a6f2 | https://github.com/arendjr/laces.js/blob/e04fd060a4668abe58064267b1405e6a40f8a6f2/laces.local.js#L35-L48 |
48,804 | 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('pageready', _store);
}
};
} | javascript | function createCompleteCallback(name) {
return function(data) {
_store[name] = data;
var allCallbacksComplete = Object.keys(_store).reduce(isStoreValid, true);
if (allCallbacksComplete) {
clearTimeout(pageReadyWarning);
ceddl.emitEvent('pageready', _store);
}
};
} | [
"function",
"createCompleteCallback",
"(",
"name",
")",
"{",
"return",
"function",
"(",
"data",
")",
"{",
"_store",
"[",
"name",
"]",
"=",
"data",
";",
"var",
"allCallbacksComplete",
"=",
"Object",
".",
"keys",
"(",
"_store",
")",
".",
"reduce",
"(",
"isStoreValid",
",",
"true",
")",
";",
"if",
"(",
"allCallbacksComplete",
")",
"{",
"clearTimeout",
"(",
"pageReadyWarning",
")",
";",
"ceddl",
".",
"emitEvent",
"(",
"'pageready'",
",",
"_store",
")",
";",
"}",
"}",
";",
"}"
] | 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",
"pageready",
"event",
"should",
"that",
"be",
"the",
"case",
"."
] | 0e018d463107a0b631c317d7bf372aa9e194b7da | https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/page-ready.js#L42-L52 |
48,805 | 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 anything dispatch event when the page is ready.
if (!eventNames || eventNames.length === 0) {
pageReady(function() {
ceddl.emitEvent('pageready', _store);
});
return;
}
startWarningTimeout();
if (!Array.isArray(eventNames)) {
// Split on whitespace and remove empty entries.
eventNames = eventNames.split(' ').filter(function(value) {
return !!value;
});
}
if(_el) {
_el.setAttribute('data-page-ready', eventNames.join(' '));
}
// Create the new state
eventNames.forEach(function(name) {
_store[name] = false;
});
_listeners = eventNames.map(setCompleteListener);
} | 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 anything dispatch event when the page is ready.
if (!eventNames || eventNames.length === 0) {
pageReady(function() {
ceddl.emitEvent('pageready', _store);
});
return;
}
startWarningTimeout();
if (!Array.isArray(eventNames)) {
// Split on whitespace and remove empty entries.
eventNames = eventNames.split(' ').filter(function(value) {
return !!value;
});
}
if(_el) {
_el.setAttribute('data-page-ready', eventNames.join(' '));
}
// Create the new state
eventNames.forEach(function(name) {
_store[name] = false;
});
_listeners = eventNames.map(setCompleteListener);
} | [
"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 anything dispatch event when the page is ready.",
"if",
"(",
"!",
"eventNames",
"||",
"eventNames",
".",
"length",
"===",
"0",
")",
"{",
"pageReady",
"(",
"function",
"(",
")",
"{",
"ceddl",
".",
"emitEvent",
"(",
"'pageready'",
",",
"_store",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"startWarningTimeout",
"(",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"eventNames",
")",
")",
"{",
"// Split on whitespace and remove empty entries.",
"eventNames",
"=",
"eventNames",
".",
"split",
"(",
"' '",
")",
".",
"filter",
"(",
"function",
"(",
"value",
")",
"{",
"return",
"!",
"!",
"value",
";",
"}",
")",
";",
"}",
"if",
"(",
"_el",
")",
"{",
"_el",
".",
"setAttribute",
"(",
"'data-page-ready'",
",",
"eventNames",
".",
"join",
"(",
"' '",
")",
")",
";",
"}",
"// Create the new state",
"eventNames",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"_store",
"[",
"name",
"]",
"=",
"false",
";",
"}",
")",
";",
"_listeners",
"=",
"eventNames",
".",
"map",
"(",
"setCompleteListener",
")",
";",
"}"
] | 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",
"the",
"pageready",
"event",
"."
] | 0e018d463107a0b631c317d7bf372aa9e194b7da | https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/page-ready.js#L83-L117 |
48,806 | 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",
".",
"description",
",",
"generator",
":",
"'node-comics-scrape'",
",",
"feed_url",
":",
"meta",
".",
"xmlUrl",
",",
"site_url",
":",
"meta",
".",
"link",
",",
"pubDate",
":",
"meta",
".",
"pubDate",
",",
"ttl",
":",
"ONE_DAY_MINUTES",
"}",
")",
";",
"}"
] | out-feed | [
"out",
"-",
"feed"
] | 269161d83c10381b70f0d423cc8d212ddff543d7 | https://github.com/leesei/node-comics-feed/blob/269161d83c10381b70f0d423cc8d212ddff543d7/lib/main.js#L27-L38 |
48,807 | 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 target[key] !== optionsValueType);
if (shouldReplace) {
target[key] = options[key];
} else if (optionsValueType === 'object') {
// go deep, don't care about loops here, we are simple API!:
target[key] = merge(target[key], options[key]);
}
}
}
}
return target;
} | 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 target[key] !== optionsValueType);
if (shouldReplace) {
target[key] = options[key];
} else if (optionsValueType === 'object') {
// go deep, don't care about loops here, we are simple API!:
target[key] = merge(target[key], options[key]);
}
}
}
}
return target;
} | [
"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",
"target",
"[",
"key",
"]",
"!==",
"optionsValueType",
")",
";",
"if",
"(",
"shouldReplace",
")",
"{",
"target",
"[",
"key",
"]",
"=",
"options",
"[",
"key",
"]",
";",
"}",
"else",
"if",
"(",
"optionsValueType",
"===",
"'object'",
")",
"{",
"// go deep, don't care about loops here, we are simple API!:",
"target",
"[",
"key",
"]",
"=",
"merge",
"(",
"target",
"[",
"key",
"]",
",",
"options",
"[",
"key",
"]",
")",
";",
"}",
"}",
"}",
"}",
"return",
"target",
";",
"}"
] | 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 |
48,808 | 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",
"]",
"=",
"shuffled",
"[",
"r",
"]",
";",
"shuffled",
"[",
"r",
"]",
"=",
"v",
";",
"return",
"acc",
"+",
"1",
";",
"}",
",",
"0",
")",
";",
"return",
"shuffled",
";",
"}"
] | 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 |
|
48,809 | 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 = new RegExp(REGEXP_ANSI, 'gm');
$match = $str.match($regex);
if (!!$match)
{
$str = $str.substr($match[0].length);
$match = true;
}
}
// trim extra seperator space when available
if ($match && $str.substr(0, 1) === ' ')
{
$str = $str.substr(1);
}
return $str;
} | 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 = new RegExp(REGEXP_ANSI, 'gm');
$match = $str.match($regex);
if (!!$match)
{
$str = $str.substr($match[0].length);
$match = true;
}
}
// trim extra seperator space when available
if ($match && $str.substr(0, 1) === ' ')
{
$str = $str.substr(1);
}
return $str;
} | [
"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",
"=",
"new",
"RegExp",
"(",
"REGEXP_ANSI",
",",
"'gm'",
")",
";",
"$match",
"=",
"$str",
".",
"match",
"(",
"$regex",
")",
";",
"if",
"(",
"!",
"!",
"$match",
")",
"{",
"$str",
"=",
"$str",
".",
"substr",
"(",
"$match",
"[",
"0",
"]",
".",
"length",
")",
";",
"$match",
"=",
"true",
";",
"}",
"}",
"// trim extra seperator space when available",
"if",
"(",
"$match",
"&&",
"$str",
".",
"substr",
"(",
"0",
",",
"1",
")",
"===",
"' '",
")",
"{",
"$str",
"=",
"$str",
".",
"substr",
"(",
"1",
")",
";",
"}",
"return",
"$str",
";",
"}"
] | 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",
"searches",
"for",
"color",
"coded",
"timestamps",
"."
] | ccc958e47de73dffdf7d4c0d62766e6d85e5b066 | https://github.com/roeldev-deprecated-stuff/log-interceptor/blob/ccc958e47de73dffdf7d4c0d62766e6d85e5b066/lib/utils.js#L35-L64 |
|
48,810 | 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;
return Promise.reject(err);
});
} catch (e) {
return Promise.reject(e);
}
} | 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;
return Promise.reject(err);
});
} catch (e) {
return Promise.reject(e);
}
} | [
"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",
";",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"e",
")",
";",
"}",
"}"
] | 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 |
48,811 | 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.title.testTotalPasses++
that.title.passed++
if(that.groupEnded) {
that.mainGroup.title.testTotalFailures--
that.groupEndCountSubtracted = true // marks that failures were subtracted after the test finished (so successes can be later subtracted correctly if need be)
}
} else if(that.groupEndCountSubtracted || that.count - 1 === that.expected) {
that.title.passed--
that.mainGroup.title.testTotalPasses--
if(that.groupEnded) {
that.mainGroup.title.testTotalFailures++
}
}
}
} | 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.title.testTotalPasses++
that.title.passed++
if(that.groupEnded) {
that.mainGroup.title.testTotalFailures--
that.groupEndCountSubtracted = true // marks that failures were subtracted after the test finished (so successes can be later subtracted correctly if need be)
}
} else if(that.groupEndCountSubtracted || that.count - 1 === that.expected) {
that.title.passed--
that.mainGroup.title.testTotalPasses--
if(that.groupEnded) {
that.mainGroup.title.testTotalFailures++
}
}
}
} | [
"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",
".",
"title",
".",
"testTotalPasses",
"++",
"that",
".",
"title",
".",
"passed",
"++",
"if",
"(",
"that",
".",
"groupEnded",
")",
"{",
"that",
".",
"mainGroup",
".",
"title",
".",
"testTotalFailures",
"--",
"that",
".",
"groupEndCountSubtracted",
"=",
"true",
"// marks that failures were subtracted after the test finished (so successes can be later subtracted correctly if need be)",
"}",
"}",
"else",
"if",
"(",
"that",
".",
"groupEndCountSubtracted",
"||",
"that",
".",
"count",
"-",
"1",
"===",
"that",
".",
"expected",
")",
"{",
"that",
".",
"title",
".",
"passed",
"--",
"that",
".",
"mainGroup",
".",
"title",
".",
"testTotalPasses",
"--",
"if",
"(",
"that",
".",
"groupEnded",
")",
"{",
"that",
".",
"mainGroup",
".",
"title",
".",
"testTotalFailures",
"++",
"}",
"}",
"}",
"}"
] | 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 |
48,812 | 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",
".",
"length",
"===",
"1",
"}"
] | 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 |
48,813 | 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",
"=",
"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",
")",
"}",
"}"
] | 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 |
48,814 | 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()
.find('code').addClass('blurred')
.filter('.current-fragment').removeClass('blurred');
}
} | 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()
.find('code').addClass('blurred')
.filter('.current-fragment').removeClass('blurred');
}
} | [
"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",
"(",
")",
".",
"find",
"(",
"'code'",
")",
".",
"addClass",
"(",
"'blurred'",
")",
".",
"filter",
"(",
"'.current-fragment'",
")",
".",
"removeClass",
"(",
"'blurred'",
")",
";",
"}",
"}"
] | set up fragment highlighting | [
"set",
"up",
"fragment",
"highlighting"
] | 64d5e605d51d5cb3c588258b5738128ca56634bf | https://github.com/TotallyRadRichard/jumbotron/blob/64d5e605d51d5cb3c588258b5738128ca56634bf/public/js/reveal/jumbotron.reveal.js#L86-L100 |
|
48,815 | 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",
";",
"}",
"else",
"{",
"len",
"=",
"content",
".",
"length",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"fragment",
".",
"appendChild",
"(",
"content",
"[",
"i",
"]",
")",
";",
"}",
"return",
"fragment",
";",
"}",
"}"
] | 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 |
48,816 | 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', start) + 1;
doc = doc.substring(0, start) + doc.substring(end);
}
});
return doc;
} | 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', start) + 1;
doc = doc.substring(0, start) + doc.substring(end);
}
});
return doc;
} | [
"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'",
",",
"start",
")",
"+",
"1",
";",
"doc",
"=",
"doc",
".",
"substring",
"(",
"0",
",",
"start",
")",
"+",
"doc",
".",
"substring",
"(",
"end",
")",
";",
"}",
"}",
")",
";",
"return",
"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 |
|
48,817 | 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, remove <code>, fix escape chars
functionLine = '### \'' + functionLine.split('#').join('.').split('<code>').join('').split('</code>').join('').split('&.').join('&#') + '\'';
//remove links
var foundLinks = false;
var field;
var start;
var end;
do {
end = functionLine.indexOf('](');
if (end !== -1) {
start = functionLine.lastIndexOf('[', end);
field = functionLine.substring(start + 1, end);
end = functionLine.indexOf(')', start) + 1;
functionLine = functionLine.substring(0, start) + field + functionLine.substring(end);
foundLinks = true;
} else {
foundLinks = false;
}
} while (foundLinks);
}
if (functionLine && postHook && (typeof postHook === 'function')) {
functionLine = postHook(functionLine);
}
doc = functionLine + doc.substring(index);
return doc;
} | 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, remove <code>, fix escape chars
functionLine = '### \'' + functionLine.split('#').join('.').split('<code>').join('').split('</code>').join('').split('&.').join('&#') + '\'';
//remove links
var foundLinks = false;
var field;
var start;
var end;
do {
end = functionLine.indexOf('](');
if (end !== -1) {
start = functionLine.lastIndexOf('[', end);
field = functionLine.substring(start + 1, end);
end = functionLine.indexOf(')', start) + 1;
functionLine = functionLine.substring(0, start) + field + functionLine.substring(end);
foundLinks = true;
} else {
foundLinks = false;
}
} while (foundLinks);
}
if (functionLine && postHook && (typeof postHook === 'function')) {
functionLine = postHook(functionLine);
}
doc = functionLine + doc.substring(index);
return doc;
} | [
"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, remove <code>, fix escape chars",
"functionLine",
"=",
"'### \\''",
"+",
"functionLine",
".",
"split",
"(",
"'#'",
")",
".",
"join",
"(",
"'.'",
")",
".",
"split",
"(",
"'<code>'",
")",
".",
"join",
"(",
"''",
")",
".",
"split",
"(",
"'</code>'",
")",
".",
"join",
"(",
"''",
")",
".",
"split",
"(",
"'&.'",
")",
".",
"join",
"(",
"'&#'",
")",
"+",
"'\\''",
";",
"//remove links",
"var",
"foundLinks",
"=",
"false",
";",
"var",
"field",
";",
"var",
"start",
";",
"var",
"end",
";",
"do",
"{",
"end",
"=",
"functionLine",
".",
"indexOf",
"(",
"']('",
")",
";",
"if",
"(",
"end",
"!==",
"-",
"1",
")",
"{",
"start",
"=",
"functionLine",
".",
"lastIndexOf",
"(",
"'['",
",",
"end",
")",
";",
"field",
"=",
"functionLine",
".",
"substring",
"(",
"start",
"+",
"1",
",",
"end",
")",
";",
"end",
"=",
"functionLine",
".",
"indexOf",
"(",
"')'",
",",
"start",
")",
"+",
"1",
";",
"functionLine",
"=",
"functionLine",
".",
"substring",
"(",
"0",
",",
"start",
")",
"+",
"field",
"+",
"functionLine",
".",
"substring",
"(",
"end",
")",
";",
"foundLinks",
"=",
"true",
";",
"}",
"else",
"{",
"foundLinks",
"=",
"false",
";",
"}",
"}",
"while",
"(",
"foundLinks",
")",
";",
"}",
"if",
"(",
"functionLine",
"&&",
"postHook",
"&&",
"(",
"typeof",
"postHook",
"===",
"'function'",
")",
")",
"{",
"functionLine",
"=",
"postHook",
"(",
"functionLine",
")",
";",
"}",
"doc",
"=",
"functionLine",
"+",
"doc",
".",
"substring",
"(",
"index",
")",
";",
"return",
"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
@returns {String} The updated doc | [
"Returns",
"the",
"doc",
"with",
"updated",
"signature",
"line",
"."
] | 42dd07a8a3b2c49db71f489e08b94ac7279007a3 | https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/apidoc2readme.js#L52-L90 |
|
48,818 | 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.indexOf(linkString, index + 1);
if (index === -1) {
grunt.fail.warn(new Error('API link: ' + apiDocLink + ' not found.'));
}
}
return index;
} | 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.indexOf(linkString, index + 1);
if (index === -1) {
grunt.fail.warn(new Error('API link: ' + apiDocLink + ' not found.'));
}
}
return index;
} | [
"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",
".",
"indexOf",
"(",
"linkString",
",",
"index",
"+",
"1",
")",
";",
"if",
"(",
"index",
"===",
"-",
"1",
")",
"{",
"grunt",
".",
"fail",
".",
"warn",
"(",
"new",
"Error",
"(",
"'API link: '",
"+",
"apiDocLink",
"+",
"' not found.'",
")",
")",
";",
"}",
"}",
"return",
"index",
";",
"}"
] | 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 location of the requested link | [
"Returns",
"the",
"link",
"location",
"in",
"the",
"docs",
"."
] | 42dd07a8a3b2c49db71f489e08b94ac7279007a3 | https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/apidoc2readme.js#L103-L118 |
|
48,819 | 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[cleanName] = pos;
}
if (!(romaji in dataIndex)) {
dataIndex[romaji] = pos;
}
// +1 for the \n
pos += line.length + 1;
});
callback(null, this);
} | 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[cleanName] = pos;
}
if (!(romaji in dataIndex)) {
dataIndex[romaji] = pos;
}
// +1 for the \n
pos += line.length + 1;
});
callback(null, this);
} | [
"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",
"[",
"cleanName",
"]",
"=",
"pos",
";",
"}",
"if",
"(",
"!",
"(",
"romaji",
"in",
"dataIndex",
")",
")",
"{",
"dataIndex",
"[",
"romaji",
"]",
"=",
"pos",
";",
"}",
"// +1 for the \\n",
"pos",
"+=",
"line",
".",
"length",
"+",
"1",
";",
"}",
")",
";",
"callback",
"(",
"null",
",",
"this",
")",
";",
"}"
] | 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 |
|
48,820 | 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);
}));
return fiber.wait();
} | 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);
}));
return fiber.wait();
} | [
"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",
")",
";",
"}",
")",
")",
";",
"return",
"fiber",
".",
"wait",
"(",
")",
";",
"}"
] | 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 |
48,821 | 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",
")",
";",
"spec",
"=",
"isProxyEndpointAvailable",
"(",
"spec",
")",
";",
"writeFileSync",
"(",
"'server.mustache'",
",",
"spec",
",",
"'server.js'",
")",
";",
"writeFileSync",
"(",
"'package.mustache'",
",",
"spec",
",",
"'package.json'",
")",
";",
"}"
] | Generates the project files | [
"Generates",
"the",
"project",
"files"
] | e74b63811675c9a033e02f58604f270fac388dde | https://github.com/Raathigesh/AtmoExpressES5Generator/blob/e74b63811675c9a033e02f58604f270fac388dde/src/index.js#L9-L17 |
48,822 | 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.eval = true;
} else {
endpoint.response.content = endpoint.response.content.replace(/(\r\n|\n|\r)/gm,"");
}
endpoint.httpMethod = endpoint.method.toLowerCase();
}
return spec;
} | 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.eval = true;
} else {
endpoint.response.content = endpoint.response.content.replace(/(\r\n|\n|\r)/gm,"");
}
endpoint.httpMethod = endpoint.method.toLowerCase();
}
return spec;
} | [
"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",
".",
"eval",
"=",
"true",
";",
"}",
"else",
"{",
"endpoint",
".",
"response",
".",
"content",
"=",
"endpoint",
".",
"response",
".",
"content",
".",
"replace",
"(",
"/",
"(\\r\\n|\\n|\\r)",
"/",
"gm",
",",
"\"\"",
")",
";",
"}",
"endpoint",
".",
"httpMethod",
"=",
"endpoint",
".",
"method",
".",
"toLowerCase",
"(",
")",
";",
"}",
"return",
"spec",
";",
"}"
] | 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 |
48,823 | 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";
endpoint.payload = endpoint.payload.replace(/(\r\n|\n|\r)/gm,"");
}
return spec;
} | 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";
endpoint.payload = endpoint.payload.replace(/(\r\n|\n|\r)/gm,"");
}
return spec;
} | [
"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\"",
";",
"endpoint",
".",
"payload",
"=",
"endpoint",
".",
"payload",
".",
"replace",
"(",
"/",
"(\\r\\n|\\n|\\r)",
"/",
"gm",
",",
"\"\"",
")",
";",
"}",
"return",
"spec",
";",
"}"
] | 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 |
48,824 | 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'",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"path",
".",
"join",
"(",
"projectDirectory",
",",
"filename",
")",
",",
"Mustache",
".",
"render",
"(",
"templateString",
",",
"templateOption",
")",
")",
";",
"}"
] | 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 |
48,825 | 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",
".",
"get",
"(",
"context",
")",
";",
"if",
"(",
"!",
"events",
"[",
"eventName",
"]",
")",
"{",
"events",
"[",
"eventName",
"]",
"=",
"{",
"listeners",
":",
"[",
"]",
",",
"meta",
":",
"new",
"WeakMap",
"(",
")",
"}",
";",
"}",
"return",
"events",
"[",
"eventName",
"]",
";",
"}"
] | 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 |
48,826 | 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 |
48,827 | 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",
"(",
"idx",
",",
"1",
")",
";",
"event",
".",
"meta",
".",
"delete",
"(",
"callback",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | 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 |
48,828 | 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 traitSet === 'number' || typeof traitSet === 'string' ) {
throw new Error(\`\${traitSet} cannot be used as a trait set.\`);
}
}
`);
// getSymbol( targetSymName, ...traits )
// looks for `targetSymName` inside `traits`, and returns the symbol, if found
const getSymbolBuilder = template(`
function GET_SYMBOL( targetSymName, ...traitSets ) {
let symbol;
traitSets.forEach( traitSet=>{
const sym = traitSet[targetSymName];
if( typeof sym === 'symbol' ) {
if( !! symbol && symbol !== sym ) {
throw new Error(\`Symbol \${targetSymName} offered by multiple trait sets.\`);
}
symbol = sym;
}
});
if( ! symbol ) {
throw new Error(\`No trait set is providing symbol \${targetSymName}.\`);
}
return symbol;
}
`);
// implSymbol( target, sym, value ): `target.*[sym] = value`
const implSymbolBuilder = template(`
function IMPL_SYMBOL( target, sym, value ) {
Object.defineProperty( target, sym, {value, configurable:true} );
return target[sym];
}
`);
// generating identifiers for the above functions
const identifiers = {
testTraitSet: path.scope.generateUidIdentifier(`testTraitSet`),
getSymbol: path.scope.generateUidIdentifier(`getSymbol`),
implSymbol: path.scope.generateUidIdentifier(`implSymbol`),
};
// adding to the AST the code for the above functions
path.unshiftContainer('body', testTraitBuilder({ TEST_TRAIT_SET:identifiers.testTraitSet }) );
path.unshiftContainer('body', getSymbolBuilder({ GET_SYMBOL:identifiers.getSymbol }) );
path.unshiftContainer('body', implSymbolBuilder({ IMPL_SYMBOL:identifiers.implSymbol }) );
// returning the identifiers
return identifiers;
} | 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 traitSet === 'number' || typeof traitSet === 'string' ) {
throw new Error(\`\${traitSet} cannot be used as a trait set.\`);
}
}
`);
// getSymbol( targetSymName, ...traits )
// looks for `targetSymName` inside `traits`, and returns the symbol, if found
const getSymbolBuilder = template(`
function GET_SYMBOL( targetSymName, ...traitSets ) {
let symbol;
traitSets.forEach( traitSet=>{
const sym = traitSet[targetSymName];
if( typeof sym === 'symbol' ) {
if( !! symbol && symbol !== sym ) {
throw new Error(\`Symbol \${targetSymName} offered by multiple trait sets.\`);
}
symbol = sym;
}
});
if( ! symbol ) {
throw new Error(\`No trait set is providing symbol \${targetSymName}.\`);
}
return symbol;
}
`);
// implSymbol( target, sym, value ): `target.*[sym] = value`
const implSymbolBuilder = template(`
function IMPL_SYMBOL( target, sym, value ) {
Object.defineProperty( target, sym, {value, configurable:true} );
return target[sym];
}
`);
// generating identifiers for the above functions
const identifiers = {
testTraitSet: path.scope.generateUidIdentifier(`testTraitSet`),
getSymbol: path.scope.generateUidIdentifier(`getSymbol`),
implSymbol: path.scope.generateUidIdentifier(`implSymbol`),
};
// adding to the AST the code for the above functions
path.unshiftContainer('body', testTraitBuilder({ TEST_TRAIT_SET:identifiers.testTraitSet }) );
path.unshiftContainer('body', getSymbolBuilder({ GET_SYMBOL:identifiers.getSymbol }) );
path.unshiftContainer('body', implSymbolBuilder({ IMPL_SYMBOL:identifiers.implSymbol }) );
// returning the identifiers
return identifiers;
} | [
"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",
"(",
"`",
"\\`",
"\\$",
"\\`",
"`",
")",
";",
"// getSymbol( targetSymName, ...traits )",
"// looks for `targetSymName` inside `traits`, and returns the symbol, if found",
"const",
"getSymbolBuilder",
"=",
"template",
"(",
"`",
"\\`",
"\\$",
"\\`",
"\\`",
"\\$",
"\\`",
"`",
")",
";",
"// implSymbol( target, sym, value ): `target.*[sym] = value`",
"const",
"implSymbolBuilder",
"=",
"template",
"(",
"`",
"`",
")",
";",
"// generating identifiers for the above functions",
"const",
"identifiers",
"=",
"{",
"testTraitSet",
":",
"path",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"`",
"`",
")",
",",
"getSymbol",
":",
"path",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"`",
"`",
")",
",",
"implSymbol",
":",
"path",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"`",
"`",
")",
",",
"}",
";",
"// adding to the AST the code for the above functions",
"path",
".",
"unshiftContainer",
"(",
"'body'",
",",
"testTraitBuilder",
"(",
"{",
"TEST_TRAIT_SET",
":",
"identifiers",
".",
"testTraitSet",
"}",
")",
")",
";",
"path",
".",
"unshiftContainer",
"(",
"'body'",
",",
"getSymbolBuilder",
"(",
"{",
"GET_SYMBOL",
":",
"identifiers",
".",
"getSymbol",
"}",
")",
")",
";",
"path",
".",
"unshiftContainer",
"(",
"'body'",
",",
"implSymbolBuilder",
"(",
"{",
"IMPL_SYMBOL",
":",
"identifiers",
".",
"implSymbol",
"}",
")",
")",
";",
"// returning the identifiers",
"return",
"identifiers",
";",
"}"
] | 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 |
48,829 | 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",
"dFlat",
")",
"{",
"val",
"(",
"res",
",",
"key",
",",
"dFlat",
"[",
"key",
"]",
")",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"oFlat",
")",
"{",
"val",
"(",
"res",
",",
"key",
",",
"oFlat",
"[",
"key",
"]",
")",
";",
"}",
"return",
"res",
";",
"}"
] | 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 |
48,830 | 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.apiCalls[1].params = {isSpecial: true}; // add extra param to existing API call
this.templateName = 'altHomePage.jade'; // select alternate template
}
} | 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.apiCalls[1].params = {isSpecial: true}; // add extra param to existing API call
this.templateName = 'altHomePage.jade'; // select alternate template
}
} | [
"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",
".",
"apiCalls",
"[",
"1",
"]",
".",
"params",
"=",
"{",
"isSpecial",
":",
"true",
"}",
";",
"// add extra param to existing API call",
"this",
".",
"templateName",
"=",
"'altHomePage.jade'",
";",
"// select alternate template",
"}",
"}"
] | 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 |
|
48,831 | 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 base object sent to jade template
res.yukon.renderData = {
globalNav: res.yukon.globalNav,
cmsData: res.yukon.data1,
myData: res.yukon.data2,
clientMsg: clientMsg
};
} | 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 base object sent to jade template
res.yukon.renderData = {
globalNav: res.yukon.globalNav,
cmsData: res.yukon.data1,
myData: res.yukon.data2,
clientMsg: clientMsg
};
} | [
"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 base object sent to jade template",
"res",
".",
"yukon",
".",
"renderData",
"=",
"{",
"globalNav",
":",
"res",
".",
"yukon",
".",
"globalNav",
",",
"cmsData",
":",
"res",
".",
"yukon",
".",
"data1",
",",
"myData",
":",
"res",
".",
"yukon",
".",
"data2",
",",
"clientMsg",
":",
"clientMsg",
"}",
";",
"}"
] | 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 |
|
48,832 | 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 internal phantom errors, not client javascript errors.
if (context.cached.error) {
this.logger.warn('The last try gave us an error, try to recompute.', { error: context.cached.error });
context.options.force = true;
context.options.wait = true;
}
next(null);
});
} | 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 internal phantom errors, not client javascript errors.
if (context.cached.error) {
this.logger.warn('The last try gave us an error, try to recompute.', { error: context.cached.error });
context.options.force = true;
context.options.wait = true;
}
next(null);
});
} | [
"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 internal phantom errors, not client javascript errors.",
"if",
"(",
"context",
".",
"cached",
".",
"error",
")",
"{",
"this",
".",
"logger",
".",
"warn",
"(",
"'The last try gave us an error, try to recompute.'",
",",
"{",
"error",
":",
"context",
".",
"cached",
".",
"error",
"}",
")",
";",
"context",
".",
"options",
".",
"force",
"=",
"true",
";",
"context",
".",
"options",
".",
"wait",
"=",
"true",
";",
"}",
"next",
"(",
"null",
")",
";",
"}",
")",
";",
"}"
] | 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 |
|
48,833 | 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) {
if (err) return next(err);
context.cached = cached;
next(null);
}
));
if (!context.options.wait)
next(null);
}
else next(null);
} | 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) {
if (err) return next(err);
context.cached = cached;
next(null);
}
));
if (!context.options.wait)
next(null);
}
else next(null);
} | [
"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",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
";",
"context",
".",
"cached",
"=",
"cached",
";",
"next",
"(",
"null",
")",
";",
"}",
")",
")",
";",
"if",
"(",
"!",
"context",
".",
"options",
".",
"wait",
")",
"next",
"(",
"null",
")",
";",
"}",
"else",
"next",
"(",
"null",
")",
";",
"}"
] | 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 |
|
48,834 | 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.requests,
template: context.cached.template,
context: context.options.solidifyContext,
host: this.options.host,
sessionID: context.options.sessionID
};
// solidify the template by feeding it.
return this._solidify.feed(opts, function (err, result) {
if (err)
return next(new errors.Internal('Solidify error: ' + err.message));
context.solidified = result;
next(null);
});
} | 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.requests,
template: context.cached.template,
context: context.options.solidifyContext,
host: this.options.host,
sessionID: context.options.sessionID
};
// solidify the template by feeding it.
return this._solidify.feed(opts, function (err, result) {
if (err)
return next(new errors.Internal('Solidify error: ' + err.message));
context.solidified = result;
next(null);
});
} | [
"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",
".",
"requests",
",",
"template",
":",
"context",
".",
"cached",
".",
"template",
",",
"context",
":",
"context",
".",
"options",
".",
"solidifyContext",
",",
"host",
":",
"this",
".",
"options",
".",
"host",
",",
"sessionID",
":",
"context",
".",
"options",
".",
"sessionID",
"}",
";",
"// solidify the template by feeding it.",
"return",
"this",
".",
"_solidify",
".",
"feed",
"(",
"opts",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"new",
"errors",
".",
"Internal",
"(",
"'Solidify error: '",
"+",
"err",
".",
"message",
")",
")",
";",
"context",
".",
"solidified",
"=",
"result",
";",
"next",
"(",
"null",
")",
";",
"}",
")",
";",
"}"
] | 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 |
|
48,835 | 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/e728951a850dae8102b7fa68894535be43ec0521/src/format/DateTimeFormatterBuilder.js#L615
//TODO js-joda should support locales soonish,
//so we can default to system date format.
var pattern = props.pattern || 'MM/dd/yyyy';
var formatter = js_joda_1.DateTimeFormatter.ofPattern(pattern);
try {
var localDate = js_joda_1.LocalDateTime.ofInstant(js_joda_1.Instant.parse(isoDate));
var formattedDate = localDate.format(formatter);
return React.createElement("time", { dateTime: isoDate }, formattedDate);
}
catch (e) {
dev_1.warn("Provided datetime was not in ISO8061 format (yyyy-MM-ddTHH:mm:ssZ): " + props.date);
return empty;
}
} | 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/e728951a850dae8102b7fa68894535be43ec0521/src/format/DateTimeFormatterBuilder.js#L615
//TODO js-joda should support locales soonish,
//so we can default to system date format.
var pattern = props.pattern || 'MM/dd/yyyy';
var formatter = js_joda_1.DateTimeFormatter.ofPattern(pattern);
try {
var localDate = js_joda_1.LocalDateTime.ofInstant(js_joda_1.Instant.parse(isoDate));
var formattedDate = localDate.format(formatter);
return React.createElement("time", { dateTime: isoDate }, formattedDate);
}
catch (e) {
dev_1.warn("Provided datetime was not in ISO8061 format (yyyy-MM-ddTHH:mm:ssZ): " + props.date);
return empty;
}
} | [
"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/e728951a850dae8102b7fa68894535be43ec0521/src/format/DateTimeFormatterBuilder.js#L615",
"//TODO js-joda should support locales soonish,",
"//so we can default to system date format.",
"var",
"pattern",
"=",
"props",
".",
"pattern",
"||",
"'MM/dd/yyyy'",
";",
"var",
"formatter",
"=",
"js_joda_1",
".",
"DateTimeFormatter",
".",
"ofPattern",
"(",
"pattern",
")",
";",
"try",
"{",
"var",
"localDate",
"=",
"js_joda_1",
".",
"LocalDateTime",
".",
"ofInstant",
"(",
"js_joda_1",
".",
"Instant",
".",
"parse",
"(",
"isoDate",
")",
")",
";",
"var",
"formattedDate",
"=",
"localDate",
".",
"format",
"(",
"formatter",
")",
";",
"return",
"React",
".",
"createElement",
"(",
"\"time\"",
",",
"{",
"dateTime",
":",
"isoDate",
"}",
",",
"formattedDate",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"dev_1",
".",
"warn",
"(",
"\"Provided datetime was not in ISO8061 format (yyyy-MM-ddTHH:mm:ssZ): \"",
"+",
"props",
".",
"date",
")",
";",
"return",
"empty",
";",
"}",
"}"
] | 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 |
48,836 | 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",
"new",
"Proxy",
"(",
"result",
",",
"{",
"get",
"(",
"target",
",",
"key",
",",
"receiver",
")",
"{",
"if",
"(",
"key",
"!==",
"'pipe'",
")",
"return",
"target",
"[",
"key",
"]",
"return",
"function",
"(",
"dest",
")",
"{",
"pump",
"(",
"result",
",",
"dest",
")",
"return",
"dest",
"}",
"}",
"}",
")",
"}"
] | 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 |
48,837 | 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 |
48,838 | 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 |
48,839 | 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 |
48,840 | 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 |
48,841 | 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",
")",
")",
"value",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"input",
".",
"push",
"(",
"null",
")",
")",
"}"
] | 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 |
48,842 | 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 |
48,843 | 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+'");')
});
// Once DOMContentLoaded
src.push('document.addEventListener("DOMContentLoaded",function() {');
// Inject html source
if(result.head) {
src.push('var head = document.getElementsByTagName("head")[0];')
src.push('head.insertAdjacentHTML("beforeend",'+JSON.stringify(result.head)+');')
}
if(result.body) {
src.push('var body = document.getElementsByTagName("body")[0];')
src.push('var root = body.appendChild(document.createElement("div"));')
src.push('root.setAttribute("hidden","");')
src.push('root.innerHTML=' + JSON.stringify(result.body)+ ';')
}
// Require scripts
result.scripts.forEach(function(script) {
src.push('require("'+script+'");')
})
// Append inline sources
result.inline.forEach(function(inline) {
src.push(';(function() {\n'+inline+'\n})();')
})
// End DOMContentLoaded
src.push('\n})')
return src.join('\n')
} | 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+'");')
});
// Once DOMContentLoaded
src.push('document.addEventListener("DOMContentLoaded",function() {');
// Inject html source
if(result.head) {
src.push('var head = document.getElementsByTagName("head")[0];')
src.push('head.insertAdjacentHTML("beforeend",'+JSON.stringify(result.head)+');')
}
if(result.body) {
src.push('var body = document.getElementsByTagName("body")[0];')
src.push('var root = body.appendChild(document.createElement("div"));')
src.push('root.setAttribute("hidden","");')
src.push('root.innerHTML=' + JSON.stringify(result.body)+ ';')
}
// Require scripts
result.scripts.forEach(function(script) {
src.push('require("'+script+'");')
})
// Append inline sources
result.inline.forEach(function(inline) {
src.push(';(function() {\n'+inline+'\n})();')
})
// End DOMContentLoaded
src.push('\n})')
return src.join('\n')
} | [
"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",
"+",
"'\");'",
")",
"}",
")",
";",
"// Once DOMContentLoaded",
"src",
".",
"push",
"(",
"'document.addEventListener(\"DOMContentLoaded\",function() {'",
")",
";",
"// Inject html source",
"if",
"(",
"result",
".",
"head",
")",
"{",
"src",
".",
"push",
"(",
"'var head = document.getElementsByTagName(\"head\")[0];'",
")",
"src",
".",
"push",
"(",
"'head.insertAdjacentHTML(\"beforeend\",'",
"+",
"JSON",
".",
"stringify",
"(",
"result",
".",
"head",
")",
"+",
"');'",
")",
"}",
"if",
"(",
"result",
".",
"body",
")",
"{",
"src",
".",
"push",
"(",
"'var body = document.getElementsByTagName(\"body\")[0];'",
")",
"src",
".",
"push",
"(",
"'var root = body.appendChild(document.createElement(\"div\"));'",
")",
"src",
".",
"push",
"(",
"'root.setAttribute(\"hidden\",\"\");'",
")",
"src",
".",
"push",
"(",
"'root.innerHTML='",
"+",
"JSON",
".",
"stringify",
"(",
"result",
".",
"body",
")",
"+",
"';'",
")",
"}",
"// Require scripts",
"result",
".",
"scripts",
".",
"forEach",
"(",
"function",
"(",
"script",
")",
"{",
"src",
".",
"push",
"(",
"'require(\"'",
"+",
"script",
"+",
"'\");'",
")",
"}",
")",
"// Append inline sources",
"result",
".",
"inline",
".",
"forEach",
"(",
"function",
"(",
"inline",
")",
"{",
"src",
".",
"push",
"(",
"';(function() {\\n'",
"+",
"inline",
"+",
"'\\n})();'",
")",
"}",
")",
"// End DOMContentLoaded",
"src",
".",
"push",
"(",
"'\\n})'",
")",
"return",
"src",
".",
"join",
"(",
"'\\n'",
")",
"}"
] | 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 |
48,844 | 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 stylesheets
inlineStylesheet($, filepath)
// Inline css minification and remove comments
minifyHtml($)
// Extract transformed html source:
result.head = $("head").html().trim();
result.body = $("body").html().trim();
return result;
} | 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 stylesheets
inlineStylesheet($, filepath)
// Inline css minification and remove comments
minifyHtml($)
// Extract transformed html source:
result.head = $("head").html().trim();
result.body = $("body").html().trim();
return result;
} | [
"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 stylesheets",
"inlineStylesheet",
"(",
"$",
",",
"filepath",
")",
"// Inline css minification and remove comments",
"minifyHtml",
"(",
"$",
")",
"// Extract transformed html source:",
"result",
".",
"head",
"=",
"$",
"(",
"\"head\"",
")",
".",
"html",
"(",
")",
".",
"trim",
"(",
")",
";",
"result",
".",
"body",
"=",
"$",
"(",
"\"body\"",
")",
".",
"html",
"(",
")",
".",
"trim",
"(",
")",
";",
"return",
"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 other javascript modules
- `inline` {Array}: Inline script sources
- `head` {String}: Source to insert into the main document's head
- `body` {String}: Source to insert into the document's body | [
"Parse",
"a",
"polymer",
"component",
"and",
"return",
"a",
"parse",
"result",
"object"
] | 3f525ff5144c084ba4d501ab174828844f5a53dd | https://github.com/nodys/polymerize/blob/3f525ff5144c084ba4d501ab174828844f5a53dd/lib/polymerize.js#L96-L118 |
48,845 | 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",
".",
"attr",
"(",
"'href'",
")",
";",
"if",
"(",
"ABS",
".",
"test",
"(",
"href",
")",
")",
"return",
";",
"imports",
".",
"push",
"(",
"/",
"^\\.",
"/",
".",
"test",
"(",
"href",
")",
"?",
"href",
":",
"'./'",
"+",
"href",
")",
";",
"el",
".",
"remove",
"(",
")",
";",
"}",
")",
"return",
"imports",
";",
"}"
] | 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 |
48,846 | 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",
".",
"attr",
"(",
"'src'",
")",
";",
"if",
"(",
"ABS",
".",
"test",
"(",
"src",
")",
")",
"return",
";",
"scripts",
".",
"push",
"(",
"/",
"^\\.",
"/",
".",
"test",
"(",
"src",
")",
"?",
"src",
":",
"'./'",
"+",
"src",
")",
";",
"el",
".",
"remove",
"(",
")",
";",
"}",
")",
"return",
"scripts",
";",
"}"
] | 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 |
48,847 | 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'))
}
scripts.push(src);
el.remove();
})
return scripts;
} | 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'))
}
scripts.push(src);
el.remove();
})
return scripts;
} | [
"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'",
")",
")",
"}",
"scripts",
".",
"push",
"(",
"src",
")",
";",
"el",
".",
"remove",
"(",
")",
";",
"}",
")",
"return",
"scripts",
";",
"}"
] | 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 |
48,848 | 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),
extensions : [extname(relpath)]
})
var content = read(srcpath);
var style = whacko('<style>' + content + '</style>');
style.attr(el.attr());
style.attr('href', null);
style.attr('rel', null);
el.replaceWith(whacko.html(style));
})
} | 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),
extensions : [extname(relpath)]
})
var content = read(srcpath);
var style = whacko('<style>' + content + '</style>');
style.attr(el.attr());
style.attr('href', null);
style.attr('rel', null);
el.replaceWith(whacko.html(style));
})
} | [
"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",
")",
",",
"extensions",
":",
"[",
"extname",
"(",
"relpath",
")",
"]",
"}",
")",
"var",
"content",
"=",
"read",
"(",
"srcpath",
")",
";",
"var",
"style",
"=",
"whacko",
"(",
"'<style>'",
"+",
"content",
"+",
"'</style>'",
")",
";",
"style",
".",
"attr",
"(",
"el",
".",
"attr",
"(",
")",
")",
";",
"style",
".",
"attr",
"(",
"'href'",
",",
"null",
")",
";",
"style",
".",
"attr",
"(",
"'rel'",
",",
"null",
")",
";",
"el",
".",
"replaceWith",
"(",
"whacko",
".",
"html",
"(",
"style",
")",
")",
";",
"}",
")",
"}"
] | 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 |
48,849 | 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 === 'text') {
// return true if the node is only whitespace
return !((/\S/).test(node.data));
}
}).remove();
} | 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 === 'text') {
// return true if the node is only whitespace
return !((/\S/).test(node.data));
}
}).remove();
} | [
"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",
"===",
"'text'",
")",
"{",
"// return true if the node is only whitespace",
"return",
"!",
"(",
"(",
"/",
"\\S",
"/",
")",
".",
"test",
"(",
"node",
".",
"data",
")",
")",
";",
"}",
"}",
")",
".",
"remove",
"(",
")",
";",
"}"
] | 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 |
48,850 | 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",
"[",
"key",
"]",
"instanceof",
"obj",
")",
")",
"{",
"data",
"[",
"key",
"]",
"=",
"toJS",
"(",
"entity",
"[",
"key",
"]",
")",
"}",
"else",
"{",
"data",
"[",
"key",
"]",
"=",
"entity",
"[",
"key",
"]",
"}",
"}",
")",
";",
"return",
"data",
"}"
] | 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 |
48,851 | 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 version provided')
}
const oSteps = {
download: {
number: 1,
details: { name: 'download' }
},
unzip: {
number: 2,
details: { name: 'unzip' }
}
}
const iTotalSteps = Object.keys(oSteps).length
const sTargetPath = `${sDownloadPath}/${sUI5Version}`
const sSuccessMessage = `UI5 download (${sUI5Version}) already exist at ${sDownloadPath}/${sUI5Version}`
const fnProgressCallback =
typeof oOptions.onProgress === 'function' ? oOptions.onProgress : () => {}
// check if ui5 library was already downloaded and ectracted
return fs.existsSync(sTargetPath)
? // download is already available
Promise.resolve(sSuccessMessage)
: // download and unzip sources
new Promise((resolve, reject) => {
progress(
request.get(
sDownloadURL,
{ encoding: null },
(oError, oResponse, oData) => {
if (oError) {
// reject promise
return reject(oError)
}
// update progress information (start step 2)
const oStep = oSteps['unzip']
fnProgressCallback(oStep.number, iTotalSteps, oStep.details)
// Do something after request finishes
const oBuffer = new Buffer(oData, 'binary')
const zip = new Zip(oBuffer)
const overwrite = true
// extracts everything
zip.extractAllTo(sTargetPath, overwrite)
// if sap-ui-core.js is not located in extracted root,
// we will rename the download directory to 'resources'
if (!fs.existsSync(`${sTargetPath}/sap-ui-core.js`)) {
// read all extracted files in current directory
const aFiles = fs.readdirSync(sTargetPath)
aFiles.forEach(sFileName => {
if (
fs.statSync(`${sTargetPath}/${sFileName}`).isDirectory()
) {
// rename download folder in root
try {
fs.renameSync(
`${sTargetPath}/${sFileName}`,
`${sTargetPath}/resources`
)
} catch (e) {
// skip renaming
}
}
})
}
// resolve promise
return resolve(`UI5 download successful: ${sTargetPath}`)
}
)
).on('progress', oProgressDetails => {
// update progress information
const oStep = oSteps['download']
fnProgressCallback(
oStep.number,
iTotalSteps,
Object.assign({}, oStep.details, {
progress: oProgressDetails.percent * 100
})
)
})
})
} | 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 version provided')
}
const oSteps = {
download: {
number: 1,
details: { name: 'download' }
},
unzip: {
number: 2,
details: { name: 'unzip' }
}
}
const iTotalSteps = Object.keys(oSteps).length
const sTargetPath = `${sDownloadPath}/${sUI5Version}`
const sSuccessMessage = `UI5 download (${sUI5Version}) already exist at ${sDownloadPath}/${sUI5Version}`
const fnProgressCallback =
typeof oOptions.onProgress === 'function' ? oOptions.onProgress : () => {}
// check if ui5 library was already downloaded and ectracted
return fs.existsSync(sTargetPath)
? // download is already available
Promise.resolve(sSuccessMessage)
: // download and unzip sources
new Promise((resolve, reject) => {
progress(
request.get(
sDownloadURL,
{ encoding: null },
(oError, oResponse, oData) => {
if (oError) {
// reject promise
return reject(oError)
}
// update progress information (start step 2)
const oStep = oSteps['unzip']
fnProgressCallback(oStep.number, iTotalSteps, oStep.details)
// Do something after request finishes
const oBuffer = new Buffer(oData, 'binary')
const zip = new Zip(oBuffer)
const overwrite = true
// extracts everything
zip.extractAllTo(sTargetPath, overwrite)
// if sap-ui-core.js is not located in extracted root,
// we will rename the download directory to 'resources'
if (!fs.existsSync(`${sTargetPath}/sap-ui-core.js`)) {
// read all extracted files in current directory
const aFiles = fs.readdirSync(sTargetPath)
aFiles.forEach(sFileName => {
if (
fs.statSync(`${sTargetPath}/${sFileName}`).isDirectory()
) {
// rename download folder in root
try {
fs.renameSync(
`${sTargetPath}/${sFileName}`,
`${sTargetPath}/resources`
)
} catch (e) {
// skip renaming
}
}
})
}
// resolve promise
return resolve(`UI5 download successful: ${sTargetPath}`)
}
)
).on('progress', oProgressDetails => {
// update progress information
const oStep = oSteps['download']
fnProgressCallback(
oStep.number,
iTotalSteps,
Object.assign({}, oStep.details, {
progress: oProgressDetails.percent * 100
})
)
})
})
} | [
"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 version provided'",
")",
"}",
"const",
"oSteps",
"=",
"{",
"download",
":",
"{",
"number",
":",
"1",
",",
"details",
":",
"{",
"name",
":",
"'download'",
"}",
"}",
",",
"unzip",
":",
"{",
"number",
":",
"2",
",",
"details",
":",
"{",
"name",
":",
"'unzip'",
"}",
"}",
"}",
"const",
"iTotalSteps",
"=",
"Object",
".",
"keys",
"(",
"oSteps",
")",
".",
"length",
"const",
"sTargetPath",
"=",
"`",
"${",
"sDownloadPath",
"}",
"${",
"sUI5Version",
"}",
"`",
"const",
"sSuccessMessage",
"=",
"`",
"${",
"sUI5Version",
"}",
"${",
"sDownloadPath",
"}",
"${",
"sUI5Version",
"}",
"`",
"const",
"fnProgressCallback",
"=",
"typeof",
"oOptions",
".",
"onProgress",
"===",
"'function'",
"?",
"oOptions",
".",
"onProgress",
":",
"(",
")",
"=>",
"{",
"}",
"// check if ui5 library was already downloaded and ectracted",
"return",
"fs",
".",
"existsSync",
"(",
"sTargetPath",
")",
"?",
"// download is already available",
"Promise",
".",
"resolve",
"(",
"sSuccessMessage",
")",
":",
"// download and unzip sources",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"progress",
"(",
"request",
".",
"get",
"(",
"sDownloadURL",
",",
"{",
"encoding",
":",
"null",
"}",
",",
"(",
"oError",
",",
"oResponse",
",",
"oData",
")",
"=>",
"{",
"if",
"(",
"oError",
")",
"{",
"// reject promise",
"return",
"reject",
"(",
"oError",
")",
"}",
"// update progress information (start step 2)",
"const",
"oStep",
"=",
"oSteps",
"[",
"'unzip'",
"]",
"fnProgressCallback",
"(",
"oStep",
".",
"number",
",",
"iTotalSteps",
",",
"oStep",
".",
"details",
")",
"// Do something after request finishes",
"const",
"oBuffer",
"=",
"new",
"Buffer",
"(",
"oData",
",",
"'binary'",
")",
"const",
"zip",
"=",
"new",
"Zip",
"(",
"oBuffer",
")",
"const",
"overwrite",
"=",
"true",
"// extracts everything",
"zip",
".",
"extractAllTo",
"(",
"sTargetPath",
",",
"overwrite",
")",
"// if sap-ui-core.js is not located in extracted root,",
"// we will rename the download directory to 'resources'",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"`",
"${",
"sTargetPath",
"}",
"`",
")",
")",
"{",
"// read all extracted files in current directory",
"const",
"aFiles",
"=",
"fs",
".",
"readdirSync",
"(",
"sTargetPath",
")",
"aFiles",
".",
"forEach",
"(",
"sFileName",
"=>",
"{",
"if",
"(",
"fs",
".",
"statSync",
"(",
"`",
"${",
"sTargetPath",
"}",
"${",
"sFileName",
"}",
"`",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"// rename download folder in root",
"try",
"{",
"fs",
".",
"renameSync",
"(",
"`",
"${",
"sTargetPath",
"}",
"${",
"sFileName",
"}",
"`",
",",
"`",
"${",
"sTargetPath",
"}",
"`",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"// skip renaming",
"}",
"}",
"}",
")",
"}",
"// resolve promise",
"return",
"resolve",
"(",
"`",
"${",
"sTargetPath",
"}",
"`",
")",
"}",
")",
")",
".",
"on",
"(",
"'progress'",
",",
"oProgressDetails",
"=>",
"{",
"// update progress information",
"const",
"oStep",
"=",
"oSteps",
"[",
"'download'",
"]",
"fnProgressCallback",
"(",
"oStep",
".",
"number",
",",
"iTotalSteps",
",",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"oStep",
".",
"details",
",",
"{",
"progress",
":",
"oProgressDetails",
".",
"percent",
"*",
"100",
"}",
")",
")",
"}",
")",
"}",
")",
"}"
] | 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 subdirectory named <code>/{{sUI5Version}}</code>.
@param {Object} [oOptions] Download options.
@param {function(number,number,{ name: string, progress: number|null}):void} [oOptions.onProgress] Callback function to track download progress taking as params: current step number, total step number and if available, step details (object with name and progress in percent).
@returns {Promise.string} Promise which resolves to a success or error message. | [
"Download",
"OpenUI5",
"repository",
"from",
"external",
"URL",
"and",
"unzip",
"."
] | d257d57e80515adc9638bfeb80992997cf5357d4 | https://github.com/pulseshift/ui5-lib-util/blob/d257d57e80515adc9638bfeb80992997cf5357d4/index.js#L41-L135 |
48,852 | 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,
parser: {
filename: sFileName,
paths: [sDestDir]
},
compiler: { compress: false }
}
// build a theme
const oBuildThemePromise = builder
.build(oOptions)
.catch(oError => {
// CSS build fails in 99% of all cases, because of a missing .less file
// create empty LESS file and try again if build failed
// try to parse error message to find out which missing LESS file caused the failed build
const sMissingFileName = (oError.message.match(
/((\.*?\/?)*\w.*\.\w+)/g
) || [''])[0]
const sSourceFileName = oError.filename
const sMissingFilePath = path.resolve(
sDestDir,
sSourceFileName.replace('library.source.less', ''),
sMissingFileName
)
let isIssueFixed = false
// create missing .less file (with empty content), else the library.css can't be created
if (!fs.existsSync(sMissingFilePath)) {
try {
fs.writeFileSync(sMissingFilePath, '')
isIssueFixed = true
} catch (e) {
isIssueFixed = false
}
}
if (!isIssueFixed) {
// if this error message raises up, the build failed due to the other 1% cases
return Promise.reject('Compile UI5 less lib: ')
}
// if missing file could be created, try theme build again
return isIssueFixed ? ui5CompileLessLib(oFile) : Promise.reject()
})
.then(oResult => {
// build css content was successfull >> save result
const aTargetFiles = [
{
path: `${sDestDir}/library.css`,
content: oResult.css
},
{
path: `${sDestDir}/library-RTL.css`,
content: oResult.cssRtl
},
{
path: `${sDestDir}/library-parameters.json`,
content:
JSON.stringify(
oResult.variables,
null,
oOptions.compiler.compress ? 0 : 4
) || ''
}
]
const aWriteFilesPromises = aTargetFiles.map(oFile => {
return new Promise((resolve, reject) =>
fs.writeFile(
oFile.path,
oFile.content,
oError => (oError ? reject() : resolve())
)
)
})
// return promise
return Promise.all(aWriteFilesPromises)
})
.then(() => {
// clear builder cache when finished to cleanup memory
builder.clearCache()
return Promise.resolve()
})
return oBuildThemePromise
} | 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,
parser: {
filename: sFileName,
paths: [sDestDir]
},
compiler: { compress: false }
}
// build a theme
const oBuildThemePromise = builder
.build(oOptions)
.catch(oError => {
// CSS build fails in 99% of all cases, because of a missing .less file
// create empty LESS file and try again if build failed
// try to parse error message to find out which missing LESS file caused the failed build
const sMissingFileName = (oError.message.match(
/((\.*?\/?)*\w.*\.\w+)/g
) || [''])[0]
const sSourceFileName = oError.filename
const sMissingFilePath = path.resolve(
sDestDir,
sSourceFileName.replace('library.source.less', ''),
sMissingFileName
)
let isIssueFixed = false
// create missing .less file (with empty content), else the library.css can't be created
if (!fs.existsSync(sMissingFilePath)) {
try {
fs.writeFileSync(sMissingFilePath, '')
isIssueFixed = true
} catch (e) {
isIssueFixed = false
}
}
if (!isIssueFixed) {
// if this error message raises up, the build failed due to the other 1% cases
return Promise.reject('Compile UI5 less lib: ')
}
// if missing file could be created, try theme build again
return isIssueFixed ? ui5CompileLessLib(oFile) : Promise.reject()
})
.then(oResult => {
// build css content was successfull >> save result
const aTargetFiles = [
{
path: `${sDestDir}/library.css`,
content: oResult.css
},
{
path: `${sDestDir}/library-RTL.css`,
content: oResult.cssRtl
},
{
path: `${sDestDir}/library-parameters.json`,
content:
JSON.stringify(
oResult.variables,
null,
oOptions.compiler.compress ? 0 : 4
) || ''
}
]
const aWriteFilesPromises = aTargetFiles.map(oFile => {
return new Promise((resolve, reject) =>
fs.writeFile(
oFile.path,
oFile.content,
oError => (oError ? reject() : resolve())
)
)
})
// return promise
return Promise.all(aWriteFilesPromises)
})
.then(() => {
// clear builder cache when finished to cleanup memory
builder.clearCache()
return Promise.resolve()
})
return oBuildThemePromise
} | [
"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",
",",
"parser",
":",
"{",
"filename",
":",
"sFileName",
",",
"paths",
":",
"[",
"sDestDir",
"]",
"}",
",",
"compiler",
":",
"{",
"compress",
":",
"false",
"}",
"}",
"// build a theme",
"const",
"oBuildThemePromise",
"=",
"builder",
".",
"build",
"(",
"oOptions",
")",
".",
"catch",
"(",
"oError",
"=>",
"{",
"// CSS build fails in 99% of all cases, because of a missing .less file",
"// create empty LESS file and try again if build failed",
"// try to parse error message to find out which missing LESS file caused the failed build",
"const",
"sMissingFileName",
"=",
"(",
"oError",
".",
"message",
".",
"match",
"(",
"/",
"((\\.*?\\/?)*\\w.*\\.\\w+)",
"/",
"g",
")",
"||",
"[",
"''",
"]",
")",
"[",
"0",
"]",
"const",
"sSourceFileName",
"=",
"oError",
".",
"filename",
"const",
"sMissingFilePath",
"=",
"path",
".",
"resolve",
"(",
"sDestDir",
",",
"sSourceFileName",
".",
"replace",
"(",
"'library.source.less'",
",",
"''",
")",
",",
"sMissingFileName",
")",
"let",
"isIssueFixed",
"=",
"false",
"// create missing .less file (with empty content), else the library.css can't be created",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"sMissingFilePath",
")",
")",
"{",
"try",
"{",
"fs",
".",
"writeFileSync",
"(",
"sMissingFilePath",
",",
"''",
")",
"isIssueFixed",
"=",
"true",
"}",
"catch",
"(",
"e",
")",
"{",
"isIssueFixed",
"=",
"false",
"}",
"}",
"if",
"(",
"!",
"isIssueFixed",
")",
"{",
"// if this error message raises up, the build failed due to the other 1% cases",
"return",
"Promise",
".",
"reject",
"(",
"'Compile UI5 less lib: '",
")",
"}",
"// if missing file could be created, try theme build again",
"return",
"isIssueFixed",
"?",
"ui5CompileLessLib",
"(",
"oFile",
")",
":",
"Promise",
".",
"reject",
"(",
")",
"}",
")",
".",
"then",
"(",
"oResult",
"=>",
"{",
"// build css content was successfull >> save result",
"const",
"aTargetFiles",
"=",
"[",
"{",
"path",
":",
"`",
"${",
"sDestDir",
"}",
"`",
",",
"content",
":",
"oResult",
".",
"css",
"}",
",",
"{",
"path",
":",
"`",
"${",
"sDestDir",
"}",
"`",
",",
"content",
":",
"oResult",
".",
"cssRtl",
"}",
",",
"{",
"path",
":",
"`",
"${",
"sDestDir",
"}",
"`",
",",
"content",
":",
"JSON",
".",
"stringify",
"(",
"oResult",
".",
"variables",
",",
"null",
",",
"oOptions",
".",
"compiler",
".",
"compress",
"?",
"0",
":",
"4",
")",
"||",
"''",
"}",
"]",
"const",
"aWriteFilesPromises",
"=",
"aTargetFiles",
".",
"map",
"(",
"oFile",
"=>",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"fs",
".",
"writeFile",
"(",
"oFile",
".",
"path",
",",
"oFile",
".",
"content",
",",
"oError",
"=>",
"(",
"oError",
"?",
"reject",
"(",
")",
":",
"resolve",
"(",
")",
")",
")",
")",
"}",
")",
"// return promise",
"return",
"Promise",
".",
"all",
"(",
"aWriteFilesPromises",
")",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"// clear builder cache when finished to cleanup memory",
"builder",
".",
"clearCache",
"(",
")",
"return",
"Promise",
".",
"resolve",
"(",
")",
"}",
")",
"return",
"oBuildThemePromise",
"}"
] | 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 |
48,853 | 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",
"Buffer",
"(",
"sPrelaodJSON",
")",
"return",
"oFile",
"}"
] | 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 |
48,854 | 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 Buffer(sUpdatedFile)
// return updated file
return oFile
} | 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 Buffer(sUpdatedFile)
// return updated file
return oFile
} | [
"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",
"Buffer",
"(",
"sUpdatedFile",
")",
"// return updated file",
"return",
"oFile",
"}"
] | 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 |
48,855 | 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 {
const scalar = maxSpeed * distanceSq / arriveThresholdSq;
desiredVelocity.scaleBy(scalar);
}
const force = desiredVelocity.subtract(velocity);
steeringForce.add(force);
force.dispose();
return boid;
} | javascript | function arrive(targetVec) {
const desiredVelocity = targetVec.clone().subtract(position);
desiredVelocity.normalize();
const distanceSq = position.distanceSq(targetVec);
if (distanceSq > arriveThresholdSq) {
desiredVelocity.scaleBy(maxSpeed);
} else {
const scalar = maxSpeed * distanceSq / arriveThresholdSq;
desiredVelocity.scaleBy(scalar);
}
const force = desiredVelocity.subtract(velocity);
steeringForce.add(force);
force.dispose();
return boid;
} | [
"function",
"arrive",
"(",
"targetVec",
")",
"{",
"const",
"desiredVelocity",
"=",
"targetVec",
".",
"clone",
"(",
")",
".",
"subtract",
"(",
"position",
")",
";",
"desiredVelocity",
".",
"normalize",
"(",
")",
";",
"const",
"distanceSq",
"=",
"position",
".",
"distanceSq",
"(",
"targetVec",
")",
";",
"if",
"(",
"distanceSq",
">",
"arriveThresholdSq",
")",
"{",
"desiredVelocity",
".",
"scaleBy",
"(",
"maxSpeed",
")",
";",
"}",
"else",
"{",
"const",
"scalar",
"=",
"maxSpeed",
"*",
"distanceSq",
"/",
"arriveThresholdSq",
";",
"desiredVelocity",
".",
"scaleBy",
"(",
"scalar",
")",
";",
"}",
"const",
"force",
"=",
"desiredVelocity",
".",
"subtract",
"(",
"velocity",
")",
";",
"steeringForce",
".",
"add",
"(",
"force",
")",
";",
"force",
".",
"dispose",
"(",
")",
";",
"return",
"boid",
";",
"}"
] | seek until within arriveThreshold | [
"seek",
"until",
"within",
"arriveThreshold"
] | cef69760c5777898a389707905fc1ca387441bcd | https://github.com/ianmcgregor/boid/blob/cef69760c5777898a389707905fc1ca387441bcd/src/boid.js#L145-L161 |
48,856 | 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 - wanderRange * 0.5;
const force = center.add(offset);
steeringForce.add(force);
offset.dispose();
force.dispose();
return boid;
} | 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 - wanderRange * 0.5;
const force = center.add(offset);
steeringForce.add(force);
offset.dispose();
force.dispose();
return boid;
} | [
"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",
"-",
"wanderRange",
"*",
"0.5",
";",
"const",
"force",
"=",
"center",
".",
"add",
"(",
"offset",
")",
";",
"steeringForce",
".",
"add",
"(",
"force",
")",
";",
"offset",
".",
"dispose",
"(",
")",
";",
"force",
".",
"dispose",
"(",
")",
";",
"return",
"boid",
";",
"}"
] | 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 |
48,857 | 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);
const dotProd = difference.dotProduct(heading);
// if obstacle in front of boid
if (dotProd > 0) {
// vec to represent 'feeler' arm
const feeler = heading.clone().scaleBy(avoidDistance);
// project difference onto feeler
const projection = heading.clone().scaleBy(dotProd);
// distance from obstacle to feeler
const vecDistance = projection.subtract(difference);
const distance = vecDistance.length;
// if feeler intersects obstacle (plus buffer), and projection
// less than feeler length, will collide
if (distance < (obstacle.radius || 0) + avoidBuffer && projection.length < feeler.length) {
// calc a force +/- 90 deg from vec to circ
const force = heading.clone().scaleBy(maxSpeed);
force.angle += difference.sign(velocity) * PI_D2;
// scale force by distance (further = smaller force)
const dist = projection.length / feeler.length;
force.scaleBy(1 - dist);
// add to steering force
steeringForce.add(force);
// braking force - slows boid down so it has time to turn (closer = harder)
velocity.scaleBy(dist);
force.dispose();
}
feeler.dispose();
projection.dispose();
vecDistance.dispose();
}
heading.dispose();
difference.dispose();
}
return boid;
} | 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);
const dotProd = difference.dotProduct(heading);
// if obstacle in front of boid
if (dotProd > 0) {
// vec to represent 'feeler' arm
const feeler = heading.clone().scaleBy(avoidDistance);
// project difference onto feeler
const projection = heading.clone().scaleBy(dotProd);
// distance from obstacle to feeler
const vecDistance = projection.subtract(difference);
const distance = vecDistance.length;
// if feeler intersects obstacle (plus buffer), and projection
// less than feeler length, will collide
if (distance < (obstacle.radius || 0) + avoidBuffer && projection.length < feeler.length) {
// calc a force +/- 90 deg from vec to circ
const force = heading.clone().scaleBy(maxSpeed);
force.angle += difference.sign(velocity) * PI_D2;
// scale force by distance (further = smaller force)
const dist = projection.length / feeler.length;
force.scaleBy(1 - dist);
// add to steering force
steeringForce.add(force);
// braking force - slows boid down so it has time to turn (closer = harder)
velocity.scaleBy(dist);
force.dispose();
}
feeler.dispose();
projection.dispose();
vecDistance.dispose();
}
heading.dispose();
difference.dispose();
}
return boid;
} | [
"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",
")",
";",
"const",
"dotProd",
"=",
"difference",
".",
"dotProduct",
"(",
"heading",
")",
";",
"// if obstacle in front of boid",
"if",
"(",
"dotProd",
">",
"0",
")",
"{",
"// vec to represent 'feeler' arm",
"const",
"feeler",
"=",
"heading",
".",
"clone",
"(",
")",
".",
"scaleBy",
"(",
"avoidDistance",
")",
";",
"// project difference onto feeler",
"const",
"projection",
"=",
"heading",
".",
"clone",
"(",
")",
".",
"scaleBy",
"(",
"dotProd",
")",
";",
"// distance from obstacle to feeler",
"const",
"vecDistance",
"=",
"projection",
".",
"subtract",
"(",
"difference",
")",
";",
"const",
"distance",
"=",
"vecDistance",
".",
"length",
";",
"// if feeler intersects obstacle (plus buffer), and projection",
"// less than feeler length, will collide",
"if",
"(",
"distance",
"<",
"(",
"obstacle",
".",
"radius",
"||",
"0",
")",
"+",
"avoidBuffer",
"&&",
"projection",
".",
"length",
"<",
"feeler",
".",
"length",
")",
"{",
"// calc a force +/- 90 deg from vec to circ",
"const",
"force",
"=",
"heading",
".",
"clone",
"(",
")",
".",
"scaleBy",
"(",
"maxSpeed",
")",
";",
"force",
".",
"angle",
"+=",
"difference",
".",
"sign",
"(",
"velocity",
")",
"*",
"PI_D2",
";",
"// scale force by distance (further = smaller force)",
"const",
"dist",
"=",
"projection",
".",
"length",
"/",
"feeler",
".",
"length",
";",
"force",
".",
"scaleBy",
"(",
"1",
"-",
"dist",
")",
";",
"// add to steering force",
"steeringForce",
".",
"add",
"(",
"force",
")",
";",
"// braking force - slows boid down so it has time to turn (closer = harder)",
"velocity",
".",
"scaleBy",
"(",
"dist",
")",
";",
"force",
".",
"dispose",
"(",
")",
";",
"}",
"feeler",
".",
"dispose",
"(",
")",
";",
"projection",
".",
"dispose",
"(",
")",
";",
"vecDistance",
".",
"dispose",
"(",
")",
";",
"}",
"heading",
".",
"dispose",
"(",
")",
";",
"difference",
".",
"dispose",
"(",
")",
";",
"}",
"return",
"boid",
";",
"}"
] | 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 |
48,858 | 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 (loop) {
pathIndex = 0;
}
} else {
pathIndex++;
}
}
if (pathIndex >= path.length - 1 && !loop) {
arrive(wayPoint);
} else {
seek(wayPoint);
}
return boid;
} | 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 (loop) {
pathIndex = 0;
}
} else {
pathIndex++;
}
}
if (pathIndex >= path.length - 1 && !loop) {
arrive(wayPoint);
} else {
seek(wayPoint);
}
return boid;
} | [
"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",
"(",
"loop",
")",
"{",
"pathIndex",
"=",
"0",
";",
"}",
"}",
"else",
"{",
"pathIndex",
"++",
";",
"}",
"}",
"if",
"(",
"pathIndex",
">=",
"path",
".",
"length",
"-",
"1",
"&&",
"!",
"loop",
")",
"{",
"arrive",
"(",
"wayPoint",
")",
";",
"}",
"else",
"{",
"seek",
"(",
"wayPoint",
")",
";",
"}",
"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 |
48,859 | 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.dispose();
difference.dispose();
return dotProd >= 0;
} | 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.dispose();
difference.dispose();
return dotProd >= 0;
} | [
"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",
".",
"dispose",
"(",
")",
";",
"difference",
".",
"dispose",
"(",
")",
";",
"return",
"dotProd",
">=",
"0",
";",
"}"
] | 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 |
48,860 | ianmcgregor/boid | src/boid.js | flock | function flock(boids) {
const averageVelocity = velocity.clone();
const averagePosition = Vec2.get();
let inSightCount = 0;
for (let i = 0; i < boids.length; i++) {
const b = boids[i];
if (b !== boid && inSight(b)) {
averageVelocity.add(b.velocity);
averagePosition.add(b.position);
if (position.distanceSq(b.position) < minDistanceSq) {
flee(b.position);
}
inSightCount++;
}
}
if (inSightCount > 0) {
averageVelocity.divideBy(inSightCount);
averagePosition.divideBy(inSightCount);
seek(averagePosition);
steeringForce.add(averageVelocity.subtract(velocity));
}
averageVelocity.dispose();
averagePosition.dispose();
return boid;
} | javascript | function flock(boids) {
const averageVelocity = velocity.clone();
const averagePosition = Vec2.get();
let inSightCount = 0;
for (let i = 0; i < boids.length; i++) {
const b = boids[i];
if (b !== boid && inSight(b)) {
averageVelocity.add(b.velocity);
averagePosition.add(b.position);
if (position.distanceSq(b.position) < minDistanceSq) {
flee(b.position);
}
inSightCount++;
}
}
if (inSightCount > 0) {
averageVelocity.divideBy(inSightCount);
averagePosition.divideBy(inSightCount);
seek(averagePosition);
steeringForce.add(averageVelocity.subtract(velocity));
}
averageVelocity.dispose();
averagePosition.dispose();
return boid;
} | [
"function",
"flock",
"(",
"boids",
")",
"{",
"const",
"averageVelocity",
"=",
"velocity",
".",
"clone",
"(",
")",
";",
"const",
"averagePosition",
"=",
"Vec2",
".",
"get",
"(",
")",
";",
"let",
"inSightCount",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"boids",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"b",
"=",
"boids",
"[",
"i",
"]",
";",
"if",
"(",
"b",
"!==",
"boid",
"&&",
"inSight",
"(",
"b",
")",
")",
"{",
"averageVelocity",
".",
"add",
"(",
"b",
".",
"velocity",
")",
";",
"averagePosition",
".",
"add",
"(",
"b",
".",
"position",
")",
";",
"if",
"(",
"position",
".",
"distanceSq",
"(",
"b",
".",
"position",
")",
"<",
"minDistanceSq",
")",
"{",
"flee",
"(",
"b",
".",
"position",
")",
";",
"}",
"inSightCount",
"++",
";",
"}",
"}",
"if",
"(",
"inSightCount",
">",
"0",
")",
"{",
"averageVelocity",
".",
"divideBy",
"(",
"inSightCount",
")",
";",
"averagePosition",
".",
"divideBy",
"(",
"inSightCount",
")",
";",
"seek",
"(",
"averagePosition",
")",
";",
"steeringForce",
".",
"add",
"(",
"averageVelocity",
".",
"subtract",
"(",
"velocity",
")",
")",
";",
"}",
"averageVelocity",
".",
"dispose",
"(",
")",
";",
"averagePosition",
".",
"dispose",
"(",
")",
";",
"return",
"boid",
";",
"}"
] | flock - group of boids loosely move together | [
"flock",
"-",
"group",
"of",
"boids",
"loosely",
"move",
"together"
] | cef69760c5777898a389707905fc1ca387441bcd | https://github.com/ianmcgregor/boid/blob/cef69760c5777898a389707905fc1ca387441bcd/src/boid.js#L300-L326 |
48,861 | tianjianchn/javascript-packages | packages/umc-managed-store/src/parse-structure.js | getEntityNameKeyMap | function getEntityNameKeyMap(structure) {
const result = {};
for (const kk in structure) {
const vv = structure[kk];
if (typeof vv === 'string') {
if (types.isMap(vv)) {
const info = types.getTypeInfo(vv);
const entityName = info.entity;
if (_entityNameType[entityName]) throw new Error(`Duplicate entity ${entityName}`);
_entityNameType[entityName] = vv;
result[entityName] = kk;
delete structure[kk];
}
}
}
return result;
} | javascript | function getEntityNameKeyMap(structure) {
const result = {};
for (const kk in structure) {
const vv = structure[kk];
if (typeof vv === 'string') {
if (types.isMap(vv)) {
const info = types.getTypeInfo(vv);
const entityName = info.entity;
if (_entityNameType[entityName]) throw new Error(`Duplicate entity ${entityName}`);
_entityNameType[entityName] = vv;
result[entityName] = kk;
delete structure[kk];
}
}
}
return result;
} | [
"function",
"getEntityNameKeyMap",
"(",
"structure",
")",
"{",
"const",
"result",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"kk",
"in",
"structure",
")",
"{",
"const",
"vv",
"=",
"structure",
"[",
"kk",
"]",
";",
"if",
"(",
"typeof",
"vv",
"===",
"'string'",
")",
"{",
"if",
"(",
"types",
".",
"isMap",
"(",
"vv",
")",
")",
"{",
"const",
"info",
"=",
"types",
".",
"getTypeInfo",
"(",
"vv",
")",
";",
"const",
"entityName",
"=",
"info",
".",
"entity",
";",
"if",
"(",
"_entityNameType",
"[",
"entityName",
"]",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"entityName",
"}",
"`",
")",
";",
"_entityNameType",
"[",
"entityName",
"]",
"=",
"vv",
";",
"result",
"[",
"entityName",
"]",
"=",
"kk",
";",
"delete",
"structure",
"[",
"kk",
"]",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | currently only support top level key | [
"currently",
"only",
"support",
"top",
"level",
"key"
] | 3abe85edbfe323939c84c1d02128d74d6374bcde | https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/umc-managed-store/src/parse-structure.js#L18-L36 |
48,862 | nknapp/process-streams | src/process-streams.js | wrapProcess | function wrapProcess (tmpIn, tmpOut, processProvider) {
return createStream(tmpIn, tmpOut, function (input, output, callback) {
var _this = this
var process = processProvider.call(this, tmpIn, tmpOut)
process.on('error', function (error) {
callback(error)
})
if (!tmpIn) {
input.pipe(process.stdin).on('error', function (error) {
if (error.code === 'ECONNRESET' && error.syscall === 'read') {
// This can happen if the process closes stdin before all data has been read
// e.g. in ps.spawn("exiftool", ["-s3", "-MimeType", "-fast","-"]);
// This is not necessarily an error, since the output is still valid
_this.emit('input-closed', error)
} else if (error.code === 'EPIPE' && error.syscall === 'write') {
// This also can happen if the process closes stdin before all data has been read
// e.g. in ps.spawn("head", ["-2"]);
// This is not necessarily an error, since the output is still valid
_this.emit('input-closed', error)
} else {
// This "emit" causes test cases to fail
// it is most likely a followup-error of an error that is already
// emitted
// _this.emit("error", error);
}
})
}
if (!tmpOut) {
process.stdout.pipe(output)
}
process.on('exit', function (code, signal) {
_this.emit('exit', code, signal)
callback(null)
})
})
} | javascript | function wrapProcess (tmpIn, tmpOut, processProvider) {
return createStream(tmpIn, tmpOut, function (input, output, callback) {
var _this = this
var process = processProvider.call(this, tmpIn, tmpOut)
process.on('error', function (error) {
callback(error)
})
if (!tmpIn) {
input.pipe(process.stdin).on('error', function (error) {
if (error.code === 'ECONNRESET' && error.syscall === 'read') {
// This can happen if the process closes stdin before all data has been read
// e.g. in ps.spawn("exiftool", ["-s3", "-MimeType", "-fast","-"]);
// This is not necessarily an error, since the output is still valid
_this.emit('input-closed', error)
} else if (error.code === 'EPIPE' && error.syscall === 'write') {
// This also can happen if the process closes stdin before all data has been read
// e.g. in ps.spawn("head", ["-2"]);
// This is not necessarily an error, since the output is still valid
_this.emit('input-closed', error)
} else {
// This "emit" causes test cases to fail
// it is most likely a followup-error of an error that is already
// emitted
// _this.emit("error", error);
}
})
}
if (!tmpOut) {
process.stdout.pipe(output)
}
process.on('exit', function (code, signal) {
_this.emit('exit', code, signal)
callback(null)
})
})
} | [
"function",
"wrapProcess",
"(",
"tmpIn",
",",
"tmpOut",
",",
"processProvider",
")",
"{",
"return",
"createStream",
"(",
"tmpIn",
",",
"tmpOut",
",",
"function",
"(",
"input",
",",
"output",
",",
"callback",
")",
"{",
"var",
"_this",
"=",
"this",
"var",
"process",
"=",
"processProvider",
".",
"call",
"(",
"this",
",",
"tmpIn",
",",
"tmpOut",
")",
"process",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
")",
"}",
")",
"if",
"(",
"!",
"tmpIn",
")",
"{",
"input",
".",
"pipe",
"(",
"process",
".",
"stdin",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"code",
"===",
"'ECONNRESET'",
"&&",
"error",
".",
"syscall",
"===",
"'read'",
")",
"{",
"// This can happen if the process closes stdin before all data has been read",
"// e.g. in ps.spawn(\"exiftool\", [\"-s3\", \"-MimeType\", \"-fast\",\"-\"]);",
"// This is not necessarily an error, since the output is still valid",
"_this",
".",
"emit",
"(",
"'input-closed'",
",",
"error",
")",
"}",
"else",
"if",
"(",
"error",
".",
"code",
"===",
"'EPIPE'",
"&&",
"error",
".",
"syscall",
"===",
"'write'",
")",
"{",
"// This also can happen if the process closes stdin before all data has been read",
"// e.g. in ps.spawn(\"head\", [\"-2\"]);",
"// This is not necessarily an error, since the output is still valid",
"_this",
".",
"emit",
"(",
"'input-closed'",
",",
"error",
")",
"}",
"else",
"{",
"// This \"emit\" causes test cases to fail",
"// it is most likely a followup-error of an error that is already",
"// emitted",
"// _this.emit(\"error\", error);",
"}",
"}",
")",
"}",
"if",
"(",
"!",
"tmpOut",
")",
"{",
"process",
".",
"stdout",
".",
"pipe",
"(",
"output",
")",
"}",
"process",
".",
"on",
"(",
"'exit'",
",",
"function",
"(",
"code",
",",
"signal",
")",
"{",
"_this",
".",
"emit",
"(",
"'exit'",
",",
"code",
",",
"signal",
")",
"callback",
"(",
"null",
")",
"}",
")",
"}",
")",
"}"
] | Wraps a process provided by a function in a stream such that the stream input is piped to stdin and stdout is piped to the stream output.
If tmpIn is provided, no pipe is set up to stdin. Instead, the data is piped into tmpIn which can than be provided to the process
as command line argument. The same applies for stdout.
@param processProvider
@param tmpIn the location of a temporary file that is filled with the input data.
@param tmpOut the location of a temporary file that the process writes to and that is used as source to the stream output. | [
"Wraps",
"a",
"process",
"provided",
"by",
"a",
"function",
"in",
"a",
"stream",
"such",
"that",
"the",
"stream",
"input",
"is",
"piped",
"to",
"stdin",
"and",
"stdout",
"is",
"piped",
"to",
"the",
"stream",
"output",
".",
"If",
"tmpIn",
"is",
"provided",
"no",
"pipe",
"is",
"set",
"up",
"to",
"stdin",
".",
"Instead",
"the",
"data",
"is",
"piped",
"into",
"tmpIn",
"which",
"can",
"than",
"be",
"provided",
"to",
"the",
"process",
"as",
"command",
"line",
"argument",
".",
"The",
"same",
"applies",
"for",
"stdout",
"."
] | 227747e73ea541a9eeca1a4bf21c6d85c3c78bb0 | https://github.com/nknapp/process-streams/blob/227747e73ea541a9eeca1a4bf21c6d85c3c78bb0/src/process-streams.js#L105-L140 |
48,863 | nknapp/process-streams | src/process-streams.js | parseString | function parseString (string, tmpIn, tmpOut) {
var resultIn = null
var resultOut = null
var resultString = string.replace(placeHolderRegex, function (match) {
switch (match) {
case IN:
resultIn = resultIn || tmpIn
return resultIn
case OUT:
resultOut = resultOut || tmpOut
return resultOut
/* istanbul ignore next */
default:
throw new Error("Found '" + match + "'. Placeholder regex not consistent: " + JSON.stringify({
IN: IN,
OUT: OUT,
match: match
}))
}
})
return {
in: resultIn,
out: resultOut,
string: resultString
}
} | javascript | function parseString (string, tmpIn, tmpOut) {
var resultIn = null
var resultOut = null
var resultString = string.replace(placeHolderRegex, function (match) {
switch (match) {
case IN:
resultIn = resultIn || tmpIn
return resultIn
case OUT:
resultOut = resultOut || tmpOut
return resultOut
/* istanbul ignore next */
default:
throw new Error("Found '" + match + "'. Placeholder regex not consistent: " + JSON.stringify({
IN: IN,
OUT: OUT,
match: match
}))
}
})
return {
in: resultIn,
out: resultOut,
string: resultString
}
} | [
"function",
"parseString",
"(",
"string",
",",
"tmpIn",
",",
"tmpOut",
")",
"{",
"var",
"resultIn",
"=",
"null",
"var",
"resultOut",
"=",
"null",
"var",
"resultString",
"=",
"string",
".",
"replace",
"(",
"placeHolderRegex",
",",
"function",
"(",
"match",
")",
"{",
"switch",
"(",
"match",
")",
"{",
"case",
"IN",
":",
"resultIn",
"=",
"resultIn",
"||",
"tmpIn",
"return",
"resultIn",
"case",
"OUT",
":",
"resultOut",
"=",
"resultOut",
"||",
"tmpOut",
"return",
"resultOut",
"/* istanbul ignore next */",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"Found '\"",
"+",
"match",
"+",
"\"'. Placeholder regex not consistent: \"",
"+",
"JSON",
".",
"stringify",
"(",
"{",
"IN",
":",
"IN",
",",
"OUT",
":",
"OUT",
",",
"match",
":",
"match",
"}",
")",
")",
"}",
"}",
")",
"return",
"{",
"in",
":",
"resultIn",
",",
"out",
":",
"resultOut",
",",
"string",
":",
"resultString",
"}",
"}"
] | Replace placeholders in a string
@param string
@param tmpIn
@param tmpOut
@returns {{in: *, out: *, string: (XML|string|void|*)}} | [
"Replace",
"placeholders",
"in",
"a",
"string"
] | 227747e73ea541a9eeca1a4bf21c6d85c3c78bb0 | https://github.com/nknapp/process-streams/blob/227747e73ea541a9eeca1a4bf21c6d85c3c78bb0/src/process-streams.js#L189-L215 |
48,864 | pollen5/ladybug-fetch | src/url.js | cleanJoin | function cleanJoin(req) {
if(!isAbsoluteURL(req.url) && req.baseURL) {
const parsedBase = url.parse(req.baseURL, true);
const parsed = url.parse(req.url, true);
return {
protocol: parsedBase.protocol,
host: parsedBase.hostname,
port: parsedBase.port,
path: URLJoin(parsedBase.pathname, parsed.pathname),
query: mergeObjects(req._query, parsedBase.query, parsed.query)
};
} else {
const parsed = url.parse(req.url, true);
return {
protocol: parsed.protocol,
host: parsed.hostname,
port: parsed.port,
path: parsed.pathname,
query: mergeObjects(req._query, parsed.query)
};
}
} | javascript | function cleanJoin(req) {
if(!isAbsoluteURL(req.url) && req.baseURL) {
const parsedBase = url.parse(req.baseURL, true);
const parsed = url.parse(req.url, true);
return {
protocol: parsedBase.protocol,
host: parsedBase.hostname,
port: parsedBase.port,
path: URLJoin(parsedBase.pathname, parsed.pathname),
query: mergeObjects(req._query, parsedBase.query, parsed.query)
};
} else {
const parsed = url.parse(req.url, true);
return {
protocol: parsed.protocol,
host: parsed.hostname,
port: parsed.port,
path: parsed.pathname,
query: mergeObjects(req._query, parsed.query)
};
}
} | [
"function",
"cleanJoin",
"(",
"req",
")",
"{",
"if",
"(",
"!",
"isAbsoluteURL",
"(",
"req",
".",
"url",
")",
"&&",
"req",
".",
"baseURL",
")",
"{",
"const",
"parsedBase",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"baseURL",
",",
"true",
")",
";",
"const",
"parsed",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"url",
",",
"true",
")",
";",
"return",
"{",
"protocol",
":",
"parsedBase",
".",
"protocol",
",",
"host",
":",
"parsedBase",
".",
"hostname",
",",
"port",
":",
"parsedBase",
".",
"port",
",",
"path",
":",
"URLJoin",
"(",
"parsedBase",
".",
"pathname",
",",
"parsed",
".",
"pathname",
")",
",",
"query",
":",
"mergeObjects",
"(",
"req",
".",
"_query",
",",
"parsedBase",
".",
"query",
",",
"parsed",
".",
"query",
")",
"}",
";",
"}",
"else",
"{",
"const",
"parsed",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"url",
",",
"true",
")",
";",
"return",
"{",
"protocol",
":",
"parsed",
".",
"protocol",
",",
"host",
":",
"parsed",
".",
"hostname",
",",
"port",
":",
"parsed",
".",
"port",
",",
"path",
":",
"parsed",
".",
"pathname",
",",
"query",
":",
"mergeObjects",
"(",
"req",
".",
"_query",
",",
"parsed",
".",
"query",
")",
"}",
";",
"}",
"}"
] | Joins two URLs Cleanly, respecting any queries that appears in both base url path and the request query object. | [
"Joins",
"two",
"URLs",
"Cleanly",
"respecting",
"any",
"queries",
"that",
"appears",
"in",
"both",
"base",
"url",
"path",
"and",
"the",
"request",
"query",
"object",
"."
] | 7787a245454ff04e0b67b1de40b119bc7caf251d | https://github.com/pollen5/ladybug-fetch/blob/7787a245454ff04e0b67b1de40b119bc7caf251d/src/url.js#L6-L27 |
48,865 | davestewart/laravel-sketchpad-reload | index.js | load | function load () {
const str = fs.readFileSync(settingsFile, 'utf8')
if (str) {
const settings = JSON.parse(str)
this.settings = settings.livereload
this.paths = getPaths(settings)
.map(p => path.normalize(this.root + '/' + p))
.map(p => makeGlob(p))
}
} | javascript | function load () {
const str = fs.readFileSync(settingsFile, 'utf8')
if (str) {
const settings = JSON.parse(str)
this.settings = settings.livereload
this.paths = getPaths(settings)
.map(p => path.normalize(this.root + '/' + p))
.map(p => makeGlob(p))
}
} | [
"function",
"load",
"(",
")",
"{",
"const",
"str",
"=",
"fs",
".",
"readFileSync",
"(",
"settingsFile",
",",
"'utf8'",
")",
"if",
"(",
"str",
")",
"{",
"const",
"settings",
"=",
"JSON",
".",
"parse",
"(",
"str",
")",
"this",
".",
"settings",
"=",
"settings",
".",
"livereload",
"this",
".",
"paths",
"=",
"getPaths",
"(",
"settings",
")",
".",
"map",
"(",
"p",
"=>",
"path",
".",
"normalize",
"(",
"this",
".",
"root",
"+",
"'/'",
"+",
"p",
")",
")",
".",
"map",
"(",
"p",
"=>",
"makeGlob",
"(",
"p",
")",
")",
"}",
"}"
] | Load the settings file contents and assign to properties
@returns {boolean} | [
"Load",
"the",
"settings",
"file",
"contents",
"and",
"assign",
"to",
"properties"
] | 65b4bfdfdfb27b1dd4ba972aca897321b9a756b2 | https://github.com/davestewart/laravel-sketchpad-reload/blob/65b4bfdfdfb27b1dd4ba972aca897321b9a756b2/index.js#L160-L169 |
48,866 | davestewart/laravel-sketchpad-reload | index.js | init | function init (root, storage) {
// calling path
const calling = path.dirname(getCallingScript())
// root path
root = !root || root === '.' || root === './'
? root = calling
: path.isAbsolute(root)
? root
: path.normalize(calling + root)
sketchpad.root = root.replace(/\/*$/, '/')
// settings path
const settingsFolder = path.normalize(sketchpad.root + (storage || 'storage') + '/sketchpad/')
settingsFile = settingsFolder + 'settings.json'
// check for settings
if (!fs.existsSync(settingsFolder)) {
return error('Folder "' +settingsFolder+ '" not found')
}
if (!fs.existsSync(settingsFile)) {
return error('File "settings.json" not found in "' +settingsFolder+ '"')
}
// load settings
sketchpad.load()
return this
} | javascript | function init (root, storage) {
// calling path
const calling = path.dirname(getCallingScript())
// root path
root = !root || root === '.' || root === './'
? root = calling
: path.isAbsolute(root)
? root
: path.normalize(calling + root)
sketchpad.root = root.replace(/\/*$/, '/')
// settings path
const settingsFolder = path.normalize(sketchpad.root + (storage || 'storage') + '/sketchpad/')
settingsFile = settingsFolder + 'settings.json'
// check for settings
if (!fs.existsSync(settingsFolder)) {
return error('Folder "' +settingsFolder+ '" not found')
}
if (!fs.existsSync(settingsFile)) {
return error('File "settings.json" not found in "' +settingsFolder+ '"')
}
// load settings
sketchpad.load()
return this
} | [
"function",
"init",
"(",
"root",
",",
"storage",
")",
"{",
"// calling path",
"const",
"calling",
"=",
"path",
".",
"dirname",
"(",
"getCallingScript",
"(",
")",
")",
"// root path",
"root",
"=",
"!",
"root",
"||",
"root",
"===",
"'.'",
"||",
"root",
"===",
"'./'",
"?",
"root",
"=",
"calling",
":",
"path",
".",
"isAbsolute",
"(",
"root",
")",
"?",
"root",
":",
"path",
".",
"normalize",
"(",
"calling",
"+",
"root",
")",
"sketchpad",
".",
"root",
"=",
"root",
".",
"replace",
"(",
"/",
"\\/*$",
"/",
",",
"'/'",
")",
"// settings path",
"const",
"settingsFolder",
"=",
"path",
".",
"normalize",
"(",
"sketchpad",
".",
"root",
"+",
"(",
"storage",
"||",
"'storage'",
")",
"+",
"'/sketchpad/'",
")",
"settingsFile",
"=",
"settingsFolder",
"+",
"'settings.json'",
"// check for settings",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"settingsFolder",
")",
")",
"{",
"return",
"error",
"(",
"'Folder \"'",
"+",
"settingsFolder",
"+",
"'\" not found'",
")",
"}",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"settingsFile",
")",
")",
"{",
"return",
"error",
"(",
"'File \"settings.json\" not found in \"'",
"+",
"settingsFolder",
"+",
"'\"'",
")",
"}",
"// load settings",
"sketchpad",
".",
"load",
"(",
")",
"return",
"this",
"}"
] | Initialize Sketchpad, optionally with non-standard paths
@param {string} [root] Relative path to Laravel root folder
@param {string} [storage] Relative path to storage folder from root
@returns {boolean} | [
"Initialize",
"Sketchpad",
"optionally",
"with",
"non",
"-",
"standard",
"paths"
] | 65b4bfdfdfb27b1dd4ba972aca897321b9a756b2 | https://github.com/davestewart/laravel-sketchpad-reload/blob/65b4bfdfdfb27b1dd4ba972aca897321b9a756b2/index.js#L178-L205 |
48,867 | ssbc/ssb-names | util.js | getOwnNameFallBack | function getOwnNameFallBack(names, dest) {
if (!names[dest]) return dest
else return names[dest][dest] || dest
} | javascript | function getOwnNameFallBack(names, dest) {
if (!names[dest]) return dest
else return names[dest][dest] || dest
} | [
"function",
"getOwnNameFallBack",
"(",
"names",
",",
"dest",
")",
"{",
"if",
"(",
"!",
"names",
"[",
"dest",
"]",
")",
"return",
"dest",
"else",
"return",
"names",
"[",
"dest",
"]",
"[",
"dest",
"]",
"||",
"dest",
"}"
] | Falls back to a user's name for themselves | [
"Falls",
"back",
"to",
"a",
"user",
"s",
"name",
"for",
"themselves"
] | e288aa4494c4d00983437391f9df84ae77b2bb51 | https://github.com/ssbc/ssb-names/blob/e288aa4494c4d00983437391f9df84ae77b2bb51/util.js#L41-L44 |
48,868 | mavin/node-wordpress-shortcode | index.js | function (tag, text, index) {
var re = wp.shortcode.regexp(tag)
var match
var result
re.lastIndex = index || 0
match = re.exec(text)
if (!match) {
return
}
// If we matched an escaped shortcode, try again.
if (match[1] === '[' && match[7] === ']') {
return wp.shortcode.next(tag, text, re.lastIndex)
}
result = {
index: match.index,
content: match[0],
shortcode: wp.shortcode.fromMatch(match)
}
// If we matched a leading `[`, strip it from the match
// and increment the index accordingly.
if (match[1]) {
result.content = result.content.slice(1)
result.index++
}
// If we matched a trailing `]`, strip it from the match.
if (match[7]) {
result.content = result.content.slice(0, -1)
}
return result
} | javascript | function (tag, text, index) {
var re = wp.shortcode.regexp(tag)
var match
var result
re.lastIndex = index || 0
match = re.exec(text)
if (!match) {
return
}
// If we matched an escaped shortcode, try again.
if (match[1] === '[' && match[7] === ']') {
return wp.shortcode.next(tag, text, re.lastIndex)
}
result = {
index: match.index,
content: match[0],
shortcode: wp.shortcode.fromMatch(match)
}
// If we matched a leading `[`, strip it from the match
// and increment the index accordingly.
if (match[1]) {
result.content = result.content.slice(1)
result.index++
}
// If we matched a trailing `]`, strip it from the match.
if (match[7]) {
result.content = result.content.slice(0, -1)
}
return result
} | [
"function",
"(",
"tag",
",",
"text",
",",
"index",
")",
"{",
"var",
"re",
"=",
"wp",
".",
"shortcode",
".",
"regexp",
"(",
"tag",
")",
"var",
"match",
"var",
"result",
"re",
".",
"lastIndex",
"=",
"index",
"||",
"0",
"match",
"=",
"re",
".",
"exec",
"(",
"text",
")",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"}",
"// If we matched an escaped shortcode, try again.",
"if",
"(",
"match",
"[",
"1",
"]",
"===",
"'['",
"&&",
"match",
"[",
"7",
"]",
"===",
"']'",
")",
"{",
"return",
"wp",
".",
"shortcode",
".",
"next",
"(",
"tag",
",",
"text",
",",
"re",
".",
"lastIndex",
")",
"}",
"result",
"=",
"{",
"index",
":",
"match",
".",
"index",
",",
"content",
":",
"match",
"[",
"0",
"]",
",",
"shortcode",
":",
"wp",
".",
"shortcode",
".",
"fromMatch",
"(",
"match",
")",
"}",
"// If we matched a leading `[`, strip it from the match",
"// and increment the index accordingly.",
"if",
"(",
"match",
"[",
"1",
"]",
")",
"{",
"result",
".",
"content",
"=",
"result",
".",
"content",
".",
"slice",
"(",
"1",
")",
"result",
".",
"index",
"++",
"}",
"// If we matched a trailing `]`, strip it from the match.",
"if",
"(",
"match",
"[",
"7",
"]",
")",
"{",
"result",
".",
"content",
"=",
"result",
".",
"content",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
"}",
"return",
"result",
"}"
] | Find the next matching shortcode
Given a shortcode `tag`, a block of `text`, and an optional starting
`index`, returns the next matching shortcode or `undefined`.
Shortcodes are formatted as an object that contains the match
`content`, the matching `index`, and the parsed `shortcode` object.
@param tag
@param text
@param index
@return {*} | [
"Find",
"the",
"next",
"matching",
"shortcode"
] | 2e7b967327e85685b3ba0aed1c7afec790b66b1c | https://github.com/mavin/node-wordpress-shortcode/blob/2e7b967327e85685b3ba0aed1c7afec790b66b1c/index.js#L31-L67 |
|
48,869 | mavin/node-wordpress-shortcode | index.js | function (match) {
var type
if (match[4]) {
type = 'self-closing'
} else if (match[6]) {
type = 'closed'
} else {
type = 'single'
}
return new Shortcode({
tag: match[2],
attrs: match[3],
type: type,
content: match[5]
})
} | javascript | function (match) {
var type
if (match[4]) {
type = 'self-closing'
} else if (match[6]) {
type = 'closed'
} else {
type = 'single'
}
return new Shortcode({
tag: match[2],
attrs: match[3],
type: type,
content: match[5]
})
} | [
"function",
"(",
"match",
")",
"{",
"var",
"type",
"if",
"(",
"match",
"[",
"4",
"]",
")",
"{",
"type",
"=",
"'self-closing'",
"}",
"else",
"if",
"(",
"match",
"[",
"6",
"]",
")",
"{",
"type",
"=",
"'closed'",
"}",
"else",
"{",
"type",
"=",
"'single'",
"}",
"return",
"new",
"Shortcode",
"(",
"{",
"tag",
":",
"match",
"[",
"2",
"]",
",",
"attrs",
":",
"match",
"[",
"3",
"]",
",",
"type",
":",
"type",
",",
"content",
":",
"match",
"[",
"5",
"]",
"}",
")",
"}"
] | Generate a Shortcode Object from a RegExp match
Accepts a `match` object from calling `regexp.exec()` on a `RegExp`
generated by `wp.shortcode.regexp()`. `match` can also be set to the
`arguments` from a callback passed to `regexp.replace()`.
@param match
@return {Shortcode} | [
"Generate",
"a",
"Shortcode",
"Object",
"from",
"a",
"RegExp",
"match"
] | 2e7b967327e85685b3ba0aed1c7afec790b66b1c | https://github.com/mavin/node-wordpress-shortcode/blob/2e7b967327e85685b3ba0aed1c7afec790b66b1c/index.js#L212-L229 |
|
48,870 | mavin/node-wordpress-shortcode | index.js | function () {
var text = '[' + this.tag
_.each(this.attrs.numeric, function (value) {
if (/\s/.test(value)) {
text += ' "' + value + '"'
} else {
text += ' ' + value
}
})
_.each(this.attrs.named, function (value, name) {
text += ' ' + name + '="' + value + '"'
})
// If the tag is marked as `single` or `self-closing`, close the
// tag and ignore any additional content.
if (this.type === 'single') {
return text + ']'
} else if (this.type === 'self-closing') {
return text + ' /]'
}
// Complete the opening tag.
text += ']'
if (this.content) {
text += this.content
}
// Add the closing tag.
return text + '[/' + this.tag + ']'
} | javascript | function () {
var text = '[' + this.tag
_.each(this.attrs.numeric, function (value) {
if (/\s/.test(value)) {
text += ' "' + value + '"'
} else {
text += ' ' + value
}
})
_.each(this.attrs.named, function (value, name) {
text += ' ' + name + '="' + value + '"'
})
// If the tag is marked as `single` or `self-closing`, close the
// tag and ignore any additional content.
if (this.type === 'single') {
return text + ']'
} else if (this.type === 'self-closing') {
return text + ' /]'
}
// Complete the opening tag.
text += ']'
if (this.content) {
text += this.content
}
// Add the closing tag.
return text + '[/' + this.tag + ']'
} | [
"function",
"(",
")",
"{",
"var",
"text",
"=",
"'['",
"+",
"this",
".",
"tag",
"_",
".",
"each",
"(",
"this",
".",
"attrs",
".",
"numeric",
",",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"/",
"\\s",
"/",
".",
"test",
"(",
"value",
")",
")",
"{",
"text",
"+=",
"' \"'",
"+",
"value",
"+",
"'\"'",
"}",
"else",
"{",
"text",
"+=",
"' '",
"+",
"value",
"}",
"}",
")",
"_",
".",
"each",
"(",
"this",
".",
"attrs",
".",
"named",
",",
"function",
"(",
"value",
",",
"name",
")",
"{",
"text",
"+=",
"' '",
"+",
"name",
"+",
"'=\"'",
"+",
"value",
"+",
"'\"'",
"}",
")",
"// If the tag is marked as `single` or `self-closing`, close the",
"// tag and ignore any additional content.",
"if",
"(",
"this",
".",
"type",
"===",
"'single'",
")",
"{",
"return",
"text",
"+",
"']'",
"}",
"else",
"if",
"(",
"this",
".",
"type",
"===",
"'self-closing'",
")",
"{",
"return",
"text",
"+",
"' /]'",
"}",
"// Complete the opening tag.",
"text",
"+=",
"']'",
"if",
"(",
"this",
".",
"content",
")",
"{",
"text",
"+=",
"this",
".",
"content",
"}",
"// Add the closing tag.",
"return",
"text",
"+",
"'[/'",
"+",
"this",
".",
"tag",
"+",
"']'",
"}"
] | Transform the shortcode match into a string
@return {string} | [
"Transform",
"the",
"shortcode",
"match",
"into",
"a",
"string"
] | 2e7b967327e85685b3ba0aed1c7afec790b66b1c | https://github.com/mavin/node-wordpress-shortcode/blob/2e7b967327e85685b3ba0aed1c7afec790b66b1c/index.js#L312-L344 |
|
48,871 | tunnckoCore/async-exec-cmd | index.js | checkArguments | function checkArguments (argz) {
if (!argz.args.length) {
return error('first argument cant be function')
}
if (isEmptyFunction(argz.cb.toString())) {
return error('should have `callback` (non empty callback)')
}
if (typeOf(argz.args[0]) !== 'string') {
return type('expect `cmd` be string', argz.cb)
}
if (typeOf(argz.args[1]) === 'object') {
argz.args[2] = argz.args[1]
argz.args[1] = []
}
if (typeOf(argz.args[2]) !== 'object') {
argz.args[2] = {}
}
return {
cmd: argz.args[0],
args: argz.args[1],
opts: argz.args[2],
callback: argz.cb
}
} | javascript | function checkArguments (argz) {
if (!argz.args.length) {
return error('first argument cant be function')
}
if (isEmptyFunction(argz.cb.toString())) {
return error('should have `callback` (non empty callback)')
}
if (typeOf(argz.args[0]) !== 'string') {
return type('expect `cmd` be string', argz.cb)
}
if (typeOf(argz.args[1]) === 'object') {
argz.args[2] = argz.args[1]
argz.args[1] = []
}
if (typeOf(argz.args[2]) !== 'object') {
argz.args[2] = {}
}
return {
cmd: argz.args[0],
args: argz.args[1],
opts: argz.args[2],
callback: argz.cb
}
} | [
"function",
"checkArguments",
"(",
"argz",
")",
"{",
"if",
"(",
"!",
"argz",
".",
"args",
".",
"length",
")",
"{",
"return",
"error",
"(",
"'first argument cant be function'",
")",
"}",
"if",
"(",
"isEmptyFunction",
"(",
"argz",
".",
"cb",
".",
"toString",
"(",
")",
")",
")",
"{",
"return",
"error",
"(",
"'should have `callback` (non empty callback)'",
")",
"}",
"if",
"(",
"typeOf",
"(",
"argz",
".",
"args",
"[",
"0",
"]",
")",
"!==",
"'string'",
")",
"{",
"return",
"type",
"(",
"'expect `cmd` be string'",
",",
"argz",
".",
"cb",
")",
"}",
"if",
"(",
"typeOf",
"(",
"argz",
".",
"args",
"[",
"1",
"]",
")",
"===",
"'object'",
")",
"{",
"argz",
".",
"args",
"[",
"2",
"]",
"=",
"argz",
".",
"args",
"[",
"1",
"]",
"argz",
".",
"args",
"[",
"1",
"]",
"=",
"[",
"]",
"}",
"if",
"(",
"typeOf",
"(",
"argz",
".",
"args",
"[",
"2",
"]",
")",
"!==",
"'object'",
")",
"{",
"argz",
".",
"args",
"[",
"2",
"]",
"=",
"{",
"}",
"}",
"return",
"{",
"cmd",
":",
"argz",
".",
"args",
"[",
"0",
"]",
",",
"args",
":",
"argz",
".",
"args",
"[",
"1",
"]",
",",
"opts",
":",
"argz",
".",
"args",
"[",
"2",
"]",
",",
"callback",
":",
"argz",
".",
"cb",
"}",
"}"
] | > Create flexible arguments - check types.
@param {Object} `argz`
@return {Object}
@api private | [
">",
"Create",
"flexible",
"arguments",
"-",
"check",
"types",
"."
] | a9ab9ba7df404ccf29b3d008d3350775dcd62ed2 | https://github.com/tunnckoCore/async-exec-cmd/blob/a9ab9ba7df404ccf29b3d008d3350775dcd62ed2/index.js#L66-L94 |
48,872 | tunnckoCore/async-exec-cmd | index.js | buildSpawn | function buildSpawn (cmd, args, opts, callback) {
var proc = spawn(cmd, args, opts)
var buffer = new Buffer('')
var cmdError = {}
cmd = cmd + ' ' + args.join(' ')
if (proc.stdout) {
proc.stdout.on('data', function indexOnData (data) {
buffer = Buffer.concat([buffer, data])
})
}
proc
.on('error', function spawnOnError (err) {
cmdError = new CommandError({
command: cmd,
message: err.message ? err.message : undefined,
stack: err.stack ? err.stack : undefined,
buffer: buffer ? buffer : undefined,
status: err.status ? err.status : 1
})
})
.on('close', function spawnOnClose (code) {
if (code === 0) {
callback(null, buffer.toString().trim(), code, buffer)
return
}
cmdError = new CommandError({
command: cmd,
message: cmdError.message ? cmdError.message : undefined,
stack: cmdError.stack ? cmdError.stack : undefined,
buffer: cmdError.buffer ? cmdError.buffer : buffer,
status: cmdError.status ? cmdError.status : code
})
callback(cmdError, undefined, code, undefined)
})
return proc
} | javascript | function buildSpawn (cmd, args, opts, callback) {
var proc = spawn(cmd, args, opts)
var buffer = new Buffer('')
var cmdError = {}
cmd = cmd + ' ' + args.join(' ')
if (proc.stdout) {
proc.stdout.on('data', function indexOnData (data) {
buffer = Buffer.concat([buffer, data])
})
}
proc
.on('error', function spawnOnError (err) {
cmdError = new CommandError({
command: cmd,
message: err.message ? err.message : undefined,
stack: err.stack ? err.stack : undefined,
buffer: buffer ? buffer : undefined,
status: err.status ? err.status : 1
})
})
.on('close', function spawnOnClose (code) {
if (code === 0) {
callback(null, buffer.toString().trim(), code, buffer)
return
}
cmdError = new CommandError({
command: cmd,
message: cmdError.message ? cmdError.message : undefined,
stack: cmdError.stack ? cmdError.stack : undefined,
buffer: cmdError.buffer ? cmdError.buffer : buffer,
status: cmdError.status ? cmdError.status : code
})
callback(cmdError, undefined, code, undefined)
})
return proc
} | [
"function",
"buildSpawn",
"(",
"cmd",
",",
"args",
",",
"opts",
",",
"callback",
")",
"{",
"var",
"proc",
"=",
"spawn",
"(",
"cmd",
",",
"args",
",",
"opts",
")",
"var",
"buffer",
"=",
"new",
"Buffer",
"(",
"''",
")",
"var",
"cmdError",
"=",
"{",
"}",
"cmd",
"=",
"cmd",
"+",
"' '",
"+",
"args",
".",
"join",
"(",
"' '",
")",
"if",
"(",
"proc",
".",
"stdout",
")",
"{",
"proc",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"function",
"indexOnData",
"(",
"data",
")",
"{",
"buffer",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"buffer",
",",
"data",
"]",
")",
"}",
")",
"}",
"proc",
".",
"on",
"(",
"'error'",
",",
"function",
"spawnOnError",
"(",
"err",
")",
"{",
"cmdError",
"=",
"new",
"CommandError",
"(",
"{",
"command",
":",
"cmd",
",",
"message",
":",
"err",
".",
"message",
"?",
"err",
".",
"message",
":",
"undefined",
",",
"stack",
":",
"err",
".",
"stack",
"?",
"err",
".",
"stack",
":",
"undefined",
",",
"buffer",
":",
"buffer",
"?",
"buffer",
":",
"undefined",
",",
"status",
":",
"err",
".",
"status",
"?",
"err",
".",
"status",
":",
"1",
"}",
")",
"}",
")",
".",
"on",
"(",
"'close'",
",",
"function",
"spawnOnClose",
"(",
"code",
")",
"{",
"if",
"(",
"code",
"===",
"0",
")",
"{",
"callback",
"(",
"null",
",",
"buffer",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
",",
"code",
",",
"buffer",
")",
"return",
"}",
"cmdError",
"=",
"new",
"CommandError",
"(",
"{",
"command",
":",
"cmd",
",",
"message",
":",
"cmdError",
".",
"message",
"?",
"cmdError",
".",
"message",
":",
"undefined",
",",
"stack",
":",
"cmdError",
".",
"stack",
"?",
"cmdError",
".",
"stack",
":",
"undefined",
",",
"buffer",
":",
"cmdError",
".",
"buffer",
"?",
"cmdError",
".",
"buffer",
":",
"buffer",
",",
"status",
":",
"cmdError",
".",
"status",
"?",
"cmdError",
".",
"status",
":",
"code",
"}",
")",
"callback",
"(",
"cmdError",
",",
"undefined",
",",
"code",
",",
"undefined",
")",
"}",
")",
"return",
"proc",
"}"
] | > Handle cross-spawn.
@param {String} `cmd`
@param {Array} `args`
@param {Object} `opts`
@param {Function} `callback`
@return {Stream} actually what `child_process.spawn` returns
@api private | [
">",
"Handle",
"cross",
"-",
"spawn",
"."
] | a9ab9ba7df404ccf29b3d008d3350775dcd62ed2 | https://github.com/tunnckoCore/async-exec-cmd/blob/a9ab9ba7df404ccf29b3d008d3350775dcd62ed2/index.js#L120-L160 |
48,873 | tunnckoCore/async-exec-cmd | index.js | CommandError | function CommandError (err) {
this.name = 'CommandError'
this.command = err.command
this.message = err.message
this.stack = err.stack
this.buffer = err.buffer
this.status = err.status
Error.captureStackTrace(this, CommandError)
} | javascript | function CommandError (err) {
this.name = 'CommandError'
this.command = err.command
this.message = err.message
this.stack = err.stack
this.buffer = err.buffer
this.status = err.status
Error.captureStackTrace(this, CommandError)
} | [
"function",
"CommandError",
"(",
"err",
")",
"{",
"this",
".",
"name",
"=",
"'CommandError'",
"this",
".",
"command",
"=",
"err",
".",
"command",
"this",
".",
"message",
"=",
"err",
".",
"message",
"this",
".",
"stack",
"=",
"err",
".",
"stack",
"this",
".",
"buffer",
"=",
"err",
".",
"buffer",
"this",
".",
"status",
"=",
"err",
".",
"status",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"CommandError",
")",
"}"
] | > Construct `CommandError`.
@param {Object} `err`
@api private | [
">",
"Construct",
"CommandError",
"."
] | a9ab9ba7df404ccf29b3d008d3350775dcd62ed2 | https://github.com/tunnckoCore/async-exec-cmd/blob/a9ab9ba7df404ccf29b3d008d3350775dcd62ed2/index.js#L168-L176 |
48,874 | tianjianchn/midd | packages/uni-router/src/router.js | router | function router(req, resp, next) {
const routerPath = req.routePath || '';
const beforeRunMiddleware = (route) => {
const match = matchRoute(routerPath, req, route);
if (!match) return false;
const { params, path: matchPath } = match;
if (options.params) req.params = { ...options.params, ...params };
else req.params = params;
// dynamically set req.routePath for the route
req.routePath = routerPath + matchPath;
return true;
};
const routeStack = compose(router.routes, { beforeRunMiddleware });
return routeStack.call(this, req, resp, () => {
req.routePath = routerPath;// restore routePath
return next && next();
});
} | javascript | function router(req, resp, next) {
const routerPath = req.routePath || '';
const beforeRunMiddleware = (route) => {
const match = matchRoute(routerPath, req, route);
if (!match) return false;
const { params, path: matchPath } = match;
if (options.params) req.params = { ...options.params, ...params };
else req.params = params;
// dynamically set req.routePath for the route
req.routePath = routerPath + matchPath;
return true;
};
const routeStack = compose(router.routes, { beforeRunMiddleware });
return routeStack.call(this, req, resp, () => {
req.routePath = routerPath;// restore routePath
return next && next();
});
} | [
"function",
"router",
"(",
"req",
",",
"resp",
",",
"next",
")",
"{",
"const",
"routerPath",
"=",
"req",
".",
"routePath",
"||",
"''",
";",
"const",
"beforeRunMiddleware",
"=",
"(",
"route",
")",
"=>",
"{",
"const",
"match",
"=",
"matchRoute",
"(",
"routerPath",
",",
"req",
",",
"route",
")",
";",
"if",
"(",
"!",
"match",
")",
"return",
"false",
";",
"const",
"{",
"params",
",",
"path",
":",
"matchPath",
"}",
"=",
"match",
";",
"if",
"(",
"options",
".",
"params",
")",
"req",
".",
"params",
"=",
"{",
"...",
"options",
".",
"params",
",",
"...",
"params",
"}",
";",
"else",
"req",
".",
"params",
"=",
"params",
";",
"// dynamically set req.routePath for the route",
"req",
".",
"routePath",
"=",
"routerPath",
"+",
"matchPath",
";",
"return",
"true",
";",
"}",
";",
"const",
"routeStack",
"=",
"compose",
"(",
"router",
".",
"routes",
",",
"{",
"beforeRunMiddleware",
"}",
")",
";",
"return",
"routeStack",
".",
"call",
"(",
"this",
",",
"req",
",",
"resp",
",",
"(",
")",
"=>",
"{",
"req",
".",
"routePath",
"=",
"routerPath",
";",
"// restore routePath",
"return",
"next",
"&&",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] | the router instance | [
"the",
"router",
"instance"
] | 849f07f68c30335a68be5e1e2b709eb930a560d7 | https://github.com/tianjianchn/midd/blob/849f07f68c30335a68be5e1e2b709eb930a560d7/packages/uni-router/src/router.js#L19-L41 |
48,875 | heroqu/node-content-store | lib/event-promise.js | eventPromise | function eventPromise (emitter, eventName) {
return new Promise((resolve, reject) => {
emitter.on(eventName, (...args) => {
return resolve(args)
})
})
} | javascript | function eventPromise (emitter, eventName) {
return new Promise((resolve, reject) => {
emitter.on(eventName, (...args) => {
return resolve(args)
})
})
} | [
"function",
"eventPromise",
"(",
"emitter",
",",
"eventName",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"emitter",
".",
"on",
"(",
"eventName",
",",
"(",
"...",
"args",
")",
"=>",
"{",
"return",
"resolve",
"(",
"args",
")",
"}",
")",
"}",
")",
"}"
] | Wrap an event emmiting object event handler in such a way,
that when the event is detected, the promise get resolved. | [
"Wrap",
"an",
"event",
"emmiting",
"object",
"event",
"handler",
"in",
"such",
"a",
"way",
"that",
"when",
"the",
"event",
"is",
"detected",
"the",
"promise",
"get",
"resolved",
"."
] | 0100814bfd988d60ad94cdf5a441eff328208a6a | https://github.com/heroqu/node-content-store/blob/0100814bfd988d60ad94cdf5a441eff328208a6a/lib/event-promise.js#L5-L11 |
48,876 | cpsubrian/mgit | lib/index.js | status | function status() {
var tasks = [],
cwd = process.cwd();
findRepos(function(err, repos) {
if (err) return console.log(err);
repos.forEach(function(repo) {
tasks.push(function(done) {
repo.status(function(err, status) {
if (err) return done(err);
if (argv.b) {
repo.branch(function(err, head) {
if (err) return done(err);
done(null, {status: status, head: head});
});
}
else {
done(null, {status: status});
}
});
});
});
async.series(tasks, function(err, results) {
if (err) return console.log(err);
var row,
col,
res,
file,
head = [],
table,
symbol;
head.push('Repo');
if (argv.b) {
head.push('Branch');
}
head.push('Status');
table = new Table({
head: head,
style: {
compact: true,
'padding-left': 1,
'padding-right': 1,
head: ['white', 'bold']
}
});
results.forEach(function(res) {
var row = [];
row.push(res.status.repo.path.replace(cwd + '/', ''));
if (argv.b) {
row.push(res.head.name);
}
row.push(res.status.clean ? 'Clean'.green : 'Changed'.red);
table.push(row);
if (argv.v) {
for (var name in res.status.files) {
row = [];
row.push('');
if (argv.b) {
row.push('');
}
switch (res.status.files[name].type) {
case 'A':
symbol = '+'.green; break;
case 'D':
symbol = '-'.red; break;
case 'M':
symbol = '*'.yellow; break;
default:
symbol = '~'.grey; break;
}
row.push(' ' + symbol + ' ' + name);
table.push(row);
}
}
});
console.log(table.toString());
});
});
} | javascript | function status() {
var tasks = [],
cwd = process.cwd();
findRepos(function(err, repos) {
if (err) return console.log(err);
repos.forEach(function(repo) {
tasks.push(function(done) {
repo.status(function(err, status) {
if (err) return done(err);
if (argv.b) {
repo.branch(function(err, head) {
if (err) return done(err);
done(null, {status: status, head: head});
});
}
else {
done(null, {status: status});
}
});
});
});
async.series(tasks, function(err, results) {
if (err) return console.log(err);
var row,
col,
res,
file,
head = [],
table,
symbol;
head.push('Repo');
if (argv.b) {
head.push('Branch');
}
head.push('Status');
table = new Table({
head: head,
style: {
compact: true,
'padding-left': 1,
'padding-right': 1,
head: ['white', 'bold']
}
});
results.forEach(function(res) {
var row = [];
row.push(res.status.repo.path.replace(cwd + '/', ''));
if (argv.b) {
row.push(res.head.name);
}
row.push(res.status.clean ? 'Clean'.green : 'Changed'.red);
table.push(row);
if (argv.v) {
for (var name in res.status.files) {
row = [];
row.push('');
if (argv.b) {
row.push('');
}
switch (res.status.files[name].type) {
case 'A':
symbol = '+'.green; break;
case 'D':
symbol = '-'.red; break;
case 'M':
symbol = '*'.yellow; break;
default:
symbol = '~'.grey; break;
}
row.push(' ' + symbol + ' ' + name);
table.push(row);
}
}
});
console.log(table.toString());
});
});
} | [
"function",
"status",
"(",
")",
"{",
"var",
"tasks",
"=",
"[",
"]",
",",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"findRepos",
"(",
"function",
"(",
"err",
",",
"repos",
")",
"{",
"if",
"(",
"err",
")",
"return",
"console",
".",
"log",
"(",
"err",
")",
";",
"repos",
".",
"forEach",
"(",
"function",
"(",
"repo",
")",
"{",
"tasks",
".",
"push",
"(",
"function",
"(",
"done",
")",
"{",
"repo",
".",
"status",
"(",
"function",
"(",
"err",
",",
"status",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"if",
"(",
"argv",
".",
"b",
")",
"{",
"repo",
".",
"branch",
"(",
"function",
"(",
"err",
",",
"head",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"done",
"(",
"null",
",",
"{",
"status",
":",
"status",
",",
"head",
":",
"head",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"done",
"(",
"null",
",",
"{",
"status",
":",
"status",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"async",
".",
"series",
"(",
"tasks",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"return",
"console",
".",
"log",
"(",
"err",
")",
";",
"var",
"row",
",",
"col",
",",
"res",
",",
"file",
",",
"head",
"=",
"[",
"]",
",",
"table",
",",
"symbol",
";",
"head",
".",
"push",
"(",
"'Repo'",
")",
";",
"if",
"(",
"argv",
".",
"b",
")",
"{",
"head",
".",
"push",
"(",
"'Branch'",
")",
";",
"}",
"head",
".",
"push",
"(",
"'Status'",
")",
";",
"table",
"=",
"new",
"Table",
"(",
"{",
"head",
":",
"head",
",",
"style",
":",
"{",
"compact",
":",
"true",
",",
"'padding-left'",
":",
"1",
",",
"'padding-right'",
":",
"1",
",",
"head",
":",
"[",
"'white'",
",",
"'bold'",
"]",
"}",
"}",
")",
";",
"results",
".",
"forEach",
"(",
"function",
"(",
"res",
")",
"{",
"var",
"row",
"=",
"[",
"]",
";",
"row",
".",
"push",
"(",
"res",
".",
"status",
".",
"repo",
".",
"path",
".",
"replace",
"(",
"cwd",
"+",
"'/'",
",",
"''",
")",
")",
";",
"if",
"(",
"argv",
".",
"b",
")",
"{",
"row",
".",
"push",
"(",
"res",
".",
"head",
".",
"name",
")",
";",
"}",
"row",
".",
"push",
"(",
"res",
".",
"status",
".",
"clean",
"?",
"'Clean'",
".",
"green",
":",
"'Changed'",
".",
"red",
")",
";",
"table",
".",
"push",
"(",
"row",
")",
";",
"if",
"(",
"argv",
".",
"v",
")",
"{",
"for",
"(",
"var",
"name",
"in",
"res",
".",
"status",
".",
"files",
")",
"{",
"row",
"=",
"[",
"]",
";",
"row",
".",
"push",
"(",
"''",
")",
";",
"if",
"(",
"argv",
".",
"b",
")",
"{",
"row",
".",
"push",
"(",
"''",
")",
";",
"}",
"switch",
"(",
"res",
".",
"status",
".",
"files",
"[",
"name",
"]",
".",
"type",
")",
"{",
"case",
"'A'",
":",
"symbol",
"=",
"'+'",
".",
"green",
";",
"break",
";",
"case",
"'D'",
":",
"symbol",
"=",
"'-'",
".",
"red",
";",
"break",
";",
"case",
"'M'",
":",
"symbol",
"=",
"'*'",
".",
"yellow",
";",
"break",
";",
"default",
":",
"symbol",
"=",
"'~'",
".",
"grey",
";",
"break",
";",
"}",
"row",
".",
"push",
"(",
"' '",
"+",
"symbol",
"+",
"' '",
"+",
"name",
")",
";",
"table",
".",
"push",
"(",
"row",
")",
";",
"}",
"}",
"}",
")",
";",
"console",
".",
"log",
"(",
"table",
".",
"toString",
"(",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Output the status of found git repositories. | [
"Output",
"the",
"status",
"of",
"found",
"git",
"repositories",
"."
] | a938dbeb833c3e0c19efa9ca47ee2ebfe77aeed7 | https://github.com/cpsubrian/mgit/blob/a938dbeb833c3e0c19efa9ca47ee2ebfe77aeed7/lib/index.js#L24-L109 |
48,877 | cpsubrian/mgit | lib/index.js | pull | function pull() {
var tasks = [],
cwd = process.cwd();
findRepos(function(err, repos) {
if (err) return console.log(err);
repos.forEach(function(repo) {
tasks.push(function(done) {
repo.status(function(err, status) {
var name = status.repo.path.replace(cwd + '/', '');
if (!status.clean) {
console.log('Skipped '.red + name.bold + ' (not clean)'.grey);
done();
}
else {
console.log('Pulling '.green + name.bold);
process.chdir(status.repo.path);
exec('git fetch', function(err, stdout, stderr) {
if (err) return done(stderr);
if (stdout && argv.v) console.log(indent(stdout));
exec('git rebase', function(err, stdout, stderr) {
if (err) return done(stderr);
if (stdout && argv.v) console.log(indent(stdout));
done(null);
});
});
}
});
});
});
async.series(tasks, function(err, results) {
if (err) {
console.log('Error:'.red);
console.log(err);
}
else {
console.log('Done!');
}
});
});
} | javascript | function pull() {
var tasks = [],
cwd = process.cwd();
findRepos(function(err, repos) {
if (err) return console.log(err);
repos.forEach(function(repo) {
tasks.push(function(done) {
repo.status(function(err, status) {
var name = status.repo.path.replace(cwd + '/', '');
if (!status.clean) {
console.log('Skipped '.red + name.bold + ' (not clean)'.grey);
done();
}
else {
console.log('Pulling '.green + name.bold);
process.chdir(status.repo.path);
exec('git fetch', function(err, stdout, stderr) {
if (err) return done(stderr);
if (stdout && argv.v) console.log(indent(stdout));
exec('git rebase', function(err, stdout, stderr) {
if (err) return done(stderr);
if (stdout && argv.v) console.log(indent(stdout));
done(null);
});
});
}
});
});
});
async.series(tasks, function(err, results) {
if (err) {
console.log('Error:'.red);
console.log(err);
}
else {
console.log('Done!');
}
});
});
} | [
"function",
"pull",
"(",
")",
"{",
"var",
"tasks",
"=",
"[",
"]",
",",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"findRepos",
"(",
"function",
"(",
"err",
",",
"repos",
")",
"{",
"if",
"(",
"err",
")",
"return",
"console",
".",
"log",
"(",
"err",
")",
";",
"repos",
".",
"forEach",
"(",
"function",
"(",
"repo",
")",
"{",
"tasks",
".",
"push",
"(",
"function",
"(",
"done",
")",
"{",
"repo",
".",
"status",
"(",
"function",
"(",
"err",
",",
"status",
")",
"{",
"var",
"name",
"=",
"status",
".",
"repo",
".",
"path",
".",
"replace",
"(",
"cwd",
"+",
"'/'",
",",
"''",
")",
";",
"if",
"(",
"!",
"status",
".",
"clean",
")",
"{",
"console",
".",
"log",
"(",
"'Skipped '",
".",
"red",
"+",
"name",
".",
"bold",
"+",
"' (not clean)'",
".",
"grey",
")",
";",
"done",
"(",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'Pulling '",
".",
"green",
"+",
"name",
".",
"bold",
")",
";",
"process",
".",
"chdir",
"(",
"status",
".",
"repo",
".",
"path",
")",
";",
"exec",
"(",
"'git fetch'",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"stderr",
")",
";",
"if",
"(",
"stdout",
"&&",
"argv",
".",
"v",
")",
"console",
".",
"log",
"(",
"indent",
"(",
"stdout",
")",
")",
";",
"exec",
"(",
"'git rebase'",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"stderr",
")",
";",
"if",
"(",
"stdout",
"&&",
"argv",
".",
"v",
")",
"console",
".",
"log",
"(",
"indent",
"(",
"stdout",
")",
")",
";",
"done",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"async",
".",
"series",
"(",
"tasks",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'Error:'",
".",
"red",
")",
";",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'Done!'",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Pull and rebase all CLEAN git repos in the CWD. | [
"Pull",
"and",
"rebase",
"all",
"CLEAN",
"git",
"repos",
"in",
"the",
"CWD",
"."
] | a938dbeb833c3e0c19efa9ca47ee2ebfe77aeed7 | https://github.com/cpsubrian/mgit/blob/a938dbeb833c3e0c19efa9ca47ee2ebfe77aeed7/lib/index.js#L112-L153 |
48,878 | cpsubrian/mgit | lib/index.js | indent | function indent(str, prefix) {
prefix = prefix || ' ';
var lines = str.split("\n");
lines.forEach(function(line, i) {
lines[i] = prefix + line;
});
return lines.join("\n");
} | javascript | function indent(str, prefix) {
prefix = prefix || ' ';
var lines = str.split("\n");
lines.forEach(function(line, i) {
lines[i] = prefix + line;
});
return lines.join("\n");
} | [
"function",
"indent",
"(",
"str",
",",
"prefix",
")",
"{",
"prefix",
"=",
"prefix",
"||",
"' '",
";",
"var",
"lines",
"=",
"str",
".",
"split",
"(",
"\"\\n\"",
")",
";",
"lines",
".",
"forEach",
"(",
"function",
"(",
"line",
",",
"i",
")",
"{",
"lines",
"[",
"i",
"]",
"=",
"prefix",
"+",
"line",
";",
"}",
")",
";",
"return",
"lines",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"}"
] | Indent a block of text. | [
"Indent",
"a",
"block",
"of",
"text",
"."
] | a938dbeb833c3e0c19efa9ca47ee2ebfe77aeed7 | https://github.com/cpsubrian/mgit/blob/a938dbeb833c3e0c19efa9ca47ee2ebfe77aeed7/lib/index.js#L156-L163 |
48,879 | cpsubrian/mgit | lib/index.js | findRepos | function findRepos(callback) {
var cwd = process.cwd(),
tasks = [];
fs.readdir(cwd, function(err, files) {
if (err) return callback(err);
var repos = [];
files.forEach(function(file) {
if (fs.existsSync(path.join(cwd, file, '.git'))) {
repos.push(path.join(cwd, file));
}
});
if (repos.length === 0) {
return callback(new Error('No repositories found'));
}
repos.forEach(function(dir) {
tasks.push(function(done) {
done(err, git(dir));
});
});
async.series(tasks, function(err, results) {
callback(err, results);
});
});
} | javascript | function findRepos(callback) {
var cwd = process.cwd(),
tasks = [];
fs.readdir(cwd, function(err, files) {
if (err) return callback(err);
var repos = [];
files.forEach(function(file) {
if (fs.existsSync(path.join(cwd, file, '.git'))) {
repos.push(path.join(cwd, file));
}
});
if (repos.length === 0) {
return callback(new Error('No repositories found'));
}
repos.forEach(function(dir) {
tasks.push(function(done) {
done(err, git(dir));
});
});
async.series(tasks, function(err, results) {
callback(err, results);
});
});
} | [
"function",
"findRepos",
"(",
"callback",
")",
"{",
"var",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
",",
"tasks",
"=",
"[",
"]",
";",
"fs",
".",
"readdir",
"(",
"cwd",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"var",
"repos",
"=",
"[",
"]",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"path",
".",
"join",
"(",
"cwd",
",",
"file",
",",
"'.git'",
")",
")",
")",
"{",
"repos",
".",
"push",
"(",
"path",
".",
"join",
"(",
"cwd",
",",
"file",
")",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"repos",
".",
"length",
"===",
"0",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'No repositories found'",
")",
")",
";",
"}",
"repos",
".",
"forEach",
"(",
"function",
"(",
"dir",
")",
"{",
"tasks",
".",
"push",
"(",
"function",
"(",
"done",
")",
"{",
"done",
"(",
"err",
",",
"git",
"(",
"dir",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"async",
".",
"series",
"(",
"tasks",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"callback",
"(",
"err",
",",
"results",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Find and open all git repositories in the CWD. | [
"Find",
"and",
"open",
"all",
"git",
"repositories",
"in",
"the",
"CWD",
"."
] | a938dbeb833c3e0c19efa9ca47ee2ebfe77aeed7 | https://github.com/cpsubrian/mgit/blob/a938dbeb833c3e0c19efa9ca47ee2ebfe77aeed7/lib/index.js#L166-L194 |
48,880 | kriskowal/iterator | iterator.js | Iterator | function Iterator(iterator) {
if (Array.isArray(iterator) || typeof iterator == "string")
return Iterator.iterate(iterator);
iterator = Object(iterator);
if (!(this instanceof Iterator))
return new Iterator(iterator);
this.next = this.send =
iterator.send || iterator.next || iterator;
if (
Object.prototype.toString.call(this.next) !=
"[object Function]"
)
throw new TypeError();
} | javascript | function Iterator(iterator) {
if (Array.isArray(iterator) || typeof iterator == "string")
return Iterator.iterate(iterator);
iterator = Object(iterator);
if (!(this instanceof Iterator))
return new Iterator(iterator);
this.next = this.send =
iterator.send || iterator.next || iterator;
if (
Object.prototype.toString.call(this.next) !=
"[object Function]"
)
throw new TypeError();
} | [
"function",
"Iterator",
"(",
"iterator",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"iterator",
")",
"||",
"typeof",
"iterator",
"==",
"\"string\"",
")",
"return",
"Iterator",
".",
"iterate",
"(",
"iterator",
")",
";",
"iterator",
"=",
"Object",
"(",
"iterator",
")",
";",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Iterator",
")",
")",
"return",
"new",
"Iterator",
"(",
"iterator",
")",
";",
"this",
".",
"next",
"=",
"this",
".",
"send",
"=",
"iterator",
".",
"send",
"||",
"iterator",
".",
"next",
"||",
"iterator",
";",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"this",
".",
"next",
")",
"!=",
"\"[object Function]\"",
")",
"throw",
"new",
"TypeError",
"(",
")",
";",
"}"
] | upgrades an iterator to a Iterator | [
"upgrades",
"an",
"iterator",
"to",
"a",
"Iterator"
] | 00a41500ad73ff14aee347fdf27872198e0991c3 | https://github.com/kriskowal/iterator/blob/00a41500ad73ff14aee347fdf27872198e0991c3/iterator.js#L5-L24 |
48,881 | kaerus-component/uP | index.js | traverse | function traverse(_promise){
var c = _promise._chain,
s = _promise._state,
v = _promise._value,
o = _promise._opaque,
t, p, h, r;
while((t = c.shift())){
p = t[0];
h = t[s];
if(typeof h === 'function') {
try {
r = h(v,o);
p.resolve(r,o);
} catch(e) {
p.reject(e);
}
} else {
p._promise._state = s;
p._promise._value = v;
p._promise._opaque = o;
task(traverse,[p._promise]);
}
}
} | javascript | function traverse(_promise){
var c = _promise._chain,
s = _promise._state,
v = _promise._value,
o = _promise._opaque,
t, p, h, r;
while((t = c.shift())){
p = t[0];
h = t[s];
if(typeof h === 'function') {
try {
r = h(v,o);
p.resolve(r,o);
} catch(e) {
p.reject(e);
}
} else {
p._promise._state = s;
p._promise._value = v;
p._promise._opaque = o;
task(traverse,[p._promise]);
}
}
} | [
"function",
"traverse",
"(",
"_promise",
")",
"{",
"var",
"c",
"=",
"_promise",
".",
"_chain",
",",
"s",
"=",
"_promise",
".",
"_state",
",",
"v",
"=",
"_promise",
".",
"_value",
",",
"o",
"=",
"_promise",
".",
"_opaque",
",",
"t",
",",
"p",
",",
"h",
",",
"r",
";",
"while",
"(",
"(",
"t",
"=",
"c",
".",
"shift",
"(",
")",
")",
")",
"{",
"p",
"=",
"t",
"[",
"0",
"]",
";",
"h",
"=",
"t",
"[",
"s",
"]",
";",
"if",
"(",
"typeof",
"h",
"===",
"'function'",
")",
"{",
"try",
"{",
"r",
"=",
"h",
"(",
"v",
",",
"o",
")",
";",
"p",
".",
"resolve",
"(",
"r",
",",
"o",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"p",
".",
"reject",
"(",
"e",
")",
";",
"}",
"}",
"else",
"{",
"p",
".",
"_promise",
".",
"_state",
"=",
"s",
";",
"p",
".",
"_promise",
".",
"_value",
"=",
"v",
";",
"p",
".",
"_promise",
".",
"_opaque",
"=",
"o",
";",
"task",
"(",
"traverse",
",",
"[",
"p",
".",
"_promise",
"]",
")",
";",
"}",
"}",
"}"
] | Resolver function, yields a promised value to handlers | [
"Resolver",
"function",
"yields",
"a",
"promised",
"value",
"to",
"handlers"
] | 2c70cf5c539f4fc8e660a1f4f8d376d17dc4532e | https://github.com/kaerus-component/uP/blob/2c70cf5c539f4fc8e660a1f4f8d376d17dc4532e/index.js#L748-L774 |
48,882 | graphmalizer/graphmalizer-core | utils/permutations.js | cart | function cart(xs, ys)
{
// nothing on the left
if(!xs || xs.length === 0)
return ys.map(function(y){
return [[],y]
});
// nothing on the right
if(!ys || ys.length === 0)
return xs.map(function(x){
return [x,[]]
});
return Combinatorics.cartesianProduct(x, y).toArray();
} | javascript | function cart(xs, ys)
{
// nothing on the left
if(!xs || xs.length === 0)
return ys.map(function(y){
return [[],y]
});
// nothing on the right
if(!ys || ys.length === 0)
return xs.map(function(x){
return [x,[]]
});
return Combinatorics.cartesianProduct(x, y).toArray();
} | [
"function",
"cart",
"(",
"xs",
",",
"ys",
")",
"{",
"// nothing on the left",
"if",
"(",
"!",
"xs",
"||",
"xs",
".",
"length",
"===",
"0",
")",
"return",
"ys",
".",
"map",
"(",
"function",
"(",
"y",
")",
"{",
"return",
"[",
"[",
"]",
",",
"y",
"]",
"}",
")",
";",
"// nothing on the right",
"if",
"(",
"!",
"ys",
"||",
"ys",
".",
"length",
"===",
"0",
")",
"return",
"xs",
".",
"map",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"[",
"x",
",",
"[",
"]",
"]",
"}",
")",
";",
"return",
"Combinatorics",
".",
"cartesianProduct",
"(",
"x",
",",
"y",
")",
".",
"toArray",
"(",
")",
";",
"}"
] | save version of Combinatorics.cartesianProduct | [
"save",
"version",
"of",
"Combinatorics",
".",
"cartesianProduct"
] | a17ff4ef958c245652288e24dc663f77ddb1e80e | https://github.com/graphmalizer/graphmalizer-core/blob/a17ff4ef958c245652288e24dc663f77ddb1e80e/utils/permutations.js#L9-L24 |
48,883 | switer/chainjs | lib/utils.js | function(obj, iterator, context) {
if (!obj) return
else if (obj.forEach) obj.forEach(iterator)
else if (obj.length == +obj.length) {
for (var i = 0; i < obj.length; i++) iterator.call(context, obj[i], i)
} else {
for (var key in obj) iterator.call(context, obj[key], key)
}
} | javascript | function(obj, iterator, context) {
if (!obj) return
else if (obj.forEach) obj.forEach(iterator)
else if (obj.length == +obj.length) {
for (var i = 0; i < obj.length; i++) iterator.call(context, obj[i], i)
} else {
for (var key in obj) iterator.call(context, obj[key], key)
}
} | [
"function",
"(",
"obj",
",",
"iterator",
",",
"context",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"return",
"else",
"if",
"(",
"obj",
".",
"forEach",
")",
"obj",
".",
"forEach",
"(",
"iterator",
")",
"else",
"if",
"(",
"obj",
".",
"length",
"==",
"+",
"obj",
".",
"length",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obj",
".",
"length",
";",
"i",
"++",
")",
"iterator",
".",
"call",
"(",
"context",
",",
"obj",
"[",
"i",
"]",
",",
"i",
")",
"}",
"else",
"{",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"iterator",
".",
"call",
"(",
"context",
",",
"obj",
"[",
"key",
"]",
",",
"key",
")",
"}",
"}"
] | forEach
I don't want to import underscore, it looks like so heavy if using in chain | [
"forEach",
"I",
"don",
"t",
"want",
"to",
"import",
"underscore",
"it",
"looks",
"like",
"so",
"heavy",
"if",
"using",
"in",
"chain"
] | 7b5c0ceb55135df7b7a621a891cf59f49cc67d6c | https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/lib/utils.js#L11-L19 |
|
48,884 | switer/chainjs | lib/utils.js | function(context, handlers/*, params*/ ) {
var args = this.slice(arguments)
args.shift()
args.shift()
this.each(handlers, function(handler) {
if (handler) handler.apply(context, args)
})
} | javascript | function(context, handlers/*, params*/ ) {
var args = this.slice(arguments)
args.shift()
args.shift()
this.each(handlers, function(handler) {
if (handler) handler.apply(context, args)
})
} | [
"function",
"(",
"context",
",",
"handlers",
"/*, params*/",
")",
"{",
"var",
"args",
"=",
"this",
".",
"slice",
"(",
"arguments",
")",
"args",
".",
"shift",
"(",
")",
"args",
".",
"shift",
"(",
")",
"this",
".",
"each",
"(",
"handlers",
",",
"function",
"(",
"handler",
")",
"{",
"if",
"(",
"handler",
")",
"handler",
".",
"apply",
"(",
"context",
",",
"args",
")",
"}",
")",
"}"
] | Invoke handlers in batch process | [
"Invoke",
"handlers",
"in",
"batch",
"process"
] | 7b5c0ceb55135df7b7a621a891cf59f49cc67d6c | https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/lib/utils.js#L32-L39 |
|
48,885 | switer/chainjs | lib/utils.js | function(array) {
// return Array.prototype.slice.call(array)
var i = array.length
var a = new Array(i)
while(i) {
i --
a[i] = array[i]
}
return a
} | javascript | function(array) {
// return Array.prototype.slice.call(array)
var i = array.length
var a = new Array(i)
while(i) {
i --
a[i] = array[i]
}
return a
} | [
"function",
"(",
"array",
")",
"{",
"// return Array.prototype.slice.call(array)",
"var",
"i",
"=",
"array",
".",
"length",
"var",
"a",
"=",
"new",
"Array",
"(",
"i",
")",
"while",
"(",
"i",
")",
"{",
"i",
"--",
"a",
"[",
"i",
"]",
"=",
"array",
"[",
"i",
"]",
"}",
"return",
"a",
"}"
] | Array.slice | [
"Array",
".",
"slice"
] | 7b5c0ceb55135df7b7a621a891cf59f49cc67d6c | https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/lib/utils.js#L53-L62 |
|
48,886 | switer/chainjs | lib/utils.js | function(obj, extObj) {
this.each(extObj, function(value, key) {
if (extObj.hasOwnProperty(key)) obj[key] = value
})
return obj
} | javascript | function(obj, extObj) {
this.each(extObj, function(value, key) {
if (extObj.hasOwnProperty(key)) obj[key] = value
})
return obj
} | [
"function",
"(",
"obj",
",",
"extObj",
")",
"{",
"this",
".",
"each",
"(",
"extObj",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"extObj",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"obj",
"[",
"key",
"]",
"=",
"value",
"}",
")",
"return",
"obj",
"}"
] | Merge for extObj to obj | [
"Merge",
"for",
"extObj",
"to",
"obj"
] | 7b5c0ceb55135df7b7a621a891cf59f49cc67d6c | https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/lib/utils.js#L66-L71 |
|
48,887 | switer/chainjs | lib/utils.js | function (f, proto) {
function Ctor() {}
Ctor.prototype = proto
f.prototype = new Ctor()
f.prototype.constructor = Ctor
return f
} | javascript | function (f, proto) {
function Ctor() {}
Ctor.prototype = proto
f.prototype = new Ctor()
f.prototype.constructor = Ctor
return f
} | [
"function",
"(",
"f",
",",
"proto",
")",
"{",
"function",
"Ctor",
"(",
")",
"{",
"}",
"Ctor",
".",
"prototype",
"=",
"proto",
"f",
".",
"prototype",
"=",
"new",
"Ctor",
"(",
")",
"f",
".",
"prototype",
".",
"constructor",
"=",
"Ctor",
"return",
"f",
"}"
] | Create a class with specified proto | [
"Create",
"a",
"class",
"with",
"specified",
"proto"
] | 7b5c0ceb55135df7b7a621a891cf59f49cc67d6c | https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/lib/utils.js#L84-L90 |
|
48,888 | bholloway/browserify-debug-tools | lib/inspect.js | inspect | function inspect(callback) {
return function (filename) {
var chunks = [];
function transform(chunk, encoding, done) {
/* jshint validthis:true */
chunks.push(chunk);
this.push(chunk);
done();
}
function flush(done) {
callback(filename, chunks.join(''), done);
if (callback.length < 3) {
done();
}
}
return through(transform, flush);
}
} | javascript | function inspect(callback) {
return function (filename) {
var chunks = [];
function transform(chunk, encoding, done) {
/* jshint validthis:true */
chunks.push(chunk);
this.push(chunk);
done();
}
function flush(done) {
callback(filename, chunks.join(''), done);
if (callback.length < 3) {
done();
}
}
return through(transform, flush);
}
} | [
"function",
"inspect",
"(",
"callback",
")",
"{",
"return",
"function",
"(",
"filename",
")",
"{",
"var",
"chunks",
"=",
"[",
"]",
";",
"function",
"transform",
"(",
"chunk",
",",
"encoding",
",",
"done",
")",
"{",
"/* jshint validthis:true */",
"chunks",
".",
"push",
"(",
"chunk",
")",
";",
"this",
".",
"push",
"(",
"chunk",
")",
";",
"done",
"(",
")",
";",
"}",
"function",
"flush",
"(",
"done",
")",
"{",
"callback",
"(",
"filename",
",",
"chunks",
".",
"join",
"(",
"''",
")",
",",
"done",
")",
";",
"if",
"(",
"callback",
".",
"length",
"<",
"3",
")",
"{",
"done",
"(",
")",
";",
"}",
"}",
"return",
"through",
"(",
"transform",
",",
"flush",
")",
";",
"}",
"}"
] | Call the given method for each file on its completion.
@param {function(string,string,[function])} callback A method to call with name, contents, and optional async done | [
"Call",
"the",
"given",
"method",
"for",
"each",
"file",
"on",
"its",
"completion",
"."
] | 47aa05164d73ec7512bdd4a18db0e12fa6b96209 | https://github.com/bholloway/browserify-debug-tools/blob/47aa05164d73ec7512bdd4a18db0e12fa6b96209/lib/inspect.js#L7-L27 |
48,889 | boylesoftware/x2node-dbos | lib/query-tree-builder.js | getKeyColumn | function getKeyColumn(propDesc, keyPropContainer) {
if (propDesc.keyColumn)
return propDesc.keyColumn;
const keyPropDesc = keyPropContainer.getPropertyDesc(
propDesc.keyPropertyName);
return keyPropDesc.column;
} | javascript | function getKeyColumn(propDesc, keyPropContainer) {
if (propDesc.keyColumn)
return propDesc.keyColumn;
const keyPropDesc = keyPropContainer.getPropertyDesc(
propDesc.keyPropertyName);
return keyPropDesc.column;
} | [
"function",
"getKeyColumn",
"(",
"propDesc",
",",
"keyPropContainer",
")",
"{",
"if",
"(",
"propDesc",
".",
"keyColumn",
")",
"return",
"propDesc",
".",
"keyColumn",
";",
"const",
"keyPropDesc",
"=",
"keyPropContainer",
".",
"getPropertyDesc",
"(",
"propDesc",
".",
"keyPropertyName",
")",
";",
"return",
"keyPropDesc",
".",
"column",
";",
"}"
] | Get map key column.
@private
@param {module:x2node-records~PropertyDescriptor} propDesc Map property
descriptor.
@param {module:x2node-records~PropertiesContainer} keyPropContainer Container
where to look for the key property, if applicable.
@returns {string} Column name. | [
"Get",
"map",
"key",
"column",
"."
] | d7b847d859b79dce0c46e04788201e05d5a70886 | https://github.com/boylesoftware/x2node-dbos/blob/d7b847d859b79dce0c46e04788201e05d5a70886/lib/query-tree-builder.js#L30-L36 |
48,890 | boylesoftware/x2node-dbos | lib/query-tree-builder.js | makeSelector | function makeSelector(sql, markup) {
return {
sql: (sql instanceof Translatable ? sql.translate.bind(sql) : sql),
markup: markup
};
} | javascript | function makeSelector(sql, markup) {
return {
sql: (sql instanceof Translatable ? sql.translate.bind(sql) : sql),
markup: markup
};
} | [
"function",
"makeSelector",
"(",
"sql",
",",
"markup",
")",
"{",
"return",
"{",
"sql",
":",
"(",
"sql",
"instanceof",
"Translatable",
"?",
"sql",
".",
"translate",
".",
"bind",
"(",
"sql",
")",
":",
"sql",
")",
",",
"markup",
":",
"markup",
"}",
";",
"}"
] | Create and return an object for the select list element.
@private
@param {(string|module:x2node-dbos~Translatable|function)} sql The
value, which can be a SQL expression, a value expression object or a SQL
translation function.
@param {string} markup Markup for the result set parser.
@returns {Object} The select list element descriptor. | [
"Create",
"and",
"return",
"an",
"object",
"for",
"the",
"select",
"list",
"element",
"."
] | d7b847d859b79dce0c46e04788201e05d5a70886 | https://github.com/boylesoftware/x2node-dbos/blob/d7b847d859b79dce0c46e04788201e05d5a70886/lib/query-tree-builder.js#L48-L53 |
48,891 | boylesoftware/x2node-dbos | lib/query-tree-builder.js | makeOrderElement | function makeOrderElement(sql) {
return {
sql: (sql instanceof Translatable ? sql.translate.bind(sql) : sql)
};
} | javascript | function makeOrderElement(sql) {
return {
sql: (sql instanceof Translatable ? sql.translate.bind(sql) : sql)
};
} | [
"function",
"makeOrderElement",
"(",
"sql",
")",
"{",
"return",
"{",
"sql",
":",
"(",
"sql",
"instanceof",
"Translatable",
"?",
"sql",
".",
"translate",
".",
"bind",
"(",
"sql",
")",
":",
"sql",
")",
"}",
";",
"}"
] | Create and return an object for the order list element.
@private
@param {(string|module:x2node-dbos~Translatable|function)} sql The
value, which can be a SQL expression, a value expression object or a SQL
translation function.
@returns {Object} The order list element descriptor. | [
"Create",
"and",
"return",
"an",
"object",
"for",
"the",
"order",
"list",
"element",
"."
] | d7b847d859b79dce0c46e04788201e05d5a70886 | https://github.com/boylesoftware/x2node-dbos/blob/d7b847d859b79dce0c46e04788201e05d5a70886/lib/query-tree-builder.js#L64-L68 |
48,892 | boylesoftware/x2node-dbos | lib/query-tree-builder.js | buildQueryTree | function buildQueryTree(
dbDriver, recordTypes, propsTree, anchorNode, clauses, singleAxis) {
// get and validate top records specification data
const recordTypeDesc = recordTypes.getRecordTypeDesc(
propsTree.desc.refTarget);
const topIdPropName = recordTypeDesc.idPropertyName;
const topIdColumn = recordTypeDesc.getPropertyDesc(topIdPropName).column;
// create top query tree node
const topNode = (
anchorNode ?
anchorNode.createChildNode(
propsTree, recordTypeDesc.table, topIdColumn,
false, false,
topIdColumn, topIdColumn) :
new QueryTreeNode(
dbDriver, recordTypes, new Map(), new Map(), new Map(),
singleAxis, propsTree, true, recordTypeDesc.table, 'z',
topIdColumn)
);
topNode.rootPropNode = propsTree;
// add top record id property to have it in front of the select list
const idPropSql = topNode.tableAlias + '.' + topIdColumn;
topNode.addSelect(makeSelector(idPropSql, topIdPropName));
topNode.addPropSql(topIdPropName, idPropSql);
topNode.addPropValueColumn(
topIdPropName, topNode.table, topNode.tableAlias, topIdColumn);
// add the rest of selected properties
if (propsTree.hasChildren()) {
const topMarkupCtx = {
prefix: '',
nextChildMarkupDisc: 'a'.charCodeAt(0)
};
for (let p of propsTree.children)
if (!p.desc.isId()) // already included
topNode.addProperty(p, clauses, topMarkupCtx);
}
// return the query tree
return topNode;
} | javascript | function buildQueryTree(
dbDriver, recordTypes, propsTree, anchorNode, clauses, singleAxis) {
// get and validate top records specification data
const recordTypeDesc = recordTypes.getRecordTypeDesc(
propsTree.desc.refTarget);
const topIdPropName = recordTypeDesc.idPropertyName;
const topIdColumn = recordTypeDesc.getPropertyDesc(topIdPropName).column;
// create top query tree node
const topNode = (
anchorNode ?
anchorNode.createChildNode(
propsTree, recordTypeDesc.table, topIdColumn,
false, false,
topIdColumn, topIdColumn) :
new QueryTreeNode(
dbDriver, recordTypes, new Map(), new Map(), new Map(),
singleAxis, propsTree, true, recordTypeDesc.table, 'z',
topIdColumn)
);
topNode.rootPropNode = propsTree;
// add top record id property to have it in front of the select list
const idPropSql = topNode.tableAlias + '.' + topIdColumn;
topNode.addSelect(makeSelector(idPropSql, topIdPropName));
topNode.addPropSql(topIdPropName, idPropSql);
topNode.addPropValueColumn(
topIdPropName, topNode.table, topNode.tableAlias, topIdColumn);
// add the rest of selected properties
if (propsTree.hasChildren()) {
const topMarkupCtx = {
prefix: '',
nextChildMarkupDisc: 'a'.charCodeAt(0)
};
for (let p of propsTree.children)
if (!p.desc.isId()) // already included
topNode.addProperty(p, clauses, topMarkupCtx);
}
// return the query tree
return topNode;
} | [
"function",
"buildQueryTree",
"(",
"dbDriver",
",",
"recordTypes",
",",
"propsTree",
",",
"anchorNode",
",",
"clauses",
",",
"singleAxis",
")",
"{",
"// get and validate top records specification data",
"const",
"recordTypeDesc",
"=",
"recordTypes",
".",
"getRecordTypeDesc",
"(",
"propsTree",
".",
"desc",
".",
"refTarget",
")",
";",
"const",
"topIdPropName",
"=",
"recordTypeDesc",
".",
"idPropertyName",
";",
"const",
"topIdColumn",
"=",
"recordTypeDesc",
".",
"getPropertyDesc",
"(",
"topIdPropName",
")",
".",
"column",
";",
"// create top query tree node",
"const",
"topNode",
"=",
"(",
"anchorNode",
"?",
"anchorNode",
".",
"createChildNode",
"(",
"propsTree",
",",
"recordTypeDesc",
".",
"table",
",",
"topIdColumn",
",",
"false",
",",
"false",
",",
"topIdColumn",
",",
"topIdColumn",
")",
":",
"new",
"QueryTreeNode",
"(",
"dbDriver",
",",
"recordTypes",
",",
"new",
"Map",
"(",
")",
",",
"new",
"Map",
"(",
")",
",",
"new",
"Map",
"(",
")",
",",
"singleAxis",
",",
"propsTree",
",",
"true",
",",
"recordTypeDesc",
".",
"table",
",",
"'z'",
",",
"topIdColumn",
")",
")",
";",
"topNode",
".",
"rootPropNode",
"=",
"propsTree",
";",
"// add top record id property to have it in front of the select list",
"const",
"idPropSql",
"=",
"topNode",
".",
"tableAlias",
"+",
"'.'",
"+",
"topIdColumn",
";",
"topNode",
".",
"addSelect",
"(",
"makeSelector",
"(",
"idPropSql",
",",
"topIdPropName",
")",
")",
";",
"topNode",
".",
"addPropSql",
"(",
"topIdPropName",
",",
"idPropSql",
")",
";",
"topNode",
".",
"addPropValueColumn",
"(",
"topIdPropName",
",",
"topNode",
".",
"table",
",",
"topNode",
".",
"tableAlias",
",",
"topIdColumn",
")",
";",
"// add the rest of selected properties",
"if",
"(",
"propsTree",
".",
"hasChildren",
"(",
")",
")",
"{",
"const",
"topMarkupCtx",
"=",
"{",
"prefix",
":",
"''",
",",
"nextChildMarkupDisc",
":",
"'a'",
".",
"charCodeAt",
"(",
"0",
")",
"}",
";",
"for",
"(",
"let",
"p",
"of",
"propsTree",
".",
"children",
")",
"if",
"(",
"!",
"p",
".",
"desc",
".",
"isId",
"(",
")",
")",
"// already included",
"topNode",
".",
"addProperty",
"(",
"p",
",",
"clauses",
",",
"topMarkupCtx",
")",
";",
"}",
"// return the query tree",
"return",
"topNode",
";",
"}"
] | Build query tree.
@private
@param {module:x2node-dbos.DBDriver} dbDriver The database driver.
@param {module:x2node-records~RecordTypesLibrary} recordTypes Record types
library.
@param {module:x2node-dbos~PropertyTreeNode} propsTree Selected properties
tree.
@param {module:x2node-dbos~QueryTreeNode} [anchorNode] Anchor table node,
if any.
@param {Array.<string>} clauses The clauses to include from the properties
tree.
@param {boolean} singleAxis <code>true</code> to enforce single axis query
tree.
@returns {module:x2node-dbos~QueryTreeNode} Top node of the query tree. | [
"Build",
"query",
"tree",
"."
] | d7b847d859b79dce0c46e04788201e05d5a70886 | https://github.com/boylesoftware/x2node-dbos/blob/d7b847d859b79dce0c46e04788201e05d5a70886/lib/query-tree-builder.js#L1662-L1705 |
48,893 | aaronabramov/esfmt | package/list.js | long | function long(nodes, context, recur, wrap) {
context.write(WRAPPERS[wrap].left);
for (var i = 0; i < nodes.length; i++) {
recur(nodes[i]);
if (nodes[i + 1]) {
context.write(', ');}}
context.write(WRAPPERS[wrap].right);} | javascript | function long(nodes, context, recur, wrap) {
context.write(WRAPPERS[wrap].left);
for (var i = 0; i < nodes.length; i++) {
recur(nodes[i]);
if (nodes[i + 1]) {
context.write(', ');}}
context.write(WRAPPERS[wrap].right);} | [
"function",
"long",
"(",
"nodes",
",",
"context",
",",
"recur",
",",
"wrap",
")",
"{",
"context",
".",
"write",
"(",
"WRAPPERS",
"[",
"wrap",
"]",
".",
"left",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"nodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"recur",
"(",
"nodes",
"[",
"i",
"]",
")",
";",
"if",
"(",
"nodes",
"[",
"i",
"+",
"1",
"]",
")",
"{",
"context",
".",
"write",
"(",
"', '",
")",
";",
"}",
"}",
"context",
".",
"write",
"(",
"WRAPPERS",
"[",
"wrap",
"]",
".",
"right",
")",
";",
"}"
] | Render the long version of the list
@example
[1, 2, 3, 4, 5] | [
"Render",
"the",
"long",
"version",
"of",
"the",
"list"
] | 8e05fa01d777d504f965ba484c287139a00b5b00 | https://github.com/aaronabramov/esfmt/blob/8e05fa01d777d504f965ba484c287139a00b5b00/package/list.js#L28-L39 |
48,894 | aaronabramov/esfmt | package/list.js | short | function short(nodes, context, recur, wrap) {
context.write(WRAPPERS[wrap].left);
context.indentIn();
context.write('\n');
for (var i = 0; i < nodes.length; i++) {
context.write(context.getIndent());
recur(nodes[i]);
if (nodes[i + 1]) {
context.write(',\n');}}
context.indentOut();
context.write('\n', context.getIndent(), WRAPPERS[wrap].right);} | javascript | function short(nodes, context, recur, wrap) {
context.write(WRAPPERS[wrap].left);
context.indentIn();
context.write('\n');
for (var i = 0; i < nodes.length; i++) {
context.write(context.getIndent());
recur(nodes[i]);
if (nodes[i + 1]) {
context.write(',\n');}}
context.indentOut();
context.write('\n', context.getIndent(), WRAPPERS[wrap].right);} | [
"function",
"short",
"(",
"nodes",
",",
"context",
",",
"recur",
",",
"wrap",
")",
"{",
"context",
".",
"write",
"(",
"WRAPPERS",
"[",
"wrap",
"]",
".",
"left",
")",
";",
"context",
".",
"indentIn",
"(",
")",
";",
"context",
".",
"write",
"(",
"'\\n'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"nodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"context",
".",
"write",
"(",
"context",
".",
"getIndent",
"(",
")",
")",
";",
"recur",
"(",
"nodes",
"[",
"i",
"]",
")",
";",
"if",
"(",
"nodes",
"[",
"i",
"+",
"1",
"]",
")",
"{",
"context",
".",
"write",
"(",
"',\\n'",
")",
";",
"}",
"}",
"context",
".",
"indentOut",
"(",
")",
";",
"context",
".",
"write",
"(",
"'\\n'",
",",
"context",
".",
"getIndent",
"(",
")",
",",
"WRAPPERS",
"[",
"wrap",
"]",
".",
"right",
")",
";",
"}"
] | Render the short or compact version of the list
@example
[
1,
2,
3,
4
] | [
"Render",
"the",
"short",
"or",
"compact",
"version",
"of",
"the",
"list"
] | 8e05fa01d777d504f965ba484c287139a00b5b00 | https://github.com/aaronabramov/esfmt/blob/8e05fa01d777d504f965ba484c287139a00b5b00/package/list.js#L53-L68 |
48,895 | meetings/gearsloth | lib/gearman/multiserver-worker.js | MultiserverWorker | function MultiserverWorker(servers, func_name, callback, options) {
var that = this;
options = options || {};
Multiserver.call(this, servers, function(server, index) {
return new gearman.Worker(func_name, function(payload, worker) {
that._debug('received job from', that._serverString(index));
return callback(payload, worker);
}, {
host: server.host,
port: server.port,
debug: options.debug || false
});
}, Multiserver.component_prefix(options.component_name) + 'worker');
} | javascript | function MultiserverWorker(servers, func_name, callback, options) {
var that = this;
options = options || {};
Multiserver.call(this, servers, function(server, index) {
return new gearman.Worker(func_name, function(payload, worker) {
that._debug('received job from', that._serverString(index));
return callback(payload, worker);
}, {
host: server.host,
port: server.port,
debug: options.debug || false
});
}, Multiserver.component_prefix(options.component_name) + 'worker');
} | [
"function",
"MultiserverWorker",
"(",
"servers",
",",
"func_name",
",",
"callback",
",",
"options",
")",
"{",
"var",
"that",
"=",
"this",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"Multiserver",
".",
"call",
"(",
"this",
",",
"servers",
",",
"function",
"(",
"server",
",",
"index",
")",
"{",
"return",
"new",
"gearman",
".",
"Worker",
"(",
"func_name",
",",
"function",
"(",
"payload",
",",
"worker",
")",
"{",
"that",
".",
"_debug",
"(",
"'received job from'",
",",
"that",
".",
"_serverString",
"(",
"index",
")",
")",
";",
"return",
"callback",
"(",
"payload",
",",
"worker",
")",
";",
"}",
",",
"{",
"host",
":",
"server",
".",
"host",
",",
"port",
":",
"server",
".",
"port",
",",
"debug",
":",
"options",
".",
"debug",
"||",
"false",
"}",
")",
";",
"}",
",",
"Multiserver",
".",
"component_prefix",
"(",
"options",
".",
"component_name",
")",
"+",
"'worker'",
")",
";",
"}"
] | A gearman worker that supports multiple servers.
Contains multiple gearman-coffee workers that are each
connected to a different server. The workers all run in
the same thread
Servers are provided in an array of json-objects, possible fields are:
`.host`: a string that identifies a gearman job server host
`.port`: an integer that identifies a geaerman job server port
`.debug`: a boolean that tells whether debug mode should be used
@param {[Object]} servers
@param {String} func_name
@param {Function} callback
@param {Object} options
@return {Object} | [
"A",
"gearman",
"worker",
"that",
"supports",
"multiple",
"servers",
".",
"Contains",
"multiple",
"gearman",
"-",
"coffee",
"workers",
"that",
"are",
"each",
"connected",
"to",
"a",
"different",
"server",
".",
"The",
"workers",
"all",
"run",
"in",
"the",
"same",
"thread"
] | 21d07729d6197bdbea515f32922896e3ae485d46 | https://github.com/meetings/gearsloth/blob/21d07729d6197bdbea515f32922896e3ae485d46/lib/gearman/multiserver-worker.js#L25-L38 |
48,896 | cliffano/ae86 | lib/cli.js | exec | function exec() {
var actions = {
commands: {
init: { action: _init },
gen: { action: _gen },
watch: { action: _watch },
drift: { action: _watch },
clean: { action: _clean }
}
};
bag.command(__dirname, actions);
} | javascript | function exec() {
var actions = {
commands: {
init: { action: _init },
gen: { action: _gen },
watch: { action: _watch },
drift: { action: _watch },
clean: { action: _clean }
}
};
bag.command(__dirname, actions);
} | [
"function",
"exec",
"(",
")",
"{",
"var",
"actions",
"=",
"{",
"commands",
":",
"{",
"init",
":",
"{",
"action",
":",
"_init",
"}",
",",
"gen",
":",
"{",
"action",
":",
"_gen",
"}",
",",
"watch",
":",
"{",
"action",
":",
"_watch",
"}",
",",
"drift",
":",
"{",
"action",
":",
"_watch",
"}",
",",
"clean",
":",
"{",
"action",
":",
"_clean",
"}",
"}",
"}",
";",
"bag",
".",
"command",
"(",
"__dirname",
",",
"actions",
")",
";",
"}"
] | Execute AE86 CLI. | [
"Execute",
"AE86",
"CLI",
"."
] | 7687e438a93638231bf7d2bebe1e8b062082a9a3 | https://github.com/cliffano/ae86/blob/7687e438a93638231bf7d2bebe1e8b062082a9a3/lib/cli.js#L30-L43 |
48,897 | observing/fossa | lib/predefine.js | pluck | function pluck(data) {
//
// Either map as array or return object through single map.
//
if (Array.isArray(data)) return data.map(map);
return map(data);
/**
* Recursive mapping function.
*
* @param {Object} d Collection, Model or plain object.
* @returns {Object} plucked object
* @api private
*/
function map(d) {
if (isModel(d)) return pluck(d.attributes);
for (var key in d) {
if (isCollection(d[key])) {
d[key] = pluck(d[key].models);
}
if (isModel(d[key])) {
//
// Delete MongoDB ObjectIDs. The stored state of the model is ambigious
// as the referenced model could have different values in its own
// collection. Hence doing recursive storage should be limited as much
// as possible, since duplicate data will be stored.
//
d[key] = pluck(d[key].attributes);
delete d[key]._id;
}
}
return d;
}
} | javascript | function pluck(data) {
//
// Either map as array or return object through single map.
//
if (Array.isArray(data)) return data.map(map);
return map(data);
/**
* Recursive mapping function.
*
* @param {Object} d Collection, Model or plain object.
* @returns {Object} plucked object
* @api private
*/
function map(d) {
if (isModel(d)) return pluck(d.attributes);
for (var key in d) {
if (isCollection(d[key])) {
d[key] = pluck(d[key].models);
}
if (isModel(d[key])) {
//
// Delete MongoDB ObjectIDs. The stored state of the model is ambigious
// as the referenced model could have different values in its own
// collection. Hence doing recursive storage should be limited as much
// as possible, since duplicate data will be stored.
//
d[key] = pluck(d[key].attributes);
delete d[key]._id;
}
}
return d;
}
} | [
"function",
"pluck",
"(",
"data",
")",
"{",
"//",
"// Either map as array or return object through single map.",
"//",
"if",
"(",
"Array",
".",
"isArray",
"(",
"data",
")",
")",
"return",
"data",
".",
"map",
"(",
"map",
")",
";",
"return",
"map",
"(",
"data",
")",
";",
"/**\n * Recursive mapping function.\n *\n * @param {Object} d Collection, Model or plain object.\n * @returns {Object} plucked object\n * @api private\n */",
"function",
"map",
"(",
"d",
")",
"{",
"if",
"(",
"isModel",
"(",
"d",
")",
")",
"return",
"pluck",
"(",
"d",
".",
"attributes",
")",
";",
"for",
"(",
"var",
"key",
"in",
"d",
")",
"{",
"if",
"(",
"isCollection",
"(",
"d",
"[",
"key",
"]",
")",
")",
"{",
"d",
"[",
"key",
"]",
"=",
"pluck",
"(",
"d",
"[",
"key",
"]",
".",
"models",
")",
";",
"}",
"if",
"(",
"isModel",
"(",
"d",
"[",
"key",
"]",
")",
")",
"{",
"//",
"// Delete MongoDB ObjectIDs. The stored state of the model is ambigious",
"// as the referenced model could have different values in its own",
"// collection. Hence doing recursive storage should be limited as much",
"// as possible, since duplicate data will be stored.",
"//",
"d",
"[",
"key",
"]",
"=",
"pluck",
"(",
"d",
"[",
"key",
"]",
".",
"attributes",
")",
";",
"delete",
"d",
"[",
"key",
"]",
".",
"_id",
";",
"}",
"}",
"return",
"d",
";",
"}",
"}"
] | Recursively pluck attributes from either a Model or Collection.
@param {Array|Object} data Array of Models or single Model
@returns {Mixed} Object or Array of objects
@api private | [
"Recursively",
"pluck",
"attributes",
"from",
"either",
"a",
"Model",
"or",
"Collection",
"."
] | 29b3717ee10a13fb607f5bbddcb8b003faf008c6 | https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/lib/predefine.js#L281-L317 |
48,898 | observing/fossa | lib/predefine.js | map | function map(d) {
if (isModel(d)) return pluck(d.attributes);
for (var key in d) {
if (isCollection(d[key])) {
d[key] = pluck(d[key].models);
}
if (isModel(d[key])) {
//
// Delete MongoDB ObjectIDs. The stored state of the model is ambigious
// as the referenced model could have different values in its own
// collection. Hence doing recursive storage should be limited as much
// as possible, since duplicate data will be stored.
//
d[key] = pluck(d[key].attributes);
delete d[key]._id;
}
}
return d;
} | javascript | function map(d) {
if (isModel(d)) return pluck(d.attributes);
for (var key in d) {
if (isCollection(d[key])) {
d[key] = pluck(d[key].models);
}
if (isModel(d[key])) {
//
// Delete MongoDB ObjectIDs. The stored state of the model is ambigious
// as the referenced model could have different values in its own
// collection. Hence doing recursive storage should be limited as much
// as possible, since duplicate data will be stored.
//
d[key] = pluck(d[key].attributes);
delete d[key]._id;
}
}
return d;
} | [
"function",
"map",
"(",
"d",
")",
"{",
"if",
"(",
"isModel",
"(",
"d",
")",
")",
"return",
"pluck",
"(",
"d",
".",
"attributes",
")",
";",
"for",
"(",
"var",
"key",
"in",
"d",
")",
"{",
"if",
"(",
"isCollection",
"(",
"d",
"[",
"key",
"]",
")",
")",
"{",
"d",
"[",
"key",
"]",
"=",
"pluck",
"(",
"d",
"[",
"key",
"]",
".",
"models",
")",
";",
"}",
"if",
"(",
"isModel",
"(",
"d",
"[",
"key",
"]",
")",
")",
"{",
"//",
"// Delete MongoDB ObjectIDs. The stored state of the model is ambigious",
"// as the referenced model could have different values in its own",
"// collection. Hence doing recursive storage should be limited as much",
"// as possible, since duplicate data will be stored.",
"//",
"d",
"[",
"key",
"]",
"=",
"pluck",
"(",
"d",
"[",
"key",
"]",
".",
"attributes",
")",
";",
"delete",
"d",
"[",
"key",
"]",
".",
"_id",
";",
"}",
"}",
"return",
"d",
";",
"}"
] | Recursive mapping function.
@param {Object} d Collection, Model or plain object.
@returns {Object} plucked object
@api private | [
"Recursive",
"mapping",
"function",
"."
] | 29b3717ee10a13fb607f5bbddcb8b003faf008c6 | https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/lib/predefine.js#L295-L316 |
48,899 | observing/fossa | lib/predefine.js | persist | function persist(client, next) {
var single = isModel(item)
, data;
switch (method) {
case 'create':
data = single ? [ item.clone() ] : item.clone().models;
client.insert(pluck(data), config, function inserted(error, results) {
if (error) return next(error);
//
// Set the _stored property for each model to true.
//
results.forEach(function each(model) {
if (single) return item.stored = model._id;
item.id(model._id).stored = model._id;
});
next(null, results);
});
break;
case 'read':
//
// Models will be read by Model _id if no query was passed or if
// the Model already exists in the database. This would otherwise
// result in data ambiguity.
//
query = query || {};
if (single && item.id) query._id = item.id;
//
// No query and Model has no ObjectId reference, return early.
//
if (single && !Object.keys(query).length) return next(null, null);
//
// Read the documents from the MongoDB database and process
// the results, depending on the item being a Model or Collection.
//
client.find(query, config).toArray(function found(error, results) {
if (error) return next(error);
if (single) results = results[0];
//
// If the item is a model, parse first. After merge the results
// of the read operation in the current item.
//
if (single && options.parse) results = item.parse(results, options);
item.set(results);
next(null, results);
});
break;
case 'update':
case 'patch':
data = single ? [ item ] : item.models;
async.reduce(data, 0, function loopModels(memo, model, fn) {
model = model.clone();
var update = { $set: pluck(model) };
if (config.upsert) update = pluck(model);
client.update({ _id: model.id }, update, config, function updated(error, results) {
if (error) return next(error);
model.stored = model.id;
fn(null, memo + results);
});
}, next);
break;
case 'delete':
data = single ? [ item ] : item.models;
async.reduce(data, 0, function loopModels(memo, model, fn) {
client.remove({ _id: model.id }, config, function updated(error, results) {
if (error) return fn(error);
//
// Update the stored state properties to false.
//
model.stored = false;
fn(null, memo + results);
});
}, next);
break;
}
} | javascript | function persist(client, next) {
var single = isModel(item)
, data;
switch (method) {
case 'create':
data = single ? [ item.clone() ] : item.clone().models;
client.insert(pluck(data), config, function inserted(error, results) {
if (error) return next(error);
//
// Set the _stored property for each model to true.
//
results.forEach(function each(model) {
if (single) return item.stored = model._id;
item.id(model._id).stored = model._id;
});
next(null, results);
});
break;
case 'read':
//
// Models will be read by Model _id if no query was passed or if
// the Model already exists in the database. This would otherwise
// result in data ambiguity.
//
query = query || {};
if (single && item.id) query._id = item.id;
//
// No query and Model has no ObjectId reference, return early.
//
if (single && !Object.keys(query).length) return next(null, null);
//
// Read the documents from the MongoDB database and process
// the results, depending on the item being a Model or Collection.
//
client.find(query, config).toArray(function found(error, results) {
if (error) return next(error);
if (single) results = results[0];
//
// If the item is a model, parse first. After merge the results
// of the read operation in the current item.
//
if (single && options.parse) results = item.parse(results, options);
item.set(results);
next(null, results);
});
break;
case 'update':
case 'patch':
data = single ? [ item ] : item.models;
async.reduce(data, 0, function loopModels(memo, model, fn) {
model = model.clone();
var update = { $set: pluck(model) };
if (config.upsert) update = pluck(model);
client.update({ _id: model.id }, update, config, function updated(error, results) {
if (error) return next(error);
model.stored = model.id;
fn(null, memo + results);
});
}, next);
break;
case 'delete':
data = single ? [ item ] : item.models;
async.reduce(data, 0, function loopModels(memo, model, fn) {
client.remove({ _id: model.id }, config, function updated(error, results) {
if (error) return fn(error);
//
// Update the stored state properties to false.
//
model.stored = false;
fn(null, memo + results);
});
}, next);
break;
}
} | [
"function",
"persist",
"(",
"client",
",",
"next",
")",
"{",
"var",
"single",
"=",
"isModel",
"(",
"item",
")",
",",
"data",
";",
"switch",
"(",
"method",
")",
"{",
"case",
"'create'",
":",
"data",
"=",
"single",
"?",
"[",
"item",
".",
"clone",
"(",
")",
"]",
":",
"item",
".",
"clone",
"(",
")",
".",
"models",
";",
"client",
".",
"insert",
"(",
"pluck",
"(",
"data",
")",
",",
"config",
",",
"function",
"inserted",
"(",
"error",
",",
"results",
")",
"{",
"if",
"(",
"error",
")",
"return",
"next",
"(",
"error",
")",
";",
"//",
"// Set the _stored property for each model to true.",
"//",
"results",
".",
"forEach",
"(",
"function",
"each",
"(",
"model",
")",
"{",
"if",
"(",
"single",
")",
"return",
"item",
".",
"stored",
"=",
"model",
".",
"_id",
";",
"item",
".",
"id",
"(",
"model",
".",
"_id",
")",
".",
"stored",
"=",
"model",
".",
"_id",
";",
"}",
")",
";",
"next",
"(",
"null",
",",
"results",
")",
";",
"}",
")",
";",
"break",
";",
"case",
"'read'",
":",
"//",
"// Models will be read by Model _id if no query was passed or if",
"// the Model already exists in the database. This would otherwise",
"// result in data ambiguity.",
"//",
"query",
"=",
"query",
"||",
"{",
"}",
";",
"if",
"(",
"single",
"&&",
"item",
".",
"id",
")",
"query",
".",
"_id",
"=",
"item",
".",
"id",
";",
"//",
"// No query and Model has no ObjectId reference, return early.",
"//",
"if",
"(",
"single",
"&&",
"!",
"Object",
".",
"keys",
"(",
"query",
")",
".",
"length",
")",
"return",
"next",
"(",
"null",
",",
"null",
")",
";",
"//",
"// Read the documents from the MongoDB database and process",
"// the results, depending on the item being a Model or Collection.",
"//",
"client",
".",
"find",
"(",
"query",
",",
"config",
")",
".",
"toArray",
"(",
"function",
"found",
"(",
"error",
",",
"results",
")",
"{",
"if",
"(",
"error",
")",
"return",
"next",
"(",
"error",
")",
";",
"if",
"(",
"single",
")",
"results",
"=",
"results",
"[",
"0",
"]",
";",
"//",
"// If the item is a model, parse first. After merge the results",
"// of the read operation in the current item.",
"//",
"if",
"(",
"single",
"&&",
"options",
".",
"parse",
")",
"results",
"=",
"item",
".",
"parse",
"(",
"results",
",",
"options",
")",
";",
"item",
".",
"set",
"(",
"results",
")",
";",
"next",
"(",
"null",
",",
"results",
")",
";",
"}",
")",
";",
"break",
";",
"case",
"'update'",
":",
"case",
"'patch'",
":",
"data",
"=",
"single",
"?",
"[",
"item",
"]",
":",
"item",
".",
"models",
";",
"async",
".",
"reduce",
"(",
"data",
",",
"0",
",",
"function",
"loopModels",
"(",
"memo",
",",
"model",
",",
"fn",
")",
"{",
"model",
"=",
"model",
".",
"clone",
"(",
")",
";",
"var",
"update",
"=",
"{",
"$set",
":",
"pluck",
"(",
"model",
")",
"}",
";",
"if",
"(",
"config",
".",
"upsert",
")",
"update",
"=",
"pluck",
"(",
"model",
")",
";",
"client",
".",
"update",
"(",
"{",
"_id",
":",
"model",
".",
"id",
"}",
",",
"update",
",",
"config",
",",
"function",
"updated",
"(",
"error",
",",
"results",
")",
"{",
"if",
"(",
"error",
")",
"return",
"next",
"(",
"error",
")",
";",
"model",
".",
"stored",
"=",
"model",
".",
"id",
";",
"fn",
"(",
"null",
",",
"memo",
"+",
"results",
")",
";",
"}",
")",
";",
"}",
",",
"next",
")",
";",
"break",
";",
"case",
"'delete'",
":",
"data",
"=",
"single",
"?",
"[",
"item",
"]",
":",
"item",
".",
"models",
";",
"async",
".",
"reduce",
"(",
"data",
",",
"0",
",",
"function",
"loopModels",
"(",
"memo",
",",
"model",
",",
"fn",
")",
"{",
"client",
".",
"remove",
"(",
"{",
"_id",
":",
"model",
".",
"id",
"}",
",",
"config",
",",
"function",
"updated",
"(",
"error",
",",
"results",
")",
"{",
"if",
"(",
"error",
")",
"return",
"fn",
"(",
"error",
")",
";",
"//",
"// Update the stored state properties to false.",
"//",
"model",
".",
"stored",
"=",
"false",
";",
"fn",
"(",
"null",
",",
"memo",
"+",
"results",
")",
";",
"}",
")",
";",
"}",
",",
"next",
")",
";",
"break",
";",
"}",
"}"
] | Persist item data to MongoDB.
@param {Object} client Fossa MongoDB client
@param {Function} next callback
@api private | [
"Persist",
"item",
"data",
"to",
"MongoDB",
"."
] | 29b3717ee10a13fb607f5bbddcb8b003faf008c6 | https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/lib/predefine.js#L326-L413 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.