_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q64100
test
function(user, identifier, containerIdentifier, revision, target, out, cb) { var containerDef; var systemId; systemId = _sr.findSystem(identifier); if (!systemId) { logger.error(ERR_NOSYSID); return cb(new Error(ERR_NOSYSID)); } var systemRoot = _sr.repoPath(systemId); out.initProgress(9, '--> finding container'); fetchTarget(systemId, target, revision, function(err, target) { if (err) { return cb(err); } _builder.loadMatchingTargets(systemId, revision, target, function(err, targets) { if (err) { return cb(err); } _builder.findContainer(systemId, revision, targets, containerIdentifier, function(err, containerDefId, targets) { if (err) { out.stdout(err); logger.error(err); return cb(err); } if (!containerDefId) { out.stdout(ERR_NOCDEF); logger.error(ERR_NOCDEF); return cb(ERR_NOCDEF); } async.eachSeries(_.values(targets), function(json, cb) { var root = buildSys(json); containerDef = root.containerDefByDefId(containerDefId); json.repoPath = systemRoot; if (!containerDef.specific || !containerDef.specific.repositoryUrl) { return _builder.build(user, systemId, targets, json, containerDef, target, out, cb); } _synchrotron.synch(json, containerDef, out, function(err) { if (err) { out.stdout(err); logger.error(err); return cb(err); } _builder.build(user, systemId, targets, json, containerDef, target, out, cb); }); }, cb); }); }); }); }
javascript
{ "resource": "" }
q64101
test
function(user, systemName, revision, target, out, cb) { var systemId = _sr.findSystem(systemName); if (!systemId) { logger.error(ERR_NOSYSID); return cb(new Error(ERR_NOSYSID)); } logger.info({ systemId: systemId, revision: revision }, 'building all containers'); fetchTarget(systemId, target, revision, function(err, target) { if (err) { return cb(err); } _builder.loadMatchingTargets(systemId, revision, target, function(err, targets) { if (err) { return cb(err); } out.stdout('--> building all containers for ' + targets[Object.keys(targets)[0]].name + ' revision ' + revision + ' target ' + target); var containers = _.chain(targets) .filter(function(value, key) { return target === 'alltargets' || key === target; }) .map(function(target) { return _.map(target.containerDefinitions, function(cdef) { return { id: cdef.id, target: target.topology.name, type: cdef.type }; }); }) .flatten() .reduce(function(acc, cont) { var notPresent = !_.find(acc, function(found) { return found.id === cont.id && found.type === cont.type; }); if (notPresent) { acc.push(cont); } return acc; }, []) .value(); async.eachSeries(containers, function (cont, next) { buildContainer(user, systemId, cont.id, revision, cont.target, out, function(err) { if (err) { out.stderr(err); } // so that buildall fails if one build fail next(err); }); }, cb); }); }); }
javascript
{ "resource": "" }
q64102
test
function(systemId, target, revision, cb) { if (target === 'alltargets') { cb(null, target); } else { _sr.getDeployedRevisionId(systemId, target, function(err, deployedRevId) { if (typeof revision === 'function') { cb = revision; if (!err) { revision = deployedRevId; } else { revision = 'latest'; } } _builder.loadTargets(systemId, revision, function(err, targets) { if (err) { return cb(err); } var candidates = Object.keys(targets).filter(function(candidate) { return candidate.indexOf(target) >= 0; }); if (candidates.length === 0 || candidates.length > 1) { logger.error(ERR_NOTARGET); return cb(new Error(ERR_NOTARGET)); } else { target = candidates[0]; } cb(null, target); }); }); } }
javascript
{ "resource": "" }
q64103
test
function(user, identifier, revisionIdentifier, target, mode, out, cb) { var systemId = _sr.findSystem(identifier); if (!systemId) { logger.error(ERR_NOSYSID); return cb(new Error(ERR_NOSYSID)); } fetchTarget(systemId, target, revisionIdentifier, function(err, target) { if (err) { return cb(err); } _sr.findRevision(systemId, revisionIdentifier, function(err, revisionId) { if (err) { out.stdout(ERR_NOREV); logger.error(ERR_NOREV); return cb(ERR_NOREV); } logger.info({ systemId: systemId, revisionId: revisionId, environment: target }, 'deploy revision'); if (!mode) { mode = 'live'; } if (!revisionId) { return cb(new Error('revisionId is needed to deploy')); } return createAnalyzeAndDeployTask(user, systemId, revisionId, target, mode, out, cb); }); }); }
javascript
{ "resource": "" }
q64104
test
function(user, identifier, revisionIdentifier, target, out, cb) { logger.info('preview revision: ' + identifier + ', ' + revisionIdentifier + ' ' + target); deployRevision(user, identifier, revisionIdentifier, target, 'preview', out, function(err) { cb(err, {plan: out.getPlan(), ops: out.operations()}); }); }
javascript
{ "resource": "" }
q64105
test
function(identifier, cb) { logger.info('list revisions: ' + identifier); if (!identifier) { return cb(new Error('no identifier')); } var systemId = _sr.findSystem(identifier); if (!systemId) { return cb(new Error('system not found')); } _sr.listRevisions(systemId, function(err, revisions) { cb(err, _.first(revisions, 20)); //cb(err, revisions); }); }
javascript
{ "resource": "" }
q64106
test
function(identifier, revisionIdentifier, target, cb) { logger.info('get revision: ' + identifier + ', ' + revisionIdentifier); var systemId = _sr.findSystem(identifier); if (!systemId) { logger.error(ERR_NOSYSID); return cb(new Error(ERR_NOSYSID)); } fetchTarget(systemId, target, revisionIdentifier, function(err, target) { if (err) { return cb(err); } _sr.findRevision(systemId, revisionIdentifier, function(err, revisionId) { if (err) { return cb(err); } _sr.getRevision(systemId, revisionId, target, cb); }); }); }
javascript
{ "resource": "" }
q64107
test
function(user, identifier, comment, out, cb) { logger.info('compile system: ' + identifier); var systemId = _sr.findSystem(identifier); var system; if (!systemId) { logger.error(ERR_NOSYSID); return cb(new Error(ERR_NOSYSID)); } var repoPath = _sr.repoPath(systemId); _compiler.compile(systemId, repoPath, out, function(err, systems) { if (err) { return cb(err); } async.eachSeries(_.keys(systems), function(key, next) { system = systems[key]; _sr.writeFile(system.id, key + '.json', JSON.stringify(system, null, 2), next); }, function(err) { cb(err); }); }); }
javascript
{ "resource": "" }
q64108
test
function(user, identifier, comment, out, cb) { logger.info('commit system: ' + identifier); var systemId = _sr.findSystem(identifier); _sr.commitRevision(user, systemId, comment, function(err, revisionId) { _sr.getDeployedTargets(systemId, function(err, targets) { if (targets) { async.eachSeries(targets, function(target, next) { if (target.commit === 'edits') { _sr.markDeployedRevision(user, systemId, revisionId, target.env, function() { next(); }); } else { next(); } }, function() { cb(err, revisionId); }); } else { cb(err, revisionId); } }); }); }
javascript
{ "resource": "" }
q64109
finalizeBuild
test
function finalizeBuild(sourceReport){ // Something went wrong. Fail the build. if(errorCount > 0) { grunt.fail.warn("Coffeeification failed."); // The build succeeded. Call done to // finish the grunt task. } else { done("Coffeified " + sourceReport.count + ": " + sourceReport.locations); } }
javascript
{ "resource": "" }
q64110
injectCode
test
function injectCode() { var fullpath = path.join(rootpath, "app.js"); var source = fs.readFileSync(fullpath, 'utf8'); var test = /\/\/ALLOY-RESOLVER/.test(source); logger.trace("CODE INJECTED ALREADY: " + test); if(!test) { source = source.replace(/(var\s+Alloy[^;]+;)/g, "$1\n//ALLOY-RESOLVER\nvar process=require('/process');\nAlloy.resolve=new (require('/resolver'))().resolve;\n"); fs.writeFileSync(fullpath, source); } }
javascript
{ "resource": "" }
q64111
fixFiles
test
function fixFiles() { logger.trace("inside fixFiles()"); _.each(registry.files, function(file) { var fullpath = path.join(rootpath, file); var basepath = path.posix.dirname(file); var basefile = path.posix.resolve(file); var source = fs.readFileSync(fullpath, 'utf8'); logger.trace("fixing file: " + fullpath); var requireRegex = /(require)\s*\(((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*)\)/g; var staticRequireRegex = /(require)(?:\(\s*['"])([^'"]+)(?:['"]\s*\))/g; source = source.replace(requireRegex, function($1, $2, $3) { var requestedModule = $2; if(staticRequireRegex.test($1)) { var staticRequireSource = $1; staticRequireSource = staticRequireSource.replace(staticRequireRegex, function($1, $2, $3) { var resolved_path = resolver.resolve($3, basepath); return 'require("' + resolved_path + '")'; }); return staticRequireSource; } else { return 'require(Alloy.resolve(' + $3 + ', "' + basepath + '"))'; } }); fs.writeFileSync(fullpath, source, { mode: 0o755 }); }); }
javascript
{ "resource": "" }
q64112
findFiles
test
function findFiles(rootpath, patterns) { logger.trace("inside findFiles()"); var patterns = patterns || ['**']; if(_.isString(patterns)) { patterns = [patterns]; } var files = _.map(wrench.readdirSyncRecursive(rootpath), function(filename) { return path.posix.sep + replaceBackSlashes(filename); }); var matchedFiles = match(files, patterns, { nocase: true, matchBase: true, dot: true, }); return _.filter(matchedFiles, function(file) { return !fs.statSync(path.join(rootpath, file)).isDirectory(); }) || []; }
javascript
{ "resource": "" }
q64113
loadFiles
test
function loadFiles() { logger.trace("inside loadFiles()"); var allfiles = findFiles(rootpath, includes); var filepaths = _.filter(allfiles, function(filepath) { return !/.+(package\.json)/.test(filepath); }); _.forEach(filepaths, function(filepath) { registry.files.push(filepath); }); var packagepaths = _.filter(allfiles, function(filepath) { return(/.+(package\.json)/.test(filepath)); }); _.forEach(packagepaths, function(filepath) { var content = fs.readFileSync(path.posix.join(rootpath, filepath), 'utf8'); var json = JSON.parse(content); if(json.main) { registry.directories.push({ id: path.posix.dirname(filepath), path: path.posix.resolve(path.posix.join(path.posix.dirname(filepath), json.main)) }); } }); var indexpaths = _.filter(allfiles, function(filepath) { return(/.+(index\.js)/.test(filepath)); }); _.forEach(indexpaths, function(filepath) { var existingdir = _.find(registry.directories, function(dir) { return dir.id === path.posix.dirname(filepath); }); if(!existingdir) { registry.directories.push({ id: path.posix.dirname(filepath), path: filepath }); } }); return registry; }
javascript
{ "resource": "" }
q64114
writeRegistry
test
function writeRegistry() { logger.trace("inside writeRegistry()"); var filepath = path.join(rootpath, "resolver.js"); var content = fs.readFileSync(filepath, 'utf8'); var regex = /(var\s+registry\s+=\s+)[^;]*(;)/g; var modified = content.replace(regex, "$1" + JSON.stringify(registry) + "$2"); fs.writeFileSync(filepath, modified); }
javascript
{ "resource": "" }
q64115
build
test
function build(mode, system, cdef, out, cb) { _containers.getHandler(system, cdef.type, function(err, container) { if (err) { return cb(err); } if (!container) { err = new Error('no matching container available for type: ' + cdef.type); logger.error(err.message); return cb(err); } if (container.build) { out.progress('--> executing container specific build for ' + cdef.id); logger.info({ containerDefinition: cdef.id }, 'executing container specific build'); container.build(mode, system, cdef, out, function(err, specific) { if (err) { logger.error(err); out.stdout(err); return cb(err); } out.progress('--> ' + cdef.id + ' built'); logger.info({ containerDefinition: cdef.id }, 'built'); cb(err); }); } else { out.progress('--> no need to build ' + cdef.id); cb(null, {}); } }); }
javascript
{ "resource": "" }
q64116
findContainer
test
function findContainer(systemId, revision, targets, containerIdentifier, cb) { var cdefId; var types = []; async.filter(_.keys(targets), function(key, next) { _sr.findContainer(systemId, revision, containerIdentifier, key, function(err, containerDefId, cdef) { var def; if (!err && containerDefId) { cdefId = containerDefId; def = _.find(targets[key].containerDefinitions, function(def) { return def.id === cdefId; }); if (types.indexOf(def.type) < 0) { types.push(def.type); return next(true); } } next(false); }); }, function(keys) { var result = keys.reduce(function(acc, key) { acc[key] = targets[key]; return acc; }, {}); cb(null, cdefId, result); }); }
javascript
{ "resource": "" }
q64117
setAppConsts
test
function setAppConsts() { var mergedConstants = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : (0, _seamlessImmutable2.default)(appConsts); // set node app consts if (typeof self === 'undefined' && typeof global !== 'undefined') { global.appConsts = global.appConsts ? _seamlessImmutable2.default.merge(global.appConsts, mergedConstants) : mergedConstants; return global.appConsts; } else if (typeof self !== 'undefined') { // set main & worker threads self.appConsts = self.appConsts ? _seamlessImmutable2.default.merge(self.appConsts, mergedConstants) : mergedConstants; return self.appConsts; } return {}; }
javascript
{ "resource": "" }
q64118
test
function(cb) { fse.readFile(systemsJsonPath, 'utf8', function(err, data) { if (err) { if (err.code !== 'ENOENT') { return cb(err); } fse.mkdirpSync(sysRepoPath); fse.writeFileSync(systemsJsonPath, JSON.stringify(blank, null, 2), 'utf8'); return git.createRepository(sysRepoPath, 'system', '[email protected]', function(err_) { _systems = blank; cb(err_); }); } _systems = JSON.parse(data); cb(); }); }
javascript
{ "resource": "" }
q64119
test
function(user, namespace, name, repoName, repoPath, systemId, cb) { if (!_systems[systemId]) { _systems[systemId] = { name: name, namespace: namespace, repoName: repoName, repoPath: repoPath }; fse.writeFileSync(systemsJsonPath, JSON.stringify(_systems, null, 2), 'utf8'); git.commit(sysRepoPath, 'registered system: ' + repoPath, user.name, user.email, cb); } else { cb(null); } }
javascript
{ "resource": "" }
q64120
test
function(user, systemId, cb) { if (!_systems[systemId]) { return cb(); } var newSystems = _.clone(_systems); delete newSystems[systemId]; fse.writeFileSync(systemsJsonPath, JSON.stringify(newSystems, null, 2), 'utf8'); _systems = newSystems; git.commit(sysRepoPath, 'unregistered system: ' + systemId, user.name, user.email, cb); }
javascript
{ "resource": "" }
q64121
test
function() { var domWrapper; this._children = []; this._createRootHtml(); domWrapper = utils.html.parseHTML(this.html); if (domWrapper.childNodes.length > 1) { throw new Error("Component should have only one root element"); } this.root = domWrapper.firstChild; this.processInstance(); }
javascript
{ "resource": "" }
q64122
test
function() { var i, elements, element, value; if (this._root) { (this.$meta.domProcessors || []).forEach(function(processor) { elements = this._root.querySelectorAll("[" + processor.attribute + "]"); for (i = 0; i < elements.length; i++) { element = elements[i]; value = element.getAttribute(processor.attribute); processor.process(this, element, value); } }, this); } }
javascript
{ "resource": "" }
q64123
test
function(child) { this._validateChild(child); if (child.parent) { child.parent.remove(child); } child.parent = this; this._children.push(child); this.root.appendChild(child.root); if (this.__fastinject__) { this.__fastinject__(child); } // otherwise it will be injected when __fastinject__ is set }
javascript
{ "resource": "" }
q64124
test
function(child) { var index = this._children.indexOf(child); if (index !== -1) { this._children.splice(index, 1); child.root.parentNode.removeChild(child.root); child.destroy(); } }
javascript
{ "resource": "" }
q64125
test
function(child, element, root) { this._children.push(child); (root || this.root).insertBefore(child.root, element); (root || this.root).removeChild(element); }
javascript
{ "resource": "" }
q64126
test
function(repoPath, doc, done) { generify(path.join(__dirname, 'template'), repoPath, { name: doc.name, namespace: doc.namespace, id: doc.id }, done); }
javascript
{ "resource": "" }
q64127
test
function(repoPath) { var sys; if (fse.existsSync(path.join(repoPath, 'system.js'))) { // TODO extract in its own module sys = require(repoPath + '/system.js'); delete require.cache[repoPath + '/system.js']; } if (!sys) { return new Error('missing system.js, is this an nscale repository?'); } if (!sys.name) { return new Error('missing name in system.js, correct and try again'); } if (!sys.namespace) { return new Error('missing namespace in system.js, correct and try again'); } if (!sys.id) { return new Error('missing id in system.js, correct and try again'); } }
javascript
{ "resource": "" }
q64128
test
function(user, namespace, name, cwd, cb) { var repoName = name; var doc = _.extend({}, blank); var repoPath = path.join(cwd, repoName); doc.name = name; doc.namespace = namespace; doc.id = uuid.v4(); if (!fse.existsSync(repoPath)) { fse.mkdirpSync(repoPath); initNscaleFiles(repoPath, doc, function() { git.createRepository(repoPath, user.name, user.email, function(err) { if (err) { return cb(err); } _meta.register(user, namespace, name, repoName, cwd + '/' + repoName, doc.id, function(err) { writeTimeline(user, doc.id, 'create', 'system created', function() { // swallow any errors here cb(err, {id: doc.id, err: err}); }); }); }); }); } else { cb(null, { id: _meta.repoId(repoName), err: null}); } }
javascript
{ "resource": "" }
q64129
test
function(user, path_, cwd, cb) { var repoPath = path.resolve(cwd, path_); var sys; var validationError = validateSystem(repoPath); if (validationError) { return cb(validationError); } sys = require(repoPath + '/system.js'); delete require.cache[repoPath + '/system.js']; _meta.register(user, sys.namespace, sys.name, path.basename(repoPath), repoPath, sys.id, function(err) { writeTimeline(user, sys.id, 'link', 'system linked', function() { cb(err, {id: sys.id, err: err}); }); }); }
javascript
{ "resource": "" }
q64130
test
function(user, systemId, cb) { writeTimeline(user, systemId, 'system unlinked', function() { // swallow any errors here _meta.unregister(user, systemId, function(err) { cb(err); }); }); }
javascript
{ "resource": "" }
q64131
test
function(systemId, fileName, contents, cb) { var repoPath = _meta.repoPath(systemId); fse.writeFile(path.join(repoPath, fileName), contents, 'utf8', cb); }
javascript
{ "resource": "" }
q64132
test
function(systemId, target, cb) { listRevisions(systemId, function(err, revs) { if (err) { return cb(err); } getRevision(systemId, revs[0].id, target, cb); }); }
javascript
{ "resource": "" }
q64133
test
function(systemId, revisionId, target, cb) { var repoPath = _meta.repoPath(systemId); git.getFileRevision(repoPath, revisionId, target + '.json', function(err, rev) { if (err) { return cb(err); } var s; try { s = JSON.parse(rev); } catch (e) { return cb(new Error('invalid system definition: ' + e.message), null); } cb(err, s); }); }
javascript
{ "resource": "" }
q64134
test
function(systemId, revisionId, target, cb) { if (revisionId === EDITS) { _getOnDiskVersion(systemId, revisionId, target, cb); } else { findRevision(systemId, revisionId, function(err, rev) { if (err) { return cb(err); } if (rev === EDITS) { _getOnDiskVersion(systemId, revisionId, target, cb); } else { _getRevision(systemId, rev, target, cb); } }); } }
javascript
{ "resource": "" }
q64135
test
function(systemId, env, cb) { var repoPath = _meta.repoPath(systemId); var tagName = baseTag + env; var editsTagName = editsTag + env; ngit.Repository.open(repoPath, function(err, repo) { if (err) { return cb(err); } ngit.Reference.nameToId(repo, tagName, function(err, head) { if (err && (!err.message || err.message.indexOf('not found') === -1)) { return cb(err); } if (head) { cb(null, head.toString()); } else { ngit.Reference.nameToId(repo, editsTagName, function(err) { if (err) { return cb(err); } cb(null, EDITS); }); } }); }); }
javascript
{ "resource": "" }
q64136
test
function(systemId, cb) { var repoPath = _meta.repoPath(systemId); getDeployedTargets(systemId, function(err, targets) { if (err) { return cb(err); } git.listRevisions(repoPath, function(err, revisions) { revisions.forEach(function(revision) { var deployedTo = _.find(targets, function(target) { return target.commit === revision.id; }); if (deployedTo) { revision.deployedTo = deployedTo.env; } }); cb(err, revisions); }); }); }
javascript
{ "resource": "" }
q64137
test
function(systemId, identifier, cb) { var re = new RegExp('^' + identifier + '.*', ['i']); var revision; if (identifier !== 'head' && identifier !== 'latest') { listRevisions(systemId, function(err, revisions) { revision = _.find(revisions, function(revision) { return re.test(revision.id); }); if (revision) { cb(err, revision.id); } else { cb(new Error('revision not found')); } }); } else { getHeadRevisionId(systemId, cb); } }
javascript
{ "resource": "" }
q64138
test
function (environment, baseConfig) { if ('emoji' in baseConfig) { if (!baseConfig.emoji) { _emojiConfig = false; } else { Object.keys(_defaultEmojiConfig).forEach(function (key) { _emojiConfig[key] = baseConfig.emoji.hasOwnProperty(key) ? baseConfig.emoji[key] : _defaultEmojiConfig[key]; }); } } else { _emojiConfig = _defaultEmojiConfig; } if (environment === 'development') { return { emoji: _emojiConfig, contentSecurityPolicy: { 'script-src': "'self' 'unsafe-eval' 'unsafe-inline'" } }; } return { emoji: _emojiConfig }; }
javascript
{ "resource": "" }
q64139
test
function(analyzed) { var containers = analyzed.topology.containers; var targets = []; _.each(containers, function(c) { if (c.containerDefinitionId.indexOf('__proxy') === 0) { var cdef = _.find(analyzed.containerDefinitions, function(cdef) { return cdef.id === c.containerDefinitionId; }); targets.push({containerDef: cdef, container: c}); } }); return targets; }
javascript
{ "resource": "" }
q64140
test
function( model, relation, options ) { var type = !_.isString( relation.type ) ? relation.type : Backbone[ relation.type ] || this.getObjectByName( relation.type ); if ( type && type.prototype instanceof Backbone.Relation ) { new type( model, relation, options ); // Also pushes the new Relation into `model._relations` } else { Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid relation type!', relation ); } }
javascript
{ "resource": "" }
q64141
test
function( modelType ) { _.find( this._subModels, function( subModelDef ) { return _.find( subModelDef.subModels || [], function( subModelTypeName, typeValue ) { var subModelType = this.getObjectByName( subModelTypeName ); if ( modelType === subModelType ) { // Set 'modelType' as a child of the found superModel subModelDef.superModelType._subModels[ typeValue ] = modelType; // Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'. modelType._superModel = subModelDef.superModelType; modelType._subModelTypeValue = typeValue; modelType._subModelTypeAttribute = subModelDef.superModelType.prototype.subModelTypeAttribute; return true; } }, this ); }, this ); }
javascript
{ "resource": "" }
q64142
test
function( relation ) { var exists = _.any( this._reverseRelations, function( rel ) { return _.all( relation || [], function( val, key ) { return val === rel[ key ]; }); }); if ( !exists && relation.model && relation.type ) { this._reverseRelations.push( relation ); this._addRelation( relation.model, relation ); this.retroFitRelation( relation ); } }
javascript
{ "resource": "" }
q64143
test
function( relation ) { var exists = _.any( this._orphanRelations, function( rel ) { return _.all( relation || [], function( val, key ) { return val === rel[ key ]; }); }); if ( !exists && relation.model && relation.type ) { this._orphanRelations.push( relation ); } }
javascript
{ "resource": "" }
q64144
test
function() { // Make sure to operate on a copy since we're removing while iterating _.each( this._orphanRelations.slice( 0 ), function( rel ) { var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel ); if ( relatedModel ) { this.initializeRelation( null, rel ); this._orphanRelations = _.without( this._orphanRelations, rel ); } }, this ); }
javascript
{ "resource": "" }
q64145
test
function( relation ) { var coll = this.getCollection( relation.model, false ); coll && coll.each( function( model ) { if ( !( model instanceof relation.model ) ) { return; } new relation.type( model, relation ); }, this ); }
javascript
{ "resource": "" }
q64146
test
function( type, create ) { if ( type instanceof Backbone.RelationalModel ) { type = type.constructor; } var rootModel = type; while ( rootModel._superModel ) { rootModel = rootModel._superModel; } var coll = _.find( this._collections, function(item) { return item.model === rootModel; }); if ( !coll && create !== false ) { coll = this._createCollection( rootModel ); } return coll; }
javascript
{ "resource": "" }
q64147
test
function( name ) { var parts = name.split( '.' ), type = null; _.find( this._modelScopes, function( scope ) { type = _.reduce( parts || [], function( memo, val ) { return memo ? memo[ val ] : undefined; }, scope ); if ( type && type !== scope ) { return true; } }, this ); return type; }
javascript
{ "resource": "" }
q64148
test
function( type, item ) { var id = _.isString( item ) || _.isNumber( item ) ? item : null; if ( id === null ) { if ( item instanceof Backbone.RelationalModel ) { id = item.id; } else if ( _.isObject( item ) ) { id = item[ type.prototype.idAttribute ]; } } // Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179') if ( !id && id !== 0 ) { id = null; } return id; }
javascript
{ "resource": "" }
q64149
test
function( type, item ) { var id = this.resolveIdForItem( type, item ); var coll = this.getCollection( type ); // Because the found object could be of any of the type's superModel // types, only return it if it's actually of the type asked for. if ( coll ) { var obj = coll.get( id ); if ( obj instanceof type ) { return obj; } } return null; }
javascript
{ "resource": "" }
q64150
test
function( model ) { var coll = this.getCollection( model ); if ( coll ) { var modelColl = model.collection; coll.add( model ); this.listenTo( model, 'destroy', this.unregister, this ); this.listenTo( model, 'relational:unregister', this.unregister, this ); model.collection = modelColl; } }
javascript
{ "resource": "" }
q64151
test
function( model, id ) { var coll = this.getCollection( model ), duplicate = coll && coll.get( id ); if ( duplicate && model !== duplicate ) { if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { console.warn( 'Duplicate id! Old RelationalModel=%o, new RelationalModel=%o', duplicate, model ); } throw new Error( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" ); } }
javascript
{ "resource": "" }
q64152
test
function( model, collection, options ) { this.stopListening( model ); var coll = this.getCollection( model ); coll && coll.remove( model, options ); }
javascript
{ "resource": "" }
q64153
test
function() { var i = this.instance, k = this.key, m = this.model, rm = this.relatedModel, warn = Backbone.Relational.showWarnings && typeof console !== 'undefined'; if ( !m || !k || !rm ) { warn && console.warn( 'Relation=%o: missing model, key or relatedModel (%o, %o, %o).', this, m, k, rm ); return false; } // Check if the type in 'model' inherits from Backbone.RelationalModel if ( !( m.prototype instanceof Backbone.RelationalModel ) ) { warn && console.warn( 'Relation=%o: model does not inherit from Backbone.RelationalModel (%o).', this, i ); return false; } // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel if ( !( rm.prototype instanceof Backbone.RelationalModel ) ) { warn && console.warn( 'Relation=%o: relatedModel does not inherit from Backbone.RelationalModel (%o).', this, rm ); return false; } // Check if this is not a HasMany, and the reverse relation is HasMany as well if ( this instanceof Backbone.HasMany && this.reverseRelation.type === Backbone.HasMany ) { warn && console.warn( 'Relation=%o: relation is a HasMany, and the reverseRelation is HasMany as well.', this ); return false; } // Check if we're not attempting to create a relationship on a `key` that's already used. if ( i && _.keys( i._relations ).length ) { var existing = _.find( i._relations, function( rel ) { return rel.key === k; }, this ); if ( existing ) { warn && console.warn( 'Cannot create relation=%o on %o for model=%o: already taken by relation=%o.', this, k, i, existing ); return false; } } return true; }
javascript
{ "resource": "" }
q64154
test
function() { this.stopListening(); if ( this instanceof Backbone.HasOne ) { this.setRelated( null ); } else if ( this instanceof Backbone.HasMany ) { this.setRelated( this._prepareCollection() ); } _.each( this.getReverseRelations(), function( relation ) { relation.removeRelated( this.instance ); }, this ); }
javascript
{ "resource": "" }
q64155
test
function( keyContents ) { this.keyContents = keyContents; this.keyId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, this.keyContents ); }
javascript
{ "resource": "" }
q64156
test
function( model, coll, options ) { if ( ( this.keyId || this.keyId === 0 ) && model.id === this.keyId ) { // since 0 can be a valid `id` as well this.addRelated( model, options ); this.keyId = null; } }
javascript
{ "resource": "" }
q64157
test
function( collection ) { if ( this.related ) { this.stopListening( this.related ); } if ( !collection || !( collection instanceof Backbone.Collection ) ) { var options = _.isFunction( this.options.collectionOptions ) ? this.options.collectionOptions( this.instance ) : this.options.collectionOptions; collection = new this.collectionType( null, options ); } collection.model = this.relatedModel; if ( this.options.collectionKey ) { var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey; if ( collection[ key ] && collection[ key ] !== this.instance ) { if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey ); } } else if ( key ) { collection[ key ] = this.instance; } } this.listenTo( collection, 'relational:add', this.handleAddition ) .listenTo( collection, 'relational:remove', this.handleRemoval ) .listenTo( collection, 'relational:reset', this.handleReset ); return collection; }
javascript
{ "resource": "" }
q64158
test
function( keyContents ) { this.keyContents = keyContents instanceof Backbone.Collection ? keyContents : null; this.keyIds = []; if ( !this.keyContents && ( keyContents || keyContents === 0 ) ) { // since 0 can be a valid `id` as well // Handle cases the an API/user supplies just an Object/id instead of an Array this.keyContents = _.isArray( keyContents ) ? keyContents : [ keyContents ]; _.each( this.keyContents, function( item ) { var itemId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item ); if ( itemId || itemId === 0 ) { this.keyIds.push( itemId ); } }, this ); } }
javascript
{ "resource": "" }
q64159
test
function( key, options, refresh ) { // Set default `options` for fetch options = _.extend( { update: true, remove: false }, options ); var setUrl, requests = [], rel = this.getRelation( key ), idsToFetch = rel && ( ( rel.keyIds && rel.keyIds.slice( 0 ) ) || ( ( rel.keyId || rel.keyId === 0 ) ? [ rel.keyId ] : [] ) ); // On `refresh`, add the ids for current models in the relation to `idsToFetch` if ( refresh ) { var models = rel.related instanceof Backbone.Collection ? rel.related.models : [ rel.related ]; _.each( models, function( model ) { if ( model.id || model.id === 0 ) { idsToFetch.push( model.id ); } }); } if ( idsToFetch && idsToFetch.length ) { // Find (or create) a model for each one that is to be fetched var created = [], models = _.map( idsToFetch, function( id ) { var model = Backbone.Relational.store.find( rel.relatedModel, id ); if ( !model ) { var attrs = {}; attrs[ rel.relatedModel.prototype.idAttribute ] = id; model = rel.relatedModel.findOrCreate( attrs, options ); created.push( model ); } return model; }, this ); // Try if the 'collection' can provide a url to fetch a set of models in one request. if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) { setUrl = rel.related.url( models ); } // An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls. // To make sure it can, test if the url we got by supplying a list of models to fetch is different from // the one supplied for the default fetch action (without args to 'url'). if ( setUrl && setUrl !== rel.related.url() ) { var opts = _.defaults( { error: function() { var args = arguments; _.each( created, function( model ) { model.trigger( 'destroy', model, model.collection, options ); options.error && options.error.apply( model, args ); }); }, url: setUrl }, options ); requests = [ rel.related.fetch( opts ) ]; } else { requests = _.map( models, function( model ) { var opts = _.defaults( { error: function() { if ( _.contains( created, model ) ) { model.trigger( 'destroy', model, model.collection, options ); options.error && options.error.apply( model, arguments ); } } }, options ); return model.fetch( opts ); }, this ); } } return requests; }
javascript
{ "resource": "" }
q64160
test
function( options ) { // If this Model has already been fully serialized in this branch once, return to avoid loops if ( this.isLocked() ) { return this.id; } this.acquire(); var json = Backbone.Model.prototype.toJSON.call( this, options ); if ( this.constructor._superModel && !( this.constructor._subModelTypeAttribute in json ) ) { json[ this.constructor._subModelTypeAttribute ] = this.constructor._subModelTypeValue; } _.each( this._relations, function( rel ) { var related = json[ rel.key ], includeInJSON = rel.options.includeInJSON, value = null; if ( includeInJSON === true ) { if ( related && _.isFunction( related.toJSON ) ) { value = related.toJSON( options ); } } else if ( _.isString( includeInJSON ) ) { if ( related instanceof Backbone.Collection ) { value = related.pluck( includeInJSON ); } else if ( related instanceof Backbone.Model ) { value = related.get( includeInJSON ); } // Add ids for 'unfound' models if includeInJSON is equal to (only) the relatedModel's `idAttribute` if ( includeInJSON === rel.relatedModel.prototype.idAttribute ) { if ( rel instanceof Backbone.HasMany ) { value = value.concat( rel.keyIds ); } else if ( rel instanceof Backbone.HasOne ) { value = value || rel.keyId; } } } else if ( _.isArray( includeInJSON ) ) { if ( related instanceof Backbone.Collection ) { value = []; related.each( function( model ) { var curJson = {}; _.each( includeInJSON, function( key ) { curJson[ key ] = model.get( key ); }); value.push( curJson ); }); } else if ( related instanceof Backbone.Model ) { value = {}; _.each( includeInJSON, function( key ) { value[ key ] = related.get( key ); }); } } else { delete json[ rel.key ]; } if ( includeInJSON ) { json[ rel.keyDestination ] = value; } if ( rel.keyDestination !== rel.key ) { delete json[ rel.key ]; } }); this.release(); return json; }
javascript
{ "resource": "" }
q64161
test
function( attributes, options ) { options || ( options = {} ); options.create = false; return this.findOrCreate( attributes, options ); }
javascript
{ "resource": "" }
q64162
XtallatX
test
function XtallatX(superClass) { return class extends superClass { constructor() { super(...arguments); this._evCount = {}; } static get observedAttributes() { return [disabled]; } /** * Any component that emits events should not do so if it is disabled. * Note that this is not enforced, but the disabled property is made available. * Users of this mix-in should ensure not to call "de" if this property is set to true. */ get disabled() { return this._disabled; } set disabled(val) { this.attr(disabled, val, ''); } /** * Set attribute value. * @param name * @param val * @param trueVal String to set attribute if true. */ attr(name, val, trueVal) { const v = val ? 'set' : 'remove'; //verb this[v + 'Attribute'](name, trueVal || val); } /** * Turn number into string with even and odd values easy to query via css. * @param n */ to$(n) { const mod = n % 2; return (n - mod) / 2 + '-' + mod; } /** * Increment event count * @param name */ incAttr(name) { const ec = this._evCount; if (name in ec) { ec[name]++; } else { ec[name] = 0; } this.attr('data-' + name, this.to$(ec[name])); } attributeChangedCallback(name, oldVal, newVal) { switch (name) { case disabled: this._disabled = newVal !== null; break; } } /** * Dispatch Custom Event * @param name Name of event to dispatch ("-changed" will be appended if asIs is false) * @param detail Information to be passed with the event * @param asIs If true, don't append event name with '-changed' */ de(name, detail, asIs = false) { const eventName = name + (asIs ? '' : '-changed'); const newEvent = new CustomEvent(eventName, { detail: detail, bubbles: true, composed: false, }); this.dispatchEvent(newEvent); this.incAttr(eventName); return newEvent; } /** * Needed for asynchronous loading * @param props Array of property names to "upgrade", without losing value set while element was Unknown */ _upgradeProperties(props) { props.forEach(prop => { if (this.hasOwnProperty(prop)) { let value = this[prop]; delete this[prop]; this[prop] = value; } }); } }; }
javascript
{ "resource": "" }
q64163
Bitmap
test
function Bitmap(imageOrUri) { this.DisplayObject_constructor(); // public properties: /** * The source image to display. This can be a CanvasImageSource * (image, video, canvas), an object with a `getImage` method that returns a CanvasImageSource, or a string URL to an image. * If the latter, a new Image instance with the URL as its src will be used. * @property image * @type CanvasImageSource | Object **/ if (typeof imageOrUri == "string") { this.image = document.createElement("img"); this.image.src = imageOrUri; } else { this.image = imageOrUri; } /** * Specifies an area of the source image to draw. If omitted, the whole image will be drawn. * Note that video sources must have a width / height set to work correctly with `sourceRect`. * @property sourceRect * @type Rectangle * @default null */ this.sourceRect = null; // private properties: /** * Docced in superclass. */ this._webGLRenderStyle = createjs.DisplayObject._StageGL_BITMAP; }
javascript
{ "resource": "" }
q64164
canonicalize
test
function canonicalize(value, stack) { var canonicalizedObj; /* eslint-disable no-unused-vars */ var prop; /* eslint-enable no-unused-vars */ var type = getType(value); function withStack(value, fn) { stack.push(value); fn(); stack.pop(); } stack = stack || []; if (stack.indexOf(value) !== -1) { return '[Circular]'; } switch (type) { case 'undefined': case 'buffer': case 'null': canonicalizedObj = value; break; case 'array': withStack(value, function() { canonicalizedObj = value.map(function(item) { return canonicalize(item, stack); }); }); break; case 'function': /* eslint-disable guard-for-in */ for (prop in value) { canonicalizedObj = {}; break; } /* eslint-enable guard-for-in */ if (!canonicalizedObj) { canonicalizedObj = emptyRepresentation(value, type); break; } /* falls through */ case 'object': canonicalizedObj = canonicalizedObj || {}; withStack(value, function() { Object.keys(value).sort().forEach(function(key) { canonicalizedObj[key] = canonicalize(value[key], stack); }); }); break; case 'date': case 'number': case 'regexp': case 'boolean': canonicalizedObj = value; break; default: canonicalizedObj = value.toString(); } return canonicalizedObj; }
javascript
{ "resource": "" }
q64165
emptyRepresentation
test
function emptyRepresentation(value, type) { type = type || getType(value); switch (type) { case 'function': return '[Function]'; case 'object': return '{}'; case 'array': return '[]'; default: return value.toString(); } }
javascript
{ "resource": "" }
q64166
test
function(doc, first, last) { var f = doc.WordPos[first]; var l; if (last==doc.WordPos.length-1) // l = doc.DocLength; else l = doc.WordPos[last+1]; return l-f; }
javascript
{ "resource": "" }
q64167
compile
test
function compile() { var buf = ''; buf += '(function() {\n'; buf += '\n// CommonJS require()\n\n'; buf += browser.require + '\n\n'; buf += 'require.modules = {};\n\n'; buf += 'require.resolve = ' + browser.resolve + ';\n\n'; buf += 'require.register = ' + browser.register + ';\n\n'; buf += 'require.relative = ' + browser.relative + ';\n\n'; args.forEach(function(file){ var js = files[file]; file = file.replace('lib/', ''); buf += '\nrequire.register("' + file + '", function(module, exports, require){\n'; buf += js; buf += '\n}); // module: ' + file + '\n'; }); buf += '\nwindow.kiwi = require("kiwi");\n'; buf += '})();\n'; fs.writeFile('kiwi.js', buf, function(err){ if (err) throw err; console.log(' \033[90m create : \033[0m\033[36m%s\033[0m', 'kiwi.js'); console.log(); }); }
javascript
{ "resource": "" }
q64168
fp
test
function fp() { var args = Array.prototype.slice.call(arguments, 0); if (args.length) { if (!args.every(isStringOrFunction)) { var signature = args.map(humanizeArgument).join('\n\t'); throw new Error('Invalid arguments to functional pipeline - not a string or function\n\t' + signature); } var fns = splitDots(args); return function (d) { var originalObject = d; fns.forEach(function (fn) { if (typeof fn === 'string') { if (typeof d[fn] === 'function') { d = d[fn].call(d, d); } else if (typeof d[fn] !== 'undefined') { d = d[fn]; } else { var signature = args.map(humanizeArgument).join('\n\t'); throw new Error('Cannot use property ' + fn + ' from object ' + JSON.stringify(d, null, 2) + '\npipeline\n\t' + signature + '\noriginal object\n' + JSON.stringify(originalObject, null, 2)); } } else if (typeof fn === 'function') { d = fn(d); } else { throw new Error('Cannot apply ' + JSON.stringify(fn, null, 2) + ' to value ' + d + ' not a property name or a function'); } }); return d; }; } }
javascript
{ "resource": "" }
q64169
test
function(tickRate){ events.EventEmitter.call(this); // Initialize private properties this._milliseconds = 0; this._setState('stopped'); this._timer = new NanoTimer(); tickRate = tickRate || 100; Object.defineProperty(this, 'tickRate', { enumerable: true, configurable: false, writable: false, value: tickRate }); }
javascript
{ "resource": "" }
q64170
onProcessed
test
function onProcessed(err, processed) { if(err) return callback(err); _this._tokenize(processed, onTokenized); }
javascript
{ "resource": "" }
q64171
Template
test
function Template(str, options) { // Handle the case where the only argument passed is the `options` object if(_.isObject(str) && !options){ options = str; str = null; } // Create options if not provided options = options ? _.clone(options) : {}; // Set default cache behavior // if node if(!_.isBoolean(options.cache)) { options.cache = process.env.NODE_ENV === 'production'; } // end // Merges given `options` with `DEFAULTS` options = _.defaults(options, DEFAULTS); options.cacheContext = options.cacheContext || Template; // Sets instance variables this.template = str; this.options = options; this._compiled = null; // Creates the cache if not already done if(options.cache && !(this._getCache() instanceof options.cacheHandler)) { var cacheOptions = [options.cacheHandler].concat(options.cacheOptions); options.cacheContext[options._cacheProp] = typeof window !== 'undefined' ? new options.cacheHandler() : construct.apply(this, cacheOptions); } }
javascript
{ "resource": "" }
q64172
test
function (fn, rate) { var allowed = true; return function () { if (allowed) { allowed = false; fn.apply(null, [].slice.call(arguments, 0)); setTimeout(function () { allowed = true; }, rate); } } }
javascript
{ "resource": "" }
q64173
get_data
test
function get_data (callback) { var data; try { data = program.data ? JSON.parse(program.data) : {}; callback(data); } catch (err) { fs.readFile(program.data, function (err, str) { str = '' + str; if (!err) { try { data = JSON.parse(str); callback(data); } catch (err) { data = eval(str); callback(data); } } }); } return data; }
javascript
{ "resource": "" }
q64174
secureWebhookEndpoints
test
function secureWebhookEndpoints() { var authenticationMiddleware = require(__dirname + '/middleware/slack_authentication.js'); // convert a variable argument list to an array, drop the webserver argument var tokens = Array.prototype.slice.call(arguments); var webserver = tokens.shift(); slack_botkit.logger.info( '** Requiring token authentication for webhook endpoints for Slash commands ' + 'and outgoing webhooks; configured ' + tokens.length + ' token(s)' ); webserver.use(authenticationMiddleware(tokens)); }
javascript
{ "resource": "" }
q64175
postForm
test
function postForm(url, formData, cb, multipart) { cb = cb || noop; bot.logger.info('** API CALL: ' + url); var params = { url: url, headers: { 'User-Agent': bot.userAgent(), } }; if (multipart === true) { params.formData = formData; } else { params.form = formData; } request.post(params, function(error, response, body) { bot.logger.debug('Got response', error, body); if (error) { return cb(error); } if (response.statusCode == 200) { var json; try { json = JSON.parse(body); } catch (parseError) { return cb(parseError); } return cb((json.ok ? null : json.error), json); } else if (response.statusCode == 429) { return cb(new Error('Rate limit exceeded')); } else { return cb(new Error('Invalid response')); } }); }
javascript
{ "resource": "" }
q64176
verifyRequest
test
function verifyRequest(req, res, buf, encoding) { var expected = req.headers['x-hub-signature']; var calculated = getSignature(buf); if (expected !== calculated) { throw new Error('Invalid signature on incoming request'); } else { // facebook_botkit.logger.debug('** X-Hub Verification successful!') } }
javascript
{ "resource": "" }
q64177
test
function() { if ( !this.selfUpdating ) { this.deferred = true; } var i = this.refs.length; while ( i-- ) { this.refs[ i ].update(); } if ( this.deferred ) { this.update(); this.deferred = false; } }
javascript
{ "resource": "" }
q64178
DockerCmdManager
test
function DockerCmdManager(dockerdescPath) { dockerdescPath = dockerdescPath || './dockerdesc.json'; if (!fs.existsSync(dockerdescPath)) { throw new Error(util.format('The path "%s" does not exists.', dockerdescPath)); } /** @type {string} */ this.dockerdescDir = path.dirname(dockerdescPath); var dockerdescPathStat = fs.statSync(dockerdescPath); if (dockerdescPathStat.isDirectory()) { this.dockerdescDir = dockerdescPath; dockerdescPath = path.join(dockerdescPath, 'dockerdesc.json'); } /** @type {Dockerdesc} */ var dockerdescContent = fs.readFileSync(dockerdescPath); try { this.dockerdesc = JSON.parse(dockerdescContent); } catch (err) { throw new Error('Problem in the dockerdesc.json file format.\n' + err.stack); } }
javascript
{ "resource": "" }
q64179
dd
test
function dd(object, _context, _key, _root, _rootPath) { _root = _root || object; _rootPath = _rootPath || []; var drill = function(key) { var nextObject = ( object && object.hasOwnProperty(key) && object[key] || undefined ); return dd(nextObject, object, key, _root, _rootPath.concat(key)); }; drill.val = object; drill.exists = object !== undefined; drill.set = function(value) { if (_rootPath.length === 0) { return; } var contextIterator = _root; for (var depth = 0; depth < _rootPath.length; depth++) { var key = _rootPath[depth]; var isFinalDepth = (depth === _rootPath.length - 1); if (!isFinalDepth) { contextIterator[key] = ( contextIterator.hasOwnProperty(key) && typeof contextIterator[key] === 'object' ? contextIterator[key] : {} ); contextIterator = contextIterator[key]; } else { _context = contextIterator; _key = key; } } _context[_key] = value; drill.val = value; drill.exists = value !== undefined; return value; }; drill.update = function(value) { if (drill.exists) { _context[_key] = value; drill.val = value; return value; } }; drill.invoke = isFunction(object) ? Function.prototype.bind.call(object, _context) : function () { }; return drill; }
javascript
{ "resource": "" }
q64180
printTasks
test
function printTasks(tasks, verbose) { tasks = tasks .filterHidden(verbose) .sort(); var results = [ 'Usage: gulp [task] [task2] ...', '', 'Tasks: ' ]; var fieldTaskLen = tasks.getLongestNameLength(); tasks.forEach(function(task) { var comment = task.comment || {}; var lines = comment.lines || []; results.push(formatColumn(task.name, fieldTaskLen) + (lines[0] || '')); for (var i = 1; i < lines.length; i++) { results.push(formatColumn('', fieldTaskLen) + ' ' + lines[i]); } }); return results.join('\n'); }
javascript
{ "resource": "" }
q64181
formatColumn
test
function formatColumn(text, width, offsetLeft, offsetRight) { offsetLeft = undefined !== offsetLeft ? offsetLeft : 3; offsetRight = undefined !== offsetRight ? offsetRight : 3; return new Array(offsetLeft + 1).join(' ') + text + new Array(Math.max(width - text.length, 0) + 1).join(' ') + new Array(offsetRight + 1).join(' '); }
javascript
{ "resource": "" }
q64182
inheritGulp
test
function inheritGulp() { function TaskDoc() { this.taskList = new TaskList(); gulp.Gulp.call(this); } TaskDoc.prototype = gulp; return new TaskDoc(); }
javascript
{ "resource": "" }
q64183
_log
test
function _log(level) { return function() { var meta = null; var args = arguments; if (arguments.length === 0) { // we only check here current level, but we also should more but restify uses it only for trace checks return this._winston.level === level; } else if (arguments[0] instanceof Error) { // winston supports Error in meta, so pass it as last meta = arguments[0].toString(); args = Array.prototype.slice.call(arguments, 1); args.push(meta); } else if (typeof (args[0]) === 'string') { // just arrayize for level args = Array.prototype.slice.call(arguments); } else { // push provided object as meta meta = arguments[0]; args = Array.prototype.slice.call(arguments, 1); args.push(meta); } args.unshift(level); this._winston.log.apply(this._winston, args); } }
javascript
{ "resource": "" }
q64184
isPromise
test
function isPromise(item) { if (!item) return false; return ( (util.types && util.types.isPromise && util.types.isPromise(item)) || (item.constructor && item.constructor.name == 'Promise') || (!item instanceof objectInstance && item.then && typeof item.then == 'function') ); }
javascript
{ "resource": "" }
q64185
hasCallback
test
function hasCallback(fn) { var fnString = fn.toString(); // console.log('---'); // console.log('GIVEN', '>>> ' + fnString + ' <<<'); var bits, fnArgs; if (/^async /.test(fnString)) { // console.log('IS ASYNC'); return false; // Its an async function and should only ever return a promise } else if (bits = /^function\s*(?:.*?)\s*\((.*?)\)/.exec(fnString)) { // console.log('> FUNC', bits[1]); fnArgs = bits[1]; } else if (/^\(\s*\)\s*=>/.test(fnString)) { // console.log('ARROW (no args)'); return false; } else if (bits = /^\s\((.*?)\)\s*?=>/.exec(fnString)) { // console.log('> ARROW (braces)', bits[1]); fnArgs = bits[1]; } else if (bits = /^(.*?)\s*=>/.exec(fnString)) { // console.log('> ARROW (no braces)', bits[1]); fnArgs = bits[1]; } else { // console.log('> EMPTY'); return false; } fnArgs = fnArgs.replace(/^\s+/, '').replace(/\s+$/, ''); // Clean up args by trimming whitespace // console.log('ARGS:', fnArgs); return !! fnArgs; }
javascript
{ "resource": "" }
q64186
race
test
function race() { var self = this; argy(arguments) .ifForm('', function() {}) .ifForm('array', function(tasks) { self._struct.push({ type: 'race', payload: tasks }); }) .ifForm('string array', function(id, tasks) { self._struct.push({ type: 'race', id: arguments[0], payload: arguments[1] }); }) .ifFormElse(function(form) { throw new Error('Unknown call style for .parallel(): ' + form); }) return self; }
javascript
{ "resource": "" }
q64187
deferAdd
test
function deferAdd(id, task, parentChain) { var self = this; parentChain.waitingOn = (parentChain.waitingOn || 0) + 1; if (! parentChain.waitingOnIds) parentChain.waitingOnIds = []; parentChain.waitingOnIds.push(id); self._deferred.push({ id: id || null, prereq: parentChain.prereq || [], payload: function(next) { self._context._id = id; run(self._options.context, task, function(err, value) { // Glue callback function to first arg if (id) self._context[id] = value; self._deferredRunning--; if (--parentChain.waitingOn == 0) { parentChain.completed = true; if (self._struct.length && self._struct[self._structPointer].type == 'await') self._execute(err); } self._execute(err); }, (parentChain.prereq || []).map(function(pre) { return self._context[pre]; })); } }); }
javascript
{ "resource": "" }
q64188
await
test
function await() { var payload = []; // Slurp all args into payload argy(arguments) .getForm() .split(',') .forEach(function(type, offset) { switch (type) { case '': // Blank arguments - do nothing // Pass break; case 'string': payload.push(args[offset]); break; case 'array': payload.concat(args[offset]); break; default: throw new Error('Unknown argument type passed to .await(): ' + type); } }); this._struct.push({ type: 'await', payload: payload }); return this; }
javascript
{ "resource": "" }
q64189
timeout
test
function timeout(newTimeout) { var self = this; argy(arguments) .ifForm('', function() { self._struct.push({ type: 'timeout', delay: false }); }) .ifForm('boolean', function(setTimeout) { if (setTimeout) throw new Error('When calling .timeout(Boolean) only False is accepted to disable the timeout'); self._struct.push({ type: 'timeout', delay: false }); }) .ifForm('number', function(delay) { self._struct.push({ type: 'timeout', delay: delay }); }) .ifForm('function', function(callback) { self._struct.push({ type: 'timeout', callback: callback }); }) .ifForm('number function', function(delay, callback) { self._struct.push({ type: 'timeout', delay: delay, callback: callback }); }) .ifForm('function number', function(delay, callback) { self._struct.push({ type: 'timeout', delay: delay, callback: callback }); }) .ifFormElse(function(form) { throw new Error('Unknown call style for .timeout():' + form); }); return self; }
javascript
{ "resource": "" }
q64190
_timeoutHandler
test
function _timeoutHandler() { var currentTaskIndex = this._struct.findIndex(function(task) { return ! task.completed }); if (!currentTaskIndex < 0) { console.log('Async-Chainable timeout on unknown task'); console.log('Full structure:', this._struct); } else { console.log('Async-Chainable timeout: Task #', currentTaskIndex + 1, '(' + this._struct[currentTaskIndex].type + ')', 'elapsed timeout of', this._options.timeout + 'ms'); } this.fire('timeout'); }
javascript
{ "resource": "" }
q64191
run
test
function run(context, fn, finish, args) { // Argument mangling {{{ if (typeof context == 'function') { // called as run(fn, finish, args); args = finish; finish = fn; fn = context; context = this; } // }}} if (isPromise(fn)) { // Given a promise that has already resolved? fn .then(function(value) { finish.apply(context, [null, value]); }) .catch(function(err) { finish.call(context, err || 'An error occured'); }); } else if (hasCallback(fn)) { // Callback w/ (err, result) pattern var result = fn.apply(context, args ? [finish].concat(args) : [finish]); if (isPromise(result)) { result .then(function(value) { // Remap result from (val) => (err, val) finish.apply(context, [null, value]); }) .catch(function(err) { finish.call(context, err || 'An error occured'); }); } } else { // Maybe either a promise or sync function? var result; try { result = fn.apply(context, args || []); // Run the function and see what it gives us } catch (e) { finish.call(context, e); } if (isPromise(result)) { // Got back a promise - attach to the .then() function result .then(function(value) { // Remap result from (val) => (err, val) finish.apply(context, [null, value]); }) .catch(function(err) { finish.call(context, err || 'An error occured'); }); } else { // Didn't provide back a promise - assume it was a sync function finish.apply(context, [null, result]); } } }
javascript
{ "resource": "" }
q64192
runWhile
test
function runWhile(iter, limit, callback) { var index = 0; var hasExited = false; var err; var running = 0; if (!Number.isFinite(limit)) limit = 10; var invoke = function() { iter.call(this._context, function(taskErr, taskResult) { if (taskErr) err = taskErr; if (taskErr || !taskResult) hasExited = true; --running; if (err && !running) { callback(err, res); } else if (running <= 0 && hasExited) { callback(err); } else if (!hasExited) { setTimeout(invoke); } }, index++); }; for (var i = 0; i < limit; i++) { running++; setTimeout(invoke); } return this; }
javascript
{ "resource": "" }
q64193
reset
test
function reset() { this._struct = []; this._structPointer = 0; var reAttachContext = (this._options.context == this._context); // Reattach the context pointer after reset? this._context = { _struct: this._struct, _structPointer: this._structPointer, _options: this._options, _deferredRunning: this._deferredRunning, hook: this.hook.bind(this), fire: this.fire.bind(this), }; if (reAttachContext) this._options.context = this._context; }
javascript
{ "resource": "" }
q64194
hook
test
function hook() { var self = this; argy(arguments) .ifForm('', function() {}) .ifForm('string function', function(hook, callback) { // Attach to one hook if (!self._hooks[hook]) self._hooks[hook] = []; self._hooks[hook].push({cb: callback}); }) .ifForm('string string function', function(hook, id, callback) { // Attach a named hook if (!self._hooks[hook]) self._hooks[hook] = []; self._hooks[hook].push({id: id, cb: callback}); }) .ifForm('string array function', function(hook, prereqs, callback) { // Attach to a hook with prerequisites if (!self._hooks[hook]) self._hooks[hook] = []; self._hooks[hook].push({prereqs: prereqs, cb: callback}); }) .ifForm('string string array function', function(hook, id, prereqs, callback) { // Attach a named hook with prerequisites if (!self._hooks[hook]) self._hooks[hook] = []; self._hooks[hook].push({id: id, prereqs: prereqs, cb: callback}); }) .ifForm('array function', function(hooks, callback) { // Attach to many hooks hooks.forEach(function(hook) { if (!self._hooks[hook]) self._hooks[hook] = []; self._hooks[hook].push({cb: callback}); }); }) .ifFormElse(function(form) { throw new Error('Unknown call style for .on(): ' + form); }); return self; }
javascript
{ "resource": "" }
q64195
tag
test
function tag(name) { if (!this.comment || !this.comment.tags) { return null; } for (var i = 0; i < this.comment.tags.length; i++) { var tagObj = this.comment.tags[i]; if (tagObj.name === name) { return tagObj.value; } } return null; }
javascript
{ "resource": "" }
q64196
checkPattern
test
function checkPattern(file, blackList, whiteList){ if (util.isRegExp(blackList) && blackList.test(file)) { return false; } if (util.isRegExp(whiteList)) { if (whiteList.test(file)) { return true; } return false; } return true; }
javascript
{ "resource": "" }
q64197
Seven
test
function Seven(_a) { var _b = _a === void 0 ? {} : _a, height = _b.height, width = _b.width, _c = _b.angle, angle = _c === void 0 ? 10 : _c, _d = _b.ratioLtoW, ratioLtoW = _d === void 0 ? 4 : _d, _e = _b.ratioLtoS, ratioLtoS = _e === void 0 ? 32 : _e, _f = _b.digit, digit = _f === void 0 ? Digit.BLANK : _f; /** The cononical points for a horizontal segment for the given configuration. */ this._horizontalSegmentGeometry = [ { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 } ]; /** The cononical points for a vertical segment for the given configuration. */ this._verticalSegmentGeometry = [ { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 } ]; /** The x and y shifts that must be applied to each segment. */ this._translations = [ { x: 0, y: 0, a: this._horizontalSegmentGeometry }, { x: 0, y: 0, a: this._verticalSegmentGeometry }, { x: 0, y: 0, a: this._verticalSegmentGeometry }, { x: 0, y: 0, a: this._horizontalSegmentGeometry }, { x: 0, y: 0, a: this._verticalSegmentGeometry }, { x: 0, y: 0, a: this._verticalSegmentGeometry }, { x: 0, y: 0, a: this._horizontalSegmentGeometry } ]; /** The segments, A-G of the digit. */ this.segments = [new Segment(), new Segment(), new Segment(), new Segment(), new Segment(), new Segment(), new Segment()]; this._angleDegree = angle; this.digit = digit; this._ratioLtoW = ratioLtoW; this._ratioLtoS = ratioLtoS; this._height = this._width = 100; //initialize so checkConfig passes, and for default case this._isHeightFixed = true; if (height !== undefined) { this._height = height; } else if (width !== undefined) { this._width = width; this._isHeightFixed = false; } //else - neither specified, default to height=100 this._positionSegments(); }
javascript
{ "resource": "" }
q64198
onChange
test
function onChange(event) { try { if (remove()) { return; } resolve(Array.from(input.files)); // actually got file(s) } catch (error) { reject(error); } }
javascript
{ "resource": "" }
q64199
RemoveObserver_init
test
function RemoveObserver_init(ref, node) { let self = Self.get(node); if (!self) { self = new RemoveObserverPrivate(node); Self.set(node, self); } Self.set(ref, self); }
javascript
{ "resource": "" }