_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q12300
train
function () { var connection = this.connection(); // if a connection is defined, get the ID from connection if (connection) { if (!connection.transactionId) { throw new AdapterError(AdapterError.TRANSACTION_NOT_ASSOCIATED); } return (this._id = connection.transactionId); // save it just in case, during return } // at this point if we do not have an id, we know that we will need to return a dummy one return this._id || (this._id = util.uid()); }
javascript
{ "resource": "" }
q12301
train
function (connectionName, callback) { var self = this, _db = Transaction.databases[connectionName], transactionId; // validate db setup prior to every connection. this ensures nothing goes forward post teardown if (!_db) { callback(new AdapterError(AdapterError.TRANSACTION_NOT_SETUP)); } // validate connection name if (!connectionName) { callback(new AdapterError(AdapterError.TRANSACTION_NOT_IDENTIFIED)); } // if this transaction is already connected, then continue if (self.connection()) { // @todo implement error check when multi-db conn is attempted // // callback with error if connection name and current connection mismatch // if (connectionName !== self.connection().identity) { // callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED)); // } callback(undefined, self.connection()); return; } // at this point, it seems like the connection has not been setup yet, so we setup one and then move forward transactionId = self.id(); // this will return and cache a new transaction ID if not already present // set the actual connection name self._connectionName = connectionName; _db.getConnection(function (error, conn) { if (!error) { self._connection = conn; // save reference Transaction.associateConnection(conn, transactionId, _db.transactionConfig); // @note disassociate on dc } callback(error, self._connection); }); }
javascript
{ "resource": "" }
q12302
train
function (connectionName, callback) { var self = this, conn = self.connection(); // if not yet connected, spawn new connection and initiate transaction if (!conn) { self.connect(connectionName, function (error, conn) { if (error) { callback(error, conn); return; } // now that we have the connection, we initiate transaction. note that this sql_start is part of the new // connection branch. it is always highly likely that this would be the program flow. in a very unlikely // case the alternate flow will kick in, which is the `conn.query` right after this if-block. conn.beginTransaction(function (error) { callback(error, self); }); }); return; // do not proceed with sql_start if connection wasn't initially present. } // if transaction is attempted across multiple connections, return an error if (connectionName !== self._connectionName) { return callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED)); } conn.beginTransaction(function (error) { // if callback mode is used, then execute it and send self as a parameter to match the new Constructor API. callback(error, self); }); }
javascript
{ "resource": "" }
q12303
train
function (callback) { var conn = this.connection(), id = this._id; // use the raw ID object // prevent new transactions from using this connection. this.disconnect(); // if commit was called with no active conn, it implies, no transact action // was called. as such it is an error. if (!conn) { // allow one pseudo commit even without connection, so that programmatic call of repeated commits or // rollbacks can be trapped. // note that the absence of `_id` indicates that a `.disconnect` was called. return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_COMM)); } // we commit the connection and then release from hash conn.commit(function (error) { // try releasing the connection. // if that fails then treat it as a major error. try { conn.release(); } // if there was an error during release, set that as the main error. catch (err) { !error && (error = err); } // if failure to issue commit or release, then rollback if (error && conn.transactionConfig.rollbackOnError) { return conn.rollback(function () { // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); } // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); }
javascript
{ "resource": "" }
q12304
train
function (callback) { var conn = this.connection(), id = this._id; // use the raw ID object // prevent new transactions from using this connection. this.disconnect(); // if commit was called with no active conn, it implies, no transact action // was called. as such it is an error. if (!conn) { // allow one pseudo commit even without connection, so that programmatic call of repeated commits or // rollbacks can be trapped. // note that the absence of `_id` indicates that a `.disconnect` was called. return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_ROLL)); } conn.rollback(function (error) { // try releasing the connection. // if that fails then treat it as a major error. try { conn.release(); } // if there was an error during release, set that as the main error. catch (err) { !error && (error = err); } // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); }
javascript
{ "resource": "" }
q12305
train
function (config) { if (!config) { return; } var replConfig, peerNames, sanitisePeerConfig, source = this.sources[config.identity]; // fn // at this stage, the source should not be there if (source) { source.end(); // in case sources exist (almost unlikely, end them) console.log('Warn: duplicate setup of connection found in replication setup for ' + config.identity); } // set default for configuration objects and also clone them // --------------------------------------------------------- // clone and set defaults for the configuration variables. config = util.clone(config); // clone config. do it here to clone replication config too replConfig = util.fill(config.replication || { enabled: false // blank config means replication disabled }, DEFAULT_REPL_SOURCE_CFG); // extract repl config from main config !replConfig.sources && (replConfig.sources = {}); // set default to no source if none specified delete config.replication; // we remove the recursive config from main config clone. // setup a dumb source as a precaution and since we should fall back to original connection if setup fails source = this.sources[config.identity] = db.oneDumbSource(); // replication explicitly disabled or no peers defined. we do this after ending any ongoing sources source._replication = !!replConfig.enabled; if (source._replication === false) { return; } // create default connection parameters for cluster // ------------------------------------------------ // get the list of peer names defined in sources and setup the config defaults for peer sources peerNames = _.filter(Object.keys(replConfig.sources) || [], function (peer) { // remove all disabled peers return (peer = replConfig.sources[peer]) && (peer.enabled !== false); }); sanitisePeerConfig = function (peerConfig) { return util.fill(util.extend(peerConfig, { database: peerConfig._database || config.database, // force db name to be same pool: true, waitForConnections: true, multipleStatements: true }), (replConfig.inheritMaster === true) && config); }; // depending upon the number of peers defined, create simple connection or clustered connection // -------------------------------------------------------------------------------------------- // nothing much to do, if there are no replication source defined if (peerNames.length === 0) { sails && sails.log.info('smt is re-using master as readonly source'); // if it is marked to inherit master in replication, we simply create a new source out of the master config if (replConfig.inheritMaster === true) { this.sources[config.identity] = db.createSource(sanitisePeerConfig({})); } return; } // for a single peer, the configuration is simple, we do not need a cluster but a simple pool if (peerNames.length === 1) { sails && sails.log.info('smt is using 1 "' + config.identity + '" readonly source - ' + peerNames[0]); // ensure that the single source's config is taken care of by setting the default and if needed inheriting // from master this.sources[config.identity] = db.createSource(sanitisePeerConfig(replConfig.sources[peerNames[0]])); return; } // iterate over all sources and normalise and validate their configuration util.each(replConfig.sources, sanitisePeerConfig); sails && sails.log.info('smt is using ' + peerNames.length + ' "' + config.identity + '" readonly sources - ' + peerNames.join(', ')); // create connections for read-replicas and add it to the peering list this.sources[config.identity] = db.createCluster(replConfig); }
javascript
{ "resource": "" }
q12306
train
function () { // release all pending connections util.each(this.connections, function (connection, threadId, connections) { try { connection.release(); } catch (e) { } // nothing to do with error delete connections[threadId]; }); // execute end on the db. will end pool if pool, or otherwise will execute whatever `end` that has been // exposed by db.js util.each(this.sources, function (source, identity, sources) { try { source && source.end(); } catch (e) { } // nothing to do with error delete sources[identity]; }); }
javascript
{ "resource": "" }
q12307
train
function (callback) { var self = this; if (!Multiplexer.sources[self._connectionName]) { return callback(new AdapterError(AdapterError.UNKNOWN_CONNECTION)); } Multiplexer.sources[self._connectionName].getConnection(function (error, connection) { if (error) { return callback(error); } // give a unique id to the connection and store it if not already self._threadId = util.uid(); Multiplexer.connections[self._threadId] = connection; callback(null, self._threadId, connection); }); }
javascript
{ "resource": "" }
q12308
train
function (threadId) { Multiplexer.connections[threadId] && Multiplexer.connections[threadId].release(); delete Multiplexer.connections[threadId]; }
javascript
{ "resource": "" }
q12309
train
function (connectionName, collectionName, obj, cb) { if (_.isObject(obj)) { try { var modelInstance = new this._model(obj); return cb(null, modelInstance); } catch (err) { return cb(err, null); } } }
javascript
{ "resource": "" }
q12310
mapOptions
train
function mapOptions() { return { element: element[0], scope: 'usa', height: scope.height, width: scope.width, fills: { defaultFill: '#b9b9b9' }, data: {}, done: function (datamap) { function redraw() { datamap.svg.selectAll('g').attr('transform', 'translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')'); } if (angular.isDefined(attrs.onClick)) { datamap.svg.selectAll('.datamaps-subunit').on('click', function (geography) { scope.onClick()(geography); }); } if (angular.isDefined(attrs.zoomable)) { datamap.svg.call(d3.behavior.zoom().on('zoom', redraw)); } } }; }
javascript
{ "resource": "" }
q12311
train
function(path) { // TODO: Does file exist at the file location path? If so, do something about it... //var defaultManager = $.NSFileManager('alloc')('init') //if (defaultManager('fileExistsAtPath',NSlocation)) { // console.log("File already exists!") //} if (!path){ // Default Destination: e.g. "/Users/hugs/Desktop/Castro_uul3di.mov" var homeDir = $.NSHomeDirectory(); var desktopDir = homeDir.toString() + '/Desktop/'; var randomString = (Math.random() + 1).toString(36).substring(12); var filename = 'Castro_' + randomString + '.mp4'; this.location = desktopDir + filename; } else { // TODO: Make sure path is legit. this.location = path; } this.NSlocation = $.NSString('stringWithUTF8String', this.location); this.NSlocationURL = $.NSURL('fileURLWithPath', this.NSlocation); }
javascript
{ "resource": "" }
q12312
train
function(player, options, ready){ this.player_ = player; // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // Updated options with supplied options options = this.options(options); // Get ID from options, element, or create using player ID and unique ID this.id_ = options['id'] || ((options['el'] && options['el']['id']) ? options['el']['id'] : player.id() + '_component_' + vjs.guid++ ); this.name_ = options['name'] || null; // Create element if one wasn't provided in options this.el_ = options['el'] || this.createEl(); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options this.initChildren(); this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } }
javascript
{ "resource": "" }
q12313
train
function(tag, options, ready){ this.tag = tag; // Store the original tag used to set options // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = vjs.obj.merge(this.getTagSettings(tag), options); // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options['poster']; // Set controls this.controls_ = options['controls']; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options. // Builds the element through createEl() // Inits and embeds any child components in opts vjs.Component.call(this, this, options, ready); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Firstplay event implimentation. Not sold on the event yet. // Could probably just check currentTime==0? this.one('play', function(e){ var fpEvent = { type: 'firstplay', target: this.el_ }; // Using vjs.trigger so we can check if default was prevented var keepGoing = vjs.trigger(this.el_, fpEvent); if (!keepGoing) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); } }); this.on('ended', this.onEnded); this.on('play', this.onPlay); this.on('firstplay', this.onFirstPlay); this.on('pause', this.onPause); this.on('progress', this.onProgress); this.on('durationchange', this.onDurationChange); this.on('error', this.onError); this.on('fullscreenchange', this.onFullscreenChange); // Make player easily findable by ID vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenForUserActivity(); }
javascript
{ "resource": "" }
q12314
train
function (data) { if (!isLog()) { return undefined; } try { _fs.appendFileSync("pkgscript.log", (_utils.now() + " " + data + "\n"), "utf8"); } catch (e) { console.error(_utils.now + " [package-script] Package Script, ERROR:", e); } }
javascript
{ "resource": "" }
q12315
train
function (msg) { if (!isLog()) { return undefined; } if (msg) { console.log(_utils.now() + " " + msg); this.log2file(msg); } }
javascript
{ "resource": "" }
q12316
setSpawnObject
train
function setSpawnObject(admin) { admin = ((admin === undefined) ? getDefaultAdmin() : admin); if (isLinux && admin) { spawn = sudoarg; } else { spawn = cparg.spawn; } return admin; }
javascript
{ "resource": "" }
q12317
install
train
function install(items, callback) { var item = items[next], command = item.command, args = item.args, admin = item.admin, spawnopt = (item.spawnopt || {}), print; // set the spawn object according to the passed admin argument admin = setSpawnObject(admin); // run the command if (isLinux) { if (admin) { // use sudo args.unshift(command); print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + print); sudoopt.spawnOptions = {}; jsutils.Object.copy(spawnopt, sudoopt.spawnOptions); cprocess = spawn(args, sudoopt); } else { //use child_process print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + command + " " + print); cprocess = spawn(command, args, spawnopt); } } else { args.unshift(command); args.unshift("/c"); command = "cmd"; print = [command, args.join(" ")].join(" "); logger.console.log("[package-script] Running Installer command: " + print); cprocess = spawn(command, args, spawnopt); } // -- Spawn Listeners cprocess.stdout.on('data', function (data) { var log = 'CAT Installer: ' + data; logger.logall(log); }); cprocess.stderr.on('data', function (data) { if (data && (new String(data)).indexOf("npm ERR") != -1) { logger.logall('Package Script : ' + data); } else { logger.log2file('Package Script : ' + data); } }); cprocess.on('close', function (code) { logger.log2file('Package Script Complete ' + code); next++; if (next < size) { install(items, callback); } else { // callback if (callback && _.isFunction(callback)) { callback.call(this, code); } } }); }
javascript
{ "resource": "" }
q12318
train
function(config, init, callback) { var me = this; // first initialize if (init) { this.init(init); } logger.log2file("\n\n************ Package Script ************************************* process id: " + process.pid); if (config && _.isArray(config)) { commands = commands.concat(config); size = commands.length; if (size > 0) { install(commands, function() { logger.logall("[package-script] process completed, see pkgscript.log for more information"); if (callback) { callback.call(me); } }); } } else { logger.logall("[package-script] No valid configuration for 'install' function, see the docs for more information "); } }
javascript
{ "resource": "" }
q12319
wrapQueryMethod
train
function wrapQueryMethod(fn, ctx) { return function() { // Obtain function arguments var args = [].slice.call(arguments); // Return a thunkified function that receives a done callback return function(done) { // Add a custom callback to provided args args.push(function(err, result) { // Query failed? if (err) { return done(err); } // Query succeeded done(null, result); }); // Execute the query fn.apply(ctx, args); }; }; }
javascript
{ "resource": "" }
q12320
wrapConnection
train
function wrapConnection(conn) { // Already wrapped this function? if (conn._coWrapped) { return conn; } // Set flag to avoid re-wrapping conn._coWrapped = true; // Functions to thunkify var queryMethods = [ 'query', 'execute' ]; // Traverse query methods list queryMethods.forEach(function(name) { // Thunkify the method conn[name] = wrapQueryMethod(conn[name], conn); }); // Return co-friendly connection return conn; }
javascript
{ "resource": "" }
q12321
evaluateCardCodes
train
function evaluateCardCodes(codes) { const len = codes.length if (len === 5) return evaluate5cards.apply(null, codes) if (len === 6) return evaluate6cards.apply(null, codes) if (len === 7) return evaluate7cards.apply(null, codes) throw new Error(`Can only evaluate 5, 6 or 7 cards, you gave me ${len}`) }
javascript
{ "resource": "" }
q12322
evaluateBoard
train
function evaluateBoard(board) { if (typeof board !== 'string') throw new Error('board needs to be a string') const cards = board.trim().split(/ /) return evaluateCardsFast(cards) }
javascript
{ "resource": "" }
q12323
setCardCodes
train
function setCardCodes(set) { const codeSet = new Set() for (const v of set) codeSet.add(cardCode(v)) return codeSet }
javascript
{ "resource": "" }
q12324
setStringifyCardCodes
train
function setStringifyCardCodes(set) { const stringSet = new Set() for (const v of set) stringSet.add(stringifyCardCode(v)) return stringSet }
javascript
{ "resource": "" }
q12325
hash_binary
train
function hash_binary(q, len, k) { var sum = 0 for (var i = 0; i < len; i++) { if (q[i]) { if (len - i - 1 >= k) { sum += choose[len - i - 1][k] } k-- if (k === 0) break } } return sum }
javascript
{ "resource": "" }
q12326
Handle_forEach
train
function Handle_forEach(t, path, aggressive_optimization, possible_undefined) { var arrayName = path.scope.generateUidIdentifier("a"), funcName = path.scope.generateUidIdentifier("f"), iterator = path.scope.generateUidIdentifier("i"), call = t.expressionStatement ( t.callExpression(funcName, [ t.memberExpression ( arrayName, iterator, true ), iterator, arrayName ]) ) path.getStatementParent().insertBefore ([ t.variableDeclaration("let", [ t.variableDeclarator ( arrayName, path.node.callee.object ) ]), t.variableDeclaration("let", [ t.variableDeclarator ( funcName, path.node.arguments[0] ) ]), aggressive_optimization ? t.forStatement ( t.variableDeclaration("let", [ t.variableDeclarator ( iterator, t.memberExpression ( arrayName, t.identifier("length") ) ) ]), possible_undefined ? t.logicalExpression ( "&&", t.updateExpression("--", iterator), t.binaryExpression ( "!==", t.memberExpression ( arrayName, iterator, true ), t.identifier("undefined") ) ) : t.updateExpression("--", iterator), null, call ) : t.forStatement ( t.variableDeclaration("let", [ t.variableDeclarator ( iterator, t.numericLiteral(0) ) ]), possible_undefined ? t.logicalExpression ( "&&", t.binaryExpression ( "<", iterator, t.memberExpression ( arrayName, t.identifier("length") ) ), t.binaryExpression ( "!==", t.memberExpression ( arrayName, iterator, true ), t.identifier("undefined") ) ) : t.updateExpression("--", iterator), t.updateExpression("++", iterator), call ) ]) path.remove() }
javascript
{ "resource": "" }
q12327
stringifyCardCode
train
function stringifyCardCode(code) { const rank = code & 0b111100 const suit = code & 0b000011 return rankCodeStrings[rank] + suitCodeStrings[suit] }
javascript
{ "resource": "" }
q12328
handRank
train
function handRank(val) { if (val > 6185) return HIGH_CARD // 1277 high card if (val > 3325) return ONE_PAIR // 2860 one pair if (val > 2467) return TWO_PAIR // 858 two pair if (val > 1609) return THREE_OF_A_KIND // 858 three-kind if (val > 1599) return STRAIGHT // 10 straights if (val > 322) return FLUSH // 1277 flushes if (val > 166) return FULL_HOUSE // 156 full house if (val > 10) return FOUR_OF_A_KIND // 156 four-kind return STRAIGHT_FLUSH // 10 straight-flushes }
javascript
{ "resource": "" }
q12329
handleRoute
train
function handleRoute(seneca, options, request, reply, route, next) { if (options.parseBody) { return ReadBody(request, finish) } finish(null, request.body || {}) // Express requires a body parser to work in production // This util creates a body obj without neededing a parser // but doesn't impact loading one in. function finish(err, body) { if (err) { return next(err) } // This is what the seneca handler will get // Note! request$ and response$ will be stripped // if the message is sent over transport. const payload = { request$: request, response$: reply, args: { body: body, route: route, params: request.params, query: request.query, user: request.user || null } } // Call the seneca action specified in the config seneca.act(route.pattern, payload, (err, response) => { if (err) { return next(err) } // Redirect or reply depending on config. if (route.redirect) { return reply.redirect(route.redirect) } if (route.autoreply) { return reply.send(response) } }) } }
javascript
{ "resource": "" }
q12330
unsecuredRoute
train
function unsecuredRoute(seneca, options, context, method, middleware, route) { const routeArgs = [route.path].concat(middleware).concat([ (request, reply, next) => { handleRoute(seneca, options, request, reply, route, next) } ]) context[method].apply(context, routeArgs) }
javascript
{ "resource": "" }
q12331
authRoute
train
function authRoute(seneca, options, context, method, route, middleware, auth) { const opts = { failureRedirect: route.auth.fail, successRedirect: route.auth.pass } const routeArgs = [route.path] .concat([auth.authenticate(route.auth.strategy, opts)]) .concat(middleware) .concat([ (request, reply, next) => { handleRoute(seneca, options, request, reply, route, next) } ]) context[method].apply(context, routeArgs) }
javascript
{ "resource": "" }
q12332
initCpt
train
function initCpt(numValues) { var cpt = []; var sum = 0; for(var i=0; i < numValues; i++) { cpt[i] = Math.random(); sum += cpt[i]; } for(var i=0; i < numValues; i++) { cpt[i] = cpt[i] / sum; } return cpt; }
javascript
{ "resource": "" }
q12333
initCptWithParents
train
function initCptWithParents(values, parents, paIndex) { if(parents && parents.length > 0) { if(parents.length === 1 || paIndex === parents.length - 1) { var idx = parents.length === 1 ? 0 : paIndex; var numPaVals = parents[idx].values.length; var cpts = []; for(var i=0; i < numPaVals; i++) { var cpt = initCpt(values.length); cpts.push(cpt); } return cpts; } else { var cpts = []; var numPaVals = parents[paIndex].values.length; for(var i=0; i < numPaVals; i++) { var cpt = initCptWithParents(values, parents, paIndex+1); cpts.push(cpt); } return cpts; } } else { return initCpt(values.length); } }
javascript
{ "resource": "" }
q12334
async
train
function async(f, args) { return new Promise( function(resolve, reject) { try { var r = f.apply(undefined, args); resolve(r); } catch(e) { reject(e); } } ); }
javascript
{ "resource": "" }
q12335
isArrayOfArray
train
function isArrayOfArray(o) { if(isArray(o)) { if(o.length > 0) { if(isArray(o[0])) { return true; } } } return false; }
javascript
{ "resource": "" }
q12336
setNodeCptProbs
train
function setNodeCptProbs(cpt, probs, index) { if(!isArrayOfArray(cpt)) { for(var i=0; i < cpt.length; i++) { cpt[i] = probs[index][i]; } var nextIndex = index + 1; return nextIndex; } else { var next = index; for(var i=0; i < cpt.length; i++) { next = setNodeCptProbs(cpt[i], probs, next); } return next; } }
javascript
{ "resource": "" }
q12337
initNodeCpt
train
function initNodeCpt(values, parents, probs) { var cpt = initCptWithParents(values, parents, 0); setNodeCptProbs(cpt, probs, 0); return cpt; }
javascript
{ "resource": "" }
q12338
normalizeProbs
train
function normalizeProbs(arr) { var probs = []; var sum = 0.0; for (var i=0; i < arr.length; i++) { probs[i] = arr[i] + 0.001 sum += probs[i] } for (var i=0; i < arr.length; i++) { probs[i] = probs[i] / sum; } return probs; }
javascript
{ "resource": "" }
q12339
normalizeCpts
train
function normalizeCpts(cpts) { var probs = [] for (var i=0; i < cpts.length; i++) { probs.push(normalizeProbs(cpts[i])); } return probs; }
javascript
{ "resource": "" }
q12340
check
train
function check(cmd, filter, mapping, coefficient = 1) { return new Promise((resolve, reject) => { exec(cmd, (error, stdout) => { if (error) { reject(error) } try { resolve(mapOutput(stdout, filter, mapping, coefficient)) } catch (err) { reject(err) } }) }) }
javascript
{ "resource": "" }
q12341
checkWin32
train
function checkWin32(directoryPath) { if (directoryPath.charAt(1) !== ':') { return new Promise((resolve, reject) => { reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`)) }) } return check( `wmic logicaldisk get size,freespace,caption`, driveData => { // Only get the drive which match the path const driveLetter = driveData[0] return directoryPath.startsWith(driveLetter) }, { diskPath: 0, free: 1, size: 2 } ) }
javascript
{ "resource": "" }
q12342
checkUnix
train
function checkUnix(directoryPath) { if (!path.normalize(directoryPath).startsWith(path.sep)) { return new Promise((resolve, reject) => { reject(new InvalidPathError(`The following path is invalid (should start by ${path.sep}): ${directoryPath}`)) }) } return check( `df -Pk "${module.exports.getFirstExistingParentPath(directoryPath)}"`, () => true, // We should only get one line, so we did not need to filter { diskPath: 5, free: 3, size: 1 }, 1024 // We get sizes in kB, we need to convert that to bytes ) }
javascript
{ "resource": "" }
q12343
init
train
function init() { element.wrap('<div class="ng-flat-datepicker-wrapper"></div>'); $compile(template)(scope); element.after(template); if (angular.isDefined(ngModel.$modelValue) && moment.isDate(ngModel.$modelValue)) { scope.calendarCursor = ngModel.$modelValue; } }
javascript
{ "resource": "" }
q12344
getWeeks
train
function getWeeks (date) { var weeks = []; var date = moment.utc(date); var firstDayOfMonth = moment(date).date(1); var lastDayOfMonth = moment(date).date(date.daysInMonth()); var startDay = moment(firstDayOfMonth); var endDay = moment(lastDayOfMonth); // NB: We use weekday() to get a locale aware weekday startDay = firstDayOfMonth.weekday() === 0 ? startDay : startDay.weekday(0); endDay = lastDayOfMonth.weekday() === 6 ? endDay : endDay.weekday(6); var currentWeek = []; for (var start = moment(startDay); start.isBefore(moment(endDay).add(1, 'days')); start.add(1, 'days')) { var afterMinDate = !scope.config.minDate || start.isAfter(scope.config.minDate, 'day'); var beforeMaxDate = !scope.config.maxDate || start.isBefore(scope.config.maxDate, 'day'); var isFuture = start.isAfter(today); var beforeFuture = scope.config.allowFuture || !isFuture; var day = { date: moment(start).toDate(), isToday: start.isSame(today, 'day'), isInMonth: start.isSame(firstDayOfMonth, 'month'), isSelected: start.isSame(dateSelected, 'day'), isSelectable: afterMinDate && beforeMaxDate && beforeFuture }; currentWeek.push(day); if (start.weekday() === 6 || start === endDay) { weeks.push(currentWeek); currentWeek = []; } } return weeks; }
javascript
{ "resource": "" }
q12345
resetSelectedDays
train
function resetSelectedDays () { scope.currentWeeks.forEach(function(week, wIndex){ week.forEach(function(day, dIndex){ scope.currentWeeks[wIndex][dIndex].isSelected = false; }); }); }
javascript
{ "resource": "" }
q12346
getYearsList
train
function getYearsList() { var yearsList = []; for (var i = 2005; i <= moment().year(); i++) { yearsList.push(i); } return yearsList; }
javascript
{ "resource": "" }
q12347
getDaysNames
train
function getDaysNames () { var daysNameList = []; for (var i = 0; i < 7 ; i++) { daysNameList.push(moment().weekday(i).format('ddd')); } return daysNameList; }
javascript
{ "resource": "" }
q12348
encrypt
train
function encrypt (input, firstKey = 0xAB) { const buf = Buffer.from(input); let key = firstKey; for (let i = 0; i < buf.length; i++) { buf[i] = buf[i] ^ key; key = buf[i]; } return buf; }
javascript
{ "resource": "" }
q12349
encryptWithHeader
train
function encryptWithHeader (input, firstKey = 0xAB) { const msgBuf = encrypt(input, firstKey); const outBuf = Buffer.alloc(msgBuf.length + 4); outBuf.writeUInt32BE(msgBuf.length, 0); msgBuf.copy(outBuf, 4); return outBuf; }
javascript
{ "resource": "" }
q12350
decrypt
train
function decrypt (input, firstKey = 0xAB) { const buf = Buffer.from(input); let key = firstKey; let nextKey; for (let i = 0; i < buf.length; i++) { nextKey = buf[i]; buf[i] = buf[i] ^ key; key = nextKey; } return buf; }
javascript
{ "resource": "" }
q12351
getPendingPacket
train
function getPendingPacket(ls){ var i; for (i = pendingPackets.length - 1; i >= 0; i--) if (pendingPackets[i].header.ls == ls) return pendingPackets[i]; }
javascript
{ "resource": "" }
q12352
UserPacket
train
function UserPacket(commands){ Packet.call(this); this.interval = undefined; // If the packet contains commands if (typeof commands !== 'undefined'){ // If it is a connect packet if (commands === null) { this.header.flags = flags.connect; this.body.commands = [{ get length() { return 8; }, serialize: function() { const connectCmd = '0100000000000000'; return (new Buffer(connectCmd, 'hex')); } }]; } else { this.body.commands = commands; this.header.flags = flags.sync; } } // If the packet contains no commands else { this.header.flags = flags.sync; } }
javascript
{ "resource": "" }
q12353
AtemPacket
train
function AtemPacket(msg){ Packet.call(this); this.header.flags = msg[0]>>>3; this.header.uid = msg.readUInt16BE(2); this.header.fs = msg.readUInt16BE(4); this.header.ls = msg.readUInt16BE(10); if ((this.header.flags & flags.unknown) == flags.unknown) console.log('Unknown Packet flag!'); if (state === ConnectionState.attempting) { if (this.isSync()){ atem.state = ConnectionState.establishing; uid = this.header.uid; } } else if (state === ConnectionState.establishing){ if (msg.length==12 && !this.isConnect()){ atem.state = ConnectionState.open; clearInterval(syncInterval); syncInterval = setInterval(sync, 600); } } if (this.isConnect()) { //Do something } else if ((msg.length == (msg.readUInt16BE(0)&0x7FF) && this.header.uid == uid)){ const body = msg.slice(12); var name, data, cmd, cmdLength, cursor=0; while (cursor < body.length-1) { cmdLength = body.readUInt16BE(cursor); name = body.toString('utf8', cursor+4, cursor+8); data = body.slice(cursor+8, cursor+cmdLength); cmd = new Command(name, data); this.body.commands.push(cmd); cursor += cmdLength; /** * @event Device#rawCommand * @type {Command} */ // todo: check foreign sequence number, to prevent the event emitter // from emitting the same message twice. atem.emit('rawCommand', cmd); atem.emit(cmd.name, cmd.data); } } else if (msg.length != (msg.readUInt16BE(0)&0x7FF)) { const err = new Error('Message length mismatch'); self.emit('error', err); } else { const err2 = new Error('UID mismatch'); self.emit('error', err2); } }
javascript
{ "resource": "" }
q12354
handleQueue
train
function handleQueue() { const count = commandQueue.length if (count>0) { const packet = new UserPacket(commandQueue.slice(0)); commandQueue = []; packet.transmit(); } return count }
javascript
{ "resource": "" }
q12355
generate
train
function generate(schema) { const ret = []; if (!validate(schema)) { return ret; } const fullSample = jsf(schema); if (!fullSample) { return ret; } ret.push({ valid: true, data: fullSample, message: 'should work with all required properties' }); ret.push(...generateFromRequired(schema)); ret.push(...generateFromRequired(schema, false)); ret.push(...generateForTypes(schema)); return ret; }
javascript
{ "resource": "" }
q12356
serversync
train
function serversync(key, action, handler) { var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, _ref$tracing = _ref.tracing, tracing = _ref$tracing === undefined ? false : _ref$tracing, _ref$logger = _ref.logger, logger = _ref$logger === undefined ? console : _ref$logger, _ref$logLevel = _ref.logLevel, logLevel = _ref$logLevel === undefined ? 'info' : _ref$logLevel; (0, _invariant2.default)(key, 'key is required'); (0, _invariant2.default)(action, 'action is required'); (0, _invariant2.default)(handler, 'handler is required'); var log = function log() { return tracing ? logger[logLevel].apply(logger, arguments) : function () {}; }; var isRunning = false; var trigger = function trigger() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } log('serversync#trigger', args); var value = action.apply(undefined, args); log('serversync#trigger action output ignored', args, value); }; var start = function start() { log('serversync#start'); isRunning = true; }; var stop = function stop() { log('serversync#stop'); isRunning = false; }; return { start: start, stop: stop, trigger: trigger, get isRunning() { return isRunning; }, mechanism: mechanism, isFallback: false, isServer: true }; }
javascript
{ "resource": "" }
q12357
_extractLocaleDays
train
function _extractLocaleDays(abbr, locale) { if(abbr) { return cldr ? cldr.extractDayNames(locale).format.abbreviated : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; } else { return cldr ? cldr.extractDayNames(locale).format.wide : ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; } }
javascript
{ "resource": "" }
q12358
_extractLocaleMonths
train
function _extractLocaleMonths(abbr, locale) { var months = [] if(abbr) { months = cldr ? cldr.extractMonthNames(locale).format.abbreviated : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; } else { months = cldr ? cldr.extractMonthNames(locale).format.wide : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; } months.unshift(''); return months; }
javascript
{ "resource": "" }
q12359
_toordinal
train
function _toordinal(year, month, day) { var days_before_year = ((year - 1) * 365) + Math.floor((year - 1) / 4) - Math.floor((year - 1) / 100) + Math.floor((year - 1) / 400); var days_before_month = _DAYS_BEFORE_MONTH[month] + (month > 2 && isleap(year) ? 1 : 0); return (days_before_year + days_before_month + day); }
javascript
{ "resource": "" }
q12360
leapdays
train
function leapdays(y1, y2) { y1--; y2--; return (Math.floor(y2/4) - Math.floor(y1/4)) - (Math.floor(y2/100) - Math.floor(y1/100)) + (Math.floor(y2/400) - Math.floor(y1/400)); }
javascript
{ "resource": "" }
q12361
setlocale
train
function setlocale(locale) { locale = typeof(locale) === "undefined" ? "en_US" : locale; if((cldr && (cldr.localeIds.indexOf(locale.replace(/-/g, '_').toLowerCase()) === -1)) || (!cldr && ((locale.replace(/-/g, '_').toLowerCase() !== "en_us")))) { throw new IllegalLocaleError(); } this.day_name = _extractLocaleDays(false, locale); this.day_abbr = _extractLocaleDays(true, locale); this.month_name = _extractLocaleMonths(false, locale); this.month_abbr = _extractLocaleMonths(true, locale); }
javascript
{ "resource": "" }
q12362
timegm
train
function timegm(timegmt) { var year = timegmt[0]; var month = timegmt[1]; var day = timegmt[2]; var hour = timegmt[3]; var minute = timegmt[4]; var second = timegmt[5]; if(month < 1 || month > 12) { throw new IllegalMonthError(); } if(day < 1 || day > (_DAYS_IN_MONTH[month] + (month === 2 && isleap(year)))) { throw new IllegalDayError(); } if(hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) { throw new IllegalTimeError(); } var days = _toordinal(year, month, 1) - 719163 + day - 1; var hours = (days * 24) + hour; var minutes = (hours * 60) + minute; var seconds = (minutes * 60) + second; return seconds; }
javascript
{ "resource": "" }
q12363
Calendar
train
function Calendar(firstweekday) { this._firstweekday = typeof(firstweekday) === "undefined" ? 0 : firstweekday; if(firstweekday < 0 || firstweekday > 6) { throw new IllegalWeekdayError(); } this._oneday = 1000 * 60 * 60 * 24; this._onehour = 1000 * 60 * 60; }
javascript
{ "resource": "" }
q12364
defaultClientIDHandler
train
function defaultClientIDHandler(args, context, info) { return get(args, [ 'clientID' ]) || get(context, [ 'clientID' ]) || get(info, [ 'rootValue', 'clientID' ]); }
javascript
{ "resource": "" }
q12365
trimCanvasXY
train
function trimCanvasXY(xy) { if( xy.length === 0 ) return; var last = xy[xy.length-1], i, point; var c = 0; for( i = xy.length-2; i >= 0; i-- ) { point = xy[i]; if( Math.abs(last.x - point.x) === 0 && Math.abs(last.y - point.y) === 0 ) { xy.splice(i, 1); c++; } else { last = point; } } if( xy.length <= 1 ) { xy.push(last); c--; } }
javascript
{ "resource": "" }
q12366
train
function(backend, name, options) { options = _.extend({keyPath: 'id'}, options || {}); this.options = options; this.backend = backend; this.name = name; this.keyPath = this.options.keyPath; }
javascript
{ "resource": "" }
q12367
resolverMiddleware
train
function resolverMiddleware (resolver) { return function (req, res, next) { try { const { source, args, context, info } = req const ctx = { req, res, next } const value = resolver.call(ctx, source, args, context, info) return Promise.resolve(value) .then(result => { req.result = result return next() }) .catch(next) } catch (err) { return next(err) } } }
javascript
{ "resource": "" }
q12368
nextMiddleware
train
function nextMiddleware (factory, mw, info) { const { resolved, index, routes, middlewares, errorMiddleware, req, res, metrics } = info const local = { finished: false, timeout: null } // check if the request has already been resolved if (resolved) return // get the current middleware const current = mw[index] const exec = { name: current.functionName, started: Date.now(), ended: null, data: null } metrics.executions.push(exec) // create a next method const next = data => { clearTimeout(local.timeout) if (local.finished || info.resolved) return local.finished = true // add the result exec.ended = Date.now() exec.data = data // allow reroutes to valid named route paths if (_.isString(data)) { const route = routes[data] if (!route) { if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 req.error = new Error(`No route found for "${data}"`) return nextMiddleware(factory, errorMiddleware, info) } res.end(data) } // get the correct route set const mwSet = route.type === ERROR_MIDDLEWARE ? errorMiddleware : middlewares // increment the re-route counter, set the index and go req.reroutes += 1 info.index = route.index return nextMiddleware(factory, mwSet, info) } // check for an error passed to the next method and not // already in the error middleware chain. if condition met // start processing error middleware if (data instanceof Error) { if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 req.error = data return nextMiddleware(factory, errorMiddleware, info) } res.end(data) } // check if there is any more middleware in the chain // if not, call end to complete the request return info.index === mw.length ? res.end() : nextMiddleware(factory, mw, info) } // create a timeout for the middleware if timeout > 0 if (current.timeout > 0) { local.timeout = setTimeout(() => { local.finished = true req.error = new Error(current.functionName + ' middleware timed out') // add the result exec.ended = Date.now() exec.data = req.error // if already in error middleware and timed out // end the entire request, othewise move to error mw if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 return nextMiddleware(factory, errorMiddleware, info) } return res.end() }, current.timeout) } // try to execute the resolver and if unable // move to error middleware. if already in error // middleware end the request try { info.index += 1 current.resolver(req, res, next) } catch (err) { clearTimeout(local.timeout) local.finished = true factory.emit(EVENT_ERROR, err) req.error = err // add the result exec.ended = Date.now() exec.data = req.error if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 return nextMiddleware(factory, errorMiddleware, info) } return res.end() } }
javascript
{ "resource": "" }
q12369
train
function (source, args, context, info) { // console.log(this.utils.getRootFieldDef(info, '_tableName')) let typeName = this.utils.getReturnTypeName(info) let db = this.globals.db.main let config = db.tables[typeName] let cursor = db.cursor return cursor.db(config.db).table(config.table).run() }
javascript
{ "resource": "" }
q12370
train
function() { var self = this; return Q.ninvoke(fs, 'readdir', path.join(this.backend.options.path, this.name)) .then(function(files) { return Q.all(files.map(function(f) { return self.delete(f); })); }) .then(function() { return true; }); }
javascript
{ "resource": "" }
q12371
train
function(file) { return path.join(this.backend.options.path, this.name, ''+path.basename(file)); }
javascript
{ "resource": "" }
q12372
filterStore
train
function filterStore(operation, store, args) { const filter = obj => { switch (operation) { case 'omit': return _.isFunction(args[0]) ? _.omitBy(obj, args[0]) : _.omit(obj, args); case 'pick': return _.isFunction(args[0]) ? _.pickBy(obj, args[0]) : _.pick(obj, args); default: break; } }; switch (store) { case 'context': case 'functions': case 'directives': case 'plugins': case 'types': _.set(this, `_${store}`, filter(_.get(this, `_${store}`))); break; default: assert(false, `invalid store for ${operation} operation`); break; } return this; }
javascript
{ "resource": "" }
q12373
defaultConflictResolution
train
function defaultConflictResolution(definition, name, type, tgt, src) { // TODO: Add support for type/field level conflict settings // TODO: Add support for extending types via extend key switch(type) { case 'type': const { query, mutation, subscription } = get(definition, [ 'schema' ]) || {}; // always merge a rootTypes definition if ([ query, mutation, subscription].indexOf(name) !== -1) { return { name, config: merge(tgt, src) }; } break; case 'function': return { name, config: Object.assign(tgt, src) }; case 'context': return { name, config: merge(tgt, src) }; default: break; } // emit a warning definition.emit(FactoryEvent.WARN, 'MergeConflict: Duplicate ' + type + ' with name "' + name + '" found. Using newer value'); return { name, config: tgt }; }
javascript
{ "resource": "" }
q12374
handleConflict
train
function handleConflict(definition, method, name, type, tgt, src) { const _method = method ? method : defaultConflictResolution; // allow the method to be a function that returns the new name // and type configuration if (typeof _method === 'function') { return _method(definition, name, type, tgt, src); } switch (_method) { // merges the target and source configurations case NameConflictResolution.MERGE: return { name, config: merge(tgt, src) }; // throws an error case NameConflictResolution.ERROR: throw new Error('Duplicate ' + type + ' name "' + name + '" is not allowed ' + 'when conflict is set to ' + NameConflictResolution.ERROR); // prints a warning and then overwrites the existing type definition case NameConflictResolution.WARN: definition.emit(FactoryEvent.WARN, 'GraphQLFactoryWarning: duplicate ' + 'type name "' + name + '" found. Merging ' + type + ' configuration') return { name, config: merge(tgt, src) }; // ignores the definition case NameConflictResolution.SKIP: return { name, config: tgt }; // silently overwrites the value case NameConflictResolution.OVERWRITE: return { name, config: src }; default: throw new Error('Invalid name conflict resolution'); } }
javascript
{ "resource": "" }
q12375
render
train
function render(context, xyPoints, map, canvasFeature) { ctx = context; if( canvasFeature.type === 'Point' ) { renderPoint(xyPoints, this.size); } else if( canvasFeature.type === 'LineString' ) { renderLine(xyPoints); } else if( canvasFeature.type === 'Polygon' ) { renderPolygon(xyPoints); } else if( canvasFeature.type === 'MultiPolygon' ) { xyPoints.forEach(renderPolygon); } }
javascript
{ "resource": "" }
q12376
intersects
train
function intersects(e) { if( !this.showing ) return; var dpp = this.getDegreesPerPx(e.latlng); var mpp = this.getMetersPerPx(e.latlng); var r = mpp * 5; // 5 px radius buffer; var center = { type : 'Point', coordinates : [e.latlng.lng, e.latlng.lat] }; var containerPoint = e.containerPoint; var x1 = e.latlng.lng - dpp; var x2 = e.latlng.lng + dpp; var y1 = e.latlng.lat - dpp; var y2 = e.latlng.lat + dpp; var intersects = this.intersectsBbox([[x1, y1], [x2, y2]], r, center, containerPoint); onIntersectsListCreated.call(this, e, intersects); }
javascript
{ "resource": "" }
q12377
processBody
train
function processBody(opts, body) { if (body === undefined) { return ''; } const handlers = Object.assign({}, serializers, opts.serializers); const headers = typeof opts.headers === 'object' ? opts.headers : {}; const contentType = Object.keys(headers).reduce((type, header) => { if (typeof type === 'string') { return type; } if ( header.match(/^content-type$/i) && typeof headers[header] === 'string' ) { return headers[header].toLowerCase(); } return type; }, undefined); const handler = handlers[contentType]; if (typeof handler === 'function') { return String(handler(body)); } if (typeof body === 'object') { return JSON.stringify(body); } return String(body); }
javascript
{ "resource": "" }
q12378
processData
train
function processData(res, data, options) { const handlers = Object.assign({}, deserializers, options.deserializers); const contentType = res.headers['content-type']; const types = typeof contentType === 'string' ? contentType.split(';') : []; // if there are no content types, return the data unmodified if (!types.length) { return data; } return types.reduce((d, type) => { try { const t = type.toLocaleLowerCase().trim(); const handler = handlers[t]; if (d instanceof Error || typeof handler !== 'function') { return d; } return handler(d); } catch (error) { return error; } }, data); }
javascript
{ "resource": "" }
q12379
mongoType
train
function mongoType( typeStr, options ) { const required = typeStr.match(/^(\S+)!$/); const list = typeStr.match(/^\[(\S+)]$/); if (required) { const innerType = required[1]; if (_.includes(SCALARS, innerType)) { options.required = true; } return mongoType(innerType); } else if (list) { return [ mongoType(list[1]) ]; } switch (typeStr) { case 'String': return String; case 'Int': case 'Float': return Number; case 'Boolean': return Boolean; case 'DateTime': return Date; case 'ID': return mongoose.Schema.Types.ObjectId; case 'JSON': return mongoose.Schema.Types.Mixed; default: throw new Error(typeStr); } }
javascript
{ "resource": "" }
q12380
getTypeInfo
train
function getTypeInfo (obj, info) { const constructorName = _.constructorName(obj) const _info = info || { type: null, name: null, isList: false, isNonNull: false } switch (constructorName) { case 'GraphQLNonNull': _info.isNonNull = true return getTypeInfo(obj.ofType, _info) case 'GraphQLList': _info.isList = true return getTypeInfo(obj.ofType, _info) default: _info.type = obj _info.name = obj.name } return _info }
javascript
{ "resource": "" }
q12381
baseDef
train
function baseDef (info) { const { name, isList, isNonNull } = info const def = { type: isList ? [ name ] : name } if (isNonNull) def.nullable = false return def }
javascript
{ "resource": "" }
q12382
resolveBuild
train
function resolveBuild(schema) { const build = _.get(schema, 'definition._build'); return isPromise(build) ? build : Promise.resolve(); }
javascript
{ "resource": "" }
q12383
middleware
train
function middleware(definition, resolver, options) { const customExecution = options.factoryExecution !== false; const resolve = function(source, args, context, info) { // ensure that context is an object and extend it const ctx = _.isObjectLike(context) ? context : {}; Object.assign(ctx, definition.context); info.definition = definition; return customExecution ? factoryExecute(source, args, ctx, info) : graphqlExecute(source, args, ctx, info); }; // add the resolver as a property on the resolve middleware // function so that when deconstructing the schema the original // resolver is preserved. Also add a flag that identifies this // resolver as factory middleware resolve.__resolver = resolver; resolve.__factoryMiddleware = true; return resolve; }
javascript
{ "resource": "" }
q12384
defaultResolveUser
train
function defaultResolveUser(source, args, context, info) { return ( get(args, ['userID']) || get(context, ['userID']) || get(info, ['rootValue', 'userID']) ); }
javascript
{ "resource": "" }
q12385
resolverMiddleware
train
function resolverMiddleware (resolver) { return function (req, res, next) { try { const { source, args, context, info } = req const nonCircularReq = _.omit(req, [ 'context' ]) const ctx = _.assign({}, context, { req: nonCircularReq, res, next }) const value = resolver(source, args, ctx, info) // return a resolved promise return Promise.resolve(value) .then(result => { req.result = result return next() }) .catch(next) } catch (err) { return next(err) } } }
javascript
{ "resource": "" }
q12386
addTypeFunction
train
function addTypeFunction (typeName, funcName, func) { if (!stringValue(typeName)) { throw new Error('Invalid "typeName" argument, must be String') } else if (!_.isFunction(func) && !stringValue(func)) { throw new Error('Invalid func argument, must be function') } _.set(this.backing, [ typeName, `_${funcName}` ], func) return this }
javascript
{ "resource": "" }
q12387
deleteDefaultResourceAt
train
function deleteDefaultResourceAt(baseDir, resourceName) { shell.ls(path.join(baseDir, 'res/drawable-*')) .forEach(function (drawableFolder) { var imagePath = path.join(drawableFolder, resourceName); shell.rm('-f', [imagePath, imagePath.replace(/\.png$/, '.9.png')]); events.emit('verbose', 'Deleted ' + imagePath); }); }
javascript
{ "resource": "" }
q12388
queryTargetScripts
train
function queryTargetScripts(targetDir) { var scripts = []; fs.readdirSync(targetDir).forEach(function (file) { if (!path.basename(file).toLowerCase().match(/.d.ts/g) && path.basename(file).toLowerCase().match(/\.ts$/i)) { scripts.push(path.basename(file, path.extname(file))); } }); return scripts; }
javascript
{ "resource": "" }
q12389
queryPluginVersion
train
function queryPluginVersion(pluginDir) { var pluginXml = path.join(pluginDir, 'plugin.xml'); var domPluginXml = jsdom.jsdom(fs.readFileSync(pluginXml).toString()); return $(domPluginXml).find('plugin').attr('version'); }
javascript
{ "resource": "" }
q12390
setBanner
train
function setBanner() { if (grunt.config.get('app_plugins_mode_release')) { var moduleName = grunt.config.get('app_plugins_work_script_name') + '.js'; var version = grunt.config.get('app_plugins_work_version'); var src = path.join( grunt.config.get('app_plugins_root_dir'), grunt.config.get('app_plugins_work_id'), grunt.config.get('plugins_www'), grunt.config.get('app_plugins_work_script_name') + '.js' ); var info = { src: src, moduleName: moduleName, version: version, }; grunt.config.set('banner_info', info); grunt.task.run('banner_setup'); } }
javascript
{ "resource": "" }
q12391
Api
train
function Api(platform, platformRootDir, events) { // 'platform' property is required as per PlatformApi spec this.platform = platform || 'ios'; this.root = platformRootDir || path.resolve(__dirname, '..'); this.events = events || ConsoleLogger.get(); // NOTE: trick to share one EventEmitter instance across all js code require('cordova-common').events = this.events; var xcodeProjDir; var xcodeCordovaProj; try { xcodeProjDir = fs.readdirSync(this.root).filter( function(e) { return e.match(/\.xcodeproj$/i); })[0]; if (!xcodeProjDir) { throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.'); } var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep)+1, xcodeProjDir.indexOf('.xcodeproj')); xcodeCordovaProj = path.join(this.root, cordovaProjName); } catch(e) { throw new CordovaError('The provided path "'+this.root+'" is not a Cordova iOS project.'); } this.locations = { root: this.root, www: path.join(this.root, 'www'), platformWww: path.join(this.root, 'platform_www'), configXml: path.join(xcodeCordovaProj, 'config.xml'), defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'), pbxproj: path.join(this.root, xcodeProjDir, 'project.pbxproj'), xcodeProjDir: path.join(this.root, xcodeProjDir), xcodeCordovaProj: xcodeCordovaProj, // NOTE: this is required by browserify logic. // As per platformApi spec we return relative to template root paths here cordovaJs: 'bin/CordovaLib/cordova.js', cordovaJsSrc: 'bin/cordova-js-src' }; }
javascript
{ "resource": "" }
q12392
parseTargetDevicePreference
train
function parseTargetDevicePreference(value) { if (!value) return null; var map = { 'universal': '"1,2"', 'handset': '"1"', 'tablet': '"2"'}; if (map[value.toLowerCase()]) { return map[value.toLowerCase()]; } events.emit('warn', 'Unknown target-device preference value: "' + value + '".'); return null; }
javascript
{ "resource": "" }
q12393
getDocDom
train
function getDocDom() { return jsdom.jsdom(fs.readFileSync(path.join(grunt.config.get('tmpdir'), 'index.html')).toString()); }
javascript
{ "resource": "" }
q12394
getExtension
train
function getExtension(file) { var ret; if (file) { var fileTypes = file.split('.'); var len = fileTypes.length; if (0 === len) { return ret; } ret = fileTypes[len - 1]; return ret; } }
javascript
{ "resource": "" }
q12395
getScriptElements
train
function getScriptElements($typeLazy) { var scripts; var src = $typeLazy.attr("src"); if ("js" === getExtension(src).toLowerCase()) { return $typeLazy; } else { src = path.join(grunt.config.get('tmpdir'), src); if (fs.existsSync(src)) { scripts = jsdom.jsdom(fs.readFileSync(src).toString()); return $(scripts).find("script"); } else { return $(); } } }
javascript
{ "resource": "" }
q12396
prepareAppScriptsInfo
train
function prepareAppScriptsInfo(docDom) { // read index file, and getting target ts files. var appScripts = []; var $appScripts = $(docDom).find('script[type="lazy"]'); var findAppJs = false; $appScripts.each(function () { var $scripts = getScriptElements($(this)); $scripts.each(function () { var src = $(this).attr('src'); if (src.match(/app.js$/i)) { findAppJs = true; } appScripts.push(path.join(grunt.config.get('tmpdir'), src).replace(/\.js$/i, '.ts')); }); }); if (!findAppJs) { grunt.config.set('app_js_suffix', '-all'); } // set app_scripts grunt.config.set('app_scripts', appScripts); }
javascript
{ "resource": "" }
q12397
deployToSim
train
function deployToSim(appPath, target) { // Select target device for emulator. Default is 'iPhone-6' if (!target) { return require('./list-emulator-images').run() .then(function (emulators) { if (emulators.length > 0) { target = emulators[0]; } emulators.forEach(function (emulator) { if (emulator.indexOf('iPhone') === 0) { target = emulator; } }); events.emit('log','No target specified for emulator. Deploying to ' + target + ' simulator'); return startSim(appPath, target); }); } else { return startSim(appPath, target); } }
javascript
{ "resource": "" }
q12398
prepareCssModulesInfo
train
function prepareCssModulesInfo(docDom) { var cssModule = { name: '' }, cssModulesInfo = []; $(docDom).find('link[rel="stylesheet"]') .filter(function () { if (grunt.config.get('lib_kind_fileter_enable')) { var type = path.join(grunt.config.get('lib_kind'), grunt.config.get('stylesheets')); var regexp = new RegExp('^' + type + '\/', 'i'); return $(this).attr('href').match(regexp) ? true : false; } else { return true; } }) .each(function () { var href = $(this).attr('href'); var name = href.slice(href.lastIndexOf('/') + 1, href.length).replace(/\.css$/i, ''); cssModule = { name: name, version: $(this).attr('data-version'), }; cssModulesInfo.push(cssModule); }); // set lib_css_modules_info grunt.config.set('lib_css_modules_info', cssModulesInfo); }
javascript
{ "resource": "" }
q12399
lowerScriptsInfo
train
function lowerScriptsInfo(docDom) { // read index file, and getting target ts files. var $scripts = $(docDom).find('script[src]'); $scripts.each(function () { $(this).attr('src', function (idx, path) { return path.toLowerCase(); }); }); }
javascript
{ "resource": "" }