repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
stezu/node-stream | lib/modifiers/where.js | where | function where(query) {
var matcher = _.matches(query);
return filter(function (value, next) {
if (!_.isPlainObject(query)) {
return next(new TypeError('Expected `query` to be an object.'));
}
return next(null, matcher(value));
});
} | javascript | function where(query) {
var matcher = _.matches(query);
return filter(function (value, next) {
if (!_.isPlainObject(query)) {
return next(new TypeError('Expected `query` to be an object.'));
}
return next(null, matcher(value));
});
} | [
"function",
"where",
"(",
"query",
")",
"{",
"var",
"matcher",
"=",
"_",
".",
"matches",
"(",
"query",
")",
";",
"return",
"filter",
"(",
"function",
"(",
"value",
",",
"next",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isPlainObject",
"(",
"query",
")",
")",
"{",
"return",
"next",
"(",
"new",
"TypeError",
"(",
"'Expected `query` to be an object.'",
")",
")",
";",
"}",
"return",
"next",
"(",
"null",
",",
"matcher",
"(",
"value",
")",
")",
";",
"}",
")",
";",
"}"
]
| A convenient form of filter which performs a deep comparison between a given `query`
and items in the source stream. Items that match the `query` are forwarded to the output
stream.
@static
@since 1.3.0
@category Modifiers
@param {Object} query - An object of properties to compare against all items in
the source stream.
@returns {Stream.Transform} - Transform stream.
@example
// Get all users from a given zip code
users // => [{ name: 'Bill', zip: 90210 }, { name: 'Tracy', zip: 33193 }, { name: 'Paul', zip: 90210 }]
.pipe(nodeStream.where({ zip: 90210 }))
// => [{ name: 'Bill', zip: 90210 }, { name: 'Paul', zip: 90210 }] | [
"A",
"convenient",
"form",
"of",
"filter",
"which",
"performs",
"a",
"deep",
"comparison",
"between",
"a",
"given",
"query",
"and",
"items",
"in",
"the",
"source",
"stream",
".",
"Items",
"that",
"match",
"the",
"query",
"are",
"forwarded",
"to",
"the",
"output",
"stream",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/where.js#L25-L36 | train |
jlas/quirky | game.js | Game | function Game(name) {
this.name = name;
this.board = []; // list representation
this.boardmat = []; // matrix representation
for (var i=0; i<181; i++) {
this.boardmat[i] = new Array(181);
}
this.players = {};
this.turn_pieces = []; // pieces played this turn
this.chat = []; // chat log
// board dimensions
this.dimensions = {'top': 90, 'right': 90, 'bottom': 90, 'left': 90};
/* Keep track of the pieces by having a list of piece objects each with a
* count attribute that tracks how many of that piece are left. When this
* reaches 0, we remove the piece object from the list.
*/
this.pieces = [];
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
var shapes = ['circle', 'star', 'diamond', 'square', 'triangle', 'clover'];
for (var c in colors) {
if (!colors.hasOwnProperty(c)) {
continue;
}
for (var s in shapes) {
if (!shapes.hasOwnProperty(s)) {
continue;
}
this.pieces.push({'piece': new Piece(shapes[s], colors[c]), 'count': 3});
}
}
} | javascript | function Game(name) {
this.name = name;
this.board = []; // list representation
this.boardmat = []; // matrix representation
for (var i=0; i<181; i++) {
this.boardmat[i] = new Array(181);
}
this.players = {};
this.turn_pieces = []; // pieces played this turn
this.chat = []; // chat log
// board dimensions
this.dimensions = {'top': 90, 'right': 90, 'bottom': 90, 'left': 90};
/* Keep track of the pieces by having a list of piece objects each with a
* count attribute that tracks how many of that piece are left. When this
* reaches 0, we remove the piece object from the list.
*/
this.pieces = [];
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
var shapes = ['circle', 'star', 'diamond', 'square', 'triangle', 'clover'];
for (var c in colors) {
if (!colors.hasOwnProperty(c)) {
continue;
}
for (var s in shapes) {
if (!shapes.hasOwnProperty(s)) {
continue;
}
this.pieces.push({'piece': new Piece(shapes[s], colors[c]), 'count': 3});
}
}
} | [
"function",
"Game",
"(",
"name",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"board",
"=",
"[",
"]",
";",
"this",
".",
"boardmat",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"181",
";",
"i",
"++",
")",
"{",
"this",
".",
"boardmat",
"[",
"i",
"]",
"=",
"new",
"Array",
"(",
"181",
")",
";",
"}",
"this",
".",
"players",
"=",
"{",
"}",
";",
"this",
".",
"turn_pieces",
"=",
"[",
"]",
";",
"this",
".",
"chat",
"=",
"[",
"]",
";",
"this",
".",
"dimensions",
"=",
"{",
"'top'",
":",
"90",
",",
"'right'",
":",
"90",
",",
"'bottom'",
":",
"90",
",",
"'left'",
":",
"90",
"}",
";",
"this",
".",
"pieces",
"=",
"[",
"]",
";",
"var",
"colors",
"=",
"[",
"'red'",
",",
"'orange'",
",",
"'yellow'",
",",
"'green'",
",",
"'blue'",
",",
"'purple'",
"]",
";",
"var",
"shapes",
"=",
"[",
"'circle'",
",",
"'star'",
",",
"'diamond'",
",",
"'square'",
",",
"'triangle'",
",",
"'clover'",
"]",
";",
"for",
"(",
"var",
"c",
"in",
"colors",
")",
"{",
"if",
"(",
"!",
"colors",
".",
"hasOwnProperty",
"(",
"c",
")",
")",
"{",
"continue",
";",
"}",
"for",
"(",
"var",
"s",
"in",
"shapes",
")",
"{",
"if",
"(",
"!",
"shapes",
".",
"hasOwnProperty",
"(",
"s",
")",
")",
"{",
"continue",
";",
"}",
"this",
".",
"pieces",
".",
"push",
"(",
"{",
"'piece'",
":",
"new",
"Piece",
"(",
"shapes",
"[",
"s",
"]",
",",
"colors",
"[",
"c",
"]",
")",
",",
"'count'",
":",
"3",
"}",
")",
";",
"}",
"}",
"}"
]
| number of lines to store from chats | [
"number",
"of",
"lines",
"to",
"store",
"from",
"chats"
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L53-L85 | train |
jlas/quirky | game.js | respOk | function respOk (response, data, type) {
if (type) {
headers = {'Content-Type': type};
}
response.writeHead(200, headers);
if (data) {
response.write(data, 'utf-8');
}
response.end();
} | javascript | function respOk (response, data, type) {
if (type) {
headers = {'Content-Type': type};
}
response.writeHead(200, headers);
if (data) {
response.write(data, 'utf-8');
}
response.end();
} | [
"function",
"respOk",
"(",
"response",
",",
"data",
",",
"type",
")",
"{",
"if",
"(",
"type",
")",
"{",
"headers",
"=",
"{",
"'Content-Type'",
":",
"type",
"}",
";",
"}",
"response",
".",
"writeHead",
"(",
"200",
",",
"headers",
")",
";",
"if",
"(",
"data",
")",
"{",
"response",
".",
"write",
"(",
"data",
",",
"'utf-8'",
")",
";",
"}",
"response",
".",
"end",
"(",
")",
";",
"}"
]
| typical response helper | [
"typical",
"response",
"helper"
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L158-L167 | train |
jlas/quirky | game.js | playerFromReq | function playerFromReq(request, response, game) {
var jar = new cookies(request, response);
var p = decodeURIComponent(jar.get('player'));
return game.players[p];
} | javascript | function playerFromReq(request, response, game) {
var jar = new cookies(request, response);
var p = decodeURIComponent(jar.get('player'));
return game.players[p];
} | [
"function",
"playerFromReq",
"(",
"request",
",",
"response",
",",
"game",
")",
"{",
"var",
"jar",
"=",
"new",
"cookies",
"(",
"request",
",",
"response",
")",
";",
"var",
"p",
"=",
"decodeURIComponent",
"(",
"jar",
".",
"get",
"(",
"'player'",
")",
")",
";",
"return",
"game",
".",
"players",
"[",
"p",
"]",
";",
"}"
]
| find player from request cookie | [
"find",
"player",
"from",
"request",
"cookie"
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L291-L295 | train |
jlas/quirky | game.js | requestBody | function requestBody(request, onEnd) {
var fullBody = '';
request.on('data', function(d) {
fullBody += d.toString();
});
request.on('end', function() {
onEnd(querystring.parse(fullBody));
});
} | javascript | function requestBody(request, onEnd) {
var fullBody = '';
request.on('data', function(d) {
fullBody += d.toString();
});
request.on('end', function() {
onEnd(querystring.parse(fullBody));
});
} | [
"function",
"requestBody",
"(",
"request",
",",
"onEnd",
")",
"{",
"var",
"fullBody",
"=",
"''",
";",
"request",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"d",
")",
"{",
"fullBody",
"+=",
"d",
".",
"toString",
"(",
")",
";",
"}",
")",
";",
"request",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"onEnd",
"(",
"querystring",
".",
"parse",
"(",
"fullBody",
")",
")",
";",
"}",
")",
";",
"}"
]
| extract data from request body and pass to onEnd functon | [
"extract",
"data",
"from",
"request",
"body",
"and",
"pass",
"to",
"onEnd",
"functon"
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L303-L311 | train |
jlas/quirky | game.js | nextTurn | function nextTurn(game, player) {
if (player.has_turn === false) { // we assume that player has the turn
return;
}
player.has_turn = false;
// give next player the turn
var _players = Object.keys(game.players);
var next_idx = (_players.indexOf(player.name) + 1) %
_players.length;
var next = game.players[_players[next_idx]];
next.has_turn = true;
// next player draws new pieces
next.pieces = next.pieces.concat(game.drawPieces(
6 - next.pieces.length));
} | javascript | function nextTurn(game, player) {
if (player.has_turn === false) { // we assume that player has the turn
return;
}
player.has_turn = false;
// give next player the turn
var _players = Object.keys(game.players);
var next_idx = (_players.indexOf(player.name) + 1) %
_players.length;
var next = game.players[_players[next_idx]];
next.has_turn = true;
// next player draws new pieces
next.pieces = next.pieces.concat(game.drawPieces(
6 - next.pieces.length));
} | [
"function",
"nextTurn",
"(",
"game",
",",
"player",
")",
"{",
"if",
"(",
"player",
".",
"has_turn",
"===",
"false",
")",
"{",
"return",
";",
"}",
"player",
".",
"has_turn",
"=",
"false",
";",
"var",
"_players",
"=",
"Object",
".",
"keys",
"(",
"game",
".",
"players",
")",
";",
"var",
"next_idx",
"=",
"(",
"_players",
".",
"indexOf",
"(",
"player",
".",
"name",
")",
"+",
"1",
")",
"%",
"_players",
".",
"length",
";",
"var",
"next",
"=",
"game",
".",
"players",
"[",
"_players",
"[",
"next_idx",
"]",
"]",
";",
"next",
".",
"has_turn",
"=",
"true",
";",
"next",
".",
"pieces",
"=",
"next",
".",
"pieces",
".",
"concat",
"(",
"game",
".",
"drawPieces",
"(",
"6",
"-",
"next",
".",
"pieces",
".",
"length",
")",
")",
";",
"}"
]
| Pass the turn to the next player,
@param game: {obj} game object
@param player: {obj} player object | [
"Pass",
"the",
"turn",
"to",
"the",
"next",
"player"
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L318-L333 | train |
jlas/quirky | game.js | addPlayerToGame | function addPlayerToGame(game, playernm) {
var p = new Player(playernm);
p.pieces = game.drawPieces(6);
game.players[p.name] = p;
// if first player, make it his turn
if (Object.keys(game.players).length === 1) {
p.has_turn = true;
}
} | javascript | function addPlayerToGame(game, playernm) {
var p = new Player(playernm);
p.pieces = game.drawPieces(6);
game.players[p.name] = p;
// if first player, make it his turn
if (Object.keys(game.players).length === 1) {
p.has_turn = true;
}
} | [
"function",
"addPlayerToGame",
"(",
"game",
",",
"playernm",
")",
"{",
"var",
"p",
"=",
"new",
"Player",
"(",
"playernm",
")",
";",
"p",
".",
"pieces",
"=",
"game",
".",
"drawPieces",
"(",
"6",
")",
";",
"game",
".",
"players",
"[",
"p",
".",
"name",
"]",
"=",
"p",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"game",
".",
"players",
")",
".",
"length",
"===",
"1",
")",
"{",
"p",
".",
"has_turn",
"=",
"true",
";",
"}",
"}"
]
| Create and add a player to a game.
@param game: {obj} game object
@param playernm: {str} player name | [
"Create",
"and",
"add",
"a",
"player",
"to",
"a",
"game",
"."
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L350-L359 | train |
jlas/quirky | game.js | handlePlayers | function handlePlayers(request, response, game, path) {
var func, player, resp;
if (!path.length) {
// return info on the players collection
if (request.method === "POST") {
player = playerFromReq(request, response, game);
if (player) {
// end turn
// TODO should this be under /players/<name>/?
func = function (form) {
if (form && form.end_turn) {
switchPlayers(game, player);
respOk(response);
}
};
} else {
// add player to a game
func = function(form) {
if (form && form.name) {
addPlayerToGame(game, form.name);
var jar = new cookies(request, response);
jar.set("player", encodeURIComponent(form.name),
{httpOnly: false});
respOk(response, '', 'text/json');
}
};
}
requestBody(request, func);
return;
} else if (request.method === 'DELETE') {
// delete player from a game
func = function(form) {
if (form && form.name) {
player = game.players[form.name];
if (player === undefined) {
// huh? player is not in this game
response.writeHead(404, {'Content-Type': 'text/json'});
response.end();
return;
}
nextTurn(game, player);
game.returnPieces(player.pieces);
delete game.players[form.name];
if (Object.keys(game.players).length === 0) {
delete games[game.name];
}
respOk(response);
}
};
requestBody(request, func);
return;
} else {
resp = JSON.stringify(game.players);
}
} else {
// return info on a specific player
player = game.players[path[0]];
if (typeof player === 'undefined') {
// player not found
response.writeHead(404, {'Content-Type': 'text/json'});
response.end();
return;
}
if (path[1] === 'pieces') {
resp = JSON.stringify(player.pieces);
}
}
respOk(response, resp, 'text/json');
} | javascript | function handlePlayers(request, response, game, path) {
var func, player, resp;
if (!path.length) {
// return info on the players collection
if (request.method === "POST") {
player = playerFromReq(request, response, game);
if (player) {
// end turn
// TODO should this be under /players/<name>/?
func = function (form) {
if (form && form.end_turn) {
switchPlayers(game, player);
respOk(response);
}
};
} else {
// add player to a game
func = function(form) {
if (form && form.name) {
addPlayerToGame(game, form.name);
var jar = new cookies(request, response);
jar.set("player", encodeURIComponent(form.name),
{httpOnly: false});
respOk(response, '', 'text/json');
}
};
}
requestBody(request, func);
return;
} else if (request.method === 'DELETE') {
// delete player from a game
func = function(form) {
if (form && form.name) {
player = game.players[form.name];
if (player === undefined) {
// huh? player is not in this game
response.writeHead(404, {'Content-Type': 'text/json'});
response.end();
return;
}
nextTurn(game, player);
game.returnPieces(player.pieces);
delete game.players[form.name];
if (Object.keys(game.players).length === 0) {
delete games[game.name];
}
respOk(response);
}
};
requestBody(request, func);
return;
} else {
resp = JSON.stringify(game.players);
}
} else {
// return info on a specific player
player = game.players[path[0]];
if (typeof player === 'undefined') {
// player not found
response.writeHead(404, {'Content-Type': 'text/json'});
response.end();
return;
}
if (path[1] === 'pieces') {
resp = JSON.stringify(player.pieces);
}
}
respOk(response, resp, 'text/json');
} | [
"function",
"handlePlayers",
"(",
"request",
",",
"response",
",",
"game",
",",
"path",
")",
"{",
"var",
"func",
",",
"player",
",",
"resp",
";",
"if",
"(",
"!",
"path",
".",
"length",
")",
"{",
"if",
"(",
"request",
".",
"method",
"===",
"\"POST\"",
")",
"{",
"player",
"=",
"playerFromReq",
"(",
"request",
",",
"response",
",",
"game",
")",
";",
"if",
"(",
"player",
")",
"{",
"func",
"=",
"function",
"(",
"form",
")",
"{",
"if",
"(",
"form",
"&&",
"form",
".",
"end_turn",
")",
"{",
"switchPlayers",
"(",
"game",
",",
"player",
")",
";",
"respOk",
"(",
"response",
")",
";",
"}",
"}",
";",
"}",
"else",
"{",
"func",
"=",
"function",
"(",
"form",
")",
"{",
"if",
"(",
"form",
"&&",
"form",
".",
"name",
")",
"{",
"addPlayerToGame",
"(",
"game",
",",
"form",
".",
"name",
")",
";",
"var",
"jar",
"=",
"new",
"cookies",
"(",
"request",
",",
"response",
")",
";",
"jar",
".",
"set",
"(",
"\"player\"",
",",
"encodeURIComponent",
"(",
"form",
".",
"name",
")",
",",
"{",
"httpOnly",
":",
"false",
"}",
")",
";",
"respOk",
"(",
"response",
",",
"''",
",",
"'text/json'",
")",
";",
"}",
"}",
";",
"}",
"requestBody",
"(",
"request",
",",
"func",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"request",
".",
"method",
"===",
"'DELETE'",
")",
"{",
"func",
"=",
"function",
"(",
"form",
")",
"{",
"if",
"(",
"form",
"&&",
"form",
".",
"name",
")",
"{",
"player",
"=",
"game",
".",
"players",
"[",
"form",
".",
"name",
"]",
";",
"if",
"(",
"player",
"===",
"undefined",
")",
"{",
"response",
".",
"writeHead",
"(",
"404",
",",
"{",
"'Content-Type'",
":",
"'text/json'",
"}",
")",
";",
"response",
".",
"end",
"(",
")",
";",
"return",
";",
"}",
"nextTurn",
"(",
"game",
",",
"player",
")",
";",
"game",
".",
"returnPieces",
"(",
"player",
".",
"pieces",
")",
";",
"delete",
"game",
".",
"players",
"[",
"form",
".",
"name",
"]",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"game",
".",
"players",
")",
".",
"length",
"===",
"0",
")",
"{",
"delete",
"games",
"[",
"game",
".",
"name",
"]",
";",
"}",
"respOk",
"(",
"response",
")",
";",
"}",
"}",
";",
"requestBody",
"(",
"request",
",",
"func",
")",
";",
"return",
";",
"}",
"else",
"{",
"resp",
"=",
"JSON",
".",
"stringify",
"(",
"game",
".",
"players",
")",
";",
"}",
"}",
"else",
"{",
"player",
"=",
"game",
".",
"players",
"[",
"path",
"[",
"0",
"]",
"]",
";",
"if",
"(",
"typeof",
"player",
"===",
"'undefined'",
")",
"{",
"response",
".",
"writeHead",
"(",
"404",
",",
"{",
"'Content-Type'",
":",
"'text/json'",
"}",
")",
";",
"response",
".",
"end",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"path",
"[",
"1",
"]",
"===",
"'pieces'",
")",
"{",
"resp",
"=",
"JSON",
".",
"stringify",
"(",
"player",
".",
"pieces",
")",
";",
"}",
"}",
"respOk",
"(",
"response",
",",
"resp",
",",
"'text/json'",
")",
";",
"}"
]
| Handle a player resource transaction.
- POST to add player to the game.
- GET player pieces | [
"Handle",
"a",
"player",
"resource",
"transaction",
".",
"-",
"POST",
"to",
"add",
"player",
"to",
"the",
"game",
".",
"-",
"GET",
"player",
"pieces"
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L366-L437 | train |
jlas/quirky | game.js | handleGame | function handleGame(request, response, game, path) {
var resp;
switch(path[0]) {
case 'board':
// add pieces to the board
if (request.method === "POST") {
requestBody(request, function(form) {
var player = playerFromReq(request, response, game);
// console.info('adding pieces, player:'+player.name);
// console.info('form info:'+JSON.stringify(form));
if (form && form.shape && form.color &&
form.row && form.column && player) {
// TODO should do form check?
var row = parseInt(form.row, 10);
var column = parseInt(form.column, 10);
var piece = new Piece(form.shape, form.color);
// check player has piece
var idx = -1, _idx = 0;
for (var p in player.pieces) {
var _piece = player.pieces[p];
//console.log('check:'+JSON.stringify(p)+', and:'+
// JSON.stringify(piece));
if (piece.equals(_piece)) {
idx = _idx;
break;
}
_idx += 1;
}
if (idx > -1) {
var gp = new GamePiece(piece, row, column);
// console.info('adding piece:'+JSON.stringify(gp));
resp = addGamePiece(game, gp);
if (typeof resp === "string") {
// add gamepiece failed
response.writeHead(409, {'Content-Type': 'text/json'});
response.write(resp, 'utf-8');
response.end();
return;
} else {
// add gamepiece succeeded
player.points += resp;
player.pieces.splice(idx, 1);
respOk(response, '', 'text/json');
}
}
}
});
return;
}
// get pieces on the board
resp = JSON.stringify(game.board);
break;
case 'players':
handlePlayers(request, response, game, path.slice(1));
return;
case 'pieces':
// get pieces in the bag
resp = JSON.stringify(game.pieces);
break;
case 'chat':
handleChat(request, response, game.chat);
break;
case 'dimensions':
resp = JSON.stringify(game.dimensions);
}
respOk(response, resp, 'text/json');
} | javascript | function handleGame(request, response, game, path) {
var resp;
switch(path[0]) {
case 'board':
// add pieces to the board
if (request.method === "POST") {
requestBody(request, function(form) {
var player = playerFromReq(request, response, game);
// console.info('adding pieces, player:'+player.name);
// console.info('form info:'+JSON.stringify(form));
if (form && form.shape && form.color &&
form.row && form.column && player) {
// TODO should do form check?
var row = parseInt(form.row, 10);
var column = parseInt(form.column, 10);
var piece = new Piece(form.shape, form.color);
// check player has piece
var idx = -1, _idx = 0;
for (var p in player.pieces) {
var _piece = player.pieces[p];
//console.log('check:'+JSON.stringify(p)+', and:'+
// JSON.stringify(piece));
if (piece.equals(_piece)) {
idx = _idx;
break;
}
_idx += 1;
}
if (idx > -1) {
var gp = new GamePiece(piece, row, column);
// console.info('adding piece:'+JSON.stringify(gp));
resp = addGamePiece(game, gp);
if (typeof resp === "string") {
// add gamepiece failed
response.writeHead(409, {'Content-Type': 'text/json'});
response.write(resp, 'utf-8');
response.end();
return;
} else {
// add gamepiece succeeded
player.points += resp;
player.pieces.splice(idx, 1);
respOk(response, '', 'text/json');
}
}
}
});
return;
}
// get pieces on the board
resp = JSON.stringify(game.board);
break;
case 'players':
handlePlayers(request, response, game, path.slice(1));
return;
case 'pieces':
// get pieces in the bag
resp = JSON.stringify(game.pieces);
break;
case 'chat':
handleChat(request, response, game.chat);
break;
case 'dimensions':
resp = JSON.stringify(game.dimensions);
}
respOk(response, resp, 'text/json');
} | [
"function",
"handleGame",
"(",
"request",
",",
"response",
",",
"game",
",",
"path",
")",
"{",
"var",
"resp",
";",
"switch",
"(",
"path",
"[",
"0",
"]",
")",
"{",
"case",
"'board'",
":",
"if",
"(",
"request",
".",
"method",
"===",
"\"POST\"",
")",
"{",
"requestBody",
"(",
"request",
",",
"function",
"(",
"form",
")",
"{",
"var",
"player",
"=",
"playerFromReq",
"(",
"request",
",",
"response",
",",
"game",
")",
";",
"if",
"(",
"form",
"&&",
"form",
".",
"shape",
"&&",
"form",
".",
"color",
"&&",
"form",
".",
"row",
"&&",
"form",
".",
"column",
"&&",
"player",
")",
"{",
"var",
"row",
"=",
"parseInt",
"(",
"form",
".",
"row",
",",
"10",
")",
";",
"var",
"column",
"=",
"parseInt",
"(",
"form",
".",
"column",
",",
"10",
")",
";",
"var",
"piece",
"=",
"new",
"Piece",
"(",
"form",
".",
"shape",
",",
"form",
".",
"color",
")",
";",
"var",
"idx",
"=",
"-",
"1",
",",
"_idx",
"=",
"0",
";",
"for",
"(",
"var",
"p",
"in",
"player",
".",
"pieces",
")",
"{",
"var",
"_piece",
"=",
"player",
".",
"pieces",
"[",
"p",
"]",
";",
"if",
"(",
"piece",
".",
"equals",
"(",
"_piece",
")",
")",
"{",
"idx",
"=",
"_idx",
";",
"break",
";",
"}",
"_idx",
"+=",
"1",
";",
"}",
"if",
"(",
"idx",
">",
"-",
"1",
")",
"{",
"var",
"gp",
"=",
"new",
"GamePiece",
"(",
"piece",
",",
"row",
",",
"column",
")",
";",
"resp",
"=",
"addGamePiece",
"(",
"game",
",",
"gp",
")",
";",
"if",
"(",
"typeof",
"resp",
"===",
"\"string\"",
")",
"{",
"response",
".",
"writeHead",
"(",
"409",
",",
"{",
"'Content-Type'",
":",
"'text/json'",
"}",
")",
";",
"response",
".",
"write",
"(",
"resp",
",",
"'utf-8'",
")",
";",
"response",
".",
"end",
"(",
")",
";",
"return",
";",
"}",
"else",
"{",
"player",
".",
"points",
"+=",
"resp",
";",
"player",
".",
"pieces",
".",
"splice",
"(",
"idx",
",",
"1",
")",
";",
"respOk",
"(",
"response",
",",
"''",
",",
"'text/json'",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"return",
";",
"}",
"resp",
"=",
"JSON",
".",
"stringify",
"(",
"game",
".",
"board",
")",
";",
"break",
";",
"case",
"'players'",
":",
"handlePlayers",
"(",
"request",
",",
"response",
",",
"game",
",",
"path",
".",
"slice",
"(",
"1",
")",
")",
";",
"return",
";",
"case",
"'pieces'",
":",
"resp",
"=",
"JSON",
".",
"stringify",
"(",
"game",
".",
"pieces",
")",
";",
"break",
";",
"case",
"'chat'",
":",
"handleChat",
"(",
"request",
",",
"response",
",",
"game",
".",
"chat",
")",
";",
"break",
";",
"case",
"'dimensions'",
":",
"resp",
"=",
"JSON",
".",
"stringify",
"(",
"game",
".",
"dimensions",
")",
";",
"}",
"respOk",
"(",
"response",
",",
"resp",
",",
"'text/json'",
")",
";",
"}"
]
| Handle a game resource transaction.
- POST to add piece to the board.
- Forward player transactions to separate function.
- GET pieces on board & in bag
- GET dimensions | [
"Handle",
"a",
"game",
"resource",
"transaction",
".",
"-",
"POST",
"to",
"add",
"piece",
"to",
"the",
"board",
".",
"-",
"Forward",
"player",
"transactions",
"to",
"separate",
"function",
".",
"-",
"GET",
"pieces",
"on",
"board",
"&",
"in",
"bag",
"-",
"GET",
"dimensions"
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L446-L517 | train |
jlas/quirky | game.js | handleGames | function handleGames(request, response, path) {
var resp;
if (!path.length) {
if (request.method === "POST") {
// add a new game object
requestBody(request, function(form) {
var gamenm = form.name;
while (games[gamenm]) {
// game already exists, randomize a new one
gamenm = gamenm+Math.floor(Math.random()*10);
}
var game = new Game(gamenm);
var jar = new cookies(request, response);
var p = decodeURIComponent(jar.get('player'));
games[gamenm] = game;
addPlayerToGame(game, p);
// respond with the game name, in case we randomized a new one
respOk(response, JSON.stringify({name: gamenm}), 'text/json');
});
} else {
// return info on the games collection
resp = JSON.stringify(games);
respOk(response, resp, 'text/json');
}
} else {
// return info on a specifc game
var game = games[path.shift()];
if (game === undefined) {
response.writeHead(404, {'Content-Type': 'text/json'});
response.write("No such game exists", 'utf-8');
response.end();
return;
}
handleGame(request, response, game, path);
}
} | javascript | function handleGames(request, response, path) {
var resp;
if (!path.length) {
if (request.method === "POST") {
// add a new game object
requestBody(request, function(form) {
var gamenm = form.name;
while (games[gamenm]) {
// game already exists, randomize a new one
gamenm = gamenm+Math.floor(Math.random()*10);
}
var game = new Game(gamenm);
var jar = new cookies(request, response);
var p = decodeURIComponent(jar.get('player'));
games[gamenm] = game;
addPlayerToGame(game, p);
// respond with the game name, in case we randomized a new one
respOk(response, JSON.stringify({name: gamenm}), 'text/json');
});
} else {
// return info on the games collection
resp = JSON.stringify(games);
respOk(response, resp, 'text/json');
}
} else {
// return info on a specifc game
var game = games[path.shift()];
if (game === undefined) {
response.writeHead(404, {'Content-Type': 'text/json'});
response.write("No such game exists", 'utf-8');
response.end();
return;
}
handleGame(request, response, game, path);
}
} | [
"function",
"handleGames",
"(",
"request",
",",
"response",
",",
"path",
")",
"{",
"var",
"resp",
";",
"if",
"(",
"!",
"path",
".",
"length",
")",
"{",
"if",
"(",
"request",
".",
"method",
"===",
"\"POST\"",
")",
"{",
"requestBody",
"(",
"request",
",",
"function",
"(",
"form",
")",
"{",
"var",
"gamenm",
"=",
"form",
".",
"name",
";",
"while",
"(",
"games",
"[",
"gamenm",
"]",
")",
"{",
"gamenm",
"=",
"gamenm",
"+",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"10",
")",
";",
"}",
"var",
"game",
"=",
"new",
"Game",
"(",
"gamenm",
")",
";",
"var",
"jar",
"=",
"new",
"cookies",
"(",
"request",
",",
"response",
")",
";",
"var",
"p",
"=",
"decodeURIComponent",
"(",
"jar",
".",
"get",
"(",
"'player'",
")",
")",
";",
"games",
"[",
"gamenm",
"]",
"=",
"game",
";",
"addPlayerToGame",
"(",
"game",
",",
"p",
")",
";",
"respOk",
"(",
"response",
",",
"JSON",
".",
"stringify",
"(",
"{",
"name",
":",
"gamenm",
"}",
")",
",",
"'text/json'",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"resp",
"=",
"JSON",
".",
"stringify",
"(",
"games",
")",
";",
"respOk",
"(",
"response",
",",
"resp",
",",
"'text/json'",
")",
";",
"}",
"}",
"else",
"{",
"var",
"game",
"=",
"games",
"[",
"path",
".",
"shift",
"(",
")",
"]",
";",
"if",
"(",
"game",
"===",
"undefined",
")",
"{",
"response",
".",
"writeHead",
"(",
"404",
",",
"{",
"'Content-Type'",
":",
"'text/json'",
"}",
")",
";",
"response",
".",
"write",
"(",
"\"No such game exists\"",
",",
"'utf-8'",
")",
";",
"response",
".",
"end",
"(",
")",
";",
"return",
";",
"}",
"handleGame",
"(",
"request",
",",
"response",
",",
"game",
",",
"path",
")",
";",
"}",
"}"
]
| Handle transaction on game collection resource. | [
"Handle",
"transaction",
"on",
"game",
"collection",
"resource",
"."
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L522-L557 | train |
jlas/quirky | game.js | handleChat | function handleChat(request, response, chat) {
var resp, id;
if (request.method === "POST") {
// add a line to the chat log
requestBody(request, function(form) {
while (chat.length > CHATLINES) {
chat.shift();
}
/* If data is present in the chat, then increment the last id,
* otherwise start at 0.
*/
if (chat.length) {
id = chat[chat.length-1].id + 1;
} else {
id = 0;
}
chat.push({
id: id, // chat line id
name: form.name, // the user's name
input: form.input // the user's text input
});
respOk(response, '', 'text/json');
});
} else {
/* Return chat data. If lastid is specified, then we only return
* chat lines since this id.
*/
var form = requestQuery(request);
var lastid = +form.lastid;
if (lastid >= 0) {
for (var i=0; i<chat.length; i++) {
if (chat[i].id === lastid) {
break;
}
}
resp = JSON.stringify(chat.slice(i+1));
} else {
resp = JSON.stringify(chat);
}
respOk(response, resp, 'text/json');
}
} | javascript | function handleChat(request, response, chat) {
var resp, id;
if (request.method === "POST") {
// add a line to the chat log
requestBody(request, function(form) {
while (chat.length > CHATLINES) {
chat.shift();
}
/* If data is present in the chat, then increment the last id,
* otherwise start at 0.
*/
if (chat.length) {
id = chat[chat.length-1].id + 1;
} else {
id = 0;
}
chat.push({
id: id, // chat line id
name: form.name, // the user's name
input: form.input // the user's text input
});
respOk(response, '', 'text/json');
});
} else {
/* Return chat data. If lastid is specified, then we only return
* chat lines since this id.
*/
var form = requestQuery(request);
var lastid = +form.lastid;
if (lastid >= 0) {
for (var i=0; i<chat.length; i++) {
if (chat[i].id === lastid) {
break;
}
}
resp = JSON.stringify(chat.slice(i+1));
} else {
resp = JSON.stringify(chat);
}
respOk(response, resp, 'text/json');
}
} | [
"function",
"handleChat",
"(",
"request",
",",
"response",
",",
"chat",
")",
"{",
"var",
"resp",
",",
"id",
";",
"if",
"(",
"request",
".",
"method",
"===",
"\"POST\"",
")",
"{",
"requestBody",
"(",
"request",
",",
"function",
"(",
"form",
")",
"{",
"while",
"(",
"chat",
".",
"length",
">",
"CHATLINES",
")",
"{",
"chat",
".",
"shift",
"(",
")",
";",
"}",
"if",
"(",
"chat",
".",
"length",
")",
"{",
"id",
"=",
"chat",
"[",
"chat",
".",
"length",
"-",
"1",
"]",
".",
"id",
"+",
"1",
";",
"}",
"else",
"{",
"id",
"=",
"0",
";",
"}",
"chat",
".",
"push",
"(",
"{",
"id",
":",
"id",
",",
"name",
":",
"form",
".",
"name",
",",
"input",
":",
"form",
".",
"input",
"}",
")",
";",
"respOk",
"(",
"response",
",",
"''",
",",
"'text/json'",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"var",
"form",
"=",
"requestQuery",
"(",
"request",
")",
";",
"var",
"lastid",
"=",
"+",
"form",
".",
"lastid",
";",
"if",
"(",
"lastid",
">=",
"0",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"chat",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"chat",
"[",
"i",
"]",
".",
"id",
"===",
"lastid",
")",
"{",
"break",
";",
"}",
"}",
"resp",
"=",
"JSON",
".",
"stringify",
"(",
"chat",
".",
"slice",
"(",
"i",
"+",
"1",
")",
")",
";",
"}",
"else",
"{",
"resp",
"=",
"JSON",
".",
"stringify",
"(",
"chat",
")",
";",
"}",
"respOk",
"(",
"response",
",",
"resp",
",",
"'text/json'",
")",
";",
"}",
"}"
]
| Handle transaction on chat.
@param chat {list}: a chat object, which is a list of
{id: {number}, name: {string}, input: {string}} objects | [
"Handle",
"transaction",
"on",
"chat",
"."
]
| 1ee950d2cc447ea16f189f499fbcd2e25925267c | https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L564-L606 | train |
voltraco/mineral | compilers/html.js | escapedValue | function escapedValue (data, info, str) {
return he.escape(getValue(data, info, str) + '')
} | javascript | function escapedValue (data, info, str) {
return he.escape(getValue(data, info, str) + '')
} | [
"function",
"escapedValue",
"(",
"data",
",",
"info",
",",
"str",
")",
"{",
"return",
"he",
".",
"escape",
"(",
"getValue",
"(",
"data",
",",
"info",
",",
"str",
")",
"+",
"''",
")",
"}"
]
| determine if this is a path or just regular content | [
"determine",
"if",
"this",
"is",
"a",
"path",
"or",
"just",
"regular",
"content"
]
| 072c6b125e562d6e2b97d9e3ff5362998a0193a9 | https://github.com/voltraco/mineral/blob/072c6b125e562d6e2b97d9e3ff5362998a0193a9/compilers/html.js#L38-L40 | train |
rich-nguyen/grunt-asset-hash | tasks/asset_hash.js | writeMappingFile | function writeMappingFile() {
// The full mapping combines the asset and source map files.
var fullMapping = {};
copyObjectProperties(assetFileMapping, fullMapping);
copyObjectProperties(sourceFileMapping, fullMapping);
// Sort the keys.
var sortedMapping = {};
var sortedAssets = Object.keys(fullMapping).sort();
sortedAssets.forEach(function(asset) {
// track which assets were renamed
// for filename reference replacement
// (eg. in CSS files referencing renamed images)
renameInfos.push({
from: asset,
fromRegex: new RegExp('\\b' + asset + '\\b', 'g'),
to: fullMapping[asset]
});
sortedMapping[asset] = fullMapping[asset];
});
if (options.assetMap) {
grunt.file.write(options.assetMap, JSON.stringify(sortedMapping, null, 2));
grunt.log.oklns('Asset map saved as ' + options.assetMap);
}
} | javascript | function writeMappingFile() {
// The full mapping combines the asset and source map files.
var fullMapping = {};
copyObjectProperties(assetFileMapping, fullMapping);
copyObjectProperties(sourceFileMapping, fullMapping);
// Sort the keys.
var sortedMapping = {};
var sortedAssets = Object.keys(fullMapping).sort();
sortedAssets.forEach(function(asset) {
// track which assets were renamed
// for filename reference replacement
// (eg. in CSS files referencing renamed images)
renameInfos.push({
from: asset,
fromRegex: new RegExp('\\b' + asset + '\\b', 'g'),
to: fullMapping[asset]
});
sortedMapping[asset] = fullMapping[asset];
});
if (options.assetMap) {
grunt.file.write(options.assetMap, JSON.stringify(sortedMapping, null, 2));
grunt.log.oklns('Asset map saved as ' + options.assetMap);
}
} | [
"function",
"writeMappingFile",
"(",
")",
"{",
"var",
"fullMapping",
"=",
"{",
"}",
";",
"copyObjectProperties",
"(",
"assetFileMapping",
",",
"fullMapping",
")",
";",
"copyObjectProperties",
"(",
"sourceFileMapping",
",",
"fullMapping",
")",
";",
"var",
"sortedMapping",
"=",
"{",
"}",
";",
"var",
"sortedAssets",
"=",
"Object",
".",
"keys",
"(",
"fullMapping",
")",
".",
"sort",
"(",
")",
";",
"sortedAssets",
".",
"forEach",
"(",
"function",
"(",
"asset",
")",
"{",
"renameInfos",
".",
"push",
"(",
"{",
"from",
":",
"asset",
",",
"fromRegex",
":",
"new",
"RegExp",
"(",
"'\\\\b'",
"+",
"\\\\",
"+",
"asset",
",",
"'\\\\b'",
")",
",",
"\\\\",
"}",
")",
";",
"'g'",
"}",
")",
";",
"to",
":",
"fullMapping",
"[",
"asset",
"]",
"}"
]
| Write the accompanying json file that maps non-hashed assets to their hashed locations. | [
"Write",
"the",
"accompanying",
"json",
"file",
"that",
"maps",
"non",
"-",
"hashed",
"assets",
"to",
"their",
"hashed",
"locations",
"."
]
| 44ee2abfe5426d29899b3ecf562b4faf2fbc7ce7 | https://github.com/rich-nguyen/grunt-asset-hash/blob/44ee2abfe5426d29899b3ecf562b4faf2fbc7ce7/tasks/asset_hash.js#L148-L173 | train |
divio/djangocms-casper-helpers | gulp/index.js | function (tests) {
return new Promise(function (resolve) {
var visual = argv && argv.visual;
var visualPort = argv && argv.visualPort || '8002';
var params = ['test', '--web-security=no', '--server-port=' + serverPort];
if (visual) {
params.push('--visual=' + (visual || 10));
params.push('--visual-port=' + visualPort);
}
var casperChild = spawn(
pathToCasper,
params.concat(tests)
);
casperChild.stdout.on('data', function (data) {
logger('CasperJS:', data.toString().slice(0, -1));
});
casperChild.on('close', function (code) {
resolve(code);
});
});
} | javascript | function (tests) {
return new Promise(function (resolve) {
var visual = argv && argv.visual;
var visualPort = argv && argv.visualPort || '8002';
var params = ['test', '--web-security=no', '--server-port=' + serverPort];
if (visual) {
params.push('--visual=' + (visual || 10));
params.push('--visual-port=' + visualPort);
}
var casperChild = spawn(
pathToCasper,
params.concat(tests)
);
casperChild.stdout.on('data', function (data) {
logger('CasperJS:', data.toString().slice(0, -1));
});
casperChild.on('close', function (code) {
resolve(code);
});
});
} | [
"function",
"(",
"tests",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"var",
"visual",
"=",
"argv",
"&&",
"argv",
".",
"visual",
";",
"var",
"visualPort",
"=",
"argv",
"&&",
"argv",
".",
"visualPort",
"||",
"'8002'",
";",
"var",
"params",
"=",
"[",
"'test'",
",",
"'--web-security=no'",
",",
"'--server-port='",
"+",
"serverPort",
"]",
";",
"if",
"(",
"visual",
")",
"{",
"params",
".",
"push",
"(",
"'--visual='",
"+",
"(",
"visual",
"||",
"10",
")",
")",
";",
"params",
".",
"push",
"(",
"'--visual-port='",
"+",
"visualPort",
")",
";",
"}",
"var",
"casperChild",
"=",
"spawn",
"(",
"pathToCasper",
",",
"params",
".",
"concat",
"(",
"tests",
")",
")",
";",
"casperChild",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"logger",
"(",
"'CasperJS:'",
",",
"data",
".",
"toString",
"(",
")",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
")",
";",
"}",
")",
";",
"casperChild",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
"code",
")",
"{",
"resolve",
"(",
"code",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Runs casperjs process with tests passed as arguments to it and logs output.
@method runTests
@param {String[]} tests paths to tests
@returns {Promise} resolves with casper exit code (0 or 1) | [
"Runs",
"casperjs",
"process",
"with",
"tests",
"passed",
"as",
"arguments",
"to",
"it",
"and",
"logs",
"output",
"."
]
| 200e0f29b01341cba34e7bc9e7d329f81d531b2a | https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/gulp/index.js#L179-L202 | train |
|
noderaider/repackage | jspm_packages/npm/[email protected]/lib/generation/generators/methods.js | _method | function _method(node, print) {
var value = node.value;
var kind = node.kind;
var key = node.key;
if (kind === "method" || kind === "init") {
if (value.generator) {
this.push("*");
}
}
if (kind === "get" || kind === "set") {
this.push(kind + " ");
}
if (value.async) this.push("async ");
if (node.computed) {
this.push("[");
print.plain(key);
this.push("]");
} else {
print.plain(key);
}
this._params(value, print);
this.space();
print.plain(value.body);
} | javascript | function _method(node, print) {
var value = node.value;
var kind = node.kind;
var key = node.key;
if (kind === "method" || kind === "init") {
if (value.generator) {
this.push("*");
}
}
if (kind === "get" || kind === "set") {
this.push(kind + " ");
}
if (value.async) this.push("async ");
if (node.computed) {
this.push("[");
print.plain(key);
this.push("]");
} else {
print.plain(key);
}
this._params(value, print);
this.space();
print.plain(value.body);
} | [
"function",
"_method",
"(",
"node",
",",
"print",
")",
"{",
"var",
"value",
"=",
"node",
".",
"value",
";",
"var",
"kind",
"=",
"node",
".",
"kind",
";",
"var",
"key",
"=",
"node",
".",
"key",
";",
"if",
"(",
"kind",
"===",
"\"method\"",
"||",
"kind",
"===",
"\"init\"",
")",
"{",
"if",
"(",
"value",
".",
"generator",
")",
"{",
"this",
".",
"push",
"(",
"\"*\"",
")",
";",
"}",
"}",
"if",
"(",
"kind",
"===",
"\"get\"",
"||",
"kind",
"===",
"\"set\"",
")",
"{",
"this",
".",
"push",
"(",
"kind",
"+",
"\" \"",
")",
";",
"}",
"if",
"(",
"value",
".",
"async",
")",
"this",
".",
"push",
"(",
"\"async \"",
")",
";",
"if",
"(",
"node",
".",
"computed",
")",
"{",
"this",
".",
"push",
"(",
"\"[\"",
")",
";",
"print",
".",
"plain",
"(",
"key",
")",
";",
"this",
".",
"push",
"(",
"\"]\"",
")",
";",
"}",
"else",
"{",
"print",
".",
"plain",
"(",
"key",
")",
";",
"}",
"this",
".",
"_params",
"(",
"value",
",",
"print",
")",
";",
"this",
".",
"space",
"(",
")",
";",
"print",
".",
"plain",
"(",
"value",
".",
"body",
")",
";",
"}"
]
| Prints method-like nodes, prints key, value, and body, handles async, generator, computed, and get or set. | [
"Prints",
"method",
"-",
"like",
"nodes",
"prints",
"key",
"value",
"and",
"body",
"handles",
"async",
"generator",
"computed",
"and",
"get",
"or",
"set",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/methods.js#L46-L74 | train |
noderaider/repackage | jspm_packages/npm/[email protected]/lib/generation/generators/methods.js | ArrowFunctionExpression | function ArrowFunctionExpression(node, print) {
if (node.async) this.push("async ");
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
print.plain(node.params[0]);
} else {
this._params(node, print);
}
this.push(" => ");
var bodyNeedsParens = t.isObjectExpression(node.body);
if (bodyNeedsParens) {
this.push("(");
}
print.plain(node.body);
if (bodyNeedsParens) {
this.push(")");
}
} | javascript | function ArrowFunctionExpression(node, print) {
if (node.async) this.push("async ");
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
print.plain(node.params[0]);
} else {
this._params(node, print);
}
this.push(" => ");
var bodyNeedsParens = t.isObjectExpression(node.body);
if (bodyNeedsParens) {
this.push("(");
}
print.plain(node.body);
if (bodyNeedsParens) {
this.push(")");
}
} | [
"function",
"ArrowFunctionExpression",
"(",
"node",
",",
"print",
")",
"{",
"if",
"(",
"node",
".",
"async",
")",
"this",
".",
"push",
"(",
"\"async \"",
")",
";",
"if",
"(",
"node",
".",
"params",
".",
"length",
"===",
"1",
"&&",
"t",
".",
"isIdentifier",
"(",
"node",
".",
"params",
"[",
"0",
"]",
")",
")",
"{",
"print",
".",
"plain",
"(",
"node",
".",
"params",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"this",
".",
"_params",
"(",
"node",
",",
"print",
")",
";",
"}",
"this",
".",
"push",
"(",
"\" => \"",
")",
";",
"var",
"bodyNeedsParens",
"=",
"t",
".",
"isObjectExpression",
"(",
"node",
".",
"body",
")",
";",
"if",
"(",
"bodyNeedsParens",
")",
"{",
"this",
".",
"push",
"(",
"\"(\"",
")",
";",
"}",
"print",
".",
"plain",
"(",
"node",
".",
"body",
")",
";",
"if",
"(",
"bodyNeedsParens",
")",
"{",
"this",
".",
"push",
"(",
"\")\"",
")",
";",
"}",
"}"
]
| Prints ArrowFunctionExpression, prints params and body, handles async.
Leaves out parentheses when single param. | [
"Prints",
"ArrowFunctionExpression",
"prints",
"params",
"and",
"body",
"handles",
"async",
".",
"Leaves",
"out",
"parentheses",
"when",
"single",
"param",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/methods.js#L108-L130 | train |
Kaniwani/KanaWana | src/packages/kanawana/utils/isCharJapanesePunctuation.js | isCharJapanesePunctuation | function isCharJapanesePunctuation(char = '') {
return JAPANESE_FULLWIDTH_PUNCTUATION_RANGES.some(([start, end]) => isCharInRange(char, start, end));
} | javascript | function isCharJapanesePunctuation(char = '') {
return JAPANESE_FULLWIDTH_PUNCTUATION_RANGES.some(([start, end]) => isCharInRange(char, start, end));
} | [
"function",
"isCharJapanesePunctuation",
"(",
"char",
"=",
"''",
")",
"{",
"return",
"JAPANESE_FULLWIDTH_PUNCTUATION_RANGES",
".",
"some",
"(",
"(",
"[",
"start",
",",
"end",
"]",
")",
"=>",
"isCharInRange",
"(",
"char",
",",
"start",
",",
"end",
")",
")",
";",
"}"
]
| Tests a character. Returns true if the character is considered Japanese punctuation.
@param {String} char character string to test
@return {Boolean} | [
"Tests",
"a",
"character",
".",
"Returns",
"true",
"if",
"the",
"character",
"is",
"considered",
"Japanese",
"punctuation",
"."
]
| 7084d6c50e68023c225f663f994544f693ff8d3a | https://github.com/Kaniwani/KanaWana/blob/7084d6c50e68023c225f663f994544f693ff8d3a/src/packages/kanawana/utils/isCharJapanesePunctuation.js#L9-L11 | train |
samcday/node-clusterphone | clusterphone.js | constructMessageApi | function constructMessageApi(namespace, cmd, destName, seq) {
var api = {},
valid = true,
timeout = module.exports.ackTimeout,
resolve,
reject;
var promise = new Promise(function(_resolve, _reject) {
resolve = _resolve;
reject = _reject;
});
setImmediate(function() {
valid = false;
});
api.within = function(newTimeout) {
if (!valid) {
throw new Error("within() / acknowledged() calls are only valid immediately after sending a message.");
}
if (resolve.monitored) {
throw new Error("within() must be called *before* acknowledged()");
}
if ("number" !== typeof newTimeout) {
newTimeout = parseInt(newTimeout, 10);
}
if(!newTimeout) {
throw new Error("Timeout must be a number");
}
timeout = newTimeout;
return api;
};
api.acknowledged = function(cb) {
if (!valid) {
throw new Error("within() / acknowledged() calls are only valid immediately after sending a message.");
}
// This flag indicates that the caller does actually care about the resolution of this acknowledgement.
resolve.monitored = true;
return promise.timeout(timeout)
.catch(Promise.TimeoutError, function() {
// We retrieve the pending here to ensure it's deleted.
namespace.getPending(seq);
throw new Error("Timed out waiting for acknowledgement for message " + cmd + " with seq " + seq + " to " + destName + " in namespace " + namespace.interface.name);
})
.nodeify(cb);
};
api.ackd = api.acknowledged;
return [api, resolve, reject];
} | javascript | function constructMessageApi(namespace, cmd, destName, seq) {
var api = {},
valid = true,
timeout = module.exports.ackTimeout,
resolve,
reject;
var promise = new Promise(function(_resolve, _reject) {
resolve = _resolve;
reject = _reject;
});
setImmediate(function() {
valid = false;
});
api.within = function(newTimeout) {
if (!valid) {
throw new Error("within() / acknowledged() calls are only valid immediately after sending a message.");
}
if (resolve.monitored) {
throw new Error("within() must be called *before* acknowledged()");
}
if ("number" !== typeof newTimeout) {
newTimeout = parseInt(newTimeout, 10);
}
if(!newTimeout) {
throw new Error("Timeout must be a number");
}
timeout = newTimeout;
return api;
};
api.acknowledged = function(cb) {
if (!valid) {
throw new Error("within() / acknowledged() calls are only valid immediately after sending a message.");
}
// This flag indicates that the caller does actually care about the resolution of this acknowledgement.
resolve.monitored = true;
return promise.timeout(timeout)
.catch(Promise.TimeoutError, function() {
// We retrieve the pending here to ensure it's deleted.
namespace.getPending(seq);
throw new Error("Timed out waiting for acknowledgement for message " + cmd + " with seq " + seq + " to " + destName + " in namespace " + namespace.interface.name);
})
.nodeify(cb);
};
api.ackd = api.acknowledged;
return [api, resolve, reject];
} | [
"function",
"constructMessageApi",
"(",
"namespace",
",",
"cmd",
",",
"destName",
",",
"seq",
")",
"{",
"var",
"api",
"=",
"{",
"}",
",",
"valid",
"=",
"true",
",",
"timeout",
"=",
"module",
".",
"exports",
".",
"ackTimeout",
",",
"resolve",
",",
"reject",
";",
"var",
"promise",
"=",
"new",
"Promise",
"(",
"function",
"(",
"_resolve",
",",
"_reject",
")",
"{",
"resolve",
"=",
"_resolve",
";",
"reject",
"=",
"_reject",
";",
"}",
")",
";",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"valid",
"=",
"false",
";",
"}",
")",
";",
"api",
".",
"within",
"=",
"function",
"(",
"newTimeout",
")",
"{",
"if",
"(",
"!",
"valid",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"within() / acknowledged() calls are only valid immediately after sending a message.\"",
")",
";",
"}",
"if",
"(",
"resolve",
".",
"monitored",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"within() must be called *before* acknowledged()\"",
")",
";",
"}",
"if",
"(",
"\"number\"",
"!==",
"typeof",
"newTimeout",
")",
"{",
"newTimeout",
"=",
"parseInt",
"(",
"newTimeout",
",",
"10",
")",
";",
"}",
"if",
"(",
"!",
"newTimeout",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Timeout must be a number\"",
")",
";",
"}",
"timeout",
"=",
"newTimeout",
";",
"return",
"api",
";",
"}",
";",
"api",
".",
"acknowledged",
"=",
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"!",
"valid",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"within() / acknowledged() calls are only valid immediately after sending a message.\"",
")",
";",
"}",
"resolve",
".",
"monitored",
"=",
"true",
";",
"return",
"promise",
".",
"timeout",
"(",
"timeout",
")",
".",
"catch",
"(",
"Promise",
".",
"TimeoutError",
",",
"function",
"(",
")",
"{",
"namespace",
".",
"getPending",
"(",
"seq",
")",
";",
"throw",
"new",
"Error",
"(",
"\"Timed out waiting for acknowledgement for message \"",
"+",
"cmd",
"+",
"\" with seq \"",
"+",
"seq",
"+",
"\" to \"",
"+",
"destName",
"+",
"\" in namespace \"",
"+",
"namespace",
".",
"interface",
".",
"name",
")",
";",
"}",
")",
".",
"nodeify",
"(",
"cb",
")",
";",
"}",
";",
"api",
".",
"ackd",
"=",
"api",
".",
"acknowledged",
";",
"return",
"[",
"api",
",",
"resolve",
",",
"reject",
"]",
";",
"}"
]
| We use this to prevent callers from obtaining the "clusterphone" namespace. Build the object that we return from sendTo calls. | [
"We",
"use",
"this",
"to",
"prevent",
"callers",
"from",
"obtaining",
"the",
"clusterphone",
"namespace",
".",
"Build",
"the",
"object",
"that",
"we",
"return",
"from",
"sendTo",
"calls",
"."
]
| 01c12f8a4efd737603dedc4fcb972f0ef3a5dfe0 | https://github.com/samcday/node-clusterphone/blob/01c12f8a4efd737603dedc4fcb972f0ef3a5dfe0/clusterphone.js#L27-L78 | train |
samcday/node-clusterphone | clusterphone.js | getWorkerData | function getWorkerData(worker) {
/* istanbul ignore if */
if (!worker) {
throw new TypeError("Trying to get private data for null worker?!");
}
var data = worker[clusterphone.workerDataAccessor];
if (!data) {
worker[clusterphone.workerDataAccessor] = data = {};
}
return data;
} | javascript | function getWorkerData(worker) {
/* istanbul ignore if */
if (!worker) {
throw new TypeError("Trying to get private data for null worker?!");
}
var data = worker[clusterphone.workerDataAccessor];
if (!data) {
worker[clusterphone.workerDataAccessor] = data = {};
}
return data;
} | [
"function",
"getWorkerData",
"(",
"worker",
")",
"{",
"if",
"(",
"!",
"worker",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Trying to get private data for null worker?!\"",
")",
";",
"}",
"var",
"data",
"=",
"worker",
"[",
"clusterphone",
".",
"workerDataAccessor",
"]",
";",
"if",
"(",
"!",
"data",
")",
"{",
"worker",
"[",
"clusterphone",
".",
"workerDataAccessor",
"]",
"=",
"data",
"=",
"{",
"}",
";",
"}",
"return",
"data",
";",
"}"
]
| Gets our private data section from a worker object. | [
"Gets",
"our",
"private",
"data",
"section",
"from",
"a",
"worker",
"object",
"."
]
| 01c12f8a4efd737603dedc4fcb972f0ef3a5dfe0 | https://github.com/samcday/node-clusterphone/blob/01c12f8a4efd737603dedc4fcb972f0ef3a5dfe0/clusterphone.js#L81-L93 | train |
samcday/node-clusterphone | clusterphone.js | function(worker) {
var data = getWorkerNamespacedData(worker);
Object.keys(data.pending).forEach(function(seqNum) {
var item = data.pending[seqNum];
delete data.pending[seqNum];
if (item[0].monitored) {
item[1](new Error("Undeliverable message: worker died before we could get acknowledgement"));
}
});
} | javascript | function(worker) {
var data = getWorkerNamespacedData(worker);
Object.keys(data.pending).forEach(function(seqNum) {
var item = data.pending[seqNum];
delete data.pending[seqNum];
if (item[0].monitored) {
item[1](new Error("Undeliverable message: worker died before we could get acknowledgement"));
}
});
} | [
"function",
"(",
"worker",
")",
"{",
"var",
"data",
"=",
"getWorkerNamespacedData",
"(",
"worker",
")",
";",
"Object",
".",
"keys",
"(",
"data",
".",
"pending",
")",
".",
"forEach",
"(",
"function",
"(",
"seqNum",
")",
"{",
"var",
"item",
"=",
"data",
".",
"pending",
"[",
"seqNum",
"]",
";",
"delete",
"data",
".",
"pending",
"[",
"seqNum",
"]",
";",
"if",
"(",
"item",
"[",
"0",
"]",
".",
"monitored",
")",
"{",
"item",
"[",
"1",
"]",
"(",
"new",
"Error",
"(",
"\"Undeliverable message: worker died before we could get acknowledgement\"",
")",
")",
";",
"}",
"}",
")",
";",
"}"
]
| If a worker dies, fail any monitored ack deferreds. | [
"If",
"a",
"worker",
"dies",
"fail",
"any",
"monitored",
"ack",
"deferreds",
"."
]
| 01c12f8a4efd737603dedc4fcb972f0ef3a5dfe0 | https://github.com/samcday/node-clusterphone/blob/01c12f8a4efd737603dedc4fcb972f0ef3a5dfe0/clusterphone.js#L221-L231 | train |
|
fcingolani/hubot-game-idea | lib/generator.js | random | function random(arr) {
if(!arr) { return false; }
if(!arr.length) {
arr = Object.keys(arr);
}
return arr[Math.floor(Math.random() * arr.length)];
} | javascript | function random(arr) {
if(!arr) { return false; }
if(!arr.length) {
arr = Object.keys(arr);
}
return arr[Math.floor(Math.random() * arr.length)];
} | [
"function",
"random",
"(",
"arr",
")",
"{",
"if",
"(",
"!",
"arr",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"arr",
".",
"length",
")",
"{",
"arr",
"=",
"Object",
".",
"keys",
"(",
"arr",
")",
";",
"}",
"return",
"arr",
"[",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"arr",
".",
"length",
")",
"]",
";",
"}"
]
| return a random element from an array
or random key from an object | [
"return",
"a",
"random",
"element",
"from",
"an",
"array",
"or",
"random",
"key",
"from",
"an",
"object"
]
| 46f24fdff6bdd1d2f91ee66d4f787cc88a173c43 | https://github.com/fcingolani/hubot-game-idea/blob/46f24fdff6bdd1d2f91ee66d4f787cc88a173c43/lib/generator.js#L126-L134 | train |
fcingolani/hubot-game-idea | lib/generator.js | function(type) {
if(!type || !data[type]) {
type = random(data);
}
var templates = data[type].templates;
var template = random(templates);
var compiled = Handlebars.compile(template);
var rendered = compiled(data);
// get rid of multiple, leading and trailing spaces
rendered = rendered.replace(/ +(?= )/g,'').trim();
return capitaliseFirstLetter( rendered );
} | javascript | function(type) {
if(!type || !data[type]) {
type = random(data);
}
var templates = data[type].templates;
var template = random(templates);
var compiled = Handlebars.compile(template);
var rendered = compiled(data);
// get rid of multiple, leading and trailing spaces
rendered = rendered.replace(/ +(?= )/g,'').trim();
return capitaliseFirstLetter( rendered );
} | [
"function",
"(",
"type",
")",
"{",
"if",
"(",
"!",
"type",
"||",
"!",
"data",
"[",
"type",
"]",
")",
"{",
"type",
"=",
"random",
"(",
"data",
")",
";",
"}",
"var",
"templates",
"=",
"data",
"[",
"type",
"]",
".",
"templates",
";",
"var",
"template",
"=",
"random",
"(",
"templates",
")",
";",
"var",
"compiled",
"=",
"Handlebars",
".",
"compile",
"(",
"template",
")",
";",
"var",
"rendered",
"=",
"compiled",
"(",
"data",
")",
";",
"rendered",
"=",
"rendered",
".",
"replace",
"(",
"/",
" +(?= )",
"/",
"g",
",",
"''",
")",
".",
"trim",
"(",
")",
";",
"return",
"capitaliseFirstLetter",
"(",
"rendered",
")",
";",
"}"
]
| generate a random game idea | [
"generate",
"a",
"random",
"game",
"idea"
]
| 46f24fdff6bdd1d2f91ee66d4f787cc88a173c43 | https://github.com/fcingolani/hubot-game-idea/blob/46f24fdff6bdd1d2f91ee66d4f787cc88a173c43/lib/generator.js#L149-L164 | train |
|
vadimdemedes/stable-node-version | index.js | stableNodeVersion | function stableNodeVersion () {
// thanks to github.com/tj/n
var versionRegex = /[0-9]+\.[0-9]*[02468]\.[0-9]+/;
return got('https://nodejs.org/dist/')
.then(function (res) {
var response = res.body
.split('\n')
.filter(function (line) {
return /\<\/a\>/.test(line);
})
.filter(function (line) {
return versionRegex.test(line);
})
.map(function (line) {
return versionRegex.exec(line)[0];
});
response.sort(function (a, b) {
return semver.gt(a, b);
});
response.reverse();
var version = response[0];
return version;
});
} | javascript | function stableNodeVersion () {
// thanks to github.com/tj/n
var versionRegex = /[0-9]+\.[0-9]*[02468]\.[0-9]+/;
return got('https://nodejs.org/dist/')
.then(function (res) {
var response = res.body
.split('\n')
.filter(function (line) {
return /\<\/a\>/.test(line);
})
.filter(function (line) {
return versionRegex.test(line);
})
.map(function (line) {
return versionRegex.exec(line)[0];
});
response.sort(function (a, b) {
return semver.gt(a, b);
});
response.reverse();
var version = response[0];
return version;
});
} | [
"function",
"stableNodeVersion",
"(",
")",
"{",
"var",
"versionRegex",
"=",
"/",
"[0-9]+\\.[0-9]*[02468]\\.[0-9]+",
"/",
";",
"return",
"got",
"(",
"'https://nodejs.org/dist/'",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"var",
"response",
"=",
"res",
".",
"body",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"filter",
".",
"(",
"function",
"(",
"line",
")",
"{",
"return",
"/",
"\\<\\/a\\>",
"/",
".",
"test",
"(",
"line",
")",
";",
"}",
")",
"filter",
".",
"(",
"function",
"(",
"line",
")",
"{",
"return",
"versionRegex",
".",
"test",
"(",
"line",
")",
";",
"}",
")",
"map",
";",
"(",
"function",
"(",
"line",
")",
"{",
"return",
"versionRegex",
".",
"exec",
"(",
"line",
")",
"[",
"0",
"]",
";",
"}",
")",
"response",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"semver",
".",
"gt",
"(",
"a",
",",
"b",
")",
";",
"}",
")",
";",
"response",
".",
"reverse",
"(",
")",
";",
"var",
"version",
"=",
"response",
"[",
"0",
"]",
";",
"}",
")",
";",
"}"
]
| Fetch stable Node.js version | [
"Fetch",
"stable",
"Node",
".",
"js",
"version"
]
| 1168b628317c3fccb1014dd17511c4688b306ab8 | https://github.com/vadimdemedes/stable-node-version/blob/1168b628317c3fccb1014dd17511c4688b306ab8/index.js#L22-L50 | train |
skazska/nanoDSA | small-numbers.js | factorizeArray | function factorizeArray(n) {
let factors = [];
factorize(n, factor => {
factors.push(factor);
});
return factors;
} | javascript | function factorizeArray(n) {
let factors = [];
factorize(n, factor => {
factors.push(factor);
});
return factors;
} | [
"function",
"factorizeArray",
"(",
"n",
")",
"{",
"let",
"factors",
"=",
"[",
"]",
";",
"factorize",
"(",
"n",
",",
"factor",
"=>",
"{",
"factors",
".",
"push",
"(",
"factor",
")",
";",
"}",
")",
";",
"return",
"factors",
";",
"}"
]
| returns all prime multipliers in array
@param n
@returns {Array} | [
"returns",
"all",
"prime",
"multipliers",
"in",
"array"
]
| 0fa053b4b09d7a18d0fcceee150652af6c5bc50c | https://github.com/skazska/nanoDSA/blob/0fa053b4b09d7a18d0fcceee150652af6c5bc50c/small-numbers.js#L85-L91 | train |
skazska/nanoDSA | small-numbers.js | factorizeHash | function factorizeHash(n) {
let factors = {};
factorize(n, factor => {
if (factors[factor]) {
factors[factor] += 1;
} else {
factors[factor] = 1;
}
});
return factors;
} | javascript | function factorizeHash(n) {
let factors = {};
factorize(n, factor => {
if (factors[factor]) {
factors[factor] += 1;
} else {
factors[factor] = 1;
}
});
return factors;
} | [
"function",
"factorizeHash",
"(",
"n",
")",
"{",
"let",
"factors",
"=",
"{",
"}",
";",
"factorize",
"(",
"n",
",",
"factor",
"=>",
"{",
"if",
"(",
"factors",
"[",
"factor",
"]",
")",
"{",
"factors",
"[",
"factor",
"]",
"+=",
"1",
";",
"}",
"else",
"{",
"factors",
"[",
"factor",
"]",
"=",
"1",
";",
"}",
"}",
")",
";",
"return",
"factors",
";",
"}"
]
| returns multipliers as counts in hash
@param n | [
"returns",
"multipliers",
"as",
"counts",
"in",
"hash"
]
| 0fa053b4b09d7a18d0fcceee150652af6c5bc50c | https://github.com/skazska/nanoDSA/blob/0fa053b4b09d7a18d0fcceee150652af6c5bc50c/small-numbers.js#L97-L107 | train |
MaximeMaillet/dtorrent | src/utils/torrent.js | getDataTorrentFromFile | function getDataTorrentFromFile(torrentFile) {
if(!fs.existsSync(torrentFile)) {
throw new Error(`This torrent file does not exists : ${torrentFile}`);
}
const torrent = parseTorrent(fs.readFileSync(torrentFile));
torrent.path = torrentFile;
torrent.hash = torrent.infoHash.toUpperCase();
return torrent;
} | javascript | function getDataTorrentFromFile(torrentFile) {
if(!fs.existsSync(torrentFile)) {
throw new Error(`This torrent file does not exists : ${torrentFile}`);
}
const torrent = parseTorrent(fs.readFileSync(torrentFile));
torrent.path = torrentFile;
torrent.hash = torrent.infoHash.toUpperCase();
return torrent;
} | [
"function",
"getDataTorrentFromFile",
"(",
"torrentFile",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"torrentFile",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"torrentFile",
"}",
"`",
")",
";",
"}",
"const",
"torrent",
"=",
"parseTorrent",
"(",
"fs",
".",
"readFileSync",
"(",
"torrentFile",
")",
")",
";",
"torrent",
".",
"path",
"=",
"torrentFile",
";",
"torrent",
".",
"hash",
"=",
"torrent",
".",
"infoHash",
".",
"toUpperCase",
"(",
")",
";",
"return",
"torrent",
";",
"}"
]
| Read torrent content then return result
@param torrentFile
@return {Object} | [
"Read",
"torrent",
"content",
"then",
"return",
"result"
]
| ed7fdd8e8959a4f30f9a2f1afa3ec17c64bc5535 | https://github.com/MaximeMaillet/dtorrent/blob/ed7fdd8e8959a4f30f9a2f1afa3ec17c64bc5535/src/utils/torrent.js#L9-L18 | train |
kevoree/kevoree-js | tools/kevoree-scripts/scripts/build.js | browserBuild | function browserBuild(config) {
const compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
return reject(new Error(messages.errors.join('\n\n')));
}
return resolve({ stats, warnings: messages.warnings });
});
});
} | javascript | function browserBuild(config) {
const compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
return reject(new Error(messages.errors.join('\n\n')));
}
return resolve({ stats, warnings: messages.warnings });
});
});
} | [
"function",
"browserBuild",
"(",
"config",
")",
"{",
"const",
"compiler",
"=",
"webpack",
"(",
"config",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"compiler",
".",
"run",
"(",
"(",
"err",
",",
"stats",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"const",
"messages",
"=",
"formatWebpackMessages",
"(",
"stats",
".",
"toJson",
"(",
"{",
"}",
",",
"true",
")",
")",
";",
"if",
"(",
"messages",
".",
"errors",
".",
"length",
")",
"{",
"return",
"reject",
"(",
"new",
"Error",
"(",
"messages",
".",
"errors",
".",
"join",
"(",
"'\\n\\n'",
")",
")",
")",
";",
"}",
"\\n",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Create the browser build | [
"Create",
"the",
"browser",
"build"
]
| 7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd | https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-scripts/scripts/build.js#L94-L108 | train |
fibo/algebra-cyclic | index.js | isPrime | function isPrime (n) {
if (n === 1) return false
if (n === 2) return true
var m = Math.sqrt(n)
for (var i = 2; i <= m; i++) if (n % i === 0) return false
return true
} | javascript | function isPrime (n) {
if (n === 1) return false
if (n === 2) return true
var m = Math.sqrt(n)
for (var i = 2; i <= m; i++) if (n % i === 0) return false
return true
} | [
"function",
"isPrime",
"(",
"n",
")",
"{",
"if",
"(",
"n",
"===",
"1",
")",
"return",
"false",
"if",
"(",
"n",
"===",
"2",
")",
"return",
"true",
"var",
"m",
"=",
"Math",
".",
"sqrt",
"(",
"n",
")",
"for",
"(",
"var",
"i",
"=",
"2",
";",
"i",
"<=",
"m",
";",
"i",
"++",
")",
"if",
"(",
"n",
"%",
"i",
"===",
"0",
")",
"return",
"false",
"return",
"true",
"}"
]
| Check if a number is prime
@param {Number} n
@returns {Boolean} | [
"Check",
"if",
"a",
"number",
"is",
"prime"
]
| 1c003be0d5480bcd09e1b7efba34650e1a21c2d3 | https://github.com/fibo/algebra-cyclic/blob/1c003be0d5480bcd09e1b7efba34650e1a21c2d3/index.js#L29-L38 | train |
fibo/algebra-cyclic | index.js | unique | function unique (elements) {
for (var i = 0; i < elements.length - 1; i++) {
for (var j = i + 1; j < elements.length; j++) {
if (elements[i] === elements[j]) return false
}
}
return true
} | javascript | function unique (elements) {
for (var i = 0; i < elements.length - 1; i++) {
for (var j = i + 1; j < elements.length; j++) {
if (elements[i] === elements[j]) return false
}
}
return true
} | [
"function",
"unique",
"(",
"elements",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"elements",
".",
"length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"i",
"+",
"1",
";",
"j",
"<",
"elements",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"elements",
"[",
"i",
"]",
"===",
"elements",
"[",
"j",
"]",
")",
"return",
"false",
"}",
"}",
"return",
"true",
"}"
]
| Check if given elements are unique
@param {Array} elements
@returns {Boolean} | [
"Check",
"if",
"given",
"elements",
"are",
"unique"
]
| 1c003be0d5480bcd09e1b7efba34650e1a21c2d3 | https://github.com/fibo/algebra-cyclic/blob/1c003be0d5480bcd09e1b7efba34650e1a21c2d3/index.js#L48-L56 | train |
131/browserify-reload | index.js | function(host, port) {
var sock = new WebSocket('ws://' + host + ':' + port);
sock.onopen = function() {
console.log("Connected to browserify-reload handle");
}
sock.onmessage = function(msg){
if(msg && msg.data == "reload")
document.location = document.location.href;
}
} | javascript | function(host, port) {
var sock = new WebSocket('ws://' + host + ':' + port);
sock.onopen = function() {
console.log("Connected to browserify-reload handle");
}
sock.onmessage = function(msg){
if(msg && msg.data == "reload")
document.location = document.location.href;
}
} | [
"function",
"(",
"host",
",",
"port",
")",
"{",
"var",
"sock",
"=",
"new",
"WebSocket",
"(",
"'ws://'",
"+",
"host",
"+",
"':'",
"+",
"port",
")",
";",
"sock",
".",
"onopen",
"=",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"\"Connected to browserify-reload handle\"",
")",
";",
"}",
"sock",
".",
"onmessage",
"=",
"function",
"(",
"msg",
")",
"{",
"if",
"(",
"msg",
"&&",
"msg",
".",
"data",
"==",
"\"reload\"",
")",
"document",
".",
"location",
"=",
"document",
".",
"location",
".",
"href",
";",
"}",
"}"
]
| this code is serialized and injected client-side as it might not be processed by browserify transform, keep it ES5 | [
"this",
"code",
"is",
"serialized",
"and",
"injected",
"client",
"-",
"side",
"as",
"it",
"might",
"not",
"be",
"processed",
"by",
"browserify",
"transform",
"keep",
"it",
"ES5"
]
| b8a94df091d653dd8852e50be9beb99608f314f5 | https://github.com/131/browserify-reload/blob/b8a94df091d653dd8852e50be9beb99608f314f5/index.js#L11-L21 | train |
|
Bartvds/minitable | lib/core.js | getBlock | function getBlock(handle) {
var block = {
handle: handle,
rows: []
};
blocks.push(block);
return block;
} | javascript | function getBlock(handle) {
var block = {
handle: handle,
rows: []
};
blocks.push(block);
return block;
} | [
"function",
"getBlock",
"(",
"handle",
")",
"{",
"var",
"block",
"=",
"{",
"handle",
":",
"handle",
",",
"rows",
":",
"[",
"]",
"}",
";",
"blocks",
".",
"push",
"(",
"block",
")",
";",
"return",
"block",
";",
"}"
]
| a block of rows written by a handle | [
"a",
"block",
"of",
"rows",
"written",
"by",
"a",
"handle"
]
| 7b666ed40dd6b331fcabcc6b1f9c273ad6cd6e0e | https://github.com/Bartvds/minitable/blob/7b666ed40dd6b331fcabcc6b1f9c273ad6cd6e0e/lib/core.js#L66-L73 | train |
Bartvds/minitable | lib/core.js | getRowChainHeads | function getRowChainHeads(collumns) {
var row = Object.create(null);
Object.keys(collumns).forEach(function (name) {
row[name] = minichain.getMultiChain({
plain: {
write: miniwrite.buffer(),
style: ministyle.plain()
},
display: {
write: miniwrite.buffer(),
style: style
}
});
});
return row;
} | javascript | function getRowChainHeads(collumns) {
var row = Object.create(null);
Object.keys(collumns).forEach(function (name) {
row[name] = minichain.getMultiChain({
plain: {
write: miniwrite.buffer(),
style: ministyle.plain()
},
display: {
write: miniwrite.buffer(),
style: style
}
});
});
return row;
} | [
"function",
"getRowChainHeads",
"(",
"collumns",
")",
"{",
"var",
"row",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"Object",
".",
"keys",
"(",
"collumns",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"row",
"[",
"name",
"]",
"=",
"minichain",
".",
"getMultiChain",
"(",
"{",
"plain",
":",
"{",
"write",
":",
"miniwrite",
".",
"buffer",
"(",
")",
",",
"style",
":",
"ministyle",
".",
"plain",
"(",
")",
"}",
",",
"display",
":",
"{",
"write",
":",
"miniwrite",
".",
"buffer",
"(",
")",
",",
"style",
":",
"style",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"row",
";",
"}"
]
| get a minichain-multiChain to write both plain text as well as a 'fancy' text lines version of each cell | [
"get",
"a",
"minichain",
"-",
"multiChain",
"to",
"write",
"both",
"plain",
"text",
"as",
"well",
"as",
"a",
"fancy",
"text",
"lines",
"version",
"of",
"each",
"cell"
]
| 7b666ed40dd6b331fcabcc6b1f9c273ad6cd6e0e | https://github.com/Bartvds/minitable/blob/7b666ed40dd6b331fcabcc6b1f9c273ad6cd6e0e/lib/core.js#L76-L91 | train |
ssbc/graphreduce | index.js | randomNode | function randomNode (g) {
var keys = Object.keys(g)
return keys[~~(keys.length*Math.random())]
} | javascript | function randomNode (g) {
var keys = Object.keys(g)
return keys[~~(keys.length*Math.random())]
} | [
"function",
"randomNode",
"(",
"g",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"g",
")",
"return",
"keys",
"[",
"~",
"~",
"(",
"keys",
".",
"length",
"*",
"Math",
".",
"random",
"(",
")",
")",
"]",
"}"
]
| get a random node | [
"get",
"a",
"random",
"node"
]
| a553abbb95a2237e98fcebe91fdcd92cc6cb6ea0 | https://github.com/ssbc/graphreduce/blob/a553abbb95a2237e98fcebe91fdcd92cc6cb6ea0/index.js#L39-L42 | train |
ssbc/graphreduce | index.js | addGraph | function addGraph (g1, g2) {
eachEdge(g2, function (from, to, data) {
addEdge(g1, from, to, data)
})
return g1
} | javascript | function addGraph (g1, g2) {
eachEdge(g2, function (from, to, data) {
addEdge(g1, from, to, data)
})
return g1
} | [
"function",
"addGraph",
"(",
"g1",
",",
"g2",
")",
"{",
"eachEdge",
"(",
"g2",
",",
"function",
"(",
"from",
",",
"to",
",",
"data",
")",
"{",
"addEdge",
"(",
"g1",
",",
"from",
",",
"to",
",",
"data",
")",
"}",
")",
"return",
"g1",
"}"
]
| add another subgraph | [
"add",
"another",
"subgraph"
]
| a553abbb95a2237e98fcebe91fdcd92cc6cb6ea0 | https://github.com/ssbc/graphreduce/blob/a553abbb95a2237e98fcebe91fdcd92cc6cb6ea0/index.js#L45-L50 | train |
aureooms/js-heapsort | lib/heapsort.js | dary | function dary(arity) {
/**
* Note that here we reverse the order of the
* comparison operator since when we extract
* values from the heap they can only be stored
* at the end of the array. We thus build a max-heap
* and then pop elements from it until it is empty.
*/
var sort = function sort(compare, a, i, j) {
// construct the max-heap
var k = i + 1;
for (; k < j; ++k) {
var current = k - i;
// while we are not the root
while (current !== 0) {
// address of the parent in a zero-based
// d-ary heap
var parent = i + ((current - 1) / arity | 0);
current += i;
// if current value is smaller than its parent
// then we are done
if (compare(a[current], a[parent]) <= 0) {
break;
}
// otherwise
// swap with parent
var tmp = a[current];
a[current] = a[parent];
a[parent] = tmp;
current = parent - i;
}
}
// exhaust the max-heap
for (--k; k > i; --k) {
// put max element at the end of the array
// and percolate new max element down
// the heap
var _tmp = a[k];
a[k] = a[i];
a[i] = _tmp;
var _current = 0;
while (true) {
// address of the first child in a zero-based
// d-ary heap
var candidate = i + arity * _current + 1;
// if current node has no children
// then we are done
if (candidate >= k) {
break;
}
// search for greatest child
var t = Math.min(candidate + arity, k);
var y = candidate;
for (++y; y < t; ++y) {
if (compare(a[y], a[candidate]) > 0) {
candidate = y;
}
}
// if current value is greater than its greatest
// child then we are done
_current += i;
if (compare(a[_current], a[candidate]) >= 0) {
break;
}
// otherwise
// swap with greatest child
var _tmp2 = a[_current];
a[_current] = a[candidate];
a[candidate] = _tmp2;
_current = candidate - i;
}
}
};
return sort;
} | javascript | function dary(arity) {
/**
* Note that here we reverse the order of the
* comparison operator since when we extract
* values from the heap they can only be stored
* at the end of the array. We thus build a max-heap
* and then pop elements from it until it is empty.
*/
var sort = function sort(compare, a, i, j) {
// construct the max-heap
var k = i + 1;
for (; k < j; ++k) {
var current = k - i;
// while we are not the root
while (current !== 0) {
// address of the parent in a zero-based
// d-ary heap
var parent = i + ((current - 1) / arity | 0);
current += i;
// if current value is smaller than its parent
// then we are done
if (compare(a[current], a[parent]) <= 0) {
break;
}
// otherwise
// swap with parent
var tmp = a[current];
a[current] = a[parent];
a[parent] = tmp;
current = parent - i;
}
}
// exhaust the max-heap
for (--k; k > i; --k) {
// put max element at the end of the array
// and percolate new max element down
// the heap
var _tmp = a[k];
a[k] = a[i];
a[i] = _tmp;
var _current = 0;
while (true) {
// address of the first child in a zero-based
// d-ary heap
var candidate = i + arity * _current + 1;
// if current node has no children
// then we are done
if (candidate >= k) {
break;
}
// search for greatest child
var t = Math.min(candidate + arity, k);
var y = candidate;
for (++y; y < t; ++y) {
if (compare(a[y], a[candidate]) > 0) {
candidate = y;
}
}
// if current value is greater than its greatest
// child then we are done
_current += i;
if (compare(a[_current], a[candidate]) >= 0) {
break;
}
// otherwise
// swap with greatest child
var _tmp2 = a[_current];
a[_current] = a[candidate];
a[candidate] = _tmp2;
_current = candidate - i;
}
}
};
return sort;
} | [
"function",
"dary",
"(",
"arity",
")",
"{",
"var",
"sort",
"=",
"function",
"sort",
"(",
"compare",
",",
"a",
",",
"i",
",",
"j",
")",
"{",
"var",
"k",
"=",
"i",
"+",
"1",
";",
"for",
"(",
";",
"k",
"<",
"j",
";",
"++",
"k",
")",
"{",
"var",
"current",
"=",
"k",
"-",
"i",
";",
"while",
"(",
"current",
"!==",
"0",
")",
"{",
"var",
"parent",
"=",
"i",
"+",
"(",
"(",
"current",
"-",
"1",
")",
"/",
"arity",
"|",
"0",
")",
";",
"current",
"+=",
"i",
";",
"if",
"(",
"compare",
"(",
"a",
"[",
"current",
"]",
",",
"a",
"[",
"parent",
"]",
")",
"<=",
"0",
")",
"{",
"break",
";",
"}",
"var",
"tmp",
"=",
"a",
"[",
"current",
"]",
";",
"a",
"[",
"current",
"]",
"=",
"a",
"[",
"parent",
"]",
";",
"a",
"[",
"parent",
"]",
"=",
"tmp",
";",
"current",
"=",
"parent",
"-",
"i",
";",
"}",
"}",
"for",
"(",
"--",
"k",
";",
"k",
">",
"i",
";",
"--",
"k",
")",
"{",
"var",
"_tmp",
"=",
"a",
"[",
"k",
"]",
";",
"a",
"[",
"k",
"]",
"=",
"a",
"[",
"i",
"]",
";",
"a",
"[",
"i",
"]",
"=",
"_tmp",
";",
"var",
"_current",
"=",
"0",
";",
"while",
"(",
"true",
")",
"{",
"var",
"candidate",
"=",
"i",
"+",
"arity",
"*",
"_current",
"+",
"1",
";",
"if",
"(",
"candidate",
">=",
"k",
")",
"{",
"break",
";",
"}",
"var",
"t",
"=",
"Math",
".",
"min",
"(",
"candidate",
"+",
"arity",
",",
"k",
")",
";",
"var",
"y",
"=",
"candidate",
";",
"for",
"(",
"++",
"y",
";",
"y",
"<",
"t",
";",
"++",
"y",
")",
"{",
"if",
"(",
"compare",
"(",
"a",
"[",
"y",
"]",
",",
"a",
"[",
"candidate",
"]",
")",
">",
"0",
")",
"{",
"candidate",
"=",
"y",
";",
"}",
"}",
"_current",
"+=",
"i",
";",
"if",
"(",
"compare",
"(",
"a",
"[",
"_current",
"]",
",",
"a",
"[",
"candidate",
"]",
")",
">=",
"0",
")",
"{",
"break",
";",
"}",
"var",
"_tmp2",
"=",
"a",
"[",
"_current",
"]",
";",
"a",
"[",
"_current",
"]",
"=",
"a",
"[",
"candidate",
"]",
";",
"a",
"[",
"candidate",
"]",
"=",
"_tmp2",
";",
"_current",
"=",
"candidate",
"-",
"i",
";",
"}",
"}",
"}",
";",
"return",
"sort",
";",
"}"
]
| Template for a d-ary implementation of heapsort. | [
"Template",
"for",
"a",
"d",
"-",
"ary",
"implementation",
"of",
"heapsort",
"."
]
| dc6eac5bc1a8024b0b9971694380604d9c6e4756 | https://github.com/aureooms/js-heapsort/blob/dc6eac5bc1a8024b0b9971694380604d9c6e4756/lib/heapsort.js#L14-L125 | train |
ZeroNetJS/zeronet-crypto | src/key/index.js | sign | function sign (privateKey, data) {
const pair = ECPair.fromWIF(privateKey)
return btcMessage.sign(data, pair.d.toBuffer(32), pair.compressed).toString('base64')
} | javascript | function sign (privateKey, data) {
const pair = ECPair.fromWIF(privateKey)
return btcMessage.sign(data, pair.d.toBuffer(32), pair.compressed).toString('base64')
} | [
"function",
"sign",
"(",
"privateKey",
",",
"data",
")",
"{",
"const",
"pair",
"=",
"ECPair",
".",
"fromWIF",
"(",
"privateKey",
")",
"return",
"btcMessage",
".",
"sign",
"(",
"data",
",",
"pair",
".",
"d",
".",
"toBuffer",
"(",
"32",
")",
",",
"pair",
".",
"compressed",
")",
".",
"toString",
"(",
"'base64'",
")",
"}"
]
| Signs data with a bitcoin signature
@param {string} privateKey - Bitcoin private key in WIF formate
@param {string} data - Data to sign
@return {string} - Base64 encoded signature | [
"Signs",
"data",
"with",
"a",
"bitcoin",
"signature"
]
| 56498a5b79983fd401b9aa5ea9c314957b4a29a5 | https://github.com/ZeroNetJS/zeronet-crypto/blob/56498a5b79983fd401b9aa5ea9c314957b4a29a5/src/key/index.js#L25-L28 | train |
ZeroNetJS/zeronet-crypto | src/key/index.js | constructValidSigners | function constructValidSigners (address, inner_path, data) {
let valid_signers = []
if (inner_path === 'content.json') {
if (data.signers) valid_signers = Object.keys(data.signers)
} else {
// TODO: multi-user
}
if (valid_signers.indexOf(address) === -1) valid_signers.push(address) // Address is always a valid signer
return valid_signers
} | javascript | function constructValidSigners (address, inner_path, data) {
let valid_signers = []
if (inner_path === 'content.json') {
if (data.signers) valid_signers = Object.keys(data.signers)
} else {
// TODO: multi-user
}
if (valid_signers.indexOf(address) === -1) valid_signers.push(address) // Address is always a valid signer
return valid_signers
} | [
"function",
"constructValidSigners",
"(",
"address",
",",
"inner_path",
",",
"data",
")",
"{",
"let",
"valid_signers",
"=",
"[",
"]",
"if",
"(",
"inner_path",
"===",
"'content.json'",
")",
"{",
"if",
"(",
"data",
".",
"signers",
")",
"valid_signers",
"=",
"Object",
".",
"keys",
"(",
"data",
".",
"signers",
")",
"}",
"else",
"{",
"}",
"if",
"(",
"valid_signers",
".",
"indexOf",
"(",
"address",
")",
"===",
"-",
"1",
")",
"valid_signers",
".",
"push",
"(",
"address",
")",
"return",
"valid_signers",
"}"
]
| Gets the valid signers for a file based on it's path and address
Will be soon deperacted in favor of zeronet-auth
@param {string} address - The address of the zie
@param {string} inner_path - The path of the content.json file
@param {object} data - The content.json contents as object
@return {array} - Array of valid signers | [
"Gets",
"the",
"valid",
"signers",
"for",
"a",
"file",
"based",
"on",
"it",
"s",
"path",
"and",
"address",
"Will",
"be",
"soon",
"deperacted",
"in",
"favor",
"of",
"zeronet",
"-",
"auth"
]
| 56498a5b79983fd401b9aa5ea9c314957b4a29a5 | https://github.com/ZeroNetJS/zeronet-crypto/blob/56498a5b79983fd401b9aa5ea9c314957b4a29a5/src/key/index.js#L38-L47 | train |
kubosho/kotori | src/stats.js | selectFormat | function selectFormat(format) {
let method = "toTable";
let extension = `.${format}`;
switch (format) {
case "json":
method = "toJSON";
break;
case "csv":
method = "toCSV";
break;
case "html":
method = "toHTML";
break;
case "md":
method = "toMarkdown";
break;
default:
break;
}
return {
extension: extension,
method: method
}
} | javascript | function selectFormat(format) {
let method = "toTable";
let extension = `.${format}`;
switch (format) {
case "json":
method = "toJSON";
break;
case "csv":
method = "toCSV";
break;
case "html":
method = "toHTML";
break;
case "md":
method = "toMarkdown";
break;
default:
break;
}
return {
extension: extension,
method: method
}
} | [
"function",
"selectFormat",
"(",
"format",
")",
"{",
"let",
"method",
"=",
"\"toTable\"",
";",
"let",
"extension",
"=",
"`",
"${",
"format",
"}",
"`",
";",
"switch",
"(",
"format",
")",
"{",
"case",
"\"json\"",
":",
"method",
"=",
"\"toJSON\"",
";",
"break",
";",
"case",
"\"csv\"",
":",
"method",
"=",
"\"toCSV\"",
";",
"break",
";",
"case",
"\"html\"",
":",
"method",
"=",
"\"toHTML\"",
";",
"break",
";",
"case",
"\"md\"",
":",
"method",
"=",
"\"toMarkdown\"",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"return",
"{",
"extension",
":",
"extension",
",",
"method",
":",
"method",
"}",
"}"
]
| Select CSS statistics data format
@param {String} format
@returns {{extension: String, method: String}}
@private | [
"Select",
"CSS",
"statistics",
"data",
"format"
]
| 4a869d470408db17733caf9dabe67ecaa20cf4b7 | https://github.com/kubosho/kotori/blob/4a869d470408db17733caf9dabe67ecaa20cf4b7/src/stats.js#L87-L112 | train |
mgsisk/postcss-modular-rhythm | src/index.js | modularScale | function modularScale(power, ratio, bases) {
const scale = []
let step = 0
while (Math.abs(step) <= Math.abs(power)) {
for (let i = 0; i < bases.length; i++) {
scale.push(bases[i] * Math.pow(ratio, step))
}
step += 1
if (power < 0) {
step -= 2
}
}
return Array.from(new Set(scale))[Math.abs(step) - 1] // eslint-disable-line no-undef
} | javascript | function modularScale(power, ratio, bases) {
const scale = []
let step = 0
while (Math.abs(step) <= Math.abs(power)) {
for (let i = 0; i < bases.length; i++) {
scale.push(bases[i] * Math.pow(ratio, step))
}
step += 1
if (power < 0) {
step -= 2
}
}
return Array.from(new Set(scale))[Math.abs(step) - 1] // eslint-disable-line no-undef
} | [
"function",
"modularScale",
"(",
"power",
",",
"ratio",
",",
"bases",
")",
"{",
"const",
"scale",
"=",
"[",
"]",
"let",
"step",
"=",
"0",
"while",
"(",
"Math",
".",
"abs",
"(",
"step",
")",
"<=",
"Math",
".",
"abs",
"(",
"power",
")",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"bases",
".",
"length",
";",
"i",
"++",
")",
"{",
"scale",
".",
"push",
"(",
"bases",
"[",
"i",
"]",
"*",
"Math",
".",
"pow",
"(",
"ratio",
",",
"step",
")",
")",
"}",
"step",
"+=",
"1",
"if",
"(",
"power",
"<",
"0",
")",
"{",
"step",
"-=",
"2",
"}",
"}",
"return",
"Array",
".",
"from",
"(",
"new",
"Set",
"(",
"scale",
")",
")",
"[",
"Math",
".",
"abs",
"(",
"step",
")",
"-",
"1",
"]",
"}"
]
| Calculate a modular scale value.
@param {number} power The power of the modular scale value.
@param {number} ratio The modular scale ratio.
@param {Array} bases One or more modular scale bases.
@returns {number} | [
"Calculate",
"a",
"modular",
"scale",
"value",
"."
]
| b7d63edfa12021ee3212aebf4fc3cf6040eb2e15 | https://github.com/mgsisk/postcss-modular-rhythm/blob/b7d63edfa12021ee3212aebf4fc3cf6040eb2e15/src/index.js#L11-L28 | train |
mgsisk/postcss-modular-rhythm | src/index.js | lineHeightScale | function lineHeightScale(lineHeight, power, ratio, bases) {
const baseHeight = lineHeight / modularScale(power, ratio, bases)
let realHeight = baseHeight
while (realHeight < 1) {
realHeight += baseHeight
}
return realHeight
} | javascript | function lineHeightScale(lineHeight, power, ratio, bases) {
const baseHeight = lineHeight / modularScale(power, ratio, bases)
let realHeight = baseHeight
while (realHeight < 1) {
realHeight += baseHeight
}
return realHeight
} | [
"function",
"lineHeightScale",
"(",
"lineHeight",
",",
"power",
",",
"ratio",
",",
"bases",
")",
"{",
"const",
"baseHeight",
"=",
"lineHeight",
"/",
"modularScale",
"(",
"power",
",",
"ratio",
",",
"bases",
")",
"let",
"realHeight",
"=",
"baseHeight",
"while",
"(",
"realHeight",
"<",
"1",
")",
"{",
"realHeight",
"+=",
"baseHeight",
"}",
"return",
"realHeight",
"}"
]
| Calculate a unitless line height for a given modular scale.
@param {number} lineHeight The base, unitless line height.
@param {number} power The power of the modular scale value.
@param {number} ratio The modular scale ratio.
@param {Array} bases One or more modular scale bases.
@returns {number} | [
"Calculate",
"a",
"unitless",
"line",
"height",
"for",
"a",
"given",
"modular",
"scale",
"."
]
| b7d63edfa12021ee3212aebf4fc3cf6040eb2e15 | https://github.com/mgsisk/postcss-modular-rhythm/blob/b7d63edfa12021ee3212aebf4fc3cf6040eb2e15/src/index.js#L39-L48 | train |
Kaniwani/KanaWana | src/packages/kanawana/utils/isCharInRange.js | isCharInRange | function isCharInRange(char = '', start, end) {
if (isEmpty(char)) return false;
const code = char.charCodeAt(0);
return start <= code && code <= end;
} | javascript | function isCharInRange(char = '', start, end) {
if (isEmpty(char)) return false;
const code = char.charCodeAt(0);
return start <= code && code <= end;
} | [
"function",
"isCharInRange",
"(",
"char",
"=",
"''",
",",
"start",
",",
"end",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"char",
")",
")",
"return",
"false",
";",
"const",
"code",
"=",
"char",
".",
"charCodeAt",
"(",
"0",
")",
";",
"return",
"start",
"<=",
"code",
"&&",
"code",
"<=",
"end",
";",
"}"
]
| Takes a character and a unicode range. Returns true if the char is in the range.
@param {String} char unicode character
@param {Number} start unicode start range
@param {Number} end unicode end range
@return {Boolean} | [
"Takes",
"a",
"character",
"and",
"a",
"unicode",
"range",
".",
"Returns",
"true",
"if",
"the",
"char",
"is",
"in",
"the",
"range",
"."
]
| 7084d6c50e68023c225f663f994544f693ff8d3a | https://github.com/Kaniwani/KanaWana/blob/7084d6c50e68023c225f663f994544f693ff8d3a/src/packages/kanawana/utils/isCharInRange.js#L10-L14 | train |
McNull/gulp-angular | lib/modules.js | getIncludes | function getIncludes(ext, exclude) {
var globs = [];
modules.forEach(function (module) {
if (!settings.release) {
// Not in release mode:
// Ensure the main module file is included first
globs.push(module.folder + '/' + module.folder + ext);
globs.push(module.folder + '/**/*' + ext);
} else {
// In release mode:
// Include the minified version.
globs.push(module.folder + '/' + module.folder + '.min' + ext);
}
});
var res = gulp.src(globs, {
read: false,
cwd: path.resolve(settings.folders.dest)
});
if (exclude) {
res = res.pipe(gfilter('!**/*' + exclude));
// res = res.pipe(utils.dumpFilePaths());
}
return res;
} | javascript | function getIncludes(ext, exclude) {
var globs = [];
modules.forEach(function (module) {
if (!settings.release) {
// Not in release mode:
// Ensure the main module file is included first
globs.push(module.folder + '/' + module.folder + ext);
globs.push(module.folder + '/**/*' + ext);
} else {
// In release mode:
// Include the minified version.
globs.push(module.folder + '/' + module.folder + '.min' + ext);
}
});
var res = gulp.src(globs, {
read: false,
cwd: path.resolve(settings.folders.dest)
});
if (exclude) {
res = res.pipe(gfilter('!**/*' + exclude));
// res = res.pipe(utils.dumpFilePaths());
}
return res;
} | [
"function",
"getIncludes",
"(",
"ext",
",",
"exclude",
")",
"{",
"var",
"globs",
"=",
"[",
"]",
";",
"modules",
".",
"forEach",
"(",
"function",
"(",
"module",
")",
"{",
"if",
"(",
"!",
"settings",
".",
"release",
")",
"{",
"globs",
".",
"push",
"(",
"module",
".",
"folder",
"+",
"'/'",
"+",
"module",
".",
"folder",
"+",
"ext",
")",
";",
"globs",
".",
"push",
"(",
"module",
".",
"folder",
"+",
"'/**/*'",
"+",
"ext",
")",
";",
"}",
"else",
"{",
"globs",
".",
"push",
"(",
"module",
".",
"folder",
"+",
"'/'",
"+",
"module",
".",
"folder",
"+",
"'.min'",
"+",
"ext",
")",
";",
"}",
"}",
")",
";",
"var",
"res",
"=",
"gulp",
".",
"src",
"(",
"globs",
",",
"{",
"read",
":",
"false",
",",
"cwd",
":",
"path",
".",
"resolve",
"(",
"settings",
".",
"folders",
".",
"dest",
")",
"}",
")",
";",
"if",
"(",
"exclude",
")",
"{",
"res",
"=",
"res",
".",
"pipe",
"(",
"gfilter",
"(",
"'!**/*'",
"+",
"exclude",
")",
")",
";",
"}",
"return",
"res",
";",
"}"
]
| - - - - 8-< - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | [
"-",
"-",
"-",
"-",
"8",
"-",
"<",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-"
]
| e41b659a4b4ee5ff6e8eecda8395e2e88829162f | https://github.com/McNull/gulp-angular/blob/e41b659a4b4ee5ff6e8eecda8395e2e88829162f/lib/modules.js#L253-L286 | train |
CollinearGroup/smart-deep-sort | lib/index.js | sortObject | function sortObject(originalSrc, options, done) {
var callback
if (options === undefined) {
// do nothing
} else if (typeof options === "function") {
callback = options
} else {
callback = done
}
if (callback) {
process.nextTick(function() {
done(work(originalSrc))
})
return
}
function work(obj) {
try {
// Uses module to sort all objects key names based on standard
// string ordering.
var deepSorted = deep_sort_object(obj)
// Once object keys are sorted, we still need to check for arrays.
var out = deepInspect(deepSorted)
return out
} catch (e) {
console.log(e)
throw e
}
}
return work(originalSrc)
} | javascript | function sortObject(originalSrc, options, done) {
var callback
if (options === undefined) {
// do nothing
} else if (typeof options === "function") {
callback = options
} else {
callback = done
}
if (callback) {
process.nextTick(function() {
done(work(originalSrc))
})
return
}
function work(obj) {
try {
// Uses module to sort all objects key names based on standard
// string ordering.
var deepSorted = deep_sort_object(obj)
// Once object keys are sorted, we still need to check for arrays.
var out = deepInspect(deepSorted)
return out
} catch (e) {
console.log(e)
throw e
}
}
return work(originalSrc)
} | [
"function",
"sortObject",
"(",
"originalSrc",
",",
"options",
",",
"done",
")",
"{",
"var",
"callback",
"if",
"(",
"options",
"===",
"undefined",
")",
"{",
"}",
"else",
"if",
"(",
"typeof",
"options",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"options",
"}",
"else",
"{",
"callback",
"=",
"done",
"}",
"if",
"(",
"callback",
")",
"{",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"done",
"(",
"work",
"(",
"originalSrc",
")",
")",
"}",
")",
"return",
"}",
"function",
"work",
"(",
"obj",
")",
"{",
"try",
"{",
"var",
"deepSorted",
"=",
"deep_sort_object",
"(",
"obj",
")",
"var",
"out",
"=",
"deepInspect",
"(",
"deepSorted",
")",
"return",
"out",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"e",
")",
"throw",
"e",
"}",
"}",
"return",
"work",
"(",
"originalSrc",
")",
"}"
]
| Will return a deep sorted version of the object. | [
"Will",
"return",
"a",
"deep",
"sorted",
"version",
"of",
"the",
"object",
"."
]
| 42b0ea0c991c62fd421de4013521fe3a95a2f0c1 | https://github.com/CollinearGroup/smart-deep-sort/blob/42b0ea0c991c62fd421de4013521fe3a95a2f0c1/lib/index.js#L12-L46 | train |
CollinearGroup/smart-deep-sort | lib/index.js | deepInspect | function deepInspect(the_object) {
var out = the_object
if (getConstructorName(the_object) === "Array") {
out = keyCompare(out)
} else if (getConstructorName(the_object) === "Object") {
Object.keys(out).forEach(function(key) {
if (_.isArray(out[key])) {
out[key] = keyCompare(out[key])
} else if (_.isObject(out[key])) {
out[key] = deepInspect(out[key])
} else {
// do nothing.
}
})
}
return out
} | javascript | function deepInspect(the_object) {
var out = the_object
if (getConstructorName(the_object) === "Array") {
out = keyCompare(out)
} else if (getConstructorName(the_object) === "Object") {
Object.keys(out).forEach(function(key) {
if (_.isArray(out[key])) {
out[key] = keyCompare(out[key])
} else if (_.isObject(out[key])) {
out[key] = deepInspect(out[key])
} else {
// do nothing.
}
})
}
return out
} | [
"function",
"deepInspect",
"(",
"the_object",
")",
"{",
"var",
"out",
"=",
"the_object",
"if",
"(",
"getConstructorName",
"(",
"the_object",
")",
"===",
"\"Array\"",
")",
"{",
"out",
"=",
"keyCompare",
"(",
"out",
")",
"}",
"else",
"if",
"(",
"getConstructorName",
"(",
"the_object",
")",
"===",
"\"Object\"",
")",
"{",
"Object",
".",
"keys",
"(",
"out",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"out",
"[",
"key",
"]",
")",
")",
"{",
"out",
"[",
"key",
"]",
"=",
"keyCompare",
"(",
"out",
"[",
"key",
"]",
")",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"out",
"[",
"key",
"]",
")",
")",
"{",
"out",
"[",
"key",
"]",
"=",
"deepInspect",
"(",
"out",
"[",
"key",
"]",
")",
"}",
"else",
"{",
"}",
"}",
")",
"}",
"return",
"out",
"}"
]
| Will recursively inspect the object for arrays that need to be
sorted. | [
"Will",
"recursively",
"inspect",
"the",
"object",
"for",
"arrays",
"that",
"need",
"to",
"be",
"sorted",
"."
]
| 42b0ea0c991c62fd421de4013521fe3a95a2f0c1 | https://github.com/CollinearGroup/smart-deep-sort/blob/42b0ea0c991c62fd421de4013521fe3a95a2f0c1/lib/index.js#L52-L68 | train |
CollinearGroup/smart-deep-sort | lib/index.js | createSortyOpts | function createSortyOpts(keys) {
var result = []
keys.forEach(function(keyName) {
result.push({
name: keyName,
dir: "asc"
})
})
return result
} | javascript | function createSortyOpts(keys) {
var result = []
keys.forEach(function(keyName) {
result.push({
name: keyName,
dir: "asc"
})
})
return result
} | [
"function",
"createSortyOpts",
"(",
"keys",
")",
"{",
"var",
"result",
"=",
"[",
"]",
"keys",
".",
"forEach",
"(",
"function",
"(",
"keyName",
")",
"{",
"result",
".",
"push",
"(",
"{",
"name",
":",
"keyName",
",",
"dir",
":",
"\"asc\"",
"}",
")",
"}",
")",
"return",
"result",
"}"
]
| Creates the sorty module opts from the provided object keys. | [
"Creates",
"the",
"sorty",
"module",
"opts",
"from",
"the",
"provided",
"object",
"keys",
"."
]
| 42b0ea0c991c62fd421de4013521fe3a95a2f0c1 | https://github.com/CollinearGroup/smart-deep-sort/blob/42b0ea0c991c62fd421de4013521fe3a95a2f0c1/lib/index.js#L146-L155 | train |
myelements/myelements.jquery | lib/index.js | attachToHttpServer | function attachToHttpServer(httpServer, onConnectionCallback) {
// socket.io
var socketIoOptions = extend({}, {
path: config.socketPath
});
var sockets = io.listen(httpServer, socketIoOptions);
debug("Attaching to http.Server");
return attachToSocketIo(sockets, onConnectionCallback);
} | javascript | function attachToHttpServer(httpServer, onConnectionCallback) {
// socket.io
var socketIoOptions = extend({}, {
path: config.socketPath
});
var sockets = io.listen(httpServer, socketIoOptions);
debug("Attaching to http.Server");
return attachToSocketIo(sockets, onConnectionCallback);
} | [
"function",
"attachToHttpServer",
"(",
"httpServer",
",",
"onConnectionCallback",
")",
"{",
"var",
"socketIoOptions",
"=",
"extend",
"(",
"{",
"}",
",",
"{",
"path",
":",
"config",
".",
"socketPath",
"}",
")",
";",
"var",
"sockets",
"=",
"io",
".",
"listen",
"(",
"httpServer",
",",
"socketIoOptions",
")",
";",
"debug",
"(",
"\"Attaching to http.Server\"",
")",
";",
"return",
"attachToSocketIo",
"(",
"sockets",
",",
"onConnectionCallback",
")",
";",
"}"
]
| Listen for socket.io events on httpServer.
@param {http.Server} httpServer. The server to attach socket.io to.
@param {Function} onConnectionCallback. Called when a socket client connects.
- @param {Error} err. Null if nothing bad happened.
- @param {EventEmitter} client. Event client. | [
"Listen",
"for",
"socket",
".",
"io",
"events",
"on",
"httpServer",
"."
]
| 0123edec30fc70ea494611695b5b2593e4f23745 | https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/index.js#L79-L88 | train |
myelements/myelements.jquery | lib/index.js | onClientConnection | function onClientConnection(clientSocket, onConnectionCallback) {
var elementsEventHandler = new ElementsEventHandler(clientSocket);
elementsEventHandler.session = clientSocket.handshake.session;
debug("client connection");
clientSocket.trigger = trigger.bind(clientSocket);
//clientSocket.broadcast.trigger = broadcast.bind(clientSocket);
clientSocket.on.message = onmessage.bind(clientSocket);
onConnectionCallback(null, elementsEventHandler);
elementsEventHandler.on("disconnect", function deleteElementsEventHandler() {
elementsEventHandler = undefined;
});
} | javascript | function onClientConnection(clientSocket, onConnectionCallback) {
var elementsEventHandler = new ElementsEventHandler(clientSocket);
elementsEventHandler.session = clientSocket.handshake.session;
debug("client connection");
clientSocket.trigger = trigger.bind(clientSocket);
//clientSocket.broadcast.trigger = broadcast.bind(clientSocket);
clientSocket.on.message = onmessage.bind(clientSocket);
onConnectionCallback(null, elementsEventHandler);
elementsEventHandler.on("disconnect", function deleteElementsEventHandler() {
elementsEventHandler = undefined;
});
} | [
"function",
"onClientConnection",
"(",
"clientSocket",
",",
"onConnectionCallback",
")",
"{",
"var",
"elementsEventHandler",
"=",
"new",
"ElementsEventHandler",
"(",
"clientSocket",
")",
";",
"elementsEventHandler",
".",
"session",
"=",
"clientSocket",
".",
"handshake",
".",
"session",
";",
"debug",
"(",
"\"client connection\"",
")",
";",
"clientSocket",
".",
"trigger",
"=",
"trigger",
".",
"bind",
"(",
"clientSocket",
")",
";",
"clientSocket",
".",
"on",
".",
"message",
"=",
"onmessage",
".",
"bind",
"(",
"clientSocket",
")",
";",
"onConnectionCallback",
"(",
"null",
",",
"elementsEventHandler",
")",
";",
"elementsEventHandler",
".",
"on",
"(",
"\"disconnect\"",
",",
"function",
"deleteElementsEventHandler",
"(",
")",
"{",
"elementsEventHandler",
"=",
"undefined",
";",
"}",
")",
";",
"}"
]
| Handles a new myelements client connection.
@param {socket}. client socket for the new connection
@param {Function} onConnectionCallback. called after socket.io connection event
- @param {Error} err. Null if nothing bad happened.
- @param {ElementsEventHandler} elementsEventHandler. An instance
of myelements client's event handler. | [
"Handles",
"a",
"new",
"myelements",
"client",
"connection",
"."
]
| 0123edec30fc70ea494611695b5b2593e4f23745 | https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/index.js#L119-L131 | train |
myelements/myelements.jquery | lib/index.js | trigger | function trigger(event, data) {
// Warn if someone tries to trigger a message but the client socket
// has already disconnected
if (this.disconnected) {
debug("Trying to trigger client socket but client is disconnected");
return;
}
// If the broadcast flag is set, call to this.broadcast.send
if (this.flags && this.flags.broadcast) {
debug("Broadcasting %s to frontend clients, with data: %j.", event, data);
this.broadcast.send({
"event": event,
"data": data
});
} else {
debug("Triggering: %s on frontend with data: %j.", event, data);
this.send({
"event": event,
"data": data
});
}
} | javascript | function trigger(event, data) {
// Warn if someone tries to trigger a message but the client socket
// has already disconnected
if (this.disconnected) {
debug("Trying to trigger client socket but client is disconnected");
return;
}
// If the broadcast flag is set, call to this.broadcast.send
if (this.flags && this.flags.broadcast) {
debug("Broadcasting %s to frontend clients, with data: %j.", event, data);
this.broadcast.send({
"event": event,
"data": data
});
} else {
debug("Triggering: %s on frontend with data: %j.", event, data);
this.send({
"event": event,
"data": data
});
}
} | [
"function",
"trigger",
"(",
"event",
",",
"data",
")",
"{",
"if",
"(",
"this",
".",
"disconnected",
")",
"{",
"debug",
"(",
"\"Trying to trigger client socket but client is disconnected\"",
")",
";",
"return",
";",
"}",
"if",
"(",
"this",
".",
"flags",
"&&",
"this",
".",
"flags",
".",
"broadcast",
")",
"{",
"debug",
"(",
"\"Broadcasting %s to frontend clients, with data: %j.\"",
",",
"event",
",",
"data",
")",
";",
"this",
".",
"broadcast",
".",
"send",
"(",
"{",
"\"event\"",
":",
"event",
",",
"\"data\"",
":",
"data",
"}",
")",
";",
"}",
"else",
"{",
"debug",
"(",
"\"Triggering: %s on frontend with data: %j.\"",
",",
"event",
",",
"data",
")",
";",
"this",
".",
"send",
"(",
"{",
"\"event\"",
":",
"event",
",",
"\"data\"",
":",
"data",
"}",
")",
";",
"}",
"}"
]
| Triggers a message event that gets sent to the client
@param {String} Message event to send to the client
@param {Object} data to send to with the message | [
"Triggers",
"a",
"message",
"event",
"that",
"gets",
"sent",
"to",
"the",
"client"
]
| 0123edec30fc70ea494611695b5b2593e4f23745 | https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/index.js#L187-L209 | train |
tonylukasavage/grunt-titanium | tasks/titanium.js | killer | function killer(data) {
grunt.log.write(data);
if (ti.killed) {
return;
} else if (success && success(data)) {
ti.kill();
grunt.log.ok('titanium run successful');
} else if (failure && failure(data)) {
ti.kill();
grunt.fail.warn('titanium run failed');
}
} | javascript | function killer(data) {
grunt.log.write(data);
if (ti.killed) {
return;
} else if (success && success(data)) {
ti.kill();
grunt.log.ok('titanium run successful');
} else if (failure && failure(data)) {
ti.kill();
grunt.fail.warn('titanium run failed');
}
} | [
"function",
"killer",
"(",
"data",
")",
"{",
"grunt",
".",
"log",
".",
"write",
"(",
"data",
")",
";",
"if",
"(",
"ti",
".",
"killed",
")",
"{",
"return",
";",
"}",
"else",
"if",
"(",
"success",
"&&",
"success",
"(",
"data",
")",
")",
"{",
"ti",
".",
"kill",
"(",
")",
";",
"grunt",
".",
"log",
".",
"ok",
"(",
"'titanium run successful'",
")",
";",
"}",
"else",
"if",
"(",
"failure",
"&&",
"failure",
"(",
"data",
")",
")",
"{",
"ti",
".",
"kill",
"(",
")",
";",
"grunt",
".",
"fail",
".",
"warn",
"(",
"'titanium run failed'",
")",
";",
"}",
"}"
]
| prepare functions for killing this process | [
"prepare",
"functions",
"for",
"killing",
"this",
"process"
]
| bb4f9f6085a358699eb116a18f0cdc6627009eee | https://github.com/tonylukasavage/grunt-titanium/blob/bb4f9f6085a358699eb116a18f0cdc6627009eee/tasks/titanium.js#L259-L270 | train |
tonylukasavage/grunt-titanium | tasks/titanium.js | ensureLogin | function ensureLogin(callback) {
exec('"' + getTitaniumPath() + '" status -o json', function(err, stdout, stderr) {
if (err) { return callback(err); }
if (!JSON.parse(stdout).loggedIn) {
grunt.fail.fatal([
'You must be logged in to use grunt-titanium. Use `titanium login`.'
]);
}
return callback();
});
} | javascript | function ensureLogin(callback) {
exec('"' + getTitaniumPath() + '" status -o json', function(err, stdout, stderr) {
if (err) { return callback(err); }
if (!JSON.parse(stdout).loggedIn) {
grunt.fail.fatal([
'You must be logged in to use grunt-titanium. Use `titanium login`.'
]);
}
return callback();
});
} | [
"function",
"ensureLogin",
"(",
"callback",
")",
"{",
"exec",
"(",
"'\"'",
"+",
"getTitaniumPath",
"(",
")",
"+",
"'\" status -o json'",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"JSON",
".",
"parse",
"(",
"stdout",
")",
".",
"loggedIn",
")",
"{",
"grunt",
".",
"fail",
".",
"fatal",
"(",
"[",
"'You must be logged in to use grunt-titanium. Use `titanium login`.'",
"]",
")",
";",
"}",
"return",
"callback",
"(",
")",
";",
"}",
")",
";",
"}"
]
| ensure appc user is logged in | [
"ensure",
"appc",
"user",
"is",
"logged",
"in"
]
| bb4f9f6085a358699eb116a18f0cdc6627009eee | https://github.com/tonylukasavage/grunt-titanium/blob/bb4f9f6085a358699eb116a18f0cdc6627009eee/tasks/titanium.js#L302-L312 | train |
PAI-Tech/PAI-BOT-JS | src/modules-ext/modules-data-sources/mongodb/pai-entity-to-mongo-convertor.js | getMongoModelForEntity | function getMongoModelForEntity(entity) {
const entityName = entity.setEntityName();
if(!models.hasOwnProperty(entity.setEntityName()))
{
models[entityName] = convertPAIEntityToMongoSchema(entity);
PAILogger.info("MongoDB Model just created: " + entityName);
}
return models[entityName];
} | javascript | function getMongoModelForEntity(entity) {
const entityName = entity.setEntityName();
if(!models.hasOwnProperty(entity.setEntityName()))
{
models[entityName] = convertPAIEntityToMongoSchema(entity);
PAILogger.info("MongoDB Model just created: " + entityName);
}
return models[entityName];
} | [
"function",
"getMongoModelForEntity",
"(",
"entity",
")",
"{",
"const",
"entityName",
"=",
"entity",
".",
"setEntityName",
"(",
")",
";",
"if",
"(",
"!",
"models",
".",
"hasOwnProperty",
"(",
"entity",
".",
"setEntityName",
"(",
")",
")",
")",
"{",
"models",
"[",
"entityName",
"]",
"=",
"convertPAIEntityToMongoSchema",
"(",
"entity",
")",
";",
"PAILogger",
".",
"info",
"(",
"\"MongoDB Model just created: \"",
"+",
"entityName",
")",
";",
"}",
"return",
"models",
"[",
"entityName",
"]",
";",
"}"
]
| Get MongoDB Model
@param entity
@return {Model} | [
"Get",
"MongoDB",
"Model"
]
| 7744e54f580e18264861e33f2c05aac58b5ad1d9 | https://github.com/PAI-Tech/PAI-BOT-JS/blob/7744e54f580e18264861e33f2c05aac58b5ad1d9/src/modules-ext/modules-data-sources/mongodb/pai-entity-to-mongo-convertor.js#L77-L89 | train |
skerit/protoblast | lib/object.js | calculate_sizeof | function calculate_sizeof(input, weak_map) {
var bytes,
type = typeof input,
key;
if (type == 'string') {
return input.length * 2;
} else if (type == 'number') {
return 8;
} else if (type == 'boolean') {
return 4;
} else if (type == 'symbol') {
return (input.toString().length - 8) * 2;
} else if (input == null) {
return 0;
}
// If this has already been seen, skip the actual value
if (weak_map.get(input)) {
return 0;
}
weak_map.set(input, true);
if (typeof input[Blast.sizeofSymbol] == 'function') {
try {
return input[Blast.sizeofSymbol]();
} catch (err) {
// Continue;
}
}
bytes = 0;
if (Array.isArray(input)) {
type = 'array';
} else if (Blast.isNode && Buffer.isBuffer(input)) {
return input.length;
}
for (key in input) {
// Skip properties coming from the prototype
if (!Object.hasOwnProperty.call(input, key)) {
continue;
}
// Each entry is a reference to a certain place in the memory,
// on 64bit devices this will be 8 bytes
bytes += 8;
if (type == 'array' && Number(key) > -1) {
// Don't count array indices
} else {
bytes += key.length * 2;
}
bytes += calculate_sizeof(input[key], weak_map);
}
return bytes;
} | javascript | function calculate_sizeof(input, weak_map) {
var bytes,
type = typeof input,
key;
if (type == 'string') {
return input.length * 2;
} else if (type == 'number') {
return 8;
} else if (type == 'boolean') {
return 4;
} else if (type == 'symbol') {
return (input.toString().length - 8) * 2;
} else if (input == null) {
return 0;
}
// If this has already been seen, skip the actual value
if (weak_map.get(input)) {
return 0;
}
weak_map.set(input, true);
if (typeof input[Blast.sizeofSymbol] == 'function') {
try {
return input[Blast.sizeofSymbol]();
} catch (err) {
// Continue;
}
}
bytes = 0;
if (Array.isArray(input)) {
type = 'array';
} else if (Blast.isNode && Buffer.isBuffer(input)) {
return input.length;
}
for (key in input) {
// Skip properties coming from the prototype
if (!Object.hasOwnProperty.call(input, key)) {
continue;
}
// Each entry is a reference to a certain place in the memory,
// on 64bit devices this will be 8 bytes
bytes += 8;
if (type == 'array' && Number(key) > -1) {
// Don't count array indices
} else {
bytes += key.length * 2;
}
bytes += calculate_sizeof(input[key], weak_map);
}
return bytes;
} | [
"function",
"calculate_sizeof",
"(",
"input",
",",
"weak_map",
")",
"{",
"var",
"bytes",
",",
"type",
"=",
"typeof",
"input",
",",
"key",
";",
"if",
"(",
"type",
"==",
"'string'",
")",
"{",
"return",
"input",
".",
"length",
"*",
"2",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'number'",
")",
"{",
"return",
"8",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'boolean'",
")",
"{",
"return",
"4",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'symbol'",
")",
"{",
"return",
"(",
"input",
".",
"toString",
"(",
")",
".",
"length",
"-",
"8",
")",
"*",
"2",
";",
"}",
"else",
"if",
"(",
"input",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"weak_map",
".",
"get",
"(",
"input",
")",
")",
"{",
"return",
"0",
";",
"}",
"weak_map",
".",
"set",
"(",
"input",
",",
"true",
")",
";",
"if",
"(",
"typeof",
"input",
"[",
"Blast",
".",
"sizeofSymbol",
"]",
"==",
"'function'",
")",
"{",
"try",
"{",
"return",
"input",
"[",
"Blast",
".",
"sizeofSymbol",
"]",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}",
"bytes",
"=",
"0",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"{",
"type",
"=",
"'array'",
";",
"}",
"else",
"if",
"(",
"Blast",
".",
"isNode",
"&&",
"Buffer",
".",
"isBuffer",
"(",
"input",
")",
")",
"{",
"return",
"input",
".",
"length",
";",
"}",
"for",
"(",
"key",
"in",
"input",
")",
"{",
"if",
"(",
"!",
"Object",
".",
"hasOwnProperty",
".",
"call",
"(",
"input",
",",
"key",
")",
")",
"{",
"continue",
";",
"}",
"bytes",
"+=",
"8",
";",
"if",
"(",
"type",
"==",
"'array'",
"&&",
"Number",
"(",
"key",
")",
">",
"-",
"1",
")",
"{",
"}",
"else",
"{",
"bytes",
"+=",
"key",
".",
"length",
"*",
"2",
";",
"}",
"bytes",
"+=",
"calculate_sizeof",
"(",
"input",
"[",
"key",
"]",
",",
"weak_map",
")",
";",
"}",
"return",
"bytes",
";",
"}"
]
| Calculate the size of a variable
@author Jelle De Loecker <[email protected]>
@since 0.6.0
@version 0.6.0
@param {Mixed} input
@param {WeakMap} weak_map
@return {Number} | [
"Calculate",
"the",
"size",
"of",
"a",
"variable"
]
| 22f35b05611bd507d380782023179a3f6ec383ae | https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/object.js#L264-L326 | train |
skerit/protoblast | lib/object.js | flatten_object | function flatten_object(obj, divider, level, flatten_arrays) {
var divider_start,
divider_end,
new_key,
result = {},
temp,
key,
sub;
if (level == null) {
level = 0;
}
if (!divider) {
divider_start = '.';
} else if (typeof divider == 'string') {
divider_start = divider;
} else if (Array.isArray(divider)) {
divider_start = divider[0];
divider_end = divider[1];
}
if (flatten_arrays == null) {
flatten_arrays = true;
}
for (key in obj) {
// Only flatten own properties
if (!obj.hasOwnProperty(key)) continue;
if (Obj.isPlainObject(obj[key]) || (flatten_arrays && Array.isArray(obj[key]))) {
temp = flatten_object(obj[key], divider, level + 1, flatten_arrays);
// Inject the keys of the sub-object into the result
for (sub in temp) {
// Again: skip prototype properties
if (!temp.hasOwnProperty(sub)) continue;
if (divider_end) {
new_key = key;
// The root does not have an end divider:
// For example: root[child]
if (level) {
new_key += divider_end;
}
new_key += divider_start + sub;
// If we're back in the root,
// make sure it has an ending divider
if (!level) {
new_key += divider_end;
}
} else {
new_key = key + divider_start + sub;
}
result[new_key] = temp[sub];
}
} else if (Obj.isPrimitiveObject(obj[key])) {
// Convert object form of primitives to their primitive values
result[key] = obj[key].valueOf();
} else {
result[key] = obj[key];
}
}
return result;
} | javascript | function flatten_object(obj, divider, level, flatten_arrays) {
var divider_start,
divider_end,
new_key,
result = {},
temp,
key,
sub;
if (level == null) {
level = 0;
}
if (!divider) {
divider_start = '.';
} else if (typeof divider == 'string') {
divider_start = divider;
} else if (Array.isArray(divider)) {
divider_start = divider[0];
divider_end = divider[1];
}
if (flatten_arrays == null) {
flatten_arrays = true;
}
for (key in obj) {
// Only flatten own properties
if (!obj.hasOwnProperty(key)) continue;
if (Obj.isPlainObject(obj[key]) || (flatten_arrays && Array.isArray(obj[key]))) {
temp = flatten_object(obj[key], divider, level + 1, flatten_arrays);
// Inject the keys of the sub-object into the result
for (sub in temp) {
// Again: skip prototype properties
if (!temp.hasOwnProperty(sub)) continue;
if (divider_end) {
new_key = key;
// The root does not have an end divider:
// For example: root[child]
if (level) {
new_key += divider_end;
}
new_key += divider_start + sub;
// If we're back in the root,
// make sure it has an ending divider
if (!level) {
new_key += divider_end;
}
} else {
new_key = key + divider_start + sub;
}
result[new_key] = temp[sub];
}
} else if (Obj.isPrimitiveObject(obj[key])) {
// Convert object form of primitives to their primitive values
result[key] = obj[key].valueOf();
} else {
result[key] = obj[key];
}
}
return result;
} | [
"function",
"flatten_object",
"(",
"obj",
",",
"divider",
",",
"level",
",",
"flatten_arrays",
")",
"{",
"var",
"divider_start",
",",
"divider_end",
",",
"new_key",
",",
"result",
"=",
"{",
"}",
",",
"temp",
",",
"key",
",",
"sub",
";",
"if",
"(",
"level",
"==",
"null",
")",
"{",
"level",
"=",
"0",
";",
"}",
"if",
"(",
"!",
"divider",
")",
"{",
"divider_start",
"=",
"'.'",
";",
"}",
"else",
"if",
"(",
"typeof",
"divider",
"==",
"'string'",
")",
"{",
"divider_start",
"=",
"divider",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"divider",
")",
")",
"{",
"divider_start",
"=",
"divider",
"[",
"0",
"]",
";",
"divider_end",
"=",
"divider",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"flatten_arrays",
"==",
"null",
")",
"{",
"flatten_arrays",
"=",
"true",
";",
"}",
"for",
"(",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"continue",
";",
"if",
"(",
"Obj",
".",
"isPlainObject",
"(",
"obj",
"[",
"key",
"]",
")",
"||",
"(",
"flatten_arrays",
"&&",
"Array",
".",
"isArray",
"(",
"obj",
"[",
"key",
"]",
")",
")",
")",
"{",
"temp",
"=",
"flatten_object",
"(",
"obj",
"[",
"key",
"]",
",",
"divider",
",",
"level",
"+",
"1",
",",
"flatten_arrays",
")",
";",
"for",
"(",
"sub",
"in",
"temp",
")",
"{",
"if",
"(",
"!",
"temp",
".",
"hasOwnProperty",
"(",
"sub",
")",
")",
"continue",
";",
"if",
"(",
"divider_end",
")",
"{",
"new_key",
"=",
"key",
";",
"if",
"(",
"level",
")",
"{",
"new_key",
"+=",
"divider_end",
";",
"}",
"new_key",
"+=",
"divider_start",
"+",
"sub",
";",
"if",
"(",
"!",
"level",
")",
"{",
"new_key",
"+=",
"divider_end",
";",
"}",
"}",
"else",
"{",
"new_key",
"=",
"key",
"+",
"divider_start",
"+",
"sub",
";",
"}",
"result",
"[",
"new_key",
"]",
"=",
"temp",
"[",
"sub",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"Obj",
".",
"isPrimitiveObject",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
".",
"valueOf",
"(",
")",
";",
"}",
"else",
"{",
"result",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"result",
";",
"}"
]
| Flatten an object
@author Jelle De Loecker <[email protected]>
@since 0.1.2
@version 0.5.8
@param {Object} obj The object to flatten
@param {String|Array} divider The divider to use (.)
@param {Number} level
@param {Boolean} flatten_arrays (true)
@return {Object} | [
"Flatten",
"an",
"object"
]
| 22f35b05611bd507d380782023179a3f6ec383ae | https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/object.js#L370-L443 | train |
icelab/viewloader | index.js | getElements | function getElements(node, attr) {
return Array.prototype.slice.call(node.querySelectorAll("[" + attr + "]"));
} | javascript | function getElements(node, attr) {
return Array.prototype.slice.call(node.querySelectorAll("[" + attr + "]"));
} | [
"function",
"getElements",
"(",
"node",
",",
"attr",
")",
"{",
"return",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"node",
".",
"querySelectorAll",
"(",
"\"[\"",
"+",
"attr",
"+",
"\"]\"",
")",
")",
";",
"}"
]
| getElements
Return an array of elements, or an empty array;
@param {Element} node - an element to scope the query to
@param {String} attr
@return {Array} | [
"getElements",
"Return",
"an",
"array",
"of",
"elements",
"or",
"an",
"empty",
"array",
";"
]
| 48a78c09515fe6840465ac8673b0f0e94c68d54a | https://github.com/icelab/viewloader/blob/48a78c09515fe6840465ac8673b0f0e94c68d54a/index.js#L9-L11 | train |
icelab/viewloader | index.js | parseProps | function parseProps(value) {
var pattern = /^{/;
if (pattern.test(value)) {
value = JSON.parse(value);
}
return value;
} | javascript | function parseProps(value) {
var pattern = /^{/;
if (pattern.test(value)) {
value = JSON.parse(value);
}
return value;
} | [
"function",
"parseProps",
"(",
"value",
")",
"{",
"var",
"pattern",
"=",
"/",
"^{",
"/",
";",
"if",
"(",
"pattern",
".",
"test",
"(",
"value",
")",
")",
"{",
"value",
"=",
"JSON",
".",
"parse",
"(",
"value",
")",
";",
"}",
"return",
"value",
";",
"}"
]
| parseProps
Return the value of the data-attribute
Parse the value if it looks like an object
@param {String} value
@return {String} value | [
"parseProps",
"Return",
"the",
"value",
"of",
"the",
"data",
"-",
"attribute",
"Parse",
"the",
"value",
"if",
"it",
"looks",
"like",
"an",
"object"
]
| 48a78c09515fe6840465ac8673b0f0e94c68d54a | https://github.com/icelab/viewloader/blob/48a78c09515fe6840465ac8673b0f0e94c68d54a/index.js#L33-L39 | train |
icelab/viewloader | index.js | checkElement | function checkElement(node, attr, includeScope) {
var elements = getElements(node, attr);
if (includeScope && node.hasAttribute(attr)) {
elements.push(node);
}
return elements;
} | javascript | function checkElement(node, attr, includeScope) {
var elements = getElements(node, attr);
if (includeScope && node.hasAttribute(attr)) {
elements.push(node);
}
return elements;
} | [
"function",
"checkElement",
"(",
"node",
",",
"attr",
",",
"includeScope",
")",
"{",
"var",
"elements",
"=",
"getElements",
"(",
"node",
",",
"attr",
")",
";",
"if",
"(",
"includeScope",
"&&",
"node",
".",
"hasAttribute",
"(",
"attr",
")",
")",
"{",
"elements",
".",
"push",
"(",
"node",
")",
";",
"}",
"return",
"elements",
";",
"}"
]
| checkElement
Get an array of elements for a node.
return elements
@param {Element} node
@param {String} attr
@param {Boolean} includeScope
@return {Array} | [
"checkElement",
"Get",
"an",
"array",
"of",
"elements",
"for",
"a",
"node",
".",
"return",
"elements"
]
| 48a78c09515fe6840465ac8673b0f0e94c68d54a | https://github.com/icelab/viewloader/blob/48a78c09515fe6840465ac8673b0f0e94c68d54a/index.js#L51-L59 | train |
icelab/viewloader | index.js | callViewFunction | function callViewFunction(viewFunction, viewAttr, el) {
return viewFunction.call(this, el, parseProps(el.getAttribute(viewAttr)));
} | javascript | function callViewFunction(viewFunction, viewAttr, el) {
return viewFunction.call(this, el, parseProps(el.getAttribute(viewAttr)));
} | [
"function",
"callViewFunction",
"(",
"viewFunction",
",",
"viewAttr",
",",
"el",
")",
"{",
"return",
"viewFunction",
".",
"call",
"(",
"this",
",",
"el",
",",
"parseProps",
"(",
"el",
".",
"getAttribute",
"(",
"viewAttr",
")",
")",
")",
";",
"}"
]
| callViewFunction
Call the associated function for this specific view
Passing in the element and the value of the data attribute
@param {Function} viewFunction
@param {String} viewAttr - data view attribute name: data-view-my-bar-chart
@param {Element} el | [
"callViewFunction",
"Call",
"the",
"associated",
"function",
"for",
"this",
"specific",
"view",
"Passing",
"in",
"the",
"element",
"and",
"the",
"value",
"of",
"the",
"data",
"attribute"
]
| 48a78c09515fe6840465ac8673b0f0e94c68d54a | https://github.com/icelab/viewloader/blob/48a78c09515fe6840465ac8673b0f0e94c68d54a/index.js#L70-L72 | train |
zipscene/objtools | lib/object-mask.js | sanitizeFalsies | function sanitizeFalsies(obj) {
var key;
if (!obj._) {
delete obj._;
for (key in obj) {
if (obj[key] === false) delete obj[key];
}
}
return obj;
} | javascript | function sanitizeFalsies(obj) {
var key;
if (!obj._) {
delete obj._;
for (key in obj) {
if (obj[key] === false) delete obj[key];
}
}
return obj;
} | [
"function",
"sanitizeFalsies",
"(",
"obj",
")",
"{",
"var",
"key",
";",
"if",
"(",
"!",
"obj",
".",
"_",
")",
"{",
"delete",
"obj",
".",
"_",
";",
"for",
"(",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
"[",
"key",
"]",
"===",
"false",
")",
"delete",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"obj",
";",
"}"
]
| shallowly removes falsey keys if obj does not have a wildcard | [
"shallowly",
"removes",
"falsey",
"keys",
"if",
"obj",
"does",
"not",
"have",
"a",
"wildcard"
]
| 24b5ddf1a079561b978e9e131e14fa8bec19f9ae | https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/object-mask.js#L389-L398 | train |
rm-rf-etc/encore | internal/e_helpers_process.js | fail | function fail (msg, lvl, typ, req) {
var msg = msg || 'No error message was defined for this condition.'
var err
if ( !_.isUndefined(typ) )
err = new typ(msg)
else
err = new ReferenceError(msg)
err.lvl = lvl || 1
func(err)
} | javascript | function fail (msg, lvl, typ, req) {
var msg = msg || 'No error message was defined for this condition.'
var err
if ( !_.isUndefined(typ) )
err = new typ(msg)
else
err = new ReferenceError(msg)
err.lvl = lvl || 1
func(err)
} | [
"function",
"fail",
"(",
"msg",
",",
"lvl",
",",
"typ",
",",
"req",
")",
"{",
"var",
"msg",
"=",
"msg",
"||",
"'No error message was defined for this condition.'",
"var",
"err",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"typ",
")",
")",
"err",
"=",
"new",
"typ",
"(",
"msg",
")",
"else",
"err",
"=",
"new",
"ReferenceError",
"(",
"msg",
")",
"err",
".",
"lvl",
"=",
"lvl",
"||",
"1",
"func",
"(",
"err",
")",
"}"
]
| public
Call this when everything goes really wrong.
@method fail
@for systemLogger
@param msg {String} text that will go into the error.
@param lvl {Number} level value that will go into the error.
@param typ {Error} optional, include if you don't want a ReferenceError.
@param req {Error} optional, for future integration with node server. | [
"public",
"Call",
"this",
"when",
"everything",
"goes",
"really",
"wrong",
"."
]
| 09262df0bd85dc3378c765d1d18e9621c248ccb4 | https://github.com/rm-rf-etc/encore/blob/09262df0bd85dc3378c765d1d18e9621c248ccb4/internal/e_helpers_process.js#L26-L38 | train |
stezu/node-stream | lib/modifiers/pluck.js | pluck | function pluck(property) {
var matcher = _.property(property);
return map(function (chunk, next) {
if (!_.isString(property) && !_.isNumber(property)) {
return next(new TypeError('Expected `property` to be a string or a number.'));
}
return next(null, matcher(chunk));
});
} | javascript | function pluck(property) {
var matcher = _.property(property);
return map(function (chunk, next) {
if (!_.isString(property) && !_.isNumber(property)) {
return next(new TypeError('Expected `property` to be a string or a number.'));
}
return next(null, matcher(chunk));
});
} | [
"function",
"pluck",
"(",
"property",
")",
"{",
"var",
"matcher",
"=",
"_",
".",
"property",
"(",
"property",
")",
";",
"return",
"map",
"(",
"function",
"(",
"chunk",
",",
"next",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"property",
")",
"&&",
"!",
"_",
".",
"isNumber",
"(",
"property",
")",
")",
"{",
"return",
"next",
"(",
"new",
"TypeError",
"(",
"'Expected `property` to be a string or a number.'",
")",
")",
";",
"}",
"return",
"next",
"(",
"null",
",",
"matcher",
"(",
"chunk",
")",
")",
";",
"}",
")",
";",
"}"
]
| Creates a new stream with the output composed of the plucked property
from each item in the source stream.
@static
@since 1.3.0
@category Modifiers
@param {String|Number} property - A property name that will be plucked from
each item in the source stream.
@returns {Stream.Transform} - Transform stream.
@example
// get the value of the "age" property for every item in the stream
objStream // => [{ name: 'pam', age: 24 }, { name: 'joe', age: 30 }])
.pipe(nodeStream.pluck('age'))
// => [24, 30] | [
"Creates",
"a",
"new",
"stream",
"with",
"the",
"output",
"composed",
"of",
"the",
"plucked",
"property",
"from",
"each",
"item",
"in",
"the",
"source",
"stream",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/pluck.js#L24-L35 | train |
nathggns/uri.js | dist/uri.js.js | function(url) {
// If the URL is an object with toString, do that
if (typeof url === 'object' && typeof url.toString === 'function') {
url = url.toString();
}
var query_string;
// If the url does not have a query, return a blank string
if (url.indexOf('?') === -1 && url.indexOf('=') === -1) {
query_string = '';
} else {
var parts = url.split('?');
var part = parts.slice(parts.length === 1 ? 0 : 1);
query_string = '?' + part.join('?').split('#')[0];
}
return query_string;
} | javascript | function(url) {
// If the URL is an object with toString, do that
if (typeof url === 'object' && typeof url.toString === 'function') {
url = url.toString();
}
var query_string;
// If the url does not have a query, return a blank string
if (url.indexOf('?') === -1 && url.indexOf('=') === -1) {
query_string = '';
} else {
var parts = url.split('?');
var part = parts.slice(parts.length === 1 ? 0 : 1);
query_string = '?' + part.join('?').split('#')[0];
}
return query_string;
} | [
"function",
"(",
"url",
")",
"{",
"if",
"(",
"typeof",
"url",
"===",
"'object'",
"&&",
"typeof",
"url",
".",
"toString",
"===",
"'function'",
")",
"{",
"url",
"=",
"url",
".",
"toString",
"(",
")",
";",
"}",
"var",
"query_string",
";",
"if",
"(",
"url",
".",
"indexOf",
"(",
"'?'",
")",
"===",
"-",
"1",
"&&",
"url",
".",
"indexOf",
"(",
"'='",
")",
"===",
"-",
"1",
")",
"{",
"query_string",
"=",
"''",
";",
"}",
"else",
"{",
"var",
"parts",
"=",
"url",
".",
"split",
"(",
"'?'",
")",
";",
"var",
"part",
"=",
"parts",
".",
"slice",
"(",
"parts",
".",
"length",
"===",
"1",
"?",
"0",
":",
"1",
")",
";",
"query_string",
"=",
"'?'",
"+",
"part",
".",
"join",
"(",
"'?'",
")",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
";",
"}",
"return",
"query_string",
";",
"}"
]
| Extract a query string from a url
@param {string} url The url
@return {string} The extracted query string | [
"Extract",
"a",
"query",
"string",
"from",
"a",
"url"
]
| 640a5f598983b239d5655c4d922ec560280aa2f0 | https://github.com/nathggns/uri.js/blob/640a5f598983b239d5655c4d922ec560280aa2f0/dist/uri.js.js#L43-L63 | train |
|
nathggns/uri.js | dist/uri.js.js | function(url, decode) {
// If we're passed an object, convert it to a string
if (typeof url === 'object') url = url.toString();
// Default decode to true
if (typeof decode === 'undefined') decode = true;
// Extract query string from url
var query_string = this.search(url);
// Replace the starting ?, if it is there
query_string = query_string.replace(/^\?/, '');
var parts;
// If query string is blank, parts should be blank
if (query_string === '') {
parts = [];
} else {
// Split the query string into key value parts
parts = query_string.split('&');
}
// Iniate the return value
var query = {};
// Loop through each other the parts, splitting it into keys and values
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
var key;
var val = '';
if (part.match('=')) {
// If it is in the format key=val
// Split into the key and value by the = symbol
var part_parts = part.split('=');
// Assign key and value
key = part_parts[0];
val = part_parts[1];
} else {
// If there is no value, just set the key to the full part
key = part;
}
// If we actually have a value, URI decode it
if (val !== '' && decode) {
val = decodeURIComponent(val);
}
// Assign to the return value
query[key] = val;
}
return query;
} | javascript | function(url, decode) {
// If we're passed an object, convert it to a string
if (typeof url === 'object') url = url.toString();
// Default decode to true
if (typeof decode === 'undefined') decode = true;
// Extract query string from url
var query_string = this.search(url);
// Replace the starting ?, if it is there
query_string = query_string.replace(/^\?/, '');
var parts;
// If query string is blank, parts should be blank
if (query_string === '') {
parts = [];
} else {
// Split the query string into key value parts
parts = query_string.split('&');
}
// Iniate the return value
var query = {};
// Loop through each other the parts, splitting it into keys and values
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
var key;
var val = '';
if (part.match('=')) {
// If it is in the format key=val
// Split into the key and value by the = symbol
var part_parts = part.split('=');
// Assign key and value
key = part_parts[0];
val = part_parts[1];
} else {
// If there is no value, just set the key to the full part
key = part;
}
// If we actually have a value, URI decode it
if (val !== '' && decode) {
val = decodeURIComponent(val);
}
// Assign to the return value
query[key] = val;
}
return query;
} | [
"function",
"(",
"url",
",",
"decode",
")",
"{",
"if",
"(",
"typeof",
"url",
"===",
"'object'",
")",
"url",
"=",
"url",
".",
"toString",
"(",
")",
";",
"if",
"(",
"typeof",
"decode",
"===",
"'undefined'",
")",
"decode",
"=",
"true",
";",
"var",
"query_string",
"=",
"this",
".",
"search",
"(",
"url",
")",
";",
"query_string",
"=",
"query_string",
".",
"replace",
"(",
"/",
"^\\?",
"/",
",",
"''",
")",
";",
"var",
"parts",
";",
"if",
"(",
"query_string",
"===",
"''",
")",
"{",
"parts",
"=",
"[",
"]",
";",
"}",
"else",
"{",
"parts",
"=",
"query_string",
".",
"split",
"(",
"'&'",
")",
";",
"}",
"var",
"query",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"parts",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"var",
"part",
"=",
"parts",
"[",
"i",
"]",
";",
"var",
"key",
";",
"var",
"val",
"=",
"''",
";",
"if",
"(",
"part",
".",
"match",
"(",
"'='",
")",
")",
"{",
"var",
"part_parts",
"=",
"part",
".",
"split",
"(",
"'='",
")",
";",
"key",
"=",
"part_parts",
"[",
"0",
"]",
";",
"val",
"=",
"part_parts",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"key",
"=",
"part",
";",
"}",
"if",
"(",
"val",
"!==",
"''",
"&&",
"decode",
")",
"{",
"val",
"=",
"decodeURIComponent",
"(",
"val",
")",
";",
"}",
"query",
"[",
"key",
"]",
"=",
"val",
";",
"}",
"return",
"query",
";",
"}"
]
| Parse URI query strings
@param {string} url The URL or query string to parse
@param {bool} decode Should values be URI decoded?
@return {object} The parsed query string | [
"Parse",
"URI",
"query",
"strings"
]
| 640a5f598983b239d5655c4d922ec560280aa2f0 | https://github.com/nathggns/uri.js/blob/640a5f598983b239d5655c4d922ec560280aa2f0/dist/uri.js.js#L71-L128 | train |
|
nathggns/uri.js | dist/uri.js.js | function() {
// Not as nice as arguments.callee but at least we'll only have on reference.
var _this = this;
var extend = function() { return _this.extend.apply(_this, arguments); };
// If we don't have enough arguments to do anything, just return an object
if (arguments.length < 2) {
return {};
}
// Argument shuffling
if (typeof arguments[0] !== 'boolean') {
Array.prototype.unshift.call(arguments, true);
}
// Remove the variables we need from the arguments stack.
var deep = Array.prototype.shift.call(arguments);
var one = Array.prototype.shift.call(arguments);
var two = Array.prototype.shift.call(arguments);
// If we have more than two objects to merge
if (arguments.length > 0) {
// Push two back on to the arguments stack, it's no longer special.
Array.prototype.unshift.call(arguments, two);
// While we have any more arguments, call extend with the initial obj and the next argument
while (arguments.length > 0) {
two = Array.prototype.shift.call(arguments);
if (typeof two !== 'object') continue;
one = extend(deep, one, two);
}
return one;
}
// Do some checking to force one and two to be objects
if (typeof one !== 'object') {
one = {};
}
if (typeof two !== 'object') {
two = {};
}
// Loop through the second object to merge it with the first
for (var key in two) {
// If this key actually belongs to the second argument
if (Object.prototype.hasOwnProperty.call(two, key)) {
var current = two[key];
if (deep && typeof current === 'object' && typeof one[key] === 'object') {
// Deep copy
one[key] = extend(one[key], current);
} else {
one[key] = current;
}
}
}
return one;
} | javascript | function() {
// Not as nice as arguments.callee but at least we'll only have on reference.
var _this = this;
var extend = function() { return _this.extend.apply(_this, arguments); };
// If we don't have enough arguments to do anything, just return an object
if (arguments.length < 2) {
return {};
}
// Argument shuffling
if (typeof arguments[0] !== 'boolean') {
Array.prototype.unshift.call(arguments, true);
}
// Remove the variables we need from the arguments stack.
var deep = Array.prototype.shift.call(arguments);
var one = Array.prototype.shift.call(arguments);
var two = Array.prototype.shift.call(arguments);
// If we have more than two objects to merge
if (arguments.length > 0) {
// Push two back on to the arguments stack, it's no longer special.
Array.prototype.unshift.call(arguments, two);
// While we have any more arguments, call extend with the initial obj and the next argument
while (arguments.length > 0) {
two = Array.prototype.shift.call(arguments);
if (typeof two !== 'object') continue;
one = extend(deep, one, two);
}
return one;
}
// Do some checking to force one and two to be objects
if (typeof one !== 'object') {
one = {};
}
if (typeof two !== 'object') {
two = {};
}
// Loop through the second object to merge it with the first
for (var key in two) {
// If this key actually belongs to the second argument
if (Object.prototype.hasOwnProperty.call(two, key)) {
var current = two[key];
if (deep && typeof current === 'object' && typeof one[key] === 'object') {
// Deep copy
one[key] = extend(one[key], current);
} else {
one[key] = current;
}
}
}
return one;
} | [
"function",
"(",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"var",
"extend",
"=",
"function",
"(",
")",
"{",
"return",
"_this",
".",
"extend",
".",
"apply",
"(",
"_this",
",",
"arguments",
")",
";",
"}",
";",
"if",
"(",
"arguments",
".",
"length",
"<",
"2",
")",
"{",
"return",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"arguments",
"[",
"0",
"]",
"!==",
"'boolean'",
")",
"{",
"Array",
".",
"prototype",
".",
"unshift",
".",
"call",
"(",
"arguments",
",",
"true",
")",
";",
"}",
"var",
"deep",
"=",
"Array",
".",
"prototype",
".",
"shift",
".",
"call",
"(",
"arguments",
")",
";",
"var",
"one",
"=",
"Array",
".",
"prototype",
".",
"shift",
".",
"call",
"(",
"arguments",
")",
";",
"var",
"two",
"=",
"Array",
".",
"prototype",
".",
"shift",
".",
"call",
"(",
"arguments",
")",
";",
"if",
"(",
"arguments",
".",
"length",
">",
"0",
")",
"{",
"Array",
".",
"prototype",
".",
"unshift",
".",
"call",
"(",
"arguments",
",",
"two",
")",
";",
"while",
"(",
"arguments",
".",
"length",
">",
"0",
")",
"{",
"two",
"=",
"Array",
".",
"prototype",
".",
"shift",
".",
"call",
"(",
"arguments",
")",
";",
"if",
"(",
"typeof",
"two",
"!==",
"'object'",
")",
"continue",
";",
"one",
"=",
"extend",
"(",
"deep",
",",
"one",
",",
"two",
")",
";",
"}",
"return",
"one",
";",
"}",
"if",
"(",
"typeof",
"one",
"!==",
"'object'",
")",
"{",
"one",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"two",
"!==",
"'object'",
")",
"{",
"two",
"=",
"{",
"}",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"two",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"two",
",",
"key",
")",
")",
"{",
"var",
"current",
"=",
"two",
"[",
"key",
"]",
";",
"if",
"(",
"deep",
"&&",
"typeof",
"current",
"===",
"'object'",
"&&",
"typeof",
"one",
"[",
"key",
"]",
"===",
"'object'",
")",
"{",
"one",
"[",
"key",
"]",
"=",
"extend",
"(",
"one",
"[",
"key",
"]",
",",
"current",
")",
";",
"}",
"else",
"{",
"one",
"[",
"key",
"]",
"=",
"current",
";",
"}",
"}",
"}",
"return",
"one",
";",
"}"
]
| Deep merge two or more objects
@param {boolean} deep Should this be a deep copy or not?
@return {object} Merged version of the arguments | [
"Deep",
"merge",
"two",
"or",
"more",
"objects"
]
| 640a5f598983b239d5655c4d922ec560280aa2f0 | https://github.com/nathggns/uri.js/blob/640a5f598983b239d5655c4d922ec560280aa2f0/dist/uri.js.js#L135-L199 | train |
|
nathggns/uri.js | dist/uri.js.js | function(object) {
var str = '';
var first = true;
for (var key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
var val = object[key];
str += first ? '?' : '&';
str += key;
str += '=';
str += val;
first = false;
}
}
return str;
} | javascript | function(object) {
var str = '';
var first = true;
for (var key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
var val = object[key];
str += first ? '?' : '&';
str += key;
str += '=';
str += val;
first = false;
}
}
return str;
} | [
"function",
"(",
"object",
")",
"{",
"var",
"str",
"=",
"''",
";",
"var",
"first",
"=",
"true",
";",
"for",
"(",
"var",
"key",
"in",
"object",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"object",
",",
"key",
")",
")",
"{",
"var",
"val",
"=",
"object",
"[",
"key",
"]",
";",
"str",
"+=",
"first",
"?",
"'?'",
":",
"'&'",
";",
"str",
"+=",
"key",
";",
"str",
"+=",
"'='",
";",
"str",
"+=",
"val",
";",
"first",
"=",
"false",
";",
"}",
"}",
"return",
"str",
";",
"}"
]
| Compile a query object into a string
@param {Object} object The object to compile
@return {String} Compiled object | [
"Compile",
"a",
"query",
"object",
"into",
"a",
"string"
]
| 640a5f598983b239d5655c4d922ec560280aa2f0 | https://github.com/nathggns/uri.js/blob/640a5f598983b239d5655c4d922ec560280aa2f0/dist/uri.js.js#L206-L225 | train |
|
chibitronics/ltc-npm-modulate | afsk-encoder.js | function (buf) {
var out = "";
for (var i = 0; i < buf.length; i++)
out += "0x" + buf[i].toString(16) + ",";
return out;
} | javascript | function (buf) {
var out = "";
for (var i = 0; i < buf.length; i++)
out += "0x" + buf[i].toString(16) + ",";
return out;
} | [
"function",
"(",
"buf",
")",
"{",
"var",
"out",
"=",
"\"\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"buf",
".",
"length",
";",
"i",
"++",
")",
"out",
"+=",
"\"0x\"",
"+",
"buf",
"[",
"i",
"]",
".",
"toString",
"(",
"16",
")",
"+",
"\",\"",
";",
"return",
"out",
";",
"}"
]
| for debug. | [
"for",
"debug",
"."
]
| bd29301b7c0906747d0542a376a8352724a104c3 | https://github.com/chibitronics/ltc-npm-modulate/blob/bd29301b7c0906747d0542a376a8352724a104c3/afsk-encoder.js#L50-L55 | train |
|
Eomm/file-utils-easy | index.js | writeToFile | function writeToFile(fileContent, filePath) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, fileContent, 'utf8', (err) => {
if (err) {
reject(err);
return;
}
resolve(filePath);
});
});
} | javascript | function writeToFile(fileContent, filePath) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, fileContent, 'utf8', (err) => {
if (err) {
reject(err);
return;
}
resolve(filePath);
});
});
} | [
"function",
"writeToFile",
"(",
"fileContent",
",",
"filePath",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"fileContent",
",",
"'utf8'",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"resolve",
"(",
"filePath",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Write a string to a file
@param {string} fileContent the payload of the file
@param {string} filePath path and filename: where store the file
@returns {Promise<string>} resolve with the filePath received in input | [
"Write",
"a",
"string",
"to",
"a",
"file"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L19-L29 | train |
Eomm/file-utils-easy | index.js | appendToFile | function appendToFile(fileContent, filePath) {
return new Promise((resolve, reject) => {
fs.appendFile(filePath, fileContent, 'utf8', (err) => {
if (err) {
reject(err);
} else {
resolve(filePath);
}
});
});
} | javascript | function appendToFile(fileContent, filePath) {
return new Promise((resolve, reject) => {
fs.appendFile(filePath, fileContent, 'utf8', (err) => {
if (err) {
reject(err);
} else {
resolve(filePath);
}
});
});
} | [
"function",
"appendToFile",
"(",
"fileContent",
",",
"filePath",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"appendFile",
"(",
"filePath",
",",
"fileContent",
",",
"'utf8'",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"filePath",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Append a string to a file, if the file doesn't exist it is created
@param {string} fileContent the payload of the file
@param {string} filePath path and filename: where store the file
@returns {Promise<string>} resolve with the filePath received in input | [
"Append",
"a",
"string",
"to",
"a",
"file",
"if",
"the",
"file",
"doesn",
"t",
"exist",
"it",
"is",
"created"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L37-L47 | train |
Eomm/file-utils-easy | index.js | readFileStats | function readFileStats(filePath) {
return new Promise((resolve, reject) => {
fs.stat(filePath, (err, fstat) => {
if (err) {
reject(err);
return;
}
resolve(fstat);
});
});
} | javascript | function readFileStats(filePath) {
return new Promise((resolve, reject) => {
fs.stat(filePath, (err, fstat) => {
if (err) {
reject(err);
return;
}
resolve(fstat);
});
});
} | [
"function",
"readFileStats",
"(",
"filePath",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"stat",
"(",
"filePath",
",",
"(",
"err",
",",
"fstat",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"resolve",
"(",
"fstat",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Read the metadata of the file
@param {string} filePath path and filename: the file to read
@return {Promise<fs.Stats>} a node fs.Stats that provides information about a file
@see https://nodejs.org/api/fs.html#fs_class_fs_stats | [
"Read",
"the",
"metadata",
"of",
"the",
"file"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L72-L82 | train |
Eomm/file-utils-easy | index.js | readDirectoryFiles | function readDirectoryFiles(directory) {
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, files) => {
if (err) {
reject(err);
return;
}
const isFile = fileName => readFileStats(path.join(directory, fileName))
.then((fstat) => {
if (fstat.isFile()) {
return fileName;
}
return null;
});
Promise.all(files.map(isFile))
.then(fileList => resolve(fileList.filter(f => f !== null)))
.catch(reject);
});
});
} | javascript | function readDirectoryFiles(directory) {
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, files) => {
if (err) {
reject(err);
return;
}
const isFile = fileName => readFileStats(path.join(directory, fileName))
.then((fstat) => {
if (fstat.isFile()) {
return fileName;
}
return null;
});
Promise.all(files.map(isFile))
.then(fileList => resolve(fileList.filter(f => f !== null)))
.catch(reject);
});
});
} | [
"function",
"readDirectoryFiles",
"(",
"directory",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"readdir",
"(",
"directory",
",",
"(",
"err",
",",
"files",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"const",
"isFile",
"=",
"fileName",
"=>",
"readFileStats",
"(",
"path",
".",
"join",
"(",
"directory",
",",
"fileName",
")",
")",
".",
"then",
"(",
"(",
"fstat",
")",
"=>",
"{",
"if",
"(",
"fstat",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"fileName",
";",
"}",
"return",
"null",
";",
"}",
")",
";",
"Promise",
".",
"all",
"(",
"files",
".",
"map",
"(",
"isFile",
")",
")",
".",
"then",
"(",
"fileList",
"=>",
"resolve",
"(",
"fileList",
".",
"filter",
"(",
"f",
"=>",
"f",
"!==",
"null",
")",
")",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| List the files names of a directory, ignoring directories
@param {string} directory path of the directory to read
@returns {Promise<array>} strings names of the files in the input directory | [
"List",
"the",
"files",
"names",
"of",
"a",
"directory",
"ignoring",
"directories"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L90-L111 | train |
Eomm/file-utils-easy | index.js | saveUrlToFile | function saveUrlToFile(url, filePath) {
return new Promise((resolve, reject) => {
const outFile = fs.createWriteStream(filePath);
const protocol = url.startsWith('https') ? https : http;
protocol.get(url, (response) => {
response.pipe(outFile);
response.on('end', () => resolve(filePath));
response.on('error', (err) => {
// outFile.destroy();
// fs.unlinkSync(filePath);
reject(err);
});
})
.on('error', (err) => {
reject(err);
});
});
} | javascript | function saveUrlToFile(url, filePath) {
return new Promise((resolve, reject) => {
const outFile = fs.createWriteStream(filePath);
const protocol = url.startsWith('https') ? https : http;
protocol.get(url, (response) => {
response.pipe(outFile);
response.on('end', () => resolve(filePath));
response.on('error', (err) => {
// outFile.destroy();
// fs.unlinkSync(filePath);
reject(err);
});
})
.on('error', (err) => {
reject(err);
});
});
} | [
"function",
"saveUrlToFile",
"(",
"url",
",",
"filePath",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"outFile",
"=",
"fs",
".",
"createWriteStream",
"(",
"filePath",
")",
";",
"const",
"protocol",
"=",
"url",
".",
"startsWith",
"(",
"'https'",
")",
"?",
"https",
":",
"http",
";",
"protocol",
".",
"get",
"(",
"url",
",",
"(",
"response",
")",
"=>",
"{",
"response",
".",
"pipe",
"(",
"outFile",
")",
";",
"response",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"resolve",
"(",
"filePath",
")",
")",
";",
"response",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Save the content of a url to a file
@param {string} url where will be done an HTTP/GET to get the content
@param {string} filePath path and filename where store the output of url
@returns {Promise<string>} resolve with the filePath saved | [
"Save",
"the",
"content",
"of",
"a",
"url",
"to",
"a",
"file"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L149-L166 | train |
Eomm/file-utils-easy | index.js | deleteFile | function deleteFile(filePath) {
return new Promise((resolve, reject) => {
fs.unlink(filePath, (err) => {
if (err) {
reject(err);
return;
}
resolve(filePath);
});
});
} | javascript | function deleteFile(filePath) {
return new Promise((resolve, reject) => {
fs.unlink(filePath, (err) => {
if (err) {
reject(err);
return;
}
resolve(filePath);
});
});
} | [
"function",
"deleteFile",
"(",
"filePath",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"unlink",
"(",
"filePath",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"resolve",
"(",
"filePath",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Delete a file from the file system
@param {string} filePath path and filename: the file to delete
@returns {Promise<string>} resolve with the filePath deleted | [
"Delete",
"a",
"file",
"from",
"the",
"file",
"system"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L174-L184 | train |
Eomm/file-utils-easy | index.js | deleteDirectoryFiles | function deleteDirectoryFiles(directory, filter = () => true) {
return readDirectoryFiles(directory)
.then((files) => {
const quietDelete = f => deleteFile(path.join(directory, f)).catch(() => null);
const deletingFiles = files.filter(filter).map(quietDelete);
return Promise.all(deletingFiles).then(deleted => deleted.filter(d => d !== null));
});
} | javascript | function deleteDirectoryFiles(directory, filter = () => true) {
return readDirectoryFiles(directory)
.then((files) => {
const quietDelete = f => deleteFile(path.join(directory, f)).catch(() => null);
const deletingFiles = files.filter(filter).map(quietDelete);
return Promise.all(deletingFiles).then(deleted => deleted.filter(d => d !== null));
});
} | [
"function",
"deleteDirectoryFiles",
"(",
"directory",
",",
"filter",
"=",
"(",
")",
"=>",
"true",
")",
"{",
"return",
"readDirectoryFiles",
"(",
"directory",
")",
".",
"then",
"(",
"(",
"files",
")",
"=>",
"{",
"const",
"quietDelete",
"=",
"f",
"=>",
"deleteFile",
"(",
"path",
".",
"join",
"(",
"directory",
",",
"f",
")",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"null",
")",
";",
"const",
"deletingFiles",
"=",
"files",
".",
"filter",
"(",
"filter",
")",
".",
"map",
"(",
"quietDelete",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"deletingFiles",
")",
".",
"then",
"(",
"deleted",
"=>",
"deleted",
".",
"filter",
"(",
"d",
"=>",
"d",
"!==",
"null",
")",
")",
";",
"}",
")",
";",
"}"
]
| Delete all the files in a directory, applying an optional filter
@param {string} directory path of the directory to clean
@returns {Promise<array>} resolve with all the files deleted succesfully | [
"Delete",
"all",
"the",
"files",
"in",
"a",
"directory",
"applying",
"an",
"optional",
"filter"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L192-L199 | train |
Eomm/file-utils-easy | index.js | renameFile | function renameFile(from, to) {
return new Promise((resolve, reject) => {
fs.rename(from, to, (err) => {
if (err) {
reject(err);
return;
}
resolve(to);
});
});
} | javascript | function renameFile(from, to) {
return new Promise((resolve, reject) => {
fs.rename(from, to, (err) => {
if (err) {
reject(err);
return;
}
resolve(to);
});
});
} | [
"function",
"renameFile",
"(",
"from",
",",
"to",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"rename",
"(",
"from",
",",
"to",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"resolve",
"(",
"to",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Rename a file to another path
@param {string} from origin path and filename
@param {string} to destination path and filename
@returns {Promise<string>} resolve with the destination filePath | [
"Rename",
"a",
"file",
"to",
"another",
"path"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L208-L218 | train |
Eomm/file-utils-easy | index.js | copyFile | function copyFile(from, to) {
return new Promise((resolve, reject) => {
fs.copyFile(from, to, (err) => {
if (err) {
reject(err);
return;
}
resolve(to);
});
});
} | javascript | function copyFile(from, to) {
return new Promise((resolve, reject) => {
fs.copyFile(from, to, (err) => {
if (err) {
reject(err);
return;
}
resolve(to);
});
});
} | [
"function",
"copyFile",
"(",
"from",
",",
"to",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"copyFile",
"(",
"from",
",",
"to",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"resolve",
"(",
"to",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Copy a file to another path
@param {string} from origin path and filename
@param {string} to destination path and filename
@returns {Promise<string>} resolve with the destination filePath | [
"Copy",
"a",
"file",
"to",
"another",
"path"
]
| 8eb728d4893ed949f6dbc36deadf0d65216ba1e2 | https://github.com/Eomm/file-utils-easy/blob/8eb728d4893ed949f6dbc36deadf0d65216ba1e2/index.js#L227-L237 | train |
trend-community/trend-components | scripts/pathResolver.js | getAbsPath | function getAbsPath(...relativePathPartsToRoot) {
const { resolve, join } = path;
return fs.existsSync(relativePathPartsToRoot[0])
? resolve(join(...relativePathPartsToRoot))
: resolve(join(getRepoRootAbsPath(), ...relativePathPartsToRoot));
} | javascript | function getAbsPath(...relativePathPartsToRoot) {
const { resolve, join } = path;
return fs.existsSync(relativePathPartsToRoot[0])
? resolve(join(...relativePathPartsToRoot))
: resolve(join(getRepoRootAbsPath(), ...relativePathPartsToRoot));
} | [
"function",
"getAbsPath",
"(",
"...",
"relativePathPartsToRoot",
")",
"{",
"const",
"{",
"resolve",
",",
"join",
"}",
"=",
"path",
";",
"return",
"fs",
".",
"existsSync",
"(",
"relativePathPartsToRoot",
"[",
"0",
"]",
")",
"?",
"resolve",
"(",
"join",
"(",
"...",
"relativePathPartsToRoot",
")",
")",
":",
"resolve",
"(",
"join",
"(",
"getRepoRootAbsPath",
"(",
")",
",",
"...",
"relativePathPartsToRoot",
")",
")",
";",
"}"
]
| Returns the absolute path resolved from zero or more path parts.
@param {...string} relativePathPartsToRoot File system path parts.
@return {string} | [
"Returns",
"the",
"absolute",
"path",
"resolved",
"from",
"zero",
"or",
"more",
"path",
"parts",
"."
]
| 51650e25069fa9bef52184ae5bc6979bb7ca75bc | https://github.com/trend-community/trend-components/blob/51650e25069fa9bef52184ae5bc6979bb7ca75bc/scripts/pathResolver.js#L24-L30 | train |
onehilltech/base-object | lib/mixin.js | setupEmulateDynamicDispatch | function setupEmulateDynamicDispatch (baseFn, overrideFn) {
// If the override function does not call _super, then we need to return
// the override function. If the base function does not exist, then we need
// to return the override function.
const callsBaseMethod = METHOD_CALLS_SUPER_REGEXP.test (overrideFn);
if (!callsBaseMethod)
return overrideFn;
// Make sure the base method exists, even if it is a no-op method.
baseFn = baseFn || function __baseFn () {};
function __override () {
let original = this._super;
this._super = baseFn;
// Call the method override. The override method will call _super, which
// will call the base method.
let ret = overrideFn.call (this, ...arguments);
this._super = original;
return ret;
}
__override.__baseMethod = baseFn;
return __override;
} | javascript | function setupEmulateDynamicDispatch (baseFn, overrideFn) {
// If the override function does not call _super, then we need to return
// the override function. If the base function does not exist, then we need
// to return the override function.
const callsBaseMethod = METHOD_CALLS_SUPER_REGEXP.test (overrideFn);
if (!callsBaseMethod)
return overrideFn;
// Make sure the base method exists, even if it is a no-op method.
baseFn = baseFn || function __baseFn () {};
function __override () {
let original = this._super;
this._super = baseFn;
// Call the method override. The override method will call _super, which
// will call the base method.
let ret = overrideFn.call (this, ...arguments);
this._super = original;
return ret;
}
__override.__baseMethod = baseFn;
return __override;
} | [
"function",
"setupEmulateDynamicDispatch",
"(",
"baseFn",
",",
"overrideFn",
")",
"{",
"const",
"callsBaseMethod",
"=",
"METHOD_CALLS_SUPER_REGEXP",
".",
"test",
"(",
"overrideFn",
")",
";",
"if",
"(",
"!",
"callsBaseMethod",
")",
"return",
"overrideFn",
";",
"baseFn",
"=",
"baseFn",
"||",
"function",
"__baseFn",
"(",
")",
"{",
"}",
";",
"function",
"__override",
"(",
")",
"{",
"let",
"original",
"=",
"this",
".",
"_super",
";",
"this",
".",
"_super",
"=",
"baseFn",
";",
"let",
"ret",
"=",
"overrideFn",
".",
"call",
"(",
"this",
",",
"...",
"arguments",
")",
";",
"this",
".",
"_super",
"=",
"original",
";",
"return",
"ret",
";",
"}",
"__override",
".",
"__baseMethod",
"=",
"baseFn",
";",
"return",
"__override",
";",
"}"
]
| Emulate the polymorphic behavior between the base function and the
override function.
@param baseFn
@param overrideFn
@returns {*} | [
"Emulate",
"the",
"polymorphic",
"behavior",
"between",
"the",
"base",
"function",
"and",
"the",
"override",
"function",
"."
]
| 8e0011b082b911907276ae14c13e209b5c613421 | https://github.com/onehilltech/base-object/blob/8e0011b082b911907276ae14c13e209b5c613421/lib/mixin.js#L48-L76 | train |
rhgb/json-uri | index.js | findSingleVacancies | function findSingleVacancies(str, size) {
var vacs = [];
for (var i = 0; i < CANDIDATE_CHARS.length; i++) {
if (str.indexOf(CANDIDATE_CHARS[i]) < 0) {
vacs.push(CANDIDATE_CHARS[i]);
if (size && vacs.length >= size) break;
}
}
return vacs;
} | javascript | function findSingleVacancies(str, size) {
var vacs = [];
for (var i = 0; i < CANDIDATE_CHARS.length; i++) {
if (str.indexOf(CANDIDATE_CHARS[i]) < 0) {
vacs.push(CANDIDATE_CHARS[i]);
if (size && vacs.length >= size) break;
}
}
return vacs;
} | [
"function",
"findSingleVacancies",
"(",
"str",
",",
"size",
")",
"{",
"var",
"vacs",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"CANDIDATE_CHARS",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"str",
".",
"indexOf",
"(",
"CANDIDATE_CHARS",
"[",
"i",
"]",
")",
"<",
"0",
")",
"{",
"vacs",
".",
"push",
"(",
"CANDIDATE_CHARS",
"[",
"i",
"]",
")",
";",
"if",
"(",
"size",
"&&",
"vacs",
".",
"length",
">=",
"size",
")",
"break",
";",
"}",
"}",
"return",
"vacs",
";",
"}"
]
| Find single-character vacancies of a string
@param {string} str
@param {number} [size]
@returns {string[]} | [
"Find",
"single",
"-",
"character",
"vacancies",
"of",
"a",
"string"
]
| 16e4322070cb6069aec9102fc9736eb895b7d89f | https://github.com/rhgb/json-uri/blob/16e4322070cb6069aec9102fc9736eb895b7d89f/index.js#L27-L36 | train |
rhgb/json-uri | index.js | findDoubleVacancies | function findDoubleVacancies(str, size) {
var vacs = [];
for (var i = 0; i < CANDIDATE_CHARS.length; i++) {
for (var j = 0; j < CANDIDATE_CHARS.length; j++) {
if (i != j) {
var pair = CANDIDATE_CHARS[i] + CANDIDATE_CHARS[j];
if (str.indexOf(pair) < 0) {
vacs.push(pair);
if (size && vacs.length >= size) break;
}
}
}
}
return vacs;
} | javascript | function findDoubleVacancies(str, size) {
var vacs = [];
for (var i = 0; i < CANDIDATE_CHARS.length; i++) {
for (var j = 0; j < CANDIDATE_CHARS.length; j++) {
if (i != j) {
var pair = CANDIDATE_CHARS[i] + CANDIDATE_CHARS[j];
if (str.indexOf(pair) < 0) {
vacs.push(pair);
if (size && vacs.length >= size) break;
}
}
}
}
return vacs;
} | [
"function",
"findDoubleVacancies",
"(",
"str",
",",
"size",
")",
"{",
"var",
"vacs",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"CANDIDATE_CHARS",
".",
"length",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"CANDIDATE_CHARS",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"i",
"!=",
"j",
")",
"{",
"var",
"pair",
"=",
"CANDIDATE_CHARS",
"[",
"i",
"]",
"+",
"CANDIDATE_CHARS",
"[",
"j",
"]",
";",
"if",
"(",
"str",
".",
"indexOf",
"(",
"pair",
")",
"<",
"0",
")",
"{",
"vacs",
".",
"push",
"(",
"pair",
")",
";",
"if",
"(",
"size",
"&&",
"vacs",
".",
"length",
">=",
"size",
")",
"break",
";",
"}",
"}",
"}",
"}",
"return",
"vacs",
";",
"}"
]
| Find two-character vacancies of a string; currently unused
@param {string} str
@param {number} [size]
@returns {string[]} | [
"Find",
"two",
"-",
"character",
"vacancies",
"of",
"a",
"string",
";",
"currently",
"unused"
]
| 16e4322070cb6069aec9102fc9736eb895b7d89f | https://github.com/rhgb/json-uri/blob/16e4322070cb6069aec9102fc9736eb895b7d89f/index.js#L43-L57 | train |
rhgb/json-uri | index.js | encode | function encode(str) {
var i;
var vacs = findSingleVacancies(str, singleLen + complexLen);
var singleReplacements = vacs.slice(0, singleLen);
var complexReplacements = vacs.slice(singleLen);
var dest = str;
// first replace complex delimiters
for (i = COMPLEX_DELIMITERS.length - 1; i >= 0; i--) {
if (i < complexReplacements.length) {
dest = dest.split(COMPLEX_DELIMITERS[i]).join(complexReplacements[i]);
}
}
// then replace single delimiters
for (i = 0; i < singleReplacements.length; i++) {
dest = dest.split(SINGLE_DELIMITERS[i]).join(singleReplacements[i]);
}
// concatenate with replacement map
dest = singleReplacements.join('') + SECTION_DELIMITER + complexReplacements.join('') + SECTION_DELIMITER + dest;
return dest;
} | javascript | function encode(str) {
var i;
var vacs = findSingleVacancies(str, singleLen + complexLen);
var singleReplacements = vacs.slice(0, singleLen);
var complexReplacements = vacs.slice(singleLen);
var dest = str;
// first replace complex delimiters
for (i = COMPLEX_DELIMITERS.length - 1; i >= 0; i--) {
if (i < complexReplacements.length) {
dest = dest.split(COMPLEX_DELIMITERS[i]).join(complexReplacements[i]);
}
}
// then replace single delimiters
for (i = 0; i < singleReplacements.length; i++) {
dest = dest.split(SINGLE_DELIMITERS[i]).join(singleReplacements[i]);
}
// concatenate with replacement map
dest = singleReplacements.join('') + SECTION_DELIMITER + complexReplacements.join('') + SECTION_DELIMITER + dest;
return dest;
} | [
"function",
"encode",
"(",
"str",
")",
"{",
"var",
"i",
";",
"var",
"vacs",
"=",
"findSingleVacancies",
"(",
"str",
",",
"singleLen",
"+",
"complexLen",
")",
";",
"var",
"singleReplacements",
"=",
"vacs",
".",
"slice",
"(",
"0",
",",
"singleLen",
")",
";",
"var",
"complexReplacements",
"=",
"vacs",
".",
"slice",
"(",
"singleLen",
")",
";",
"var",
"dest",
"=",
"str",
";",
"for",
"(",
"i",
"=",
"COMPLEX_DELIMITERS",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"i",
"<",
"complexReplacements",
".",
"length",
")",
"{",
"dest",
"=",
"dest",
".",
"split",
"(",
"COMPLEX_DELIMITERS",
"[",
"i",
"]",
")",
".",
"join",
"(",
"complexReplacements",
"[",
"i",
"]",
")",
";",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"singleReplacements",
".",
"length",
";",
"i",
"++",
")",
"{",
"dest",
"=",
"dest",
".",
"split",
"(",
"SINGLE_DELIMITERS",
"[",
"i",
"]",
")",
".",
"join",
"(",
"singleReplacements",
"[",
"i",
"]",
")",
";",
"}",
"dest",
"=",
"singleReplacements",
".",
"join",
"(",
"''",
")",
"+",
"SECTION_DELIMITER",
"+",
"complexReplacements",
".",
"join",
"(",
"''",
")",
"+",
"SECTION_DELIMITER",
"+",
"dest",
";",
"return",
"dest",
";",
"}"
]
| Encode JSON string
@param {string} str
@returns {string} | [
"Encode",
"JSON",
"string"
]
| 16e4322070cb6069aec9102fc9736eb895b7d89f | https://github.com/rhgb/json-uri/blob/16e4322070cb6069aec9102fc9736eb895b7d89f/index.js#L63-L82 | train |
desgeeko/svgoban | src/geometry.js | function(i, coordSystem) {
if ("aa" === coordSystem) {
return String.fromCharCode(CODE_a + --i);
}
else { // "A1" (default)
var skipI = i >= 9 ? 1 : 0;
return String.fromCharCode(CODE_A + --i + skipI);
}
} | javascript | function(i, coordSystem) {
if ("aa" === coordSystem) {
return String.fromCharCode(CODE_a + --i);
}
else { // "A1" (default)
var skipI = i >= 9 ? 1 : 0;
return String.fromCharCode(CODE_A + --i + skipI);
}
} | [
"function",
"(",
"i",
",",
"coordSystem",
")",
"{",
"if",
"(",
"\"aa\"",
"===",
"coordSystem",
")",
"{",
"return",
"String",
".",
"fromCharCode",
"(",
"CODE_a",
"+",
"--",
"i",
")",
";",
"}",
"else",
"{",
"var",
"skipI",
"=",
"i",
">=",
"9",
"?",
"1",
":",
"0",
";",
"return",
"String",
".",
"fromCharCode",
"(",
"CODE_A",
"+",
"--",
"i",
"+",
"skipI",
")",
";",
"}",
"}"
]
| Defines horizontal label.
@param {number} i index of column
@param {string} coordSystem ("A1" or "aa")
@returns {string} | [
"Defines",
"horizontal",
"label",
"."
]
| e4cb5416cdca343e0ed29049a4c728be4410af67 | https://github.com/desgeeko/svgoban/blob/e4cb5416cdca343e0ed29049a4c728be4410af67/src/geometry.js#L25-L33 | train |
|
desgeeko/svgoban | src/geometry.js | function(j, coordSystem, size) {
if ("aa" === coordSystem) {
return String.fromCharCode(CODE_a + --j);
}
else { // "A1" (default)
return (size - --j).toString();
}
} | javascript | function(j, coordSystem, size) {
if ("aa" === coordSystem) {
return String.fromCharCode(CODE_a + --j);
}
else { // "A1" (default)
return (size - --j).toString();
}
} | [
"function",
"(",
"j",
",",
"coordSystem",
",",
"size",
")",
"{",
"if",
"(",
"\"aa\"",
"===",
"coordSystem",
")",
"{",
"return",
"String",
".",
"fromCharCode",
"(",
"CODE_a",
"+",
"--",
"j",
")",
";",
"}",
"else",
"{",
"return",
"(",
"size",
"-",
"--",
"j",
")",
".",
"toString",
"(",
")",
";",
"}",
"}"
]
| Defines vertical label.
@param {number} j index of row
@param {string} coordSystem ("A1" or "aa")
@param {number} size the grid base (9, 13, 19)
@returns {string} | [
"Defines",
"vertical",
"label",
"."
]
| e4cb5416cdca343e0ed29049a4c728be4410af67 | https://github.com/desgeeko/svgoban/blob/e4cb5416cdca343e0ed29049a4c728be4410af67/src/geometry.js#L43-L50 | train |
|
desgeeko/svgoban | src/geometry.js | function(intersection, size) {
var i, j;
if (intersection.charCodeAt(1) > CODE_9) { // "aa"
i = intersection.charCodeAt(0) - CODE_a + 1;
j = intersection.charCodeAt(1) - CODE_a + 1;
}
else { // "A1"
i = intersection.charCodeAt(0) - CODE_A + 1;
var skipI = i >= 9 ? 1 : 0;
i -= skipI;
j = size - (+intersection.substring(1)) + 1;
}
return {i: i, j: j};
} | javascript | function(intersection, size) {
var i, j;
if (intersection.charCodeAt(1) > CODE_9) { // "aa"
i = intersection.charCodeAt(0) - CODE_a + 1;
j = intersection.charCodeAt(1) - CODE_a + 1;
}
else { // "A1"
i = intersection.charCodeAt(0) - CODE_A + 1;
var skipI = i >= 9 ? 1 : 0;
i -= skipI;
j = size - (+intersection.substring(1)) + 1;
}
return {i: i, j: j};
} | [
"function",
"(",
"intersection",
",",
"size",
")",
"{",
"var",
"i",
",",
"j",
";",
"if",
"(",
"intersection",
".",
"charCodeAt",
"(",
"1",
")",
">",
"CODE_9",
")",
"{",
"i",
"=",
"intersection",
".",
"charCodeAt",
"(",
"0",
")",
"-",
"CODE_a",
"+",
"1",
";",
"j",
"=",
"intersection",
".",
"charCodeAt",
"(",
"1",
")",
"-",
"CODE_a",
"+",
"1",
";",
"}",
"else",
"{",
"i",
"=",
"intersection",
".",
"charCodeAt",
"(",
"0",
")",
"-",
"CODE_A",
"+",
"1",
";",
"var",
"skipI",
"=",
"i",
">=",
"9",
"?",
"1",
":",
"0",
";",
"i",
"-=",
"skipI",
";",
"j",
"=",
"size",
"-",
"(",
"+",
"intersection",
".",
"substring",
"(",
"1",
")",
")",
"+",
"1",
";",
"}",
"return",
"{",
"i",
":",
"i",
",",
"j",
":",
"j",
"}",
";",
"}"
]
| Calculates column and row of intersection.
@param {string} intersection either in "A1" or "aa" coordinates
@param {number} size the grid base (9, 13, 19)
@returns {Object} | [
"Calculates",
"column",
"and",
"row",
"of",
"intersection",
"."
]
| e4cb5416cdca343e0ed29049a4c728be4410af67 | https://github.com/desgeeko/svgoban/blob/e4cb5416cdca343e0ed29049a4c728be4410af67/src/geometry.js#L59-L72 | train |
|
desgeeko/svgoban | src/geometry.js | function(intersection, size) {
var i, j, ret;
if (intersection.charCodeAt(1) > CODE_9) { // "aa"
i = intersection.charCodeAt(0) - CODE_a + 1;
j = intersection.charCodeAt(1) - CODE_a + 1;
ret = horizontal(i, "A1") + vertical(j, "A1", size);
}
else { // "A1"
i = intersection.charCodeAt(0) - CODE_A + 1;
var skipI = i >= 9 ? 1 : 0;
i -= skipI;
j = size - (+intersection.substring(1)) + 1;
ret = horizontal(i, "aa") + vertical(j, "aa", size);
}
return ret;
} | javascript | function(intersection, size) {
var i, j, ret;
if (intersection.charCodeAt(1) > CODE_9) { // "aa"
i = intersection.charCodeAt(0) - CODE_a + 1;
j = intersection.charCodeAt(1) - CODE_a + 1;
ret = horizontal(i, "A1") + vertical(j, "A1", size);
}
else { // "A1"
i = intersection.charCodeAt(0) - CODE_A + 1;
var skipI = i >= 9 ? 1 : 0;
i -= skipI;
j = size - (+intersection.substring(1)) + 1;
ret = horizontal(i, "aa") + vertical(j, "aa", size);
}
return ret;
} | [
"function",
"(",
"intersection",
",",
"size",
")",
"{",
"var",
"i",
",",
"j",
",",
"ret",
";",
"if",
"(",
"intersection",
".",
"charCodeAt",
"(",
"1",
")",
">",
"CODE_9",
")",
"{",
"i",
"=",
"intersection",
".",
"charCodeAt",
"(",
"0",
")",
"-",
"CODE_a",
"+",
"1",
";",
"j",
"=",
"intersection",
".",
"charCodeAt",
"(",
"1",
")",
"-",
"CODE_a",
"+",
"1",
";",
"ret",
"=",
"horizontal",
"(",
"i",
",",
"\"A1\"",
")",
"+",
"vertical",
"(",
"j",
",",
"\"A1\"",
",",
"size",
")",
";",
"}",
"else",
"{",
"i",
"=",
"intersection",
".",
"charCodeAt",
"(",
"0",
")",
"-",
"CODE_A",
"+",
"1",
";",
"var",
"skipI",
"=",
"i",
">=",
"9",
"?",
"1",
":",
"0",
";",
"i",
"-=",
"skipI",
";",
"j",
"=",
"size",
"-",
"(",
"+",
"intersection",
".",
"substring",
"(",
"1",
")",
")",
"+",
"1",
";",
"ret",
"=",
"horizontal",
"(",
"i",
",",
"\"aa\"",
")",
"+",
"vertical",
"(",
"j",
",",
"\"aa\"",
",",
"size",
")",
";",
"}",
"return",
"ret",
";",
"}"
]
| Translates intersection in other coordinate system.
@param {string} intersection either in "A1" or "aa" coordinates
@param {number} size the grid base (9, 13, 19)
@returns {string} | [
"Translates",
"intersection",
"in",
"other",
"coordinate",
"system",
"."
]
| e4cb5416cdca343e0ed29049a4c728be4410af67 | https://github.com/desgeeko/svgoban/blob/e4cb5416cdca343e0ed29049a4c728be4410af67/src/geometry.js#L81-L96 | train |
|
Appfairy/speech-tree | src/client/label_matcher.js | createLabelMatcher | function createLabelMatcher(speechEmitter) {
if (speechEmitter == null) {
throw TypeError('speech emitter must be provided');
}
if (!(speechEmitter instanceof SpeechEmitter)) {
throw TypeError('first argument must be a speech emitter');
}
// This will be used to register events for fetched labels
const labelEmitter = new SpeechEmitter();
const sentencePattern = /.*/;
// This will fetch labels and emit them whenever there is an incoming sentence
const fetchHandler = (sentence) => {
// e.g. ' ' (space) will be replaced with '%20'
const encodedSentence = encodeURIComponent(sentence);
const labelQueryUrl = `${settings.apiUrl}/label?sentence=${encodedSentence}`;
const request = new Request(labelQueryUrl);
fetch(request).then(response => response.json()).then(({ label }) => {
labelEmitter.emit(label, sentence);
// Re-register event listener after it (could have been) zeroed by the speech node.
// Here we wait run the registration in the next event loop to ensure all promises
// have been resolved
setTimeout(() => {
speechEmitter.once(sentencePattern, fetchHandler);
});
})
.catch((error) => {
console.error(error);
});
};
// Here we use the once() method and not the on() method we re-register the event
// listener once a fetch has been done
speechEmitter.once(sentencePattern, fetchHandler);
// A factory function which will generate an event handler for matching sentences
// against fetched labels. Be sure to call the dispose() method once you don't need
// the labels logic anymore! Otherwise requests will keep being made to the server
// in the background
const matchLabel = (label) => {
if (label == null) {
throw TypeError('label must be provided');
}
if (typeof label != 'string') {
throw TypeError('label must be a string');
}
// An async event handler which returns a promise
return () => new Promise((resolve) => {
// The promise will resolve itself whenever an emitted label matches the
// expected label
const labelTest = (actualLabel, sentence) => {
// This makes it a one-time test
labelEmitter.off(labelTest);
if (actualLabel == label) {
// These are the arguments with whom the event handler will be invoked with
return [sentence, label];
}
};
labelEmitter.on(labelTest, resolve);
});
};
// The disposal methods disposes all the registered label events and it stops the
// auto-fetching to the server whenever there is an incoming sentence
matchLabel.dispose = () => {
speechEmitter.off(sentencePattern, fetchHandler);
labelEmitter.off();
};
return matchLabel;
} | javascript | function createLabelMatcher(speechEmitter) {
if (speechEmitter == null) {
throw TypeError('speech emitter must be provided');
}
if (!(speechEmitter instanceof SpeechEmitter)) {
throw TypeError('first argument must be a speech emitter');
}
// This will be used to register events for fetched labels
const labelEmitter = new SpeechEmitter();
const sentencePattern = /.*/;
// This will fetch labels and emit them whenever there is an incoming sentence
const fetchHandler = (sentence) => {
// e.g. ' ' (space) will be replaced with '%20'
const encodedSentence = encodeURIComponent(sentence);
const labelQueryUrl = `${settings.apiUrl}/label?sentence=${encodedSentence}`;
const request = new Request(labelQueryUrl);
fetch(request).then(response => response.json()).then(({ label }) => {
labelEmitter.emit(label, sentence);
// Re-register event listener after it (could have been) zeroed by the speech node.
// Here we wait run the registration in the next event loop to ensure all promises
// have been resolved
setTimeout(() => {
speechEmitter.once(sentencePattern, fetchHandler);
});
})
.catch((error) => {
console.error(error);
});
};
// Here we use the once() method and not the on() method we re-register the event
// listener once a fetch has been done
speechEmitter.once(sentencePattern, fetchHandler);
// A factory function which will generate an event handler for matching sentences
// against fetched labels. Be sure to call the dispose() method once you don't need
// the labels logic anymore! Otherwise requests will keep being made to the server
// in the background
const matchLabel = (label) => {
if (label == null) {
throw TypeError('label must be provided');
}
if (typeof label != 'string') {
throw TypeError('label must be a string');
}
// An async event handler which returns a promise
return () => new Promise((resolve) => {
// The promise will resolve itself whenever an emitted label matches the
// expected label
const labelTest = (actualLabel, sentence) => {
// This makes it a one-time test
labelEmitter.off(labelTest);
if (actualLabel == label) {
// These are the arguments with whom the event handler will be invoked with
return [sentence, label];
}
};
labelEmitter.on(labelTest, resolve);
});
};
// The disposal methods disposes all the registered label events and it stops the
// auto-fetching to the server whenever there is an incoming sentence
matchLabel.dispose = () => {
speechEmitter.off(sentencePattern, fetchHandler);
labelEmitter.off();
};
return matchLabel;
} | [
"function",
"createLabelMatcher",
"(",
"speechEmitter",
")",
"{",
"if",
"(",
"speechEmitter",
"==",
"null",
")",
"{",
"throw",
"TypeError",
"(",
"'speech emitter must be provided'",
")",
";",
"}",
"if",
"(",
"!",
"(",
"speechEmitter",
"instanceof",
"SpeechEmitter",
")",
")",
"{",
"throw",
"TypeError",
"(",
"'first argument must be a speech emitter'",
")",
";",
"}",
"const",
"labelEmitter",
"=",
"new",
"SpeechEmitter",
"(",
")",
";",
"const",
"sentencePattern",
"=",
"/",
".*",
"/",
";",
"const",
"fetchHandler",
"=",
"(",
"sentence",
")",
"=>",
"{",
"const",
"encodedSentence",
"=",
"encodeURIComponent",
"(",
"sentence",
")",
";",
"const",
"labelQueryUrl",
"=",
"`",
"${",
"settings",
".",
"apiUrl",
"}",
"${",
"encodedSentence",
"}",
"`",
";",
"const",
"request",
"=",
"new",
"Request",
"(",
"labelQueryUrl",
")",
";",
"fetch",
"(",
"request",
")",
".",
"then",
"(",
"response",
"=>",
"response",
".",
"json",
"(",
")",
")",
".",
"then",
"(",
"(",
"{",
"label",
"}",
")",
"=>",
"{",
"labelEmitter",
".",
"emit",
"(",
"label",
",",
"sentence",
")",
";",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"speechEmitter",
".",
"once",
"(",
"sentencePattern",
",",
"fetchHandler",
")",
";",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
"error",
")",
"=>",
"{",
"console",
".",
"error",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
";",
"speechEmitter",
".",
"once",
"(",
"sentencePattern",
",",
"fetchHandler",
")",
";",
"const",
"matchLabel",
"=",
"(",
"label",
")",
"=>",
"{",
"if",
"(",
"label",
"==",
"null",
")",
"{",
"throw",
"TypeError",
"(",
"'label must be provided'",
")",
";",
"}",
"if",
"(",
"typeof",
"label",
"!=",
"'string'",
")",
"{",
"throw",
"TypeError",
"(",
"'label must be a string'",
")",
";",
"}",
"return",
"(",
")",
"=>",
"new",
"Promise",
"(",
"(",
"resolve",
")",
"=>",
"{",
"const",
"labelTest",
"=",
"(",
"actualLabel",
",",
"sentence",
")",
"=>",
"{",
"labelEmitter",
".",
"off",
"(",
"labelTest",
")",
";",
"if",
"(",
"actualLabel",
"==",
"label",
")",
"{",
"return",
"[",
"sentence",
",",
"label",
"]",
";",
"}",
"}",
";",
"labelEmitter",
".",
"on",
"(",
"labelTest",
",",
"resolve",
")",
";",
"}",
")",
";",
"}",
";",
"matchLabel",
".",
"dispose",
"=",
"(",
")",
"=>",
"{",
"speechEmitter",
".",
"off",
"(",
"sentencePattern",
",",
"fetchHandler",
")",
";",
"labelEmitter",
".",
"off",
"(",
")",
";",
"}",
";",
"return",
"matchLabel",
";",
"}"
]
| This will start listening for incoming sentences and will fetch labels from the server each time a speech was recognized. It will return a factory function which will generate an event handler for testing sentences against fetched labels | [
"This",
"will",
"start",
"listening",
"for",
"incoming",
"sentences",
"and",
"will",
"fetch",
"labels",
"from",
"the",
"server",
"each",
"time",
"a",
"speech",
"was",
"recognized",
".",
"It",
"will",
"return",
"a",
"factory",
"function",
"which",
"will",
"generate",
"an",
"event",
"handler",
"for",
"testing",
"sentences",
"against",
"fetched",
"labels"
]
| 6ebc084aedd5ed4a6faaf96e9772de8a0c0ff6ef | https://github.com/Appfairy/speech-tree/blob/6ebc084aedd5ed4a6faaf96e9772de8a0c0ff6ef/src/client/label_matcher.js#L21-L99 | train |
jsdoc2md/ddata | lib/ddata.js | module | function module (options) {
options.hash.kind = 'module'
var result = _identifiers(options)[0]
return result ? options.fn(result) : 'ERROR, Cannot find module.'
} | javascript | function module (options) {
options.hash.kind = 'module'
var result = _identifiers(options)[0]
return result ? options.fn(result) : 'ERROR, Cannot find module.'
} | [
"function",
"module",
"(",
"options",
")",
"{",
"options",
".",
"hash",
".",
"kind",
"=",
"'module'",
"var",
"result",
"=",
"_identifiers",
"(",
"options",
")",
"[",
"0",
"]",
"return",
"result",
"?",
"options",
".",
"fn",
"(",
"result",
")",
":",
"'ERROR, Cannot find module.'",
"}"
]
| render the supplied block for the specified module
@static
@category Block helper: selector | [
"render",
"the",
"supplied",
"block",
"for",
"the",
"specified",
"module"
]
| f34be998eae49f13696ba056f264fd3acab089c9 | https://github.com/jsdoc2md/ddata/blob/f34be998eae49f13696ba056f264fd3acab089c9/lib/ddata.js#L167-L171 | train |
jsdoc2md/ddata | lib/ddata.js | classes | function classes (options) {
options.hash.kind = 'class'
return handlebars.helpers.each(_identifiers(options), options)
} | javascript | function classes (options) {
options.hash.kind = 'class'
return handlebars.helpers.each(_identifiers(options), options)
} | [
"function",
"classes",
"(",
"options",
")",
"{",
"options",
".",
"hash",
".",
"kind",
"=",
"'class'",
"return",
"handlebars",
".",
"helpers",
".",
"each",
"(",
"_identifiers",
"(",
"options",
")",
",",
"options",
")",
"}"
]
| render the block for each class
@static
@category Block helper: selector | [
"render",
"the",
"block",
"for",
"each",
"class"
]
| f34be998eae49f13696ba056f264fd3acab089c9 | https://github.com/jsdoc2md/ddata/blob/f34be998eae49f13696ba056f264fd3acab089c9/lib/ddata.js#L188-L191 | train |
jsdoc2md/ddata | lib/ddata.js | misc | function misc (options) {
options.hash.scope = undefined
options.hash['!kind'] = /module|constructor|external/
options.hash['!isExported'] = true
return handlebars.helpers.each(_identifiers(options), options)
} | javascript | function misc (options) {
options.hash.scope = undefined
options.hash['!kind'] = /module|constructor|external/
options.hash['!isExported'] = true
return handlebars.helpers.each(_identifiers(options), options)
} | [
"function",
"misc",
"(",
"options",
")",
"{",
"options",
".",
"hash",
".",
"scope",
"=",
"undefined",
"options",
".",
"hash",
"[",
"'!kind'",
"]",
"=",
"/",
"module|constructor|external",
"/",
"options",
".",
"hash",
"[",
"'!isExported'",
"]",
"=",
"true",
"return",
"handlebars",
".",
"helpers",
".",
"each",
"(",
"_identifiers",
"(",
"options",
")",
",",
"options",
")",
"}"
]
| render the supplied block for each orphan with no scope set
@static
@category Block helper: selector | [
"render",
"the",
"supplied",
"block",
"for",
"each",
"orphan",
"with",
"no",
"scope",
"set"
]
| f34be998eae49f13696ba056f264fd3acab089c9 | https://github.com/jsdoc2md/ddata/blob/f34be998eae49f13696ba056f264fd3acab089c9/lib/ddata.js#L253-L258 | train |
dreampiggy/functional.js | Retroactive/lib/data_structures/bst.js | BST | function BST(compareFn) {
this.root = null;
this._size = 0;
/**
* @var Comparator
*/
this._comparator = new Comparator(compareFn);
/**
* Read-only property for the size of the tree
*/
Object.defineProperty(this, 'size', {
get: function () { return this._size; }.bind(this)
});
} | javascript | function BST(compareFn) {
this.root = null;
this._size = 0;
/**
* @var Comparator
*/
this._comparator = new Comparator(compareFn);
/**
* Read-only property for the size of the tree
*/
Object.defineProperty(this, 'size', {
get: function () { return this._size; }.bind(this)
});
} | [
"function",
"BST",
"(",
"compareFn",
")",
"{",
"this",
".",
"root",
"=",
"null",
";",
"this",
".",
"_size",
"=",
"0",
";",
"this",
".",
"_comparator",
"=",
"new",
"Comparator",
"(",
"compareFn",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'size'",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_size",
";",
"}",
".",
"bind",
"(",
"this",
")",
"}",
")",
";",
"}"
]
| Binary Search Tree | [
"Binary",
"Search",
"Tree"
]
| ec7b7213de7965659a8a1e8fa61438e3ae564260 | https://github.com/dreampiggy/functional.js/blob/ec7b7213de7965659a8a1e8fa61438e3ae564260/Retroactive/lib/data_structures/bst.js#L7-L21 | train |
bootprint/bootprint-base | handlebars/helpers.js | function (value, options) {
if (!value) {
return value
}
var html = marked(value)
// We strip the surrounding <p>-tag, if
if (options.hash && options.hash.stripParagraph) {
var $ = cheerio('<root>' + html + '</root>')
// Only strip <p>-tags and only if there is just one of them.
if ($.children().length === 1 && $.children('p').length === 1) {
html = $.children('p').html()
}
}
return new Handlebars.SafeString(html)
} | javascript | function (value, options) {
if (!value) {
return value
}
var html = marked(value)
// We strip the surrounding <p>-tag, if
if (options.hash && options.hash.stripParagraph) {
var $ = cheerio('<root>' + html + '</root>')
// Only strip <p>-tags and only if there is just one of them.
if ($.children().length === 1 && $.children('p').length === 1) {
html = $.children('p').html()
}
}
return new Handlebars.SafeString(html)
} | [
"function",
"(",
"value",
",",
"options",
")",
"{",
"if",
"(",
"!",
"value",
")",
"{",
"return",
"value",
"}",
"var",
"html",
"=",
"marked",
"(",
"value",
")",
"if",
"(",
"options",
".",
"hash",
"&&",
"options",
".",
"hash",
".",
"stripParagraph",
")",
"{",
"var",
"$",
"=",
"cheerio",
"(",
"'<root>'",
"+",
"html",
"+",
"'</root>'",
")",
"if",
"(",
"$",
".",
"children",
"(",
")",
".",
"length",
"===",
"1",
"&&",
"$",
".",
"children",
"(",
"'p'",
")",
".",
"length",
"===",
"1",
")",
"{",
"html",
"=",
"$",
".",
"children",
"(",
"'p'",
")",
".",
"html",
"(",
")",
"}",
"}",
"return",
"new",
"Handlebars",
".",
"SafeString",
"(",
"html",
")",
"}"
]
| Render a markdown-formatted text as HTML.
@param {string} `value` the markdown-formatted text
@param {boolean} `options.hash.stripParagraph` the marked-md-renderer wraps generated HTML in a <p>-tag by default.
If this options is set to true, the <p>-tag is stripped.
@returns {Handlebars.SafeString} a Handlebars-SafeString containing the provieded
markdown, rendered as HTML. | [
"Render",
"a",
"markdown",
"-",
"formatted",
"text",
"as",
"HTML",
"."
]
| fdb843317d68f04eaf513e2cdda439774a7ca134 | https://github.com/bootprint/bootprint-base/blob/fdb843317d68f04eaf513e2cdda439774a7ca134/handlebars/helpers.js#L119-L133 | train |
|
StirfireStudios/Jacquard-YarnParser | src/listener/util.js | dsStatement | function dsStatement(statement) {
switch(statement.constructor) {
case Statements.Blank:
case Statements.Conditional:
case Statements.DialogueSegment:
case Statements.Evaluate:
case Statements.Function:
case Statements.Link:
case Statements.Option:
case Statements.OptionGroup:
case Statements.Shortcut:
case Statements.ShortcutGroup:
return false;
case Statements.Command:
case Statements.LineGroup:
case Statements.Text:
case Statements.Hashtag:
return true;
default:
console.warn(`Unrecognized statement type: ${statement.constructor.name}`);
return false;
}
} | javascript | function dsStatement(statement) {
switch(statement.constructor) {
case Statements.Blank:
case Statements.Conditional:
case Statements.DialogueSegment:
case Statements.Evaluate:
case Statements.Function:
case Statements.Link:
case Statements.Option:
case Statements.OptionGroup:
case Statements.Shortcut:
case Statements.ShortcutGroup:
return false;
case Statements.Command:
case Statements.LineGroup:
case Statements.Text:
case Statements.Hashtag:
return true;
default:
console.warn(`Unrecognized statement type: ${statement.constructor.name}`);
return false;
}
} | [
"function",
"dsStatement",
"(",
"statement",
")",
"{",
"switch",
"(",
"statement",
".",
"constructor",
")",
"{",
"case",
"Statements",
".",
"Blank",
":",
"case",
"Statements",
".",
"Conditional",
":",
"case",
"Statements",
".",
"DialogueSegment",
":",
"case",
"Statements",
".",
"Evaluate",
":",
"case",
"Statements",
".",
"Function",
":",
"case",
"Statements",
".",
"Link",
":",
"case",
"Statements",
".",
"Option",
":",
"case",
"Statements",
".",
"OptionGroup",
":",
"case",
"Statements",
".",
"Shortcut",
":",
"case",
"Statements",
".",
"ShortcutGroup",
":",
"return",
"false",
";",
"case",
"Statements",
".",
"Command",
":",
"case",
"Statements",
".",
"LineGroup",
":",
"case",
"Statements",
".",
"Text",
":",
"case",
"Statements",
".",
"Hashtag",
":",
"return",
"true",
";",
"default",
":",
"console",
".",
"warn",
"(",
"`",
"${",
"statement",
".",
"constructor",
".",
"name",
"}",
"`",
")",
";",
"return",
"false",
";",
"}",
"}"
]
| Dialog segment utils! | [
"Dialog",
"segment",
"utils!"
]
| fd2d3e1b3a952d2b2502c16919eaf12f2b5764b8 | https://github.com/StirfireStudios/Jacquard-YarnParser/blob/fd2d3e1b3a952d2b2502c16919eaf12f2b5764b8/src/listener/util.js#L52-L74 | train |
websemantics/svg-smart | smart.js | read | function read (filename) {
var data = null
try {
data = readfile(filename)
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
console.error('File ' + filename + ' is not found')
}
}
return data
} | javascript | function read (filename) {
var data = null
try {
data = readfile(filename)
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
console.error('File ' + filename + ' is not found')
}
}
return data
} | [
"function",
"read",
"(",
"filename",
")",
"{",
"var",
"data",
"=",
"null",
"try",
"{",
"data",
"=",
"readfile",
"(",
"filename",
")",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"code",
"===",
"'MODULE_NOT_FOUND'",
")",
"{",
"console",
".",
"error",
"(",
"'File '",
"+",
"filename",
"+",
"' is not found'",
")",
"}",
"}",
"return",
"data",
"}"
]
| Read a dot file, .. simple, huh ..
@param {filename} string, json file
@return object | [
"Read",
"a",
"dot",
"file",
"..",
"simple",
"huh",
".."
]
| d4a81574b2ef10a0f44b81a02ee9c898e97b4604 | https://github.com/websemantics/svg-smart/blob/d4a81574b2ef10a0f44b81a02ee9c898e97b4604/smart.js#L241-L251 | train |
websemantics/svg-smart | smart.js | function (smart_filename, package_filename) {
var smart = read(smart_filename)
var data = {
global: hydrate(smart.global, smart.global),
package: read(package_filename)
}
var dist = data.global.files.dist || 'dist'
var res = resources(hydrate(smart.template, data),
hydrate(smart.data, data), data.global.files.concatenator, dist)
return {
svg: res.svg,
png: res.png,
icon: res.icon,
sprite: res.sprite,
dist: dist,
html: hydrate(smart.html, data)
}
} | javascript | function (smart_filename, package_filename) {
var smart = read(smart_filename)
var data = {
global: hydrate(smart.global, smart.global),
package: read(package_filename)
}
var dist = data.global.files.dist || 'dist'
var res = resources(hydrate(smart.template, data),
hydrate(smart.data, data), data.global.files.concatenator, dist)
return {
svg: res.svg,
png: res.png,
icon: res.icon,
sprite: res.sprite,
dist: dist,
html: hydrate(smart.html, data)
}
} | [
"function",
"(",
"smart_filename",
",",
"package_filename",
")",
"{",
"var",
"smart",
"=",
"read",
"(",
"smart_filename",
")",
"var",
"data",
"=",
"{",
"global",
":",
"hydrate",
"(",
"smart",
".",
"global",
",",
"smart",
".",
"global",
")",
",",
"package",
":",
"read",
"(",
"package_filename",
")",
"}",
"var",
"dist",
"=",
"data",
".",
"global",
".",
"files",
".",
"dist",
"||",
"'dist'",
"var",
"res",
"=",
"resources",
"(",
"hydrate",
"(",
"smart",
".",
"template",
",",
"data",
")",
",",
"hydrate",
"(",
"smart",
".",
"data",
",",
"data",
")",
",",
"data",
".",
"global",
".",
"files",
".",
"concatenator",
",",
"dist",
")",
"return",
"{",
"svg",
":",
"res",
".",
"svg",
",",
"png",
":",
"res",
".",
"png",
",",
"icon",
":",
"res",
".",
"icon",
",",
"sprite",
":",
"res",
".",
"sprite",
",",
"dist",
":",
"dist",
",",
"html",
":",
"hydrate",
"(",
"smart",
".",
"html",
",",
"data",
")",
"}",
"}"
]
| Load and process the svg-smart json file
@param {smart_filename} string, the svg-smart json file
@param {package_filename} string, node.js package filename (reuse of information)
@return object, a list of resources to be generated (svg, png, ico, sprite) | [
"Load",
"and",
"process",
"the",
"svg",
"-",
"smart",
"json",
"file"
]
| d4a81574b2ef10a0f44b81a02ee9c898e97b4604 | https://github.com/websemantics/svg-smart/blob/d4a81574b2ef10a0f44b81a02ee9c898e97b4604/smart.js#L270-L289 | train |
|
noderaider/repackage | jspm_packages/npm/[email protected]/lib/transformation/transformers/validation/react.js | check | function check(source, file) {
if (t.isLiteral(source)) {
var name = source.value;
var lower = name.toLowerCase();
if (lower === "react" && name !== lower) {
throw file.errorWithNode(source, messages.get("didYouMean", "react"));
}
}
} | javascript | function check(source, file) {
if (t.isLiteral(source)) {
var name = source.value;
var lower = name.toLowerCase();
if (lower === "react" && name !== lower) {
throw file.errorWithNode(source, messages.get("didYouMean", "react"));
}
}
} | [
"function",
"check",
"(",
"source",
",",
"file",
")",
"{",
"if",
"(",
"t",
".",
"isLiteral",
"(",
"source",
")",
")",
"{",
"var",
"name",
"=",
"source",
".",
"value",
";",
"var",
"lower",
"=",
"name",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"lower",
"===",
"\"react\"",
"&&",
"name",
"!==",
"lower",
")",
"{",
"throw",
"file",
".",
"errorWithNode",
"(",
"source",
",",
"messages",
".",
"get",
"(",
"\"didYouMean\"",
",",
"\"react\"",
")",
")",
";",
"}",
"}",
"}"
]
| check if the input Literal `source` is an alternate casing of "react" | [
"check",
"if",
"the",
"input",
"Literal",
"source",
"is",
"an",
"alternate",
"casing",
"of",
"react"
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/transformation/transformers/validation/react.js#L19-L28 | train |
emmetio/html-snippets-resolver | index.js | merge | function merge(from, to) {
to.name = from.name;
if (from.selfClosing) {
to.selfClosing = true;
}
if (from.value != null) {
to.value = from.value;
}
if (from.repeat) {
to.repeat = Object.assign({}, from.repeat);
}
return mergeAttributes(from, to);
} | javascript | function merge(from, to) {
to.name = from.name;
if (from.selfClosing) {
to.selfClosing = true;
}
if (from.value != null) {
to.value = from.value;
}
if (from.repeat) {
to.repeat = Object.assign({}, from.repeat);
}
return mergeAttributes(from, to);
} | [
"function",
"merge",
"(",
"from",
",",
"to",
")",
"{",
"to",
".",
"name",
"=",
"from",
".",
"name",
";",
"if",
"(",
"from",
".",
"selfClosing",
")",
"{",
"to",
".",
"selfClosing",
"=",
"true",
";",
"}",
"if",
"(",
"from",
".",
"value",
"!=",
"null",
")",
"{",
"to",
".",
"value",
"=",
"from",
".",
"value",
";",
"}",
"if",
"(",
"from",
".",
"repeat",
")",
"{",
"to",
".",
"repeat",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"from",
".",
"repeat",
")",
";",
"}",
"return",
"mergeAttributes",
"(",
"from",
",",
"to",
")",
";",
"}"
]
| Adds data from first node into second node and returns it
@param {Node} from
@param {Node} to
@return {Node} | [
"Adds",
"data",
"from",
"first",
"node",
"into",
"second",
"node",
"and",
"returns",
"it"
]
| a65d8f769af1ea12f8edc031bf37ddeb3383f9e8 | https://github.com/emmetio/html-snippets-resolver/blob/a65d8f769af1ea12f8edc031bf37ddeb3383f9e8/index.js#L69-L85 | train |
emmetio/html-snippets-resolver | index.js | mergeClassNames | function mergeClassNames(from, to) {
const classNames = from.classList;
for (let i = 0; i < classNames.length; i++) {
to.addClass(classNames[i]);
}
return to;
} | javascript | function mergeClassNames(from, to) {
const classNames = from.classList;
for (let i = 0; i < classNames.length; i++) {
to.addClass(classNames[i]);
}
return to;
} | [
"function",
"mergeClassNames",
"(",
"from",
",",
"to",
")",
"{",
"const",
"classNames",
"=",
"from",
".",
"classList",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"classNames",
".",
"length",
";",
"i",
"++",
")",
"{",
"to",
".",
"addClass",
"(",
"classNames",
"[",
"i",
"]",
")",
";",
"}",
"return",
"to",
";",
"}"
]
| Adds class names from first node to second one
@param {Node} from
@param {Node} to
@return {Node} | [
"Adds",
"class",
"names",
"from",
"first",
"node",
"to",
"second",
"one"
]
| a65d8f769af1ea12f8edc031bf37ddeb3383f9e8 | https://github.com/emmetio/html-snippets-resolver/blob/a65d8f769af1ea12f8edc031bf37ddeb3383f9e8/index.js#L140-L147 | train |
emmetio/html-snippets-resolver | index.js | findDeepestNode | function findDeepestNode(node) {
while (node.children.length) {
node = node.children[node.children.length - 1];
}
return node;
} | javascript | function findDeepestNode(node) {
while (node.children.length) {
node = node.children[node.children.length - 1];
}
return node;
} | [
"function",
"findDeepestNode",
"(",
"node",
")",
"{",
"while",
"(",
"node",
".",
"children",
".",
"length",
")",
"{",
"node",
"=",
"node",
".",
"children",
"[",
"node",
".",
"children",
".",
"length",
"-",
"1",
"]",
";",
"}",
"return",
"node",
";",
"}"
]
| Finds node which is the deepest for in current node or node itself.
@param {Node} node
@return {Node} | [
"Finds",
"node",
"which",
"is",
"the",
"deepest",
"for",
"in",
"current",
"node",
"or",
"node",
"itself",
"."
]
| a65d8f769af1ea12f8edc031bf37ddeb3383f9e8 | https://github.com/emmetio/html-snippets-resolver/blob/a65d8f769af1ea12f8edc031bf37ddeb3383f9e8/index.js#L154-L160 | train |
skerit/protoblast | lib/request_browser.js | done | function done() {
if (!error && xhr.status > 399) {
error = new Error(xhr.statusText);
error.status = error.number = xhr.status;
}
if (type && type.indexOf('json') > -1 && result) {
result = Collection.JSON.undry(result);
}
if (error) {
error.result = result;
pledge.reject(error);
that.error = error;
} else {
that.result = result;
pledge.resolve(result);
}
} | javascript | function done() {
if (!error && xhr.status > 399) {
error = new Error(xhr.statusText);
error.status = error.number = xhr.status;
}
if (type && type.indexOf('json') > -1 && result) {
result = Collection.JSON.undry(result);
}
if (error) {
error.result = result;
pledge.reject(error);
that.error = error;
} else {
that.result = result;
pledge.resolve(result);
}
} | [
"function",
"done",
"(",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"xhr",
".",
"status",
">",
"399",
")",
"{",
"error",
"=",
"new",
"Error",
"(",
"xhr",
".",
"statusText",
")",
";",
"error",
".",
"status",
"=",
"error",
".",
"number",
"=",
"xhr",
".",
"status",
";",
"}",
"if",
"(",
"type",
"&&",
"type",
".",
"indexOf",
"(",
"'json'",
")",
">",
"-",
"1",
"&&",
"result",
")",
"{",
"result",
"=",
"Collection",
".",
"JSON",
".",
"undry",
"(",
"result",
")",
";",
"}",
"if",
"(",
"error",
")",
"{",
"error",
".",
"result",
"=",
"result",
";",
"pledge",
".",
"reject",
"(",
"error",
")",
";",
"that",
".",
"error",
"=",
"error",
";",
"}",
"else",
"{",
"that",
".",
"result",
"=",
"result",
";",
"pledge",
".",
"resolve",
"(",
"result",
")",
";",
"}",
"}"
]
| Function that'll cleanup the request & resolve or reject the pledge | [
"Function",
"that",
"ll",
"cleanup",
"the",
"request",
"&",
"resolve",
"or",
"reject",
"the",
"pledge"
]
| 22f35b05611bd507d380782023179a3f6ec383ae | https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/request_browser.js#L173-L192 | train |
M6Web/immutable-set | src/set.js | set | function set(base, path, value, { withArrays, sameValue }) {
if (path.length === 0) {
return value;
}
const [key, nextKey] = path;
const isArrayKeys = Array.isArray(key);
let currentBase = base;
if (!base || typeof base !== 'object') {
currentBase = (isArrayKeys && typeof key[0] === 'number') || (withArrays && typeof key === 'number') ? [] : {};
}
if (isArrayKeys) {
if (Array.isArray(currentBase)) {
return reduceWithArray(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, [...currentBase]);
}
return {
...currentBase,
...reduceWithObject(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, {}),
};
}
if (Array.isArray(currentBase)) {
return [
...currentBase.slice(0, key),
set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }),
...currentBase.slice(key + 1),
];
}
return {
...currentBase,
[key]: set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }),
};
} | javascript | function set(base, path, value, { withArrays, sameValue }) {
if (path.length === 0) {
return value;
}
const [key, nextKey] = path;
const isArrayKeys = Array.isArray(key);
let currentBase = base;
if (!base || typeof base !== 'object') {
currentBase = (isArrayKeys && typeof key[0] === 'number') || (withArrays && typeof key === 'number') ? [] : {};
}
if (isArrayKeys) {
if (Array.isArray(currentBase)) {
return reduceWithArray(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, [...currentBase]);
}
return {
...currentBase,
...reduceWithObject(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, {}),
};
}
if (Array.isArray(currentBase)) {
return [
...currentBase.slice(0, key),
set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }),
...currentBase.slice(key + 1),
];
}
return {
...currentBase,
[key]: set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }),
};
} | [
"function",
"set",
"(",
"base",
",",
"path",
",",
"value",
",",
"{",
"withArrays",
",",
"sameValue",
"}",
")",
"{",
"if",
"(",
"path",
".",
"length",
"===",
"0",
")",
"{",
"return",
"value",
";",
"}",
"const",
"[",
"key",
",",
"nextKey",
"]",
"=",
"path",
";",
"const",
"isArrayKeys",
"=",
"Array",
".",
"isArray",
"(",
"key",
")",
";",
"let",
"currentBase",
"=",
"base",
";",
"if",
"(",
"!",
"base",
"||",
"typeof",
"base",
"!==",
"'object'",
")",
"{",
"currentBase",
"=",
"(",
"isArrayKeys",
"&&",
"typeof",
"key",
"[",
"0",
"]",
"===",
"'number'",
")",
"||",
"(",
"withArrays",
"&&",
"typeof",
"key",
"===",
"'number'",
")",
"?",
"[",
"]",
":",
"{",
"}",
";",
"}",
"if",
"(",
"isArrayKeys",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"currentBase",
")",
")",
"{",
"return",
"reduceWithArray",
"(",
"set",
")",
"(",
"currentBase",
",",
"path",
",",
"key",
",",
"nextKey",
",",
"value",
",",
"{",
"withArrays",
",",
"sameValue",
"}",
",",
"[",
"...",
"currentBase",
"]",
")",
";",
"}",
"return",
"{",
"...",
"currentBase",
",",
"...",
"reduceWithObject",
"(",
"set",
")",
"(",
"currentBase",
",",
"path",
",",
"key",
",",
"nextKey",
",",
"value",
",",
"{",
"withArrays",
",",
"sameValue",
"}",
",",
"{",
"}",
")",
",",
"}",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"currentBase",
")",
")",
"{",
"return",
"[",
"...",
"currentBase",
".",
"slice",
"(",
"0",
",",
"key",
")",
",",
"set",
"(",
"nextBase",
"(",
"currentBase",
",",
"key",
",",
"nextKey",
",",
"withArrays",
")",
",",
"path",
".",
"slice",
"(",
"1",
")",
",",
"value",
",",
"{",
"withArrays",
",",
"sameValue",
"}",
")",
",",
"...",
"currentBase",
".",
"slice",
"(",
"key",
"+",
"1",
")",
",",
"]",
";",
"}",
"return",
"{",
"...",
"currentBase",
",",
"[",
"key",
"]",
":",
"set",
"(",
"nextBase",
"(",
"currentBase",
",",
"key",
",",
"nextKey",
",",
"withArrays",
")",
",",
"path",
".",
"slice",
"(",
"1",
")",
",",
"value",
",",
"{",
"withArrays",
",",
"sameValue",
"}",
")",
",",
"}",
";",
"}"
]
| Recursive immutable set
@param base current base
@param path current path
@param value current value
@param config
- withArrays create arrays instead of object when nextKey is a number and key has no value in the current base
- sameValue use the same value for each element
@returns {*} a new instance of the given level | [
"Recursive",
"immutable",
"set"
]
| 8e096b74959abdd1a7489d51b76f989def02c7d8 | https://github.com/M6Web/immutable-set/blob/8e096b74959abdd1a7489d51b76f989def02c7d8/src/set.js#L93-L129 | train |
NotNinja/node-blinkt | src/blinkt.js | show | function show() {
if (dat == null && clk == null) {
dat = new Gpio(23, 'out');
clk = new Gpio(24, 'out');
}
sof();
var pixel;
for (var i = 0, length = pixels.length; i < length; i++) {
pixel = pixels[i];
writeByte(0xe0 | pixel[3]);
writeByte(pixel[2]);
writeByte(pixel[1]);
writeByte(pixel[0]);
}
eof();
} | javascript | function show() {
if (dat == null && clk == null) {
dat = new Gpio(23, 'out');
clk = new Gpio(24, 'out');
}
sof();
var pixel;
for (var i = 0, length = pixels.length; i < length; i++) {
pixel = pixels[i];
writeByte(0xe0 | pixel[3]);
writeByte(pixel[2]);
writeByte(pixel[1]);
writeByte(pixel[0]);
}
eof();
} | [
"function",
"show",
"(",
")",
"{",
"if",
"(",
"dat",
"==",
"null",
"&&",
"clk",
"==",
"null",
")",
"{",
"dat",
"=",
"new",
"Gpio",
"(",
"23",
",",
"'out'",
")",
";",
"clk",
"=",
"new",
"Gpio",
"(",
"24",
",",
"'out'",
")",
";",
"}",
"sof",
"(",
")",
";",
"var",
"pixel",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"length",
"=",
"pixels",
".",
"length",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"pixel",
"=",
"pixels",
"[",
"i",
"]",
";",
"writeByte",
"(",
"0xe0",
"|",
"pixel",
"[",
"3",
"]",
")",
";",
"writeByte",
"(",
"pixel",
"[",
"2",
"]",
")",
";",
"writeByte",
"(",
"pixel",
"[",
"1",
"]",
")",
";",
"writeByte",
"(",
"pixel",
"[",
"0",
"]",
")",
";",
"}",
"eof",
"(",
")",
";",
"}"
]
| Outputs the buffer to Blinkt!
@return {void}
@public | [
"Outputs",
"the",
"buffer",
"to",
"Blinkt!"
]
| 95d85ea46901f3a90c63082fec1f974e04d23b50 | https://github.com/NotNinja/node-blinkt/blob/95d85ea46901f3a90c63082fec1f974e04d23b50/src/blinkt.js#L166-L186 | train |
webgme/ui-replay | src/visualizers/widgets/UIReplay/UIReplayCommitBadge.js | function (containerEl, client, params) {
var self = this,
index = params.index;
this._client = client;
this._commitHash = params.id;
if (typeof index === 'number') {
// Add some margins just in case.
this._n = index > 90 ? index + 20 : 100;
} else {
// Until webgme v2.18.0 look through 300 commits.
this._n = 300;
}
this._destroyed = false;
this.$el = $('<i>', {
class: 'fa fa-video-camera ui-replay-commit-status-icon loading'
});
$(containerEl).append(this.$el);
RecordReplayControllers.getStatus(client.getActiveProjectId(), this._commitHash, function (err, status) {
if (self._destroyed) {
return;
}
self.$el.removeClass('loading');
if (err) {
self.$el.addClass('error');
self.$el.attr('title', 'Errored');
} else if (status.exists === true) {
self.$el.addClass('success');
self.$el.attr('title', 'Start playback to current commit from this commit');
self.$el.on('click', function () {
self._showReplayDialog();
});
} else {
self.$el.addClass('unavailable');
self.$el.attr('title', 'No recording available');
}
});
} | javascript | function (containerEl, client, params) {
var self = this,
index = params.index;
this._client = client;
this._commitHash = params.id;
if (typeof index === 'number') {
// Add some margins just in case.
this._n = index > 90 ? index + 20 : 100;
} else {
// Until webgme v2.18.0 look through 300 commits.
this._n = 300;
}
this._destroyed = false;
this.$el = $('<i>', {
class: 'fa fa-video-camera ui-replay-commit-status-icon loading'
});
$(containerEl).append(this.$el);
RecordReplayControllers.getStatus(client.getActiveProjectId(), this._commitHash, function (err, status) {
if (self._destroyed) {
return;
}
self.$el.removeClass('loading');
if (err) {
self.$el.addClass('error');
self.$el.attr('title', 'Errored');
} else if (status.exists === true) {
self.$el.addClass('success');
self.$el.attr('title', 'Start playback to current commit from this commit');
self.$el.on('click', function () {
self._showReplayDialog();
});
} else {
self.$el.addClass('unavailable');
self.$el.attr('title', 'No recording available');
}
});
} | [
"function",
"(",
"containerEl",
",",
"client",
",",
"params",
")",
"{",
"var",
"self",
"=",
"this",
",",
"index",
"=",
"params",
".",
"index",
";",
"this",
".",
"_client",
"=",
"client",
";",
"this",
".",
"_commitHash",
"=",
"params",
".",
"id",
";",
"if",
"(",
"typeof",
"index",
"===",
"'number'",
")",
"{",
"this",
".",
"_n",
"=",
"index",
">",
"90",
"?",
"index",
"+",
"20",
":",
"100",
";",
"}",
"else",
"{",
"this",
".",
"_n",
"=",
"300",
";",
"}",
"this",
".",
"_destroyed",
"=",
"false",
";",
"this",
".",
"$el",
"=",
"$",
"(",
"'<i>'",
",",
"{",
"class",
":",
"'fa fa-video-camera ui-replay-commit-status-icon loading'",
"}",
")",
";",
"$",
"(",
"containerEl",
")",
".",
"append",
"(",
"this",
".",
"$el",
")",
";",
"RecordReplayControllers",
".",
"getStatus",
"(",
"client",
".",
"getActiveProjectId",
"(",
")",
",",
"this",
".",
"_commitHash",
",",
"function",
"(",
"err",
",",
"status",
")",
"{",
"if",
"(",
"self",
".",
"_destroyed",
")",
"{",
"return",
";",
"}",
"self",
".",
"$el",
".",
"removeClass",
"(",
"'loading'",
")",
";",
"if",
"(",
"err",
")",
"{",
"self",
".",
"$el",
".",
"addClass",
"(",
"'error'",
")",
";",
"self",
".",
"$el",
".",
"attr",
"(",
"'title'",
",",
"'Errored'",
")",
";",
"}",
"else",
"if",
"(",
"status",
".",
"exists",
"===",
"true",
")",
"{",
"self",
".",
"$el",
".",
"addClass",
"(",
"'success'",
")",
";",
"self",
".",
"$el",
".",
"attr",
"(",
"'title'",
",",
"'Start playback to current commit from this commit'",
")",
";",
"self",
".",
"$el",
".",
"on",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"self",
".",
"_showReplayDialog",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"self",
".",
"$el",
".",
"addClass",
"(",
"'unavailable'",
")",
";",
"self",
".",
"$el",
".",
"attr",
"(",
"'title'",
",",
"'No recording available'",
")",
";",
"}",
"}",
")",
";",
"}"
]
| var STATUS_CLASSES = 'loading success unavailable error'; | [
"var",
"STATUS_CLASSES",
"=",
"loading",
"success",
"unavailable",
"error",
";"
]
| 0e0ad90b044d92cd508af03246ce0e9cbc382097 | https://github.com/webgme/ui-replay/blob/0e0ad90b044d92cd508af03246ce0e9cbc382097/src/visualizers/widgets/UIReplay/UIReplayCommitBadge.js#L15-L58 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.