_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q9300
interpolatedOptions
train
function interpolatedOptions(options, context, source, hierarchy = '') { Object.keys(options).forEach((key) => { if (typeof options[key] === 'object') { interpolatedOptions(options[key], context, source, `${hierarchy}.${key}`); } else if (typeof options[key] === 'string' && shouldPatchProperty(`${hierarchy}.${key}`)) { options[key] = utils.interpolateName(context, options[key], { content: source }); } }); return options; }
javascript
{ "resource": "" }
q9301
Executable
train
function Executable(log, command) { /** @type {string} */ this.command = command /** @type {Array.<function(Error, Buffer, Buffer)>} */ this.callbacks = [] /** @type {Arguments} */ this.results = null var startTime = Date.now() child_process.exec(this.command, function() { var timeDiff = `${Date.now() - startTime}` if (timeDiff.length < 3) timeDiff = ` ${timeDiff}`.slice(-3) log.debug(`Exec | ${timeDiff}ms | ${this.command}`) this.results = arguments for (var i = 0; i < this.callbacks.length; i++) { var callback = this.callbacks[i] callback.apply(null, arguments) } }.bind(this)) }
javascript
{ "resource": "" }
q9302
execute
train
function execute(log, command, opt_callback) { if (!registry[command]) { registry[command] = new Executable(log, command) } var executable = registry[command] if (opt_callback) executable.addCallback(opt_callback) }
javascript
{ "resource": "" }
q9303
deserializeNavState
train
function deserializeNavState() { var navID = $('.navigation .nav-accordion-menu').data('nav-id'); if (sessionStorage) { var checkboxMap = sessionStorage.getItem(navID + '-accordion-state'); // If there is no data in session storage then create an empty map. if (checkboxMap == null) { checkboxMap = '{}'; } checkboxMap = JSON.parse(checkboxMap); $('.navigation .nav-accordion-menu').find('input[type="checkbox"]').each(function() { var checkboxValue = checkboxMap[$(this).attr('name')]; if (typeof checkboxValue === 'boolean') { $(this).prop('checked', checkboxValue); } }); } // Set navigation menu visible $('.navigation .nav-accordion-menu').removeClass('hidden'); // Set navigation menu scroll bar from session state. if (sessionStorage) { var navScrollTop = sessionStorage.getItem(navID + '-scrolltop'); if (typeof navScrollTop === 'string') { $('.navigation').prop('scrollTop', navScrollTop); } } }
javascript
{ "resource": "" }
q9304
hideNavContextMenu
train
function hideNavContextMenu(event) { var contextMenuButton = $('#context-menu'); var popupmenu = $('#contextpopup .mdl-menu__container'); // If an event is defined then make sure it isn't targeting the context menu. if (event) { // Picked element is not the menu if (!$(event.target).parents('#contextpopup').length > 0) { // Hide menu if currently visible if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); } } } else // No event defined so always close context menu and remove node highlighting. { // Hide menu if currently visible if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); } } }
javascript
{ "resource": "" }
q9305
onNavContextClick
train
function onNavContextClick(event) { // Hides any existing nav context menu. hideNavContextMenu(event); var target = $(this); var packageLink = target.data('package-link'); var packageType = target.data('package-type') || '...'; // Create proper name for package type. switch (packageType) { case 'npm': packageType = 'NPM'; break; } var packageVersion = target.data('package-version'); var scmLink = target.data('scm-link'); var scmType = target.data('scm-type') || '...'; // Create proper name for SCM type. switch (scmType) { case 'github': scmType = 'Github'; break; } var popupmenu = $('#contextpopup .mdl-menu__container'); // Populate data for the context menu. popupmenu.find('li').each(function(index) { var liTarget = $(this); switch (index) { case 0: if (scmLink) { liTarget.text('Open on ' + scmType); liTarget.data('link', scmLink); liTarget.removeClass('hidden'); // Add divider if there are additional non-hidden items if (packageLink || packageVersion) { liTarget.addClass('mdl-menu__item--full-bleed-divider'); } else { liTarget.removeClass('mdl-menu__item--full-bleed-divider'); } } else { liTarget.addClass('hidden'); } break; case 1: if (packageLink) { liTarget.text('Open on ' + packageType); liTarget.data('link', packageLink); liTarget.removeClass('hidden'); // Add divider if there are additional non-hidden items if (packageVersion) { liTarget.addClass('mdl-menu__item--full-bleed-divider'); } else { liTarget.removeClass('mdl-menu__item--full-bleed-divider'); } } else { liTarget.addClass('hidden'); } break; case 2: if (packageVersion) { liTarget.text('Version: ' + packageVersion); liTarget.removeClass('hidden'); } else { liTarget.addClass('hidden'); } break; } }); // Wrapping in a 100ms timeout allows MDL to draw animation when showing a context menu after one has been hidden. setTimeout(function() { // For MDL a programmatic click of the hidden context menu. var contextMenuButton = $("#context-menu"); contextMenuButton.click(); // Necessary to defer reposition of the context menu. setTimeout(function() { popupmenu.parent().css({ position: 'relative' }); popupmenu.css({ left: event.pageX, top: event.pageY - $('header').outerHeight(), position:'absolute' }); }, 0); }, 100); }
javascript
{ "resource": "" }
q9306
serializeNavState
train
function serializeNavState() { var checkboxMap = {}; $('.navigation .nav-accordion-menu').find('input[type="checkbox"]').each(function() { checkboxMap[$(this).attr('name')] = $(this).is(':checked'); }); var navID = $('.navigation .nav-accordion-menu').data('nav-id'); if (sessionStorage) { sessionStorage.setItem(navID + '-accordion-state', JSON.stringify(checkboxMap))} }
javascript
{ "resource": "" }
q9307
compile
train
function compile(gl, vertSource, fragSource, attribs, verbose) { var log = ""; var vert = loadShader(gl, gl.VERTEX_SHADER, vertSource, verbose); var frag = loadShader(gl, gl.FRAGMENT_SHADER, fragSource, verbose); var vertShader = vert.shader; var fragShader = frag.shader; log += vert.log + "\n" + frag.log; var program = gl.createProgram(); gl.attachShader(program, vertShader); gl.attachShader(program, fragShader); //TODO: Chrome seems a bit buggy with attribute bindings... if (attribs) { for (var key in attribs) { if (attribs.hasOwnProperty(key)) { gl.bindAttribLocation(program, Math.floor(attribs[key]), key); } } } gl.linkProgram(program); log += gl.getProgramInfoLog(program) || ""; if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { if (verbose) { console.error("Shader error:\n"+log); console.error("Problematic shaders:\nVERTEX_SHADER:\n"+addLineNumbers(vertSource) +"\n\nFRAGMENT_SHADER:\n"+addLineNumbers(fragSource)); } //delete before throwing error gl.detachShader(program, vertShader); gl.detachShader(program, fragShader); gl.deleteShader(vertShader); gl.deleteShader(fragShader); throw new Error("Error linking the shader program:\n" + log); } return { program: program, vertex: vertShader, fragment: fragShader, log: log.trim() }; }
javascript
{ "resource": "" }
q9308
encrypt
train
function encrypt(kms, params, logger) { logger = logger || console; const startMs = Date.now(); return kms.encrypt(params).promise().then( result => { if (logger.traceEnabled) logger.trace(`KMS encrypt success took ${Date.now() - startMs} ms`); return result; }, err => { logger.error(`KMS encrypt failure took ${Date.now() - startMs} ms`, err); throw err; } ); }
javascript
{ "resource": "" }
q9309
encryptKey
train
function encryptKey(kms, keyId, plaintext, logger) { const params = {KeyId: keyId, Plaintext: plaintext}; return encrypt(kms, params, logger).then(result => result.CiphertextBlob && result.CiphertextBlob.toString('base64')); }
javascript
{ "resource": "" }
q9310
decryptKey
train
function decryptKey(kms, ciphertextBase64, logger) { const params = {CiphertextBlob: new Buffer(ciphertextBase64, 'base64')}; return decrypt(kms, params, logger).then(result => result.Plaintext && result.Plaintext.toString('utf8')); }
javascript
{ "resource": "" }
q9311
genericLog
train
function genericLog(logger, moduletag, logLevel='info'){ const isDebug = logLevel==='debug' const level = isDebug ? 'info' : logLevel const levelLogger = logger[level] const active = isDebug ? enabled(moduletag) : true /** * tagged Logger * @function taggedLog * @param {...string} tags Optional message tags */ function taggedLog(...tags) { const tag = normalizeDefaults(tags) /** * message Logger * @function messageLog * @template T * @param {...T} messages message * @returns {T} */ function messageLog(...messages) { if (active) { const protectedMessage = messageArrayProtect(messages) levelLogger(tag, ...protectedMessage) } return messages[0] } return messageLog } /** * Array logge Prinst every value on separated line * @function mapLog * @param {...string} tags Optional message tags */ function mapLog(...tags) { /** * Array logge Prinst every value on separated line * @function printArray * @param {Array} message Printed list * @returns {Array} */ function printArray(message) { if (active) { arrayCheck(message) const tag = normalizeDefaults(tags) //count length + 2. Also handles edge case with objects without 'length' field const spaceLn = P( length, defaultTo(0), add(2) ) const ln = sum( map( spaceLn, tags ) ) const spaces = new Array(ln) .fill(' ') .join('') const getFormatted = num => chalk.green(`<${num}>`) levelLogger( tag, getFormatted(0), head( message ) ) const printTail = (e, i) => levelLogger(spaces, getFormatted(i+1), e) P( tail, indexedMap(printTail) )(message) } return message } return printArray } taggedLog.map = mapLog return taggedLog }
javascript
{ "resource": "" }
q9312
mapLog
train
function mapLog(...tags) { /** * Array logge Prinst every value on separated line * @function printArray * @param {Array} message Printed list * @returns {Array} */ function printArray(message) { if (active) { arrayCheck(message) const tag = normalizeDefaults(tags) //count length + 2. Also handles edge case with objects without 'length' field const spaceLn = P( length, defaultTo(0), add(2) ) const ln = sum( map( spaceLn, tags ) ) const spaces = new Array(ln) .fill(' ') .join('') const getFormatted = num => chalk.green(`<${num}>`) levelLogger( tag, getFormatted(0), head( message ) ) const printTail = (e, i) => levelLogger(spaces, getFormatted(i+1), e) P( tail, indexedMap(printTail) )(message) } return message } return printArray }
javascript
{ "resource": "" }
q9313
Logger
train
function Logger(moduletag) { const trimmedModule = trim(moduletag) winston.loggers.add(trimmedModule, { console: { colorize: true, label : trimmedModule } }) const logger = winston.loggers.get(trimmedModule) const defs = genericLog(logger, trimmedModule) defs.warn = genericLog(logger, trimmedModule, 'warn') defs.error = genericLog(logger, trimmedModule, 'error') defs.debug = genericLog(logger, trimmedModule, 'debug') defs.info = genericLog(logger, trimmedModule, 'info') return defs }
javascript
{ "resource": "" }
q9314
getInvokedFunctionArnFunctionName
train
function getInvokedFunctionArnFunctionName(awsContext) { const invokedFunctionArn = awsContext && awsContext.invokedFunctionArn; const resources = getArnResources(invokedFunctionArn); return resources.resource; }
javascript
{ "resource": "" }
q9315
train
function(search, type, limit, fields) { if (!search) return Promise.reject(new Error('wotblitz.account.list: search is required')); return request({ hostname: hosts.wotb, path: '/wotb/account/list/' }, { fields: fields ? fields.toString() : '', limit: limit, search: search, type: type }); }
javascript
{ "resource": "" }
q9316
train
function(access_token, expires_at) { if (!access_token) return Promise.reject(new Error('wotblitz.auth.prolongate: access_token is required')); return request({ hostname: hosts.wot, path: '/wot/auth/prolongate/' }, { access_token: access_token, expires_at: expires_at || 14 * 24 * 60 * 60 // 14 days in seconds }); }
javascript
{ "resource": "" }
q9317
train
function(access_token, message_id, filters, fields) { if (!access_token) return Promise.reject(new Error('wotblitz.clanmessages.messages: access_token is required')); return request({ hostname: hosts.wotb, path: '/wotb/clanmessages/messages/' }, Object.assign({ access_token: access_token, message_id: message_id, fields: fields ? fields.toString() : '' }, filters, { order_by: filters && filters.order_by ? filters.order_by.toString() : '' })); }
javascript
{ "resource": "" }
q9318
train
function(access_token, title, text, type, importance, expires_at) { if (!expires_at) return Promise.reject(new Error('wotblitz.clanmessages.create: all arguments are required')); return request({ hostname: hosts.wotb, path: '/wotb/clanmessages/create/' }, { access_token: access_token, expires_at: expires_at, importance: importance, text: text, title: title, type: type }); }
javascript
{ "resource": "" }
q9319
train
function(access_token, message_id) { if (!message_id) return Promise.reject(new Error('wotblitz.clanmessages.delete: all arguments are required')); return request({ hostname: hosts.wotb, path: '/wotb/clanmessages/delete/' }, { access_token: access_token, message_id: message_id }); }
javascript
{ "resource": "" }
q9320
train
function(access_token, message_id, action) { if (!action) return Promise.reject(new Error('wotblitz.clanmessages.like: all arguments are required')); return request({ hostname: hosts.wotb, path: '/wotb/clanmessages/like/' }, { access_token, action: action, message_id: message_id }); }
javascript
{ "resource": "" }
q9321
train
function(access_token, message_id, fields) { if (!access_token) return Promise.reject(new Error('wotblitz.clanmessages.likes: access_token is required')); if (!message_id) return Promise.reject(new Error('wotblitz.clanmessages.likes: message_id is required')); return request({ hostname: hosts.wotb, path: '/wotb/clanmessages/likes/' }, { access_token: access_token, message_id: message_id, fields: fields ? fields.toString() : '' }); }
javascript
{ "resource": "" }
q9322
train
function(search, page_no, limit, fields) { return request({ hostname: hosts.wotb, path: '/wotb/clans/list/' }, { search: search, page_no: page_no, limit: limit, fields: fields ? fields.toString() : '' }); }
javascript
{ "resource": "" }
q9323
train
function(fields) { return request({ hostname: hosts.wotb, path: '/wotb/clans/glossary/' }, { fields: fields ? fields.toString() : '' }); }
javascript
{ "resource": "" }
q9324
train
function(tank_id, nation, fields) { return request({ hostname: hosts.wotb, path: '/wotb/encyclopedia/vehicles/' }, { tank_id: tank_id ? tank_id.toString() : '', nation: nation ? nation.toString() : '', fields: fields ? fields.toString() : '' }); }
javascript
{ "resource": "" }
q9325
train
function(tank_id, profile_id, modules, fields) { if (!tank_id) return Promise.reject(new Error('wotblitz.encyclopedia.vehicleprofile: tank_id is required')); return request({ hostname: hosts.wotb, path: '/wotb/encyclopedia/vehicleprofile/' }, Object.assign({ tank_id: tank_id, fields: fields ? fields.toString() : '' }, modules || { profile_id: profile_id })); }
javascript
{ "resource": "" }
q9326
train
function(module_id, fields) { return request({ hostname: hosts.wotb, path: '/wotb/encyclopedia/modules/' }, { module_id: module_id ? module_id.toString() : '', fields: fields ? fields.toString() : '' }); }
javascript
{ "resource": "" }
q9327
train
function(tank_id, provision_id, type, fields) { return request({ hostname: hosts.wotb, path: '/wotb/encyclopedia/provisions/' }, { tank_id: tank_id ? tank_id.toString() : '', provision_id: provision_id ? provision_id.toString() : '', type: type, fields: fields ? fields.toString() : '' }); }
javascript
{ "resource": "" }
q9328
train
function(skill_id, vehicle_type, fields) { return request({ hostname: hosts.wotb, path: '/wotb/encyclopedia/crewskills/' }, { skill_id: skill_id ? skill_id.toString() : '', vehicle_type: vehicle_type ? vehicle_type.toString() : '', fields: fields ? fields.toString() : '' }); }
javascript
{ "resource": "" }
q9329
train
function(options, fields) { options = Object.assign({ search: null, status: null, page_no: null, limit: null }, options, { fields: fields ? fields.toString() : '' }); if (Array.isArray(options.status)) options.status = options.status.toString(); return request({ hostname: hosts.wotb, path: '/wotb/tournaments/list/' }, options); }
javascript
{ "resource": "" }
q9330
_deepDefaults
train
function _deepDefaults(dest, src) { if(_.isUndefined(dest) || _.isNull(dest) || !_.isPlainObject(dest)) { return dest; } _.each(src, function(v, k) { if(_.isUndefined(dest[k])) { dest[k] = v; } else if(_.isPlainObject(v)) { _deepDefaults(dest[k], v); } }); return dest; }
javascript
{ "resource": "" }
q9331
genStorageKey
train
function genStorageKey (ns, key) { return (ns === '') ? ns.concat(key) : ns.concat('.').concat(key); }
javascript
{ "resource": "" }
q9332
LocalStorage
train
function LocalStorage (params) { events.EventEmitter.call(this); if (!params || typeof params === 'string') { params = { ns: params || '' }; } this.ns = params.ns || ''; if (typeof this.ns !== 'string') { throw new Error('Namespace must be a string.'); } this.preSave = params.preSave || defProcessor; this.postLoad = params.postLoad || defProcessor; if (this.preSave && typeof this.preSave !== 'function') { throw new Error('preSave option must be a function'); } if (this.postLoad && typeof this.postLoad !== 'function') { throw new Error('postLoad option must be a function'); } this.EVENTS = EVENTS; }
javascript
{ "resource": "" }
q9333
train
function (invoiceitem, cb) { Invoiceitem.findOrCreate(invoiceitem.id, invoiceitem) .exec(function (err, foundInvoiceitem){ if (err) return cb(err); if (foundInvoiceitem.lastStripeEvent > invoiceitem.lastStripeEvent) return cb(null, foundInvoiceitem); if (foundInvoiceitem.lastStripeEvent == invoiceitem.lastStripeEvent) return Invoiceitem.afterStripeInvoiceitemUpdated(foundInvoiceitem, function(err, invoiceitem){ return cb(err, invoiceitem)}); Invoiceitem.update(foundInvoiceitem.id, invoiceitem) .exec(function(err, updatedInvoiceitem){ if (err) return cb(err); if (!updatedInvoiceitem) return cb(null,null); Invoiceitem.afterStripeInvoiceitemUpdated(updatedInvoiceitem[0], function(err, invoiceitem){ cb(err, invoiceitem); }); }); }); }
javascript
{ "resource": "" }
q9334
train
function (invoiceitem, cb) { Invoiceitem.destroy(invoiceitem.id) .exec(function (err, destroyedInvoiceitems){ if (err) return cb(err); if (!destroyedInvoiceitems) return cb(null, null); Invoiceitem.afterStripeInvoiceitemDeleted(destroyedInvoiceitems[0], function(err, invoiceitem){ cb(err, invoiceitem); }); }); }
javascript
{ "resource": "" }
q9335
validateTableConfig
train
function validateTableConfig(obj) { /** If configuration has missing or invalid 'tableName' configuration, throw error */ if ( typeof obj.tableName !== `string` || !obj.tableName.match(/^[a-z_]+$/) ) throw new Error(`ezobjects.validateTableConfig(): Configuration has missing or invalid 'tableName', must be string containing characters 'a-z_'.`); validateClassConfig(obj); }
javascript
{ "resource": "" }
q9336
ev_canvas
train
function ev_canvas(ev) { if(!root.is('.blocked')) { if(ev.layerX || ev.layerX == 0) { // Firefox ev._x = ev.layerX; ev._y = ev.layerY; } else if(ev.offsetX || ev.offsetX == 0) { // Opera ev._x = ev.offsetX; ev._y = ev.offsetY; } // Call the event handler of the tool. var func = tool[ev.type]; if(func) { func(ev); } } }
javascript
{ "resource": "" }
q9337
train
function (coupon, cb) { Coupon.findOrCreate(coupon.id, coupon) .exec(function (err, foundCoupon){ if (err) return cb(err); if (foundCoupon.lastStripeEvent > coupon.lastStripeEvent) return cb(null, foundCoupon); if (foundCoupon.lastStripeEvent == coupon.lastStripeEvent) return Coupon.afterStripeCouponCreated(foundCoupon, function(err, coupon){ return cb(err, coupon)}); Coupon.update(foundCoupon.id, coupon) .exec(function(err, updatedCoupons){ if (err) return cb(err); Coupon.afterStripeCouponCreated(updatedCoupons[0], function(err, coupon){ cb(err, coupon); }); }); }); }
javascript
{ "resource": "" }
q9338
train
function (coupon, cb) { Coupon.destroy(coupon.id) .exec(function (err, destroyedCoupons){ if (err) return cb(err); if(!destroyedCoupons) return cb(null, null); Coupon.afterStripeCouponDeleted(destroyedCoupons[0], function(err, coupon){ cb(null, coupon); }); }); }
javascript
{ "resource": "" }
q9339
train
function (account, cb) { Stripeaccount.findOrCreate(account.id, account) .exec(function (err, foundAccount){ if (err) return cb(err); Stripeaccount.update(foundAccount.id, account) .exec(function(err, updatedAccounts){ if (err) return cb(err); cb(null, updatedAccounts[0]); }); }); }
javascript
{ "resource": "" }
q9340
checkboxValues
train
function checkboxValues(selection) { return selection.select('.body') .selectAll('input:checked').data().map(d => d.id); }
javascript
{ "resource": "" }
q9341
addDepsToRequiredTargets
train
function addDepsToRequiredTargets(target, parents){ if (parents.have(target)){ callback(new Error("Circular dependencies detected")); return; } requiredTargets.add(target); parents.add(target); for(var deps in makeInst.targets[target].dependsOn.hash){ addDepsToRequiredTargets(deps, parents.clone()); } }
javascript
{ "resource": "" }
q9342
MPU
train
function MPU (ops) { File.call(this, ops); this._parts = {}; this._bufferParts = []; this._data.UploadId = makeUploadId(); }
javascript
{ "resource": "" }
q9343
find
train
function find(model) { var _this = this; var forceFetch = arguments[1] === undefined ? false : arguments[1]; var record = this.records.get(model); if (record && !forceFetch) { return Promise.resolve(record); } else { model = this._ensureModel(model); return Promise.resolve(model.fetch()).then(function () { return _this.insert(model); }); } }
javascript
{ "resource": "" }
q9344
findAll
train
function findAll() { var _this = this; var options = arguments[0] === undefined ? {} : arguments[0]; var forceFetch = arguments[1] === undefined ? false : arguments[1]; if (this._hasSynced && !forceFetch) { return Promise.resolve(this.records); } else { return Promise.resolve(this.records.fetch(options)).then(function () { return _this.records; }); } }
javascript
{ "resource": "" }
q9345
save
train
function save(model) { var _this = this; var record = this.records.get(model); model = record || this._ensureModel(model); return Promise.resolve(model.save()).then(function () { if (!record) { _this.insert(model); } return model; }); }
javascript
{ "resource": "" }
q9346
insert
train
function insert(model) { model = this.records.add(model, { merge: true }); return Promise.resolve(model); }
javascript
{ "resource": "" }
q9347
_ensureModel
train
function _ensureModel(model) { if (model instanceof this.model) { return model; } else if (typeof model === "object") { return new this.model(model); } else { return new this.model({ id: model }); } }
javascript
{ "resource": "" }
q9348
train
function(input, callback) { // Handle non-function `input`. if (!_.isFunction(input)) { callback(null, input) return } // Handle asynchronous `input` function. if (input.length) { input(callback) return } // Handle synchronous `input` function. var results = null var err = null try { results = input() } catch (e) { err = e } callback(err, results) }
javascript
{ "resource": "" }
q9349
sassVars
train
function sassVars (filePath) { const declarations = collectDeclarations(filePath); let variables = {}; if (!declarations.length) { message('Warning: Zero declarations found'); return; } declarations.forEach(function (declaration) { const parsedDeclaration = parseDeclaration(declaration); const varName = parsedDeclaration.key; let varValue = parsedDeclaration.value; const valueType = getValueType(varValue); /* * $key: $value; */ if (valueType === 'var') { const localVarName = varValue; varValue = getVarValue(localVarName, variables); if (!varValue) { message(`Warning: Null value for variable ${localVarName}`); } } /* * $key: ($value-1 + $value-2) * $value-3 ... ; */ if (valueType === 'expression') { // todo } /* * $key: value; */ variables[varName] = varValue; }); return variables; }
javascript
{ "resource": "" }
q9350
getOrderedPlayers
train
function getOrderedPlayers (tnmt) { var res = [] for (var i = 0; i < tnmt.players.length; i++) { res[tnmt.players[i].positionInSWT] = tnmt.players[i]['2020'] } return res }
javascript
{ "resource": "" }
q9351
getOrderedTeams
train
function getOrderedTeams (tnmt) { var res = [] for (var i = 0; i < tnmt.teams.length; i++) { res[tnmt.teams[i].positionInSWT] = tnmt.teams[i]['1018'] } return res }
javascript
{ "resource": "" }
q9352
playerPairingFilter
train
function playerPairingFilter (tnmt) { return function (pairing) { // board number too high? if (tnmt.general[35] && pairing[4006] > tnmt.general[34]) { return false } // no color set? if (pairing[4000] === '4000-0') { return false } return true } }
javascript
{ "resource": "" }
q9353
NWTIO
train
function NWTIO(args) { this.req = new XMLHttpRequest(); this.config = {}; this.url = args[0]; // Data to send as this.ioData = ''; var chainableSetters = ['success', 'failure', 'serialize'], i, setter, mythis = this, // Returns the setter function getSetter = function (setter) { return function (value) { mythis.config[setter] = value; return this; } }; for (i = 0, setter; setter = chainableSetters[i]; i++) { this[setter] = getSetter(setter); } }
javascript
{ "resource": "" }
q9354
train
function() { var mythis = this; this.req.onload = function() { if (mythis.config.success) { var response = new NWTIOResponse(mythis.req); mythis.config.success(response); } }; this.req.onerror = function() { if (mythis.config.failure) { var response = new NWTIOResponse(mythis.req); mythis.config.failure(response); } }; this.req.send(this.ioData ? this.ioData : null); return this; }
javascript
{ "resource": "" }
q9355
train
function(data, method) { var urlencodedForm = true; if (typeof data == 'string') { this.ioData = data; } else if (typeof data == 'object' && data._node) { if (data.getAttribute('enctype')) { urlencodedForm = false; } this.ioData = new FormData(data._node); } var req = this.req, method = method || 'POST'; req.open(method, this.url); //Send the proper header information along with the request // Send as form encoded if we do not have a file field if (urlencodedForm) { req.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); } return this._run(); }
javascript
{ "resource": "" }
q9356
train
function(data) { // Strip out the old query string and append the new one if (data) { this.url = this.url.split('?', 1)[0] + '?' + data; } this.req.open('GET', this.url); return this._run(); }
javascript
{ "resource": "" }
q9357
train
function(fn) { asyncjs.each(modelNames, function(name, _fn) { // get model definition var modelDefinition = modelDefinitions[name]; modelDefinition.__name = name; // get connection info var connectionInfo = lib.findConnection(mycro, name); if (!connectionInfo) { mycro.log('silly', '[models] Unable to find explicit adapter for model (' + name + ')'); if (!defaultConnection ) { return _fn('Unable to find adapter for model (' + name + ')'); } else { connectionInfo = defaultConnection; } } // validate handler exists var adapter = connectionInfo.adapter; if (!adapter.registerModel || !_.isFunction(adapter.registerModel) || adapter.registerModel.length < 3) { return _fn('Invalid adapter api: adapters should define a `registerModel` method that accepts a connection object, model definition object, and a callback'); } // hand off to adapter var registerModelCallback = function(err, model) { if (err) { return _fn(err); } if (!model) { return _fn('No model (' + name + ') returned from `adapter.registerModel`'); } mycro.models[name] = model; _fn(); }; if (adapter.registerModel.length === 3) { return adapter.registerModel(connectionInfo.connection, modelDefinition, registerModelCallback); } else if (adapter.registerModel.length === 4) { return adapter.registerModel(connectionInfo.connection, modelDefinition, name, registerModelCallback); } else { return adapter.registerModel(connectionInfo.connection, modelDefinition, name, mycro, registerModelCallback); } }, fn); }
javascript
{ "resource": "" }
q9358
train
function(err, model) { if (err) { return _fn(err); } if (!model) { return _fn('No model (' + name + ') returned from `adapter.registerModel`'); } mycro.models[name] = model; _fn(); }
javascript
{ "resource": "" }
q9359
train
function(baseURI) { var hash = baseURI.indexOf("#"); if (hash>=0) { baseURI = baseURI.substring(0,hash); } if (options && options.baseURIMap) { baseURI = options.baseURIMap(baseURI); } return baseURI; }
javascript
{ "resource": "" }
q9360
train
function (subscription, cb) { Subscription.findOrCreate(subscription.id, subscription) .exec(function (err, foundSubscription){ if (err) return cb(err); if (foundSubscription.lastStripeEvent > subscription.lastStripeEvent) return cb(null, foundSubscription); if (foundSubscription.lastStripeEvent == subscription.lastStripeEvent) return Subscription.afterStripeCustomerSubscriptionUpdated(foundSubscription, function(err, subscription){ return cb(err, subscription)}); Subscription.update(foundSubscription.id, subscription) .exec(function(err, updatedSubscriptions){ if (err) return cb(err); if(!updatedSubscriptions) return cb(null, null); Subscription.afterStripeCustomerSubscriptionUpdated(updatedSubscriptions[0], function(err, subscription){ cb(err, subscription); }); }); }); }
javascript
{ "resource": "" }
q9361
train
function (subscription, cb) { Subscription.destroy(subscription.id) .exec(function (err, destroyedSubscriptions){ if (err) return cb(err); if (!destroyedSubscriptions) return cb(null, subscription); Subscription.afterStripeCustomerSubscriptionDeleted(destroyedSubscriptions[0], function(err, subscription){ cb(err, subscription); }); }); }
javascript
{ "resource": "" }
q9362
fetchRepoREADME
train
function fetchRepoREADME (repo) { request({ uri: 'https://api.github.com/repos/' + repo + '/readme', headers: _.extend(headers, { // Get raw README content 'Accept': 'application/vnd.github.VERSION.raw' }) }, function (error, response, body) { if (!error && response.statusCode === 200) { lintMarkdown(body, repo); } else { if (response.headers['x-ratelimit-remaining'] === '0') { getAuthToken(); } else { console.log('README for https://github.com/' + repo.blue + ' not found.'.red); return; } } }); }
javascript
{ "resource": "" }
q9363
lintMarkdown
train
function lintMarkdown (body, file) { var codeBlocks = parseMarkdown(body); didLogFileBreak = false; var failedCodeBlocks = _.reject(_.compact(codeBlocks), function (codeBlock) { return validateCodeBlock(codeBlock, file); }); numFilesToParse--; if (failedCodeBlocks.length === 0) { if (program.verbose) { console.log('Markdown passed linting for '.green + file.blue.bold + '\n'); } else if (numFilesToParse === 0) { console.log('All markdown files passed linting'.green); } } else { if (numFailedFiles % 2 === 0) { console.log('Markdown failed linting for '.red + file.yellow); } else { console.log('Markdown failed linting for '.red + file.blue); } numFailedFiles++; console.log(''); } }
javascript
{ "resource": "" }
q9364
logFileBreak
train
function logFileBreak (text) { if (numFailedFiles % 2 === 0) { console.log(text.yellow.inverse); } else { console.log(text.blue.inverse); } }
javascript
{ "resource": "" }
q9365
validateCodeBlock
train
function validateCodeBlock (codeBlock, file) { var lang = codeBlock.lang; var code = codeBlock.code; if (lang === 'json') { try { JSON.parse(code); } catch (e) { console.log(e); console.log(code); return false; } return true; } else if (lang === 'js' || lang === 'javascript') { code = preprocessCode(code); try { esprima.parse(code, { tolerant: true }); } catch (e) { // Get indeces from lineNumber and column var line = e.lineNumber - 1; var column = e.column - 1; // Highlight error in code code = code.split('\n'); code[line] = code[line].slice(0, column).magenta + code[line][column].red + code[line].slice(column + 1).magenta; code = code.join('\n'); if (!didLogFileBreak) { logFileBreak(file); didLogFileBreak = true; } console.log(e); console.log(code); return false; } return true; } }
javascript
{ "resource": "" }
q9366
getAuthToken
train
function getAuthToken () { console.log('You have hit the rate limit for unauthenticated requests, please log in to raise your rate limit:\n'.red); program.prompt('GitHub Username: ', function (user) { console.log('\nAfter entering your password, hit return' + ' twice.\n'.green); var authProcess = spawn('curl', [ '-u', user, '-d', '{"scopes":["repo"],"note":"mdlint"}', '-s', 'https://api.github.com/authorizations' ], { stdio: [process.stdin, 'pipe', process.stderr] }); authProcess.stdout.setEncoding('utf8'); authProcess.stdout.on('data', function (data) { var response = JSON.parse(data); if (response.message) { console.log(response.message.red + '\n'); process.exit(); } else { fs.writeFileSync(tokenFile, response.token); console.log('Authenticated :). Now try your lint again. \n'.green); process.exit(); } }); }); }
javascript
{ "resource": "" }
q9367
preprocessCode
train
function preprocessCode (code) { // Remove starting comments while (code.indexOf('//') === 0) { code = code.slice(code.indexOf('\n')); } // Starts with an object literal if (code.indexOf('{') === 0) { code = 'var json = ' + code; // Starts with an object property } else if (code.indexOf(':') !== -1 && code.indexOf(':') < code.indexOf(' ')) { code = 'var json = {' + code + '}'; } // Starts with an anonymous function if (code.indexOf('function') === 0) { code = 'var func = ' + code; } // Contains ... return code.replace('...', ''); }
javascript
{ "resource": "" }
q9368
processExec
train
function processExec(opts, createOpts, execOpts, callback) { this.execRaw(createOpts, (createErr, exec) => { if( createErr ) { callback(createErr); return } exec.start(execOpts, (execErr, stream) => { if( execErr ) { callback(execErr); return } if( 'live' in opts && opts.live ) { // If the user wants live streams, give them a function to attach to the builtin demuxStream callback(null, (stdout, stderr) => { if( stdout || stderr ) { this.modem.demuxStream(stream, stdout, stderr) } // Allow an .on('end'). return stream }) } else { const results = {} let callbackCalled = false const callbackOnce = err => { if( !callbackCalled ) { callbackCalled = true if( err ) { Object.assign(results, {error: err}) } // Inspect the exec and put that information into the results as well // Allow this to be turned off via option later // Workaround: if the user only has stdin and no stdout, // the process will sometimes not immediately end. let times = 10 const inspectLoop = () => { exec.inspect((inspError, inspect) => { if( inspect.ExitCode !== null ) { if( times !== 10 ) { inspect.tries = 10 - times } Object.assign(results, {inspect}) callback(inspError, results) } else { times-- setTimeout(inspectLoop, 50) } }) } inspectLoop() } } if( execOpts.Detach ) { // Bitbucket the stream's data, so that it can close. stream.on('data', () => {}) } if( opts.stdin ) { // Send the process whatever the user's going for. if( isStream(opts.stdin) ) { opts.stdin.pipe(stream) } else { const sender = new Stream.Readable() sender.push(opts.stdin) sender.push(null) sender.pipe(stream) } } if( opts.stdout || opts.stderr ) { // Set up the battery to merge in its results when it's done. If it had an error, trigger the whole thing returning. const battery = new StreamBattery(['stdout', 'stderr'], (battError, battResults) => { Object.assign(results, battResults) if( battError ) { callbackOnce(battError) } }) // Start the stream demuxing this.modem.demuxStream(stream, ...battery.streams) stream.on('end', () => battery.end()) } // Wait for the exec to end. stream.on('end', callbackOnce) stream.on('close', callbackOnce) stream.on('error', callbackOnce) } }) }) }
javascript
{ "resource": "" }
q9369
train
function() { // Internal reference. var _self = this; // Loop through our hidden element collection. _self.hidden.each( function( i ) { // Cache this element. var $elem = $( this ), _tmp = _self.tmp[ i ]; // Get the stored 'style' value for this element. // If the stored value is undefined. if( _tmp === undefined ) // Remove the style attribute. $elem.removeAttr( 'style' ); else // Otherwise, reset the element style attribute. $elem.attr( 'style', _tmp ); }); // Reset the tmp array. _self.tmp = []; // Reset the hidden elements variable. _self.hidden = null; }
javascript
{ "resource": "" }
q9370
train
function (transfer, cb) { Transfer.findOrCreate(transfer.id, transfer) .exec(function (err, foundTransfer){ if (err) return cb(err); if (foundTransfer.lastStripeEvent > transfer.lastStripeEvent) return cb(null, foundTransfer); if (foundTransfer.lastStripeEvent == transfer.lastStripeEvent) return Transfer.afterStripeTransferCreated(foundTransfer, function(err, transfer){ return cb(err, transfer)}); Transfer.update(foundTransfer.id, transfer) .exec(function(err, updatedTransfers){ if (err) return cb(err); if(!updatedTransfers) return cb(null, null); Transfer.afterStripeTransferCreated(updatedTransfers[0], function(err, transfer){ cb(err, transfer); }); }); }); }
javascript
{ "resource": "" }
q9371
initJSArch
train
async function initJSArch({ CONFIG, EOL, glob, fs, parser, log = noop }) { return jsArch; /** * Compile an run a template * @param {Object} options * Options (destructured) * @param {Object} options.cwd * Current working directory * @param {Object} options.patterns * Patterns to look files for (see node-glob) * @param {Object} options.eol * End of line character (default to the OS one) * @param {Object} options.titleLevel * The base title level of the output makdown document * @param {Object} options.base * The base directory for the ARCHITECTURE.md references * @return {Promise<String>} * Computed architecture notes as a markdown file */ async function jsArch({ cwd, patterns, eol, titleLevel = TITLE_LEVEL, base = BASE, }) { eol = eol || EOL; const files = await _computePatterns({ glob, log }, cwd, patterns); const architectureNotes = _linearize( await Promise.all( files.map(_extractArchitectureNotes.bind(null, { parser, fs, log })), ), ); const content = architectureNotes .sort(compareNotes) .reduce((content, architectureNote) => { let linesLink = '#L' + architectureNote.loc.start.line + '-L' + architectureNote.loc.end.line; if (CONFIG.gitProvider.toLowerCase() === 'bitbucket') { linesLink = '#' + path.basename(architectureNote.filePath) + '-' + architectureNote.loc.start.line + ':' + architectureNote.loc.end.line; } return ( content + eol + eol + titleLevel + architectureNote.num .split('.') .map(() => '#') .join('') + ' ' + architectureNote.title + eol + eol + architectureNote.content.replace( new RegExp( '([\r\n]+)[ \t]{' + architectureNote.loc.start.column + '}', 'g', ), '$1', ) + eol + eol + '[See in context](' + base + '/' + path.relative(cwd, architectureNote.filePath) + linesLink + ')' + eol + eol ); }, ''); if (content) { return ( JSARCH_PREFIX.replace(EOL_REGEXP, eol) + titleLevel + ' Architecture Notes' + eol + eol + content ); } return content; } }
javascript
{ "resource": "" }
q9372
getItem
train
function getItem(tableName, key, opts, desc, context) { try { const params = { TableName: tableName, Key: key }; if (opts) merge(opts, params, mergeOpts); if (context.traceEnabled) context.trace(`Loading ${desc} from ${tableName} using params (${JSON.stringify(params)})`); return context.dynamoDBDocClient.get(params).promise() .then(result => { if (context.traceEnabled) context.trace(`Loaded ${desc} from ${tableName} - result (${JSON.stringify(result)})`); if (result && typeof result === 'object') { return result; } throw new TypeError(`Unexpected result from get ${desc} from ${tableName} - result (${JSON.stringify(result)})`); }) .catch(err => { context.error(`Failed to load ${desc} from ${tableName}`, err); throw err; }); } catch (err) { context.error(`Failed to load ${desc} from ${tableName}`, err); return Promise.reject(err); } }
javascript
{ "resource": "" }
q9373
updateProjectionExpression
train
function updateProjectionExpression(opts, expressions) { if (!expressions || !Array.isArray(expressions) || expressions.length <= 0) return opts; if (!opts) opts = {}; const projectionExpressions = opts.ProjectionExpression ? opts.ProjectionExpression.split(',').filter(isNotBlank).map(trim) : []; expressions.forEach(expression => { if (isNotBlank(expression) && projectionExpressions.indexOf(expression) === -1) { projectionExpressions.push(trim(expression)); } }); const projectionExpression = projectionExpressions.length > 0 ? projectionExpressions.join(',') : undefined; opts.ProjectionExpression = isNotBlank(projectionExpression) ? projectionExpression : undefined; return opts; }
javascript
{ "resource": "" }
q9374
updateExpressionAttributeNames
train
function updateExpressionAttributeNames(opts, expressionAttributeNames) { if (!expressionAttributeNames || typeof expressionAttributeNames !== 'object') return opts; if (!opts) opts = {}; if (!opts.ExpressionAttributeNames) opts.ExpressionAttributeNames = {}; const keys = Object.getOwnPropertyNames(expressionAttributeNames); keys.forEach(key => { opts.ExpressionAttributeNames[key] = expressionAttributeNames[key]; }); return opts; }
javascript
{ "resource": "" }
q9375
updateExpressionAttributeValues
train
function updateExpressionAttributeValues(opts, expressionAttributeValues) { if (!expressionAttributeValues || typeof expressionAttributeValues !== 'object') return opts; if (!opts) opts = {}; if (!opts.ExpressionAttributeValues) opts.ExpressionAttributeValues = {}; const keys = Object.getOwnPropertyNames(expressionAttributeValues); keys.forEach(key => { opts.ExpressionAttributeValues[key] = expressionAttributeValues[key]; }); return opts; }
javascript
{ "resource": "" }
q9376
train
function (card, cb) { Card.findOrCreate(card.id, card) .exec(function (err, foundCard){ if (err) return cb(err); if (foundCard.lastStripeEvent > card.lastStripeEvent) return cb(null, foundCard); if (foundCard.lastStripeEvent == card.lastStripeEvent) return Card.afterStripeCustomerCardUpdated(foundCard, function(err, card){ return cb(err, card)}); Card.update(foundCard.id, card) .exec(function(err, updatedCards){ if (err) return cb(err); if (!updatedCards) return cb(null, null); Card.afterStripeCustomerCardUpdated(updatedCards[0], function(err, card){ cb(err, card); }); }); }); }
javascript
{ "resource": "" }
q9377
train
function (card, cb) { Card.destroy(card.id) .exec(function (err, destroyedCards){ if (err) return cb(err); if (!destroyedCards) return cb(null, null); Card.afterStripeCustomerCardDeleted(destroyedCards[0], function(err, card){ cb(null, card); }); }); }
javascript
{ "resource": "" }
q9378
getOrigin
train
function getOrigin(loc) { var a; if (loc.protocol !== undefined) { a = loc; } else { a = document.createElement("a"); a.href = loc; } return a.protocol.replace(/:/g, "") + a.host; }
javascript
{ "resource": "" }
q9379
train
function(ev) { var regex = new RegExp(searchBox.value, 'i'), targets = optionsList.querySelectorAll('li'); for (var i=0; i<targets.length; i++) { var target = targets[i]; // With multiple active options are never shown in the options list, with single // we show both the active/inactive options with the active highlighted if(multiple && target.classList.contains('active')) continue; if(!target.textContent.match(regex)) { target.style.display = 'none'; } else { target.style.display = 'block'; } }; searchBox.style.width = ((searchBox.value.length * selected.textWidth) + 25) + 'px'; moveOptionList(); }
javascript
{ "resource": "" }
q9380
train
function(option, selected) { var item = document.createElement('li'); item.textContent = option.textContent; var activate = function() { // If multiple we just remove this option from the list if (multiple) { item.style.display = 'none'; // If single ensure no other options are selected, but keep in the list } else { for (var i=0; i<options.length; i++) { if (options[i]._deselected) options[i]._deselected.classList.remove('active'); } } item.classList.add('active'); } item.addEventListener('click', function(ev) { activate(); selectOption(option); // create "selected" option }); if (selected) { activate(); } optionsList.appendChild(item); option._deselected = item; }
javascript
{ "resource": "" }
q9381
train
function () { var self = this; if (typeof this._isIntercepted === 'undefined') { // Got through all injector objects each(res.injectors, function (obj) { if (obj.when(req, res)) { self._isIntercepted = true; obj.active = true; } }); if (!this._isIntercepted) { this._isIntercepted = false; } debug('first time _interceptCheck ran', this._isIntercepted); } return this._isIntercepted; }
javascript
{ "resource": "" }
q9382
train
function(status, reasonPhrase, headers) { var self = this; each(headers || reasonPhrase, function(value, name) { self.setHeader(name, value); }); return this._super(status, typeof reasonPhrase === 'string' ? reasonPhrase : undefined); }
javascript
{ "resource": "" }
q9383
train
function (chunk, encoding) { if (this._interceptCheck()) { if(!this._interceptBuffer) { debug('initializing _interceptBuffer'); this._interceptBuffer = new WritableStream(); } return this._interceptBuffer.write(chunk, encoding); } return this._super.apply(this, arguments); }
javascript
{ "resource": "" }
q9384
train
function (data, encoding) { var self = this; var _super = this._super.bind(this); if (!this._interceptCheck()) { debug('not intercepting, ending with original .end'); return _super(data, encoding); } if (data) { this.write(data, encoding); } debug('resetting to original response.write'); this.write = oldWrite; // Responses without a body can just be ended if(!this._hasBody || !this._interceptBuffer) { debug('ending empty resopnse without injecting anything'); return _super(); } var gzipped = this.getHeader('content-encoding') === 'gzip'; var chain = Q(this._interceptBuffer.getContents()); if(gzipped) { debug('unzipping content'); // Unzip the buffer chain = chain.then(function(buffer) { return Q.nfcall(zlib.gunzip, buffer); }); } this.injectors.forEach(function(injector) { // Run all converters, if they are active // In series, using the previous output if(injector.active) { debug('adding injector to chain'); var converter = injector.converter.bind(self); chain = chain.then(function(prev) { return Q.nfcall(converter, prev, req, res); }); } }); if(gzipped) { debug('re-zipping content'); // Zip it again chain = chain.then(function(result) { return Q.nfcall(zlib.gzip, result); }); } chain.then(_super).fail(function(e) { debug('injector chain failed, emitting error event'); self.emit('error', e); }); return true; }
javascript
{ "resource": "" }
q9385
isJavaScriptFile
train
function isJavaScriptFile(filepath) { if (!fs.statSync(filepath).isFile()) { return false; } if (path.basename(filepath) === 'index.js') { return false; } return filepath.slice(-3) === '.js'; }
javascript
{ "resource": "" }
q9386
onValue
train
function onValue(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'value'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var callbackPeak = function callbackPeak(snap) { var processed = snapCallback.bind(this)(snap); snapPeak[storageKey] = JSON.stringify(processed); processedCallback.bind(this)(processed); }; dbRef.on('value', callbackPeak, cancelCallbackOrContext, context); }); }
javascript
{ "resource": "" }
q9387
offValue
train
function offValue(dbRef) { var storageKey = getStorageKeyFromDbRef(dbRef, 'value'); //Turn listener off. dbRef.off(); return new Promise(function (resolve, reject) { if (storageKey in snapPeak) { var dataToCache = snapPeak[storageKey]; delete snapPeak[storageKey]; resolve(_reactNative.AsyncStorage.setItem(storageKey, dataToCache)); } else { resolve(null); } }); }
javascript
{ "resource": "" }
q9388
onChildAdded
train
function onChildAdded(dbRef, fromCacheCallback, newDataArrivingCallback, snapCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(fromCacheCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var firstData = true; var callbackIntercept = function callbackIntercept(snap) { //Call the data arriving callback the first time new data comes in. if (firstData) { firstData = false; newDataArrivingCallback.bind(this)(); } //Then call the snapCallback as normal. snapCallback.bind(this)(snap); }; dbRef.on('child_added', callbackIntercept, cancelCallbackOrContext, context); }); }
javascript
{ "resource": "" }
q9389
offChildAdded
train
function offChildAdded(dbRef, dataToCache) { var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added'); //Turn listener off. dbRef.off(); return new Promise(function (resolve, reject) { resolve(_reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(dataToCache))); }); }
javascript
{ "resource": "" }
q9390
onChildRemoved
train
function onChildRemoved(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_removed', callback, cancelCallbackOrContext, context); }
javascript
{ "resource": "" }
q9391
onChildChanged
train
function onChildChanged(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_changed', callback, cancelCallbackOrContext, context); }
javascript
{ "resource": "" }
q9392
onChildMoved
train
function onChildMoved(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_moved', callback, cancelCallbackOrContext, context); }
javascript
{ "resource": "" }
q9393
twice
train
function twice(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'twice'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var callbackPeak = function callbackPeak(snap) { var processed = snapCallback.bind(this)(snap); //Store to cache. _reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(processed)).then(function () { processedCallback.bind(this)(processed); }.bind(this)); }; dbRef.once('value', callbackPeak, cancelCallbackOrContext, context); }); }
javascript
{ "resource": "" }
q9394
clearCacheForRef
train
function clearCacheForRef(dbRef) { var location = dbRef.toString().substring(dbRef.root.toString().length); var promises = []; acceptedOnVerbs.forEach(function (eventType) { var storageKey = '@FirebaseLocalCache:' + eventType + ':' + location; promises.push(_reactNative.AsyncStorage.removeItem(storageKey)); }); return Promise.all(promises); }
javascript
{ "resource": "" }
q9395
clearCache
train
function clearCache() { return _reactNative.AsyncStorage.getAllKeys().then(function (keys) { var promises = []; keys.forEach(function (key) { if (key.startsWith('@FirebaseLocalCache:')) { //delete it from the cache if it exists. promises.push(_reactNative.AsyncStorage.removeItem(key)); } }); return Promise.all(promises); }); }
javascript
{ "resource": "" }
q9396
parseIntValue
train
function parseIntValue(input) { let value = input.buf.readInt32LE(input.i); input.i += 4; return value; }
javascript
{ "resource": "" }
q9397
XAudioJSMediaStreamPushAudio
train
function XAudioJSMediaStreamPushAudio(event) { var index = 0; var audioLengthRequested = event.data; var samplesPerCallbackAll = XAudioJSSamplesPerCallback * XAudioJSChannelsAllocated; var XAudioJSMediaStreamLengthAlias = audioLengthRequested % XAudioJSSamplesPerCallback; audioLengthRequested = audioLengthRequested - (XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback)) - XAudioJSMediaStreamLengthAlias + XAudioJSSamplesPerCallback; XAudioJSMediaStreamLengthAliasCounter -= XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback); XAudioJSMediaStreamLengthAliasCounter += XAudioJSSamplesPerCallback - XAudioJSMediaStreamLengthAlias; if (XAudioJSMediaStreamBuffer.length != samplesPerCallbackAll) { XAudioJSMediaStreamBuffer = new Float32Array(samplesPerCallbackAll); } XAudioJSResampleRefill(); while (index < audioLengthRequested) { var index2 = 0; while (index2 < samplesPerCallbackAll && XAudioJSResampleBufferStart != XAudioJSResampleBufferEnd) { XAudioJSMediaStreamBuffer[index2++] = XAudioJSResampledBuffer[XAudioJSResampleBufferStart++]; if (XAudioJSResampleBufferStart == XAudioJSResampleBufferSize) { XAudioJSResampleBufferStart = 0; } } XAudioJSMediaStreamWorker.postMessage([0, XAudioJSMediaStreamBuffer]); index += XAudioJSSamplesPerCallback; } }
javascript
{ "resource": "" }
q9398
listEventSourceMappings
train
function listEventSourceMappings(lambda, params, logger) { logger = logger || console; const functionName = params.FunctionName; const listEventSourceMappingsAsync = Promises.wrap(lambda.listEventSourceMappings); const startMs = Date.now(); return listEventSourceMappingsAsync.call(lambda, params).then( result => { if (logger.traceEnabled) { const mappings = Array.isArray(result.EventSourceMappings) ? result.EventSourceMappings : []; const n = mappings.length; logger.trace(`Found ${n} event source mapping${n !== 1 ? 's' : ''} for ${functionName} - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`); } return result; }, err => { logger.error(`Failed to list event source mappings for function (${functionName}) - took ${Date.now() - startMs} ms`, err); throw err; } ); }
javascript
{ "resource": "" }
q9399
updateEventSourceMapping
train
function updateEventSourceMapping(lambda, params, logger) { logger = logger || console; const functionName = params.FunctionName; const uuid = params.UUID; const updateEventSourceMappingAsync = Promises.wrap(lambda.updateEventSourceMapping); const startMs = Date.now(); return updateEventSourceMappingAsync.call(lambda, params).then( result => { logger.info(`Updated event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`); return result; }, err => { logger.error(`Failed to update event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms`, err); throw err; } ); }
javascript
{ "resource": "" }