_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q41100 | train | function (e) {
var chart = e.target,
i,
elem;
// Destroy the extra buttons added
for (i = 0; i < chart.exportSVGElements.length; i++) {
elem = chart.exportSVGElements[i];
// Destroy and null the svg/vml elements
if (elem) { // #1822
elem.onclick = elem.ontouchstart = null;
chart.exportSVGElements[i] = elem.destroy();
}
}
// Destroy the divs for the menu
for (i = 0; i < chart.exportDivElements.length; i++) {
elem = chart.exportDivElements[i];
// Remove the event handler
removeEvent(elem, 'mouseleave');
// Remove inline events
chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null;
// Destroy the div by moving to garbage bin
discardElement(elem);
}
} | javascript | {
"resource": ""
} | |
q41101 | InternalOpenIDError | train | function InternalOpenIDError(message, err) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'InternalOpenIDError';
this.message = message;
this.openidError = err;
} | javascript | {
"resource": ""
} |
q41102 | printCollectedDeviceData | train | function printCollectedDeviceData(results) {
var dataToKeep = {
'AIN0': 'val',
'FIRMWARE_VERSION': 'val',
'WIFI_IP': 'str',
'ETHERNET_IP': 'str',
'WIFI_RSSI': 'str',
'WIFI_VERSION': 'val',
'SERIAL_NUMBER': 'val',
'HARDWARE_INSTALLED': 'productType',
};
var vals = [];
results.forEach(function(result) {
result = result.data;
var data = {};
var keyToKeep = 'res';
if(dataToKeep[result.name]) {
keyToKeep = dataToKeep[result.name];
}
data[result.name] = result.res;
if(result[keyToKeep]) {
data[result.name] = result[keyToKeep];
}
vals.push(data);
});
if(DEBUG_COLLECTED_DEVICE_DATA) {
console.log('Connection Type', self.curatedDevice.savedAttributes.connectionTypeName);
console.log('Serial Number', self.curatedDevice.savedAttributes.serialNumber);
console.log('Read Data', self.curatedDevice.getDevice().handle,':');
console.log(vals);
}
} | javascript | {
"resource": ""
} |
q41103 | curatedDeviceDisconnected | train | function curatedDeviceDisconnected(eventData) {
self.log(' *** Handle', self.handle, 'triggered event: DEVICE_DISCONNECTED', eventData.name, eventData.operation);
} | javascript | {
"resource": ""
} |
q41104 | linkToCuratedDeviceEvents | train | function linkToCuratedDeviceEvents() {
self.curatedDevice.on(
'DEVICE_DISCONNECTED',
curatedDeviceDisconnected
);
self.curatedDevice.on(
'DEVICE_RECONNECTED',
curatedDeviceReconnected
);
self.curatedDevice.on(
'DEVICE_ERROR',
curatedDeviceError
);
self.curatedDevice.on(
'DEVICE_RECONNECTING',
curatedDeviceReconnecting
);
self.curatedDevice.on(
'DEVICE_ATTRIBUTES_CHANGED',
cureatedDeviceAttributesChanged
);
} | javascript | {
"resource": ""
} |
q41105 | unlinkFromCuratedDeviceEvents | train | function unlinkFromCuratedDeviceEvents() {
self.curatedDevice.removeListener(
'DEVICE_DISCONNECTED',
curatedDeviceDisconnected
);
self.curatedDevice.removeListener(
'DEVICE_RECONNECTED',
curatedDeviceReconnected
);
self.curatedDevice.removeListener(
'DEVICE_ERROR',
curatedDeviceError
);
self.curatedDevice.removeListener(
'DEVICE_RECONNECTING',
curatedDeviceReconnecting
);
self.curatedDevice.removeListener(
'DEVICE_ATTRIBUTES_CHANGED',
cureatedDeviceAttributesChanged
);
} | javascript | {
"resource": ""
} |
q41106 | saveCollectedDeviceData | train | function saveCollectedDeviceData(results) {
self.log('Finished Collecting Data from Device:', self.handle);
// Loop through each of the results.
results.forEach(function(result) {
// De-reference the actual data
var data = result.data;
// Determine what register was saved
var name = data.name;
// Save the data to the cached device results object.
self.cachedDeviceResults[name] = data;
});
} | javascript | {
"resource": ""
} |
q41107 | innerCollectDeviceData | train | function innerCollectDeviceData(infoToCache) {
var defered = q.defer();
self.dataCollectionDefered = defered;
self.log('Collecting Data from a handle', self.handle);
// Indicate that this device was opened by the device scanner.
self.openedByScanner = true;
var deviceHandle = self.handle;
var dt = self.openParameters.deviceType;
var ct = self.openParameters.connectionType;
var id = self.openParameters.identifier;
// Initialize a curated device object.
self.curatedDevice = new device_curator.device();
// Link the device handle to the curated device object.
self.curatedDevice.linkToHandle(deviceHandle, dt, ct, id)
.then(function finishedLinkingHandle(res) {
self.log(
'Finished linking to a handle',
deviceHandle,
self.curatedDevice.savedAttributes.connectionTypeName
);
// Create a data collection timeout.
var collectionTimeout = setTimeout(
deviceHandleDataCollectionTimeout,
DEVICE_DATA_COLLECTION_TIMEOUT
);
// Attach event listeners to the curated device.
linkToCuratedDeviceEvents();
console.log('reading multiple...', deviceHandle);
// Collect information from the curated device.
self.curatedDevice.iReadMultiple(infoToCache)
.then(function finishedCollectingData(results) {
// Clear the data collection timeout
clearTimeout(collectionTimeout);
self.log('Collecting data from a handle', deviceHandle);
printCollectedDeviceData(results);
saveCollectedDeviceData(results);
// Report that the device is finished collecting data.
stopCollectingDeviceData();
}, function(err) {
self.log('Error collecting data from a handle', deviceHandle, err);
// Report that the device is finished collecting data.
stopCollectingDeviceData();
});
}, function errorLinkingHandle(err) {
console.error('Error linking to handle...');
defered.resolve();
});
return defered.promise;
} | javascript | {
"resource": ""
} |
q41108 | lodashRequire | train | function lodashRequire(functionName) {
var moduleId = getLodashId(functionName);
try {
var method = localRequire(moduleId);
method.toString = lodashFunctionToString(functionName);
return method;
} catch (err) {
throw new ReferenceError('Could not find '+functionName+', did you forget to install '+moduleId);
}
} | javascript | {
"resource": ""
} |
q41109 | getPathStack | train | function getPathStack() {
return (module.parent || module).paths.map(function(path) {
return lop(path)
}).filter(function(path) {
return (path !== '');
});
} | javascript | {
"resource": ""
} |
q41110 | loadPackageModules | train | function loadPackageModules(packages, packageData, modType) {
Object.keys(packageData[modType] || {}).forEach(function(packageName) {
if (lodashTest.test(packageName)) packages.push(tryModule(packageName));
});
} | javascript | {
"resource": ""
} |
q41111 | Jade | train | function Jade() {
var opts = (app.config.engines && app.config.engines.jade) || {};
this.options = protos.extend({
pretty: true
}, opts);
this.module = jade;
this.multiPart = false;
this.extensions = ['jade', 'jade.html'];
} | javascript | {
"resource": ""
} |
q41112 | wJson | train | function wJson(path, data, options, callback) {
if (typeof options === "function") {
callback = options;
options = {};
} else if (typeof options === "number") {
options = {
space: options
};
} else if (typeof options === "boolean") {
options = {
new_line: options
};
}
options = options || {};
options.space = typeof options.space === "number" ? options.space : 2;
options.new_line = !!options.new_line;
Fs["writeFile" + (typeof callback === "function" ? "" : "Sync")](
path
, JSON.stringify(data, null, options.space) + (options.new_line ? "\n" : "")
, callback
);
} | javascript | {
"resource": ""
} |
q41113 | train | function(db) {
function merge(a_, b_, plv8, ERROR) {
function copy_properties(o, a) {
Object.keys(a).forEach(function(k) {
o[k] = a[k];
});
return o;
}
function copy(a, b) {
return copy_properties(copy_properties({}, a), b);
}
try {
return copy(a_, b_);
} catch (e) {
plv8.elog(ERROR, e);
return;
}
}
return db.query('CREATE SCHEMA IF NOT EXISTS nopg')
.query('CREATE OR REPLACE FUNCTION nopg.merge(a json, b json) RETURNS json LANGUAGE plv8 STABLE AS ' + NoPg._escapeFunction(merge,
["a", "b", "plv8", "ERROR"]) );
} | javascript | {
"resource": ""
} | |
q41114 | describeMessage | train | function describeMessage(message, batch, context) {
const b = batch || context.batch;
const state = b && b.states.get(message);
return message ? `Message (${state && state.msgDesc})` : '';
} | javascript | {
"resource": ""
} |
q41115 | describeUnusableRecord | train | function describeUnusableRecord(unusableRecord, batch, context) {
const b = batch || context.batch;
const state = b && b.states.get(unusableRecord);
return `Unusable record (${state && state.recDesc})`;
} | javascript | {
"resource": ""
} |
q41116 | describeRejectedMessage | train | function describeRejectedMessage(rejectedMessage, batch, context) {
const b = batch || context.batch;
const state = b && b.states.get(rejectedMessage);
return `Rejected message (${state && (state.msgDesc || state.recDesc)})`;
} | javascript | {
"resource": ""
} |
q41117 | readStylusFile | train | function readStylusFile(file, callback) {
fs.readFile(file, function (err, data) {
if (err) {
throw err;
}
stylus.render(data.toString(), function (err, css) {
if (err) {
throw err;
}
callback(css);
});
});
} | javascript | {
"resource": ""
} |
q41118 | EOFError | train | function EOFError(message) {
// Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
if (!(this instanceof EOFError)) { return new EOFError(message); }
Error.captureStackTrace(this, EOFError);
if (message !== undefined) {
Object.defineProperty(this, 'message', {
value: String(message),
configurable: true,
writable: true
});
}
} | javascript | {
"resource": ""
} |
q41119 | jws | train | function jws ( details ) {
if (!details.header)
throw new Error('No header for JWS token')
if (!details.header.alg)
throw new Error('No JWS signing algorithm specified')
if (!signAlg[details.header.alg])
throw new Error('Unsupported JWS signing algorithm:"'+details.header.alg+'"')
if (!details.payload)
throw new Error('No payload for JWS token')
if (!details.credentials)
throw new Error('No credentials for JWS token')
if (!details.credentials.kid)
throw new Error('No credentials.kid for JWS token')
if (!details.credentials.key)
throw new Error('No credentials.key for JWS token')
return signAlg[details.header.alg]( details )
} | javascript | {
"resource": ""
} |
q41120 | keygen | train | function keygen (alg) {
var algs =
{ 'HS256': 256/8
, 'HS512': 512/8
, 'A128CBC+HS256': 256/8
, 'A256CBC+HS512': 512/8
};
if (!algs[alg]) return null;
return (b64url.encode(crypto.randomBytes(algs[alg])))
} | javascript | {
"resource": ""
} |
q41121 | builtinRead | train | function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
} | javascript | {
"resource": ""
} |
q41122 | train | function(options) {
// Contains line objects of the user-draggable code.
// The order is not meaningful (unchanged from the initial state) but
// indent property for each line object is updated as the user moves
// codelines around. (see parseCode for line object description)
this.modified_lines = [];
// contains line objects of distractors (see parseCode for line object description)
this.extra_lines = [];
// contains line objects (see parseCode for line object description)
this.model_solution = [];
//To collect statistics, feedback should not be based on this
this.user_actions = [];
//State history for feedback purposes
this.state_path = [];
this.states = {};
var defaults = {
'incorrectSound': false,
'x_indent': 50,
'can_indent': true,
'feedback_cb': false,
'first_error_only': true,
'max_wrong_lines': 10,
'lang': 'en',
'toggleSeparator': '::'
};
this.options = jQuery.extend({}, defaults, options);
this.feedback_exists = false;
this.id_prefix = options['sortableId'] + 'codeline';
if (translations.hasOwnProperty(this.options.lang)) {
this.translations = translations[this.options.lang];
} else {
this.translations = translations['en'];
}
// translate trash_label and solution_label
if (!this.options.hasOwnProperty("trash_label")) {
this.options.trash_label = this.translations.trash_label;
}
if (!this.options.hasOwnProperty("solution_label")) {
this.options.solution_label = this.translations.solution_label;
}
this.FEEDBACK_STYLES = { 'correctPosition' : 'correctPosition',
'incorrectPosition' : 'incorrectPosition',
'correctIndent' : 'correctIndent',
'incorrectIndent' : 'incorrectIndent'};
// use grader passed as an option if defined and is a function
if (this.options.grader && _.isFunction(this.options.grader)) {
this.grader = new this.options.grader(this);
} else {
// initialize the grader
if (typeof(this.options.unittests) !== "undefined") { /// unittests are specified
this.grader = new UnitTestGrader(this);
} else if (typeof(this.options.vartests) !== "undefined") { /// tests for variable values
this.grader = new VariableCheckGrader(this);
} else { // "traditional" parson feedback
this.grader = new LineBasedGrader(this);
}
}
} | javascript | {
"resource": ""
} | |
q41123 | createAutoPauseLineStream | train | function createAutoPauseLineStream(readStream) {
//Use readline to read the lines of text
const lineReader = readline.createInterface({
input: readStream
});
//Create a line queue for the lines that are emitted from the line reader.
//Once the line reader has read a chunk from the read stream, it will
//continue to emit lines until it has processed the entire chunk. Pausing
//the line reader or stream will cause them not to emit or process any more
//chunks, but it will not immediately stop lines from being emitted. So
//we'll store emitted lines in the line queue until it's time to emit them.
const lineQueue = new Queue();
//Keep track of whether the stream has ended
let streamEnd = false;
//Create and return the Bacon stream generator function
return Bacon.fromBinder(sink => {
//Keep track of whether the stream is currently paused
let paused = false;
//Set an event handler for the error events
lineReader.on('error', error => sink(new Bacon.Error(error)));
//Set an event handler for the line event
lineReader.on('line', lineString => {
//Add the line to the line buffer
lineQueue.enq(lineString);
//Pause the line reader
readStream.pause();
//If the stream is not currently paused, emit a line
if(!paused) {
emitLine();
}
});
//Set an event handler for the close event, which indicates
//that we've read all the lines
lineReader.on('close', () => {
//Indicate the stream has ended
streamEnd = true;
//If the stream is not paused, emit a line
if(!paused) {
emitLine();
}
});
//Emits a line if possible
function emitLine() {
if(lineQueue.size() > 0)
{
pause();
sink({line: lineQueue.deq(), resume});
}
else if(streamEnd) {
sink(new Bacon.End());
}
else {
//If we've run out of lines to emit
readStream.resume();
}
}
//Pauses the stream
function pause() {
paused = true;
}
//Resumes the stream
function resume() {
paused = false;
emitLine();
}
return () => {};
});
} | javascript | {
"resource": ""
} |
q41124 | emitLine | train | function emitLine() {
if(lineQueue.size() > 0)
{
pause();
sink({line: lineQueue.deq(), resume});
}
else if(streamEnd) {
sink(new Bacon.End());
}
else {
//If we've run out of lines to emit
readStream.resume();
}
} | javascript | {
"resource": ""
} |
q41125 | train | function(x, y, dir) {
if(!this.isCell(x, y)) { return null; }
// dir must be string and in dirmap
if(!this.isDir(dir)) { return null; }
let _DX = { "E": 1, "W": -1, "N": 0, "S": 0 };
let _DY = { "E": 0, "W": 0, "N": -1, "S": 1 };
var nx = x + _DX[dir];
var ny = y + _DY[dir];
if(!this.isCell(nx, ny)) {
return null;
}
return { x: nx, y: ny };
} | javascript | {
"resource": ""
} | |
q41126 | compose | train | function compose() {
var funcs = slice.call(arguments);
return function() {
var thisArg = this;
var boundFuncs = funcs.map(function(func) {
return function() {
return promise.Promise.from(func.apply(thisArg, arguments));
};
});
var args = slice.call(arguments);
args.unshift(boundFuncs);
return concurrent.pipeline.apply(concurrent, args);
};
} | javascript | {
"resource": ""
} |
q41127 | MemcachedCache | train | function MemcachedCache(options) {
options = options || {};
this.client = memjs.Client.create(options.url || 'localhost/11211');
this.expireAfterSeconds = options.expireAfterSeconds || 60;
} | javascript | {
"resource": ""
} |
q41128 | train | function() {
this.links.forEach(link => {
link.labelCount.forEach((count, label) => {
link.labelWeight.set(label, count / this.numExamples.get(label))
})
})
this.weightsNeedBuilding = false
} | javascript | {
"resource": ""
} | |
q41129 | _explore | train | function _explore(start, callfile, calldir, options, done) {
const {fs, followSymlink, resolve} = options;
let count = 0;
function take() {
++count;
}
function give(err) {
if (--count === 0 || err) {
done(err);
}
}
// Start process
take();
fs.lstat(start, (err, stats) => {
let linkStats;
if (err) {
give(err);
return;
}
if (stats.isSymbolicLink() && (followSymlink || resolve)) {
linkStats = stats;
fs.realpath(start, (err, resolvedPath) => {
if (err) {
give(err);
return;
}
fs.lstat(resolvedPath, (err, stats) => {
if (err) {
// invalid symlink
callfile(start, stats, give);
return;
}
__doExplore(start, callfile, calldir, options, stats, linkStats, take, give);
});
});
} else {
__doExplore(start, callfile, calldir, options, stats, linkStats, take, give);
}
});
} | javascript | {
"resource": ""
} |
q41130 | fitRect | train | function fitRect(rect, target, mode) {
mode = mode || 'contain';
var sw = target[2]/rect[2];
var sh = target[3]/rect[3];
var scale = 1;
if (mode == 'contain') {
scale = Math.min(sw, sh);
}
else if (mode == 'cover') {
scale = Math.max(sw, sh);
}
return [
target[0] + (target[2] - rect[2]*scale)/2,
target[1] + (target[3] - rect[3]*scale)/2,
rect[2]*scale,
rect[3]*scale
]
} | javascript | {
"resource": ""
} |
q41131 | encode | train | function encode(params) {
var data, property, className;
if(params === null){
return params;
}
className = Object.prototype.toString.call(params).replace('[object ', '').replace(']', '');
if ( className == 'Object' ) {
data = {};
Object.keys(params).forEach(function (property) {
if ( (typeof params[property] !== 'undefined') && (typeof params[property] !== 'function') ) {
data[property.toString().underscore()] = this.encode(params[property]);
}
}, this);
} else if (className == 'Array') {
data = params.map(function (value) {
return this.encode(value);
}, this);
} else {
data = params;
}
return data;
} | javascript | {
"resource": ""
} |
q41132 | list | train | function list(appName, callback) {
var uri = format('/%s/apps/%s/config/', deis.version, appName);
commons.get(uri, function onListResponse(err, result) {
callback(err, result ? result.values : null);
});
} | javascript | {
"resource": ""
} |
q41133 | set | train | function set(appName, keyValues, keyLimits, callback) {
var config = {};
if (!isObject(keyValues)) {
return callback(new Error('To set a variable pass an object'));
}
config.values = keyValues;
if (isObject(keyLimits)) {
if (keyLimits.hasOwnProperty('memory')) {
config.memory = keyLimits.memory;
}
if (keyLimits.hasOwnProperty('cpu')) {
config.cpu = keyLimits.cpu;
}
} else {
callback = keyLimits;
}
var uri = format('/%s/apps/%s/config/', deis.version, appName);
commons.post(uri, config, function onSetResponse(err, result) {
callback(err, result ? result.values : null);
});
} | javascript | {
"resource": ""
} |
q41134 | unset | train | function unset(appName, variableNames, callback) {
if (!util.isArray(variableNames)) {
return callback(new Error('To unset a variable pass an array of names'));
}
var keyValues = {};
variableNames.forEach(function onUnsetResponse(variableName) {
keyValues[variableName] = null;
});
set(appName, keyValues, callback);
} | javascript | {
"resource": ""
} |
q41135 | LogWrapper | train | function LogWrapper (isLogging) {
if (this.constructor.name === 'Function') {
throw new Error('Missing object context')
}
if (!isLogging) {
// stub the logger out
this.logger = {}
this.logger.info = function () {}
this.logger.error = function () {}
this.logger.warn = function () {}
return
}
// Else config winston for logging
const Winston = require('winston')
let winstonTransport = new (Winston.transports.Console)({
json: false,
colorize: true
})
this.logger = new (Winston.Logger)({
transports: [winstonTransport]
})
} | javascript | {
"resource": ""
} |
q41136 | train | function(suffix) {
if ( suffix.match(/^([a-z]*:?\d*)\/\//) ) { return suffix; }
var base = this.enablePushState ? this.baseUrl : '#/';
return base + suffix.replace(/^\//,'');
} | javascript | {
"resource": ""
} | |
q41137 | train | function(to, from, fnName, setupFn) {
to[fnName] = function() {
if (setupFn) {
setupFn();
}
return from[fnName].apply(from, arguments);
};
} | javascript | {
"resource": ""
} | |
q41138 | train | function() {
return elementArrayFinder.getWebElements().then(function(webElements) {
if (webElements.length === 0) {
throw new webdriver.error.Error(
webdriver.error.ErrorCode.NO_SUCH_ELEMENT,
'No element found using locator: ' +
elementArrayFinder.locator_.toString());
} else {
if (webElements.length > 1) {
console.log('warning: more than one element found for locator ' +
elementArrayFinder.locator_.toString() +
' - you may need to be more specific');
}
return [webElements[0]];
}
});
} | javascript | {
"resource": ""
} | |
q41139 | diffFile | train | function diffFile(existing, proposed, options) {
let { ensureContents, exists, readChunk } = utils;
let opts = options || {};
let contentsA = existing.contents;
let contentsB = proposed.contents;
if (!contentsA && exists(existing)) {
contentsA = readChunk(existing.path, 0, 4 + 4096);
}
if (!contentsB && exists(proposed)) {
contentsB = readChunk(proposed.path, 0, 4 + 4096);
}
if ((contentsA && isBuffer(contentsA)) || (contentsB && isBuffer(contentsB))) {
return diffBinary(existing, proposed);
}
ensureContents(existing);
ensureContents(proposed);
if (opts.diffText === true) {
return diffText(existing.contents.toString(), proposed.contents.toString(), opts);
}
return diffChars(existing.contents.toString(), proposed.contents.toString(), opts);
} | javascript | {
"resource": ""
} |
q41140 | diffImage | train | function diffImage(existing, proposed, options) {
let { bytes, dateformat, imageSize, Table, toFile, colors } = utils;
existing = toFile(existing, options);
proposed = toFile(proposed, options);
let table = new Table({ head: ['Attribute', 'Existing', 'Replacement', 'Diff'] });
let dimensionsA = imageSize(existing.path);
let dimensionsB = imageSize(proposed.path);
let statA = existing.stat;
let statB = proposed.stat;
let isSmaller = existing.size > proposed.size;
let sizeDiff = isSmaller ? '-' : '+';
sizeDiff += bytes(Math.abs(existing.size - proposed.size));
// dates
let mtimeA = statA ? dateformat(statA.mtime) : 'New';
let mtimeB = statB ? dateformat(statB.mtime) : 'New';
if (statA.mtime && statB.mtime && statA.mtime < statB.mtime) {
mtimeB = colors.green(mtimeB);
} else {
mtimeA = colors.green(mtimeA);
}
let birthtimeA = statA ? dateformat(statA.birthtime) : 'New';
let birthtimeB = statB ? dateformat(statB.birthtime) : 'New';
if (statA.birthtime && statB.birthtime && statA.birthtime < statB.birthtime) {
birthtimeB = colors.green(birthtimeB);
} else {
birthtimeA = colors.green(birthtimeA);
}
// size
let sizeA = bytes(existing.size);
let sizeB = bytes(proposed.size);
if (isSmaller) {
sizeDiff = colors.red(sizeDiff);
dimensionsA = colors.green(dimensionsA);
sizeA = colors.green(sizeA);
} else {
sizeDiff = colors.green(sizeDiff);
dimensionsB = colors.green(dimensionsB);
sizeB = colors.green(sizeB);
}
table.push(['Path', existing.relative, proposed.relative, '']);
table.push(['Size', sizeA, sizeB, sizeDiff]);
table.push(['Dimensions', dimensionsA, dimensionsB, 'N/A']);
table.push(['Date created', birthtimeA, birthtimeB, 'N/A']);
table.push(['Date modified', mtimeA, mtimeB, 'N/A']);
return table.toString();
} | javascript | {
"resource": ""
} |
q41141 | defaultShouldReload | train | function defaultShouldReload(items, params) {
// Go through all and check if any redata shouldReload.
for (const key in items) {
if (items[key].shouldReload(params)) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q41142 | train | function (number, name_type, create) {
const names = { male: [], female: [] };
if (typeof create === 'undefined') { create = false; }
if (typeof number === 'undefined') { number = 10; }
if (typeof name_type === 'undefined' || name_type === '') {
name_type = 'random';
}
for (let i = 1; i <= number; i++) {
const gender = (i <= Math.ceil(number / 2)) ? 'male' : 'female';
if (create && name_type !== 'holmesian' && name_type !== 'demonic') {
names[gender].push(createName(name_type, gender, true));
} else {
names[gender].push(selectName(name_type, gender));
}
}
return names;
} | javascript | {
"resource": ""
} | |
q41143 | train | function (name_type, gender, style) {
let name = '';
if (typeof name_type === 'undefined' || name_type === '' || name_type === 'random') {
// randomize a type...
name_type = randomizer.rollRandom(Object.keys(namedata.options));
}
if (typeof gender === 'undefined' || gender === 'random') {
// randomize a gender...
gender = randomizer.rollRandom(['male', 'female']);
}
if (typeof style === 'undefined' || style !== 'first') {
style = '';
}
switch (name_type) {
case 'holmesian':
name = holmesname();
break;
case 'demonic':
name = demonname();
break;
case 'cornish':
case 'flemish':
case 'dutch':
case 'turkish':
default:
name = randomizer.rollRandom(namedata[name_type][gender]);
if (style !== 'first' && typeof namedata[name_type]['surname'] !== 'undefined' && !r_helpers.isEmpty(namedata[name_type]['surname'])) {
name += ' ' + randomizer.rollRandom(namedata[name_type]['surname']);
}
name = randomizer.findToken(name).trim();
break;
}
return capitalizeName(name);
} | javascript | {
"resource": ""
} | |
q41144 | train | function (name_type, gender, style) {
if (typeof name_type === 'undefined' || name_type === '' || name_type === 'random') {
// randomize a type...
name_type = randomizer.rollRandom(Object.keys(namedata.options));
}
if (typeof style === 'undefined') { style = ''; }
if (!namedata[name_type]) { return ''; }
if (typeof gender === 'undefined' || (gender !== 'male' && gender !== 'female')) { gender = randomizer.rollRandom(['male', 'female']); }
const mkey = `${name_type}_${gender}`;
let lastname = '';
let thename = '';
if (!markov.memory) {
markov = new MarkovGenerator({ order: 3 });
}
if (!markov.memory[mkey]) {
// console.log('learn '+mkey);
let namelist = [];
if (gender === '') {
namelist = namedata[name_type]['male'];
namelist = namelist.concat(namedata[name_type]['female']);
} else {
namelist = namedata[name_type][gender];
}
namelist.forEach((v) => {
markov.learn(mkey, v);
});
}
if (style !== 'first' && !r_helpers.isEmpty(namedata[name_type]['surname'])) {
const skey = name_type + '_last';
if (!markov.memory[skey]) {
// console.log('learn surname '+skey);
const namelist = namedata[name_type]['surname'];
namelist.forEach((v) => {
markov.learn(skey, v);
});
}
lastname = markov.generate(skey);
}
thename = `${markov.generate(mkey)} ${lastname}`;
return capitalizeName(thename.trim());
} | javascript | {
"resource": ""
} | |
q41145 | train | function (name) {
const leave_lower = ['of', 'the', 'from', 'de', 'le', 'la'];
// need to find spaces in name and capitalize letter after space
const parts = name.split(' ');
const upper_parts = parts.map((w) => {
return (leave_lower.indexOf(w) >= 0) ? w : `${r_helpers.capitalize(w)}`;
});
return upper_parts.join(' ');
} | javascript | {
"resource": ""
} | |
q41146 | train | function () {
let name = '';
const scount = randomizer.getWeightedRandom(namedata.holmesian_scount.values, namedata.holmesian_scount.weights);
for (let i = 1; i <= scount; i++) {
name += randomizer.rollRandom(namedata.holmesian_syllables); // array
if (i < scount) {
name += randomizer.getWeightedRandom(['', ' ', '-'], [3, 2, 2]);
}
}
name = name.toLowerCase() + ' ' + randomizer.rollRandom(namedata.holmesian_title);
name = randomizer.findToken(name);
name = name.replace(/[\s\-]([a-z]{1})/g, (match) => {
return match.toUpperCase();
});
return name;
} | javascript | {
"resource": ""
} | |
q41147 | isPromise | train | function isPromise(v) {
return v && v.isFulfilled && v.then && v.catch && v.value;
} | javascript | {
"resource": ""
} |
q41148 | Help | train | function Help(filename, path, github, preprocess) {
if (!(this instanceof Help)) return new Help(filename, path, preprocess);
this.html = '';
this.path = path;
this.github = github;
this.filename = filename;
this.preprocess = preprocess;
this.url = filename.slice(0, -3);
this.title = filename.slice(0, -3).replace(/\-/g, ' ');
if (this.title in Help.rename) {
this.title = Help.rename[this.title];
}
} | javascript | {
"resource": ""
} |
q41149 | train | function (question, defaultValue) {
// For simplicity we uncheck all boxes and
// use .default to set the active ones.
_.each(question.choices, function (choice) {
if (typeof choice === 'object') {
choice.checked = false;
}
});
return defaultValue;
} | javascript | {
"resource": ""
} | |
q41150 | train | function (question, defaultValue) {
var choiceValues = _.map(question.choices, function (choice) {
if (typeof choice === 'object') {
return choice.value;
} else {
return choice;
}
});
return choiceValues.indexOf(defaultValue);
} | javascript | {
"resource": ""
} | |
q41151 | train | function (question, answer) {
var choiceValues = _.map(question.choices, 'value');
var choiceIndex = choiceValues.indexOf(answer);
// Check if answer is not equal to default value
if (question.default !== choiceIndex) {
return true;
}
return false;
} | javascript | {
"resource": ""
} | |
q41152 | scale | train | function scale(appName, configuration, callback) {
if (!isObject(configuration)) {
return callback(new Error('To scale pass an object with the type as key'));
}
var url = format('/%s/apps/%s/scale/', deis.version, appName);
commons.post(url, configuration, 204, callback);
} | javascript | {
"resource": ""
} |
q41153 | byType | train | function byType(appName, type, callback) {
var url = format('/%s/apps/%s/containers/%s/', deis.version, appName, type);
commons.get(url, callback);
} | javascript | {
"resource": ""
} |
q41154 | loadConfig | train | function loadConfig(opts) {
if (opts != null && (typeof opts === "undefined" ? "undefined" : (0, _typeof3.default)(opts)) !== "object") {
throw new Error("Babel options must be an object, null, or undefined");
}
return (0, _optionManager2.default)(opts || {});
} | javascript | {
"resource": ""
} |
q41155 | createVelocity | train | function createVelocity()
{
const duration = 2000
const easing = 'easeInOutSine'
Velocity(box('scaleX'), { scaleX: 2 }, { duration, easing, loop: true })
Velocity(box('scaleY'), { scaleY: 2 }, { duration, easing, loop: true })
Velocity(box('top/left'), { left: window.innerWidth / 2, top: window.innerHeight / 2 }, { duration, easing, loop: true })
Velocity(box('scale'), { scale: 0 }, { duration, easing, loop: true })
// Velocity(box('backgroundColor'), { backgroundColor: ['red', 'blue', 'transparent'] }, { duration, easing, loop: true })
Velocity(box('opacity'), { opacity: 0 }, { duration, easing, loop: true })
Velocity(box('width'), { width: SIZE * 2 }, { duration, easing, loop: true })
Velocity(box('height'), { height: 0 }, { duration, easing, loop: true })
// Velocity(box('color'), { color: ['green', 'yellow', 'purple'] }, { duration, easing, loop: true })
} | javascript | {
"resource": ""
} |
q41156 | wrapProgram | train | function wrapProgram(tree, url, commonPath) {
var name = generateNameForUrl(url, commonPath);
return new Program(null,
[new ModuleDefinition(null,
createIdentifierToken(name), tree.programElements)]);
} | javascript | {
"resource": ""
} |
q41157 | inlineAndCompile | train | function inlineAndCompile(filenames, options, reporter, callback, errback) {
// The caller needs to do a chdir.
var basePath = './';
var depTarget = options && options.depTarget;
var loadCount = 0;
var elements = [];
var project = new Project(basePath);
var loader = new InlineCodeLoader(reporter, project, elements, depTarget);
function loadNext() {
var codeUnit = loader.load(filenames[loadCount]);
startCodeUnit = codeUnit;
codeUnit.addListener(function() {
loadCount++;
if (loadCount < filenames.length) {
loadNext();
} else if (depTarget) {
callback(null);
} else {
var tree = allLoaded(basePath, reporter, elements);
callback(tree);
}
}, function() {
console.error(codeUnit.loader.error);
errback(codeUnit.loader.error);
});
}
loadNext();
} | javascript | {
"resource": ""
} |
q41158 | sn_util_copyAll | train | function sn_util_copyAll(obj1, obj2) {
var keys = Object.getOwnPropertyNames(obj1), i, len, key, desc;
if (obj2 === undefined) {
obj2 = {};
}
for (i = 0, len = keys.length; i < len; i += 1) {
key = keys[i];
desc = Object.getOwnPropertyDescriptor(obj1, key);
if (desc) {
Object.defineProperty(obj2, key, desc);
} else {
obj2[key] = obj1[key];
}
}
return obj2;
} | javascript | {
"resource": ""
} |
q41159 | sn_util_merge | train | function sn_util_merge(obj1, obj2) {
var prop, desc;
if (obj2 === undefined) {
obj2 = {};
}
for (prop in obj1) {
if (obj1.hasOwnProperty(prop) && obj2[prop] === undefined) {
desc = Object.getOwnPropertyDescriptor(obj1, prop);
if (desc) {
Object.defineProperty(obj2, prop, desc);
} else {
obj2[prop] = obj1[prop];
}
}
}
return obj2;
} | javascript | {
"resource": ""
} |
q41160 | sn_util_arraysAreEqual | train | function sn_util_arraysAreEqual(a1, a2) {
var i, len;
if (!(Array.isArray(a1) && Array.isArray(a2))) {
return false;
}
if (a1.length !== a2.length) {
return false;
}
for (i = 0, len = a1.length; i < len; i += 1) {
if (Array.isArray(a1[i]) && Array.isArray(a2[i]) && arraysAreEqual(a1[i], a2[i]) !== true) {
return false;
} else if (a1[i] !== a2[i]) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q41161 | sn_util_superMethod | train | function sn_util_superMethod(name) {
var that = this, method = that[name];
return function() {
return method.apply(that, arguments);
};
} | javascript | {
"resource": ""
} |
q41162 | sn_api_user_queueInstructionURL | train | function sn_api_user_queueInstructionURL(topic, parameters) {
var url = sn_api_user_baseURL(this) + "/instr/add?nodeId=" + this.nodeId + "&topic=" + encodeURIComponent(topic);
if (Array.isArray(parameters)) {
var i, len;
for (i = 0, len = parameters.length; i < len; i++) {
url += "&" + encodeURIComponent("parameters[" + i + "].name") + "=" + encodeURIComponent(parameters[i].name) + "&" + encodeURIComponent("parameters[" + i + "].value") + "=" + encodeURIComponent(parameters[i].value);
}
}
return url;
} | javascript | {
"resource": ""
} |
q41163 | train | function(key, enabled) {
var val = enabled;
if (key === undefined) {
return this;
}
if (val === undefined) {
val = this.map[key] === undefined;
}
return this.value(key, val === true ? true : null);
} | javascript | {
"resource": ""
} | |
q41164 | train | function(key, newValue) {
var me = this;
if (arguments.length === 1) {
return this.map[key];
}
if (newValue === null) {
delete this.map[key];
if (this.hasOwnProperty(key)) {
delete this[key];
}
} else {
this.map[key] = newValue;
if (!this.hasOwnProperty(key)) {
Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
get: function() {
return me.map[key];
},
set: function(value) {
me.map[key] = value;
}
});
}
}
return this;
} | javascript | {
"resource": ""
} | |
q41165 | sn_net_encodeURLQueryTerms | train | function sn_net_encodeURLQueryTerms(parameters) {
var result = "", prop, val, i, len;
function handleValue(k, v) {
if (result.length) {
result += "&";
}
result += encodeURIComponent(k) + "=" + encodeURIComponent(v);
}
if (parameters) {
for (prop in parameters) {
if (parameters.hasOwnProperty(prop)) {
val = parameters[prop];
if (Array.isArray(val)) {
for (i = 0, len = val.length; i < len; i++) {
handleValue(prop, val[i]);
}
} else {
handleValue(prop, val);
}
}
}
}
return result;
} | javascript | {
"resource": ""
} |
q41166 | generateCanonicalRequestMessage | train | function generateCanonicalRequestMessage(params) {
var msg = (params.method === undefined ? "GET" : params.method.toUpperCase()) + "\n" + params.uri.path + "\n" + (params.queryParams ? params.queryParams : "") + "\n";
params.headers.headerNames.forEach(function(name) {
msg += name + ":" + params.headers.headers[name] + "\n";
});
msg += params.headers.headerNames.join(";") + "\n";
msg += CryptoJS.enc.Hex.stringify(params.bodyDigest);
return msg;
} | javascript | {
"resource": ""
} |
q41167 | train | function(location) {
return Math.sqrt(Math.pow(location.x - this.matrix[4], 2), Math.pow(location.y - this.matrix[5], 2));
} | javascript | {
"resource": ""
} | |
q41168 | train | function(elm) {
var m = this.support.use3d === true ? this.toMatrix3D() : this.toMatrix2D();
elm.style[this.support.tProp] = m;
} | javascript | {
"resource": ""
} | |
q41169 | train | function(elm, finished) {
var listener = undefined;
var self = this;
listener = function(event) {
if (event.target === elm) {
elm.removeEventListener(self.support.trEndEvent, listener, false);
finished.apply(elm);
}
};
elm.addEventListener(self.support.trEndEvent, listener, false);
} | javascript | {
"resource": ""
} | |
q41170 | train | function(elm, timing, duration, finished) {
var self = this;
this.animateListen(elm, function() {
elm.style[self.support.trProp] = "";
if (finished !== undefined) {
finished.apply(elm);
}
});
var cssValue = this.support.trTransform + " " + (duration !== undefined ? duration : "0.3s") + " " + (timing !== undefined ? timing : "ease-out");
elm.style[this.support.trProp] = cssValue;
this.apply(elm);
} | javascript | {
"resource": ""
} | |
q41171 | check | train | function check(suppliedOptions){
var options = assign(Object.create(defaultOptions), suppliedOptions || {});
var packageJson = require(path.resolve(process.cwd(), options.package));
var checkDevDependencies = !!options.checkDevDependencies;
var checkDependencies = !!options.checkDependencies;
var moduleTimes = {
dependencies: {},
devDependencies: {}
};
var loadTime = -1;
if(packageJson.main){
loadTime = execSync(execString + path.resolve(process.cwd(), packageJson.main), {encoding: "utf8"});
}
if(checkDependencies){
Object.keys(packageJson.dependencies).forEach(function(depen){
var time = execSync(execString + path.resolve(process.cwd(), "node_modules", depen), {
encoding: "utf8",
cwd: process.cwd()
});
moduleTimes.dependencies[depen] = parseFloat(time);
});
}
if(checkDevDependencies){
Object.keys(packageJson.devDependencies).forEach(function(depen){
var time = execSync(execString + path.resolve(process.cwd(), "node_modules", depen), {
encoding: "utf8",
cwd: process.cwd()
});
moduleTimes.devDependencies[depen] = parseFloat(time);
});
}
return {
moduleTimes: moduleTimes,
loadTime: loadTime
};
} | javascript | {
"resource": ""
} |
q41172 | setCallbackAsWatcherOf | train | function setCallbackAsWatcherOf(callback, watchersSet) {
if (!callback[WATCHER_IDENTIFIER]) {
defineProperty(callback, WATCHER_IDENTIFIER, { watching: new Set() });
defineProperty(callback, "stopWatchingAll", function(){
callback[WATCHER_IDENTIFIER].watching.forEach(watcherList =>
watcherList.delete(callback)
);
callback[WATCHER_IDENTIFIER].watching.clear();
});
}
callback[WATCHER_IDENTIFIER].watching.add(watchersSet);
} | javascript | {
"resource": ""
} |
q41173 | offsetTop | train | function offsetTop (elem) {
let top = 0
do {
if (!isNaN(elem.offsetTop)) top += elem.offsetTop
} while (elem = elem.offsetParent)
return top
} | javascript | {
"resource": ""
} |
q41174 | offsetLeft | train | function offsetLeft (elem) {
let left = 0
do {
if (!isNaN(elem.offsetLeft)) left += elem.offsetLeft
} while (elem = elem.offsetParent )
return left
} | javascript | {
"resource": ""
} |
q41175 | enhanceSpm | train | function enhanceSpm (comName, checkSignature, fn) {
var sp = new SerialPort(comName)
, open = false;
sp.writable = true;
sp.on('open', function() {
open = true;
if (checkSignature)
getSignature(sp, function(e, sig) {
fn(e, sp, sig);
});
else
fn(null, sp, null);
});
sp.once('error', function(e) {
console.log('ERROR', e, comName);
if (!open)
fn(e);
});
} | javascript | {
"resource": ""
} |
q41176 | getSignature | train | function getSignature (sp, fn) {
var start = null
, sig = ''
, timer;
var handleSignature = function(data) {
if (data)
sig += data.toString() || '';
clearTimeout(timer);
if (!start && data) {
start = Date.now();
} else if (Date.now() - start > 100) {
sp.removeListener('data', handleSignature);
return fn(null, sig.trim());
}
timer = setTimeout(handleSignature, 100);
};
sp.on('data', handleSignature);
} | javascript | {
"resource": ""
} |
q41177 | listen | train | function listen(eventIdentifier, callback, context) {
if (typeof callback !== 'function') { throw new TypeError('on: Illegal Argument: callback must be a function, was ' + (typeof callback)); }
// This allows us to work even if the constructor hasn't been called. Useful for mixins.
if (this._emitterListeners === undefined) {
this._emitterListeners = new MultiMap();
}
if (typeof eventIdentifier === 'function' && (eventIdentifier.prototype instanceof metaEvents.MetaEvent || eventIdentifier === metaEvents.MetaEvent)) {
// Since triggering meta events can be expensive, we only
// do so if a listener has been added to listen to them.
this._emitterMetaEventsOn = true;
}
var currentListeners = this._emitterListeners.getValues(eventIdentifier);
currentListeners = currentListeners.filter(function(listenerRecord) {
return listenerRecord.registeredContext === context
&& (listenerRecord.callback === callback
|| (listenerRecord.callback._wrappedCallback !== undefined
&& listenerRecord.callback._wrappedCallback === callback._wrappedCallback));
});
if (currentListeners.length > 0) {
throw new Error('This callback is already listening to this event.');
}
this._emitterListeners.add(eventIdentifier, {
eventIdentifier: eventIdentifier,
callback: callback,
registeredContext: context,
context: context !== undefined ? context : this
});
if (this._emitterMetaEventsOn === true) {
this.trigger(new metaEvents.AddListenerEvent(eventIdentifier, callback._onceFunctionMarker === ONCE_FUNCTION_MARKER ? callback._wrappedCallback : callback, context));
}
} | javascript | {
"resource": ""
} |
q41178 | train | function(eventIdentifier, callback, context) {
if (typeof callback !== 'function') { throw new TypeError('once: Illegal Argument: callback must be a function, was ' + (typeof callback)); }
var off = this.off.bind(this), hasFired = false;
function onceEventHandler() {
if (hasFired === false) {
hasFired = true;
off(eventIdentifier, onceEventHandler, context);
callback.apply(this, arguments);
}
}
// We need this to enable us to remove the wrapping event handler
// when off is called with the original callback.
onceEventHandler._onceFunctionMarker = ONCE_FUNCTION_MARKER;
onceEventHandler._wrappedCallback = callback;
this.on(eventIdentifier, onceEventHandler, context);
} | javascript | {
"resource": ""
} | |
q41179 | off | train | function off(eventIdentifier, callback, context) {
// not initialised - so no listeners of any kind
if (this._emitterListeners == null) { return false; }
if (arguments.length === 0) {
// clear all listeners.
if (this._emitterMetaEventsOn === true) {
var allListeners = this._emitterListeners.getValues();
notifyRemoves(this, allListeners);
}
this._emitterListeners.clear();
return true;
} else if (arguments.length === 1) {
// clear all listeners for a particular eventIdentifier.
if (this._emitterListeners.hasAny(eventIdentifier)) {
var listeners = this._emitterListeners.getValues(eventIdentifier);
this._emitterListeners['delete'](eventIdentifier);
if (this._emitterMetaEventsOn === true) {
notifyRemoves(this, listeners);
}
return true;
}
return false;
} else if (eventIdentifier === null && callback === null) {
// clear all listeners for a particular context.
return this.clearListeners(context);
} else {
// clear a specific listener.
if (typeof callback !== 'function') { throw new TypeError('off: Illegal Argument: callback must be a function, was ' + (typeof callback)); }
var removedAListener = this._emitterListeners.removeLastMatch(eventIdentifier, function(record) {
var callbackToCompare = record.callback._onceFunctionMarker === ONCE_FUNCTION_MARKER ? record.callback._wrappedCallback : record.callback;
var callbackMatches = callback === callbackToCompare;
var contextMatches = record.registeredContext === context;
return callbackMatches && contextMatches;
});
if (removedAListener && this._emitterMetaEventsOn === true) {
this.trigger(new metaEvents.RemoveListenerEvent(eventIdentifier, callback, context));
}
return removedAListener;
}
} | javascript | {
"resource": ""
} |
q41180 | trigger | train | function trigger(event) {
var args;
var anyListeners = false;
if (this._emitterListeners != null) {
args = slice.call(arguments, 1);
if (this._emitterListeners.hasAny(event)) {
anyListeners = true;
notify(this._emitterListeners.getValues(event), Emitter.suppressErrors, args);
}
// navigate up the prototype chain emitting against the constructors.
if (typeof event === 'object') {
var last = event, proto = Object.getPrototypeOf(event);
while (proto !== null && proto !== last) {
if (this._emitterListeners.hasAny(proto.constructor)) {
anyListeners = true;
notify(this._emitterListeners.getValues(proto.constructor), Emitter.suppressErrors, arguments);
}
last = proto;
proto = Object.getPrototypeOf(proto);
}
}
}
if (this._emitterMetaEventsOn === true && anyListeners === false && event instanceof metaEvents.DeadEvent === false) {
this.trigger(new metaEvents.DeadEvent(event, args));
}
return anyListeners;
} | javascript | {
"resource": ""
} |
q41181 | clearListeners | train | function clearListeners(context) {
if (context == null) { throw new Error('clearListeners: context must be provided.'); }
// notify for every listener we throw out.
var removedListeners, trackRemovals = false;
if (this._emitterMetaEventsOn === true) {
trackRemovals = true;
removedListeners = [];
}
this._emitterListeners.filterAll(function(record) {
var keepListener = record.registeredContext !== context;
if (trackRemovals && keepListener === false) {
removedListeners.push(record);
}
return keepListener;
});
if (trackRemovals && removedListeners.length > 0) {
notifyRemoves(this, removedListeners);
}
} | javascript | {
"resource": ""
} |
q41182 | getIncluded | train | function getIncluded(payload, type, id) {
for (var i = payload.included.length - 1; i >= 0; i--) {
if (payload.included[i].id === id && payload.included[i].type === type) {
return payload.included[i];
}
}
} | javascript | {
"resource": ""
} |
q41183 | getDeepRelationship | train | function getDeepRelationship(payload, parentResource, deepKey) {
var path = deepKey.split('.');
var subResources = parentResource;
for (var i = 0; i < path.length; i++) {
if (Array.isArray(subResources)) {
subResources = subResources.reduce(function (results, subResource) {
return results.concat(
subResource && getRelationship(payload, subResource, path[i])
);
}, []);
}
else {
subResources = subResources && getRelationship(payload, subResources, path[i]);
}
}
return subResources;
} | javascript | {
"resource": ""
} |
q41184 | AggregateTypeMismatch | train | function AggregateTypeMismatch(expected, got){
this.name = 'AggregateTypeMismatch';
this.message = 'Aggregate type mismatch: expected (' + typeof(expected) + ')' + expected + ', got (' + typeof(got) + ')' + got;
this.labels = {
expected: expected,
got: got,
critical: true // This error precludes retry attempts (assuming a sane retry strategy is employed).
};
} | javascript | {
"resource": ""
} |
q41185 | AbstractCliError | train | function AbstractCliError(message, statusCode) {
Error.call(this, message, statusCode);
Error.captureStackTrace(this, AbstractCliError);
this.message = message || this.message
} | javascript | {
"resource": ""
} |
q41186 | createInstanceOf | train | function createInstanceOf(ctor, args) {
var tempCtor = function() {
// This will return the instance or the explicit return of the ctor
// accordingly.
// Remember that if you return a primitive type, the constructor will
// still return the object instance.
return ctor.apply(this, args);
};
tempCtor.prototype = ctor.prototype;
return new tempCtor();
} | javascript | {
"resource": ""
} |
q41187 | merge | train | function merge(input, output) {
const text = fs.readFileSync(input, 'utf8');
const loaded = yaml.safeLoad(text.toString(), { schema: yamlfiles.YAML_FILES_SCHEMA });
// write to output
fs.writeFileSync(output, yaml.safeDump(loaded));
return output;
} | javascript | {
"resource": ""
} |
q41188 | concat | train | function concat(res, done) {
const chunks = []
res
.on('data', chunk => {
chunks.push(chunk)
})
.on('end', () => {
done(Buffer.concat(chunks))
})
} | javascript | {
"resource": ""
} |
q41189 | train | function(app, args) {
let serverType = args.serverType || Constants.RESERVED.MASTER;
let serverId = args.id || app.getMaster().id;
let mode = args.mode || Constants.RESERVED.CLUSTER;
let masterha = args.masterha || 'false';
let type = args.type || Constants.RESERVED.ALL;
let startId = args.startId;
app.set(Constants.RESERVED.MAIN, args.main, true);
app.set(Constants.RESERVED.SERVER_TYPE, serverType, true);
app.set(Constants.RESERVED.SERVER_ID, serverId, true);
app.set(Constants.RESERVED.MODE, mode, true);
app.set(Constants.RESERVED.TYPE, type, true);
if(!!startId) {
app.set(Constants.RESERVED.STARTID, startId, true);
}
if (masterha === 'true') {
app.master = args;
app.set(Constants.RESERVED.CURRENT_SERVER, args, true);
} else if (serverType !== Constants.RESERVED.MASTER) {
app.set(Constants.RESERVED.CURRENT_SERVER, args, true);
} else {
app.set(Constants.RESERVED.CURRENT_SERVER, app.getMaster(), true);
}
} | javascript | {
"resource": ""
} | |
q41190 | onerror | train | function onerror(cb) {
return function (err) {
if (err) {
shas = {}
arguments[0] = err instanceof Error ? err : new Error(err.toString())
}
cb.apply(null, arguments)
}
} | javascript | {
"resource": ""
} |
q41191 | evalSha | train | function evalSha(redis, sha, keys, args, callback) {
if (sha) {
return redis.evalsha.apply(redis, _.flatten([sha, keys.length, keys, args, callback]));
}
return callback(new Error('evalsha called for not loaded script'));
} | javascript | {
"resource": ""
} |
q41192 | loadScript | train | function loadScript(redis, script_name, script, callback) {
redis.multi()
.script('load', script)
.exec(function (err, sha1) {
if (err) {
return callback(err);
}
shas[script_name] = sha1 && sha1.length && sha1[0];
callback(null, sha1);
});
} | javascript | {
"resource": ""
} |
q41193 | train | function(command, host, options, cb) {
let child = null;
if(env === Constants.RESERVED.ENV_DEV) {
child = cp.spawn(command, options);
let prefix = command === Constants.COMMAND.SSH ? '[' + host + '] ' : '';
child.stderr.on('data', function (chunk) {
let msg = chunk.toString();
process.stderr.write(msg);
if(!!cb) {
cb(msg);
}
});
child.stdout.on('data', function (chunk) {
let msg = prefix + chunk.toString();
process.stdout.write(msg);
});
} else {
child = cp.spawn(command, options, {detached: true, stdio: 'inherit'});
child.unref();
}
child.on('exit', function (code) {
if(code !== 0) {
logger.warn('child process exit with error, error code: %s, executed command: %s', code, command);
}
if (typeof cb === 'function') {
cb(code === 0 ? null : code);
}
});
} | javascript | {
"resource": ""
} | |
q41194 | opt | train | function opt(argv, arg, index, key) {
var value = argv[index + 1], equals = arg.indexOf('=');
if(equals > -1) {
value = arg.substr(equals + 1);
}
if(value && ~keys.indexOf(value)) {
return value;
}
if(arg === option[key]) {
return modes[key];
}
} | javascript | {
"resource": ""
} |
q41195 | Store | train | function Store(dir, options) {
// Specify the directory and its options
assert(dir, '`Store` expected a `dir` (directory) to be passed in but it was not defined');
this.dir = dir;
this.memoryCache = {};
// Fallback options
options = options || {};
this.ext = options.ext || Store.ext;
this.stringify = options.stringify || Store.stringify;
this.parse = options.parse || Store.parse;
} | javascript | {
"resource": ""
} |
q41196 | resumeable | train | function resumeable(last,source,s){
source.last = last;
source.on('data',function(data){
source.last = data;
s.write(data);
})
var onPause = function(){
source.pause();
};
var onDrain = function(){
source.resume();
};
var onEnd = function(){
source.end();
};
var cleanup = function(){
s.removeListener('pause',onPause);
s.removeListener('drain',onDrain);
s.removeListener('end',onEnd);
};
s.on('pause',onPause);
s.on('drain',onDrain);
s.on('end',onEnd);
source.on('error',function(){
source._errored = true;
cleanup();
});
source.on('end',function(){
cleanup();
if(!source._errored) {
s.end();
}
})
return s;
} | javascript | {
"resource": ""
} |
q41197 | train | function()
{
var url = this.docsUrl;
var _this = this;
var d = Q.defer();
// Need to create an array of promises for all the pages and their hash
Q.nfcall(request, url + '/api-docs').then(function(data) {
var $ = cheerio.load(data);
var list = $('ul.nav-list li a');
var requests = [];
list.each(function() {
var href = $(this).attr('href');
// If a service, get the promise for the scraped data and
// notify when we've got it
if (/service$/.test(href)) {
var p = _this.getServiceInterface(url + href);
p.then(function(s) { d.notify(s.serviceName); });
requests.push(p);
}
});
// Spread out over all of the promises, when they're all done,
// we've got the data in the arguments var, iterate over that and
// build the hash to return
Q.spread(requests, function() {
d.resolve(_(arguments).toArray());
});
});
return d.promise;
} | javascript | {
"resource": ""
} | |
q41198 | train | function()
{
var url = this.tableUrl;
var _this = this;
var d = new Q.defer();
var tableInfo;
this.getTableInfo()
.then(function(info) {
tableInfo = info;
return Q.nfcall(request, url + '/index.html');
})
.then(function(data) {
var $ = cheerio.load(data);
var list = $('#tables li');
var requests = [];
list.each(function() {
var $this = this;
var title = $this.find('a').text();
var link = $this.find('a').attr('href');
// Once we've got the table, add the description and fire an
// update back on the promise
var p = _this.getTableFields(url + '/' + link);
p.then(function(t) { t.description = tableInfo[t.tableName]; });
p.then(function(s) { d.notify(s.tableName); });
requests.push(p);
});
Q.spread(requests, function() {
d.resolve(_(arguments).toArray());
});
});
return d.promise;
} | javascript | {
"resource": ""
} | |
q41199 | train | function(tableUrl)
{
var _this = this;
return Q.nfcall(request, tableUrl).then(function(data) {
var $ = cheerio.load(data);
var title = $('h2').first().text();
var $rows = $('table tr');
_this.tables.push(title);
var ret = {
tableName: title,
description: '',
fields: []
};
$rows.each(function() {
var $row = $(this);
var name = $row.find('td').first().text();
var type = $row.find('td:nth-child(2)').text();
var access = $row.find('td:nth-child(3)')
.text().toLowerCase().trim().split(' ');
if (!name) return;
ret.fields.push({
name: name,
type: type,
access: access
});
});
return ret;
});
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.