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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
greggman/HappyFunTimes | server/player.js | function(client, relayServer, id) {
this.client = client;
this.relayServer = relayServer;
this.id = id;
debug("" + id + ": start player");
var addPlayerToGame = function(data) {
var game = this.relayServer.addPlayerToGame(this, data.gameId, data.data);
if (!game) {
// TODO: Make this URL set from some global so we can set it some place else.
debug("game does not exist:", data.gameId);
this.disconnect();
} else {
this.setGame(game);
}
}.bind(this);
this.setGame = function(game) {
this.game = game;
}.bind(this);
var assignAsServerForGame = function(data) {
this.client.on('message', undefined);
this.client.on('disconnect', undefined);
this.relayServer.assignAsClientForGame(data, this.client);
}.bind(this);
var passMessageFromPlayerToGame = function(data) {
if (!this.game) {
console.warn("player " + this.id + " has no game");
return;
}
this.game.send(this, {
cmd: 'update',
id: this.id,
data: data,
});
}.bind(this);
var messageHandlers = {
'join': addPlayerToGame,
'server': assignAsServerForGame,
'update': passMessageFromPlayerToGame,
};
var onMessage = function(message) {
var cmd = message.cmd;
var handler = messageHandlers[cmd];
if (!handler) {
console.error("unknown player message: " + cmd);
return;
}
handler(message.data);
};
var onDisconnect = function() {
debug("" + this.id + ": disconnected");
if (this.game) {
this.game.removePlayer(this);
}
this.disconnect();
}.bind(this);
client.on('message', onMessage);
client.on('disconnect', onDisconnect);
} | javascript | function(client, relayServer, id) {
this.client = client;
this.relayServer = relayServer;
this.id = id;
debug("" + id + ": start player");
var addPlayerToGame = function(data) {
var game = this.relayServer.addPlayerToGame(this, data.gameId, data.data);
if (!game) {
// TODO: Make this URL set from some global so we can set it some place else.
debug("game does not exist:", data.gameId);
this.disconnect();
} else {
this.setGame(game);
}
}.bind(this);
this.setGame = function(game) {
this.game = game;
}.bind(this);
var assignAsServerForGame = function(data) {
this.client.on('message', undefined);
this.client.on('disconnect', undefined);
this.relayServer.assignAsClientForGame(data, this.client);
}.bind(this);
var passMessageFromPlayerToGame = function(data) {
if (!this.game) {
console.warn("player " + this.id + " has no game");
return;
}
this.game.send(this, {
cmd: 'update',
id: this.id,
data: data,
});
}.bind(this);
var messageHandlers = {
'join': addPlayerToGame,
'server': assignAsServerForGame,
'update': passMessageFromPlayerToGame,
};
var onMessage = function(message) {
var cmd = message.cmd;
var handler = messageHandlers[cmd];
if (!handler) {
console.error("unknown player message: " + cmd);
return;
}
handler(message.data);
};
var onDisconnect = function() {
debug("" + this.id + ": disconnected");
if (this.game) {
this.game.removePlayer(this);
}
this.disconnect();
}.bind(this);
client.on('message', onMessage);
client.on('disconnect', onDisconnect);
} | [
"function",
"(",
"client",
",",
"relayServer",
",",
"id",
")",
"{",
"this",
".",
"client",
"=",
"client",
";",
"this",
".",
"relayServer",
"=",
"relayServer",
";",
"this",
".",
"id",
"=",
"id",
";",
"debug",
"(",
"\"\"",
"+",
"id",
"+",
"\": start player\"",
")",
";",
"var",
"addPlayerToGame",
"=",
"function",
"(",
"data",
")",
"{",
"var",
"game",
"=",
"this",
".",
"relayServer",
".",
"addPlayerToGame",
"(",
"this",
",",
"data",
".",
"gameId",
",",
"data",
".",
"data",
")",
";",
"if",
"(",
"!",
"game",
")",
"{",
"debug",
"(",
"\"game does not exist:\"",
",",
"data",
".",
"gameId",
")",
";",
"this",
".",
"disconnect",
"(",
")",
";",
"}",
"else",
"{",
"this",
".",
"setGame",
"(",
"game",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"setGame",
"=",
"function",
"(",
"game",
")",
"{",
"this",
".",
"game",
"=",
"game",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"var",
"assignAsServerForGame",
"=",
"function",
"(",
"data",
")",
"{",
"this",
".",
"client",
".",
"on",
"(",
"'message'",
",",
"undefined",
")",
";",
"this",
".",
"client",
".",
"on",
"(",
"'disconnect'",
",",
"undefined",
")",
";",
"this",
".",
"relayServer",
".",
"assignAsClientForGame",
"(",
"data",
",",
"this",
".",
"client",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"var",
"passMessageFromPlayerToGame",
"=",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"!",
"this",
".",
"game",
")",
"{",
"console",
".",
"warn",
"(",
"\"player \"",
"+",
"this",
".",
"id",
"+",
"\" has no game\"",
")",
";",
"return",
";",
"}",
"this",
".",
"game",
".",
"send",
"(",
"this",
",",
"{",
"cmd",
":",
"'update'",
",",
"id",
":",
"this",
".",
"id",
",",
"data",
":",
"data",
",",
"}",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"var",
"messageHandlers",
"=",
"{",
"'join'",
":",
"addPlayerToGame",
",",
"'server'",
":",
"assignAsServerForGame",
",",
"'update'",
":",
"passMessageFromPlayerToGame",
",",
"}",
";",
"var",
"onMessage",
"=",
"function",
"(",
"message",
")",
"{",
"var",
"cmd",
"=",
"message",
".",
"cmd",
";",
"var",
"handler",
"=",
"messageHandlers",
"[",
"cmd",
"]",
";",
"if",
"(",
"!",
"handler",
")",
"{",
"console",
".",
"error",
"(",
"\"unknown player message: \"",
"+",
"cmd",
")",
";",
"return",
";",
"}",
"handler",
"(",
"message",
".",
"data",
")",
";",
"}",
";",
"var",
"onDisconnect",
"=",
"function",
"(",
")",
"{",
"debug",
"(",
"\"\"",
"+",
"this",
".",
"id",
"+",
"\": disconnected\"",
")",
";",
"if",
"(",
"this",
".",
"game",
")",
"{",
"this",
".",
"game",
".",
"removePlayer",
"(",
"this",
")",
";",
"}",
"this",
".",
"disconnect",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"client",
".",
"on",
"(",
"'message'",
",",
"onMessage",
")",
";",
"client",
".",
"on",
"(",
"'disconnect'",
",",
"onDisconnect",
")",
";",
"}"
] | A Player in a game.
@constructor
@param {!Client} client The websocket for this player
@param {!RelayServer} relayServer The server managing this
player.
@param {string} id a unique id for this player. | [
"A",
"Player",
"in",
"a",
"game",
"."
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/server/player.js#L45-L112 | train |
|
greggman/HappyFunTimes | server/game-group.js | function(gameId, relayServer, options) {
options = options || {};
this.options = options;
this.gameId = gameId;
this.relayServer = relayServer;
this.games = []; // first game is the "master"
this.nextGameId = 0; // start at 0 because it's easy to switch games with (gameNum + numGames + dir) % numGames
} | javascript | function(gameId, relayServer, options) {
options = options || {};
this.options = options;
this.gameId = gameId;
this.relayServer = relayServer;
this.games = []; // first game is the "master"
this.nextGameId = 0; // start at 0 because it's easy to switch games with (gameNum + numGames + dir) % numGames
} | [
"function",
"(",
"gameId",
",",
"relayServer",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"gameId",
"=",
"gameId",
";",
"this",
".",
"relayServer",
"=",
"relayServer",
";",
"this",
".",
"games",
"=",
"[",
"]",
";",
"this",
".",
"nextGameId",
"=",
"0",
";",
"}"
] | Represents a group of games.
Normally a group only has 1 game but
for situations where we need more than
1 game ... | [
"Represents",
"a",
"group",
"of",
"games",
"."
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/server/game-group.js#L45-L52 | train |
|
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | function(str, opt_obj) {
var dst = opt_obj || {};
try {
var q = str.indexOf("?");
var e = str.indexOf("#");
if (e < 0) {
e = str.length;
}
var query = str.substring(q + 1, e);
searchStringToObject(query, dst);
} catch (e) {
console.error(e);
}
return dst;
} | javascript | function(str, opt_obj) {
var dst = opt_obj || {};
try {
var q = str.indexOf("?");
var e = str.indexOf("#");
if (e < 0) {
e = str.length;
}
var query = str.substring(q + 1, e);
searchStringToObject(query, dst);
} catch (e) {
console.error(e);
}
return dst;
} | [
"function",
"(",
"str",
",",
"opt_obj",
")",
"{",
"var",
"dst",
"=",
"opt_obj",
"||",
"{",
"}",
";",
"try",
"{",
"var",
"q",
"=",
"str",
".",
"indexOf",
"(",
"\"?\"",
")",
";",
"var",
"e",
"=",
"str",
".",
"indexOf",
"(",
"\"#\"",
")",
";",
"if",
"(",
"e",
"<",
"0",
")",
"{",
"e",
"=",
"str",
".",
"length",
";",
"}",
"var",
"query",
"=",
"str",
".",
"substring",
"(",
"q",
"+",
"1",
",",
"e",
")",
";",
"searchStringToObject",
"(",
"query",
",",
"dst",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"e",
")",
";",
"}",
"return",
"dst",
";",
"}"
] | Reads the query values from a URL like string.
@param {String} url URL like string eg. http://foo?key=value
@param {Object} [opt_obj] Object to attach key values to
@return {Object} Object with key values from URL
@memberOf module:Misc | [
"Reads",
"the",
"query",
"values",
"from",
"a",
"URL",
"like",
"string",
"."
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L132-L146 | train |
|
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | gotoIFrame | function gotoIFrame(src) {
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = src;
document.body.appendChild(iframe);
return iframe;
} | javascript | function gotoIFrame(src) {
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = src;
document.body.appendChild(iframe);
return iframe;
} | [
"function",
"gotoIFrame",
"(",
"src",
")",
"{",
"var",
"iframe",
"=",
"document",
".",
"createElement",
"(",
"\"iframe\"",
")",
";",
"iframe",
".",
"style",
".",
"display",
"=",
"\"none\"",
";",
"iframe",
".",
"src",
"=",
"src",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"iframe",
")",
";",
"return",
"iframe",
";",
"}"
] | Creates an invisible iframe and sets the src
@param {string} src the source for the iframe
@return {HTMLIFrameElement} The iframe | [
"Creates",
"an",
"invisible",
"iframe",
"and",
"sets",
"the",
"src"
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L214-L220 | train |
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | function(opt_randFunc) {
var randFunc = opt_randFunc || randInt;
var strong = randFunc(3);
var colors = [];
for (var ii = 0; ii < 3; ++ii) {
colors.push(randFunc(128) + (ii === strong ? 128 : 64));
}
return "rgb(" + colors.join(",") + ")";
} | javascript | function(opt_randFunc) {
var randFunc = opt_randFunc || randInt;
var strong = randFunc(3);
var colors = [];
for (var ii = 0; ii < 3; ++ii) {
colors.push(randFunc(128) + (ii === strong ? 128 : 64));
}
return "rgb(" + colors.join(",") + ")";
} | [
"function",
"(",
"opt_randFunc",
")",
"{",
"var",
"randFunc",
"=",
"opt_randFunc",
"||",
"randInt",
";",
"var",
"strong",
"=",
"randFunc",
"(",
"3",
")",
";",
"var",
"colors",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"3",
";",
"++",
"ii",
")",
"{",
"colors",
".",
"push",
"(",
"randFunc",
"(",
"128",
")",
"+",
"(",
"ii",
"===",
"strong",
"?",
"128",
":",
"64",
")",
")",
";",
"}",
"return",
"\"rgb(\"",
"+",
"colors",
".",
"join",
"(",
"\",\"",
")",
"+",
"\")\"",
";",
"}"
] | get a random CSS color
@param {function(number): number?) opt_randFunc function to generate random numbers
@return {string} random css color
@memberOf module:Misc | [
"get",
"a",
"random",
"CSS",
"color"
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L238-L246 | train |
|
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | function(opt_randFunc) {
var randFunc = opt_randFunc || randInt;
var strong = randFunc(3);
var color = 0xFF;
for (var ii = 0; ii < 3; ++ii) {
color = (color << 8) | (randFunc(128) + (ii === strong ? 128 : 64));
}
return color;
} | javascript | function(opt_randFunc) {
var randFunc = opt_randFunc || randInt;
var strong = randFunc(3);
var color = 0xFF;
for (var ii = 0; ii < 3; ++ii) {
color = (color << 8) | (randFunc(128) + (ii === strong ? 128 : 64));
}
return color;
} | [
"function",
"(",
"opt_randFunc",
")",
"{",
"var",
"randFunc",
"=",
"opt_randFunc",
"||",
"randInt",
";",
"var",
"strong",
"=",
"randFunc",
"(",
"3",
")",
";",
"var",
"color",
"=",
"0xFF",
";",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"3",
";",
"++",
"ii",
")",
"{",
"color",
"=",
"(",
"color",
"<<",
"8",
")",
"|",
"(",
"randFunc",
"(",
"128",
")",
"+",
"(",
"ii",
"===",
"strong",
"?",
"128",
":",
"64",
")",
")",
";",
"}",
"return",
"color",
";",
"}"
] | get a random 32bit color
@param {function(number): number?) opt_randFunc function to generate random numbers
@return {string} random 32bit color
@memberOf module:Misc | [
"get",
"a",
"random",
"32bit",
"color"
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L263-L271 | train |
|
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | function(selector) {
for (var ii = 0; ii < document.styleSheets.length; ++ii) {
var styleSheet = document.styleSheets[ii];
var rules = styleSheet.cssRules || styleSheet.rules;
if (rules) {
for (var rr = 0; rr < rules.length; ++rr) {
var rule = rules[rr];
if (rule.selectorText === selector) {
return rule;
}
}
}
}
} | javascript | function(selector) {
for (var ii = 0; ii < document.styleSheets.length; ++ii) {
var styleSheet = document.styleSheets[ii];
var rules = styleSheet.cssRules || styleSheet.rules;
if (rules) {
for (var rr = 0; rr < rules.length; ++rr) {
var rule = rules[rr];
if (rule.selectorText === selector) {
return rule;
}
}
}
}
} | [
"function",
"(",
"selector",
")",
"{",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"document",
".",
"styleSheets",
".",
"length",
";",
"++",
"ii",
")",
"{",
"var",
"styleSheet",
"=",
"document",
".",
"styleSheets",
"[",
"ii",
"]",
";",
"var",
"rules",
"=",
"styleSheet",
".",
"cssRules",
"||",
"styleSheet",
".",
"rules",
";",
"if",
"(",
"rules",
")",
"{",
"for",
"(",
"var",
"rr",
"=",
"0",
";",
"rr",
"<",
"rules",
".",
"length",
";",
"++",
"rr",
")",
"{",
"var",
"rule",
"=",
"rules",
"[",
"rr",
"]",
";",
"if",
"(",
"rule",
".",
"selectorText",
"===",
"selector",
")",
"{",
"return",
"rule",
";",
"}",
"}",
"}",
"}",
"}"
] | finds a CSS rule.
@param {string} selector
@return {Rule?} matching css rule
@memberOf module:Misc | [
"finds",
"a",
"CSS",
"rule",
"."
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L279-L292 | train |
|
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | function(element) {
var r = { x: element.offsetLeft, y: element.offsetTop };
if (element.offsetParent) {
var tmp = getAbsolutePosition(element.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
} | javascript | function(element) {
var r = { x: element.offsetLeft, y: element.offsetTop };
if (element.offsetParent) {
var tmp = getAbsolutePosition(element.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
} | [
"function",
"(",
"element",
")",
"{",
"var",
"r",
"=",
"{",
"x",
":",
"element",
".",
"offsetLeft",
",",
"y",
":",
"element",
".",
"offsetTop",
"}",
";",
"if",
"(",
"element",
".",
"offsetParent",
")",
"{",
"var",
"tmp",
"=",
"getAbsolutePosition",
"(",
"element",
".",
"offsetParent",
")",
";",
"r",
".",
"x",
"+=",
"tmp",
".",
"x",
";",
"r",
".",
"y",
"+=",
"tmp",
".",
"y",
";",
"}",
"return",
"r",
";",
"}"
] | Returns the absolute position of an element for certain browsers.
@param {HTMLElement} element The element to get a position
for.
@returns {Object} An object containing x and y as the
absolute position of the given element.
@memberOf module:Misc | [
"Returns",
"the",
"absolute",
"position",
"of",
"an",
"element",
"for",
"certain",
"browsers",
"."
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L314-L322 | train |
|
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | function(canvas, useDevicePixelRatio) {
var mult = useDevicePixelRatio ? window.devicePixelRatio : 1;
mult = mult || 1;
var width = Math.floor(canvas.clientWidth * mult);
var height = Math.floor(canvas.clientHeight * mult);
if (canvas.width !== width ||
canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
} | javascript | function(canvas, useDevicePixelRatio) {
var mult = useDevicePixelRatio ? window.devicePixelRatio : 1;
mult = mult || 1;
var width = Math.floor(canvas.clientWidth * mult);
var height = Math.floor(canvas.clientHeight * mult);
if (canvas.width !== width ||
canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
} | [
"function",
"(",
"canvas",
",",
"useDevicePixelRatio",
")",
"{",
"var",
"mult",
"=",
"useDevicePixelRatio",
"?",
"window",
".",
"devicePixelRatio",
":",
"1",
";",
"mult",
"=",
"mult",
"||",
"1",
";",
"var",
"width",
"=",
"Math",
".",
"floor",
"(",
"canvas",
".",
"clientWidth",
"*",
"mult",
")",
";",
"var",
"height",
"=",
"Math",
".",
"floor",
"(",
"canvas",
".",
"clientHeight",
"*",
"mult",
")",
";",
"if",
"(",
"canvas",
".",
"width",
"!==",
"width",
"||",
"canvas",
".",
"height",
"!==",
"height",
")",
"{",
"canvas",
".",
"width",
"=",
"width",
";",
"canvas",
".",
"height",
"=",
"height",
";",
"return",
"true",
";",
"}",
"}"
] | Resizes a cavnas to match its CSS displayed size.
@param {Canvas} canvas canvas to resize.
@param {boolean?} useDevicePixelRatio if true canvas will be
created to match devicePixelRatio.
@memberOf module:Misc | [
"Resizes",
"a",
"cavnas",
"to",
"match",
"its",
"CSS",
"displayed",
"size",
"."
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L419-L430 | train |
|
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | applyObject | function applyObject(src, dst) {
Object.keys(src).forEach(function(key) {
dst[key] = src[key];
});
return dst;
} | javascript | function applyObject(src, dst) {
Object.keys(src).forEach(function(key) {
dst[key] = src[key];
});
return dst;
} | [
"function",
"applyObject",
"(",
"src",
",",
"dst",
")",
"{",
"Object",
".",
"keys",
"(",
"src",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"dst",
"[",
"key",
"]",
"=",
"src",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"dst",
";",
"}"
] | Copies all the src properties to the dst
@param {Object} src an object with some properties
@param {Object} dst an object to receive copes of the properties
@return returns the dst object. | [
"Copies",
"all",
"the",
"src",
"properties",
"to",
"the",
"dst"
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L438-L443 | train |
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | makeRandomId | function makeRandomId(digits) {
digits = digits || 16;
var id = "";
for (var ii = 0; ii < digits; ++ii) {
id = id + ((Math.random() * 16 | 0)).toString(16);
}
return id;
} | javascript | function makeRandomId(digits) {
digits = digits || 16;
var id = "";
for (var ii = 0; ii < digits; ++ii) {
id = id + ((Math.random() * 16 | 0)).toString(16);
}
return id;
} | [
"function",
"makeRandomId",
"(",
"digits",
")",
"{",
"digits",
"=",
"digits",
"||",
"16",
";",
"var",
"id",
"=",
"\"\"",
";",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"digits",
";",
"++",
"ii",
")",
"{",
"id",
"=",
"id",
"+",
"(",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"16",
"|",
"0",
")",
")",
".",
"toString",
"(",
"16",
")",
";",
"}",
"return",
"id",
";",
"}"
] | Creates a random id
@param {number} [digits] number of digits. default 16 | [
"Creates",
"a",
"random",
"id"
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L481-L488 | train |
greggman/HappyFunTimes | src/hft/scripts/misc/misc.js | applyListeners | function applyListeners(emitter, listeners) {
Object.keys(listeners).forEach(function(name) {
emitter.addEventListener(name, listeners[name]);
});
} | javascript | function applyListeners(emitter, listeners) {
Object.keys(listeners).forEach(function(name) {
emitter.addEventListener(name, listeners[name]);
});
} | [
"function",
"applyListeners",
"(",
"emitter",
",",
"listeners",
")",
"{",
"Object",
".",
"keys",
"(",
"listeners",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"emitter",
".",
"addEventListener",
"(",
"name",
",",
"listeners",
"[",
"name",
"]",
")",
";",
"}",
")",
";",
"}"
] | Applies an object of listeners to an emitter.
Example:
applyListeners(someDivElement, {
mousedown: someFunc1,
mousemove: someFunc2,
mouseup: someFunc3,
});
Which is the same as
someDivElement.addEventListener("mousedown", someFunc1);
someDivElement.addEventListener("mousemove", someFunc2);
someDivElement.addEventListener("mouseup", someFunc3);
@param {Emitter} emitter some object that emits events and has a function `addEventListener`
@param {Object.<string, function>} listeners eventname function pairs. | [
"Applies",
"an",
"object",
"of",
"listeners",
"to",
"an",
"emitter",
"."
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/misc/misc.js#L510-L514 | train |
greggman/HappyFunTimes | src/hft/scripts/syncedclock.js | function(opt_syncRateSeconds, callback) {
var query = misc.parseUrlQuery();
var url = (query.hftUrl || window.location.href).replace("ws:", "http:");
var syncRateMS = (opt_syncRateSeconds || 10) * 1000;
var timeOffset = 0;
var syncToServer = function(queueNext) {
var sendTime = getLocalTime();
io.sendJSON(url, {cmd: 'time'}, function(exception, obj) {
if (exception) {
console.error("syncToServer: " + exception);
} else {
var receiveTime = getLocalTime();
var duration = receiveTime - sendTime;
var serverTime = obj.time + duration * 0.5;
timeOffset = serverTime - receiveTime;
if (callback) {
callback();
callback = undefined;
}
//g_services.logger.log("duration: ", duration, " timeOff:", timeOffset);
}
if (queueNext) {
setTimeout(function() {
syncToServer(true);
}, syncRateMS);
}
});
};
var syncToServerNoQueue = function() {
syncToServer(false);
};
syncToServer(true);
setTimeout(syncToServerNoQueue, 1000);
setTimeout(syncToServerNoQueue, 2000);
setTimeout(syncToServerNoQueue, 4000);
/**
* Gets the current time in seconds.
* @private
*/
this.getTime = function() {
return getLocalTime() + timeOffset;
};
} | javascript | function(opt_syncRateSeconds, callback) {
var query = misc.parseUrlQuery();
var url = (query.hftUrl || window.location.href).replace("ws:", "http:");
var syncRateMS = (opt_syncRateSeconds || 10) * 1000;
var timeOffset = 0;
var syncToServer = function(queueNext) {
var sendTime = getLocalTime();
io.sendJSON(url, {cmd: 'time'}, function(exception, obj) {
if (exception) {
console.error("syncToServer: " + exception);
} else {
var receiveTime = getLocalTime();
var duration = receiveTime - sendTime;
var serverTime = obj.time + duration * 0.5;
timeOffset = serverTime - receiveTime;
if (callback) {
callback();
callback = undefined;
}
//g_services.logger.log("duration: ", duration, " timeOff:", timeOffset);
}
if (queueNext) {
setTimeout(function() {
syncToServer(true);
}, syncRateMS);
}
});
};
var syncToServerNoQueue = function() {
syncToServer(false);
};
syncToServer(true);
setTimeout(syncToServerNoQueue, 1000);
setTimeout(syncToServerNoQueue, 2000);
setTimeout(syncToServerNoQueue, 4000);
/**
* Gets the current time in seconds.
* @private
*/
this.getTime = function() {
return getLocalTime() + timeOffset;
};
} | [
"function",
"(",
"opt_syncRateSeconds",
",",
"callback",
")",
"{",
"var",
"query",
"=",
"misc",
".",
"parseUrlQuery",
"(",
")",
";",
"var",
"url",
"=",
"(",
"query",
".",
"hftUrl",
"||",
"window",
".",
"location",
".",
"href",
")",
".",
"replace",
"(",
"\"ws:\"",
",",
"\"http:\"",
")",
";",
"var",
"syncRateMS",
"=",
"(",
"opt_syncRateSeconds",
"||",
"10",
")",
"*",
"1000",
";",
"var",
"timeOffset",
"=",
"0",
";",
"var",
"syncToServer",
"=",
"function",
"(",
"queueNext",
")",
"{",
"var",
"sendTime",
"=",
"getLocalTime",
"(",
")",
";",
"io",
".",
"sendJSON",
"(",
"url",
",",
"{",
"cmd",
":",
"'time'",
"}",
",",
"function",
"(",
"exception",
",",
"obj",
")",
"{",
"if",
"(",
"exception",
")",
"{",
"console",
".",
"error",
"(",
"\"syncToServer: \"",
"+",
"exception",
")",
";",
"}",
"else",
"{",
"var",
"receiveTime",
"=",
"getLocalTime",
"(",
")",
";",
"var",
"duration",
"=",
"receiveTime",
"-",
"sendTime",
";",
"var",
"serverTime",
"=",
"obj",
".",
"time",
"+",
"duration",
"*",
"0.5",
";",
"timeOffset",
"=",
"serverTime",
"-",
"receiveTime",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
")",
";",
"callback",
"=",
"undefined",
";",
"}",
"}",
"if",
"(",
"queueNext",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"syncToServer",
"(",
"true",
")",
";",
"}",
",",
"syncRateMS",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"var",
"syncToServerNoQueue",
"=",
"function",
"(",
")",
"{",
"syncToServer",
"(",
"false",
")",
";",
"}",
";",
"syncToServer",
"(",
"true",
")",
";",
"setTimeout",
"(",
"syncToServerNoQueue",
",",
"1000",
")",
";",
"setTimeout",
"(",
"syncToServerNoQueue",
",",
"2000",
")",
";",
"setTimeout",
"(",
"syncToServerNoQueue",
",",
"4000",
")",
";",
"this",
".",
"getTime",
"=",
"function",
"(",
")",
"{",
"return",
"getLocalTime",
"(",
")",
"+",
"timeOffset",
";",
"}",
";",
"}"
] | A clock that gets the current time in seconds attempting to
keep the clock synced to the server.
@constructor | [
"A",
"clock",
"that",
"gets",
"the",
"current",
"time",
"in",
"seconds",
"attempting",
"to",
"keep",
"the",
"clock",
"synced",
"to",
"the",
"server",
"."
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/src/hft/scripts/syncedclock.js#L120-L167 | train |
|
greggman/HappyFunTimes | docs/assets/js/io.js | function(url, jsonObject, callback, options) {
var options = JSON.parse(JSON.stringify(options || {}));
options.headers = options.headers || {};
options.headers["Content-type"] = "application/json";
return request(
url,
JSON.stringify(jsonObject),
function(err, content) {
if (err) {
return callback(err);
}
try {
var json = JSON.parse(content);
} catch (e) {
return callback(e);
}
callback(null, json);
},
options);
} | javascript | function(url, jsonObject, callback, options) {
var options = JSON.parse(JSON.stringify(options || {}));
options.headers = options.headers || {};
options.headers["Content-type"] = "application/json";
return request(
url,
JSON.stringify(jsonObject),
function(err, content) {
if (err) {
return callback(err);
}
try {
var json = JSON.parse(content);
} catch (e) {
return callback(e);
}
callback(null, json);
},
options);
} | [
"function",
"(",
"url",
",",
"jsonObject",
",",
"callback",
",",
"options",
")",
"{",
"var",
"options",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"options",
"||",
"{",
"}",
")",
")",
";",
"options",
".",
"headers",
"=",
"options",
".",
"headers",
"||",
"{",
"}",
";",
"options",
".",
"headers",
"[",
"\"Content-type\"",
"]",
"=",
"\"application/json\"",
";",
"return",
"request",
"(",
"url",
",",
"JSON",
".",
"stringify",
"(",
"jsonObject",
")",
",",
"function",
"(",
"err",
",",
"content",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"try",
"{",
"var",
"json",
"=",
"JSON",
".",
"parse",
"(",
"content",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"callback",
"(",
"e",
")",
";",
"}",
"callback",
"(",
"null",
",",
"json",
")",
";",
"}",
",",
"options",
")",
";",
"}"
] | sends a JSON 'POST' request, returns JSON repsonse
@memberOf module:IO
@param {string} url url to POST to.
@param {Object=} jsonObject JavaScript object on which to
call JSON.stringify.
@param {!function(error, object)} callback Function to call
on success or failure. If successful error will be
null, object will be json result from request.
@param {module:IO~Request~Options?} options | [
"sends",
"a",
"JSON",
"POST",
"request",
"returns",
"JSON",
"repsonse"
] | 1c29e334ef9eca269980f5fc2b73894452688490 | https://github.com/greggman/HappyFunTimes/blob/1c29e334ef9eca269980f5fc2b73894452688490/docs/assets/js/io.js#L141-L160 | train |
|
alexindigo/asynckit | lib/readable_serial.js | ReadableSerial | function ReadableSerial(list, iterator, callback)
{
if (!(this instanceof ReadableSerial))
{
return new ReadableSerial(list, iterator, callback);
}
// turn on object mode
ReadableSerial.super_.call(this, {objectMode: true});
this._start(serial, list, iterator, callback);
} | javascript | function ReadableSerial(list, iterator, callback)
{
if (!(this instanceof ReadableSerial))
{
return new ReadableSerial(list, iterator, callback);
}
// turn on object mode
ReadableSerial.super_.call(this, {objectMode: true});
this._start(serial, list, iterator, callback);
} | [
"function",
"ReadableSerial",
"(",
"list",
",",
"iterator",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ReadableSerial",
")",
")",
"{",
"return",
"new",
"ReadableSerial",
"(",
"list",
",",
"iterator",
",",
"callback",
")",
";",
"}",
"ReadableSerial",
".",
"super_",
".",
"call",
"(",
"this",
",",
"{",
"objectMode",
":",
"true",
"}",
")",
";",
"this",
".",
"_start",
"(",
"serial",
",",
"list",
",",
"iterator",
",",
"callback",
")",
";",
"}"
] | Streaming wrapper to `asynckit.serial`
@param {array|object} list - array or object (named list) to iterate over
@param {function} iterator - iterator to run
@param {function} callback - invoked when all elements processed
@returns {stream.Readable#} | [
"Streaming",
"wrapper",
"to",
"asynckit",
".",
"serial"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/readable_serial.js#L14-L25 | train |
alexindigo/asynckit | lib/streamify.js | wrapIterator | function wrapIterator(iterator)
{
var stream = this;
return function(item, key, cb)
{
var aborter
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
;
stream.jobs[key] = wrappedCb;
// it's either shortcut (item, cb)
if (iterator.length == 2)
{
aborter = iterator(item, wrappedCb);
}
// or long format (item, key, cb)
else
{
aborter = iterator(item, key, wrappedCb);
}
return aborter;
};
} | javascript | function wrapIterator(iterator)
{
var stream = this;
return function(item, key, cb)
{
var aborter
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
;
stream.jobs[key] = wrappedCb;
// it's either shortcut (item, cb)
if (iterator.length == 2)
{
aborter = iterator(item, wrappedCb);
}
// or long format (item, key, cb)
else
{
aborter = iterator(item, key, wrappedCb);
}
return aborter;
};
} | [
"function",
"wrapIterator",
"(",
"iterator",
")",
"{",
"var",
"stream",
"=",
"this",
";",
"return",
"function",
"(",
"item",
",",
"key",
",",
"cb",
")",
"{",
"var",
"aborter",
",",
"wrappedCb",
"=",
"async",
"(",
"wrapIteratorCallback",
".",
"call",
"(",
"stream",
",",
"cb",
",",
"key",
")",
")",
";",
"stream",
".",
"jobs",
"[",
"key",
"]",
"=",
"wrappedCb",
";",
"if",
"(",
"iterator",
".",
"length",
"==",
"2",
")",
"{",
"aborter",
"=",
"iterator",
"(",
"item",
",",
"wrappedCb",
")",
";",
"}",
"else",
"{",
"aborter",
"=",
"iterator",
"(",
"item",
",",
"key",
",",
"wrappedCb",
")",
";",
"}",
"return",
"aborter",
";",
"}",
";",
"}"
] | Wraps iterators with long signature
@this ReadableAsyncKit#
@param {function} iterator - function to wrap
@returns {function} - wrapped function | [
"Wraps",
"iterators",
"with",
"long",
"signature"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L16-L41 | train |
alexindigo/asynckit | lib/streamify.js | wrapCallback | function wrapCallback(callback)
{
var stream = this;
var wrapped = function(error, result)
{
return finisher.call(stream, error, result, callback);
};
return wrapped;
} | javascript | function wrapCallback(callback)
{
var stream = this;
var wrapped = function(error, result)
{
return finisher.call(stream, error, result, callback);
};
return wrapped;
} | [
"function",
"wrapCallback",
"(",
"callback",
")",
"{",
"var",
"stream",
"=",
"this",
";",
"var",
"wrapped",
"=",
"function",
"(",
"error",
",",
"result",
")",
"{",
"return",
"finisher",
".",
"call",
"(",
"stream",
",",
"error",
",",
"result",
",",
"callback",
")",
";",
"}",
";",
"return",
"wrapped",
";",
"}"
] | Wraps provided callback function
allowing to execute snitch function before
real callback
@this ReadableAsyncKit#
@param {function} callback - function to wrap
@returns {function} - wrapped function | [
"Wraps",
"provided",
"callback",
"function",
"allowing",
"to",
"execute",
"snitch",
"function",
"before",
"real",
"callback"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L52-L62 | train |
alexindigo/asynckit | lib/streamify.js | wrapIteratorCallback | function wrapIteratorCallback(callback, key)
{
var stream = this;
return function(error, output)
{
// don't repeat yourself
if (!(key in stream.jobs))
{
callback(error, output);
return;
}
// clean up jobs
delete stream.jobs[key];
return streamer.call(stream, error, {key: key, value: output}, callback);
};
} | javascript | function wrapIteratorCallback(callback, key)
{
var stream = this;
return function(error, output)
{
// don't repeat yourself
if (!(key in stream.jobs))
{
callback(error, output);
return;
}
// clean up jobs
delete stream.jobs[key];
return streamer.call(stream, error, {key: key, value: output}, callback);
};
} | [
"function",
"wrapIteratorCallback",
"(",
"callback",
",",
"key",
")",
"{",
"var",
"stream",
"=",
"this",
";",
"return",
"function",
"(",
"error",
",",
"output",
")",
"{",
"if",
"(",
"!",
"(",
"key",
"in",
"stream",
".",
"jobs",
")",
")",
"{",
"callback",
"(",
"error",
",",
"output",
")",
";",
"return",
";",
"}",
"delete",
"stream",
".",
"jobs",
"[",
"key",
"]",
";",
"return",
"streamer",
".",
"call",
"(",
"stream",
",",
"error",
",",
"{",
"key",
":",
"key",
",",
"value",
":",
"output",
"}",
",",
"callback",
")",
";",
"}",
";",
"}"
] | Wraps provided iterator callback function
makes sure snitch only called once,
but passes secondary calls to the original callback
@this ReadableAsyncKit#
@param {function} callback - callback to wrap
@param {number|string} key - iteration key
@returns {function} wrapped callback | [
"Wraps",
"provided",
"iterator",
"callback",
"function",
"makes",
"sure",
"snitch",
"only",
"called",
"once",
"but",
"passes",
"secondary",
"calls",
"to",
"the",
"original",
"callback"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L74-L92 | train |
alexindigo/asynckit | lib/streamify.js | streamer | function streamer(error, output, callback)
{
if (error && !this.error)
{
this.error = error;
this.pause();
this.emit('error', error);
// send back value only, as expected
callback(error, output && output.value);
return;
}
// stream stuff
this.push(output);
// back to original track
// send back value only, as expected
callback(error, output && output.value);
} | javascript | function streamer(error, output, callback)
{
if (error && !this.error)
{
this.error = error;
this.pause();
this.emit('error', error);
// send back value only, as expected
callback(error, output && output.value);
return;
}
// stream stuff
this.push(output);
// back to original track
// send back value only, as expected
callback(error, output && output.value);
} | [
"function",
"streamer",
"(",
"error",
",",
"output",
",",
"callback",
")",
"{",
"if",
"(",
"error",
"&&",
"!",
"this",
".",
"error",
")",
"{",
"this",
".",
"error",
"=",
"error",
";",
"this",
".",
"pause",
"(",
")",
";",
"this",
".",
"emit",
"(",
"'error'",
",",
"error",
")",
";",
"callback",
"(",
"error",
",",
"output",
"&&",
"output",
".",
"value",
")",
";",
"return",
";",
"}",
"this",
".",
"push",
"(",
"output",
")",
";",
"callback",
"(",
"error",
",",
"output",
"&&",
"output",
".",
"value",
")",
";",
"}"
] | Stream wrapper for iterator callback
@this ReadableAsyncKit#
@param {mixed} error - error response
@param {mixed} output - iterator output
@param {function} callback - callback that expects iterator results | [
"Stream",
"wrapper",
"for",
"iterator",
"callback"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L102-L120 | train |
alexindigo/asynckit | lib/streamify.js | finisher | function finisher(error, output, callback)
{
// signal end of the stream
// only for successfully finished streams
if (!error)
{
this.push(null);
}
// back to original track
callback(error, output);
} | javascript | function finisher(error, output, callback)
{
// signal end of the stream
// only for successfully finished streams
if (!error)
{
this.push(null);
}
// back to original track
callback(error, output);
} | [
"function",
"finisher",
"(",
"error",
",",
"output",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"error",
")",
"{",
"this",
".",
"push",
"(",
"null",
")",
";",
"}",
"callback",
"(",
"error",
",",
"output",
")",
";",
"}"
] | Stream wrapper for finishing callback
@this ReadableAsyncKit#
@param {mixed} error - error response
@param {mixed} output - iterator output
@param {function} callback - callback that expects final results | [
"Stream",
"wrapper",
"for",
"finishing",
"callback"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/streamify.js#L130-L141 | train |
alexindigo/asynckit | lib/iterate.js | iterate | function iterate(list, iterator, state, callback)
{
// store current index
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
{
// don't repeat yourself
// skip secondary callbacks
if (!(key in state.jobs))
{
return;
}
// clean up jobs
delete state.jobs[key];
if (error)
{
// don't process rest of the results
// stop still active jobs
// and reset the list
abort(state);
}
else
{
state.results[key] = output;
}
// return salvaged results
callback(error, state.results);
});
} | javascript | function iterate(list, iterator, state, callback)
{
// store current index
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
{
// don't repeat yourself
// skip secondary callbacks
if (!(key in state.jobs))
{
return;
}
// clean up jobs
delete state.jobs[key];
if (error)
{
// don't process rest of the results
// stop still active jobs
// and reset the list
abort(state);
}
else
{
state.results[key] = output;
}
// return salvaged results
callback(error, state.results);
});
} | [
"function",
"iterate",
"(",
"list",
",",
"iterator",
",",
"state",
",",
"callback",
")",
"{",
"var",
"key",
"=",
"state",
"[",
"'keyedList'",
"]",
"?",
"state",
"[",
"'keyedList'",
"]",
"[",
"state",
".",
"index",
"]",
":",
"state",
".",
"index",
";",
"state",
".",
"jobs",
"[",
"key",
"]",
"=",
"runJob",
"(",
"iterator",
",",
"key",
",",
"list",
"[",
"key",
"]",
",",
"function",
"(",
"error",
",",
"output",
")",
"{",
"if",
"(",
"!",
"(",
"key",
"in",
"state",
".",
"jobs",
")",
")",
"{",
"return",
";",
"}",
"delete",
"state",
".",
"jobs",
"[",
"key",
"]",
";",
"if",
"(",
"error",
")",
"{",
"abort",
"(",
"state",
")",
";",
"}",
"else",
"{",
"state",
".",
"results",
"[",
"key",
"]",
"=",
"output",
";",
"}",
"callback",
"(",
"error",
",",
"state",
".",
"results",
")",
";",
"}",
")",
";",
"}"
] | Iterates over each job object
@param {array|object} list - array or object (named list) to iterate over
@param {function} iterator - iterator to run
@param {object} state - current job status
@param {function} callback - invoked when all elements processed | [
"Iterates",
"over",
"each",
"job",
"object"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/iterate.js#L16-L48 | train |
alexindigo/asynckit | lib/iterate.js | runJob | function runJob(iterator, key, item, callback)
{
var aborter;
// allow shortcut if iterator expects only two arguments
if (iterator.length == 2)
{
aborter = iterator(item, async(callback));
}
// otherwise go with full three arguments
else
{
aborter = iterator(item, key, async(callback));
}
return aborter;
} | javascript | function runJob(iterator, key, item, callback)
{
var aborter;
// allow shortcut if iterator expects only two arguments
if (iterator.length == 2)
{
aborter = iterator(item, async(callback));
}
// otherwise go with full three arguments
else
{
aborter = iterator(item, key, async(callback));
}
return aborter;
} | [
"function",
"runJob",
"(",
"iterator",
",",
"key",
",",
"item",
",",
"callback",
")",
"{",
"var",
"aborter",
";",
"if",
"(",
"iterator",
".",
"length",
"==",
"2",
")",
"{",
"aborter",
"=",
"iterator",
"(",
"item",
",",
"async",
"(",
"callback",
")",
")",
";",
"}",
"else",
"{",
"aborter",
"=",
"iterator",
"(",
"item",
",",
"key",
",",
"async",
"(",
"callback",
")",
")",
";",
"}",
"return",
"aborter",
";",
"}"
] | Runs iterator over provided job element
@param {function} iterator - iterator to invoke
@param {string|number} key - key/index of the element in the list of jobs
@param {mixed} item - job description
@param {function} callback - invoked after iterator is done with the job
@returns {function|mixed} - job abort function or something else | [
"Runs",
"iterator",
"over",
"provided",
"job",
"element"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/iterate.js#L59-L75 | train |
alexindigo/asynckit | serialOrdered.js | serialOrdered | function serialOrdered(list, iterator, sortMethod, callback)
{
var state = initState(list, sortMethod);
iterate(list, iterator, state, function iteratorHandler(error, result)
{
if (error)
{
callback(error, result);
return;
}
state.index++;
// are we there yet?
if (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, iteratorHandler);
return;
}
// done here
callback(null, state.results);
});
return terminator.bind(state, callback);
} | javascript | function serialOrdered(list, iterator, sortMethod, callback)
{
var state = initState(list, sortMethod);
iterate(list, iterator, state, function iteratorHandler(error, result)
{
if (error)
{
callback(error, result);
return;
}
state.index++;
// are we there yet?
if (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, iteratorHandler);
return;
}
// done here
callback(null, state.results);
});
return terminator.bind(state, callback);
} | [
"function",
"serialOrdered",
"(",
"list",
",",
"iterator",
",",
"sortMethod",
",",
"callback",
")",
"{",
"var",
"state",
"=",
"initState",
"(",
"list",
",",
"sortMethod",
")",
";",
"iterate",
"(",
"list",
",",
"iterator",
",",
"state",
",",
"function",
"iteratorHandler",
"(",
"error",
",",
"result",
")",
"{",
"if",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
",",
"result",
")",
";",
"return",
";",
"}",
"state",
".",
"index",
"++",
";",
"if",
"(",
"state",
".",
"index",
"<",
"(",
"state",
"[",
"'keyedList'",
"]",
"||",
"list",
")",
".",
"length",
")",
"{",
"iterate",
"(",
"list",
",",
"iterator",
",",
"state",
",",
"iteratorHandler",
")",
";",
"return",
";",
"}",
"callback",
"(",
"null",
",",
"state",
".",
"results",
")",
";",
"}",
")",
";",
"return",
"terminator",
".",
"bind",
"(",
"state",
",",
"callback",
")",
";",
"}"
] | Runs iterator over provided sorted array elements in series
@param {array|object} list - array or object (named list) to iterate over
@param {function} iterator - iterator to run
@param {function} sortMethod - custom sort function
@param {function} callback - invoked when all elements processed
@returns {function} - jobs terminator | [
"Runs",
"iterator",
"over",
"provided",
"sorted",
"array",
"elements",
"in",
"series"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/serialOrdered.js#L21-L47 | train |
alexindigo/asynckit | lib/readable_parallel.js | ReadableParallel | function ReadableParallel(list, iterator, callback)
{
if (!(this instanceof ReadableParallel))
{
return new ReadableParallel(list, iterator, callback);
}
// turn on object mode
ReadableParallel.super_.call(this, {objectMode: true});
this._start(parallel, list, iterator, callback);
} | javascript | function ReadableParallel(list, iterator, callback)
{
if (!(this instanceof ReadableParallel))
{
return new ReadableParallel(list, iterator, callback);
}
// turn on object mode
ReadableParallel.super_.call(this, {objectMode: true});
this._start(parallel, list, iterator, callback);
} | [
"function",
"ReadableParallel",
"(",
"list",
",",
"iterator",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ReadableParallel",
")",
")",
"{",
"return",
"new",
"ReadableParallel",
"(",
"list",
",",
"iterator",
",",
"callback",
")",
";",
"}",
"ReadableParallel",
".",
"super_",
".",
"call",
"(",
"this",
",",
"{",
"objectMode",
":",
"true",
"}",
")",
";",
"this",
".",
"_start",
"(",
"parallel",
",",
"list",
",",
"iterator",
",",
"callback",
")",
";",
"}"
] | Streaming wrapper to `asynckit.parallel`
@param {array|object} list - array or object (named list) to iterate over
@param {function} iterator - iterator to run
@param {function} callback - invoked when all elements processed
@returns {stream.Readable#} | [
"Streaming",
"wrapper",
"to",
"asynckit",
".",
"parallel"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/readable_parallel.js#L14-L25 | train |
alexindigo/asynckit | lib/readable_serial_ordered.js | ReadableSerialOrdered | function ReadableSerialOrdered(list, iterator, sortMethod, callback)
{
if (!(this instanceof ReadableSerialOrdered))
{
return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
}
// turn on object mode
ReadableSerialOrdered.super_.call(this, {objectMode: true});
this._start(serialOrdered, list, iterator, sortMethod, callback);
} | javascript | function ReadableSerialOrdered(list, iterator, sortMethod, callback)
{
if (!(this instanceof ReadableSerialOrdered))
{
return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
}
// turn on object mode
ReadableSerialOrdered.super_.call(this, {objectMode: true});
this._start(serialOrdered, list, iterator, sortMethod, callback);
} | [
"function",
"ReadableSerialOrdered",
"(",
"list",
",",
"iterator",
",",
"sortMethod",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ReadableSerialOrdered",
")",
")",
"{",
"return",
"new",
"ReadableSerialOrdered",
"(",
"list",
",",
"iterator",
",",
"sortMethod",
",",
"callback",
")",
";",
"}",
"ReadableSerialOrdered",
".",
"super_",
".",
"call",
"(",
"this",
",",
"{",
"objectMode",
":",
"true",
"}",
")",
";",
"this",
".",
"_start",
"(",
"serialOrdered",
",",
"list",
",",
"iterator",
",",
"sortMethod",
",",
"callback",
")",
";",
"}"
] | Streaming wrapper to `asynckit.serialOrdered`
@param {array|object} list - array or object (named list) to iterate over
@param {function} iterator - iterator to run
@param {function} sortMethod - custom sort function
@param {function} callback - invoked when all elements processed
@returns {stream.Readable#} | [
"Streaming",
"wrapper",
"to",
"asynckit",
".",
"serialOrdered"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/readable_serial_ordered.js#L18-L29 | train |
alexindigo/asynckit | lib/readable_asynckit.js | _start | function _start()
{
// first argument – runner function
var runner = arguments[0]
// take away first argument
, args = Array.prototype.slice.call(arguments, 1)
// second argument - input data
, input = args[0]
// last argument - result callback
, endCb = streamify.callback.call(this, args[args.length - 1])
;
args[args.length - 1] = endCb;
// third argument - iterator
args[1] = streamify.iterator.call(this, args[1]);
// allow time for proper setup
defer(function()
{
if (!this.destroyed)
{
this.terminator = runner.apply(null, args);
}
else
{
endCb(null, Array.isArray(input) ? [] : {});
}
}.bind(this));
} | javascript | function _start()
{
// first argument – runner function
var runner = arguments[0]
// take away first argument
, args = Array.prototype.slice.call(arguments, 1)
// second argument - input data
, input = args[0]
// last argument - result callback
, endCb = streamify.callback.call(this, args[args.length - 1])
;
args[args.length - 1] = endCb;
// third argument - iterator
args[1] = streamify.iterator.call(this, args[1]);
// allow time for proper setup
defer(function()
{
if (!this.destroyed)
{
this.terminator = runner.apply(null, args);
}
else
{
endCb(null, Array.isArray(input) ? [] : {});
}
}.bind(this));
} | [
"function",
"_start",
"(",
")",
"{",
"var",
"runner",
"=",
"arguments",
"[",
"0",
"]",
",",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
",",
"input",
"=",
"args",
"[",
"0",
"]",
",",
"endCb",
"=",
"streamify",
".",
"callback",
".",
"call",
"(",
"this",
",",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
")",
";",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
"=",
"endCb",
";",
"args",
"[",
"1",
"]",
"=",
"streamify",
".",
"iterator",
".",
"call",
"(",
"this",
",",
"args",
"[",
"1",
"]",
")",
";",
"defer",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"destroyed",
")",
"{",
"this",
".",
"terminator",
"=",
"runner",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}",
"else",
"{",
"endCb",
"(",
"null",
",",
"Array",
".",
"isArray",
"(",
"input",
")",
"?",
"[",
"]",
":",
"{",
"}",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Starts provided jobs in async manner
@private | [
"Starts",
"provided",
"jobs",
"in",
"async",
"manner"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/readable_asynckit.js#L51-L79 | train |
alexindigo/asynckit | lib/state.js | state | function state(list, sortMethod)
{
var isNamedList = !Array.isArray(list)
, initState =
{
index : 0,
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
jobs : {},
results : isNamedList ? {} : [],
size : isNamedList ? Object.keys(list).length : list.length
}
;
if (sortMethod)
{
// sort array keys based on it's values
// sort object's keys just on own merit
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
{
return sortMethod(list[a], list[b]);
});
}
return initState;
} | javascript | function state(list, sortMethod)
{
var isNamedList = !Array.isArray(list)
, initState =
{
index : 0,
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
jobs : {},
results : isNamedList ? {} : [],
size : isNamedList ? Object.keys(list).length : list.length
}
;
if (sortMethod)
{
// sort array keys based on it's values
// sort object's keys just on own merit
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
{
return sortMethod(list[a], list[b]);
});
}
return initState;
} | [
"function",
"state",
"(",
"list",
",",
"sortMethod",
")",
"{",
"var",
"isNamedList",
"=",
"!",
"Array",
".",
"isArray",
"(",
"list",
")",
",",
"initState",
"=",
"{",
"index",
":",
"0",
",",
"keyedList",
":",
"isNamedList",
"||",
"sortMethod",
"?",
"Object",
".",
"keys",
"(",
"list",
")",
":",
"null",
",",
"jobs",
":",
"{",
"}",
",",
"results",
":",
"isNamedList",
"?",
"{",
"}",
":",
"[",
"]",
",",
"size",
":",
"isNamedList",
"?",
"Object",
".",
"keys",
"(",
"list",
")",
".",
"length",
":",
"list",
".",
"length",
"}",
";",
"if",
"(",
"sortMethod",
")",
"{",
"initState",
".",
"keyedList",
".",
"sort",
"(",
"isNamedList",
"?",
"sortMethod",
":",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"sortMethod",
"(",
"list",
"[",
"a",
"]",
",",
"list",
"[",
"b",
"]",
")",
";",
"}",
")",
";",
"}",
"return",
"initState",
";",
"}"
] | Creates initial state object
for iteration over list
@param {array|object} list - list to iterate over
@param {function|null} sortMethod - function to use for keys sort,
or `null` to keep them as is
@returns {object} - initial state object | [
"Creates",
"initial",
"state",
"object",
"for",
"iteration",
"over",
"list"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/state.js#L13-L37 | train |
alexindigo/asynckit | lib/abort.js | abort | function abort(state)
{
Object.keys(state.jobs).forEach(clean.bind(state));
// reset leftover jobs
state.jobs = {};
} | javascript | function abort(state)
{
Object.keys(state.jobs).forEach(clean.bind(state));
// reset leftover jobs
state.jobs = {};
} | [
"function",
"abort",
"(",
"state",
")",
"{",
"Object",
".",
"keys",
"(",
"state",
".",
"jobs",
")",
".",
"forEach",
"(",
"clean",
".",
"bind",
"(",
"state",
")",
")",
";",
"state",
".",
"jobs",
"=",
"{",
"}",
";",
"}"
] | Aborts leftover active jobs
@param {object} state - current state object | [
"Aborts",
"leftover",
"active",
"jobs"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/abort.js#L9-L15 | train |
alexindigo/asynckit | lib/async.js | async | function async(callback)
{
var isAsync = false;
// check if async happened
defer(function() { isAsync = true; });
return function async_callback(err, result)
{
if (isAsync)
{
callback(err, result);
}
else
{
defer(function nextTick_callback()
{
callback(err, result);
});
}
};
} | javascript | function async(callback)
{
var isAsync = false;
// check if async happened
defer(function() { isAsync = true; });
return function async_callback(err, result)
{
if (isAsync)
{
callback(err, result);
}
else
{
defer(function nextTick_callback()
{
callback(err, result);
});
}
};
} | [
"function",
"async",
"(",
"callback",
")",
"{",
"var",
"isAsync",
"=",
"false",
";",
"defer",
"(",
"function",
"(",
")",
"{",
"isAsync",
"=",
"true",
";",
"}",
")",
";",
"return",
"function",
"async_callback",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"isAsync",
")",
"{",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
"else",
"{",
"defer",
"(",
"function",
"nextTick_callback",
"(",
")",
"{",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"}"
] | Runs provided callback asynchronously
even if callback itself is not
@param {function} callback - callback to invoke
@returns {function} - augmented callback | [
"Runs",
"provided",
"callback",
"asynchronously",
"even",
"if",
"callback",
"itself",
"is",
"not"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/async.js#L13-L34 | train |
alexindigo/asynckit | parallel.js | parallel | function parallel(list, iterator, callback)
{
var state = initState(list);
while (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, function(error, result)
{
if (error)
{
callback(error, result);
return;
}
// looks like it's the last one
if (Object.keys(state.jobs).length === 0)
{
callback(null, state.results);
return;
}
});
state.index++;
}
return terminator.bind(state, callback);
} | javascript | function parallel(list, iterator, callback)
{
var state = initState(list);
while (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, function(error, result)
{
if (error)
{
callback(error, result);
return;
}
// looks like it's the last one
if (Object.keys(state.jobs).length === 0)
{
callback(null, state.results);
return;
}
});
state.index++;
}
return terminator.bind(state, callback);
} | [
"function",
"parallel",
"(",
"list",
",",
"iterator",
",",
"callback",
")",
"{",
"var",
"state",
"=",
"initState",
"(",
"list",
")",
";",
"while",
"(",
"state",
".",
"index",
"<",
"(",
"state",
"[",
"'keyedList'",
"]",
"||",
"list",
")",
".",
"length",
")",
"{",
"iterate",
"(",
"list",
",",
"iterator",
",",
"state",
",",
"function",
"(",
"error",
",",
"result",
")",
"{",
"if",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
",",
"result",
")",
";",
"return",
";",
"}",
"if",
"(",
"Object",
".",
"keys",
"(",
"state",
".",
"jobs",
")",
".",
"length",
"===",
"0",
")",
"{",
"callback",
"(",
"null",
",",
"state",
".",
"results",
")",
";",
"return",
";",
"}",
"}",
")",
";",
"state",
".",
"index",
"++",
";",
"}",
"return",
"terminator",
".",
"bind",
"(",
"state",
",",
"callback",
")",
";",
"}"
] | Runs iterator over provided array elements in parallel
@param {array|object} list - array or object (named list) to iterate over
@param {function} iterator - iterator to run
@param {function} callback - invoked when all elements processed
@returns {function} - jobs terminator | [
"Runs",
"iterator",
"over",
"provided",
"array",
"elements",
"in",
"parallel"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/parallel.js#L17-L43 | train |
alexindigo/asynckit | lib/terminator.js | terminator | function terminator(callback)
{
if (!Object.keys(this.jobs).length)
{
return;
}
// fast forward iteration index
this.index = this.size;
// abort jobs
abort(this);
// send back results we have so far
async(callback)(null, this.results);
} | javascript | function terminator(callback)
{
if (!Object.keys(this.jobs).length)
{
return;
}
// fast forward iteration index
this.index = this.size;
// abort jobs
abort(this);
// send back results we have so far
async(callback)(null, this.results);
} | [
"function",
"terminator",
"(",
"callback",
")",
"{",
"if",
"(",
"!",
"Object",
".",
"keys",
"(",
"this",
".",
"jobs",
")",
".",
"length",
")",
"{",
"return",
";",
"}",
"this",
".",
"index",
"=",
"this",
".",
"size",
";",
"abort",
"(",
"this",
")",
";",
"async",
"(",
"callback",
")",
"(",
"null",
",",
"this",
".",
"results",
")",
";",
"}"
] | Terminates jobs in the attached state context
@this AsyncKitState#
@param {function} callback - final callback to invoke after termination | [
"Terminates",
"jobs",
"in",
"the",
"attached",
"state",
"context"
] | 583a75ed4fe41761b66416bb6e703ebb1f8963bf | https://github.com/alexindigo/asynckit/blob/583a75ed4fe41761b66416bb6e703ebb1f8963bf/lib/terminator.js#L14-L29 | train |
af83/oauth2_client_node | lib/oauth2_client.js | function(serverName, config, options) {
this.methods[serverName] = {};
this.config.servers[serverName] = config;
var self = this;
['valid_grant', 'treat_access_token', 'transform_token_response'].forEach(function(fctName) {
self.methods[serverName][fctName] = options[fctName] || self[fctName].bind(self);
});
} | javascript | function(serverName, config, options) {
this.methods[serverName] = {};
this.config.servers[serverName] = config;
var self = this;
['valid_grant', 'treat_access_token', 'transform_token_response'].forEach(function(fctName) {
self.methods[serverName][fctName] = options[fctName] || self[fctName].bind(self);
});
} | [
"function",
"(",
"serverName",
",",
"config",
",",
"options",
")",
"{",
"this",
".",
"methods",
"[",
"serverName",
"]",
"=",
"{",
"}",
";",
"this",
".",
"config",
".",
"servers",
"[",
"serverName",
"]",
"=",
"config",
";",
"var",
"self",
"=",
"this",
";",
"[",
"'valid_grant'",
",",
"'treat_access_token'",
",",
"'transform_token_response'",
"]",
".",
"forEach",
"(",
"function",
"(",
"fctName",
")",
"{",
"self",
".",
"methods",
"[",
"serverName",
"]",
"[",
"fctName",
"]",
"=",
"options",
"[",
"fctName",
"]",
"||",
"self",
"[",
"fctName",
"]",
".",
"bind",
"(",
"self",
")",
";",
"}",
")",
";",
"}"
] | Add oauth2 server | [
"Add",
"oauth2",
"server"
] | 40d5e56e717f88f6b2b9a725ca77a90b0a775535 | https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L44-L51 | train |
|
af83/oauth2_client_node | lib/oauth2_client.js | function(data, code, callback) {
var self = this;
var cconfig = this.config.client;
var sconfig = this.config.servers[data.oauth2_server_id];
request.post({uri: sconfig.server_token_endpoint,
headers: {'content-type': 'application/x-www-form-urlencoded'},
body: querystring.stringify({
grant_type: "authorization_code",
client_id: sconfig.client_id,
code: code,
client_secret: sconfig.client_secret,
redirect_uri: cconfig.redirect_uri
})
}, function(error, response, body) {
console.log(body);
if (!error && response.statusCode == 200) {
try {
var methods = self.methods[data.oauth2_server_id];
var token = methods.transform_token_response(body)
callback(null, token);
} catch(err) {
callback(err);
}
} else {
// TODO: check if error code indicates problem on the client,
console.error(error, body);
callback(error);
}
});
} | javascript | function(data, code, callback) {
var self = this;
var cconfig = this.config.client;
var sconfig = this.config.servers[data.oauth2_server_id];
request.post({uri: sconfig.server_token_endpoint,
headers: {'content-type': 'application/x-www-form-urlencoded'},
body: querystring.stringify({
grant_type: "authorization_code",
client_id: sconfig.client_id,
code: code,
client_secret: sconfig.client_secret,
redirect_uri: cconfig.redirect_uri
})
}, function(error, response, body) {
console.log(body);
if (!error && response.statusCode == 200) {
try {
var methods = self.methods[data.oauth2_server_id];
var token = methods.transform_token_response(body)
callback(null, token);
} catch(err) {
callback(err);
}
} else {
// TODO: check if error code indicates problem on the client,
console.error(error, body);
callback(error);
}
});
} | [
"function",
"(",
"data",
",",
"code",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"cconfig",
"=",
"this",
".",
"config",
".",
"client",
";",
"var",
"sconfig",
"=",
"this",
".",
"config",
".",
"servers",
"[",
"data",
".",
"oauth2_server_id",
"]",
";",
"request",
".",
"post",
"(",
"{",
"uri",
":",
"sconfig",
".",
"server_token_endpoint",
",",
"headers",
":",
"{",
"'content-type'",
":",
"'application/x-www-form-urlencoded'",
"}",
",",
"body",
":",
"querystring",
".",
"stringify",
"(",
"{",
"grant_type",
":",
"\"authorization_code\"",
",",
"client_id",
":",
"sconfig",
".",
"client_id",
",",
"code",
":",
"code",
",",
"client_secret",
":",
"sconfig",
".",
"client_secret",
",",
"redirect_uri",
":",
"cconfig",
".",
"redirect_uri",
"}",
")",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"console",
".",
"log",
"(",
"body",
")",
";",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"==",
"200",
")",
"{",
"try",
"{",
"var",
"methods",
"=",
"self",
".",
"methods",
"[",
"data",
".",
"oauth2_server_id",
"]",
";",
"var",
"token",
"=",
"methods",
".",
"transform_token_response",
"(",
"body",
")",
"callback",
"(",
"null",
",",
"token",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"error",
",",
"body",
")",
";",
"callback",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}"
] | Valid the grant given by user requesting the OAuth2 server
at OAuth2 token endpoint.
Arguments:
- data: hash containing:
- oauth2_server_id: string, the OAuth2 server is (ex: "facebook.com").
- next_url: string, the next_url associated with the OAuth2 request.
- state: hash, state associated with the OAuth2 request.
- code: the authorization code given by OAuth2 server to user.
- callback: function to be called once grant is validated/rejected.
Called with the access_token returned by OAuth2 server as first
parameter. If given token might be null, meaning it was rejected
by OAuth2 server. | [
"Valid",
"the",
"grant",
"given",
"by",
"user",
"requesting",
"the",
"OAuth2",
"server",
"at",
"OAuth2",
"token",
"endpoint",
"."
] | 40d5e56e717f88f6b2b9a725ca77a90b0a775535 | https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L87-L116 | train |
|
af83/oauth2_client_node | lib/oauth2_client.js | function(req, res) {
var params = URL.parse(req.url, true).query
, code = params.code
, state = params.state
;
if(!code) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "code" parameter is missing.');
}
if(!state) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "state" parameter is missing.');
}
try {
state = this.serializer.parse(state);
} catch(err) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "state" parameter is invalid.');
}
var data = {
oauth2_server_id: state[0]
, next_url: state[1]
, state: state[2]
}
var methods = this.methods[data.oauth2_server_id];
methods.valid_grant(data, code, function(err, token) {
if (err) return server_error(res, err);
if(!token) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('Invalid grant.');
return;
}
data.token = token;
methods.treat_access_token(data, req, res, function() {
redirect(res, data.next_url);
}, function(err){server_error(res, err)});
});
} | javascript | function(req, res) {
var params = URL.parse(req.url, true).query
, code = params.code
, state = params.state
;
if(!code) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "code" parameter is missing.');
}
if(!state) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "state" parameter is missing.');
}
try {
state = this.serializer.parse(state);
} catch(err) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "state" parameter is invalid.');
}
var data = {
oauth2_server_id: state[0]
, next_url: state[1]
, state: state[2]
}
var methods = this.methods[data.oauth2_server_id];
methods.valid_grant(data, code, function(err, token) {
if (err) return server_error(res, err);
if(!token) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('Invalid grant.');
return;
}
data.token = token;
methods.treat_access_token(data, req, res, function() {
redirect(res, data.next_url);
}, function(err){server_error(res, err)});
});
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"params",
"=",
"URL",
".",
"parse",
"(",
"req",
".",
"url",
",",
"true",
")",
".",
"query",
",",
"code",
"=",
"params",
".",
"code",
",",
"state",
"=",
"params",
".",
"state",
";",
"if",
"(",
"!",
"code",
")",
"{",
"res",
".",
"writeHead",
"(",
"400",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"return",
"res",
".",
"end",
"(",
"'The \"code\" parameter is missing.'",
")",
";",
"}",
"if",
"(",
"!",
"state",
")",
"{",
"res",
".",
"writeHead",
"(",
"400",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"return",
"res",
".",
"end",
"(",
"'The \"state\" parameter is missing.'",
")",
";",
"}",
"try",
"{",
"state",
"=",
"this",
".",
"serializer",
".",
"parse",
"(",
"state",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"res",
".",
"writeHead",
"(",
"400",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"return",
"res",
".",
"end",
"(",
"'The \"state\" parameter is invalid.'",
")",
";",
"}",
"var",
"data",
"=",
"{",
"oauth2_server_id",
":",
"state",
"[",
"0",
"]",
",",
"next_url",
":",
"state",
"[",
"1",
"]",
",",
"state",
":",
"state",
"[",
"2",
"]",
"}",
"var",
"methods",
"=",
"this",
".",
"methods",
"[",
"data",
".",
"oauth2_server_id",
"]",
";",
"methods",
".",
"valid_grant",
"(",
"data",
",",
"code",
",",
"function",
"(",
"err",
",",
"token",
")",
"{",
"if",
"(",
"err",
")",
"return",
"server_error",
"(",
"res",
",",
"err",
")",
";",
"if",
"(",
"!",
"token",
")",
"{",
"res",
".",
"writeHead",
"(",
"400",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"'Invalid grant.'",
")",
";",
"return",
";",
"}",
"data",
".",
"token",
"=",
"token",
";",
"methods",
".",
"treat_access_token",
"(",
"data",
",",
"req",
",",
"res",
",",
"function",
"(",
")",
"{",
"redirect",
"(",
"res",
",",
"data",
".",
"next_url",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"server_error",
"(",
"res",
",",
"err",
")",
"}",
")",
";",
"}",
")",
";",
"}"
] | Check the grant given by user to login in authserver is a good one.
Arguments:
- req
- res | [
"Check",
"the",
"grant",
"given",
"by",
"user",
"to",
"login",
"in",
"authserver",
"is",
"a",
"good",
"one",
"."
] | 40d5e56e717f88f6b2b9a725ca77a90b0a775535 | https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L150-L188 | train |
|
af83/oauth2_client_node | lib/oauth2_client.js | function(oauth2_server_id, res, next_url, state) {
var sconfig = this.config.servers[oauth2_server_id];
var cconfig = this.config.client;
var data = {
client_id: sconfig.client_id,
redirect_uri: cconfig.redirect_uri,
response_type: 'code',
state: this.serializer.stringify([oauth2_server_id, next_url, state || null])
};
var url = sconfig.server_authorize_endpoint +'?'+ querystring.stringify(data);
redirect(res, url);
} | javascript | function(oauth2_server_id, res, next_url, state) {
var sconfig = this.config.servers[oauth2_server_id];
var cconfig = this.config.client;
var data = {
client_id: sconfig.client_id,
redirect_uri: cconfig.redirect_uri,
response_type: 'code',
state: this.serializer.stringify([oauth2_server_id, next_url, state || null])
};
var url = sconfig.server_authorize_endpoint +'?'+ querystring.stringify(data);
redirect(res, url);
} | [
"function",
"(",
"oauth2_server_id",
",",
"res",
",",
"next_url",
",",
"state",
")",
"{",
"var",
"sconfig",
"=",
"this",
".",
"config",
".",
"servers",
"[",
"oauth2_server_id",
"]",
";",
"var",
"cconfig",
"=",
"this",
".",
"config",
".",
"client",
";",
"var",
"data",
"=",
"{",
"client_id",
":",
"sconfig",
".",
"client_id",
",",
"redirect_uri",
":",
"cconfig",
".",
"redirect_uri",
",",
"response_type",
":",
"'code'",
",",
"state",
":",
"this",
".",
"serializer",
".",
"stringify",
"(",
"[",
"oauth2_server_id",
",",
"next_url",
",",
"state",
"||",
"null",
"]",
")",
"}",
";",
"var",
"url",
"=",
"sconfig",
".",
"server_authorize_endpoint",
"+",
"'?'",
"+",
"querystring",
".",
"stringify",
"(",
"data",
")",
";",
"redirect",
"(",
"res",
",",
"url",
")",
";",
"}"
] | Redirects the user to OAuth2 server for authentication.
Arguments:
- oauth2_server_id: OAuth2 server identification (ex: "facebook.com").
- res
- next_url: an url to redirect to once the process is complete.
- state: optional, a hash containing info you want to retrieve at the end
of the process. | [
"Redirects",
"the",
"user",
"to",
"OAuth2",
"server",
"for",
"authentication",
"."
] | 40d5e56e717f88f6b2b9a725ca77a90b0a775535 | https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L200-L211 | train |
|
af83/oauth2_client_node | lib/oauth2_client.js | function(req, params) {
if(!params) {
params = URL.parse(req.url, true).query;
}
var cconfig = this.config.client;
var next = params.next || cconfig.default_redirection_url;
var url = cconfig.base_url + next;
return url;
} | javascript | function(req, params) {
if(!params) {
params = URL.parse(req.url, true).query;
}
var cconfig = this.config.client;
var next = params.next || cconfig.default_redirection_url;
var url = cconfig.base_url + next;
return url;
} | [
"function",
"(",
"req",
",",
"params",
")",
"{",
"if",
"(",
"!",
"params",
")",
"{",
"params",
"=",
"URL",
".",
"parse",
"(",
"req",
".",
"url",
",",
"true",
")",
".",
"query",
";",
"}",
"var",
"cconfig",
"=",
"this",
".",
"config",
".",
"client",
";",
"var",
"next",
"=",
"params",
".",
"next",
"||",
"cconfig",
".",
"default_redirection_url",
";",
"var",
"url",
"=",
"cconfig",
".",
"base_url",
"+",
"next",
";",
"return",
"url",
";",
"}"
] | Returns value of next url query parameter if present, default otherwise.
The next query parameter should not contain the domain, the result will. | [
"Returns",
"value",
"of",
"next",
"url",
"query",
"parameter",
"if",
"present",
"default",
"otherwise",
".",
"The",
"next",
"query",
"parameter",
"should",
"not",
"contain",
"the",
"domain",
"the",
"result",
"will",
"."
] | 40d5e56e717f88f6b2b9a725ca77a90b0a775535 | https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L217-L225 | train |
|
af83/oauth2_client_node | lib/oauth2_client.js | function(req, res) {
var params = URL.parse(req.url, true).query;
var oauth2_server_id = params.provider || this.config.default_server;
var next_url = this.nexturl_query(req, params);
this.redirects_for_login(oauth2_server_id, res, next_url);
} | javascript | function(req, res) {
var params = URL.parse(req.url, true).query;
var oauth2_server_id = params.provider || this.config.default_server;
var next_url = this.nexturl_query(req, params);
this.redirects_for_login(oauth2_server_id, res, next_url);
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"params",
"=",
"URL",
".",
"parse",
"(",
"req",
".",
"url",
",",
"true",
")",
".",
"query",
";",
"var",
"oauth2_server_id",
"=",
"params",
".",
"provider",
"||",
"this",
".",
"config",
".",
"default_server",
";",
"var",
"next_url",
"=",
"this",
".",
"nexturl_query",
"(",
"req",
",",
"params",
")",
";",
"this",
".",
"redirects_for_login",
"(",
"oauth2_server_id",
",",
"res",
",",
"next_url",
")",
";",
"}"
] | Triggers redirects_for_login with next param if present in url query. | [
"Triggers",
"redirects_for_login",
"with",
"next",
"param",
"if",
"present",
"in",
"url",
"query",
"."
] | 40d5e56e717f88f6b2b9a725ca77a90b0a775535 | https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L238-L243 | train |
|
af83/oauth2_client_node | lib/oauth2_client.js | function() {
var client = this;
var cconf = this.config.client;
return router(function(app) {
app.get(cconf.process_login_url, client.auth_process_login.bind(client));
app.get(cconf.login_url, client.login.bind(client));
app.get(cconf.logout_url, client.logout.bind(client));
});
} | javascript | function() {
var client = this;
var cconf = this.config.client;
return router(function(app) {
app.get(cconf.process_login_url, client.auth_process_login.bind(client));
app.get(cconf.login_url, client.login.bind(client));
app.get(cconf.logout_url, client.logout.bind(client));
});
} | [
"function",
"(",
")",
"{",
"var",
"client",
"=",
"this",
";",
"var",
"cconf",
"=",
"this",
".",
"config",
".",
"client",
";",
"return",
"router",
"(",
"function",
"(",
"app",
")",
"{",
"app",
".",
"get",
"(",
"cconf",
".",
"process_login_url",
",",
"client",
".",
"auth_process_login",
".",
"bind",
"(",
"client",
")",
")",
";",
"app",
".",
"get",
"(",
"cconf",
".",
"login_url",
",",
"client",
".",
"login",
".",
"bind",
"(",
"client",
")",
")",
";",
"app",
".",
"get",
"(",
"cconf",
".",
"logout_url",
",",
"client",
".",
"logout",
".",
"bind",
"(",
"client",
")",
")",
";",
"}",
")",
";",
"}"
] | Returns OAuth2 client connect middleware.
This middleware will intercep requests aiming at OAuth2 client
and treat them. | [
"Returns",
"OAuth2",
"client",
"connect",
"middleware",
"."
] | 40d5e56e717f88f6b2b9a725ca77a90b0a775535 | https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L251-L260 | train |
|
af83/oauth2_client_node | lib/oauth2_client.js | createClient | function createClient(conf, options) {
conf.default_redirection_url = conf.default_redirection_url || '/';
options = options || {};
return new OAuth2Client(conf, options);
} | javascript | function createClient(conf, options) {
conf.default_redirection_url = conf.default_redirection_url || '/';
options = options || {};
return new OAuth2Client(conf, options);
} | [
"function",
"createClient",
"(",
"conf",
",",
"options",
")",
"{",
"conf",
".",
"default_redirection_url",
"=",
"conf",
".",
"default_redirection_url",
"||",
"'/'",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"return",
"new",
"OAuth2Client",
"(",
"conf",
",",
"options",
")",
";",
"}"
] | Returns OAuth2 client
Arguments:
- config: hash containing:
- client, hash containing:
- base_url: The base URL of the OAuth2 client.
Ex: http://domain.com:8080
- process_login_url: the URL where to the OAuth2 server must redirect
the user when authenticated.
- login_url: the URL where the user must go to be redirected
to OAuth2 server for authentication.
- logout_url: the URL where the user must go so that his session is
cleared, and he is unlogged from client.
- default_redirection_url: default URL to redirect to after login / logout.
Optional, default to '/'.
- crypt_key: string, encryption key used to crypt information
contained in the states.
This is a symmetric key and must be kept secret.
- sign_key: string, signature key used to sign (HMAC) issued states.
This is a symmetric key and must be kept secret.
- default_server: which server to use for default login when user
access login_url (ex: 'facebook.com').
- servers: hash associating OAuth2 server ids (ex: "facebook.com")
with a hash containing (for each):
- server_authorize_endpoint: full URL, OAuth2 server token endpoint
(ex: "https://graph.facebook.com/oauth/authorize").
- server_token_endpoint: full url, where to check the token
(ex: "https://graph.facebook.com/oauth/access_token").
- client_id: the client id as registered by this OAuth2 server.
- client_secret: shared secret between client and this OAuth2 server.
- options: optional, hash associating OAuth2 server ids
(ex: "facebook.com") with hash containing some options specific to the server.
Not all servers have to be listed here, neither all options.
Possible options:
- valid_grant: a function which will replace the default one
to check the grant is ok. You might want to use this shortcut if you
have a faster way of checking than requesting the OAuth2 server
with an HTTP request.
- treat_access_token: a function which will replace the
default one to do something with the access token. You will tipically
use that function to set some info in session.
- transform_token_response: a function which will replace
the default one to obtain a hash containing the access_token from
the OAuth2 server reply. This method should be provided if the
OAuth2 server we are requesting does not return JSON encoded data. | [
"Returns",
"OAuth2",
"client"
] | 40d5e56e717f88f6b2b9a725ca77a90b0a775535 | https://github.com/af83/oauth2_client_node/blob/40d5e56e717f88f6b2b9a725ca77a90b0a775535/lib/oauth2_client.js#L314-L318 | train |
bvalosek/tiny-ecs | lib/Loop.js | Loop | function Loop(messenger)
{
// Messenger we'll use for clock signals
this.messenger = messenger || new Messenger();
this.fixedDuration = 8;
this.started = false;
// Live stats
this.currentTime = 0;
this.fixedStepsPerFrame = 0;
this.fixedTimePerFrame = 0;
this.renderTimePerFrame = 0;
this.frameTime = 0;
} | javascript | function Loop(messenger)
{
// Messenger we'll use for clock signals
this.messenger = messenger || new Messenger();
this.fixedDuration = 8;
this.started = false;
// Live stats
this.currentTime = 0;
this.fixedStepsPerFrame = 0;
this.fixedTimePerFrame = 0;
this.renderTimePerFrame = 0;
this.frameTime = 0;
} | [
"function",
"Loop",
"(",
"messenger",
")",
"{",
"this",
".",
"messenger",
"=",
"messenger",
"||",
"new",
"Messenger",
"(",
")",
";",
"this",
".",
"fixedDuration",
"=",
"8",
";",
"this",
".",
"started",
"=",
"false",
";",
"this",
".",
"currentTime",
"=",
"0",
";",
"this",
".",
"fixedStepsPerFrame",
"=",
"0",
";",
"this",
".",
"fixedTimePerFrame",
"=",
"0",
";",
"this",
".",
"renderTimePerFrame",
"=",
"0",
";",
"this",
".",
"frameTime",
"=",
"0",
";",
"}"
] | Game loop with independent clock events for fixed durations and variable
durations.
@param {Messenger} messenger
@constructor | [
"Game",
"loop",
"with",
"independent",
"clock",
"events",
"for",
"fixed",
"durations",
"and",
"variable",
"durations",
"."
] | c74f65660f622a9a32eca200f49fafc1728e6d4d | https://github.com/bvalosek/tiny-ecs/blob/c74f65660f622a9a32eca200f49fafc1728e6d4d/lib/Loop.js#L11-L25 | train |
ryanseys/lune | lib/lune.js | kepler | function kepler (m, ecc) {
const epsilon = 1e-6
m = torad(m)
let e = m
while (1) {
const delta = e - ecc * Math.sin(e) - m
e -= delta / (1.0 - ecc * Math.cos(e))
if (Math.abs(delta) <= epsilon) {
break
}
}
return e
} | javascript | function kepler (m, ecc) {
const epsilon = 1e-6
m = torad(m)
let e = m
while (1) {
const delta = e - ecc * Math.sin(e) - m
e -= delta / (1.0 - ecc * Math.cos(e))
if (Math.abs(delta) <= epsilon) {
break
}
}
return e
} | [
"function",
"kepler",
"(",
"m",
",",
"ecc",
")",
"{",
"const",
"epsilon",
"=",
"1e-6",
"m",
"=",
"torad",
"(",
"m",
")",
"let",
"e",
"=",
"m",
"while",
"(",
"1",
")",
"{",
"const",
"delta",
"=",
"e",
"-",
"ecc",
"*",
"Math",
".",
"sin",
"(",
"e",
")",
"-",
"m",
"e",
"-=",
"delta",
"/",
"(",
"1.0",
"-",
"ecc",
"*",
"Math",
".",
"cos",
"(",
"e",
")",
")",
"if",
"(",
"Math",
".",
"abs",
"(",
"delta",
")",
"<=",
"epsilon",
")",
"{",
"break",
"}",
"}",
"return",
"e",
"}"
] | Solve the equation of Kepler. | [
"Solve",
"the",
"equation",
"of",
"Kepler",
"."
] | 667d6ff778d0deb2cd09988e3d89eb8ca0428a23 | https://github.com/ryanseys/lune/blob/667d6ff778d0deb2cd09988e3d89eb8ca0428a23/lib/lune.js#L99-L114 | train |
ryanseys/lune | lib/lune.js | phase | function phase (phase_date) {
if (!phase_date) {
phase_date = new Date()
}
phase_date = julian.fromDate(phase_date)
const day = phase_date - EPOCH
// calculate sun position
const sun_mean_anomaly =
(360.0 / 365.2422) * day +
(ECLIPTIC_LONGITUDE_EPOCH - ECLIPTIC_LONGITUDE_PERIGEE)
const sun_true_anomaly =
2 * todeg(Math.atan(
Math.sqrt((1.0 + ECCENTRICITY) / (1.0 - ECCENTRICITY)) *
Math.tan(0.5 * kepler(sun_mean_anomaly, ECCENTRICITY))
))
const sun_ecliptic_longitude =
ECLIPTIC_LONGITUDE_PERIGEE + sun_true_anomaly
const sun_orbital_distance_factor =
(1 + ECCENTRICITY * dcos(sun_true_anomaly)) /
(1 - ECCENTRICITY * ECCENTRICITY)
// calculate moon position
const moon_mean_longitude =
MOON_MEAN_LONGITUDE_EPOCH + 13.1763966 * day
const moon_mean_anomaly =
moon_mean_longitude - 0.1114041 * day - MOON_MEAN_PERIGEE_EPOCH
const moon_evection =
1.2739 * dsin(
2 * (moon_mean_longitude - sun_ecliptic_longitude) - moon_mean_anomaly
)
const moon_annual_equation =
0.1858 * dsin(sun_mean_anomaly)
// XXX: what is the proper name for this value?
const moon_mp =
moon_mean_anomaly +
moon_evection -
moon_annual_equation -
0.37 * dsin(sun_mean_anomaly)
const moon_equation_center_correction =
6.2886 * dsin(moon_mp)
const moon_corrected_longitude =
moon_mean_longitude +
moon_evection +
moon_equation_center_correction -
moon_annual_equation +
0.214 * dsin(2.0 * moon_mp)
const moon_age =
fixangle(
moon_corrected_longitude -
sun_ecliptic_longitude +
0.6583 * dsin(
2 * (moon_corrected_longitude - sun_ecliptic_longitude)
)
)
const moon_distance =
(MOON_SMAXIS * (1.0 - MOON_ECCENTRICITY * MOON_ECCENTRICITY)) /
(1.0 + MOON_ECCENTRICITY * dcos(moon_mp + moon_equation_center_correction))
return {
phase: (1.0 / 360.0) * moon_age,
illuminated: 0.5 * (1.0 - dcos(moon_age)),
age: (SYNODIC_MONTH / 360.0) * moon_age,
distance: moon_distance,
angular_diameter: MOON_ANGULAR_SIZE_SMAXIS / moon_distance,
sun_distance: SUN_SMAXIS / sun_orbital_distance_factor,
sun_angular_diameter: SUN_ANGULAR_SIZE_SMAXIS * sun_orbital_distance_factor
}
} | javascript | function phase (phase_date) {
if (!phase_date) {
phase_date = new Date()
}
phase_date = julian.fromDate(phase_date)
const day = phase_date - EPOCH
// calculate sun position
const sun_mean_anomaly =
(360.0 / 365.2422) * day +
(ECLIPTIC_LONGITUDE_EPOCH - ECLIPTIC_LONGITUDE_PERIGEE)
const sun_true_anomaly =
2 * todeg(Math.atan(
Math.sqrt((1.0 + ECCENTRICITY) / (1.0 - ECCENTRICITY)) *
Math.tan(0.5 * kepler(sun_mean_anomaly, ECCENTRICITY))
))
const sun_ecliptic_longitude =
ECLIPTIC_LONGITUDE_PERIGEE + sun_true_anomaly
const sun_orbital_distance_factor =
(1 + ECCENTRICITY * dcos(sun_true_anomaly)) /
(1 - ECCENTRICITY * ECCENTRICITY)
// calculate moon position
const moon_mean_longitude =
MOON_MEAN_LONGITUDE_EPOCH + 13.1763966 * day
const moon_mean_anomaly =
moon_mean_longitude - 0.1114041 * day - MOON_MEAN_PERIGEE_EPOCH
const moon_evection =
1.2739 * dsin(
2 * (moon_mean_longitude - sun_ecliptic_longitude) - moon_mean_anomaly
)
const moon_annual_equation =
0.1858 * dsin(sun_mean_anomaly)
// XXX: what is the proper name for this value?
const moon_mp =
moon_mean_anomaly +
moon_evection -
moon_annual_equation -
0.37 * dsin(sun_mean_anomaly)
const moon_equation_center_correction =
6.2886 * dsin(moon_mp)
const moon_corrected_longitude =
moon_mean_longitude +
moon_evection +
moon_equation_center_correction -
moon_annual_equation +
0.214 * dsin(2.0 * moon_mp)
const moon_age =
fixangle(
moon_corrected_longitude -
sun_ecliptic_longitude +
0.6583 * dsin(
2 * (moon_corrected_longitude - sun_ecliptic_longitude)
)
)
const moon_distance =
(MOON_SMAXIS * (1.0 - MOON_ECCENTRICITY * MOON_ECCENTRICITY)) /
(1.0 + MOON_ECCENTRICITY * dcos(moon_mp + moon_equation_center_correction))
return {
phase: (1.0 / 360.0) * moon_age,
illuminated: 0.5 * (1.0 - dcos(moon_age)),
age: (SYNODIC_MONTH / 360.0) * moon_age,
distance: moon_distance,
angular_diameter: MOON_ANGULAR_SIZE_SMAXIS / moon_distance,
sun_distance: SUN_SMAXIS / sun_orbital_distance_factor,
sun_angular_diameter: SUN_ANGULAR_SIZE_SMAXIS * sun_orbital_distance_factor
}
} | [
"function",
"phase",
"(",
"phase_date",
")",
"{",
"if",
"(",
"!",
"phase_date",
")",
"{",
"phase_date",
"=",
"new",
"Date",
"(",
")",
"}",
"phase_date",
"=",
"julian",
".",
"fromDate",
"(",
"phase_date",
")",
"const",
"day",
"=",
"phase_date",
"-",
"EPOCH",
"const",
"sun_mean_anomaly",
"=",
"(",
"360.0",
"/",
"365.2422",
")",
"*",
"day",
"+",
"(",
"ECLIPTIC_LONGITUDE_EPOCH",
"-",
"ECLIPTIC_LONGITUDE_PERIGEE",
")",
"const",
"sun_true_anomaly",
"=",
"2",
"*",
"todeg",
"(",
"Math",
".",
"atan",
"(",
"Math",
".",
"sqrt",
"(",
"(",
"1.0",
"+",
"ECCENTRICITY",
")",
"/",
"(",
"1.0",
"-",
"ECCENTRICITY",
")",
")",
"*",
"Math",
".",
"tan",
"(",
"0.5",
"*",
"kepler",
"(",
"sun_mean_anomaly",
",",
"ECCENTRICITY",
")",
")",
")",
")",
"const",
"sun_ecliptic_longitude",
"=",
"ECLIPTIC_LONGITUDE_PERIGEE",
"+",
"sun_true_anomaly",
"const",
"sun_orbital_distance_factor",
"=",
"(",
"1",
"+",
"ECCENTRICITY",
"*",
"dcos",
"(",
"sun_true_anomaly",
")",
")",
"/",
"(",
"1",
"-",
"ECCENTRICITY",
"*",
"ECCENTRICITY",
")",
"const",
"moon_mean_longitude",
"=",
"MOON_MEAN_LONGITUDE_EPOCH",
"+",
"13.1763966",
"*",
"day",
"const",
"moon_mean_anomaly",
"=",
"moon_mean_longitude",
"-",
"0.1114041",
"*",
"day",
"-",
"MOON_MEAN_PERIGEE_EPOCH",
"const",
"moon_evection",
"=",
"1.2739",
"*",
"dsin",
"(",
"2",
"*",
"(",
"moon_mean_longitude",
"-",
"sun_ecliptic_longitude",
")",
"-",
"moon_mean_anomaly",
")",
"const",
"moon_annual_equation",
"=",
"0.1858",
"*",
"dsin",
"(",
"sun_mean_anomaly",
")",
"const",
"moon_mp",
"=",
"moon_mean_anomaly",
"+",
"moon_evection",
"-",
"moon_annual_equation",
"-",
"0.37",
"*",
"dsin",
"(",
"sun_mean_anomaly",
")",
"const",
"moon_equation_center_correction",
"=",
"6.2886",
"*",
"dsin",
"(",
"moon_mp",
")",
"const",
"moon_corrected_longitude",
"=",
"moon_mean_longitude",
"+",
"moon_evection",
"+",
"moon_equation_center_correction",
"-",
"moon_annual_equation",
"+",
"0.214",
"*",
"dsin",
"(",
"2.0",
"*",
"moon_mp",
")",
"const",
"moon_age",
"=",
"fixangle",
"(",
"moon_corrected_longitude",
"-",
"sun_ecliptic_longitude",
"+",
"0.6583",
"*",
"dsin",
"(",
"2",
"*",
"(",
"moon_corrected_longitude",
"-",
"sun_ecliptic_longitude",
")",
")",
")",
"const",
"moon_distance",
"=",
"(",
"MOON_SMAXIS",
"*",
"(",
"1.0",
"-",
"MOON_ECCENTRICITY",
"*",
"MOON_ECCENTRICITY",
")",
")",
"/",
"(",
"1.0",
"+",
"MOON_ECCENTRICITY",
"*",
"dcos",
"(",
"moon_mp",
"+",
"moon_equation_center_correction",
")",
")",
"return",
"{",
"phase",
":",
"(",
"1.0",
"/",
"360.0",
")",
"*",
"moon_age",
",",
"illuminated",
":",
"0.5",
"*",
"(",
"1.0",
"-",
"dcos",
"(",
"moon_age",
")",
")",
",",
"age",
":",
"(",
"SYNODIC_MONTH",
"/",
"360.0",
")",
"*",
"moon_age",
",",
"distance",
":",
"moon_distance",
",",
"angular_diameter",
":",
"MOON_ANGULAR_SIZE_SMAXIS",
"/",
"moon_distance",
",",
"sun_distance",
":",
"SUN_SMAXIS",
"/",
"sun_orbital_distance_factor",
",",
"sun_angular_diameter",
":",
"SUN_ANGULAR_SIZE_SMAXIS",
"*",
"sun_orbital_distance_factor",
"}",
"}"
] | Finds the phase information for specific date.
@param {Date} phase_date Date to get phase information of.
@return {Object} Phase data | [
"Finds",
"the",
"phase",
"information",
"for",
"specific",
"date",
"."
] | 667d6ff778d0deb2cd09988e3d89eb8ca0428a23 | https://github.com/ryanseys/lune/blob/667d6ff778d0deb2cd09988e3d89eb8ca0428a23/lib/lune.js#L121-L190 | train |
ryanseys/lune | lib/lune.js | phase_hunt | function phase_hunt (sdate) {
if (!sdate) {
sdate = new Date()
}
let adate = new Date(sdate.getTime() - (45 * 86400000)) // 45 days prior
let k1 = Math.floor(12.3685 * (adate.getFullYear() + (1.0 / 12.0) * adate.getMonth() - 1900))
let nt1 = meanphase(adate.getTime(), k1)
sdate = julian.fromDate(sdate)
adate = nt1 + SYNODIC_MONTH
let k2 = k1 + 1
let nt2 = meanphase(adate, k2)
while (nt1 > sdate || sdate >= nt2) {
adate += SYNODIC_MONTH
k1++
k2++
nt1 = nt2
nt2 = meanphase(adate, k2)
}
return {
new_date: truephase(k1, NEW),
q1_date: truephase(k1, FIRST),
full_date: truephase(k1, FULL),
q3_date: truephase(k1, LAST),
nextnew_date: truephase(k2, NEW)
}
} | javascript | function phase_hunt (sdate) {
if (!sdate) {
sdate = new Date()
}
let adate = new Date(sdate.getTime() - (45 * 86400000)) // 45 days prior
let k1 = Math.floor(12.3685 * (adate.getFullYear() + (1.0 / 12.0) * adate.getMonth() - 1900))
let nt1 = meanphase(adate.getTime(), k1)
sdate = julian.fromDate(sdate)
adate = nt1 + SYNODIC_MONTH
let k2 = k1 + 1
let nt2 = meanphase(adate, k2)
while (nt1 > sdate || sdate >= nt2) {
adate += SYNODIC_MONTH
k1++
k2++
nt1 = nt2
nt2 = meanphase(adate, k2)
}
return {
new_date: truephase(k1, NEW),
q1_date: truephase(k1, FIRST),
full_date: truephase(k1, FULL),
q3_date: truephase(k1, LAST),
nextnew_date: truephase(k2, NEW)
}
} | [
"function",
"phase_hunt",
"(",
"sdate",
")",
"{",
"if",
"(",
"!",
"sdate",
")",
"{",
"sdate",
"=",
"new",
"Date",
"(",
")",
"}",
"let",
"adate",
"=",
"new",
"Date",
"(",
"sdate",
".",
"getTime",
"(",
")",
"-",
"(",
"45",
"*",
"86400000",
")",
")",
"let",
"k1",
"=",
"Math",
".",
"floor",
"(",
"12.3685",
"*",
"(",
"adate",
".",
"getFullYear",
"(",
")",
"+",
"(",
"1.0",
"/",
"12.0",
")",
"*",
"adate",
".",
"getMonth",
"(",
")",
"-",
"1900",
")",
")",
"let",
"nt1",
"=",
"meanphase",
"(",
"adate",
".",
"getTime",
"(",
")",
",",
"k1",
")",
"sdate",
"=",
"julian",
".",
"fromDate",
"(",
"sdate",
")",
"adate",
"=",
"nt1",
"+",
"SYNODIC_MONTH",
"let",
"k2",
"=",
"k1",
"+",
"1",
"let",
"nt2",
"=",
"meanphase",
"(",
"adate",
",",
"k2",
")",
"while",
"(",
"nt1",
">",
"sdate",
"||",
"sdate",
">=",
"nt2",
")",
"{",
"adate",
"+=",
"SYNODIC_MONTH",
"k1",
"++",
"k2",
"++",
"nt1",
"=",
"nt2",
"nt2",
"=",
"meanphase",
"(",
"adate",
",",
"k2",
")",
"}",
"return",
"{",
"new_date",
":",
"truephase",
"(",
"k1",
",",
"NEW",
")",
",",
"q1_date",
":",
"truephase",
"(",
"k1",
",",
"FIRST",
")",
",",
"full_date",
":",
"truephase",
"(",
"k1",
",",
"FULL",
")",
",",
"q3_date",
":",
"truephase",
"(",
"k1",
",",
"LAST",
")",
",",
"nextnew_date",
":",
"truephase",
"(",
"k2",
",",
"NEW",
")",
"}",
"}"
] | Find time of phases of the moon which surround the current date.
Five phases are found, starting and ending with the new moons
which bound the current lunation.
@param {Date} sdate Date to start hunting from (defaults to current date)
@return {Object} Object containing recent past and future phases | [
"Find",
"time",
"of",
"phases",
"of",
"the",
"moon",
"which",
"surround",
"the",
"current",
"date",
".",
"Five",
"phases",
"are",
"found",
"starting",
"and",
"ending",
"with",
"the",
"new",
"moons",
"which",
"bound",
"the",
"current",
"lunation",
"."
] | 667d6ff778d0deb2cd09988e3d89eb8ca0428a23 | https://github.com/ryanseys/lune/blob/667d6ff778d0deb2cd09988e3d89eb8ca0428a23/lib/lune.js#L301-L329 | train |
dundalek/react-blessed-contrib | examples/dashboard.js | generateTable | function generateTable() {
var data = []
for (var i=0; i<30; i++) {
var row = []
row.push(commands[Math.round(Math.random()*(commands.length-1))])
row.push(Math.round(Math.random()*5))
row.push(Math.round(Math.random()*100))
data.push(row)
}
return {headers: ['Process', 'Cpu (%)', 'Memory'], data: data};
} | javascript | function generateTable() {
var data = []
for (var i=0; i<30; i++) {
var row = []
row.push(commands[Math.round(Math.random()*(commands.length-1))])
row.push(Math.round(Math.random()*5))
row.push(Math.round(Math.random()*100))
data.push(row)
}
return {headers: ['Process', 'Cpu (%)', 'Memory'], data: data};
} | [
"function",
"generateTable",
"(",
")",
"{",
"var",
"data",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"30",
";",
"i",
"++",
")",
"{",
"var",
"row",
"=",
"[",
"]",
"row",
".",
"push",
"(",
"commands",
"[",
"Math",
".",
"round",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"(",
"commands",
".",
"length",
"-",
"1",
")",
")",
"]",
")",
"row",
".",
"push",
"(",
"Math",
".",
"round",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"5",
")",
")",
"row",
".",
"push",
"(",
"Math",
".",
"round",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"100",
")",
")",
"data",
".",
"push",
"(",
"row",
")",
"}",
"return",
"{",
"headers",
":",
"[",
"'Process'",
",",
"'Cpu (%)'",
",",
"'Memory'",
"]",
",",
"data",
":",
"data",
"}",
";",
"}"
] | set dummy data for table | [
"set",
"dummy",
"data",
"for",
"table"
] | 2beb36f4416665aaca5dfb85a49dbcd625911e1d | https://github.com/dundalek/react-blessed-contrib/blob/2beb36f4416665aaca5dfb85a49dbcd625911e1d/examples/dashboard.js#L13-L25 | train |
dundalek/react-blessed-contrib | src/index.js | Grid | function Grid(props) {
const grid = new contrib.grid({...props, screen: { append: () => {} }});
const children = props.children instanceof Array ? props.children : [props.children];
return React.createElement(props.component || 'element', {}, children.map((child, key) => {
const props = child.props;
const options = grid.set(props.row, props.col, props.rowSpan || 1, props.colSpan || 1, x => x, props.options);
options.key = key;
return React.cloneElement(child, options);
}));
} | javascript | function Grid(props) {
const grid = new contrib.grid({...props, screen: { append: () => {} }});
const children = props.children instanceof Array ? props.children : [props.children];
return React.createElement(props.component || 'element', {}, children.map((child, key) => {
const props = child.props;
const options = grid.set(props.row, props.col, props.rowSpan || 1, props.colSpan || 1, x => x, props.options);
options.key = key;
return React.cloneElement(child, options);
}));
} | [
"function",
"Grid",
"(",
"props",
")",
"{",
"const",
"grid",
"=",
"new",
"contrib",
".",
"grid",
"(",
"{",
"...",
"props",
",",
"screen",
":",
"{",
"append",
":",
"(",
")",
"=>",
"{",
"}",
"}",
"}",
")",
";",
"const",
"children",
"=",
"props",
".",
"children",
"instanceof",
"Array",
"?",
"props",
".",
"children",
":",
"[",
"props",
".",
"children",
"]",
";",
"return",
"React",
".",
"createElement",
"(",
"props",
".",
"component",
"||",
"'element'",
",",
"{",
"}",
",",
"children",
".",
"map",
"(",
"(",
"child",
",",
"key",
")",
"=>",
"{",
"const",
"props",
"=",
"child",
".",
"props",
";",
"const",
"options",
"=",
"grid",
".",
"set",
"(",
"props",
".",
"row",
",",
"props",
".",
"col",
",",
"props",
".",
"rowSpan",
"||",
"1",
",",
"props",
".",
"colSpan",
"||",
"1",
",",
"x",
"=>",
"x",
",",
"props",
".",
"options",
")",
";",
"options",
".",
"key",
"=",
"key",
";",
"return",
"React",
".",
"cloneElement",
"(",
"child",
",",
"options",
")",
";",
"}",
")",
")",
";",
"}"
] | We stub methods for contrib.grid to let it compute params for us which we then render in the React way | [
"We",
"stub",
"methods",
"for",
"contrib",
".",
"grid",
"to",
"let",
"it",
"compute",
"params",
"for",
"us",
"which",
"we",
"then",
"render",
"in",
"the",
"React",
"way"
] | 2beb36f4416665aaca5dfb85a49dbcd625911e1d | https://github.com/dundalek/react-blessed-contrib/blob/2beb36f4416665aaca5dfb85a49dbcd625911e1d/src/index.js#L53-L62 | train |
grncdr/js-shell-parse | build.js | parse | function parse (input, opts) {
// Wrap parser.parse to allow specifying the start rule
// as a shorthand option
if (!opts) {
opts = {}
}
else if (typeof opts == 'string') {
opts = { startRule: opts }
}
return parser.parse(input, opts)
} | javascript | function parse (input, opts) {
// Wrap parser.parse to allow specifying the start rule
// as a shorthand option
if (!opts) {
opts = {}
}
else if (typeof opts == 'string') {
opts = { startRule: opts }
}
return parser.parse(input, opts)
} | [
"function",
"parse",
"(",
"input",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"opts",
")",
"{",
"opts",
"=",
"{",
"}",
"}",
"else",
"if",
"(",
"typeof",
"opts",
"==",
"'string'",
")",
"{",
"opts",
"=",
"{",
"startRule",
":",
"opts",
"}",
"}",
"return",
"parser",
".",
"parse",
"(",
"input",
",",
"opts",
")",
"}"
] | This isn't called directly, but stringified into the resulting source | [
"This",
"isn",
"t",
"called",
"directly",
"but",
"stringified",
"into",
"the",
"resulting",
"source"
] | f5f65af37f42b120912bbad608e9da1cd909c27c | https://github.com/grncdr/js-shell-parse/blob/f5f65af37f42b120912bbad608e9da1cd909c27c/build.js#L58-L68 | train |
easylogic/codemirror-colorpicker | addon/codemirror-colorpicker.js | partial | function partial(area) {
var allFilter = null;
for (var _len2 = arguments.length, filters = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
filters[_key2 - 1] = arguments[_key2];
}
if (filters.length == 1 && typeof filters[0] === 'string') {
allFilter = filter$1(filters[0]);
} else {
allFilter = merge$1(filters);
}
return function (bitmap, done) {
var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
allFilter(getBitmap(bitmap, area), function (newBitmap) {
done(putBitmap(bitmap, newBitmap, area));
}, opt);
};
} | javascript | function partial(area) {
var allFilter = null;
for (var _len2 = arguments.length, filters = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
filters[_key2 - 1] = arguments[_key2];
}
if (filters.length == 1 && typeof filters[0] === 'string') {
allFilter = filter$1(filters[0]);
} else {
allFilter = merge$1(filters);
}
return function (bitmap, done) {
var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
allFilter(getBitmap(bitmap, area), function (newBitmap) {
done(putBitmap(bitmap, newBitmap, area));
}, opt);
};
} | [
"function",
"partial",
"(",
"area",
")",
"{",
"var",
"allFilter",
"=",
"null",
";",
"for",
"(",
"var",
"_len2",
"=",
"arguments",
".",
"length",
",",
"filters",
"=",
"Array",
"(",
"_len2",
">",
"1",
"?",
"_len2",
"-",
"1",
":",
"0",
")",
",",
"_key2",
"=",
"1",
";",
"_key2",
"<",
"_len2",
";",
"_key2",
"++",
")",
"{",
"filters",
"[",
"_key2",
"-",
"1",
"]",
"=",
"arguments",
"[",
"_key2",
"]",
";",
"}",
"if",
"(",
"filters",
".",
"length",
"==",
"1",
"&&",
"typeof",
"filters",
"[",
"0",
"]",
"===",
"'string'",
")",
"{",
"allFilter",
"=",
"filter$1",
"(",
"filters",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"allFilter",
"=",
"merge$1",
"(",
"filters",
")",
";",
"}",
"return",
"function",
"(",
"bitmap",
",",
"done",
")",
"{",
"var",
"opt",
"=",
"arguments",
".",
"length",
">",
"2",
"&&",
"arguments",
"[",
"2",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"2",
"]",
":",
"{",
"}",
";",
"allFilter",
"(",
"getBitmap",
"(",
"bitmap",
",",
"area",
")",
",",
"function",
"(",
"newBitmap",
")",
"{",
"done",
"(",
"putBitmap",
"(",
"bitmap",
",",
"newBitmap",
",",
"area",
")",
")",
";",
"}",
",",
"opt",
")",
";",
"}",
";",
"}"
] | apply filter into special area
F.partial({x,y,width,height}, filter, filter, filter )
F.partial({x,y,width,height}, 'filter' )
@param {{x, y, width, height}} area
@param {*} filters | [
"apply",
"filter",
"into",
"special",
"area"
] | 5dc686d8394b89fefb1ff1ac968521575f41d1cd | https://github.com/easylogic/codemirror-colorpicker/blob/5dc686d8394b89fefb1ff1ac968521575f41d1cd/addon/codemirror-colorpicker.js#L4028-L4048 | train |
darach/eep-js | samples/custom.js | function(regex) {
var self = this; var re = new RegExp(regex);
var keys = {};
self.init = function() { keys = {}; };
self.accumulate = function(line) {
var m = re.exec(line);
if (m == null) return;
var k = m[1]; // use 1st group as key
var v = keys[k];
if (v) keys[k] = v+1; else keys[k] = 1; // count by key
};
self.compensate = function(line) {
var m = re.exec(line);
if (m == null) return;
var k = m[1]; // use 1st group as key
var v = keys[k];
if (v) keys[k] = v-1; else keys[k] = 1;
};
self.emit = function() {
return keys;
};
self.make = function() { return new WideFinderFunction(regex); };
} | javascript | function(regex) {
var self = this; var re = new RegExp(regex);
var keys = {};
self.init = function() { keys = {}; };
self.accumulate = function(line) {
var m = re.exec(line);
if (m == null) return;
var k = m[1]; // use 1st group as key
var v = keys[k];
if (v) keys[k] = v+1; else keys[k] = 1; // count by key
};
self.compensate = function(line) {
var m = re.exec(line);
if (m == null) return;
var k = m[1]; // use 1st group as key
var v = keys[k];
if (v) keys[k] = v-1; else keys[k] = 1;
};
self.emit = function() {
return keys;
};
self.make = function() { return new WideFinderFunction(regex); };
} | [
"function",
"(",
"regex",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"regex",
")",
";",
"var",
"keys",
"=",
"{",
"}",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"keys",
"=",
"{",
"}",
";",
"}",
";",
"self",
".",
"accumulate",
"=",
"function",
"(",
"line",
")",
"{",
"var",
"m",
"=",
"re",
".",
"exec",
"(",
"line",
")",
";",
"if",
"(",
"m",
"==",
"null",
")",
"return",
";",
"var",
"k",
"=",
"m",
"[",
"1",
"]",
";",
"var",
"v",
"=",
"keys",
"[",
"k",
"]",
";",
"if",
"(",
"v",
")",
"keys",
"[",
"k",
"]",
"=",
"v",
"+",
"1",
";",
"else",
"keys",
"[",
"k",
"]",
"=",
"1",
";",
"}",
";",
"self",
".",
"compensate",
"=",
"function",
"(",
"line",
")",
"{",
"var",
"m",
"=",
"re",
".",
"exec",
"(",
"line",
")",
";",
"if",
"(",
"m",
"==",
"null",
")",
"return",
";",
"var",
"k",
"=",
"m",
"[",
"1",
"]",
";",
"var",
"v",
"=",
"keys",
"[",
"k",
"]",
";",
"if",
"(",
"v",
")",
"keys",
"[",
"k",
"]",
"=",
"v",
"-",
"1",
";",
"else",
"keys",
"[",
"k",
"]",
"=",
"1",
";",
"}",
";",
"self",
".",
"emit",
"=",
"function",
"(",
")",
"{",
"return",
"keys",
";",
"}",
";",
"self",
".",
"make",
"=",
"function",
"(",
")",
"{",
"return",
"new",
"WideFinderFunction",
"(",
"regex",
")",
";",
"}",
";",
"}"
] | Widefinder aggregate function | [
"Widefinder",
"aggregate",
"function"
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/samples/custom.js#L9-L31 | train |
|
darach/eep-js | lib/eep.aggregate_function.js | AggregateFunction | function AggregateFunction() {
var self = this;
// function type can be one of
// - simple (default)
// - ordered - will require window to store elements in arrival and sorted order
//
self.type = "simple";
// invoked when a window opens - should 'reset' or 'zero' a windows internal state
self.init = function() { throw "Must subclass"; };
// invoked when an event is enqueued into a window
self.accumulate = function(value) { throw "Must subclass"; };
// invoked to compensate sliding window overwrite
self.compensate = function(value) { throw "Must subclass"; };
// invoked when a window closes
self.emit = function() { throw "Must subclass"; };
// used by window implementations variously to preallocate function instances - makes things 'fast', basically
self.make = function(win) { throw "Must subclass"; };
} | javascript | function AggregateFunction() {
var self = this;
// function type can be one of
// - simple (default)
// - ordered - will require window to store elements in arrival and sorted order
//
self.type = "simple";
// invoked when a window opens - should 'reset' or 'zero' a windows internal state
self.init = function() { throw "Must subclass"; };
// invoked when an event is enqueued into a window
self.accumulate = function(value) { throw "Must subclass"; };
// invoked to compensate sliding window overwrite
self.compensate = function(value) { throw "Must subclass"; };
// invoked when a window closes
self.emit = function() { throw "Must subclass"; };
// used by window implementations variously to preallocate function instances - makes things 'fast', basically
self.make = function(win) { throw "Must subclass"; };
} | [
"function",
"AggregateFunction",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"type",
"=",
"\"simple\"",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"throw",
"\"Must subclass\"",
";",
"}",
";",
"self",
".",
"accumulate",
"=",
"function",
"(",
"value",
")",
"{",
"throw",
"\"Must subclass\"",
";",
"}",
";",
"self",
".",
"compensate",
"=",
"function",
"(",
"value",
")",
"{",
"throw",
"\"Must subclass\"",
";",
"}",
";",
"self",
".",
"emit",
"=",
"function",
"(",
")",
"{",
"throw",
"\"Must subclass\"",
";",
"}",
";",
"self",
".",
"make",
"=",
"function",
"(",
"win",
")",
"{",
"throw",
"\"Must subclass\"",
";",
"}",
";",
"}"
] | Constraints computations on event streams to a simple functional contract | [
"Constraints",
"computations",
"on",
"event",
"streams",
"to",
"a",
"simple",
"functional",
"contract"
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.aggregate_function.js#L25-L42 | train |
darach/eep-js | lib/eep.fn.stats.js | CountFunction | function CountFunction(win) {
var self = this, n;
self.name = "count";
self.type = "simple";
self.init = function() { n = 0; };
self.accumulate = function(ignored) { n += 1; };
self.compensate = function(ignored) { n -= 1; };
self.emit = function() { return n; };
self.make = function(win) { return new CountFunction(win); };
} | javascript | function CountFunction(win) {
var self = this, n;
self.name = "count";
self.type = "simple";
self.init = function() { n = 0; };
self.accumulate = function(ignored) { n += 1; };
self.compensate = function(ignored) { n -= 1; };
self.emit = function() { return n; };
self.make = function(win) { return new CountFunction(win); };
} | [
"function",
"CountFunction",
"(",
"win",
")",
"{",
"var",
"self",
"=",
"this",
",",
"n",
";",
"self",
".",
"name",
"=",
"\"count\"",
";",
"self",
".",
"type",
"=",
"\"simple\"",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"n",
"=",
"0",
";",
"}",
";",
"self",
".",
"accumulate",
"=",
"function",
"(",
"ignored",
")",
"{",
"n",
"+=",
"1",
";",
"}",
";",
"self",
".",
"compensate",
"=",
"function",
"(",
"ignored",
")",
"{",
"n",
"-=",
"1",
";",
"}",
";",
"self",
".",
"emit",
"=",
"function",
"(",
")",
"{",
"return",
"n",
";",
"}",
";",
"self",
".",
"make",
"=",
"function",
"(",
"win",
")",
"{",
"return",
"new",
"CountFunction",
"(",
"win",
")",
";",
"}",
";",
"}"
] | Count all the things | [
"Count",
"all",
"the",
"things"
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L26-L35 | train |
darach/eep-js | lib/eep.fn.stats.js | SumFunction | function SumFunction(win) {
var self = this, s;
self.name = "sum";
self.type = "simple";
self.init = function() { s = 0; };
self.accumulate = function(v) { s += v; };
self.compensate = function(v) { s -= v; };
self.emit = function() { return s; };
self.make = function(win) { return new SumFunction(win); };
} | javascript | function SumFunction(win) {
var self = this, s;
self.name = "sum";
self.type = "simple";
self.init = function() { s = 0; };
self.accumulate = function(v) { s += v; };
self.compensate = function(v) { s -= v; };
self.emit = function() { return s; };
self.make = function(win) { return new SumFunction(win); };
} | [
"function",
"SumFunction",
"(",
"win",
")",
"{",
"var",
"self",
"=",
"this",
",",
"s",
";",
"self",
".",
"name",
"=",
"\"sum\"",
";",
"self",
".",
"type",
"=",
"\"simple\"",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"s",
"=",
"0",
";",
"}",
";",
"self",
".",
"accumulate",
"=",
"function",
"(",
"v",
")",
"{",
"s",
"+=",
"v",
";",
"}",
";",
"self",
".",
"compensate",
"=",
"function",
"(",
"v",
")",
"{",
"s",
"-=",
"v",
";",
"}",
";",
"self",
".",
"emit",
"=",
"function",
"(",
")",
"{",
"return",
"s",
";",
"}",
";",
"self",
".",
"make",
"=",
"function",
"(",
"win",
")",
"{",
"return",
"new",
"SumFunction",
"(",
"win",
")",
";",
"}",
";",
"}"
] | Sum all the things | [
"Sum",
"all",
"the",
"things"
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L39-L48 | train |
darach/eep-js | lib/eep.fn.stats.js | MinFunction | function MinFunction(win) {
var self = this, r;
self.win = win;
self.name = "min";
self.type = "ordered_reverse";
self.init = function() { r = null; };
self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v < r) ? v : r; };
self.compensate = function(v) { r = self.win.min(); };
self.emit = function() { return r; };
self.make = function(win) { return new MinFunction(win); };
} | javascript | function MinFunction(win) {
var self = this, r;
self.win = win;
self.name = "min";
self.type = "ordered_reverse";
self.init = function() { r = null; };
self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v < r) ? v : r; };
self.compensate = function(v) { r = self.win.min(); };
self.emit = function() { return r; };
self.make = function(win) { return new MinFunction(win); };
} | [
"function",
"MinFunction",
"(",
"win",
")",
"{",
"var",
"self",
"=",
"this",
",",
"r",
";",
"self",
".",
"win",
"=",
"win",
";",
"self",
".",
"name",
"=",
"\"min\"",
";",
"self",
".",
"type",
"=",
"\"ordered_reverse\"",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"r",
"=",
"null",
";",
"}",
";",
"self",
".",
"accumulate",
"=",
"function",
"(",
"v",
")",
"{",
"if",
"(",
"v",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"r",
"==",
"null",
")",
"{",
"r",
"=",
"v",
";",
"return",
";",
"}",
"r",
"=",
"(",
"v",
"<",
"r",
")",
"?",
"v",
":",
"r",
";",
"}",
";",
"self",
".",
"compensate",
"=",
"function",
"(",
"v",
")",
"{",
"r",
"=",
"self",
".",
"win",
".",
"min",
"(",
")",
";",
"}",
";",
"self",
".",
"emit",
"=",
"function",
"(",
")",
"{",
"return",
"r",
";",
"}",
";",
"self",
".",
"make",
"=",
"function",
"(",
"win",
")",
"{",
"return",
"new",
"MinFunction",
"(",
"win",
")",
";",
"}",
";",
"}"
] | Get the smallest of all the things | [
"Get",
"the",
"smallest",
"of",
"all",
"the",
"things"
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L52-L62 | train |
darach/eep-js | lib/eep.fn.stats.js | MaxFunction | function MaxFunction(win) {
var self = this, r;
self.win = win;
self.name = "max";
self.type = "ordered_reverse";
self.init = function() { r = null; };
self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v > r) ? v : r; };
self.compensate = function(v) { r = self.win.max(); };
self.emit = function() { return r; };
self.make = function(win) { return new MaxFunction(win); };
} | javascript | function MaxFunction(win) {
var self = this, r;
self.win = win;
self.name = "max";
self.type = "ordered_reverse";
self.init = function() { r = null; };
self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v > r) ? v : r; };
self.compensate = function(v) { r = self.win.max(); };
self.emit = function() { return r; };
self.make = function(win) { return new MaxFunction(win); };
} | [
"function",
"MaxFunction",
"(",
"win",
")",
"{",
"var",
"self",
"=",
"this",
",",
"r",
";",
"self",
".",
"win",
"=",
"win",
";",
"self",
".",
"name",
"=",
"\"max\"",
";",
"self",
".",
"type",
"=",
"\"ordered_reverse\"",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"r",
"=",
"null",
";",
"}",
";",
"self",
".",
"accumulate",
"=",
"function",
"(",
"v",
")",
"{",
"if",
"(",
"v",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"r",
"==",
"null",
")",
"{",
"r",
"=",
"v",
";",
"return",
";",
"}",
"r",
"=",
"(",
"v",
">",
"r",
")",
"?",
"v",
":",
"r",
";",
"}",
";",
"self",
".",
"compensate",
"=",
"function",
"(",
"v",
")",
"{",
"r",
"=",
"self",
".",
"win",
".",
"max",
"(",
")",
";",
"}",
";",
"self",
".",
"emit",
"=",
"function",
"(",
")",
"{",
"return",
"r",
";",
"}",
";",
"self",
".",
"make",
"=",
"function",
"(",
"win",
")",
"{",
"return",
"new",
"MaxFunction",
"(",
"win",
")",
";",
"}",
";",
"}"
] | Get the biggest of all the things | [
"Get",
"the",
"biggest",
"of",
"all",
"the",
"things"
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L66-L76 | train |
darach/eep-js | lib/eep.fn.stats.js | VarianceFunction | function VarianceFunction(win) {
var self = this, m, m2, d, n;
self.name = "vars";
self.type = "simple";
self.init = function() { m = 0; m2 = 0; d = 0; n = 0; };
self.accumulate = function(v) { n+=1; d = v - m; m = d/n + m; m2 = m2 + d*(v - m); };
self.compensate = function(v) { n-=1; d = m - v; m = m + d/n; m2 = d*(v - m) + m2; };
self.emit = function() { return m2/(n-1); };
self.make = function(win) { return new VarianceFunction(win); };
} | javascript | function VarianceFunction(win) {
var self = this, m, m2, d, n;
self.name = "vars";
self.type = "simple";
self.init = function() { m = 0; m2 = 0; d = 0; n = 0; };
self.accumulate = function(v) { n+=1; d = v - m; m = d/n + m; m2 = m2 + d*(v - m); };
self.compensate = function(v) { n-=1; d = m - v; m = m + d/n; m2 = d*(v - m) + m2; };
self.emit = function() { return m2/(n-1); };
self.make = function(win) { return new VarianceFunction(win); };
} | [
"function",
"VarianceFunction",
"(",
"win",
")",
"{",
"var",
"self",
"=",
"this",
",",
"m",
",",
"m2",
",",
"d",
",",
"n",
";",
"self",
".",
"name",
"=",
"\"vars\"",
";",
"self",
".",
"type",
"=",
"\"simple\"",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"m",
"=",
"0",
";",
"m2",
"=",
"0",
";",
"d",
"=",
"0",
";",
"n",
"=",
"0",
";",
"}",
";",
"self",
".",
"accumulate",
"=",
"function",
"(",
"v",
")",
"{",
"n",
"+=",
"1",
";",
"d",
"=",
"v",
"-",
"m",
";",
"m",
"=",
"d",
"/",
"n",
"+",
"m",
";",
"m2",
"=",
"m2",
"+",
"d",
"*",
"(",
"v",
"-",
"m",
")",
";",
"}",
";",
"self",
".",
"compensate",
"=",
"function",
"(",
"v",
")",
"{",
"n",
"-=",
"1",
";",
"d",
"=",
"m",
"-",
"v",
";",
"m",
"=",
"m",
"+",
"d",
"/",
"n",
";",
"m2",
"=",
"d",
"*",
"(",
"v",
"-",
"m",
")",
"+",
"m2",
";",
"}",
";",
"self",
".",
"emit",
"=",
"function",
"(",
")",
"{",
"return",
"m2",
"/",
"(",
"n",
"-",
"1",
")",
";",
"}",
";",
"self",
".",
"make",
"=",
"function",
"(",
"win",
")",
"{",
"return",
"new",
"VarianceFunction",
"(",
"win",
")",
";",
"}",
";",
"}"
] | Get the sample variance of all the things | [
"Get",
"the",
"sample",
"variance",
"of",
"all",
"the",
"things"
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L93-L102 | train |
darach/eep-js | lib/eep.fn.stats.js | StdevFunction | function StdevFunction(win) {
var self = this, m, m2, d, n;
self.name = "stdevs";
self.type = "simple";
self.init = function() { m = 0, m2 = 0, d = 0, n = 0; };
self.accumulate = function(v) {
n+=1;
d = v - m;
m = m + d/n;
m2 = m2 + d*(v-m);
};
self.compensate = function(v) {
n-=1;
d = m - v;
m = d/n + m;
m2 = d*(v-m) + m2;
};
self.emit = function() { return Math.sqrt(m2/(n-1)); };
self.make = function(win) { return new StdevFunction(win); };
} | javascript | function StdevFunction(win) {
var self = this, m, m2, d, n;
self.name = "stdevs";
self.type = "simple";
self.init = function() { m = 0, m2 = 0, d = 0, n = 0; };
self.accumulate = function(v) {
n+=1;
d = v - m;
m = m + d/n;
m2 = m2 + d*(v-m);
};
self.compensate = function(v) {
n-=1;
d = m - v;
m = d/n + m;
m2 = d*(v-m) + m2;
};
self.emit = function() { return Math.sqrt(m2/(n-1)); };
self.make = function(win) { return new StdevFunction(win); };
} | [
"function",
"StdevFunction",
"(",
"win",
")",
"{",
"var",
"self",
"=",
"this",
",",
"m",
",",
"m2",
",",
"d",
",",
"n",
";",
"self",
".",
"name",
"=",
"\"stdevs\"",
";",
"self",
".",
"type",
"=",
"\"simple\"",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"m",
"=",
"0",
",",
"m2",
"=",
"0",
",",
"d",
"=",
"0",
",",
"n",
"=",
"0",
";",
"}",
";",
"self",
".",
"accumulate",
"=",
"function",
"(",
"v",
")",
"{",
"n",
"+=",
"1",
";",
"d",
"=",
"v",
"-",
"m",
";",
"m",
"=",
"m",
"+",
"d",
"/",
"n",
";",
"m2",
"=",
"m2",
"+",
"d",
"*",
"(",
"v",
"-",
"m",
")",
";",
"}",
";",
"self",
".",
"compensate",
"=",
"function",
"(",
"v",
")",
"{",
"n",
"-=",
"1",
";",
"d",
"=",
"m",
"-",
"v",
";",
"m",
"=",
"d",
"/",
"n",
"+",
"m",
";",
"m2",
"=",
"d",
"*",
"(",
"v",
"-",
"m",
")",
"+",
"m2",
";",
"}",
";",
"self",
".",
"emit",
"=",
"function",
"(",
")",
"{",
"return",
"Math",
".",
"sqrt",
"(",
"m2",
"/",
"(",
"n",
"-",
"1",
")",
")",
";",
"}",
";",
"self",
".",
"make",
"=",
"function",
"(",
"win",
")",
"{",
"return",
"new",
"StdevFunction",
"(",
"win",
")",
";",
"}",
";",
"}"
] | Get the standard deviation of all the things | [
"Get",
"the",
"standard",
"deviation",
"of",
"all",
"the",
"things"
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.fn.stats.js#L106-L125 | train |
darach/eep-js | lib/eep.clock_counting.js | CountingClock | function CountingClock() {
var self = this, at, mark = null;
self.at = function() {
return at;
};
self.init = function() {
at = mark = 0;
return at;
};
self.inc = function() {
at += 1;
};
self.tick = function() {
if (mark === null) {
mark = at + 1;
}
return ((at - mark) >= 1);
};
self.tock = function(elapsed) {
var d = at - elapsed;
if ( d >= 1) {
mark += 1;
return true;
}
return false;
};
} | javascript | function CountingClock() {
var self = this, at, mark = null;
self.at = function() {
return at;
};
self.init = function() {
at = mark = 0;
return at;
};
self.inc = function() {
at += 1;
};
self.tick = function() {
if (mark === null) {
mark = at + 1;
}
return ((at - mark) >= 1);
};
self.tock = function(elapsed) {
var d = at - elapsed;
if ( d >= 1) {
mark += 1;
return true;
}
return false;
};
} | [
"function",
"CountingClock",
"(",
")",
"{",
"var",
"self",
"=",
"this",
",",
"at",
",",
"mark",
"=",
"null",
";",
"self",
".",
"at",
"=",
"function",
"(",
")",
"{",
"return",
"at",
";",
"}",
";",
"self",
".",
"init",
"=",
"function",
"(",
")",
"{",
"at",
"=",
"mark",
"=",
"0",
";",
"return",
"at",
";",
"}",
";",
"self",
".",
"inc",
"=",
"function",
"(",
")",
"{",
"at",
"+=",
"1",
";",
"}",
";",
"self",
".",
"tick",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"mark",
"===",
"null",
")",
"{",
"mark",
"=",
"at",
"+",
"1",
";",
"}",
"return",
"(",
"(",
"at",
"-",
"mark",
")",
">=",
"1",
")",
";",
"}",
";",
"self",
".",
"tock",
"=",
"function",
"(",
"elapsed",
")",
"{",
"var",
"d",
"=",
"at",
"-",
"elapsed",
";",
"if",
"(",
"d",
">=",
"1",
")",
"{",
"mark",
"+=",
"1",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
";",
"}"
] | Simple monotonic clock. Ticks and tocks like the count on Sesame St. Mwa ha ha. Monotonic, basically. | [
"Simple",
"monotonic",
"clock",
".",
"Ticks",
"and",
"tocks",
"like",
"the",
"count",
"on",
"Sesame",
"St",
".",
"Mwa",
"ha",
"ha",
".",
"Monotonic",
"basically",
"."
] | 1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6 | https://github.com/darach/eep-js/blob/1f5e1574c0dacfc73ca5de00daf4835f8d9d8dc6/lib/eep.clock_counting.js#L26-L58 | train |
nymag/nymag-fs | index.js | getFolders | function getFolders(dir) {
try {
return fs.readdirSync(dir)
.filter(function (file) {
return exports.isDirectory(path.join(dir, file));
});
} catch (ex) {
return [];
}
} | javascript | function getFolders(dir) {
try {
return fs.readdirSync(dir)
.filter(function (file) {
return exports.isDirectory(path.join(dir, file));
});
} catch (ex) {
return [];
}
} | [
"function",
"getFolders",
"(",
"dir",
")",
"{",
"try",
"{",
"return",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"return",
"exports",
".",
"isDirectory",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"file",
")",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"return",
"[",
"]",
";",
"}",
"}"
] | Get folder names.
Should only occur once per directory.
@param {string} dir enclosing folder
@return {[]} array of folder names | [
"Get",
"folder",
"names",
"."
] | 94dcd3be2c0593b676131a9760c2318c75255a71 | https://github.com/nymag/nymag-fs/blob/94dcd3be2c0593b676131a9760c2318c75255a71/index.js#L80-L89 | train |
nymag/nymag-fs | index.js | tryRequire | function tryRequire(filePath) {
let resolvedPath = req.resolve(filePath);
if (resolvedPath) {
return req(resolvedPath);
}
return undefined;
} | javascript | function tryRequire(filePath) {
let resolvedPath = req.resolve(filePath);
if (resolvedPath) {
return req(resolvedPath);
}
return undefined;
} | [
"function",
"tryRequire",
"(",
"filePath",
")",
"{",
"let",
"resolvedPath",
"=",
"req",
".",
"resolve",
"(",
"filePath",
")",
";",
"if",
"(",
"resolvedPath",
")",
"{",
"return",
"req",
"(",
"resolvedPath",
")",
";",
"}",
"return",
"undefined",
";",
"}"
] | Try to require a module, do not fail if module is missing
@param {string} filePath
@returns {module}
@throw if fails for reason other than missing module | [
"Try",
"to",
"require",
"a",
"module",
"do",
"not",
"fail",
"if",
"module",
"is",
"missing"
] | 94dcd3be2c0593b676131a9760c2318c75255a71 | https://github.com/nymag/nymag-fs/blob/94dcd3be2c0593b676131a9760c2318c75255a71/index.js#L97-L105 | train |
nymag/nymag-fs | index.js | tryRequireEach | function tryRequireEach(paths) {
let result;
while (!result && paths.length) {
result = tryRequire(paths.shift());
}
return result;
} | javascript | function tryRequireEach(paths) {
let result;
while (!result && paths.length) {
result = tryRequire(paths.shift());
}
return result;
} | [
"function",
"tryRequireEach",
"(",
"paths",
")",
"{",
"let",
"result",
";",
"while",
"(",
"!",
"result",
"&&",
"paths",
".",
"length",
")",
"{",
"result",
"=",
"tryRequire",
"(",
"paths",
".",
"shift",
"(",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Try to get a module, or return false.
@param {[string]} paths Possible paths to find their module.
@returns {object|false} | [
"Try",
"to",
"get",
"a",
"module",
"or",
"return",
"false",
"."
] | 94dcd3be2c0593b676131a9760c2318c75255a71 | https://github.com/nymag/nymag-fs/blob/94dcd3be2c0593b676131a9760c2318c75255a71/index.js#L113-L121 | train |
nymag/nymag-fs | control.js | memoize | function memoize(fn) {
const dataProp = '__data__.string.__data__',
memFn = _.memoize.apply(_, _.slice(arguments)),
report = _.throttle(reportMemoryLeak, minute),
controlFn = function () {
const result = memFn.apply(null, _.slice(arguments));
if (_.size(_.get(memFn, `cache.${dataProp}`)) >= memoryLeakThreshold) {
report(fn, _.get(memFn, `cache.${dataProp}`));
}
return result;
};
Object.defineProperty(controlFn, 'cache', defineWritable({
get() { return memFn.cache; },
set(value) { memFn.cache = value; }
}));
return controlFn;
} | javascript | function memoize(fn) {
const dataProp = '__data__.string.__data__',
memFn = _.memoize.apply(_, _.slice(arguments)),
report = _.throttle(reportMemoryLeak, minute),
controlFn = function () {
const result = memFn.apply(null, _.slice(arguments));
if (_.size(_.get(memFn, `cache.${dataProp}`)) >= memoryLeakThreshold) {
report(fn, _.get(memFn, `cache.${dataProp}`));
}
return result;
};
Object.defineProperty(controlFn, 'cache', defineWritable({
get() { return memFn.cache; },
set(value) { memFn.cache = value; }
}));
return controlFn;
} | [
"function",
"memoize",
"(",
"fn",
")",
"{",
"const",
"dataProp",
"=",
"'__data__.string.__data__'",
",",
"memFn",
"=",
"_",
".",
"memoize",
".",
"apply",
"(",
"_",
",",
"_",
".",
"slice",
"(",
"arguments",
")",
")",
",",
"report",
"=",
"_",
".",
"throttle",
"(",
"reportMemoryLeak",
",",
"minute",
")",
",",
"controlFn",
"=",
"function",
"(",
")",
"{",
"const",
"result",
"=",
"memFn",
".",
"apply",
"(",
"null",
",",
"_",
".",
"slice",
"(",
"arguments",
")",
")",
";",
"if",
"(",
"_",
".",
"size",
"(",
"_",
".",
"get",
"(",
"memFn",
",",
"`",
"${",
"dataProp",
"}",
"`",
")",
")",
">=",
"memoryLeakThreshold",
")",
"{",
"report",
"(",
"fn",
",",
"_",
".",
"get",
"(",
"memFn",
",",
"`",
"${",
"dataProp",
"}",
"`",
")",
")",
";",
"}",
"return",
"result",
";",
"}",
";",
"Object",
".",
"defineProperty",
"(",
"controlFn",
",",
"'cache'",
",",
"defineWritable",
"(",
"{",
"get",
"(",
")",
"{",
"return",
"memFn",
".",
"cache",
";",
"}",
",",
"set",
"(",
"value",
")",
"{",
"memFn",
".",
"cache",
"=",
"value",
";",
"}",
"}",
")",
")",
";",
"return",
"controlFn",
";",
"}"
] | Memoize, but warn if the target is not suitable for memoization
@param {function} fn
@returns {function} | [
"Memoize",
"but",
"warn",
"if",
"the",
"target",
"is",
"not",
"suitable",
"for",
"memoization"
] | 94dcd3be2c0593b676131a9760c2318c75255a71 | https://github.com/nymag/nymag-fs/blob/94dcd3be2c0593b676131a9760c2318c75255a71/control.js#L42-L62 | train |
IonicaBizau/iterate-object | lib/index.js | iterateObject | function iterateObject(obj, fn) {
var i = 0
, keys = []
;
if (Array.isArray(obj)) {
for (; i < obj.length; ++i) {
if (fn(obj[i], i, obj) === false) {
break;
}
}
} else if (typeof obj === "object" && obj !== null) {
keys = Object.keys(obj);
for (; i < keys.length; ++i) {
if (fn(obj[keys[i]], keys[i], obj) === false) {
break;
}
}
}
} | javascript | function iterateObject(obj, fn) {
var i = 0
, keys = []
;
if (Array.isArray(obj)) {
for (; i < obj.length; ++i) {
if (fn(obj[i], i, obj) === false) {
break;
}
}
} else if (typeof obj === "object" && obj !== null) {
keys = Object.keys(obj);
for (; i < keys.length; ++i) {
if (fn(obj[keys[i]], keys[i], obj) === false) {
break;
}
}
}
} | [
"function",
"iterateObject",
"(",
"obj",
",",
"fn",
")",
"{",
"var",
"i",
"=",
"0",
",",
"keys",
"=",
"[",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"for",
"(",
";",
"i",
"<",
"obj",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"fn",
"(",
"obj",
"[",
"i",
"]",
",",
"i",
",",
"obj",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"typeof",
"obj",
"===",
"\"object\"",
"&&",
"obj",
"!==",
"null",
")",
"{",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"for",
"(",
";",
"i",
"<",
"keys",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"fn",
"(",
"obj",
"[",
"keys",
"[",
"i",
"]",
"]",
",",
"keys",
"[",
"i",
"]",
",",
"obj",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"}",
"}"
] | iterateObject
Iterates an object. Note the object field order may differ.
@name iterateObject
@function
@param {Object} obj The input object.
@param {Function} fn A function that will be called with the current value, field name and provided object.
@return {Function} The `iterateObject` function. | [
"iterateObject",
"Iterates",
"an",
"object",
".",
"Note",
"the",
"object",
"field",
"order",
"may",
"differ",
"."
] | 8c96db262c95c62524cc4c5ab7374439a5ff8971 | https://github.com/IonicaBizau/iterate-object/blob/8c96db262c95c62524cc4c5ab7374439a5ff8971/lib/index.js#L11-L30 | train |
gbv/jskos-tools | lib/tools.js | compareMappingsDeep | function compareMappingsDeep(mapping1, mapping2) {
return _.isEqualWith(mapping1, mapping2, (object1, object2, prop) => {
let mapping1 = { [prop]: object1 }
let mapping2 = { [prop]: object2 }
if (prop == "from" || prop == "to") {
if (!_.isEqual(Object.getOwnPropertyNames(_.get(object1, prop, {})), Object.getOwnPropertyNames(_.get(object2, prop, {})))) {
return false
}
return _.isEqualWith(conceptsOfMapping(mapping1, prop), conceptsOfMapping(mapping2, prop), (concept1, concept2, index) => {
if (index != undefined) {
return compare(concept1, concept2)
}
return undefined
})
}
if (prop == "fromScheme" || prop == "toScheme") {
return compare(object1, object2)
}
// Let lodash's isEqual do the comparison
return undefined
})
} | javascript | function compareMappingsDeep(mapping1, mapping2) {
return _.isEqualWith(mapping1, mapping2, (object1, object2, prop) => {
let mapping1 = { [prop]: object1 }
let mapping2 = { [prop]: object2 }
if (prop == "from" || prop == "to") {
if (!_.isEqual(Object.getOwnPropertyNames(_.get(object1, prop, {})), Object.getOwnPropertyNames(_.get(object2, prop, {})))) {
return false
}
return _.isEqualWith(conceptsOfMapping(mapping1, prop), conceptsOfMapping(mapping2, prop), (concept1, concept2, index) => {
if (index != undefined) {
return compare(concept1, concept2)
}
return undefined
})
}
if (prop == "fromScheme" || prop == "toScheme") {
return compare(object1, object2)
}
// Let lodash's isEqual do the comparison
return undefined
})
} | [
"function",
"compareMappingsDeep",
"(",
"mapping1",
",",
"mapping2",
")",
"{",
"return",
"_",
".",
"isEqualWith",
"(",
"mapping1",
",",
"mapping2",
",",
"(",
"object1",
",",
"object2",
",",
"prop",
")",
"=>",
"{",
"let",
"mapping1",
"=",
"{",
"[",
"prop",
"]",
":",
"object1",
"}",
"let",
"mapping2",
"=",
"{",
"[",
"prop",
"]",
":",
"object2",
"}",
"if",
"(",
"prop",
"==",
"\"from\"",
"||",
"prop",
"==",
"\"to\"",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isEqual",
"(",
"Object",
".",
"getOwnPropertyNames",
"(",
"_",
".",
"get",
"(",
"object1",
",",
"prop",
",",
"{",
"}",
")",
")",
",",
"Object",
".",
"getOwnPropertyNames",
"(",
"_",
".",
"get",
"(",
"object2",
",",
"prop",
",",
"{",
"}",
")",
")",
")",
")",
"{",
"return",
"false",
"}",
"return",
"_",
".",
"isEqualWith",
"(",
"conceptsOfMapping",
"(",
"mapping1",
",",
"prop",
")",
",",
"conceptsOfMapping",
"(",
"mapping2",
",",
"prop",
")",
",",
"(",
"concept1",
",",
"concept2",
",",
"index",
")",
"=>",
"{",
"if",
"(",
"index",
"!=",
"undefined",
")",
"{",
"return",
"compare",
"(",
"concept1",
",",
"concept2",
")",
"}",
"return",
"undefined",
"}",
")",
"}",
"if",
"(",
"prop",
"==",
"\"fromScheme\"",
"||",
"prop",
"==",
"\"toScheme\"",
")",
"{",
"return",
"compare",
"(",
"object1",
",",
"object2",
")",
"}",
"return",
"undefined",
"}",
")",
"}"
] | Compare two mappings based on their properties. Concept sets and schemes are compared by URI.
@memberof module:jskos-tools | [
"Compare",
"two",
"mappings",
"based",
"on",
"their",
"properties",
".",
"Concept",
"sets",
"and",
"schemes",
"are",
"compared",
"by",
"URI",
"."
] | da8672203362ea874f4ab9cdd34b990369987075 | https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/tools.js#L419-L440 | train |
bem-contrib/md-to-bemjson | packages/mdast-util-to-bemjson/lib/index.js | toBemjson | function toBemjson(tree, options) {
const transform = transformFactory(tree, options);
return traverse(transform, tree);
} | javascript | function toBemjson(tree, options) {
const transform = transformFactory(tree, options);
return traverse(transform, tree);
} | [
"function",
"toBemjson",
"(",
"tree",
",",
"options",
")",
"{",
"const",
"transform",
"=",
"transformFactory",
"(",
"tree",
",",
"options",
")",
";",
"return",
"traverse",
"(",
"transform",
",",
"tree",
")",
";",
"}"
] | Augments bemNode with custom logic
@callback BjsonConverter~augmentCallback
@param {Object} bemNode - representation of bem entity
@returns {Object} - must return bemNode
Transform `tree`, which is an MDAST node, to a Bemjson node.
@param {Node} tree - MDAST tree
@param {Object} options - transform options
@return {Object} | [
"Augments",
"bemNode",
"with",
"custom",
"logic"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/index.js#L21-L25 | train |
rangle/koast | lib/authentication/oauth.js | makeLoginHandler | function makeLoginHandler(provider, providerAccounts) {
return function (accessToken, refreshToken, profile, done) {
log.debug('Authentiated for ' + provider);
log.debug(profile);
profile.provider = provider;
profile.idWithProvider = profile.id;
exports.getUserFromProfile(providerAccounts, profile)
.then(function (userRecord) {
// Save the user if they are new.
var fieldsToCopy = ['provider', 'displayName', 'emails'];
if (userRecord && userRecord.data) {
return userRecord;
} else {
userRecord = {
isAuthenticated: true
};
userRecord.meta = {
isRegistered: false
};
userRecord.data = {
idWithProvider: profile.id,
};
fieldsToCopy.forEach(function (key) {
userRecord.data[key] = profile[key];
});
return providerAccounts.create(userRecord.data)
.then(function () {
return userRecord;
});
}
})
.then(function (userRecord) {
done(null, userRecord);
})
.then(null, function (error) {
log.error(error);
done(error);
})
.then(null, log.error);
};
} | javascript | function makeLoginHandler(provider, providerAccounts) {
return function (accessToken, refreshToken, profile, done) {
log.debug('Authentiated for ' + provider);
log.debug(profile);
profile.provider = provider;
profile.idWithProvider = profile.id;
exports.getUserFromProfile(providerAccounts, profile)
.then(function (userRecord) {
// Save the user if they are new.
var fieldsToCopy = ['provider', 'displayName', 'emails'];
if (userRecord && userRecord.data) {
return userRecord;
} else {
userRecord = {
isAuthenticated: true
};
userRecord.meta = {
isRegistered: false
};
userRecord.data = {
idWithProvider: profile.id,
};
fieldsToCopy.forEach(function (key) {
userRecord.data[key] = profile[key];
});
return providerAccounts.create(userRecord.data)
.then(function () {
return userRecord;
});
}
})
.then(function (userRecord) {
done(null, userRecord);
})
.then(null, function (error) {
log.error(error);
done(error);
})
.then(null, log.error);
};
} | [
"function",
"makeLoginHandler",
"(",
"provider",
",",
"providerAccounts",
")",
"{",
"return",
"function",
"(",
"accessToken",
",",
"refreshToken",
",",
"profile",
",",
"done",
")",
"{",
"log",
".",
"debug",
"(",
"'Authentiated for '",
"+",
"provider",
")",
";",
"log",
".",
"debug",
"(",
"profile",
")",
";",
"profile",
".",
"provider",
"=",
"provider",
";",
"profile",
".",
"idWithProvider",
"=",
"profile",
".",
"id",
";",
"exports",
".",
"getUserFromProfile",
"(",
"providerAccounts",
",",
"profile",
")",
".",
"then",
"(",
"function",
"(",
"userRecord",
")",
"{",
"var",
"fieldsToCopy",
"=",
"[",
"'provider'",
",",
"'displayName'",
",",
"'emails'",
"]",
";",
"if",
"(",
"userRecord",
"&&",
"userRecord",
".",
"data",
")",
"{",
"return",
"userRecord",
";",
"}",
"else",
"{",
"userRecord",
"=",
"{",
"isAuthenticated",
":",
"true",
"}",
";",
"userRecord",
".",
"meta",
"=",
"{",
"isRegistered",
":",
"false",
"}",
";",
"userRecord",
".",
"data",
"=",
"{",
"idWithProvider",
":",
"profile",
".",
"id",
",",
"}",
";",
"fieldsToCopy",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"userRecord",
".",
"data",
"[",
"key",
"]",
"=",
"profile",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"providerAccounts",
".",
"create",
"(",
"userRecord",
".",
"data",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"userRecord",
";",
"}",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"userRecord",
")",
"{",
"done",
"(",
"null",
",",
"userRecord",
")",
";",
"}",
")",
".",
"then",
"(",
"null",
",",
"function",
"(",
"error",
")",
"{",
"log",
".",
"error",
"(",
"error",
")",
";",
"done",
"(",
"error",
")",
";",
"}",
")",
".",
"then",
"(",
"null",
",",
"log",
".",
"error",
")",
";",
"}",
";",
"}"
] | Makes a handler to be called after the user was authenticated with an OAuth provider. | [
"Makes",
"a",
"handler",
"to",
"be",
"called",
"after",
"the",
"user",
"was",
"authenticated",
"with",
"an",
"OAuth",
"provider",
"."
] | 446dfaba7f80c03ae17d86b34dfafd6328be1ba6 | https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/oauth.js#L73-L117 | train |
rangle/koast | lib/authentication/oauth.js | redirectToNext | function redirectToNext(req, res) {
var redirectTo = req.session.next || '';
req.session.next = null; // Null it so that we do not use it again.
res.redirect(redirectTo);
} | javascript | function redirectToNext(req, res) {
var redirectTo = req.session.next || '';
req.session.next = null; // Null it so that we do not use it again.
res.redirect(redirectTo);
} | [
"function",
"redirectToNext",
"(",
"req",
",",
"res",
")",
"{",
"var",
"redirectTo",
"=",
"req",
".",
"session",
".",
"next",
"||",
"''",
";",
"req",
".",
"session",
".",
"next",
"=",
"null",
";",
"res",
".",
"redirect",
"(",
"redirectTo",
")",
";",
"}"
] | Redirects the user to the new url. | [
"Redirects",
"the",
"user",
"to",
"the",
"new",
"url",
"."
] | 446dfaba7f80c03ae17d86b34dfafd6328be1ba6 | https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/oauth.js#L120-L124 | train |
rangle/koast | lib/authentication/oauth.js | setupStrategies | function setupStrategies(auth) {
var result = {};
if (auth.maintenance === 'token') {
result = {
facebook: require('passport-facebook').Strategy,
twitter: require('passport-twitter').Strategy
};
} else {
result = {
google: require('passport-google-oauth').OAuth2Strategy,
facebook: require('passport-facebook').Strategy,
twitter: require('passport-twitter').Strategy
};
}
return result;
} | javascript | function setupStrategies(auth) {
var result = {};
if (auth.maintenance === 'token') {
result = {
facebook: require('passport-facebook').Strategy,
twitter: require('passport-twitter').Strategy
};
} else {
result = {
google: require('passport-google-oauth').OAuth2Strategy,
facebook: require('passport-facebook').Strategy,
twitter: require('passport-twitter').Strategy
};
}
return result;
} | [
"function",
"setupStrategies",
"(",
"auth",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"if",
"(",
"auth",
".",
"maintenance",
"===",
"'token'",
")",
"{",
"result",
"=",
"{",
"facebook",
":",
"require",
"(",
"'passport-facebook'",
")",
".",
"Strategy",
",",
"twitter",
":",
"require",
"(",
"'passport-twitter'",
")",
".",
"Strategy",
"}",
";",
"}",
"else",
"{",
"result",
"=",
"{",
"google",
":",
"require",
"(",
"'passport-google-oauth'",
")",
".",
"OAuth2Strategy",
",",
"facebook",
":",
"require",
"(",
"'passport-facebook'",
")",
".",
"Strategy",
",",
"twitter",
":",
"require",
"(",
"'passport-twitter'",
")",
".",
"Strategy",
"}",
";",
"}",
"return",
"result",
";",
"}"
] | setup strategies that we can use google OAuth2Strategy requires session, which we do not setup if using token | [
"setup",
"strategies",
"that",
"we",
"can",
"use",
"google",
"OAuth2Strategy",
"requires",
"session",
"which",
"we",
"do",
"not",
"setup",
"if",
"using",
"token"
] | 446dfaba7f80c03ae17d86b34dfafd6328be1ba6 | https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/oauth.js#L238-L254 | train |
RavelLaw/e3 | addon/utils/shadow/line-interpolation/monotone.js | d3_svg_lineHermite | function d3_svg_lineHermite(points, tangents) {
if (tangents.length < 1 || (points.length !== tangents.length && points.length !== tangents.length + 2)) {
return points;
}
var quad = points.length !== tangents.length,
commands = [],
p0 = points[0],
p = points[1],
t0 = tangents[0],
t = t0,
pi = 1;
if (quad) {
commands.push([
p[0] - t0[0] * 2 / 3,
p[1] - t0[1] * 2 / 3,
p[0],
p[1]
]);
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
commands.push([
p0[0] + t0[0],
p0[1] + t0[1],
p[0] - t[0],
p[1] - t[1],
p[0],
p[1]
]);
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
let lt = tangents[i - 1];
let lp = points[i - 1];
commands.push([
lp[0] + lt[0], // Add the last tangent but reflected
lp[1] + lt[1],
p[0] - t[0],
p[1] - t[1],
p[0],
p[1]
]);
}
}
if (quad) {
var lp = points[pi];
commands.push([
p[0] + t[0] * 2 / 3,
p[1] + t[1] * 2 / 3,
lp[0],
lp[1]
]);
}
return commands;
} | javascript | function d3_svg_lineHermite(points, tangents) {
if (tangents.length < 1 || (points.length !== tangents.length && points.length !== tangents.length + 2)) {
return points;
}
var quad = points.length !== tangents.length,
commands = [],
p0 = points[0],
p = points[1],
t0 = tangents[0],
t = t0,
pi = 1;
if (quad) {
commands.push([
p[0] - t0[0] * 2 / 3,
p[1] - t0[1] * 2 / 3,
p[0],
p[1]
]);
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
commands.push([
p0[0] + t0[0],
p0[1] + t0[1],
p[0] - t[0],
p[1] - t[1],
p[0],
p[1]
]);
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
let lt = tangents[i - 1];
let lp = points[i - 1];
commands.push([
lp[0] + lt[0], // Add the last tangent but reflected
lp[1] + lt[1],
p[0] - t[0],
p[1] - t[1],
p[0],
p[1]
]);
}
}
if (quad) {
var lp = points[pi];
commands.push([
p[0] + t[0] * 2 / 3,
p[1] + t[1] * 2 / 3,
lp[0],
lp[1]
]);
}
return commands;
} | [
"function",
"d3_svg_lineHermite",
"(",
"points",
",",
"tangents",
")",
"{",
"if",
"(",
"tangents",
".",
"length",
"<",
"1",
"||",
"(",
"points",
".",
"length",
"!==",
"tangents",
".",
"length",
"&&",
"points",
".",
"length",
"!==",
"tangents",
".",
"length",
"+",
"2",
")",
")",
"{",
"return",
"points",
";",
"}",
"var",
"quad",
"=",
"points",
".",
"length",
"!==",
"tangents",
".",
"length",
",",
"commands",
"=",
"[",
"]",
",",
"p0",
"=",
"points",
"[",
"0",
"]",
",",
"p",
"=",
"points",
"[",
"1",
"]",
",",
"t0",
"=",
"tangents",
"[",
"0",
"]",
",",
"t",
"=",
"t0",
",",
"pi",
"=",
"1",
";",
"if",
"(",
"quad",
")",
"{",
"commands",
".",
"push",
"(",
"[",
"p",
"[",
"0",
"]",
"-",
"t0",
"[",
"0",
"]",
"*",
"2",
"/",
"3",
",",
"p",
"[",
"1",
"]",
"-",
"t0",
"[",
"1",
"]",
"*",
"2",
"/",
"3",
",",
"p",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"]",
")",
";",
"p0",
"=",
"points",
"[",
"1",
"]",
";",
"pi",
"=",
"2",
";",
"}",
"if",
"(",
"tangents",
".",
"length",
">",
"1",
")",
"{",
"t",
"=",
"tangents",
"[",
"1",
"]",
";",
"p",
"=",
"points",
"[",
"pi",
"]",
";",
"pi",
"++",
";",
"commands",
".",
"push",
"(",
"[",
"p0",
"[",
"0",
"]",
"+",
"t0",
"[",
"0",
"]",
",",
"p0",
"[",
"1",
"]",
"+",
"t0",
"[",
"1",
"]",
",",
"p",
"[",
"0",
"]",
"-",
"t",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"-",
"t",
"[",
"1",
"]",
",",
"p",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"]",
")",
";",
"for",
"(",
"var",
"i",
"=",
"2",
";",
"i",
"<",
"tangents",
".",
"length",
";",
"i",
"++",
",",
"pi",
"++",
")",
"{",
"p",
"=",
"points",
"[",
"pi",
"]",
";",
"t",
"=",
"tangents",
"[",
"i",
"]",
";",
"let",
"lt",
"=",
"tangents",
"[",
"i",
"-",
"1",
"]",
";",
"let",
"lp",
"=",
"points",
"[",
"i",
"-",
"1",
"]",
";",
"commands",
".",
"push",
"(",
"[",
"lp",
"[",
"0",
"]",
"+",
"lt",
"[",
"0",
"]",
",",
"lp",
"[",
"1",
"]",
"+",
"lt",
"[",
"1",
"]",
",",
"p",
"[",
"0",
"]",
"-",
"t",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"-",
"t",
"[",
"1",
"]",
",",
"p",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"]",
")",
";",
"}",
"}",
"if",
"(",
"quad",
")",
"{",
"var",
"lp",
"=",
"points",
"[",
"pi",
"]",
";",
"commands",
".",
"push",
"(",
"[",
"p",
"[",
"0",
"]",
"+",
"t",
"[",
"0",
"]",
"*",
"2",
"/",
"3",
",",
"p",
"[",
"1",
"]",
"+",
"t",
"[",
"1",
"]",
"*",
"2",
"/",
"3",
",",
"lp",
"[",
"0",
"]",
",",
"lp",
"[",
"1",
"]",
"]",
")",
";",
"}",
"return",
"commands",
";",
"}"
] | Hermite spline construction; generates "C" commands. | [
"Hermite",
"spline",
"construction",
";",
"generates",
"C",
"commands",
"."
] | 7149b2a9ebddd5c512132a41f7ae7c3a2235ac0d | https://github.com/RavelLaw/e3/blob/7149b2a9ebddd5c512132a41f7ae7c3a2235ac0d/addon/utils/shadow/line-interpolation/monotone.js#L79-L144 | train |
Incroud/cassanova | lib/model.js | Model | function Model(name, table) {
this.model = this;
if(!name || typeof name !== "string"){
throw new Error("Attempting to instantiate a model without a valid name. Create models using the Cassanova.model API.");
}
if(!table){
throw new Error("Attempting to instantiate a model, " + name + ", without a valid table. Create models using the Cassanova.model API.");
}
this.name = name;
this.table = table;
} | javascript | function Model(name, table) {
this.model = this;
if(!name || typeof name !== "string"){
throw new Error("Attempting to instantiate a model without a valid name. Create models using the Cassanova.model API.");
}
if(!table){
throw new Error("Attempting to instantiate a model, " + name + ", without a valid table. Create models using the Cassanova.model API.");
}
this.name = name;
this.table = table;
} | [
"function",
"Model",
"(",
"name",
",",
"table",
")",
"{",
"this",
".",
"model",
"=",
"this",
";",
"if",
"(",
"!",
"name",
"||",
"typeof",
"name",
"!==",
"\"string\"",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Attempting to instantiate a model without a valid name. Create models using the Cassanova.model API.\"",
")",
";",
"}",
"if",
"(",
"!",
"table",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Attempting to instantiate a model, \"",
"+",
"name",
"+",
"\", without a valid table. Create models using the Cassanova.model API.\"",
")",
";",
"}",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"table",
"=",
"table",
";",
"}"
] | Cassanova.Model
@param {String} name The name of the model. Used to creation and retrieve.
@param {Table} table The table associated with the model. | [
"Cassanova",
".",
"Model"
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/model.js#L9-L22 | train |
hoodiehq/pouchdb-hoodie-sync | lib/off.js | off | function off (state, eventName, handler) {
if (arguments.length === 2) {
state.emitter.removeAllListeners(eventName)
} else {
state.emitter.removeListener(eventName, handler)
}
return state.api
} | javascript | function off (state, eventName, handler) {
if (arguments.length === 2) {
state.emitter.removeAllListeners(eventName)
} else {
state.emitter.removeListener(eventName, handler)
}
return state.api
} | [
"function",
"off",
"(",
"state",
",",
"eventName",
",",
"handler",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"state",
".",
"emitter",
".",
"removeAllListeners",
"(",
"eventName",
")",
"}",
"else",
"{",
"state",
".",
"emitter",
".",
"removeListener",
"(",
"eventName",
",",
"handler",
")",
"}",
"return",
"state",
".",
"api",
"}"
] | unbinds event from handler
@param {String} eventName push, pull, connect, disconnect
@param {Function} handler function unbound from event
@return {Promise} | [
"unbinds",
"event",
"from",
"handler"
] | c489baf813020c7f0cbd111224432cb6718c90de | https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/off.js#L10-L18 | train |
bem-contrib/md-to-bemjson | packages/md-to-bemjson/lib/augment.js | augmentFactory | function augmentFactory(options) {
/**
* Apply custom augmentation
*
* @param {Object} bemNode - representation of bem entity
* @returns {Object} bemNode
*/
function augment(bemNode) {
if (bemNode.block === 'md-root') {
bemNode.isRoot = true;
}
if (options.html) {
bemNode = augmentHtml(bemNode, options.html);
}
if (options.map) {
bemNode = augmentMap(bemNode, options.map);
}
if (options.prefix) {
bemNode = augmentPrefix(bemNode, options.prefix);
}
if (options.scope) {
bemNode = augmentScope(bemNode, options.scope);
}
if (bemNode.isRoot) delete bemNode.isRoot;
return bemNode;
}
return augment;
} | javascript | function augmentFactory(options) {
/**
* Apply custom augmentation
*
* @param {Object} bemNode - representation of bem entity
* @returns {Object} bemNode
*/
function augment(bemNode) {
if (bemNode.block === 'md-root') {
bemNode.isRoot = true;
}
if (options.html) {
bemNode = augmentHtml(bemNode, options.html);
}
if (options.map) {
bemNode = augmentMap(bemNode, options.map);
}
if (options.prefix) {
bemNode = augmentPrefix(bemNode, options.prefix);
}
if (options.scope) {
bemNode = augmentScope(bemNode, options.scope);
}
if (bemNode.isRoot) delete bemNode.isRoot;
return bemNode;
}
return augment;
} | [
"function",
"augmentFactory",
"(",
"options",
")",
"{",
"function",
"augment",
"(",
"bemNode",
")",
"{",
"if",
"(",
"bemNode",
".",
"block",
"===",
"'md-root'",
")",
"{",
"bemNode",
".",
"isRoot",
"=",
"true",
";",
"}",
"if",
"(",
"options",
".",
"html",
")",
"{",
"bemNode",
"=",
"augmentHtml",
"(",
"bemNode",
",",
"options",
".",
"html",
")",
";",
"}",
"if",
"(",
"options",
".",
"map",
")",
"{",
"bemNode",
"=",
"augmentMap",
"(",
"bemNode",
",",
"options",
".",
"map",
")",
";",
"}",
"if",
"(",
"options",
".",
"prefix",
")",
"{",
"bemNode",
"=",
"augmentPrefix",
"(",
"bemNode",
",",
"options",
".",
"prefix",
")",
";",
"}",
"if",
"(",
"options",
".",
"scope",
")",
"{",
"bemNode",
"=",
"augmentScope",
"(",
"bemNode",
",",
"options",
".",
"scope",
")",
";",
"}",
"if",
"(",
"bemNode",
".",
"isRoot",
")",
"delete",
"bemNode",
".",
"isRoot",
";",
"return",
"bemNode",
";",
"}",
"return",
"augment",
";",
"}"
] | create augment function with options
@param {MDConverter~AugmentOptions} options - augmentation options
@returns {Function} | [
"create",
"augment",
"function",
"with",
"options"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/md-to-bemjson/lib/augment.js#L13-L48 | train |
bem-contrib/md-to-bemjson | packages/md-to-bemjson/lib/augment.js | augmentScope | function augmentScope(bemNode, scope) {
assert(typeof scope === 'string', 'options.scope must be string');
if (bemNode.isRoot) {
bemNode.block = scope;
} else {
bemNode.elem = bemNode.block;
bemNode.elemMods = bemNode.mods;
delete bemNode.block;
delete bemNode.mods;
}
return bemNode;
} | javascript | function augmentScope(bemNode, scope) {
assert(typeof scope === 'string', 'options.scope must be string');
if (bemNode.isRoot) {
bemNode.block = scope;
} else {
bemNode.elem = bemNode.block;
bemNode.elemMods = bemNode.mods;
delete bemNode.block;
delete bemNode.mods;
}
return bemNode;
} | [
"function",
"augmentScope",
"(",
"bemNode",
",",
"scope",
")",
"{",
"assert",
"(",
"typeof",
"scope",
"===",
"'string'",
",",
"'options.scope must be string'",
")",
";",
"if",
"(",
"bemNode",
".",
"isRoot",
")",
"{",
"bemNode",
".",
"block",
"=",
"scope",
";",
"}",
"else",
"{",
"bemNode",
".",
"elem",
"=",
"bemNode",
".",
"block",
";",
"bemNode",
".",
"elemMods",
"=",
"bemNode",
".",
"mods",
";",
"delete",
"bemNode",
".",
"block",
";",
"delete",
"bemNode",
".",
"mods",
";",
"}",
"return",
"bemNode",
";",
"}"
] | Replace root with scope and blocks with elems.
@param {Object} bemNode - representation of bem entity
@param {string} scope - new root block name
@returns {Object} bemNode | [
"Replace",
"root",
"with",
"scope",
"and",
"blocks",
"with",
"elems",
"."
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/md-to-bemjson/lib/augment.js#L80-L95 | train |
bem-contrib/md-to-bemjson | packages/md-to-bemjson/lib/augment.js | augmentMap | function augmentMap(bemNode, map) {
const name = bemNode.block;
if (map[name]) {
assert(typeof map[name] === 'string', `options.map: new name of ${name} must be string`);
bemNode.block = map[name];
}
return bemNode;
} | javascript | function augmentMap(bemNode, map) {
const name = bemNode.block;
if (map[name]) {
assert(typeof map[name] === 'string', `options.map: new name of ${name} must be string`);
bemNode.block = map[name];
}
return bemNode;
} | [
"function",
"augmentMap",
"(",
"bemNode",
",",
"map",
")",
"{",
"const",
"name",
"=",
"bemNode",
".",
"block",
";",
"if",
"(",
"map",
"[",
"name",
"]",
")",
"{",
"assert",
"(",
"typeof",
"map",
"[",
"name",
"]",
"===",
"'string'",
",",
"`",
"${",
"name",
"}",
"`",
")",
";",
"bemNode",
".",
"block",
"=",
"map",
"[",
"name",
"]",
";",
"}",
"return",
"bemNode",
";",
"}"
] | Replace block names with new one
@param {Object} bemNode - representation of bem entity
@param {Object} map - key:blockName, value:newBlockName
@returns {Object} bemNode | [
"Replace",
"block",
"names",
"with",
"new",
"one"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/md-to-bemjson/lib/augment.js#L104-L113 | train |
tamaina/mfmf | dist/script/prelude/array.js | intersperse | function intersperse(sep, xs) {
return concat(xs.map(x => [sep, x])).slice(1);
} | javascript | function intersperse(sep, xs) {
return concat(xs.map(x => [sep, x])).slice(1);
} | [
"function",
"intersperse",
"(",
"sep",
",",
"xs",
")",
"{",
"return",
"concat",
"(",
"xs",
".",
"map",
"(",
"x",
"=>",
"[",
"sep",
",",
"x",
"]",
")",
")",
".",
"slice",
"(",
"1",
")",
";",
"}"
] | Intersperse the element between the elements of the array
@param sep The element to be interspersed | [
"Intersperse",
"the",
"element",
"between",
"the",
"elements",
"of",
"the",
"array"
] | 31208f7265a37438ee0e7527969db91ded001f7c | https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L28-L30 | train |
tamaina/mfmf | dist/script/prelude/array.js | groupBy | function groupBy(f, xs) {
const groups = [];
for (const x of xs) {
if (groups.length !== 0 && f(groups[groups.length - 1][0], x)) {
groups[groups.length - 1].push(x);
}
else {
groups.push([x]);
}
}
return groups;
} | javascript | function groupBy(f, xs) {
const groups = [];
for (const x of xs) {
if (groups.length !== 0 && f(groups[groups.length - 1][0], x)) {
groups[groups.length - 1].push(x);
}
else {
groups.push([x]);
}
}
return groups;
} | [
"function",
"groupBy",
"(",
"f",
",",
"xs",
")",
"{",
"const",
"groups",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"x",
"of",
"xs",
")",
"{",
"if",
"(",
"groups",
".",
"length",
"!==",
"0",
"&&",
"f",
"(",
"groups",
"[",
"groups",
".",
"length",
"-",
"1",
"]",
"[",
"0",
"]",
",",
"x",
")",
")",
"{",
"groups",
"[",
"groups",
".",
"length",
"-",
"1",
"]",
".",
"push",
"(",
"x",
")",
";",
"}",
"else",
"{",
"groups",
".",
"push",
"(",
"[",
"x",
"]",
")",
";",
"}",
"}",
"return",
"groups",
";",
"}"
] | Splits an array based on the equivalence relation.
The concatenation of the result is equal to the argument. | [
"Splits",
"an",
"array",
"based",
"on",
"the",
"equivalence",
"relation",
".",
"The",
"concatenation",
"of",
"the",
"result",
"is",
"equal",
"to",
"the",
"argument",
"."
] | 31208f7265a37438ee0e7527969db91ded001f7c | https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L66-L77 | train |
tamaina/mfmf | dist/script/prelude/array.js | groupOn | function groupOn(f, xs) {
return groupBy((a, b) => f(a) === f(b), xs);
} | javascript | function groupOn(f, xs) {
return groupBy((a, b) => f(a) === f(b), xs);
} | [
"function",
"groupOn",
"(",
"f",
",",
"xs",
")",
"{",
"return",
"groupBy",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"f",
"(",
"a",
")",
"===",
"f",
"(",
"b",
")",
",",
"xs",
")",
";",
"}"
] | Splits an array based on the equivalence relation induced by the function.
The concatenation of the result is equal to the argument. | [
"Splits",
"an",
"array",
"based",
"on",
"the",
"equivalence",
"relation",
"induced",
"by",
"the",
"function",
".",
"The",
"concatenation",
"of",
"the",
"result",
"is",
"equal",
"to",
"the",
"argument",
"."
] | 31208f7265a37438ee0e7527969db91ded001f7c | https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L83-L85 | train |
tamaina/mfmf | dist/script/prelude/array.js | lessThan | function lessThan(xs, ys) {
for (let i = 0; i < Math.min(xs.length, ys.length); i++) {
if (xs[i] < ys[i])
return true;
if (xs[i] > ys[i])
return false;
}
return xs.length < ys.length;
} | javascript | function lessThan(xs, ys) {
for (let i = 0; i < Math.min(xs.length, ys.length); i++) {
if (xs[i] < ys[i])
return true;
if (xs[i] > ys[i])
return false;
}
return xs.length < ys.length;
} | [
"function",
"lessThan",
"(",
"xs",
",",
"ys",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"Math",
".",
"min",
"(",
"xs",
".",
"length",
",",
"ys",
".",
"length",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"xs",
"[",
"i",
"]",
"<",
"ys",
"[",
"i",
"]",
")",
"return",
"true",
";",
"if",
"(",
"xs",
"[",
"i",
"]",
">",
"ys",
"[",
"i",
"]",
")",
"return",
"false",
";",
"}",
"return",
"xs",
".",
"length",
"<",
"ys",
".",
"length",
";",
"}"
] | Compare two arrays by lexicographical order | [
"Compare",
"two",
"arrays",
"by",
"lexicographical",
"order"
] | 31208f7265a37438ee0e7527969db91ded001f7c | https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L90-L98 | train |
tamaina/mfmf | dist/script/prelude/array.js | takeWhile | function takeWhile(f, xs) {
const ys = [];
for (const x of xs) {
if (f(x)) {
ys.push(x);
}
else {
break;
}
}
return ys;
} | javascript | function takeWhile(f, xs) {
const ys = [];
for (const x of xs) {
if (f(x)) {
ys.push(x);
}
else {
break;
}
}
return ys;
} | [
"function",
"takeWhile",
"(",
"f",
",",
"xs",
")",
"{",
"const",
"ys",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"x",
"of",
"xs",
")",
"{",
"if",
"(",
"f",
"(",
"x",
")",
")",
"{",
"ys",
".",
"push",
"(",
"x",
")",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"return",
"ys",
";",
"}"
] | Returns the longest prefix of elements that satisfy the predicate | [
"Returns",
"the",
"longest",
"prefix",
"of",
"elements",
"that",
"satisfy",
"the",
"predicate"
] | 31208f7265a37438ee0e7527969db91ded001f7c | https://github.com/tamaina/mfmf/blob/31208f7265a37438ee0e7527969db91ded001f7c/dist/script/prelude/array.js#L103-L114 | train |
fissionjs/fission | lib/renderables/collectionView.js | function(){
return {
collection: configCollection,
data: config.data,
query: config.query,
offset: config.offset,
limit: config.limit,
where: config.where,
filter: config.filter,
filters: config.filters,
watch: config.watch,
sort: config.sort
};
} | javascript | function(){
return {
collection: configCollection,
data: config.data,
query: config.query,
offset: config.offset,
limit: config.limit,
where: config.where,
filter: config.filter,
filters: config.filters,
watch: config.watch,
sort: config.sort
};
} | [
"function",
"(",
")",
"{",
"return",
"{",
"collection",
":",
"configCollection",
",",
"data",
":",
"config",
".",
"data",
",",
"query",
":",
"config",
".",
"query",
",",
"offset",
":",
"config",
".",
"offset",
",",
"limit",
":",
"config",
".",
"limit",
",",
"where",
":",
"config",
".",
"where",
",",
"filter",
":",
"config",
".",
"filter",
",",
"filters",
":",
"config",
".",
"filters",
",",
"watch",
":",
"config",
".",
"watch",
",",
"sort",
":",
"config",
".",
"sort",
"}",
";",
"}"
] | most options can be passed via config or props props takes precedence | [
"most",
"options",
"can",
"be",
"passed",
"via",
"config",
"or",
"props",
"props",
"takes",
"precedence"
] | e34eed78ed2386bb7934a69214e13f17fcd311c3 | https://github.com/fissionjs/fission/blob/e34eed78ed2386bb7934a69214e13f17fcd311c3/lib/renderables/collectionView.js#L53-L66 | train |
|
fissionjs/fission | lib/renderables/collectionView.js | function(props) {
if (typeof props !== 'object') {
throw new Error('_configureItems called with invalid props');
}
// not initialized yet
if (!this._items) {
return;
}
this._items.configure({
where: bindIfFn(props.where, this),
filter: bindIfFn(props.filter, this),
limit: bindIfFn(props.limit, this),
offset: bindIfFn(props.offset, this),
comparator: bindIfFn(props.sort, this)
}, true);
} | javascript | function(props) {
if (typeof props !== 'object') {
throw new Error('_configureItems called with invalid props');
}
// not initialized yet
if (!this._items) {
return;
}
this._items.configure({
where: bindIfFn(props.where, this),
filter: bindIfFn(props.filter, this),
limit: bindIfFn(props.limit, this),
offset: bindIfFn(props.offset, this),
comparator: bindIfFn(props.sort, this)
}, true);
} | [
"function",
"(",
"props",
")",
"{",
"if",
"(",
"typeof",
"props",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'_configureItems called with invalid props'",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"_items",
")",
"{",
"return",
";",
"}",
"this",
".",
"_items",
".",
"configure",
"(",
"{",
"where",
":",
"bindIfFn",
"(",
"props",
".",
"where",
",",
"this",
")",
",",
"filter",
":",
"bindIfFn",
"(",
"props",
".",
"filter",
",",
"this",
")",
",",
"limit",
":",
"bindIfFn",
"(",
"props",
".",
"limit",
",",
"this",
")",
",",
"offset",
":",
"bindIfFn",
"(",
"props",
".",
"offset",
",",
"this",
")",
",",
"comparator",
":",
"bindIfFn",
"(",
"props",
".",
"sort",
",",
"this",
")",
"}",
",",
"true",
")",
";",
"}"
] | internal fn to sync props to shadow collection | [
"internal",
"fn",
"to",
"sync",
"props",
"to",
"shadow",
"collection"
] | e34eed78ed2386bb7934a69214e13f17fcd311c3 | https://github.com/fissionjs/fission/blob/e34eed78ed2386bb7934a69214e13f17fcd311c3/lib/renderables/collectionView.js#L136-L151 | train |
|
cutting-room-floor/markers.js | dist/markers.js | reposition | function reposition(marker) {
// remember the tile coordinate so we don't have to reproject every time
if (!marker.coord) marker.coord = m.map.locationCoordinate(marker.location);
var pos = m.map.coordinatePoint(marker.coord);
var pos_loc, new_pos;
// If this point has wound around the world, adjust its position
// to the new, onscreen location
if (pos.x < 0) {
pos_loc = new MM.Location(marker.location.lat, marker.location.lon);
pos_loc.lon += Math.ceil((left.lon - marker.location.lon) / 360) * 360;
new_pos = m.map.locationPoint(pos_loc);
if (new_pos.x < m.map.dimensions.x) {
pos = new_pos;
marker.coord = m.map.locationCoordinate(pos_loc);
}
} else if (pos.x > m.map.dimensions.x) {
pos_loc = new MM.Location(marker.location.lat, marker.location.lon);
pos_loc.lon -= Math.ceil((marker.location.lon - right.lon) / 360) * 360;
new_pos = m.map.locationPoint(pos_loc);
if (new_pos.x > 0) {
pos = new_pos;
marker.coord = m.map.locationCoordinate(pos_loc);
}
}
pos.scale = 1;
pos.width = pos.height = 0;
MM.moveElement(marker.element, pos);
} | javascript | function reposition(marker) {
// remember the tile coordinate so we don't have to reproject every time
if (!marker.coord) marker.coord = m.map.locationCoordinate(marker.location);
var pos = m.map.coordinatePoint(marker.coord);
var pos_loc, new_pos;
// If this point has wound around the world, adjust its position
// to the new, onscreen location
if (pos.x < 0) {
pos_loc = new MM.Location(marker.location.lat, marker.location.lon);
pos_loc.lon += Math.ceil((left.lon - marker.location.lon) / 360) * 360;
new_pos = m.map.locationPoint(pos_loc);
if (new_pos.x < m.map.dimensions.x) {
pos = new_pos;
marker.coord = m.map.locationCoordinate(pos_loc);
}
} else if (pos.x > m.map.dimensions.x) {
pos_loc = new MM.Location(marker.location.lat, marker.location.lon);
pos_loc.lon -= Math.ceil((marker.location.lon - right.lon) / 360) * 360;
new_pos = m.map.locationPoint(pos_loc);
if (new_pos.x > 0) {
pos = new_pos;
marker.coord = m.map.locationCoordinate(pos_loc);
}
}
pos.scale = 1;
pos.width = pos.height = 0;
MM.moveElement(marker.element, pos);
} | [
"function",
"reposition",
"(",
"marker",
")",
"{",
"if",
"(",
"!",
"marker",
".",
"coord",
")",
"marker",
".",
"coord",
"=",
"m",
".",
"map",
".",
"locationCoordinate",
"(",
"marker",
".",
"location",
")",
";",
"var",
"pos",
"=",
"m",
".",
"map",
".",
"coordinatePoint",
"(",
"marker",
".",
"coord",
")",
";",
"var",
"pos_loc",
",",
"new_pos",
";",
"if",
"(",
"pos",
".",
"x",
"<",
"0",
")",
"{",
"pos_loc",
"=",
"new",
"MM",
".",
"Location",
"(",
"marker",
".",
"location",
".",
"lat",
",",
"marker",
".",
"location",
".",
"lon",
")",
";",
"pos_loc",
".",
"lon",
"+=",
"Math",
".",
"ceil",
"(",
"(",
"left",
".",
"lon",
"-",
"marker",
".",
"location",
".",
"lon",
")",
"/",
"360",
")",
"*",
"360",
";",
"new_pos",
"=",
"m",
".",
"map",
".",
"locationPoint",
"(",
"pos_loc",
")",
";",
"if",
"(",
"new_pos",
".",
"x",
"<",
"m",
".",
"map",
".",
"dimensions",
".",
"x",
")",
"{",
"pos",
"=",
"new_pos",
";",
"marker",
".",
"coord",
"=",
"m",
".",
"map",
".",
"locationCoordinate",
"(",
"pos_loc",
")",
";",
"}",
"}",
"else",
"if",
"(",
"pos",
".",
"x",
">",
"m",
".",
"map",
".",
"dimensions",
".",
"x",
")",
"{",
"pos_loc",
"=",
"new",
"MM",
".",
"Location",
"(",
"marker",
".",
"location",
".",
"lat",
",",
"marker",
".",
"location",
".",
"lon",
")",
";",
"pos_loc",
".",
"lon",
"-=",
"Math",
".",
"ceil",
"(",
"(",
"marker",
".",
"location",
".",
"lon",
"-",
"right",
".",
"lon",
")",
"/",
"360",
")",
"*",
"360",
";",
"new_pos",
"=",
"m",
".",
"map",
".",
"locationPoint",
"(",
"pos_loc",
")",
";",
"if",
"(",
"new_pos",
".",
"x",
">",
"0",
")",
"{",
"pos",
"=",
"new_pos",
";",
"marker",
".",
"coord",
"=",
"m",
".",
"map",
".",
"locationCoordinate",
"(",
"pos_loc",
")",
";",
"}",
"}",
"pos",
".",
"scale",
"=",
"1",
";",
"pos",
".",
"width",
"=",
"pos",
".",
"height",
"=",
"0",
";",
"MM",
".",
"moveElement",
"(",
"marker",
".",
"element",
",",
"pos",
")",
";",
"}"
] | reposition a single marker element | [
"reposition",
"a",
"single",
"marker",
"element"
] | 3feae089a43b4c10835bb0f147e8166333fc7b6a | https://github.com/cutting-room-floor/markers.js/blob/3feae089a43b4c10835bb0f147e8166333fc7b6a/dist/markers.js#L46-L75 | train |
cutting-room-floor/markers.js | dist/markers.js | stopPropagation | function stopPropagation(e) {
e.cancelBubble = true;
if (e.stopPropagation) { e.stopPropagation(); }
return false;
} | javascript | function stopPropagation(e) {
e.cancelBubble = true;
if (e.stopPropagation) { e.stopPropagation(); }
return false;
} | [
"function",
"stopPropagation",
"(",
"e",
")",
"{",
"e",
".",
"cancelBubble",
"=",
"true",
";",
"if",
"(",
"e",
".",
"stopPropagation",
")",
"{",
"e",
".",
"stopPropagation",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Block mouse and touch events | [
"Block",
"mouse",
"and",
"touch",
"events"
] | 3feae089a43b4c10835bb0f147e8166333fc7b6a | https://github.com/cutting-room-floor/markers.js/blob/3feae089a43b4c10835bb0f147e8166333fc7b6a/dist/markers.js#L430-L434 | train |
cutting-room-floor/markers.js | dist/markers.js | csv_parse | function csv_parse(text) {
var header;
return csv_parseRows(text, function(row, i) {
if (i) {
var o = {}, j = -1, m = header.length;
while (++j < m) o[header[j]] = row[j];
return o;
} else {
header = row;
return null;
}
});
} | javascript | function csv_parse(text) {
var header;
return csv_parseRows(text, function(row, i) {
if (i) {
var o = {}, j = -1, m = header.length;
while (++j < m) o[header[j]] = row[j];
return o;
} else {
header = row;
return null;
}
});
} | [
"function",
"csv_parse",
"(",
"text",
")",
"{",
"var",
"header",
";",
"return",
"csv_parseRows",
"(",
"text",
",",
"function",
"(",
"row",
",",
"i",
")",
"{",
"if",
"(",
"i",
")",
"{",
"var",
"o",
"=",
"{",
"}",
",",
"j",
"=",
"-",
"1",
",",
"m",
"=",
"header",
".",
"length",
";",
"while",
"(",
"++",
"j",
"<",
"m",
")",
"o",
"[",
"header",
"[",
"j",
"]",
"]",
"=",
"row",
"[",
"j",
"]",
";",
"return",
"o",
";",
"}",
"else",
"{",
"header",
"=",
"row",
";",
"return",
"null",
";",
"}",
"}",
")",
";",
"}"
] | Extracted from d3 | [
"Extracted",
"from",
"d3"
] | 3feae089a43b4c10835bb0f147e8166333fc7b6a | https://github.com/cutting-room-floor/markers.js/blob/3feae089a43b4c10835bb0f147e8166333fc7b6a/dist/markers.js#L506-L518 | train |
Icinetic/baucis-swagger2 | Controller.js | swagger20TypeFor | function swagger20TypeFor(type) {
if (!type) { return null; }
if (type === Number) { return 'number'; }
if (type === Boolean) { return 'boolean'; }
if (type === String ||
type === Date ||
type === mongoose.Schema.Types.ObjectId ||
type === mongoose.Schema.Types.Oid) {
return 'string';
}
if (type === mongoose.Schema.Types.Array ||
Array.isArray(type) ||
type.name === "Array") {
return 'array';
}
if (type === Object ||
type instanceof Object ||
type === mongoose.Schema.Types.Mixed ||
type === mongoose.Schema.Types.Buffer) {
return null;
}
throw new Error('Unrecognized type: ' + type);
} | javascript | function swagger20TypeFor(type) {
if (!type) { return null; }
if (type === Number) { return 'number'; }
if (type === Boolean) { return 'boolean'; }
if (type === String ||
type === Date ||
type === mongoose.Schema.Types.ObjectId ||
type === mongoose.Schema.Types.Oid) {
return 'string';
}
if (type === mongoose.Schema.Types.Array ||
Array.isArray(type) ||
type.name === "Array") {
return 'array';
}
if (type === Object ||
type instanceof Object ||
type === mongoose.Schema.Types.Mixed ||
type === mongoose.Schema.Types.Buffer) {
return null;
}
throw new Error('Unrecognized type: ' + type);
} | [
"function",
"swagger20TypeFor",
"(",
"type",
")",
"{",
"if",
"(",
"!",
"type",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"type",
"===",
"Number",
")",
"{",
"return",
"'number'",
";",
"}",
"if",
"(",
"type",
"===",
"Boolean",
")",
"{",
"return",
"'boolean'",
";",
"}",
"if",
"(",
"type",
"===",
"String",
"||",
"type",
"===",
"Date",
"||",
"type",
"===",
"mongoose",
".",
"Schema",
".",
"Types",
".",
"ObjectId",
"||",
"type",
"===",
"mongoose",
".",
"Schema",
".",
"Types",
".",
"Oid",
")",
"{",
"return",
"'string'",
";",
"}",
"if",
"(",
"type",
"===",
"mongoose",
".",
"Schema",
".",
"Types",
".",
"Array",
"||",
"Array",
".",
"isArray",
"(",
"type",
")",
"||",
"type",
".",
"name",
"===",
"\"Array\"",
")",
"{",
"return",
"'array'",
";",
"}",
"if",
"(",
"type",
"===",
"Object",
"||",
"type",
"instanceof",
"Object",
"||",
"type",
"===",
"mongoose",
".",
"Schema",
".",
"Types",
".",
"Mixed",
"||",
"type",
"===",
"mongoose",
".",
"Schema",
".",
"Types",
".",
"Buffer",
")",
"{",
"return",
"null",
";",
"}",
"throw",
"new",
"Error",
"(",
"'Unrecognized type: '",
"+",
"type",
")",
";",
"}"
] | Convert a Mongoose type into a Swagger type | [
"Convert",
"a",
"Mongoose",
"type",
"into",
"a",
"Swagger",
"type"
] | 502200ae8ac131849fe20d95636bf3170561e81e | https://github.com/Icinetic/baucis-swagger2/blob/502200ae8ac131849fe20d95636bf3170561e81e/Controller.js#L161-L183 | train |
Icinetic/baucis-swagger2 | Controller.js | generatePropertyDefinition | function generatePropertyDefinition(name, path, definitionName) {
var property = {};
var type = path.options.type ? swagger20TypeFor(path.options.type) : 'string'; // virtuals don't have type
if (skipProperty(name, path, controller)) {
return;
}
// Configure the property
if (path.options.type === mongoose.Schema.Types.ObjectId) {
if ("_id" === name) {
property.type = 'string';
}
else if (path.options.ref) {
property.$ref = '#/definitions/' + utils.capitalize(path.options.ref);
}
}
else if (path.schema) {
//Choice (1. embed schema here or 2. reference and publish as a root definition)
property.type = 'array';
property.items = {
//2. reference
$ref: '#/definitions/'+ definitionName + utils.capitalize(name)
};
}
else {
property.type = type;
if ('array' === type) {
if (isArrayOfRefs(path.options.type)) {
property.items = {
type: 'string' //handle references as string (serialization for objectId)
};
}
else {
var resolvedType = referenceForType(path.options.type);
if (resolvedType.isPrimitive) {
property.items = {
type: resolvedType.type
};
}
else {
property.items = {
$ref: resolvedType.type
};
}
}
}
var format = swagger20TypeFormatFor(path.options.type);
if (format) {
property.format = format;
}
if ('__v' === name) {
property.format = 'int32';
}
}
/*
// Set enum values if applicable
if (path.enumValues && path.enumValues.length > 0) {
// Pending: property.allowableValues = { valueType: 'LIST', values: path.enumValues };
}
// Set allowable values range if min or max is present
if (!isNaN(path.options.min) || !isNaN(path.options.max)) {
// Pending: property.allowableValues = { valueType: 'RANGE' };
}
if (!isNaN(path.options.min)) {
// Pending: property.allowableValues.min = path.options.min;
}
if (!isNaN(path.options.max)) {
// Pending: property.allowableValues.max = path.options.max;
}
*/
if (!property.type && !property.$ref) {
warnInvalidType(name, path);
property.type = 'string';
}
return property;
} | javascript | function generatePropertyDefinition(name, path, definitionName) {
var property = {};
var type = path.options.type ? swagger20TypeFor(path.options.type) : 'string'; // virtuals don't have type
if (skipProperty(name, path, controller)) {
return;
}
// Configure the property
if (path.options.type === mongoose.Schema.Types.ObjectId) {
if ("_id" === name) {
property.type = 'string';
}
else if (path.options.ref) {
property.$ref = '#/definitions/' + utils.capitalize(path.options.ref);
}
}
else if (path.schema) {
//Choice (1. embed schema here or 2. reference and publish as a root definition)
property.type = 'array';
property.items = {
//2. reference
$ref: '#/definitions/'+ definitionName + utils.capitalize(name)
};
}
else {
property.type = type;
if ('array' === type) {
if (isArrayOfRefs(path.options.type)) {
property.items = {
type: 'string' //handle references as string (serialization for objectId)
};
}
else {
var resolvedType = referenceForType(path.options.type);
if (resolvedType.isPrimitive) {
property.items = {
type: resolvedType.type
};
}
else {
property.items = {
$ref: resolvedType.type
};
}
}
}
var format = swagger20TypeFormatFor(path.options.type);
if (format) {
property.format = format;
}
if ('__v' === name) {
property.format = 'int32';
}
}
/*
// Set enum values if applicable
if (path.enumValues && path.enumValues.length > 0) {
// Pending: property.allowableValues = { valueType: 'LIST', values: path.enumValues };
}
// Set allowable values range if min or max is present
if (!isNaN(path.options.min) || !isNaN(path.options.max)) {
// Pending: property.allowableValues = { valueType: 'RANGE' };
}
if (!isNaN(path.options.min)) {
// Pending: property.allowableValues.min = path.options.min;
}
if (!isNaN(path.options.max)) {
// Pending: property.allowableValues.max = path.options.max;
}
*/
if (!property.type && !property.$ref) {
warnInvalidType(name, path);
property.type = 'string';
}
return property;
} | [
"function",
"generatePropertyDefinition",
"(",
"name",
",",
"path",
",",
"definitionName",
")",
"{",
"var",
"property",
"=",
"{",
"}",
";",
"var",
"type",
"=",
"path",
".",
"options",
".",
"type",
"?",
"swagger20TypeFor",
"(",
"path",
".",
"options",
".",
"type",
")",
":",
"'string'",
";",
"if",
"(",
"skipProperty",
"(",
"name",
",",
"path",
",",
"controller",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"path",
".",
"options",
".",
"type",
"===",
"mongoose",
".",
"Schema",
".",
"Types",
".",
"ObjectId",
")",
"{",
"if",
"(",
"\"_id\"",
"===",
"name",
")",
"{",
"property",
".",
"type",
"=",
"'string'",
";",
"}",
"else",
"if",
"(",
"path",
".",
"options",
".",
"ref",
")",
"{",
"property",
".",
"$ref",
"=",
"'#/definitions/'",
"+",
"utils",
".",
"capitalize",
"(",
"path",
".",
"options",
".",
"ref",
")",
";",
"}",
"}",
"else",
"if",
"(",
"path",
".",
"schema",
")",
"{",
"property",
".",
"type",
"=",
"'array'",
";",
"property",
".",
"items",
"=",
"{",
"$ref",
":",
"'#/definitions/'",
"+",
"definitionName",
"+",
"utils",
".",
"capitalize",
"(",
"name",
")",
"}",
";",
"}",
"else",
"{",
"property",
".",
"type",
"=",
"type",
";",
"if",
"(",
"'array'",
"===",
"type",
")",
"{",
"if",
"(",
"isArrayOfRefs",
"(",
"path",
".",
"options",
".",
"type",
")",
")",
"{",
"property",
".",
"items",
"=",
"{",
"type",
":",
"'string'",
"}",
";",
"}",
"else",
"{",
"var",
"resolvedType",
"=",
"referenceForType",
"(",
"path",
".",
"options",
".",
"type",
")",
";",
"if",
"(",
"resolvedType",
".",
"isPrimitive",
")",
"{",
"property",
".",
"items",
"=",
"{",
"type",
":",
"resolvedType",
".",
"type",
"}",
";",
"}",
"else",
"{",
"property",
".",
"items",
"=",
"{",
"$ref",
":",
"resolvedType",
".",
"type",
"}",
";",
"}",
"}",
"}",
"var",
"format",
"=",
"swagger20TypeFormatFor",
"(",
"path",
".",
"options",
".",
"type",
")",
";",
"if",
"(",
"format",
")",
"{",
"property",
".",
"format",
"=",
"format",
";",
"}",
"if",
"(",
"'__v'",
"===",
"name",
")",
"{",
"property",
".",
"format",
"=",
"'int32'",
";",
"}",
"}",
"if",
"(",
"!",
"property",
".",
"type",
"&&",
"!",
"property",
".",
"$ref",
")",
"{",
"warnInvalidType",
"(",
"name",
",",
"path",
")",
";",
"property",
".",
"type",
"=",
"'string'",
";",
"}",
"return",
"property",
";",
"}"
] | A method used to generated a Swagger property for a model | [
"A",
"method",
"used",
"to",
"generated",
"a",
"Swagger",
"property",
"for",
"a",
"model"
] | 502200ae8ac131849fe20d95636bf3170561e81e | https://github.com/Icinetic/baucis-swagger2/blob/502200ae8ac131849fe20d95636bf3170561e81e/Controller.js#L225-L301 | train |
Incroud/cassanova | lib/query.js | processPartitionKeys | function processPartitionKeys(keys){
var result = "(",
j,
len,
keyGroup;
if(typeof keys === 'string'){
return result += keys + ")";
}
len = keys.length;
for(j = 0; j< keys.length; j++){
keyGroup = keys[j];
if(keyGroup instanceof Array){
result += "(";
result += keyGroup.join(", ");
result += ")";
}else{
result += keyGroup;
}
result += (j < len-1) ? ", " : "";
}
result += ")";
return result;
} | javascript | function processPartitionKeys(keys){
var result = "(",
j,
len,
keyGroup;
if(typeof keys === 'string'){
return result += keys + ")";
}
len = keys.length;
for(j = 0; j< keys.length; j++){
keyGroup = keys[j];
if(keyGroup instanceof Array){
result += "(";
result += keyGroup.join(", ");
result += ")";
}else{
result += keyGroup;
}
result += (j < len-1) ? ", " : "";
}
result += ")";
return result;
} | [
"function",
"processPartitionKeys",
"(",
"keys",
")",
"{",
"var",
"result",
"=",
"\"(\"",
",",
"j",
",",
"len",
",",
"keyGroup",
";",
"if",
"(",
"typeof",
"keys",
"===",
"'string'",
")",
"{",
"return",
"result",
"+=",
"keys",
"+",
"\")\"",
";",
"}",
"len",
"=",
"keys",
".",
"length",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"keys",
".",
"length",
";",
"j",
"++",
")",
"{",
"keyGroup",
"=",
"keys",
"[",
"j",
"]",
";",
"if",
"(",
"keyGroup",
"instanceof",
"Array",
")",
"{",
"result",
"+=",
"\"(\"",
";",
"result",
"+=",
"keyGroup",
".",
"join",
"(",
"\", \"",
")",
";",
"result",
"+=",
"\")\"",
";",
"}",
"else",
"{",
"result",
"+=",
"keyGroup",
";",
"}",
"result",
"+=",
"(",
"j",
"<",
"len",
"-",
"1",
")",
"?",
"\", \"",
":",
"\"\"",
";",
"}",
"result",
"+=",
"\")\"",
";",
"return",
"result",
";",
"}"
] | An internal method, it processes primary partition keys into a CQL statement.
@param {Object} keys A string, Array or multi-dimensional Array
@return {String} A CQL formatted string of the partition key | [
"An",
"internal",
"method",
"it",
"processes",
"primary",
"partition",
"keys",
"into",
"a",
"CQL",
"statement",
"."
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/query.js#L22-L47 | train |
Incroud/cassanova | lib/query.js | function(collection, blacklist){
var obj,
result = [],
prop,
i,
j,
collLen,
listLen;
blacklist = blacklist || ["__columns"];
if(!collection || !collection.length){
return result;
}
collLen = collection.length;
for(i=0; i<collLen; i++){
obj = collection[i];
//delete null properties
for(prop in obj){
if(obj[prop] === null){
delete obj[prop];
}
}
listLen = blacklist.length;
for(j=0; j<listLen; j++){
delete obj[blacklist[j]];
}
//These are javascript objects and not json, so we have to do this magic to strip it of get methods.
result.push(JSON.parse(JSON.stringify(obj)));
}
return result;
} | javascript | function(collection, blacklist){
var obj,
result = [],
prop,
i,
j,
collLen,
listLen;
blacklist = blacklist || ["__columns"];
if(!collection || !collection.length){
return result;
}
collLen = collection.length;
for(i=0; i<collLen; i++){
obj = collection[i];
//delete null properties
for(prop in obj){
if(obj[prop] === null){
delete obj[prop];
}
}
listLen = blacklist.length;
for(j=0; j<listLen; j++){
delete obj[blacklist[j]];
}
//These are javascript objects and not json, so we have to do this magic to strip it of get methods.
result.push(JSON.parse(JSON.stringify(obj)));
}
return result;
} | [
"function",
"(",
"collection",
",",
"blacklist",
")",
"{",
"var",
"obj",
",",
"result",
"=",
"[",
"]",
",",
"prop",
",",
"i",
",",
"j",
",",
"collLen",
",",
"listLen",
";",
"blacklist",
"=",
"blacklist",
"||",
"[",
"\"__columns\"",
"]",
";",
"if",
"(",
"!",
"collection",
"||",
"!",
"collection",
".",
"length",
")",
"{",
"return",
"result",
";",
"}",
"collLen",
"=",
"collection",
".",
"length",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"collLen",
";",
"i",
"++",
")",
"{",
"obj",
"=",
"collection",
"[",
"i",
"]",
";",
"for",
"(",
"prop",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
"[",
"prop",
"]",
"===",
"null",
")",
"{",
"delete",
"obj",
"[",
"prop",
"]",
";",
"}",
"}",
"listLen",
"=",
"blacklist",
".",
"length",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"listLen",
";",
"j",
"++",
")",
"{",
"delete",
"obj",
"[",
"blacklist",
"[",
"j",
"]",
"]",
";",
"}",
"result",
".",
"push",
"(",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"obj",
")",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Removes black-listed properties from the data | [
"Removes",
"black",
"-",
"listed",
"properties",
"from",
"the",
"data"
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/query.js#L664-L700 | train |
|
hoodiehq/pouchdb-hoodie-sync | lib/one.js | one | function one (state, eventName, handler) {
state.emitter.once(eventName, handler)
return state.api
} | javascript | function one (state, eventName, handler) {
state.emitter.once(eventName, handler)
return state.api
} | [
"function",
"one",
"(",
"state",
",",
"eventName",
",",
"handler",
")",
"{",
"state",
".",
"emitter",
".",
"once",
"(",
"eventName",
",",
"handler",
")",
"return",
"state",
".",
"api",
"}"
] | binds event only once to handler
@param {String} eventName push, pull, connect, disconnect
@param {Function} handler function once bound to event
@return {Promise} | [
"binds",
"event",
"only",
"once",
"to",
"handler"
] | c489baf813020c7f0cbd111224432cb6718c90de | https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/one.js#L10-L14 | train |
jugglingdb/connect-jugglingdb | index.js | JugglingStore | function JugglingStore(schema, options) {
options = options || {};
Store.call(this, options);
this.maxAge = options.maxAge || defaults.maxAge;
var coll = this.collection = schema.define('Session', {
sid: {
type: String,
index: true
},
expires: {
type: Date,
index: true
},
session: schema.constructor.JSON
}, {
table: options.table || defaults.table
});
coll.validatesUniquenessOf('sid');
// destroy all expired sessions after each create/update
coll.afterSave = function(next) {
coll.iterate({where: {
expires: {lte: new Date()}
}}, function(obj, nexti, i) {
obj.destroy(nexti);
}, next);
};
} | javascript | function JugglingStore(schema, options) {
options = options || {};
Store.call(this, options);
this.maxAge = options.maxAge || defaults.maxAge;
var coll = this.collection = schema.define('Session', {
sid: {
type: String,
index: true
},
expires: {
type: Date,
index: true
},
session: schema.constructor.JSON
}, {
table: options.table || defaults.table
});
coll.validatesUniquenessOf('sid');
// destroy all expired sessions after each create/update
coll.afterSave = function(next) {
coll.iterate({where: {
expires: {lte: new Date()}
}}, function(obj, nexti, i) {
obj.destroy(nexti);
}, next);
};
} | [
"function",
"JugglingStore",
"(",
"schema",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"Store",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"maxAge",
"=",
"options",
".",
"maxAge",
"||",
"defaults",
".",
"maxAge",
";",
"var",
"coll",
"=",
"this",
".",
"collection",
"=",
"schema",
".",
"define",
"(",
"'Session'",
",",
"{",
"sid",
":",
"{",
"type",
":",
"String",
",",
"index",
":",
"true",
"}",
",",
"expires",
":",
"{",
"type",
":",
"Date",
",",
"index",
":",
"true",
"}",
",",
"session",
":",
"schema",
".",
"constructor",
".",
"JSON",
"}",
",",
"{",
"table",
":",
"options",
".",
"table",
"||",
"defaults",
".",
"table",
"}",
")",
";",
"coll",
".",
"validatesUniquenessOf",
"(",
"'sid'",
")",
";",
"coll",
".",
"afterSave",
"=",
"function",
"(",
"next",
")",
"{",
"coll",
".",
"iterate",
"(",
"{",
"where",
":",
"{",
"expires",
":",
"{",
"lte",
":",
"new",
"Date",
"(",
")",
"}",
"}",
"}",
",",
"function",
"(",
"obj",
",",
"nexti",
",",
"i",
")",
"{",
"obj",
".",
"destroy",
"(",
"nexti",
")",
";",
"}",
",",
"next",
")",
";",
"}",
";",
"}"
] | Initialize JugglingStore with the given `options`.
@param {JugglingDB.Schema} schema
@param {Object} options
@api public | [
"Initialize",
"JugglingStore",
"with",
"the",
"given",
"options",
"."
] | b088660f6d69bd52dfd79c8523034cd0d2673694 | https://github.com/jugglingdb/connect-jugglingdb/blob/b088660f6d69bd52dfd79c8523034cd0d2673694/index.js#L30-L58 | train |
rangle/koast | lib/app/app-maker.js | validateRouteDefinition | function validateRouteDefinition(routeDef) {
var expectedKeys = ['route', 'type', 'module', 'path'];
var expectedTypes = ['static', 'module'];
var expectedTypeMap = {
'static': 'path',
'module': 'module'
};
var keys = Object.keys(routeDef);
var EXPECTED_NUMBER_OF_PROPERTIES = 3;
//Handle warnings first;
if (routeDef.route && routeDef.route.substr(0, 1) !== '/') {
log.warn('Route path does not start with a slash:', routeDef.route);
}
if(keys.length !== EXPECTED_NUMBER_OF_PROPERTIES) {
throw new Error('Route definition does not contain all required properties');
}
_.map(keys, function compareAgainstExpected(key) {
if (expectedKeys.indexOf(key) === -1) {
throw new Error('Unexpected property found in route definition. Please check the spelling');
}
});
if (expectedTypes.indexOf(routeDef.type) === -1) {
throw new Error('Unknown type of route. Please check your configuration');
}
if (keys.indexOf(expectedTypeMap[routeDef.type]) === -1) {
throw new Error('Route type ' + routeDef.type + ' requires ' + expectedTypeMap[routeDef.type] + ' to be defined');
}
return true;
} | javascript | function validateRouteDefinition(routeDef) {
var expectedKeys = ['route', 'type', 'module', 'path'];
var expectedTypes = ['static', 'module'];
var expectedTypeMap = {
'static': 'path',
'module': 'module'
};
var keys = Object.keys(routeDef);
var EXPECTED_NUMBER_OF_PROPERTIES = 3;
//Handle warnings first;
if (routeDef.route && routeDef.route.substr(0, 1) !== '/') {
log.warn('Route path does not start with a slash:', routeDef.route);
}
if(keys.length !== EXPECTED_NUMBER_OF_PROPERTIES) {
throw new Error('Route definition does not contain all required properties');
}
_.map(keys, function compareAgainstExpected(key) {
if (expectedKeys.indexOf(key) === -1) {
throw new Error('Unexpected property found in route definition. Please check the spelling');
}
});
if (expectedTypes.indexOf(routeDef.type) === -1) {
throw new Error('Unknown type of route. Please check your configuration');
}
if (keys.indexOf(expectedTypeMap[routeDef.type]) === -1) {
throw new Error('Route type ' + routeDef.type + ' requires ' + expectedTypeMap[routeDef.type] + ' to be defined');
}
return true;
} | [
"function",
"validateRouteDefinition",
"(",
"routeDef",
")",
"{",
"var",
"expectedKeys",
"=",
"[",
"'route'",
",",
"'type'",
",",
"'module'",
",",
"'path'",
"]",
";",
"var",
"expectedTypes",
"=",
"[",
"'static'",
",",
"'module'",
"]",
";",
"var",
"expectedTypeMap",
"=",
"{",
"'static'",
":",
"'path'",
",",
"'module'",
":",
"'module'",
"}",
";",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"routeDef",
")",
";",
"var",
"EXPECTED_NUMBER_OF_PROPERTIES",
"=",
"3",
";",
"if",
"(",
"routeDef",
".",
"route",
"&&",
"routeDef",
".",
"route",
".",
"substr",
"(",
"0",
",",
"1",
")",
"!==",
"'/'",
")",
"{",
"log",
".",
"warn",
"(",
"'Route path does not start with a slash:'",
",",
"routeDef",
".",
"route",
")",
";",
"}",
"if",
"(",
"keys",
".",
"length",
"!==",
"EXPECTED_NUMBER_OF_PROPERTIES",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Route definition does not contain all required properties'",
")",
";",
"}",
"_",
".",
"map",
"(",
"keys",
",",
"function",
"compareAgainstExpected",
"(",
"key",
")",
"{",
"if",
"(",
"expectedKeys",
".",
"indexOf",
"(",
"key",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unexpected property found in route definition. Please check the spelling'",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"expectedTypes",
".",
"indexOf",
"(",
"routeDef",
".",
"type",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown type of route. Please check your configuration'",
")",
";",
"}",
"if",
"(",
"keys",
".",
"indexOf",
"(",
"expectedTypeMap",
"[",
"routeDef",
".",
"type",
"]",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Route type '",
"+",
"routeDef",
".",
"type",
"+",
"' requires '",
"+",
"expectedTypeMap",
"[",
"routeDef",
".",
"type",
"]",
"+",
"' to be defined'",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Validate the incoming route configurations are valie.
@param routeDef
@example
{
'route': '/alwaysStartWithSlash',
'type': 'static' || 'module',
'module' || 'path': 'filePath'
}
@return true if valid otherwise throw an error. | [
"Validate",
"the",
"incoming",
"route",
"configurations",
"are",
"valie",
"."
] | 446dfaba7f80c03ae17d86b34dfafd6328be1ba6 | https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/app/app-maker.js#L73-L107 | train |
entrinsik-org/utils | lib/constant-aggregate-expression.js | ConstantAggregateExpression | function ConstantAggregateExpression(number) {
if(!Number.isFinite(number))
this.number = parseFloat(number);
else
this.number = number;
} | javascript | function ConstantAggregateExpression(number) {
if(!Number.isFinite(number))
this.number = parseFloat(number);
else
this.number = number;
} | [
"function",
"ConstantAggregateExpression",
"(",
"number",
")",
"{",
"if",
"(",
"!",
"Number",
".",
"isFinite",
"(",
"number",
")",
")",
"this",
".",
"number",
"=",
"parseFloat",
"(",
"number",
")",
";",
"else",
"this",
".",
"number",
"=",
"number",
";",
"}"
] | Represent a constant number for use an an argument to a aggregation calculation
@param number {number}
@constructor | [
"Represent",
"a",
"constant",
"number",
"for",
"use",
"an",
"an",
"argument",
"to",
"a",
"aggregation",
"calculation"
] | da2bff77afd0c3316148d7b79b2416d021a9b53a | https://github.com/entrinsik-org/utils/blob/da2bff77afd0c3316148d7b79b2416d021a9b53a/lib/constant-aggregate-expression.js#L11-L16 | train |
gbv/jskos-tools | lib/identifiers.js | reduceSet | function reduceSet(set) {
return set.map(member => member && member.uri).filter(Boolean)
} | javascript | function reduceSet(set) {
return set.map(member => member && member.uri).filter(Boolean)
} | [
"function",
"reduceSet",
"(",
"set",
")",
"{",
"return",
"set",
".",
"map",
"(",
"member",
"=>",
"member",
"&&",
"member",
".",
"uri",
")",
".",
"filter",
"(",
"Boolean",
")",
"}"
] | Reduce JSKOS set to members with URI. | [
"Reduce",
"JSKOS",
"set",
"to",
"members",
"with",
"URI",
"."
] | da8672203362ea874f4ab9cdd34b990369987075 | https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/identifiers.js#L10-L12 | train |
gbv/jskos-tools | lib/identifiers.js | mappingContent | function mappingContent(mapping) {
const { from, to, type } = mapping
let result = {
from: reduceBundle(from || {}),
to: reduceBundle(to || {}),
type: [
type && type[0] || "http://www.w3.org/2004/02/skos/core#mappingRelation"
]
}
for (let side of ["from", "to"]) {
if ((result[side][memberField(result[side])] || []).length == 0) {
let scheme = mapping[side + "Scheme"]
if (scheme && scheme.uri) {
// Create new object to remove all unnecessary properties.
result[side + "Scheme"] = { uri: scheme.uri }
}
}
}
return result
} | javascript | function mappingContent(mapping) {
const { from, to, type } = mapping
let result = {
from: reduceBundle(from || {}),
to: reduceBundle(to || {}),
type: [
type && type[0] || "http://www.w3.org/2004/02/skos/core#mappingRelation"
]
}
for (let side of ["from", "to"]) {
if ((result[side][memberField(result[side])] || []).length == 0) {
let scheme = mapping[side + "Scheme"]
if (scheme && scheme.uri) {
// Create new object to remove all unnecessary properties.
result[side + "Scheme"] = { uri: scheme.uri }
}
}
}
return result
} | [
"function",
"mappingContent",
"(",
"mapping",
")",
"{",
"const",
"{",
"from",
",",
"to",
",",
"type",
"}",
"=",
"mapping",
"let",
"result",
"=",
"{",
"from",
":",
"reduceBundle",
"(",
"from",
"||",
"{",
"}",
")",
",",
"to",
":",
"reduceBundle",
"(",
"to",
"||",
"{",
"}",
")",
",",
"type",
":",
"[",
"type",
"&&",
"type",
"[",
"0",
"]",
"||",
"\"http://www.w3.org/2004/02/skos/core#mappingRelation\"",
"]",
"}",
"for",
"(",
"let",
"side",
"of",
"[",
"\"from\"",
",",
"\"to\"",
"]",
")",
"{",
"if",
"(",
"(",
"result",
"[",
"side",
"]",
"[",
"memberField",
"(",
"result",
"[",
"side",
"]",
")",
"]",
"||",
"[",
"]",
")",
".",
"length",
"==",
"0",
")",
"{",
"let",
"scheme",
"=",
"mapping",
"[",
"side",
"+",
"\"Scheme\"",
"]",
"if",
"(",
"scheme",
"&&",
"scheme",
".",
"uri",
")",
"{",
"result",
"[",
"side",
"+",
"\"Scheme\"",
"]",
"=",
"{",
"uri",
":",
"scheme",
".",
"uri",
"}",
"}",
"}",
"}",
"return",
"result",
"}"
] | Reduce mapping to reduced fields from, to, and type. | [
"Reduce",
"mapping",
"to",
"reduced",
"fields",
"from",
"to",
"and",
"type",
"."
] | da8672203362ea874f4ab9cdd34b990369987075 | https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/identifiers.js#L29-L48 | train |
gbv/jskos-tools | lib/identifiers.js | mappingMembers | function mappingMembers(mapping) {
const { from, to } = mapping
const memberUris = [ from, to ].filter(Boolean)
.map(bundle => reduceSet(bundle[memberField(bundle)] || []))
return [].concat(...memberUris).sort()
} | javascript | function mappingMembers(mapping) {
const { from, to } = mapping
const memberUris = [ from, to ].filter(Boolean)
.map(bundle => reduceSet(bundle[memberField(bundle)] || []))
return [].concat(...memberUris).sort()
} | [
"function",
"mappingMembers",
"(",
"mapping",
")",
"{",
"const",
"{",
"from",
",",
"to",
"}",
"=",
"mapping",
"const",
"memberUris",
"=",
"[",
"from",
",",
"to",
"]",
".",
"filter",
"(",
"Boolean",
")",
".",
"map",
"(",
"bundle",
"=>",
"reduceSet",
"(",
"bundle",
"[",
"memberField",
"(",
"bundle",
")",
"]",
"||",
"[",
"]",
")",
")",
"return",
"[",
"]",
".",
"concat",
"(",
"...",
"memberUris",
")",
".",
"sort",
"(",
")",
"}"
] | Get a sorted list of member URIs. | [
"Get",
"a",
"sorted",
"list",
"of",
"member",
"URIs",
"."
] | da8672203362ea874f4ab9cdd34b990369987075 | https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/identifiers.js#L51-L56 | train |
hoodiehq/pouchdb-hoodie-sync | lib/on.js | on | function on (state, eventName, handler) {
state.emitter.on(eventName, handler)
return state.api
} | javascript | function on (state, eventName, handler) {
state.emitter.on(eventName, handler)
return state.api
} | [
"function",
"on",
"(",
"state",
",",
"eventName",
",",
"handler",
")",
"{",
"state",
".",
"emitter",
".",
"on",
"(",
"eventName",
",",
"handler",
")",
"return",
"state",
".",
"api",
"}"
] | binds event to handler
@param {String} eventName push, pull, connect, disconnect
@param {Function} handler function bound to event
@return {Promise} | [
"binds",
"event",
"to",
"handler"
] | c489baf813020c7f0cbd111224432cb6718c90de | https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/on.js#L10-L14 | train |
Pinoccio/client-node-pinoccio | lib/commands/bridge/index.js | bridgeCommand | function bridgeCommand(command,cb){
if(!connected) return setImmediate(function(){
cb('killed');
});
if(!connected.pings) connected.pings = {};
var id = ++pingid;
var timer;
connected.pings[id] = function(err,data){
clearTimeout(timer);
delete connected.pings[id]
cb(err,data);
};
connected.send({command:command,cb:id});
// set 5 second time limit for callback.
timer = setTimeout(function(){
cb("timeout");
},5000);
} | javascript | function bridgeCommand(command,cb){
if(!connected) return setImmediate(function(){
cb('killed');
});
if(!connected.pings) connected.pings = {};
var id = ++pingid;
var timer;
connected.pings[id] = function(err,data){
clearTimeout(timer);
delete connected.pings[id]
cb(err,data);
};
connected.send({command:command,cb:id});
// set 5 second time limit for callback.
timer = setTimeout(function(){
cb("timeout");
},5000);
} | [
"function",
"bridgeCommand",
"(",
"command",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"connected",
")",
"return",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"cb",
"(",
"'killed'",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"connected",
".",
"pings",
")",
"connected",
".",
"pings",
"=",
"{",
"}",
";",
"var",
"id",
"=",
"++",
"pingid",
";",
"var",
"timer",
";",
"connected",
".",
"pings",
"[",
"id",
"]",
"=",
"function",
"(",
"err",
",",
"data",
")",
"{",
"clearTimeout",
"(",
"timer",
")",
";",
"delete",
"connected",
".",
"pings",
"[",
"id",
"]",
"cb",
"(",
"err",
",",
"data",
")",
";",
"}",
";",
"connected",
".",
"send",
"(",
"{",
"command",
":",
"command",
",",
"cb",
":",
"id",
"}",
")",
";",
"timer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"cb",
"(",
"\"timeout\"",
")",
";",
"}",
",",
"5000",
")",
";",
"}"
] | rpc to worker process for commands. | [
"rpc",
"to",
"worker",
"process",
"for",
"commands",
"."
] | 9ee7b254639190a228dce6a4db9680f2c1bf1ca5 | https://github.com/Pinoccio/client-node-pinoccio/blob/9ee7b254639190a228dce6a4db9680f2c1bf1ca5/lib/commands/bridge/index.js#L200-L218 | train |
Pinoccio/client-node-pinoccio | lib/commands/bridge/index.js | deviceScan | function deviceScan(){
shuffle(Object.keys(watchs.boards)).forEach(function(id){
plugHandler({event:'plug',device:watchs.boards[id]});
});
} | javascript | function deviceScan(){
shuffle(Object.keys(watchs.boards)).forEach(function(id){
plugHandler({event:'plug',device:watchs.boards[id]});
});
} | [
"function",
"deviceScan",
"(",
")",
"{",
"shuffle",
"(",
"Object",
".",
"keys",
"(",
"watchs",
".",
"boards",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"id",
")",
"{",
"plugHandler",
"(",
"{",
"event",
":",
"'plug'",
",",
"device",
":",
"watchs",
".",
"boards",
"[",
"id",
"]",
"}",
")",
";",
"}",
")",
";",
"}"
] | find the next eligble bridge scout. | [
"find",
"the",
"next",
"eligble",
"bridge",
"scout",
"."
] | 9ee7b254639190a228dce6a4db9680f2c1bf1ca5 | https://github.com/Pinoccio/client-node-pinoccio/blob/9ee7b254639190a228dce6a4db9680f2c1bf1ca5/lib/commands/bridge/index.js#L497-L501 | train |
hoodiehq/pouchdb-hoodie-sync | lib/sync.js | sync | function sync (state, docsOrIds) {
var syncedObjects = []
var errors = state.db.constructor.Errors
return Promise.resolve(state.remote)
.then(function (remote) {
return new Promise(function (resolve, reject) {
if (Array.isArray(docsOrIds)) {
docsOrIds = docsOrIds.map(toId)
} else {
docsOrIds = docsOrIds && [toId(docsOrIds)]
}
if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) {
return Promise.reject(errors.NOT_AN_OBJECT)
}
var replication = state.db.sync(remote, {
doc_ids: docsOrIds,
include_docs: true
})
/* istanbul ignore next */
replication.catch(function () {
// handled trough 'error' event
})
replication.on('complete', function () {
resolve(syncedObjects)
})
replication.on('error', reject)
replication.on('change', function (change) {
syncedObjects = syncedObjects.concat(change.change.docs)
for (var i = 0; i < change.change.docs.length; i++) {
state.emitter.emit(change.direction, change.change.docs[i])
}
})
})
})
} | javascript | function sync (state, docsOrIds) {
var syncedObjects = []
var errors = state.db.constructor.Errors
return Promise.resolve(state.remote)
.then(function (remote) {
return new Promise(function (resolve, reject) {
if (Array.isArray(docsOrIds)) {
docsOrIds = docsOrIds.map(toId)
} else {
docsOrIds = docsOrIds && [toId(docsOrIds)]
}
if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) {
return Promise.reject(errors.NOT_AN_OBJECT)
}
var replication = state.db.sync(remote, {
doc_ids: docsOrIds,
include_docs: true
})
/* istanbul ignore next */
replication.catch(function () {
// handled trough 'error' event
})
replication.on('complete', function () {
resolve(syncedObjects)
})
replication.on('error', reject)
replication.on('change', function (change) {
syncedObjects = syncedObjects.concat(change.change.docs)
for (var i = 0; i < change.change.docs.length; i++) {
state.emitter.emit(change.direction, change.change.docs[i])
}
})
})
})
} | [
"function",
"sync",
"(",
"state",
",",
"docsOrIds",
")",
"{",
"var",
"syncedObjects",
"=",
"[",
"]",
"var",
"errors",
"=",
"state",
".",
"db",
".",
"constructor",
".",
"Errors",
"return",
"Promise",
".",
"resolve",
"(",
"state",
".",
"remote",
")",
".",
"then",
"(",
"function",
"(",
"remote",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"docsOrIds",
")",
")",
"{",
"docsOrIds",
"=",
"docsOrIds",
".",
"map",
"(",
"toId",
")",
"}",
"else",
"{",
"docsOrIds",
"=",
"docsOrIds",
"&&",
"[",
"toId",
"(",
"docsOrIds",
")",
"]",
"}",
"if",
"(",
"docsOrIds",
"&&",
"docsOrIds",
".",
"filter",
"(",
"Boolean",
")",
".",
"length",
"!==",
"docsOrIds",
".",
"length",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"errors",
".",
"NOT_AN_OBJECT",
")",
"}",
"var",
"replication",
"=",
"state",
".",
"db",
".",
"sync",
"(",
"remote",
",",
"{",
"doc_ids",
":",
"docsOrIds",
",",
"include_docs",
":",
"true",
"}",
")",
"replication",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"}",
")",
"replication",
".",
"on",
"(",
"'complete'",
",",
"function",
"(",
")",
"{",
"resolve",
"(",
"syncedObjects",
")",
"}",
")",
"replication",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
"replication",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
"change",
")",
"{",
"syncedObjects",
"=",
"syncedObjects",
".",
"concat",
"(",
"change",
".",
"change",
".",
"docs",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"change",
".",
"change",
".",
"docs",
".",
"length",
";",
"i",
"++",
")",
"{",
"state",
".",
"emitter",
".",
"emit",
"(",
"change",
".",
"direction",
",",
"change",
".",
"change",
".",
"docs",
"[",
"i",
"]",
")",
"}",
"}",
")",
"}",
")",
"}",
")",
"}"
] | syncs one or multiple objects between local and remote database
@param {StringOrObject} docsOrIds object or ID of object or array of objects/ids (all optional)
@return {Promise} | [
"syncs",
"one",
"or",
"multiple",
"objects",
"between",
"local",
"and",
"remote",
"database"
] | c489baf813020c7f0cbd111224432cb6718c90de | https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/sync.js#L13-L55 | train |
bem-contrib/md-to-bemjson | packages/remark-bemjson/lib/exports.js | createExport | function createExport(exportOptions, content) {
if (!content) return content;
const type = exportOptions.type;
const name = exportOptions.name;
const exportFunction = exportFabric(type);
return exportFunction(name, content);
} | javascript | function createExport(exportOptions, content) {
if (!content) return content;
const type = exportOptions.type;
const name = exportOptions.name;
const exportFunction = exportFabric(type);
return exportFunction(name, content);
} | [
"function",
"createExport",
"(",
"exportOptions",
",",
"content",
")",
"{",
"if",
"(",
"!",
"content",
")",
"return",
"content",
";",
"const",
"type",
"=",
"exportOptions",
".",
"type",
";",
"const",
"name",
"=",
"exportOptions",
".",
"name",
";",
"const",
"exportFunction",
"=",
"exportFabric",
"(",
"type",
")",
";",
"return",
"exportFunction",
"(",
"name",
",",
"content",
")",
";",
"}"
] | Create export for one of provided modules
@param {Object} exportOptions - export type and name
@param {ExportType} exportOptions.type - export type
@param {String} [exportOptions.name] - export name, required for browser modules
@param {String} content - bemjson content
@returns {String} | [
"Create",
"export",
"for",
"one",
"of",
"provided",
"modules"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/remark-bemjson/lib/exports.js#L33-L41 | train |
soajs/soajs.core.drivers | infra/google/kubernetes/index.js | createVpcNetwork | function createVpcNetwork(mCb) {
let networksOptions = Object.assign({}, options);
networksOptions.params = {
name,
returnGlobalOperation: true
};
networks.add(networksOptions, (error, globalOperationResponse) => {
if (error) return cb(error);
//assign network name to deployment entry
oneDeployment.options.network = name;
//check if network is ready then update firewall rules
checkVpcNetwork(globalOperationResponse, mCb);
});
function checkVpcNetwork(globalOperationResponse, mCb) {
function globalOperations(miniCB) {
options.soajs.log.debug("Checking network Create Status");
//Ref https://cloud.google.com/compute/docs/reference/latest/globalOperations/get
let request = getConnector(options.infra.api);
delete request.projectId;
request.operation = globalOperationResponse.name;
v1Compute().globalOperations.get(request, (error, response) => {
if (error) {
return miniCB(error);
}
if (!response || response.status !== "DONE") {
setTimeout(function () {
globalOperations(miniCB);
}, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5000);
} else {
return miniCB(null, response);
}
});
}
globalOperations(function (err) {
if (err) {
return mCb(err);
} else {
//Ref: https://cloud.google.com/compute/docs/reference/latest/firewalls/insert
let firewallRules = getFirewallRules(oneDeployment.options.network);
let request = getConnector(options.infra.api);
async.eachSeries(firewallRules, (oneRule, vCb) => {
options.soajs.log.debug("Registering new firewall rule:", oneRule.name);
request.resource = oneRule;
v1Compute().firewalls.insert(request, vCb);
}, mCb);
}
});
}
} | javascript | function createVpcNetwork(mCb) {
let networksOptions = Object.assign({}, options);
networksOptions.params = {
name,
returnGlobalOperation: true
};
networks.add(networksOptions, (error, globalOperationResponse) => {
if (error) return cb(error);
//assign network name to deployment entry
oneDeployment.options.network = name;
//check if network is ready then update firewall rules
checkVpcNetwork(globalOperationResponse, mCb);
});
function checkVpcNetwork(globalOperationResponse, mCb) {
function globalOperations(miniCB) {
options.soajs.log.debug("Checking network Create Status");
//Ref https://cloud.google.com/compute/docs/reference/latest/globalOperations/get
let request = getConnector(options.infra.api);
delete request.projectId;
request.operation = globalOperationResponse.name;
v1Compute().globalOperations.get(request, (error, response) => {
if (error) {
return miniCB(error);
}
if (!response || response.status !== "DONE") {
setTimeout(function () {
globalOperations(miniCB);
}, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5000);
} else {
return miniCB(null, response);
}
});
}
globalOperations(function (err) {
if (err) {
return mCb(err);
} else {
//Ref: https://cloud.google.com/compute/docs/reference/latest/firewalls/insert
let firewallRules = getFirewallRules(oneDeployment.options.network);
let request = getConnector(options.infra.api);
async.eachSeries(firewallRules, (oneRule, vCb) => {
options.soajs.log.debug("Registering new firewall rule:", oneRule.name);
request.resource = oneRule;
v1Compute().firewalls.insert(request, vCb);
}, mCb);
}
});
}
} | [
"function",
"createVpcNetwork",
"(",
"mCb",
")",
"{",
"let",
"networksOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"networksOptions",
".",
"params",
"=",
"{",
"name",
",",
"returnGlobalOperation",
":",
"true",
"}",
";",
"networks",
".",
"add",
"(",
"networksOptions",
",",
"(",
"error",
",",
"globalOperationResponse",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"return",
"cb",
"(",
"error",
")",
";",
"oneDeployment",
".",
"options",
".",
"network",
"=",
"name",
";",
"checkVpcNetwork",
"(",
"globalOperationResponse",
",",
"mCb",
")",
";",
"}",
")",
";",
"function",
"checkVpcNetwork",
"(",
"globalOperationResponse",
",",
"mCb",
")",
"{",
"function",
"globalOperations",
"(",
"miniCB",
")",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Checking network Create Status\"",
")",
";",
"let",
"request",
"=",
"getConnector",
"(",
"options",
".",
"infra",
".",
"api",
")",
";",
"delete",
"request",
".",
"projectId",
";",
"request",
".",
"operation",
"=",
"globalOperationResponse",
".",
"name",
";",
"v1Compute",
"(",
")",
".",
"globalOperations",
".",
"get",
"(",
"request",
",",
"(",
"error",
",",
"response",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"miniCB",
"(",
"error",
")",
";",
"}",
"if",
"(",
"!",
"response",
"||",
"response",
".",
"status",
"!==",
"\"DONE\"",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"globalOperations",
"(",
"miniCB",
")",
";",
"}",
",",
"(",
"process",
".",
"env",
".",
"SOAJS_CLOOSTRO_TEST",
")",
"?",
"1",
":",
"5000",
")",
";",
"}",
"else",
"{",
"return",
"miniCB",
"(",
"null",
",",
"response",
")",
";",
"}",
"}",
")",
";",
"}",
"globalOperations",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"mCb",
"(",
"err",
")",
";",
"}",
"else",
"{",
"let",
"firewallRules",
"=",
"getFirewallRules",
"(",
"oneDeployment",
".",
"options",
".",
"network",
")",
";",
"let",
"request",
"=",
"getConnector",
"(",
"options",
".",
"infra",
".",
"api",
")",
";",
"async",
".",
"eachSeries",
"(",
"firewallRules",
",",
"(",
"oneRule",
",",
"vCb",
")",
"=>",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Registering new firewall rule:\"",
",",
"oneRule",
".",
"name",
")",
";",
"request",
".",
"resource",
"=",
"oneRule",
";",
"v1Compute",
"(",
")",
".",
"firewalls",
".",
"insert",
"(",
"request",
",",
"vCb",
")",
";",
"}",
",",
"mCb",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | method used to create a google vpc network
@returns {*} | [
"method",
"used",
"to",
"create",
"a",
"google",
"vpc",
"network"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L95-L150 | train |
soajs/soajs.core.drivers | infra/google/kubernetes/index.js | useVpcNetwork | function useVpcNetwork(mCb) {
//assign network name to deployment entry
oneDeployment.options.network = name;
function patchFirewall() {
let firewallRules = getFirewallRules(oneDeployment.options.network);
let request = getConnector(options.infra.api);
request.filter = `network eq .*${oneDeployment.options.network}`;
request.project = options.infra.api.project;
//list firewalls
//Ref: https://cloud.google.com/compute/docs/reference/rest/v1/firewalls/list
v1Compute().firewalls.list(request, function (error, firewalls) {
if (error) return mCb(error);
if (!firewalls.items) firewalls.items = [];
async.eachSeries(firewallRules, (oneRule, vCb) => {
let foundFirewall = firewalls.items.find((oneEntry) => {
return oneEntry.name === oneRule.name
});
if (foundFirewall) {
options.soajs.log.debug("Firewall rule:", oneRule.name, "already exists, skipping");
return vCb();
} else {
options.soajs.log.debug("Creating firewall rule:", oneRule.name);
request.resource = oneRule;
return v1Compute().firewalls.insert(request, vCb);
}
}, mCb);
});
}
patchFirewall();
} | javascript | function useVpcNetwork(mCb) {
//assign network name to deployment entry
oneDeployment.options.network = name;
function patchFirewall() {
let firewallRules = getFirewallRules(oneDeployment.options.network);
let request = getConnector(options.infra.api);
request.filter = `network eq .*${oneDeployment.options.network}`;
request.project = options.infra.api.project;
//list firewalls
//Ref: https://cloud.google.com/compute/docs/reference/rest/v1/firewalls/list
v1Compute().firewalls.list(request, function (error, firewalls) {
if (error) return mCb(error);
if (!firewalls.items) firewalls.items = [];
async.eachSeries(firewallRules, (oneRule, vCb) => {
let foundFirewall = firewalls.items.find((oneEntry) => {
return oneEntry.name === oneRule.name
});
if (foundFirewall) {
options.soajs.log.debug("Firewall rule:", oneRule.name, "already exists, skipping");
return vCb();
} else {
options.soajs.log.debug("Creating firewall rule:", oneRule.name);
request.resource = oneRule;
return v1Compute().firewalls.insert(request, vCb);
}
}, mCb);
});
}
patchFirewall();
} | [
"function",
"useVpcNetwork",
"(",
"mCb",
")",
"{",
"oneDeployment",
".",
"options",
".",
"network",
"=",
"name",
";",
"function",
"patchFirewall",
"(",
")",
"{",
"let",
"firewallRules",
"=",
"getFirewallRules",
"(",
"oneDeployment",
".",
"options",
".",
"network",
")",
";",
"let",
"request",
"=",
"getConnector",
"(",
"options",
".",
"infra",
".",
"api",
")",
";",
"request",
".",
"filter",
"=",
"`",
"${",
"oneDeployment",
".",
"options",
".",
"network",
"}",
"`",
";",
"request",
".",
"project",
"=",
"options",
".",
"infra",
".",
"api",
".",
"project",
";",
"v1Compute",
"(",
")",
".",
"firewalls",
".",
"list",
"(",
"request",
",",
"function",
"(",
"error",
",",
"firewalls",
")",
"{",
"if",
"(",
"error",
")",
"return",
"mCb",
"(",
"error",
")",
";",
"if",
"(",
"!",
"firewalls",
".",
"items",
")",
"firewalls",
".",
"items",
"=",
"[",
"]",
";",
"async",
".",
"eachSeries",
"(",
"firewallRules",
",",
"(",
"oneRule",
",",
"vCb",
")",
"=>",
"{",
"let",
"foundFirewall",
"=",
"firewalls",
".",
"items",
".",
"find",
"(",
"(",
"oneEntry",
")",
"=>",
"{",
"return",
"oneEntry",
".",
"name",
"===",
"oneRule",
".",
"name",
"}",
")",
";",
"if",
"(",
"foundFirewall",
")",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Firewall rule:\"",
",",
"oneRule",
".",
"name",
",",
"\"already exists, skipping\"",
")",
";",
"return",
"vCb",
"(",
")",
";",
"}",
"else",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Creating firewall rule:\"",
",",
"oneRule",
".",
"name",
")",
";",
"request",
".",
"resource",
"=",
"oneRule",
";",
"return",
"v1Compute",
"(",
")",
".",
"firewalls",
".",
"insert",
"(",
"request",
",",
"vCb",
")",
";",
"}",
"}",
",",
"mCb",
")",
";",
"}",
")",
";",
"}",
"patchFirewall",
"(",
")",
";",
"}"
] | method used to use an existing google vpc network
@returns {*} | [
"method",
"used",
"to",
"use",
"an",
"existing",
"google",
"vpc",
"network"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L156-L192 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.