id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
40,100
jlas/quirky
game-client.js
drawChatIn
function drawChatIn() { $(CHATIN).show(); function submit() { var chatin = $(CHATIN+"> input")[0].value; if (!CHATRE.test(chatin)) { if(chatin) { alert("Your input text is too long!"); } return false; } var game = $.cookie("game"); var resource; if (game) { resource = "/games/" + enc(game) + "/chat"; } else { resource = "/chat"; } $.post(resource, { input: chatin, name: $.cookie("player") }, function() { $(CHATIN+"> input").val(''); // post was succesful, so clear input drawChatLog(); }); } $(CHATIN+"> button").click(submit); $(CHATIN+"> input:visible").focus(); $(CHATIN+"> input").keydown(function(event) { if (event.keyCode === 13) { submit(); } }); }
javascript
function drawChatIn() { $(CHATIN).show(); function submit() { var chatin = $(CHATIN+"> input")[0].value; if (!CHATRE.test(chatin)) { if(chatin) { alert("Your input text is too long!"); } return false; } var game = $.cookie("game"); var resource; if (game) { resource = "/games/" + enc(game) + "/chat"; } else { resource = "/chat"; } $.post(resource, { input: chatin, name: $.cookie("player") }, function() { $(CHATIN+"> input").val(''); // post was succesful, so clear input drawChatLog(); }); } $(CHATIN+"> button").click(submit); $(CHATIN+"> input:visible").focus(); $(CHATIN+"> input").keydown(function(event) { if (event.keyCode === 13) { submit(); } }); }
[ "function", "drawChatIn", "(", ")", "{", "$", "(", "CHATIN", ")", ".", "show", "(", ")", ";", "function", "submit", "(", ")", "{", "var", "chatin", "=", "$", "(", "CHATIN", "+", "\"> input\"", ")", "[", "0", "]", ".", "value", ";", "if", "(", "!", "CHATRE", ".", "test", "(", "chatin", ")", ")", "{", "if", "(", "chatin", ")", "{", "alert", "(", "\"Your input text is too long!\"", ")", ";", "}", "return", "false", ";", "}", "var", "game", "=", "$", ".", "cookie", "(", "\"game\"", ")", ";", "var", "resource", ";", "if", "(", "game", ")", "{", "resource", "=", "\"/games/\"", "+", "enc", "(", "game", ")", "+", "\"/chat\"", ";", "}", "else", "{", "resource", "=", "\"/chat\"", ";", "}", "$", ".", "post", "(", "resource", ",", "{", "input", ":", "chatin", ",", "name", ":", "$", ".", "cookie", "(", "\"player\"", ")", "}", ",", "function", "(", ")", "{", "$", "(", "CHATIN", "+", "\"> input\"", ")", ".", "val", "(", "''", ")", ";", "// post was succesful, so clear input", "drawChatLog", "(", ")", ";", "}", ")", ";", "}", "$", "(", "CHATIN", "+", "\"> button\"", ")", ".", "click", "(", "submit", ")", ";", "$", "(", "CHATIN", "+", "\"> input:visible\"", ")", ".", "focus", "(", ")", ";", "$", "(", "CHATIN", "+", "\"> input\"", ")", ".", "keydown", "(", "function", "(", "event", ")", "{", "if", "(", "event", ".", "keyCode", "===", "13", ")", "{", "submit", "(", ")", ";", "}", "}", ")", ";", "}" ]
Draw the chat input.
[ "Draw", "the", "chat", "input", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L400-L432
40,101
jlas/quirky
game-client.js
drawAddGuest
function drawAddGuest() { $(ADDGUEST).show(); function submit() { var name = $(ADDGUESTFRM+"> input")[0].value; if (!NAMERE.test(name)) { if(name) { alert("Your input text is too long!"); } return false; } $.cookie("player", name); main(); } $(ADDGUESTFRM+"> button").click(submit); $(ADDGUESTFRM+"> input:visible").focus(); $(ADDGUESTFRM+"> input").keydown(function(event) { if (event.keyCode === 13) { submit(); } }); }
javascript
function drawAddGuest() { $(ADDGUEST).show(); function submit() { var name = $(ADDGUESTFRM+"> input")[0].value; if (!NAMERE.test(name)) { if(name) { alert("Your input text is too long!"); } return false; } $.cookie("player", name); main(); } $(ADDGUESTFRM+"> button").click(submit); $(ADDGUESTFRM+"> input:visible").focus(); $(ADDGUESTFRM+"> input").keydown(function(event) { if (event.keyCode === 13) { submit(); } }); }
[ "function", "drawAddGuest", "(", ")", "{", "$", "(", "ADDGUEST", ")", ".", "show", "(", ")", ";", "function", "submit", "(", ")", "{", "var", "name", "=", "$", "(", "ADDGUESTFRM", "+", "\"> input\"", ")", "[", "0", "]", ".", "value", ";", "if", "(", "!", "NAMERE", ".", "test", "(", "name", ")", ")", "{", "if", "(", "name", ")", "{", "alert", "(", "\"Your input text is too long!\"", ")", ";", "}", "return", "false", ";", "}", "$", ".", "cookie", "(", "\"player\"", ",", "name", ")", ";", "main", "(", ")", ";", "}", "$", "(", "ADDGUESTFRM", "+", "\"> button\"", ")", ".", "click", "(", "submit", ")", ";", "$", "(", "ADDGUESTFRM", "+", "\"> input:visible\"", ")", ".", "focus", "(", ")", ";", "$", "(", "ADDGUESTFRM", "+", "\"> input\"", ")", ".", "keydown", "(", "function", "(", "event", ")", "{", "if", "(", "event", ".", "keyCode", "===", "13", ")", "{", "submit", "(", ")", ";", "}", "}", ")", ";", "}" ]
Draw the add guest widget. - Set the player cookie when the user submits and switch to displaying the chat input.
[ "Draw", "the", "add", "guest", "widget", ".", "-", "Set", "the", "player", "cookie", "when", "the", "user", "submits", "and", "switch", "to", "displaying", "the", "chat", "input", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L439-L460
40,102
jlas/quirky
game-client.js
drawLobby
function drawLobby(games) { $(LOBBYCHAT).append($(CHATPNL)[0]); $(CHATPNL).addClass('lobby_chat_panel'); drawGameList(games); // setup future calls to get game list function pollGames() { $.getJSON("/games", drawGameList); GETGAMESTID = setTimeout(pollGames, 2000); } GETGAMESTID = setTimeout(pollGames, 2000); }
javascript
function drawLobby(games) { $(LOBBYCHAT).append($(CHATPNL)[0]); $(CHATPNL).addClass('lobby_chat_panel'); drawGameList(games); // setup future calls to get game list function pollGames() { $.getJSON("/games", drawGameList); GETGAMESTID = setTimeout(pollGames, 2000); } GETGAMESTID = setTimeout(pollGames, 2000); }
[ "function", "drawLobby", "(", "games", ")", "{", "$", "(", "LOBBYCHAT", ")", ".", "append", "(", "$", "(", "CHATPNL", ")", "[", "0", "]", ")", ";", "$", "(", "CHATPNL", ")", ".", "addClass", "(", "'lobby_chat_panel'", ")", ";", "drawGameList", "(", "games", ")", ";", "// setup future calls to get game list", "function", "pollGames", "(", ")", "{", "$", ".", "getJSON", "(", "\"/games\"", ",", "drawGameList", ")", ";", "GETGAMESTID", "=", "setTimeout", "(", "pollGames", ",", "2000", ")", ";", "}", "GETGAMESTID", "=", "setTimeout", "(", "pollGames", ",", "2000", ")", ";", "}" ]
Draw the lobby.
[ "Draw", "the", "lobby", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L588-L599
40,103
jlas/quirky
game-client.js
drawGame
function drawGame() { getPlayers(); getBoard(); getPiecesLeft(); $(SIDEBOARD).append("<hr/>"); $(SIDEBOARD).append($(CHATPNL)); $(CHATPNL).addClass('game_chat_panel'); $(LEAVEGAME)[0].onclick = function () { clearTimeout(GETPLAYERSTID); $.ajax({ type: 'DELETE', url: "/games/" + enc($.cookie("game")) + "/players", data: {name: $.cookie("player")}, success: function() { $.removeCookie('game'); location.reload(); } }); }; // setup future calls function pollPlayers() { getPlayers(); GETPLAYERSTID = setTimeout(pollPlayers, 2000); } GETPLAYERSTID = setTimeout(pollPlayers, 2000); }
javascript
function drawGame() { getPlayers(); getBoard(); getPiecesLeft(); $(SIDEBOARD).append("<hr/>"); $(SIDEBOARD).append($(CHATPNL)); $(CHATPNL).addClass('game_chat_panel'); $(LEAVEGAME)[0].onclick = function () { clearTimeout(GETPLAYERSTID); $.ajax({ type: 'DELETE', url: "/games/" + enc($.cookie("game")) + "/players", data: {name: $.cookie("player")}, success: function() { $.removeCookie('game'); location.reload(); } }); }; // setup future calls function pollPlayers() { getPlayers(); GETPLAYERSTID = setTimeout(pollPlayers, 2000); } GETPLAYERSTID = setTimeout(pollPlayers, 2000); }
[ "function", "drawGame", "(", ")", "{", "getPlayers", "(", ")", ";", "getBoard", "(", ")", ";", "getPiecesLeft", "(", ")", ";", "$", "(", "SIDEBOARD", ")", ".", "append", "(", "\"<hr/>\"", ")", ";", "$", "(", "SIDEBOARD", ")", ".", "append", "(", "$", "(", "CHATPNL", ")", ")", ";", "$", "(", "CHATPNL", ")", ".", "addClass", "(", "'game_chat_panel'", ")", ";", "$", "(", "LEAVEGAME", ")", "[", "0", "]", ".", "onclick", "=", "function", "(", ")", "{", "clearTimeout", "(", "GETPLAYERSTID", ")", ";", "$", ".", "ajax", "(", "{", "type", ":", "'DELETE'", ",", "url", ":", "\"/games/\"", "+", "enc", "(", "$", ".", "cookie", "(", "\"game\"", ")", ")", "+", "\"/players\"", ",", "data", ":", "{", "name", ":", "$", ".", "cookie", "(", "\"player\"", ")", "}", ",", "success", ":", "function", "(", ")", "{", "$", ".", "removeCookie", "(", "'game'", ")", ";", "location", ".", "reload", "(", ")", ";", "}", "}", ")", ";", "}", ";", "// setup future calls", "function", "pollPlayers", "(", ")", "{", "getPlayers", "(", ")", ";", "GETPLAYERSTID", "=", "setTimeout", "(", "pollPlayers", ",", "2000", ")", ";", "}", "GETPLAYERSTID", "=", "setTimeout", "(", "pollPlayers", ",", "2000", ")", ";", "}" ]
Draw the game.
[ "Draw", "the", "game", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L604-L630
40,104
jlas/quirky
game-client.js
gameOrLobby
function gameOrLobby(games) { $(LOBBY).hide(); $(GAMEROOM).hide(); $(ADDGUEST).hide(); if (!$.cookie("player")) { drawAddGuest(); return; } // hide the fork me banner from now on $(FORKME).hide(); var my_game = $.cookie("game"); // User is not in a valid game if (typeof games[my_game] === 'undefined') { $.removeCookie('game'); $(LOBBY).show(); drawLobby(games); } else { $(GAMEROOM).show(); drawGame(); } $(CHATPNL).show(); drawChatLog(); drawChatIn(); // setup future calls to get chat function pollChat() { drawChatLog(); DRAWCHATTID = setTimeout(pollChat, 2000); } DRAWCHATTID = setTimeout(pollChat, 2000); }
javascript
function gameOrLobby(games) { $(LOBBY).hide(); $(GAMEROOM).hide(); $(ADDGUEST).hide(); if (!$.cookie("player")) { drawAddGuest(); return; } // hide the fork me banner from now on $(FORKME).hide(); var my_game = $.cookie("game"); // User is not in a valid game if (typeof games[my_game] === 'undefined') { $.removeCookie('game'); $(LOBBY).show(); drawLobby(games); } else { $(GAMEROOM).show(); drawGame(); } $(CHATPNL).show(); drawChatLog(); drawChatIn(); // setup future calls to get chat function pollChat() { drawChatLog(); DRAWCHATTID = setTimeout(pollChat, 2000); } DRAWCHATTID = setTimeout(pollChat, 2000); }
[ "function", "gameOrLobby", "(", "games", ")", "{", "$", "(", "LOBBY", ")", ".", "hide", "(", ")", ";", "$", "(", "GAMEROOM", ")", ".", "hide", "(", ")", ";", "$", "(", "ADDGUEST", ")", ".", "hide", "(", ")", ";", "if", "(", "!", "$", ".", "cookie", "(", "\"player\"", ")", ")", "{", "drawAddGuest", "(", ")", ";", "return", ";", "}", "// hide the fork me banner from now on", "$", "(", "FORKME", ")", ".", "hide", "(", ")", ";", "var", "my_game", "=", "$", ".", "cookie", "(", "\"game\"", ")", ";", "// User is not in a valid game", "if", "(", "typeof", "games", "[", "my_game", "]", "===", "'undefined'", ")", "{", "$", ".", "removeCookie", "(", "'game'", ")", ";", "$", "(", "LOBBY", ")", ".", "show", "(", ")", ";", "drawLobby", "(", "games", ")", ";", "}", "else", "{", "$", "(", "GAMEROOM", ")", ".", "show", "(", ")", ";", "drawGame", "(", ")", ";", "}", "$", "(", "CHATPNL", ")", ".", "show", "(", ")", ";", "drawChatLog", "(", ")", ";", "drawChatIn", "(", ")", ";", "// setup future calls to get chat", "function", "pollChat", "(", ")", "{", "drawChatLog", "(", ")", ";", "DRAWCHATTID", "=", "setTimeout", "(", "pollChat", ",", "2000", ")", ";", "}", "DRAWCHATTID", "=", "setTimeout", "(", "pollChat", ",", "2000", ")", ";", "}" ]
Display the lobby, a game room, or the add guest for the user.
[ "Display", "the", "lobby", "a", "game", "room", "or", "the", "add", "guest", "for", "the", "user", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game-client.js#L635-L668
40,105
WindomZ/fmtconv
lib/converter.js
fmtconv
function fmtconv (input, output, compact = false) { if (!input) { throw new TypeError('"input" argument must be a file path') } else if (!output) { throw new TypeError('"output" argument must be a file path') } let extInput = path.extname(input).toLowerCase() if (extInput !== '.yaml' && extInput !== '.yml' && extInput !== '.json') { throw new TypeError('"input" file extension must be ".yaml" or ".yml" or ".json"') } let extOutput = path.extname(output).toLowerCase() if (extOutput !== '.yaml' && extOutput !== '.yml' && extOutput !== '.json') { throw new TypeError('"output" file extension must be ".yaml" or ".yml" or ".json"') } fs.accessSync(input, fs.R_OK) let doc = '' + fs.readFileSync(input) switch (extInput) { case '.yaml': case '.yml': switch (extOutput) { case '.json': fs.writeFileSync(output, transcode.stringYAML2JSON(doc, compact), null) break default: fs.writeFileSync(output, transcode.stringYAML2YAML(doc, compact), null) break } break case '.json': switch (extOutput) { case '.yaml': case '.yml': fs.writeFileSync(output, transcode.stringJSON2YAML(doc, compact), null) break default: fs.writeFileSync(output, transcode.stringJSON2JSON(doc, compact), null) break } break } }
javascript
function fmtconv (input, output, compact = false) { if (!input) { throw new TypeError('"input" argument must be a file path') } else if (!output) { throw new TypeError('"output" argument must be a file path') } let extInput = path.extname(input).toLowerCase() if (extInput !== '.yaml' && extInput !== '.yml' && extInput !== '.json') { throw new TypeError('"input" file extension must be ".yaml" or ".yml" or ".json"') } let extOutput = path.extname(output).toLowerCase() if (extOutput !== '.yaml' && extOutput !== '.yml' && extOutput !== '.json') { throw new TypeError('"output" file extension must be ".yaml" or ".yml" or ".json"') } fs.accessSync(input, fs.R_OK) let doc = '' + fs.readFileSync(input) switch (extInput) { case '.yaml': case '.yml': switch (extOutput) { case '.json': fs.writeFileSync(output, transcode.stringYAML2JSON(doc, compact), null) break default: fs.writeFileSync(output, transcode.stringYAML2YAML(doc, compact), null) break } break case '.json': switch (extOutput) { case '.yaml': case '.yml': fs.writeFileSync(output, transcode.stringJSON2YAML(doc, compact), null) break default: fs.writeFileSync(output, transcode.stringJSON2JSON(doc, compact), null) break } break } }
[ "function", "fmtconv", "(", "input", ",", "output", ",", "compact", "=", "false", ")", "{", "if", "(", "!", "input", ")", "{", "throw", "new", "TypeError", "(", "'\"input\" argument must be a file path'", ")", "}", "else", "if", "(", "!", "output", ")", "{", "throw", "new", "TypeError", "(", "'\"output\" argument must be a file path'", ")", "}", "let", "extInput", "=", "path", ".", "extname", "(", "input", ")", ".", "toLowerCase", "(", ")", "if", "(", "extInput", "!==", "'.yaml'", "&&", "extInput", "!==", "'.yml'", "&&", "extInput", "!==", "'.json'", ")", "{", "throw", "new", "TypeError", "(", "'\"input\" file extension must be \".yaml\" or \".yml\" or \".json\"'", ")", "}", "let", "extOutput", "=", "path", ".", "extname", "(", "output", ")", ".", "toLowerCase", "(", ")", "if", "(", "extOutput", "!==", "'.yaml'", "&&", "extOutput", "!==", "'.yml'", "&&", "extOutput", "!==", "'.json'", ")", "{", "throw", "new", "TypeError", "(", "'\"output\" file extension must be \".yaml\" or \".yml\" or \".json\"'", ")", "}", "fs", ".", "accessSync", "(", "input", ",", "fs", ".", "R_OK", ")", "let", "doc", "=", "''", "+", "fs", ".", "readFileSync", "(", "input", ")", "switch", "(", "extInput", ")", "{", "case", "'.yaml'", ":", "case", "'.yml'", ":", "switch", "(", "extOutput", ")", "{", "case", "'.json'", ":", "fs", ".", "writeFileSync", "(", "output", ",", "transcode", ".", "stringYAML2JSON", "(", "doc", ",", "compact", ")", ",", "null", ")", "break", "default", ":", "fs", ".", "writeFileSync", "(", "output", ",", "transcode", ".", "stringYAML2YAML", "(", "doc", ",", "compact", ")", ",", "null", ")", "break", "}", "break", "case", "'.json'", ":", "switch", "(", "extOutput", ")", "{", "case", "'.yaml'", ":", "case", "'.yml'", ":", "fs", ".", "writeFileSync", "(", "output", ",", "transcode", ".", "stringJSON2YAML", "(", "doc", ",", "compact", ")", ",", "null", ")", "break", "default", ":", "fs", ".", "writeFileSync", "(", "output", ",", "transcode", ".", "stringJSON2JSON", "(", "doc", ",", "compact", ")", ",", "null", ")", "break", "}", "break", "}", "}" ]
Convert between JSON and YAML format files. @param {string} input @param {string} output @param {boolean} [compact] @api public
[ "Convert", "between", "JSON", "and", "YAML", "format", "files", "." ]
80923dc9d63714a92bac2f7d4f412a2b46c063a1
https://github.com/WindomZ/fmtconv/blob/80923dc9d63714a92bac2f7d4f412a2b46c063a1/lib/converter.js#L19-L64
40,106
andrglo/mssql-cr-layer
src/index.js
MssqlCrLayer
function MssqlCrLayer(config) { if (!(this instanceof MssqlCrLayer)) { return new MssqlCrLayer(config) } const mssqlConfig = toMssqlConfig(config) connectionParams.set(this, mssqlConfig) this.user = mssqlConfig.user this.database = mssqlConfig.database this.host = mssqlConfig.server this.port = mssqlConfig.port this.ISOLATION_LEVEL = (config && config.ISOLATION_LEVEL) || 'READ_COMMITTED' }
javascript
function MssqlCrLayer(config) { if (!(this instanceof MssqlCrLayer)) { return new MssqlCrLayer(config) } const mssqlConfig = toMssqlConfig(config) connectionParams.set(this, mssqlConfig) this.user = mssqlConfig.user this.database = mssqlConfig.database this.host = mssqlConfig.server this.port = mssqlConfig.port this.ISOLATION_LEVEL = (config && config.ISOLATION_LEVEL) || 'READ_COMMITTED' }
[ "function", "MssqlCrLayer", "(", "config", ")", "{", "if", "(", "!", "(", "this", "instanceof", "MssqlCrLayer", ")", ")", "{", "return", "new", "MssqlCrLayer", "(", "config", ")", "}", "const", "mssqlConfig", "=", "toMssqlConfig", "(", "config", ")", "connectionParams", ".", "set", "(", "this", ",", "mssqlConfig", ")", "this", ".", "user", "=", "mssqlConfig", ".", "user", "this", ".", "database", "=", "mssqlConfig", ".", "database", "this", ".", "host", "=", "mssqlConfig", ".", "server", "this", ".", "port", "=", "mssqlConfig", ".", "port", "this", ".", "ISOLATION_LEVEL", "=", "(", "config", "&&", "config", ".", "ISOLATION_LEVEL", ")", "||", "'READ_COMMITTED'", "}" ]
SQL Server common requests interface layer @param config {object} user: <username>, password: <password>, host: <host>, pool: { max: <max pool size>, idleTimeout: <idle timeout in milliseconds> } @returns {MssqlCrLayer} @constructor
[ "SQL", "Server", "common", "requests", "interface", "layer" ]
59d3f45a9a8a5bd93053a652c72df5dbf61833b6
https://github.com/andrglo/mssql-cr-layer/blob/59d3f45a9a8a5bd93053a652c72df5dbf61833b6/src/index.js#L25-L36
40,107
dreampiggy/functional.js
Retroactive/lib/data_structures/graph.js
Graph
function Graph(directed) { this.directed = (directed === undefined ? true : !!directed); this.adjList = Object.create(null); this.vertices = new HashSet(); }
javascript
function Graph(directed) { this.directed = (directed === undefined ? true : !!directed); this.adjList = Object.create(null); this.vertices = new HashSet(); }
[ "function", "Graph", "(", "directed", ")", "{", "this", ".", "directed", "=", "(", "directed", "===", "undefined", "?", "true", ":", "!", "!", "directed", ")", ";", "this", ".", "adjList", "=", "Object", ".", "create", "(", "null", ")", ";", "this", ".", "vertices", "=", "new", "HashSet", "(", ")", ";", "}" ]
Adjacency list representation of a graph @param {bool} directed
[ "Adjacency", "list", "representation", "of", "a", "graph" ]
ec7b7213de7965659a8a1e8fa61438e3ae564260
https://github.com/dreampiggy/functional.js/blob/ec7b7213de7965659a8a1e8fa61438e3ae564260/Retroactive/lib/data_structures/graph.js#L9-L13
40,108
KodersLab/react-native-for-web-stylesheet
lib/storage.js
pick
function pick(propName, propValue) { var possibleClassIds = Object.keys(storage[propName] || {}).filter(function (classId) { return (0, _lodash2.default)(storage[propName][classId], propValue); }); return possibleClassIds.length > 0 ? parseInt(possibleClassIds[0], 10) : null; }
javascript
function pick(propName, propValue) { var possibleClassIds = Object.keys(storage[propName] || {}).filter(function (classId) { return (0, _lodash2.default)(storage[propName][classId], propValue); }); return possibleClassIds.length > 0 ? parseInt(possibleClassIds[0], 10) : null; }
[ "function", "pick", "(", "propName", ",", "propValue", ")", "{", "var", "possibleClassIds", "=", "Object", ".", "keys", "(", "storage", "[", "propName", "]", "||", "{", "}", ")", ".", "filter", "(", "function", "(", "classId", ")", "{", "return", "(", "0", ",", "_lodash2", ".", "default", ")", "(", "storage", "[", "propName", "]", "[", "classId", "]", ",", "propValue", ")", ";", "}", ")", ";", "return", "possibleClassIds", ".", "length", ">", "0", "?", "parseInt", "(", "possibleClassIds", "[", "0", "]", ",", "10", ")", ":", "null", ";", "}" ]
get the classId
[ "get", "the", "classId" ]
963c70925aa8d3d6581c40afcccb3be31bf257b8
https://github.com/KodersLab/react-native-for-web-stylesheet/blob/963c70925aa8d3d6581c40afcccb3be31bf257b8/lib/storage.js#L20-L26
40,109
KodersLab/react-native-for-web-stylesheet
lib/storage.js
put
function put(propName, propValue, classId) { if (pick(propName, propValue)) return false; if (!classId) { nextClassId++; classId = nextClassId; } nextClassId = nextClassId < classId ? classId : nextClassId; storage[propName] = storage[propName] || {}; storage[propName][classId] = propValue; return true; }
javascript
function put(propName, propValue, classId) { if (pick(propName, propValue)) return false; if (!classId) { nextClassId++; classId = nextClassId; } nextClassId = nextClassId < classId ? classId : nextClassId; storage[propName] = storage[propName] || {}; storage[propName][classId] = propValue; return true; }
[ "function", "put", "(", "propName", ",", "propValue", ",", "classId", ")", "{", "if", "(", "pick", "(", "propName", ",", "propValue", ")", ")", "return", "false", ";", "if", "(", "!", "classId", ")", "{", "nextClassId", "++", ";", "classId", "=", "nextClassId", ";", "}", "nextClassId", "=", "nextClassId", "<", "classId", "?", "classId", ":", "nextClassId", ";", "storage", "[", "propName", "]", "=", "storage", "[", "propName", "]", "||", "{", "}", ";", "storage", "[", "propName", "]", "[", "classId", "]", "=", "propValue", ";", "return", "true", ";", "}" ]
sets the classId
[ "sets", "the", "classId" ]
963c70925aa8d3d6581c40afcccb3be31bf257b8
https://github.com/KodersLab/react-native-for-web-stylesheet/blob/963c70925aa8d3d6581c40afcccb3be31bf257b8/lib/storage.js#L29-L43
40,110
ben-eb/postcss-font-family
index.js
removeAfterKeyword
function removeAfterKeyword () { var hasKeyword = false; return function (family) { if (~keywords.indexOf(family)) { hasKeyword = true; return true; } return !hasKeyword; }; }
javascript
function removeAfterKeyword () { var hasKeyword = false; return function (family) { if (~keywords.indexOf(family)) { hasKeyword = true; return true; } return !hasKeyword; }; }
[ "function", "removeAfterKeyword", "(", ")", "{", "var", "hasKeyword", "=", "false", ";", "return", "function", "(", "family", ")", "{", "if", "(", "~", "keywords", ".", "indexOf", "(", "family", ")", ")", "{", "hasKeyword", "=", "true", ";", "return", "true", ";", "}", "return", "!", "hasKeyword", ";", "}", ";", "}" ]
No point in keeping the rest of the declaration after a keyword
[ "No", "point", "in", "keeping", "the", "rest", "of", "the", "declaration", "after", "a", "keyword" ]
22cb5bc3efc892b93e50763c5e07ce519e7eb453
https://github.com/ben-eb/postcss-font-family/blob/22cb5bc3efc892b93e50763c5e07ce519e7eb453/index.js#L22-L31
40,111
gdbots/common-js
src/isValidUri.js
urlStyleUriRegex
function urlStyleUriRegex() { const protocol = '(?:[A-Za-z]{3,9}://)'; const auth = '(?:\\S+(?::\\S*)?@)?'; const ipv4 = '(?:\\[?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\]?'; const host = '(?:(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)'; const domain = '(?:\\.(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)*'; const tld = '(?:\\.(?:[a-zA-Z]{2,}))\\.?'; const port = '(?::\\d{2,5})?'; const path = '(?:[/?#][\\x21-\\x7F]*)?'; // ascii no whitespaces const regex = `(?:${protocol}|www\\.)${auth}(?:localhost|${ipv4}|${host}${domain}${tld})${port}${path}`; return new RegExp(`^${regex}$`, 'i'); }
javascript
function urlStyleUriRegex() { const protocol = '(?:[A-Za-z]{3,9}://)'; const auth = '(?:\\S+(?::\\S*)?@)?'; const ipv4 = '(?:\\[?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\]?'; const host = '(?:(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)'; const domain = '(?:\\.(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)*'; const tld = '(?:\\.(?:[a-zA-Z]{2,}))\\.?'; const port = '(?::\\d{2,5})?'; const path = '(?:[/?#][\\x21-\\x7F]*)?'; // ascii no whitespaces const regex = `(?:${protocol}|www\\.)${auth}(?:localhost|${ipv4}|${host}${domain}${tld})${port}${path}`; return new RegExp(`^${regex}$`, 'i'); }
[ "function", "urlStyleUriRegex", "(", ")", "{", "const", "protocol", "=", "'(?:[A-Za-z]{3,9}://)'", ";", "const", "auth", "=", "'(?:\\\\S+(?::\\\\S*)?@)?'", ";", "const", "ipv4", "=", "'(?:\\\\[?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\\\]?'", ";", "const", "host", "=", "'(?:(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)'", ";", "const", "domain", "=", "'(?:\\\\.(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)*'", ";", "const", "tld", "=", "'(?:\\\\.(?:[a-zA-Z]{2,}))\\\\.?'", ";", "const", "port", "=", "'(?::\\\\d{2,5})?'", ";", "const", "path", "=", "'(?:[/?#][\\\\x21-\\\\x7F]*)?'", ";", "// ascii no whitespaces", "const", "regex", "=", "`", "${", "protocol", "}", "\\\\", "${", "auth", "}", "${", "ipv4", "}", "${", "host", "}", "${", "domain", "}", "${", "tld", "}", "${", "port", "}", "${", "path", "}", "`", ";", "return", "new", "RegExp", "(", "`", "${", "regex", "}", "`", ",", "'i'", ")", ";", "}" ]
Compose a url style uri regex The most common form of URI is the Uniform Resource Locator (URL), frequently referred to informally as a web address. More rarely seen in usage is the Uniform Resource Name (URN), which was designed to complement URLs by providing a mechanism for the identification of resources in particular namespaces. - scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] - https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
[ "Compose", "a", "url", "style", "uri", "regex" ]
a2aa6d68ed1ba525498d278a88571e664f0d4ac3
https://github.com/gdbots/common-js/blob/a2aa6d68ed1ba525498d278a88571e664f0d4ac3/src/isValidUri.js#L20-L32
40,112
trabus/ember-cli-mv
lib/tasks/verify-file.js
function(destPath) { var exists, stats; var dirpath = path.dirname(destPath); try{ stats = fs.lstatSync(dirpath); exists = stats.isDirectory(); } catch(e) { this.createDestDir = dirpath; } return !!exists; }
javascript
function(destPath) { var exists, stats; var dirpath = path.dirname(destPath); try{ stats = fs.lstatSync(dirpath); exists = stats.isDirectory(); } catch(e) { this.createDestDir = dirpath; } return !!exists; }
[ "function", "(", "destPath", ")", "{", "var", "exists", ",", "stats", ";", "var", "dirpath", "=", "path", ".", "dirname", "(", "destPath", ")", ";", "try", "{", "stats", "=", "fs", ".", "lstatSync", "(", "dirpath", ")", ";", "exists", "=", "stats", ".", "isDirectory", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "this", ".", "createDestDir", "=", "dirpath", ";", "}", "return", "!", "!", "exists", ";", "}" ]
determine if we need to create the destination directory
[ "determine", "if", "we", "need", "to", "create", "the", "destination", "directory" ]
3887906b48de90f74c8c0f5a74697609f83e792b
https://github.com/trabus/ember-cli-mv/blob/3887906b48de90f74c8c0f5a74697609f83e792b/lib/tasks/verify-file.js#L64-L74
40,113
trabus/ember-cli-mv
lib/tasks/verify-file.js
function(destPath) { this.checkDestDir(destPath); var exists = existsSync(destPath); // we warn if // if (exists) { // this.ui.writeLine('The destination path: ' + destPath + ' already exists. Cannot overrwrite.', 'WARNING'); // } return { destExists: exists, destDir: this.createDestDir }; }
javascript
function(destPath) { this.checkDestDir(destPath); var exists = existsSync(destPath); // we warn if // if (exists) { // this.ui.writeLine('The destination path: ' + destPath + ' already exists. Cannot overrwrite.', 'WARNING'); // } return { destExists: exists, destDir: this.createDestDir }; }
[ "function", "(", "destPath", ")", "{", "this", ".", "checkDestDir", "(", "destPath", ")", ";", "var", "exists", "=", "existsSync", "(", "destPath", ")", ";", "// we warn if", "// if (exists) {", "// this.ui.writeLine('The destination path: ' + destPath + ' already exists. Cannot overrwrite.', 'WARNING');", "// }", "return", "{", "destExists", ":", "exists", ",", "destDir", ":", "this", ".", "createDestDir", "}", ";", "}" ]
determine if the file already exists and will be overwritten
[ "determine", "if", "the", "file", "already", "exists", "and", "will", "be", "overwritten" ]
3887906b48de90f74c8c0f5a74697609f83e792b
https://github.com/trabus/ember-cli-mv/blob/3887906b48de90f74c8c0f5a74697609f83e792b/lib/tasks/verify-file.js#L137-L149
40,114
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/modification.js
hoist
function hoist() { var scope = arguments.length <= 0 || arguments[0] === undefined ? this.scope : arguments[0]; var hoister = new _libHoister2["default"](this, scope); return hoister.run(); }
javascript
function hoist() { var scope = arguments.length <= 0 || arguments[0] === undefined ? this.scope : arguments[0]; var hoister = new _libHoister2["default"](this, scope); return hoister.run(); }
[ "function", "hoist", "(", ")", "{", "var", "scope", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "this", ".", "scope", ":", "arguments", "[", "0", "]", ";", "var", "hoister", "=", "new", "_libHoister2", "[", "\"default\"", "]", "(", "this", ",", "scope", ")", ";", "return", "hoister", ".", "run", "(", ")", ";", "}" ]
Hoist the current node to the highest scope possible and return a UID referencing it.
[ "Hoist", "the", "current", "node", "to", "the", "highest", "scope", "possible", "and", "return", "a", "UID", "referencing", "it", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/modification.js#L252-L257
40,115
plepe/openstreetmap-date-parser
src/parser.js
osmDateParser
function osmDateParser (value, options) { var m, v, g m = value.match(/^(.*)\.\.(.*)$/) if (m) { let s = osmDateParser(m[1]) let e = osmDateParser(m[2]) if (s === null || e === null) { return null } if (s[0] > e[1]) { return null } return [ s[0], e[1] ] } m = value.match(/^(\d*) BCE?$/i) if (m) { [ v, g ] = parseDate(value) return [ v, v ] } m = value.match(/^before (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ null, v - 1 ] } m = value.match(/^after (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ v + g, null ] } m = value.match(/^early (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ v, Math.round(v + g * 0.33) ] } m = value.match(/^mid (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ Math.round(v + g * 0.33), Math.round(v + g * 0.67 - 1) ] } m = value.match(/^late (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ Math.round(v + g * 0.67 - 1), v + g - 1 ] } m = parseDate(value) if (m) { [ v, g ] = m return [ v, v + g - 1 ] } return null }
javascript
function osmDateParser (value, options) { var m, v, g m = value.match(/^(.*)\.\.(.*)$/) if (m) { let s = osmDateParser(m[1]) let e = osmDateParser(m[2]) if (s === null || e === null) { return null } if (s[0] > e[1]) { return null } return [ s[0], e[1] ] } m = value.match(/^(\d*) BCE?$/i) if (m) { [ v, g ] = parseDate(value) return [ v, v ] } m = value.match(/^before (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ null, v - 1 ] } m = value.match(/^after (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ v + g, null ] } m = value.match(/^early (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ v, Math.round(v + g * 0.33) ] } m = value.match(/^mid (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ Math.round(v + g * 0.33), Math.round(v + g * 0.67 - 1) ] } m = value.match(/^late (.*)$/i) if (m) { [ v, g ] = parseDate(m[1]) return [ Math.round(v + g * 0.67 - 1), v + g - 1 ] } m = parseDate(value) if (m) { [ v, g ] = m return [ v, v + g - 1 ] } return null }
[ "function", "osmDateParser", "(", "value", ",", "options", ")", "{", "var", "m", ",", "v", ",", "g", "m", "=", "value", ".", "match", "(", "/", "^(.*)\\.\\.(.*)$", "/", ")", "if", "(", "m", ")", "{", "let", "s", "=", "osmDateParser", "(", "m", "[", "1", "]", ")", "let", "e", "=", "osmDateParser", "(", "m", "[", "2", "]", ")", "if", "(", "s", "===", "null", "||", "e", "===", "null", ")", "{", "return", "null", "}", "if", "(", "s", "[", "0", "]", ">", "e", "[", "1", "]", ")", "{", "return", "null", "}", "return", "[", "s", "[", "0", "]", ",", "e", "[", "1", "]", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^(\\d*) BCE?$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "value", ")", "return", "[", "v", ",", "v", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^before (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "null", ",", "v", "-", "1", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^after (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "v", "+", "g", ",", "null", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^early (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "v", ",", "Math", ".", "round", "(", "v", "+", "g", "*", "0.33", ")", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^mid (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "Math", ".", "round", "(", "v", "+", "g", "*", "0.33", ")", ",", "Math", ".", "round", "(", "v", "+", "g", "*", "0.67", "-", "1", ")", "]", "}", "m", "=", "value", ".", "match", "(", "/", "^late (.*)$", "/", "i", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "parseDate", "(", "m", "[", "1", "]", ")", "return", "[", "Math", ".", "round", "(", "v", "+", "g", "*", "0.67", "-", "1", ")", ",", "v", "+", "g", "-", "1", "]", "}", "m", "=", "parseDate", "(", "value", ")", "if", "(", "m", ")", "{", "[", "v", ",", "g", "]", "=", "m", "return", "[", "v", ",", "v", "+", "g", "-", "1", "]", "}", "return", "null", "}" ]
return the lowest or highest possible year which fits the value
[ "return", "the", "lowest", "or", "highest", "possible", "year", "which", "fits", "the", "value" ]
9c5d794c5b7c8fd5f42c7348719a812802e094dd
https://github.com/plepe/openstreetmap-date-parser/blob/9c5d794c5b7c8fd5f42c7348719a812802e094dd/src/parser.js#L34-L93
40,116
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
40,117
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", "=", "[", "]", ";", "// 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\n * count attribute that tracks how many of that piece are left. When this\n * reaches 0, we remove the piece object from the list.\n */", "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
40,118
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
40,119
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
40,120
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
40,121
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", ")", "{", "// 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", ")", ")", ";", "}" ]
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
40,122
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 first player, make it his turn", "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
40,123
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", ")", "{", "// 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'", ")", ";", "}" ]
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
40,124
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'", ":", "// 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'", ")", ";", "}" ]
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
40,125
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\"", ")", "{", "// 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", ")", ";", "}", "}" ]
Handle transaction on game collection resource.
[ "Handle", "transaction", "on", "game", "collection", "resource", "." ]
1ee950d2cc447ea16f189f499fbcd2e25925267c
https://github.com/jlas/quirky/blob/1ee950d2cc447ea16f189f499fbcd2e25925267c/game.js#L522-L557
40,126
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\"", ")", "{", "// 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,\n * otherwise start at 0.\n */", "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\n * chat lines since this id.\n */", "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
40,127
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
40,128
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", "(", ")", "{", "// 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", ")", ";", "}", "}" ]
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
40,129
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
40,130
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
40,131
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
40,132
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
40,133
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.\"", ")", ";", "}", "// 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", "]", ";", "}" ]
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
40,134
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", ")", "{", "/* 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", ";", "}" ]
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
40,135
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
40,136
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
40,137
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", ")", ";", "// get rid of multiple, leading and trailing spaces", "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
40,138
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", "(", ")", "{", "// 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", ";", "}", ")", ";", "}" ]
Fetch stable Node.js version
[ "Fetch", "stable", "Node", ".", "js", "version" ]
1168b628317c3fccb1014dd17511c4688b306ab8
https://github.com/vadimdemedes/stable-node-version/blob/1168b628317c3fccb1014dd17511c4688b306ab8/index.js#L22-L50
40,139
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
40,140
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
40,141
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
40,142
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'", ")", ")", ")", ";", "}", "return", "resolve", "(", "{", "stats", ",", "warnings", ":", "messages", ".", "warnings", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
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
40,143
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
40,144
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
40,145
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
40,146
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
40,147
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
40,148
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
40,149
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
40,150
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", ")", "{", "/**\n * Note that here we reverse the order of the\n * comparison operator since when we extract\n * values from the heap they can only be stored\n * at the end of the array. We thus build a max-heap\n * and then pop elements from it until it is empty.\n */", "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", ";", "}" ]
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
40,151
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
40,152
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", "{", "// TODO: multi-user", "}", "if", "(", "valid_signers", ".", "indexOf", "(", "address", ")", "===", "-", "1", ")", "valid_signers", ".", "push", "(", "address", ")", "// Address is always a valid signer", "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
40,153
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
40,154
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", "]", "// eslint-disable-line no-undef", "}" ]
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
40,155
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
40,156
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
40,157
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", ")", "{", "// 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", ";", "}" ]
- - - - 8-< - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ "-", "-", "-", "-", "8", "-", "<", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-" ]
e41b659a4b4ee5ff6e8eecda8395e2e88829162f
https://github.com/McNull/gulp-angular/blob/e41b659a4b4ee5ff6e8eecda8395e2e88829162f/lib/modules.js#L253-L286
40,158
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", ")", "{", "// 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", ")", "}" ]
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
40,159
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", "{", "// do nothing.", "}", "}", ")", "}", "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
40,160
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
40,161
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", ")", "{", "// socket.io ", "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
40,162
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.broadcast.trigger = broadcast.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
40,163
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", ")", "{", "// 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", "}", ")", ";", "}", "}" ]
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
40,164
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
40,165
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
40,166
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
40,167
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 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", ";", "}" ]
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
40,168
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", ")", "{", "// 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", ";", "}" ]
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
40,169
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
40,170
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
40,171
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
40,172
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
40,173
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
40,174
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
40,175
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
40,176
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 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", ";", "}" ]
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
40,177
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 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", ";", "}" ]
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
40,178
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", "(", ")", "{", "// 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", ";", "}" ]
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
40,179
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
40,180
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
40,181
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
40,182
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
40,183
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
40,184
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
40,185
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", ")", "=>", "{", "// outFile.destroy();", "// fs.unlinkSync(filePath);", "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
40,186
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
40,187
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
40,188
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
40,189
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
40,190
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
40,191
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", ")", "{", "// 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", ";", "}" ]
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
40,192
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
40,193
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
40,194
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", ";", "// 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", ";", "}" ]
Encode JSON string @param {string} str @returns {string}
[ "Encode", "JSON", "string" ]
16e4322070cb6069aec9102fc9736eb895b7d89f
https://github.com/rhgb/json-uri/blob/16e4322070cb6069aec9102fc9736eb895b7d89f/index.js#L63-L82
40,195
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", "{", "// \"A1\" (default)", "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
40,196
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", "{", "// \"A1\" (default)", "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
40,197
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", ")", "{", "// \"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", "}", ";", "}" ]
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
40,198
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", ")", "{", "// \"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", ";", "}" ]
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
40,199
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'", ")", ";", "}", "// 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", "}", "${", "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", ";", "}" ]
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