_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q54800
train
function(dict, options) { Pair.call(this); this.encoder = new Encoder(dict, true, options); this.decoder = new Decoder(dict, true, options); }
javascript
{ "resource": "" }
q54801
train
function(dict, progressive, options) { /** * Dictionary hash. * @type {Object.<string,number>} */ this.dict = {}; /** * Next dictionary index. * @type {number} */ this.next = 0; if (dict && Array.isArray(dict)) { while (this.next < dict.length) { this.dict[dict[this.next]] = this.next++; } } /** * Whether the encoder is progressive or static. * @type {boolean} */ this.progressive = !!progressive; /** * Options. * @type {Object.<string,*>} */ this.options = options || {}; }
javascript
{ "resource": "" }
q54802
train
function(dict, progressive, options) { /** * Dictionary array. * @type {Array.<string>} */ this.dict = (dict && Array.isArray(dict)) ? dict : []; /** * Whether this is a progressive or a static decoder. * @type {boolean} */ this.progressive = !!progressive; /** * Options. * @type {Object.<string,*>} */ this.options = options || {}; }
javascript
{ "resource": "" }
q54803
determineSelectedBranch
train
function determineSelectedBranch() { var branch = 'stable', path = window.location.pathname; // path is like /en/<branch>/<lang>/build/ -> extract 'lang' // split[0] is an '' because the path starts with the separator branch = path.split('/')[2]; return branch; }
javascript
{ "resource": "" }
q54804
appsAreEqual
train
function appsAreEqual(x, y) { function pp(o) { return JSON.stringify(o); } var xs = pp(x); var ys = pp(y); return xs === ys; }
javascript
{ "resource": "" }
q54805
existsInCache
train
function existsInCache(x, cache) { var found = _.find(cache, function(y) { return appsAreEqual(x, y); }); return !!found; }
javascript
{ "resource": "" }
q54806
train
function(app) { if (!appCache.good) { appCache.good = []; } if (!existsInCache(app, appCache.good)) { appCache.good.push(app); } }
javascript
{ "resource": "" }
q54807
train
function(app) { if (!appCache.bad) { appCache.bad = []; } if (!existsInCache(app, appCache.bad)) { appCache.bad.push(app); } }
javascript
{ "resource": "" }
q54808
train
function() { var globalConfig = getGlobalConfig(); // Read contents of app registry file. return Promise.fromNode(function(cb) { fs.readFile(globalConfig.appRegistry, {encoding: 'utf8'}, cb); }) // Parse contents and return app dirs. .then(function(data) { var json = JSON.parse(data); if (json) { return json; } else { return []; } }) // Handle no entry error. .catch(function(err) { if (err.code === 'ENOENT') { return []; } else { throw err; } }); }
javascript
{ "resource": "" }
q54809
train
function(apps) { var filepath = getGlobalConfig().appRegistry; var tempFilepath = filepath + '.tmp'; // Write to temp file. return Promise.fromNode(function(cb) { fs.writeFile(tempFilepath, JSON.stringify(apps), cb); log.debug(format('Setting app registry with %j', apps)); }) // Rename temp file to normal file. .then(function() { return Promise.fromNode(function(cb) { fs.rename(tempFilepath, filepath, cb); }); }); }
javascript
{ "resource": "" }
q54810
train
function(app) { var filepath = path.join(app.dir, APP_CONFIG_FILENAME); // Read contents of file. return Promise.fromNode(function(cb) { fs.readFile(filepath, {encoding: 'utf8'}, cb); }) // Handle no entry error. .catch(function(err) { if (err.code === 'ENOENT') { cacheBadApp(app); } else { throw new VError(err, 'Failed to load config: %s', filepath); } }) // Return appName. .then(function(data) { var json = util.yaml.dataToJson(data); if (!json) { return null; } else if (!json.name) { log.debug(format('Does NOT contain %s property!', filepath)); return null; } else if (json.name === app.name) { cacheApp(app); return app; } else if (json.name !== app.name) { cacheBadApp(app); return null; } else { return null; } }); }
javascript
{ "resource": "" }
q54811
train
function() { // Get list of dirs from app registry. return getAppRegistry() // Map app dirs to app names. .then(inspectDirs) .all() .tap(function(appRegistryApps) { log.debug(format('Apps in registry: %j', appRegistryApps)); }); }
javascript
{ "resource": "" }
q54812
train
function(cache) { // Init a promise. return Promise.resolve() .then(function() { if (!_.isEmpty(appCache)) { // Return cached value. return appCache[cache] || []; } else { // Reload and cache app dirs, then get app dir from cache again. return list() .then(function() { return appCache[cache] || []; }); } }); }
javascript
{ "resource": "" }
q54813
train
function() { // Get app. return kbox.app.get(self.name) // Ignore errors. .catch(function() {}) .then(function(app) { if (app) { // Return app. return app; } else { // Take a short delay then try again. return $q.delay(5 * 1000) .then(function() { return getApp(); }); } }); }
javascript
{ "resource": "" }
q54814
reloadSites
train
function reloadSites() { function reload() { sites.get() .then(function(sites) { $scope.ui.sites = sites; }); } /* * Reload sites mutliple times, because sometimes updates to list of sites * aren't ready immediately. */ // Reload sites immediately. reload(); // Reload sites again after 5 seconds. setTimeout(reload, 1000 * 5); // Reload sites again after 15 seconds. setTimeout(reload, 1000 * 15); }
javascript
{ "resource": "" }
q54815
train
function(task, type) { // Make sure we are going to add a task with a real app if (!get(type)) { // todo: something useful besides silentfail // todo: never forget how funny this was/is/will always be throw new Error('F!'); } // Get the app plugin metadata var app = get(type); // Create the basic task data task.path = ['create', type]; task.category = 'global'; task.description = app.task.description; task.options = parseOptions(app.options, 'task'); // Extract our inquiry var inquiry = _.identity(parseOptions(app.options, 'inquire')); // Add a generic app options to build elsewhere task.options.push({ name: 'dir', kind: 'string', description: 'Creates the app in this directory. Defaults to CWD.', }); // Specify an alternate location to grab the app skeleton task.options.push({ name: 'from', kind: 'string', description: 'Local path to override app skeleton (be careful with this)', }); // The func that this app create task runs task.func = function(done) { // Grab the CLI options that are available var options = this.options; // Filter out interactive questions based on passed in options var questions = kbox.util.cli.filterQuestions(inquiry, options); // Launch the inquiry inquirer.prompt(questions, function(answers) { // Add the create type to the results object // NOTE: the create type can be different than the // type found in the config aka config.type = php but // answers._type = drupal7 answers._type = type; // Create the app return createApp(app, _.merge({}, options, answers)) // Return. .nodeify(done); }); }; }
javascript
{ "resource": "" }
q54816
train
function(node, path) { // Validate. if (!isBranch(node)) { assert(false); } if (path.length === 0) { assert(false); } // Partition head and tail. var hd = path[0]; var tl = path.slice(1); // Find a child of node that matches path. var cursor = _.find(node.children, function(obj) { return getName(obj) === hd; }); // Conflicting tasks exist in task tree. if (cursor && isTask(cursor)) { throw new Error('Task already exists: ' + task.path.join(' -> ')); } // Continue. if (tl.length === 0) { // We are at the end of the path. task.path = [hd]; if (cursor) { addChild(cursor, task); } else { addChild(node, task); } return; } else { // We are NOT at the end of the path. if (!cursor) { cursor = createBranch(hd); addChild(node, cursor); } return rec(cursor, tl); } }
javascript
{ "resource": "" }
q54817
train
function(node, payload) { if (payload.length === 0) { // Reached end of argv path, so return current node. node.argv = { payload: payload, options: argv.options, rawOptions: argv.rawOptions }; return node; } else if (isTask(node)) { // A task has been found along the argv path, so return it. node.argv = { payload: payload, options: argv.options, rawOptions: argv.rawOptions }; return node; } else if (isBranch(node)) { // Get the head of the argv path. var hd = payload[0]; var tl = payload.slice(1); // Find a child of node branch that matches hd. var child = findChild(node, hd); if (child) { // Update the argv path and then recurse with child that was found. return rec(child, tl); } else { // No matching child was found, it's a dead search so return null. return null; } } else { // This should never happen. assert(false); } }
javascript
{ "resource": "" }
q54818
train
function(node) { if (isTask(node)) { // This is a task so do nothing. return [node]; } else if (isBranch(node)) { // Concat map children with a recMap. node.children = _.flatten(_.map(node.children, recMap)); // Sort children. node.children.sort(compareBranchOrTask); // Resolve duplicate named children. // Group children by name. var nameMap = _.groupBy(node.children, getName); // Resolve conflicts. node.children = _.map(_.values(nameMap), function(children) { if (children.length === 1) { // No conflicts so just return head of array. return children[0]; } else { // Resolve conflict by finding a single node with the override flag. var overrides = _.filter(children, function(child) { return child.__override; }); if (overrides.length === 1) { // Conflict resolved. return overrides[0]; } else { // Conflict can not be resolved, throw an error. throw new Error('Conflicting task names can not be resolved: ' + pp(children)); } } }); if (getName(node) === appName) { // Replace this node with this nodes children. _.each(node.children, function(child) { // Mark each child with an override flag so we can resolve conflicts. child.__override = true; }); return node.children; } else { // Just return. return [node]; } } else { // This should never happen. assert(false); } }
javascript
{ "resource": "" }
q54819
train
function(node, lines, parentName, depth) { // Default depth. if (_.isUndefined(depth)) { depth = 0; } // Default parentName. if (_.isUndefined(parentName)) { parentName = 'root'; } if (isTask(node)) { // This is a task so add to lines and nothing further. lines.push({ depth: depth, name: getName(node), parentName: parentName, description: node.description }); } else if (isBranch(node)) { lines.push({ depth: depth, name: getName(node), parentName: parentName }); node.children.forEach(function(child) { recAdd(child, lines, getName(node), depth + 1); }); } else { // This should never happen. assert(false); } }
javascript
{ "resource": "" }
q54820
getEnvironment
train
function getEnvironment(opts) { if (opts.app) { // Merge app env over the process env and return. var processEnv = _.cloneDeep(process.env); var appEnv = opts.app.env.getEnv(); return _.merge(processEnv, appEnv); } else { // Just use process env. return process.env; } }
javascript
{ "resource": "" }
q54821
train
function(name, fn) { try { // Create options. var opts = createInternals(name, fn); // Create new integration instance. var newIntegration = new Integration(opts); // Get key to register with. var key = newIntegration.name; // Ensure this integration isn't already registered. if (integrations[key]) { throw new Error('Integration already exists: ' + key); } // Register integration. integrations[key] = newIntegration; // Return integration. return newIntegration; } catch (err) { // Wrap errors. throw new VError(err, 'Error creating new integration: ' + name); } }
javascript
{ "resource": "" }
q54822
train
function(name) { if (name) { // Find integration by name. var result = integrations[name]; if (!result) { throw new Error('Integration does not exist: ' + name); } return result; } else { // Return entire singleton integration map. return integrations; } }
javascript
{ "resource": "" }
q54823
rec
train
function rec(counter) { // Format next app name to check for. var name = counter ? util.format(opts.template, appName, counter) : appName; // Check if app name exists. return exists(name) .then(function(exists) { // App name already exists. if (exists) { // We've checked for a reasonable amount of app names without finding // one so just return original app name. if (counter > 255) { return appName; // Recurse with an incremented counter. } else if (!counter) { return rec(1); // Recurse with an incremented counter. } else { return rec(counter + 1); } // App name does NOT already exist, we found it! } else { return name; } }); }
javascript
{ "resource": "" }
q54824
rec
train
function rec() { // Start a new promise. return Promise.fromNode(function(cb) { // Apply jitter to interval to get next timeout duration. var duration = applyJitter(opts.jitter, opts.interval); // Init a timeout. setTimeout(function() { // Run handler function. return $q.try(fn) // Handle errors. .catch(function(err) { return errorHandler(err); }) // Resolve promise. .nodeify(cb); }, duration); }) // Recurse unless top flag has been set. .then(function() { if (!stopFlag) { return rec(); } }); }
javascript
{ "resource": "" }
q54825
assignTokens
train
function assignTokens () { var sourceBranch = shelljs.exec('git rev-parse --abbrev-ref HEAD', {silent: true}); var sourceCommit = shelljs.exec('git rev-parse --short HEAD', {silent: true}); if (sourceBranch.code === 0) { tokens.branch = sourceBranch.output.replace(/\n/g, ''); } if (sourceCommit.code === 0) { tokens.commit = sourceCommit.output.replace(/\n/g, ''); } if (shelljs.test('-f', 'package.json', {silent: true})) { tokens.name = JSON.parse(fs.readFileSync('package.json', 'utf8')).name; } else { tokens.name = process.cwd().split('/').pop(); } }
javascript
{ "resource": "" }
q54826
initGit
train
function initGit () { if (!fs.existsSync(path.join(gruntDir, options.dir, '.git'))) { log.subhead('Creating git repository in "' + options.dir + '".'); execWrap('git init'); } }
javascript
{ "resource": "" }
q54827
initRemote
train
function initRemote () { remoteName = "remote-" + crypto.createHash('md5').update(options.remote).digest('hex').substring(0, 6); if (shelljs.exec('git remote', {silent: true}).output.indexOf(remoteName) === -1) { log.subhead('Creating remote.'); execWrap('git remote add ' + remoteName + ' ' + options.remote); } }
javascript
{ "resource": "" }
q54828
gitFetch
train
function gitFetch (dest) { var branch = (options.remoteBranch || options.branch) + (dest ? ':' + options.branch : ''); log.subhead('Fetching "' + options.branch + '" ' + (options.shallowFetch ? 'files' : 'history') + ' from ' + options.remote + '.'); // `--update-head-ok` allows fetch on a branch with uncommited changes execWrap('git fetch --update-head-ok ' + progress + depth + remoteName + ' ' + branch, false, true); }
javascript
{ "resource": "" }
q54829
gitTrack
train
function gitTrack () { var remoteBranch = options.remoteBranch || options.branch; if (shelljs.exec('git config branch.' + options.branch + '.remote', {silent: true}).output.replace(/\n/g, '') !== remoteName) { execWrap('git branch --set-upstream-to=' + remoteName + '/' + remoteBranch + ' ' + options.branch); } }
javascript
{ "resource": "" }
q54830
gitCommit
train
function gitCommit () { var message = options.message .replace(/%sourceName%/g, tokens.name) .replace(/%sourceCommit%/g, tokens.commit) .replace(/%sourceBranch%/g, tokens.branch); // If there are no changes, skip commit if (shelljs.exec('git status --porcelain', {silent: true}).output === '') { log.subhead('No changes to your branch. Skipping commit.'); return; } log.subhead('Committing changes to "' + options.branch + '".'); execWrap('git add -A .'); // generate commit message var commitFile = 'commitFile-' + crypto.createHash('md5').update(message).digest('hex').substring(0, 6); fs.writeFileSync(commitFile, message); execWrap('git commit --file=' + commitFile); fs.unlinkSync(commitFile); }
javascript
{ "resource": "" }
q54831
gitTag
train
function gitTag () { // If the tag exists, skip tagging if (shelljs.exec('git ls-remote --tags --exit-code ' + remoteName + ' ' + options.tag, {silent: true}).code === 0) { log.subhead('The tag "' + options.tag + '" already exists on remote. Skipping tagging.'); return; } log.subhead('Tagging the local repository with ' + options.tag); execWrap('git tag ' + options.tag); }
javascript
{ "resource": "" }
q54832
gitPush
train
function gitPush () { var branch = options.branch; var withForce = options.force ? ' --force ' : ''; if (options.remoteBranch) branch += ':' + options.remoteBranch; log.subhead('Pushing ' + options.branch + ' to ' + options.remote + withForce); execWrap('git push ' + withForce + remoteName + ' ' + branch, false, true); if (options.tag) { execWrap('git push ' + remoteName + ' ' + options.tag); } }
javascript
{ "resource": "" }
q54833
train
function(state) { // Check if state has explicit parent OR we try guess parent from its name var parent = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1]; var isObjectParent = typeof parent === "object"; // if parent is a object reference, then extract the name return isObjectParent ? parent.name : parent; }
javascript
{ "resource": "" }
q54834
train
function(chain, stateRef) { var conf, parentParams, ref = parseStateRef(stateRef), force = false, skip = false; for(var i=0, l=chain.length; i<l; i+=1) { if (chain[i].name === ref.state) { return; } } conf = $state.get(ref.state); // Get breadcrumb options if(conf.ncyBreadcrumb) { if(conf.ncyBreadcrumb.force){ force = true; } if(conf.ncyBreadcrumb.skip){ skip = true; } } if((!conf.abstract || $$options.includeAbstract || force) && !skip) { if(ref.paramExpr) { parentParams = $lastViewScope.$eval(ref.paramExpr); } conf.ncyBreadcrumbLink = $state.href(ref.state, parentParams || $stateParams || {}); conf.ncyBreadcrumbStateRef = stateRef; chain.unshift(conf); } }
javascript
{ "resource": "" }
q54835
train
function(stateRef) { var ref = parseStateRef(stateRef), conf = $state.get(ref.state); if(conf.ncyBreadcrumb && conf.ncyBreadcrumb.parent) { // Handle the "parent" property of the breadcrumb, override the parent/child relation of the state var isFunction = typeof conf.ncyBreadcrumb.parent === 'function'; var parentStateRef = isFunction ? conf.ncyBreadcrumb.parent($lastViewScope) : conf.ncyBreadcrumb.parent; if(parentStateRef) { return parentStateRef; } } return $$parentState(conf); }
javascript
{ "resource": "" }
q54836
train
function (params) { return _.every(_.keys(params), function (key) { return _.contains(put_params, key); }); }
javascript
{ "resource": "" }
q54837
train
function (key, dest) { var path; if (_.last(dest) === '/') { // if the path string is a directory, remove it from the key path = key.replace(dest, ''); } else if (key.replace(dest, '') === '') { path = _.last(key.split('/')); } else { path = key; } return path; }
javascript
{ "resource": "" }
q54838
train
function (options, callback) { fs.stat(options.file_path, function (err, stats) { if (err) { callback(err); } else { var local_date = new Date(stats.mtime).getTime(); var server_date = new Date(options.server_date).getTime(); if (options.compare_date === 'newer') { callback(null, local_date > server_date); } else { callback(null, local_date < server_date); } } }); }
javascript
{ "resource": "" }
q54839
train
function() { if (options.fit) { options.cy.fit(options.eles.nodes(), options.padding); } if (!ready) { ready = true; self.cy.one('layoutready', options.ready); self.cy.trigger({type: 'layoutready', layout: self}); } }
javascript
{ "resource": "" }
q54840
ChannelStream
train
function ChannelStream(chan, encoding){ if(!encoding) encoding = 'binary'; if(typeof chan != 'object' || !chan.isChannel) { log.warn('invalid channel passed to streamize'); return false; } var allowHalfOpen = (chan.type === "thtp") ? true : false; Duplex.call(this,{allowHalfOpen: allowHalfOpen, objectMode:true}) this.on('finish',function(){ chan.send({json:{end:true}}); }); this.on('error',function(err){ if(err == chan.err) return; // ignore our own generated errors chan.send({json:{err:err.toString()}}); }); var stream = this this.on('pipe', function(from){ from.on('end',function(){ stream.end() }) }) chan.receiving = chan_to_stream(this); this._chan = chan; this._encoding = encoding; return this; }
javascript
{ "resource": "" }
q54841
fail
train
function fail(err, cbErr) { if(!err) return; // only catch errors log.warn('chat fail',err); chat.err = err; // TODO error inbox/outbox if(typeof cbErr == 'function') cbErr(err); readyUp(err); }
javascript
{ "resource": "" }
q54842
stamp
train
function stamp() { if(!chat.seq) return fail('chat history overflow, please restart'); var id = lib.hashname.siphash(mesh.hashname, chat.secret); for(var i = 0; i < chat.seq; i++) id = lib.hashname.siphash(id.key,id); chat.seq--; return lib.base32.encode(id); }
javascript
{ "resource": "" }
q54843
sync
train
function sync(id) { if(id == last.json.id) return; // bottoms up, send older first sync(lib.base32.encode(lib.hashname.siphash(mesh.hashname, lib.base32.decode(id)))); stream.write(chat.messages[id]); }
javascript
{ "resource": "" }
q54844
rlog
train
function rlog() { process.stdout.clearLine(); process.stdout.cursorTo(0); console.log.apply(console, arguments); rl.prompt(); }
javascript
{ "resource": "" }
q54845
loadMeshJSON
train
function loadMeshJSON(mesh,hashname, args){ // add/get json store var json = mesh.json_store[hashname]; if(!json) json = mesh.json_store[hashname] = {hashname:hashname,paths:[],keys:{}}; if(args.keys) json.keys = args.keys; // only know a single csid/key if(args.csid && args.key) { json.keys[args.csid] = args.key; } // make sure no buffers Object.keys(json.keys).forEach(function(csid){ if(Buffer.isBuffer(json.keys[csid])) json.keys[csid] = base32.encode(json.keys[csid]); }); return json; }
javascript
{ "resource": "" }
q54846
ready
train
function ready(err, mesh) { // links can be passed in if(Array.isArray(args.links)) args.links.forEach(function forEachLinkArg(linkArg){ if(linkArg.hashname == mesh.hashname) return; // ignore ourselves, happens mesh.link(linkArg); }); cbMesh(err,mesh); }
javascript
{ "resource": "" }
q54847
loaded
train
function loaded(err) { if(err) { log.error(err); cbMesh(err); return false; } return telehash.mesh(args, function(err, mesh){ if(!mesh) return cbMesh(err); // sync links automatically to file whenever they change if(linksFile) mesh.linked(function(json, str){ log.debug('syncing links json',linksFile,str.length); fs.writeFileSync(linksFile, str); }); cbMesh(err, mesh); }); }
javascript
{ "resource": "" }
q54848
handshake_collect
train
function handshake_collect(mesh, id, handshake, pipe, message) { handshake = handshake_bootstrap(handshake); if (!handshake) return false; var valid = handshake_validate(id,handshake, message, mesh); if (!valid) return false; // get all from cache w/ matching at, by type var types = handshake_types(handshake, id); // bail unless we have a link if(!types.link) { log.debug('handshakes w/ no link yet',id,types); return false; } // build a from json container var from = handshake_from(handshake, pipe, types.link) // if we already linked this hashname, just update w/ the new info if(mesh.index[from.hashname]) { log.debug('refresh link handshake') from.sync = false; // tell .link to not auto-sync! return mesh.link(from); } else { } log.debug('untrusted hashname',from); from.received = {packet:types.link._message, pipe:pipe} // optimization hints as link args from.handshake = types; // include all handshakes if(mesh.accept) mesh.accept(from); return false; }
javascript
{ "resource": "" }
q54849
bouncer
train
function bouncer(err) { if(!err) return; var json = {err:err}; json.c = inner.json.c; log.debug('bouncing open',json); link.x.send({json:json}); }
javascript
{ "resource": "" }
q54850
peer_send
train
function peer_send(packet, link, cbSend) { var router = mesh.index[to]; if(!router) return cbSend('cannot peer to an unknown router: '+pipe.to); if(!router.x) return cbSend('cannot peer yet via this router: '+pipe.to); if(!link) return cbSend('requires link'); // no packet means try to send our keys if(!packet) { Object.keys(mesh.keys).forEach(function(csid){ if(link.csid && link.csid != csid) return; // if we know the csid, only send that key var json = {type:'peer',peer:link.hashname,c:router.x.cid()}; var body = lob.encode(hashname.intermediates(mesh.keys), hashname.key(csid, mesh.keys)); var attach = lob.encode({type:'link', csid:csid}, body); log.debug('sending peer key to',router.hashname,json,csid); router.x.send({json:json,body:attach}); }); return; } // if it's an encrypted channel packet, pass through direct to router if(packet.head.length == 0) return router.x.sending(packet); // otherwise we're always creating a new peer channel to carry the request var json = {type:'peer',peer:link.hashname,c:router.x.cid()}; var body = lob.encode(packet); log.debug('sending peer handshake to',router.hashname,json,body); router.x.send({json:json,body:body}); cbSend(); }
javascript
{ "resource": "" }
q54851
mapInactives
train
function mapInactives() { var mappedStates = {}; angular.forEach(inactiveStates, function (state, name) { var stickyAncestors = getStickyStateStack(state); for (var i = 0; i < stickyAncestors.length; i++) { var parent = stickyAncestors[i].parent; mappedStates[parent.name] = mappedStates[parent.name] || []; mappedStates[parent.name].push(state); } if (mappedStates['']) { // This is necessary to compute Transition.inactives when there are sticky states are children to root state. mappedStates['__inactives'] = mappedStates['']; // jshint ignore:line } }); return mappedStates; }
javascript
{ "resource": "" }
q54852
getStickyStateStack
train
function getStickyStateStack(state) { var stack = []; if (!state) return stack; do { if (state.sticky) stack.push(state); state = state.parent; } while (state); stack.reverse(); return stack; }
javascript
{ "resource": "" }
q54853
train
function (state) { // Keep locals around. inactiveStates[state.self.name] = state; // Notify states they are being Inactivated (i.e., a different // sticky state tree is now active). state.self.status = 'inactive'; if (state.self.onInactivate) $injector.invoke(state.self.onInactivate, state.self, state.locals.globals); }
javascript
{ "resource": "" }
q54854
train
function (exiting, exitQueue, onExit) { var exitingNames = {}; angular.forEach(exitQueue, function (state) { exitingNames[state.self.name] = true; }); angular.forEach(inactiveStates, function (inactiveExiting, name) { // TODO: Might need to run the inactivations in the proper depth-first order? if (!exitingNames[name] && inactiveExiting.includes[exiting.name]) { if (DEBUG) $log.debug("Exiting " + name + " because it's a substate of " + exiting.name + " and wasn't found in ", exitingNames); if (inactiveExiting.self.onExit) $injector.invoke(inactiveExiting.self.onExit, inactiveExiting.self, inactiveExiting.locals.globals); angular.forEach(inactiveExiting.locals, function(localval, key) { delete inactivePseudoState.locals[key]; }); inactiveExiting.locals = null; inactiveExiting.self.status = 'exited'; delete inactiveStates[name]; } }); if (onExit) $injector.invoke(onExit, exiting.self, exiting.locals.globals); exiting.locals = null; exiting.self.status = 'exited'; delete inactiveStates[exiting.self.name]; }
javascript
{ "resource": "" }
q54855
train
function (entering, params, onEnter, updateParams) { var inactivatedState = getInactivatedState(entering); if (inactivatedState && (updateParams || !getInactivatedState(entering, params))) { var savedLocals = entering.locals; this.stateExiting(inactivatedState); entering.locals = savedLocals; } entering.self.status = 'entered'; if (onEnter) $injector.invoke(onEnter, entering.self, entering.locals.globals); }
javascript
{ "resource": "" }
q54856
SurrogateState
train
function SurrogateState(type) { return { resolve: { }, locals: { globals: root && root.locals && root.locals.globals }, views: { }, self: { }, params: { }, ownParams: ( versionHeuristics.hasParamSet ? { $$equals: function() { return true; } } : []), surrogateType: type }; }
javascript
{ "resource": "" }
q54857
protoKeys
train
function protoKeys(object, ignoreKeys) { var result = []; for (var key in object) { if (!ignoreKeys || ignoreKeys.indexOf(key) === -1) result.push(key); } return result; }
javascript
{ "resource": "" }
q54858
train
function(opts){ var buildPath = (opts && opts.path) || this.options.path; assert(!!buildPath, "Path needs to be provided"); var p = path.resolve(buildPath); var stealCordova = this; return new Promise(function(resolve, reject){ fse.exists(p, function(doesExist){ if(doesExist) { resolve(); } else { stealCordova.init(opts) .then(function() { resolve(); }) .catch(reject); } }); }); }
javascript
{ "resource": "" }
q54859
assign
train
function assign(obj, props) { for (let i in props) { if (props.hasOwnProperty(i)) { obj[i] = props[i]; } } return obj; }
javascript
{ "resource": "" }
q54860
deepAssign
train
function deepAssign(target, source) { //if they aren't both objects, use target if it is defined (null/0/false/etc. are OK), otherwise use source if (!(target && source && typeof target==='object' && typeof source==='object')) { return typeof target !== 'undefined' ? target : source; } let out = assign({}, target); for (let i in source) { if (source.hasOwnProperty(i)) { out[i] = deepAssign(target[i], source[i]); } } return out; }
javascript
{ "resource": "" }
q54861
onSuccess
train
function onSuccess(stream) { videoStream = stream; if (window.hasModernUserMedia) { videoElem.srcObject = stream; } else if (navigator.mozGetUserMedia) { // Firefox supports a src object videoElem.mozSrcObject = stream; } else { var vendorURL = window.URL || window.webkitURL; videoElem.src = vendorURL.createObjectURL(stream); } /* Start playing the video to show the stream from the webcam */ videoElem.play(); $scope.config.video = videoElem; /* Call custom callback */ if ($scope.onStream) { $scope.onStream({stream: stream}); } }
javascript
{ "resource": "" }
q54862
onFailure
train
function onFailure(err) { _removeDOMElement(placeholder); if (console && console.debug) { console.debug('The following error occured: ', err); } /* Call custom callback */ if ($scope.onError) { $scope.onError({err:err}); } return; }
javascript
{ "resource": "" }
q54863
train
function (dimensions, fullScreenMode) { var w = dimensions.width; var h = dimensions.height; var minW = dimensions.minWidth; var minH = dimensions.minHeight; var maxW = dimensions.maxWidth; var maxH = dimensions.maxHeight; var displayW = w; var displayH = h; if (!fullScreenMode) { // resize the image if it is too small if (w < minW && h < minH) { // the image is both too thin and short, so compare the aspect ratios to // determine whether to min the width or height if (w / h > maxW / maxH) { displayH = minH; displayW = Math.round(w * minH / h); } else { displayW = minW; displayH = Math.round(h * minW / w); } } else if (w < minW) { // the image is too thin displayW = minW; displayH = Math.round(h * minW / w); } else if (h < minH) { // the image is too short displayH = minH; displayW = Math.round(w * minH / h); } // resize the image if it is too large if (w > maxW && h > maxH) { // the image is both too tall and wide, so compare the aspect ratios // to determine whether to max the width or height if (w / h > maxW / maxH) { displayW = maxW; displayH = Math.round(h * maxW / w); } else { displayH = maxH; displayW = Math.round(w * maxH / h); } } else if (w > maxW) { // the image is too wide displayW = maxW; displayH = Math.round(h * maxW / w); } else if (h > maxH) { // the image is too tall displayH = maxH; displayW = Math.round(w * maxH / h); } } else { // full screen mode var ratio = Math.min(maxW / w, maxH / h); var zoomedW = Math.round(w * ratio); var zoomedH = Math.round(h * ratio); displayW = Math.max(minW, zoomedW); displayH = Math.max(minH, zoomedH); } return { 'width': displayW || 0, 'height': displayH || 0 // NaN is possible when dimensions.width is 0 }; }
javascript
{ "resource": "" }
q54864
train
function () { // get the window dimensions var windowWidth = $window.innerWidth; var windowHeight = $window.innerHeight; // calculate the max/min dimensions for the image var imageDimensionLimits = Lightbox.calculateImageDimensionLimits({ 'windowWidth': windowWidth, 'windowHeight': windowHeight, 'imageWidth': imageWidth, 'imageHeight': imageHeight }); // calculate the dimensions to display the image var imageDisplayDimensions = calculateImageDisplayDimensions( angular.extend({ 'width': imageWidth, 'height': imageHeight, 'minWidth': 1, 'minHeight': 1, 'maxWidth': 3000, 'maxHeight': 3000, }, imageDimensionLimits), Lightbox.fullScreenMode ); // calculate the dimensions of the modal container var modalDimensions = Lightbox.calculateModalDimensions({ 'windowWidth': windowWidth, 'windowHeight': windowHeight, 'imageDisplayWidth': imageDisplayDimensions.width, 'imageDisplayHeight': imageDisplayDimensions.height }); // resize the image element.css({ 'width': imageDisplayDimensions.width + 'px', 'height': imageDisplayDimensions.height + 'px' }); // setting the height on .modal-dialog does not expand the div with the // background, which is .modal-content angular.element( document.querySelector('.lightbox-modal .modal-dialog') ).css({ 'width': formatDimension(modalDimensions.width) }); // .modal-content has no width specified; if we set the width on // .modal-content and not on .modal-dialog, .modal-dialog retains its // default width of 600px and that places .modal-content off center angular.element( document.querySelector('.lightbox-modal .modal-content') ).css({ 'height': formatDimension(modalDimensions.height) }); }
javascript
{ "resource": "" }
q54865
train
function () { var state = this.state, currentPage = state.pages[state.currentPage - 1], rowIndex = currentPage.rowIndex, nextRow = state.rows[rowIndex + 1]; return nextRow && nextRow[0] + 1 || state.currentPage; }
javascript
{ "resource": "" }
q54866
train
function () { var state = this.state, currentPage = state.pages[state.currentPage - 1], rowIndex = currentPage.rowIndex, prevRow = state.rows[rowIndex - 1]; return prevRow && prevRow[0] + 1 || state.currentPage; }
javascript
{ "resource": "" }
q54867
findCircularDependencies
train
function findCircularDependencies(componentName, dependencies, path) { var i; path = path || componentName; for (i = 0; i < dependencies.length; ++i) { if (componentName === dependencies[i]) { throw new Error('Circular dependency detected: ' + path + '->' + dependencies[i]); } else if (components[dependencies[i]]) { findCircularDependencies(componentName, components[dependencies[i]].mixins, path + '->' + dependencies[i]); } } }
javascript
{ "resource": "" }
q54868
train
function (name, mixins, creator) { if (mixins instanceof Function) { creator = mixins; mixins = []; } // make sure this component won't cause a circular mixin dependency findCircularDependencies(name, mixins); components[name] = { mixins: mixins, creator: creator }; }
javascript
{ "resource": "" }
q54869
train
function (name, scope) { var component = components[name]; if (component) { var args = []; for (var i = 0; i < component.mixins.length; ++i) { args.push(this.createComponent(component.mixins[i], scope)); } args.unshift(scope); return component.creator.apply(component.creator, args); } return null; }
javascript
{ "resource": "" }
q54870
train
function (name) { var utility = utilities[name]; if (utility) { if (!utility.instance) { utility.instance = utility.creator(this); } return utility.instance; } return null; }
javascript
{ "resource": "" }
q54871
broadcast
train
function broadcast(messageName, data) { var i, len, instance, messages; for (i = 0, len = instances.length; i < len; ++i) { instance = instances[i]; if (!instance) { continue; } messages = instance.messages || []; if (util.inArray(messageName, messages) !== -1) { if (util.isFn(instance.onmessage)) { instance.onmessage.call(instance, messageName, data); } } } }
javascript
{ "resource": "" }
q54872
destroyComponent
train
function destroyComponent(instance) { if (util.isFn(instance.destroy) && !instance._destroyed) { instance.destroy(); instance._destroyed = true; } }
javascript
{ "resource": "" }
q54873
buildEventObject
train
function buildEventObject(type, data) { var isDefaultPrevented = false; return { type: type, data: data, /** * Prevent the default action for this event * @returns {void} */ preventDefault: function () { isDefaultPrevented = true; }, /** * Return true if preventDefault() has been called on this event * @returns {Boolean} */ isDefaultPrevented: function () { return isDefaultPrevented; } }; }
javascript
{ "resource": "" }
q54874
train
function(type, handler) { var handlers = this._handlers[type], i, len; if (handlers instanceof Array) { if (!handler) { handlers.length = 0; return; } for (i = 0, len = handlers.length; i < len; i++) { if (handlers[i] === handler || handlers[i].handler === handler) { handlers.splice(i, 1); break; } } } }
javascript
{ "resource": "" }
q54875
train
function(type, handler) { var self = this, proxy = function (event) { self.off(type, proxy); handler.call(self, event); }; proxy.handler = handler; this.on(type, proxy); }
javascript
{ "resource": "" }
q54876
train
function() { var url = this.getURL(), $promise = ajax.fetch(url, Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target return $promise.then(processJSONContent).promise({ abort: $promise.abort }); }
javascript
{ "resource": "" }
q54877
train
function(objectType, pageNum) { var img = this.getImage(), retries = Crocodoc.ASSET_REQUEST_RETRIES, loaded = false, url = this.getURL(pageNum), $deferred = $.Deferred(); function loadImage() { img.setAttribute('src', url); } function abortImage() { if (img) { img.removeAttribute('src'); } } // add load and error handlers img.onload = function () { loaded = true; $deferred.resolve(img); }; img.onerror = function () { if (retries > 0) { retries--; abortImage(); loadImage(); } else { img = null; loaded = false; $deferred.reject({ error: 'image failed to load', resource: url }); } }; // load the image loadImage(); return $deferred.promise({ abort: function () { if (!loaded) { abortImage(); $deferred.reject(); } } }); }
javascript
{ "resource": "" }
q54878
train
function (pageNum) { var imgPath = util.template(config.template.img, { page: pageNum }); return config.url + imgPath + config.queryString; }
javascript
{ "resource": "" }
q54879
interpolateCSSText
train
function interpolateCSSText(text, cssText) { // CSS text var stylesheetHTML = '<style>' + cssText + '</style>'; // If using Firefox with no subpx support, add "text-rendering" CSS. // @NOTE(plai): We are not adding this to Chrome because Chrome supports "textLength" // on tspans and because the "text-rendering" property slows Chrome down significantly. // In Firefox, we're waiting on this bug: https://bugzilla.mozilla.org/show_bug.cgi?id=890692 // @TODO: Use feature detection instead (textLength) if (browser.firefox && !subpx.isSubpxSupported()) { stylesheetHTML += '<style>text { text-rendering: geometricPrecision; }</style>'; } // inline the CSS! text = text.replace(inlineCSSRegExp, stylesheetHTML); return text; }
javascript
{ "resource": "" }
q54880
processSVGContent
train
function processSVGContent(text) { if (destroyed) { return; } var query = config.queryString.replace('&', '&#38;'), dataUrlCount; dataUrlCount = util.countInStr(text, 'xlink:href="data:image'); // remove data:urls from the SVG content if the number exceeds MAX_DATA_URLS if (dataUrlCount > MAX_DATA_URLS) { // remove all data:url images that are smaller than 5KB text = text.replace(/<image[\s\w-_="]*xlink:href="data:image\/[^"]{0,5120}"[^>]*>/ig, ''); } // @TODO: remove this, because we no longer use any external assets in this way // modify external asset urls for absolute path text = text.replace(/href="([^"#:]*)"/g, function (match, group) { return 'href="' + config.url + group + query + '"'; }); return scope.get('stylesheet').then(function (cssText) { return interpolateCSSText(text, cssText); }); }
javascript
{ "resource": "" }
q54881
train
function (pageNum) { var svgPath = util.template(config.template.svg, { page: pageNum }); return config.url + svgPath + config.queryString; }
javascript
{ "resource": "" }
q54882
processTextContent
train
function processTextContent(text) { if (destroyed) { return; } // in the text layer, divs are only used for text boxes, so // they should provide an accurate count var numTextBoxes = util.countInStr(text, '<div'); // too many textboxes... don't load this page for performance reasons if (numTextBoxes > MAX_TEXT_BOXES) { return ''; } // remove reference to the styles text = text.replace(/<link rel="stylesheet".*/, ''); return text; }
javascript
{ "resource": "" }
q54883
train
function(objectType, pageNum) { var url = this.getURL(pageNum), $promise; if (cache[pageNum]) { return cache[pageNum]; } $promise = ajax.fetch(url, Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target cache[pageNum] = $promise.then(processTextContent).promise({ abort: function () { $promise.abort(); if (cache) { delete cache[pageNum]; } } }); return cache[pageNum]; }
javascript
{ "resource": "" }
q54884
train
function (pageNum) { var textPath = util.template(config.template.html, { page: pageNum }); return config.url + textPath + config.queryString; }
javascript
{ "resource": "" }
q54885
processStylesheetContent
train
function processStylesheetContent(text) { // @NOTE: There is a bug in IE that causes the text layer to // not render the font when loaded for a second time (i.e., // destroy and recreate a viewer for the same document), so // namespace the font-family so there is no collision if (browser.ie) { text = text.replace(/font-family:[\s\"\']*([\w-]+)\b/g, '$0-' + config.id); } return text; }
javascript
{ "resource": "" }
q54886
train
function() { if ($cachedPromise) { return $cachedPromise; } var $promise = ajax.fetch(this.getURL(), Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target $cachedPromise = $promise.then(processStylesheetContent).promise({ abort: function () { $promise.abort(); $cachedPromise = null; } }); return $cachedPromise; }
javascript
{ "resource": "" }
q54887
parseOptions
train
function parseOptions(options) { options = util.extend(true, {}, options || {}); options.method = options.method || 'GET'; options.headers = options.headers || []; options.data = options.data || ''; options.withCredentials = !!options.withCredentials; if (typeof options.data !== 'string') { options.data = $.param(options.data); if (options.method !== 'GET') { options.data = options.data; options.headers.push(['Content-Type', 'application/x-www-form-urlencoded']); } } return options; }
javascript
{ "resource": "" }
q54888
setHeaders
train
function setHeaders(req, headers) { var i; for (i = 0; i < headers.length; ++i) { req.setRequestHeader(headers[i][0], headers[i][1]); } }
javascript
{ "resource": "" }
q54889
doXHR
train
function doXHR(url, method, data, headers, withCredentials, success, fail) { var req = support.getXHR(); req.open(method, url, true); req.onreadystatechange = function () { var status; if (req.readyState === 4) { // DONE // remove the onreadystatechange handler, // because it could be called again // @NOTE: we replace it with a noop function, because // IE8 will throw an error if the value is not of type // 'function' when using ActiveXObject req.onreadystatechange = function () {}; try { status = req.status; } catch (e) { // NOTE: IE (9?) throws an error when the request is aborted fail(req); return; } // status is 0 for successful local file requests, so assume 200 if (status === 0 && isRequestToLocalFile(url)) { status = 200; } if (isSuccessfulStatusCode(status)) { success(req); } else { fail(req); } } }; setHeaders(req, headers); // this needs to be after the open call and before the send call req.withCredentials = withCredentials; req.send(data); return req; }
javascript
{ "resource": "" }
q54890
doXDR
train
function doXDR(url, method, data, success, fail) { var req = support.getXDR(); try { req.open(method, url); req.onload = function () { success(req); }; // NOTE: IE (8/9) requires onerror, ontimeout, and onprogress // to be defined when making XDR to https servers req.onerror = function () { fail(req); }; req.ontimeout = function () { fail(req); }; req.onprogress = function () {}; req.send(data); } catch (e) { return fail({ status: 0, statusText: e.message }); } return req; }
javascript
{ "resource": "" }
q54891
train
function (url, options) { var opt = parseOptions(options), method = opt.method, data = opt.data, headers = opt.headers, withCredentials = opt.withCredentials; if (method === 'GET' && data) { url = urlUtil.appendQueryParams(url, data); data = ''; } /** * Function to call on successful AJAX request * @returns {void} * @private */ function ajaxSuccess(req) { if (util.isFn(opt.success)) { opt.success.call(createRequestWrapper(req)); } return req; } /** * Function to call on failed AJAX request * @returns {void} * @private */ function ajaxFail(req) { if (util.isFn(opt.fail)) { opt.fail.call(createRequestWrapper(req)); } return req; } // is XHR supported at all? if (!support.isXHRSupported()) { return opt.fail({ status: 0, statusText: 'AJAX not supported' }); } // cross-domain request? check if CORS is supported... if (urlUtil.isCrossDomain(url) && !support.isCORSSupported()) { // the browser supports XHR, but not XHR+CORS, so (try to) use XDR return doXDR(url, method, data, ajaxSuccess, ajaxFail); } else { // the browser supports XHR and XHR+CORS, so just do a regular XHR return doXHR(url, method, data, headers, withCredentials, ajaxSuccess, ajaxFail); } }
javascript
{ "resource": "" }
q54892
ajaxSuccess
train
function ajaxSuccess(req) { if (util.isFn(opt.success)) { opt.success.call(createRequestWrapper(req)); } return req; }
javascript
{ "resource": "" }
q54893
ajaxFail
train
function ajaxFail(req) { if (util.isFn(opt.fail)) { opt.fail.call(createRequestWrapper(req)); } return req; }
javascript
{ "resource": "" }
q54894
train
function (url, retries) { var req, aborted = false, ajax = this, $deferred = $.Deferred(); /** * If there are retries remaining, make another attempt, otherwise * give up and reject the deferred * @param {Object} error The error object * @returns {void} * @private */ function retryOrFail(error) { if (retries > 0) { // if we have retries remaining, make another request retries--; req = request(); } else { // finally give up $deferred.reject(error); } } /** * Make an AJAX request for the asset * @returns {XMLHttpRequest|XDomainRequest} Request object * @private */ function request() { return ajax.request(url, { success: function () { var retryAfter, req; if (!aborted) { req = this.rawRequest; // check status code for 202 if (this.status === 202 && util.isFn(req.getResponseHeader)) { // retry the request retryAfter = parseInt(req.getResponseHeader('retry-after')); if (retryAfter > 0) { setTimeout(request, retryAfter * 1000); return; } } if (this.responseText) { $deferred.resolve(this.responseText); } else { // the response was empty, so consider this a // failed request retryOrFail({ error: 'empty response', status: this.status, resource: url }); } } }, fail: function () { if (!aborted) { retryOrFail({ error: this.statusText, status: this.status, resource: url }); } } }); } req = request(); return $deferred.promise({ abort: function() { aborted = true; req.abort(); } }); }
javascript
{ "resource": "" }
q54895
request
train
function request() { return ajax.request(url, { success: function () { var retryAfter, req; if (!aborted) { req = this.rawRequest; // check status code for 202 if (this.status === 202 && util.isFn(req.getResponseHeader)) { // retry the request retryAfter = parseInt(req.getResponseHeader('retry-after')); if (retryAfter > 0) { setTimeout(request, retryAfter * 1000); return; } } if (this.responseText) { $deferred.resolve(this.responseText); } else { // the response was empty, so consider this a // failed request retryOrFail({ error: 'empty response', status: this.status, resource: url }); } } }, fail: function () { if (!aborted) { retryOrFail({ error: this.statusText, status: this.status, resource: url }); } } }); }
javascript
{ "resource": "" }
q54896
train
function (list, x, prop) { var val, mid, low = 0, high = list.length; while (low < high) { mid = Math.floor((low + high) / 2); val = prop ? list[mid][prop] : list[mid]; if (val < x) { low = mid + 1; } else { high = mid; } } return low; }
javascript
{ "resource": "" }
q54897
train
function (wait, fn) { var context, args, timeout, result, previous = 0; function later () { previous = util.now(); timeout = null; result = fn.apply(context, args); } return function throttled() { var now = util.now(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = fn.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }
javascript
{ "resource": "" }
q54898
train
function (wait, fn) { var context, args, timeout, timestamp, result; function later() { var last = util.now() - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = fn.apply(context, args); context = args = null; } } return function debounced() { context = this; args = arguments; timestamp = util.now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; }
javascript
{ "resource": "" }
q54899
train
function (css) { var styleEl = document.createElement('style'), cssTextNode = document.createTextNode(css); try { styleEl.setAttribute('type', 'text/css'); styleEl.appendChild(cssTextNode); } catch (err) { // uhhh IE < 9 } document.getElementsByTagName('head')[0].appendChild(styleEl); return styleEl; }
javascript
{ "resource": "" }