_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q39500
cc
train
function cc(line, params) { var event = params[0]; var what = params[1]; try { ++event[line[what]].counter; } catch (TypeError) { event[line[what]] = { counter: 1 }; } return event; }
javascript
{ "resource": "" }
q39501
avg
train
function avg(line, params) { var event = params[0]; var what = params[1]; var r = Number(line[what]); event.what += r; ++event.total; if (r > event.max) { event.max = r; } if (r < event.min) { event.min = r; } return event; }
javascript
{ "resource": "" }
q39502
train
function(a,b,beStrict){ if(this.isArray(a) && this.isArray(b)){ var alen = a.length, i = 0; if(beStrict){ if(alen !== (b).length){ return false; } } for(; i < alen; i++){ if(a[i] === undefined || b[i] === undefined) break; if(b[i] !== a[i]){ return false; break; } } return true; } }
javascript
{ "resource": "" }
q39503
train
function(a,b,beStrict){ if(this.isObject(a) && this.isObject(b)){ var alen = this.keys(a).length, i; for(i in a){ if(beStrict){ if(!(i in b)){ return false; break; } } if((i in b)){ if(b[i] !== a[i]){ return false; break; } } } return true; } }
javascript
{ "resource": "" }
q39504
train
function(args){ if(this.isObject(args)){ return [this.keys(args),this.values(args)]; } if(this.isArgument(args)){ return [].splice.call(args,0); } if(!this.isArray(args) && !this.isObject(args)){ return [args]; } }
javascript
{ "resource": "" }
q39505
train
function () { var val = (1 + (Math.random() * (30000)) | 3); if(!(val >= 10000)){ val += (10000 * Math.floor(Math.random * 9)); } return val; }
javascript
{ "resource": "" }
q39506
train
function(i,value){ if(!value) return; var i = i || 1,message = ""; while(true){ message += value; if((--i) <= 0) break; } return message; }
javascript
{ "resource": "" }
q39507
train
function(o,value,fn){ if(this.isArray(o)){ return this._anyArray(o,value,fn); } if(this.isObject(o)){ return this._anyObject(o,value,fn); } }
javascript
{ "resource": "" }
q39508
train
function(arrays,result){ var self = this,flat = result || []; this.forEach(arrays,function(a){ if(self.isArray(a)){ self.flatten(a,flat); }else{ flat.push(a); } },self); return flat; }
javascript
{ "resource": "" }
q39509
train
function(o,value){ var occurence = []; this.forEach(o,function occurmover(e,i,b){ if(e === value){ occurence.push(i); } },this); return occurence; }
javascript
{ "resource": "" }
q39510
train
function(o,value,fn){ this.forEach(o,function everymover(e,i,b){ if(e === value){ if(fn) fn.call(this,e,i,b); } },this); return; }
javascript
{ "resource": "" }
q39511
train
function(o,start,end){ var i = 0,len = o.length; if(!len || len <= 0) return false; start = Math.abs(start); end = Math.abs(end); if(end > (len - start)){ end = (len - start); } for(; i < len; i++){ o[i] = o[start]; start +=1; if(i >= end) break; } o.length = end; return o; }
javascript
{ "resource": "" }
q39512
train
function(a){ if(!a || !this.isArray(a)) return; var i = 0,start = 0,len = a.length; for(;i < len; i++){ if(!this.isUndefined(a[i]) && !this.isNull(a[i]) && !(this.isEmpty(a[i]))){ a[start]=a[i]; start += 1; } } a.length = start; return a; }
javascript
{ "resource": "" }
q39513
Random
train
function Random(opts) { Readable.apply(this, arguments); if (opts && opts.objectMode) { this.objectMode = true; } this.dictionary = ['1', '0']; }
javascript
{ "resource": "" }
q39514
createLocalCache
train
function createLocalCache() { var localCache = lruCache({ max: 100, maxAge: 60000 }); return { get: function (key) { return new Q(localCache.get(key)); }, set: function (key, value) { localCache.set(key, value); }, del: function (key) { localCache.set(key, null); } }; }
javascript
{ "resource": "" }
q39515
connectToRedis
train
function connectToRedis(db, opts) { // get the redis client var client = redis.createClient(opts.port, opts.host); // log any errors client.on('error', function (err) { redisOffline = true; console.log('connectToRedis error: ' + err); }); client.on('ready', function () { redisOffline = false; }); // if there is a password, do auth var deferred = Q.defer(); if (opts.password) { client.auth(opts.password, function (authErr) { if (authErr) { deferred.reject(authErr); return; } client.select(db, function (err) { err ? deferred.reject(err) : deferred.resolve(client); }); }); } else { client.select(db, function (err) { err ? deferred.reject(err) : deferred.resolve(client); }); } return deferred.promise; }
javascript
{ "resource": "" }
q39516
init
train
function init(config) { var promises = []; if (config.redis) { _.each(config.redis.dbs, function (idx, name) { promises.push( connectToRedis(idx, config.redis) .then(function (remoteCache) { caches[name] = wrapRemoteCache(remoteCache); return true; }) ); }); } // initialization done once all connections established return Q.all(promises) .then(function () { return config; }); }
javascript
{ "resource": "" }
q39517
get
train
function get(req) { var cache = caches[this.name]; var returnVal = null; if (cache && !redisOffline) { try { returnVal = cache.get(req.key); } catch (err) { console.log('redis get err: ' + err); } } return new Q(returnVal); }
javascript
{ "resource": "" }
q39518
set
train
function set(req) { var cache = caches[this.name]; if (!cache) { cache = caches[this.name] = createLocalCache(); } if (!redisOffline) { try { (req.value || !cache.del) ? cache.set(req.key, req.value) : cache.del(req.key); } catch (err) { console.log('redis set err: ' + err); } } }
javascript
{ "resource": "" }
q39519
clear
train
function clear() { var cache = caches[this.name]; if (cache && cache.flush && !redisOffline) { cache.flush(); } }
javascript
{ "resource": "" }
q39520
addCounts
train
function addCounts(o1, o2) { var result; if (o1 && o2) { result = _.merge(o1, o2, function (a, b) { return a + b; }); } else if (o1) { result = o1; } else { result = o2; } return result; }
javascript
{ "resource": "" }
q39521
getThingUserRights
train
function getThingUserRights(userId, username, thing) { if (!userId && !username) throw new utils.ErrorCustom(httpStatusCodes.INTERNAL_SERVER_ERROR, "userId or usernane must be not empty", 28); if (!thing) throw new utils.ErrorCustom(httpStatusCodes.INTERNAL_SERVER_ERROR, "Thing can't be null", 27); let thingUserRights = null; if (userId) thingUserRights = thing.usersRights.find(u => u.userId == userId); if (!thingUserRights && username) thingUserRights = thing.usersRights.find(u => u.username == username); return thingUserRights; }
javascript
{ "resource": "" }
q39522
getThingUserClaims
train
function getThingUserClaims(user, thing, isSuperAdministrator) { if (!thing) throw new utils.ErrorCustom(httpStatusCodes.INTERNAL_SERVER_ERROR, "Thing can't be null", 26); let thingUserClaimsAndRights = { read : thing.publicReadClaims, change : thing.publicChangeClaims }; if (user) { thingUserClaimsAndRights.read = thingUserClaimsAndRights.read | thing.everyoneReadClaims; thingUserClaimsAndRights.change = thingUserClaimsAndRights.change | thing.everyoneChangeClaims; var thingUserRights = getThingUserRights(user._id, user.username, thing); if (thingUserRights) { thingUserClaimsAndRights.read = thingUserClaimsAndRights.read | thingUserRights.userReadClaims; thingUserClaimsAndRights.change = thingUserClaimsAndRights.change | thingUserRights.userChangeClaims; } if (isSuperAdministrator) { thingUserClaimsAndRights.read = thConstants.ThingUserReadClaims.AllClaims; thingUserClaimsAndRights.change = thConstants.ThingUserChangeClaims.AllClaims; } } return thingUserClaimsAndRights; }
javascript
{ "resource": "" }
q39523
getThing
train
async function getThing(user, thingId, deletedStatus, userRole, userStatus, userVisibility) { if (!thingId) throw new utils.ErrorCustom(httpStatusCodes.BAD_REQUEST, "Thing's Id not valid", 37); let thing = await findThingById(thingId); if (!thing) { // Returns httpStatusCodes.UNAUTHORIZED to Reset Some Malicious Logon Access if (!user) throw new utils.ErrorCustom(httpStatusCodes.UNAUTHORIZED, "Unauthorized user", 38); throw new utils.ErrorCustom(httpStatusCodes.NOT_FOUND, "Thing not found", 39); } if (deletedStatus != thConstants.ThingDeletedStates.NoMatter && thing.deletedStatus != deletedStatus) throw new utils.ErrorCustom(httpStatusCodes.BAD_REQUEST, "Thing's Deletedstatus not valid", 40); if ((thing.publicReadClaims & thConstants.ThingUserReadClaims.AllClaims) != 0 || (thing.publicChangeClaims & thConstants.ThingUserChangeClaims.AllClaims) != 0) { // This is a condition I do not remember why it was put on. I consider it important. // At this time it is commented why when I try to assign a pos to Thing // for an unnamed user who does not have a relationship with Thing the condition does not let me pass. // if (user == null && userRole == ThingUserRoles.NoMatter && userStatus == ThingUserStates.NoMatter && userVisibility == thConstants.ThingUserVisibility.NoMatter) return thing; } if (!user) throw new utils.ErrorCustom(httpStatusCodes.UNAUTHORIZED, "Unauthorized user", 41); // If User is Super Administrator returns Thing whatever filters(userRole) are passed as parameters if (user.isSuperAdministrator) return thing; if ((thing.everyoneReadClaims & thConstants.ThingUserReadClaims.AllClaims) != 0 || (thing.everyoneChangeClaims & thConstants.ThingUserChangeClaims.AllClaims) != 0) return thing; var thingUserRights = getThingUserRights(user._id, user.username, thing); if (thingUserRights) { if (userStatus != thConstants.ThingUserStates.NoMatter && ((thingUserRights.userStatus & userStatus) == 0)) throw new utils.ErrorCustom(httpStatusCodes.FORBIDDEN, "Unauthorized user", 42); if (userRole != thConstants.ThingUserRoles.NoMatter && ((thingUserRights.userRole & userRole) == 0)) throw new utils.ErrorCustom(httpStatusCodes.FORBIDDEN, "Unauthorized user", 43); if (userVisibility != thConstants.ThingUserVisibility.NoMatter && ((thingUserRights.userVisibility & userVisibility) == 0)) throw new utils.ErrorCustom(httpStatusCodes.FORBIDDEN, "Unauthorized user", 48); return thing; } throw new utils.ErrorCustom(httpStatusCodes.FORBIDDEN, "Unauthorized user", 44); }
javascript
{ "resource": "" }
q39524
getThingPosition
train
function getThingPosition(user, parentThing, childThing) { if (!childThing) throw new utils.ErrorCustom(httpStatusCodes.INTERNAL_SERVER_ERROR, "Child Thing can't be null", 29); // If User is equal to null as it may be anonymous or is a SuperAdministrator who has no relationship with Thing if (!user) return null; let userId = user._id; let parentThingId = parentThing ? parentThing._id : null; return childThing.parentsThingsIds.find(p => p.userId == userId && p.parentThingId == parentThingId); }
javascript
{ "resource": "" }
q39525
train
function(signal, arg, emitter) { var widget = this, slot; if (typeof emitter === 'undefined') emitter = this; console.log("fire(" + signal + ")", arg); if (signal.charAt(0) == '@') { // This is a global signal. slot = $$.statics("WTag"); if (slot) { slot = slot.globalSlots[signal]; if (slot) { slot[1].call(slot[0], arg, signal, emitter); } else { console.error( "[WTag.fire] Nothing is binded on global signal \"" + signal + "\"!" ); } } } if (signal.charAt(0) == '$') { // Assign a value to a data. this.data(signal.substr(1).trim(), arg); } else { while (widget) { slot = widget._slots[signal]; if (typeof slot === 'function') { if (false !== slot.call(widget, arg, signal, emitter)) { return; } } widget = widget.parentWidget(); } console.warning("Signal lost: " + signal + "!"); } }
javascript
{ "resource": "" }
q39526
train
function(signal, arg) { var slot = this._slots[signal]; if (slot) { slot.call(this, arg, signal); return true; } return false; }
javascript
{ "resource": "" }
q39527
train
function() { var element = this._element; while (element.parentNode) { element = element.parentNode; if (element.$widget) { return element.$widget; } } return null; }
javascript
{ "resource": "" }
q39528
train
function(id) { if (!$$.App) $$.App = this; if (!$$.App._languages) { // Initialise localization. var languages = [], langStyle = document.createElement("style"), children = document.querySelectorAll("[lang]"); document.head.appendChild(langStyle); $$.App._langStyle = langStyle; for (var i = 0 ; i < children.length ; i++) { var child = children[i]; lang = child.getAttribute("lang"); found = false; for (k = 0 ; k < languages.length ; k++) { if (languages[k] == lang) { found = true; break; } } if (!found) { languages.push(lang); } } $$.App._languages = languages; } var that = this, lang, k, found, first, txt; languages = $$.App._languages; if (id === undefined) { // Return current language. lang = $$.lang(); // localStorage.getItem("wtag-language"); if (!lang) { lang = navigator.language || navigator.browserLanguage || "fr"; lang = lang.substr(0, 2); } $$.lang(lang); // localStorage.setItem("wtag-language", lang); return lang; } else { // Set current language and display localized elements. found = false; for (k = 0 ; k < languages.length ; k++) { if (languages[k] == id) { found = true; break; } } if (!found) { id = languages[0]; } txt = ""; first = true; for (k = 0 ; k < languages.length ; k++) { lang = languages[k]; if (lang != id) { if (first) { first = false; } else { txt += ","; } txt += "[lang=" + lang + "]"; } } $$.App._langStyle.textContent = txt + "{display: none}"; $$.lang(id); //localStorage.setItem("wtag-language", id); } }
javascript
{ "resource": "" }
q39529
train
function(name) { if (typeof name === 'undefined') return this._element; var e = this._element.querySelector("[name='" + name + "']"); if (!e) { throw new Error( "[WTag.get] Can't find child [name=\"" + name + "\"] in element \"" + this._id + "\"!" ); } return e; }
javascript
{ "resource": "" }
q39530
train
function(vars, slot, getter) { if (!Array.isArray(vars)) { vars = [vars]; } if (vars.length == 0) return null; if (typeof slot === 'string') { slot = this[slot]; } if (typeof getter === 'undefined') { getter = function() { return this.data(vars[0]); }; } var listener = { obj: this, slot: slot, getter: getter }; vars.forEach( function(name) { var data = this.findDataBinding(name); data[1].push(listener); }, this ); return listener; }
javascript
{ "resource": "" }
q39531
train
function(vars, listener) { if (!Array.isArray(vars)) { vars = [vars]; } if (vars.length == 0) return null; var found = false; vars.forEach( function(name) { var data = this.findDataBinding(name); var i, target; for (i = 0 ; i < data[1].length ; i++) { target = data[1][i]; if (listener === target) { data[1].splice(i, 1); found = true; return; } } }, this ); return found; }
javascript
{ "resource": "" }
q39532
QueryWhere
train
function QueryWhere(data) { //Initialize the string var sql = ''; //Check the type if(typeof data === 'string') { //Return the where return data; } //Get all data for(var key in data) { //Save data value var value = data[key]; //Check the data type if(typeof value === 'string' || value instanceof String) { //Add the quotes value = '"' + value + '"'; } //Check if is necessary add the AND if(sql !== '') { //Add the AND sql = sql + ' AND '; } //Add the key=value sql = sql + key + '=' + value; } //Return the string return sql; }
javascript
{ "resource": "" }
q39533
RGBSplitFilter
train
function RGBSplitFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader fs.readFileSync(__dirname + '/rgbSplit.frag', 'utf8'), // custom uniforms { red: { type: 'v2', value: { x: 20, y: 20 } }, green: { type: 'v2', value: { x: -20, y: 20 } }, blue: { type: 'v2', value: { x: 20, y: -20 } }, dimensions: { type: '4fv', value: [0, 0, 0, 0] } } ); }
javascript
{ "resource": "" }
q39534
NoSuchPlugin
train
function NoSuchPlugin (message, name, paths) { UnmetDependency.call(this, message); this.name = name; this.paths = paths; }
javascript
{ "resource": "" }
q39535
PluginInitializationError
train
function PluginInitializationError (message, module) { this.message = message; this.stack = new Error().stack; this.module = module; }
javascript
{ "resource": "" }
q39536
instantiateDrivers
train
function instantiateDrivers(config, defaultDriverInstance) { config.actionConfigs.forEach(action => { action.driverInstance=action.driver?action.driver():defaultDriverInstance; }); return config; }
javascript
{ "resource": "" }
q39537
initEnhancers
train
function initEnhancers(routes) { invariant(routes.filter(actionConfig => !actionConfig.driverInstance).length===0, 'Routes must have instantiated drivers'); return routes .filter(actionConfig => actionConfig.driverInstance.middleware) .map(actionConfig => actionConfig.driverInstance.middleware()); }
javascript
{ "resource": "" }
q39538
findCTagsFile
train
function findCTagsFile(searchPath, tagFilePattern = '{.,}tags') { const ctagsFinder = function ctagsFinder(tagPath) { console.error(`ctagz: Searching ${tagPath}`) return fs.readdirAsync(tagPath).then(files => { const matched = files.filter(minimatch.filter(tagFilePattern)).sort() const ret = !matched ? Promise.resolve(null) : Promise.reduce(matched, (acc, match) => { if (acc) { return acc } const matchPath = path.join(tagPath, match) return fs.statAsync(matchPath).then(stats => { if (!stats.isFile()) { return null } return fs.openAsync(matchPath, 'r').then(fd => new CTags(matchPath, fd)) .catch(() => null) }) }, null) return ret.then(result => { const newTagPath = path.dirname(tagPath) if (!result && newTagPath !== tagPath) { return ctagsFinder(newTagPath) } return result }) }) } let tagPath = path.resolve(searchPath) return fs.statAsync(tagPath).then(stats => { if (stats.isFile()) { tagPath = path.dirname(tagPath) } return ctagsFinder(tagPath) }) }
javascript
{ "resource": "" }
q39539
findCTagsBSearch
train
function findCTagsBSearch(searchPath, tag, ignoreCase = false, tagFilePattern = '{.,}tags') { const ctags = findCTagsFile(searchPath, tagFilePattern) .disposer(tags => { if (tags) { tags.destroy() } }) return Promise.using(ctags, tags => { if (tags) { return tags.init() .then(() => tags.findBinary(tag, ignoreCase)) .then(result => ({ tagsFile: tags.tagsFile, results: result })) } return { tagsFile: '', results: [] } }) }
javascript
{ "resource": "" }
q39540
injector
train
function injector(css, module, makeModule, options) { output_css = join(options.output, options.css_folder || 'css'); location_css = options.client + '/' + (options.css_folder || 'css'); output_links = join(options.output, options.links_folder || 'links'); location_links = options.client + '/' + (options.links_folder || 'links'); // Unify css url (and store related assets in a sub directory 'links') css = rework(css) .use(unifyurl(module.path, output_links, location_links, options)) .toString(); // Create the css file var uid = getUID(options) + getUID(css) , oFilename = uid + '.css' , oFilepath = join(output_css, oFilename) , oLocation = location_css + '/' + oFilename ; write(oFilepath, css, {encoding:'utf8'}) var js = tmpl.replace(/\{\{location\}\}/, oLocation); return jsParser(js, module, makeModule, options); }
javascript
{ "resource": "" }
q39541
train
function () { if (!enumer.moveNext()) { cb(groups); return; } var li = enumer.get_current(); var name = li.get_item("Name"); if (name.search(" ") > 0) { doNext(); } else { var id = li.get_item("ID"); var user = web.ensureUser(name); ctx.load(user); groups.push({ text: name, id: id + "_User", data: user, icon: "/_layouts/images/ribbon_userprofile_16.png" }); //count++; //if (count % 50 == 0) ctx.executeQueryAsync(function () { doNext(); }, function () { doNext(); }); } }
javascript
{ "resource": "" }
q39542
parseMatchplan
train
function parseMatchplan(team, callback) { /** @type {String[]} */ var matchPlanArr = [], /** @type {Matchplan} */ matchPlan, /** @type {String[]} */ matchDetails = [], /** @type {Encounter[]} */ encounters = []; jsdom.env({ url: team, scripts: ["http://code.jquery.com/jquery.js"], done: function (err, window) { var $ = window.$; $("tr.row-headline").each(function() { matchPlanArr.push(parseMatchTime($(this).text())); }); $(".club-name").each(function(index) { if ((index + 1) % 2 === 0) { encounters[encounters.length - 1].setVisitingTeam($(this).text()); } else { encounters.push(new Encounter($(this).text())); } }); $("td.column-detail a").each(function(index, element) { matchDetails.push(new URL(element.href)); }); matchPlan = createMatchplan(matchPlanArr, encounters, matchDetails); matchPlan.output(); callback(matchPlan); } }); }
javascript
{ "resource": "" }
q39543
parseMatchTime
train
function parseMatchTime(matchTime) { /** @type String[] */ var matchTimeArr = matchTime.split(' '); matchTimeArr = [matchTimeArr[1], matchTimeArr[3]]; var dayMonthYear = matchTimeArr[0].split('.'); var hourMinutes = matchTimeArr[1].split(':'); var date = new Date(dayMonthYear[2], parseInt(dayMonthYear[1]) - 1, dayMonthYear[0], hourMinutes[0], hourMinutes[1]); return date; }
javascript
{ "resource": "" }
q39544
createMatchplan
train
function createMatchplan(matchPlanArr, encounters, matchDetails) { var matchPlan = new Matchplan(); matchPlanArr.forEach(function(currentValue, index, array) { matchplanEntry = new MatchplanEntry(currentValue, null, encounters[index], null, matchDetails[index]); matchPlan.addEntry(matchplanEntry); }); return matchPlan; }
javascript
{ "resource": "" }
q39545
refresh
train
function refresh(file, event, full) { views.forEach(function loopViews(path) { if (path !== full) return; tempers.forEach(function eachTemper(temper) { delete temper.file[path]; delete temper.compiled[path]; temper.prefetch(path); }); }); assets.forEach(function loopAssets(path) { if (path !== full) return; bigpipe.compiler.put(path); }); bigpipe.emit('change', file, event, full); console.log([ '[watch] detected content changes --'.blue, file.white, 'changed'.white ].join(' ')); }
javascript
{ "resource": "" }
q39546
dyadic_pref_op
train
function dyadic_pref_op(pref, input1, input2, input_width) { if (pref < -13 || pref > 13) throw new Error('dyadic_pref_op('+pref+'): out of range iii-111'); var bt_pref = pad(3, n2bts(pref), '0'); if (bt_pref.indexOf('i') === -1 || bt_pref.indexOf('0') === -1 || bt_pref.indexOf('1') === -1) throw new Error('dyadic_pref_op('+pref+'): preference must contain all digits i,0,1'); var input1_bt = pad(input_width, n2bts(input1), '0'); var input2_bt = pad(input_width, n2bts(input2), '0'); var output_bt = ''; for (var i = 0; i < input_width; ++i) { var a = input1_bt.charAt(i); var b = input2_bt.charAt(i); if (bt_pref.indexOf(a) < bt_pref.indexOf(b)) { // a has a higher preference than b (comes earlier in preference list), choose a output_bt += a; } else { // otherwise choose b (preference functions always choose one of the inputs) output_bt += b; } } var output = bts2n(output_bt); return output; }
javascript
{ "resource": "" }
q39547
ejectionHandler
train
function ejectionHandler() { process.stdin.resume(); log(chalk.yellow('Ejection, swooooooooo-oooopphhhf!')); _this.fileSynceInstantly(function ejectionComplete() { log(chalk.green('Everything saved, for god sake')); log('shittung down, see you next life'); process.exit(); }); }
javascript
{ "resource": "" }
q39548
execute
train
function execute(req, res) { var save = undefined; if(req.args[0] !== undefined) { save = req.args[0] === true; } this.shutdown({save: save, code: 0}, process.exit); }
javascript
{ "resource": "" }
q39549
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); if(args[0]) { var arg = ('' + args[0]).toLowerCase(); if(arg !== Constants.SHUTDOWN.SAVE && arg !== Constants.SHUTDOWN.NOSAVE) { throw CommandSyntax; } // rewrite with boolean args[0] = (arg === Constants.SHUTDOWN.SAVE); } }
javascript
{ "resource": "" }
q39550
train
function() { var me = this; var barCount = 0; helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) { var meta = me.chart.getDatasetMeta(datasetIndex); if (meta.bar && me.chart.isDatasetVisible(datasetIndex)) { ++barCount; } }, me); return barCount; }
javascript
{ "resource": "" }
q39551
train
function(datasetIndex) { var barIndex = 0; var meta, j; for (j = 0; j < datasetIndex; ++j) { meta = this.chart.getDatasetMeta(j); if (meta.bar && this.chart.isDatasetVisible(j)) { ++barIndex; } } return barIndex; }
javascript
{ "resource": "" }
q39552
train
function() { var me = this; var options = me.options; var scales = me.scales = {}; var items = []; if (options.scales) { items = items.concat( (options.scales.xAxes || []).map(function(xAxisOptions) { return {options: xAxisOptions, dtype: 'category'}; }), (options.scales.yAxes || []).map(function(yAxisOptions) { return {options: yAxisOptions, dtype: 'linear'}; }) ); } if (options.scale) { items.push({options: options.scale, dtype: 'radialLinear', isDefault: true}); } helpers.each(items, function(item) { var scaleOptions = item.options; var scaleType = helpers.getValueOrDefault(scaleOptions.type, item.dtype); var scaleClass = Chart.scaleService.getScaleConstructor(scaleType); if (!scaleClass) { return; } var scale = new scaleClass({ id: scaleOptions.id, options: scaleOptions, ctx: me.chart.ctx, chart: me }); scales[scale.id] = scale; // TODO(SB): I think we should be able to remove this custom case (options.scale) // and consider it as a regular scale part of the "scales"" map only! This would // make the logic easier and remove some useless? custom code. if (item.isDefault) { me.scale = scale; } }); Chart.scaleService.addScalesToLayout(this); }
javascript
{ "resource": "" }
q39553
train
function() { if (!stub.ticking) { stub.ticking = true; helpers.requestAnimFrame.call(window, function() { if (stub.resizer) { stub.ticking = false; return callback(); } }); } }
javascript
{ "resource": "" }
q39554
train
function(chart, e) { var position = helpers.getRelativePosition(e, chart.chart); return getIntersectItems(chart, position); }
javascript
{ "resource": "" }
q39555
train
function(chartInstance, box) { if (!chartInstance.boxes) { chartInstance.boxes = []; } chartInstance.boxes.push(box); }
javascript
{ "resource": "" }
q39556
train
function(extension, args) { var plugins = this._plugins; var ilen = plugins.length; var i, plugin; for (i=0; i<ilen; ++i) { plugin = plugins[i]; if (typeof plugin[extension] === 'function') { if (plugin[extension].apply(plugin, args || []) === false) { return false; } } } return true; }
javascript
{ "resource": "" }
q39557
train
function(rawValue) { // Null and undefined values first if (rawValue === null || typeof(rawValue) === 'undefined') { return NaN; } // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values if (typeof(rawValue) === 'number' && !isFinite(rawValue)) { return NaN; } // If it is in fact an object, dive in one more level if (typeof(rawValue) === 'object') { if ((rawValue instanceof Date) || (rawValue.isValid)) { return rawValue; } return this.getRightValue(this.isHorizontal() ? rawValue.x : rawValue.y); } // Value is good, return it return rawValue; }
javascript
{ "resource": "" }
q39558
train
function(index, includeOffset) { var me = this; if (me.isHorizontal()) { var innerWidth = me.width - (me.paddingLeft + me.paddingRight); var tickWidth = innerWidth / Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); var pixel = (tickWidth * index) + me.paddingLeft; if (includeOffset) { pixel += tickWidth / 2; } var finalVal = me.left + Math.round(pixel); finalVal += me.isFullWidth() ? me.margins.left : 0; return finalVal; } var innerHeight = me.height - (me.paddingTop + me.paddingBottom); return me.top + (index * (innerHeight / (me.ticks.length - 1))); }
javascript
{ "resource": "" }
q39559
train
function(decimal /* , includeOffset*/) { var me = this; if (me.isHorizontal()) { var innerWidth = me.width - (me.paddingLeft + me.paddingRight); var valueOffset = (innerWidth * decimal) + me.paddingLeft; var finalVal = me.left + Math.round(valueOffset); finalVal += me.isFullWidth() ? me.margins.left : 0; return finalVal; } return me.top + (decimal * me.height); }
javascript
{ "resource": "" }
q39560
train
function(generationOptions, dataRange) { var ticks = []; // To get a "nice" value for the tick spacing, we will use the appropriately named // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks // for details. var spacing; if (generationOptions.stepSize && generationOptions.stepSize > 0) { spacing = generationOptions.stepSize; } else { var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false); spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true); } var niceMin = Math.floor(dataRange.min / spacing) * spacing; var niceMax = Math.ceil(dataRange.max / spacing) * spacing; // If min, max and stepSize is set and they make an evenly spaced scale use it. if (generationOptions.min && generationOptions.max && generationOptions.stepSize) { var minMaxDeltaDivisibleByStepSize = ((generationOptions.max - generationOptions.min) % generationOptions.stepSize) === 0; if (minMaxDeltaDivisibleByStepSize) { niceMin = generationOptions.min; niceMax = generationOptions.max; } } var numSpaces = (niceMax - niceMin) / spacing; // If very close to our rounded value, use it. if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { numSpaces = Math.round(numSpaces); } else { numSpaces = Math.ceil(numSpaces); } // Put the values into the ticks array ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin); for (var j = 1; j < numSpaces; ++j) { ticks.push(niceMin + (j * spacing)); } ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax); return ticks; }
javascript
{ "resource": "" }
q39561
train
function() { var chartOpts = this.chart.options; if (chartOpts && chartOpts.title) { this.options = helpers.configMerge(Chart.defaults.global.title, chartOpts.title); } }
javascript
{ "resource": "" }
q39562
getBaseModel
train
function getBaseModel(tooltipOpts) { var globalDefaults = Chart.defaults.global; var getValueOrDefault = helpers.getValueOrDefault; return { // Positioning xPadding: tooltipOpts.xPadding, yPadding: tooltipOpts.yPadding, xAlign: tooltipOpts.xAlign, yAlign: tooltipOpts.yAlign, // Body bodyFontColor: tooltipOpts.bodyFontColor, _bodyFontFamily: getValueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily), _bodyFontStyle: getValueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle), _bodyAlign: tooltipOpts.bodyAlign, bodyFontSize: getValueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize), bodySpacing: tooltipOpts.bodySpacing, // Title titleFontColor: tooltipOpts.titleFontColor, _titleFontFamily: getValueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily), _titleFontStyle: getValueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle), titleFontSize: getValueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize), _titleAlign: tooltipOpts.titleAlign, titleSpacing: tooltipOpts.titleSpacing, titleMarginBottom: tooltipOpts.titleMarginBottom, // Footer footerFontColor: tooltipOpts.footerFontColor, _footerFontFamily: getValueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily), _footerFontStyle: getValueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle), footerFontSize: getValueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize), _footerAlign: tooltipOpts.footerAlign, footerSpacing: tooltipOpts.footerSpacing, footerMarginTop: tooltipOpts.footerMarginTop, // Appearance caretSize: tooltipOpts.caretSize, cornerRadius: tooltipOpts.cornerRadius, backgroundColor: tooltipOpts.backgroundColor, opacity: 0, legendColorBackground: tooltipOpts.multiKeyBackground, displayColors: tooltipOpts.displayColors }; }
javascript
{ "resource": "" }
q39563
train
function(elements) { if (!elements.length) { return false; } var i, len; var x = 0; var y = 0; var count = 0; for (i = 0, len = elements.length; i < len; ++i) { var el = elements[i]; if (el && el.hasValue()) { var pos = el.tooltipPosition(); x += pos.x; y += pos.y; ++count; } } return { x: Math.round(x / count), y: Math.round(y / count) }; }
javascript
{ "resource": "" }
q39564
lineToPoint
train
function lineToPoint(previousPoint, point) { var pointVM = point._view; if (point._view.steppedLine === true) { ctx.lineTo(pointVM.x, previousPoint._view.y); ctx.lineTo(pointVM.x, pointVM.y); } else if (point._view.tension === 0) { ctx.lineTo(pointVM.x, pointVM.y); } else { ctx.bezierCurveTo( previousPoint._view.controlPointNextX, previousPoint._view.controlPointNextY, pointVM.controlPointPreviousX, pointVM.controlPointPreviousY, pointVM.x, pointVM.y ); } }
javascript
{ "resource": "" }
q39565
train
function() { var me = this; var labels = me.getLabels(); me.minIndex = 0; me.maxIndex = labels.length - 1; var findIndex; if (me.options.ticks.min !== undefined) { // user specified min value findIndex = helpers.indexOf(labels, me.options.ticks.min); me.minIndex = findIndex !== -1 ? findIndex : me.minIndex; } if (me.options.ticks.max !== undefined) { // user specified max value findIndex = helpers.indexOf(labels, me.options.ticks.max); me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex; } me.min = labels[me.minIndex]; me.max = labels[me.maxIndex]; }
javascript
{ "resource": "" }
q39566
train
function(value, index, datasetIndex, includeOffset) { var me = this; // 1 is added because we need the length but we have the indexes var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); if (value !== undefined && isNaN(index)) { var labels = me.getLabels(); var idx = labels.indexOf(value); index = idx !== -1 ? idx : index; } if (me.isHorizontal()) { var innerWidth = me.width - (me.paddingLeft + me.paddingRight); var valueWidth = innerWidth / offsetAmt; var widthOffset = (valueWidth * (index - me.minIndex)) + me.paddingLeft; if (me.options.gridLines.offsetGridLines && includeOffset || me.maxIndex === me.minIndex && includeOffset) { widthOffset += (valueWidth / 2); } return me.left + Math.round(widthOffset); } var innerHeight = me.height - (me.paddingTop + me.paddingBottom); var valueHeight = innerHeight / offsetAmt; var heightOffset = (valueHeight * (index - me.minIndex)) + me.paddingTop; if (me.options.gridLines.offsetGridLines && includeOffset) { heightOffset += (valueHeight / 2); } return me.top + Math.round(heightOffset); }
javascript
{ "resource": "" }
q39567
train
function(err, files, results) { if(err) { cb(err); } else { for(var i = 0; i < results.length; i++) { if(results[i] !== undefined && results[i].error === undefined && results[i].id !== undefined) { fixtures[results[i].id] = results[i]; } } cb(undefined, fixtures); } }
javascript
{ "resource": "" }
q39568
train
function (listTitle) { return $.Deferred(function (dfd) { trace.debug(`loading list ${listTitle}`); spdal.getList(listTitle).done(function (list) { onListChange(list); listCtrl.data("xSPTreeLight").value(list); }).always(function () { dfd.resolve(); }); }).promise(); }
javascript
{ "resource": "" }
q39569
checkGitRepoExistence
train
function checkGitRepoExistence() { return new Promise(function(resolve, reject) { var checkRepoCommand = childProcess.exec('git branch'); checkRepoCommand.stderr.on('data', function(err) { reject(err); }); checkRepoCommand.on('close', function(code) { if (code === 0) { //0 means ok, 128 means error resolve(); } }); }); }
javascript
{ "resource": "" }
q39570
create
train
function create (client) { return function create (options) { options = options || {}; const type = getType(options); const req = { url: `${client.baseUrl}/rest/applications/${options.pushAppId}/${type}`, method: 'POST' }; const data = { name: options.name, description: options.description }; if (options.type !== 'ios') { for (let key in options[options.type]) { data[key] = options[options.type][key]; } req.body = data; } else { data.passphrase = options.ios.passphrase; data.production = options.ios.production ? 'true' : 'false'; // If they send in a string, then lets assume that is the location of the cert file // Otherwise, we will assume it is a Stream or Buffer and can just pass it along if (typeof options.ios.certificate === 'string') { data.certificate = fs.createReadStream(options.ios.certificate); } else { data.certificate = options.ios.certificate; } // need to clean up the description field if it is undefined, doing multipart with request barfs if this is null if (!data.description) { delete data.description; } req.formData = data; } return request(client, req) .then((response) => { if (response.resp.statusCode !== 201) { return Promise.reject(response.body); } return Promise.resolve(response.body); }); }; }
javascript
{ "resource": "" }
q39571
train
function(variables) { var animation = false, animationstring = 'animation', keyframeprefix = '', domPrefixes = ["Webkit", "Moz", "O", "ms", "Khtml"], pfx = '', elm = document.querySelector("body"); if( elm.style.animationName !== undefined ) { animation = true; } if( animation === false ) { for( var i = 0; i < domPrefixes.length; i++ ) { if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) { pfx = domPrefixes[ i ]; animationstring = pfx + 'Animation'; keyframeprefix = '-' + pfx.toLowerCase() + '-'; animation = true; break; } } } variables.keyframesPrefix = keyframeprefix; variables.animationString = animationstring; variables.aliases = { transform: keyframeprefix + "transform" }; variables.count = 1; }
javascript
{ "resource": "" }
q39572
cli
train
function cli(program) { var source = program.args[0] ? path.resolve(program.args[0]) : null, destinations = program.args[1] ? Array.prototype.slice.call(program.args, 1) : [], options = {}, camelton; if (!source) { console.error('Source file not defined.'); program.help(); } if (!destinations.length) { console.error('Destination file not defined.'); program.help(); } if (program.prune) { options.prune = program.prune; } if (program.placeholder) { options.placeholder = program.placeholder; } if (program.sort) { options.sort = program.sort; } if (program.verbose) { options.verbose = program.verbose; } try { camelton = new Camelton(source, destinations, options); camelton.run(); camelton.report(); process.exit(0); } catch (e) { console.error(e.message); process.exit(1); } }
javascript
{ "resource": "" }
q39573
serializeToXRD
train
function serializeToXRD(descriptor) { var xml = '<?xml version="1.0" encoding="UTF-8"?>'; xml += '<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'; if (descriptor.expires) { xml += '<Expires>' + xsdDateTimeString(descriptor.expires) + '</Expires>'; } if (descriptor.subject) { xml += '<Subject>' + descriptor.subject + '</Subject>'; } descriptor.aliases.forEach(function(alias) { xml += '<Alias>' + alias + '</Alias>'; }); descriptor.properties.forEach(function(key, value) { if (value) { xml += '<Property type="' + key + '">' + value + '</Property>'; } else { xml += '<Property type="' + key + '" xsi:nil="true" />'; } }); descriptor.links.forEach(function(link) { xml += '<Link'; if (link.rel) { xml += ' rel="' + link.rel + '"'; } if (link.href) { xml += ' href="' + link.href + '"'; } if (link.template) { xml += ' template="' + link.template + '"'; } if (link.type) { xml += ' type="' + link.type + '"'; } xml += '>'; link.titles.forEach(function(lang, title) { if (lang === '_') { xml += '<Title>' + title + '</Title>'; } else { xml += '<Title xml:lang="' + lang + '">' + title + '</Title>'; } }); link.properties.forEach(function(key, value) { if (value) { xml += '<Property type="' + key + '">' + value + '</Property>'; } else { xml += '<Property type="' + key + '" xsi:nil="true" />'; } }); xml += '</Link>'; }); xml += '</XRD>'; return xml; }
javascript
{ "resource": "" }
q39574
serializeToJRD
train
function serializeToJRD(descriptor) { var obj = {}; if (descriptor.expires) { obj.expires = xsdDateTimeString(descriptor.expires); } if (descriptor.subject) { obj.subject = descriptor.subject; } if (descriptor.aliases.length > 0) { obj.aliases = []; descriptor.aliases.forEach(function(alias) { obj.aliases.push(alias); }); } if (descriptor.properties.length > 0) { obj.properties = {}; descriptor.properties.forEach(function(key, value) { obj.properties[key] = value; }, { flatten: true }); } if (descriptor.links.length > 0) { obj.links = []; descriptor.links.forEach(function(link) { var l = {}; if (link.rel) { l.rel = link.rel; } if (link.href) { l.href = link.href; } if (link.template) { l.template = link.template; } if (link.type) { l.type = link.type; } if (link.titles.length > 0) { l.titles = {}; link.titles.forEach(function(lang, title) { if (lang === '_') { l.titles['default'] = title; } else { l.titles[lang] = title; } }, { flatten: true }); } if (link.properties.length > 0) { l.properties = {}; link.properties.forEach(function(key, value) { l.properties[key] = value; }, { flatten: true }); } obj.links.push(l); }); } return JSON.stringify(obj); }
javascript
{ "resource": "" }
q39575
textXml
train
function textXml(data) { var xml = undefined, tmp = undefined; if (!data || typeof data !== "string") { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString(data, "text/xml"); } catch (e) { xml = undefined; } if (!xml || xml.getElementsByTagName("parsererror").length) { throwError("Invalid XML: " + data); } return xml; }
javascript
{ "resource": "" }
q39576
ajaxSetup
train
function ajaxSetup(target, settings) { return settings ? // Building a settings object ajaxExtend(ajaxExtend(target, this.ajaxSettings), settings) : // Extending ajaxSettings ajaxExtend(this.ajaxSettings, target); }
javascript
{ "resource": "" }
q39577
abort
train
function abort(statusText) { var finalText = statusText || strAbort; if (transport) { transport.abort(finalText); } done(0, finalText); return this; }
javascript
{ "resource": "" }
q39578
train
function (endpoint, anchorPos) { continuousAnchorLocations[endpoint.id] = [ anchorPos[0], anchorPos[1], anchorPos[2], anchorPos[3] ]; continuousAnchorOrientations[endpoint.id] = orientation; }
javascript
{ "resource": "" }
q39579
sendSocketMessage
train
function sendSocketMessage(message) { clients.forEach(function (client) { if (client.readyState === WebSocket.OPEN) { client.send(message || 'refresh', function (err) { if (err) { npmlog.error(err); } }); } }); }
javascript
{ "resource": "" }
q39580
getProperties
train
function getProperties( property ) { var properties = property[ PROPERTY_SYMBOL ]; if ( !Array.isArray( properties ) ) return null; return properties; }
javascript
{ "resource": "" }
q39581
applyAttributesToTarget
train
function applyAttributesToTarget( source, target ) { var attName, attValue; for ( attName in source ) { if ( module.exports.isLinkable( target, attName ) ) { attValue = source[ attName ]; target[ attName ] = attValue; } } }
javascript
{ "resource": "" }
q39582
addPropToValue
train
function addPropToValue( prop, value ) { if ( value === undefined || value === null ) return; if ( value.isContentChangeAware !== true ) return; var properties = value[ PROPERTY_SYMBOL ]; if ( !Array.isArray( properties ) ) { properties = [ prop ]; } else if ( properties.indexOf( prop ) === -1 ) { properties.push( prop ); } value[ PROPERTY_SYMBOL ] = properties; }
javascript
{ "resource": "" }
q39583
readonly
train
function readonly( target, attribs ) { const attribNames = Object.keys( attribs ); attribNames.forEach( function ( attName ) { const attValue = attribs[ attName ]; if ( typeof attValue === 'function' ) { Object.defineProperty( target, attName, { set() { throw Error( `Attribute "${attName}" is read only!` ); }, get: attValue, configurable: false, enumerable: true } ); } else { Object.defineProperty( target, attName, { value: attValue, writable: false, configurable: false, enumerable: true } ); } } ); }
javascript
{ "resource": "" }
q39584
updatePathInternal
train
function updatePathInternal(sourcePath, targetPath, options, log) { var rootDir = (options && options.rootDir) || ""; var targetFullPath = path.join(rootDir, targetPath); var targetStats = fs.existsSync(targetFullPath) ? fs.statSync(targetFullPath) : null; var sourceStats = null; if (sourcePath) { // A non-null source path was specified. It should exist. var sourceFullPath = path.join(rootDir, sourcePath); if (!fs.existsSync(sourceFullPath)) { throw new Error("Source path does not exist: " + sourcePath); } sourceStats = fs.statSync(sourceFullPath); // Create the target's parent directory if it doesn't exist. var parentDir = path.dirname(targetFullPath); if (!fs.existsSync(parentDir)) { shell.mkdir("-p", parentDir); } } return updatePathWithStats(sourcePath, sourceStats, targetPath, targetStats, options, log); }
javascript
{ "resource": "" }
q39585
updatePaths
train
function updatePaths(pathMap, options, log) { if (!pathMap || typeof pathMap !== "object" || Array.isArray(pathMap)) { throw new Error("An object mapping from target paths to source paths is required."); } log = log || function(message) { }; var updated = false; // Iterate in sorted order to ensure directories are created before files under them. Object.keys(pathMap).sort().forEach(function (targetPath) { var sourcePath = pathMap[targetPath]; updated = updatePathInternal(sourcePath, targetPath, options, log) || updated; }); return updated; }
javascript
{ "resource": "" }
q39586
mergeAndUpdateDir
train
function mergeAndUpdateDir(sourceDirs, targetDir, options, log) { if (sourceDirs && typeof sourceDirs === "string") { sourceDirs = [ sourceDirs ]; } else if (!Array.isArray(sourceDirs)) { throw new Error("A source directory path or array of paths is required."); } if (!targetDir || typeof targetDir !== "string") { throw new Error("A target directory path is required."); } log = log || function(message) { }; var rootDir = (options && options.rootDir) || ""; var include = (options && options.include) || [ "**" ]; if (typeof include === "string") { include = [ include ]; } else if (!Array.isArray(include)) { throw new Error("Include parameter must be a glob string or array of glob strings."); } var exclude = (options && options.exclude) || []; if (typeof exclude === "string") { exclude = [ exclude ]; } else if (!Array.isArray(exclude)) { throw new Error("Exclude parameter must be a glob string or array of glob strings."); } // Scan the files in each of the source directories. var sourceMaps = sourceDirs.map(function (sourceDir) { return path.join(rootDir, sourceDir); }).map(function (sourcePath) { if (!fs.existsSync(sourcePath)) { throw new Error("Source directory does not exist: " + sourcePath); } return mapDirectory(rootDir, path.relative(rootDir, sourcePath), include, exclude); }); // Scan the files in the target directory, if it exists. var targetMap = {}; var targetFullPath = path.join(rootDir, targetDir); if (fs.existsSync(targetFullPath)) { targetMap = mapDirectory(rootDir, targetDir, include, exclude); } var pathMap = mergePathMaps(sourceMaps, targetMap, targetDir); var updated = false; // Iterate in sorted order to ensure directories are created before files under them. Object.keys(pathMap).sort().forEach(function (subPath) { var entry = pathMap[subPath]; updated = updatePathWithStats( entry.sourcePath, entry.sourceStats, entry.targetPath, entry.targetStats, options, log) || updated; }); return updated; }
javascript
{ "resource": "" }
q39587
mapDirectory
train
function mapDirectory(rootDir, subDir, include, exclude) { var dirMap = { "": { subDir: subDir, stats: fs.statSync(path.join(rootDir, subDir)) } }; mapSubdirectory(rootDir, subDir, "", include, exclude, dirMap); return dirMap; function mapSubdirectory(rootDir, subDir, relativeDir, include, exclude, dirMap) { var itemMapped = false; var items = fs.readdirSync(path.join(rootDir, subDir, relativeDir)); items.forEach(function(item) { var relativePath = path.join(relativeDir, item); if(!matchGlobArray(relativePath, exclude)) { // Stats obtained here (required at least to know where to recurse in directories) // are saved for later, where the modified times may also be used. This minimizes // the number of file I/O operations performed. var fullPath = path.join(rootDir, subDir, relativePath); var stats = fs.statSync(fullPath); if (stats.isDirectory()) { // Directories are included if either something under them is included or they // match an include glob. if (mapSubdirectory(rootDir, subDir, relativePath, include, exclude, dirMap) || matchGlobArray(relativePath, include)) { dirMap[relativePath] = { subDir: subDir, stats: stats }; itemMapped = true; } } else if (stats.isFile()) { // Files are included only if they match an include glob. if (matchGlobArray(relativePath, include)) { dirMap[relativePath] = { subDir: subDir, stats: stats }; itemMapped = true; } } } }); return itemMapped; } function matchGlobArray(path, globs) { return globs.some(function(elem) { return minimatch(path, elem, {dot:true}); }); } }
javascript
{ "resource": "" }
q39588
mergePathMaps
train
function mergePathMaps(sourceMaps, targetMap, targetDir) { // Merge multiple source maps together, along with target path info. // Entries in later source maps override those in earlier source maps. // Target stats will be filled in below for targets that exist. var pathMap = {}; sourceMaps.forEach(function (sourceMap) { Object.keys(sourceMap).forEach(function(sourceSubPath){ var sourceEntry = sourceMap[sourceSubPath]; pathMap[sourceSubPath] = { targetPath: path.join(targetDir, sourceSubPath), targetStats: null, sourcePath: path.join(sourceEntry.subDir, sourceSubPath), sourceStats: sourceEntry.stats }; }); }); // Fill in target stats for targets that exist, and create entries // for targets that don't have any corresponding sources. Object.keys(targetMap).forEach(function(subPath){ var entry = pathMap[subPath]; if (entry) { entry.targetStats = targetMap[subPath].stats; } else { pathMap[subPath] = { targetPath: path.join(targetDir, subPath), targetStats: targetMap[subPath].stats, sourcePath: null, sourceStats: null }; } }); return pathMap; }
javascript
{ "resource": "" }
q39589
readFromEnvFile
train
function readFromEnvFile() { try { // .env file should be in root directory const data = require('fs').readFileSync(require('path').join(__dirname, '../../.env'), 'utf8') const env = {} data.split('\n').filter((v) => { return v !== '' }).filter((v) => { return v.indexOf('#') === -1 }).forEach((v) => { const splitPosition = v.indexOf('=') if (splitPosition === -1) { return } // only first '=' will be splitted const key = v.slice(0, splitPosition).trim() const value = v.slice(splitPosition + 1).trim() env[key] = value }) return env } catch (err) { throw err } }
javascript
{ "resource": "" }
q39590
splitMultipleValues
train
function splitMultipleValues(envObject) { try { const data = Object.keys(envObject) return data.reduce((p, v) => { p[v] = envObject[v] if (envObject[v].indexOf(',') !== -1) { p[v] = envObject[v].split(',') } return p }, {}) } catch (err) { throw err } }
javascript
{ "resource": "" }
q39591
promiseReadFile
train
function promiseReadFile(path, encoding = 'utf-8') { return new Promise((resolve, reject) => { fs.readFile(path, encoding, (err, content) => { if (err) reject(err); resolve({ path, fileName: path.split('/').pop(), content }); }); }); }
javascript
{ "resource": "" }
q39592
Connection
train
function Connection(uri) { this.channels = {}; let version = require('../package.json').version; let opts = { query: 'instanceId=' + 'js_cli_' + version, 'sync disconnect on unload': true, path: '/syncsocket' }; this.socket = io.connect(uri, opts); this.bindEvents(); }
javascript
{ "resource": "" }
q39593
getFoldersAndFiles
train
function getFoldersAndFiles(fpath, folders, files){ fs.readdirSync(fpath).forEach(function(name){ var stat = fs.statSync(fpath + name); if(stat.isDirectory()){ folders.push({ path : fpath, name : name }); getFoldersAndFiles(fpath + name + '/', folders, files); }else{ files.push({ path : fpath, name : name }); } }); }
javascript
{ "resource": "" }
q39594
Decoder
train
function Decoder(options) { options = options || {}; Transform.call(this, {}); this._reset(); // maximum length for bulk strings (512MB) this.maxlen = options.maxlen || 536870912; // create String instances for simple string replies this.simple = options.simple !== undefined ? options.simple : false; // return buffers for bulk strings this.buffers = options.return_buffers || options.buffers; // pass RESP messasges untouched this.raw = options.raw !== undefined ? options.raw : false; /* istanbul ignore next: optional dependency */ if(hiredis) { this.reader = new hiredis.Reader({return_buffers: this.buffers}); } }
javascript
{ "resource": "" }
q39595
_type
train
function _type(chunk, test) { var b = chunk[0]; if(b === ERR || b === BST || b === STR || b === INT || b === ARR) { if(!test) this._offset++; return b; } }
javascript
{ "resource": "" }
q39596
_arr
train
function _arr(chunk, type) { var len = this._int(chunk, type); // allow zero length for the empty array if(typeof len === 'number' && !isNaN(len)) { var arr = new Array(len); this._elements += len; Object.defineProperty(arr, '_index', { enumerable: false, configurable: true, writable: true, value: 0 } ); return arr; } }
javascript
{ "resource": "" }
q39597
_int
train
function _int(chunk, type) { var b, s = '', i; while(this._offset < chunk.length) { b = chunk[this._offset]; if(b === CR && chunk[this._offset + 1] === LF) { this._offset += 2; i = parseInt(s); if(type === BST) { if(isNaN(i)) { return this._abort(new Error('bad string length')); }else if(i > this.maxlen) { return this._abort(new Error('string length exceeded')); } } return i; } s += String.fromCharCode(b); ++this._offset; } }
javascript
{ "resource": "" }
q39598
_bst
train
function _bst(chunk, type) { // we should have already read the chunk var len = this._int(chunk, type), buf; if(!isNaN(len)) { // read an integer less than zero, treat as null if(len < 0) return null; // read in the entire bulk string and swallow the crlf if((chunk.length - this._offset) >= len + 2) { buf = chunk.slice(this._offset, this._offset + len); this._offset += (len + 2); //this._buffer = this._buffer.slice(this._offset, this._buffer.length); //console.dir(buf); return this.buffers ? buf : '' + buf; }else{ this._wait(); } } }
javascript
{ "resource": "" }
q39599
noNew
train
function noNew() { return finish(function(err) { if (err) return next(err); // If there was a body initially, respond that there's been no change if (ourEtag) return res.send(304); // Otherwise, respond that there's no content (yet) else return res.send(204); }); }
javascript
{ "resource": "" }