_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q34000 | presentResults | train | function presentResults (graph, reverseMap, rawResults, query) {
var nodesWithLocales = rawResults.map(r => reverseMap[r])
var canonicalNodesWithPaths = nodesWithLocales.reduce((canonicalNodes, nwl) => {
return canonicalNodes.concat(findCanonicalNodeWithPath(graph, nwl.node, nwl.locale, []))
}, [])
const ... | javascript | {
"resource": ""
} |
q34001 | checkTable | train | function checkTable(count) {
// Make sure we don't go into an infinite loop
if (++count > 1000) return cb(new Error('Wait limit exceeded'))
self.describeTable(function(err, data) {
if (err) return cb(err)
if (data.TableStatus !== 'ACTIVE' || (data.GlobalSecondaryIndexes &&
... | javascript | {
"resource": ""
} |
q34002 | createReadStreamBackpressureManager | train | function createReadStreamBackpressureManager(readableStream) {
const manager = {
waitPush: true,
programmedPushs: [],
programPush: function programPush(chunk, encoding, done) {
// Store the current write
manager.programmedPushs.push([chunk, encoding, done]);
// Need to be async to avoid ... | javascript | {
"resource": ""
} |
q34003 | train | function (menuId, menuItemId, menuItemTitle, menuItemUiState, menuItemType, position) {
this.validateMenuExistance(menuId);
// Push new menu item
menus[menuId].items.push({
id: menuItemId,
title: menuItemTitle,
uiState: menuItemUiState... | javascript | {
"resource": ""
} | |
q34004 | notify | train | async function notify({ title, message, icon = 'default', timeout, }) { try {
if (!Notifications) { console.info('notify', arguments[0]); return false; }
const create = !open; open = true; const options = {
type: 'basic', title, message,
iconUrl: (/^\w+$/).test(icon) ? (await getIcon(icon)) : icon,
}; !isGecko &... | javascript | {
"resource": ""
} |
q34005 | runModules | train | function runModules(str, modules) {
var replacements = [],
module;
if (Array.isArray(modules) === false) {
modules = [modules];
}
modules.forEach(function forEachModule(module) {
if (!module) {
throw new Error("Unknown module '" + module + "'");
}
r... | javascript | {
"resource": ""
} |
q34006 | runModule | train | function runModule(module, str, replacements) {
var pattern = module.pattern,
replace = module.replace,
match;
// Reset the pattern so we can re-use it
pattern.lastIndex = 0;
while ((match = pattern.exec(str)) !== null) {
replacements[match.index] = {
oldStr: match[... | javascript | {
"resource": ""
} |
q34007 | applyReplacements | train | function applyReplacements(str, replacements) {
var result = "",
replacement,
i;
for (i = 0; i < replacements.length; i++) {
replacement = replacements[i];
if (replacement) {
result += replacement.newStr;
i += replacement.oldStr.length - 1;
} else... | javascript | {
"resource": ""
} |
q34008 | decorate | train | function decorate(pages, page) {
Object.defineProperties(page, {
first: {
enumerable: true,
set: function() {},
get: function() {
return pages.first && pages.first.current;
}
},
current: {
enumerable: true,
set: function() {},
get: function() {
re... | javascript | {
"resource": ""
} |
q34009 | toHex | train | function toHex(binary, start, end) {
var hex = "";
if (end === undefined) {
end = binary.length;
if (start === undefined) start = 0;
}
for (var i = start; i < end; i++) {
var byte = binary[i];
hex += String.fromCharCode(nibbleToCode(byte >> 4)) +
String.fromCharCode(nibbleToCode(byte ... | javascript | {
"resource": ""
} |
q34010 | nodeValue | train | function nodeValue(node1, node2) {
return (node1.dist + heuristic(node1.point)) - (node2.dist + heuristic(node2.point));
} | javascript | {
"resource": ""
} |
q34011 | train | function (currency, callback) {
// Call an asynchronous function, often a save() to DB
self.getPricesForSingleCurrency(from, to, currency, function (err, result) {
if (err) {
callback(err)
} else {
ratesWithTimes[currency] = result
callback()
}
})
... | javascript | {
"resource": ""
} | |
q34012 | train | function (err) {
if (err) {
callback(err, null)
}
_.each(ratesWithTimes, function (rates, currency) {
rates.forEach(function (timeratepair) {
var newEntry = {}
newEntry[currency] = timeratepair.rate
if (allRates[timeratepair.time]) {
allRates[t... | javascript | {
"resource": ""
} | |
q34013 | logger | train | function logger(config = {}) {
// return an middleware
return store => next => action => {
const prevState = store.getState();
const r = next(action);
function prinf(prev, action, next) {
console.group(action, "@" + new Date().toISOString());
console.log("%cprev state", "color:#9E9E9E", pre... | javascript | {
"resource": ""
} |
q34014 | toRems | train | function toRems(rem, type) {
return R.compose(
R.objOf(type),
R.map(R.multiply(rem)),
R.prop(type)
);
} | javascript | {
"resource": ""
} |
q34015 | sanitize | train | function sanitize(html) {
const parts = (html ? html +'' : '').split(rTag);
return parts.map((s, i) => i % 2 ? s : s.replace(rEsc, c => oEsc[c])).join('');
} | javascript | {
"resource": ""
} |
q34016 | generateContourGrid | train | function generateContourGrid(arr) {
// Generate grid for holding values.
var contour_grid = new Array(arr.length - 1);
for (var n = 0; n < contour_grid.length; n++) {
contour_grid[n] = new Array(arr[0].length - 1);
}
var corners = [1.1, 1.2, 1.3, 1.4];
// Specifies the resulting values for the above cor... | javascript | {
"resource": ""
} |
q34017 | find | train | function find(arr, obj, cmp) {
if (typeof cmp !== 'undefined') {
for (var i = 0; i < arr.length; i++) {
if (cmp(arr[i], obj)) {
return i;
}
}
return -1;
}
} | javascript | {
"resource": ""
} |
q34018 | nextNeighbor | train | function nextNeighbor(elt, dir) {
var drow = 0, dcol = 0;
if (dir == "none") {
return null;
} else {
var offset = directions[dir];
return {r: elt.r + offset[0], c: elt.c + offset[1]};
}
} | javascript | {
"resource": ""
} |
q34019 | nextCell | train | function nextCell(elt) {
if (elt.c + 1 < actionInfo[elt.r].length) {
return {r: elt.r, c: elt.c + 1};
} else if (elt.r + 1 < actionInfo.length) {
return {r: elt.r + 1, c: 0};
}
return null;
} | javascript | {
"resource": ""
} |
q34020 | getCoordinates | train | function getCoordinates(location) {
var tile_width = 40;
var x = location.r * tile_width;
var y = location.c * tile_width;
return {x: x, y: y};
} | javascript | {
"resource": ""
} |
q34021 | convertShapesToCoords | train | function convertShapesToCoords(shapes) {
var tile_width = 40;
var new_shapes = map2d(shapes, function(loc) {
// It would be loc.r + 1 and loc.c + 1 but that has been removed
// to account for the one-tile width of padding added in doParse.
var row = loc.r * tile_width;
var col = loc.c * tile_width;... | javascript | {
"resource": ""
} |
q34022 | validateName | train | function validateName(var_name) {
var o = "";
for (var i = 0; i < var_name.length; i++) {
var code = var_name.charCodeAt(i);
if ((code > 47 && code < 58) || // numeric (0-9)
(code > 64 && code < 91) || // upper alpha (A-Z)
(code > 96 && code < 123)... | javascript | {
"resource": ""
} |
q34023 | absolute | train | function absolute(rem){return{abs:{position:'absolute'},
top0:{top:0},
right0:{right:0},
bottom0:{bottom:0},
left0:{left:0},
top1:{top:1*rem},
right1:{right:1*rem},
bottom1:{bottom:1*rem},
left1:{left:1*rem},
top2:{top:2*rem},
right2:{right:2*rem},
bottom2:{bottom:2*rem},
left2:{left:2*rem},
top3:{top:3*rem},
right3... | javascript | {
"resource": ""
} |
q34024 | PollingTagUpdater | train | function PollingTagUpdater(platform, options) {
EventEmitter.call(this);
this.tagsByUUID = {};
this.options = Object.assign({}, options);
if (! this.options.wsdl_url) {
let apiBaseURI;
if (platform) apiBaseURI = platform.apiBaseURI;
if (options && options.apiBaseURI) apiBaseURI =... | javascript | {
"resource": ""
} |
q34025 | updateTag | train | function updateTag(tag, tagData) {
// if not a valid object for receiving updates, we are done
if (! tag) return;
// check that this is the current tag manager
if (tagData.mac && (tag.wirelessTagManager.mac !== tagData.mac)) {
throw new Error("expected tag " + tag.uuid
+ ... | javascript | {
"resource": ""
} |
q34026 | createTag | train | function createTag(tagData, platform, factory) {
let mgrData = {};
managerProps.forEach((k) => {
let mk = k.replace(/^manager([A-Z])/, '$1');
if (mk !== k) mk = mk.toLowerCase();
mgrData[mk] = tagData[k];
delete tagData[k];
});
if (! platform) platform = {};
if (! fac... | javascript | {
"resource": ""
} |
q34027 | createSoapClient | train | function createSoapClient(opts) {
let wsdl = opts && opts.wsdl_url ?
opts.wsdl_url : API_BASE_URI + WSDL_URL_PATH;
let clientOpts = { request: request.defaults({ jar: true, gzip: true }) };
return new Promise((resolve, reject) => {
soap.createClient(wsdl, clientOpts, (err, client) => {
... | javascript | {
"resource": ""
} |
q34028 | pollForNextUpdate | train | function pollForNextUpdate(client, tagManager, callback) {
let req = new Promise((resolve, reject) => {
let methodName = tagManager ?
"GetNextUpdateForAllManagersOnDB" :
"GetNextUpdateForAllManagers";
let soapMethod = client[methodName];
let args = {};
if (tag... | javascript | {
"resource": ""
} |
q34029 | logError | train | function logError(log, err) {
let debug = log.debug || log.trace || log.log;
if (err.Fault) {
log.error(err.Fault);
if (err.response && err.response.request) {
log.error("URL: " + err.response.request.href);
}
if (err.body) debug(err.body);
} else {
log.er... | javascript | {
"resource": ""
} |
q34030 | train | function (connectionInfo, query, params) {
var connection,
client = new pg.Client(connectionInfo);
client.connect(function (err) {
if (err) {
return respond({
success: false,
data: {
err: err,
query: query,
... | javascript | {
"resource": ""
} | |
q34031 | train | function (connectionInfo, query, params) {
var connection;
// Connection validation
if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) {
return respond({
success: false,
data: {
err: 'Bad hostname provided.',
quer... | javascript | {
"resource": ""
} | |
q34032 | injectAsync | train | function injectAsync(_function, ...args) { return new Promise((resolve, reject) => {
if (typeof _function !== 'function') { throw new TypeError('Injecting a string is a form of eval()'); }
const { document, } = (this || global); // call with an iframe.contentWindow as this to inject into its context
const script = ... | javascript | {
"resource": ""
} |
q34033 | remScale | train | function remScale(config){
return R.compose(
R.merge(config),
R.converge(R.merge,[
toRems(config.rem,'scale'),
toRems(config.rem,'typeScale')]))(
config);
} | javascript | {
"resource": ""
} |
q34034 | extendConfig | train | function extendConfig(options){
return R.mapObjIndexed(function(prop,type){return(
prop(options[type]));},extendOps);
} | javascript | {
"resource": ""
} |
q34035 | train | function(year, month, day) {
var date = new Date(Date.UTC(year, month - 1, day));
return date;
} | javascript | {
"resource": ""
} | |
q34036 | train | function(year, month, day) {
var dayOfWeek = this.createDate(year, month, day).getDay();
return dayOfWeek === this.SATURDAY || dayOfWeek === this.SUNDAY;
} | javascript | {
"resource": ""
} | |
q34037 | train | function(year) {
var a = year % 19;
var b = Math.floor(year / 100);
var c = year % 100;
var d = Math.floor(b / 4);
var e = b % 4;
var f = Math.floor((b + 8) / 25);
var g = Math.floor((b - f + 1) / 3);
var h = (19 * a + b - d - g + 15) % 30;
var i = Math.floor(c / 4);
var k = c % ... | javascript | {
"resource": ""
} | |
q34038 | train | function(year) {
var date = this.easterSunday(year);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate() + 1;
return this.createDate(y, m, d);
} | javascript | {
"resource": ""
} | |
q34039 | train | function(year) {
var self = this;
var date = this.easterSunday(year);
var dayOfWeek = null;
function resolveFriday() {
if (dayOfWeek === self.FRIDAY) {
return date;
} else {
date = self.subtractDays(date, 1);
dayOfWeek = self.getDayOfWeek(date);
return resolv... | javascript | {
"resource": ""
} | |
q34040 | train | function(year) {
var self = this;
var month = 6;
var midsummerEve;
self.range(19, 26).forEach(function(day) {
if (!midsummerEve) {
var date = self.createDate(year, month, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.FRIDAY) {
midsummerEv... | javascript | {
"resource": ""
} | |
q34041 | train | function(year) {
var self = this;
var month = 6;
var midsummerDay;
self.range(20, 26).forEach(function(day) {
if (!midsummerDay) {
var date = self.createDate(year, month, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.SATURDAY) {
midsummer... | javascript | {
"resource": ""
} | |
q34042 | train | function(year) {
var self = this;
var october31 = self.createDate(year, 10, 31);
var secondMonth = 11;
var allSaintsDay;
if (self.getDayOfWeek(october31) === self.SATURDAY) {
allSaintsDay = october31;
} else {
self.range(1, 6).forEach(function(day) {
if (!allSaintsDay) {
... | javascript | {
"resource": ""
} | |
q34043 | train | function(num) {
num = parseInt(num);
if (num < 10) {
num = '0' + num;
} else {
num = num.toString();
}
return num;
} | javascript | {
"resource": ""
} | |
q34044 | train | function(fromNumber, toNumber) {
if (typeof fromNumber === 'undefined' || typeof toNumber === 'undefined') {
throw Error('Invalid range.');
}
var arr = [];
for (var i = fromNumber; i <= toNumber; i++) {
arr.push(i);
}
return arr;
} | javascript | {
"resource": ""
} | |
q34045 | Rollout | train | function Rollout(client) {
this.client = client || redis.createClient();
this._id = 'id';
this._namespace = null;
this._groups = {};
this.group('all', function(user) { return true; });
} | javascript | {
"resource": ""
} |
q34046 | objectToSignature | train | function objectToSignature(source) {
function sortObject(input) {
if(typeof input !== 'object' ||input===null)
return input
var output = {};
Object.keys(input).sort().forEach(function (key) {
output[key] = sortObject(input[key]);
});
return output;
}
var signature=... | javascript | {
"resource": ""
} |
q34047 | defaultFillCommandData | train | function defaultFillCommandData(defaults, file, extension) {
var data;
try {
data = require(file).command || {};
} catch (e) {
// If it's JavaScript then return the error
if (extension === '.js') {
data = {failedRequire: e};
}
}
return _.merge(defaults, data);
} | javascript | {
"resource": ""
} |
q34048 | isOneOrMore | train | function isOneOrMore(commands, iterator) {
var list = commands.filter(iterator);
if (list.length === 1) {
return list[0];
} else if (list.length > 1) {
return new Error(util.format('There are %d options for "%s": %s',
list.length, cmd, list.join(', ')));
}
return false;
} | javascript | {
"resource": ""
} |
q34049 | FilteraddMessage | train | function FilteraddMessage(arg, options) {
Message.call(this, options);
this.command = 'filteradd';
$.checkArgument(
_.isUndefined(arg) || BufferUtil.isBuffer(arg),
'First argument is expected to be a Buffer or undefined'
);
this.data = arg || BufferUtil.EMPTY_BUFFER;
} | javascript | {
"resource": ""
} |
q34050 | train | function (dirname, options) {
var src = options.graphqlPath || (dirname + '/node_modules/graphql');
// console.log(src);
try {
graphql = require(src).graphql;
var graphqlUtil = require(src + '/utilities');
introspectionQuery = graphqlUtil.introspectionQuery;
printSchema = graphqlUtil.printSchema;... | javascript | {
"resource": ""
} | |
q34051 | resize | train | function resize() {
console.log("resizing base");
base.width = parent.clientWidth;
svg.setAttributeNS(null, "width", base.width);
// only resize the height if aspect was specified instead of height
if (opts.aspect) {
base.height = base.width * opts.aspect;
svg.setAttributeNS(null, "height", ... | javascript | {
"resource": ""
} |
q34052 | distinct | train | function distinct(array){
return Object.keys(array.reduce(function(current, value){
current[value] = true;
return current;
}, {}));
} | javascript | {
"resource": ""
} |
q34053 | readFile | train | async function readFile(path, encoding) {
const url = browser.extension.getURL(realpath(path));
return new Promise((resolve, reject) => {
const xhr = new global.XMLHttpRequest;
xhr.responseType = encoding == null ? 'arraybuffer' : 'text';
xhr.addEventListener('load', () => resolve(xhr.response));
xhr.addEven... | javascript | {
"resource": ""
} |
q34054 | VersionMessage | train | function VersionMessage(arg, options) {
/* jshint maxcomplexity: 10 */
if (!arg) {
arg = {};
}
Message.call(this, options);
this.command = 'version';
this.version = arg.version || options.protocolVersion;
this.nonce = arg.nonce || utils.getNonce();
this.services = arg.services || new BN(1, 10);
th... | javascript | {
"resource": ""
} |
q34055 | validateNode | train | function validateNode (cost) {
cost = Number(cost)
if (isNaN(cost)) {
throw new TypeError(`Cost must be a number, istead got ${cost}`)
}
if (cost <= 0) {
throw new TypeError(`The cost must be a number above 0, instead got ${cost}`)
}
return cost
} | javascript | {
"resource": ""
} |
q34056 | populateMap | train | function populateMap (map, object, keys) {
// Return the map once all the keys have been populated
if (!keys.length) return map
let key = keys.shift()
let value = object[key]
if (value !== null && typeof value === 'object') {
// When the key is an object, we recursevely populate its proprieties into
... | javascript | {
"resource": ""
} |
q34057 | LogStream | train | function LogStream(options) {
this.model = options.model || false;
if (!this.model) {
throw new Error('[LogStream] - Fatal Error - No mongoose model provided!');
}
Writable.call(this, options);
} | javascript | {
"resource": ""
} |
q34058 | HeadersMessage | train | function HeadersMessage(arg, options) {
Message.call(this, options);
this.BlockHeader = options.BlockHeader;
this.command = 'headers';
$.checkArgument(
_.isUndefined(arg) || (Array.isArray(arg) && arg[0] instanceof this.BlockHeader),
'First argument is expected to be an array of BlockHeader instances'
... | javascript | {
"resource": ""
} |
q34059 | runInFrame | train | async function runInFrame(tabId, frameId, script, ...args) {
if (typeof tabId !== 'number') { tabId = (await getActiveTabId()); }
return (await Frame.get(tabId, frameId || 0)).call(getScource(script), args);
} | javascript | {
"resource": ""
} |
q34060 | train | function(conf) {
if (!conf) {
throw new Error("'conf' is required");
}
var text, headers, message, smtpClient,
callback = conf.callback || function(){};
text = this._buildTemplate(conf.templateName, conf.params);
headers = this._buildHeaders(conf, text);... | javascript | {
"resource": ""
} | |
q34061 | FileCache | train | function FileCache(name) {
this._filename = name || '.gulp-cache';
// load cache
try {
this._cache = JSON.parse(fs.readFileSync(this._filename, 'utf8'));
} catch (err) {
this._cache = {};
}
} | javascript | {
"resource": ""
} |
q34062 | flush | train | function flush(callback) {
fs.writeFile(_this._filename, JSON.stringify(_this._cache), callback);
} | javascript | {
"resource": ""
} |
q34063 | train | function (metricType, statsdKey) {
statsdKey = statsdKey.replace(/([^a-zA-Z0-9:_])/g, '_');
return [prefixes[metricType], '_', statsdKey].join('');
} | javascript | {
"resource": ""
} | |
q34064 | factory | train | function factory(check, filter) {
return match
function match(tags, ranges) {
var values = normalize(tags, ranges)
var result = []
var next
var tagIndex
var tagLength
var tag
var rangeIndex
var rangeLength
var range
var matches
tags = values.tags
ranges = values.ran... | javascript | {
"resource": ""
} |
q34065 | cast | train | function cast(values, name) {
var value = values && typeof values === 'string' ? [values] : values
if (!value || typeof value !== 'object' || !('length' in value)) {
throw new Error(
'Invalid ' + name + ' `' + value + '`, expected non-empty string'
)
}
return value
} | javascript | {
"resource": ""
} |
q34066 | watchifyFile | train | function watchifyFile(src, out) {
var opts = assign({}, watchify.args, {
entries: src,
standalone: "NavMesh",
debug: true
});
var b = watchify(browserify(opts));
function bundle() {
return b.bundle()
.on('error', gutil.log.bind(gutil, "Browserify Error"))
... | javascript | {
"resource": ""
} |
q34067 | train | function(tile) {
var x = tile.x;
var y = tile.y;
var xUp = x + 1 < xUpperBound;
var xDown = x >= 0;
var yUp = y + 1 < yUpperBound;
var yDown = y >= 0;
var adjacents = [];
if (xUp) {
adjacents.push({x: x + 1, y: y});
if (yUp) {
adjacents.push({x: x + 1, y: y + 1});
... | javascript | {
"resource": ""
} | |
q34068 | MerkleblockMessage | train | function MerkleblockMessage(arg, options) {
Message.call(this, options);
this.MerkleBlock = options.MerkleBlock; // constructor
this.command = 'merkleblock';
$.checkArgument(
_.isUndefined(arg) || arg instanceof this.MerkleBlock,
'An instance of MerkleBlock or undefined is expected'
);
this.merkleBl... | javascript | {
"resource": ""
} |
q34069 | cellref | train | function cellref (ref) {
if (R1C1.test(ref)) {
return convertR1C1toA1(ref)
}
if (A1.test(ref)) {
return convertA1toR1C1(ref)
}
throw new Error(`could not detect cell reference notation for ${ref}`)
} | javascript | {
"resource": ""
} |
q34070 | convertA1toR1C1 | train | function convertA1toR1C1 (ref) {
if (!A1.test(ref)) {
throw new Error(`${ref} is not a valid A1 cell reference`)
}
var refParts = ref
.replace(A1, '$1,$2')
.split(',')
var columnStr = refParts[0]
var row = refParts[1]
var column = 0
for (var i = 0; i < columnStr.length; i++) {
column = ... | javascript | {
"resource": ""
} |
q34071 | convertR1C1toA1 | train | function convertR1C1toA1 (ref) {
if (!R1C1.test(ref)) {
throw new Error(`${ref} is not a valid R1C1 cell reference`)
}
var refParts = ref
.replace(R1C1, '$1,$2')
.split(',')
var row = refParts[0]
var column = refParts[1]
var columnStr = ''
for (; column; column = Math.floor((column - 1) / 2... | javascript | {
"resource": ""
} |
q34072 | train | function (data) {
data = data || '';
var jobServer = this.clientOrWorker._getJobServerByUid(this.jobServerUid);
Worker.logger.log('debug', 'work data, handle=%s, data=%s', this.handle, data.toString());
jobServer.send(protocol.encodePacket(protocol.PACKET_TYPES.WORK_DATA, [this.handle, d... | javascript | {
"resource": ""
} | |
q34073 | train | function (packetType, packetData) {
var jobServer = this.clientOrWorker._getJobServerByUid(this.jobServerUid);
jobServer.send(protocol.encodePacket(packetType, packetData));
if(!this.clientOrWorker.readyReset)// ensure the worker won't exit
jobServer.send(protocol.encodePacket(protocol.PACKET_TY... | javascript | {
"resource": ""
} | |
q34074 | train | function(english, language) {
if (typeof translations[english] !== 'undefined' && typeof translations[english][language] !== 'undefined') {
return translations[english][language];
} else {
return english;
}
} | javascript | {
"resource": ""
} | |
q34075 | scrollHandler | train | function scrollHandler() {
for (let i = 0; i < scrollElements.length; i++) {
animationBus.applyStyles(scrollElements[i])
}
isTicking = false
} | javascript | {
"resource": ""
} |
q34076 | train | function (time, metrics) {
/**
* Iterate over every kind of metric we want to send to new relic
*/
options.dispatchMetrics.forEach(function (metricType) {
var statsdKeysForType = metrics[metricType],
statsdKey,
statsdValue,
dispatchMetric = function (dispatc... | javascript | {
"resource": ""
} | |
q34077 | mixin | train | function mixin(target, properties) {
Object.keys(properties).forEach(function(prop) {
target[prop] = properties[prop];
});
} | javascript | {
"resource": ""
} |
q34078 | off | train | function off(event, callback) {
if (callback) {
listeners[event].splice(listeners[event].indexOf(callback), 1);
}
else {
listeners[event] = [];
}
} | javascript | {
"resource": ""
} |
q34079 | tracker | train | function tracker(prop) {
function _tracker(context) {
return function(_prop, _arg) {
context.deps[_prop] = context.deps[_prop] || [];
if (!context.deps[_prop].reduce(function found(prev, curr) {
return prev || (curr[0] === prop);
}, false)) {
context.deps[_p... | javascript | {
"resource": ""
} |
q34080 | _get | train | function _get(prop) {
var val = obj[prop];
return cache[prop] = (typeof val === 'function') ?
val.call(tracker(prop)) : val;
} | javascript | {
"resource": ""
} |
q34081 | setter | train | function setter(prop, val) {
var oldVal = _get(prop);
if (typeof obj[prop] === 'function') {
// Computed property setter
obj[prop].call(tracker(prop), val);
}
else {
// Simple property
obj[prop] = val;
}
delete cache[prop];
delete children[prop];
return (oldVal... | javascript | {
"resource": ""
} |
q34082 | accessor | train | function accessor(prop, arg) {
return (arg === undefined) ? getter(prop) : setter(prop, arg);
} | javascript | {
"resource": ""
} |
q34083 | construct | train | function construct(target) {
mixin(target, {
values: obj,
parent: parent || null,
root: root || target,
prop: prop === undefined ? null : prop,
// .on(event[, prop], callback)
on: on,
// .off(event[, prop][, callback])
off: off,
// .trigger(event[, prop])
... | javascript | {
"resource": ""
} |
q34084 | wrapMutatingArrayMethod | train | function wrapMutatingArrayMethod(method, func) {
return function() {
var result = [][method].apply(obj, arguments);
this.len = this.values.length;
cache = {};
children = {};
func.apply(this, arguments);
target.parent.trigger('update', target.prop);
return re... | javascript | {
"resource": ""
} |
q34085 | matchOperator | train | function matchOperator(str, operatorList) {
return operatorList.reduce((match, operator) => {
return match ||
(str.startsWith(operator.symbol) ? operator : null);
}, null);
} | javascript | {
"resource": ""
} |
q34086 | _parseParenthesizedSubformula | train | function _parseParenthesizedSubformula(self, currentString) {
if (currentString.charAt(0) !== '(') {
return null;
}
const parsedSubformula = _parseFormula(self, sliceSymbol(currentString, '('), MIN_PRECEDENCE);
if (parsedSubformula.remainder.charAt(0) !== ')') {
throw new SyntaxError('Invalid formula! ... | javascript | {
"resource": ""
} |
q34087 | _parseUnarySubformula | train | function _parseUnarySubformula(self, currentString) {
const unary = matchOperator(currentString, self.unaries);
if (!unary) {
return null;
}
const parsedSubformula = _parseFormula(self, sliceSymbol(currentString, unary.symbol), unary.precedence);
return {
json: { [unary.key]: parsedSubformula.json }... | javascript | {
"resource": ""
} |
q34088 | _parseBinarySubformula | train | function _parseBinarySubformula(self, currentString, currentPrecedence, leftOperandJSON) {
const binary = matchOperator(currentString, self.binaries);
if (!binary || binary.precedence < currentPrecedence) {
return null;
}
const nextPrecedence = binary.precedence + (binary.associativity === 'left');
const... | javascript | {
"resource": ""
} |
q34089 | convertPolyToP2TPoly | train | function convertPolyToP2TPoly(poly) {
return poly.points.map(function(p) {
return new poly2tri.Point(p.x, p.y);
});
} | javascript | {
"resource": ""
} |
q34090 | separatePolys | train | function separatePolys(polys, offset) {
offset = offset || 1;
var discovered = {};
var dupes = {};
// Offset to use in calculation.
// Find duplicates.
for (var s1 = 0; s1 < polys.length; s1++) {
var poly = polys[s1];
for (var i = 0; i < poly.numpoints; i++) {
var point = poly.points[i].toStri... | javascript | {
"resource": ""
} |
q34091 | train | function(count, includeWeekends) {
initialize();
count = count || 3;
includeWeekends = includeWeekends || false;
var self = this;
var holidays = [];
if (count > self.MAX_HOLIDAYS) {
throw Error('Cannot request more than {MAX_HOLIDAYS} holidays at once.'.replace('{MAX HOLIDAYS}', self.MA... | javascript | {
"resource": ""
} | |
q34092 | collectHolidays | train | function collectHolidays() {
if (typeof self.year.holidays[self.m] !== 'undefined' && typeof self.year.holidays[self.m] !== 'undefined') {
self.year.holidays[self.m].forEach(function(holiday) {
if (holidays.length < count && holiday.day >= self.d) {
holidays.push(holiday);
... | javascript | {
"resource": ""
} |
q34093 | train | function(year, includeWeekends) {
initialize(year);
includeWeekends = includeWeekends || false;
var self = this;
var holidays = [];
if (!includeWeekends) {
self.year.discardWeekends();
}
Object.keys(self.year.holidays).forEach(function(month) {
self.year.holidays[month].forEa... | javascript | {
"resource": ""
} | |
q34094 | train | function(month, year, includeWeekends) {
initialize(year, month);
includeWeekends = includeWeekends || false;
if (!month || !year) {
throw Error('Month or year missing.');
}
var self = this;
var holidays = [];
if (!includeWeekends) {
self.year.discardWeekends();
}
if... | javascript | {
"resource": ""
} | |
q34095 | initialize | train | function initialize(y, m, d) {
var today = dateUtils.today();
var thisDay = dateUtils.getDay(today);
var thisMonth = dateUtils.getMonth(today);
var thisYear = dateUtils.getYear(today);
calendar.y = y || thisYear;
calendar.m = m || thisMonth;
calendar.d = d || thisDay;
calendar.year = yearFactory.get(c... | javascript | {
"resource": ""
} |
q34096 | nextMonth | train | function nextMonth() {
if (calendar.m === 12) {
calendar.m = 1;
calendar.y += 1;
calendar.d = 1;
} else {
calendar.m += 1;
calendar.d = 1;
}
calendar.year = yearFactory.get(calendar.y);
} | javascript | {
"resource": ""
} |
q34097 | parse_html | train | function parse_html() {
var reading_js = false, reading_css = false;
var parser = new htmlparser.Parser({
onopentag: function(name, attribs){
if (name === "script" && ! attribs.src && (attribs.type === "text/javascript" || ! attribs.type)){
reading_js = true;
}
... | javascript | {
"resource": ""
} |
q34098 | remove_inline_scripts | train | function remove_inline_scripts(){
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].length && scripts[i] !== "\n") {
html = html.replace(scripts[i], "");
}
}
} | javascript | {
"resource": ""
} |
q34099 | remove_inline_stylesheets | train | function remove_inline_stylesheets(){
for (var i = 0; i < styles.length; i++) {
if (styles[i].length && styles[i] !== "\n") {
html = html.replace(styles[i], "");
}
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.