_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q54300
train
function (err, pStatus) { if (err) { log.error(that._name + " - Could not get player status- " + err); } else { that._playerStatus(pStatus); } }
javascript
{ "resource": "" }
q54301
train
function(err, content_name, parsed_content, modified_date) { if (!err) { parsed_contents[content_name] = parsed_content; if (modified_date > last_modified) { last_modified = modified_date; } } if (content_files.length) { return parseFile(content_files.pop(), parse_file_callback); } else { return callback(null, parsed_contents, last_modified); } }
javascript
{ "resource": "" }
q54302
train
function(callback) { var self = this; var sections = [Path.join("/")]; var paths_to_traverse = []; var should_exclude = function(entry) { return entry[0] === "." || entry[0] === "_" || entry === "shared"; }; var traverse_path = function() { var current_path = paths_to_traverse.shift() || ""; Fs.readdir(Path.join(self.contentDir, current_path), function(err, entries) { if (err) { throw err; } var run_callbacks = function() { if (entries.length) { return next_entry(); } else if (paths_to_traverse.length) { return traverse_path(); } else { return callback(sections); } }; var next_entry = function() { var current_entry = entries.shift(); if (should_exclude(current_entry)) { return run_callbacks(); } var current_entry_path = Path.join(current_path, current_entry); Fs.stat(Path.join(self.contentDir, current_entry_path), function(err, stat) { if (err) { return run_callbacks(); } if (stat.isDirectory()) { sections.push(Path.join("/",current_entry_path)); paths_to_traverse.push(current_entry_path); } return run_callbacks(); }); }; return run_callbacks(); }); }; return traverse_path(); }
javascript
{ "resource": "" }
q54303
train
function(basePath, output_extension, options, callback) { var self = this; var collected_contents = {}; var content_options = {}; var last_modified = null; // treat files with special output extensions if (output_extension !== ".html") { basePath = basePath + output_extension; } self.getContent(basePath, function(err, contents, modified_date) { if (!err) { collected_contents = _.extend(collected_contents, contents); last_modified = modified_date; var run_callback = function() { return callback(null, collected_contents, content_options, last_modified); }; //fetch shared content self.getSharedContent(function(err, shared_content, shared_modified_date) { if (!err) { collected_contents = _.extend(shared_content, collected_contents); if (shared_modified_date > last_modified) { last_modified = shared_modified_date; } } return run_callback(); }); } else { return callback("[Error: Content for " + basePath + " not found]", null, null, {}); } }); }
javascript
{ "resource": "" }
q54304
start
train
function start(app) { /** * Create HTTP server. */ const config = require('./config')(); port = normalizePort(config.get('port')); server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ app.set('port', port); server.listen(port); server.on('error', onError); server.on('listening', onListening); return server; }
javascript
{ "resource": "" }
q54305
estimatedNumberOfRows
train
function estimatedNumberOfRows(node, context, callback) { var sql = estimatedCountTemplate({ sourceQuery: node.sql() }); context.runSQL(sql, function(err, resultSet){ var estimated_rows = null; if (!err) { if (resultSet.rows) { estimated_rows = resultSet.rows[0]['QUERY PLAN'][0].Plan['Plan Rows']; } else { // If we get no results (e.g. working with a fake db) // we make a most permissive estimate estimated_rows = 0; } } return callback(err, estimated_rows); }); }
javascript
{ "resource": "" }
q54306
numberOfRows
train
function numberOfRows(node, context, callback) { var sql = exactCountTemplate({ sourceQuery: node.sql() }); context.runSQL(sql, function(err, resultSet){ var counted_rows = null; if (!err) { counted_rows = resultSet.rows[0].result_rows; } return callback(err, counted_rows); }); }
javascript
{ "resource": "" }
q54307
numberOfDistinctValues
train
function numberOfDistinctValues(node, context, columnName, callback) { var sql = countDistinctValuesTemplate({ source: node.sql(), column: columnName }); context.runSQL(sql, function(err, resultSet){ var number = null; if (!err) { number = resultSet.rows[0].count_distict_values; } return callback(err, number); }); }
javascript
{ "resource": "" }
q54308
train
function(parallels = 1) { this._parallels = parallels || 1; /** * _queueCounter * each lock() increased this number * each unlock() decreases this number * If _qC==0, the state is in idle * @type {Number} */ this._qC = 0; /** * _idleCalls * contains all promises that where added via requestIdlePromise() * and not have been resolved * @type {Set<Promise>} _iC with oldest promise first */ this._iC = new Set(); /** * _lastHandleNumber * @type {Number} */ this._lHN = 0; /** * _handlePromiseMap * Contains the handleNumber on the left * And the assigned promise on the right. * This is stored so you can use cancelIdleCallback(handleNumber) * to stop executing the callback. * @type {Map<Number><Promise>} */ this._hPM = new Map(); this._pHM = new Map(); // _promiseHandleMap }
javascript
{ "resource": "" }
q54309
_resolveOneIdleCall
train
function _resolveOneIdleCall(idleQueue) { if (idleQueue._iC.size === 0) return; const iterator = idleQueue._iC.values(); const oldestPromise = iterator.next().value; oldestPromise._manRes(); // try to call the next tick setTimeout(() => _tryIdleCall(idleQueue), 0); }
javascript
{ "resource": "" }
q54310
_removeIdlePromise
train
function _removeIdlePromise(idleQueue, promise) { if (!promise) return; // remove timeout if exists if (promise._timeoutObj) clearTimeout(promise._timeoutObj); // remove handle-nr if exists if (idleQueue._pHM.has(promise)) { const handle = idleQueue._pHM.get(promise); idleQueue._hPM.delete(handle); idleQueue._pHM.delete(promise); } // remove from queue idleQueue._iC.delete(promise); }
javascript
{ "resource": "" }
q54311
_tryIdleCall
train
function _tryIdleCall(idleQueue) { // ensure this does not run in parallel if (idleQueue._tryIR || idleQueue._iC.size === 0) return; idleQueue._tryIR = true; // w8 one tick setTimeout(() => { // check if queue empty if (!idleQueue.isIdle()) { idleQueue._tryIR = false; return; } /** * wait 1 tick here * because many functions do IO->CPU->IO * which means the queue is empty for a short time * but the ressource is not idle */ setTimeout(() => { // check if queue still empty if (!idleQueue.isIdle()) { idleQueue._tryIR = false; return; } // ressource is idle _resolveOneIdleCall(idleQueue); idleQueue._tryIR = false; }, 0); }, 0); }
javascript
{ "resource": "" }
q54312
train
function(view, config) { var formInputs = getForm(view); formInputs = _.reject(formInputs, function(el) { var reject; var myType = getElementType(el); var extractor = config.keyExtractors.get(myType); var identifier = extractor($(el)); var foundInIgnored = _.find(config.ignoredTypes, function(ignoredTypeOrSelector) { return (ignoredTypeOrSelector === myType) || $(el).is(ignoredTypeOrSelector); }); var foundInInclude = _.includes(config.include, identifier); var foundInExclude = _.includes(config.exclude, identifier); if (foundInInclude) { reject = false; } else { if (config.include) { reject = true; } else { reject = (foundInExclude || foundInIgnored); } } return reject; }); return formInputs; }
javascript
{ "resource": "" }
q54313
train
function(options) { var config = _.clone(options) || {}; config.ignoredTypes = _.clone(Syphon.ignoredTypes); config.inputReaders = config.inputReaders || Syphon.InputReaders; config.inputWriters = config.inputWriters || Syphon.InputWriters; config.keyExtractors = config.keyExtractors || Syphon.KeyExtractors; config.keySplitter = config.keySplitter || Syphon.KeySplitter; config.keyJoiner = config.keyJoiner || Syphon.KeyJoiner; config.keyAssignmentValidators = config.keyAssignmentValidators || Syphon.KeyAssignmentValidators; return config; }
javascript
{ "resource": "" }
q54314
getSocketAddressFromURLSafeHostname
train
function getSocketAddressFromURLSafeHostname(hostname) { return __awaiter(this, void 0, void 0, function* () { // IPv4 addresses are fine if (net_1.isIPv4(hostname)) return hostname; // IPv6 addresses are wrapped in [], which need to be removed if (/^\[.+\]$/.test(hostname)) { const potentialIPv6 = hostname.slice(1, -1); if (net_1.isIPv6(potentialIPv6)) return potentialIPv6; } // This is a hostname, look it up try { const address = yield lookupAsync(hostname); // We found an address if (address) return address; } catch (e) { // Lookup failed, continue working with the hostname } return hostname; }); }
javascript
{ "resource": "" }
q54315
lookupAsync
train
function lookupAsync(hostname) { return new Promise((resolve, reject) => { dns.lookup(hostname, { all: true }, (err, addresses) => { if (err) return reject(err); resolve(addresses[0].address); }); }); }
javascript
{ "resource": "" }
q54316
padStart
train
function padStart(str, targetLen, fill = " ") { // simply return strings that are long enough to not be padded if (str != null && str.length >= targetLen) return str; // make sure that <fill> isn't empty if (fill == null || fill.length < 1) throw new Error("fill must be at least one char"); // figure out how often we need to repeat <fill> const missingLength = targetLen - str.length; const repeats = Math.ceil(missingLength / fill.length); return fill.repeat(repeats).substr(0, missingLength) + str; }
javascript
{ "resource": "" }
q54317
train
function(dashed) { var i; var camel = ''; var nextCap = false; for (i = 0; i < dashed.length; i++) { if (dashed[i] !== '-') { camel += nextCap ? dashed[i].toUpperCase() : dashed[i]; nextCap = false; } else { nextCap = true; } } return camel; }
javascript
{ "resource": "" }
q54318
train
function(str) { var deliminator_stack = []; var length = str.length; var i; var parts = []; var current_part = ''; var opening_index; var closing_index; for (i = 0; i < length; i++) { opening_index = opening_deliminators.indexOf(str[i]); closing_index = closing_deliminators.indexOf(str[i]); if (is_space.test(str[i])) { if (deliminator_stack.length === 0) { if (current_part !== '') { parts.push(current_part); } current_part = ''; } else { current_part += str[i]; } } else { if (str[i] === '\\') { i++; current_part += str[i]; } else { current_part += str[i]; if ( closing_index !== -1 && closing_index === deliminator_stack[deliminator_stack.length - 1] ) { deliminator_stack.pop(); } else if (opening_index !== -1) { deliminator_stack.push(opening_index); } } } } if (current_part !== '') { parts.push(current_part); } return parts; }
javascript
{ "resource": "" }
q54319
train
function(value) { var i; for (i = value; i < this._length; i++) { delete this[i]; } this._length = value; }
javascript
{ "resource": "" }
q54320
train
function(cmdfunc) { var outfunc = function(msg, reply, meta) { if ('save' !== msg.cmd) { if (null == msg.q) { msg.q = {} if (null != msg.id) { msg.q.id = msg.id delete msg.id } } if (null == msg.qent) { msg.qent = this.make$({ entity$: { name: msg.name, base: msg.base, zone: msg.zone } }) } } if (null != msg.ent && 'function' != typeof msg.ent.canon$) { msg.ent = this.make$({ entity$: { name: msg.name, base: msg.base, zone: msg.zone } }).data$(msg.ent) } return cmdfunc.call(this, msg, reply, meta) } return outfunc }
javascript
{ "resource": "" }
q54321
train
function (err) { //if any error happened in the previous tasks, exit with a code > 0 if (err) { var exitCode = 2; console.log('[ERROR] gulp build task failed', err); console.log('[FAIL] gulp build task failed - exiting with code ' + exitCode); return process.exit(exitCode); } else { return callback(); } }
javascript
{ "resource": "" }
q54322
splitWords
train
function splitWords(str) { return str // insert a space between lower & upper .replace(/([a-z])([A-Z])/g, '$1 $2') // space before last upper in a sequence followed by lower .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3') // uppercase the first character .replace(/^./, function(str){ return str.toUpperCase(); }) }
javascript
{ "resource": "" }
q54323
train
function (stream, state) { var plannedToken = state.plannedTokens.shift(); if (plannedToken === undefined) { return null; } stream.match(plannedToken.value); var tokens = plannedToken.type.split('.'); return cmTokenFromAceTokens(tokens); }
javascript
{ "resource": "" }
q54324
configureConfigFile
train
function configureConfigFile(err, result) { for (var key in result) { if (key === 'port' && !result[key] || key === 'port' && result[key] !== result[key]) { shell.echo('exports.' + key + ' = 8080' + '\n').toEnd(clientFiles.config) } else { shell.echo('exports.' + key + ' = ' + JSON.stringify(result[key]) + '\n').toEnd(clientFiles.config) } } if (err) { return onErr(err) } console.log(chalk.yellow('Here\'s what I\'ve got down, if something is wrong you can edit this in your enclave.js file.:')) console.log(chalk.red(' entry: ') + chalk.magenta(result.entry)) console.log(chalk.red(' output: ') + chalk.magenta(result.output)) console.log(!result.port ? chalk.red(' port: 8080') : chalk.red(' port: ') + chalk.magenta(result.port)) console.log(chalk.red(' index: ') + chalk.magenta(result.index)) console.log(chalk.red(' autoInstall: ') + chalk.magenta(result.autoInstall)) console.log(chalk.red(' live: ') + chalk.magenta(result.live)) console.log(chalk.green('To run your app, just type'), chalk.green.bold('$ npm run enclave-serve')) shell.sed(insertScript.flag, insertScript.insertionPoint, insertScript.addition, insertScript.file) preventFinishFor(5000) }
javascript
{ "resource": "" }
q54325
train
function (value) { if (typeof value === 'object' && value !== null) { if (_.size(value) <= 2 && _.all(value, function (v, k) { return typeof k === 'string' && k.substr(0, 1) === '$'; })) { for (var i = 0; i < builtinConverters.length; i++) { var converter = builtinConverters[i]; if (converter.matchJSONValue(value)) { return converter.fromJSONValue(value); } } } } return value; }
javascript
{ "resource": "" }
q54326
SetConfigNodeConnectionListeners
train
function SetConfigNodeConnectionListeners(node) { node.clientNode.rtmClient.on("connecting", () => { node.status(statuses.connecting); }); node.clientNode.rtmClient.on("ready", () => { node.status(statuses.connected); }); node.clientNode.rtmClient.on("disconnected", e => { var status = statuses.disconnected; /** * { * code: 'slackclient_platform_error', * data: { ok: false, error: 'invalid_auth' } * } */ if (e.code == "slackclient_platform_error" && e.data.ok === false) { status.text = e.data.error; } node.status(status); }); /** * if connectivity is dropped we go from connected -> reconnecting * directly bypassing disconnected */ node.clientNode.rtmClient.on("reconnecting", () => { node.status(statuses.disconnected); }); }
javascript
{ "resource": "" }
q54327
SlackState
train
function SlackState(n) { RED.nodes.createNode(this, n); var node = this; this.client = n.client; this.clientNode = RED.nodes.getNode(this.client); node.status(statuses.disconnected); if (node.client) { SetConfigNodeConnectionListeners(node); node.on("input", function(msg) { SlackDebug("slack-state incomiming message", msg); node.status(statuses.sending); /** * support for forcing a refresh of data */ if (msg.payload === true) { node.clientNode .refreshState() .then(() => { msg.slackState = node.clientNode.state; node.send(msg); node.status(statuses.connected); }) .catch(e => { SlackDebug("slack-state error response", e.data); msg.payload = e.data; node.send(msg); node.status(statuses.connected); }); } else { msg.slackState = node.clientNode.state; node.send(msg); node.status(statuses.connected); } }); ["state_initialized"].forEach(eventName => { node.clientNode.on(eventName, e => { node.status(statuses.sending); var msg = {}; switch (eventName) { case "state_initialized": eventName = "ready"; break; } msg.slackState = node.clientNode.state; msg.payload = { type: eventName }; node.send([null, msg]); node.status(statuses.connected); }); }); } else { node.status(statuses.misconfigured); } }
javascript
{ "resource": "" }
q54328
moneyBuyDescriptionHandler
train
function moneyBuyDescriptionHandler(descriptions, position) { descriptions.each(function (i) { $(this).removeClass('show-money-buy-copy'); if (position === i + 1) { $(this).addClass('show-money-buy-copy'); } }) }
javascript
{ "resource": "" }
q54329
onYouTubePlayerAPIReady
train
function onYouTubePlayerAPIReady() { // Loop through each iframe video on the page jQuery( "iframe.copy-video__video").each(function (index) { // Create IDs dynamically var iframeID = "js-copy-video-" + index; var buttonID = "js-copy-video-" + index + "__button"; // Set IDs jQuery(this).attr('id', iframeID); jQuery(this).next('button.copy-video__button').attr('id', buttonID); // Associate video player with button via index players[buttonID] = { player: null, } // Set-up a player object for each video players[buttonID].player = new YT.Player(iframeID, { events: { 'onReady': onPlayerReady } }); }); }
javascript
{ "resource": "" }
q54330
getProcessedData
train
async function getProcessedData(url) { let data; try { data = await downloadData(url); } catch (error) { data = await downloadFallbackData(url); } return processDataInWorker(data); }
javascript
{ "resource": "" }
q54331
regexpForFunctionCall
train
function regexpForFunctionCall(fnName, args) { const optionalWhitespace = '\\s*'; const argumentParts = args.map( arg => optionalWhitespace + arg + optionalWhitespace ); let parts = [fnName, '\\(', argumentParts.join(','), '\\)']; return new RegExp(parts.join(''), 'g'); }
javascript
{ "resource": "" }
q54332
stringifyParams
train
function stringifyParams (obj) { return obj ? arrayMap(objectKeys(obj).sort(), function (key) { var val = obj[key] if (angular.isArray(val)) { return arrayMap(val.sort(), function (val2) { return encodeURIComponent(key) + '=' + encodeURIComponent(val2) }).join('&') } return encodeURIComponent(key) + '=' + encodeURIComponent(val) }).join('&') : '' }
javascript
{ "resource": "" }
q54333
Thumbnailer
train
function Thumbnailer (opts) { // for the benefit of testing // perform dependency injection. _.extend(this, { tmp: require('tmp'), logger: require(config.get('logger')) }, opts) }
javascript
{ "resource": "" }
q54334
Worker
train
function Worker (opts) { _.extend(this, { grabber: null, saver: null, logger: require(config.get('logger')) }, opts) this.sqs = new aws.SQS({ accessKeyId: config.get('awsKey'), secretAccessKey: config.get('awsSecret'), region: config.get('awsRegion') }) config.set('sqsQueueUrl', this.sqs.endpoint.protocol + '//' + this.sqs.endpoint.hostname + '/' + config.get('sqsQueue')) }
javascript
{ "resource": "" }
q54335
Client
train
function Client (opts) { // update client instance and config // with overrides from opts. _.extend(this, { Saver: require('./saver').Saver }, opts) config.extend(opts) // allow sqs to be overridden // in tests. if (opts && opts.sqs) { this.sqs = opts.sqs delete opts.sqs } else { this.sqs = new aws.SQS({ accessKeyId: config.get('awsKey'), secretAccessKey: config.get('awsSecret'), region: config.get('awsRegion') }) } config.set('sqsQueueUrl', this.sqs.endpoint.protocol + '//' + this.sqs.endpoint.hostname + '/' + config.get('sqsQueue')) }
javascript
{ "resource": "" }
q54336
buildOpts
train
function buildOpts (keys) { var opts = {} var pairs = _.pairs(keys) for (var i in pairs) { var argvKey = pairs[i][0] var envKey = argvKey.toUpperCase() var configKey = pairs[i][1] opts[configKey] = argv[argvKey] || config.get(configKey) if (opts[configKey] === null) { throw Error("The environment variable '" + envKey + "', or command line parameter '--" + argvKey + "' must be set.") } } return opts }
javascript
{ "resource": "" }
q54337
SymbolicLinkFinder
train
function SymbolicLinkFinder(options) { this.scanDirs = options && options.scanDirs || ['.']; this.extensions = options && options.extensions || ['.js']; this.ignore = options && options.ignore || null; }
javascript
{ "resource": "" }
q54338
train
function(buildConfig, path) { ensureBlacklistsComputed(buildConfig); var buildConfigBlacklistRE = buildConfig.blacklistRE; var internalDependenciesBlacklistRE = buildConfig._reactPageBlacklistRE; if (BLACKLIST_FILE_EXTS_RE.test(path) || buildConfig._middlewareBlacklistRE.test(path) || internalDependenciesBlacklistRE.test(path) || buildConfigBlacklistRE && buildConfigBlacklistRE.test(path) || buildConfig.ignorePaths && buildConfig.ignorePaths(path)) { return true; } return false; }
javascript
{ "resource": "" }
q54339
requireLazy
train
function requireLazy(dependencies, factory, context) { return define( dependencies, factory, undefined, REQUIRE_WHEN_READY, context, 1 ); }
javascript
{ "resource": "" }
q54340
train
function(id, deps, factory, _special) { define(id, deps, factory, _special || USED_AS_TRANSPORT); }
javascript
{ "resource": "" }
q54341
requireUnsee
train
function requireUnsee(module) { if (window.requirejs.has(module)) { window.requirejs.unsee(module); } }
javascript
{ "resource": "" }
q54342
rm
train
function rm(filepath, callback) { var killswitch = false; fs.stat(filepath, function(err, stat) { if (err) return callback(err); if (stat.isFile()) return fs.unlink(filepath, callback); if (!stat.isDirectory()) return callback(new Error('Unrecognized file.')); Step(function() { fs.readdir(filepath, this); }, function(err, files) { if (err) throw err; if (files.length === 0) return this(null, []); var group = this.group(); _(files).each(function(file) { rm(path.join(filepath, file), group()); }); }, function(err) { if (err) return callback(err); fs.rmdir(filepath, callback); }); }); }
javascript
{ "resource": "" }
q54343
forcelink
train
function forcelink(src, dest, options, callback) { if (!options || !options.cache) throw new Error('options.cache not defined!'); if (!callback) throw new Error('callback not defined!'); // uses relative path if linking to cache dir if (path.relative) { src = path.relative(options.cache, dest).slice(0, 2) !== '..' ? path.relative(path.dirname(dest), src) : src; } fs.lstat(dest, function(err, stat) { // Error. if (err && err.code !== 'ENOENT') { return callback(err); } // Path does not exist. Symlink. if (err && err.code === 'ENOENT') { if (env == 'development') console.error("[millstone] linking '" + dest + "' -> '" + src + "'"); return fs.symlink(src, dest, callback); } // Path exists and is not a symlink. Do nothing. if (!stat.isSymbolicLink()) { if (env == 'development') console.error("[millstone] skipping re-linking '" + src + "' because '" + dest + " is already an existing file"); return callback(); } // Path exists and is a symlink. Check existing link path and update if necessary. // NOTE : broken symlinks will pass through this step fs.readlink(dest, function(err, old) { if (err) return callback(err); if (old === src) return callback(); fs.unlink(dest, function(err) { if (err) return callback(err); if (env == 'development') console.error("[millstone] re-linking '" + dest + "' -> '" + src + "'"); fs.symlink(src, dest, callback); }); }); }); }
javascript
{ "resource": "" }
q54344
localize
train
function localize(url, options, callback) { existsAsync(options.filepath, function(exists) { if (exists) { var re_download = false; // unideal workaround for frequently corrupt/partially downloaded zips // https://github.com/mapbox/millstone/issues/85 if (path.extname(options.filepath) == '.zip') { try { var zf = new zipfile.ZipFile(options.filepath); if (zf.names.length < 1) { throw new Error("could not find any valid data in zip archive: '" + options.filepath + "'"); } } catch (e) { if (env == 'development') console.error('[millstone] could not open zip archive: "' + options.filepath + '" attempting to re-download from "'+url+"'"); re_download = true; } } if (!re_download) { return callback(null, options.filepath); } } var dir_path = path.dirname(options.filepath); mkdirp(dir_path, 0755, function(err) { if (err && err.code !== 'EEXIST') { if (env == 'development') console.error('[millstone] could not create directory: ' + dir_path); callback(err); } else { download(url, options, function(err, filepath) { if (err) return callback(err); callback(null, filepath); }); } }); }); }
javascript
{ "resource": "" }
q54345
cachepath
train
function cachepath(location) { var uri = url.parse(location); if (!uri.protocol) { throw new Error('Invalid URL: ' + location); } else { var hash = crypto.createHash('md5') .update(location) .digest('hex') .substr(0,8) + '-' + path.basename(uri.pathname, path.extname(uri.pathname)); var extname = path.extname(uri.pathname); return _(['.shp', '.zip', '']).include(extname.toLowerCase()) ? path.join(hash, hash + extname) : path.join(hash + extname); } }
javascript
{ "resource": "" }
q54346
metapath
train
function metapath(filepath) { return path.join(path.dirname(filepath), '.' + path.basename(filepath)); }
javascript
{ "resource": "" }
q54347
readExtension
train
function readExtension(file, cb) { fs.readFile(metapath(file), 'utf-8', function(err, data) { if (err) { if (err.code === 'ENOENT') return cb(new Error('Metadata file does not exist.')); return cb(err); } try { var ext = guessExtension(JSON.parse(data)); if (ext) { if (env == 'development') console.error("[millstone] detected extension of '" + ext + "' for '" + file + "'"); } return cb(null, ext); } catch (e) { return cb(e); } }); }
javascript
{ "resource": "" }
q54348
fixSRS
train
function fixSRS(obj) { if (!obj.srs) return; var normalized = _(obj.srs.split(' ')).chain() .select(function(s) { return s.indexOf('=') > 0; }) .sortBy(function(s) { return s; }) .reduce(function(memo, s) { var key = s.split('=')[0]; var val = s.split('=')[1]; if (val === '0') val = '0.0'; memo[key] = val; return memo; }, {}) .value(); var legacy = { '+a': '6378137', '+b': '6378137', '+lat_ts': '0.0', '+lon_0': '0.0', '+proj': 'merc', '+units': 'm', '+x_0': '0.0', '+y_0': '0.0' }; if (!_(legacy).chain() .reject(function(v, k) { return normalized[k] === v; }) .size() .value()) obj.srs = SRS['900913']; }
javascript
{ "resource": "" }
q54349
localizeCartoURIs
train
function localizeCartoURIs(s,cb) { // Get all unique URIs in stylesheet // TODO - avoid finding non url( uris? var matches = s.data.match(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi); var URIs = _.uniq(matches || []); var CartoURIs = []; // remove any matched urls that are not clearly // part of a carto style // TODO - consider moving to carto so we can also avoid // downloading commented out code URIs.forEach(function(u) { var idx = s.data.indexOf(u); if (idx > -1) { var pre_url = s.data.slice(idx-5,idx); if (pre_url.indexOf('url(') > -1) { CartoURIs.push(u); // Update number of async calls so that we don't // call this() too soon (before everything is done) remaining += 1; } } }); CartoURIs.forEach(function(u) { var uri = url.parse(encodeURI(u)); // URL. if (uri.protocol && (uri.protocol == 'http:' || uri.protocol == 'https:')) { var filepath = path.join(cache, cachepath(u)); localize(uri.href, {filepath:filepath,name:s.id}, function(err, file) { if (err) { cb(err); } else { var extname = path.extname(file); if (!extname) { readExtension(file, function(error, ext) { // note - we ignore any readExtension errors if (ext) { var new_filename = file + ext; fs.rename(file, new_filename, function(err) { s.data = s.data.split(u).join(new_filename); cb(err); }); } else { s.data = s.data.split(u).join(file); cb(err); } }); } else { s.data = s.data.split(u).join(file); cb(err); } } }); } else { cb(); } }); cb(); }
javascript
{ "resource": "" }
q54350
indexOf
train
function indexOf(haystack, needle, i) { if (!Buffer.isBuffer(needle)) needle = new Buffer(needle); if (typeof i === 'undefined') i = 0; var l = haystack.length - needle.length + 1; while (i<l) { var good = true; for (var j=0, n=needle.length; j<n; j++) { if (haystack[i+j] !== needle[j]) { good = false; break; } } if (good) return i; i++; } return -1; }
javascript
{ "resource": "" }
q54351
hashPassword
train
function hashPassword (passport, next) { if (passport.password) { bcrypt.hash(passport.password, 10, function (err, hash) { passport.password = hash; next(err, passport); }); } else { next(null, passport); } }
javascript
{ "resource": "" }
q54352
train
function(target, key, value, receiver) { // If the receiver is not this observable (the observable might be on the proto chain), // set the key on the reciever. if (receiver !== this.proxy) { return makeObject.setKey(receiver, key, value, this); } // If it has a defined property definiition var computedValue = computedHelpers.set(receiver, key, value); if(computedValue === true ) { return true; } // Gets the observable value to set. value = makeObject.getValueToSet(key, value, this); var startingLength = target.length; // Sets the value on the target. If there // is a change, calls the callback. makeObject.setValueAndOnChange(key, value, this, function(key, value, meta, hadOwn, old) { // Determine the patches this change should dispatch var patches = [{ key: key, type: hadOwn ? "set" : "add", value: value }]; var numberKey = !isSymbolLike(key) && +key; // If we are adding an indexed value like `arr[5] =value` ... if ( isInteger(numberKey) ) { // If we set an enumerable property after the length ... if (!hadOwn && numberKey > startingLength) { // ... add patches for those values. patches.push({ index: startingLength, deleteCount: 0, insert: target.slice(startingLength), type: "splice" }); } else { // Otherwise, splice the value into the array. patches.push.apply(patches, mutateMethods.splice(target, [numberKey, 1, value])); } } // In the case of deleting items by setting the length of the array, // add patches that splice the items removed. // (deleting individual items from an array doesn't change the length; it just creates holes) if (didLengthChangeCauseDeletions(key, value, old, meta)) { patches.push({ index: value, deleteCount: old - value, insert: [], type: "splice" }); } //!steal-remove-start var reasonLog = [canReflect.getName(meta.proxy)+" set", key,"to", value]; //!steal-remove-end var dispatchArgs = { type: key, patches: patches, keyChanged: !hadOwn ? key : undefined }; //!steal-remove-start if(process.env.NODE_ENV !== 'production') { dispatchArgs.reasonLog = reasonLog; } //!steal-remove-end mapBindings.dispatch.call( meta.proxy, dispatchArgs, [value, old]); }); return true; }
javascript
{ "resource": "" }
q54353
getStoredToken
train
function getStoredToken (storageLocation) { var token = readCookie(storageLocation); if (!token && (window && window.localStorage || window.sessionStorage)) { token = window.sessionStorage.getItem(storageLocation) || window.localStorage.getItem(storageLocation); } return token; }
javascript
{ "resource": "" }
q54354
hasValidToken
train
function hasValidToken (storageLocation) { var token = getStoredToken(storageLocation); if (token) { try { var payload = decode(token); return payloadIsValid(payload); } catch (error) { return false; } } return false; }
javascript
{ "resource": "" }
q54355
toPairs
train
function toPairs (v) { if (ktypes.isArray(v)) { var pairs = [] var i for (i = 0; i < v.length; i++) { pairs.push([i, v[i]]) } return pairs } return _.toPairs(v) }
javascript
{ "resource": "" }
q54356
train
function (auth) { var clientCredentials = Buffer.from(auth.slice('basic '.length), 'base64').toString().split(':') var clientId = querystring.unescape(clientCredentials[0]) var clientSecret = querystring.unescape(clientCredentials[1]) return { id: clientId, secret: clientSecret } }
javascript
{ "resource": "" }
q54357
train
function(x){ if(!x || x.type !== type){ return false; } if(value){ return x.src === value; } return true; }
javascript
{ "resource": "" }
q54358
getPathToDestination
train
function getPathToDestination(pathToSource, pathToDestinationFile) { var isDestinationDirectory = (/\/$/).test(pathToDestinationFile); var fileName = path.basename(pathToSource); var newPathToDestination; if (typeof pathToDestinationFile === 'undefined') { newPathToDestination = pathToSource; } else { newPathToDestination = pathToDestinationFile + (isDestinationDirectory ? fileName : ''); } return newPathToDestination; }
javascript
{ "resource": "" }
q54359
fixHeaders
train
function fixHeaders(contents) { contents = contents.replace(/x-poedit-keywordslist:/i, 'X-Poedit-KeywordsList:'); contents = contents.replace(/x-poedit-searchpath-/ig, 'X-Poedit-SearchPath-'); contents = contents.replace(/x-poedit-searchpathexcluded-/ig, 'X-Poedit-SearchPathExcluded-'); contents = contents.replace(/x-poedit-sourcecharset:/i, 'X-Poedit-SourceCharset:'); return contents; }
javascript
{ "resource": "" }
q54360
normalizeForComparison
train
function normalizeForComparison(pot) { var clone = _.cloneDeep(pot); if (!pot) { return pot; } // Normalize the content type case. clone.headers['content-type'] = clone.headers['content-type'].toLowerCase(); // Blank out the dates. clone.headers['pot-creation-date'] = ''; clone.headers['po-revision-date'] = ''; // Blank out the headers in the translations object. These are used for // reference only and won't be compiled, so they shouldn't be used when // comparing POT objects. clone.translations['']['']['msgstr'] = ''; return clone; }
javascript
{ "resource": "" }
q54361
Pot
train
function Pot(filename) { if (! (this instanceof Pot)) { return new Pot(filename); } this.isOpen = false; this.filename = filename; this.contents = ''; this.initialDate = ''; this.fingerprint = ''; }
javascript
{ "resource": "" }
q54362
train
function(file, args) { return new Promise(function(resolve, reject) { var child = spawn(file, args, { stdio: 'inherit' }); child.on('error', reject); child.on('close', resolve); }); }
javascript
{ "resource": "" }
q54363
updatePoFiles
train
function updatePoFiles(filename, pattern) { var merged = []; var searchPath = path.dirname(filename); pattern = pattern || '*.po'; glob.sync(pattern, { cwd: path.dirname(filename) }).forEach(function(file) { var poFile = path.join(searchPath, file); merged.push(mergeFiles(filename, poFile)); }); return Promise.all(merged); }
javascript
{ "resource": "" }
q54364
guessSlug
train
function guessSlug(wpPackage) { var directory = wpPackage.getPath(); var slug = path.basename(directory); var slug2 = path.basename(path.dirname(directory)); if ('trunk' === slug || 'src' === slug) { slug = slug2; } else if (-1 !== ['branches', 'tags'].indexOf(slug2)) { slug = path.basename(path.dirname(path.dirname(directory))); } return slug; }
javascript
{ "resource": "" }
q54365
findMainFile
train
function findMainFile(wpPackage) { if (wpPackage.isType('wp-theme')) { return 'style.css'; } var found = ''; var pluginFile = guessSlug(wpPackage) + '.php'; var filename = wpPackage.getPath(pluginFile); // Check if the main file exists. if (util.fileExists(filename) && wpPackage.getHeader('Plugin Name', filename)) { return pluginFile; } // Search for plugin headers in php files in the main directory. glob.sync('*.php', { cwd: wpPackage.getPath() }).forEach(function(file) { var filename = wpPackage.getPath(file); if (wpPackage.getHeader('Plugin Name', filename)) { found = file; } }); return found; }
javascript
{ "resource": "" }
q54366
WPPackage
train
function WPPackage(directory, type) { if (!(this instanceof WPPackage)) { return new WPPackage(directory, type); } this.directory = null; this.domainPath = null; this.mainFile = null; this.potFile = null; this.type = 'wp-plugin'; this.initialize(directory, type); }
javascript
{ "resource": "" }
q54367
train
function(o) { for (i in o) { if (!!o[i] && typeof(o[i]) == "object") { if (!o[i].length && o[i].type === 'tag') { nodeCount += 1; o[i]._id = nodeCount; } traverseIds(o[i]); } } }
javascript
{ "resource": "" }
q54368
GitkitClient
train
function GitkitClient(options) { this.widgetUrl = options.widgetUrl; this.maxTokenExpiration = 86400 * 30; // 30 days this.audiences = []; if (options.projectId !== undefined) { this.audiences.push(options.projectId); } if (options.clientId !== undefined) { this.audiences.push(options.clientId); } if (this.audiences.length == 0) { throw new Error("Missing projectId or clientId in server configuration."); } this.authClient = new google.auth.JWT( options.serviceAccountEmail, options.serviceAccountPrivateKeyFile, options.serviceAccountPrivateKey, [GitkitClient.GITKIT_SCOPE], ''); this.certificateCache = null; this.certificateExpiry = null; }
javascript
{ "resource": "" }
q54369
getStudySetup
train
async function getStudySetup() { // shallow copy const studySetup = Object.assign({}, baseStudySetup); studySetup.allowEnroll = await cachingFirstRunShouldAllowEnroll(studySetup); const testingOverrides = await browser.study.getTestingOverrides(); studySetup.testing = { variationName: testingOverrides.variationName, firstRunTimestamp: testingOverrides.firstRunTimestamp, expired: testingOverrides.expired, }; return studySetup; }
javascript
{ "resource": "" }
q54370
sendTelemetry
train
async function sendTelemetry(payload) { utilsLogger.debug("called sendTelemetry payload"); function throwIfInvalid(obj) { // Check: all keys and values must be strings, for (const k in obj) { if (typeof k !== "string") throw new ExtensionError(`key ${k} not a string`); if (typeof obj[k] !== "string") throw new ExtensionError(`value ${k} ${obj[k]} not a string`); } return true; } throwIfInvalid(payload); return studyUtils.telemetry(payload); }
javascript
{ "resource": "" }
q54371
onEveryExtensionLoad
train
async function onEveryExtensionLoad() { new StudyLifeCycleHandler(); const studySetup = await getStudySetup(); await browser.study.logger.log(["Study setup: ", studySetup]); await browser.study.setup(studySetup); }
javascript
{ "resource": "" }
q54372
createLogger
train
function createLogger(prefix, maxLogLevelPref, maxLogLevel = "warn") { const ConsoleAPI = ChromeUtils.import( "resource://gre/modules/Console.jsm", {}, ).ConsoleAPI; return new ConsoleAPI({ prefix, maxLogLevelPref, maxLogLevel, }); }
javascript
{ "resource": "" }
q54373
train
function(csv, options) { // cache settings var separator = options.separator; var delimiter = options.delimiter; // set initial state if it's missing if(!options.state.rowNum) { options.state.rowNum = 1; } if(!options.state.colNum) { options.state.colNum = 1; } // clear initial state var entry = []; var state = 0; var value = ''; function endOfValue() { if(options.onParseValue === undefined) { // onParseValue hook not set entry.push(value); } else { var hook = options.onParseValue(value, options.state); // onParseValue Hook // false skips the value, configurable through a hook if(hook !== false) { entry.push(hook); } } // reset the state value = ''; state = 0; // update global state options.state.colNum++; } // checked for a cached regEx first if(!options.match) { // escape regex-specific control chars var escSeparator = RegExp.escape(separator); var escDelimiter = RegExp.escape(delimiter); // compile the regEx str using the custom delimiter/separator var match = /(D|S|\n|\r|[^DS\r\n]+)/; var matchSrc = match.source; matchSrc = matchSrc.replace(/S/g, escSeparator); matchSrc = matchSrc.replace(/D/g, escDelimiter); options.match = RegExp(matchSrc, 'gm'); } // put on your fancy pants... // process control chars individually, use look-ahead on non-control chars csv.replace(options.match, function (m0) { switch (state) { // the start of a value case 0: // null last value if (m0 === separator) { value += ''; endOfValue(); break; } // opening delimiter if (m0 === delimiter) { state = 1; break; } // skip un-delimited new-lines if (m0 === '\n' || m0 === '\r') { break; } // un-delimited value value += m0; state = 3; break; // delimited input case 1: // second delimiter? check further if (m0 === delimiter) { state = 2; break; } // delimited data value += m0; state = 1; break; // delimiter found in delimited input case 2: // escaped delimiter? if (m0 === delimiter) { value += m0; state = 1; break; } // null value if (m0 === separator) { endOfValue(); break; } // skip un-delimited new-lines if (m0 === '\n' || m0 === '\r') { break; } // broken paser? throw new Error('CSVDataError: Illegal State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']'); // un-delimited input case 3: // null last value if (m0 === separator) { endOfValue(); break; } // skip un-delimited new-lines if (m0 === '\n' || m0 === '\r') { break; } // non-compliant data if (m0 === delimiter) { throw new Error('CSVDataError: Illegal Quote [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']'); } // broken parser? throw new Error('CSVDataError: Illegal Data [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']'); default: // shenanigans throw new Error('CSVDataError: Unknown State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']'); } //console.log('val:' + m0 + ' state:' + state); }); // submit the last value endOfValue(); return entry; }
javascript
{ "resource": "" }
q54374
train
function(t,i,isOver){ var inc = drag.x-drag.l, c = t.c[i], c2 = t.c[i+1]; var w = c.w + inc; var w2= c2.w- inc; //their new width is obtained c.width( w + PX); c2.width(w2 + PX); //and set t.cg.eq(i).width( w + PX); t.cg.eq(i+1).width( w2 + PX); if(isOver){c.w=w; c2.w=w2;} }
javascript
{ "resource": "" }
q54375
train
function(e){ d.unbind('touchend.'+SIGNATURE+' mouseup.'+SIGNATURE).unbind('touchmove.'+SIGNATURE+' mousemove.'+SIGNATURE); $("head :last-child").remove(); //remove the dragging cursor style if(!drag) return; drag.removeClass(drag.t.opt.draggingClass); //remove the grip's dragging css-class var t = drag.t; var cb = t.opt.onResize; //get some values if(drag.x){ //only if the column width has been changed syncCols(t,drag.i, true); syncGrips(t); //the columns and grips are updated if (cb) { e.currentTarget = t[0]; cb(e); } //if there is a callback function, it is fired } if(t.p && S) memento(t); //if postbackSafe is enabled and there is sessionStorage support, the new layout is serialized and stored drag = null; //since the grip's dragging is over }
javascript
{ "resource": "" }
q54376
train
function(){ for(t in tables){ var t = tables[t], i, mw=0; t.removeClass(SIGNATURE); //firefox doesnt like layout-fixed in some cases if (t.w != t.width()) { //if the the table's width has changed t.w = t.width(); //its new value is kept for(i=0; i<t.ln; i++) mw+= t.c[i].w; //the active cells area is obtained //cell rendering is not as trivial as it might seem, and it is slightly different for //each browser. In the begining i had a big switch for each browser, but since the code //was extremelly ugly now I use a different approach with several reflows. This works //pretty well but it's a bit slower. For now, lets keep things simple... for(i=0; i<t.ln; i++) t.c[i].css("width", M.round(1000*t.c[i].w/mw)/10 + "%").l=true; //c.l locks the column, telling us that its c.w is outdated } syncGrips(t.addClass(SIGNATURE)); } }
javascript
{ "resource": "" }
q54377
train
function(oSettings) { //trick to show row numbers for (var i = 0; i < oSettings.aiDisplay.length; i++) { $("td:eq(0)", oSettings.aoData[oSettings.aiDisplay[i]].nTr).html(i + 1); } //Hide pagination when we have a single page var activePaginateButton = false; $(oSettings.nTableWrapper).find(".paginate_button").each(function() { if ($(this).attr("class").indexOf("current") == -1 && $(this).attr("class").indexOf("disabled") == -1) { activePaginateButton = true; } }); if (activePaginateButton) { $(oSettings.nTableWrapper).find(".dataTables_paginate").show(); } else { $(oSettings.nTableWrapper).find(".dataTables_paginate").hide(); } }
javascript
{ "resource": "" }
q54378
getLayers
train
function getLayers(elements) { if (elements.length === 0) { return [[""]]; } const layers = []; layers.push(elements); while (layers[layers.length - 1].length > 1) { layers.push(getNextLayer(layers[layers.length - 1])); } return layers; }
javascript
{ "resource": "" }
q54379
getProof
train
function getProof(index, layers) { let i = index; const proof = layers.reduce((current, layer) => { const pair = getPair(i, layer); if (pair) { current.push(pair); } i = Math.floor(i / 2); // finds the index of the parent of the current node return current; }, []); return proof; }
javascript
{ "resource": "" }
q54380
containsMultipartFormData
train
function containsMultipartFormData(api) { if (_.includes(api.consumes, 'multipart/form-data')) { return true; } var foundMultipartData = false; _.forEach(_.keys(api.paths), function (path) { var pathData = api.paths[path]; _.forEach(_.keys(pathData), function (method) { if (_.includes(pathData[method].consumes, 'multipart/form-data')) { foundMultipartData = true; return; } }); if (foundMultipartData) { return; } }); return foundMultipartData; }
javascript
{ "resource": "" }
q54381
handleMulterConfig
train
function handleMulterConfig(multerConfig, logger, serviceLoader) { // Special handling of storage var storageString = _.get(multerConfig, 'storage'); if (storageString) { var multerStorage; if (storageString === MULTER_MEMORY_STORAGE) { // simple memory storage logger.debug('loading simple multer memoryStorage'); multerStorage = multer.memoryStorage(); } else { // otherwise try and load the service for custom multer storage engine logger.debug('loading custom multer storage service'); var multerService = serviceLoader.get(storageString); if (!multerService) { logger.warn('Multer config "storage" property must either be "' + MULTER_MEMORY_STORAGE + '"'); logger.warn('or the name of a service that returns a multer storage engine'); } else { multerStorage = multerService.storage; } } _.set(multerConfig, 'storage', multerStorage); } return multerConfig; }
javascript
{ "resource": "" }
q54382
setDefaultQueryParams
train
function setDefaultQueryParams(req, data, logger) { var parameters = _.toArray(data.parameters); for (var i = 0; i < parameters.length; i++) { var parm = parameters[i]; if (parm.in === 'query') { if (!_.isUndefined(parm.default) && _.isUndefined(req.query[parm.name])) { req.query[parm.name] = swaggerUtil.cast(parm, parm.default); } } } }
javascript
{ "resource": "" }
q54383
train
function(callback) { var toInit = ['config', 'logger']; loader.loadServices(path.resolve(serverRoot, 'services')); injectDependencies(loader); loader.init(toInit, function(err) { callback(err); }); }
javascript
{ "resource": "" }
q54384
injectDependencies
train
function injectDependencies(serviceLoader) { var EventEmitter = require('events').EventEmitter; serviceLoader.inject('events', new EventEmitter()); //inject itself so that services can directly use the service loader serviceLoader.inject('serviceLoader', serviceLoader); //app will be injected by middleware, so this is a placeholder to force our dependency calculations to be correct serviceLoader.inject('app', {}, ['middleware']); }
javascript
{ "resource": "" }
q54385
train
function (err) { var message = {cmd: 'startupComplete', pid: process.pid}; if (err) { console.warn(err.stack); message.error = err.message; } process.send(message); }
javascript
{ "resource": "" }
q54386
setAuthCodeOnReq
train
function setAuthCodeOnReq(req, res, next) { if (req.query.code) { req.code = req.query.code; debug('Found auth code %s on query param', req.code); return next(); } //look for something like {"code": "..."} if (req.body.code) { req.code = req.body.code; debug('Found auth code %s in JSON body', req.code); return next(); } getRawBody(req, function(err, string) { if (err) { debug(err); } if (string.toString().length > 0) { req.code = string.toString(); debug('Found auth code %s in body', req.code); } next(); }); }
javascript
{ "resource": "" }
q54387
authCodeCallback
train
function authCodeCallback(req, res, next) { var code = req.code; if (!code) { return res.status(400).send('Missing auth code'); } var tokenData = { code: code, client_id: _cfg.clientId, client_secret: _cfg.clientSecret, grant_type: 'authorization_code', redirect_uri: _cfg.redirectURI }; getToken(tokenData, function (err, authData) { if (err) { debug('Error getting new access token: %s', err); return res.sendStatus(401); } else { req.session.auth = authData; if (_cfg.profile === true) { //optional step to get profile data debug('Requesting profile data'); getProfileData(authData.access_token, function(err, data) { if (err) { debug('Error getting profile data: %s', err.message); return next(err); } req.session.auth.profile = data; res.sendStatus(200); }); } else { res.sendStatus(200); } } }); }
javascript
{ "resource": "" }
q54388
signOutUser
train
function signOutUser(req, res, next) { debug('Signing out user'); //make a best attempt effort at revoking the tokens var accessToken = req.session.auth ? req.session.auth.access_token: null; var refreshToken = req.session.auth ? req.session.auth.refresh_token: null; if (accessToken) { debug('Revoking access token'); request.get({ url: LOGOUT_URL, qs: { token: accessToken } }, function(err, response, body) { if (err) { debug('Error revoking access token', err.message); } else { debug('Revoked access token, %s', response.statusCode); } }); } if (refreshToken) { request.get({ url: LOGOUT_URL, qs: { token: refreshToken } }, function (err, response, body) { if (err) { debug('Error revoking refresh token', err.message); } else { debug('Revoked refresh token, %s', response.statusCode); } }); } delete req.session.auth; res.sendStatus(200); }
javascript
{ "resource": "" }
q54389
getToken
train
function getToken(data, callback) { request.post({url: TOKEN_URL, form: data}, function (err, resp, body) { //this would be something like a connection error if (err) { return callback({statusCode: 500, message: err.message}); } if (resp.statusCode !== 200) { //error return callback({statusCode: resp.statusCode, message: JSON.parse(body)}); } else { debug('Got response back from token endpoint', body); /* Body should look like { "access_token": "ya29.UQH0mtJ5M-CNiXc-mDF9II_R7CRzRQm6AmxIc6TjtouR_HxUtg-I1icHJy36e065UUmIL5HIdfBijg", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "1/7EBZ1cWgvFaPji8FNuAcMIGHYj3nHJkNDjb7CSaAPfM", "id_token": "..." } */ var authData = JSON.parse(body); //id_token is a JWT token. Since we're getting this directly from google, no need to authenticate it var idData = jwt.decode(authData.id_token); /* Sample id data { iss: 'accounts.google.com', sub: '103117966615020283234', azp: '107463652566-jo264sjf04n1uk17i2ijdqbs2tuu2rf0.apps.googleusercontent.com', email: 'foo@gmail.com', at_hash: 'qCF-HkLhiGtrHgv6EsPzQQ', email_verified: true, aud: '107463652566-jo264sjf04n1uk17i2ijdqbs2tuu2rf0.apps.googleusercontent.com', iat: 1428691188, exp: 1428694788 } */ return callback(null, { id: idData.sub, email: idData.email, access_token: authData.access_token, expiration: Date.now() + (1000 * authData.expires_in), refresh_token: authData.refresh_token || data.refresh_token }); } }); }
javascript
{ "resource": "" }
q54390
train
function (key, callback) { return client.get(key, function (err, result) { return callback(err, result); }); }
javascript
{ "resource": "" }
q54391
fetchUnmetDependencies
train
function fetchUnmetDependencies() { var runAgain = false; for (var id in dependencyMap) { _.forEach(dependencyMap[id], function (depId) { if (!dependencyMap[depId] && !injectedMap[depId]) { try { loadExternalModule(id, depId); } catch (err) { throw new Error('Error loading dependency ' + depId + ' for ' + id + ': ' + err.message); } runAgain = true; } }); } if (runAgain) { //continue until all we don't have any more unmet dependencies fetchUnmetDependencies(); } }
javascript
{ "resource": "" }
q54392
train
function (dir, failOnDups) { debug('Loading services from %s', dir); di.iterateOverJsFiles(dir, function(dir, file) { var modPath = path.resolve(dir, file); var mod; try { mod = subRequire(modPath); //subRequire inserts the _id field } catch (e) { throw new Error('Could not load ' + modPath + ': ' + e.message); } registerServiceModule(mod, failOnDups); }); }
javascript
{ "resource": "" }
q54393
train
function() { var loader = this; return { //callback is optional, but will guarantee module was initialized get: function(name, callback) { if (!_.isString(name)) { debug('To get a registered service, the service name must be provided.'); return; } var normalizedName = normalizeServiceName(name); if (!callback) { //sync version if (!_.includes(initMods, normalizedName)) { //hasn't been initialized debug('Using services.get on %s before it has been initialized.', name); } return loader.get(normalizedName); } else { //async version if (_.includes(initMods, normalizedName)) { //already initialized debug('Found already-initialized module %s, invoking callback.', name); return callback(loader.get(normalizedName)); } else { debug('Adding callback %s to notify list for service %s', (callback.name || '<anonymous>'), name); notifyList.push({name: normalizedName, callback: callback}); } } } }; }
javascript
{ "resource": "" }
q54394
loadFromIndividualConfigFile
train
function loadFromIndividualConfigFile(key) { key = _.replace(key, /\/|\\/g, ''); //forward and backslashes are unsafe when resolving filenames if (individualKeyCache[key]) { return individualKeyCache[key]; } else { var toLoad = path.resolve(global.__appDir, 'config/' + key + '.json'); var content = '{}'; try { content = fs.readFileSync(toLoad); } catch (err) { //file must not exists } var json = {}; try { json = JSON.parse(stripJsonComments(content.toString())); } catch (err) { console.warn('Error parsing JSON for %s', toLoad); } security.decryptObject(json, function (str) { //Decryption function return security.decrypt(str, process.env.decryptionKey); }); individualKeyCache[key] = json; return individualKeyCache[key]; } }
javascript
{ "resource": "" }
q54395
getLocation
train
function getLocation() { var trace = stackTrace.get(); //trace.forEach(function(e){ // console.log('mytrace: ' + e.getFileName()); //}); //use (start at) index 2 because 0 is the call to getLocation, and 1 is the call to logger // However, component loggers put an extra level in, so search down until the location is not 'logger' // There's code to search a long way down the stack, but in practice the next (3) will be hit and used // since its name is not logger. var idx = 2; var modNm = 'logger'; var rmodNm = null; var skip = ['logger', 'logger.js']; while ((_.includes(skip, modNm)) && trace.length > idx) { var fpath = trace[idx].getFileName(); ++idx; if (fpath.slice(0, 'native'.length) === 'native') { continue; // skip native modules } modNm = null; var mod = null; try { mod = require(fpath); } catch (err) { // do nothing here, it's checked later } if (mod) { //__id is injected into services by the loader if (!mod.__id) { modNm = _.split(fpath, '/').pop(); rmodNm = modNm; } else { modNm = mod.__id; if (modNm !== null) { rmodNm = modNm; } } } else { modNm = _.split(fpath, '/').pop(); rmodNm = modNm; } } return rmodNm; }
javascript
{ "resource": "" }
q54396
isBlueoakProject
train
function isBlueoakProject() { if ((path.basename(global.__appDir) !== 'server')) { return false; } try { return fs.statSync(path.resolve(global.__appDir, '../common/swagger')).isDirectory(); } catch (err) { return false; } }
javascript
{ "resource": "" }
q54397
containsEncryptedData
train
function containsEncryptedData(obj) { var foundEncrypted = false; if (_.isString(obj)) { foundEncrypted = isEncrypted(obj); } else if (_.isArray(obj)) { for (var i = 0; i < obj.length; i++) { foundEncrypted = foundEncrypted || containsEncryptedData(obj[i]); } } else if (_.isObject(obj)) { for (var key in obj) { foundEncrypted = foundEncrypted || containsEncryptedData(obj[key]); } } return foundEncrypted; }
javascript
{ "resource": "" }
q54398
decryptObject
train
function decryptObject(obj, decryptFunction) { if (_.isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_.isString(obj[i])) { if (isEncrypted(obj[i])) { obj[i] = decryptFunction(obj[i]); } } else { decryptObject(obj[i], decryptFunction); } } } else if (_.isObject(obj)) { for (var key in obj) { if (_.isString(obj[key])) { if (isEncrypted(obj[key])) { obj[key] = decryptFunction(obj[key]); } } else { decryptObject(obj[key], decryptFunction); } } } }
javascript
{ "resource": "" }
q54399
collectStats
train
function collectStats(callback) { var serviceStats = {}; var services = loader.listServices(); async.each(services, function(service, callback) { var mod = loader.get(service); if (mod.stats) { //does it have a stats function? invokeStatsOnMod(mod, function(err, data) { serviceStats[service] = data; return callback(err); }); } else { return callback(); //nothing to do, no stats method exposed } }, function(err) { callback(err, serviceStats); }); }
javascript
{ "resource": "" }