_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 canonicalNodesWithPathsAndWeights = canonicalNodesWithPaths.map(cnwp => addWeight(cnwp, query))
canonicalNodesWithPathsAndWeights.sort(byWeightAndThenAlphabetically)
const uniqueNodesWithPathsAndWeights = uniqBy(canonicalNodesWithPathsAndWeights, (cnwp) => {
return presentableName(cnwp.node, preferredLocale)
})
uniqueNodesWithPathsAndWeights.sort(byWeightAndThenAlphabetically)
var presentableNodes = uniqueNodesWithPathsAndWeights.map(cnwp => {
var canonicalName = presentableName(cnwp.node, preferredLocale)
var pathToName = ''
if (showPaths && cnwp.path.length) {
var stableNamesInPath = cnwp.path
.filter(pathNode => pathNode.node.meta['stable-name'])
.map(pathNode => presentableName(pathNode.node, pathNode.locale))
var lastNode = stableNamesInPath.pop()
if (lastNode) {
pathToName = lastNode
}
}
return {
name: canonicalName,
path: pathToName
}
})
return presentableNodes
} | 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 &&
!data.GlobalSecondaryIndexes.every(function (idx) {return idx.IndexStatus === 'ACTIVE'}))) {
return setTimeout(checkTable, 1000, count)
}
// If the table is ACTIVE then return
cb(null, data)
})
} | 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 nested push attempts
// Programm a push attempt
setImmediate(manager.attemptPush);
// Let's say we're ready for a read
readableStream.emit('readable');
readableStream.emit('drain');
},
attemptPush: function attemptPush() {
let nextPush;
if (manager.waitPush) {
if (manager.programmedPushs.length) {
nextPush = manager.programmedPushs.shift();
manager.waitPush = readableStream.push(nextPush[0], nextPush[1]);
nextPush[2]();
}
} else {
setImmediate(() => {
// Need to be async to avoid nested push attempts
readableStream.emit('readable');
});
}
},
};
// Patch the readable stream to manage reads
readableStream._read = function streamFilterRestoreRead() {
manager.waitPush = true;
// Need to be async to avoid nested push attempts
setImmediate(manager.attemptPush);
};
return manager;
} | 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,
class: menuItemType,
position: position || 0,
items: []
});
// Return the menu object
return menus[menuId];
} | 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 && (options.requireInteraction = true);
try { (await Notifications[create || isGecko ? 'create' : 'update'](
'web-ext-utils:notice', options,
)); } catch (_) { open = false; throw _; }
clearNotice(timeout == null ? -1 : typeof timeout === 'number' && timeout > 1e3 && timeout < 30 ** 2 ? timeout : 5000);
onhide && onhide(); onclick = onhide = null;
return new Promise(done => { onclick = () => done(true); onhide = () => done(false); });
} catch (_) { try {
console.error(`failed to show notification`, arguments[0], _);
} catch (_) { } } return false; } | 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 + "'");
}
runModule(module, str, replacements);
});
return replacements;
} | 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[0],
newStr: typeof replace === "function"? replace(match) : replace
};
if (pattern.global === false) {
// if the search isn't global we need to break manually
// because pattern.exec() will always return something
break;
}
}
} | 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 {
result += str.charAt(i);
}
}
result += str.substr(i, str.length);
return result;
} | 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() {
return this.idx + 1;
}
},
last: {
enumerable: true,
set: function() {},
get: function() {
return pages.last && pages.last.current;
}
},
total: {
enumerable: true,
set: function() {},
get: function() {
return pages.total;
}
}
});
var prev = pages.last;
var idx = pages.total;
page.idx = idx;
if (prev) {
page.prev = prev.current;
prev.next = page.current;
}
return page;
} | 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 & 0xf));
}
return hex;
} | 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[timeratepair.time].push(newEntry)
} else {
allRates[timeratepair.time] = [newEntry]
}
})
})
var allRatesNice = []
_.each(allRates, function (rates, time) {
var ratesNice = {}
_.each(rates, function (currencyratepair) {
_.each(currencyratepair, function (rate, currency) {
ratesNice[currency] = rate
})
})
allRatesNice.push({time: time, rates: ratesNice})
})
callback(null, allRatesNice)
} | 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", prev);
console.log("%caction", "color:#2196F3", action);
console.log("%cnext state", "color:#4CAF50", next);
console.groupEnd();
}
if (r && typeof r.then === "function") {
return next(action).then(
d =>
prinf(prevState, action.name, store.getState()) && Promise.resolve(d)
);
} else {
prinf(prevState, action.name, store.getState());
return r;
}
};
} | 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 corner values. The index
// of the objects in this array corresponds to the proper values for the
// quadrant of the same index.
var corner_values = [
{1.1: 3, 1.2: 0, 1.3: 2, 1.4: 1},
{1.1: 0, 1.2: 3, 1.3: 1, 1.4: 2},
{1.1: 3, 1.2: 1, 1.3: 2, 1.4: 0},
{1.1: 1, 1.2: 3, 1.3: 0, 1.4: 2}
];
for (var i = 0; i < (arr.length - 1); i++) {
for (var j = 0; j < (arr[0].length - 1); j++) {
var cell = [arr[i][j], arr[i][j+1], arr[i+1][j+1], arr[i+1][j]];
// Convert corner tiles to appropriate representation.
cell.forEach(function(val, i, cell) {
if (corners.indexOf(val) !== -1) {
cell[i] = corner_values[i][val];
}
});
contour_grid[i][j] = cell;
}
}
return contour_grid;
} | 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;
return {x: row, y: col}
});
return new_shapes;
} | 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) || // lower alpha (a-z)
var_name[i] === "$" ||
var_name[i] === "_" ||
var_name[i] === "." ||
var_name[i] === "&" ||
code > 255 // utf
) {
o += var_name[i];
} else {
o += "_$" + code + "_";
}
}
if (!isNaN(o[0])) o = "_" + o ; // first letter is number, add _ ahead.
return o;
} | 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:{right:3*rem},
bottom3:{bottom:3*rem},
left3:{left:3*rem},
top4:{top:4*rem},
right4:{right:4*rem},
bottom4:{bottom:4*rem},
left4:{left:4*rem},
z1:{zIndex:1,elevation:1},
z2:{zIndex:2,elevation:2},
z3:{zIndex:4,elevation:4},
z4:{zIndex:8,elevation:8}};
} | 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 = options.apiBaseURI;
if (! apiBaseURI) apiBaseURI = API_BASE_URI;
this.options.wsdl_url = apiBaseURI + WSDL_URL_PATH;
}
/**
* @name discoveryMode
* @type {boolean}
* @memberof module:plugins/polling-updater~PollingTagUpdater#
*/
Object.defineProperty(this, "discoveryMode", {
enumerable: true,
get: function() { return this.options.discoveryMode },
set: function(v) { this.options.discoveryMode = v }
});
let h = this.stopUpdateLoop.bind(this);
/**
* @name platform
* @type {WirelessTagPlatform}
* @memberof module:plugins/polling-updater~PollingTagUpdater#
*/
Object.defineProperty(this, "platform", {
enumerable: true,
get: function() { return this._platform },
set: function(p) {
if (this._platform && this._platform !== p) {
this._platform.removeListener('disconnect', h);
if (this.options.log === this._platform.log) {
this.options.log = undefined;
}
}
this._platform = p;
if (p) {
if (! this.options.log) this.options.log = p.log;
p.on('disconnect', h);
}
}
});
this.platform = platform;
/** @member {WirelessTagPlatform~factory} */
this.factory = this.options.factory;
} | 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
+ " to be with tag manager " + tag.mac
+ " but is reported to be with " + tagData.mac);
}
// we don't currently have anything more to do for the extra properties
// identifying the tag manager, so simply get rid of them
managerProps.forEach((k) => { delete tagData[k] });
// almost done
tag.data = tagData;
} | 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 (! factory) factory = platform.factory;
if (! factory) throw new TypeError("must have valid platform object or "
+ "object factory in discovery mode");
let mgrProm = platform.findTagManager ?
platform.findTagManager(mgrData.mac) :
Promise.resolve(factory.createTagManager(mgrData));
return mgrProm.then((mgr) => {
if (! mgr) throw new Error("no such tag manager: " + mgrData.mac);
return factory.createTag(mgr, tagData);
});
} | 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) => {
if (err) return reject(err);
resolve(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 (tagManager) args.dbid = tagManager.dbid;
soapMethod(args, function(err, result) {
if (err) return reject(err);
let tagDataList = JSON.parse(result[methodName + "Result"]);
try {
if (callback) callback(null, { object: tagManager,
value: tagDataList });
} catch (e) {
logError(console, e);
// no good reason to escalate an error thrown by callback
}
resolve(tagDataList);
});
});
if (callback) {
req = req.catch((err) => {
callback(err);
throw err;
});
}
return req;
} | 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.error(err.stack ? err.stack : err);
}
} | 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,
connection: connectionInfo
}
});
}
// execute a query on our database
client.query(query, params, function (err, result) {
// close the client
client.end();
// treat the error
if (err) {
return respond({
success: false,
data: {
err: err,
query: query,
connection: connectionInfo
}
});
}
// Return the respose
return respond({
success: true,
data: result
});
});
});
} | 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.',
query: query,
connection: connectionInfo
}
});
}
if (typeof connectionInfo.user !== 'string' || connectionInfo.user.length === 0) {
return respond({
success: false,
data: {
err: 'Bad username provided.',
query: query,
connection: connectionInfo
}
});
}
if (typeof connectionInfo.password !== 'string') {
return respond({
success: false,
data: {
err: 'Bad password provided.',
query: query,
connection: connectionInfo
}
});
}
if (typeof connectionInfo.database !== 'string' || connectionInfo.database.length === 0) {
return respond({
success: false,
data: {
err: 'Bad database provided.',
query: query,
connection: connectionInfo
}
});
}
// Return if no sql query specified
if (query.length === 0) {
return respond({
success: false,
data: {
err: 'No SQL query specified.'
}
});
}
// Create the connection to the database
connection = mysql.createConnection(connectionInfo);
// Connect to the database
connection.connect();
// Do the query
connection.query(query, params, function (err, rows, fields) {
// End the connection
connection.end();
// Return the error and stop
if (err) {
return respond({
success: false,
data: {
err: err,
query: query,
connection: connectionInfo
}
});
}
// Do the callback
respond({
success: true,
data: {
rows: rows,
fields: fields
}
});
});
} | 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 = document.createElement('script');
script.dataset.args = JSON.stringify(args);
script.dataset.source = _function +''; // get the functions source
script.textContent = (`(`+ function (script) {
const args = JSON.parse(script.dataset.args);
const _function = new Function('return ('+ script.dataset.source +').apply(this, arguments);');
script.dataset.done = true;
Promise.resolve().then(() => _function.apply(this, args)) // eslint-disable-line no-invalid-this
.then(value => report('value', value))
.catch(error => report('error', error));
function report(type, value) {
value = type === 'error' && (value instanceof Error)
? '$_ERROR_$'+ JSON.stringify({ name: value.name, message: value.message, stack: value.stack, })
: JSON.stringify(value);
script.dispatchEvent(new this.CustomEvent(type, { detail: value, })); // eslint-disable-line no-invalid-this
}
} +`).call(this, document.currentScript)`);
document.documentElement.appendChild(script).remove(); // evaluates .textContent synchronously in the page context
if (!script.dataset.done) {
throw new EvalError('Script was not executed at all'); // may fail due to sandboxing or CSP
}
function reported({ type, detail: value, }) {
if (typeof value !== 'string') { throw new Error(`Unexpected event value type in injectAsync`); }
switch (type) {
case 'value': {
resolve(JSON.parse(value));
} break;
case 'error': {
reject(parseError(value));
} break;
default: {
throw new Error(`Unexpected event "${ type }" in injectAsync`);
}
}
script.removeEventListener('value', reported);
script.removeEventListener('error', reported);
}
script.addEventListener('value', reported);
script.addEventListener('error', reported);
}); } | 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 % 4;
var l = (32 + 2 * e + 2 * i - h - k) % 7;
var m = Math.floor((a + 11 * h + 22 * l) / 451);
var n0 = h + l + 7 * m + 114;
var n = Math.floor(n0 / 31) - 1;
var p = n0 % 31 + 1;
var date = this.createDate(year, n + 1, p);
return date;
} | 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 resolveFriday();
}
}
return resolveFriday();
} | 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) {
midsummerEve = date;
}
}
});
return midsummerEve;
} | 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) {
midsummerDay = date;
}
}
});
return midsummerDay;
} | 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) {
var date = self.createDate(year, secondMonth, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.SATURDAY) {
allSaintsDay = date;
}
}
});
}
return 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={};
//
// what about transactions and transfers ??
// FIXME append 'amount_negative',
['balance','card','id','wid','email','apikey'].forEach(function (key) {
signature[key]=source[key];
});
return sortObject(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;
} catch (err) {
throw new gutil.PluginError('gulp-graphql', err, {
message: 'failed to load graphql from ' + src
});
}
if (!graphql || !introspectionQuery || !printSchema) {
throw new gutil.PluginError('gulp-graphql',
'failed to load graphql from ' + src);
}
} | 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", base.height);
}
base.scale = base.width / base.original_width;
// optional callback
if (opts.onResize) {
opts.onResize(base.width, base.height, base.scale);
}
} | 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.addEventListener('error', reject);
xhr.open('GET', url);
xhr.send();
});
} | 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);
this.timestamp = arg.timestamp || new Date();
this.subversion = arg.subversion || '/axecore:' + packageInfo.version + '/';
this.startHeight = arg.startHeight || 0;
this.relay = arg.relay === false ? false : true;
} | 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
// a new `Map`
value = populateMap(new Map(), value, Object.keys(value))
} else {
// Ensure the node is a positive number
value = validateNode(value)
}
// Set the value into the map
map.set(key, value)
// Recursive call
return populateMap(map, object, keys)
} | 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'
);
this.headers = arg;
} | 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);
message = email.message.create(headers);
this._processAttachments(message, conf.attachments);
debug(message);
if (ENV !== 'test') {
smtpClient = new email.server.connect(this.smtpConf);
smtpClient.send(message, callback);
} else {
conf.callback.call(this, null, message);
}
} | 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.ranges
rangeLength = ranges.length
rangeIndex = -1
while (++rangeIndex < rangeLength) {
range = ranges[rangeIndex]
// Ignore wildcards in lookup mode.
if (!filter && range === asterisk) {
continue
}
tagLength = tags.length
tagIndex = -1
next = []
while (++tagIndex < tagLength) {
tag = tags[tagIndex]
matches = check(tag, range)
;(matches ? result : next).push(tag)
// Exit if this is a lookup and we have a match.
if (!filter && matches) {
return tag
}
}
tags = next
}
// If this is a filter, return the list. If it’s a lookup, we didn’t find
// a match, so return `undefined`.
return filter ? result : undefined
}
} | 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"))
.pipe(source(src.replace(/^src\//, '')))
.pipe(derequire())
.pipe(gulp.dest(out));
}
b.on('update', bundle);
b.on('log', gutil.log);
return bundle();
} | 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});
}
if (yDown) {
adjacents.push({x: x + 1, y: y - 1});
}
}
if (xDown) {
adjacents.push({x: x - 1, y: y});
if (yUp) {
adjacents.push({x: x - 1, y: y + 1});
}
if (yDown) {
adjacents.push({x: x - 1, y: y - 1});
}
}
if (yUp) {
adjacents.push({x: x, y: y + 1});
}
if (yDown) {
adjacents.push({x: x, y: y - 1});
}
return adjacents;
} | 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.merkleBlock = arg;
} | 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 = 26 * column + columnStr.charCodeAt(i) - 64
}
return `R${row}C${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) / 26)) {
columnStr = String.fromCharCode(((column - 1) % 26) + 65) + columnStr
}
return columnStr + row
} | 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, data]));
} | 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_TYPES.GRAB_JOB));
this.close();
} | 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 (dispatcherType) {
dispatcher[dispatcherType](metricType, statsdKey, statsdValue);
};
for (statsdKey in statsdKeysForType) {
if (statsdKeysForType.hasOwnProperty(statsdKey)) {
statsdValue = metrics[metricType][statsdKey];
options.dispatchers.forEach(dispatchMetric);
}
}
});
} | 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[_prop].push([prop, instance]);
}
return context(_prop, _arg, true);
}
}
var result = _tracker(instance);
construct(result);
result.parent = parent ? _tracker(parent) : null;
result.root = _tracker(root || instance);
return result;
} | 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 !== val) && trigger('update', prop);
} | 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])
trigger: trigger,
toJSON: toJSON,
// internal: dependency tracking
deps: deps
});
// Wrap mutating array method to update
// state and notify listeners
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 result;
};
}
// Wrap callback of an array method to
// provide this content to the currently processed item
function proxyArrayMethod(method) {
return function(callback) {
return [][method].apply(
obj,
[function(el, i) {
return callback.apply(target(i), [].slice.call(arguments));
}].concat([].slice.call(arguments, 1))
);
};
}
if (Array.isArray(obj)) {
mixin(target, {
// Function prototype already contains length
// `len` specifies array length
len: obj.length,
pop: wrapMutatingArrayMethod('pop', function() {
trigger('delete', this.len, 1);
}),
push: wrapMutatingArrayMethod('push', function() {
trigger('insert', this.len - 1, 1);
}),
reverse: wrapMutatingArrayMethod('reverse', function() {
trigger('delete', 0, this.len);
trigger('insert', 0, this.len);
}),
shift: wrapMutatingArrayMethod('shift', function() {
trigger('delete', 0, 1);
}),
unshift: wrapMutatingArrayMethod('unshift', function() {
trigger('insert', 0, 1);
}),
sort: wrapMutatingArrayMethod('sort', function() {
trigger('delete', 0, this.len);
trigger('insert', 0, this.len);
}),
splice: wrapMutatingArrayMethod('splice', function() {
if (arguments[1]) {
trigger('delete', arguments[0], arguments[1]);
}
if (arguments.length > 2) {
trigger('insert', arguments[0], arguments.length - 2);
}
})
});
['forEach', 'every', 'some', 'filter', 'map', 'reduce', 'reduceRight']
.forEach(function(method) {
target[method] = proxyArrayMethod(method);
});
}
} | 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 result;
};
} | 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! Found unmatched parenthesis.');
}
return {
json: parsedSubformula.json,
remainder: sliceSymbol(parsedSubformula.remainder, ')')
};
} | 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 },
remainder: parsedSubformula.remainder
};
} | 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 parsedRightOperand = _parseFormula(self, sliceSymbol(currentString, binary.symbol), nextPrecedence);
return {
json: { [binary.key]: [leftOperandJSON, parsedRightOperand.json] },
remainder: parsedRightOperand.remainder
};
} | 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].toString();
if (!discovered.hasOwnProperty(point)) {
discovered[point] = true;
} else {
dupes[point] = true;
}
}
}
// Get duplicate points.
var dupe_points = [];
var dupe;
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];
if (dupes.hasOwnProperty(point.toString())) {
dupe = [point, i, poly];
dupe_points.push(dupe);
}
}
}
// Sort elements in descending order based on their indices to
// prevent future indices from becoming invalid when changes are made.
dupe_points.sort(function(a, b) {
return b[1] - a[1]
});
// Edit duplicates.
var prev, next, point, index, p1, p2;
dupe_points.forEach(function(e, i, ary) {
point = e[0], index = e[1], poly = e[2];
prev = poly.points[poly.getPrevI(index)];
next = poly.points[poly.getNextI(index)];
p1 = point.add(prev.sub(point).normalize().mul(offset));
p2 = point.add(next.sub(point).normalize().mul(offset));
// Insert new points.
poly.points.splice(index, 1, p1, p2);
poly.update();
});
} | 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.MAX_HOLIDAYS));
}
/**
* Collects holidays.
*/
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);
}
});
}
}
while (holidays.length < count) {
if (!includeWeekends) {
self.year.discardWeekends();
}
collectHolidays();
if (holidays.length < count) {
nextMonth();
}
}
return holidays;
} | 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].forEach(function(holiday) {
holidays.push(holiday);
});
});
return holidays;
} | 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 (typeof self.year.holidays[month] !== 'undefined') {
self.year.holidays[month].forEach(function(holiday) {
holidays.push(holiday);
});
}
return holidays;
} | 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(calendar.y);
} | 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;
}
else if (name === "style") {
reading_css = true;
}
},
ontext: function(text){
if (reading_js) {
scripts.push(text);
}
if (reading_css) {
styles.push(text);
}
},
onclosetag: function(tagname){
if (tagname === "script"){
reading_js = false;
}
else if (tagname === "style"){
reading_css = false;
}
}
});
parser.write(src);
parser.end();
return 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.