_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q32300
train
function() { const query = {clientId}; var body = sg.extend({partnerId, version, sessionId}, {rsvr}); self.POST('hq', '/clientStart', query, body, function(err, config) { //console.log('clientStart-object', query, body, err, config); if (sg.ok(err, config)) { self.config = sg.deepCopy(config); _.each(self.config.upstreams, (upstream, prj_app) => { self.upstreams[prj_app] = upstream; }); if (sg.verbosity() > 2) { _.each(self.upstreams, (upstream, prj_app) => { console.log(`Using upstream: ${sg.lpad(prj_app, 20)} ->> ${upstream}`); }); } ctor_callback(err, self.config); } }); }
javascript
{ "resource": "" }
q32301
flatten
train
function flatten(array) { return array.reduce(function (a, b) { return isArray(b) ? a.concat(flatten(b)) : a.concat(b); }, []); }
javascript
{ "resource": "" }
q32302
handleConnection
train
function handleConnection(socket) { // server 'connect' socket.setEncoding('utf-8') socket.on('data', requestResponder) function requestResponder(data) { socket.end(String(process.pid)) self.emit('data', data) } }
javascript
{ "resource": "" }
q32303
getVariable
train
function getVariable(variable) { if ( cached.data == null ) { getData(); } if (variable.toUpperCase() in cached.data ) { return cached.data[variable.toUpperCase()]; } else if (variable in cached.data) { return cached.data[variable]; } }
javascript
{ "resource": "" }
q32304
resolve
train
function resolve(moduleMeta, options) { function setPath(path) { return { path: path }; } return resolvePath(moduleMeta, options).then(setPath, log2console); }
javascript
{ "resource": "" }
q32305
resolvePath
train
function resolvePath(moduleMeta, options) { var parentPath = getParentPath(moduleMeta, options); var filePath = path.resolve(path.dirname(options.baseUrl), moduleMeta.name); if (fs.existsSync(filePath)) { return Promise.resolve(filePath); } return new Promise(function(resolve, reject) { browserResolve(moduleMeta.name, {filename: parentPath}, function(err, path) { if (err) { reject(err); } else { resolve(path); } }); }); }
javascript
{ "resource": "" }
q32306
getParentPath
train
function getParentPath(moduleMeta, options) { var referrer = moduleMeta.referrer; return (referrer && moduleMeta !== referrer) ? referrer.path : options.baseUrl; }
javascript
{ "resource": "" }
q32307
train
function(point) { var latitude = point.hasOwnProperty('lat') ? 'lat' : 'latitude'; var longitude = (point.hasOwnProperty('lng') ? 'lng' : false) || (point.hasOwnProperty('long') ? 'long' : false) || 'longitude'; var elevation = (point.hasOwnProperty('alt') ? 'alt' : false) || (point.hasOwnProperty('altitude') ? 'altitude' : false) || (point.hasOwnProperty('elev') ? 'elev' : false) || 'elevation'; return { latitude: latitude, longitude: longitude, elevation: elevation }; }
javascript
{ "resource": "" }
q32308
train
function(start, end, accuracy) { var keys = geolib.getKeys(start); var latitude = keys.latitude; var longitude = keys.longitude; accuracy = Math.floor(accuracy) || 1; var coord1 = {}, coord2 = {}; coord1[latitude] = parseFloat(geolib.useDecimal(start[latitude])).toRad(); coord1[longitude] = parseFloat(geolib.useDecimal(start[longitude])).toRad(); coord2[latitude] = parseFloat(geolib.useDecimal(end[latitude])).toRad(); coord2[longitude] = parseFloat(geolib.useDecimal(end[longitude])).toRad(); var distance = Math.round( Math.acos( Math.sin( coord2[latitude] ) * Math.sin( coord1[latitude] ) + Math.cos( coord2[latitude] ) * Math.cos( coord1[latitude] ) * Math.cos( coord1[longitude] - coord2[longitude] ) ) * radius ); return geolib.distance = Math.floor(Math.round(distance/accuracy)*accuracy); }
javascript
{ "resource": "" }
q32309
train
function(coords) { if (!coords.length) { return false; } var keys = geolib.getKeys(coords[0]); var latitude = keys.latitude; var longitude = keys.longitude; var max = function( array ){ return Math.max.apply( Math, array ); }; var min = function( array ){ return Math.min.apply( Math, array ); }; var lat, lng, splitCoords = {lat: [], lng: []}; for(var coord in coords) { splitCoords.lat.push(geolib.useDecimal(coords[coord][latitude])); splitCoords.lng.push(geolib.useDecimal(coords[coord][longitude])); } var minLat = min(splitCoords.lat); var minLng = min(splitCoords.lng); var maxLat = max(splitCoords.lat); var maxLng = max(splitCoords.lng); lat = ((minLat + maxLat)/2).toFixed(6); lng = ((minLng + maxLng)/2).toFixed(6); // distance from the deepest left to the highest right point (diagonal distance) var distance = geolib.convertUnit('km', geolib.getDistance({lat:minLat, lng:minLng}, {lat:maxLat, lng:maxLng})); return {"latitude": lat, "longitude": lng, "distance": distance}; }
javascript
{ "resource": "" }
q32310
train
function(latlng, coords) { var keys = geolib.getKeys(latlng); var latitude = keys.latitude; var longitude = keys.longitude; for(var c = false, i = -1, l = coords.length, j = l - 1; ++i < l; j = i) { ( (coords[i][longitude] <= latlng[longitude] && latlng[longitude] < coords[j][longitude]) || (coords[j][longitude] <= latlng[longitude] && latlng[longitude] < coords[i][longitude]) ) && (latlng[latitude] < (coords[j][latitude] - coords[i][latitude]) * (latlng[longitude] - coords[i][longitude]) / (coords[j][longitude] - coords[i][longitude]) + coords[i][latitude]) && (c = !c); } return c; }
javascript
{ "resource": "" }
q32311
train
function(originLL, destLL) { var keys = geolib.getKeys(originLL); var latitude = keys.latitude; var longitude = keys.longitude; destLL[latitude] = geolib.useDecimal(destLL[latitude]); destLL[longitude] = geolib.useDecimal(destLL[longitude]); originLL[latitude] = geolib.useDecimal(originLL[latitude]); originLL[longitude] = geolib.useDecimal(originLL[longitude]); var bearing = ( ( Math.atan2( Math.sin( destLL[longitude].toRad() - originLL[longitude].toRad() ) * Math.cos( destLL[latitude].toRad() ), Math.cos( originLL[latitude].toRad() ) * Math.sin( destLL[latitude].toRad() ) - Math.sin( originLL[latitude].toRad() ) * Math.cos( destLL[latitude].toRad() ) * Math.cos( destLL[longitude].toRad() - originLL[longitude].toRad() ) ) ).toDeg() + 360 ) % 360; return bearing; }
javascript
{ "resource": "" }
q32312
train
function(originLL, destLL, bearingMode) { var direction; if(bearingMode == 'circle') { // use great circle bearing var bearing = geolib.getBearing(originLL, destLL); } else { // default is rhumb line bearing var bearing = geolib.getRhumbLineBearing(originLL, destLL); } switch(Math.round(bearing/22.5)) { case 1: direction = {exact: "NNE", rough: "N"}; break; case 2: direction = {exact: "NE", rough: "N"} break; case 3: direction = {exact: "ENE", rough: "E"} break; case 4: direction = {exact: "E", rough: "E"} break; case 5: direction = {exact: "ESE", rough: "E"} break; case 6: direction = {exact: "SE", rough: "E"} break; case 7: direction = {exact: "SSE", rough: "S"} break; case 8: direction = {exact: "S", rough: "S"} break; case 9: direction = {exact: "SSW", rough: "S"} break; case 10: direction = {exact: "SW", rough: "S"} break; case 11: direction = {exact: "WSW", rough: "W"} break; case 12: direction = {exact: "W", rough: "W"} break; case 13: direction = {exact: "WNW", rough: "W"} break; case 14: direction = {exact: "NW", rough: "W"} break; case 15: direction = {exact: "NNW", rough: "N"} break; default: direction = {exact: "N", rough: "N"} } return direction; }
javascript
{ "resource": "" }
q32313
train
function(latlng, coords) { var keys = geolib.getKeys(latlng); var latitude = keys.latitude; var longitude = keys.longitude; var coordsArray = []; for(var coord in coords) { var d = geolib.getDistance(latlng, coords[coord]); coordsArray.push({key: coord, latitude: coords[coord][latitude], longitude: coords[coord][longitude], distance: d}); } return coordsArray.sort(function(a, b) { return a.distance - b.distance; }); }
javascript
{ "resource": "" }
q32314
train
function(latlng, coords, offset) { offset = offset || 0; var ordered = geolib.orderByDistance(latlng, coords); return ordered[offset]; }
javascript
{ "resource": "" }
q32315
train
function(coords) { var dist = 0, last; for (var i = 0, l = coords.length; i < l; ++i) { if(last) { dist += geolib.getDistance(coords[i], last); } last = coords[i]; } return dist; }
javascript
{ "resource": "" }
q32316
train
function(unit, distance, round) { if(distance == 0 || typeof distance == 'undefined') { if(geolib.distance == 0) { // throw 'No distance given.'; return 0; } else { distance = geolib.distance; } } unit = unit || 'm'; round = (null == round ? 4 : round); switch(unit) { case 'm': // Meter return geolib.round(distance, round); break; case 'km': // Kilometer return geolib.round(distance / 1000, round); break; case 'cm': // Centimeter return geolib.round(distance * 100, round); break; case 'mm': // Millimeter return geolib.round(distance * 1000, round); break; case 'mi': // Miles return geolib.round(distance * (1 / 1609.344), round); break; case 'sm': // Seamiles return geolib.round(distance * (1 / 1852.216), round); break; case 'ft': // Feet return geolib.round(distance * (100 / 30.48), round); break; case 'in': // Inch return geolib.round(distance * 100 / 2.54, round); break; case 'yd': // Yards return geolib.round(distance * (1 / 0.9144), round); break; } return distance; }
javascript
{ "resource": "" }
q32317
train
function(value) { value = value.toString().replace(/\s*/, ''); // looks silly but works as expected // checks if value is in decimal format if (!isNaN(parseFloat(value)) && parseFloat(value).toString() == value) { return parseFloat(value); // checks if it's sexagesimal format (HHH° MM' SS" (NESW)) } else if(geolib.isSexagesimal(value) == true) { return parseFloat(geolib.sexagesimal2decimal(value)); } else { throw 'Unknown format.'; } }
javascript
{ "resource": "" }
q32318
train
function(dec) { if (dec in geolib.sexagesimal) { return geolib.sexagesimal[dec]; } var tmp = dec.toString().split('.'); var deg = Math.abs(tmp[0]); var min = ('0.' + tmp[1])*60; var sec = min.toString().split('.'); min = Math.floor(min); sec = (('0.' + sec[1]) * 60).toFixed(2); geolib.sexagesimal[dec] = (deg + '° ' + min + "' " + sec + '"'); return geolib.sexagesimal[dec]; }
javascript
{ "resource": "" }
q32319
train
function(sexagesimal) { if (sexagesimal in geolib.decimal) { return geolib.decimal[sexagesimal]; } var regEx = new RegExp(sexagesimalPattern); var data = regEx.exec(sexagesimal); if(data) { var min = parseFloat(data[2]/60); var sec = parseFloat(data[4]/3600) || 0; } var dec = ((parseFloat(data[1]) + min + sec)).toFixed(8); // South and West are negative decimals dec = (data[7] == 'S' || data[7] == 'W') ? dec * -1 : dec; geolib.decimal[sexagesimal] = dec; return dec; }
javascript
{ "resource": "" }
q32320
train
function (jsonObject, path, force, value) { if (!path) { return; } var newValue, obj; obj = jsonObject || {}; path.trim().split('.').some(function (key, index, array) { if (!key && key !== 0) { return false; } newValue = obj[key]; if (index == array.length - 1) { if (value === undefined) { value = {}; } obj[key] = value; return true; } if (!newValue && newValue != 0 && index <= (array.length - 1)) { if (force) { obj[key] = {}; } else { return true; } } obj = obj[key]; }); return jsonObject; }
javascript
{ "resource": "" }
q32321
gatherEntityFilters
train
function gatherEntityFilters(context, expression) { let ii, len, bf, result, obj; let filter = expression[0]; result = EntityFilter.create(); switch (filter) { case ANY: case ANY_FILTER: case ALL: case ALL_FILTER: case NONE: case NONE_FILTER: case INCLUDE: case INCLUDE_FILTER: if (expression[1] === ROOT) { result.add(ROOT); } else { obj = context.valueOf(expression[1], true); if (!obj) { if (filter == ALL_FILTER) { result.add(ROOT); return; } return null; } bf = context.componentsToBitfield(context, obj); // filter = expression[0]; switch (filter) { case ALL_FILTER: filter = ALL; break; case ANY_FILTER: filter = ANY; break; case NONE_FILTER: filter = NONE; break; case INCLUDE_FILTER: filter = INCLUDE; break; default: break; } // console.log('CONVERTED TO BF', filter, bf.toString(), bf.toJSON() ); result.add(filter, bf); } break; case AND: expression = expression.slice(1); // _.rest(expression); for (ii = 0, len = expression.length; ii < len; ii++) { obj = gatherEntityFilters(context, expression[ii]); if (!obj) { return null; } result.filters = result.filters.concat(obj.filters); } break; default: return null; } return result; }
javascript
{ "resource": "" }
q32322
initialize
train
function initialize() { var creditcard; // [square] @import "creditcard/index.js" this.lib = creditcard; // // Create references to elements. // this.number = this.$('input[name="full_number"]'); this.cvv = this.$('input[name="cvv"]'); this.year = this.$('select[name="expiration_year"]'); this.month = this.$('select[name="expiration_month"]'); this.card = this.$('.card'); // // Is validation required? // this.validate = !!this.$el.get('validate'); }
javascript
{ "resource": "" }
q32323
digit
train
function digit(event) { var element = event.element , code = event.keyCode || event.which , result; result = (code >= 48 && code <= 57) || code === 8 || code === 46; if (!result) event.preventDefault(); return { allowed: result, code: code, removal: code === 8 || code === 48 }; }
javascript
{ "resource": "" }
q32324
date
train
function date(event) { var result = this.lib.expiry(this.month.get('value'), this.year.get('value')) , className = result ? 'valid' : 'invalid'; // // Update both select boxes. // this.month.removeClass('invalid').addClass(className); this.year.removeClass('invalid').addClass(className); }
javascript
{ "resource": "" }
q32325
number
train
function number(event) { var element = event.element , value = element.value , key = this.digit(event) , valid; // // Input must be numerical. // if (!key.allowed && event.type !== 'blur') return; // // Always format if the event is of type blur. This will ensure the input // box does not stay red on blur if formatted value is valid. // if (event.type === 'blur') this.number.set('value', this.lib.format(value)); // // Check if the number is valid. // if (value.replace(/\D/g, '').length >= 16 || key.removal) { valid = this.lib.validate(value); // // Show card type or hide if invalid. // this.card[valid ? 'removeClass' : 'addClass']('gone'); this.card.find('strong').set('innerHTML', this.lib.cardscheme(value)); if (this.validate) { // // Check against testnumbers in production mode. Valid should be checked // as well, otherwise an incomplete credit card number would be valid. // if (this.production) { valid = valid && !~this.lib.testnumbers.indexOf(+value.replace(/\D/g, '')); } // // Update the styling of the input. // this.number.set('className', valid ? 'valid' : 'invalid'); } } // // Add spaces for each block of 4 characters. // this.number.set('value', this.lib.format(value)); }
javascript
{ "resource": "" }
q32326
cvv
train
function cvv(event) { var element = event.element , value = element.value , key = this.digit(event); // // Input must be numerical. // if (!key.allowed && event.type !== 'blur') return; // // Check if the number is valid. // if (this.validate && (value.length >= 3 || key.removal)) { this.cvv.set( 'className', this.lib.parse(this.number.get('value')).cvv === value.length ? 'valid' : 'invalid' ); } }
javascript
{ "resource": "" }
q32327
removeItem
train
function removeItem(key) { delete storage[key]; window.name = qs.stringify(storage, prefix); windowStorage.length--; }
javascript
{ "resource": "" }
q32328
train
function(input, options) { this.preprocess(input, options); for (var inputIndex=0; inputIndex < this.inputList.length; ++inputIndex) { this.input = this.inputList[inputIndex][1][1].replace(/\\/g,'\\\\'); // first stage : configurable crusher var output = this.findRedundancies(options); this.inputList[inputIndex].push(output); // second stage : convert token string to regexp output = packer.packToRegexpCharClass(options); this.inputList[inputIndex].push(output); // third stage : try a negated regexp instead output = packer.packToNegatedRegexpCharClass(); this.inputList[inputIndex].push(output); } }
javascript
{ "resource": "" }
q32329
train
function(matchIndex) { var oldToken = this.matchesLookup[matchIndex].token; for (var j=0;j<this.matchesLookup.length;++j) { this.matchesLookup[j].usedBy = this.matchesLookup[j].usedBy.split(oldToken).join(""); } this.matchesLookup[matchIndex].cleared=true; }
javascript
{ "resource": "" }
q32330
getTag
train
function getTag(val) { const tag = Object.prototype.toString.call(val).slice(8, -1) if (basicTypes.includes(tag.toLowerCase())) { return tag.toLowerCase() } return tag }
javascript
{ "resource": "" }
q32331
Question
train
function Question(name, message, options) { if (utils.isObject(name)) { options = utils.merge({}, message, name); message = options.message; name = options.name; } if (utils.isObject(message)) { options = utils.merge({}, options, message); message = options.message; } utils.define(this, 'isQuestion', true); utils.define(this, 'cache', {}); this.options = options || {}; this.type = this.options.type || 'input'; this.message = message || this.options.message; this.name = name || this.options.name; if (!this.message) { this.message = this.name; } utils.merge(this, this.options); createNext(this); }
javascript
{ "resource": "" }
q32332
createNext
train
function createNext(question) { if (!question.options.next) return; if (typeof question.options.next === 'function') { question.next = function() { question.options.next.apply(question, arguments); }; return; } if (typeof question.options.next === 'string') { question.type = 'confirm'; question.next = function(answer, questions, answers, next) { if (answer === true) { questions.ask(question.options.next, next); } else { next(null, answers); } }; } }
javascript
{ "resource": "" }
q32333
_parseConfig
train
function _parseConfig(config) { const _config = Object.assign({}, { filename:module.parent.filename, scope: settings.get('scope') || {}, includeGlobals:false, proxyGlobal:true, useSandbox: settings.get('useSandbox') || false, workspace: [workspaces.DEFAULT_WORKSPACE], squashErrors: !!(config.resolver || {}).squashErrors }, config); if (isBuffer(_config.content)) _config.content = _config.content.toString(); return _config; }
javascript
{ "resource": "" }
q32334
_createOptions
train
function _createOptions(config) { return { filename:config.filename, displayErrors:true, timeout: config.timeout || 20*1000 }; }
javascript
{ "resource": "" }
q32335
_createScript
train
function _createScript(config, options, scope={}) { if (!isString(config.content)) return config.content; const stringScript = wrap(config.content.replace(/^\#\!.*/, ''), scope); try { return new vm.Script(stringScript, options); } catch(error) { // These are not squashed as not evaluation errors but something else. if (_runError(error, module)) throw error; } }
javascript
{ "resource": "" }
q32336
wrap
train
function wrap(content, scope) { const scopeParams = Object.keys(scope).join(','); const comma = ((scopeParams !== '')?', ':''); return `(function (exports, require, module, __filename, __dirname${comma}${scopeParams}) { ${content} });` }
javascript
{ "resource": "" }
q32337
_getScopeParams
train
function _getScopeParams(config, module, scope={}) { return [ module.exports, module.require, module, module.filename, config.basedir || path.dirname(module.filename), ...values(scope) ]; }
javascript
{ "resource": "" }
q32338
_runError
train
function _runError(error, module) { const _error = new emitter.Error({ target:module.filename, source:(module.parent || module).filename, error }); module.exports = _error; emitter.emit('error', _error); return (!!_error.ignore || (_error.ignore && isFunction(_error.ignore) && _error.ignore())); }
javascript
{ "resource": "" }
q32339
_runScript
train
function _runScript(config, options) { const useSandbox = ((isFunction(config.useSandbox)) ? _config.useSandbox(_config) || false : config.useSandbox); const module = new Module(config); const scopeParams = _getScopeParams(config, module, config.scope); const script = _createScript(config, options, config.scope); try { if (useSandbox) { script.runInContext(_createSandbox(config), options)(...scopeParams); } else { script.runInThisContext(options)(...scopeParams); } } catch(error) { if (config.squashErrors) cache.delete(options.filename); if (!config.squashErrors) { if (_runError(error, module)) throw error; } else { throw error; } } return module; }
javascript
{ "resource": "" }
q32340
evaluate
train
function evaluate(config) { const _config = _parseConfig(config); const options = _createOptions(_config); return _runScript(_config, options); }
javascript
{ "resource": "" }
q32341
hasFileType
train
function hasFileType(file, fileExt) { file = path.basename(file); var ext = path.extname(file); do { if (ext === fileExt) { return true; } else { file = path.basename(file, ext); ext = path.extname(file); } } while (ext); return false; }
javascript
{ "resource": "" }
q32342
train
function (contents, wfCb) { async.eachSeries(contents.split('\n'), function (line, eachCb) { setImmediateCompat(function() { if (line && line.indexOf('#') !== 0) { var directive = line.match(DIRECTIVE_REGEX); if (!directive) { eachCb(new Error('Bad directive in manifest file: ' + line)); } else { var cmd = directive[1]; var file = directive[2]; if (self[cmd]) { self[cmd](manifest, assetBundle, file, eachCb); } else { eachCb(new Error('Bad directive in manifest file: ' + line)); } } } else { eachCb(); } }); }, wfCb); }
javascript
{ "resource": "" }
q32343
Namy
train
function Namy(input, callback) { if (/package.json$/.test(input)) { return ReadJson(input, function (err, data) { if (err) { return callback(err); } if (!data.main) { return callback(new Error("Cannot find the main field in package.json")); } Namy(data.main, callback); }); } var path = null , isInCache = null , res = null , name = null ; try { path = require.resolve(input) isInCache = !!require.cache[path] // TODO Make this async res = require(input) } catch (err) { return callback(err); } if (typeof res === "function") { name = res.name || null; } else { return callback(new Error("The module does not export a function.")); } if (!isInCache) { delete require.cache[path]; } if (!name) { return callback(new Error("The function does not have a name.")); } callback(null, name); }
javascript
{ "resource": "" }
q32344
train
function(srcArray, dest, options) { if (!srcArray.length) { // both no data, don't add to filesArray. (Don't return undefined.) return typeof dest === 'string' && fileUpdates.isNew(dest, options); // But filesArray isn't usable for 'files', 'cause Grunt doesn't support empty src. } else if (!dest) { return srcArray.some(function(src) { return fileUpdates.isNew(src, options); }); } else if (srcArray.length === 1 && path.resolve(srcArray[0]) === path.resolve(dest)) { return fileUpdates.isNew(dest, options); } // both files if (srcArray.length === 1) { return fileUpdates.compare(srcArray[0], dest) === 1; } else { // New file exists. return srcArray.some(function(src) { return fileUpdates.compare(src, dest) === 1; }); } }
javascript
{ "resource": "" }
q32345
train
function(filepath) { return grunt.file.exists(filepath) ? Math.floor(fs.statSync(filepath).mtime.getTime() / 1000) : 0; // mtime before epochtime isn't supported. }
javascript
{ "resource": "" }
q32346
train
function(filepath, options) { // options.mtimeOffset: 3 default if (!fileUpdates.offset) { fileUpdates.offset = options.mtimeOffset || 3; } if (!fileUpdates.storeData) { // Initialize data. if (grunt.file.exists(fileUpdates.storeDataPath)) { fileUpdates.storeData = grunt.file.readJSON(fileUpdates.storeDataPath); } if (!fileUpdates.storeData) { fileUpdates.storeData = {}; } // Run the task that finalize data. grunt.task.run('taskHelperFin'); // The task starts after current target. NOT task. // (i.e. every target, and before other tasks) // Can't specify time after all tasks? // Grunt 0.5 may support a event that all tasks finish. // https://github.com/gruntjs/grunt/wiki/Roadmap } filepath = path.resolve(filepath); // full-path if (!(filepath in fileUpdates.storeData)) { fileUpdates.storeData[filepath] = 0; } return fileUpdates.storeData[filepath]; }
javascript
{ "resource": "" }
q32347
createSymlinks
train
function createSymlinks(symlinks) { let path = require('path'); let fs = require('fs'); let del = require('del'); del.sync(symlinks.map(sl => sl.dest)); try { symlinks.forEach(sl => { let src = path.resolve(sl.src); fs.symlinkSync(src, sl.dest); }); } catch (err) { console.error(err); if (err.code === 'EPERM' && err.errno === -4048) { console.error('***************************'); console.error('*** PLEASE RUN AS ADMIN ***'); console.error('***************************'); } } }
javascript
{ "resource": "" }
q32348
crawlDirectoryWithFS
train
function crawlDirectoryWithFS(parent, sync) { return fsCmd('readdir', sync, parent).then(function (things) { return Q.all(things.map(function (file) { file = path.join(parent, file); return Q.all([file, fsCmd('stat', sync, file)]); })); }).then(function (stats) { return Q.all(stats.map(function (args) { var file = args[0], stat = args[1]; if (stat.isDirectory()) { return crawlDirectoryWithFS(file, sync); } return file; })); }).then(function (grouped) { return [].concat.apply([], grouped); }); }
javascript
{ "resource": "" }
q32349
crawlDirectory
train
function crawlDirectory(parent, sync) { if (sync) { return crawlDirectory(parent, sync); } /* Use `find` if available, because it's fast! */ return exec('find ' + parent + ' -not -type d').spread(function (stdin) { return stdin.split('\n').filter(function (file) { return !!file; }); }).fail(function () { return crawlDirectoryWithFS(parent, sync); }); }
javascript
{ "resource": "" }
q32350
train
function(el, value) { !conbo.isEmpty(value) ? el.classList.add('cb-hide') : el.classList.remove('cb-hide'); }
javascript
{ "resource": "" }
q32351
train
function(el, value, options, styleName) { if (!styleName) { conbo.warn('cb-style attributes must specify one or more styles in the format cb-style="myProperty:style-name"'); } styleName = conbo.toCamelCase(styleName); el.style[styleName] = value; }
javascript
{ "resource": "" }
q32352
train
function(el, value, options) { var view = options.view; var states = value.split(' '); var stateChangeHandler = (function() { this.cbInclude(el, states.indexOf(view.currentState) != -1); }).bind(this); view.addEventListener('change:currentState', stateChangeHandler, this); stateChangeHandler.call(this); }
javascript
{ "resource": "" }
q32353
train
function(el, value, options) { var view = options.view; var states = value.split(' '); var stateChangeHandler = function() { this.cbExclude(el, states.indexOf(view.currentState) != -1); }; view.addEventListener('change:currentState', stateChangeHandler, this); stateChangeHandler.call(this); }
javascript
{ "resource": "" }
q32354
train
function(el) { if (el.tagName == 'A') { el.onclick = function(event) { window.location = el.href; event.preventDefault(); return false; }; } }
javascript
{ "resource": "" }
q32355
train
function(el, validator) { var validateFunction; switch (true) { case conbo.isFunction(validator): { validateFunction = validator; break; } case conbo.isString(validator): { validator = new RegExp(validator); } case conbo.isRegExp(validator): { validateFunction = function(value) { return validator.test(value); }; break; } } if (!conbo.isFunction(validateFunction)) { conbo.warn(validator+' cannot be used with cb-validate'); return; } var ep = __ep(el); var form = ep.closest('form'); var getClasses = function(regEx) { return function (classes) { return classes.split(/\s+/).filter(function(el) { return regEx.test(el); }) .join(' '); }; }; var validate = function() { // Form item var value = el.value || el.innerHTML , result = validateFunction(value) , valid = (result === true) , classes = [] ; classes.push(valid ? 'cb-valid' : 'cb-invalid'); if (conbo.isString(result)) { classes.push('cb-invalid-'+result); } ep.removeClass('cb-valid cb-invalid') .removeClass(getClasses(/^cb-invalid-/)) .addClass(classes.join(' ')) ; // Form if (form) { var fp = __ep(form); fp.removeClass('cb-valid cb-invalid') .removeClass(getClasses(/^cb-invalid-/)) ; if (valid) { valid = !form.querySelector('.cb-invalid'); if (valid) { conbo.toArray(form.querySelectorAll('[required]')).forEach(function(rEl) { if (!String(rEl.value || rEl.innerHTML).trim()) { valid = false; return false; } }); } } fp.addClass(valid ? 'cb-valid' : 'cb-invalid'); } }; ep.addEventListener('change input blur', validate); }
javascript
{ "resource": "" }
q32356
train
function(el, value) { // TODO Restrict to text input fields? if (el.cbRestrict) { el.removeEventListener('keypress', el.cbRestrict); } el.cbRestrict = function(event) { if (event.ctrlKey) { return; } var code = event.keyCode || event.which; var char = event.key || String.fromCharCode(code); var regExp = value; if (!conbo.isRegExp(regExp)) { regExp = new RegExp('['+regExp+']', 'g'); } if (!char.match(regExp)) { event.preventDefault(); } }; el.addEventListener('keypress', el.cbRestrict); }
javascript
{ "resource": "" }
q32357
train
function(el, value) { // TODO Restrict to text input fields? if (el.cbMaxChars) { el.removeEventListener('keypress', el.cbMaxChars); } el.cbMaxChars = function(event) { if ((el.value || el.innerHTML).length >= value) { event.preventDefault(); } }; el.addEventListener('keypress', el.cbMaxChars); }
javascript
{ "resource": "" }
q32358
Policy
train
function Policy(name, Transport, options) { var policy = this; if ('string' !== typeof name) { options = Transport; Transport = name; name = undefined; } if ('function' !== typeof Transport) { throw new Error('Transport should be a constructor.'); } policy.name = (name || Transport.prototype.name).toLowerCase(); policy.Transport = Transport; policy.options = options || {}; policy.id = 0; }
javascript
{ "resource": "" }
q32359
Strategy
train
function Strategy(transports, options) { var strategy = this; if (!(strategy instanceof Strategy)) return new Strategy(transports, options); if (Object.prototype.toString.call(transports) !== '[object Array]') { options = transports; transports = []; } strategy.transports = []; // List of active transports. strategy.transport = 0; // Current selected transport id. strategy.length = 0; // Amount of transports available. strategy.id = 0; // ID generation pool. for (var i = 0; i < transports.length; i++) { strategy.push(transports[i]); } }
javascript
{ "resource": "" }
q32360
Segment
train
function Segment(props) { var segmentStyle = props.segmentStyle; var fillStyle = props.fillStyle; var commonStyle = { position: 'absolute' }; return React.createElement( 'div', { style: _extends({}, commonStyle, segmentStyle) }, React.createElement('div', { style: _extends({}, commonStyle, fillStyle) }) ); }
javascript
{ "resource": "" }
q32361
load_followers_priodically
train
function load_followers_priodically() { try{ twimap.followersAsync(last_check, function(result) { if(typeof result != "undefined" && result.length >=1){ //save it in our variable _followers_list = result; last_check = now(); msg_followers_thanks(); } },function (err){ // I command you to stay silent reset_values(); }); }catch(e){ //still... reset_values(); console.log(e); } }
javascript
{ "resource": "" }
q32362
msg_followers_thanks
train
function msg_followers_thanks(){ //move cursor _current_index++; //if there is no followers OR finished messaging followers stop if(_current_index >= _followers_list.length ){ _current_index = -1; _followe_list = null; return; } //otherwise get user name from twitter twit_cli.get("users/show",{screen_name:_followers_list[_current_index]}, function (err,dt){ //clean up the name var dude = filter_name(dt.name); //message the user twit_cli.post("direct_messages/new" , {screen_name:_followers_list[_current_index],text:random_msg(dude)}, function (err,dt){ if(!err) console.log("done..."); //go for another round msg_followers_thanks(); }); }); }
javascript
{ "resource": "" }
q32363
filter_name
train
function filter_name(name){ if ( typeof name == "undefined" || name=="" || name==null) name = "my friend"; if(name.length > 40 ) name = name.substr(0,40); return name; }
javascript
{ "resource": "" }
q32364
random_msg
train
function random_msg(name){ name = filter_name(name); return util.format(thanks_temp[Math.floor(Math.random()*10)%(thanks_temp.length-1)] , name); }
javascript
{ "resource": "" }
q32365
train
function(next) { var source = config.getSource(asset.source); async.parallel([ getFromSource.bind(null, source, asset, fromVersion, config), getFromSource.bind(null, source, asset, toVersion, config) ], next); }
javascript
{ "resource": "" }
q32366
train
function(files, next) { var fromFile = files[0], toFile = files[1]; differ(id, fromFile, toFile, next); }
javascript
{ "resource": "" }
q32367
train
function(patch, next) { var patchObj = toPatchObject(id, fromVersion, toVersion, patch); //cache it cacheCb(patchObj); next(null, patchObj); }
javascript
{ "resource": "" }
q32368
combinedData
train
function combinedData(flairs, presenters) { let result = [] for (let [ flairPattern, normalizedFlair ] of flairs) { for (let [ presenterPattern, presenter ] of presenters) result.push([ `${flairPattern}!${presenterPattern}`, normalizedFlair, presenter ]) } return result }
javascript
{ "resource": "" }
q32369
joinFlairs
train
function joinFlairs(data) { let result = [] for (let [ targetStringArray, ...rest ] of data) { // Raw flair containing only one flair don’t need to be modified. if (targetStringArray.length < 2) { result.push([ targetStringArray, ...rest ]) continue } // Concatenate the flairs using one, two and three spaces. for (let i = 1; i <= 3; i++) { const SPACES = pad('', i) result.push([ targetStringArray.join(SPACES), ...rest ]) } } return result }
javascript
{ "resource": "" }
q32370
padData
train
function padData(data) { let result = [] for (let [ targetString, ...rest ] of data) { // We are testing for up to 3 spaces and for empty strings we’ll use this // condition to prevent duplicates. if (targetString === '') { result.push([ ' ', ...rest ]) result.push([ ' ', ...rest ]) result.push([ ' ', ...rest ]) continue } // Other strings, add up to 3 spaces to the left and right. for (let i = 1; i <= 3; i++) { const LENGHT = targetString.length // Add spaces to the right. result.push([ pad(targetString, LENGHT + i), ...rest ]) // Add spaces to the left. result.push([ pad(LENGHT + i, targetString), ...rest ]) } } return result }
javascript
{ "resource": "" }
q32371
column
train
function column(options) { return this.navigation.slice(0, 5).reduce(function reduce(columns, section) { return columns + options.fn(section); }, ''); }
javascript
{ "resource": "" }
q32372
month
train
function month(options) { var content = '' , m = this.month; while(++m <= 12) { content += options.fn({ month: m, selected: +this.expiration_month === m ? ' selected' : '', fullMonth: this.months[m - 1] }); } return content; }
javascript
{ "resource": "" }
q32373
year
train
function year(options) { var content = '' , y = this.year; while(++y < this.max_year) { content += options.fn({ year: y, selected: +this.expiration_year === y ? ' selected' : '', }); } return content; }
javascript
{ "resource": "" }
q32374
f_Constructor
train
function f_Constructor(ins_o) { var self = this; // Sanitize instance options if (!ins_o || typeof ins_o !== 'object') { ins_o = {}; } if (!ins_o.custom_data || typeof ins_o.custom_data !== 'object') { ins_o.custom_data = {}; } // Apply instance modules and properties for (var module_name in f_instance_modules) { /* istanbul ignore else */ if (f_instance_modules.hasOwnProperty(module_name)) { self['f_' + module_name] = f_instance_modules[module_name]; } } // Apply instance options // Create data namespace, store name as f_data_namespace var data_namespace = con_o.data_namespace || ins_o.data_namespace || 'data'; self[data_namespace] = ins_o.custom_data; self.f_data_namespace = data_namespace; /** @TODO write desc for f_function_flow */ self.f_function_flow = []; for (var property_name in f_instance_properties) { /* istanbul ignore else */ if (f_instance_properties.hasOwnProperty(property_name)) { self['f_' + property_name] = f_instance_properties[property_name]; } } // Create instance function_flow, this in order to track tries con_o.function_flow.forEach(function (flow) { var new_flow_object = { tries: 0 }; for (var property in flow) { /* istanbul ignore else */ if (flow.hasOwnProperty(property)) { if (property !== 'function') { new_flow_object[property] = flow[property]; } } } self.f_function_flow.push(new_flow_object); }); // Finaly, call user specified initializer and pass the instance options // custom data as the first argument if (con_o.initializer) { con_o.initializer.apply(self, [ins_o.custom_data]); } }
javascript
{ "resource": "" }
q32375
compile
train
function compile(context, commands) { let ii, cmd, limitOptions; // log.debug('limit: in-compile cmds:', commands); // look for the limit commands within the commands for (ii = commands.length - 1; ii >= 0; ii--) { cmd = commands[ii]; if (cmd[0] === LIMIT) { // cmdLimit = cmd; limitOptions = { offset: context.valueOf(cmd[2]), limit: context.valueOf(cmd[1]) }; commands.splice(ii, 1); } else if (limitOptions && cmd[0] === ENTITY_FILTER) { // set the options object of the entityFilter command if (limitOptions) { cmd[3] = { ...cmd[3], ...limitOptions }; } limitOptions = null; } } // if we still have an open limit and no entity filter was found, add one if (limitOptions) { commands.unshift([ENTITY_FILTER, null, null, limitOptions]); } return commands; }
javascript
{ "resource": "" }
q32376
emitDone
train
function emitDone(rawArgs) { if(EventEmitter.listenerCount(emitter, "done") > 0) { var args = new Array(rawArgs.length + 1); args[0] = "done"; for(var i = 0; i < rawArgs.length; i++) args[i + 1] = rawArgs[i]; process.nextTick(function() { emitter.emit.apply(emitter, args); }); } }
javascript
{ "resource": "" }
q32377
errorHandler
train
function errorHandler(err, req, res, next){ if (!req.suppressErrorHandlerConsole && !req.app.suppressErrorHandlerConsole) { if (req.log) { req.log.error(err, "Unhandled Error"); } else { console.log("Unhandled error"); console.log(err.stack || err); } } if (err.status) res.statusCode = err.status; if (res.statusCode < 400) res.statusCode = 500; if (res._header) return; //?? var accept = req.headers.accept || ''; var stack = req.app.get('env') != 'production' ? err.stack : ''; // html if (~accept.indexOf('html')) { res.render('error.html', { message: http.STATUS_CODES[res.statusCode], statusCode: res.statusCode, error: err.toString(), errorstack: (stack || '').split('\n').slice(1) }); // json } else if (~accept.indexOf('json')) { var error = { message: err.message, stack: stack }; for (var prop in err) error[prop] = err[prop]; res.json({ error: error }); // plain text } else { res.setHeader('Content-Type', 'text/plain'); res.end(stack); } }
javascript
{ "resource": "" }
q32378
setup
train
function setup(context) { if (GLOBAL.config) { console.log('already configured'); console.trace(); return; } if (!context) { context = require('./config.js'); } GLOBAL.config = context.config; var svc = { pubsub: pubsub, auth: auth, indexer: indexer, pageCache: pageCache }; GLOBAL.svc = svc; auth.setupUsers(GLOBAL, context.logins); }
javascript
{ "resource": "" }
q32379
setParents
train
function setParents () { var q = async.queue(processFile, 1) q.drain = function () { self.emit('drain') } // Process files with no dependency first self.nodeps.forEach( q.push ) function processFile (item, cb) { debug('dep:', item.id) // Add files with no dependency left to be processed self.deps .forEach(function (file) { if ( file.count > 0 && file.deps.indexOf(item.id) >= 0 ) { item.parents.push(file.id) file.count-- debug('file %s -> %d', file.id, file.count) if (file.count === 0) q.push(file) } }) cb() } }
javascript
{ "resource": "" }
q32380
bind
train
function bind( fn, scope ) { var bound, args; if ( fn.bind === nativeBind && nativeBind ) return nativeBind.apply( fn, Array.prototype.slice.call( arguments, 1 ) ); args = Array.prototype.slice.call( arguments, 2 ); // @todo: don't link this bound = function() { if ( !(this instanceof bound) ) return fn.apply( scope, args.concat( Array.prototype.slice.call( arguments ) ) ); W.ctor.prototype = fn.prototype; var self = new ctor(); var result = fn.apply( self, args.concat( Array.prototype.slice.call( arguments ) ) ); if ( Object( result ) === result ) return result; return self; }; return bound; }
javascript
{ "resource": "" }
q32381
Route
train
function Route(method, path, callbacks, options) { options = options || {}; this.path = path; this.method = method; this.callbacks = callbacks; this.regexp = pathRegexp(path, this.keys = [], options.sensitive, options.strict); }
javascript
{ "resource": "" }
q32382
train
function () { if (this._intervalId) { clearInterval(this._intervalId); this._intervalId = undefined; this.trigger(this.options.stoppedEventName, this); return true; } return false; }
javascript
{ "resource": "" }
q32383
train
function(bufferOrArray, callback) { var self = this, ix = this.offset, frame = [], isArray = Object.prototype.toString.call( bufferOrArray) === '[object Array]'; self.frameIx = 0; while (ix < bufferOrArray.length) { var value = isArray ? bufferOrArray[ix] : bufferOrArray['read' + self.sampleType](ix); frame.push(this.map ? this.map[value] : value); if (frame.length == this.frameSize || ix+self.wordSize == bufferOrArray.length) finishFrame(frame); ix += self.wordSize; } // Did we not process any frames at all for some reason? if (this.frameIx == 0) callback(undefined); function finishFrame(frame) { if (this.scale) frame = frame.map(function (s, ix) {return s * self.scale[ix];}); callback(frame, self.frameIx); if (ix != bufferOrArray.length - self.wordSize) { ix -= (self.frameSize - self.frameStep) * self.wordSize; self.frameIx++; frame.length = 0; } } }
javascript
{ "resource": "" }
q32384
train
function (options) { events.EventEmitter.call(this); var defaultOptions = { ejsdelimiter: '?', strictbinding:false }; this.options = extend(defaultOptions, options); ejs.delimiter = this.options.ejsdelimiter; this.binders = {}; this.update = this._update; this.render = this._render; this.addBinder = this._addBinder; }
javascript
{ "resource": "" }
q32385
copyArguments
train
function copyArguments(args) { var copy = []; for (var i = 0; i < args.length; i++) { copy.push(args[i]); } return copy; }
javascript
{ "resource": "" }
q32386
executeSerializedFunction
train
function executeSerializedFunction(id, args) { SerializedFunctions.forEach(function(sf) { if (sf.id == id) { sf.func.apply(null, args); } }); }
javascript
{ "resource": "" }
q32387
hidden
train
function hidden(val) { // return whether the first element in the set // is hidden if(val === undefined) { return this.attr(attr); // hide on truthy }else if(val) { this.attr(attr, '1'); // show on falsey }else{ this.attr(attr, null); } return this; }
javascript
{ "resource": "" }
q32388
train
function (element) { var left = 0 , top = 0; do { left += element.offsetLeft; top += element.offsetTop; } while (element = element.offsetParent); return { left: left, top: top }; }
javascript
{ "resource": "" }
q32389
trigger
train
function trigger(event, target) { target = target || event.type; if (target === 'mouseout') target = 'mouseover'; return target === $(event.element).get('data-trigger'); }
javascript
{ "resource": "" }
q32390
create
train
function create(event) { if (!this.trigger(event)) return; if ('preventDefault' in event) event.preventDefault(); if (this.trigger(event, 'click') && this.remove(event)) return; // // Create a new tooltip, but make sure to destroy remaining ones before. // this.timer = setTimeout(function execute() { this.render(event); }.bind(this), this.delay); }
javascript
{ "resource": "" }
q32391
remove
train
function remove(event) { // // Current event is not set as trigger (e.g. mouse click vs. hover). // if (!this.trigger(event)) return false; if ('preventDefault' in event) event.preventDefault(); clearTimeout(this.timer); var id = document.getElementById('tooltip'); return id ? !!document.body.removeChild(id) : false; }
javascript
{ "resource": "" }
q32392
render
train
function render(event) { var tooltip = document.createElement('div') , element = $(event.element) , pos = element.get('data-placement') , offset = this.offset(event.element) , placement; // // Create the tooltip with the proper content and insert. // tooltip.id = "tooltip"; tooltip.innerHTML = element.get('data-content'); tooltip.className = ['animated', 'tooltip', 'fadeIn', pos].concat( element.get('data-color') ).filter(Boolean).join(' '); document.body.appendChild(tooltip); // // Update the position of the tooltip. // placement = this.placement(pos, tooltip, event.element); tooltip.setAttribute('style', [ 'left:' + (offset.left + placement.left) + 'px', 'top:' + (offset.top + placement.top) + 'px' ].join(';')); }
javascript
{ "resource": "" }
q32393
train
function () { addCacheItem(params.context.page); params.context.lunr = params.context.lunr || {}; params.context.lunr.dataPath = params.context.lunr.dataPath || 'search_index.json'; }
javascript
{ "resource": "" }
q32394
getPathValue
train
function getPathValue(node, path) { let names = path.split("."), name; while ( name = names.shift() ) { if (node == null) { return names.length ? void 0 : null; } node = node[name]; } return node; }
javascript
{ "resource": "" }
q32395
tokenNotExpired
train
function tokenNotExpired(tokenName, jwt) { if (tokenName === void 0) { tokenName = AuthConfigConsts.DEFAULT_TOKEN_NAME; } var token = jwt || localStorage.getItem(tokenName) || sessionStorage.getItem(tokenName); var jwtHelper = new JwtHelper(); return token != null && !jwtHelper.isTokenExpired(token); }
javascript
{ "resource": "" }
q32396
attr
train
function attr(key, val) { var i, attrs, map = {}; if(!this.length || key !== undefined && !Boolean(key)) { return this; } if(key === undefined && val === undefined) { // no args, get all attributes for first element as object attrs = this.dom[0].attributes; // convert NamedNodeMap to plain object for(i = 0;i < attrs.length;i++) { // NOTE: nodeValue is deprecated, check support for `value` in IE9! map[attrs[i].name] = attrs[i].value; } return map; }else if(typeof key === 'string' && !val) { // delete attribute on all matched elements if(val === null) { this.each(function(el) { el.removeAttribute(key); }) return this; } // get attribute for first matched elements return this.dom[0].getAttribute(key); // handle object map of attributes }else { this.each(function(el) { if(typeof key === 'object') { for(var z in key) { if(key[z] === null) { el.removeAttribute(z); continue; } el.setAttribute(z, key[z]); } }else{ el.setAttribute(key, val); } }); } return this; }
javascript
{ "resource": "" }
q32397
train
function (type) { var exec = []; switch (type || this.configs["publish"]) { case "EPUB": this.publishEPUB(exec); break; case "LATEX": this.publishLatex(exec); break; case "HTML": this.publishHTML(exec); default: break; } return exec; }
javascript
{ "resource": "" }
q32398
waitAndAdvance
train
function waitAndAdvance(step, steps) { setTimeout(function(){ if (step < steps - 1) { api.next(); waitAndAdvance(step+1, steps); } else { // after 15 seconds on last slide, exit fullscreen if(document.cancelFullScreen) { document.cancelFullScreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } } }, slideAdvance); }
javascript
{ "resource": "" }
q32399
train
function(zCriticalValue) { var baselineP = this.baseline.pEstimate(zCriticalValue); var variationP = this.variation.pEstimate(zCriticalValue); var difference = variationP.value - baselineP.value; var standardError = Math.sqrt(Math.pow(baselineP.error, 2) + Math.pow(variationP.error, 2)); return new Abba.ValueWithError(difference, standardError); }
javascript
{ "resource": "" }