_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q13000
summarizeCoverage
train
function summarizeCoverage(coverage) { var fileSummary = []; Object.keys(coverage).forEach(function (key) { fileSummary.push(summarizeFileCoverage(coverage[key])); }); return mergeSummaryObjects.apply(null, fileSummary); }
javascript
{ "resource": "" }
q13001
toYUICoverage
train
function toYUICoverage(coverage) { var ret = {}; addDerivedInfo(coverage); Object.keys(coverage).forEach(function (k) { var fileCoverage = coverage[k], lines = fileCoverage.l, functions = fileCoverage.f, fnMap = fileCoverage.fnMap, o; o = ret[k] = { lines: {}, calledLines: 0, coveredLines: 0, functions: {}, calledFunctions: 0, coveredFunctions: 0 }; Object.keys(lines).forEach(function (k) { o.lines[k] = lines[k]; o.coveredLines += 1; if (lines[k] > 0) { o.calledLines += 1; } }); Object.keys(functions).forEach(function (k) { var name = fnMap[k].name + ':' + fnMap[k].line; o.functions[name] = functions[k]; o.coveredFunctions += 1; if (functions[k] > 0) { o.calledFunctions += 1; } }); }); return ret; }
javascript
{ "resource": "" }
q13002
parseField
train
function parseField(identifier, descriptor) { switch(identifier) { // Literal (uninterpreted) fields case 'content': case 'number': case 'sampleUnits': break; // Integers case 'dimension': case 'blockSize': case 'lineSkip': case 'byteSkip': case 'spaceDimension': descriptor = parseNRRDInteger(descriptor); break; // Floats case 'min': case 'max': case 'oldMin': case 'oldMax': descriptor = parseNRRDFloat(descriptor); break; // Vectors case 'spaceOrigin': descriptor = parseNRRDVector(descriptor); break; // Lists of strings case 'labels': case 'units': case 'spaceUnits': descriptor = parseNRRDWhitespaceSeparatedList(descriptor, parseNRRDQuotedString); break; // Lists of integers case 'sizes': descriptor = parseNRRDWhitespaceSeparatedList(descriptor, parseNRRDInteger); break; // Lists of floats case 'spacings': case 'thicknesses': case 'axisMins': case 'axisMaxs': descriptor = parseNRRDWhitespaceSeparatedList(descriptor, parseNRRDFloat); break; // Lists of vectors case 'spaceDirections': case 'measurementFrame': descriptor = parseNRRDWhitespaceSeparatedList(descriptor, parseNRRDVector); break; // One-of-a-kind fields case 'type': descriptor = parseNRRDType(descriptor); break; case 'encoding': descriptor = parseNRRDEncoding(descriptor); break; case 'endian': descriptor = parseNRRDEndian(descriptor); break; case 'dataFile': descriptor = parseNRRDDataFile(descriptor); break; case 'centers': descriptor = parseNRRDWhitespaceSeparatedList(descriptor, parseNRRDCenter); break; case 'kinds': descriptor = parseNRRDWhitespaceSeparatedList(descriptor, parseNRRDKind); break; case 'space': descriptor = parseNRRDSpace(descriptor); break; // Something unknown default: console.warn("Unrecognized NRRD field: " + identifier); } return descriptor; }
javascript
{ "resource": "" }
q13003
train
function(instance) { var result = this._related(instance); if (result === undefined) { throw new Error(util.format('The relation "%s" has not yet been ' + 'loaded.', this._name)); } return result; }
javascript
{ "resource": "" }
q13004
train
function(instance) { var cacheName = this._itemObjectsQueryCacheKey; if (!instance[cacheName]) { var where = _.object([ [this.primaryKey, instance.getAttribute(this.foreignKeyAttr)], ]); var cacheResult = _.bind(this.associateFetchedObjects, this, instance); instance[cacheName] = this._relatedModel .objects.where(where).limit(1) .on('result', cacheResult); } return instance[cacheName]; }
javascript
{ "resource": "" }
q13005
train
function(instance) { var self = this; var result = Promise.bind(); var fk = instance.getAttribute(this.foreignKeyAttr); if (fk) { result = result.then(function() { return self.objectsQuery(instance).execute(); }) .then(function(result) { self.validateFetchedObjects(instance, result); return result[0]; }); } else { result = result.then(function() { // pretend like we actually did the whole fetch & got back nothing self.associateFetchedObjects(instance, [null]); }); } return result; }
javascript
{ "resource": "" }
q13006
train
function(instance, objects) { var foreignKeyAttr = this.foreignKeyAttr; var fk = instance.getAttribute(foreignKeyAttr); if (fk && objects.length === 0) { var relatedModel = this._relatedModel; var relatedClass = relatedModel.__identity__; var relatedName = relatedClass.__name__; throw new Error(util.format('Found no %s with %j %d', relatedName, foreignKeyAttr, fk)); } }
javascript
{ "resource": "" }
q13007
attachCommentsToFile
train
function attachCommentsToFile(files, comments) { return files.filter(function(file) { return file.comments = comments.filter(function(comment) { if (file.filename === comment.path) { return comment.reply = attachCommentReply.call(this, comment); } }.bind(this)); }.bind(this)); }
javascript
{ "resource": "" }
q13008
attachCommentReply
train
function attachCommentReply(comment) { return function reply(body, callback) { github.replyToReviewComment(this.repo.data.owner.login, this.repo.data.name, this.data.number, comment.id, body, callback); }.bind(this); }
javascript
{ "resource": "" }
q13009
train
function(message) { return override(function() { if (!this._isToMany) { var modelName = this._modelClass.__identity__.__name__; var relationName = this._name; throw new Error(util.format('%s for non many-to-many through relation ' + '%s#%s.', message, modelName, relationName)); } return this._super.apply(this, arguments); }); }
javascript
{ "resource": "" }
q13010
train
function(name) { var before = 'before' + _.capitalize(name); var after = 'after' + _.capitalize(name); return function() { this[before].apply(this, arguments); this._super.apply(this, arguments); this[after].apply(this, arguments); }; }
javascript
{ "resource": "" }
q13011
train
function(instance) { var args = _.rest(arguments); var objects = _.flatten(args); this.beforeAddingObjects(instance, objects); this.associateObjects(instance, objects); return Actionable.create(instance.save.bind(instance)); }
javascript
{ "resource": "" }
q13012
train
function(instance, objects) { var self = this; var after = this.afterAddingObjects.bind(this, instance, objects); return self._updateForeignKeys(instance, objects, instance.id).tap(after); }
javascript
{ "resource": "" }
q13013
train
function(instance) { var args = _.rest(arguments); var objects = _.flatten(args); this.beforeRemovingObjects(instance, objects); this.disassociateObjects(instance, objects); return Actionable.create(instance.save.bind(instance)); }
javascript
{ "resource": "" }
q13014
train
function(instance, objects) { var self = this; var after = this.afterRemovingObjects.bind(this, instance, objects); var removable = _.filter(objects, 'persisted'); return self._updateForeignKeys(instance, removable, undefined).tap(after); }
javascript
{ "resource": "" }
q13015
train
function(instance) { var updates = _.object([[this.foreignKey, undefined]]); var query = this.objectsQuery(instance).update(updates); var after = this.afterClearingObjects.bind(this, instance); return query.execute().tap(after); }
javascript
{ "resource": "" }
q13016
train
function(association, name) { var context = this._relationCallContext; var through = association.indexOf('.') !== -1 ? util.format(' through %s', association) : ''; return _.extend(new Error(util.format( 'No relation %j found for `%s` on %s query%s.', name, context, this._model.__identity__.__name__, through)), { code: 'RELATION_ITERATION_FAILURE', }); }
javascript
{ "resource": "" }
q13017
train
function(orig) { this._super(orig); this._priorModel = orig._priorModel; this._model = orig._model; this._modelTable = orig._modelTable; this._arrayTransform = orig._arrayTransform; this._modelTransform = orig._modelTransform; }
javascript
{ "resource": "" }
q13018
train
function() { var model = this._model; var arrayTransform = function(result) { // jscs:ignore jsDoc return result.rows; }; var modelTransform = function(rows) { // jscs:ignore jsDoc return rows.map(model.load.bind(model)); }; var dup = this._dup() .transform(arrayTransform) .transform(modelTransform); dup._arrayTransform = arrayTransform; dup._modelTransform = modelTransform; return dup; }
javascript
{ "resource": "" }
q13019
train
function() { var dup = this._dup(); dup = dup.transform(dup._modelTransform); dup._model = dup._priorModel; dup._priorModel = undefined; return dup; }
javascript
{ "resource": "" }
q13020
train
function(action, azulfile, options, strings) { var db = Database.create(azulfile[env]); var migrator = db.migrator(path.resolve(options.migrations)); var message = ''; var batches = ''; return migrator[action]() .tap(function(migrations) { batches = _(migrations).pluck('batch').unique().join(', '); }) .then(function(migrations) { message += migrations.length ? chalk.magenta(strings.intro, 'migrations, batch', batches, '\n') : chalk.magenta(strings.none, '\n'); migrations.forEach(function(migration) { message += chalk.cyan(migration.name, '\n'); }); message += chalk.gray(_.capitalize(env), 'environment\n'); process.stdout.write(message); }) .catch(function(e) { message += chalk.red(strings.action, 'failed.', e); process.stderr.write(message); process.exit(1); }) .finally(function() { db.disconnect(); }); }
javascript
{ "resource": "" }
q13021
train
function(sqlite3, dbSettings) { if (!(this instanceof SQLiteDB)) { return new SQLiteDB(sqlite3, dbSettings); } this.constructor.super_.call(this, NAME, dbSettings); this.name = NAME; this.settings = dbSettings; this.sqlite3 = sqlite3; this.debug = dbSettings.debug; this.current_order = []; this.file_name = dbSettings.file_name; if (this.debug) { debug('Settings %j', dbSettings); } }
javascript
{ "resource": "" }
q13022
_getUi5AppHash
train
function _getUi5AppHash(sResolvedModulePath, sPreloadPath, oOptions) { // read relevant resources for hash generation const oPreloadFileContent = fs.readFileSync(sPreloadPath, 'utf8') // some resources will be requested additionally to 'Component-preload.js' // fortunately they 'should' be listed in manifest.json, therefore, we will look them up there const sManifestPath = path.resolve(sResolvedModulePath, 'manifest.json') const oManifestFileContent = fs.existsSync(sManifestPath) ? fs.readFileSync(sManifestPath, 'utf8') : null const oManifestJSON = oManifestFileContent ? JSON.parse(oManifestFileContent) : { 'sap.ui5': {} } const aResourceKeys = oManifestJSON['sap.ui5'].resources ? Object.keys(oManifestJSON['sap.ui5'].resources) : [] const aDependedResourceContents = aResourceKeys.reduce( (aContentsList, sResourceKey) => { return aContentsList.concat( oManifestJSON['sap.ui5'].resources[sResourceKey].map(oResource => fs.readFileSync( path.resolve(sResolvedModulePath, oResource.uri), 'utf8' ) ) ) }, [] ) // generate hash based on resource contents of the app const aBufferList = aDependedResourceContents .concat(oPreloadFileContent ? oPreloadFileContent : []) .map(oContent => new Buffer(oContent)) const sNewHash = _createHash(aBufferList, oOptions) return sNewHash }
javascript
{ "resource": "" }
q13023
_getUi5LibHash
train
function _getUi5LibHash(sResolvedModulePath, sLibPreloadPath, oOptions) { // read relevant resources for hash generation const oLibPreloadFileContent = fs.readFileSync(sLibPreloadPath, 'utf8') // generate hash based on resource contents of the library const aBufferList = [oLibPreloadFileContent].map( oContent => new Buffer(oContent) ) const sNewHash = _createHash(aBufferList, oOptions) return sNewHash }
javascript
{ "resource": "" }
q13024
_getThemeRootHash
train
function _getThemeRootHash(sThemeRootPath, sThemeName, oOptions) { // read relevant resources for hash generation const aAssetContents = _readAllFiles(sThemeRootPath) // generate hash based on library CSS files in theme root const aBufferList = aAssetContents.map(oContent => new Buffer(oContent)) const sNewHash = _createHash(aBufferList, oOptions) return sNewHash }
javascript
{ "resource": "" }
q13025
_readAllFiles
train
function _readAllFiles(sDir = '', aWhitelist = []) { // read all files in current directory const aFiles = fs.readdirSync(sDir) // loop at all files const aContents = aFiles.reduce((aContents, sFileName) => { // get file stats const oFile = fs.statSync(`${sDir}/${sFileName}`) if (oFile.isDirectory()) { // append files of directory to list return aContents.concat(_readAllFiles(`${sDir}/${sFileName}`)) } // append file content to list (if contained in whitelist) return aWhitelist.length === 0 || aWhitelist.indexOf(sFileName) !== -1 ? aContents.concat(fs.readFileSync(`${sDir}/${sFileName}`, 'utf8')) : aContents }, []) return aContents }
javascript
{ "resource": "" }
q13026
_createHash
train
function _createHash(aBufferList, { HASH_TYPE, DIGEST_TYPE, MAX_LENGTH }) { // very important to sort buffer list before creating hash!! const aSortedBufferList = (aBufferList || []).sort() // create and return hash return aSortedBufferList.length > 0 ? loaderUtils .getHashDigest( Buffer.concat(aSortedBufferList), HASH_TYPE, DIGEST_TYPE, MAX_LENGTH ) // Windows machines are case insensitive while Linux machines are, so we only will use lower case paths .toLowerCase() : null }
javascript
{ "resource": "" }
q13027
lineNumberOfCharacterIndex
train
function lineNumberOfCharacterIndex(code, idx) { var everythingUpUntilTheIndex = code.substring(0, idx); // computer science! return everythingUpUntilTheIndex.split("\n").length; }
javascript
{ "resource": "" }
q13028
train
function(name, properties) { var className = _.capitalize(_.camelCase(name)); var known = this._modelClasses; var model = known[className]; if (!model) { model = known[className] = this.Model.extend({}, { __name__: className }); } return model.reopen(properties); }
javascript
{ "resource": "" }
q13029
train
function() { var self = this; if (!self.mHighlightedText) { gulpUtil.log(gulpUtil.colors.yellow('Warning:'), self.mMessage, "You will not be able to deploy."); } else { gulpUtil.log(gulpUtil.colors.yellow('Warning:'), self.mMessage, gulpUtil.colors.cyan(self.mHighlightedText), "You will not be able to deploy."); } }
javascript
{ "resource": "" }
q13030
train
function() { var self = this; if (!self.mPackageJson) { self.mPackageJson = jetpack.read(this.mOptions.package_json_file_path, 'json'); } return self.mPackageJson; }
javascript
{ "resource": "" }
q13031
train
function(baseTable, joinTable) { var jk = [baseTable, this.joinKeyAttr].join('.'); var ik = [joinTable, this.inverseKeyAttr].join('.'); var parts = [jk, ik]; // for readability, we like to keep the foreign key first in the join // condition, so if the join key is the primary key, swap the order of the // condition. if (this.joinKey === this.primaryKey) { parts.reverse(); } return parts.join('='); }
javascript
{ "resource": "" }
q13032
beforeFirstCall
train
function beforeFirstCall(instance, method, callback) { instance[method] = function() { delete instance[method]; callback.apply(this, arguments); return this[method].apply(this, arguments); }; }
javascript
{ "resource": "" }
q13033
train
function(env, action) { if (!env.modulePath) { console.log(chalk.red('Local azul not found in'), chalk.magenta(tildify(env.cwd))); console.log(chalk.red('Try running: npm install azul')); process.exit(1); } if (!env.configPath && action.azulfile) { console.log(chalk.red('No azulfile found')); process.exit(1); } }
javascript
{ "resource": "" }
q13034
train
function(program) { return program .version(require('../../package.json').version) .usage('[options] command') .option('--cwd <cwd>', 'change the current working directory') .option('--azulfile <azulfile>', 'use a specific config file') .option('--require <require>', 'require external module') .option('--completion <value>', 'a method to handle shell completions'); }
javascript
{ "resource": "" }
q13035
train
function(details) { return function() { var args = _.toArray(arguments); var options = _.last(args); action.options = options; action.name = options.name(); action.args = args; action = _.defaults(action, details, { azulfile: true }); }; }
javascript
{ "resource": "" }
q13036
train
function(instance) { let type = typeof instance; if (!instance) { return "falsey"; } else if (Array.isArray(instance)) { if ( instance.length === 2 && typeof instance[0] === "number" && typeof instance[1] === "number" ) { return "range"; } else { return "array"; } } else if (type === "object") { if (instance instanceof RegExp) { return "regexp"; } else if (instance.hasOwnProperty("highlight")) { return "custom"; } } else if (type === "function" || type === "string") { return type; } return "other"; }
javascript
{ "resource": "" }
q13037
train
function() { let ua = window.navigator.userAgent.toLowerCase(); if (ua.indexOf("firefox") !== -1) { return "firefox"; } else if (!!ua.match(/msie|trident\/7|edge/)) { return "ie"; } else if ( !!ua.match(/ipad|iphone|ipod/) && ua.indexOf("windows phone") === -1 ) { // Windows Phone flags itself as "like iPhone", thus the extra check return "ios"; } else { return "other"; } }
javascript
{ "resource": "" }
q13038
train
function() { // take padding and border pixels from highlights div let padding = this.$highlights.css([ "padding-top", "padding-right", "padding-bottom", "padding-left" ]); let border = this.$highlights.css([ "border-top-width", "border-right-width", "border-bottom-width", "border-left-width" ]); this.$highlights.css({ padding: "0", "border-width": "0" }); this.$backdrop .css({ // give padding pixels to backdrop div "margin-top": "+=" + padding["padding-top"], "margin-right": "+=" + padding["padding-right"], "margin-bottom": "+=" + padding["padding-bottom"], "margin-left": "+=" + padding["padding-left"] }) .css({ // give border pixels to backdrop div "margin-top": "+=" + border["border-top-width"], "margin-right": "+=" + border["border-right-width"], "margin-bottom": "+=" + border["border-bottom-width"], "margin-left": "+=" + border["border-left-width"] }); }
javascript
{ "resource": "" }
q13039
locateCodeImport
train
function locateCodeImport(value, fromIndex) { var index = value.indexOf(C_NEWLINE, fromIndex); if (value.charAt(index + 1) !== "<" && value.charAt(index + 2) !== "<") { return; } return index; }
javascript
{ "resource": "" }
q13040
codeImportBlock
train
function codeImportBlock(eat, value, silent) { var index = -1; var length = value.length + 1; var subvalue = EMPTY; var character; var marker; var markerCount; var queue; // eat initial spacing while (++index < length) { character = value.charAt(index); if (character !== C_TAB && character !== C_SPACE) { break; } subvalue += character; } if (value.charAt(index) !== "<") { return; } // require << if (value.charAt(index + 1) !== "<") { return; } marker = character; subvalue += character; markerCount = 1; queue = EMPTY; while (++index < length) { character = value.charAt(index); if (character !== C_RIGHT_PAREN) { markerCount++; subvalue += queue + character; queue = EMPTY; } else if (character === C_RIGHT_PAREN) { subvalue += queue + C_RIGHT_PAREN; break; } } var match = /^(<<.*?)\s*$/m.exec(subvalue); if (!match) return; var fileMatches = /<<\[(.*)\]\((.*)\)/.exec(match[0]); var statedFilename = fileMatches[1]; var actualFilename = fileMatches[2]; var cqOpts = { ...__options }; if (__lastBlockAttributes["undent"]) { cqOpts.undent = true; } if (__lastBlockAttributes["root"]) { cqOpts.root = __lastBlockAttributes["root"]; } if (__lastBlockAttributes["meta"]) { cqOpts.meta = __lastBlockAttributes["meta"]; } let newNode = { type: "cq", lang: null, statedFilename, actualFilename, query: null, cropStartLine: null, cropEndLine: null, options: cqOpts }; if (__lastBlockAttributes["lang"]) { newNode.lang = __lastBlockAttributes["lang"].toLowerCase(); } if (__lastBlockAttributes["crop-query"]) { newNode.query = __lastBlockAttributes["crop-query"]; } if (__lastBlockAttributes["crop-start-line"]) { newNode.cropStartLine = parseInt(__lastBlockAttributes["crop-start-line"]); } if (__lastBlockAttributes["crop-end-line"]) { newNode.cropEndLine = parseInt(__lastBlockAttributes["crop-end-line"]); } // meta: `{ info=string filename="foo/bar/baz.js" githubUrl="https://github.com/foo/bar"}` return eat(subvalue)(newNode); }
javascript
{ "resource": "" }
q13041
tokenizeBlockInlineAttributeList
train
function tokenizeBlockInlineAttributeList(eat, value, silent) { var self = this; var index = -1; var length = value.length + 1; var subvalue = EMPTY; var character; var marker; var markerCount; var queue; // eat initial spacing while (++index < length) { character = value.charAt(index); if (character !== C_TAB && character !== C_SPACE) { break; } subvalue += character; } if (value.charAt(index) !== C_LEFT_BRACE) { return; } // ignore {{ thing }} if (value.charAt(index + 1) === C_LEFT_BRACE) { return; } // ignore {% thing %} if (value.charAt(index + 1) === C_PERCENT) { return; } marker = character; subvalue += character; markerCount = 1; queue = EMPTY; while (++index < length) { character = value.charAt(index); if (character !== C_RIGHT_BRACE) { // no newlines allowed in the attribute blocks if (character === C_NEWLINE) { return; } markerCount++; subvalue += queue + character; queue = EMPTY; } else if (character === C_RIGHT_BRACE) { subvalue += queue + C_RIGHT_BRACE; // eat trailing spacing because we don't even want this block to leave a linebreak in the output while (++index < length) { character = value.charAt(index); if ( character !== C_TAB && character !== C_SPACE && character !== C_NEWLINE ) { break; } subvalue += character; } function parseBlockAttributes(attrString) { // e.g. {lang='JavaScript',starting-line=4,crop-start-line=4,crop-end-line=26} var matches = /{(.*?)}/.exec(attrString); var blockAttrs = {}; if (!matches || !matches[1]) { console.log("WARNING: remark-cq unknown attrString", attrString); // hmm... return blockAttrs; } var pairs = splitNoParen(matches[1]); pairs.forEach(function(pair) { var kv = pair.split(/=\s*/); blockAttrs[kv[0]] = kv[1]; }); return blockAttrs; } __lastBlockAttributes = parseBlockAttributes(subvalue); if (__options.preserveEmptyLines) { return eat(subvalue)({ type: T_BREAK }); } else { return eat(subvalue); } } else { return; } } }
javascript
{ "resource": "" }
q13042
rangeExtents
train
function rangeExtents(ranges) { var start = Number.MAX_VALUE; var end = Number.MIN_VALUE; ranges.map(function (_ref) { var rs = _ref.start, re = _ref.end; start = Math.min(start, rs); end = Math.max(end, re); }); return { start: start, end: end }; }
javascript
{ "resource": "" }
q13043
train
function (f, a, b, fa, fc, fb, options) { var h = b - a, c = (a + b) / 2, fd = f((a + c) / 2), fe = f((c + b) / 2), Q1 = (h / 6) * (fa + 4 * fc + fb), Q2 = (h / 12) * (fa + 4 * fd + 2 * fc + 4 * fe + fb), Q = Q2 + (Q2 - Q1) / 15; options.calls = options.calls + 2; // Infinite or Not-a-Number function value encountered if (!isFinite(Q)) { options.warn = Math.max(options.warn, 3); return Q; } // Maximum function count exceeded; singularity likely if (options.calls > options.maxCalls) { options.warn = Math.max(options.warn, 2); return Q; } // Accuracy over this subinterval is acceptable if (Math.abs(Q2 - Q) <= options.tolerance) { return Q; } // Minimum step size reached; singularity possible if (Math.abs(h) < options.minStep || c === a || c === b) { options.warn = Math.max(options.warn, 1); return Q; } // Otherwise, divide the interval into two subintervals return quadstep(f, a, c, fa, fd, fc, options) + quadstep(f, c, b, fc, fe, fb, options); }
javascript
{ "resource": "" }
q13044
train
function() { this._super.apply(this, arguments); if (this._options.through) { this._options.through = inflection.singularize(this._options.through); } }
javascript
{ "resource": "" }
q13045
train
function(instance, value) { var collection = this._getCollectionCache(instance); var current = collection && collection[0]; if (current) { this.removeObjects(instance, current); } if (value) { this.addObjects(instance, value); } }
javascript
{ "resource": "" }
q13046
AddDocuments
train
function AddDocuments () { // Create Helpdoc Route HLP .all("/", ReqHandle.Valid(true), GetHelp); API .use('/docs', HLP); }
javascript
{ "resource": "" }
q13047
Splitter
train
function Splitter (queue, splits) { this._shifter = queue.shifter() this._map = {} this._array = [] for (var key in splits) { var queue = new Procession var split = { selector: splits[key], queue: queue, shifter: queue.shifter() } this._map[key] = split this._array.push(split) } }
javascript
{ "resource": "" }
q13048
Subscriber
train
function Subscriber(consumer, eventDispatcher, logger, events) { assert.object(consumer, 'consumer'); assert.object(eventDispatcher, 'eventDispatcher'); assert.object(logger, 'logger'); assert.object(events, 'events'); /** * Internal message handler, passes message to event dispatcher * * @private * @method * @param {Any} data - message payload * @param {Array} messageTypes - message types * @param {Object} msg - raw message */ const internalHandler = (data, messageTypes, msg) => { logger.debug('Subscriber received message with types ' + JSON.stringify(messageTypes) + ', handing off to event dispatcher.'); return eventDispatcher.dispatch(messageTypes, data, msg) .catch(function (err){ events.emit('unhandled-error', { data: data, messageTypes: messageTypes, message: msg, error: err }); logger.error('Error during message dispatch', err); return Promise.reject(err); }) .then(function(executed){ if (!executed){ events.emit('unhandled-event', { data: data, messageTypes: messageTypes, message: msg }); return Promise.reject(new Error('No handler registered for ' + messageTypes)); } return Promise.resolve(); }); }; /** * Subscribe to an event * * @public * @method * @param {String} eventName - name of event (required) * @param {Subscriber.handlerCallback} handler - the handler to be called with the message */ const on = (eventName, handler) => { eventDispatcher.on(eventName, handler); }; /** * Subscribe to an event, for one iteration only * * @public * @method * @param {String} eventName - name of event (required) * @param {Subscriber.handlerCallback} handler - the handler to be called with the message * @returns {Promise} a promise that is fulfilled when the event has been fired - useful for automated testing of handler behavior */ const once = (eventName, handler) => { return eventDispatcher.once(eventName, handler); }; /** * Use a middleware function * * @public * @method * @param {Function} middleware - middleware to run {@see middleware.contract} */ const use = (middleware) => { consumer.use(middleware); }; /** * Start consuming events * * @param {Object} options - details in consuming from the queue * @param {Number} options.limit - the channel prefetch limit * @param {bool} options.noBatch - if true, ack/nack/reject operations will execute immediately and not be batched * @param {bool} options.noAck - if true, the broker won't expect an acknowledgement of messages delivered to this consumer; i.e., it will dequeue messages as soon as they've been sent down the wire. Defaults to false (i.e., you will be expected to acknowledge messages). * @param {String} options.consumerTag - a name which the server will use to distinguish message deliveries for the consumer; mustn't be already in use on the channel. It's usually easier to omit this, in which case the server will create a random name and supply it in the reply. * @param {bool} options.exclusive - if true, the broker won't let anyone else consume from this queue; if there already is a consumer, there goes your channel (so usually only useful if you've made a 'private' queue by letting the server choose its name). * @param {Number} options.priority - gives a priority to the consumer; higher priority consumers get messages in preference to lower priority consumers. See this RabbitMQ extension's documentation * @param {Object} options.arguments - arbitrary arguments. Go to town. * @public * @method */ const startSubscription = (options) => { return consumer.startConsuming(internalHandler, options); }; /** * Gets the route being used for consuming * * @public * @method * @returns {Object} details of the route */ const getRoute = () => { return consumer.getRoute(); }; /** * Purges messages from a route's queue. Useful for testing, to ensure your queue is empty before subscribing * * @public * @method * @returns {Promise} a promise that is fulfilled when the queue has been purged */ const purgeQueue = () => { return consumer.purgeQueue(); }; return { on: on, once: once, use: use, startSubscription: startSubscription, getRoute: getRoute, purgeQueue: purgeQueue }; }
javascript
{ "resource": "" }
q13049
format
train
function format(results) { if (_isFormatted(results)) { return results; } var dependencyErrors = results.dependencies || []; var devDependencyErrors = results.devDependencies || []; var formattedErrors = { }; formattedErrors.dependencies = dependencyErrors.length ? _formatErrors('Dependencies', dependencyErrors) : dependencyErrors; formattedErrors.devDependencies = devDependencyErrors.length ? _formatErrors('Dev Dependencies', devDependencyErrors) : devDependencyErrors; return formattedErrors; }
javascript
{ "resource": "" }
q13050
hasErrors
train
function hasErrors(results) { return (results.dependencies && results.dependencies.length) || (results.devDependencies && results.devDependencies.length) }
javascript
{ "resource": "" }
q13051
gulp
train
function gulp(opts) { opts = opts || {}; var failOnError = opts['failOnError'] || false; var interimFiles = []; var failedValidations = []; return Through( function (file) { interimFiles.push(file.path); this.queue(file); }, function () { var baseFile = opts.packageFile; interimFiles.forEach(function (file) { opts.packageFile = file; var results = validate(opts); if (hasErrors(results)) { failedValidations.push(file); log(results); } }); opts.packageFile = baseFile; if (failOnError && failedValidations.length) { this.emit('error', new PluginError('dep-validate', 'Unable to validate dependencies')); } else { this.emit('end'); } } ); }
javascript
{ "resource": "" }
q13052
log
train
function log(results, stream) { stream = stream || process.stdout; if (results instanceof Error) { results = results.meta; } if (!_isFormatted(results)) { results = format(results); } stream.write(_join(results)); }
javascript
{ "resource": "" }
q13053
removeKeyFromList
train
function removeKeyFromList(list, key, value) { for (var i = list.length - 1; i >= 0; i--) { if (list[i][key] == value) { return list.splice(i, 1); // remove from array } } return false; }
javascript
{ "resource": "" }
q13054
replaceKeyFromList
train
function replaceKeyFromList(list, key, value, object) { for (var i = list.length - 1; i >= 0; i--) { if (list[i][key] == value) { return list.splice(i, 1, object); // remove from array and replace by the new object } } return false; }
javascript
{ "resource": "" }
q13055
addKeyToList
train
function addKeyToList(list, key, object) { for (var i = list.length - 1; i >= 0; i--) { if (list[i][key] == object[key]) { return false; } } list.push(object); return true; }
javascript
{ "resource": "" }
q13056
getKeyFromList
train
function getKeyFromList(list, key, value) { for (var i = list.length - 1; i >= 0; i--) { if (list[i][key] == value) { return list[i]; } } return false; }
javascript
{ "resource": "" }
q13057
removeSubKeyFromList
train
function removeSubKeyFromList(list, sub, key, value) { for (var i = list.length - 1; i >= 0; i--) { if (a4p.isDefined(list[i][sub]) && (list[i][sub][key] == value)) { return list.splice(i, 1); // remove from array } } return false; }
javascript
{ "resource": "" }
q13058
replaceSubKeyFromList
train
function replaceSubKeyFromList(list, sub, key, value, object) { for (var i = list.length - 1; i >= 0; i--) { if (a4p.isDefined(list[i][sub]) && (list[i][sub][key] == value)) { return list.splice(i, 1, object); // remove from array and replace by the new object } } return false; }
javascript
{ "resource": "" }
q13059
addSubKeyToList
train
function addSubKeyToList(list, sub, key, object) { for (var i = list.length - 1; i >= 0; i--) { if (a4p.isDefined(list[i][sub]) && (list[i][sub][key] == object[sub][key])) { return false; } } list.push(object); return true; }
javascript
{ "resource": "" }
q13060
getSubKeyFromList
train
function getSubKeyFromList(list, sub, key, value) { for (var i = list.length - 1; i >= 0; i--) { if (a4p.isDefined(list[i][sub]) && (list[i][sub][key] == value)) { return list[i]; } } return false; }
javascript
{ "resource": "" }
q13061
removeValueFromList
train
function removeValueFromList(list, value) { for (var i = list.length - 1; i >= 0; i--) { if (list[i] == value) { return list.splice(i, 1); // remove from array } } return false; }
javascript
{ "resource": "" }
q13062
replaceValueFromList
train
function replaceValueFromList(list, oldValue, newValue) { for (var i = list.length - 1; i >= 0; i--) { if (list[i] == oldValue) { return list.splice(i, 1, newValue); // remove from array and replace by the new object } } return false; }
javascript
{ "resource": "" }
q13063
addValueToList
train
function addValueToList(list, value) { for (var i = list.length - 1; i >= 0; i--) { if (list[i] == value) { return false; } } list.push(value); return true; }
javascript
{ "resource": "" }
q13064
isValueInList
train
function isValueInList(list, value) { for (var i = list.length - 1; i >= 0; i--) { if (list[i] == value) { return true; } } return false; }
javascript
{ "resource": "" }
q13065
train
function(oldItem, newItem) { if(data.operations) { for(var i = 0; i < data.operations.length; i++) { var operation = data.operations[i]; if(newItem && newItem[operation.field] !== undefined || oldItem && oldItem[operation.field] !== undefined) { opsToolbox[operation.operation].recompute(operations[operation.field], operation, oldItem, newItem); } } } }
javascript
{ "resource": "" }
q13066
Lookup
train
function Lookup(options) { this.options = options || {}; this.cwd = this.options.cwd || process.cwd(); this.limit = this.options.limit || 25; this.versions = {}; this.history = {}; this.parents = {}; this.cache = {}; this._paths = []; this.init(options); }
javascript
{ "resource": "" }
q13067
train
function(_node){ var _module; _node = _node._$getParent(); while(!!_node){ _module = _node._$getData().module; if (_t2._$isModule(_module)){ return _module._$getExportData(); } _node = _node._$getParent(); } return null; }
javascript
{ "resource": "" }
q13068
train
function (module, config) { var ret = { url: (config.root||'')+module, version: (config.ver||_o)[module] }; // convert xxx.html to xxx_ver.html if (!!config.mode&&!!ret.version){ ret.url = ret.url.replace( /(\.[^.\/]*?)$/, '_'+ret.version+'$1' ); ret.version = null; } return ret; }
javascript
{ "resource": "" }
q13069
locals
train
function locals (router) { router.use((req, res, next) => { absoluteUrl.attach(req) // requested resource res.locals.iri = req.iri // requested resource parsed into URL object res.locals.url = url.parse(res.locals.iri) // dummy translation res.locals.t = res.locals.t || ((x) => { return x.substring(x.indexOf(':') + 1) }) next() }) }
javascript
{ "resource": "" }
q13070
train
function (res, errorCode, errorMessage) { res.writeHead(errorCode, {"Content-Type": "text/html"}); //Read the local error file return fs.readFile(options.error, "utf8", function (error, content) { //Check the error if (error) { return res.end("<" + "h1>Error</h1><p>" + errorMessage + "</p>"); } let data = {code: errorCode, message: errorMessage}; content = content.replace(/{{([^{}]+)}}/g, function(match, found) { found = found.trim(); if(typeof data[found] !== "undefined") { return data[found].toString(); } else { return match; } }); return res.end(content); }); }
javascript
{ "resource": "" }
q13071
SocketController
train
function SocketController(namespace) { SocketController.super_.call(this); Object.defineProperties(this, { /** * Socket's namespace associated to the controller. * * @property namespace * @type SocketNamespace * @final */ namespace: {value: namespace}, /** * An emitter to emits clients' messages. * * @property emitter * @type AdvancedEmitter * @final */ emitter: {value: new AdvancedEmitter()} }); }
javascript
{ "resource": "" }
q13072
toggle
train
function toggle(main, alt) { var mw = core.base(); mw.enabled = true; mw.main = main; mw.alt = (alt || common.plain()); mw.active = mw.main; mw.swap = function () { mw.active = (mw.active !== mw.main ? mw.main : mw.alt); }; mw.error = function (str) { str = String(str); if (mw.enabled && mw.active) { return mw.active.error(str); } return str; }; mw.warning = function (str) { str = String(str); if (mw.enabled && mw.active) { return mw.active.warning(str); } return str; }; mw.success = function (str) { str = String(str); if (mw.enabled && mw.active) { return mw.active.error(str); } return str; }; mw.accent = function (str) { str = String(str); if (mw.enabled && mw.active) { return mw.active.accent(str); } return str; }; mw.signal = function (str) { str = String(str); if (mw.enabled && mw.active) { return mw.active.signal(str); } return str; }; mw.muted = function (str) { str = String(str); if (mw.enabled && mw.active) { return mw.active.muted(str); } return str; }; mw.plain = function (str) { str = String(str); if (mw.enabled && mw.active) { return mw.active.plain(str); } return str; }; mw.toString = function () { return '<ministyle-toggle>'; }; return mw; }
javascript
{ "resource": "" }
q13073
train
function (url) { var ret = true, xhr; try { // try the lowest footprint synchronous request to specific url. xhr = new XMLHttpRequest(); xhr.open("HEAD", url, false); xhr.send(); } catch (e) { ret = false; } return ret; }
javascript
{ "resource": "" }
q13074
train
function (params) { var xhr = new XMLHttpRequest(), async = typeof (params.asynchronous) === "boolean" ? params.asynchronous : this.asynchronous, readystatechange = function () { if (params.onreadystatechange) { params.onreadystatechange.call(this); } else { if (this.readyState === this.DONE) { if (!this.loadcalled) { // prevent multiple done calls from xhr. var resp; if (!xhr.timedOut) { resp = this.response || this.responseText; } this.loadcalled = true; if (resp && !this.responseType && params.responseType === "json") { try { resp = JSON.parse(resp); } catch (e) { logger.debug('Unable to parse JSON: ' + resp + '\n' + e); } } params.handler.call(this, (xhr.timedOut) ? -1 : this.status, resp, params); } } } }; // setup pre-open parameters params.xhr = xhr; if (params.responseType && typeof (xhr.responseType) === 'string') { // types for level 2 are still draft. Don't attempt to set until // support is more universal. // // xhr.responseType = params.responseType; logger.debug("Ignoring responseType on XHR until fully supported."); } xhr.open(params.method, params.url, async); Object.keys((params.headers || {})).forEach(function (val) { if (!(val === "Content-Type" && params.headers[val] === "multipart/form-data")) { xhr.setRequestHeader(val, params.headers[val]); } }); // If level 2, then attach the handlers directly. if (xhr.upload) { Object.keys(params).forEach(function (key) { if (key.indexOf("on") === 0 && typeof (params[key]) === 'function') { if (typeof (xhr[key]) !== 'undefined') { xhr[key] = params[key]; } if (typeof (xhr.upload[key]) !== 'undefined') { xhr.upload[key] = params[key]; } } }); } // still support readystate event. if (params.handler || params.onreadystatechange) { xhr.onreadystatechange = readystatechange; } if (params.timeout && typeof (params.timeout) === 'number') { xhr.timeout = params.timeout; xhr.ontimeout = function () { xhr.timedOut = true; xhr.abort(); }; setTimeout(function () { /* vs. xhr.timeout */ this.response = {}; if (xhr.readyState < 4 && !xhr.timedOut) { xhr.ontimeout(); } }, xhr.timeout); } xhr.send(params.payload); }
javascript
{ "resource": "" }
q13075
train
function(value) { if (!this.context) return; if (this.setter === false) return; if (!this.setter) { try { this.setter = typeof this.expression === 'string' ? expressions.parseSetter(this.expression, this.observations.globals, this.observations.formatters) : false; } catch (e) { this.setter = false; } if (!this.setter) return; } try { var result = this.setter.call(this.context, value); } catch(e) { return; } // We can't expect code in fragments outside Observer to be aware of "sync" since observer can be replaced by other // types (e.g. one without a `sync()` method, such as one that uses `Object.observe`) in other systems. this.sync(); this.observations.sync(); return result; }
javascript
{ "resource": "" }
q13076
train
function() { var value = this.get(); // Don't call the callback if `skipNextSync` was called on the observer if (this.skip || !this.callback) { this.skip = false; if (this.getChangeRecords) { // Store an immutable version of the value, allowing for arrays and objects to change instance but not content and // still refrain from dispatching callbacks (e.g. when using an object in bind-class or when using array formatters // in bind-each) this.oldValue = diff.clone(value); } else { this.oldValue = value; } } else { var change; var useCompareBy = this.getChangeRecords && this.compareBy && Array.isArray(value) && Array.isArray(this.oldValue); if (useCompareBy) { var compareExpression = this.compareBy; var name = this.compareByName; var index = this.compareByIndex || '__index__'; var ctx = this.context; var globals = this.observations.globals; var formatters = this.observations.formatters; var oldValue = this.oldValue; if (!name) { name = '__item__'; // Turn "id" into "__item__.id" compareExpression = name + '.' + compareExpression; } var getCompareValue = expressions.parse(compareExpression, globals, formatters, name, index); changed = diff.values(value.map(getCompareValue, ctx), oldValue.map(getCompareValue, ctx)); } else if (this.getChangeRecords) { changed = diff.values(value, this.oldValue); } else { changed = diff.basic(value, this.oldValue); } var oldValue = this.oldValue; if (this.getChangeRecords) { // Store an immutable version of the value, allowing for arrays and objects to change instance but not content and // still refrain from dispatching callbacks (e.g. when using an object in bind-class or when using array formatters // in bind-each) this.oldValue = diff.clone(value); } else { this.oldValue = value; } // If an array has changed calculate the splices and call the callback. if (!changed && !this.forceUpdateNextSync) return; this.forceUpdateNextSync = false; if (Array.isArray(changed)) { this.callback.call(this.callbackContext, value, oldValue, changed); } else { this.callback.call(this.callbackContext, value, oldValue); } } }
javascript
{ "resource": "" }
q13077
train
function(_clazz,_event){ var _element = _v._$getElement(_event); if (!_element.value) _e._$delClassName(_element,_clazz); }
javascript
{ "resource": "" }
q13078
train
function(_headers,_key,_default){ var _value = _headers[_key]|| _headers[_key.toLowerCase()]; if (!_value){ _value = _default; _headers[_key] = _value; } return _value; }
javascript
{ "resource": "" }
q13079
train
function(_data,_key,_map){ if (_u._$isArray(_data)){ _map[_key] = JSON.stringify(_data); } }
javascript
{ "resource": "" }
q13080
Antiscroll
train
function Antiscroll (el, opts) { this.el = $(el); this.options = opts || {}; // CUSTOM // this.x = (false !== this.options.x) || this.options.forceHorizontal; this.x = false; // Always hide horizontal scroll this.y = (false !== this.options.y) || this.options.forceVertical; this.autoHide = false !== this.options.autoHide; this.padding = undefined === this.options.padding ? 2 : this.options.padding; this.inner = this.el.find('.antiscroll-inner'); /* CUSTOM */ /* Don't add space to hide scrollbar multiple times */ if (this.inner.outerWidth() <= this.el.outerWidth()) { this.inner.css({ 'width': '+=' + (this.y ? scrollbarSize() : 0) // 'height': '+=' + (this.x ? scrollbarSize() : 0) }); } var cssMap = {}; if (this.x) cssMap.width = '+=' + scrollbarSize(); // if (this.y) cssMap.height = '+=' + scrollbarSize(); this.inner.css(cssMap); this.refresh(); }
javascript
{ "resource": "" }
q13081
Scrollbar
train
function Scrollbar (pane) { this.pane = pane; this.pane.el.append(this.el); this.innerEl = this.pane.inner.get(0); this.dragging = false; this.enter = false; this.shown = false; // hovering this.pane.el.mouseenter($.proxy(this, 'mouseenter')); this.pane.el.mouseleave($.proxy(this, 'mouseleave')); // dragging this.el.mousedown($.proxy(this, 'mousedown')); // scrolling this.innerPaneScrollListener = $.proxy(this, 'scroll'); this.pane.inner.scroll(this.innerPaneScrollListener); // wheel -optional- this.innerPaneMouseWheelListener = $.proxy(this, 'mousewheel'); this.pane.inner.bind('mousewheel', this.innerPaneMouseWheelListener); // show var initialDisplay = this.pane.options.initialDisplay; if (initialDisplay !== false) { this.show(); if (this.pane.autoHide) { this.hiding = setTimeout($.proxy(this, 'hide'), parseInt(initialDisplay, 10) || 3000); } } }
javascript
{ "resource": "" }
q13082
inherits
train
function inherits (ctorA, ctorB) { function f() {} f.prototype = ctorB.prototype; ctorA.prototype = new f(); }
javascript
{ "resource": "" }
q13083
Router
train
function Router(socket, options) { stream.Transform.call(this, { objectMode: true }); this.options = merge(Object.create(Router.DEFAULTS), options || {}); this.socket = socket; }
javascript
{ "resource": "" }
q13084
makeRequest
train
function makeRequest(apiKey, path, opts, callback) { var key, req, dataStr = ''; if(callback === undefined) { throw 'No callback defined'; return; } path = '/plus/v1/' + path + '?key=' + apiKey; for(key in opts) { path += '&' + key + '=' + opts[key]; } req = https.request({ host: 'www.googleapis.com', port: 443, path: path, method: 'GET' }, function(res) { res.on('data', function(data) { dataStr += data; }); res.on('end', function() { if(opts.alt === undefined || opts.alt.toLowerCase() == 'json') { try { callback(null, JSON.parse(dataStr)); } catch(err) { callback(null, dataStr); } } else { callback(null, dataStr); } }); res.on('close', function () { res.emit('end'); }); }); req.end(); req.on('error', function(err) { callback(err); }); return req; }
javascript
{ "resource": "" }
q13085
train
function (args) { this.type = "mixin"; this.fn = function (service) { service.create = service[this.create]; service.read = service[this.read]; service.update = service[this.update]; service.remove = service[this.remove]; }; }
javascript
{ "resource": "" }
q13086
MapProperty
train
function MapProperty(sourceExpression, keyExpression, resultExpression, removeExpression) { var parts = sourceExpression.split(/\s+in\s+/); this.sourceExpression = parts.pop(); this.itemName = parts.pop(); this.keyExpression = keyExpression; this.resultExpression = resultExpression; this.removeExpression = removeExpression; }
javascript
{ "resource": "" }
q13087
Suite
train
function Suite(title) { this.title = _.title(title); this.parent = null; this.runnables = []; this.events = { pre: 'pre:suite', post: 'post:suite' }; }
javascript
{ "resource": "" }
q13088
train
function () { var that = this, paramHandler = this.params.handler, params = util.mixin({}, this.params); //wrap the handler callbacks in a cancel check function handler(responseCode, data, ioArgs) { that.xhr = ioArgs.xhr; that.statusCode = that.xhr && !that.xhr.timedOut && that.xhr.status || 0; if (that.canceled) { logger.debug("Request [" + that.id + "] was canceled, not calling handler"); } else { that.pending = false; that.complete = true; paramHandler(responseCode, data, ioArgs); } } if (this.canceled) { logger.debug("Request [" + that.id + "] was canceled, not executing"); } else { this.pending = true; this.fn(util.mixin(params, { handler: handler })); } }
javascript
{ "resource": "" }
q13089
handler
train
function handler(responseCode, data, ioArgs) { that.xhr = ioArgs.xhr; that.statusCode = that.xhr && !that.xhr.timedOut && that.xhr.status || 0; if (that.canceled) { logger.debug("Request [" + that.id + "] was canceled, not calling handler"); } else { that.pending = false; that.complete = true; paramHandler(responseCode, data, ioArgs); } }
javascript
{ "resource": "" }
q13090
train
function(_options){ var _upload = _isUpload(_options.headers); if (!_isXDomain(_options.url)&&!_upload) return _t._$$ProxyXHR._$allocate(_options); return _h.__getProxyByMode(_options.mode,_upload,_options); }
javascript
{ "resource": "" }
q13091
train
function(_cache,_result){ var _data = { data:_result }; // parse ext headers var _keys = _cache.result.headers; if (!!_keys){ _data.headers = _cache.req._$header(_keys); } // TODO parse other ext data return _data; }
javascript
{ "resource": "" }
q13092
train
function(_url,_data){ var _sep = _url.indexOf('?')<0?'?':'&', _data = _data||''; if (_u._$isObject(_data)) _data = _u._$object2query(_data); if (!!_data) _url += _sep+_data; return _url; }
javascript
{ "resource": "" }
q13093
StorageError
train
function StorageError(message, code) { Error.captureStackTrace(this, this.constructor); Object.defineProperties(this, { /** * The error code. * * @property code * @type Number * @final */ code: {value: code}, /** * Error message. * * @property message * @type String * @final */ message: {value: 'A storage error occurred with code "' + code + '"', writable: true}, /** * The error name. * * @property name * @type String * @final */ name: {value: 'StorageError', writable: true} }); if (message) this.message = message; }
javascript
{ "resource": "" }
q13094
searchPathsRec
train
function searchPathsRec(thisPath, pathsToIgnore) { const subLogPrefix = logPrefix + 'searchPathsRec() - '; let result = []; let thisPaths; if (! pathsToIgnore) pathsToIgnore = []; try { if (that.fs.existsSync(thisPath + '/' + target) && result.indexOf(path.normalize(thisPath + '/' + target)) === - 1 && pathsToIgnore.indexOf(thisPath) === - 1) { result.push(path.normalize(thisPath + '/' + target)); } if (! that.fs.existsSync(thisPath)) { return result; } thisPaths = that.fs.readdirSync(thisPath); } catch (err) { that.log.error(subLogPrefix + 'throwed fs error: ' + err.message); return result; } for (let i = 0; thisPaths[i] !== undefined; i ++) { try { const subStat = that.fs.statSync(thisPath + '/' + thisPaths[i]); if (subStat.isDirectory()) { if (thisPaths[i] !== target && pathsToIgnore.indexOf(thisPaths[i]) === - 1) { // If we've found a target dir, we do not wish to scan it result = result.concat(searchPathsRec(thisPath + '/' + thisPaths[i], pathsToIgnore)); } } } catch (err) { that.log.error(subLogPrefix + 'Could not read "' + thisPaths[i] + '": ' + err.message); } } return result; }
javascript
{ "resource": "" }
q13095
loadPathsRec
train
function loadPathsRec(thisPath) { const subLogPrefix = logPrefix + 'loadPathsRec() - '; let thisPaths; if (that.paths.indexOf(thisPath) === - 1) { that.log.debug(subLogPrefix + 'Adding ' + path.basename(thisPath) + ' to paths with full path ' + thisPath); that.paths.push(thisPath); } thisPaths = that.fs.readdirSync(thisPath + '/node_modules'); for (let i = 0; thisPaths[i] !== undefined; i ++) { try { const subStat = that.fs.statSync(thisPath + '/node_modules/' + thisPaths[i]); if (subStat.isDirectory()) { loadPathsRec(thisPath + '/node_modules/' + thisPaths[i]); } } catch (err) { that.log.silly(subLogPrefix + 'Could not read "' + thisPaths[i] + '": ' + err.message); } } }
javascript
{ "resource": "" }
q13096
depth
train
function depth(root) { let i = 0; let walker = document.createTreeWalker(root, 0xFFFFFFFF, { acceptNode: function(node){ let nt = node.nodeType; return nt === 1 || nt === 3; } }); while(walker.nextNode()) { i++; } return i; }
javascript
{ "resource": "" }
q13097
writeShell
train
function writeShell(grunt, options, src, cwd, argArr) { let dir = options.writeShell; if (grunt.file.isFile(options.writeShell)) { dir = path.dirname(options.writeShell); } const gf = path.basename(src.toLowerCase(), path.extname(src)); const base = path.join(dir, options.target + '__' + gf); const _ = grunt.util._; const gruntCli = (_.isUndefined(options.gruntCli) || _.isNull(options.gruntCli)) ? 'grunt' : options.gruntCli; // beh const shPath = base + '.sh'; const shContent = [ '#!/bin/bash', '', 'cd ' + path.resolve(cwd), gruntCli + ' ' + argArr.join(' '), '' ].join('\n'); grunt.file.write(shPath, shContent); //TODO chmod the shell-script? // semi broken const batPath = base + '.bat'; const batContent = [ 'set PWD=%~dp0', 'cd ' + path.resolve(cwd), gruntCli + ' ' + argArr.join(' '), 'cd "%PWD%"', '' ].join('\r\n'); grunt.file.write(batPath, batContent); console.log('argArr: ' + argArr.join(' ')); }
javascript
{ "resource": "" }
q13098
Pilot
train
function Pilot(clientEmitter, namespace) { Pilot.super_.call(this); Object.defineProperties(this, { /** * The list of actually connected clients. * * @property clients * @type Array * @final */ clients: {value: []}, /** * The emitter to receive sockets' messages from clients. * * @property clientEmitter * @type AdvancedEmitter * @final */ clientEmitter: {value: clientEmitter}, /** * The sockets' namespace to communicate with clients. * * @property namespace * @type SocketNamespace * @final */ namespace: {value: namespace} }); }
javascript
{ "resource": "" }
q13099
Colleagues
train
function Colleagues (options) { this._ua = options.ua this._mingle = options.mingle this._conduit = options.conduit this._colleague = options.colleague }
javascript
{ "resource": "" }