_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q32800
_setParams
train
function _setParams(params){ if(params){ // set the data collection params if(params.defaultEvents){ for (let i = 0; i < params.defaultEvents.length; i++){ dataCollector.configureEventCollection( params.defaultEvents[i].name, params.defaultEvents[i].status, params.defaultEvents[i].timePeriod ); } } // set the session Info if(params.sessionInfo){ for(let i = 0; i < params.sessionInfo.length; i++){ dataManager.addSessionExtra( params.sessionInfo[i].key, params.sessionInfo[i].value ); } } // set pauseOnHeadsetRemove if('pauseOnHeadsetRemove' in params){ timeManager.setRemoveHeadsetPausesPlay(!!params['pauseOnHeadsetRemove']); } } }
javascript
{ "resource": "" }
q32801
authedByUsername
train
function authedByUsername(username) { return _.first(_.where(context.authed, { username: username})); }
javascript
{ "resource": "" }
q32802
httpRequest
train
function httpRequest(options, body, callback) { // The `processResponse` callback should only be called once. The [http docs](http://nodejs.org/api/http.html#http_event_close_1) // say that a 'close' event can be fired after the 'end' event has been fired. To ensure that the `processResponse` callback // is called only once it is wrapped by `_.once()` var processResponse = _.once(function(error, responseBody, httpResponse) { if (!error && httpResponse && httpResponse.statusCode !== 200) error = httpResponse.statusCode; if (_.isFunction(callback)) callback(error, responseBody, httpResponse); }); var request = http.request(options, function(httpResponse) { var responseBody = ''; httpResponse.on('data', function(data) { responseBody += data.toString(); // 'data' can be a String or a Buffer object }).on('close', function(error) { processResponse(error, responseBody, httpResponse); }).on('end', function() { processResponse(undefined, responseBody, httpResponse); }); }).on('error', processResponse); if (!_.isEmpty(body)) request.write(body); request.end(); }
javascript
{ "resource": "" }
q32803
getEC2IAMRole
train
function getEC2IAMRole(callback) { httpRequest({host: EC2_METADATA_HOST, path: SECURITY_CREDENTIALS_RESOURCE}, null, function(error, role, httpResponse) { callback(error, _.isString(role) ? role.trim() : role, httpResponse); }); }
javascript
{ "resource": "" }
q32804
getEC2IAMSecurityCredentials
train
function getEC2IAMSecurityCredentials(role, callback) { httpRequest({host: EC2_METADATA_HOST, path: SECURITY_CREDENTIALS_RESOURCE + role}, null, function(error, jsonStr, httpResponse) { var credentials; try { credentials = JSON.parse(jsonStr); } catch (parseError) { if (!error) error = parseError; } callback(error, credentials, httpResponse); }); }
javascript
{ "resource": "" }
q32805
needsToLoadEC2IAMRoleCredentials
train
function needsToLoadEC2IAMRoleCredentials() { if (!accessKey || !secretKey) return true; if (credentialsExpiration === null) return false; return (credentialsExpiration.getTime() - Date.now()) < CREDENTIALS_EXPIRATION_THRESHOLD; }
javascript
{ "resource": "" }
q32806
train
function (cb) { this.reset(); var bundle = this.bundle; var self = this; async.waterfall([ function (wfCb) { if (self.noclean) { wfCb(); } else { // Remove the output directory if it exists existsCompat(self.outputTo, function (exists) { if (exists) { if (self.verbose) { console.log('compileAssets: removing output directory: ' + self.outputTo); } rimraf(self.outputTo, wfCb); } else { wfCb(); } }); } }, function (wfCb) { if (self.verbose) { console.log('compileAssets: starting asset discovery phase.'); } executePhase(self.phases.discovery, bundle, wfCb); }, function (b, wfCb) { if (self.verbose) { console.log('compileAssets: starting compilation phase.'); } try { // Get the correct order of asset dependencies var orderedAssets = bundle.getProcessingOrder().map(function (assetFilePath) { return bundle.getAsset(assetFilePath); }); async.eachSeries(orderedAssets, function (asset, eachCb) { setImmediateCompat(function() { executePhase(self.phases.compilation, asset, eachCb); }); }, wfCb); } catch (e) { wfCb(e); } }, function (wfCb) { if (self.verbose) { console.log('compileAssets: starting post-compilation phase.'); } async.eachLimit(bundle.getAllAssets(), 50, function (asset, eachCb) { executePhase(self.phases.postCompilation, asset, eachCb); }, wfCb); }, function (wfCb) { if (self.verbose) { console.log('compileAssets: starting output phase.'); } async.eachLimit(bundle.getAllAssets(), 50, function (asset, eachCb) { executePhase(self.phases.output, asset, eachCb); }, wfCb); } ], cb); }
javascript
{ "resource": "" }
q32807
train
function (cb) { this.reset(); var bundle = this.bundle; var self = this; async.waterfall([ function (wfCb) { if (self.verbose) { console.log('findAssets: starting discovery phase'); } executePhase(self.phases.discovery, bundle, wfCb); }, function (b, wfCb) { if (self.verbose) { console.log('findAssets: starting name transformation phase'); } async.eachLimit(bundle.getAllAssets(), 50, function (asset, eachCb) { executePhase(self.phases.nameTransformation, asset, eachCb); }, wfCb); } ], cb); }
javascript
{ "resource": "" }
q32808
train
function () { var bundle = this.bundle; var order = bundle.getProcessingOrder(); return order.map(function (file ) { return bundle.getAsset(file).logicalPath; }); }
javascript
{ "resource": "" }
q32809
train
function (storeOrEditor, path) { debug('Checking if ' + path + ' exists in the in-memory store.'); var retv = false; this.processInMemoryStore(storeOrEditor, file => { debug('Evaluating ' + file.path + ' in state ' + file.state + ' with content length ' + (file && file.contents ? file.contents.length : 'unknown')); if (file.path.indexOf(path) === 0 && file.contents !== null && file.state !== 'deleted') { debug('FOUND'); retv = true; } }); debug('RESULT ' + retv); return retv; }
javascript
{ "resource": "" }
q32810
train
function (storeOrEditor, from, to) { debug('Performing inMemoryCopy from ' + from + ' to ' + to + '.'); var fromLen = from.length; this.processInMemoryStore(storeOrEditor, (file, store) => { var idx = file.path.indexOf(from); if (idx === 0 && file.contents !== null && file.state !== 'deleted') { var absTo = path.join(to, file.path.substr(fromLen)); // exact match so we are copying a single file and not a folder if (fromLen === file.path.length) { absTo = path.join(to, path.basename(file.path)); } debug('CREATING COPY IN-MEMORY: ' + absTo); var newFile = store.get(absTo); newFile.contents = file.contents; newFile.state = 'modified'; store.add(newFile); } }); }
javascript
{ "resource": "" }
q32811
train
function (storeOrEditor, from, to) { debug('Performing inMemoryMove from ' + from + ' to ' + to); var store = (storeOrEditor && storeOrEditor.store ? storeOrEditor.store : storeOrEditor); var memFsEditor = require('mem-fs-editor').create(store); var fromLen = from.length; store.each(function (file) { var idx = file.path.indexOf(from); if (idx === 0 && file.contents !== null && file.state !== 'deleted') { var absTo = path.join(to, file.path.substr(fromLen)); // exact match so we are copying a single file and not a folder if (fromLen === file.path.length) { absTo = path.join(to, path.basename(file.path)); } debug('IN-MEMORY MOVING FROM: ' + file.path + ' TO: ' + absTo); memFsEditor.move(file.path, absTo); } }); }
javascript
{ "resource": "" }
q32812
train
function (storeOrEditor, logFn) { debug('Dumping contents of in-memory store.'); var logFunc = logFn || console.log; this.processInMemoryStore(storeOrEditor, file => { logFunc.call(this, file.path + ' [STATE:' + file.state + ']'); /* logFunc.call(this, JSON.stringify(file, function (k, v) { if (k === '_contents') { if (undefined !== v) { return 'data'; } } return v; })); */ }); }
javascript
{ "resource": "" }
q32813
processReconcile
train
function processReconcile(field, toSet, setSep, reconcileSet) { // process validated updates if (reconcileSet) { reconcileSet.forEach(function(t) { var s = { uri: t.uri }; s[toSet] = t.setVal; context.pubsub.item.save(s); }); return; } }
javascript
{ "resource": "" }
q32814
Questions
train
function Questions(options) { if (!(this instanceof Questions)) { return new Questions(options); } debug('initializing from <%s>', __filename); Options.call(this, utils.omitEmpty(options || {})); use(this); this.initQuestions(this.options); }
javascript
{ "resource": "" }
q32815
ShareJSStream
train
function ShareJSStream(ws, options) { options = options || {}; options.keepAlive = options.keepAlive !== undefined ? options.keepAlive : KEEP_ALIVE; this.debug = options.debug === true; this.ws = ws; this.headers = this.ws.upgradeReq.headers; this.remoteAddress = this.ws.upgradeReq.connection.remoteAddress; if (this.debug) { this.logger = logfmt.namespace({ ns: 'share-js-stream' }); } Duplex.call(this, { objectMode: true }); /** * Send a `null` message to the ws so that the connection is kept alive. * * This may not be necessary on all platforms. * * @method keepAlive * @private */ this.keepAlive = function keepAlive() { this.log({ evt: 'keepAlive' }); this.ws.send(null); }.bind(this); /** * Handle a closed ws client. * * This is called when the `close` event is emitted on the ws client. It: * * - Clears the keep alive interval (if there is one) * - Pushes `null` to end the stream * - Emits `close` on the stream * * @method onWsClose * @private * @param {Number} code the reason code for why the client was closed * @param {String} message a message accompanying the close */ this.onWsClose = function onWsClose(code, message) { if (this.keepAliveInterval) { clearInterval(this.keepAliveInterval); } this.log({ evt: 'wsClose', code: code, message: message }); this.push(null); this.emit('close'); }.bind(this); /** * Push a message received on the ws client as an object to the stream. * * If JSON parsing of the message fails, an error event will be emitted on the * stream. * * @method onWsMessage * @private * @param {String} msg a JSON-encoded message received on the ws client */ this.onWsMessage = function onWsMessage(msg) { this.log({ evt: 'wsMessage', msg: msg }); try { msg = JSON.parse(msg); } catch(_) { var err = new Error('Client sent invalid JSON'); err.code = CLOSE_UNSUPPORTED; this.emit('error', err); return; } this.push(msg); }.bind(this); /** * Handle the stream ending by closing the ws client connection. * * @method onStreamEnd * @private */ this.onStreamEnd = function onStreamEnd() { this.log({ evt: 'streamEnd' }); this.ws.close(CLOSE_NORMAL); }.bind(this); /** * Handle a stream error by closing the ws client connection. * * @method onStreamError * @private * @param {Error} err the error emitted on the stream */ this.onStreamError = function onStreamError(err) { this.log({ evt: 'streamError', err: err.message }); this.ws.close(err.code || CLOSE_ERROR, err.message); }.bind(this); this.ws.on('close', this.onWsClose); this.ws.on('message', this.onWsMessage); this.on('error', this.onStreamError); this.on('end', this.onStreamEnd); if (options.keepAlive) { this.keepAliveInterval = setInterval(this.keepAlive, options.keepAlive); } }
javascript
{ "resource": "" }
q32816
loadSchema
train
function loadSchema(schemaBasePath, fullSchemaFileName) { var scfPath = fullSchemaFileName.split('/'); var schemaFileName = scfPath[scfPath.length - 1]; var mainSchema = null; // First, register() the main schemas you plan to use. try { mainSchema = _jsYaml2.default.load(_fs2.default.readFileSync(_path2.default.resolve(schemaBasePath, schemaFileName), 'utf-8')); var missingSchemas = js.register(mainSchema); // Next, load the missing sub-schemas recursively missingSchemas.forEach(function (missingSchema) { loadSchema(schemaBasePath, missingSchema); }); } catch (err) { //console.log(err) } return mainSchema; }
javascript
{ "resource": "" }
q32817
train
function(argv, context, callback) { return MongoClient.connect(mongoHost, function(err, db) { if (err) { return sg.die(err, callback, 'upsertPartner.MongoClient.connect'); } var partnersDb = db.collection('partners'); var partnerId = argvGet(argv, 'partner-id,partner'); var item = {}; _.each(argv, (value, key) => { sg.setOnn(item, ['$set', sg.toCamelCase(key)], sg.smartValue(value)); }); everbose(2, `Upserting partner: ${partnerId}`); return partnersDb.updateOne({partnerId}, item, {upsert:true}, function(err, result) { if (err) { console.error(err); } db.close(); return callback(err, result.result); }); }); }
javascript
{ "resource": "" }
q32818
train
function(service, credentials, accounts, keywords) { Stream.call(this, service, credentials, accounts, keywords); // Set up instagram-node-lib Insta.set('client_id', credentials.client_id); Insta.set('client_secret', credentials.client_secret); // Set api endpoint URL for subscriber this.api_endpoint = 'https://api.instagram.com/v1/subscriptions/'; // Initialize subscriber object this.subscriber = new Subscriber(credentials, this.callback_url(), this.api_endpoint); // Initialize responder this.responder = new Responder(); // Start listening for incoming process.nextTick(function() { this.delegateResponder(); }.bind(this)); }
javascript
{ "resource": "" }
q32819
logError
train
function logError(message, err, context, event) { var current_err = err; while (current_err) { var next_err = current_err._previous; delete current_err._previous; if (current_err.stack) { console.error(current_err.stack); } else { console.error(current_err); } current_err = next_err; } // TODO add cli options for logging out context and event as well }
javascript
{ "resource": "" }
q32820
Polyfill
train
function Polyfill(object, key) { nodsl.check(typeof object === 'object', 'object must be an object; got ', object); nodsl.check(typeof key === 'string', 'key must be a string; got ', key); nodsl.check(typeof object[key] === 'string', 'object.', key, ' must be a string; got ', object[key]); var that = this; that.add = function() { var tokens = [].slice.apply(arguments); tokens.forEach(function(token, i) { nodsl.check(typeof token === 'string', 'tokens[', i, '] must be a string; got ', token); }); object[key] += (object[key].length ?' ' :'') + tokens.join(' '); }; that.remove = function(token) { nodsl.check(typeof token === 'string', 'token must be a string; got ', token); object[key] = object[key].replace(new RegExp('\\b'+ token +'\\b\\s*'), '').replace(/^\\s*/, ''); }; that.contains = function(token) { nodsl.check(typeof token === 'string', 'token must be a string; got ', token); return object[key].search(new RegExp('\\b'+ token +'\\b')) !== -1; }; Object.defineProperty(that, 'length', { get: function() { return (object[key].match(/[^\s]+/g) || []).length; }, }); return that; }
javascript
{ "resource": "" }
q32821
_isArrayOfObjects
train
function _isArrayOfObjects(value) { if (!Array.isArray(value)) { return false; } var l = value.length; var _type, cond; for (var i = 0; i < l; i++) { _type = typeof value[i]; cond = _type === 'function' || _type === 'object' && !!value[i]; if (!cond) { return false; } } return true; }
javascript
{ "resource": "" }
q32822
_get
train
function _get(obj, path) { var subpathes = path.split('.'); while (subpathes.length) { var subpath = subpathes.shift(); obj = obj[subpath]; if (!obj) { return obj; } } return obj; }
javascript
{ "resource": "" }
q32823
_set
train
function _set(obj, path, value) { var subpathes = path.split('.'); while (subpathes.length - 1) { obj = obj[subpathes.shift()]; } obj[subpathes.shift()] = value; }
javascript
{ "resource": "" }
q32824
_has
train
function _has(obj, path) { var subpathes = path.split('.'); while (subpathes.length) { var subpath = subpathes.shift(); if (!obj.hasOwnProperty(subpath)) { return false; } obj = obj[subpath]; } return true; }
javascript
{ "resource": "" }
q32825
exec
train
function exec() { // NOTE: pardon this cli target to Couchpenter methods mapping, // needed to preserve backward compatibility w/ v0.1.x const FUNCTIONS = { setup: 'setUp', 'setup-db': 'setUpDatabases', 'setup-doc': 'setUpDocuments', 'setup-doc-overwrite': 'setUpDocumentsOverwrite', teardown: 'tearDown', 'teardown-db': 'tearDownDatabases', 'teardown-doc': 'tearDownDocuments', reset: 'reset', 'reset-db': 'resetDatabases', 'reset-doc': 'resetDocuments', clean: 'clean', 'clean-db': 'cleanDatabases', 'warm-view': 'warmViews', 'live-deploy-view': 'liveDeployView' }; var actions = { commands: { init: { action: _init } } }; _.keys(FUNCTIONS).forEach(function (task) { actions.commands[task] = { action: _task(FUNCTIONS[task]) }; }); cli.command(__dirname, actions); }
javascript
{ "resource": "" }
q32826
use
train
function use(brand) { return function branding(file) { var branded = file.replace('{{brand}}', brand); return fs.existsSync(branded) ? branded : file.replace('{{brand}}', 'nodejitsu'); }; }
javascript
{ "resource": "" }
q32827
get
train
function get(done) { this.define(); done(undefined, this.mixin({}, this.defaults, this.data, this.merge( this.data, this.queue.discharge(this.name) ))); }
javascript
{ "resource": "" }
q32828
use
train
function use(namespace, name, fn) { name = name || this.name; this.temper.require('handlebars').registerHelper( namespace + '-' + name, fn ); return this; }
javascript
{ "resource": "" }
q32829
reduce
train
function reduce (m) { if (Array.isArray(m)) { try { const module = m[0].module ? m[0].module : m[0] _("register bind %o", module) return require(module) } catch (_) { return reduce(m.slice(1)) } } else return reduce([m]) }
javascript
{ "resource": "" }
q32830
teardown
train
function teardown(moduleName, e, moduleNames) { var moduleNames = moduleNames || {}; if(disposeModule(moduleName, e, moduleNames)) { // Delete the module and call teardown on its parents as well. var parents = loader.getDependants(moduleName); for(var i = 0, len = parents.length; i < len; i++) { teardown(parents[i], e, moduleNames); } } return moduleNames; }
javascript
{ "resource": "" }
q32831
config_mail_box
train
function config_mail_box(config) { imap = new Imap({ user:config.user, password:config.password, host:config.host, port:config.port, secure:config.secure }); }
javascript
{ "resource": "" }
q32832
get_new_followers
train
function get_new_followers(since, cb, cberr) { get_inbox(since); _callback = cb; _callback_err = cberr; }
javascript
{ "resource": "" }
q32833
bundlerFactory
train
function bundlerFactory(loader, options) { function bundlerDelegate(modules) { return bundler(loader, options || {}, modules); } bundlerDelegate.bundle = function(names) { return loader.fetch(names).then(bundlerDelegate); }; return bundlerDelegate; }
javascript
{ "resource": "" }
q32834
bundler
train
function bundler(loader, options, modules) { var stack = modules.slice(0); var mods = []; var finished = {}; function processModule(mod) { if (finished.hasOwnProperty(mod.id)) { return; } mod = loader.getModule(mod.id); // browser pack chunk var browserpack = { id : mod.id, source : mod.source, deps : {} }; // Gather up all dependencies var i, length, dep; for (i = 0, length = mod.deps.length; i < length; i++) { dep = mod.deps[i]; stack.push(dep); browserpack.deps[dep.id] = dep.id; } finished[mod.id] = browserpack; mods.unshift(browserpack); } // Process all modules while (stack.length) { processModule(stack.pop()); } var stream = browserPack(options).setEncoding("utf8"); var promise = pstream(stream); stream.end(JSON.stringify(mods)); return promise; }
javascript
{ "resource": "" }
q32835
isCommentLine
train
function isCommentLine (line) { var isCmnt = commentRE.test(line); if (isCmnt) { debug('removing comment: %s', line); } return !isCmnt; }
javascript
{ "resource": "" }
q32836
extractKeyValue
train
function extractKeyValue (line) { var kv = { key: undefined, value: undefined, }; var matches = kvRE.exec(line); if (matches !== null && matches.length === 3) { kv.key = matches[1]; kv.value = matches[2]; } return kv; }
javascript
{ "resource": "" }
q32837
processLine
train
function processLine (instance, acc, line) { debug('processing: %s', line); // if previous line was continued then capture this line verbatim // of course we need to handle if this is also a continuation too if (instance.key) { var hasCont = hasNewlineContinuation(line); if (hasCont) { debug('removing line continuation'); line = removeContinuation(line); } line = unescape(line); debug('saving %s=>%s', instance.key, line); acc[instance.key] += line; if (!hasCont) { instance.key = undefined; } } else { var kv = extractKeyValue(line); kv.key = unescape(kv.key); if (hasNewlineContinuation(kv.value)) { debug('removing line continuation'); kv.value = removeContinuation(kv.value); instance.key = kv.key; } kv.value = unescape(kv.value); debug('saving %s=>%s', kv.key, kv.value); acc[kv.key] = kv.value; } return acc; }
javascript
{ "resource": "" }
q32838
unescape
train
function unescape (line) { var retv = _.replace(line, propEscapeRE, '$1'); retv = _.replace(line, unicodeEscapeRE, function (m) { return String.fromCharCode(parseInt(m, 16)); }); if (retv !== line) { debug('removed escapes from: %s => %s', line, retv); } return retv; }
javascript
{ "resource": "" }
q32839
train
function(environment, mbaasConfig) { if (!client) { client = new MbaasClient(environment, mbaasConfig); } //Deprecated module.exports.app = client.app; module.exports.admin = client.admin; }
javascript
{ "resource": "" }
q32840
getContext
train
function getContext(seneca) { var transactionId = seneca.fixedargs.tx$; var context = seneca.fixedargs.context$; if (typeof context === 'undefined') { try { context = seneca.fixedargs.context$ = JSON.parse(URLSafeBase64.decode(transactionId).toString('utf8')); debug('context loaded from tx$ and cached in context$', transactionId, context); } catch (error) { context = null; debug('context cannot be loaded from tx$', transactionId, error); } } else { debug('context loaded from context$', transactionId, context); } return context; }
javascript
{ "resource": "" }
q32841
setContext
train
function setContext(seneca, context) { seneca.fixedargs.tx$ = URLSafeBase64.encode(new Buffer(JSON.stringify(context))); seneca.fixedargs.context$ = context; debug('context saved', seneca.fixedargs.tx$, context); }
javascript
{ "resource": "" }
q32842
setElement
train
function setElement( targetElement ) { // If the element has already been set, // clear the transition classes from the old element. if ( _dom ) { remove(); animateOn(); } _dom = targetElement; _dom.classList.add( _classes.BASE_CLASS ); _transitionEndEvent = _getTransitionEndEvent( _dom ); }
javascript
{ "resource": "" }
q32843
halt
train
function halt() { if ( !_isAnimating ) { return; } _dom.style.webkitTransitionDuration = '0'; _dom.style.mozTransitionDuration = '0'; _dom.style.oTransitionDuration = '0'; _dom.style.transitionDuration = '0'; _dom.removeEventListener( _transitionEndEvent, _transitionCompleteBinded ); _transitionCompleteBinded(); _dom.style.webkitTransitionDuration = ''; _dom.style.mozTransitionDuration = ''; _dom.style.oTransitionDuration = ''; _dom.style.transitionDuration = ''; }
javascript
{ "resource": "" }
q32844
_addEventListener
train
function _addEventListener() { _isAnimating = true; // If transition is not supported, call handler directly (IE9/OperaMini). if ( _transitionEndEvent ) { _dom.addEventListener( _transitionEndEvent, _transitionCompleteBinded ); this.trigger( BaseTransition.BEGIN_EVENT, { target: this } ); } else { this.trigger( BaseTransition.BEGIN_EVENT, { target: this } ); _transitionCompleteBinded(); } }
javascript
{ "resource": "" }
q32845
_flush
train
function _flush() { for ( const prop in _classes ) { if ( _classes.hasOwnProperty( prop ) && _classes[prop] !== _classes.BASE_CLASS && _dom.classList.contains( _classes[prop] ) ) { _dom.classList.remove( _classes[prop] ); } } }
javascript
{ "resource": "" }
q32846
remove
train
function remove() { if ( _dom ) { halt(); _dom.classList.remove( _classes.BASE_CLASS ); _flush(); return true; } return false; }
javascript
{ "resource": "" }
q32847
train
function(handler, priority) { if(handler && handler.constructor === Array) { handler.forEach(function(layer) { layer.priority = typeof layer.priority === 'undefined' ? 1 : layer.priority; }); _list = _list.concat(handler); } else { handler.priority = priority || (typeof handler.priority === 'undefined' ? 1 : handler.priority); _list.push(handler); } return this; }
javascript
{ "resource": "" }
q32848
train
function(callback) { var nextHandler; var executionList = _list.slice(0).sort(function(a, b) { return Math.max(-1, Math.min(1, b.priority - a.priority)); }); nextHandler = function() { $rootScope.$evalAsync(function() { var handler = executionList.shift(); // Complete if(!handler) { callback(null); // Next handler } else { handler.call(null, _data, function(err) { // Error if(err) { callback(err); // Continue } else { nextHandler(); } }); } }); }; // Start nextHandler(); }
javascript
{ "resource": "" }
q32849
isSpecs
train
function isSpecs(opt) { //logger.debug('???'); //logger.debug(`${opt.cacheDir}`); //let b:any = opt.cacheDir instanceof(String) if (!path.isAbsolute(opt.cacheDir)) { logger.error('cacheDir parameter must be an absolute path'); return false; } if ('cacheDir' in opt && 'tcp' in opt && 'port' in opt && 'engineSpec' in opt) return typeof (opt.cacheDir) == 'string' && typeof (opt.tcp) == 'string' && typeof (opt.port) == 'number' && engineLib.isEngineSpec(opt.engineSpec); //logger.debug('niet'); return false; }
javascript
{ "resource": "" }
q32850
pushMS
train
function pushMS(data, socket) { logger.debug(`newJob Packet arrived w/ ${util.format(data)}`); logger.silly(` Memory size vs nWorker :: ${liveMemory.size()} <<>> ${nWorker}`); if (liveMemory.size("notBound") >= nWorker) { logger.debug("must refuse packet, max pool size reached"); jmServer.bouncer(data, socket); return; // No early exit yet } jmServer.granted(data, socket).then((_data) => { let jobProfile = _data.jobProfile; _data.fromConsumerMS = true; //pool size if (jobLib.isJobOptProxy(_data)) { logger.debug(`jobOpt successfully decoded`); } let job = push(jobProfile, _data); }); }
javascript
{ "resource": "" }
q32851
addFileResource
train
function addFileResource(cmd, file, params, callback) { if( !file ) return callback({error:true,message:"no file provided"}); if( !fs.existsSync(file) ) return callback({error:true,message:"no file found: "+file}); if( !fs.statSync(file).isFile() ) return callback({error:true,message:"not a file: "+file}); if( !params ) return callback({error:true,message:"no resource parameters provided"}); if( !params.package_id ) return callback({error:true,message:"no package_id provided"}); // clean up filename var name = getCkanFilename(file); var folder = new Date().toISOString()+'/'+name; // set default / known parameters params.url = server+"/storage/f/"+encodeURIComponent(folder); if( !params.name ) params.name = file.replace(/.*\//,''); params.size = fs.statSync(file).size; params.resource_type = "file.upload"; exports.exec(cmd, params, function(err, pkg){ if( err ) return callback(err); rest.post(server + '/storage/upload_handle', { multipart: true, headers : { Authorization : key }, data: { key: folder, file: rest.file(file, null, fs.statSync(file).size, null, params.mimetype) } }).on('complete', function(data) { // HACK: redirects seem to fire complete twice. this is bad if( !callback ) return; if (data instanceof Error) { callback(data); } else { callback(null, data); } callback = null; }); }); }
javascript
{ "resource": "" }
q32852
train
function(locale) { this.intCol = (Intl && Intl.Collator) ? new Intl.Collator(locale) : new CollatorPolyfill(locale); }
javascript
{ "resource": "" }
q32853
giveAnswer
train
function giveAnswer(answeringPlayer, answer) { if(answeringPlayer === seller) return; if(answer <= currentBid) return; buyer = answeringPlayer; currentBid = answer; resetTimer(); notify(false); }
javascript
{ "resource": "" }
q32854
hoistingOptions
train
function hoistingOptions( target ) { if ( !target.hasOwnProperty( '_options' ) ) { let options; if ( undefined === target._options ) { options = {}; } else { // Create copy with descriptors options = Object.create( null, Object.getOwnPropertyDescriptors( target._options ) ); } Object.defineProperty( target, '_options', { value: options, enumerable: false, configurable: true } ); } }
javascript
{ "resource": "" }
q32855
markCells
train
function markCells(cells, adj, edges) { //Initialize active/next queues and flags var flags = new Array(cells.length) var constraint = new Array(3*cells.length) for(var i=0; i<3*cells.length; ++i) { constraint[i] = false } var active = [] var next = [] for(var i=0; i<cells.length; ++i) { var c = cells[i] flags[i] = 0 for(var j=0; j<3; ++j) { var a = c[(j+1)%3] var b = c[(j+2)%3] var constr = constraint[3*i+j] = isConstraint(edges, a, b) if(adj[3*i+j] >= 0) { continue } if(constr) { next.push(i) } else { flags[i] = 1 active.push(i) } } } //Mark flags var side = 1 while(active.length > 0 || next.length > 0) { while(active.length > 0) { var t = active.pop() if(flags[t] === -side) { continue } flags[t] = side var c = cells[t] for(var j=0; j<3; ++j) { var f = adj[3*t+j] if(f >= 0 && flags[f] === 0) { if(constraint[3*t+j]) { next.push(f) } else { active.push(f) flags[f] = side } } } } //Swap arrays and loop var tmp = next next = active active = tmp next.length = 0 side = -side } return flags }
javascript
{ "resource": "" }
q32856
arrayHasAny
train
function arrayHasAny(values, array) { error_if_not_array_1.errorIfNotArray(values); var i = -1; while (++i < values.length) { if (arrayHas_1.arrayHas(values[i], array)) return true; } return false; }
javascript
{ "resource": "" }
q32857
setJSHint
train
function setJSHint(path, done) { var opts = JSON.parse(fs.readFileSync(path, 'utf8')); jsHintOptions.config = opts; done(); }
javascript
{ "resource": "" }
q32858
checkJSHint
train
function checkJSHint(done) { if(!options.jshint) { options.jshint = path.join(__dirname, '.jshintrc'); } checkPath(options.jshint, setJSHint, done); }
javascript
{ "resource": "" }
q32859
setFilesets
train
function setFilesets(path, done) { var config = JSON.parse(fs.readFileSync(path, 'utf8')); /* jshint sub: true */ var includeFiles = config['includeFiles']; var excludeFiles = config['excludeFiles']; var filterFiles = config['lintOnly']; /* jshint sub: false */ if (filterFiles && !Array.isArray(filterFiles)) { filterFiles = []; console.log(chalk.yellow('invalid `lintOnly` set; ignoring')); } if (includeFiles && Array.isArray(includeFiles)) { filesets.include(includeFiles, filterFiles); } else { console.log(chalk.yellow('valid `includeFiles` not found in %s'), path); } if (excludeFiles && Array.isArray(includeFiles)) { filesets.exclude(excludeFiles); } else { console.log(chalk.yellow('valid `excludeFiles` not found in %s'), path); } done(); }
javascript
{ "resource": "" }
q32860
runReports
train
function runReports(err) { if (err) { console.log(chalk.red('Error running reports: %s'), err); } var excludes = filesets.platoExcludes(); if (excludes) { platoOptions.exclude = excludes; } jsHintOptions.ignore = filesets.jshintExcludes(); jsHintOptions.reporter = reporter.reporter; console.log(chalk.blue('Building plato reports...')); console.log(chalk.gray('(Ignore any output about being unable to parse ' + 'JSON files)')); plato.inspect(filesets.platoIncludes(), outputDir, platoOptions, function() { console.log(chalk.blue('\nPlato reports have been built to: ') + chalk.magenta(outputDir)); console.log(chalk.blue('\nJSHint Report\n=============\n')); buildJSHint(filesets.jshintIncludes(), jsHintOptions, reporter.callback); } ); }
javascript
{ "resource": "" }
q32861
getHistoricalClosePrices
train
function getHistoricalClosePrices(options = {}) { const { index, currency, start, end, yesterday } = options return request(`/historical/close.json`, { index, currency, start: start && end && formatDate(start) || undefined, end: start && end && formatDate(end) || undefined, for: yesterday ? 'yesterday' : undefined }) }
javascript
{ "resource": "" }
q32862
fileReader
train
function fileReader(moduleMeta) { // Read file from disk and return a module meta return pstream(readFile(moduleMeta.path)) .then(function(text) { return { source: text }; }, log2console); }
javascript
{ "resource": "" }
q32863
train
function(guess, filename) { var ct = guess; // Someone else just defaulted to octet-stream? if (!ct || ct === 'application/octet-stream') { ct = sg.mimeType(filename) || ct; } return ct || 'application/octet-stream'; }
javascript
{ "resource": "" }
q32864
Module
train
function Module(options) { options = options || {}; if (types.isString(options)) { options = { name: options }; } if (!types.isString(options.name) && !types.isString(options.source)) { throw new TypeError("Must provide a name or source for the module"); } this.deps = options.deps ? options.deps.slice(0) : []; this.type = options.type || Type.UNKNOWN; return this.merge(options); }
javascript
{ "resource": "" }
q32865
train
function(doRecentCheck, req, res, next) { var app = req.app; var config = app.loadConfig('auth'); var failed = !req.isAuthenticated(); if (!failed && doRecentCheck && !req.session.impersonated) { //skip recent check if login is impersonated //note: loginTime maybe a string since sessions are serialized as json failed = !req.session.loginTime || !(new Date() - new Date(req.session.loginTime) <= config.recentLoginTimeoutSeconds*1000); if (failed) { //force reauthentication (e.g. for facebook login for example) req.session.reauthenticate = true; } } // if user is not authenticated, redirect to login if (failed) { // remember original requested url req.session.returnTo = req.url; req.session.returnToMethod = req.method; req.flash('login.danger', req.session.reauthenticate ? 'You need to login again to access this page.' : 'You need to login to access this page.'); res.redirect('/login'); return; } if (config.requireEmailVerification && req.user && !req.user.local.verified) { if (config.requireEmailVerification == 'nag') { req.flash('warning', 'Please confirm your email address by clicking the link sent to <strong>'+ req.user.local.email +"</strong>.&nbsp;&nbsp;<a class='send-resend' href='#'>Resend confirmation email</a>."); } else if (config.requireEmailVerification == 'require') { // redirect to the email verification page req.session.returnTo = req.url; req.session.returnToMethod = req.method; res.redirect('/verification-required'); return; } } return next(); }
javascript
{ "resource": "" }
q32866
train
function (next) { // index creation options var body = { settings: { number_of_shards : 3, number_of_replicas : 2, analysis: { // analyzer definitions go here analyzer: { // default analyzer used for search & indexing default: { tokenizer: 'uax_url_email', // indexing/search analysis: // - trims leading/trailing whitespace // - is case-insensitive // - transforms non ascii characters into ascii character equivalents // - splits on word/number boundaries and other delimiter rules filter: [ 'trim', 'lowercase', 'asciifolding', 'word_delimiter_1' ] }, // analyzer to use in indexing for autocomplete - we want ngrams of our data to be indexed autocomplete_index: { type: 'custom', // use our own own ngram tokenizer tokenizer: 'autocomplete_ngram', filter: [ 'trim', 'lowercase', 'asciifolding', 'word_delimiter_1' ] }, // analyzer to use in analyzing autocomplete search queries (don't generate ngrams from search queries) autocomplete_search: { type: 'custom', tokenizer: 'keyword', filter: [ 'trim', 'lowercase', 'asciifolding' ] } }, // filter definitions go here filter: { // custom word_delimiter filter to preserve original input as well as tokenize it word_delimiter_1: { type: 'word_delimiter', preserve_original: true } }, // tokenizer definitions go here tokenizer: { // tokenizer to use for generating ngrams of our indexed data autocomplete_ngram: { type: 'edgeNGram', // min and max ngram length min_gram: 1, max_gram: 50, // generate ngrams that start from the front of the token only (eg. c, ca, cat) side: 'front' } } } } } // if non-default mapping info was defined on the schema (e.g. autocomplete), apply the mappings to the index body.mappings = {} body.mappings[options.type] = indexMap // console.log('mapping for', options.type, util.inspect(indexMap, true, 10, true)) var reqOpts = { method: 'PUT', url: versionedUri, body: JSON.stringify(body) } if(options.auth) { reqOpts.auth = { user: options.auth.user, pass: options.auth.password, sendImmediately: false }; } // console.log('versionedUri', versionedUri) helpers.backOffRequest(reqOpts, function (err, res, body) { if (err) { return cb(err) } if (!helpers.elasticsearchBodyOk(body)) { var error = new Error('Unexpected index creation reply: '+util.inspect(body, true, 10, true)) error.body = body return next(error) } return next() }) }
javascript
{ "resource": "" }
q32867
train
function (next) { self.count().exec(function (err, count) { if (err) { return next(err) } docsToIndex = count return next() }) }
javascript
{ "resource": "" }
q32868
train
function (next) { // if no documents to index, skip population if (!docsToIndex) { return next() } // stream docs - and upload in batches of size BATCH_SIZE var docStream = self.find().stream() // elasticsearch commands to perform batch-indexing var commandSequence = []; docStream.on('data', function (doc) { if (!doc || !doc._id) { excludedDocs++; return } // get rid of mongoose-added functions doc = helpers.serializeModel(doc,options) var selfStream = this var strObjectId = doc._id var command = { index: { _index: versionedIndexName, _type: options.type, _id: strObjectId } } // append elasticsearch command and JSON-ified doc to command commandSequence.push(command) commandSequence.push(doc) if (commandSequence.length === BATCH_SIZE) { // pause the stream of incoming docs until we're done // indexing the batch in elasticsearch selfStream.pause() exports.bulkIndexRequest(versionedIndexName, commandSequence, options, function (err) { if (err) { return next(err) } // empty our commandSequence commandSequence = [] // keep streaming now that we're ready to accept more selfStream.resume() }) } }) docStream.on('close', function () { // if no documents left in buffer, don't perform a bulk index request if (!commandSequence.length) { return next() } // take care of the rest of the docs left in the buffer exports.bulkIndexRequest(versionedIndexName, commandSequence, options, function (err) { if (err) { return next(err) } // empty the commandSequence commandSequence = [] return next() }) }) }
javascript
{ "resource": "" }
q32869
train
function (next) { var reqOpts = { method: 'GET', url: helpers.makeAliasUri(options) } if(options.auth) { reqOpts.auth = { user: options.auth.user, pass: options.auth.password, sendImmediately: false }; } helpers.backOffRequest(reqOpts, function (err, res, body) { if (err) { return next(err) } var existingIndices = Object.keys(body) // console.log('\nexistingIndices', body) var aliasName = helpers.makeIndexName(options) // get all aliases pertaining to this collection & are not the index we just created // we will remove all of them indicesToRemove = existingIndices.filter(function (indexName) { return (indexName.indexOf(aliasName) === 0 && indexName !== versionedIndexName) }) // console.log('\nindicesToRemove', indicesToRemove) // generate elasticsearch request body to atomically remove old indices and add the new one var requestBody = { actions: [ { add: { alias: aliasName, index: versionedIndexName } } ] } indicesToRemove.forEach(function (indexToRemove) { var removeObj = { remove: { alias: aliasName, index: indexToRemove } } requestBody.actions.unshift(removeObj) }) var reqOpts = { method: 'POST', url: helpers.makeAliasUri(options), body: JSON.stringify(requestBody) } if(options.auth) { reqOpts.auth = { user: options.auth.user, pass: options.auth.password, sendImmediately: false }; } helpers.backOffRequest(reqOpts, function (err, res, body) { if (err) { return next(err) } if (!helpers.elasticsearchBodyOk(body)) { var error = new Error('Alias deletion error. Elasticsearch reply:'+util.inspect(body, true, 10, true)) error.elasticsearchReply = body error.elasticsearchRequestBody = requestBody return next(error) } return next() }) }) }
javascript
{ "resource": "" }
q32870
addPlayer
train
function addPlayer(userId, callbacks) { let player = factory.addPlayer(); if(!player) return null; self._callbacks.set(player, callbacks); // If the game didn't have an owner, it does now // This should only happen when the game is first created // and the initial player is added if(!owner) owner = player; self._users[userId] = { id: userId, player }; return player; }
javascript
{ "resource": "" }
q32871
slice
train
function slice (args, start, end) { var len = args.length; start = start > 0 ? start : 0; end = end >= 0 && end < len ? end : len; var n = end - start; if (n <= 0) return []; var ret = new Array(n); for (var i = 0; i < n; ++i) { ret[i] = args[i + start]; } return ret; }
javascript
{ "resource": "" }
q32872
read
train
function read (stream, opts, db, cb) { var schema = new exports.Schema; if (opts.onType) { schema.onType = opts.onType; } stream.once('error', function (err) { debug('aborting with error: ' + err); db.close(cb.bind(err)); }); stream.on('data', function (doc) { var err = schema.consume(doc); if (err) return abort(err, stream, db, cb); }) stream.on('end', function () { debug('db closing'); db.close(function () { debug('db closed'); cb(null, schema); }) }) }
javascript
{ "resource": "" }
q32873
abort
train
function abort (err, stream, db, cb) { debug('aborting with error: ' + err); stream.destroy(); db.close(function () { cb(err); }) }
javascript
{ "resource": "" }
q32874
validate
train
function validate (uri, collection, cb) { if ('function' != typeof cb) { throw new TypeError('cb must be a function'); } if ('string' != typeof collection) { throw new TypeError('collection must be a string'); } if ('string' != typeof uri) { throw new TypeError('uri must be a string'); } }
javascript
{ "resource": "" }
q32875
train
function (texts, options, callback) { if (typeof(options) === 'function') { callback = options; options = {}; } if (Array.isArray(texts)) { texts = texts.map(function (text, i) { return textObj(text, i); }); } else if (typeof(texts) === 'string') { texts = [textObj(texts)]; } options = options || {}; options.language = options.language || 'en'; var body = {}; for (var key in options) { if (options.hasOwnProperty(key)) { body[key] = options[key] } } body.texts = texts; var params = { method: 'POST', url: '/tonality', body: body }; return client.request(params, callback); }
javascript
{ "resource": "" }
q32876
clickRegion
train
function clickRegion( e ) { let pos = { x : e.clientX, y : e.clientY }, region = '', dividant = 4, right = window.innerWidth - (window.innerWidth / dividant), left = (window.innerWidth / dividant), top = (window.innerHeight / dividant), bottom = window.innerHeight - (window.innerHeight / dividant); if( pos.y <= top ) { region = 'top'; } else if( pos.y >= bottom ) { region = 'bottom'; } if( pos.x <= left ) { region = 'left'; } else if( pos.x >= right ) { region = 'right'; } return region; }
javascript
{ "resource": "" }
q32877
getContextPlugin
train
function getContextPlugin(options) { var seneca = this; var plugin = 'get-context'; seneca.wrap(options.pin, function (message, done) { var seneca = this; message.context$ = getContext(seneca); seneca.prior(message, done); }); return {name: plugin}; }
javascript
{ "resource": "" }
q32878
build
train
function build() { console.log('Creating an optimized production build...\n'); webpack(config) .run((err, stats) => { if (err) { printErrors('Failed to compile.', [err]); process.exit(1); } if (stats.compilation.errors.length) { printErrors('Failed to compile.', stats.compilation.errors); process.exit(1); } if (process.env.CI && stats.compilation.warnings.length) { printErrors('Failed to compile.', stats.compilation.warnings); process.exit(1); } logSuccess('Compiled successfully.\n'); console.log('Bundle size details:\n'); printFileSizes(stats); console.log(`\nThe ${chalk.green('build')} folder is ready to be deployed.\n`); }); }
javascript
{ "resource": "" }
q32879
addToFooter
train
function addToFooter(schema, path, unwind) { Object.keys(schema).forEach(function(name) { if (name.slice(0,2) == '__') return true; if (!path && (name == 'id' || name == '_id')) return; if (model.schema.nested[path+name]) { addToFooter(schema[name], path+name+'.', '') } else if (schema[name] && schema[name].tree) { addToFooter(schema[name].tree, path+name+'.'); if (typeof schema[name].options.strict === 'boolean' && !schema[name].options.strict) { footer.push({name:name, path: path+name+'.*'}); } } else if (name === unwind) { addToFooter(schema[name][0].tree, path+name+'.0.') if (typeof schema[name][0].options.strict === 'boolean' && !schema[name][0].options.strict) { footer.push({name:name, path: path+name+'.0.*'}); } } else { if (skipField(path+name)) { return; } footer.push({name:name, path: path+name}) } }); }
javascript
{ "resource": "" }
q32880
diffContentItems
train
function diffContentItems(lhs, rhs) { var d = diff(lhs, rhs, function(key, value) { return value === 'visitors' || value === 'headers'; }); return d; }
javascript
{ "resource": "" }
q32881
extractContent
train
function extractContent(desc) { /* // search all possible matches, returning first find var founds = sites.findMatch(desc.uri); if (founds.length) { var $ = cheerio.load(desc.content); // use first found extractor founds.forEach(function(found) { if ($(found.selector)) { var content = $(found.selector).html(); return { selector: found.selector, content: content }; } }); } // ok, let's try unfluff var uf = unfluff(desc.content); return { selector: 'body', content: desc.content, text: uf.text, title: uf.title }; */ var title = getTitle(desc.content, '<title') || getTitle(desc.content, '<TITLE'); return { selector: 'body', content: desc.content, text: 'NOTEXTRACTED', title: title }; }
javascript
{ "resource": "" }
q32882
getTitle
train
function getTitle(content, tag) { if (!content) { return; } var ts = content.indexOf(tag); if (ts < 0) { return; } var te = content.indexOf('>', ts); var cs = content.indexOf('<', te + 1); var title = content.substring(te + 1, cs); return title.trim(); }
javascript
{ "resource": "" }
q32883
train
function() { var i = Math.floor(_listing.length-1 * Math.random()); return $q.when(_listing[i]); }
javascript
{ "resource": "" }
q32884
train
function(criteria) { var results = []; criteria = angular.isArray(criteria) ? criteria : [criteria]; // Search through each criteria.forEach(function(q) { if(q && q !== '') { _listing.forEach(function(item) { for(var name in item) { if(item[name].toLowerCase().indexOf(q.toLowerCase()) !== -1 && results.indexOf(item) === -1) { results.push(item); } } }); } }); return $q.when(results); }
javascript
{ "resource": "" }
q32885
partialWithArityOfOne
train
function partialWithArityOfOne(fn) { var args = arguments; return function(a) { return partial.apply(this, args).apply(this, arguments); }; }
javascript
{ "resource": "" }
q32886
_getFileSet
train
function _getFileSet (fileSetElement) { var filtered = utils.toBoolean(fileSetElement.getAttribute('filtered'), false); var packaged = utils.toBoolean(fileSetElement.getAttribute('packaged'), false); var encoding = fileSetElement.getAttribute('encoding'); var directory = domutils.getChild(fileSetElement, 'desc', 'directory').textContent; var includes = domutils.selectMatchingXPath('desc:includes/desc:include', fileSetElement); var excludes = domutils.selectMatchingXPath('desc:excludes/desc:exclude', fileSetElement); var fileSet = { filtered: filtered, packaged: packaged, encoding: encoding, directory: directory, includes: [], excludes: [], }; includes.forEach(function (include) { fileSet.includes.push(include.textContent); }); excludes.forEach(function (exclude) { fileSet.excludes.push(exclude.textContent); }); return fileSet; }
javascript
{ "resource": "" }
q32887
_getModule
train
function _getModule (moduleElement) { var id = moduleElement.getAttribute('id'); var dir = moduleElement.getAttribute('dir'); var name = moduleElement.getAttribute('name'); var fileSets = domutils.getChild(moduleElement, 'desc', 'fileSets'); var modules = domutils.getChild(moduleElement, 'desc', 'modules'); var module = { id: id, dir: dir, name: name, fileSets: [], modules: [] }; if (fileSets !== undefined) { var fileSetElements = domutils.selectMatchingXPath('desc:fileSet', fileSets); var numFileSets = fileSetElements.length; for (var fsIdx = 0; fsIdx < numFileSets; fsIdx++) { module.fileSets.push(_getFileSet(fileSetElements[fsIdx])); } } if (modules !== undefined) { var moduleElements = domutils.selectMatchingXPath('desc:module', modules); var numModules = moduleElements.length; for (var mIdx = 0; mIdx < numModules; mIdx++) { module.modules.push(_getModule(moduleElements[mIdx])); } } return module; }
javascript
{ "resource": "" }
q32888
unload
train
function unload() { u.each(opts.sources, function(source) { if (source.src && source.src.unref) { source.src.unref(); } if (source.cache && source.cache.unref) { source.cache.unref(); } }); u.each(opts.outputs, function(output) { if (output.output && output.output.cancel) { output.output.cancel(); } }); if (generator.reload && generator.reload.cancel) { generator.reload.cancel(); } if (generator.clientSave && generator.clientSave.cancel) { generator.clientSave.cancel(); } }
javascript
{ "resource": "" }
q32889
redirect
train
function redirect(url) { var path = u.urlPath(url); var params = u.urlParams(url); var pg = generator.aliase$[path]; if (pg) return { status:301, url:pg._href + params }; pg = generator.redirect$[path]; if (pg) return { status:302, url:pg._href + params }; // customRedirects return params also pg = generator.customRedirect && generator.customRedirect(url); if (pg) return { status:301, url:pg }; }
javascript
{ "resource": "" }
q32890
UnloqApi
train
function UnloqApi(authObj) { if(typeof authObj !== 'object' || authObj === null) { throw new Error('Unloq.Api: First constructor argument must be an instance of unloq.Auth'); } // If we receive only the object with configuration, we try and create the auth object. if(authObj.__type !== 'auth') { var AuthClass = Auth(); authObj = new AuthClass(authObj); } auth = authObj; }
javascript
{ "resource": "" }
q32891
registerApi
train
function registerApi(isApp, apiObject) { if (isApp) { return function (req, res, next) { res.__api = apiObject; return next(); }; }; return function (req, res, next) { res.__modelAPI = apiObject; return next(); }; }
javascript
{ "resource": "" }
q32892
init
train
function init(){ frameUnixTime = utils.getUnixTimeInMilliseconds(); frameDuration = 0; frameDurationClone = 0; timeSinceStart = 0; playTimeSinceStart = 0; appActive = true; appPlaying = true; videoDuration = 0; videoPlaying = false; }
javascript
{ "resource": "" }
q32893
tick
train
function tick(frameTime){ let newFrameUnixTime = utils.getUnixTimeInMilliseconds(); if (frameTime) frameDuration = frameTime; else frameDuration = newFrameUnixTime - frameUnixTime; // dont consider frame duration if app is not active frameDurationClone = appActive ? frameDuration : 0; frameUnixTime = newFrameUnixTime; timeSinceStart += frameDurationClone; if (appPlaying){ playTimeSinceStart += frameDurationClone; } if (videoPlaying){ videoDuration += utils.convertMillisecondsToSecondsFloat(frameDurationClone); } }
javascript
{ "resource": "" }
q32894
init
train
function init(owner, field, layout, val, children) { // {{{2 /** * Field wrapper constructor * * @param owner {Object} Owning wrap list * @param field {Object} Field description object * @param layout {Object} Layout * @param val {*} Field value * * @method constructor */ this.owner = owner; owner.fields.push(this); this.field = field; this.value = val; if (layout) this.layout = layout; if (children) this.children = children; }
javascript
{ "resource": "" }
q32895
condenseify
train
function condenseify(file, options) { if (/\.json$/.test(file)) return through(); var appendNewLine = true , regex = /^[ \t]+$/ , isBlank = false , eol ='\n'; options = options || {}; function transform(line, encoding, next) { if (!line.length) { isBlank = true; return next(); } line = line.toString(); if (!options['keep-non-empty'] && regex.test(line)) return next(); if (isBlank) { isBlank = false; this.push(eol); } appendNewLine = false; this.push(line + eol); next(); } function flush(done) { if (appendNewLine) this.push(eol); done(); } return pumpify(split(), through(transform, flush)); }
javascript
{ "resource": "" }
q32896
removezeros
train
function removezeros(bin){ var i = 0; while((i < bin.length) && (!bin[i])){i++;} if(i == bin.length){ return filledarray(false, 1); }else{ return bin.slice(i); } }
javascript
{ "resource": "" }
q32897
decinputtobin
train
function decinputtobin(decinput){ var len = decinput.length; if(len == 0){return filledarray(false, 1);} var bin = new Array(); var digit = new Array(4); for (var i = 0; i < len; i++){ switch (decinput[i]){ case '0': digit[0] = false; digit[1] = false; digit[2] = false; digit[3] = false; break; case '1': digit[0] = false; digit[1] = false; digit[2] = false; digit[3] = true; break; case '2': digit[0] = false; digit[1] = false; digit[2] = true; digit[3] = false; break; case '3': digit[0] = false; digit[1] = false; digit[2] = true; digit[3] = true; break; case '4': digit[0] = false; digit[1] = true; digit[2] = false; digit[3] = false; break; case '5': digit[0] = false; digit[1] = true; digit[2] = false; digit[3] = true; break; case '6': digit[0] = false; digit[1] = true; digit[2] = true; digit[3] = false; break; case '7': digit[0] = false; digit[1] = true; digit[2] = true; digit[3] = true; break; case '8': digit[0] = true; digit[1] = false; digit[2] = false; digit[3] = false; break; case '9': digit[0] = true; digit[1] = false; digit[2] = false; digit[3] = true; break; default: continue; } bin = binadd(binten(bin), digit); } return removezeros(bin); }
javascript
{ "resource": "" }
q32898
bininputtobin
train
function bininputtobin(bininput){ var len = bininput.length; if(len == 0){return filledarray(false, 1);} var bin = new Array(len); var j = 0; for (var i = 0; i < len; i++){ switch (bininput[i]){ case '0': bin[j++] = false; break; case '1': bin[j++] = true; break; default: break; } } return removezeros(bin.slice(0, j)); }
javascript
{ "resource": "" }
q32899
octinputtobin
train
function octinputtobin(octinput){ var len = octinput.length; if(len == 0){return filledarray(false, 1);} var bin = new Array(len * 3); var j = 0; for (var i = 0; i < len; i++){ switch (octinput[i]){ case '0': bin[j+0] = false; bin[j+1] = false; bin[j+2] = false; j+=3; break; case '1': bin[j+0] = false; bin[j+1] = false; bin[j+2] = true; j+=3; break; case '2': bin[j+0] = false; bin[j+1] = true; bin[j+2] = false; j+=3; break; case '3': bin[j+0] = false; bin[j+1] = true; bin[j+2] = true; j+=3; break; case '4': bin[j+0] = true; bin[j+1] = false; bin[j+2] = false; j+=3; break; case '5': bin[j+0] = true; bin[j+1] = false; bin[j+2] = true; j+=3; break; case '6': bin[j+0] = true; bin[j+1] = true; bin[j+2] = false; j+=3; break; case '7': bin[j+0] = true; bin[j+1] = true; bin[j+2] = true; j+=3; break; default: break; } } return removezeros(bin.slice(0, j)); }
javascript
{ "resource": "" }