_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q10100
train
function (alphaCoordinates) { var coordinateLabels = 'abcdefghijklmnopqrst'; var intersection = []; intersection[0] = coordinateLabels.indexOf(alphaCoordinates.substring(0, 1)); intersection[1] = coordinateLabels.indexOf(alphaCoordinates.substring(1, 2)); return intersection; }
javascript
{ "resource": "" }
q10101
train
function (input, outputType, verbose) { var output; // If no output type has been specified, try to set it to the // opposite of the input if (typeof outputType === 'undefined') { outputType = (typeof input === 'string') ? 'object' : 'string'; } /** * Turn a path object into a string. */ function stringify(input) { if (typeof input === 'string') { return input; } if (!input) { return ''; } output = input.m; var variations = []; for (var key in input) { if (input.hasOwnProperty(key) && key !== 'm') { // Only show variations that are not the primary one, since // primary variations are chosen by default if (input[key] > 0) { if (verbose) { variations.push(', variation ' + input[key] + ' at move ' + key); } else { variations.push('-' + key + ':' + input[key]); } } } } output += variations.join(''); return output; } /** * Turn a path string into an object. */ function parse(input) { if (typeof input === 'object') { input = stringify(input); } if (!input) { return { m: 0 }; } var path = input.split('-'); output = { m: Number(path.shift()) }; if (path.length) { path.forEach(function (variation, i) { variation = variation.split(':'); output[Number(variation[0])] = parseInt(variation[1], 10); }); } return output; } if (outputType === 'string') { output = stringify(input); } else if (outputType === 'object') { output = parse(input); } else { output = undefined; } return output; }
javascript
{ "resource": "" }
q10102
stringify
train
function stringify(input) { if (typeof input === 'string') { return input; } if (!input) { return ''; } output = input.m; var variations = []; for (var key in input) { if (input.hasOwnProperty(key) && key !== 'm') { // Only show variations that are not the primary one, since // primary variations are chosen by default if (input[key] > 0) { if (verbose) { variations.push(', variation ' + input[key] + ' at move ' + key); } else { variations.push('-' + key + ':' + input[key]); } } } } output += variations.join(''); return output; }
javascript
{ "resource": "" }
q10103
parse
train
function parse(input) { if (typeof input === 'object') { input = stringify(input); } if (!input) { return { m: 0 }; } var path = input.split('-'); output = { m: Number(path.shift()) }; if (path.length) { path.forEach(function (variation, i) { variation = variation.split(':'); output[Number(variation[0])] = parseInt(variation[1], 10); }); } return output; }
javascript
{ "resource": "" }
q10104
processArray
train
function processArray(req, res, nextarray) { if (!nextarray || !nextarray.length) return; var proc = nextarray.shift(); proc(req, res, function () { processArray(req, res, nextarray); }); }
javascript
{ "resource": "" }
q10105
path
train
function path(req) { var oUrl = req.originalUrl || req.url; this.string = oUrl.split('?')[0]; this.relative = req.url.split('?')[0]; }
javascript
{ "resource": "" }
q10106
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomCommon)){ return new AtomCommon(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomCommon.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10107
findPort
train
function findPort(cb) { var port = tryPort; tryPort += 1; var server = net.createServer(); server.listen(port, function(err) { server.once('close', function() { cb(port); }); server.close(); }); server.on('error', function(err) { log("port " + tryPort + " is occupied"); findPort(cb); }); }
javascript
{ "resource": "" }
q10108
startServlet
train
function startServlet(cb) { startingServer = true; servletReady = false; debugger; findPort(function(port) { servletPort = global._servletPort = '' + port; servlet = global._servlet = cp.spawn('java', ['-cp', '.:../lib/servlet-api-2.5.jar:../lib/jetty-all-7.0.2.v20100331.jar', 'RunnerServlet', servletPort], { cwd: config.rootDir + '/bin' }); servlet.stdout.on('data', function(data) { console.log('OUT:' + data); }); servlet.stderr.on('data', function(data) { console.log("" + data); if (~data.toString().indexOf(servletPort)) { servletReady = true; startingServer = false; // queue.checkQueues(); observer.emit("server.running", port); if (cb) cb(port); } }); servlet.on('exit', function(code, signal) { resetFlags(); if (code === null || signal === null) { serverExit = true; } log('servlet exist with code ' + code + 'signal ' + signal); observer.emit('server.exit',code); }); // make sure to close server after node process ends process.on('exit', function() { stopServer(true); }); }); }
javascript
{ "resource": "" }
q10109
Partyflock
train
function Partyflock(consumerKey, consumerSecret, endpoint, debug) { this.endpoint = 'partyflock.nl'; // Check instance arguments this.endpoint = (endpoint ? endpoint : this.endpoint); this.consumerKey = (consumerKey ? consumerKey : false); this.consumerSecret = (consumerSecret ? consumerSecret : false); this.debug = (typeof debug !== 'undefined' ? debug : false); // Check config options if(config.partyflock) { this.consumerKey = (this.consumerKey === false ? config.partyflock.consumerKey : false); this.consumerSecret = (this.consumerSecret === false ? config.partyflock.consumerSecret : false); this.endpoint = (this.endpoint !== config.partyflock.endpoint ? config.partyflock.endpoint : this.endpoint); this.debug = (this.debug === false && config.partyflock.debug !== 'undefined' ? config.partyflock.debug : this.debug); } // CI integration if(process.env['CONSUMER_KEY'] && process.env['CONSUMER_SECRET']) { this.consumerKey = process.env['CONSUMER_KEY']; this.consumerSecret = process.env['CONSUMER_SECRET']; } this.type = 'json'; this.date = new date(this); this.location = new location(this); this.artist = new artist(this); this.user = new user(this); this.party = new party(this); this.oauth = new OAuth.OAuth( 'https://' + this.endpoint + '/request_token', '', // no need for an oauth_token request this.consumerKey, this.consumerSecret, '1.0A', null, 'HMAC-SHA1' ); }
javascript
{ "resource": "" }
q10110
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Coverage)){ return new Coverage(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Coverage.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10111
train
function(resolution, latitude) { var degs = metersToLongitudeDegrees(resolution, latitude); return (Math.abs(degs) > 0.000001) ? Math.max(1, Math.log2(360/degs)) : 1; }
javascript
{ "resource": "" }
q10112
train
function(coordinate,size) { var latDeltaDegrees = size/g_METERS_PER_DEGREE_LATITUDE; var latitudeNorth = Math.min(90, coordinate[0] + latDeltaDegrees); var latitudeSouth = Math.max(-90, coordinate[0] - latDeltaDegrees); var bitsLat = Math.floor(latitudeBitsForResolution(size))*2; var bitsLongNorth = Math.floor(longitudeBitsForResolution(size, latitudeNorth))*2-1; var bitsLongSouth = Math.floor(longitudeBitsForResolution(size, latitudeSouth))*2-1; return Math.min(bitsLat, bitsLongNorth, bitsLongSouth, g_MAXIMUM_BITS_PRECISION); }
javascript
{ "resource": "" }
q10113
train
function(center, radius) { var latDegrees = radius/g_METERS_PER_DEGREE_LATITUDE; var latitudeNorth = Math.min(90, center[0] + latDegrees); var latitudeSouth = Math.max(-90, center[0] - latDegrees); var longDegsNorth = metersToLongitudeDegrees(radius, latitudeNorth); var longDegsSouth = metersToLongitudeDegrees(radius, latitudeSouth); var longDegs = Math.max(longDegsNorth, longDegsSouth); return [ [center[0], center[1]], [center[0], wrapLongitude(center[1] - longDegs)], [center[0], wrapLongitude(center[1] + longDegs)], [latitudeNorth, center[1]], [latitudeNorth, wrapLongitude(center[1] - longDegs)], [latitudeNorth, wrapLongitude(center[1] + longDegs)], [latitudeSouth, center[1]], [latitudeSouth, wrapLongitude(center[1] - longDegs)], [latitudeSouth, wrapLongitude(center[1] + longDegs)] ]; }
javascript
{ "resource": "" }
q10114
train
function(geohash, bits) { validateGeohash(geohash); var precision = Math.ceil(bits/g_BITS_PER_CHAR); if (geohash.length < precision) { return [geohash, geohash+"~"]; } geohash = geohash.substring(0, precision); var base = geohash.substring(0, geohash.length - 1); var lastValue = g_BASE32.indexOf(geohash.charAt(geohash.length - 1)); var significantBits = bits - (base.length*g_BITS_PER_CHAR); var unusedBits = (g_BITS_PER_CHAR - significantBits); /*jshint bitwise: false*/ // delete unused bits var startValue = (lastValue >> unusedBits) << unusedBits; var endValue = startValue + (1 << unusedBits); /*jshint bitwise: true*/ if (endValue > 31) { return [base+g_BASE32[startValue], base+"~"]; } else { return [base+g_BASE32[startValue], base+g_BASE32[endValue]]; } }
javascript
{ "resource": "" }
q10115
reducer
train
function reducer(props, map, key) { return Object.assign({}, map, { [key]: props[key], }); }
javascript
{ "resource": "" }
q10116
Markdown
train
function Markdown(props) { const tagProps = Object.keys(props).filter(filter).reduce(reducer.bind(null, props), {}); const parser = createParser(props.parser); return React.createElement( props.tagName, Object.assign(tagProps, { dangerouslySetInnerHTML: { __html: parser(props.content), }, }), ); }
javascript
{ "resource": "" }
q10117
HttpManager
train
function HttpManager(options) { if (!(this instanceof HttpManager)) { return new HttpManager(options); } options = options || {}; Manager.call(this, options); debug('New HttpManager: %j', options); this.hostname = options.hostname || null; this.port = options.port || Defaults.PORT; this.interval = options.interval || Defaults.INTERVAL; this._announceTimerId = null; this._startAnnouncements(); }
javascript
{ "resource": "" }
q10118
train
function (newFilters, oldFilters) { var self = this; if (!oldFilters) { oldFilters = this._filters; } else if (!isArray(oldFilters)) { oldFilters = [oldFilters]; } if (!newFilters) { newFilters = []; } else if (!isArray(newFilters)) { newFilters = [newFilters]; } oldFilters.forEach(function (filter) { self._removeFilter(filter); }); newFilters.forEach(function (filter) { self._addFilter(filter); }); this._runFilters(); }
javascript
{ "resource": "" }
q10119
train
function (query, indexName) { var model = this.collection.get(query, indexName); if (model && includes(this.models, model)) return model; }
javascript
{ "resource": "" }
q10120
train
function (query, indexName) { if (!query) return; var index = this._indexes[indexName || this.mainIndex]; return index[query] || index[query[this.mainIndex]] || this._indexes.cid[query] || this._indexes.cid[query.cid]; }
javascript
{ "resource": "" }
q10121
train
function (model, options, eventName) { var newModels = slice.call(this.models); var comparator = this.comparator || this.collection.comparator; //Whether or not we are to expect a sort event from our collection later var sortable = eventName === 'add' && this.collection.comparator && (options.at == null) && options.sort !== false; if (!sortable) { var index = sortedIndexBy(newModels, model, comparator); newModels.splice(index, 0, model); } else { newModels.push(model); if (options.at) newModels = this._sortModels(newModels); } this.models = newModels; this._addIndex(this._indexes, model); if (this.comparator && !sortable) { this.trigger('sort', this); } }
javascript
{ "resource": "" }
q10122
train
function (model) { var newModels = slice.call(this.models); var modelIndex = newModels.indexOf(model); if (modelIndex > -1) { newModels.splice(modelIndex, 1); this.models = newModels; this._removeIndex(this._indexes, model); return true; } return false; }
javascript
{ "resource": "" }
q10123
train
function () { // make a copy of the array for comparisons var existingModels = slice.call(this.models); var rootModels = slice.call(this.collection.models); var newIndexes = {}; var newModels, toAdd, toRemove; this._resetIndexes(newIndexes); // reduce base model set by applying filters if (this._filters.length) { newModels = reduce(this._filters, function (startingArray, filterFunc) { return startingArray.filter(filterFunc); }, rootModels); } else { newModels = slice.call(rootModels); } // sort it if (this.comparator) newModels = this._sortModels(newModels, this.comparator); newModels.forEach(function (model) { this._addIndex(newIndexes, model); }, this); // Cache a reference to the full filtered set to allow this._filtered.length. Ref: #6 if (rootModels.length) { this._filtered = newModels; this._indexes = newIndexes; } else { this._filtered = []; this._resetIndexes(this._indexes); } // now we've got our new models time to compare toAdd = difference(newModels, existingModels); toRemove = difference(existingModels, newModels); // save 'em this.models = newModels; forEach(toRemove, bind(function (model) { this.trigger('remove', model, this); }, this)); forEach(toAdd, bind(function (model) { this.trigger('add', model, this); }, this)); // unless we have the same models in same order trigger `sort` if (!isEqual(existingModels, newModels) && this.comparator) { this.trigger('sort', this); } }
javascript
{ "resource": "" }
q10124
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof NameForm)){ return new NameForm(json); } // If the given object is already an instance then just return it. DON'T copy it. if(NameForm.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10125
train
function(callback){ ubeacon.getMeshSettingsRegisterObject( function(data, error){ if( error === null ){ meshSettings.setFrom( data ); console.log( 'meshSettings: ', meshSettings ); if( meshSettings.enabled !== true && program.enableMesh !== true ){ return callback(new Error('Mesh is disabled on device. Enable it by adding `--enable-mesh` parameter.')); } return callback(null); }else{ return callback(error); } }); }
javascript
{ "resource": "" }
q10126
train
function(callback){ ubeacon.getMeshDeviceId( function( deviceAddress ){ console.log( '[ubeacon] Device address is: ' + deviceAddress + ' (0x' + deviceAddress.toString(16) + ')' ); callback(null); }); }
javascript
{ "resource": "" }
q10127
train
function(callback){ console.log( 'Start sending messages... '); setInterval(function(){ var msg = ''; if( program.message != null ){ msg = program.message; }else{ msgCounter++; msg = 'Hello #' + msgCounter + ' from node.js'; } console.log( '[ubeacon] Sending "' +msg+ '" to device: ' + program.destinationAddress ); ubeacon.sendMeshGenericMessage( program.destinationAddress, msg, function( response ){ console.log( '[ubeacon] Mesh message #' + msgCounter + ' sent. Response: ' + response ); }); }, interval); }
javascript
{ "resource": "" }
q10128
columns
train
function columns(column) { if (!column) { return this; } this._statements.push({ grouping: 'columns', value: normalizeArr.apply(null, arguments) }); return this; }
javascript
{ "resource": "" }
q10129
distinct
train
function distinct() { this._statements.push({ grouping: 'columns', value: normalizeArr.apply(null, arguments), distinct: true }); return this; }
javascript
{ "resource": "" }
q10130
_objectWhere
train
function _objectWhere(obj) { var boolVal = this._bool(); var notVal = this._not() ? 'Not' : ''; for (var key in obj) { this[boolVal + 'Where' + notVal](key, obj[key]); } return this; }
javascript
{ "resource": "" }
q10131
havingWrapped
train
function havingWrapped(callback) { this._statements.push({ grouping: 'having', type: 'whereWrapped', value: callback, bool: this._bool() }); return this; }
javascript
{ "resource": "" }
q10132
whereExists
train
function whereExists(callback) { this._statements.push({ grouping: 'where', type: 'whereExists', value: callback, not: this._not(), bool: this._bool() }); return this; }
javascript
{ "resource": "" }
q10133
whereIn
train
function whereIn(column, values) { if (Array.isArray(values) && isEmpty(values)) { return this.where(this._not()); } this._statements.push({ grouping: 'where', type: 'whereIn', column: column, value: values, not: this._not(), bool: this._bool() }); return this; }
javascript
{ "resource": "" }
q10134
whereNull
train
function whereNull(column) { this._statements.push({ grouping: 'where', type: 'whereNull', column: column, not: this._not(), bool: this._bool() }); return this; }
javascript
{ "resource": "" }
q10135
whereBetween
train
function whereBetween(column, values) { assert(Array.isArray(values), 'The second argument to whereBetween must be an array.'); assert(values.length === 2, 'You must specify 2 values for the whereBetween clause'); this._statements.push({ grouping: 'where', type: 'whereBetween', column: column, value: values, not: this._not(), bool: this._bool() }); return this; }
javascript
{ "resource": "" }
q10136
groupBy
train
function groupBy(item) { if (item instanceof Raw) { return this.groupByRaw.apply(this, arguments); } this._statements.push({ grouping: 'group', type: 'groupByBasic', value: normalizeArr.apply(null, arguments) }); return this; }
javascript
{ "resource": "" }
q10137
groupByRaw
train
function groupByRaw(sql, bindings) { var raw = sql instanceof Raw ? sql : this.client.raw(sql, bindings); this._statements.push({ grouping: 'group', type: 'groupByRaw', value: raw }); return this; }
javascript
{ "resource": "" }
q10138
orderBy
train
function orderBy(column, direction) { this._statements.push({ grouping: 'order', type: 'orderByBasic', value: column, direction: direction }); return this; }
javascript
{ "resource": "" }
q10139
union
train
function union(callbacks, wrap) { if (arguments.length === 1 || arguments.length === 2 && typeof wrap === 'boolean') { if (!Array.isArray(callbacks)) { callbacks = [callbacks]; } for (var i = 0, l = callbacks.length; i < l; i++) { this._statements.push({ grouping: 'union', clause: 'union', value: callbacks[i], wrap: wrap || false }); } } else { callbacks = normalizeArr.apply(null, arguments).slice(0, arguments.length - 1); wrap = arguments[arguments.length - 1]; if (typeof wrap !== 'boolean') { callbacks.push(wrap); wrap = false; } this.union(callbacks, wrap); } return this; }
javascript
{ "resource": "" }
q10140
unionAll
train
function unionAll(callback, wrap) { this._statements.push({ grouping: 'union', clause: 'union all', value: callback, wrap: wrap || false }); return this; }
javascript
{ "resource": "" }
q10141
having
train
function having(column, operator, value) { if (column instanceof Raw && arguments.length === 1) { return this._havingRaw(column); } // Check if the column is a function, in which case it's // a having statement wrapped in parens. if (typeof column === 'function') { return this.havingWrapped(column); } this._statements.push({ grouping: 'having', type: 'havingBasic', column: column, operator: operator, value: value, bool: this._bool() }); return this; }
javascript
{ "resource": "" }
q10142
_havingRaw
train
function _havingRaw(sql, bindings) { var raw = sql instanceof Raw ? sql : this.client.raw(sql, bindings); this._statements.push({ grouping: 'having', type: 'havingRaw', value: raw, bool: this._bool() }); return this; }
javascript
{ "resource": "" }
q10143
limit
train
function limit(value) { var val = parseInt(value, 10); if (isNaN(val)) { debug('A valid integer must be provided to limit'); } else { this._single.limit = val; } return this; }
javascript
{ "resource": "" }
q10144
pluck
train
function pluck(column) { this._method = 'pluck'; this._single.pluck = column; this._statements.push({ grouping: 'columns', type: 'pluck', value: column }); return this; }
javascript
{ "resource": "" }
q10145
fromJS
train
function fromJS(obj) { Object.keys(obj).forEach(function (key) { var val = obj[key]; if (typeof this[key] !== 'function') { debug('Knex Error: unknown key ' + key); } if (Array.isArray(val)) { this[key].apply(this, val); } else { this[key](val); } }, this); return this; }
javascript
{ "resource": "" }
q10146
_bool
train
function _bool(val) { if (arguments.length === 1) { this._boolFlag = val; return this; } var ret = this._boolFlag; this._boolFlag = 'and'; return ret; }
javascript
{ "resource": "" }
q10147
_not
train
function _not(val) { if (arguments.length === 1) { this._notFlag = val; return this; } var ret = this._notFlag; this._notFlag = false; return ret; }
javascript
{ "resource": "" }
q10148
_joinType
train
function _joinType(val) { if (arguments.length === 1) { this._joinFlag = val; return this; } var ret = this._joinFlag || 'inner'; this._joinFlag = 'inner'; return ret; }
javascript
{ "resource": "" }
q10149
_aggregate
train
function _aggregate(method, column) { this._statements.push({ grouping: 'columns', type: 'aggregate', method: method, value: column }); return this; }
javascript
{ "resource": "" }
q10150
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof ExtensibleData)){ return new ExtensibleData(json); } // If the given object is already an instance then just return it. DON'T copy it. if(ExtensibleData.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10151
generateKeyPairs
train
function generateKeyPairs () { AnvilConnectKeys.generateKeyPair(this.sig.pub, this.sig.prv) AnvilConnectKeys.generateKeyPair(this.enc.pub, this.enc.prv) }
javascript
{ "resource": "" }
q10152
generateKeyPair
train
function generateKeyPair (pub, prv) { try { mkdirp.sync(path.dirname(pub)) mkdirp.sync(path.dirname(prv)) childProcess.execFileSync('openssl', [ 'genrsa', '-out', prv, '4096' ], { stdio: 'ignore' }) childProcess.execFileSync('openssl', [ 'rsa', '-pubout', '-in', prv, '-out', pub ], { stdio: 'ignore' }) } catch (e) { throw new Error( 'Failed to generate keys using OpenSSL. Please ensure you have OpenSSL ' + 'installed and configured on your system.' ) } }
javascript
{ "resource": "" }
q10153
loadKeyPairs
train
function loadKeyPairs () { var sig = AnvilConnectKeys.loadKeyPair(this.sig.pub, this.sig.prv, 'sig') var enc = AnvilConnectKeys.loadKeyPair(this.enc.pub, this.enc.prv, 'enc') var jwkKeys = [] jwkKeys.push(sig.jwk.pub, enc.jwk.pub) return { sig: sig.pem, enc: enc.pem, jwks: { keys: jwkKeys } } }
javascript
{ "resource": "" }
q10154
loadKeyPair
train
function loadKeyPair (pub, prv, use) { var pubPEM, prvPEM, pubJWK try { pubPEM = fs.readFileSync(pub).toString('ascii') } catch (e) { throw new Error('Unable to read the public key from ' + pub) } try { prvPEM = fs.readFileSync(prv).toString('ascii') } catch (e) { throw new Error('Unable to read the private key from ' + pub) } try { pubJWK = pemjwk.pem2jwk(pubPEM) } catch (e) { throw new Error('Unable to convert the public key ' + pub + ' to a JWK') } return { pem: { pub: pubPEM, prv: prvPEM }, jwk: { pub: { kty: pubJWK.kty, use: use, alg: 'RS256', n: pubJWK.n, e: pubJWK.e } } } }
javascript
{ "resource": "" }
q10155
generateSetupToken
train
function generateSetupToken (tokenPath) { mkdirp.sync(path.dirname(tokenPath)) var token = crypto.randomBytes(256).toString('hex') try { fs.writeFileSync(tokenPath, token, 'utf8') } catch (e) { throw new Error('Unable to save setup token to ' + tokenPath) } return token }
javascript
{ "resource": "" }
q10156
Transformer
train
function Transformer( file, res ) { stream.Transform.call( this ); this.file = file; this.res = res; this.chunks = []; }
javascript
{ "resource": "" }
q10157
train
function(src, skipBlanck) { var tokens = [], cells, cap; while (src) { cells = []; while (cap = cellDelimitter.exec(src)) { src = src.substring(cap[0].length); cells.push(cap[1]); } if (cells.length || !skipBlanck) tokens.push(cells); // src should start now with \n or \r src = src.substring(1); } return tokens; }
javascript
{ "resource": "" }
q10158
defaultInstructions
train
function defaultInstructions (format) { // start with empty instructions let instructions = emptyInstructions('_defaults', format); // extend with the default recipe, if it exists for the target extension const recipeFilePath = path.join( __dirname, '..', '_defaults', `recipe.${format}.json` ); if (fs.existsSync(recipeFilePath)) { instructions = Object.assign( instructions, JSON.parse(fs.readFileSync(recipeFilePath, 'utf8')) ); } return instructions; }
javascript
{ "resource": "" }
q10159
isTemplate
train
function isTemplate (file, format) { const { prefix, ext } = splitFormat(format); return formatMap[ext] .map(e => (prefix.length ? '.' : '') + prefix + e) .some(e => file.endsWith(e)); }
javascript
{ "resource": "" }
q10160
LinkedInTokenStrategy
train
function LinkedInTokenStrategy(options, verify) { options = options || {}; options.requestTokenURL = options.requestTokenURL || 'https://api.linkedin.com/uas/oauth/requestToken'; options.accessTokenURL = options.accessTokenURL || 'https://api.linkedin.com/uas/oauth/accessToken'; options.userAuthorizationURL = options.userAuthorizationURL || 'https://www.linkedin.com/uas/oauth/authenticate'; options.sessionKey = options.sessionKey || 'oauth:linkedin'; OAuthStrategy.call(this, options, verify); this.name = 'linkedin-token'; this._profileFields = options.profileFields; this._skipExtendedUserProfile = (options.skipExtendedUserProfile === undefined) ? false : options.skipExtendedUserProfile; }
javascript
{ "resource": "" }
q10161
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof PlaceDescription)){ return new PlaceDescription(json); } // If the given object is already an instance then just return it. DON'T copy it. if(PlaceDescription.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10162
createImportError
train
function createImportError(rule) { var url = rule.import ? rule.import.replace(/\r?\n/g, '\\n') : '<no url>'; var err = ['Bad import url: @import ' + url]; if (rule.position) { err.push(' starting at line ' + rule.position.start.line + ' column ' + rule.position.start.column); err.push(' ending at line ' + rule.position.end.line + ' column ' + rule.position.end.column); if (rule.position.source) { err.push(' in ' + rule.position.source); } } return err.join('\n'); }
javascript
{ "resource": "" }
q10163
read
train
function read(file, opts) { var encoding = opts.encoding || 'utf8'; var data = opts.transform(fs.readFileSync(file, encoding)); return css.parse(data, {source: file}).stylesheet; }
javascript
{ "resource": "" }
q10164
train
function (attributes, options) { var AttrCollection = Backgrid.Extension.AdvancedFilter.AttributeFilterCollection; if (attributes.attributeFilters !== undefined && !(attributes.attributeFilters instanceof AttrCollection)) { attributes.attributeFilters = new AttrCollection(attributes.attributeFilters); } return Backbone.Model.prototype.set.call(this, attributes, options); }
javascript
{ "resource": "" }
q10165
train
function (style, exportAsString) { var self = this; var result; switch (style) { case "mongo": case "mongodb": default: var mongoParser = new Backgrid.Extension.AdvancedFilter.FilterParsers.MongoParser(); result = mongoParser.parse(self); if (exportAsString) { result = self.stringifyFilterJson(result); } } return result; }
javascript
{ "resource": "" }
q10166
train
function() { var self = this; self.newFilterCount += 1; if (self.length === 0) { return self.newFilterCount; } else { var newFilterName = self.newFilterName.replace(self.filterNamePartial, ""); var results = self.filter(function(fm) { return fm.get("name").indexOf(newFilterName) === 0; }).map(function(fm) { return fm.get("name"); }); if (_.isArray(results) && results.length > 0) { // Sort results results.sort(); // Get highest count var highestCount = parseInt(results[results.length - 1].replace(newFilterName, "")); if (_.isNaN(highestCount)) { highestCount = self.newFilterCount; } else { highestCount += 1; } } else { highestCount = self.newFilterCount; } return highestCount; } }
javascript
{ "resource": "" }
q10167
train
function (username, password, callback) { var request; var promise; // Preemptively validate username and password if (!username) { throw new Error('Invalid credentials. Missing username.'); } if (!password) { throw new Error('Invalid credentials. Missing password.'); } // Execute the API request for authentication request = this.request({ method: 'post', url: 'users/authenticate', form: { deviceToken: Vineapple.DEVICE_TOKEN || createDeviceToken([ Vineapple.DEVICE_TOKEN_SEED, username, password ].join(':')), username: username, password: password } }); promise = request.then(this.authorize.bind(this)); if (callback) { promise.then(callback.bind(null, null)).fail(callback); } return promise; }
javascript
{ "resource": "" }
q10168
train
function (callback) { var promise = this.request({ method: 'delete', url: 'users/authenticate' }).then(this.authorize.bind(this)); if (callback) { promise.then(callback.bind(null, null)).fail(callback); } return promise; }
javascript
{ "resource": "" }
q10169
train
function (settings) { this.key = settings && settings.key; this.userId = settings && settings.userId; this.username = settings && settings.username; return this; }
javascript
{ "resource": "" }
q10170
generateFileHashes
train
function generateFileHashes(options, files) { if (options.verbose) { _utils.logger.info('Generating files hash...'); } if (files.length === 0) _utils.logger.info('No files found!');else if (options.verbose) { _utils.logger.info('Files found: '); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = files[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var file = _step.value; _utils.logger.info(file); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } var promises = []; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = files[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var file = _step2.value; promises.push((0, _utils.hash)(file)); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return Promise.all(promises); }
javascript
{ "resource": "" }
q10171
makeHttpRequests
train
function makeHttpRequests(options, fileHashes) { if (options.verbose) { _utils.logger.info('Performing HTTP requests...'); } var promises = []; var _iteratorNormalCompletion4 = true; var _didIteratorError4 = false; var _iteratorError4 = undefined; try { for (var _iterator4 = fileHashes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { var fileWithHash = _step4.value; if (fileWithHash.subtitlesPresent) continue; if (options.verbose) { _utils.logger.info('Downloading subtitles for file [%s] with hash [%s]', fileWithHash.file, fileWithHash.hash); } var httpRequest = new _utils.HttpRequest(options, fileWithHash); promises.push(httpRequest.request()); } } catch (err) { _didIteratorError4 = true; _iteratorError4 = err; } finally { try { if (!_iteratorNormalCompletion4 && _iterator4.return) { _iterator4.return(); } } finally { if (_didIteratorError4) { throw _iteratorError4; } } } return Promise.all(promises); }
javascript
{ "resource": "" }
q10172
parseHttpResponse
train
function parseHttpResponse(options, filesWithHash) { if (options.verbose) { _utils.logger.info('Parsing HTTP responses...'); } var promises = []; var _iteratorNormalCompletion5 = true; var _didIteratorError5 = false; var _iteratorError5 = undefined; try { for (var _iterator5 = filesWithHash[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { var fileWithHash = _step5.value; if (fileWithHash.subtitlesPresent) continue; var p = (0, _utils.XML2JSON)(options, fileWithHash).catch(function (err) { if (options.verbose) { _utils.logger.info('Error in HTTP response: ', err.err); } return err.fileWithHash; }); promises.push(p); } } catch (err) { _didIteratorError5 = true; _iteratorError5 = err; } finally { try { if (!_iteratorNormalCompletion5 && _iterator5.return) { _iterator5.return(); } } finally { if (_didIteratorError5) { throw _iteratorError5; } } } return Promise.all(promises); }
javascript
{ "resource": "" }
q10173
parseObjectArrayField
train
function parseObjectArrayField(row, key, value) { var obj_array = []; if (value) { if (value.indexOf(',') !== -1) { obj_array = value.split(','); } else { obj_array.push(value.toString()); }; }; // if (typeof(value) === 'string' && value.indexOf(',') !== -1) { // obj_array = value.split(','); // } else { // obj_array.push(value.toString()); // }; var result = []; obj_array.forEach(function(e) { if (e) { result.push(array2object(e.split(';'))); } }); row[key] = result; }
javascript
{ "resource": "" }
q10174
parseBasicArrayField
train
function parseBasicArrayField(field, key, array) { var basic_array; if (typeof array === "string") { basic_array = array.split(arraySeparator); } else { basic_array = []; basic_array.push(array); }; var result = []; if (isNumberArray(basic_array)) { basic_array.forEach(function(element) { result.push(Number(element)); }); } else if (isBooleanArray(basic_array)) { basic_array.forEach(function(element) { result.push(toBoolean(element)); }); } else { //string array result = basic_array; }; // console.log("basic_array", result + "|||" + cell.value); field[key] = result; }
javascript
{ "resource": "" }
q10175
isBoolean
train
function isBoolean(value) { if (typeof(value) == "undefined") { return false; } if (typeof value === 'boolean') { return true; }; var b = value.toString().trim().toLowerCase(); return b === 'true' || b === 'false'; }
javascript
{ "resource": "" }
q10176
isDateType
train
function isDateType(value) { if (value) { var str = value.toString(); return moment(new Date(value), "YYYY-M-D", true).isValid() || moment(value, "YYYY-M-D H:m:s", true).isValid() || moment(value, "YYYY/M/D H:m:s", true).isValid() || moment(value, "YYYY/M/D", true).isValid(); }; return false; }
javascript
{ "resource": "" }
q10177
domator
train
function domator() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return render(parse(args)); }
javascript
{ "resource": "" }
q10178
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Subject)){ return new Subject(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Subject.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10179
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Document)){ return new Document(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Document.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10180
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof FieldValue)){ return new FieldValue(json); } // If the given object is already an instance then just return it. DON'T copy it. if(FieldValue.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10181
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Name)){ return new Name(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Name.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10182
train
function(handler) { if (typeof accessToken == 'undefined') { var body = { client_id: clientId, client_secret: clientSecret, username: username, password: password, grant_type: 'password' }; if (thisObject.debug) { console.log("Making oAuth call..."); } var options = { url: 'https://app1pub.smappee.net/dev/v1/oauth2/token', headers: { 'Host': 'app1pub.smappee.net' }, form: body }; request.post(options, function (err, httpResponse, body) { if (err) { return console.error('Request failed:', err); } if (thisObject.debug) { console.log('Server responded with:', body); } accessToken = JSON.parse(body); handler(accessToken); }); } else { handler(accessToken) } }
javascript
{ "resource": "" }
q10183
parse
train
function parse (argv, opts, target) { if ('string' === typeof argv) argv = argv.split(rSplit).filter(ignore); if (!opts) opts = {}; opts[don] = true; var parsed = parseArray(argv, opts); opts[don] = false; var through = parsed[don].length ? parseArray(parsed[don], opts) : null; if (!target) target = {}; target.options = parsed; target.commands = parsed[din]; target.input = argv; if (through) { target.through = { options: through, commands: through[din] }; delete through[din]; } delete parsed[din]; delete parsed[don]; return target; function ignore (s) { return s && '' !== s; } }
javascript
{ "resource": "" }
q10184
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Link)){ return new Link(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Link.isInstance(json)){ return json; } // TODO: Enforce spec constraint that requires either an href or a template? this.init(json); }
javascript
{ "resource": "" }
q10185
train
function(category, name, desc) { if(used[name]) return; used[name]= 1; if(!items[category]) items[category] = []; items[category].push({ name: name, desc: desc }); }
javascript
{ "resource": "" }
q10186
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof FamilyView)){ return new FamilyView(json); } // If the given object is already an instance then just return it. DON'T copy it. if(FamilyView.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10187
repeat
train
function repeat(string, times) { var result = "" // Optimized repeat function concatenates concatenated // strings. while (times > 0) { if (times & 1) result += string times >>= 1 string += string } return result }
javascript
{ "resource": "" }
q10188
endpointWithAlias
train
function endpointWithAlias(path, aliasPath) { return function () { endpoint(path)(); endpoint(aliasPath, null, getJSON(path))(); } }
javascript
{ "resource": "" }
q10189
extendingEndpoints
train
function extendingEndpoints() { var segments = Array.prototype.slice.call(arguments, 0); return function () { var path = ''; segments.forEach(function (pathSegment) { path = path + pathSegment; createEndpointFromPath(path); console.log(' registered path %s', path); }); } }
javascript
{ "resource": "" }
q10190
subEndpoints
train
function subEndpoints(prefix, suffixes) { return function () { Array.prototype.forEach.call(suffixes, function (suffix) { var path = prefix + suffix; createEndpointFromPath(path); console.log(' registered path %s', path); }); } }
javascript
{ "resource": "" }
q10191
badRequestEndpoint
train
function badRequestEndpoint(path, query, body) { return function () { body = body || getJSON(path); createEndpointFromObject(path, query, body).status(400); console.log(' registered error path %s', path); } }
javascript
{ "resource": "" }
q10192
createEndpointFromPath
train
function createEndpointFromPath(path, query, filePath) { filePath = filePath || path; return createEndpointFromObject(path, query, getJSON(filePath)); }
javascript
{ "resource": "" }
q10193
createEndpointFromObject
train
function createEndpointFromObject(path, query, body) { // OPTIONS gives server permission to use CORS server.createRoute({ request: { url: path, query: query || {}, method: 'options', }, response: { code: 200, delay: config.latency, body: {}, headers: { 'Access-Control-Allow-Origin': config.allowOrigin, // allow several methods since some endpoints are writable 'Access-Control-Allow-Methods': 'GET, PUT, POST', 'Access-Control-Allow-Credentials': 'true' } } }); return server.get(path) .query(query) .responseHeaders({ 'Access-Control-Allow-Origin': config.allowOrigin, 'Access-Control-Allow-Methods': 'GET, PUT, POST', 'Access-Control-Allow-Credentials': 'true' }) .body(body) .delay(config.latency); }
javascript
{ "resource": "" }
q10194
train
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof OnlineAccount)){ return new OnlineAccount(json); } // If the given object is already an instance then just return it. DON'T copy it. if(OnlineAccount.isInstance(json)){ return json; } this.init(json); }
javascript
{ "resource": "" }
q10195
toSQL
train
function toSQL(method) { method = method || this.method; var val = this[method](); var defaults = { method: method, options: assign({}, this.options), bindings: this.formatter.bindings }; if (typeof val === 'string') { val = { sql: val }; } if (method === 'select' && this.single.as) { defaults.as = this.single.as; } var out = assign(defaults, val); debug(out); return out; }
javascript
{ "resource": "" }
q10196
select
train
function select() { var i = -1, statements = []; while (++i < components.length) { statements.push(this[components[i]](this)); } return statements.filter(function (item) { return item; }).join(' '); }
javascript
{ "resource": "" }
q10197
update
train
function update() { var updateData = this._prepUpdate(this.single.update); var wheres = this.where(); var returning = this.single.returning; return { sql: 'update ' + this.tableName + ' set ' + updateData.join(', ') + (wheres ? ' ' + wheres : '') + this._returning(returning), returning: returning }; }
javascript
{ "resource": "" }
q10198
_columns
train
function _columns() { var distinct = false; if (this.onlyUnions()) { return ''; } var columns = this.grouped.columns || []; var i = -1, sql = []; if (columns) { while (++i < columns.length) { var stmt = columns[i]; if (stmt.distinct) { distinct = true; } if (stmt.type === 'aggregate') { sql.push(this.aggregate(stmt)); } else if (stmt.value && stmt.value.length > 0) { sql.push(this.formatter.columnize(stmt.value)); } } } if (sql.length === 0) { sql = ['*']; } return 'select ' + (distinct ? 'distinct ' : '') + sql.join(', ') + (this.tableName ? ' from ' + this.tableName : ''); }
javascript
{ "resource": "" }
q10199
_join
train
function _join() { var sql = '', i = -1, joins = this.grouped.join; if (!joins) { return ''; } while (++i < joins.length) { var join = joins[i]; if (i > 0) { sql += ' '; } if (join.joinType === 'raw') { sql += this.formatter.unwrapRaw(join.table); } else { sql += join.joinType + ' join ' + this.formatter.wrap(join.table); var ii = -1; while (++ii < join.clauses.length) { var clause = join.clauses[ii]; sql += ' ' + (ii > 0 ? clause[0] : clause[1]) + ' '; sql += this.formatter.wrap(clause[2]); if (clause[3]) { sql += ' ' + this.formatter.operator(clause[3]); } if (clause[4]) { sql += ' ' + this.formatter.wrap(clause[4]); } } } } return sql; }
javascript
{ "resource": "" }