_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q37300
train
function(step) { if (!step) { throw new Error('Not enough arguments'); } if (Array.isArray(step)) { step.forEach(function(s) { this.add(s); }, this); } else { if (step.nextDelay && step.nextDelay < 0) { throw new Error('nextDelay property must be greater than 0'); } if (step.fn && typeof(step.fn) !== 'function') { throw new Error('The property fn must be a function'); } if (step.autoDestroy && typeof(step.autoDestroy) !== 'boolean') { throw new Error('The property autoDestroy must be a boolean'); } if (step.preload && !Array.isArray(step.preload)) { throw new Error('The property preload must be an array of urls'); } this.steps.push(step); } return this; }
javascript
{ "resource": "" }
q37301
train
function(index) { var step; if (!this.steps[index]) { if (this.config.loop && this._loops < this.config.maxLoops) { this._loops++; step = this.steps[this._current = 0]; } else { return false; } } else { step = this.steps[index]; } if (step.preload && !step.preloaded) { this._handlePreload(step.preload, function() { step.preloaded = true; this._setNext(step.nextDelay); if(step.fn) { step.fn.call(this, step); } }.bind(this)); } else { this._setNext(step.nextDelay); if(step.fn) { step.fn.call(this, step); } } if (step.autoDestroy) { var i = this.steps.indexOf(step); this._current = i; this._recentDestroy = true; this.steps.splice(i, 1); } }
javascript
{ "resource": "" }
q37302
train
function(nextDelay) { var delay = nextDelay || this.config.defaultDelay; if (delay && this._playing) { this._currentTimeout = setTimeout(function() { this._executeStep(++this._current); }.bind(this), delay); } }
javascript
{ "resource": "" }
q37303
train
function(images, callback) { var loaded = 0; images.forEach(function(src) { var image = new Image(); image.onload = function() { ++loaded; loaded === images.length && callback(); }; image.src = src; }); }
javascript
{ "resource": "" }
q37304
train
function(config, name) { if (config && config !== Object(config)) { throw new Error('Config object should be a key/value object.'); } var defaultConfig = { loop: false, maxLoops: Infinity }; var instance = Object.create(Queue); this.queues.push(name ? { name: name, instance: instance } : { instance: instance }); merge(instance, { config: merge({}, defaultConfig, config), steps: [] }); return instance; }
javascript
{ "resource": "" }
q37305
train
function(program) { this.cli = program; this.cmd = this.cli; if(process.env.CLI_TOOLKIT_HELP_CMD) { var alias = this.cli.finder.getCommandByName; var cmd = alias(process.env.CLI_TOOLKIT_HELP_CMD, this.cli.commands()); if(cmd) { this.cmd = cmd; } } this.eol = eol; this.format = fmt.TEXT_FORMAT; this.help2man = !!process.env.help2man; this.conf = this.cli.configure().help; this.vanilla = this.conf.vanilla; if(this.colon === undefined) { this.colon = typeof(this.conf.colon) === 'boolean' ? this.conf.colon : true; } this.messages = this.conf.messages; this.limit = this.conf.maximum ? this.conf.maximum : 80; this.usage = this.cli.usage(); this.delimiter = this.conf.delimiter ? this.conf.delimiter : ', '; this.assignment = this.conf.assignment ? this.conf.assignment : '='; this.align = this.conf.align || columns.COLUMN_ALIGN; this.collapse = this.conf.collapse; if(!~columns.align.indexOf(this.align)) { this.align = columns.COLUMN_ALIGN; } this.sections = sections.slice(0); var i, k; // custom unknown sections in help conf if(this.cmd.sections()) { var ckeys = Object.keys(this.cmd.sections()); // custom sections come after options var ind = this.sections.indexOf(manual.OPTIONS) + 1; for(i = 0;i < ckeys.length;i++) { k = ckeys[i].toLowerCase(); if(!~this.sections.indexOf(k)) { // inject into section list this.sections.splice(ind, 0, k); ind++; } } } this.padding = this.conf.indent; this.space = this.conf.space || repeat(this.padding); this.wraps = true; this.width = this.conf.width; // whether to use columns this.use = this.format === fmt.TEXT_FORMAT; this.headers = {}; for(k in headers) { this.headers[k] = headers[k]; } this.metrics = {}; this.getMetrics(); this.titles(); }
javascript
{ "resource": "" }
q37306
AbstractFilter
train
function AbstractFilter(vertexSrc, fragmentSrc, uniforms) { /** * An array of shaders * @member {Shader[]} * @private */ this.shaders = []; /** * The extra padding that the filter might need * @member {number} */ this.padding = 0; /** * The uniforms as an object * @member {object} * @private */ this.uniforms = uniforms || {}; /** * The code of the vertex shader * @member {string[]} * @private */ this.vertexSrc = vertexSrc || DefaultShader.defaultVertexSrc; /** * The code of the frament shader * @member {string[]} * @private */ this.fragmentSrc = fragmentSrc || DefaultShader.defaultFragmentSrc; //TODO a reminder - would be cool to have lower res filters as this would give better performance. //typeof fragmentSrc === 'string' ? fragmentSrc.split('') : (fragmentSrc || []); }
javascript
{ "resource": "" }
q37307
train
function(type, node) { return seen.indexOf(node) == -1 && ((type == 'AssignmentExpression' && node.right == expr) || (type == 'VariableDeclarator' && node.init == expr)); }
javascript
{ "resource": "" }
q37308
wrapNodeSocket
train
function wrapNodeSocket(socket, reportError) { // Data traveling from node socket to consumer var incoming = makeChannel(); // Data traveling from consumer to node socket var outgoing = makeChannel(); var onDrain2 = wrapHandler(onReadable, onError); onTake = wrapHandler(onTake, onError); var paused = false; var ended = false; outgoing.take(onTake); socket.on("error", onError); socket.on("drain", wrap(onDrain, onError)); socket.on("readable", wrap(onReadable, onError)); socket.on("end", wrap(onEnd, onError)); function onError(err) { if (err.code === "EPIPE" || err.code === "ECONNRESET") { return onEnd(); } if (reportError) return reportError(err); console.error(err.stack); } function onTake(data) { if (ended) return; // console.log("TAKE", data); if (data === undefined) { ended = true; return socket.end(); } if (socket.write(data)) { outgoing.take(onTake); } else { if (!paused) paused = true; } } function onDrain() { if (paused) { paused = false; outgoing.take(onTake); } } function onEnd() { if (ended) return; ended = true; incoming.put(undefined); } function onReadable() { if (ended) return; while (true) { var chunk = socket.read(); // console.log("READ", chunk); if (!chunk) return; if (!incoming.put(chunk)) { incoming.drain(onDrain2); return; } } } return { put: outgoing.put, drain: outgoing.drain, take: incoming.take, }; }
javascript
{ "resource": "" }
q37309
request
train
function request (type, url, data) { return new Promise(function (fulfill, reject) { // Set ajax to correct XHR type. Source: https://gist.github.com/jed/993585 var Xhr = window.XMLHttpRequest||ActiveXObject, req = new Xhr('MSXML2.XMLHTTP.3.0'); req.open(type, url, true); req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); req.onreadystatechange = function (e) { if (this.readyState === 4) { if (this.status === 200) { var res = prepareResponse(req.responseText); fulfill(res, req); } else { reject(new Error('Request responded with status ' + req.statusText)); } } }; req.send(data); }); }
javascript
{ "resource": "" }
q37310
monkeyPatch
train
function monkeyPatch() { var script = function() { window.__karma__ = true; (function patch() { if (typeof window.__bs === 'undefined') { window.setTimeout(patch, 500); } else { var oldCanSync = window.__bs.prototype.canSync; window.__bs.prototype.canSync = function(data, optPath) { data.url = window.location.pathname.substr(0, window.location.pathname.indexOf('/www')) + data.url.substr(data.url.indexOf('/www')) return oldCanSync.apply(this, [data, optPath]); }; } }()); }; return '<script>(' + script.toString() + '());</script>'; }
javascript
{ "resource": "" }
q37311
startBrowserSync
train
function startBrowserSync(cordovaDir, platforms, opts, cb) { var defaults = { logFileChanges: true, logConnections: true, open: false, snippetOptions: { rule: { match: /<\/body>/i, fn: function(snippet, match) { return monkeyPatch() + snippet + match; } } }, minify: false, watchOptions: {}, files: [], server: { baseDir: [], routes: {} } }; platforms.forEach(function(platform) { var www = getWWWFolder(platform); defaults.server.baseDir.push(path.join(www)); defaults.server.routes['/' + www] = path.join(cordovaDir, www); }); opts = opts || {}; if (typeof opts === 'function') { opts = opts(defaults); } else { for (var key in defaults) { if (typeof opts[key] === 'undefined') { opts[key] = defaults[key]; } } } var bsInstance = BrowserSync.create('cordova-browsersync'); bsInstance.init(opts, function(err, callbackBsInstance) { var urls = callbackBsInstance.options.getIn(['urls']); var servers = {}; ['local', 'external', 'tunnel'].forEach(function(type) { servers[type] = urls.get(type); }); cb(err, { bsInstance: bsInstance, servers: servers }); }); return bsInstance; }
javascript
{ "resource": "" }
q37312
productHunt
train
function productHunt() { let queryParams = { }; return { /** * Sets the request query parameters to fetch the * most popular products from Product Hunt. * * @return {Object} `productHunt` module */ popular() { queryParams.filter = 'popular'; return this; }, /** * Sets the request query parameters to fetch the * newest products from Product Hunt. * * @return {Object} `productHunt` module */ newest() { queryParams.filter = 'newest'; return this; }, /** * Sets the request query parameters to fetch todays * products from Product Hunt. * * @return {Object} `productHunt` module */ today() { queryParams.page = 0; return this; }, /** * Sets the request query parameters to fetch * yesterdays products from Product Hunt. * * @return {Object} `productHunt` module */ yesterday() { queryParams.page = 1; return this; }, /** * Sets the request query parameters to fetch * Product Hunt products from `n` days ago. * * @param {Number} n - number of days * * @return {Object} `productHunt` module */ daysAgo(n) { const days = parseInt(n, 10); if (!isNaN(days)) { queryParams.page = days; } return this; }, /** * Executes the built request. * * @return {Promise} resolves to an Array of products */ exec() { const params = Object.assign( {}, DEFAULT_QUERY_PARAMS, queryParams ); const request = http.GET(API, params); queryParams = { }; return request; } }; }
javascript
{ "resource": "" }
q37313
readRequireConfig
train
function readRequireConfig( file ) { 'use strict'; var config = fs.readFileSync( file ); /*jshint -W054*/ var evaluate = new Function( 'var window = this;' + config + '; return require || window.require;' ); return evaluate.call( {} ); }
javascript
{ "resource": "" }
q37314
_detect
train
function _detect(eachFn, arr, iterator, mainCallback) { eachFn(arr, function (x, index, callback) { iterator(x, function (v, result) { if (v) { mainCallback(result || x); mainCallback = async.noop; } else { callback(); } }); }, function () { mainCallback(); }); }
javascript
{ "resource": "" }
q37315
getCurrentTarget
train
function getCurrentTarget( slot ) { if( !G.target ) return null; for( var i = 0 ; i < G.target.length ; i++ ) { var target = G.target[i]; if( !slot || typeof target.slots[slot] === 'function' ) return target; } return null; }
javascript
{ "resource": "" }
q37316
validateNew
train
function validateNew(options) { options = validateOptions(options); //console.log('options after validation', util.inspect(options, {depth: null})); //return; //console.log('skemer.validateAdd called', arguments); return validateData.apply(this, [options, undefined].concat(Array.prototype.slice.call(arguments, 1))); }
javascript
{ "resource": "" }
q37317
train
function () { return validateData.apply(this, [this.options, undefined].concat(Array.prototype.slice.call(arguments))); }
javascript
{ "resource": "" }
q37318
reset
train
function reset(req, res) { this.state.slowlog.reset(); res.send(null, Constants.OK); }
javascript
{ "resource": "" }
q37319
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var sub = info.command.sub , scmd = ('' + sub.cmd) , args = sub.args , amount; if(scmd === Constants.SUBCOMMAND.slowlog.get.name && args.length) { if(args.length > 1) { throw new CommandArgLength(cmd, scmd); } amount = parseInt('' + args[0]); if(isNaN(amount)) { throw IntegerRange; } args[0] = amount; } }
javascript
{ "resource": "" }
q37320
sassifyFn
train
function sassifyFn(rawObject) { var sassified = ''; Object.keys(rawObject).forEach(function iterateVariables(key) { var variable = rawObject[key]; var stringified = JSON.stringify(variable); // Trim off double quotes for CSS variables. stringified = stringified.substring(1, stringified.length - 1); sassified += '$' + key + ': ' + stringified + ';\n'; }); return sassified; }
javascript
{ "resource": "" }
q37321
noval
train
function noval(value, recursive) { assertType(recursive, 'boolean', true, 'Invalid parameter: recursive'); if (recursive === undefined) recursive = false; if (value === undefined || value === null) { return true; } else if (typeof value === 'string') { return (value === ''); } else if (recursive && (value instanceof Array)) { let n = value.length; for (let i = 0; i < n; i++) { if (!noval(value[i], true)) return false; } return true; } else if (recursive && (typeof value === 'object') && (value.constructor === Object)) { for (let p in value) { if (!noval(value[p], true)) return false; } return true; } else { return false; } }
javascript
{ "resource": "" }
q37322
_readContent
train
function _readContent (files, writeStream, separator) { return 0 >= files.length ? Promise.resolve() : Promise.resolve().then(() => { const file = files.shift().trim(); return isFileProm(file).then((exists) => { const isPattern = -1 < separator.indexOf("{{filename}}"); return !exists ? _readContent(files, writeStream, separator) : Promise.resolve().then(() => { return !isPattern ? Promise.resolve() : new Promise((resolve, reject) => { writeStream.write(separator.replace("{{filename}}", basename(file)), (err) => { return err ? reject(err) : resolve(); }); }); }).then(() => { return new Promise((resolve, reject) => { const readStream = createReadStream(file); let error = false; readStream.once("error", (err) => { error = true; readStream.close(); reject(err); }).once("open", () => { readStream.pipe(writeStream, { "end": false }); }).once("close", () => { if (!error) { resolve(); } }); }); }).then(() => { return 0 >= files.length ? Promise.resolve() : Promise.resolve().then(() => { return isPattern ? Promise.resolve() : new Promise((resolve, reject) => { writeStream.write(separator, (err) => { return err ? reject(err) : resolve(); }); }); }).then(() => { return _readContent(files, writeStream, separator); }); }); }); }); }
javascript
{ "resource": "" }
q37323
hsetnx
train
function hsetnx(key, field, value, req) { var val = this.getKey(key, req) , exists = this.hexists(key, field, req); if(!val) { val = new HashMap(); this.setKey(key, val, undefined, undefined, undefined, req); } if(!exists) { // set on the hashmap val.setKey(field, value); } return exists ? 0 : 1; }
javascript
{ "resource": "" }
q37324
hget
train
function hget(key, field, req) { // get at db level var val = this.getKey(key, req); if(!val) return null; // get at hash level val = val.getKey(field) if(!val) return null; return val; }
javascript
{ "resource": "" }
q37325
hexists
train
function hexists(key, field, req) { var val = this.getKey(key, req); if(!val) return 0; return val.keyExists(field); }
javascript
{ "resource": "" }
q37326
hgetall
train
function hgetall(key, req) { var val = this.getKey(key, req) , list = []; if(!val) return list; val.getKeys().forEach(function(k) { list.push(k, '' + val.getKey(k)); }); return list; }
javascript
{ "resource": "" }
q37327
hkeys
train
function hkeys(key, req) { var val = this.getKey(key, req); if(!val) return []; return val.getKeys(); }
javascript
{ "resource": "" }
q37328
hlen
train
function hlen(key, req) { var val = this.getKey(key, req); if(!val) return 0; return val.hlen(); }
javascript
{ "resource": "" }
q37329
hdel
train
function hdel(key /* field-1, field-N, req */) { var args = slice.call(arguments, 1) , req = typeof args[args.length - 1] === 'object' ? args.pop() : null , val = this.getKey(key, req) , deleted = 0 , i; // nothing at key if(!val) return 0; for(i = 0;i < args.length;i++) { deleted += val.delKey(args[i]); } if(val.hlen() === 0) { this.delKey(key, req); } return deleted; }
javascript
{ "resource": "" }
q37330
hmget
train
function hmget(key /* field-1, field-N, req */) { var args = slice.call(arguments, 1) , req = typeof args[args.length - 1] === 'object' ? args.pop() : null , val = this.getKey(key, req) , value , list = [] , i; for(i = 0;i < args.length;i++) { if(!val) { list.push(null); continue; } value = val.getKey(args[i]) list.push(value !== undefined ? value : null); } return list; }
javascript
{ "resource": "" }
q37331
hmset
train
function hmset(key /* field-1, value-1, field-N, value-N, req */) { var args = slice.call(arguments, 1) , req = typeof args[args.length - 1] === 'object' ? args.pop() : null , val = this.getKey(key, req) , i; if(!val) { val = new HashMap(); this.setKey(key, val, undefined, undefined, undefined, req); } for(i = 0;i < args.length;i+=2) { val.setKey(args[i], args[i + 1]); } return OK; }
javascript
{ "resource": "" }
q37332
hincrbyfloat
train
function hincrbyfloat(key, field, amount, req) { var map = this.getKey(key, req) , val; if(!map) { map = new HashMap(); this.setKey(key, map, undefined, undefined, undefined, req); } val = utils.strtofloat(map.getKey(field)); amount = utils.strtofloat(amount); val += amount; map.setKey(field, val); // store as number and return a number, // the command implementation should coerce the result // to a string for a bulk string reply return val; }
javascript
{ "resource": "" }
q37333
hincrby
train
function hincrby(key, field, amount, req) { var map = this.getKey(key, req) , val; if(!map) { map = new HashMap(); this.setKey(key, map, undefined, undefined, undefined, req); } val = utils.strtoint(map.getKey(field)); amount = utils.strtoint(amount); val += amount; map.setKey(field, val); return val; }
javascript
{ "resource": "" }
q37334
train
function(v) { if (v instanceof Vec3) { return new Vec3(this.x + v.x, this.y + v.y, this.z + v.z); } else if(v instanceof Vec2){ return new Vec3(this.x + v.x, this.y + v.y, this.z); } else if(typeof v === 'number') { return new Vec3(this.x + v, this.y + v, this.z + v); } else { throw new TypeError('Invalid argument', v); } }
javascript
{ "resource": "" }
q37335
train
function() { return { theta: Math.atan2(this.z, this.x), phi: Math.asin(this.y / this.length()) }; }
javascript
{ "resource": "" }
q37336
train
function(dec) { if(!dec){ dec = 2; } return '{x: ' + this.x.toFixed(dec) + ', y: ' + this.y.toFixed(dec) + ', z: ' + this.z.toFixed(dec) + '}'; }
javascript
{ "resource": "" }
q37337
train
function() { return new Vec3(Math.round(this.x), Math.round(this.y), Math.round(this.z)); }
javascript
{ "resource": "" }
q37338
train
function(m){ return new Vec3( this.x*m[0][0]+this.y*m[0][1]+this.z*m[0][2], this.x*m[1][0]+this.y*m[1][1]+this.z*m[1][2], this.x*m[2][0]+this.y*m[2][1]+this.z*m[2][2] ); }
javascript
{ "resource": "" }
q37339
train
function(m){ var x = this.x; var y = this.y; var z = this.z; this.x = x*m[0][0]+y*m[0][1]+z*m[0][2]; this.y = x*m[1][0]+y*m[1][1]+z*m[1][2]; this.z = x*m[2][0]+y*m[2][1]+z*m[2][2]; return this; }
javascript
{ "resource": "" }
q37340
train
function(p){ return new Vec3(Math.pow(this.x, p), Math.pow(this.y, p), Math.pow(this.z, p)); }
javascript
{ "resource": "" }
q37341
execSpawn
train
function execSpawn(command, args, resultMsg, errorMsg) { return superspawn.spawn(command, args).then(function(result) { return resultMsg + result; }, function(error) { return errorMsg + error; }); }
javascript
{ "resource": "" }
q37342
finishQuerying
train
function finishQuerying(domain, err, records) { // Set time until our next query var expiration = Date.now() + ttl * 1000; // If there was an error querying the domain if (err) { // If the domain was not found if (err.code == 'ENOTFOUND') { // If we have a function to handle missing domains if (notfoundHandler) { // Call it with a callback that lets it decide how to proceed return notfoundHandler(domain, function(remove) { // Remove the domain from circulation if requested if (remove) return db.hdel('querying_domains', domain, next); // Otherwise, keep it in circulation else completeQuery(); }); // If there's no function to handle missing domains } else { // Just return the domain to the query queue return completeQuery(); } // If it was some other kind of error } else { // Spit it up return cb(err); } } // Set TTLs on the records records = records.map(function(record){record.ttl = ttl; return record}); // If we process new records if (process) { // Set the new records and get the old ones db.getset('records:' + domain, JSON.stringify(records), function(err, oldrecords) { if (err) return cb(err); // If the old ones aren't the same as the new ones if (!(oldrecords && equal(records, JSON.parse(oldrecords)))) { // Mark this domain as processing db.eval(hshd, 2, 'processing_domains', 'querying_domains', domain, expiration, function(err, res) { if (err) return cb(err); // Process the new records process(domain,records,finishProcessing); }); // If the old ones were the same, // just advance as if we weren't processing } else completeQuery(); }); } else { db.set('records:' + domain, JSON.stringify(records), completeQuery); } // Mark that we've set the records (if any) and finish function completeQuery(err) { if (err) return cb(err); db.eval(zahd, 2, 'expiring_domains', 'querying_domains', expiration, domain, next); } // Mark that we've finished processing records function finishProcessing(err) { if (err) return cb(err); db.eval(hmz, 2, 'processing_domains', 'expiring_domains', domain, next); } }
javascript
{ "resource": "" }
q37343
finishProcessing
train
function finishProcessing(err) { if (err) return cb(err); db.eval(hmz, 2, 'processing_domains', 'expiring_domains', domain, next); }
javascript
{ "resource": "" }
q37344
iface
train
function iface(end) { if (end) { return db.quit(next); } else { // Get all the domains whose records expired some time before now db.eval(scoreRange,2,'expiring_domains','querying_domains', '-inf', Date.now(), function (err, res) { if (err) return cb(err); // Query each of these domains for (var i = 0; i < res.length; i += 2) { queryDomain(res[i], finishQuerying.bind(null, res[i])); } }); return iface; } }
javascript
{ "resource": "" }
q37345
getAcadSem
train
function getAcadSem(acadWeekNumber) { var earliestSupportedWeek = 1; var lastWeekofSem1 = 23; var lastWeekofSem2 = 40; var lastWeekofSpecialSem1 = 46; var lastWeekofSpecialSem2 = 52; if (acadWeekNumber >= earliestSupportedWeek && acadWeekNumber <= lastWeekofSem1) { return sem1; } else if (acadWeekNumber > lastWeekofSem1 && acadWeekNumber <= lastWeekofSem2) { return sem2; } else if (acadWeekNumber > lastWeekofSem2 && acadWeekNumber <= lastWeekofSpecialSem1) { return special1; } else if (acadWeekNumber > lastWeekofSpecialSem1 && acadWeekNumber <= lastWeekofSpecialSem2) { return special2; } console.warn('[nusmoderator] Unsupported acadWeekNumber as parameter: ' + acadWeekNumber); return null; }
javascript
{ "resource": "" }
q37346
getAcadWeekName
train
function getAcadWeekName(acadWeekNumber) { switch (acadWeekNumber) { case 7: return { weekType: 'Recess', weekNumber: null }; case 15: return { weekType: 'Reading', weekNumber: null }; case 16: case 17: return { weekType: 'Examination', weekNumber: acadWeekNumber - 15 }; default: { var weekNumber = acadWeekNumber; if (weekNumber >= 8) { // For weeks after recess week weekNumber -= 1; } if (acadWeekNumber < 1 || acadWeekNumber > 17) { console.warn('[nusmoderator] Unsupported acadWeekNumber as parameter: ' + acadWeekNumber); return null; } return { weekType: 'Instructional', weekNumber: weekNumber }; } } }
javascript
{ "resource": "" }
q37347
getAcadWeekInfo
train
function getAcadWeekInfo(date) { var currentAcad = getAcadYear(date); var acadYear = currentAcad.year; var acadYearStartDate = currentAcad.startDate; var acadWeekNumber = Math.ceil((date.getTime() - acadYearStartDate.getTime() + 1) / oneWeekDuration); var semester = getAcadSem(acadWeekNumber); var weekType = null; var weekNumber = null; switch (semester) { case sem2: // Semester 2 starts 22 weeks after Week 1 of semester 1 acadWeekNumber -= 22; case sem1: if (acadWeekNumber === 1) { weekType = 'Orientation'; break; } if (acadWeekNumber > 18) { weekType = 'Vacation'; weekNumber = acadWeekNumber - 18; break; } acadWeekNumber -= 1; { var week = getAcadWeekName(acadWeekNumber); weekType = week.weekType; weekNumber = week.weekNumber; } break; case special2: // Special Term II starts 6 weeks after Special Term I acadWeekNumber -= 6; case special1: // Special Term I starts on week 41 of the AY acadWeekNumber -= 40; weekType = 'Instructional'; weekNumber = acadWeekNumber; break; default: if (acadWeekNumber === 53) { // This means it is the 53th week of the AY, and this week is Vacation. // This happens 5 times every 28 years. weekType = 'Vacation'; weekNumber = null; } break; } return { year: acadYear, sem: semester, type: weekType, num: weekNumber }; }
javascript
{ "resource": "" }
q37348
execute
train
function execute(req, res) { // stored in milliseconds but this command returns seconds res.send(null, Math.round(this.state.lastsave / 1000)); }
javascript
{ "resource": "" }
q37349
Q_chainmap_graceful
train
function Q_chainmap_graceful(args, func, failureCallback) { return Q.when().then(function(inValue) { return args.reduce(function(soFar, arg) { return soFar.then(function(val) { return func(arg, val); }).fail(function(err) { if (failureCallback) { failureCallback(err); } }); }, Q(inValue)); }); }
javascript
{ "resource": "" }
q37350
isValueObject
train
function isValueObject(obj) { return (obj instanceof Number) || (obj instanceof String) || (obj instanceof Boolean) || (obj === null); }
javascript
{ "resource": "" }
q37351
enter
train
function enter(f, rejected) { return function() { try { return Promise.resolve(f.apply(this, arguments)).catch(rejected) } catch(e) { return rejected(e) } } }
javascript
{ "resource": "" }
q37352
internal_parse_scope
train
function internal_parse_scope(center, distributionScope) { // "?" or "*" is filted by this.require() if (distributionScope.length < 4) return this.require(":::"); // systemPart:pathPart:scopePart // - rx_tokens = /^([^:]+):(.*):([^:]+)$/ -> m[0],m[1],m[2] var rx_tokens = /^(.*):([^:]+)$/, m = distributionScope.match(rx_tokens); if (! m) return this.require(":::"); // TODO: dynamic scopePart parser, the <parts> is systemPart:pathPart // - var full = m[0], parts = m[1], scopePart = m[2]; return (m[2] == '?') ? this.require("::?") : (m[2] == '*') ? Promise.resolve(center.require(m[1])) : Promise.reject("dynamic scopePart is not support for '"+distributionScope+"'"); }
javascript
{ "resource": "" }
q37353
train
function(db) { function check_javascript_function(js, plv8, ERROR) { var fun; try { // We'll check only positive input if(js) { fun = (new Function('return (' + js + ')'))(); if(! (fun && (fun instanceof Function)) ) { throw TypeError("Input is not valid JavaScript function: " + (typeof fun) + ": " + fun); } } } catch (e) { plv8.elog(ERROR, e); return false; } return true; } return db.query('CREATE OR REPLACE FUNCTION check_javascript_function(js text) RETURNS boolean LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(check_javascript_function, ['js', 'plv8', 'ERROR'])); }
javascript
{ "resource": "" }
q37354
exec
train
function exec(cmd) { const ret = shell.exec(cmd, { silent: true }); if (ret.code != 0) { console.error("Error:", ret.stdout, ret.stderr); process.exit(1); } return ret; }
javascript
{ "resource": "" }
q37355
shutdown
train
function shutdown() { var timer for (var id in requests) if (timer = requests[id].timer) { clearTimeout(timer) requests[id].timer = null } }
javascript
{ "resource": "" }
q37356
sassTranspiler
train
function sassTranspiler(path) { return function () { return gulp.src(path) .pipe(sass({outputStyle: 'compressed'})) .pipe(autoprefixer({ browsers: ['last 2 versions'] })) .pipe(gulp.dest('dist')); } }
javascript
{ "resource": "" }
q37357
train
function(object, converters, property) { var self = this; object.__addSetter(property, this.SETTER_NAME , this.SETTER_WEIGHT, function(value, fields) { return self.apply(value, converters, property, fields, this); }); }
javascript
{ "resource": "" }
q37358
train
function(value, converters, property, fields, object) { _.each(converters, function(converter) { value = converter.call(object, value, fields, property); }); return value; }
javascript
{ "resource": "" }
q37359
rf
train
function rf(df1, df2) { var rchisqRatio; rchisqRatio = function(d) { return chisq.rchisq(d)() / d; }; if (df1 <= 0 || df2 <= 0) { return function() { return NaN; }; } return function() { return rchisqRatio(df1) / rchisqRatio(df2); }; }
javascript
{ "resource": "" }
q37360
_subscribersDelete
train
function _subscribersDelete(id, revokeMeters) { return Api.request({ method: 'DELETE', url: makeUrl([this._config.default, id]), data: { revoke_meters: revokeMeters || false }, headers: { 'Content-Type': 'application/json;charset=UTF-8' } }); }
javascript
{ "resource": "" }
q37361
parseDocToTree
train
function parseDocToTree(doc, defaultTitle) { // save the parsed tree const tree = []; const lines = doc.split('\n'); let line, m; // 保存一个文档区域 let section = null; let parentSection = null; // if in a ``` block let inBlock = false; // little trick,如果第一行不是 #,则增加一个 # if (!/^#(?!#)/.test(lines[0])) { lines.unshift('# ' + defaultTitle); } while ((line = lines.shift()) !== undefined) { m = line && line.match(/^(#+)(?!#)(.*)$/); if (!inBlock && m && m.length == 3) { section = { title: m[2].trim(), level: m[1].length, parent: null, children: [] }; while (parentSection && parentSection.level >= section.level) { parentSection = parentSection.parent; } if (parentSection) { section.parent = parentSection; parentSection.children.push(section); parentSection = section; } else { tree.push(section); parentSection = section; } } else if (section) { if (line.indexOf('```') === 0) { inBlock = !inBlock; } section.children.push(line); } else { throw new Error(`NOT VALID LINE: ${line}`); } } return tree; }
javascript
{ "resource": "" }
q37362
treeDFS
train
function treeDFS(tree, callback) { for (let it of tree.slice()) { callback(it, tree); if (typeof it === 'object') { treeDFS(it.children, callback); } } }
javascript
{ "resource": "" }
q37363
treeToDoc
train
function treeToDoc(tree) { if (tree.length === 0) return ''; return tree.map((it) => { if (typeof it === 'object') { return `${'#'.repeat(it.level)} ${it.title}\n${treeToDoc(it.children)}`; } return it; }).join('\n'); }
javascript
{ "resource": "" }
q37364
callEngineScripts
train
function callEngineScripts(engines, project_dir) { return Q.all( engines.map(function(engine){ // CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the script exists var scriptPath = engine.scriptSrc ? '"' + engine.scriptSrc + '"' : null; if(scriptPath && (isWindows || fs.existsSync(engine.scriptSrc)) ) { var d = Q.defer(); if(!isWindows) { // not required on Windows fs.chmodSync(engine.scriptSrc, '755'); } child_process.exec(scriptPath, function(error, stdout, stderr) { if (error) { events.emit('warn', engine.name +' version check failed ('+ scriptPath +'), continuing anyways.'); engine.currentVersion = null; } else { engine.currentVersion = cleanVersionOutput(stdout, engine.name); if (engine.currentVersion === '') { events.emit('warn', engine.name +' version check returned nothing ('+ scriptPath +'), continuing anyways.'); engine.currentVersion = null; } } d.resolve(engine); }); return d.promise; } else { if(engine.currentVersion) { engine.currentVersion = cleanVersionOutput(engine.currentVersion, engine.name); } else { events.emit('warn', engine.name +' version not detected (lacks script '+ scriptPath +' ), continuing.'); } return Q(engine); } }) ); }
javascript
{ "resource": "" }
q37365
defineProperties
train
function defineProperties(target, options/*, source, ...*/) { if (options == null) options = {}; var i = 2, max = arguments.length, source, prop; for (; i < max; ++i) { source = arguments[i]; if (!(source instanceof Object)) continue; for (prop in source) { if (source[prop] == null) continue; defineProperty(target, prop, { value: source[prop], enumerable: options.enumerable == null ? true : !!options.enumerable, writable: options.writable == null ? true : !!options.writable, configurable: options.configurable == null ? true : !!options.configurable }); } } return target; }
javascript
{ "resource": "" }
q37366
setProperties
train
function setProperties(target/*, source, ...*/) { var i = 1, max = arguments.length, source, prop; for (; i < max; ++i) { source = arguments[i]; if (!(source instanceof Object)) continue; for (prop in source) { if (source[prop] == null) continue; target[prop] = source[prop]; } } return target; }
javascript
{ "resource": "" }
q37367
extendClass
train
function extendClass(parent, constructor) { var anonymous = function() {}; anonymous.prototype = parent.prototype; constructor.prototype = new anonymous(); constructor.constructor = constructor; defineProperties.apply(null, [constructor.prototype, { configurable: false }].concat(Array.prototype.slice.call(arguments, 2))); defineProperties(constructor, { configurable: false }, { extend: partial(extendClass, constructor) }); return constructor; }
javascript
{ "resource": "" }
q37368
dethrow
train
function dethrow(fn) { try { /* jshint validthis: true */ return fn.apply(this, Array.prototype.slice.call(arguments, 1)); } catch (e) {} }
javascript
{ "resource": "" }
q37369
portable
train
function portable(obj, fn) { if (typeof fn === 'string') fn = obj[fn]; return function() { return fn.apply(obj, arguments); }; }
javascript
{ "resource": "" }
q37370
isValidPath
train
function isValidPath(path, allowDots) { if (typeof path !== 'string') return false; if (!path) return false; if (!/^([a-z]:[\/\\])?[a-z0-9_~\/\.\-]+$/i.test(path)) return false; if (!allowDots && /^\.{1,2}$/.test(path)) return false; return true; }
javascript
{ "resource": "" }
q37371
csv
train
function csv(array) { if (!(array instanceof Array) || array.length === 0) return ''; array = array.slice(0); var i = array.length; while (i--) array[i] = '"' + (''+array[i]).replace(/(\\|")/g, '\\$1') + '"'; return array.join(', '); }
javascript
{ "resource": "" }
q37372
train
function(encoded) { if (encoded instanceof Array) { encoded = encoded.map(function(chunk) {return chunk.replace(/^0x/g, '')}).join(''); } // Each symbol is 4 bits var result = []; var nextIndex = 0; while (nextIndex < encoded.length) { var schemaLength = parseInt(encoded.slice(nextIndex, nextIndex + 1 * 2), 16); var idLength = parseInt(encoded.slice(nextIndex + (1 + schemaLength) * 2, nextIndex + (1 + schemaLength + 2) * 2), 16); var schema = encoded.slice(nextIndex + 1 * 2, nextIndex + (1 + schemaLength) * 2); // Convert to string schema = hexToString(schema); var idHex = encoded.slice(nextIndex + (1 + schemaLength + 2) * 2, nextIndex + (1 + schemaLength + 2 + idLength) * 2); var id = schema.match(allowedProtocolsRegExp) ? idHex : hexToString(idHex); result.push(schema + ':' + id); // Get full cells var cellsPerId = Math.ceil((1 + schemaLength + 2 + idLength) / 32); nextIndex += cellsPerId * 32 * 2; } return result; }
javascript
{ "resource": "" }
q37373
openSocket
train
function openSocket (sessionInfo, callback) { var socketUrl, socketInfo, socket_endpoint, new_socket; _log(sessionInfo); socketUrl = sessionInfo.endpoints.socket[0]; socketInfo = url.parse(socketUrl); _log(socketInfo); socket_endpoint = socketUrl + me.setting.apiroot + '/feed/ws?sid=' + sessionInfo.sid; _log('Connecting to ' + socket_endpoint); new_socket = new ws(socket_endpoint); new_socket.on('open', function () { _log('socket open'); callback(new_socket); }); }
javascript
{ "resource": "" }
q37374
initialize
train
function initialize(options) { // log config.logfile = options.logfile || 'logs/spider.log'; log4js.configure({ appenders: [ { type: 'console', category: 'console'}, { type: 'dateFile', filename: config.logfile, pattern: 'yyyy-MM-dd', category: 'default' } ], replaceConsole: true }); logger = log4js.getLogger('default'); if (!options.startURLs) { logger.error('At least one URL must be specified!'); return -1; } if (!options.filter) { logger.error('Filter must be specified!'); return -1; } config.filter = options.filter; config.startURLs = options.startURLs; config.domains = options.startURLs.map(function(url) { return URL.parse(url).host; }); config.interval = options.interval || 2 * 1000; config.domains.forEach(function(host) { taskQueues[host] = []; }); config.timeout = options.timeout || 10 * 1000; // push all URLs into taskQueues config.startURLs.forEach(function(url) { var urlObj = URL.parse(url); var queue = new TaskQueue(urlObj.host); queue.tasks.push(url); taskQueues.push(queue); }); }
javascript
{ "resource": "" }
q37375
init
train
function init(ctx) { var server = ctx.server; server.ext('onRequest', checkIfSSL); return new Q(ctx); }
javascript
{ "resource": "" }
q37376
parse
train
function parse (strip, associate) { var signature = strip.split('->') if (signature.length !== 2) return null // Param types: var params = signature[0].split(',') for (var i = params.length; i--;) { var p = params[i].trim() if (p === '*') params[i] = null else params[i] = p } // Return type: var returns = signature[1].trim() if (returns === '*') returns = null return associate ? [params, returns, associate] : [params, returns] }
javascript
{ "resource": "" }
q37377
require
train
function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); }
javascript
{ "resource": "" }
q37378
call
train
function call(id, require){ var m = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep || req); }, m, m.exports, outer, modules, cache, entries); // store to cache after successful resolve cache[id] = m; // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; }
javascript
{ "resource": "" }
q37379
train
function() { // Walk all of the elements in the DOM (try to only do this once) var elements = doc.getElementsByTagName('*'); var re = /url\((http.*)\)/ig; for (var i = 0; i < elements.length; i++) { var el = elements[i]; var style = win.getComputedStyle(el); // check for Images if (el.tagName == 'IMG') { CheckElement(el, el.src); } // Check for background images if (style['background-image']) { re.lastIndex = 0; var matches = re.exec(style['background-image']); if (matches && matches.length > 1) CheckElement(el, matches[1]); } // recursively walk any iFrames if (el.tagName == 'IFRAME') { try { var rect = GetElementViewportRect(el); if (rect) { var tm = RUMSpeedIndex(el.contentWindow); if (tm) { rects.push({'tm': tm, 'area': rect.area, 'rect': rect}); } } } catch(e) { } } } }
javascript
{ "resource": "" }
q37380
Context
train
function Context(hook, opts) { var prop; this.hook = hook; //create new object, to avoid affecting input opts in other places //For example context.opts.plugin = Object is done, then it affects by reference this.opts = {}; for (prop in opts) { if (opts.hasOwnProperty(prop)) { this.opts[prop] = opts[prop]; } } this.cmdLine = process.argv.join(' '); this.cordova = require('../cordova/cordova'); }
javascript
{ "resource": "" }
q37381
grow
train
function grow(area, min, max) { if( typeof min !== 'undefined' ) { min = parseInt( min ); if( isNaN( min ) ) min = 2; } if( typeof max !== 'undefined' ) { max = parseInt( max ); if( isNaN( max ) ) max = 8; } if( max < min ) max = min; var text = area.value; var lines = 1; var index = -1; for(;;) { index = text.indexOf( "\n", index + 1 ); if( index === -1 ) break; lines++; } index = Math.max( min, Math.min( max, index ) ); $.att( area, {rows: lines} ); }
javascript
{ "resource": "" }
q37382
train
function(field){ var req = this.req; field = field.toLowerCase(); switch (field) { case 'referer': case 'referrer': return req.headers.referrer || req.headers.referer || ''; default: return req.headers[field] || ''; } }
javascript
{ "resource": "" }
q37383
logToConsole
train
function logToConsole(tags, message) { if (enabled) { if (arguments.length < 2) { message = tags; tags = []; } if (!util.isArray(tags)) tags = []; var text = new Date().getTime() + ', '; if (tags.length > 0) { text = text + tags[0] + ', '; } text = text + message; console.log(text); } }
javascript
{ "resource": "" }
q37384
parseTags
train
function parseTags(tags) { if (tags.length > 0 && util.isArray(tags[0])) { tags = tags[0]; } return tags; }
javascript
{ "resource": "" }
q37385
Logger
train
function Logger(tags) { tags = parseTags(Array.prototype.slice.call(arguments)); if (!(this instanceof Logger)) { return new Logger(tags); } this.tags = tags; }
javascript
{ "resource": "" }
q37386
rinse
train
function rinse (pageobj, finalarray, maps) { // Map where data will be inserted var map = maps.pagemap(); // Render data in temp object // var ruffian = plates.bind(partials[pageobj.mastertemplate], pageobj, map); var ruffian = partials[pageobj.mastertemplate]; // Render plates' simple case scenario // Iterate over Array of Strings if (pageobj.pagesingleset && finalarray) { insertSingleFragment(); } if (pageobj.pagemultiset && finalarray) { pageobj.pagemultiset.forEach(insertMultiFragment); } // This filters and renders collections of data from the array of objects function insertMultiFragment (collection, index, array) { // Only get the objects with the correct collection value var filtered = finalarray.filter(function (element) { return element.collection === collection; }); // Map data with corresponding partials var map = maps.multimap(collection) , obj = {fragment : plates.bind(partials[collection], filtered, maps.collections())}; ruffian = plates.bind(ruffian, obj, map); } // This filters and renders objects which do not belong to a collection function insertSingleFragment () { for (var i = 0; i < finalarray.length; i++) { // Check whether the object belongs to a collection or not if (finalarray[i].collection === 'none') { var singlepartial = finalarray[i].partial , singledest = finalarray[i].destination , map = maps.singlemap(singledest) , obj = { 'fragment':plates.bind(partials[singlepartial], finalarray[i],maps.fragments())}; ruffian = plates.bind(ruffian, obj, map); } } } ruffian = plates.bind(ruffian, pageobj, map); // ruffian = plates.bind(ruffian, pageobj); return ruffian; }
javascript
{ "resource": "" }
q37387
insertMultiFragment
train
function insertMultiFragment (collection, index, array) { // Only get the objects with the correct collection value var filtered = finalarray.filter(function (element) { return element.collection === collection; }); // Map data with corresponding partials var map = maps.multimap(collection) , obj = {fragment : plates.bind(partials[collection], filtered, maps.collections())}; ruffian = plates.bind(ruffian, obj, map); }
javascript
{ "resource": "" }
q37388
insertSingleFragment
train
function insertSingleFragment () { for (var i = 0; i < finalarray.length; i++) { // Check whether the object belongs to a collection or not if (finalarray[i].collection === 'none') { var singlepartial = finalarray[i].partial , singledest = finalarray[i].destination , map = maps.singlemap(singledest) , obj = { 'fragment':plates.bind(partials[singlepartial], finalarray[i],maps.fragments())}; ruffian = plates.bind(ruffian, obj, map); } } }
javascript
{ "resource": "" }
q37389
readPartials
train
function readPartials(userDir, cwd) { if (cwd) { userDir = path.join(cwd, userDir); } // Use working directory of process if not specified else { userDir = path.join(path.dirname(process.argv[1]), userDir); } partials = {}; var filenames = fs.readdirSync(userDir); for (var i = 0; i < filenames.length; i++) { partials[filenames[i].slice(0, -5)] = fs.readFileSync( path.join(userDir, filenames[i]), 'utf8' ); } return partials; }
javascript
{ "resource": "" }
q37390
compile
train
function compile(node) { switch (node.type) { case 'field': var obj = {}; obj[node.name] = node.value; return obj; case 'op': var obj = {}; var op = '$' + node.op; obj[op] = [ compile(node.left), compile(node.right) ]; return obj; } }
javascript
{ "resource": "" }
q37391
remove
train
function remove(el, opts) { var count; var full = (el == window); var $el = $(el); var data = $el.data('blockUI.history'); var to = $el.data('blockUI.timeout'); if (to) { clearTimeout(to); $el.removeData('blockUI.timeout'); } opts = $.extend({}, $.blockUI.defaults, opts || {}); bind(0, el, opts); // unbind events if (opts.onUnblock === null) { opts.onUnblock = $el.data('blockUI.onUnblock'); $el.removeData('blockUI.onUnblock'); } var els; if (full) // crazy selector to handle odd field errors in ie6/7 els = $('body').children().filter('.blockUI').add('body > .blockUI'); else els = $el.find('>.blockUI'); // fix cursor issue if ( opts.cursorReset ) { if ( els.length > 1 ) els[1].style.cursor = opts.cursorReset; if ( els.length > 2 ) els[2].style.cursor = opts.cursorReset; } if (full) pageBlock = pageBlockEls = null; if (opts.fadeOut) { count = els.length; els.stop().fadeOut(opts.fadeOut, function() { if ( --count === 0) reset(els,data,opts,el); }); } else reset(els, data, opts, el); }
javascript
{ "resource": "" }
q37392
reset
train
function reset(els,data,opts,el) { var $el = $(el); if ( $el.data('blockUI.isBlocked') ) return; els.each(function(i,o) { // remove via DOM calls so we don't lose event handlers if (this.parentNode) this.parentNode.removeChild(this); }); if (data && data.el) { data.el.style.display = data.display; data.el.style.position = data.position; data.el.style.cursor = 'default'; // #59 if (data.parent) data.parent.appendChild(data.el); $el.removeData('blockUI.history'); } if ($el.data('blockUI.static')) { $el.css('position', 'static'); // #22 } if (typeof opts.onUnblock == 'function') opts.onUnblock(el,opts); // fix issue in Safari 6 where block artifacts remain until reflow var body = $(document.body), w = body.width(), cssW = body[0].style.width; body.width(w-1).width(w); body[0].style.width = cssW; }
javascript
{ "resource": "" }
q37393
watchFile
train
function watchFile( file ) { // make sure file is at least something if ( !file || '' === file ) { return } // make sure it's a string file = file.toString() if ( watchers.hasOwnProperty( file ) ) { return // already exists } // watch it watchers[ file ] = chokidar.watch( file, { ignored: /[\/\\]\./, persistent: true } ) var that = this // setup event listeners watchers[ file ] // listener for when the file has been removed .on( 'unlink', function ( path ) { that.opts.storageMethod.remove( path, function ( err ) { if ( err ) { if ( that.opts.logging ) { console.log( err ) } return } // success } ) } ) // listener for when the file has been changed .on( 'change', function ( path ) { // add to main file processing queue mainQueue.add( function ( mainDone ) { // attempt to read the file fs.readFile( path, function ( err, fileContents ) { // notify nbqueue that the async function has finished, // regardless of success mainDone() // check for errors if ( err ) { // see if LocalJson instance logging is enabled if ( that.opts.logging ) { console.log( err ) } return } var parsed = LocalJson.TryParse.call( that, JSON.parse, fileContents ) // cache new json that.opts.storageMethod.set( path, parsed, function ( err ) { if ( err ) { if ( that.opts.logging ) { console.log( err ) } return } // success } ) } ) } ) } ) }
javascript
{ "resource": "" }
q37394
NameIt
train
function NameIt(input) { var res = { _: [] , } , foos = Object.keys(NameIt) , i = 0 ; for (; i < foos.length; ++i) { res._.push(res[foos[i]] = NameIt[foos[i]](input)); } return res; }
javascript
{ "resource": "" }
q37395
mergeIfNeed
train
function mergeIfNeed(rtarget, o) { for (var key in o) { if (!rtarget[key]) { rtarget[key] = o[key]; } } return rtarget; }
javascript
{ "resource": "" }
q37396
setHandlers
train
function setHandlers(enableException, enableUnhandled) { if(enableException === true) { process.on('uncaughtException', UncaughtExceptionHandler); } if(enableUnhandled === true) { process.on('unhandledRejection', unhandledRejectionHandler); } }
javascript
{ "resource": "" }
q37397
UncaughtExceptionHandler
train
function UncaughtExceptionHandler(error) { // Call module.exports.crit here so that we can intercept the call in the tests module.exports.crit(`Unhandled exception: ${error.message}`); module.exports.crit(error.stack.toString()); process.exit(1); }
javascript
{ "resource": "" }
q37398
unhandledRejectionHandler
train
function unhandledRejectionHandler(error) { let reasonString = error.message || error.msg || JSON.stringify(error); module.exports.crit(`Unhandled Promise Rejection - reason: [${reasonString}]`); module.exports.crit(error.stack.toString()); }
javascript
{ "resource": "" }
q37399
StoreError
train
function StoreError(type, message) { this.name = StoreError.name; Error.call(this); type = type || ERR; message = type + ' ' + (message || 'unknown internal error'); if(arguments.length > 2) { var args = [message].concat([].slice.call(arguments, 2)); message = util.format.apply(util, args); } this.message = message; }
javascript
{ "resource": "" }