_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q11600
where
train
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
{ "resource": "" }
q11601
Game
train
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
{ "resource": "" }
q11602
respOk
train
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
{ "resource": "" }
q11603
playerFromReq
train
function playerFromReq(request, response, game) { var jar = new cookies(request, response); var p = decodeURIComponent(jar.get('player')); return game.players[p]; }
javascript
{ "resource": "" }
q11604
requestBody
train
function requestBody(request, onEnd) { var fullBody = ''; request.on('data', function(d) { fullBody += d.toString(); }); request.on('end', function() { onEnd(querystring.parse(fullBody)); }); }
javascript
{ "resource": "" }
q11605
nextTurn
train
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
{ "resource": "" }
q11606
addPlayerToGame
train
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
{ "resource": "" }
q11607
handlePlayers
train
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
{ "resource": "" }
q11608
handleGame
train
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
{ "resource": "" }
q11609
handleGames
train
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
{ "resource": "" }
q11610
handleChat
train
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
{ "resource": "" }
q11611
escapedValue
train
function escapedValue (data, info, str) { return he.escape(getValue(data, info, str) + '') }
javascript
{ "resource": "" }
q11612
writeMappingFile
train
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
{ "resource": "" }
q11613
train
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
{ "resource": "" }
q11614
_method
train
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
{ "resource": "" }
q11615
ArrowFunctionExpression
train
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
{ "resource": "" }
q11616
isCharJapanesePunctuation
train
function isCharJapanesePunctuation(char = '') { return JAPANESE_FULLWIDTH_PUNCTUATION_RANGES.some(([start, end]) => isCharInRange(char, start, end)); }
javascript
{ "resource": "" }
q11617
constructMessageApi
train
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
{ "resource": "" }
q11618
getWorkerData
train
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
{ "resource": "" }
q11619
train
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
{ "resource": "" }
q11620
random
train
function random(arr) { if(!arr) { return false; } if(!arr.length) { arr = Object.keys(arr); } return arr[Math.floor(Math.random() * arr.length)]; }
javascript
{ "resource": "" }
q11621
train
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
{ "resource": "" }
q11622
stableNodeVersion
train
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
{ "resource": "" }
q11623
factorizeArray
train
function factorizeArray(n) { let factors = []; factorize(n, factor => { factors.push(factor); }); return factors; }
javascript
{ "resource": "" }
q11624
factorizeHash
train
function factorizeHash(n) { let factors = {}; factorize(n, factor => { if (factors[factor]) { factors[factor] += 1; } else { factors[factor] = 1; } }); return factors; }
javascript
{ "resource": "" }
q11625
getDataTorrentFromFile
train
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
{ "resource": "" }
q11626
browserBuild
train
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
{ "resource": "" }
q11627
isPrime
train
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
{ "resource": "" }
q11628
unique
train
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
{ "resource": "" }
q11629
train
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
{ "resource": "" }
q11630
getBlock
train
function getBlock(handle) { var block = { handle: handle, rows: [] }; blocks.push(block); return block; }
javascript
{ "resource": "" }
q11631
getRowChainHeads
train
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
{ "resource": "" }
q11632
randomNode
train
function randomNode (g) { var keys = Object.keys(g) return keys[~~(keys.length*Math.random())] }
javascript
{ "resource": "" }
q11633
addGraph
train
function addGraph (g1, g2) { eachEdge(g2, function (from, to, data) { addEdge(g1, from, to, data) }) return g1 }
javascript
{ "resource": "" }
q11634
dary
train
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
{ "resource": "" }
q11635
sign
train
function sign (privateKey, data) { const pair = ECPair.fromWIF(privateKey) return btcMessage.sign(data, pair.d.toBuffer(32), pair.compressed).toString('base64') }
javascript
{ "resource": "" }
q11636
constructValidSigners
train
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
{ "resource": "" }
q11637
selectFormat
train
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
{ "resource": "" }
q11638
modularScale
train
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
{ "resource": "" }
q11639
lineHeightScale
train
function lineHeightScale(lineHeight, power, ratio, bases) { const baseHeight = lineHeight / modularScale(power, ratio, bases) let realHeight = baseHeight while (realHeight < 1) { realHeight += baseHeight } return realHeight }
javascript
{ "resource": "" }
q11640
isCharInRange
train
function isCharInRange(char = '', start, end) { if (isEmpty(char)) return false; const code = char.charCodeAt(0); return start <= code && code <= end; }
javascript
{ "resource": "" }
q11641
getIncludes
train
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
{ "resource": "" }
q11642
sortObject
train
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
{ "resource": "" }
q11643
deepInspect
train
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
{ "resource": "" }
q11644
createSortyOpts
train
function createSortyOpts(keys) { var result = [] keys.forEach(function(keyName) { result.push({ name: keyName, dir: "asc" }) }) return result }
javascript
{ "resource": "" }
q11645
attachToHttpServer
train
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
{ "resource": "" }
q11646
onClientConnection
train
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
{ "resource": "" }
q11647
trigger
train
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
{ "resource": "" }
q11648
killer
train
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
{ "resource": "" }
q11649
ensureLogin
train
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
{ "resource": "" }
q11650
getMongoModelForEntity
train
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
{ "resource": "" }
q11651
calculate_sizeof
train
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
{ "resource": "" }
q11652
flatten_object
train
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
{ "resource": "" }
q11653
getElements
train
function getElements(node, attr) { return Array.prototype.slice.call(node.querySelectorAll("[" + attr + "]")); }
javascript
{ "resource": "" }
q11654
parseProps
train
function parseProps(value) { var pattern = /^{/; if (pattern.test(value)) { value = JSON.parse(value); } return value; }
javascript
{ "resource": "" }
q11655
checkElement
train
function checkElement(node, attr, includeScope) { var elements = getElements(node, attr); if (includeScope && node.hasAttribute(attr)) { elements.push(node); } return elements; }
javascript
{ "resource": "" }
q11656
callViewFunction
train
function callViewFunction(viewFunction, viewAttr, el) { return viewFunction.call(this, el, parseProps(el.getAttribute(viewAttr))); }
javascript
{ "resource": "" }
q11657
sanitizeFalsies
train
function sanitizeFalsies(obj) { var key; if (!obj._) { delete obj._; for (key in obj) { if (obj[key] === false) delete obj[key]; } } return obj; }
javascript
{ "resource": "" }
q11658
fail
train
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
{ "resource": "" }
q11659
pluck
train
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
{ "resource": "" }
q11660
train
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
{ "resource": "" }
q11661
train
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
{ "resource": "" }
q11662
train
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
{ "resource": "" }
q11663
train
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
{ "resource": "" }
q11664
train
function (buf) { var out = ""; for (var i = 0; i < buf.length; i++) out += "0x" + buf[i].toString(16) + ","; return out; }
javascript
{ "resource": "" }
q11665
writeToFile
train
function writeToFile(fileContent, filePath) { return new Promise((resolve, reject) => { fs.writeFile(filePath, fileContent, 'utf8', (err) => { if (err) { reject(err); return; } resolve(filePath); }); }); }
javascript
{ "resource": "" }
q11666
appendToFile
train
function appendToFile(fileContent, filePath) { return new Promise((resolve, reject) => { fs.appendFile(filePath, fileContent, 'utf8', (err) => { if (err) { reject(err); } else { resolve(filePath); } }); }); }
javascript
{ "resource": "" }
q11667
readFileStats
train
function readFileStats(filePath) { return new Promise((resolve, reject) => { fs.stat(filePath, (err, fstat) => { if (err) { reject(err); return; } resolve(fstat); }); }); }
javascript
{ "resource": "" }
q11668
readDirectoryFiles
train
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
{ "resource": "" }
q11669
saveUrlToFile
train
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
{ "resource": "" }
q11670
deleteFile
train
function deleteFile(filePath) { return new Promise((resolve, reject) => { fs.unlink(filePath, (err) => { if (err) { reject(err); return; } resolve(filePath); }); }); }
javascript
{ "resource": "" }
q11671
deleteDirectoryFiles
train
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
{ "resource": "" }
q11672
renameFile
train
function renameFile(from, to) { return new Promise((resolve, reject) => { fs.rename(from, to, (err) => { if (err) { reject(err); return; } resolve(to); }); }); }
javascript
{ "resource": "" }
q11673
copyFile
train
function copyFile(from, to) { return new Promise((resolve, reject) => { fs.copyFile(from, to, (err) => { if (err) { reject(err); return; } resolve(to); }); }); }
javascript
{ "resource": "" }
q11674
getAbsPath
train
function getAbsPath(...relativePathPartsToRoot) { const { resolve, join } = path; return fs.existsSync(relativePathPartsToRoot[0]) ? resolve(join(...relativePathPartsToRoot)) : resolve(join(getRepoRootAbsPath(), ...relativePathPartsToRoot)); }
javascript
{ "resource": "" }
q11675
setupEmulateDynamicDispatch
train
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
{ "resource": "" }
q11676
findSingleVacancies
train
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
{ "resource": "" }
q11677
findDoubleVacancies
train
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
{ "resource": "" }
q11678
encode
train
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
{ "resource": "" }
q11679
train
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
{ "resource": "" }
q11680
train
function(j, coordSystem, size) { if ("aa" === coordSystem) { return String.fromCharCode(CODE_a + --j); } else { // "A1" (default) return (size - --j).toString(); } }
javascript
{ "resource": "" }
q11681
train
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
{ "resource": "" }
q11682
train
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
{ "resource": "" }
q11683
createLabelMatcher
train
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
{ "resource": "" }
q11684
module
train
function module (options) { options.hash.kind = 'module' var result = _identifiers(options)[0] return result ? options.fn(result) : 'ERROR, Cannot find module.' }
javascript
{ "resource": "" }
q11685
classes
train
function classes (options) { options.hash.kind = 'class' return handlebars.helpers.each(_identifiers(options), options) }
javascript
{ "resource": "" }
q11686
misc
train
function misc (options) { options.hash.scope = undefined options.hash['!kind'] = /module|constructor|external/ options.hash['!isExported'] = true return handlebars.helpers.each(_identifiers(options), options) }
javascript
{ "resource": "" }
q11687
BST
train
function BST(compareFn) { this.root = null; this._size = 0; /** * @var Comparator */ this._comparator = new Comparator(compareFn); /** * Read-only property for the size of the tree */ Object.defineProperty(this, 'size', { get: function () { return this._size; }.bind(this) }); }
javascript
{ "resource": "" }
q11688
train
function (value, options) { if (!value) { return value } var html = marked(value) // We strip the surrounding <p>-tag, if if (options.hash && options.hash.stripParagraph) { var $ = cheerio('<root>' + html + '</root>') // Only strip <p>-tags and only if there is just one of them. if ($.children().length === 1 && $.children('p').length === 1) { html = $.children('p').html() } } return new Handlebars.SafeString(html) }
javascript
{ "resource": "" }
q11689
dsStatement
train
function dsStatement(statement) { switch(statement.constructor) { case Statements.Blank: case Statements.Conditional: case Statements.DialogueSegment: case Statements.Evaluate: case Statements.Function: case Statements.Link: case Statements.Option: case Statements.OptionGroup: case Statements.Shortcut: case Statements.ShortcutGroup: return false; case Statements.Command: case Statements.LineGroup: case Statements.Text: case Statements.Hashtag: return true; default: console.warn(`Unrecognized statement type: ${statement.constructor.name}`); return false; } }
javascript
{ "resource": "" }
q11690
read
train
function read (filename) { var data = null try { data = readfile(filename) } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { console.error('File ' + filename + ' is not found') } } return data }
javascript
{ "resource": "" }
q11691
train
function (smart_filename, package_filename) { var smart = read(smart_filename) var data = { global: hydrate(smart.global, smart.global), package: read(package_filename) } var dist = data.global.files.dist || 'dist' var res = resources(hydrate(smart.template, data), hydrate(smart.data, data), data.global.files.concatenator, dist) return { svg: res.svg, png: res.png, icon: res.icon, sprite: res.sprite, dist: dist, html: hydrate(smart.html, data) } }
javascript
{ "resource": "" }
q11692
check
train
function check(source, file) { if (t.isLiteral(source)) { var name = source.value; var lower = name.toLowerCase(); if (lower === "react" && name !== lower) { throw file.errorWithNode(source, messages.get("didYouMean", "react")); } } }
javascript
{ "resource": "" }
q11693
merge
train
function merge(from, to) { to.name = from.name; if (from.selfClosing) { to.selfClosing = true; } if (from.value != null) { to.value = from.value; } if (from.repeat) { to.repeat = Object.assign({}, from.repeat); } return mergeAttributes(from, to); }
javascript
{ "resource": "" }
q11694
mergeClassNames
train
function mergeClassNames(from, to) { const classNames = from.classList; for (let i = 0; i < classNames.length; i++) { to.addClass(classNames[i]); } return to; }
javascript
{ "resource": "" }
q11695
findDeepestNode
train
function findDeepestNode(node) { while (node.children.length) { node = node.children[node.children.length - 1]; } return node; }
javascript
{ "resource": "" }
q11696
done
train
function done() { if (!error && xhr.status > 399) { error = new Error(xhr.statusText); error.status = error.number = xhr.status; } if (type && type.indexOf('json') > -1 && result) { result = Collection.JSON.undry(result); } if (error) { error.result = result; pledge.reject(error); that.error = error; } else { that.result = result; pledge.resolve(result); } }
javascript
{ "resource": "" }
q11697
set
train
function set(base, path, value, { withArrays, sameValue }) { if (path.length === 0) { return value; } const [key, nextKey] = path; const isArrayKeys = Array.isArray(key); let currentBase = base; if (!base || typeof base !== 'object') { currentBase = (isArrayKeys && typeof key[0] === 'number') || (withArrays && typeof key === 'number') ? [] : {}; } if (isArrayKeys) { if (Array.isArray(currentBase)) { return reduceWithArray(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, [...currentBase]); } return { ...currentBase, ...reduceWithObject(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, {}), }; } if (Array.isArray(currentBase)) { return [ ...currentBase.slice(0, key), set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }), ...currentBase.slice(key + 1), ]; } return { ...currentBase, [key]: set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }), }; }
javascript
{ "resource": "" }
q11698
show
train
function show() { if (dat == null && clk == null) { dat = new Gpio(23, 'out'); clk = new Gpio(24, 'out'); } sof(); var pixel; for (var i = 0, length = pixels.length; i < length; i++) { pixel = pixels[i]; writeByte(0xe0 | pixel[3]); writeByte(pixel[2]); writeByte(pixel[1]); writeByte(pixel[0]); } eof(); }
javascript
{ "resource": "" }
q11699
train
function (containerEl, client, params) { var self = this, index = params.index; this._client = client; this._commitHash = params.id; if (typeof index === 'number') { // Add some margins just in case. this._n = index > 90 ? index + 20 : 100; } else { // Until webgme v2.18.0 look through 300 commits. this._n = 300; } this._destroyed = false; this.$el = $('<i>', { class: 'fa fa-video-camera ui-replay-commit-status-icon loading' }); $(containerEl).append(this.$el); RecordReplayControllers.getStatus(client.getActiveProjectId(), this._commitHash, function (err, status) { if (self._destroyed) { return; } self.$el.removeClass('loading'); if (err) { self.$el.addClass('error'); self.$el.attr('title', 'Errored'); } else if (status.exists === true) { self.$el.addClass('success'); self.$el.attr('title', 'Start playback to current commit from this commit'); self.$el.on('click', function () { self._showReplayDialog(); }); } else { self.$el.addClass('unavailable'); self.$el.attr('title', 'No recording available'); } }); }
javascript
{ "resource": "" }