_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q10200
where
train
function where() { var wheres = this.grouped.where; if (!wheres) { return undefined; } var i = -1, sql = []; while (++i < wheres.length) { var stmt = wheres[i]; var val = this[stmt.type](stmt); if (val) { if (sql.length === 0) { sql[0] = 'where'; } else { sql.push(stmt.bool); } sql.push(val); } } return sql.length > 1 ? sql.join(' ') : ''; }
javascript
{ "resource": "" }
q10201
having
train
function having() { var havings = this.grouped.having; if (!havings) { return ''; } var sql = ['having']; for (var i = 0, l = havings.length; i < l; i++) { var str = '', s = havings[i]; if (i !== 0) { str = s.bool + ' '; } if (s.type === 'havingBasic') { sql.push(str + this.formatter.columnize(s.column) + ' ' + this.formatter.operator(s.operator) + ' ' + this.formatter.parameter(s.value)); } else { if (s.type === 'whereWrapped') { var val = this.whereWrapped(s); if (val) { sql.push(val); } } else { sql.push(str + this.formatter.unwrapRaw(s.value)); } } } return sql.length > 1 ? sql.join(' ') : ''; }
javascript
{ "resource": "" }
q10202
_union
train
function _union() { var onlyUnions = this.onlyUnions(); var unions = this.grouped.union; if (!unions) { return ''; } var sql = ''; for (var i = 0, l = unions.length; i < l; i++) { var union = unions[i]; if (i > 0) { sql += ' '; } if (i > 0 || !onlyUnions) { sql += union.clause + ' '; } var statement = this.formatter.rawOrFn(union.value); if (statement) { if (union.wrap) { sql += '('; } sql += statement; if (union.wrap) { sql += ')'; } } } return sql; }
javascript
{ "resource": "" }
q10203
del
train
function del() { // Make sure tableName is processed by the formatter first. var tableName = this.tableName; var wheres = this.where(); var sql = 'delete from ' + tableName + (wheres ? ' ' + wheres : ''); var returning = this.single.returning; return { sql: sql + this._returning(returning), returning: returning }; }
javascript
{ "resource": "" }
q10204
_counter
train
function _counter() { var counter = this.single.counter; var toUpdate = {}; toUpdate[counter.column] = this.client.raw(this.formatter.wrap(counter.column) + ' ' + (counter.symbol || '+') + ' ' + counter.amount); this.single.update = toUpdate; return this.update(); }
javascript
{ "resource": "" }
q10205
whereBasic
train
function whereBasic(statement) { return this._not(statement, '') + this.formatter.wrap(statement.column) + ' ' + this.formatter.operator(statement.operator) + ' ' + this.formatter.parameter(statement.value); }
javascript
{ "resource": "" }
q10206
_prepUpdate
train
function _prepUpdate(data) { var vals = []; var sorted = Object.keys(data).sort(); var i = -1; while (++i < sorted.length) { vals.push(this.formatter.wrap(sorted[i]) + ' = ' + this.formatter.parameter(data[sorted[i]])); } return vals; }
javascript
{ "resource": "" }
q10207
_groupsOrders
train
function _groupsOrders(type) { var items = this.grouped[type]; if (!items) { return ''; } var formatter = this.formatter; var sql = items.map(function (item) { return (item.value instanceof Raw ? formatter.unwrapRaw(item.value) : formatter.columnize(item.value)) + (type === 'order' && item.type !== 'orderByRaw' ? ' ' + formatter.direction(item.direction) : ''); }); return sql.length ? type + ' by ' + sql.join(', ') : ''; }
javascript
{ "resource": "" }
q10208
columnInfo
train
function columnInfo() { var column = this.single.columnInfo; return { sql: 'select * from information_schema.columns where table_name = ? and table_catalog = ?', bindings: [this.single.table, this.client.database()], output: function output(resp) { var out = resp.rows.reduce(function (columns, val) { columns[val.column_name] = { type: val.data_type, maxLength: val.character_maximum_length, nullable: val.is_nullable === 'YES', defaultValue: val.column_default }; return columns; }, {}); return column && out[column] || out; } }; }
javascript
{ "resource": "" }
q10209
fixRoute
train
function fixRoute(route) { //protect special chars while we replace return route.replace(/\s*OR\s*/g,'__OR__'). replace(/\s*->\s*/g,'__->__'). replace(/[\s\t\n]+/g,'/'). replace(/__/g,' '); }
javascript
{ "resource": "" }
q10210
train
function(callback, timeout){ var id = index++; if(timeout > MAX_INT){ timeouts[id] = setTimeout(set.bind(undefined, callback, timeout - MAX_INT), MAX_INT); }else{ if(timeout < 0) timeout = 0; timeouts[id] = setTimeout(function(){ delete timeouts[id]; callback(); }, timeout); } return id; }
javascript
{ "resource": "" }
q10211
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof SourceDescription)){ return new SourceDescription(json); } // If the given object is already an instance then just return it. DON'T copy it. if(SourceDescription.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10212
from
train
function from(renderFn, name = renderFn.name) { if (typeof name === 'function') { [renderFn, name] = [name, renderFn]; } else if (typeof renderFn !== 'function') { throw InvalidArgType({ renderFn }, 'a function'); } name = String(name); if (!name) { throw InvalidArgValue({ name }, 'should not be empty'); } function RenderFunction(...args) { if (!new.target) return new RenderFunction(...args); // 1st argument may be constructor itself to (redundantly) capture identity. if (args[0] === RenderFunction) args.shift(); // Delegate processing of properties to Node. apply(Node, this, args); } // The isViewComponent, toStringTag, and provideContext properties are the // same for all render function components and could thus be moved into a // shared prototype. While that may reduce memory pressure, it also increases // the length of the prototype chain and thus property lookup latency. const RenderFunctionPrototype = create(NodePrototype, { constructor: { configurable, value: RenderFunction }, isViewComponent: { configurable, value: true }, // Flag to detect view component type. [toStringTag]: { configurable, value: 'Proact.Component' }, name: { configurable, enumerable, value: name }, render: { configurable, value: renderFn }, provideContext: { configurable, value: provideContext }, }); defineProperties(RenderFunction, { prototype: { value: RenderFunctionPrototype }, name: { configurable, enumerable, value: name }, }); return RenderFunction; }
javascript
{ "resource": "" }
q10213
ApiDox
train
function ApiDox() { this.settings = { input: '', inputText: null, inputTitle: '', output: '', fullSourceDescription: false }; this.anchors = {}; this.comments = []; this.curSection = null; this.fileComment = {}; this.lines = []; this.params = {}; this.returns = {}; this.sees = []; this.toc = []; this.throws = []; }
javascript
{ "resource": "" }
q10214
forceEnd
train
function forceEnd(path, response) { // Send a custom response for gateway timeout new $CustomResponse().head(504, null, { 'Content-Type': 'text/html' }).writeSync(`<h1>${RESPONSE_HEADER_MESSAGES[ 504 ]}</h1>`); // Log something $LogProvider.error(path, response._header); // End the response end(response); }
javascript
{ "resource": "" }
q10215
train
function(opts){ //defaults opts = opts || {}; this.username = opts.username || ''; this.password = opts.password || ''; // oAuth Token this.accessToken = opts.accessToken || ''; // API Rate Limit Details this.rateLimit = 5000; this.rateLimitRemaining = this.rateLimit; //rateLimitRemaining starts as rateLimit }
javascript
{ "resource": "" }
q10216
train
function( type, handler ) { if( handler === void 0 || handler === null ) throw new Error( 'Missing argument "handler"' ) if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' ) throw new TypeError( 'Handler must be a function.' ) this._events[ type ] ? this._events[ type ].push( handler ) : this._events[ type ] = [ handler ] if( Emitter.warn && this._events[ type ].length > this._maxListeners ) { if( this._maxListeners > 0 && !this._memLeakDetected ) { this._memLeakDetected = true console.warn( 'WARNING: Possible event emitter memory leak detected.', this._events[ type ].length, 'event handlers added.', 'Use emitter.setMaxListeners() to increase the threshold.' ) console.trace() } } return this }
javascript
{ "resource": "" }
q10217
train
function( type, handler ) { if( handler === void 0 || handler === null ) throw new Error( 'Missing argument "handler"' ) if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' ) throw new TypeError( 'Handler must be a function.' ) function wrapper() { this.removeListener( type, wrapper ) typeof handler !== 'function' ? handler.handleEvent.apply( handler, arguments ) : handler.apply( this, arguments ) } this._events[ type ] ? this._events[ type ].push( wrapper ) : this._events[ type ] = [ wrapper ] return this }
javascript
{ "resource": "" }
q10218
train
function( type ) { var emitter = this var listeners = this._events[ type ] if( type === 'error' && !listeners ) { if( !this._events.error ) { throw !( arguments[1] instanceof Error ) ? new Error( 'Unhandled "error" event.' ) : arguments[1] } } else if( !listeners ) { return false } var argv = [].slice.call( arguments, 1 ) var i, len = listeners.length function fire( handler, argv ) { typeof handler !== 'function' ? handler.handleEvent.apply( handler, argv ) : handler.apply( this, argv ) } for( i = 0; i < len; i++ ) { Emitter.nextTick( fire.bind( this, listeners[i], argv ) ) } return true }
javascript
{ "resource": "" }
q10219
train
function( type, handler ) { var handlers = this._events[ type ] var position = handlers.indexOf( handler ) if( handlers && ~position ) { if( handlers.length === 1 ) { this._events[ type ] = undefined delete this._events[ type ] } else { handlers.splice( position, 1 ) } } return this }
javascript
{ "resource": "" }
q10220
train
function( type ) { if( arguments.length === 0 ) { for( type in this._events ) { this.removeAllListeners( type ) } } else { this._events[ type ] = undefined delete this._events[ type ] } return this }
javascript
{ "resource": "" }
q10221
getOptions
train
function getOptions(options) { var opts = { include: [ { chars: [[0x0000, 0xFFFF]], min: 0 } ], exclude: [] }; // Merge the properties of our options for (var property in options) { // Ignore options that are not in our opts set or are not an array if (!opts.hasOwnProperty(property) || !Array.isArray(options[property])) { continue; } // Reset the default value for this property since it's being overridden if (property === 'include') { opts.include = []; } // Merge the options given for (var set in options[property]) { if (typeof options[property][set] === 'object' && options[property][set].hasOwnProperty('chars') && Array.isArray(options[property][set].chars) ) { // Add the character set to the options var charSet = { chars: options[property][set].chars, min: 0 }; // Set the minimum value if given if (options[property][set].hasOwnProperty('min') && isInt(options[property][set].min) && options[property][set].min > 0 ) { charSet.min = options[property][set].min; } opts[property].push(charSet); } } } return opts; }
javascript
{ "resource": "" }
q10222
generateString
train
function generateString(set, length) { var content = ''; // Cannot generate a string from an empty set if (set.length <= 0) { return content; } for (var i = 0; i < length; i++) { content += String.fromCharCode( set[Math.floor(Math.random() * set.length)] ); } return content; }
javascript
{ "resource": "" }
q10223
getCharacterList
train
function getCharacterList(options) { var regen = regenerate(); var include = options.include; for (var i in include) { for (var j in include[i].chars) { // There should always be a 0th-index element if (include[i].chars[j][0] === undefined) { continue; } regen = addCharacters(regen, include[i].chars[j]); } } removeCharacters(regen, options.exclude); return regen.valueOf(); }
javascript
{ "resource": "" }
q10224
getCharacterSets
train
function getCharacterSets(options) { var regen; var include = options.include; var sets = []; for (var i in include) { regen = regenerate(); for (var j in include[i].chars) { // There should always be a 0th-index element if (include[i].chars[j][0] === undefined) { continue; } // Add the characters from the set regen = addCharacters(regen, include[i].chars[j]); } // Remove the characters from the exclusion set regen = removeCharacters(regen, options.exclude); sets.push( { set: regen.valueOf(), min: include[i].min } ); } return sets; }
javascript
{ "resource": "" }
q10225
train
function() { var objectDescriptor = arguments[arguments.length - 1]; var klass = objectDescriptor.constructor !== Object? objectDescriptor.constructor: function Class(toCast) { if (!(this instanceof klass)) { return klass.asInstance(toCast); } if (this.initialize) arguments.length ? this.initialize.apply(this, arguments) : this.initialize(); }; var proto = Object.createPrototypeChain(klass, this, Array.prototype.slice.call(arguments, 0, arguments.length - 1)); var names = Object.getOwnPropertyNames(objectDescriptor); for ( var i = 0; i < names.length; ++i) { var name = names[i]; var result = false; if (Object.properties.hasOwnProperty(name)) { result = Object.properties[name](proto, objectDescriptor, name); } if (!result) { var d = Object.getOwnPropertyDescriptor(objectDescriptor, name); if (d.value) { var val = d.value; if (val instanceof Function) { if (/this\.superCall/.test(val.toString())) { d.value = Object.createSuperCallWrapper(klass, name, val); } } else if (val && (val.hasOwnProperty('get') || val.hasOwnProperty('value'))) { d = val; } } Object.defineProperty(proto, name, d); } } if (klass.initialize) { klass.initialize(); } return klass; }
javascript
{ "resource": "" }
q10226
train
function(obj) { if (obj === null || obj === void 0) return false; return Object(obj) instanceof this || classOf(obj).linearizedTypes.lastIndexOf(this) != -1; }
javascript
{ "resource": "" }
q10227
train
function(object) { if (object === null || object === void 0) return object; return Object.getPrototypeOf(Object(object)).constructor; }
javascript
{ "resource": "" }
q10228
train
function(obj) { if (!obj.constructor.Bind) { try { var descr = {}; Bind.each(obj, function(name, method) { descr[name] = { get : function() { return this[name] = method.bind(this.self); }, set : function(val) { Object.defineProperty(this, name, { value : val }); }, configurable : true }; }); obj.constructor.Bind = Bind.Object.inherit(descr); } catch (e) { obj.constructor.Bind = Bind.Object.inherit({}); } } return new obj.constructor.Bind(obj); }
javascript
{ "resource": "" }
q10229
train
function(svg, options) { var widthCfg; // the svg element to render charts to this._svg = svg.classed('facet-layout',true); this._attributes = options || {}; this._animDuration = commonOptionDefaults.duration; // outer margins this._margin = { top: 0, bottom: 50, left: this._attributes.yScales.primary.displayOnAxis === 'left' ? 75 : 25, right: this._attributes.yScales.primary.displayOnAxis === 'left' ? 25 : 75 }; // collection of facet panels created this._facetPanels = []; this._chartCount = 0; // the number of facetd charts to be displayed this._colCount = 0; // number of columns this._rowCount = 1; // number of rows this._colWidth = 0; // width of column this._chartHeight = 0; // the height of the chart // facet.width configuration needs to be interpreted // could be column width (FIXED) OR number of columns (FLEXING) widthCfg = this._interpretWidthConfig(options.facet.width); this._layoutMode = widthCfg.mode; if (widthCfg.mode === 'fixed') { this._colWidth = widthCfg.value; } else if (widthCfg.mode === 'flex') { this._colCount = widthCfg.value; } this._facetTitleHeight = (options.facet.fields.length * FACET_LABEL_HEIGHT) + FACET_LABEL_PADDING; // the total height of vertically stacked facet field labels this._facetHeight = this._getFacetHeight(); // the height of the facet (incl titles and chart) }
javascript
{ "resource": "" }
q10230
applyGroupedDelta
train
function applyGroupedDelta(groupedDelta, callback) { var createdCandidates = []; logger.debug('Applying grouped delta', {category: 'sync-delta'}); async.eachSeries(groupedDelta, (node, cb) => { if(node.actions.create && utility.isExcludeFile(utility.getNameFromPath(node.actions.create.path))) { //do not process files which match exclude pattern. return cb(null); } syncDb.findByRemoteId(node.id, (err, oldLocalNode) => { if(err) return cbDeltaActions(err); if(node.actions.create && node.actions.delete) delete node.actions.delete; if(!oldLocalNode) { //node localy not found by remote id -> process later to avoid conflicts //nodes which don't have a create action can be ignored (deleted nodes not present localy) if(node.actions.create) createdCandidates.push(node); cb(null); } else { applyDeltaActions(node, oldLocalNode, (err, syncedNode) => { resolveConflicts(err, syncedNode, cb); }); } }); }, (err, results) => { if(err) return callback(err); async.eachSeries(createdCandidates, (node, cb) => { applyDeltaActions(node, undefined, (err, syncedNode) => { resolveConflicts(err, syncedNode, cb); }); }, callback); }); }
javascript
{ "resource": "" }
q10231
updateNode
train
function updateNode(node, callback) { syncDb.update(node._id, node, (err, result) => { if(err) return callback(err); callback(null, node); }); }
javascript
{ "resource": "" }
q10232
resolveConflicts
train
function resolveConflicts(err, syncedNode, callback) { if(err) return callback(err); if(!syncedNode) return callback(null); async.series([ (cb) => { if(syncedNode.directory === true) { resolveDirectoryConflicts(syncedNode, cb); } else { resolveFileConflicts(syncedNode, cb); } }, (cb) => { findLocalConflict(syncedNode, cb); } ], (err, res) => { if(err) return callback(err); callback(null); }); }
javascript
{ "resource": "" }
q10233
resolveDirectoryConflicts
train
function resolveDirectoryConflicts(node, callback) { var rActions = node.remoteActions; var lActions = node.localActions; if(rActions && lActions) { if(rActions.create && lActions.create) { //on both sides created, we just need to add remoteId and remoteParent node.remoteId = rActions.create.remoteId; node.remoteParent = rActions.create.remoteParent; delete node.remoteActions; delete node.localActions; } //both sides renamed, remote wins if(rActions.rename && lActions.rename) delete lActions.rename; //both sides moved, remote wins if(rActions.move && lActions.move) delete lActions.move; //if remotely created and localy deleted node should be created localy if(rActions.create && lActions.delete) delete lActions.delete; //if localy created and remotely deleted node should be created remotely if(rActions.delete && lActions.create) delete rActions.delete; return syncDb.update(node._id, node, (err, updatedNode) => { return callback(null); }); } return callback(null); }
javascript
{ "resource": "" }
q10234
resolveFileConflicts
train
function resolveFileConflicts(node, callback) { var rActions = node.remoteActions; var lActions = node.localActions; if(!rActions || !lActions) { //only one side changed, no conflicts return callback(null); } if(rActions.create && lActions.create) { //on both sides created or updated var currentLocalPath = utility.joinPath(node.parent, node.name); var localHash, stat; try { localHash = fsWrap.md5FileSync(currentLocalPath); stat = fsWrap.lstatSync(currentLocalPath); } catch(e) { logger.warning('resolveFileConflicts failed', {category: 'sync-delta', node, err: e}); var err = new BlnDeltaError(e.message); throw err; } if(rActions.create.hash && rActions.create.hash === localHash && rActions.create.size === stat.size) { delete node.remoteActions; delete node.localActions; node.hash = localHash; node.version = rActions.create.version; node.size = stat.size; node.mtime = stat.mtime; node.ctime = stat.ctime; node.remoteId = rActions.create.remoteId; node.remoteParent = rActions.create.remoteParent; return syncDb.update(node._id, node, callback); } else if(!rActions.delete) { //if remote path changed upload local version as new version on old path var remoteNode; return async.series([ (cb) => { //create remote localy var name = rActions.rename ? rActions.rename.remoteName : node.name; var parent = rActions.move ? rActions.move.parent : node.parent; var remoteParent = rActions.move ? rActions.move.remoteParent : rActions.create.remoteParent; var newNode = { name: name, parent: parent, directory: node.directory, remoteId: node.remoteId, remoteParent: remoteParent, remoteActions: {create: rActions.create} } syncDb.create(newNode, (err, createdNode) => { remoteNode = createdNode; cb(err); }); }, (cb) => { delete node.remoteActions; delete node.remoteParent; delete node.remoteId; delete node.hash; delete node.version; syncDb.update(node._id, node, cb); }, (cb) => { //as a new node has been created conflict resolution has to be executed for the new node resolveConflicts(null, remoteNode, cb); } ], callback); } } if(rActions.delete && lActions.delete) { //on both sides deleted, just remove it from db return syncDb.delete(node._id, (err) => { return callback(null); }); } return callback(null); }
javascript
{ "resource": "" }
q10235
renameConflictNode
train
function renameConflictNode(newParent, oldPath, name, node, conflictingNode, callback) { var newLocalName = utility.renameConflictNode(newParent, name); try { fsWrap.renameSync(oldPath, utility.joinPath(newParent, newLocalName)); } catch(err) { return renameRemoteNode(node, name, callback); } conflictingNode.name = newLocalName; conflictingNode.localActions = conflictingNode.localActions || {}; if(!conflictingNode.localActions.create && !conflictingNode.localActions.rename) { //rename the node if not localy created or localy renamed (always keep original local rename actions) conflictingNode.localActions.rename = {immediate: false, actionInitialized: new Date(), oldName: name}; } return syncDb.update(conflictingNode._id, conflictingNode, callback); }
javascript
{ "resource": "" }
q10236
renameRemoteNode
train
function renameRemoteNode(node, name, callback) { var rActions = node.remoteActions || {}; var newLocalName = utility.renameConflictNodeRemote(name); var oldLocalName = node.name; var newLocalPath = utility.joinPath(node.parent, newLocalName); var oldLocalPath = utility.joinPath(node.parent, oldLocalName); if(!rActions.create && fsWrap.existsSync(oldLocalPath)) { try { fsWrap.renameSync(oldLocalPath, newLocalPath); } catch(err) { logger.warning('rename local node failed', {category: 'sync-delta', oldLocalPath, newLocalPath, err}) throw new BlnDeltaError(err.message); return; } } node.name = newLocalName; node.localActions = node.localActions || {}; var remoteId = node.remoteId || node.remoteActions.create.remoteId; return blnApi.renameNode({remoteId, name: node.name}, (err) => { if(err) { logger.warning('rename remote node failed', {category: 'sync-delta', params: {remoteId, name: node.name}, err}); throw new BlnDeltaError(err.message); return; } if(rActions.rename) { delete node.remoteActions.rename; } syncDb.update(node._id, node, callback); }); }
javascript
{ "resource": "" }
q10237
train
function(dirPath, lastCursor, callback) { async.parallel([ (cb) => { localDelta.getDelta(dirPath, cb); }, (cb) => { remoteDelta.getDelta(lastCursor, cb); } ], (err, results) => { logger.info('getDelta ended', {category: 'sync-delta'}); if(err) return callback(err); var currentRemoteCursor = results[1]; applyGroupedDelta(remoteDelta.getGroupedDelta(), (err) => { if(err) return callback(err); callback(null, currentRemoteCursor); }); }); }
javascript
{ "resource": "" }
q10238
train
function (auth, org, repo, ref, options, callback) { if (typeof options == 'function') { callback = options options = {} } // a valid ref but we're not using this format ref = ref.replace(/^refs\//, '') var url = refsBaseUrl(org, repo, type) + '/' + ref ghutils.ghget(auth, url, options, callback) }
javascript
{ "resource": "" }
q10239
getOldManifest
train
async function getOldManifest () { try { var data = await getFile('.manifest.json.gz') } catch (err) { if (err.code === 'NoSuchKey') return {} else throw err } var unzippedBody = zlib.gunzipSync(data.Body) return JSON.parse(unzippedBody) }
javascript
{ "resource": "" }
q10240
upload
train
function upload (uploadables) { var promises = uploadables.map((uploadable) => putUploadable(uploadable)) return Promise.all(promises) }
javascript
{ "resource": "" }
q10241
toCassandraValues
train
function toCassandraValues(metadata, values) { if (values === null || values === undefined) { return null; } var specs = metadata.columnSpecs; var list = []; for (var i = 0; i < specs.length; i++) { var value = values[i]; if (value === null || value === undefined) { list.push(null); } else { var spec = specs[i]; var type = types.fromType(spec.type); list.push(type.serialize(value)); } } return list; }
javascript
{ "resource": "" }
q10242
singleline
train
function singleline(multiLineString, noSpaces) { const delimiter = noSpaces ? '' : ' '; return multiLineString.replace(/\s\s+/g, delimiter).trim(); }
javascript
{ "resource": "" }
q10243
closestButNotGreaterThan
train
function closestButNotGreaterThan(numbers, maxNumber) { var positiveNumbers = numbers.map(function(number){ return Math.abs(number); }); var positiveMaxNumber = Math.abs(maxNumber); var winner = positiveMaxNumber; var winningDifference = positiveMaxNumber; for (var i=0; i < positiveNumbers.length; i++) { var lessThanMax = positiveNumbers[i] <= positiveMaxNumber; var closerToMax = (positiveMaxNumber - positiveNumbers[i]) < winningDifference; if (lessThanMax && closerToMax) { winner = positiveNumbers[i]; winningDifference = positiveMaxNumber-positiveNumbers[i]; } } return winner; }
javascript
{ "resource": "" }
q10244
closestToZero
train
function closestToZero(numbers, maxNumber) { //returns the index of value closest to 0 var positiveNumbers = numbers.map(function(number) { return Math.abs(number); }); var sortedPositiveNumbers = positiveNumbers.sort(function(a, b) { return (a - b); }); return sortedPositiveNumbers[0]; }
javascript
{ "resource": "" }
q10245
findArcHeight
train
function findArcHeight(distance, radius, maxArcHeight, greaterThan180) { var heightOptions = []; heightOptions.push(radius + Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2))); heightOptions.push(radius - Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2))); if(greaterThan180){ return closestButNotGreaterThan(heightOptions, maxArcHeight); } else{ return closestToZero(heightOptions, maxArcHeight); } }
javascript
{ "resource": "" }
q10246
negotiateLanguage
train
function negotiateLanguage( acceptable, supported, engineDefault ) { var candidates = []; var enumeration = acceptable || ''; if (enumeration) { // Create list of candidate locales. var re = /;q=[01]\.\d,?/g; var matches = enumeration.match( re ); if (matches) // Create weighted list of locales. for (var i = 0; i < matches.length; i++) { var q = matches[ i ]; var index = enumeration.indexOf( q ); var group = enumeration.substring( 0, index ); var members = group.split( ',' ); var value = +q.substr( 3, 3 ); members.forEach( function ( member ) { candidates.push( { locale: member, weight: value } ); } ); enumeration = enumeration.substring( index + q.length ); } else { // Create simple list of locales. var locales = enumeration.split( ',' ); locales.forEach( function ( member ) { candidates.push( { locale: member, weight: 1.0 } ); } ); } } // Sort locales by weight DESC, locale length DESC. candidates.sort( function ( a, b ) { if (a.weight < b.weight) return 1; if (a.weight > b.weight) return -1; if (a.locale.length < b.locale.length) return 1; if (a.locale.length > b.locale.length) return -1; return 0; } ); // Find candidates among supported locales. for (var c = 0; c < candidates.length; c++) { var item = candidates[ c ].locale; do { if (supported.indexOf( item ) > -1) return item; // Try without country/region code. item = item.substring( 0, item.lastIndexOf( '-' ) ); } while (item); } // No supported candidate: return engine's default locale. return engineDefault; }
javascript
{ "resource": "" }
q10247
CruxTaskEntry
train
function CruxTaskEntry(name) { this.autorun = true; // we can disable auto running. this.name = name; this.debug = false; this.type = 'serial'; // the type of this task. Can be: serial or parallel this.__queue = []; this.__actions = {}; this.__hasActions = false; this.__started = false; this.__scheduled = false; this.__wait = 0; this.__running = false; this.__handlers = {}; // currently, only "failed", "timeout" and "completed" this.__options = { delay: 10, // number of seconds to delay the run. timeout: 0, // number of seconds until we consider the task failed. timer: 0 // number of seconds between calls. Defaults to 0(cyclic disabled) }; this.__run_queue = []; // we place any run requests while running here. EventEmitter.call(this); }
javascript
{ "resource": "" }
q10248
xgminer
train
function xgminer(host, port, options) { this.host = host || this.defaults.host; this.port = port || this.defaults.port; this.options = this.defaults; if (options) { _.defaults(this.options, options); } }
javascript
{ "resource": "" }
q10249
encodeSpecialCharacters
train
function encodeSpecialCharacters (str) { return encodeURI(str).replace(/[!'()* ]/g, function (char) { return '%' + char.charCodeAt(0).toString(16) }) }
javascript
{ "resource": "" }
q10250
insertStaticSegments
train
function insertStaticSegments( components, segments, languages ) { for (var componentName in components) { if (components.hasOwnProperty( componentName )) { var language; var appliedTokens = [ ]; var component = components[ componentName ]; // Determine the language of the component. if (typeof languages === 'string') language = languages; else { var parts = componentName.split( '/', 2 ); language = languages.indexOf( parts[ 0 ] ) >= 0 ? parts[ 0 ] : ''; } // Insert static segments into a language specific component only. if (language) { // Get static segment tokens of the component. component.tokens.filter( function ( token ) { return token.isStatic; } ) .forEach( function ( token ) { // Get segment. var segment = segments.get( language, token.name ); // Insert the static segment into the component. var re = new RegExp( token.expression, 'g' ); component.html = component.html.replace( re, segment.html ); appliedTokens.push( token.name ); } ); // Remove applied segment tokens. component.tokens = component.tokens.filter( function ( token ) { return appliedTokens.indexOf( token.name ) < 0; } ); } } } }
javascript
{ "resource": "" }
q10251
Conversation
train
function Conversation (config) { if (!(this instanceof Conversation)) { throw new SyntaxError('Constructor must be called with the new operator'); } // public properties this.id = config && config.id || uuid.v4(); this.self = config && config.self || null; this.other = config && config.other || null; this.context = config && config.context || {}; // private properties this._send = config && config.send || null; this._inbox = []; // queue with received but not yet picked messages this._receivers = []; // queue with handlers waiting for a new message }
javascript
{ "resource": "" }
q10252
setDeveloperRoutes
train
function setDeveloperRoutes( app, filingCabinet, paths, develop ) { // Create document template for resources. var head = '\n' + ' <link rel="stylesheet" href="' + develop.cssBootstrap + '" />\n' + ' <link rel="stylesheet" href="' + develop.cssHighlight + '">\n'; var foot = '\n' + ' <script src="' + develop.jsJQuery + '"></script>\n' + ' <script src="' + develop.jsBootstrap + '"></script>\n' + ' <script src="' + develop.jsHighlight + '"></script>\n' + ' <script>hljs.initHighlightingOnLoad();</script>\n'; function wrap( title, body ) { return '<html>\n<head>' + head + '</head>\n<style>\n' + css + '\n</style>\n\n' + '<h1>' + title + '</h1>\n' + '<p><i>' + pkgInfo.name + ' v' + pkgInfo.version + '</i></p>\n' + body + foot + '\n</body>\n</html>\n'; } // Set up developer paths. PATH.init( paths.develop ); // Developer home page. app.get( PATH.root, function ( req, res ) { res.status( 200 ).send( wrap( 'Resources', '<ul>\n' + ' <li><a href="' + PATH.list.languages + '">Languages</a></li>\n' + ' <li><a href="' + PATH.list.documents + '">Documents</a></li>\n' + ' <li><a href="' + PATH.list.layouts + '">Layouts</a></li>\n' + ' <li><a href="' + PATH.list.segments + '">Segments</a></li>\n' + ' <li><a href="' + PATH.list.contents + '">Contents</a></li>\n' + ' <li><a href="' + PATH.list.menus + '">Menus</a></li>\n' + ' <li><a href="' + PATH.list.locales + '">Locales</a></li>\n' + ' <li><a href="' + PATH.list.references + '">References</a></li>\n' + ' <li><a href="' + PATH.list.controls + '">Controls</a></li>\n' + '</ul>\n' + '<p><a class="btn btn-success" href="/">Go to site</a></p>\n' ) ); } ); logger.routeAdded( PATH.root ); // Lists all languages. app.get( PATH.list.languages, function ( req, res ) { res.status( 200 ).send( wrap( 'Languages', filingCabinet.listLanguages() + backToRoot() ) ); } ); logger.routeAdded( PATH.list.languages ); // Lists all documents. app.get( PATH.list.documents, function ( req, res ) { res.status( 200 ).send( wrap( 'Documents', filingCabinet.documents.list( PATH.show.document ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.documents ); // Display a document. app.get( PATH.show.document + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Document: ' + show( key ), filingCabinet.documents.show( key ) + backTo( PATH.list.documents ) ) ); } ); logger.routeAdded( PATH.show.document ); // Lists all layouts. app.get( PATH.list.layouts, function ( req, res ) { res.status( 200 ).send( wrap( 'Layouts', filingCabinet.layouts.list( PATH.show.layout ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.layouts ); // Display a layout. app.get( PATH.show.layout + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Layout: ' + show( key ), filingCabinet.layouts.show( key ) + backTo( PATH.list.layouts ) ) ); } ); logger.routeAdded( PATH.show.layout ); // Lists all segments. app.get( PATH.list.segments, function ( req, res ) { res.status( 200 ).send( wrap( 'Segments', filingCabinet.segments.list( PATH.show.segment ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.segments ); // Display a segment. app.get( PATH.show.segment + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Segment: ' + show( key ), filingCabinet.segments.show( key ) + backTo( PATH.list.segments ) ) ); } ); logger.routeAdded( PATH.show.segment ); // Lists all contents. app.get( PATH.list.contents, function ( req, res ) { res.status( 200 ).send( wrap( 'Contents', filingCabinet.contents.list( PATH.show.content ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.contents ); // Display a content. app.get( PATH.show.content + '/:language/:key', function ( req, res ) { var language = req.params[ 'language' ]; var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Content: ' + show( key ), filingCabinet.contents.show( language, key ) + backTo( PATH.list.contents ) ) ); } ); logger.routeAdded( PATH.show.content ); // Lists all menus. app.get( PATH.list.menus, function ( req, res ) { res.status( 200 ).send( wrap( 'Menus', filingCabinet.menus.list( PATH.show.menu ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.menus ); // Display a menu. app.get( PATH.show.menu + '/:language/:key', function ( req, res ) { var language = req.params[ 'language' ]; var key = req.params[ 'key' ]; var result = filingCabinet.menus.show( language, +key ); res.status( 200 ).send( wrap( 'Menu: ' + show( result.title ), result.list + backTo( PATH.list.menus ) ) ); } ); logger.routeAdded( PATH.show.menu ); // Lists all locales. app.get( PATH.list.locales, function ( req, res ) { res.status( 200 ).send( wrap( 'Locales', filingCabinet.locales.list( filingCabinet.languages ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.locales ); // Lists all references. app.get( PATH.list.references, function ( req, res ) { res.status( 200 ).send( wrap( 'References', filingCabinet.references.list( PATH.show.reference ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.references ); // Display a reference. app.get( PATH.show.reference + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Reference: ' + show( key ), filingCabinet.references.show( key ) + backTo( PATH.list.references ) ) ); } ); logger.routeAdded( PATH.show.reference ); // Lists all controls. app.get( PATH.list.controls, function ( req, res ) { res.status( 200 ).send( wrap( 'Controls', filingCabinet.controls.list( PATH.show.control ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.controls ); // Display a control. app.get( PATH.show.control + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Control: ' + show( key ), filingCabinet.controls.show( key ) + backTo( PATH.list.controls ) ) ); } ); logger.routeAdded( PATH.show.control ); }
javascript
{ "resource": "" }
q10253
train
function(){ // the generator we will return var res=f(); // get the first result if(cond(res)&&failed){ // if we've failed twice, then we're done return; // return an undefined result }else if(cond(res)){ // otherwise, if we fail, try moving on f=function(){return next();} // now use the second list failed=true; // but remember that we failed once return fn(); // return the next element }else return res; // otherwise, we must have a good result, return it }
javascript
{ "resource": "" }
q10254
train
function(){ // the main generator you'll return var res=kid(); // call the child function and store the result if(cond(res)&&failed){ // if both generators have failed return done(); // then you're done }else if(cond(res)){ // if just the child has failed par(); // regenerate the child array return fn(); // return the next child value }else{ // otherwise.. return [temp,res]; // return combined parent and child values } }
javascript
{ "resource": "" }
q10255
removeHiddenColumns
train
function removeHiddenColumns(oldSorted, hiddenColumns){ var dirty = false; oldSorted.forEach(function(i) { var j = 0, colIndex; while (j < hiddenColumns.length) { colIndex = hiddenColumns[j].index + 1; //hack to get around 0 index if (colIndex === i) { hiddenColumns[j].unSort(); dirty = true; break; } j++; } }); return dirty; }
javascript
{ "resource": "" }
q10256
solve
train
function solve() { while (true) { // establish vars for current loop //---------------------------------------------------------- const row = this.state.i % this.state.rows const col = Math.floor(this.state.i / this.state.rows) const str = this.props.ar[this.state.i] const len = str.length const tooLong = len > this.props.maxRowLen // str is too long ? set rows to maximum //---------------------------------------------------------- if (tooLong && this.state.rows !== this.props.arLen) { this.bindState(this.props.arLen) continue } // at new col ? indent previous col //---------------------------------------------------------- if (row === 0 && this.state.i !== 0) { const prevCol = col - 1 const reqLen = this.state.widths[prevCol] + this.props.gap.len this.state.indices.forEach((ar, i) => { const prevLen = this.props.ar[ar[prevCol]].length const diff = reqLen - prevLen this.state.strs[i] += this.props.gap.ch.repeat(diff) }) } // add str to row //---------------------------------------------------------- this.state.strs[row] += str // row not too long ? update state : reset state with rows + 1 //---------------------------------------------------------- if ( this.state.strs[row].length <= this.props.maxRowLen || tooLong ) { if (len > this.state.widths[col]) this.state.widths[col] = len this.state.indices[row].push(this.state.i) this.state.i++ } else this.bindState(this.state.rows + 1) // solution reached ? exit loop //---------------------------------------------------------- if (this.state.i === this.props.arLen) break } }
javascript
{ "resource": "" }
q10257
isInvalidInboundAddress
train
function isInvalidInboundAddress(inboundAddress) { if (fuse.config.restrict_inbound === false) return false; return cleanAddress(inboundAddress) !== fuse.config.inbound_address; }
javascript
{ "resource": "" }
q10258
getEventType
train
function getEventType(inboundMessage) { let recipientAddresses = _.map(inboundMessage.recipients, 'email'); let ccAddresses = _.map(inboundMessage.cc, 'email'); if (_.max([recipientAddresses.indexOf(fuse.config.inbound_address), recipientAddresses.indexOf(inboundMessage.to.email)]) >= 0) { return 'direct_email'; } else if (_.max([ccAddresses.indexOf(fuse.config.inbound_address), ccAddresses.indexOf(inboundMessage.to.email)]) >= 0) { return 'cc_email'; } else { return 'bcc_email'; } }
javascript
{ "resource": "" }
q10259
addFromAddress
train
function addFromAddress(inboundMessage, outboundMessage) { if (inboundMessage && _.has(inboundMessage, 'from')) { outboundMessage.recipients = outboundMessage.recipients || []; outboundMessage.recipients.push(inboundMessage.from); } return outboundMessage; }
javascript
{ "resource": "" }
q10260
defaultConfiguration
train
function defaultConfiguration(config) { config = _.defaults({}, config, { name: 'Sparky', endpoint: '/relay', convos: [], sending_address: config.address, inbound_address: config.address, transport: 'sparkpost', restrict_inbound: true, logger: 'verbose', size_limit: '50mb' }); config.address = cleanAddress(config.address); config.sending_address = cleanAddress(config.sending_address); config.inbound_address = cleanAddress(config.inbound_address); config.logger = _.isString(config.logger) ? require('./logger')(config.logger) : config.logger; return config; }
javascript
{ "resource": "" }
q10261
Decision
train
function Decision (arg1, arg2) { var decision, choices; if (!(this instanceof Decision)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof arg1 === 'function') { decision = arg1; choices = arg2; } else { decision = null; choices = arg1; } if (decision) { if (typeof decision !== 'function') { throw new TypeError('Parameter decision must be a function'); } } else { decision = function (message, context) { return message; } } if (choices && (typeof choices === 'function')) { throw new TypeError('Parameter choices must be an object'); } this.decision = decision; this.choices = {}; // append all choices if (choices) { var me = this; Object.keys(choices).forEach(function (id) { me.addChoice(id, choices[id]); }); } }
javascript
{ "resource": "" }
q10262
train
function (projectName, files, params, callback) { if (callback === undefined) { callback = params; params = {}; } var filesInformation = {}; files.forEach(function (fileName) { var index = "files[" + fileName + "]"; filesInformation[index] = fs.createReadStream(fileName); }); return postApiCallWithFormData('project/' + projectName + '/add-file', extend(filesInformation, params), callback); }
javascript
{ "resource": "" }
q10263
train
function (projectName, fileNameOrStream, callback) { if (typeof fileNameOrStream === "string") { fileNameOrStream = fs.createReadStream(fileNameOrStream); } return postApiCallWithFormData('project/' + projectName + '/upload-glossary', { file: fileNameOrStream }, callback); }
javascript
{ "resource": "" }
q10264
handleError
train
function handleError(reject) { return (e) => { // prevent global error throw https://bugzilla.mozilla.org/show_bug.cgi?id=872873 if (typeof e.preventDefault === 'function') e.preventDefault() reject(e.target.error) } }
javascript
{ "resource": "" }
q10265
train
function(newData, limit) { if ((this.buffer.length + newData.length) > options.limit) { this.buffer = this.buffer.concat(newData.slice(0, options.limit - this.buffer.length)); self._sendDisplayLimitReachedMessage(limit); } else { this.buffer = this.buffer.concat(newData); } }
javascript
{ "resource": "" }
q10266
addReconnectOnReadonly
train
function addReconnectOnReadonly(cfg) { const noop = () => false; const userReconn = (typeof cfg.reconnectOnError === 'function') ? cfg.reconnectOnError : noop; cfg.reconnectOnError = err => { const shouldReconnect = (isReadonlyError(err) || userReconn(err)) ? 2 : false; if (shouldReconnect) console.warn(RECONNECT_WARNING); return shouldReconnect; }; }
javascript
{ "resource": "" }
q10267
_drawLine
train
function _drawLine(v0, v1, color) { var p = new Primitive(); p.vertices = [v0, v1]; p.color = toColor(color); renderer.addPrimitive(p); }
javascript
{ "resource": "" }
q10268
_drawArrow
train
function _drawArrow(pStart, pEnd, arrowSize, color) { var p = new Primitive(); p.color = toColor(color); p.vertices.push(pStart); p.vertices.push(pEnd); var dir = new THREE.Vector3(); dir.subVectors(pEnd, pStart); dir.normalize(); var right = new THREE.Vector3(); var dot = dir.dot(UNIT_Y); if (dot > 0.99 || dot < -0.99) { right.crossVectors(dir, UNIT_X); } else { right.crossVectors(dir, UNIT_Y); } var top = new THREE.Vector3(); top.crossVectors(right, dir); dir.multiplyScalar(arrowSize); right.multiplyScalar(arrowSize); top.multiplyScalar(arrowSize); // Right slant. var tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.addVectors(pEnd, right).sub(dir)); // Left slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.subVectors(pEnd, right).sub(dir)); // Top slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.addVectors(pEnd, top).sub(dir)); // Bottom slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.subVectors(pEnd, top).sub(dir)); renderer.addPrimitive(p); }
javascript
{ "resource": "" }
q10269
_drawSphere
train
function _drawSphere(pos, r, color) { var p = new Primitive(); p.color = toColor(color); // Decreasing these angles will increase complexity of sphere. var dtheta = 35; var dphi = 35; for (var theta = -90; theta <= (90 - dtheta); theta += dtheta) { for (var phi = 0; phi <= (360 - dphi); phi += dphi) { p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD), pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD), pos.z + r * Math.sin(theta * DEG_TO_RAD) )); p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD), pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD), pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD) )); p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD), pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD), pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD) )); if ((theta > -90) && (theta < 90)) { p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD), pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD), pos.z + r * Math.sin(theta * DEG_TO_RAD) )); } } } renderer.addPrimitive(p); }
javascript
{ "resource": "" }
q10270
train
function(position, velocity, dt) { return mf.add(position, mf.mulScalar(velocity, dt)); }
javascript
{ "resource": "" }
q10271
train
function( p, q ) { var wurzel = Math.sqrt((p * p / 4) - q); var vorwurzel = (-p / 2); var result = []; if( wurzel > 0 ) { result = [vorwurzel + wurzel, vorwurzel - wurzel]; } else if( wurzel === 0 ) { result = [vorwurzel]; } return result; }
javascript
{ "resource": "" }
q10272
train
function(myPos, myVelo, targetPos, targetVelo) { var relTargetPos = mf.sub(targetPos, myPos); var a = mf.lengthSquared(targetVelo) - myVelo * myVelo; var b = 2.0 * mf.dot(targetVelo, relTargetPos); var c = mf.lengthSquared(relTargetPos); if( a === 0 ) { if( b !== 0 ) { var time = -c / b; if( time > 0.0 ) return time; } } else { // P und Q berechnen... var p = b / a; var q = c / a; // Quadratische Gleichung lösen... var times = this.quadEquation(p, q); if( times.length === 0 ) return []; if( times.length === 2 ) { var icptTime = Math.min(times[0], times[1]); if( icptTime < 0.0 ) { icptTime = Math.max(times[0], times[1]); } return icptTime; } else if( times.length === 1 ) { if( times[0] >= 0.0 ) { return times[0]; } } } return undefined; }
javascript
{ "resource": "" }
q10273
train
function(myPos, myVelo, targetPos, targetVelo) { var ticpt = this.calcInterceptTime(myPos, myVelo, targetPos, targetVelo); if(ticpt === undefined) return undefined; return this.getPositionByVeloAndTime(targetPos, targetVelo, ticpt); }
javascript
{ "resource": "" }
q10274
train
function(myPos, myVelo, targetPos, targetVelo ) { var distance = Math.sqrt(mf.lengthSquared(mf.sub(targetPos, myPos))); var approachSpeed = this.calcApproachSpeed(myPos, myVelo, targetPos, targetVelo); if( approachSpeed > 0.0 ) { return distance / approachSpeed; } else { return undefined; } }
javascript
{ "resource": "" }
q10275
train
function(myPos, myVelo, targetPos, targetVelo) { var posDiff = mf.sub(targetPos, myPos); var veloDiff = mf.sub(targetVelo, myVelo); var approachSpeed = mf.dot(posDiff, veloDiff); var posDiffLength = Math.sqrt(mf.lengthSquared(posDiff)); if( posDiffLength <= 0.0 ) return 0.0; return -approachSpeed / posDiffLength; }
javascript
{ "resource": "" }
q10276
train
function (partialString) { var edgeQuotesMatcher = /^["']|["']$/g; var partialIDWithQuotes = partialString.replace(this.findPartialsRE, '$1'); var partialID = partialIDWithQuotes.replace(edgeQuotesMatcher, ''); return partialID; }
javascript
{ "resource": "" }
q10277
formatInboundRecipients
train
function formatInboundRecipients(recipients) { return _.map(recipients, (recipient) => { if (_.isString(recipient)) { return { email: recipient, name: '', }; } else { return { email: recipient.address || '', name: recipient.name || '' } } }); }
javascript
{ "resource": "" }
q10278
train
function (webpackConfig, paths) { var defaultWebpackConfig = { output: { filename: paths.output.name, }, module: { loaders: [ { test: /\.vue$/, loader: 'vue' }, ] }, }; if (fs.existsSync('webpack.config.js')) { var customWebpackConfig = require('./../../webpack.config.js'); defaultWebpackConfig = _.extend(defaultWebpackConfig, customWebpackConfig); } webpackConfig = _.extend(defaultWebpackConfig, webpackConfig); if (!_.contains(webpackConfig.module.loaders, {test: /\.vue$/, loader: 'vue'})) { webpackConfig.module.loaders.push({ test: /\.vue$/, loader: 'vue' }); } if (config.sourcemaps) { webpackConfig = _.defaults( webpackConfig, {devtool: '#source-map'} ); } if (config.production) { var currPlugins = _.isArray(webpackConfig.plugins) ? webpackConfig.plugins : []; webpackConfig.plugins = currPlugins.concat([new UglifyJsPlugin({sourceMap: false})]); } return webpackConfig; }
javascript
{ "resource": "" }
q10279
train
function(index, placeholder) { if (typeof this.config.indexes[index] === 'undefined') { console.log('LUNR: getLunrSearchPage will not work unless you specify a valid index from plugins.lunr.indexes in your Docpad configuration file.'); return; } placeholder = placeholder || 'Search terms'; var scriptElements = ''; var dataFilename = this.config.indexes[index].indexFilename; var scripts = ['lunr.min.js', dataFilename, 'lunr-ui.min.js']; for (var i in scripts) { scriptElements += '<script src="/lunr/' + scripts[i] + '" type="text/javascript"></script>'; } return '<input type="text" class="search-bar" id="lunr-input" placeholder="' + placeholder + '" />' + '<input type="hidden" id="lunr-hidden" />' + scriptElements; }
javascript
{ "resource": "" }
q10280
handle2dkeys
train
function handle2dkeys (keys, value, step, min, max) { //up and right - increase by one if (keys[38]) { value[1] = inc(value[1], plainify(step, 1), 1); } if (keys[39]) { value[0] = inc(value[0], plainify(step, 0), 1); } if (keys[40]) { value[1] = inc(value[1], plainify(step, 1), -1); } if (keys[37]) { value[0] = inc(value[0], plainify(step, 0), -1); } //meta var coordIdx = 1; if (keys[18] || keys[91] || keys[17] || keys[16]) coordIdx = 0; //home - min if (keys[36]) { value[coordIdx] = min[coordIdx]; } //end - max if (keys[35]) { value[coordIdx] = max[coordIdx]; } //pageup if (keys[33]) { value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), PAGE); } //pagedown if (keys[34]) { value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), -PAGE); } return value; }
javascript
{ "resource": "" }
q10281
handle1dkeys
train
function handle1dkeys (keys, value, step, min, max) { step = step || 1; //up and right - increase by one if (keys[38] || keys[39]) { value = inc(value, step, 1); } //down and left - decrease by one if (keys[40] || keys[37]) { value = inc(value, step, -1); } //home - min if (keys[36]) { value = min; } //end - max if (keys[35]) { value = max; } //pageup if (keys[33]) { value = inc(value, step, PAGE); } //pagedown if (keys[34]) { value = inc(value, step, -PAGE); } return value; }
javascript
{ "resource": "" }
q10282
train
function(el, options) { // default options for the line var defaults = require('../utils/default-options')(); // if we don't pass options, just // make it an empty object if (typeof options === 'undefined' ) { options = {}; } options = _.defaults(options, defaults); this.width = options.width; this.height = options.height; this.margin = options.margin; this.useMarkdown = options.useMarkdown; this.el = el; this._data = []; this.selection = d3.select(el).append('g') .attr('class', 'markerSeries'); if (options.clipId) { this.selection.attr('clip-path', 'url(#' + options.clipId + ')'); } this.xScale = function() { throw new Error('X scale not set'); }; this.xfield = options.xfield; this.xfieldFormat = options.xfieldFormat; this.title = options.title; this.text = options.text; this.type = options.type; // XXX wire this up this.duration = options.duration || 250; this.currentDatapoint = null; this.draw_range = null; }
javascript
{ "resource": "" }
q10283
scanFolders
train
function scanFolders(rootFolderPath, folders, folderFileExtensions, callback) { var result = []; console.log('Scanning:: Folders', folders); console.log('Scanning:: Root folder path', rootFolderPath); var fileExtensions = self.fileExtensions.slice(); scanFolder(); function scanFolder() { var folder = folders.shift(); if (folder === undefined) { // console.log('Scanning:: Finished with result', result); return callback(null, result); } if(folderFileExtensions.length){ fileExtensions = folderFileExtensions.shift(); } //var path = rootFolderPath + '/' + folder; var path = rootFolderPath + folder; console.log('Scanning:: Full path to folder', path, fileExtensions); fs.readdir(path, function (err, list) { if (err) { console.error("Error scanning folder: ", path); return scanFolder(); } var files = []; for (var i = 0; i < list.length; i++) { if (acceptFile(path, list[i], fileExtensions)) { //files.push((folder.length ? folder + '/' : folder) + list[i]); files.push(path + '/' + list[i]); } } result = result.concat(files); scanFolder(); }); } }
javascript
{ "resource": "" }
q10284
Slidy
train
function Slidy(target, options) { //force constructor if (!(this instanceof Slidy)) return new Slidy(target, options); var self = this; //ensure target & options if (!options) { if (target instanceof Element) { options = {}; } else { options = target; target = doc.createElement('div'); } } //get preferred element self.element = target; //adopt options extend(self, options); //calculate value & step //detect step automatically based on min/max range (1/100 by default) //native behaviour is always 1, so ignore it if (options.step === undefined) { self.step = detectStep(self.min, self.max); } //calc undefined valuea as a middle of range if (options.value === undefined) { self.value = detectValue(self.min, self.max); } //bind passed callbacks, if any if (options.created) on(self, 'created', options.created); //save refrence instancesCache.set(self.element, self); //generate id self.id = getUid(); self.ns = 'slidy-' + self.id; if (!self.element.id) self.element.id = self.ns; //init instance self.element.classList.add('slidy'); //create pickers, if passed a list self.pickers = []; if (isArray(options.pickers) && options.pickers.length) { options.pickers.forEach(function (opts) { self.addPicker(opts); }); } //ensure at least one picker exists, if not passed in options separately else if (!options.hasOwnProperty('pickers')) { self.addPicker(options.pickers); } // Define value as active picker value getter //FIXME: case of multiple pickers Object.defineProperty(self, 'value', { set: function (value) { var picker = this.getActivePicker(); picker && (picker.value = value); }, get: function () { var picker = this.getActivePicker(); return picker && picker.value; } }); if (self.aria) { //a11y //@ref http://www.w3.org/TR/wai-aria/roles#slider self.element.setAttribute('role', 'slider'); target.setAttribute('aria-valuemax', self.max); target.setAttribute('aria-valuemin', self.min); target.setAttribute('aria-orientation', self.orientation); target.setAttribute('aria-atomic', true); //update controls target.setAttribute('aria-controls', self.pickers.map( function (item) { return item.element.id; }).join(' ')); } //turn on events etc if (!self.element.hasAttribute('disabled')) self.enable(); //emit callback self.emit('created'); }
javascript
{ "resource": "" }
q10285
detectStep
train
function detectStep (min, max) { var range = getTransformer(function (a, b) { return Math.abs(a - b); })(max, min); var step = getTransformer(function (a) { return a < 100 ? 0.01 : 1; })(range); return step; }
javascript
{ "resource": "" }
q10286
detectValue
train
function detectValue (min, max) { return getTransformer(function (a, b) { return (a + b) * 0.5; })(min, max); }
javascript
{ "resource": "" }
q10287
setDefault
train
function setDefault (opts, key, val) { if (opts.schema) { opts.prompts = opts.schema; delete opts.schema; } const prompts = opts.prompts || (opts.prompts = {}); if (!prompts[key] || typeof prompts[key] !== 'object') { prompts[key] = { 'type': 'string', 'default': val }; } else { prompts[key]['default'] = val; } }
javascript
{ "resource": "" }
q10288
consumeIdent
train
function consumeIdent(stream) { stream.start = stream.pos; stream.eatWhile(isIdentPrefix); stream.eatWhile(isIdent); return stream.start !== stream.pos ? stream.current() : null; }
javascript
{ "resource": "" }
q10289
consumeValue
train
function consumeValue(stream) { const values = new CSSValue(); let value; while (!stream.eof()) { // use colon as value separator stream.eat(COLON); if (value = consumeNumericValue(stream) || consumeColor(stream)) { // edge case: a dash after unit-less numeric value or color should // be treated as value separator, not negative sign if (!value.unit) { stream.eat(DASH); } } else { stream.eat(DASH); value = consumeKeyword(stream, true); } if (!value) { break; } values.add(value); } return values; }
javascript
{ "resource": "" }
q10290
fract32
train
function fract32 (arr) { if (arr.length) { var fract = float32(arr) for (var i = 0, l = fract.length; i < l; i++) { fract[i] = arr[i] - fract[i] } return fract } // number return float32(arr - float32(arr)) }
javascript
{ "resource": "" }
q10291
float32
train
function float32 (arr) { if (arr.length) { if (arr instanceof Float32Array) return arr var float = new Float32Array(arr) float.set(arr) return float } // number narr[0] = arr return narr[0] }
javascript
{ "resource": "" }
q10292
corsPrefetch
train
function corsPrefetch(req, res, next) { res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type, *'); res.setHeader('Access-Control-Allow-Credentials', 'true'); if (req.method === 'OPTIONS') { res.sendStatus(200); return; } next(); }
javascript
{ "resource": "" }
q10293
writePCBuffer
train
function writePCBuffer(client, buffer) { var length = pcbuffer.createBuffer(); length.writeVarInt(buffer.buffer().length); client.write(Buffer.concat([length.buffer(), buffer.buffer()])); }
javascript
{ "resource": "" }
q10294
sendContent
train
function sendContent(res, args, action, padId, padURL, resultDb) { console.debug("starting sendContent: args ->", action, " / ", padId, " / ", padURL, " / ", resultDb); if (action == 'subscribe') { var actionMsg = "Subscribing '" + resultDb.email + "' to pad " + padId; } else { var actionMsg = "Unsubscribing '" + resultDb.email + "' from pad " + padId; } var msgCause, resultMsg, classResult; if (resultDb.foundInDb == true && resultDb.timeDiffGood == true) { // Pending data were found un Db and updated -> good resultMsg = "Success"; classResult = "validationGood"; if (action == 'subscribe') { msgCause = "You will receive email when someone changes this pad."; } else { msgCause = "You won't receive anymore email when someone changes this pad."; } } else if (resultDb.foundInDb == true) { // Pending data were found but older than a day -> fail resultMsg = "Too late!"; classResult = "validationBad"; msgCause = "You have max 24h to click the link in your confirmation email."; } else { // Pending data weren't found in Db -> fail resultMsg = "Fail"; classResult = "validationBad"; msgCause = "We couldn't find any pending " + (action == 'subscribe'?'subscription':'unsubscription') + "<br />in our system with this Id.<br />Maybe you wait more than 24h before validating"; } args.content = fs.readFileSync(__dirname + "/templates/response.ejs", 'utf-8'); args.content = args.content .replace(/\<%action%\>/, actionMsg) .replace(/\<%classResult%\>/, classResult) .replace(/\<%result%\>/, resultMsg) .replace(/\<%explanation%\>/, msgCause) .replace(/\<%padUrl%\>/g, padURL); res.contentType("text/html; charset=utf-8"); res.send(args.content); // Send it to the requester*/ }
javascript
{ "resource": "" }
q10295
preferencesReset
train
function preferencesReset() { return this.initializedPromise.then(function() { this.prefs = Object.create(DEFAULT_PREFERENCES); return this._writeToStorage(DEFAULT_PREFERENCES); }.bind(this)); }
javascript
{ "resource": "" }
q10296
preferencesGet
train
function preferencesGet(name) { return this.initializedPromise.then(function () { var defaultValue = DEFAULT_PREFERENCES[name]; if (defaultValue === undefined) { throw new Error('preferencesGet: \'' + name + '\' is undefined.'); } else { var prefValue = this.prefs[name]; if (prefValue !== undefined) { return prefValue; } } return defaultValue; }.bind(this)); }
javascript
{ "resource": "" }
q10297
secondaryToolbarSetMaxHeight
train
function secondaryToolbarSetMaxHeight(container) { if (!container || !this.buttonContainer) { return; } this.newContainerHeight = container.clientHeight; if (this.previousContainerHeight === this.newContainerHeight) { return; } this.buttonContainer.setAttribute('style', 'max-height: ' + (this.newContainerHeight - SCROLLBAR_PADDING) + 'px;'); this.previousContainerHeight = this.newContainerHeight; }
javascript
{ "resource": "" }
q10298
PDFPresentationMode_request
train
function PDFPresentationMode_request() { if (this.switchInProgress || this.active || !this.viewer.hasChildNodes()) { return false; } this._addFullscreenChangeListeners(); this._setSwitchInProgress(); this._notifyStateChange(); if (this.container.requestFullscreen) { this.container.requestFullscreen(); } else if (this.container.mozRequestFullScreen) { this.container.mozRequestFullScreen(); } else if (this.container.webkitRequestFullscreen) { this.container.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } else if (this.container.msRequestFullscreen) { this.container.msRequestFullscreen(); } else { return false; } this.args = { page: PDFViewerApplication.page, previousScale: PDFViewerApplication.currentScaleValue }; return true; }
javascript
{ "resource": "" }
q10299
isLeftMouseReleased
train
function isLeftMouseReleased(event) { if ('buttons' in event && isNotIEorIsIE10plus) { // http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons // Firefox 15+ // Internet Explorer 10+ return !(event.buttons | 1); } if (isChrome15OrOpera15plus || isSafari6plus) { // Chrome 14+ // Opera 15+ // Safari 6.0+ return event.which === 0; } }
javascript
{ "resource": "" }