_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q40400
sendAWSRequest
train
function sendAWSRequest(req) { return new Promise((resolve, reject) => { const send = new AWS.NodeHttpClient() send.handleRequest(req, null, (res) => { let body = '' res.on('data', (chunk) => { body += chunk }) res.on('end', () => { const { headers, statusCode } = res resolve({ body, headers, statusCode }) }) res.on('error', (err) => { console.log(`Error: ${err}`) reject(err) }) }, (err) => { console.log(`Error: ${err}`) reject(err) }) }) }
javascript
{ "resource": "" }
q40401
signAWSRequest
train
function signAWSRequest({ credentials, request }) { const signer = new AWS.Signers.V4(request, 'es') signer.addAuthorization(credentials, new Date()) return request }
javascript
{ "resource": "" }
q40402
resolveAndSetEventIdAndSeqNos
train
function resolveAndSetEventIdAndSeqNos(record, userRecord, state, context) { // Get the resolveEventIdAndSeqNos function to use const resolveEventIdAndSeqNos = settings.getResolveEventIdAndSeqNosFunction(context); if (!resolveEventIdAndSeqNos) { const errMsg = `FATAL - Cannot resolve event id & sequence numbers, since no 'resolveEventIdAndSeqNos' function is configured. Configure one & redeploy ASAP!`; context.error(errMsg); throw new FatalError(errMsg); } try { // Resolve the event id & sequence number(s) const eventIdAndSeqNos = resolveEventIdAndSeqNos(record, userRecord) || {}; // Set the event id & sequence number(s) on the given message's state or unusable record's state setEventIdAndSeqNos(state, eventIdAndSeqNos); return eventIdAndSeqNos; } finally { // Cache a description of the record for logging purposes resolveAndSetRecordDesc(state); } }
javascript
{ "resource": "" }
q40403
setMessageIdsAndSeqNos
train
function setMessageIdsAndSeqNos(state, messageIdsAndSeqNos) { const {ids, keys, seqNos} = messageIdsAndSeqNos || {}; setIds(state, ids); setKeys(state, keys); setSeqNos(state, seqNos); return state; }
javascript
{ "resource": "" }
q40404
init
train
function init(targetBuild) { // CONSIDER: The `|| StaticBuild.current` isn't really necessary. build = targetBuild || StaticBuild.current; initViewEngines(); // Request Pipeline initFavicon(); initLogging(); initApiProxy(); initParsing(); initCssLESS(); initSASS(); initViewRouting(); initErrorHandling(); }
javascript
{ "resource": "" }
q40405
prepareEmbed
train
function prepareEmbed(embedID) { var embed = document.getElementById(embedID); if (!isEmbeddedVideo(embed)) { throw new Error('embed must be an iframe'); } enableAPIControl(embed); }
javascript
{ "resource": "" }
q40406
isAPIEnabled
train
function isAPIEnabled(embed) { var regex = '\/?api=1&player_id=' + embed.id; regex = new RegExp(regex); return regex.test(embed.src); }
javascript
{ "resource": "" }
q40407
Request
train
function Request(conn, cmd, args) { // current connection this.conn = conn; // command name this.cmd = cmd; // command arguments may be modified // during validation this.args = args; // raw command arguments, injected by the server this.raw = null; // server will inject this // based upon the selected db index // for the connection this.db = null; // info object decorated with additional // information during validation, server will // inject this this.info = null; // server configuration object this.conf = null; // alias to the command definition this.def = null; // mark this request as coming from a script this.script = false; }
javascript
{ "resource": "" }
q40408
destroy
train
function destroy() { this.conn = null; this.cmd = null; this.args = null; this.db = null; this.info = null; this.conf = null; this.def = null; }
javascript
{ "resource": "" }
q40409
execute
train
function execute(req, res) { this.state.pubsub.subscribe(req.conn, req.args); }
javascript
{ "resource": "" }
q40410
markdown_table
train
function markdown_table (headers, table) { // FIXME: Implement better markdown table formating return ARRAY([headers, [ "---", "---" ]]).concat(table).map(cols => '| ' + ARRAY(cols).join(' | ') + ' |').join('\n'); }
javascript
{ "resource": "" }
q40411
_orphan
train
function _orphan(_el) { var id = _jsPlumb.getId(_el); var pos = _jsPlumb.getOffset(_el); _el.parentNode.removeChild(_el); _jsPlumb.getContainer().appendChild(_el); _jsPlumb.setPosition(_el, pos); delete _el._jsPlumbGroup; _unbindDragHandlers(_el); _jsPlumb.dragManager.clearParent(_el, id); }
javascript
{ "resource": "" }
q40412
_pruneOrOrphan
train
function _pruneOrOrphan(p) { if (!_isInsideParent(p.el, p.pos)) { p.el._jsPlumbGroup.remove(p.el); if (prune) { _jsPlumb.remove(p.el); } else { _orphan(p.el); } } }
javascript
{ "resource": "" }
q40413
_revalidate
train
function _revalidate(_el) { var id = _jsPlumb.getId(_el); _jsPlumb.revalidate(_el); _jsPlumb.dragManager.revalidateParent(_el, id); }
javascript
{ "resource": "" }
q40414
camelo
train
function camelo(input, regex, uc) { regex = regex || DEFAULT_SPLIT; var splits = null; if (Array.isArray(regex)) { regex = new RegExp(regex.map(reEscape).join("|"), "g"); } else if (typeof regex === "boolean") { uc = regex; regex = DEFAULT_SPLIT; } splits = input.split(regex); if (uc) { return ucFirstArray(splits).join(""); } return splits[0] + ucFirstArray(splits.slice(1)).join(""); }
javascript
{ "resource": "" }
q40415
startWorker
train
function startWorker(triggeredByError=false){ return new Promise(function(resolve){ // default restart delay let restartDelay = 0; // worker restart because of died process ? if (triggeredByError === true){ // increment restart counter _restartCounter++; } // delayed restart ? if (_restartCounter > 10){ // calculate restart delay (min: 2s) restartDelay = 200 * _restartCounter; // trigger alert message _logger.alert(`delayed worker-restart of ${restartDelay/1000}s - number of failed processes: ${_restartCounter}`); } // trigger async fork setTimeout(() => { // create a new child process // note: this method RELOADS the entire js file/module! - it is NOT a classical process.fork() ! // this allows you to hot-reload your application by restarting the workers const worker = _cluster.fork(); // return worker resolve(worker); }, restartDelay); }); }
javascript
{ "resource": "" }
q40416
stopWorker
train
function stopWorker(worker){ return new Promise(function(resolve, reject){ // set kill timeout const killTimeout = setTimeout(() => { // kill the worker worker.kill(); // failed to disconnect within given time reject(new Error(`process ${worker.process.pid} killed by timeout of ${_workerShutdownTimeout/1000}s - disconnect() failed`)); }, _workerShutdownTimeout); // wait for exit + disconnect worker.on('disconnect', () => { _logger.log(`disconnect event ${worker.process.pid}`); // disable kill timer clearTimeout(killTimeout); // ok resolve(); }); // trigger disconnect worker.disconnect(); }); }
javascript
{ "resource": "" }
q40417
shutdown
train
function shutdown(){ // trigger stop on all workers // catch errors thrown by killed workers return Promise.all(Object.values(_cluster.workers).map(worker => stopWorker(worker).catch(err => _logger.error(err)))); }
javascript
{ "resource": "" }
q40418
setOutput
train
function setOutput(output) { if (!output || typeof output.log !== 'function') { throw Error('logger.setOutput: expect an object as the parameter with "log" and "error" properties.'); } outputFunctions = { log: output.log, error: (typeof output.error === 'function') ? output.error : output.log }; }
javascript
{ "resource": "" }
q40419
joinMsgArgs
train
function joinMsgArgs(msgArgs) { if (!msgArgs) { return ''; } return msgArgs.map((arg) => { if (arg === null) { return 'null'; } else if (typeof arg === 'undefined') { return 'undefined'; } else if (typeof arg === 'string') { return arg; } else if (typeof arg === 'object') { try { return JSON.stringify(arg); } catch (ex) { return arg.toString(); } } else { // boolean, symbol, number, function return arg.toString(); } }).join(' '); }
javascript
{ "resource": "" }
q40420
writeLog
train
function writeLog(levelName, varArgs) { // eslint-disable-line no-unused-vars const args = [].slice.call(arguments); args.splice(0, 1); const str = format(new Date(), levelName, label, args); if (LEVELS[levelName] <= LEVELS.warn) { outputFunctions.error(str); } else { outputFunctions.log(str); } }
javascript
{ "resource": "" }
q40421
genPassOfDay
train
function genPassOfDay(d, s = DEFAULT_SEED) { if (!(d instanceof Date)) { throw new TypeError('Date is not a Date instance'); } if (typeof s !== 'string') { throw new TypeError('Seed is not a String instance'); } if (s.length < 1) { throw new Error('Seed min length: 1'); } const seed = s.repeat(10); const year = d.getFullYear() % 100; // Two last digits const month = d.getMonth() + 1; // January === 1 const dayOfMonth = d.getDate(); const dayOfWeek = d.getDay() === 0 ? 6 : d.getDay() - 1; // Monday === 1 const l1 = TABLE1[dayOfWeek].slice(0); l1.push(dayOfMonth); l1.push(year + month - dayOfMonth < 0 ? (year + month - dayOfMonth + 36) % 36 : (year + month - dayOfMonth) % 36); l1.push((3 + (year + month) % 12) * dayOfMonth % 37 % 36); const l2 = [...Array(8).keys()].map((_, i) => seed.charCodeAt(i) % 36); const l3 = l1.map((f, i) => (f + l2[i]) % 36); const l38 = l3.reduce((t, i) => t + i, 0) % 36; const num8 = l38 % 6; l3.push(l38); l3.push(Math.round(Math.pow(num8, 2))); const l4 = TABLE2[num8].map(i => l3[i]); const l5 = l4.map((v, i) => (seed.charCodeAt(i) + v) % 36); return l5.map(i => ALPHANUM[i]).join(''); }
javascript
{ "resource": "" }
q40422
train
function(args) { let service = args.service; let record = args.record; if (!service || !record || !record.module || !record.enable) { return; } if (service.master) { record.module.masterHandler(service.agent, null, function(err) { logger.error('interval push should not have a callback.'); }); } else { record.module.monitorHandler(service.agent, null, function(err) { logger.error('interval push should not have a callback.'); }); } }
javascript
{ "resource": "" }
q40423
wrap
train
function wrap(nodes) { nodes = nodes || []; if ('string' == typeof nodes) { nodes = new DOMParser().parseFromString(nodes); } if (nodes.attrNS && nodes._related) { // attempt to re-wrap Collection, return it directly return nodes; } else if (nodes.documentElement) { nodes = [ nodes.documentElement ]; } else if (nodes.nodeType) { nodes = [ nodes ]; } return new Collection(nodes); }
javascript
{ "resource": "" }
q40424
unique
train
function unique(ar) { var a = [] , i = -1 , j , has; while (++i < ar.length) { j = -1; has = false; while (++j < a.length) { if (a[j] === ar[i]) { has = true; break; } } if (!has) { a.push(ar[i]); } } return a; }
javascript
{ "resource": "" }
q40425
Collection
train
function Collection(nodes) { this.length = 0; if (nodes) { nodes = unique(nodes); this.length = nodes.length; // add each node to an index-based property on collection, in order to // appear "array"-like for (var i = 0, len = nodes.length; i < len; i++) { this[i] = nodes[i]; } } }
javascript
{ "resource": "" }
q40426
disableRules
train
async function disableRules(rules) { return Object.keys(rules) .reduce((collection, rule) => ({ ...collection, [rule]: OFF, }), {}); }
javascript
{ "resource": "" }
q40427
build
train
function build (conf, undertaker, done) { return undertaker.series( require('./clean').bind(null, conf, undertaker), undertaker.parallel( require('../scripts/lintScripts').bind(null, conf, undertaker), require('../styles/lintStyles').bind(null, conf, undertaker) ), undertaker.parallel( require('../scripts/buildScripts').bind(null, conf, undertaker), require('../styles/buildStyles').bind(null, conf, undertaker), require('../assets/buildImages').bind(null, conf, undertaker), require('../assets/buildFonts').bind(null, conf, undertaker) ), require('../styles/holograph').bind(null, conf, undertaker) )(done); }
javascript
{ "resource": "" }
q40428
train
function () { // Remove the other tooltips // if it was requested. if (this.reset !== false) this.resetTooltip(); // Create the tooltip elements var container = $("<div>").attr({ "class": "error-label-container" }).appendTo(this.settings.element); var arrow = $("<div>").attr({ "class": "error-label-arrow-" + this.settings.arrow }).appendTo(container); var label = $("<div>").attr({ "class": "error-label" }).html(this.settings.label).appendTo(container); // Set the red glow around the input this.settings.element.addClass("tooltip-active"); // If the fadeout option is set, then // fade it out after the given time. // Otherwise, make it clickable to let // the user remove it. if ($.isNumeric(this.settings.fadeOut)) container.delay(this.settings.fadeOut).fadeOut("slow"); label.click(function () { $(this).parent().remove(); }); }
javascript
{ "resource": "" }
q40429
Database
train
function Database(store, opts) { opts = opts || {}; // the store that holds this database this._store = store; // do not coerce values to strings this.raw = opts.raw !== undefined ? opts.raw : true; // pattern matcher this.pattern = opts.pattern || new Pattern(); this.options = opts; // set up initial state this.flushdb(); if(store) { // proxy via the store so the server // can get statistics across all databases this.on('expired', function onExpired(key) { store.emit('expired', key); }) this.on('hit', function onHit(key) { store.emit('hit', key); }) this.on('miss', function onMiss(key) { store.emit('miss', key); }) } }
javascript
{ "resource": "" }
q40430
Encoder
train
function Encoder(options) { options = options || {}; Transform.call(this, {objectMode: true}); // string length chunk for bulk strings, strings large than this amount // are broken over process ticks so as not to block the event loop // note this is character length, not byte length this.strlen = options.strlen || 4096; // maximum array length before iterating using // setImmediate this.arrlen = 512; // allow buffers to be passed through untouched this.buffers = options.buffers; // treat buffers as bulk strings this.return_buffers = options.return_buffers; }
javascript
{ "resource": "" }
q40431
pack
train
function pack(arr, buf) { assert(Array.isArray(arr), 'array expected'); var i; buf = buf || new Buffer(0); buf = _preamble(buf, arr); for(i = 0;i < arr.length;i++) { buf = _arr(buf, arr[i]); } return buf; }
javascript
{ "resource": "" }
q40432
value
train
function value(val, buf, simple) { buf = buf || new Buffer(0); var type = typeof val; // coerce booleans to integers val = type === 'boolean' ? Number(val) : val; // treat floats as strings if(type === 'number' && parseInt(val) !== val) { val = '' + val; } // String instances are treated as simple strings if(val instanceof String) { simple = true; val = val.toString(); } // re-evaluate type after coercion type = typeof val; if(val instanceof Buffer) { buf = _bst(buf, val); }else if(val === null) { buf = _nil(buf); }else if(Array.isArray(val)) { buf = _arr(buf, val); }else if(type === 'number'){ buf = _int(buf, val); }else if(type === 'string') { buf = simple ? _str(buf, val) : _bst(buf, val); }else if(val instanceof Error) { buf = _err(buf, val); }else{ assert(false, 'invalid encoder type: ' + type); } return buf; }
javascript
{ "resource": "" }
q40433
train
function() { var self = this; molecuel.once('mlcl::elements::registrations:pre', function(module) { elements = module; self.wishlistSchema = { name: { type: String, list: true, trim: true}, creation: { type: Date, 'default': Date.now, form: {readonly: true}}, entries: { }, listelements: [{type: elements.Types.Mixed}] }; _.each(molecuel.config.wishlist.types, function(type) { self.wishlistSchema.entries[type] = [{type: elements.ObjectId, ref: type}]; }); // module == elements module var schemaDefinition = { schemaName: 'wishlist', schema: self.wishlistSchema, options: {indexable: true, avoidTranslate: true} }; molecuel.config.url.pattern.wishlist = '/wishlist/{{t _id}}'; elements.registerSchemaDefinition(schemaDefinition); }); return this; }
javascript
{ "resource": "" }
q40434
baseWeight
train
function baseWeight(player, target, card, game) { let weight = card.damage || 0 weight += Math.min(player.maxHp - player.hp, (parseInt(card.hp) || 0)) weight += card.missTurns / 2 || 0 // Prefer to contact weaker targets weight += ((target.maxHp - player.hp) / 10) // Unstoppable cards are instantly more valuable if (card.type === 'unstoppable') { weight += 3 } // Try to avoid contacting a target with a deflector if (Util.find(target.conditionCards, { id: 'deflector' })) { weight = -weight } return weight }
javascript
{ "resource": "" }
q40435
findNext
train
function findNext(array, item) { return array[(Util.findIndex(array, el => el === item) + 1) % array.length] }
javascript
{ "resource": "" }
q40436
getAttackResults
train
function getAttackResults(_cards) { // Force the cards into an array. Clone is too // to avoid side effects from the simulation. const cards = Util.clone(Array.isArray(_cards) ? _cards : [_cards]) const Junkyard = require('./junkyard') const game = new Junkyard('1', '') game.addPlayer('2', '') game.addPlayer('3', '') game.start() const [p1, , p3] = game.players p1.hand = cards game.play(p1, [...cards], p3.id) game.pass(p3) return { damage: p3.maxHp - p3.hp, missTurns: p3.missTurns } }
javascript
{ "resource": "" }
q40437
getCardWeight
train
function getCardWeight(player, target, card, game) { let moves = [] if (card.validPlays) { moves = card.validPlays(player, target, game) } if (card.validCounters && target.discard.length) { moves = card.validCounters(player, target, game) } if (card.validDisasters) { moves = card.validDisasters(player, game) } // Pick out the highest weight of those moves return moves.reduce((acc, move) => { return move.weight > acc ? move.weight : acc }, 0) }
javascript
{ "resource": "" }
q40438
getPlayerCounters
train
function getPlayerCounters(player, attacker, game) { return player.hand .map((card) => { return card.validCounters ? card.validCounters(player, attacker, game) : [] }) .reduce((acc, array) => { return acc.concat(array) }, []) .sort((counterA, counterB) => counterB.weight - counterA.weight) }
javascript
{ "resource": "" }
q40439
getPlayerDisasters
train
function getPlayerDisasters(player, game) { return player.hand .map((card) => { return card.validDisasters ? card.validDisasters(player, game) : [] }) .reduce((acc, array) => { return acc.concat(array) }, []) .sort((disasterA, disasterB) => disasterB.weight - disasterA.weight) }
javascript
{ "resource": "" }
q40440
getPlayerPlays
train
function getPlayerPlays(player, game) { // Shuffle so that equal-weighted players aren't // always prioritized by their turn order return Util.shuffle(game.players) .reduce((plays, target) => { if (player === target) { return plays } return plays.concat( player.hand .map((card) => { return card.validPlays ? card.validPlays(player, target, game) : [] }) .reduce((acc, array) => { return acc.concat(array) }, []) ) }, []) .sort((playA, playB) => playB.weight - playA.weight) }
javascript
{ "resource": "" }
q40441
remove
train
function remove(array, fn) { const idx = array.findIndex(fn) if (idx !== -1) { array.splice(idx, 1) } }
javascript
{ "resource": "" }
q40442
train
function (arr, groupSize) { var groups = []; groupSize = groupSize || 100; arr.forEach(function (n, i) { var index = Math.trunc(i / groupSize); if (groups.length === index) { groups.push([]); } groups[index].push(n); }); return groups; }
javascript
{ "resource": "" }
q40443
normalize
train
function normalize(arr) { const n = copy(arr); let len = 0; for (const v of n) len += v * v; if (len > 0) { const coeff = 1 / Math.sqrt(len); for (let k = 0; k < n.length; k++) { n[k] *= coeff; } } return n; }
javascript
{ "resource": "" }
q40444
perspective4
train
function perspective4(fieldAngle, aspect, near, far, result) { result = result || new Float32Array(16); var f = Math.tan(Math.PI * 0.5 - 0.5 * fieldAngle); var rangeInv = 1.0 / (near - far); result[0] = f / aspect; result[1] = 0; result[2] = 0; result[3] = 0; result[4] = 0; result[5] = f; result[6] = 0; result[7] = 0; result[8] = 0; result[9] = 0; result[10] = (near + far) * rangeInv; result[11] = -1; result[12] = 0; result[13] = 0; result[14] = near * far * rangeInv * 2; result[15] = 0; return result; }
javascript
{ "resource": "" }
q40445
streamOutput
train
function streamOutput( callback ) { return function(err, filenames) { if (err) { callback(err, null); } else { // Create read streams from each input var streams = [] for (var i=0; i<filenames.suffix.length; i++) streams.push([ fs.createReadStream( filenames.basename + filenames.suffix[i]), filenames.suffix[i] ]); // Callback with streams callback(err, streams); } } }
javascript
{ "resource": "" }
q40446
processAsBuffer
train
function processAsBuffer( file ) { return function( callback ) { var json = JSON.parse(file.contents); callback( json, path.dirname(file.path) ); } }
javascript
{ "resource": "" }
q40447
compileJBB
train
function compileJBB( config, parseCallback, resultCallback ) { // Continue compiling the JBB bundle var compile = function( bundleJSON, bundlePath, tempName ) { // Update path in config if (!config['path']) config['path'] = path.dirname(bundlePath); // Create the JBB bundle JBBCompiler.compile( bundleJSON, tempName, config, function() { // Check for sparse bundles if (config['sparse']) { resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbbp', '_b16.jbbp', '_b32.jbbp', '_b64.jbbp' ] }); } else { // Trigger callback resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbb' ] }); } } ); }; // Open a new temporary file (to be tracked by temp) temp.open({suffix: '_tmp'}, function(err, info) { // Handle errors if (err) { resultCallback(err, null); return; } fs.close(info.fd, function(err) { if (err) { resultCallback(err, null); return; } // We are ready, continue with compiling parseCallback(function( bundleJSON, baseName ) { compile( bundleJSON, baseName, info.path ); }); }); }); }
javascript
{ "resource": "" }
q40448
train
function( bundleJSON, bundlePath, tempName ) { // Update path in config if (!config['path']) config['path'] = path.dirname(bundlePath); // Create the JBB bundle JBBCompiler.compile( bundleJSON, tempName, config, function() { // Check for sparse bundles if (config['sparse']) { resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbbp', '_b16.jbbp', '_b32.jbbp', '_b64.jbbp' ] }); } else { // Trigger callback resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbb' ] }); } } ); }
javascript
{ "resource": "" }
q40449
train
function( err, streams ) { // Get base name var path = originalFile.path; var parts = path.split("."); parts.pop(); var baseName = parts.join("."); // Push each stream to output for (var i=0; i<streams.length; i++) { var f = originalFile.clone(); f.contents = streams[i][0]; // Content f.path = baseName + streams[i][1]; // Suffix self.push(f); } // We are done done(); return; }
javascript
{ "resource": "" }
q40450
signals
train
function signals() { /** * Signal handler. */ function interrupt(signal) { this.log.notice('received %s, scheduling shutdown', signal); this.shutdown(0, process.exit); } interrupt = interrupt.bind(this); function iterate(signal) { /* test environment listener leak */ if(process.listeners(signal).length) return; process.once(signal, function() { interrupt(signal); }) } ['SIGINT', 'SIGTERM'].forEach(iterate.bind(this)); }
javascript
{ "resource": "" }
q40451
promiseThen
train
function promiseThen(success, reject, notify){ /** * @define {object} Return a new promise */ var def = Deferred(); /** * Resolved promise * @example example * @param {string} A string key for the event system * @param {function} A callback when event is triggered * @return {object} Returns promise object */ event.on('resolve', function(){ /** * If the success callback returns a promise * then resolve/reject/notify that returned promise */ var promise = success(); if(!promise) return; promise.success(function(){ /** handle the returned deferred object */ def.resolve(); }); promise.error(function(){ def.reject(); }); promise.notify(function(){ def.notify(); }); }); /** * If promise is rejected/notify trigger the callback */ event.on('reject', function(){ if(reject) reject(); }); event.on('notify', function(){ if(notify) notify(); }); /** * @return {object} Returns a promise object */ return def.promise; }
javascript
{ "resource": "" }
q40452
resolve
train
function resolve(){ var args = Array.prototype.slice.call(arguments); event.trigger('resolve', args); }
javascript
{ "resource": "" }
q40453
PancakesAngularPlugin
train
function PancakesAngularPlugin(opts) { this.templateDir = path.join(__dirname, 'transformers'); this.pancakes = opts.pluginOptions.pancakes; // initialize Jyt plugins this.registerJytPlugins(); // initialize all directives and load them into memory this.initDirectives(opts); // if mobile app then register mobile components if (this.isMobileApp()) { this.registerMobileComponents(); } // set all the transformation functions (used by the pancakes module transformation.factory this.transformers = { apiclient: apiTrans, app: appTrans, basic: basicTrans, routing: routingTrans, uipart: uipartTrans }; }
javascript
{ "resource": "" }
q40454
train
function( path, cb ) { // Set the content path octofish.setContentPath( path ); // Use the content path to retrieve content octofish.github.repos.getContent( octofish.config.contentOpts, function ( err, res ) { var data = null; // Handle any error if (err) { // Log the error - not a very useful log at the moment console.log( 'An error occured whilst getting content from github - this should be dealt with properly' ); console.log( 'It is most likely a URL error with the path' ); // Call the callback with a null value to denote an error cb( data ); return; } // Decode the data before sending on to the callback // Check for decoding an image if ( octofish.config.contentOpts.path.match(/img/) ) { data = octofish.decodeGithubImageData( res.content ); } else { data = octofish.decodeGithubData( res.content ); } // If the content was collected successfully then call the callback and remember to pass in the data cb( data ); }); }
javascript
{ "resource": "" }
q40455
train
function( authType ) { switch ( authType.toLowerCase() ) { case 'basic': console.log( 'Attempting to use basic authorisation' ); getBasicAuth() ? cb_success() : cb_failure(); break; case 'oauth': console.log( 'Using oAuth to authenticate' ); return getOAuth(); break; default: console.warn( 'Incorrect authorisation type passed to Octofish' ); console.warn( 'Authorisation to github will be unauthorised' ); cb_failure(); return false; } return true; }
javascript
{ "resource": "" }
q40456
train
function() { auth.type = 'basic'; auth.username = process.env.GHusername || octofish.config.auth.username || null; auth.password = process.env.GHpassword || octofish.config.auth.password || null; if ( !auth.password || !auth.username ) { return false; } else { octofish.github.authenticate( auth ); return true; } }
javascript
{ "resource": "" }
q40457
Predator
train
function Predator(options) { if (!(this instanceof Predator)) { return new Predator(options); } if (!options || !options.app) { throw new Error('options.app is required'); } // 主目录 this.home = pathFn.resolve(options.home || '.'); // app this.app = options.app; // build 目录 this.buildDir = pathFn.resolve(options.buildDir || './public'); }
javascript
{ "resource": "" }
q40458
createQueuePusher
train
function createQueuePusher(providerName, method, insertMethod, queue) { return function() { let args = arguments; // Add provide method to invokeQueue to execute it on bootstrap. (queue || invokeQueue)[insertMethod || 'push'](function provide(injector) { // Get provider let provider = injector.get(providerName); // Execute method on provider provider[method].apply(provider, args); // Return name in case of provider, factory, service, value or constant if (providerName === '$provide') { return args[0]; } }); return that; }; }
javascript
{ "resource": "" }
q40459
estimateFalsePositiveRate
train
function estimateFalsePositiveRate(numValues, numBuckets, numHashes) { // Formula for false positives is (1-e^(-kn/m))^k // k - number of hashes // n - number of set entries // m - number of buckets var expectedFalsePositivesRate = Math.pow((1 - Math.exp(-numHashes * numValues / numBuckets)), numHashes); return expectedFalsePositivesRate; }
javascript
{ "resource": "" }
q40460
_reset
train
function _reset() { this._queue = []; this._commands = [{cmd: Constants.MAP.multi.name, args: []}]; this._multi = false; }
javascript
{ "resource": "" }
q40461
_abort
train
function _abort(err) { this._queue = null; this._commands = null; // listen for the event so we can clean reference function onError() { this._client = null; } this._client.once('error', onError.bind(this)); this._client.emit('error', err); }
javascript
{ "resource": "" }
q40462
loadFile
train
function loadFile(filepath, defaultObj) { defaultObj = defaultObj || {}; if (!isFile(filepath)) { return defaultObj; } var extension = path.extname(filepath).replace(/^\./, ''); var contents = supportedExtensions[extension](filepath); return assign({}, defaultObj, contents); }
javascript
{ "resource": "" }
q40463
createPost
train
function createPost( file, options ) { resetDoc(); var _formatDate = options && typeof options.formatDate === 'function' ? options.formatDate : formatDate, post = new Post(); // Parse front matter to get as many post attributes as possible parseFrontMatter( file, post, options ); // Get category from path if not from front matter if ( !post.category ) { post.category = getCategoryFromPath( file ); } // Get creation date from file if not from front matter if ( !post.created ) { post.created = _formatDate( file.stat.ctime ); } // Get excerpt from first <p> tag if not from front matter if ( !post.excerpt ) { post.excerpt = getDefaultExcerpt( post.content ); } // Get title from file name if not from front matter if ( !post.title ) { post.title = getTitleFromPath( file ); } // Get updated date from file if not from front matter if ( !post.updated ) { post.updated = _formatDate( file.stat.mtime ); /* * If updated date from file system matches creation date, * assume udated date should be empty */ if ( post.updated === post.created ) { post.updated = ''; } } return JSON.stringify( post ); }
javascript
{ "resource": "" }
q40464
formatDate
train
function formatDate( date ) { var dateString = ''; date = new Date( date ); dateString = date.getMonth() + 1; dateString += '/'; dateString += date.getDate(); dateString += '/'; dateString += date.getFullYear(); return dateString; }
javascript
{ "resource": "" }
q40465
getCategoryFromPath
train
function getCategoryFromPath( file ) { var category = '', i = 0, parts = file.path.split('/'), len = parts.length, last = len - 1; for ( ; i < len; i++ ) { /* * If previous path part is "posts" and the * current path part isn't the last path part */ if ( parts[i - 1] === 'posts' && i !== last ) { category = parts[i]; break; } } return category; }
javascript
{ "resource": "" }
q40466
getTitleFromPath
train
function getTitleFromPath( file, options ) { var _titleSeparator = options && options.titleSeparator ? options.titleSeparator : titleSeparator, i = 0, parts = file.path.split('/'), fileParts = parts[parts.length - 1].split('.'), filename = fileParts[0], fileNameParts = filename.split( _titleSeparator ), len = fileNameParts.length, title = ''; for ( ; i < len; i++ ) { title += i ? ' ' : ''; title += fileNameParts[i]; } return titleCase( title ); }
javascript
{ "resource": "" }
q40467
highlightPostSyntax
train
function highlightPostSyntax( post ) { var codeTags = [], i = 0, len = 0; doc = doc || createDom( post.content ); codeTags = doc.querySelectorAll('pre code'); len = codeTags.length; for ( ; i < len; i++ ) { // Replace class names beginning with "lang-" with "language-" for Highlight.js codeTags[i].className = codeTags[i].className.replace('lang-', 'language-'); hljs.highlightBlock( codeTags[i] ); } post.content = doc.body.innerHTML; }
javascript
{ "resource": "" }
q40468
isCustomFrontMatter
train
function isCustomFrontMatter( attr ) { if ( attr !== 'title' && attr !== 'category' && attr !== 'content' && attr !== 'created' && attr !== 'excerpt' && attr !== 'updated' ) { return true; } else { return false; } }
javascript
{ "resource": "" }
q40469
parseFrontMatter
train
function parseFrontMatter( file, post, options ) { var _formatDate = options && typeof options.formatDate === 'function' ? options.formatDate : formatDate, content = frontMatter( file.contents.toString() ), prop = ''; if ( content.attributes ) { post.category = content.attributes.category || ''; post.created = content.attributes.created ? _formatDate( content.attributes.created ) : ''; post.title = content.attributes.title || ''; post.updated = content.attributes.updated ? _formatDate( content.attributes.updated ) : ''; if ( content.attributes.excerpt ) { post.excerpt = markdown( content.attributes.excerpt ); } post.content = content.body ? markdown( content.body ) : ''; if ( post.content && highlightSyntax ) { highlightPostSyntax( post ); } // Look for custom front-matter for ( prop in content.attributes ) { if ( content.attributes.hasOwnProperty( prop ) && isCustomFrontMatter( prop ) ) { post[ prop ] = content.attributes[ prop ]; } } } }
javascript
{ "resource": "" }
q40470
sortPosts
train
function sortPosts( a, b ) { var dateA = new Date( a.created ), dateB = new Date( b.created ); // See if dates match if ( dateB - dateA === 0 ) { // See if categories are the same if ( a.category === b.category ) { // Sort by title return a.title.localeCompare( b.title ); // Sort by category } else { return a.category.localeCompare( b.category ); } // Sort by date descending } else { return dateB - dateA; } }
javascript
{ "resource": "" }
q40471
removePostsContent
train
function removePostsContent( posts, options ) { var _sortPosts = options && typeof options.sortPosts === 'function' ? options.sortPosts : sortPosts, i = 0, len = 0; // Posts should be objects separated by commas but not wrapped in [] posts = JSON.parse( '[' + posts.contents.toString() + ']' ); len = posts.length; for ( i; i < len; i++ ) { delete posts[i].content; } // Sort posts by newest posts.sort( _sortPosts ); return JSON.stringify( posts ); }
javascript
{ "resource": "" }
q40472
diamondLeftToVic
train
function diamondLeftToVic(lead) { var m = lead.p; var z = lead; var x = z.l; var y = x.r; var a = y.l; var b = y.r; x.flag = false; y.l = x; x.p = y; y.r = z; z.p = y; x.r = a; a.p = x; z.l = b; b.p = z; if (m.r === lead) { m.r = y; } else { m.l = y; } y.p = m; return y; }
javascript
{ "resource": "" }
q40473
rbInsertFixup
train
function rbInsertFixup(tree, n) { // When inserting the node (at any place other than the root), we always color it red. // This is so that we don't violate the height invariant. // However, this may violate the color invariant, which we address by recursing back up the tree. n.flag = true; if (!n.p.flag) { throw new Error("n.p must be red."); } while (n.flag) { /** * The parent of n. */ var p = n.p; if (n === tree.root) { tree.root.flag = false; return; } else if (p === tree.root) { tree.root.flag = false; return; } /** * The leader of the formation. */ var lead = p.p; // Establish the n = red, p = red, g = black condition for a transformation. if (p.flag && !lead.flag) { if (p === lead.l) { var aux = lead.r; if (aux.flag) { n = colorFlip(p, lead, aux); } else if (n === p.r) { n = diamondLeftToVic(lead); } else { n = echelonLeftToVic(lead); } } else { var aux = lead.l; if (aux.flag) { n = colorFlip(p, lead, aux); } else if (n === n.p.l) { n = diamondRightToVic(lead); } else { n = echelonRightToVic(lead); } } } else { break; } } tree.root.flag = false; }
javascript
{ "resource": "" }
q40474
glb
train
function glb(tree, node, key, comp, low) { if (node === tree.z) { return low; } else if (comp(key, node.key) >= 0) { // The node key is a valid lower bound, but may not be the greatest. // Take the right link in search of larger keys. return maxNode(node, glb(tree, node.r, key, comp, low), comp); } else { // Take the left link in search of smaller keys. return glb(tree, node.l, key, comp, low); } }
javascript
{ "resource": "" }
q40475
lub
train
function lub(tree, node, key, comp, high) { if (node === tree.z) { return high; } else if (comp(key, node.key) <= 0) { // The node key is a valid upper bound, but may not be the least. return minNode(node, lub(tree, node.l, key, comp, high), comp); } else { // Take the right link in search of bigger keys. return lub(tree, node.r, key, comp, high); } }
javascript
{ "resource": "" }
q40476
Middleware
train
function Middleware(name) { if (!(this instanceof Middleware)) return new Middleware(name); this.name = name || ''; Object.defineProperty(this, '_', { enumerable: false, configurable: false, value: { length: 0, ordered: null, weights: new Map() } }); /** * Returns the length of the middleware. * @type {number} */ Object.defineProperty(this, 'length', { get: () => this._.length }); }
javascript
{ "resource": "" }
q40477
train
function(err, req, res, next) { function done(error) { log(req, util.format('middleware-end %s', name)); next(error); } if (err && !errHandler) { log(req, util.format('skipped %s Hook is not for error handling', name)); next(err); } else if (!err && errHandler) { log(req, util.format('skipped %s Hook is for error handling', name)); next(); } else { try { log(req, util.format('middleware-start %s', name)); errHandler ? hook(err, req, res, done) : hook(req, res, done); } catch (err) { done(err); } } }
javascript
{ "resource": "" }
q40478
create
train
function create(delay) { let timeoutId; let _reject; const promise = new Promise((resolve, reject) => { _reject = reject; timeoutId = setTimeout(() => { resolve(); pendingPromises.delete(promise); }, delay); }); pendingPromises.set(promise, { timeoutId, reject: _reject, }); log('debug', 'Created a delay:', delay); return promise; }
javascript
{ "resource": "" }
q40479
clear
train
async function clear(promise) { if (!pendingPromises.has(promise)) { return Promise.reject(new YError('E_BAD_DELAY')); } const { timeoutId, reject } = pendingPromises.get(promise); clearTimeout(timeoutId); reject(new YError('E_DELAY_CLEARED')); pendingPromises.delete(promise); log('debug', 'Cleared a delay'); }
javascript
{ "resource": "" }
q40480
getField
train
function getField(field) { return function map(element) { if (element) { if (Array.isArray(element)) { return element.map(map).join(''); } else if (typeof element === 'string') { return element; } else if (typeof element === 'object') { return element[field]; } } return ''; }; }
javascript
{ "resource": "" }
q40481
getList
train
function getList() { if(!COMMAND_LIST) { COMMAND_LIST = []; for(var z in this.execs) { COMMAND_LIST.push(this.execs[z].definition.getDefinition()); } } return COMMAND_LIST; }
javascript
{ "resource": "" }
q40482
info
train
function info(req, res) { var list = [] , i , exec; for(i = 0;i < req.args.length;i++) { exec = this.execs[req.args[i]]; list.push(exec ? exec.definition.getDefinition() : null); } res.send(null, list); }
javascript
{ "resource": "" }
q40483
getkeys
train
function getkeys(req, res) { var keys = [] // target command , tcmd = req.args[0] , def = Constants.MAP[tcmd]; if(def) { keys = def.getKeys(req.args.slice(1)); } res.send(null, keys); }
javascript
{ "resource": "" }
q40484
count
train
function count(req, res) { var list = getList.call(this); return res.send(null, list.length); }
javascript
{ "resource": "" }
q40485
execute
train
function execute(req, res) { if(req.info.command.sub) { this.delegate(req, res); // no subcommand return command list }else{ var list = getList.call(this); return res.send(null, list); } }
javascript
{ "resource": "" }
q40486
buildPaths
train
function buildPaths(file, arr) { if (!grunt.file.exists(file)) { grunt.log.warn('File "' + file + '" not found'); return null; } arr.unshift(file); var namespaces = pathTable[file]; if (namespaces && namespaces.length) { for (var i = namespaces.length, ns; i-- > 0;) { ns = namespaces[i]; if (!nsTable[ns]) { throw new Error( 'Required namespace "' + ns + '" not found in ' + file); } buildPaths(nsTable[ns], arr); } } return arr; }
javascript
{ "resource": "" }
q40487
create
train
function create({ pending = false, // eslint-disable-line no-shadow refreshing = false, // eslint-disable-line no-shadow fulfilled = false, // eslint-disable-line no-shadow rejected = false, // eslint-disable-line no-shadow value = null, reason = null, }) { return { pending, refreshing, fulfilled, rejected, value, reason, }; }
javascript
{ "resource": "" }
q40488
cloneById
train
function cloneById (v, k) { if (Array.isArray(v)) { let match = find(v, it => String(it[options.idField]) === String(k)); return match? cloneDeep(match) : (options.keepOrig? k : null); } else { return String(v[options.idField]) === String(k)? cloneDeep(v) : (options.keepOrig? k : null); } }
javascript
{ "resource": "" }
q40489
train
function(req, topic, messages){ payloads[0]['topic'] = topic payloads[0]['messages']= JSON.stringify(messages); console.log(payloads[0]['messages']); setTimeout(function () { producer.send(payloads, function (err, data) { if(err){ console.log(err); } }); producer.on('error', function (err) { console.log(err); }); }, 1000); }
javascript
{ "resource": "" }
q40490
train
function(callback){ if(source['brokerId']!='null'){ db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){ mqttHost = result[0]['ipAddress']; mqttPort = result[0]['port']; console.log(result); }); }else{ mqttHost = mqttPort = null; } }
javascript
{ "resource": "" }
q40491
train
function(callback){ var o_id = BSON.ObjectID.createFromHexString(source['_id']); db.db(dbName).collection(collectionName).find({_id:o_id}).toArray(function(err,result){ response.send(result); o_id = null; }); }
javascript
{ "resource": "" }
q40492
train
function(callback){ var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){ if(result.length!=0){ roadmapNum = roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1; } else{ roadmapNum = roadMapIdTemp = 1; } db.db(dbName).collection(collectionName).insertOne({ "roadMapId" : roadMapIdTemp.toString(), "clientId" : source['clientId'], "orderNode" : source['orderNode'], "initNode" : source['initNode'], "lastNode" : source['lastNode'], "incomingNode" : source['incomingNode'], "outingNode" : source['outingNode'], "isInput" : source['isInput'], "isOutput" : source['isOutput'], "nodeIds" : source['nodeIds'] },function(err, result){ response.send(roadmapNum.toString()); }); }); }
javascript
{ "resource": "" }
q40493
lset
train
function lset(index, value) { if(index < 0) index = this._data.length + index; // command should validate the index if(index < 0 || index >= this._data.length) return null; this._data[index] = value; }
javascript
{ "resource": "" }
q40494
linsert
train
function linsert(beforeAfter, pivot, value) { //console.dir(pivot); //console.dir(this._data); var ind = this.indexOf(pivot); if(ind === -1) return ind; // note beforeAfter can be a buffer ind = (('' + beforeAfter) === BEFORE) ? ind : ind + 1; this._data.splice(ind, 0, value); return this._data.length; }
javascript
{ "resource": "" }
q40495
lindex
train
function lindex(index) { if(index < 0) index = this._data.length + index; return this._data[index] || null; }
javascript
{ "resource": "" }
q40496
lrem
train
function lrem(count, value) { var ind, deleted = 0; if(count === 0) { while((ind = this.indexOf(value)) !== -1) { this._data.splice(ind, 1); deleted++; } }else if(count > 0) { while((ind = this.indexOf(value)) !== -1 && (deleted < count)) { this._data.splice(ind, 1); deleted++; } }else{ count = Math.abs(count); while((ind = this.lastIndexOf(value)) !== -1 && (deleted < count)) { this._data.splice(ind, 1); deleted++; } } return deleted; }
javascript
{ "resource": "" }
q40497
lrange
train
function lrange(start, stop) { if(start < 0) start = this._data.length + start; if(stop < 0) stop = this._data.length + stop; stop++; return this._data.slice(start, stop); }
javascript
{ "resource": "" }
q40498
iterateKeys
train
function iterateKeys() { var obj = getKeyObject(db, j); if(obj === null) return onKeysComplete(); encoder.write(obj, function onWrite() { j++; setImmediate(iterateKeys); }); }
javascript
{ "resource": "" }
q40499
train
function (user, req, cb) { CoreController.getPluginViewDefaultTemplate({ viewname: 'email/user/forgot_password_link', themefileext: appSettings.templatefileextension, }, function (err, templatepath) { if (err) { cb(err); } else { // console.log('emailForgotPasswordLink templatepath', templatepath); if (templatepath === 'email/user/forgot_password_link') { templatepath = path.resolve(process.cwd(), 'node_modules/periodicjs.ext.login/views', templatepath + '.' + appSettings.templatefileextension); } // console.log('user for forgot password', user); var coreMailerOptions = { appenvironment: appenvironment, to: user.email, from: appSettings.fromemail || appSettings.adminnotificationemail, replyTo: appSettings.fromemail || appSettings.adminnotificationemail, subject: loginExtSettings.settings.forgotPasswordEmailSubject || appSettings.name + ' - Reset your password', emailtemplatefilepath: templatepath, emailtemplatedata: { user: user, appname: appSettings.name, hostname: req.headers.host, filename: templatepath, adminPostRoute: req.adminPostRoute, }, }; if (loginExtSettings.settings.adminbccemail || appSettings.adminbccemail) { coreMailerOptions.bcc = loginExtSettings.settings.adminbccemail || appSettings.adminbccemail; } CoreMailer.sendEmail(coreMailerOptions, cb); } } ); // cb(null, options); }
javascript
{ "resource": "" }