_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q64900
test
function(config) { var me = this; var callback = config.success; if ((config.options && config.options.create) && this.path) { var folders = this.path.split("/"); if (folders[0] == '.' || folders[0] == '') { folders = folders.slice(1); } var recursiveCreation = function(dirEntry) { if (folders.length) { dirEntry.getDirectory(folders.shift(), config.options, recursiveCreation, config.failure); } else { callback(dirEntry); } }; recursiveCreation(this.fileSystem.fs.root); } else { this.fileSystem.fs.root.getDirectory(this.path, config.options, function(directory) { config.success.call(config.scope || me, directory); }, config.failure ); } }
javascript
{ "resource": "" }
q64901
test
function(config) { var me = this; var originalConfig = Ext.applyIf({}, config); if (this.fileSystem) { var failure = function(evt) { if ((config.options && config.options.create) && Ext.isString(this.path)) { var folders = this.path.split("/"); if (folders[0] == '.' || folders[0] == '') { folders = folders.slice(1); } if (folders.length > 1 && !config.recursive === true) { folders.pop(); var dirEntry = Ext.create('Ext.device.filesystem.DirectoryEntry', folders.join("/"), me.fileSystem); dirEntry.getEntry( { options: config.options, success: function() { originalConfig.recursive = true; me.getEntry(originalConfig); }, failure: config.failure } ); } else { if (config.failure) { config.failure.call(config.scope || me, evt); } } } else { if (config.failure) { config.failure.call(config.scope || me, evt); } } }; this.fileSystem.fs.root.getFile(this.path, config.options || null, function(fileEntry) { fileEntry.file( function(file) { me.length = file.size; originalConfig.success.call(config.scope || me, fileEntry); }, function(error) { failure.call(config.scope || me, error); } ); }, function(error) { failure.call(config.scope || me, error); } ); } else { config.failure({code: -1, message: "FileSystem not Initialized"}); } }
javascript
{ "resource": "" }
q64902
test
function(config) { if (config.size == null) { Ext.Logger.error('Ext.device.filesystem.FileEntry#write: You must specify a `size` of the file.'); return null; } var me = this; //noinspection JSValidateTypes this.getEntry( { success: function(fileEntry) { fileEntry.createWriter( function(writer) { writer.truncate(config.size); config.success.call(config.scope || me, me); }, function(error) { config.failure.call(config.scope || me, error) } ) }, failure: function(error) { config.failure.call(config.scope || me, error) } } ) }
javascript
{ "resource": "" }
q64903
test
function (obj) { const keys = _.sortBy(_.keys(obj), function (key) { return key; }); return _.zipObject(keys, _.map(keys, function (key) { return obj[key]; })); }
javascript
{ "resource": "" }
q64904
test
function(err) { if (err) return done(err); var ret; if (typeof leave == 'function') { try { ret = leave.call(this, child, parent); } catch (err) { return done(err); } } done(null, ret); }
javascript
{ "resource": "" }
q64905
MultiKeyCache
test
function MultiKeyCache(options) { options = options || {}; var self = this; var dispose = options.dispose; options.dispose = function (key, value) { self._dispose(key); if (dispose) { dispose(key, value); } }; this.cache = new LRU(options); this._keyMap = {}; }
javascript
{ "resource": "" }
q64906
pipe
test
function pipe() { for (var _len6 = arguments.length, fs = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { fs[_key6] = arguments[_key6]; } return function () { var _this3 = this; var first = fs.shift(); for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } return fs.reduce(function (acc, f) { return f.call(_this3, acc); }, first.apply(this, args)); }; }
javascript
{ "resource": "" }
q64907
createRawHtml
test
function createRawHtml( createTemplateFn, templateLanguage, elCommentConfig, dataAttributes ) { // Construct the HTML string var comment = elCommentConfig.noComment ? "" : "<!-- " + elCommentConfig.createContent( dataAttributes ) + " -->", insertion = elCommentConfig.among ? comment : "", isLeading = ! elCommentConfig.trailing && !elCommentConfig.among, isTrailing = elCommentConfig.trailing, baseTemplate = createTemplateFn( templateLanguage, insertion ); return isLeading ? comment + baseTemplate : isTrailing ? baseTemplate + comment : baseTemplate; }
javascript
{ "resource": "" }
q64908
createComplexTemplate
test
function createComplexTemplate ( templateLanguage, options ) { var t = getTemplateLanguageConstructs( templateLanguage ), indent = options && options.indentation || "", insert = options && options.insertion || "", lines = [ '<!-- top-level comment (single line) -->', '<!--', ' top-level', ' comment', ' (multi-line)', '-->', t.if, '<p>This is a %%paragraph', 'Some random %%text&& with different line breaks.<br><br/><br />', t.else, '<h1 class="header">This is a %%header&&</h1> ', t.endIf, t.if, '</p>', t.endIf, insert, 'Some top-level %%text&&, not wrapped in a tag.<br><br/><br />', '<!-- comment containing a <div> tag -->', "<" + "script>alert( 'foo' );</" + "script>", '<p class="significantWhitespaceExpected">', ' some text </p>', '<%%tagName&& %%attrs&&>lorem ipsum</%%tagName&&>', '<p><h1>Invalid nesting</h1></p>', t.partial, '<dl class="%%dl_class&&">', ' ' + t.loop, ' <dt class="dtclass">%%dd_name&&</dt>', ' <dd class="ddclass">%%dd_content&&</dd>', ' ' + t.endLoop, '</dl>' ], innerContent = _.map( lines, function ( line ) { return indent + line; } ).join( "\n" ); return innerContent.replace( /%%/g, t.startDelimiter ).replace( /&&/g, t.endDelimiter ); }
javascript
{ "resource": "" }
q64909
getTemplateLanguageConstructs
test
function getTemplateLanguageConstructs ( templateLanguage ) { var constructs; switch ( templateLanguage.toLowerCase() ) { case "handlebars": constructs = { startDelimiter: "{{", endDelimiter: "}}", if: "{{#if isActive}}", else: "{{else}}", endIf: "{{/if}}", loop: "{{#each looped as |value index|}}", endLoop: "{{/each}}", partial: '{{> userMessage tagName="h2" }}' }; break; case "ejs": constructs = { startDelimiter: "<%= ", endDelimiter: " %>", if: "<% if (isActive) { %>", else: "<% } else { %>", endIf: "<% } %>", loop: "<% looped.forEach(function(item) { %>", endLoop: "<% }); %>", partial: "<%- include('user/show', {user: user}); %>" }; break; case "es6": constructs = { startDelimiter: "${", endDelimiter: "}", if: "", else: "", endIf: "", loop: "", endLoop: "", partial: "" }; break; default: throw new Error( 'Unsupported template language "' + templateLanguage + '"' ); } return constructs; }
javascript
{ "resource": "" }
q64910
defineModel
test
function defineModel(modelType, options) { var primaryAttributes; var attributes; var prototype; var staticProto; var ModelConstructor; var typeName; var namespace; if (types.isValidType(modelType).indexes) { throw ModelException('Model type cannot be an array `{{type}}`', null, null, { type: String(modelType) }); } else if (models[modelType]) { throw ModelException('Model already defined `{{type}}`', null, null, { type: String(modelType) }); } options = options || {}; primaryAttributes = []; namespace = _getNamespace(modelType); typeName = _getTypeName(modelType); attributes = _prepareAttributes(options.attributes || {}, primaryAttributes); prototype = _preparePrototype(options.methods || {}, primaryAttributes, modelType, namespace, typeName); staticProto = _prepareStaticProto(options.staticMethods || {}, primaryAttributes, options.attributes, prototype._type); ModelConstructor = Function('Model, events, attributes', 'return function ' + typeName + 'Model(data) { ' + 'if (!(this instanceof ' + typeName + 'Model)){' + 'return new ' + typeName + 'Model(data);' + '}' + (attributes ? 'Object.defineProperties(this, attributes);' : '') + 'events.emit("create", data);' + 'Model.call(this, data);' + ' }' )(Model, events, attributes); util.inherits(ModelConstructor, Model); Object.defineProperties(ModelConstructor.prototype, prototype); Object.defineProperties(ModelConstructor, staticProto); if (!types.isDefined(modelType)) { types.define(modelType, options.typeValidator || _modelTypeValidator(ModelConstructor)); } // assign models[modelType] = ModelConstructor; events.emit('define', { modelType: modelType, namespace: namespace, typeName: typeName, attributes: attributes, constructor: ModelConstructor, options: options }); // Freeze model API for (var attr in attributes) { Object.freeze(attributes[attr]); } if (options.attributes) { Object.freeze(options.attributes); // freeze declared attributes } if (attributes) { Object.freeze(attributes); // freeze attributes list } Object.freeze(primaryAttributes); // freeze primary attributes //Object.freeze(ModelConstructor.prototype); // do not freeze to allow extensions return ModelConstructor; }
javascript
{ "resource": "" }
q64911
Model
test
function Model(data) { var attributes = this.__proto__.constructor.attributes; var i, ilen; var dirty = false; Object.defineProperties(this, { _id: { configurable: false, enumerable: true, writable: false, value: ++uniqueId }, _isDirty: { configurable: false, enumerable: true, get: function isDirty() { return dirty; }, set: function isDirty(d) { dirty = d; if (!d && this._previousData) { this._previousData = undefined; } } }, _isNew: { configurable: false, enumerable: true, get: function isNewModel() { var newModel = false; var attrValue; if (this._primaryAttributes) { for (i = 0, ilen = this._primaryAttributes.length; i < ilen && !newModel; ++i) { attrValue = this[this._primaryAttributes[i]]; if ((attrValue === undefined) || (attrValue === null)) { newModel = true; } } } return newModel; } } }); if (attributes) { Object.defineProperties(this, attributes); Object.defineProperty(this, '_data', { configurable: false, enumerable: false, writable: false, value: _defaultData(attributes) }); } if (Array.isArray(data)) { for (i = 0, ilen = data.length; i < ilen; ++i) { if (this._primaryAttributes[i]) { this[this._primaryAttributes[i]] = data[i]; } } } else if (data) { this.fromJSON(data); } this._isDirty = false; // overwrite... }
javascript
{ "resource": "" }
q64912
Point
test
function Point(masterApikey, feedID, streamID) { /** @private */this.masterApiKey = masterApikey; /** @private */this.feedID = feedID.toString(); /** @private */this.streamID = streamID.toString(); }
javascript
{ "resource": "" }
q64913
test
function(tabBar, newTab) { var oldActiveItem = this.getActiveItem(), newActiveItem; this.setActiveItem(tabBar.indexOf(newTab)); newActiveItem = this.getActiveItem(); return this.forcedChange || oldActiveItem !== newActiveItem; }
javascript
{ "resource": "" }
q64914
test
function(point1, point2) { var Point = Ext.util.Point; this.point1 = Point.from(point1); this.point2 = Point.from(point2); }
javascript
{ "resource": "" }
q64915
test
function(lineSegment) { var point1 = this.point1, point2 = this.point2, point3 = lineSegment.point1, point4 = lineSegment.point2, x1 = point1.x, x2 = point2.x, x3 = point3.x, x4 = point4.x, y1 = point1.y, y2 = point2.y, y3 = point3.y, y4 = point4.y, d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4), xi, yi; if (d == 0) { return null; } xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2) || xi < Math.min(x3, x4) || xi > Math.max(x3, x4) || yi < Math.min(y1, y2) || yi > Math.max(y1, y2) || yi < Math.min(y3, y4) || yi > Math.max(y3, y4)) { return null; } return new Ext.util.Point(xi, yi); }
javascript
{ "resource": "" }
q64916
SteroidsSocket
test
function SteroidsSocket(options) { var finalTarget; if (options.target && net.isIPv6(options.target)) { finalTarget = normalize6(options.target); } else { finalTarget = options.target; } this.target = finalTarget; this.port = options.port || 80; this.transport = options.transport || 'TCP'; this.lport = options.lport || null; this.timeout = options.timeout || 8000; this.allowHalfOpen = options.allowHalfOpen || null; this.wsProto = options.wsProto || 'sip'; this.wsPath = options.wsPath || null; // We init the socket in the send function to be able // to detect timeouts using UDP (no "received" or similar event) }
javascript
{ "resource": "" }
q64917
timeoutCb
test
function timeoutCb() { if (!received) { self.emit('error', { type: 'socket: timeout', data: 'Connection problem: No response' }); } // Websockets Node module doen't support any close function, we're using the client // https://github.com/Worlize/WebSocket-Node/blob/master/lib/WebSocketClient.js // So we need this var to "emulate" it and avoid returning multiple errors wsError = true; // We're closing the socket manually, so we need this to avoid errors self.close(); }
javascript
{ "resource": "" }
q64918
realWidth
test
function realWidth(str) { if (str == null) return 0; str = stripANSI(str); return str.length + (stripEmoji(str).match(/[^\x00-\xff]/g) || []).length; }
javascript
{ "resource": "" }
q64919
test
function (source, destination) { gulp.src(source) .pipe(conflict(destination)) .pipe(gulp.dest(destination)); }
javascript
{ "resource": "" }
q64920
test
function (source, destination) { if (!fs.existsSync(destination)) mkdir('-p', destination); cp('-R', source, destination); }
javascript
{ "resource": "" }
q64921
test
function (tracker, propList) { var trackingData = tracker[trackingKeyName]; propList.forEach(function (name) { Object.defineProperty(tracker, name, { enumerable: true, configurable: true, get: function () { return trackingData.object[name]; }, set: function (x) { trackingData.actions.push({ key: name, set: x, }); trackingData.object[name] = x; }, }); }); }
javascript
{ "resource": "" }
q64922
test
function (tracker, methodList) { var trackingData = tracker[trackingKeyName]; methodList.forEach(function (name) { tracker[name] = function () { var context = this; var argsArray = Array.prototype.slice.call(arguments); // Only record actions called directly on the tracker. if (this === tracker) { // Forwarded call should operate on original object. context = trackingData.object; trackingData.actions.push({ key: name, arguments: argsArray, }); } return trackingData.object[name].apply(context, argsArray); }; }); }
javascript
{ "resource": "" }
q64923
test
function (object) { var propList = []; var methodList = []; for (var k in object) { if (typeof object[k] === "function") { methodList.push(k); } else { propList.push(k); } } return { propList: propList, methodList: methodList, }; }
javascript
{ "resource": "" }
q64924
test
function(config,callback,scope) { // Ext.data.utilities.check('SyncProxy', 'constructor', 'config', config, ['store','database_name','key']); // Ext.data.SyncProxy.superclass.constructor.call(this, config); this.store= config.store; // // System Name // this.store.readValue('Sencha.Sync.system_name',function(system_name){ config.system_name= system_name || Ext.data.UUIDGenerator.generate(); this.store.writeValue('Sencha.Sync.system_name',config.system_name,function(){ // // Load Configuration // Ext.data.utilities.apply(this,[ 'readConfig_DatabaseDefinition', 'readConfig_CSV', 'readConfig_Generator'],[config],function(){ if (this.definition.system_name===undefined) { this.definition.set({system_name:Ext.data.UUIDGenerator.generate()}); } console.log("SyncProxy - Opened database '"+config.key+"/"+config.database_name+"/"+config.datastore_name+"'") if (callback) { callback.call(scope,this) } },this); },this); },this); }
javascript
{ "resource": "" }
q64925
test
function (content) { content = trim(content); if (this.mounted) { invoke(this, [ Constants.BLOCK, 'setMountedContent' ], content); } else { dom.contentNode(this).innerHTML = content; this.upgrade(); } }
javascript
{ "resource": "" }
q64926
test
function () { const props = dom.attrs.toObject(this); const xprops = this.xprops; const eprops = get(xtag, [ 'tags', this[ Constants.TAGNAME ], 'accessors' ], {}); for (let prop in eprops) { if (xprops.hasOwnProperty(prop) && eprops.hasOwnProperty(prop) && !BLOCK_COMMON_ACCESSORS.hasOwnProperty(prop)) { props[ prop ] = this[ prop ]; } } dom.attrs.typeConversion(props, xprops); return props; }
javascript
{ "resource": "" }
q64927
test
function (deep) { // not to clone the contents const node = dom.cloneNode(this, false); dom.upgrade(node); node[ Constants.TMPL ] = this[ Constants.TMPL ]; node[ Constants.INSERTED ] = false; if (deep) { node.content = this.content; } // ??? // if ('checked' in this) clone.checked = this.checked; return node; }
javascript
{ "resource": "" }
q64928
blockInit
test
function blockInit(node) { if (!node[ Constants.TAGNAME ]) { node[ Constants.INSERTED ] = false; node[ Constants.TAGNAME ] = node.tagName.toLowerCase(); node[ Constants.TMPL ] = {}; node[ Constants.UID ] = uniqueId(); return true; } return false; }
javascript
{ "resource": "" }
q64929
blockCreate
test
function blockCreate(node) { if (node.hasChildNodes()) { Array.prototype.forEach.call( node.querySelectorAll('script[type="text/x-template"][ref],template[ref]'), tmplCompileIterator, node ); } node[ Constants.BLOCK ] = new XBElement(node); }
javascript
{ "resource": "" }
q64930
accessorsCustomizer
test
function accessorsCustomizer(objValue, srcValue) { const objSetter = get(objValue, 'set'); const srcSetter = get(srcValue, 'set'); return merge({}, objValue, srcValue, { set: wrap(objSetter, wrap(srcSetter, wrapperFunction)) }); }
javascript
{ "resource": "" }
q64931
wrapperEvents
test
function wrapperEvents(srcFunc, objFunc, ...args) { const event = (args[ 0 ] instanceof Event) && args[ 0 ]; const isStopped = event ? () => event.immediatePropagationStopped : stubFalse; if (!isStopped() && isFunction(objFunc)) { objFunc.apply(this, args); } if (!isStopped() && isFunction(srcFunc)) { srcFunc.apply(this, args); } }
javascript
{ "resource": "" }
q64932
accessorsIterator
test
function accessorsIterator(options, name, accessors) { const optionsSetter = get(options, 'set'); const updateSetter = wrap(name, wrapperAccessorsSetUpdate); accessors[ name ] = merge({}, options, { set: wrap(optionsSetter, wrap(updateSetter, wrapperFunction)) }); }
javascript
{ "resource": "" }
q64933
wrapperAccessorsSetUpdate
test
function wrapperAccessorsSetUpdate(accessorName, nextValue, prevValue) { if (nextValue !== prevValue && this.xprops.hasOwnProperty(accessorName) && this.mounted) { this[ Constants.BLOCK ].update(); } }
javascript
{ "resource": "" }
q64934
lifecycleRemoved
test
function lifecycleRemoved() { this[ Constants.INSERTED ] = false; const block = this[ Constants.BLOCK ]; if (block) { block.destroy(); this[ Constants.BLOCK ] = undefined; } }
javascript
{ "resource": "" }
q64935
lifecycleInserted
test
function lifecycleInserted() { if (this[ Constants.INSERTED ]) { return; } blockInit(this); this[ Constants.INSERTED ] = true; const isScriptContent = Boolean(this.querySelector('script')); // asynchronous read content // <xb-test><script>...</script><div>not found</div></xb-test> if (isScriptContent) { lazy(blockCreateLazy, this); } else { blockCreate(this); } }
javascript
{ "resource": "" }
q64936
test
function (obj, removeProp) { var newObj = {}; for (var prop in obj) { if (!obj.hasOwnProperty(prop) || prop === removeProp) { continue; } newObj[prop] = obj[prop]; } return newObj; }
javascript
{ "resource": "" }
q64937
toDashedProperties
test
function toDashedProperties ( hash ) { var transformed = {}; _.each( hash, function ( value, key ) { transformed[toDashed( key )] = value; } ); return transformed; }
javascript
{ "resource": "" }
q64938
toCamelCasedProperties
test
function toCamelCasedProperties ( hash ) { var transformed = {}; _.each( hash, function ( value, key ) { transformed[toCamelCase( key )] = value; } ); return transformed; }
javascript
{ "resource": "" }
q64939
dashedKeyAlternatives
test
function dashedKeyAlternatives ( hash ) { var keys = _.keys( toDashedProperties( hash ) ); return _.filter( keys, function ( key ) { return key.search(/[^-]-[a-z]/) !== -1; } ); }
javascript
{ "resource": "" }
q64940
test
function(selector, root) { var selectors = selector.split(','), length = selectors.length, i = 0, results = [], noDupResults = [], dupMatcher = {}, query, resultsLn, cmp; for (; i < length; i++) { selector = Ext.String.trim(selectors[i]); query = this.parse(selector); // query = this.cache[selector]; // if (!query) { // this.cache[selector] = query = this.parse(selector); // } results = results.concat(query.execute(root)); } // multiple selectors, potential to find duplicates // lets filter them out. if (length > 1) { resultsLn = results.length; for (i = 0; i < resultsLn; i++) { cmp = results[i]; if (!dupMatcher[cmp.id]) { noDupResults.push(cmp); dupMatcher[cmp.id] = true; } } results = noDupResults; } return results; }
javascript
{ "resource": "" }
q64941
test
function(component, selector) { if (!selector) { return true; } var query = this.cache[selector]; if (!query) { this.cache[selector] = query = this.parse(selector); } return query.is(component); }
javascript
{ "resource": "" }
q64942
RouterDecorator
test
function RouterDecorator (Router) { function TelemetryRouter (options) { if (!(this instanceof TelemetryRouter)) { return new TelemetryRouter(options) } Router.call(this, options) } inherits(TelemetryRouter, Router) /** * Wraps getNearestContacts with telemetry * #getNearestContacts * @returns {Array} shortlist */ TelemetryRouter.prototype.getNearestContacts = function (key, limit, id, cb) { var self = this var callback = function (err, shortlist) { if (!err) { self._log.debug('sorting shortlist based on telemetry score') var profiles = {} each(shortlist, function (contact, iteratorCallback) { var profileCallback = function (err, profile) { profiles[contact.nodeID] = profile iteratorCallback(err) } self._rpc.telemetry.getProfile(contact, profileCallback) }, function (err) { if (err) { cb(null, shortlist) } else { shortlist.sort(self._compare.bind(self, profiles)) cb(null, shortlist) } }) } else { cb(err, null) } } Router.prototype.getNearestContacts.call(this, key, limit, id, callback) } /** * Uses the transport telemetry to compare two nodes * #_compare * @param {kad.Contact} contactA * @param {kad.Contact} contactB * @returns {Number} */ TelemetryRouter.prototype._compare = function (profiles, cA, cB) { var profileA = profiles[cA.nodeID] var profileB = profiles[cB.nodeID] var scoresA = {} var scoresB = {} this._rpc._telopts.metrics.forEach(function (Metric) { var m = new Metric() scoresA[m.key] = Metric.score(m.getMetric(profileA)) scoresB[m.key] = Metric.score(m.getMetric(profileB)) }) var resultA = TelemetryRouter.getSuccessProbability(scoresA) var resultB = TelemetryRouter.getSuccessProbability(scoresB) this._log.debug( 'success probability is %d% vs %d%', (resultA * 100).toFixed(3), (resultB * 100).toFixed(3) ) // results are close to each other, break tie with throughput score if (Math.abs(resultB - resultA) <= 0.005) { this._log.debug( 'score difference is within threshold, selecting based on throughput' ) return scoresB.throughput - scoresA.throughput } return resultB - resultA } /** * Uses a profile scorecard to calculate the probability of success * #getSuccessProbability * @param {Object} score * @returns {Number} */ TelemetryRouter.getSuccessProbability = function (score) { return (score.reliability + score.availability + score.latency) / 3 } return TelemetryRouter }
javascript
{ "resource": "" }
q64943
test
function(config) { if (!this.active) { Ext.Logger.error('Ext.device.sqlite.SQLTransaction#executeSql: An attempt was made to use a SQLTransaction that is no longer usable.'); return null; } if (config.sqlStatement == null) { Ext.Logger.error('Ext.device.sqlite.SQLTransaction#executeSql: You must specify a `sqlStatement` for the transaction.'); return null; } this.statements.push({ sqlStatement: config.sqlStatement, arguments: config.arguments, callback: config.callback, failure: config.failure, scope: config.scope }); }
javascript
{ "resource": "" }
q64944
test
function(index) { if (index < this.getLength()) { var item = {}; var row = this.rows[index]; this.names.forEach(function(name, index) { item[name] = row[index]; }); return item; } return null; }
javascript
{ "resource": "" }
q64945
createPayload
test
function createPayload(name, level, data) { return { date: getDate(), level: level, name: name, data: data }; }
javascript
{ "resource": "" }
q64946
__ENFORCETYPE
test
function __ENFORCETYPE(a, ...types) { if (env.application_env !== "development") return; let hasError = false; let expecting; let got; let i = 0; types.map( (t, index) => { if (a[index] === null) { hasError = true; expecting = t; got = "null"; i = index; return; } switch (t) { case "mixed": break; case "jsx": if (!React.isValidElement(a[index])) { hasError = true; expecting = "jsx"; got = typeof a[index]; i = index; } case "array": if (!Array.isArray(a[index])) { hasError = true; expecting = "array"; got = typeof a[index]; i = index; } break; case "object": if (typeof a[index] !== 'object' || Array.isArray(a[index]) || a[index] === null) { hasError = true; expecting = "object"; i = index; if (a[index] === null) { got = 'null'; } else { got = Array.isArray(a[index]) ? "array" : typeof a[index]; } } default: if (typeof a[index] !== t) { hasError = true;{ expecting = t; got = typeof a[index];} i = index; } } }); if (hasError) { let err = new Error(); console.error(`ENFORCETYPE: param ${i + 1} is expecting ${expecting} got ${got} instead.`, err.stack); } }
javascript
{ "resource": "" }
q64947
assign
test
function assign(parent, val, keyOpts) { var target = parent, keyParts = keyOpts.val.toString().split('.'); keyParts.forEach(function(keyPart, idx) { if (keyParts.length === idx + 1) { if (val !== undefined) { if (Array.isArray(val) && Array.isArray(target[keyPart])) { val = target[keyPart].concat(val); } if (!((Array.isArray(val) && !val.length) || (typeof val === 'object' && !Object.keys(val || {}).length))) { target[keyPart] = val; } } } else if (!(keyPart in target)) { target[keyPart] = {}; } }); }
javascript
{ "resource": "" }
q64948
test
function(node1, node2) { // A shortcut for siblings if (node1.parentNode === node2.parentNode) { return (node1.data.index < node2.data.index) ? -1 : 1; } // @NOTE: with the following algorithm we can only go 80 levels deep in the tree // and each node can contain 10000 direct children max var weight1 = 0, weight2 = 0, parent1 = node1, parent2 = node2; while (parent1) { weight1 += (Math.pow(10, (parent1.data.depth+1) * -4) * (parent1.data.index+1)); parent1 = parent1.parentNode; } while (parent2) { weight2 += (Math.pow(10, (parent2.data.depth+1) * -4) * (parent2.data.index+1)); parent2 = parent2.parentNode; } if (weight1 > weight2) { return 1; } else if (weight1 < weight2) { return -1; } return (node1.data.index > node2.data.index) ? 1 : -1; }
javascript
{ "resource": "" }
q64949
test
function(root) { var node = this.getNode(), recursive = this.getRecursive(), added = [], child = root; if (!root.childNodes.length || (!recursive && root !== node)) { return added; } if (!recursive) { return root.childNodes; } while (child) { if (child._added) { delete child._added; if (child === root) { break; } else { child = child.nextSibling || child.parentNode; } } else { if (child !== root) { added.push(child); } if (child.firstChild) { child._added = true; child = child.firstChild; } else { child = child.nextSibling || child.parentNode; } } } return added; }
javascript
{ "resource": "" }
q64950
test
function(config) { var me = this; config = Ext.device.filesystem.Abstract.prototype.requestFileSystem(config); var successCallback = function(fs) { var fileSystem = Ext.create('Ext.device.filesystem.FileSystem', fs); config.success.call(config.scope || me, fileSystem); }; if (config.type == window.PERSISTENT) { if(navigator.webkitPersistentStorage) { navigator.webkitPersistentStorage.requestQuota(config.size, function(grantedBytes) { window.webkitRequestFileSystem( config.type, grantedBytes, successCallback, config.failure ); }) }else { window.webkitStorageInfo.requestQuota(window.PERSISTENT, config.size, function(grantedBytes) { window.webkitRequestFileSystem( config.type, grantedBytes, successCallback, config.failure ); }) } } else { window.webkitRequestFileSystem( config.type, config.size, successCallback, config.failure ); } }
javascript
{ "resource": "" }
q64951
test
function(operation, callback, scope) { var me = this, writer = me.getWriter(), request = me.buildRequest(operation); request.setConfig({ headers: me.getHeaders(), timeout: me.getTimeout(), method: me.getMethod(request), callback: me.createRequestCallback(request, operation, callback, scope), scope: me, proxy: me, useDefaultXhrHeader: me.getUseDefaultXhrHeader() }); if (operation.getWithCredentials() || me.getWithCredentials()) { request.setWithCredentials(true); request.setUsername(me.getUsername()); request.setPassword(me.getPassword()); } // We now always have the writer prepare the request request = writer.write(request); Ext.Ajax.request(request.getCurrentConfig()); return request; }
javascript
{ "resource": "" }
q64952
test
function(err) { var output; try { var fieldName = err.err.substring(err.err.lastIndexOf('.$') + 2, err.err.lastIndexOf('_1')); output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exists'; } catch (ex) { output = 'Unique field already exists'; } return output; }
javascript
{ "resource": "" }
q64953
test
function( project ) { var current = process.cwd(); console.log( '\nCreating folder "' + project + '"...' ); // First, create the directory fs.mkdirSync( path.join( current, project ) ); console.log( '\nCopying the files in "' + project + '"...' ); // Then, copy the files into it wrench.copyDirSyncRecursive( path.join( __dirname, 'default', 'project' ), path.join( current, project ) ); console.log( '\nCreating the package.json file...' ); // Open the package.json file and fill it in // with the correct datas. var packagePath = path.join( current, project, 'package.json' ); // First, get the datas var pack = JSON.parse( fs.readFileSync( packagePath )); // Add the properties in the object pack.name = project; pack.version = '0.0.1'; pack.dependencies = { 'tartempion': '0.0.x' }; // And write the object to the package.json file // by overriding everything in it. fs.writeFileSync( packagePath, JSON.stringify( pack, null, 4 ) ); console.log( '\nProject "' + project + '" created.\n' ); }
javascript
{ "resource": "" }
q64954
prewatch
test
function prewatch(theOptions) { if (config.watch) { return _.defaults(theOptions, watchify.args); } return theOptions; }
javascript
{ "resource": "" }
q64955
test
function(index, filters) { // We begin by making sure we are dealing with an array of sorters if (!Ext.isArray(filters)) { filters = [filters]; } var ln = filters.length, filterRoot = this.getFilterRoot(), currentFilters = this.getFilters(), newFilters = [], filterConfig, i, filter; if (!currentFilters) { currentFilters = this.createFiltersCollection(); } // We first have to convert every sorter into a proper Sorter instance for (i = 0; i < ln; i++) { filter = filters[i]; filterConfig = { root: filterRoot }; if (Ext.isFunction(filter)) { filterConfig.filterFn = filter; } // If we are dealing with an object, we assume its a Sorter configuration. In this case // we create an instance of Sorter passing this configuration. else if (Ext.isObject(filter)) { if (!filter.isFilter) { if (filter.fn) { filter.filterFn = filter.fn; delete filter.fn; } filterConfig = Ext.apply(filterConfig, filter); } else { newFilters.push(filter); if (!filter.getRoot()) { filter.setRoot(filterRoot); } continue; } } // Finally we get to the point where it has to be invalid // <debug> else { Ext.Logger.warn('Invalid filter specified:', filter); } // </debug> // If a sorter config was created, make it an instance filter = Ext.create('Ext.util.Filter', filterConfig); newFilters.push(filter); } // Now lets add the newly created sorters. for (i = 0, ln = newFilters.length; i < ln; i++) { currentFilters.insert(index + i, newFilters[i]); } this.dirtyFilterFn = true; if (currentFilters.length) { this.filtered = true; } return currentFilters; }
javascript
{ "resource": "" }
q64956
test
function(filters) { // We begin by making sure we are dealing with an array of sorters if (!Ext.isArray(filters)) { filters = [filters]; } var ln = filters.length, currentFilters = this.getFilters(), i, filter; for (i = 0; i < ln; i++) { filter = filters[i]; if (typeof filter === 'string') { currentFilters.each(function(item) { if (item.getProperty() === filter) { currentFilters.remove(item); } }); } else if (typeof filter === 'function') { currentFilters.each(function(item) { if (item.getFilterFn() === filter) { currentFilters.remove(item); } }); } else { if (filter.isFilter) { currentFilters.remove(filter); } else if (filter.property !== undefined && filter.value !== undefined) { currentFilters.each(function(item) { if (item.getProperty() === filter.property && item.getValue() === filter.value) { currentFilters.remove(item); } }); } } } if (!currentFilters.length) { this.filtered = false; } }
javascript
{ "resource": "" }
q64957
wrapperMergeResult
test
function wrapperMergeResult(srcFunc, objFunc, ...args) { let resultObjFunction = {}; let resultSrcFunction = {}; if (isFunction(objFunc)) { resultObjFunction = objFunc.apply(this, args); } if (isFunction(srcFunc)) { resultSrcFunction = srcFunc.apply(this, args); } return merge({}, resultObjFunction, resultSrcFunction); }
javascript
{ "resource": "" }
q64958
wrapperOrResult
test
function wrapperOrResult(srcFunc, objFunc, ...args) { let resultObjFunction = false; let resultSrcFunction = false; if (isFunction(objFunc)) { resultObjFunction = objFunc.apply(this, args); } if (isFunction(srcFunc)) { resultSrcFunction = srcFunc.apply(this, args); } return resultObjFunction || resultSrcFunction; }
javascript
{ "resource": "" }
q64959
test
function(instance) { this._model = instance._model; this._instance = instance; this.id = instance.id; this.eachAttribute = function(cb) { return this._model.eachAttribute(cb); }; this.eachRelationship = function (cb) { return this._model.eachRelationship(cb); } this.attr = function(name) { return this._instance[name]; }; this.belongsTo = function(name, opts) { return (opts.id ? this._instance[name].id : new Snapshot(this._instance[name])); }; }
javascript
{ "resource": "" }
q64960
test
function(val) { var trimmed = val.trim(); if(trimmed.indexOf("'") === 0 && trimmed.lastIndexOf("'") === (trimmed.length - 1)) return '"' + trimmed.substring(1, trimmed.length - 1) + '"'; return val; }
javascript
{ "resource": "" }
q64961
test
function(typeName, obj) { this.type = typeName; if(typeof obj !== 'undefined') for(var key in obj) this[key] = obj[key]; }
javascript
{ "resource": "" }
q64962
test
function() { var idStr = '' + sforce.db.id++; return sforce.db._idTemplate.substring(0, 18 - idStr.length) + idStr; }
javascript
{ "resource": "" }
q64963
test
function(select) { var chars = new antlr4.InputStream(input); var lexer = new SelectLexer(chars); var tokens = new antlr4.CommonTokenStream(lexer); var parser = new SelectParser(tokens); parser.buildParseTrees = true; return parser.select(); }
javascript
{ "resource": "" }
q64964
test
function(obj) { var schema = sforce.db.schema; var objDesc = schema[obj.type]; if(typeof objDesc === 'undefined') throw 'No type exists by the name: ' + obj.type; for(var key in obj) { if({ Id:false, type:true }[key]) continue; var fieldDesc = null; for(var i = 0; i < objDesc.fields.length; i++) { var fd = objDesc.fields[i]; if(fd.name === key) { fieldDesc = fd; break; } } if(fieldDesc == null) throw 'No field exists by the name: ' + key + 'in the type: ' + obj.type; } }
javascript
{ "resource": "" }
q64965
test
function(type, fields) { for(var i = 0; i < fields.length; i++) sforce.db.validateField(type, fields[i]); }
javascript
{ "resource": "" }
q64966
test
function(type, field) { var objDesc = sforce.db.schema[type]; for(var i = 0; i < objDesc.fields.length; i++) if(objDesc.fields[i].name === field) return; throw 'No field exists by the name: ' + field + 'in the type: ' + type; }
javascript
{ "resource": "" }
q64967
test
function(type, rel) { var objDesc = sforce.db.schema[type]; for(var i = 0; i < objDesc.childRelationships.length; i++) if(objDesc.childRelationships[i].relationshipName === rel) return; throw 'No child relationship exists by the name: ' + rel + 'in the type: ' + type; }
javascript
{ "resource": "" }
q64968
test
function(type) { var sos = sforce.db.sobjects; if(typeof sos[type] !== 'object') sos[type] = {}; return sos[type]; }
javascript
{ "resource": "" }
q64969
test
function(resultAry, isRoot) { if(resultAry.length == 0) { if(isRoot) return { done : 'true', queryLocator : null, size : 0, }; return null; } var records = null; if(resultAry.length == 1) records = resultAry[0]; else records = resultAry; return { done : 'true', queryLocator : null, records : records, size : resultAry.length, }; }
javascript
{ "resource": "" }
q64970
test
function(obj) { var matches = this.sequence[0].matches(obj); for(var i = 1; i < this.sequence.length; i += 2) { if(this.sequence[i] === '&') matches = matches && this.sequence[i+1].matches(obj); else matches = matches || this.sequence[i+1].matches(obj); } return matches; }
javascript
{ "resource": "" }
q64971
addContents
test
function addContents($, contents) { console.log('addContents', contents); var body = document.getElementsByTagName('BODY'); if (!body) return; var $body = $(body[0]), contentsStyle = [ 'position:fixed;right:1em;top:1em;', 'padding:0.5em;min-width:120px;', 'font-size:90%;line-height:18px;', 'border:1px solid #aaa;background: #F9F9F9;' ].join(''), html = [], order = [], hash = []; for (var i = 0; i < contents.length; ++i) { order[i] = 0; hash[i] = ''; } function indexOf(tag) { for (var i = 0; i < contents.length && contents[i].toLowerCase() !== tag; ++i); return i; } $(contents.join(',')).each(function (i, obj) { var index = indexOf(obj.tagName.toLowerCase()); order[index]++; hash[index] = $(obj).text(); for (var j = index + 1; j < contents.length; ++j) { // Clear low level order order[j] = 0; hash[j] = ''; } var anchor = hash.slice(0, index + 1).join('-'); //anchor = '__id_' + tag + Math.floor(9999999 * Math.random()); // Add anchor $(obj).append(fm('<a name="{0}" style="color:#333;"></a>', anchor)); // Add contents item html.push(fm('<div style="padding-left:{0}em;"><a href="#{2}" style="text-decoration:none;">{1}</a></div>', index * 1.5, order.slice(0, index + 1).join('.') + ' ' + hash[index], anchor)); }); var $contentsWrap = $(fm(['<div style="{0}">', '<div style="text-align: center;height:22px;line-height:22px;">', '<b>Contents</b> <a href="javascript:;">hide</a>', '</div>', '<div>{1}</div>', '</div>'].join(''), contentsStyle, html.join(''))).prependTo($body), $toggle = $contentsWrap.find('> :first').find('> :last'), $contents = $contentsWrap.find('> :last'); console.log($contentsWrap, $toggle, $contents); $toggle.click(function () { $contents.slideToggle(); $toggle.html($toggle.html() === 'show' ? 'hide' : 'show'); }); }
javascript
{ "resource": "" }
q64972
addTop
test
function addTop($, top) { console.log('addTop', top); $(top.join(',')).each(function (i, obj) { //$(obj).append(' <a href="#" style="display:none;font-size: 12px;color: #333;">Top</a>'); $(obj).prepend(['<div style="position: relative;width: 1px;">', '<a href="javascript:;" style="position:absolute;width:1.2em;left:-1.2em;font-size:0.8em;display:inline-block;visibility:hidden;color:#333;text-align:left;text-decoration: none;">', '&#10022;</a>', '</div>'].join('')); var $prefix = $(this).find(':first').find(':first'); //var $top = $(this).find('a:last'); //console.log($prefix, $top); var rawCol = $(obj).css('background-color'); $(obj).mouseover( function () { $prefix.css('height', $(this).css('height')); $prefix.css('line-height', $(this).css('line-height')); $prefix.css('visibility', 'visible'); $(this).css('background-color', '#FFF8D7'); }).mouseout(function () { $prefix.css('visibility', 'hidden'); $(this).css('background-color', rawCol); }); }); }
javascript
{ "resource": "" }
q64973
test
function() { var actions = this.getActions(), namespace = this.getNamespace(), action, cls, methods, i, ln, method; for (action in actions) { if (actions.hasOwnProperty(action)) { cls = namespace[action]; if (!cls) { cls = namespace[action] = {}; } methods = actions[action]; for (i = 0, ln = methods.length; i < ln; ++i) { method = Ext.create('Ext.direct.RemotingMethod', methods[i]); cls[method.getName()] = this.createHandler(action, method); } } } }
javascript
{ "resource": "" }
q64974
test
function(transaction, event) { var success = !!event.getStatus(), functionName = success ? 'success' : 'failure', callback = transaction && transaction.getCallback(), result; if (callback) { // this doesnt make any sense. why do we have both result and data? // result = Ext.isDefined(event.getResult()) ? event.result : event.data; result = event.getResult(); if (Ext.isFunction(callback)) { callback(result, event, success); } else { Ext.callback(callback[functionName], callback.scope, [result, event, success]); Ext.callback(callback.callback, callback.scope, [result, event, success]); } } }
javascript
{ "resource": "" }
q64975
test
function(options, success, response) { var me = this, i = 0, ln, events, event, transaction, transactions; if (success) { events = me.createEvents(response); for (ln = events.length; i < ln; ++i) { event = events[i]; transaction = me.getTransaction(event); me.fireEvent('data', me, event); if (transaction) { me.runCallback(transaction, event, true); Ext.direct.Manager.removeTransaction(transaction); } } } else { transactions = [].concat(options.transaction); for (ln = transactions.length; i < ln; ++i) { transaction = me.getTransaction(transactions[i]); if (transaction && transaction.getRetryCount() < me.getMaxRetries()) { transaction.retry(); } else { event = Ext.create('Ext.direct.ExceptionEvent', { data: null, transaction: transaction, code: Ext.direct.Manager.exceptions.TRANSPORT, message: 'Unable to connect to the server.', xhr: response }); me.fireEvent('data', me, event); if (transaction) { me.runCallback(transaction, event, false); Ext.direct.Manager.removeTransaction(transaction); } } } } }
javascript
{ "resource": "" }
q64976
test
function(options) { return options && options.getTid ? Ext.direct.Manager.getTransaction(options.getTid()) : null; }
javascript
{ "resource": "" }
q64977
test
function(action, method, args) { var me = this, callData = method.getCallData(args), data = callData.data, callback = callData.callback, scope = callData.scope, transaction; transaction = Ext.create('Ext.direct.Transaction', { provider: me, args: args, action: action, method: method.getName(), data: data, callback: scope && Ext.isFunction(callback) ? Ext.Function.bind(callback, scope) : callback }); if (me.fireEvent('beforecall', me, transaction, method) !== false) { Ext.direct.Manager.addTransaction(transaction); me.queueTransaction(transaction); me.fireEvent('call', me, transaction, method); } }
javascript
{ "resource": "" }
q64978
test
function(transaction) { return { action: transaction.getAction(), method: transaction.getMethod(), data: transaction.getData(), type: 'rpc', tid: transaction.getId() }; }
javascript
{ "resource": "" }
q64979
test
function(transaction) { var me = this, enableBuffer = me.getEnableBuffer(); if (transaction.getForm()) { me.sendFormRequest(transaction); return; } me.callBuffer.push(transaction); if (enableBuffer) { if (!me.callTask) { me.callTask = Ext.create('Ext.util.DelayedTask', me.combineAndSend, me); } me.callTask.delay(Ext.isNumber(enableBuffer) ? enableBuffer : 10); } else { me.combineAndSend(); } }
javascript
{ "resource": "" }
q64980
test
function() { var buffer = this.callBuffer, ln = buffer.length; if (ln > 0) { this.sendRequest(ln == 1 ? buffer[0] : buffer); this.callBuffer = []; } }
javascript
{ "resource": "" }
q64981
test
function(action, method, form, callback, scope) { var me = this, transaction, isUpload, params; transaction = new Ext.direct.Transaction({ provider: me, action: action, method: method.getName(), args: [form, callback, scope], callback: scope && Ext.isFunction(callback) ? Ext.Function.bind(callback, scope) : callback, isForm: true }); if (me.fireEvent('beforecall', me, transaction, method) !== false) { Ext.direct.Manager.addTransaction(transaction); isUpload = String(form.getAttribute('enctype')).toLowerCase() == 'multipart/form-data'; params = { extTID: transaction.id, extAction: action, extMethod: method.getName(), extType: 'rpc', extUpload: String(isUpload) }; // change made from typeof callback check to callback.params // to support addl param passing in DirectSubmit EAC 6/2 Ext.apply(transaction, { form: Ext.getDom(form), isUpload: isUpload, params: callback && Ext.isObject(callback.params) ? Ext.apply(params, callback.params) : params }); me.fireEvent('call', me, transaction, method); me.sendFormRequest(transaction); } }
javascript
{ "resource": "" }
q64982
test
function(transaction) { var me = this; Ext.Ajax.request({ url: me.getUrl(), params: transaction.params, callback: me.onData, scope: me, form: transaction.form, isUpload: transaction.isUpload, transaction: transaction }); }
javascript
{ "resource": "" }
q64983
inlineBlockFix
test
function inlineBlockFix(decl){ var origRule = decl.parent; origRule.append( { prop:'*display', value:'inline' }, { prop:'*zoom', value:'1' } ); }
javascript
{ "resource": "" }
q64984
stubPlainTextFiles
test
function stubPlainTextFiles(resourceRoots, destination) { _.forEach(resourceRoots, function (resource) { // Replace the webstorm file:// scheme with an absolute file path var filePath = resource.replace('file://$PROJECT_DIR$', destination); filePath = filePath.replace('.idea/', ''); // Extract the location from the file path to recursively create it if it doesn't exist. var location = filePath.replace(/[^\/]*$/, ''); if (!fs.existsSync(location)) mkdir('-p', location); if (!fs.existsSync(filePath)) fs.writeFileSync(filePath, ' ', 'utf8'); }); }
javascript
{ "resource": "" }
q64985
resolveJetbrainsExe
test
function resolveJetbrainsExe(jetbrainsDirectory) { var exists = false; var webstormInstallPaths = io.resolveDirMatches(jetbrainsDirectory, /^WebStorm\s*[.\d]+$/); // Check that the Webstorm folder have a bin folder, empty folders are a known issue. for (var j = 0; j < webstormInstallPaths.length; j++) { var webstormPath = [jetbrainsDirectory, webstormInstallPaths[j], 'bin']; var resolvedWebstorm = resolveMaxedPath(webstormPath); if(resolvedWebstorm === null) break; exists = path.resolve(resolvedWebstorm.join(path.sep), 'Webstorm.exe'); if(fs.existsSync(exists)) { return exists; } } return exists; }
javascript
{ "resource": "" }
q64986
Route
test
function Route (method, path, callback, options) { this.path = path; this.method = method; this.callback = callback; this.regexp = utils.pathRegexp(path, this.keys = [], options.sensitive, options.strict); }
javascript
{ "resource": "" }
q64987
TransportDecorator
test
function TransportDecorator (Transport) { function TelemetryTransport (contact, options) { if (!(this instanceof TelemetryTransport)) { return new TelemetryTransport(contact, options) } assert.ok(options, 'Missing required options parameter') this._telopts = options.telemetry this.telemetry = new Persistence(this._telopts.storage) Transport.call(this, contact, options) } inherits(TelemetryTransport, Transport) TelemetryTransport.DEFAULT_METRICS = [ metrics.Latency, metrics.Availability, metrics.Reliability, metrics.Throughput ] /** * Wraps _open with telemetry hooks setup * #_open * @param {Function} callback */ TelemetryTransport.prototype._open = function (callback) { var self = this var metrics = this._telopts.metrics if (!metrics || metrics.length === 0) { this._telopts.metrics = TelemetryTransport.DEFAULT_METRICS } this._telopts.metrics.forEach(function (Metric) { var metric = new Metric() metric.hooks.forEach(function (hook) { self[hook.trigger]( hook.event, hook.handler(metric, self.telemetry) ) }) }) return Transport.prototype._open.call(this, callback) } return TelemetryTransport }
javascript
{ "resource": "" }
q64988
getRandomArrValue
test
function getRandomArrValue(arr, min = 0, max = arr.length - 1) { return arr[getRandomInt(min, max)]; }
javascript
{ "resource": "" }
q64989
random
test
function random(number = 1) { if (1 > number) { throw Error(`Can't use numbers bellow 1, ${number} passed`); } if (number === 1) { return getRandomArrValue(dinosaurs); } else { const l = dinosaurs.length - 1; return new Array(number).fill().map(() => getRandomArrValue(dinosaurs, 0, l)); } }
javascript
{ "resource": "" }
q64990
Response
test
function Response (ghosttrain, callback) { this.charset = ''; this.headers = {}; this.statusCode = 200; this.app = ghosttrain; this._callback = callback; }
javascript
{ "resource": "" }
q64991
test
function () { var body; var app = this.app; // If status provide, set that, and set `body` to the content correctly if (typeof arguments[0] === 'number') { this.status(arguments[0]); body = arguments[1]; } else { body = arguments[0]; } var type = this.get('Content-Type'); if (!body && type !== 'application/json') { body = utils.STATUS_CODES[this.statusCode]; if (!type) this.type('txt'); } else if (typeof body === 'string') { if (!type) { this.charset = this.charset || 'utf-8'; this.type('html'); } } else if (typeof body === 'object') { if (body === null) body = ''; else if (!type || type === 'application/json') { this.contentType('application/json'); // Cast object to string to normalize response var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); body = JSON.stringify(body, replacer, spaces); } } this.end(body); return this; }
javascript
{ "resource": "" }
q64992
test
function () { var data; if (arguments.length === 2) { this.status(arguments[0]); data = arguments[1]; } else { data = arguments[0]; } if (!this.get('Content-Type')) this.contentType('application/json'); return this.send(data); }
javascript
{ "resource": "" }
q64993
test
function (field, value) { if (arguments.length === 2) this.headers[field] = value; else { for (var prop in field) this.headers[prop] = field[prop]; } return this; }
javascript
{ "resource": "" }
q64994
test
function (body) { var type = this.get('Content-Type'); if (type === 'application/json') this._callback(JSON.parse(body || '{}')); else this._callback(body); }
javascript
{ "resource": "" }
q64995
test
function (args) { // Find the minimum expected length. var expected = Array.prototype.slice.call(arguments, 1); var minimum = expected.length var hasOptionalTypes = false; for (var i = 0; i < expected.length; i++) { if (!isValidType(expected[i])) { throw Error('Expected argument ' + i + ' is not a valid type.'); } if (isOptionalType(expected[i])) { minimum--; hasOptionalTypes = true; } }; // Exit early if in production, INSIST_IN_PROD is not equal to true and there are no optional // options. if (isDisabled && !hasOptionalTypes) { return []; } // Check if the args and expected lengths are different (and there are no optional args). if (minimum == expected.length && args.length != expected.length) { throw Error(getExpectedVsRecieved_(expected, args)); } // Check if the args are within the expected range. if (args.length < minimum || args.length > expected.length) { throw Error(getExpectedVsRecieved_(expected, args)); } // We don't have to worry about shifting if all the arguments are present. if (args.length === expected.length) { for (var i = 0; i < expected.length; i++) { if (!isOfType(args[i], expected[i])) { throw Error(getExpectedVsRecieved_(expected, args)); } }; return args; } return shiftArguments_(expected, args, minimum); }
javascript
{ "resource": "" }
q64996
test
function (expected, args, minimum) { var shiftedArgs = []; var curArg = args.length - 1; var remainingOptionalArgs = expected.length - minimum; var optionalIndiceSegments = []; var optionalIndiceSegment = []; var availableArgsSegments = []; var availableArgsSegment = []; // Fill the return array with nulls first. for (var i = 0; i < expected.length; i++) shiftedArgs[i] = null; // Capture groups of available arguments separated by ones that have been used. var advanceArg = function () { availableArgsSegment.unshift(curArg); curArg--; remainingOptionalArgs--; if (curArg < 0 || remainingOptionalArgs < 0) { throw Error(getExpectedVsRecieved_(expected, args)); } }; // Fill in all of the required types, starting from the last expected argument and working // towards the first. for (i = expected.length - 1; i >= 0; i--) { var type = expected[i]; if (isOptionalType(type)) { optionalIndiceSegment.unshift(i); continue; } // Keep moving down the line of arguments until one matches. while (!isOfType(args[curArg], type)) { advanceArg(); } // Check if this argument should be left for a trailing optional argument. if (checkIfShouldLeaveArgument_(expected, i, args, curArg)) { // Found enough matches to let this be an optional argument. Advance the argument and // then restart on this same function. advanceArg(); i++; continue; } // Capture groups of optional arguments separated by required arguments. optionalIndiceSegments.unshift(optionalIndiceSegment); optionalIndiceSegment = []; availableArgsSegments.unshift(availableArgsSegment); availableArgsSegment = [] shiftedArgs[i] = args[curArg--]; } // Now that we have found all the required arguments, group the rest for processing with optional // arguments. while (curArg >= 0) availableArgsSegment.unshift(curArg--); availableArgsSegments.unshift(availableArgsSegment); optionalIndiceSegments.unshift(optionalIndiceSegment); // Make sure that the optional argument count matches up correctly. if (availableArgsSegments.length != optionalIndiceSegments.length) { throw Error(getExpectedVsRecieved_(expected, args)); } // Go through all the optional segments and argument segments to match up the optional arguments. optionalIndiceSegments.forEach(function (optionalIndices, index) { availableArgsSegment = availableArgsSegments[index]; i = 0; availableArgsSegment.forEach(function (argIndex) { arg = args[argIndex] // Skip forward until we find an optional expected argument that matches. while (!isOfType(arg, expected[optionalIndices[i]]) && i < optionalIndices.length) { i++; } // If none match then the arguments are invalid. if (i >= optionalIndices.length) { throw Error(getExpectedVsRecieved_(expected, args)); } // Success! This is an optional expected argument. shiftedArgs[optionalIndices[i++]] = arg; }); }); return shiftedArgs; }
javascript
{ "resource": "" }
q64997
test
function () { availableArgsSegment.unshift(curArg); curArg--; remainingOptionalArgs--; if (curArg < 0 || remainingOptionalArgs < 0) { throw Error(getExpectedVsRecieved_(expected, args)); } }
javascript
{ "resource": "" }
q64998
test
function (expected, expectedIndex, actual, actualIndex) { // Check how many optional types in front of this argument that match the current value. var consecutiveOptionals = countTrailingOptionals_(expected, expectedIndex, actual[actualIndex]); // Check how many required types are behind this argument that match the current value. We // will then use this value to determine if the current argument can be allowed to fill an // optional spot instead of a required one. var matchingRequires = countLeadingMatchingRequires_(expected, expectedIndex, actual[actualIndex]); // Now that we have found the consecutive matching types, more forward through the arguments // to see if there are enough to fill the option types. var matchesRequired = 1 + matchingRequires; var availableDistance = matchingRequires + consecutiveOptionals; // Determine if there are enough optional arguments. var i = actualIndex - 1; var type = expected[expectedIndex]; while (i >= 0 && availableDistance > 0 && matchesRequired > 0) { if (isOfType(actual[i], type)) { matchesRequired--; } availableDistance--; i--; } return matchesRequired <= 0; }
javascript
{ "resource": "" }
q64999
test
function (expected, expectedIndex, value) { var i = expectedIndex + 1; var matchingOptionals = 0; var inBetweenOptionals = 0; var tmpInBetween = 0; while (i < expected.length && isOptionalType(expected[i])) { if (isOfType(value, expected[i])) { matchingOptionals++; inBetweenOptionals += tmpInBetween; tmpInBetween = 0; } else { tmpInBetween++; } i++; } return matchingOptionals + inBetweenOptionals; }
javascript
{ "resource": "" }