_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q7000
|
checkFormat
|
train
|
function checkFormat(opt_clangOptions, opt_clangFormat, opt_gulpOptions) {
var optsStr = getOptsString(opt_clangOptions);
var actualClangFormat = opt_clangFormat || clangFormat;
opt_gulpOptions = opt_gulpOptions || {};
var filePaths = [];
var pipe = combine.obj(format(opt_clangOptions, opt_clangFormat), diff());
if (opt_gulpOptions.verbose) {
pipe = combine.obj(pipe, diff.reporter({fail: false}));
}
pipe = combine.obj(
pipe,
through2({objectMode: true},
function(f, enc, done) {
if (f.diff && Object.keys(f.diff).length) filePaths.push(path.relative(process.cwd(), f.path));
done(null, f);
},
function(done) {
if (filePaths.length) {
var clangFormatBin = path.relative(process.cwd(), actualClangFormat.location);
log('WARNING: Files are not properly formatted. Please run');
log(' ' + clangFormatBin + ' -i -style="' + optsStr + '" ' +
filePaths.join(' '));
log(' (using clang-format version ' + actualClangFormat.version + ')');
var level = opt_gulpOptions.fail ? 'error' : 'warning';
pipe.emit(level,
new PluginError('gulp-clang-format', 'files not formatted'));
}
done();
}));
return pipe;
}
|
javascript
|
{
"resource": ""
}
|
q7001
|
getDctWeights
|
train
|
function getDctWeights(order, N, type = 'htk') {
const weights = new Float32Array(N * order);
const piOverN = PI / N;
const scale0 = 1 / sqrt(2);
const scale = sqrt(2 / N);
for (let k = 0; k < order; k++) {
const s = (k === 0) ? (scale0 * scale) : scale;
// const s = scale; // rta doesn't apply k=0 scaling
for (let n = 0; n < N; n++)
weights[k * N + n] = s * cos(k * (n + 0.5) * piOverN);
}
return weights;
}
|
javascript
|
{
"resource": ""
}
|
q7002
|
transformLayer
|
train
|
function transformLayer(ctx, iCanvas, layer) {
var m = layer.transform.matrix();
ctx.translate(iCanvas.width / 2, iCanvas.height / 2);
ctx.transform(m[0], m[1], m[3], m[4], m[6], m[7]);
if (layer.flip_h || layer.flip_v) {
ctx.scale(layer.flip_h ? -1 : 1, layer.flip_v ? -1 : 1);
}
ctx.translate(-layer.img.width / 2, -layer.img.height / 2);
}
|
javascript
|
{
"resource": ""
}
|
q7003
|
rectIntersect
|
train
|
function rectIntersect(r1, r2) {
var right1 = r1.x + r1.width;
var bottom1 = r1.y + r1.height;
var right2 = r2.x + r2.width;
var bottom2 = r2.y + r2.height;
var x = Math.max(r1.x, r2.x);
var y = Math.max(r1.y, r2.y);
var w = Math.max(Math.min(right1, right2) - x, 0);
var h = Math.max(Math.min(bottom1, bottom2) - y, 0);
return {x: x, y: y, width: w, height: h};
}
|
javascript
|
{
"resource": ""
}
|
q7004
|
calcLayerRect
|
train
|
function calcLayerRect(iCanvas, layer) {
var rect = transformRect(iCanvas, layer);
rect = rectIntersect(rect, {x: 0, y: 0, width: iCanvas.width, height: iCanvas.height});
return { x: Math.round(rect.x),
y: Math.round(rect.y),
width: Math.ceil(rect.width),
height: Math.ceil(rect.height)};
}
|
javascript
|
{
"resource": ""
}
|
q7005
|
getTransformedLayerData
|
train
|
function getTransformedLayerData(iCanvas, layer, rect) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = rect.width;
canvas.height = rect.height;
ctx.translate(-rect.x, -rect.y);
transformLayer(ctx, iCanvas, layer);
ctx.drawImage(layer.img, 0, 0);
return ctx.getImageData(0, 0, rect.width, rect.height);
}
|
javascript
|
{
"resource": ""
}
|
q7006
|
train
|
function (m) {
if (m !== undefined) {
// TODO Check for type and length
this.m = m;
} else {
m = new Float32Array(16);
m[0] = 1.0;
m[1] = 0.0;
m[2] = 0.0;
m[3] = 0.0;
m[4] = 0.0;
m[5] = 1.0;
m[6] = 0.0;
m[7] = 0.0;
m[8] = 0.0;
m[9] = 0.0;
m[10] = 1.0;
m[11] = 0.0;
m[12] = 0.0;
m[13] = 0.0;
m[14] = 0.0;
m[15] = 1.0;
this.m = m;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q7007
|
parse
|
train
|
function parse(str) {
str = str.replace(/\n/, ';');
str = str.replace(/RRULE:/, '');
str = str.replace(/DTSTART;/, 'DTSTART__SEMI__');
var pairs = str.split(';')
, obj = {}
;
pairs.forEach(function (pair) {
pair = pair.replace(/DTSTART__SEMI__/, 'DTSTART;');
var parts = pair.split('=')
, k = parts[0]
, ks
, param
, tzid
, vstr = parts[1]
, v
;
// Handle case of DTSTART;TZID=US-Eastern:{{yyyymmddThhmmss}} // NO Z ALLOWED
ks = k.split(';');
k = ks[0];
// TZID exists
if ('TZID' === ks[1]) {
param = ks[1].split(':');
tzid = param[0];
obj.tzid = tzid;
v = param[1];
}
// Handle case of DTSTART;LOCALE=GMT-0600 (MDT):{{yyyymmddThhmmss}} // NO Z ALLOWED
// obj.locale = obj.locale || stringifyGmtZone(obj.dtstart);
if ('LOCALE' === ks[1]) {
if (localeWarn2) {
console.warn('[parse] falling back to non-standard locale definition for timezone');
localeWarn2 = false;
}
param = vstr.split(':');
obj.locale = param[0];
// Continue with DTSTART
k = ks[0];
vstr = v = param[1];
}
switch (k) {
case 'DTSTART':
case 'UNTIL':
v = Rrecur.toRruleDateString(vstr);
break;
case 'FREQ':
case 'WKST':
v = vstr.toLowerCase();
break;
case 'INTERVAL':
case 'COUNT':
v = vstr;
break;
case 'BYWEEKDAY':
console.warn('converting rrule.js BYWEEKDAY to rrule rfc BYDAY');
k = 'BYDAY';
/* fall through */
case 'BYSETPOS':
case 'BYYEARDAY':
case 'BYMONTH':
case 'BYWEEKNO':
case 'BYDAY':
case 'BYMONTHDAY':
case 'BYHOUR':
case 'BYMINUTE':
case 'BYSECOND':
case 'BYEASTER':
v = vstr.split(',');
v.forEach(function (val, i) {
v[i] = val.toLowerCase();
});
break;
}
obj[k.toLowerCase()] = v;
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q7008
|
readDir
|
train
|
function readDir(err, files) {
if (err) {
internalServerError.call(this, err);
} else {
var dirName = decodeURIComponent(
getCurrentPathName(this)
);
this.output.push(
"<!doctype html>",
"<html>",
"<head>",
"<title>Index of ", dirName, "</title>",
'<meta name="viewport" content="',
'width=device-width,',
'initial-scale=1.0,',
'maximum-scale=1.0,',
'user-scalable=no',
'"/>',
'<meta name="generator" content="polpetta" />',
"</head>",
"<body>",
"<strong>Index of " + dirName + "</strong>",
"<ul>"
);
if (dirName != WEB_SEP) {
this.output.push(
'<li><a href="..">..</a></li>'
);
}
files.forEach(readDir.forEach, this.output);
this.output.push(
"</ul>",
"</body>",
"</html>"
);
this.output.flush(200, "text/html", "utf-8");
}
}
|
javascript
|
{
"resource": ""
}
|
q7009
|
train
|
function(prop, prefix) {
if (prop.isAbstract()) {
throw 'An interface may not contain abstract definitions. ' + prefix + ' ' + prop.getName() + ' is abstract in interface ' + definition.__interface__.name + '.';
}
if (prop.isFinal()) {
throw 'An interface may not contain final definitions. ' + prefix + ' ' + prop.getName() + ' is final in interface ' + definition.__interface__.name + '.';
}
}
|
javascript
|
{
"resource": ""
}
|
|
q7010
|
buildSchema
|
train
|
function buildSchema(jsObj, key) {
if (jsObj === undefined) return null;
var type = typeOf(jsObj);
switch (type) {
case "array":
{
let schema = {
type: "list",
detail: buildSchema(jsObj[0])
};
key && (schema.name = key);
return schema;
}
case "object":
{
let schema = {
type: "map",
detail: []
};
key && (schema.name = key);
let keys = Object.keys(jsObj);
for (var i in keys) {
let key = keys[i];
if (jsObj[key] !== undefined) {
schema.detail.push(buildSchema(jsObj[key], key));
}
}
return schema;
}
case "null":
case "string":
case "number":
case "date":
case "boolean":
{
let schema = {
type: type
};
key && (schema.name = key);
return schema;
}
default:
throw Error("Unacceptable type : " + type);
}
}
|
javascript
|
{
"resource": ""
}
|
q7011
|
requireNJS
|
train
|
function requireNJS() {
try {
var module = ru(this.path);
} catch(o_O) {
console.error(o_O);
return internalServerError.call(this, o_O);
}
module.onload(
this.request,
this.response,
this
);
}
|
javascript
|
{
"resource": ""
}
|
q7012
|
tryReaddir
|
train
|
function tryReaddir(filepath) {
var ctx = { path: filepath, files: [] };
try {
ctx.files = fs.readdirSync(filepath);
return ctx;
} catch (err) {}
try {
ctx.path = path.dirname(filepath);
ctx.files = fs.readdirSync(ctx.path);
return ctx;
} catch (err) {}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q7013
|
train
|
function(bool_return_object) {
var obj = { __joii_type: this.__joii__.name };
for (var key in this.__joii__.metadata) {
var val = this.__joii__.metadata[key];
if (val.serializable) {
var getter_name = JOII.GenerateGetterName(val);
var currentValue = null;
if (typeof (this[getter_name]) === 'function') {
// use getter if it exists. This allows custom getters to translate the data properly if needed.
currentValue = this[getter_name]();
} else {
currentValue = this[val.name];
}
if (!val.is_enum && typeof (currentValue) === 'object' && currentValue !== null) {
if ('serialize' in currentValue) {
obj[val.name] = currentValue.serialize(true);
} else {
obj[val.name] = JOII.Compat.flattenObject(currentValue);
}
} else {
obj[val.name] = currentValue;
}
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q7014
|
merge
|
train
|
function merge(oldMap, newMap) {
if (!oldMap) return newMap
if (!newMap) return oldMap
var oldMapConsumer = new SourceMapConsumer(oldMap)
var newMapConsumer = new SourceMapConsumer(newMap)
var mergedMapGenerator = new SourceMapGenerator()
// iterate on new map and overwrite original position of new map with one of old map
newMapConsumer.eachMapping(function(m) {
// pass when `originalLine` is null.
// It occurs in case that the node does not have origin in original code.
if (m.originalLine == null) return
var origPosInOldMap = oldMapConsumer.originalPositionFor({
line: m.originalLine,
column: m.originalColumn
})
if (origPosInOldMap.source == null) return
mergedMapGenerator.addMapping({
original: {
line: origPosInOldMap.line,
column: origPosInOldMap.column
},
generated: {
line: m.generatedLine,
column: m.generatedColumn
},
source: origPosInOldMap.source,
name: origPosInOldMap.name
})
})
var consumers = [oldMapConsumer, newMapConsumer]
consumers.forEach(function(consumer) {
consumer.sources.forEach(function(sourceFile) {
mergedMapGenerator._sources.add(sourceFile)
var sourceContent = consumer.sourceContentFor(sourceFile)
if (sourceContent != null) {
mergedMapGenerator.setSourceContent(sourceFile, sourceContent)
}
})
})
mergedMapGenerator._sourceRoot = oldMap.sourceRoot
mergedMapGenerator._file = oldMap.file
return JSON.parse(mergedMapGenerator.toString())
}
|
javascript
|
{
"resource": ""
}
|
q7015
|
initHannWindow
|
train
|
function initHannWindow(buffer, size, normCoefs) {
let linSum = 0;
let powSum = 0;
const step = 2 * PI / size;
for (let i = 0; i < size; i++) {
const phi = i * step;
const value = 0.5 - 0.5 * cos(phi);
buffer[i] = value;
linSum += value;
powSum += value * value;
}
normCoefs.linear = size / linSum;
normCoefs.power = sqrt(size / powSum);
}
|
javascript
|
{
"resource": ""
}
|
q7016
|
initWindow
|
train
|
function initWindow(name, buffer, size, normCoefs) {
name = name.toLowerCase();
switch (name) {
case 'hann':
case 'hanning':
initHannWindow(buffer, size, normCoefs);
break;
case 'hamming':
initHammingWindow(buffer, size, normCoefs);
break;
case 'blackman':
initBlackmanWindow(buffer, size, normCoefs);
break;
case 'blackmanharris':
initBlackmanHarrisWindow(buffer, size, normCoefs);
break;
case 'sine':
initSineWindow(buffer, size, normCoefs);
break;
case 'rectangle':
initRectangleWindow(buffer, size, normCoefs);
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q7017
|
plan
|
train
|
function plan(buhlmannTable, absPressure, isFreshWater, temperatureInCelcius) {
this.isFreshWater = isFreshWater;
this.bottomGasses = {};
this.decoGasses = {};
this.segments = [];
}
|
javascript
|
{
"resource": ""
}
|
q7018
|
endOfChunks
|
train
|
function endOfChunks() {
this.callback = fsStat.bind(this.polpetta);
if (this.boundary) {
this.i = 0;
this.received = {};
this.posted = [];
this.join("").split(this.boundary).forEach(
endOfChunks.forEach, this
);
this.i || endOfChunks.done(this, this.posted.join("&"));
} else {
endOfChunks.done(this, this.join(""));
}
}
|
javascript
|
{
"resource": ""
}
|
q7019
|
_mmult
|
train
|
function _mmult(a, m) {
m = m.slice();
var m0 = m[0];
var m1 = m[1];
var m2 = m[2];
var m3 = m[3];
var m4 = m[4];
var m5 = m[5];
var m6 = m[6];
var m7 = m[7];
var m8 = m[8];
m[0] = a[0] * m0 + a[1] * m3;
m[1] = a[0] * m1 + a[1] * m4;
m[3] = a[3] * m0 + a[4] * m3;
m[4] = a[3] * m1 + a[4] * m4;
m[6] = a[6] * m0 + a[7] * m3 + m6;
m[7] = a[6] * m1 + a[7] * m4 + m7;
return transform(m);
}
|
javascript
|
{
"resource": ""
}
|
q7020
|
getFn
|
train
|
function getFn (req, res, next) {
var reqPath = req.params[0];
debug('getFn', 'reqPath', reqPath);
stat(reqPath)
.then(function (content) {
if (!!content.type && content.type === 'file') {
return res.sendFile(reqPath, { root: ramlPath });
}
res.status(200).json(content);
}, function (err) {
if (err === 'ENOENT') {
return res.sendStatus(404);
}
next(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q7021
|
abs
|
train
|
function abs(input) {
if (!input) { return process.cwd(); }
if (input.charAt(0) === "/") { return input; }
if (input.charAt(0) === "~" && input.charAt(1) === "/") {
input = ul.HOME_DIR + input.substr(1);
}
return path.resolve(input);
}
|
javascript
|
{
"resource": ""
}
|
q7022
|
inject
|
train
|
function inject(target, source) {
for (var k in source.prototype) {
target.prototype[k] = source.prototype[k];
}
}
|
javascript
|
{
"resource": ""
}
|
q7023
|
append_nested
|
train
|
function append_nested(concater,items){
concater += `\\begin{enumerate}\n`;
for(var index in items){
concater += `\\item ${items[index].name}\n`;
// doing append job
if(items[index].subitems != undefined){
concater = append_nested(concater,items[index].subitems);
}
}
concater += `\\end{enumerate}\n`;
return concater;
}
|
javascript
|
{
"resource": ""
}
|
q7024
|
_destroy
|
train
|
function _destroy() {
var childrenLength;
if (this.element) {
this.element.remove();
}
if (this.children !== null){
childrenLength = this.children.length;
while(childrenLength > 0){
this.children[0].destroy();
if (this.children.length === childrenLength) {
this.children.shift();
}
childrenLength--;
}
}
if (this.parent) {
this.parent.removeChild(this);
}
this.children = null;
this.element = null;
}
|
javascript
|
{
"resource": ""
}
|
q7025
|
destroy
|
train
|
function destroy() {
if (this.__destroyed === true) {
console.warn('calling on destroyed object');
}
this.dispatch('beforeDestroy');
this._destroy();
this.dispatch('destroy');
this.eventListeners = null;
this.__destroyed = true;
return null;
}
|
javascript
|
{
"resource": ""
}
|
q7026
|
render
|
train
|
function render(element, beforeElement) {
if (this.__destroyed === true) {
console.warn('calling on destroyed object');
}
this.dispatch('beforeRender', {
element : element,
beforeElement : beforeElement
});
if (beforeElement) {
this.element.insertBefore(beforeElement);
} else {
this.element.appendTo(element);
}
this.dispatch('render');
return this;
}
|
javascript
|
{
"resource": ""
}
|
q7027
|
_grad
|
train
|
function _grad(hash, x, y, z) {
var h, u, v;
h = hash & 15;
u = h < 8 ? x : y;
v = h < 4 ? y : h === 12 || h === 14 ? x : z;
return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v);
}
|
javascript
|
{
"resource": ""
}
|
q7028
|
isPreBuilt
|
train
|
function isPreBuilt(indexObj, preBuiltPath) {
if (!(indexObj.isDevelopingAddon && indexObj.isDevelopingAddon()) && fs.existsSync(preBuiltPath)) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q7029
|
dockerComposeTool
|
train
|
function dockerComposeTool(beforeFunction/* :Function */,
afterFunction/* :Function */,
pathToComposeFile/* : string */,
{ startOnlyTheseServices, envName, envVars,
healthCheck, cleanUp, containerCleanUp, shouldPullImages = true, brutallyKill = false }
/* :DockerComposeToolOptions */ = {})/* : string */ {
const randomComposeEnv = envName
? extractEnvFromEnvName(envName)
: getRandomEnvironmentName(chance);
const runNameSpecific = randomComposeEnv.envName;
const runNameDisplay = `${randomComposeEnv.firstName} ${randomComposeEnv.lastName}`;
const performCleanup = cleanUp === undefined ? true : cleanUp;
const performContainerCleanup = containerCleanUp === undefined ? true : containerCleanUp;
beforeFunction(Promise.coroutine(function* () {
if (shouldPullImages) {
yield dockerPullImagesFromComposeFile(pathToComposeFile, startOnlyTheseServices);
}
if (performCleanup) {
yield cleanupOrphanEnvironments();
}
const onlyTheseServicesMessage = startOnlyTheseServices
? `, using only these services: ${startOnlyTheseServices.join(',')}`
: '';
const consoleMessage = `Docker: starting up runtime environment for this run (codenamed: ${runNameDisplay})${onlyTheseServicesMessage}... `;
const spinner = new Spinner(`${chalk.cyan(consoleMessage)}${chalk.yellow('%s')}`);
if (!process.env.NOSPIN) {
spinner.setSpinnerString('|/-\\');
spinner.start();
} else {
console.log(consoleMessage);
}
const onlyTheseServicesMessageCommandAddition = startOnlyTheseServices
? startOnlyTheseServices.join(' ')
: '';
yield exec(`docker-compose -p ${runNameSpecific} -f "${pathToComposeFile}" up -d ${onlyTheseServicesMessageCommandAddition}`,
envVars ? { env: envVars } : {});
if (!process.env.NOSPIN) {
spinner.stop();
console.log(''); // We add this in order to generate a new line after the spinner has stopped
}
if (healthCheck !== null && typeof healthCheck === 'object' && healthCheck.state === true) {
yield healthCheckMethods.verifyServicesReady(runNameSpecific,
pathToComposeFile,
healthCheck.options || {},
startOnlyTheseServices);
}
}));
afterFunction(() => {
if (performContainerCleanup) {
return cleanupContainersByEnvironmentName(runNameSpecific,
pathToComposeFile, runNameDisplay, brutallyKill);
}
return Promise.resolve();
});
return runNameSpecific;
}
|
javascript
|
{
"resource": ""
}
|
q7030
|
reverseBits
|
train
|
function reverseBits(x, bits) {
var y = 0;
for (var i = 0; i < bits; i++) {
y = (y << 1) | (x & 1);
x >>>= 1;
}
return y;
}
|
javascript
|
{
"resource": ""
}
|
q7031
|
selectorForm
|
train
|
function selectorForm(selector) {
var str;
if (selector.indexOf('[') !== -1) {
var newSelector = attributeEquals(selector);
newSelector = newSelector.replace('sel=', ''); // valid sass syntax
var firstSelector = firstPart(selector);
if (firstSelector in jquerySelectors) {
str = jquerySelectors[firstSelector]
.replace('%', '"' + newSelector + '"');
}
} else
if (selector in jquerySelectors) {
str = jquerySelectors[selector].replace('%', '');
} else {
str = '$("' + selector + '")';
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q7032
|
_getNewSection
|
train
|
function _getNewSection(line) {
var result = new RegExp(regex.section).exec(line || '');
return result && result[1];
}
|
javascript
|
{
"resource": ""
}
|
q7033
|
_isNotValidIni
|
train
|
function _isNotValidIni(line) {
var check = (line || '').match(regex.bad);
return !!(check && check.length > 1);
}
|
javascript
|
{
"resource": ""
}
|
q7034
|
getYouTubeVideoId
|
train
|
function getYouTubeVideoId(string) {
if (typeof string !== 'string') {
throw new TypeError('First argument must be a string.');
}
var match = string.match(regex);
if (match && match.length > 1) {
return match[2];
}
return string;
}
|
javascript
|
{
"resource": ""
}
|
q7035
|
link
|
train
|
function link(file, type, options) {
if (file == null || file.length === 0 || typeof file !== 'string') {
return null;
}
if (type && typeof type !== 'string') {
options = type;
type = undefined;
}
for (var i = 0; i < parsers.length; i++) {
var parser = parsers[i];
if (type ? parser.name === type : parser.pattern.test(file)) {
var Handler = new parser.Handler(file, options);
Handler.name = parser.name;
return Handler;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q7036
|
parseLoopStatement
|
train
|
function parseLoopStatement (input) {
let current = 0
let char = input[current]
// parse through keys `each **foo, bar** in x`, which is everything before
// the word "in"
const keys = []
let key = ''
while (!`${char}${lookahead(3)}`.match(/\s(in|of)\s/)) {
key += char
next()
// if we hit a comma, we're on to the next key
if (char === ',') {
keys.push(key.trim())
key = ''
next()
}
// if we reach the end of the string without getting "in/of", it's an error
if (typeof char === 'undefined') {
throw new Error("Loop statement lacking 'in' or 'of' keyword")
}
}
keys.push(key.trim())
// detect whether it's an in or of
const loopType = lookahead(2)
// space before, in/of, space after
next(4)
// the rest of the string is evaluated as the array/object to loop
let expression = ''
while (current < input.length) {
expression += char
next()
}
return {keys, expression, loopType}
// Utility: Move to the next character in the parse
function next (n = 1) {
for (let i = 0; i < n; i++) { char = input[++current] }
}
// Utility: looks ahead n characters and returns the result
function lookahead (n) {
let counter = current
const target = current + n
let res = ''
while (counter < target) {
res += input[++counter]
}
return res
}
}
|
javascript
|
{
"resource": ""
}
|
q7037
|
train
|
function (val) {
return val &&
typeof val === 'object' &&
!(val instanceof Date) &&
!(val instanceof ObjectId) &&
(!Array.isArray(val) || val.length > 0) &&
!(val instanceof Buffer);
}
|
javascript
|
{
"resource": ""
}
|
|
q7038
|
train
|
function (inData, outData, width, height, options) {
options = defaultOptions(options, {strength: 1});
var a = -clamp(options.strength, 0, 1);
convolve5x5(inData, outData, width, height,
[
[a, a, a, a, a],
[a, a, a, a, a],
[a, a, 1 - a * 24, a, a],
[a, a, a, a, a],
[a, a, a, a, a]
]);
}
|
javascript
|
{
"resource": ""
}
|
|
q7039
|
train
|
function (inData, outData, width, height) {
var c = 1 / 9;
convolve3x3(inData, outData, width, height,
[
[c, c, c],
[c, c, c],
[c, c, c]
]);
}
|
javascript
|
{
"resource": ""
}
|
|
q7040
|
train
|
function (inData, outData, width, height) {
var c = 1 / 25;
convolve5x5(inData, outData, width, height,
[
[c, c, c, c, c],
[c, c, c, c, c],
[c, c, c, c, c],
[c, c, c, c, c],
[c, c, c, c, c]
]);
}
|
javascript
|
{
"resource": ""
}
|
|
q7041
|
train
|
function (inData, outData, width, height, options) {
options = defaultOptions(options, {strength: 1});
var a = clamp(options.strength, 0, 1) * 5;
convolve3x3(inData, outData, width, height,
[
[ 0, -a, 0],
[-a, 0, a],
[ 0, a, 0]
],
false, true);
}
|
javascript
|
{
"resource": ""
}
|
|
q7042
|
train
|
function (inData, outData, width, height, options) {
options = defaultOptions(options, {amount: 1, angle: 0});
var i, n = width * height * 4,
amount = options.amount,
angle = options.angle,
x = Math.cos(-angle) * amount,
y = Math.sin(-angle) * amount,
a00 = -x - y,
a10 = -x,
a20 = y - x,
a01 = -y,
a21 = y,
a02 = -y + x,
a12 = x,
a22 = y + x,
tmpData = [];
convolve3x3(inData, tmpData, width, height,
[
[a00, a01, a02],
[a10, 0, a12],
[a20, a21, a22]
]);
for (i = 0; i < n; i += 4) {
outData[i] = 128 + tmpData[i];
outData[i + 1] = 128 + tmpData[i + 1];
outData[i + 2] = 128 + tmpData[i + 2];
outData[i + 3] = inData[i + 3];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q7043
|
train
|
function (inData, outData, width, height) {
convolve3x3(inData, outData, width, height,
[
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
],
false, true, true);
}
|
javascript
|
{
"resource": ""
}
|
|
q7044
|
train
|
function (inData, outData, width, height) {
convolve5x5(inData, outData, width, height,
[
[-1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1],
[-1, -1, 24, -1, -1],
[-1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1]
],
false, true, true);
}
|
javascript
|
{
"resource": ""
}
|
|
q7045
|
trimStringProperties
|
train
|
function trimStringProperties (obj) {
if (obj !== null && typeof obj === 'object') {
for ( var prop in obj ) {
// if the property is an object trim it too
if ( typeof obj[prop] === 'object' ) {
return trimStringProperties(obj[prop]);
}
// if it's a string remove begin and end whitespaces
if ( typeof obj[prop] === 'string' ) {
obj[prop] = obj[prop].trim();
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q7046
|
preBuild
|
train
|
function preBuild(addonPath) {
// Require the addon
let addonToBuild = require(addonPath);
// Augment it with isDevelopingAddon function.
addonToBuild.isDevelopingAddon = function() {
return true;
}
// If addon has pre-built path set in it use that else use the default path
if(!addonToBuild.PREBUILT_PATH) {
addonToBuild.PREBUILT_PATH = `${addonPath}/pre-built`;
}
fs.removeSync(addonToBuild.PREBUILT_PATH);
const ui = new UI({
inputStream: process.stdin,
outputStream: process.stdout,
errorStream: process.stderr,
writeLevel: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR',
ci: true | false
});
const project = Project.closestSync(addonPath, ui);
// Extend the current addon from base Addon
const CurrentAddon = Addon.extend(Object.assign({}, addonToBuild, {root: addonPath, pkg: project.pkg}));
const currAddon = new CurrentAddon(addonPath, project);
// Get the tree for Addon and Vendor
let addonTree = new Funnel (currAddon.treeFor('addon'), {
destDir: 'addon'
});
let vendorTree = new Funnel (currAddon.treeFor('vendor'), {
destDir: 'vendor'
});
// Merge, Build the resulting tree and store it in prebuild path
return build(new Merge([addonTree, vendorTree], { annotation: '[ember-rollup] Merging prebuild addon and vendor tree' }), addonToBuild.PREBUILT_PATH);
}
|
javascript
|
{
"resource": ""
}
|
q7047
|
generator
|
train
|
function generator(seed) {
// Note: the generator didn't work with negative seed values, so here we
// transform our original seed into a new (positive) seed value with which we
// create a new generator.
if (seed < 0) {
var gen = generator(Math.abs(seed));
for (var i = 0; i < 23; i += 1) {
gen();
}
return generator(gen(0, 10000));
}
// Based on random number generator from
// http://indiegamr.com/generate-repeatable-random-numbers-in-js/
return function (min, max) {
min = min || 0;
max = max || 1;
seed = (seed * 9301 + 49297) % 233280;
var v = seed / 233280;
return min + v * (max - min);
};
}
|
javascript
|
{
"resource": ""
}
|
q7048
|
removeExponentByOne
|
train
|
function removeExponentByOne(node) {
if (node.op === '^' && // exponent of anything
Node.Type.isConstant(node.args[1]) && // to a constant
node.args[1].value === '1') { // of value 1
const newNode = clone(node.args[0]);
return Node.Status.nodeChanged(
ChangeTypes.REMOVE_EXPONENT_BY_ONE, node, newNode);
}
return Node.Status.noChange(node);
}
|
javascript
|
{
"resource": ""
}
|
q7049
|
search
|
train
|
function search(simplificationFunction, node, preOrder) {
let status;
if (preOrder) {
status = simplificationFunction(node);
if (status.hasChanged()) {
return status;
}
}
if (Node.Type.isConstant(node) || Node.Type.isSymbol(node)) {
return Node.Status.noChange(node);
}
else if (Node.Type.isUnaryMinus(node)) {
status = search(simplificationFunction, node.args[0], preOrder);
if (status.hasChanged()) {
return Node.Status.childChanged(node, status);
}
}
else if (Node.Type.isOperator(node) || Node.Type.isFunction(node)) {
for (let i = 0; i < node.args.length; i++) {
const child = node.args[i];
const childNodeStatus = search(simplificationFunction, child, preOrder);
if (childNodeStatus.hasChanged()) {
return Node.Status.childChanged(node, childNodeStatus, i);
}
}
}
else if (Node.Type.isParenthesis(node)) {
status = search(simplificationFunction, node.content, preOrder);
if (status.hasChanged()) {
return Node.Status.childChanged(node, status);
}
}
else {
throw Error('Unsupported node type: ' + node);
}
if (!preOrder) {
return simplificationFunction(node);
}
else {
return Node.Status.noChange(node);
}
}
|
javascript
|
{
"resource": ""
}
|
q7050
|
zipObject
|
train
|
function zipObject(keys, values) {
return keys.reduce(function(object, currentValue, currentIndex) {
object[currentValue] = values[currentIndex];
return object;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q7051
|
getAll
|
train
|
function getAll(paths) {
if (paths === undefined) {
return clone(state);
}
if (!paths instanceof Array) {
throw new Error('[toystore] getAll() argument "paths" must be an array.');
}
let values = paths.map(get);
return zipObject(paths, values);
}
|
javascript
|
{
"resource": ""
}
|
q7052
|
setAll
|
train
|
function setAll(obj) {
let paths = Object.keys(obj);
paths.map(path => setSilent(path, obj[path]));
notifyWatchersOnPaths(paths);
}
|
javascript
|
{
"resource": ""
}
|
q7053
|
watch
|
train
|
function watch(paths, callback, options = {}) {
paths = paths === '*' ? paths : _pathsArray(paths);
let id = randomString();
let defaultOptions = { async: false, priority: 0 };
options = Object.assign({}, defaultOptions, options);
watchers.push({
callback,
id,
options,
paths,
});
watchers = watchers.sort(_sortByPriority);
return id;
}
|
javascript
|
{
"resource": ""
}
|
q7054
|
_deepKeys
|
train
|
function _deepKeys(obj, prefix = null) {
return Object.keys(obj).reduce(function(acc, key){
var value = obj[key];
if (_isObject(value)) {
acc.push.apply(acc, _deepKeys(value, prefix ? prefix + '.' + key : key));
} else {
acc.push(prefix ? prefix + '.' + key : key);
}
return acc;
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q7055
|
nthRootConstant
|
train
|
function nthRootConstant(node) {
let newNode = clone(node);
const radicandNode = getRadicandNode(node);
const rootNode = getRootNode(node);
if (Negative.isNegative(radicandNode)) {
return Node.Status.noChange(node);
}
else if (!Node.Type.isConstant(rootNode) || Negative.isNegative(rootNode)) {
return Node.Status.noChange(node);
}
const radicandValue = parseFloat(radicandNode.value);
const rootValue = parseFloat(rootNode.value);
const nthRootValue = math.nthRoot(radicandValue, rootValue);
// Perfect root e.g. nthRoot(4, 2) = 2
if (nthRootValue % 1 === 0) {
newNode = Node.Creator.constant(nthRootValue);
return Node.Status.nodeChanged(
ChangeTypes.NTH_ROOT_VALUE, node, newNode);
}
// Try to find if we can simplify by finding factors that can be
// pulled out of the radical
else {
// convert the number into the product of its prime factors
const factors = ConstantFactors.getPrimeFactors(radicandValue);
if (factors.length > 1) {
let substeps = [];
const factorNodes = factors.map(Node.Creator.constant);
newNode.args[0] = Node.Creator.operator('*', factorNodes);
substeps.push(Node.Status.nodeChanged(
ChangeTypes.FACTOR_INTO_PRIMES, node, newNode));
// run nthRoot on the new node
const nodeStatus = nthRootMultiplication(newNode);
if (nodeStatus.hasChanged()) {
substeps = substeps.concat(nodeStatus.substeps);
newNode = nodeStatus.newNode;
return Node.Status.nodeChanged(
ChangeTypes.NTH_ROOT_VALUE, node, newNode, true, substeps);
}
}
}
return Node.Status.noChange(node);
}
|
javascript
|
{
"resource": ""
}
|
q7056
|
getRootNode
|
train
|
function getRootNode(node) {
if (!Node.Type.isFunction(node, 'nthRoot')) {
throw Error('Expected nthRoot');
}
return node.args.length === 2 ? node.args[1] : Node.Creator.constant(2);
}
|
javascript
|
{
"resource": ""
}
|
q7057
|
sortNodes
|
train
|
function sortNodes(a, b) {
if (Node.Type.isConstant(a) && Node.Type.isConstant(b)) {
return parseFloat(a.value) - parseFloat(b.value);
}
else if (Node.Type.isConstant(a)) {
return -1;
}
else if (Node.Type.isConstant(b)) {
return 1;
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
q7058
|
isMultiplicationOfEqualNodes
|
train
|
function isMultiplicationOfEqualNodes(node) {
if (!Node.Type.isOperator(node) || node.op !== '*') {
return false;
}
// return if they are all equal nodes
return node.args.reduce((a, b) => {
return a.equals(b);
});
}
|
javascript
|
{
"resource": ""
}
|
q7059
|
LoginController
|
train
|
function LoginController($scope, $location, $http) {
var urlParams = $location.search();
Object.defineProperties(this, {
/**
* The URL of the service to redirect to.
*
* @property service
* @type String
*/
service: {
value: urlParams.service,
writable: true
}
});
}
|
javascript
|
{
"resource": ""
}
|
q7060
|
canAddLikeTermPolynomialNodes
|
train
|
function canAddLikeTermPolynomialNodes(node) {
if (!Node.Type.isOperator(node) || node.op !== '+') {
return false;
}
const args = node.args;
if (!args.every(n => Node.PolynomialTerm.isPolynomialTerm(n))) {
return false;
}
if (args.length === 1) {
return false;
}
const polynomialTermList = args.map(n => new Node.PolynomialTerm(n));
// to add terms, they must have the same symbol name *and* exponent
const firstTerm = polynomialTermList[0];
const sharedSymbol = firstTerm.getSymbolName();
const sharedExponentNode = firstTerm.getExponentNode(true);
const restTerms = polynomialTermList.slice(1);
return restTerms.every(term => {
const haveSameSymbol = sharedSymbol === term.getSymbolName();
const exponentNode = term.getExponentNode(true);
const haveSameExponent = exponentNode.equals(sharedExponentNode);
return haveSameSymbol && haveSameExponent;
});
}
|
javascript
|
{
"resource": ""
}
|
q7061
|
train
|
function (prebuild, napiVersion) {
if (prebuild) {
for (var i = 0; i < prebuild.length; i++) {
if (prebuild[i].target === napiVersion) return true
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
|
q7062
|
getTermName
|
train
|
function getTermName(node, op) {
const polyNode = new Node.PolynomialTerm(node);
// we 'name' polynomial terms by their symbol name
let termName = polyNode.getSymbolName();
// when adding terms, the exponent matters too (e.g. 2x^2 + 5x^3 can't be combined)
if (op === '+') {
const exponent = print(polyNode.getExponentNode(true));
termName += '^' + exponent;
}
return termName;
}
|
javascript
|
{
"resource": ""
}
|
q7063
|
sortTerms
|
train
|
function sortTerms(a, b) {
if (a === b) {
return 0;
}
// if no exponent, sort alphabetically
if (a.indexOf('^') === -1) {
return a < b ? -1 : 1;
}
// if exponent: sort by symbol, but then exponent decreasing
else {
const symbA = a.split('^')[0];
const expA = a.split('^')[1];
const symbB = b.split('^')[0];
const expB = b.split('^')[1];
if (symbA !== symbB) {
return symbA < symbB ? -1 : 1;
}
else {
return expA > expB ? -1 : 1;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q7064
|
getSolutionByNum
|
train
|
function getSolutionByNum(solutionSet, num) {
if(solutionSet.computed.length >= num && num >= 1) {
if(solutionSet.computed.length == num) { // If we select the last computed solution, we checked if we can compute more solutions.
if(solutionSet.remaining !== false) {
console.log("Checking for ambiguity #" + (num + 1));
var lt = sns.lazyList.tail(solutionSet.remaining);
var newSolution = getOneSolution(solutionSet.path, solutionSet.serverFileContent, lt);
if(newSolution === false) {
console.log("No more ambiguity");
solutionSet.remaining = false;
} else {
console.log("Ambiguity #" + (num + 1) + " found");
solutionSet.remaining = lt;
solutionSet.computed.push(newSolution);
}
}
}
return solutionSet.computed[num - 1];
} else {
console.log(`Requested invalid solution number ${num}. Returning the first`)
return solutionSet.computed[0];
}
}
|
javascript
|
{
"resource": ""
}
|
q7065
|
_createParticle
|
train
|
function _createParticle(profile, { width, height }) {
const { random } = Math;
const {
deltaX,
deltaY,
deltaOpacity,
radius,
color,
opacity
} = getParticleValues(profile);
return {
init() {
this.x = random() * width;
this.y = random() * -height;
this.deltaX = deltaX;
this.deltaY = deltaY;
this.color = color;
this.radius = radius;
this.opacity = opacity;
this.deltaOpacity = deltaOpacity;
return this;
}
};
}
|
javascript
|
{
"resource": ""
}
|
q7066
|
train
|
function ( query, associations ) {
_.each( associations, function ( assoc ) {
// if the associations is to be populated with the full records...
if ( assoc.include === "record" ) query.populate( assoc.alias );
} );
return query;
}
|
javascript
|
{
"resource": ""
}
|
|
q7067
|
train
|
function ( req ) {
// Allow customizable blacklist for params NOT to include as criteria.
req.options.criteria = req.options.criteria || {};
req.options.criteria.blacklist = req.options.criteria.blacklist || [ 'limit', 'skip', 'sort', 'populate' ];
// Validate blacklist to provide a more helpful error msg.
var blacklist = req.options.criteria && req.options.criteria.blacklist;
if ( blacklist && !_.isArray( blacklist ) ) {
throw new Error( 'Invalid `req.options.criteria.blacklist`. Should be an array of strings (parameter names.)' );
}
// Look for explicitly specified `where` parameter.
var where = req.params.all().where;
// If `where` parameter is a string, try to interpret it as JSON
if ( _.isString( where ) ) {
where = tryToParseJSON( where );
}
// If `where` has not been specified, but other unbound parameter variables
// **ARE** specified, build the `where` option using them.
if ( !where ) {
// Prune params which aren't fit to be used as `where` criteria
// to build a proper where query
where = req.params.all();
// Omit built-in runtime config (like query modifiers)
where = _.omit( where, blacklist || [ 'limit', 'skip', 'sort' ] );
// Omit any params w/ undefined values
where = _.omit( where, function ( p ) {
if ( _.isUndefined( p ) ) return true;
} );
// Transform ids[ .., ..] request
if ( where.ids ) {
where.id = where.ids;
delete where.ids;
}
// Omit jsonp callback param (but only if jsonp is enabled)
var jsonpOpts = req.options.jsonp && !req.isSocket;
jsonpOpts = _.isObject( jsonpOpts ) ? jsonpOpts : {
callback: JSONP_CALLBACK_PARAM
};
if ( jsonpOpts ) {
where = _.omit( where, [ jsonpOpts.callback ] );
}
}
// Merge w/ req.options.where and return
where = _.merge( {}, req.options.where || {}, where ) || undefined;
return where;
}
|
javascript
|
{
"resource": ""
}
|
|
q7068
|
addNumeratorsTogether
|
train
|
function addNumeratorsTogether(node) {
const newNode = clone(node);
newNode.args[0] = Node.Creator.constant(newNode.args[0].eval());
return Node.Status.nodeChanged(
ChangeTypes.ADD_NUMERATORS, node, newNode);
}
|
javascript
|
{
"resource": ""
}
|
q7069
|
reduceExponentByZero
|
train
|
function reduceExponentByZero(node) {
if (node.op !== '^') {
return Node.Status.noChange(node);
}
const exponent = node.args[1];
if (Node.Type.isConstant(exponent) && exponent.value === '0') {
const newNode = Node.Creator.constant(1);
return Node.Status.nodeChanged(
ChangeTypes.REDUCE_EXPONENT_BY_ZERO, node, newNode);
}
else {
return Node.Status.noChange(node);
}
}
|
javascript
|
{
"resource": ""
}
|
q7070
|
navMap_post_defaults
|
train
|
function navMap_post_defaults(map, index, parent){
replaceValues(map, {
//propertyName : "forced overide value"
//link : '#',//using this would disable ALL links (including links already defined in the main nav map file)
});
return {
depth: map.location.length,
index: index,
//link : '#',//this wouldn't do anything as the "link" property has already been defined by this stage
//parentName : parent.title,//this would set "parentName" to the current nav items parent title
}
}
|
javascript
|
{
"resource": ""
}
|
q7071
|
getWindow
|
train
|
function getWindow(node) {
if (isWindow(node)) {
return node;
}
var doc = getDocument(node);
if (needsIEFallback) {
// In IE 6-8, only the variable 'window' can be used to connect events (others
// may be only copies).
doc.parentWindow.execScript('document._parentWindow = window;', 'Javascript');
var win = doc._parentWindow;
// to prevent memory leak, unset it after use
// another possibility is to add an onUnload handler,
// (which seems overkill to @liucougar)
doc._parentWindow = null;
return win;
} else {
// standards-compliant and newer IE
return doc.defaultView || doc.parentWindow;
}
}
|
javascript
|
{
"resource": ""
}
|
q7072
|
train
|
function(block, parent) {
if (!block.nodes.length) return false;
// line count
var lines = block.nodes[block.nodes.length - 1].line - block.nodes[0].line + 1;
if (lines === 1) return false;
// word count of Text node values
var words = 0;
// number of Code nodes that are in their own lines
var codesWithOwnLine = 0;
// if the previous node was the first in its line
var prevStartLine = false;
for (var i = 0; i < block.nodes.length; i++) {
var node = block.nodes[i];
var prev = block.nodes[i - 1] || parent || {line: -1};
var next = block.nodes[i];
if (node.type === 'Text') {
words += (node.val.match(/\w+(\s+|$)/g) || []).length;
} else if (node.type === 'Code' && node.buffer && !node.block) {
if ((node.line > prev.line || prev.type === 'Text' && prev.val === '\n') && prevStartLine) {
codesWithOwnLine++;
}
} else {
// Technically Tags can also be interpolated, but determine whether to
// use multiple dot blocks or one single dot block is way too
// complicated. KISS.
return false;
}
prevStartLine = node.line > prev.line || prev.type === 'Text' && prev.val === '\n';
}
return words > 0 && codesWithOwnLine / lines < 0.35;
}
|
javascript
|
{
"resource": ""
}
|
|
q7073
|
negativeCoefficient
|
train
|
function negativeCoefficient(node) {
if (NodeType.isConstant(node)) {
node = NodeCreator.constant(0 - parseFloat(node.value));
}
else {
const numeratorValue = 0 - parseFloat(node.args[0].value);
node.args[0] = NodeCreator.constant(numeratorValue);
}
return node;
}
|
javascript
|
{
"resource": ""
}
|
q7074
|
orderCoords
|
train
|
function orderCoords(coords){
if (config.coordinateOrder){
return coords;
}
if (coords[2]){
return [coords[1], coords[0], coords[2]];
}
return coords.reverse();
}
|
javascript
|
{
"resource": ""
}
|
q7075
|
multi
|
train
|
function multi(name, memberName, membercb, geom, gmlId, params={}){
var {srsName, gmlIds} = params;
let multi = `<gml:${name}${attrs({srsName, 'gml:id':gmlId})}>`;
multi += `<gml:${memberName}>`;
geom.forEach(function(member, i){
let _gmlId = member.id || (gmlIds || [])[i] || '';
if (name == 'MultiGeometry'){
let memberType = member.type;
member = member.coordinates;
multi += membercb[memberType](member, _gmlId, params);
} else {
multi += membercb(member, _gmlId, params);
}
});
multi += `</gml:${memberName}>`;
return multi + `</gml:${name}>`;
}
|
javascript
|
{
"resource": ""
}
|
q7076
|
makeConverter
|
train
|
function makeConverter(obj) {
return Object.entries(obj).map(([type, converter]) => {
return {[type[0].toUpperCase() + type.slice(1)]: converter};
}).reduce((a, b) => Object.assign(a, b), {});
}
|
javascript
|
{
"resource": ""
}
|
q7077
|
performTermOperationOnEquation
|
train
|
function performTermOperationOnEquation(equation, op, term, changeType) {
const oldEquation = equation.clone();
const leftTerm = clone(term);
const rightTerm = clone(term);
const leftNode = performTermOperationOnExpression(
equation.leftNode, op, leftTerm);
const rightNode = performTermOperationOnExpression(
equation.rightNode, op, rightTerm);
let comparator = equation.comparator;
if (Negative.isNegative(term) && (op === '*' || op === '/')) {
comparator = COMPARATOR_TO_INVERSE[comparator];
}
const newEquation = new Equation(leftNode, rightNode, comparator);
return new EquationStatus(changeType, oldEquation, newEquation);
}
|
javascript
|
{
"resource": ""
}
|
q7078
|
performTermOperationOnExpression
|
train
|
function performTermOperationOnExpression(expression, op, term) {
const node = (Node.Type.isOperator(expression) ?
Node.Creator.parenthesis(expression) : expression);
term.changeGroup = 1;
const newNode = Node.Creator.operator(op, [node, term]);
return newNode;
}
|
javascript
|
{
"resource": ""
}
|
q7079
|
canMultiplyLikeTermPolynomialNodes
|
train
|
function canMultiplyLikeTermPolynomialNodes(node) {
if (!Node.Type.isOperator(node) || node.op !== '*') {
return false;
}
const args = node.args;
if (!args.every(n => Node.PolynomialTerm.isPolynomialTerm(n))) {
return false;
}
if (args.length === 1) {
return false;
}
const polynomialTermList = node.args.map(n => new Node.PolynomialTerm(n));
if (!polynomialTermList.every(polyTerm => !polyTerm.hasCoeff())) {
return false;
}
const firstTerm = polynomialTermList[0];
const restTerms = polynomialTermList.slice(1);
// they're considered like terms if they have the same symbol name
return restTerms.every(term => firstTerm.getSymbolName() === term.getSymbolName());
}
|
javascript
|
{
"resource": ""
}
|
q7080
|
simulatedUserInput
|
train
|
function simulatedUserInput(numArray) {
// pause + first one
// forEach after the first: outer + inner
const rest$ = numOrArray => {
if (!numOrArray.length) return after(pause, () => numOrArray)
let rest = after(pause, () => numOrArray[0])
for (let i = 1; i < numOrArray.length; i++) {
rest = concat(rest, after(outer, () => numOrArray[i]))
}
return rest
}
return from(numArray).pipe(concatMap(rest$))
}
|
javascript
|
{
"resource": ""
}
|
q7081
|
getUserInputFromStdin
|
train
|
function getUserInputFromStdin() {
// set up stdin
const keypress = require("keypress")
keypress(process.stdin)
process.stdin.setRawMode(true)
process.stdin.resume()
// A Subject is something that you can push values at, and
// it can be subscribed to as an Observable of those values
const s = new Subject()
// set up handler and return the stream as Observable
process.stdin.on("keypress", (ch, key = {}) => {
if (key.name == "x" || (key && key.ctrl && key.name == "c")) {
process.stdin.pause()
s.complete()
log("\nBye!")
process.exit()
}
if (ch === "0" || Number(ch)) {
s.next(Number(ch))
} else {
process.stdin.pause()
log("Not 0-9.\nBye!")
s.complete()
}
})
return s.asObservable()
}
|
javascript
|
{
"resource": ""
}
|
q7082
|
getTitleMap
|
train
|
function getTitleMap(startMap, userSearchTerm, isRecursive) {
var returnValue = false;
var found = false;
var isRecursive = defaultTo(isRecursive, true);
function iterator(map, searchTerm){
for(var i = 0; i < map.length; i++) {
var item = map[i];
//removes any html in the strings before searching for a match
var itemTitle = stripTags(item.title).toLowerCase();
var providedTitle = stripTags(searchTerm).toLowerCase();
//also converts strings to lowercase so they aren't case sensitive
if (itemTitle === providedTitle){
//if the provided title matches the current item title, set the return value to current item
returnValue = item;
found = true;
break;
} else if ('subnav' in item && isRecursive){
iterator(item.subnav, searchTerm);
if (found){
break;
}
}
}
}
iterator(startMap.subnav, userSearchTerm);
if (returnValue === false){
//shouldn't do this unless the function fails
console.log('\n"'+ userSearchTerm +'" title could not be found in navMap.json');
}
return returnValue;
}
|
javascript
|
{
"resource": ""
}
|
q7083
|
checkSearchTerm
|
train
|
function checkSearchTerm(searchTerm){
if (!is_string(searchTerm) && !is_numeric(searchTerm)){
console.log('\nError: This must be either a string or an interval:\n', searchTerm, ' \n');
return false;
} else {
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
q7084
|
getSpecificMap
|
train
|
function getSpecificMap(map, array){
var returnMap;
var arrayCopy = array.splice(0);
//if first item in array is "current" or "subnav" it makes the function a bit more efficient
//it restricts any title searches to just offspring of the current page
if (array[0] === 'current' || array[0] === 'subnav'){
arrayCopy.shift();
arrayCopy = pageMap.location.concat(link);
}
for (var i = 0; i < arrayCopy.length; i++){
var searchTerm = arrayCopy[i];
var searchMap = typeof returnMap !== 'undefined' ? returnMap : map;
//Output an error if neither a string or an interval provided
if (checkSearchTerm(searchTerm)){
if (is_string(searchTerm)){
//if item is a string, do a getTitleMap function on the search term using the last map
returnMap = getTitleMap(searchMap, searchTerm);
} else if(is_numeric(searchTerm) && isset(searchMap.subnav)) {
//if item is a number, return the map at the specified index of the last map in array
returnMap = searchMap.subnav[parseInt(searchTerm)];
} else {
returnMap = false;
break;
}
} else {
break;
}
}
if (returnMap){
return returnMap;
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q7085
|
getNavMap
|
train
|
function getNavMap(navMap, searchTerm, portion){
let returnMap = navMap;
if (!isset(searchTerm) || is_array(searchTerm) && searchTerm.length === 0){
//if the search term is an empty array, it will return the full nav map (excluding ROOT)
return returnMap;
}
//code for when an array is given (filters results based on numbers and titles provided in array)
if (is_array(searchTerm)){
returnMap = getSpecificMap(returnMap, searchTerm);
//code for when a string is given (searches full nav map for Title that matches)
} else if (is_string(searchTerm)) {
returnMap = getTitleMap(returnMap, searchTerm);
//code for when a single number is given (treats it as a single level location variable)
} else if (is_int(searchTerm)) {
returnMap = returnMap[searchTerm];
//throws error if searchTerm variable doesn't make sense
} else {
console.log('\nThe search term must be either a string, interval or an array. \nSearch term =\n', searchTerm);
}
if (isset(portion)) {
return returnMap[portion];
} else {
return returnMap;
}
}
|
javascript
|
{
"resource": ""
}
|
q7086
|
castInterpolate
|
train
|
function castInterpolate(template, replacements, options) {
var matches = template.match(regExp);
var placeholder;
var not;
if (matches) {
placeholder = matches[1];
// Check if exists first
if (mout.object.has(replacements, placeholder)) {
return mout.object.get(replacements, placeholder);
}
// Handle not (!) (note that !foo! is ignored but !foo isn't)
if (/^!+?[^!]+$/.test(placeholder)) {
placeholder = placeholder.replace(/!!+/, '');
not = placeholder.charAt(0) === '!';
placeholder = not ? placeholder.substr(1) : placeholder;
if (mout.object.has(replacements, placeholder)) {
placeholder = mout.object.get(replacements, placeholder);
return not ? !placeholder : !!placeholder;
}
}
}
return interpolate(template, replacements, options);
}
|
javascript
|
{
"resource": ""
}
|
q7087
|
reduceMultiplicationByZero
|
train
|
function reduceMultiplicationByZero(node) {
if (node.op !== '*') {
return Node.Status.noChange(node);
}
const zeroIndex = node.args.findIndex(arg => {
if (Node.Type.isConstant(arg) && arg.value === '0') {
return true;
}
if (Node.PolynomialTerm.isPolynomialTerm(arg)) {
const polyTerm = new Node.PolynomialTerm(arg);
return polyTerm.getCoeffValue() === 0;
}
return false;
});
if (zeroIndex >= 0) {
// reduce to just the 0 node
const newNode = Node.Creator.constant(0);
return Node.Status.nodeChanged(
ChangeTypes.MULTIPLY_BY_ZERO, node, newNode);
}
else {
return Node.Status.noChange(node);
}
}
|
javascript
|
{
"resource": ""
}
|
q7088
|
speakIt
|
train
|
function speakIt({ action }) {
const { toSpeak } = action.payload
// Remember: unlike Promises, which share a similar construction,
// the observable function is not run until the Observable recieves
// a subscribe() call.
return new Observable(observer => {
try {
const say = require("say")
say.speak(toSpeak, null, null, () => {
observer.complete()
})
// An Observable allows for cancellation by returning a
// cancellation function
return () => {
say.stop()
}
} catch (error) {
log("-- speech synthesis not available --")
observer.error()
}
})
}
|
javascript
|
{
"resource": ""
}
|
q7089
|
removeUnnecessaryParens
|
train
|
function removeUnnecessaryParens(node, rootNode=false) {
// Parens that wrap everything are redundant.
// NOTE: removeUnnecessaryParensSearch recursively removes parens that aren't
// needed, while this step only applies to the very top level expression.
// e.g. (2 + 3) * 4 can't become 2 + 3 * 4, but if (2 + 3) as a top level
// expression can become 2 + 3
if (rootNode) {
while (Node.Type.isParenthesis(node)) {
node = node.content;
}
}
return removeUnnecessaryParensSearch(node);
}
|
javascript
|
{
"resource": ""
}
|
q7090
|
removeUnnecessaryParensInOperatorNode
|
train
|
function removeUnnecessaryParensInOperatorNode(node) {
node.args.forEach((child, i) => {
node.args[i] = removeUnnecessaryParensSearch(child);
});
// Sometimes, parens are around expressions that have been simplified
// all they can be. If that expression is part of an addition or subtraction
// operation, we can remove the parenthesis.
// e.g. (x+4) + 12 -> x+4 + 12
if (node.op === '+') {
node.args.forEach((child, i) => {
if (Node.Type.isParenthesis(child) &&
!canCollectOrCombine(child.content)) {
// remove the parens by replacing the child node (in its args list)
// with its content
node.args[i] = child.content;
}
});
}
// This is different from addition because when subtracting a group of terms
//in parenthesis, we want to distribute the subtraction.
// e.g. `(2 + x) - (1 + x)` => `2 + x - (1 + x)` not `2 + x - 1 + x`
else if (node.op === '-') {
if (Node.Type.isParenthesis(node.args[0]) &&
!canCollectOrCombine(node.args[0].content)) {
node.args[0] = node.args[0].content;
}
}
return node;
}
|
javascript
|
{
"resource": ""
}
|
q7091
|
removeUnnecessaryParensInFunctionNode
|
train
|
function removeUnnecessaryParensInFunctionNode(node) {
node.args.forEach((child, i) => {
if (Node.Type.isParenthesis(child)) {
child = child.content;
}
node.args[i] = removeUnnecessaryParensSearch(child);
});
return node;
}
|
javascript
|
{
"resource": ""
}
|
q7092
|
canCollectOrCombine
|
train
|
function canCollectOrCombine(node) {
return LikeTermCollector.canCollectLikeTerms(node) ||
checks.resolvesToConstant(node) ||
checks.canSimplifyPolynomialTerms(node);
}
|
javascript
|
{
"resource": ""
}
|
q7093
|
Invoker
|
train
|
function Invoker(zk, opt) {
if (!(this instanceof Invoker)) return new Invoker(zk, opt);
var option = opt || {};
this._path = option.path;
this._dubbo = option.dubbo;
this._version = option.version;
this._timeout = option.timeout;
this._poolMax = option.poolMax;
this._poolMin = option.poolMin;
this._providers = null; // Array
this._configurators = null; // Object
this._loadBalance = new RandomLoadBalance();
this._parseProviders = this._parseProviders.bind(this);
this._parseConfigurators = this._parseConfigurators.bind(this);
if ('string' === typeof zk) {
this._uris = [zk];
} else if (Array.isArray(zk)) {
this._uris = zk;
} else if (zk) {
this._registerProviders = new Register(zk, '/dubbo/' + this._path + '/providers');
this._registerConfigurators = new Register(zk, '/dubbo/' + this._path + '/configurators');
this._registerProviders.on('change', this._parseProviders);
this._registerConfigurators.on('change', this._parseConfigurators);
}
}
|
javascript
|
{
"resource": ""
}
|
q7094
|
_expandNestedPaths
|
train
|
function _expandNestedPaths(paths) {
var expandedPaths = [];
_pathsArray(paths).forEach(function (p) {
if (p.indexOf('.') !== -1) {
var pathsWithRoots = p.split('.').map(function (value, index, array) {
return array.slice(0, index + 1).join('.');
});
expandedPaths = expandedPaths.concat(pathsWithRoots);
} else {
expandedPaths.push(p);
}
});
return expandedPaths;
}
|
javascript
|
{
"resource": ""
}
|
q7095
|
train
|
function(remoteID, keycode) {
if (!config.opened && config.pinNumber !== null) this.open(config.pinNumber);
if (!config.opened) throw new Error('Trying to write with no pins opened');
debugMsg("sendButton: remoteID: " + remoteID + " keycode: " + keycode);
// how many times to transmit a command
for (pulse= 0; pulse <= config.repeats; pulse++) {
sendPulse(1); // Start
config.high = true; // first pulse is always high
// transmit remoteID
for (i = 15; i >= 0; i--) {
var txPulse = remoteID & (1 << i); // read bits from remote ID
if (txPulse > 0) {
selectPulse(1);
} else {
selectPulse(0);
}
}
// transmit keycode
for (i = 6; i >= 0; i--)
{
var txPulse = keycode & (1 << i); // read bits from keycode
if (txPulse > 0) {
selectPulse(1);
} else {
selectPulse(0);
}
}
}
rpio.write(config.pinNumber, rpio.LOW);
}
|
javascript
|
{
"resource": ""
}
|
|
q7096
|
removeMultiplicationByOne
|
train
|
function removeMultiplicationByOne(node) {
if (node.op !== '*') {
return Node.Status.noChange(node);
}
const oneIndex = node.args.findIndex(arg => {
return Node.Type.isConstant(arg) && arg.value === '1';
});
if (oneIndex >= 0) {
let newNode = clone(node);
// remove the 1 node
newNode.args.splice(oneIndex, 1);
// if there's only one operand left, there's nothing left to multiply it
// to, so move it up the tree
if (newNode.args.length === 1) {
newNode = newNode.args[0];
}
return Node.Status.nodeChanged(
ChangeTypes.REMOVE_MULTIPLYING_BY_ONE, node, newNode);
}
return Node.Status.noChange(node);
}
|
javascript
|
{
"resource": ""
}
|
q7097
|
maybeFlattenPolynomialTerm
|
train
|
function maybeFlattenPolynomialTerm(node) {
// We recurse on the left side of the tree to find operands so far
const operands = getOperands(node.args[0], '*');
// If the last operand (so far) under * was a constant, then it's a
// polynomial term.
// e.g. 2*5*6x creates a tree where the top node is implicit multiplcation
// and the left branch goes to the tree with 2*5*6, and the right operand
// is the symbol x. We want to check that the last argument on the left (in
// this example 6) is a constant.
const lastOperand = operands.pop();
// in the above example, node.args[1] would be the symbol x
const nextOperand = flattenOperands(node.args[1]);
// a coefficient can be constant or a fraction of constants
if (Node.Type.isConstantOrConstantFraction(lastOperand)) {
// we replace the constant (which we popped) with constant*symbol
operands.push(
Node.Creator.operator('*', [lastOperand, nextOperand], true));
}
// Now we know it isn't a polynomial term, it's just another seperate operand
else {
operands.push(lastOperand);
operands.push(nextOperand);
}
return operands;
}
|
javascript
|
{
"resource": ""
}
|
q7098
|
flattenDivision
|
train
|
function flattenDivision(node) {
// We recurse on the left side of the tree to find operands so far
// Flattening division is always considered part of a bigger picture
// of multiplication, so we get operands with '*'
let operands = getOperands(node.args[0], '*');
if (operands.length === 1) {
node.args[0] = operands.pop();
node.args[1] = flattenOperands(node.args[1]);
operands = [node];
}
else {
// This is the last operand, the term we'll want to add our division to
const numerator = operands.pop();
// This is the denominator of the current division node we're recursing on
const denominator = flattenOperands(node.args[1]);
// Note that this means 2 * 3 * 4 / 5 / 6 * 7 will flatten but keep the 4/5/6
// as an operand - in simplifyDivision.js this is changed to 4/(5*6)
const divisionNode = Node.Creator.operator('/', [numerator, denominator]);
operands.push(divisionNode);
}
return operands;
}
|
javascript
|
{
"resource": ""
}
|
q7099
|
removeAdditionOfZero
|
train
|
function removeAdditionOfZero(node) {
if (node.op !== '+') {
return Node.Status.noChange(node);
}
const zeroIndex = node.args.findIndex(arg => {
return Node.Type.isConstant(arg) && arg.value === '0';
});
let newNode = clone(node);
if (zeroIndex >= 0) {
// remove the 0 node
newNode.args.splice(zeroIndex, 1);
// if there's only one operand left, there's nothing left to add it to,
// so move it up the tree
if (newNode.args.length === 1) {
newNode = newNode.args[0];
}
return Node.Status.nodeChanged(
ChangeTypes.REMOVE_ADDING_ZERO, node, newNode);
}
return Node.Status.noChange(node);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.