_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q60400
|
listIndexes
|
validation
|
function listIndexes(callback) {
debug('[%s] list existing indexes', self.queueName);
collection.indexInformation({full: true}, function(err, indexInfo) {
if (err) {
debug('[%s] error getting indexInfo. skipping ttl index check: %s', self.queueName, err);
return callback(null, null);
}
return callback(null, indexInfo);
});
}
|
javascript
|
{
"resource": ""
}
|
q60401
|
validation
|
function(datasetId, params, callback) {
var interceptor = requestInterceptors[datasetId] || defaults.requestInterceptor;
return interceptor(datasetId, params, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q60402
|
addToQueue
|
validation
|
function addToQueue(items, extraParams, targetQueue, cb) {
if (!items || items.length === 0) {
return cb();
}
var itemsToPush = _.map(items, function(item) {
return _.extend({}, item, extraParams);
});
debug("adding %d items to queue %s", itemsToPush.length, targetQueue.getName());
targetQueue.addMany(itemsToPush, cb);
}
|
javascript
|
{
"resource": ""
}
|
q60403
|
formatUpdates
|
validation
|
function formatUpdates(processedUpdates) {
var updates = {
hashes: {}
};
_.each(processedUpdates, function(update) {
var type = update.type;
var hash = update.hash;
updates.hashes[hash] = update;
updates[type] = updates[type] || {};
updates[type][hash] = update;
});
return updates;
}
|
javascript
|
{
"resource": ""
}
|
q60404
|
removeUpdatesInRequest
|
validation
|
function removeUpdatesInRequest(updatesInDb, updatesInRequest) {
var updatesNotInRequest = _.filter(updatesInDb, function(dbUpdate) {
var foundInRequest = _.findWhere(updatesInRequest, {hash: dbUpdate.hash});
return !foundInRequest;
});
return updatesNotInRequest;
}
|
javascript
|
{
"resource": ""
}
|
q60405
|
sync
|
validation
|
function sync(datasetId, params, cb) {
debug('[%s] process sync request for the dataset', datasetId);
var queryParams = params.query_params || {};
var metaData = params.meta_data || {};
var datasetClient = new DatasetClient(datasetId, {queryParams: queryParams, metaData: metaData});
debug('[%s] processing sync API request :: query_params = %j:: meta_data = %j', datasetId, queryParams, metaData);
async.series({
requestInterceptor: async.apply(interceptors.requestInterceptor, datasetId, params),
readDatasetClient: function checkDatasetclientStopped(callback) {
syncStorage.readDatasetClient(datasetClient.getId(), function(err, datasetClientJson) {
if (err) {
return callback(err);
}
if (datasetClientJson && datasetClientJson.stopped === true) {
return callback(new Error('sync stopped for dataset ' + datasetId));
} else {
return callback(null, datasetClientJson);
}
});
}
}, function(err, results) {
if (err) {
debugError('[%s] sync request returns error = %s %j', datasetId, err, params);
return cb(err);
}
return processSyncAPI(datasetId, params, results.readDatasetClient, cb);
});
}
|
javascript
|
{
"resource": ""
}
|
q60406
|
DatasetClientsCleaner
|
validation
|
function DatasetClientsCleaner(opts) {
this.retentionPeriod = opts.retentionPeriod || '24h';
this.checkFrequency = opts.checkFrequency || '1h';
this.cleanerLockName = opts.cleanerLockName || 'locks:sync:DatasetCleaner';
this.lockTimeout = parseDuration(this.checkFrequency) / 2;
this.job;
}
|
javascript
|
{
"resource": ""
}
|
q60407
|
validation
|
function (error) {
if (error) {
result.callbackError(error, false);
} else {
result.callbackOk(undefined, false);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60408
|
validation
|
function (element) {
for (var i = 0, len = this.length; i < len; i++) {
if (element === this[i]) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q60409
|
validation
|
function (elements) {
if (!_.isArray(elements)) {
elements = [ elements ];
}
elements.forEach(function (e) {
this.push(e);
}.bind(this));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q60410
|
validation
|
function (list) {
var result = false;
list.forEach(function (e) {
result |= this.removeElement(e);
}.bind(this));
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q60411
|
validation
|
function (predicate) {
var lists = new ArrayList;
var arrays = _.partition(this, predicate);
arrays.forEach(function (arr) {
var list = new ArrayList;
lists.push(list.add(arr));
});
return lists;
}
|
javascript
|
{
"resource": ""
}
|
|
q60412
|
validation
|
function (isSorted, iterator) {
var list = new ArrayList;
return list.add(_.uniq(this, isSorted, iterator));
}
|
javascript
|
{
"resource": ""
}
|
|
q60413
|
validation
|
function (iterator, context) {
var list = new ArrayList;
return list.add(_.map(this, iterator, context));
}
|
javascript
|
{
"resource": ""
}
|
|
q60414
|
validation
|
function (predicate, context) {
var list = new ArrayList;
return list.add(_.filter(this, predicate, context));
}
|
javascript
|
{
"resource": ""
}
|
|
q60415
|
validation
|
function (iterator, context) {
var list = new ArrayList;
return list.add(_.sortBy(this, iterator, context));
}
|
javascript
|
{
"resource": ""
}
|
|
q60416
|
thisToArgs
|
validation
|
function thisToArgs(that, args) {
args = Array.prototype.slice.call(args, 0);
args.unshift(that);
return args;
}
|
javascript
|
{
"resource": ""
}
|
q60417
|
KoaNunjucks
|
validation
|
function KoaNunjucks(oCtx, sPath, oOpts) {
// Configure Nunjucks
this.enviornment = nunjucks.configure(sPath, oOpts);
// Save context
this._ctx = oCtx;
}
|
javascript
|
{
"resource": ""
}
|
q60418
|
get_registers
|
validation
|
function get_registers(cpu) {
cpu = cpu.toLowerCase();
if (cpu.startsWith('arm')) {
return REGISTERS.ARM;
}
if (~[ 'x86', 'i386', 'i486', 'i686' ].indexOf(cpu)) {
return REGISTERS.X86;
}
if (cpu === 'x86_64') {
return REGISTERS.X86_64;
}
return [];
}
|
javascript
|
{
"resource": ""
}
|
q60419
|
parse
|
validation
|
function parse(report) {
var sys = report['system'] || {};
var info = report['report'] || {};
function _i(x) {
return info[x] || '';
}
function _s(x) {
return sys[x] || '';
}
var error = report['crash']['error'];
var thread = Utils.get_crash_thread(report);
return [
Utils.header('Incident Identifier:', _i('id'), 4),
Utils.header('CrashReporter Key:' , _s('device_app_hash'), 4),
Utils.header('Hardware Model:' , _s('machine'), 4),
Utils.header('Process:' , `${_s('process_name')} [${_s('process_id')}]`),
Utils.header('Path:' , _s('CFBundleExecutablePath')),
Utils.header('Identifier:' , _s('CFBundleIdentifier')),
Utils.header('Version:' , `${_s('CFBundleShortVersionString')} (${_s('CFBundleVersion')})`),
Utils.header('Code Type:' , get_cpu_arch(report)),
Utils.header('Parent Process:' , `${_s('parent_process_name')} [${_s('parent_process_id')}]`),
Utils.header('' , ''),
Utils.header('Date/Time:' , get_time(report)),
Utils.header('OS Version:' , `${_s('system_name')} ${_s('system_version')} (${_s('os_version')})`),
Utils.header('Report Version:' , 104),
Utils.header('' , '')
].concat(
Errors.parse_errors(error, thread)
);
}
|
javascript
|
{
"resource": ""
}
|
q60420
|
convert
|
validation
|
function convert(report) {
return []
.concat(
Parsers.parse('headers', report),
Parsers.parse('reason', report),
Parsers.parse('threads', report),
Parsers.parse('cpu', report),
Parsers.parse('images', report),
Parsers.parse('extras', report)
)
.join('\n')
}
|
javascript
|
{
"resource": ""
}
|
q60421
|
get_crash_thread
|
validation
|
function get_crash_thread(report) {
var crash = report['crash'] || {};
var threads = crash['threads'] || [];
var thread = threads.find(function (thread) {
return !!thread['crashed'];
});
return thread || crash['crashed_thread'];
}
|
javascript
|
{
"resource": ""
}
|
q60422
|
parse
|
validation
|
function parse(report, thread) {
var rows = [''];
var crashed = thread || Utils.get_crash_thread(report);
if (!crashed) {
return rows;
}
var index = crashed['index'];
var sys = report['system'] || {};
var type = sys['binary_cpu_type'];
var sub = sys['binary_cpu_subtype'];
var arch;
if (!type && !sub) {
arch = sys['cpu_arch'];
} else {
arch = CPU.get_cpu_arch(type, sub);
}
var cpu = CPU.get_cpu_type(arch);
rows.push(`Thread ${index} crashed with ${cpu} Thread State:`);
var registers = (crashed['registers'] || {})['basic'] || {};
var reg_order = CPU.get_registers(cpu);
var line = '';
for (var i = 0, j = reg_order.length; i < j; i++) {
if (i % 4 === 0 && i !== 0) {
rows.push(line);
line = '';
}
var register = reg_order[i];
var register_addr = registers[register] || 0;
var register_name = Utils.pad_left(register, ' ', 6);
var register_loc = Utils.pad_hex(register_addr, '0', 8);
var register_pad = Utils.pad_right(register_loc, ' ', 9);
line += `${register_name}: 0x${register_pad}`;
}
if (line) {
rows.push(line);
}
return rows;
}
|
javascript
|
{
"resource": ""
}
|
q60423
|
parse
|
validation
|
function parse(report) {
var system = report['system'] || {};
var crash = report['crash'] || {};
return [ '', 'Extra Information:' ].concat(
parse_nsexception(crash),
parse_crash_thread(report),
parse_last_exception(report),
parse_diagnosis(crash),
parse_recrash(report)
);
}
|
javascript
|
{
"resource": ""
}
|
q60424
|
parse_errors
|
validation
|
function parse_errors(error, thread) {
var signal = error['signal'];
var mach = error['mach'];
var exc_name = mach['exception_name'] || '0';
var code_name = mach['code_name'] || '0x00000000';
var sig_name = signal['name'] || signal['signal'] || '0';
var addr_name = Utils.pad_hex(error['address'] || 0, '0', 8);
var index = 0;
if (thread) {
index = thread['index'];
}
return [
Utils.header('Exception Type:' , `${exc_name} (${sig_name})`),
Utils.header('Exception Codes:' , `${code_name} at 0x${addr_name}`),
Utils.header('Crashed Thread:' , index)
];
}
|
javascript
|
{
"resource": ""
}
|
q60425
|
validation
|
function(definedLogLevels) {
logLevels = this._merge(definedLogLevels);
// go through all the loggers
for (var key in winston.loggers.loggers) {
var logger = winston.loggers.loggers[key];
if (logLevels['all']) {
if (logLevels['all'] != 'none') { // turning on everything
if (logger.transports.console) {
logger.transports.console.level = logLevels['all'];
}
else {
logger.add(winston.transports.Console, {
level : logLevels['all'],
json : false,
timestamp : true,
label : key,
align : true
}, false);
}
}
else { // all = none so remove everything
logger.remove(winston.transports.Console)
}
}
else {
// individual log levels were set
var level = logLevels[key];
if (logger.transports.console) { // if there isn't even a console, nothing to do
if (level != 'none') {
logger.transports.console.level = level;
}
else { // level = none, so turn it off
logger.remove(winston.transports.Console)
}
}
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q60426
|
parse
|
validation
|
function parse(report) {
var rows = [''];
var crash = report['crash'] || {};
var error = crash['error'];
var type = error['type'];
var reason = error['reason'];
var user_exception = error['user_reported'];
var ns_exception = error['nsexception'];
if (ns_exception) {
rows.push(format(ns_exception));
rows.push('');
return rows;
}
if (zombie_exception(report)) {
var last_exception = Utils
.get_last_exception(report);
if (last_exception) {
rows.push(format(last_exception, reason));
rows.push('NOTE: This exception has been deallocated! ' +
'Stack trace is crash from attempting to access this zombie exception.');
rows.push('');
}
return rows;
}
if (user_exception) {
rows.push(format(user_exception, reason));
var line = user_exception['line_of_code'];
var back = user_exception['backtrace'] || [];
if (line || back) {
rows.push('Custom Backtrace:');
}
if (line) {
rows.push(`Line: ${line}`);
}
return rows.concat(back);
}
if (type == 'cpp_exception') {
return rows.concat(format(error['cppexception'], reason));
}
if (type == 'deadlock') {
rows.push('Application main thread deadlocked');
rows.push('');
}
return rows;
}
|
javascript
|
{
"resource": ""
}
|
q60427
|
order_stack
|
validation
|
function order_stack (stack) {
// Find a handle with a before or after property
for (var i = 0; i < stack.length; i++) {
var handle = stack[i].handle;
if (handle._first) {
// remove handle from current position
var mid = stack.splice(i, 1)[0];
// insert it at begining of stack
stack.unshift(mid);
// remove property so we don't order it again later
delete handle._first;
// for debugging
handle._moved_first = true;
// Continue ordering for remaining handles
return order_stack (stack);
}
else if (handle._before || handle._after) {
var position = null;
if (handle._before) {
position = '_before';
}
else if (handle._after) {
position = '_after';
}
var label = handle[position];
for (var j = 0; j < stack.length; j++) {
if (stack[j].handle.label === label) {
// insert before index = j
// insert after index = j + 1
var new_index = j;
if (position == '_after') new_index++;
// move handle in new position
// http://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another
stack.splice(new_index, 0, stack.splice(i, 1)[0]);
// remove _before/_after property so we don't order ad infinitum
handle['_moved' + position] = handle[position]; // for debugging
break;
}
}
delete handle[position];
// Continue ordering for remaining handles
return order_stack (stack);
}
}
// didn't find any handle with a before/after property => done ordering
return true;
}
|
javascript
|
{
"resource": ""
}
|
q60428
|
validation
|
function(name, src, onload, requester, errorback) {
// XHR because it's easier to work with, doesn't pollute and has no reliance on DOM.
// This means support for web workers, possibility to add a pre-processing pipeline
// along with potential to cache scripts for re-use in other contexts.
var xhr = new XMLHttpRequest();
xhr.open("GET", src, true);
var onerror = function(e) {
if (errorback) {
errorback({
src: src,
requester: requester
});
} else {
throw new Error('\n Missing: ' + src + '\n Requester: ' + requester);
}
};
xhr.onerror = onerror;
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
var output = xhr.responseText;
output += "\n//# sourceURL=" + self.location.protocol + "//" + resolveRelative(self.location.host + self.location.pathname, src);
eval.call(null, output);
onload();
} else {
onerror();
}
};
xhr.send();
}
|
javascript
|
{
"resource": ""
}
|
|
q60429
|
rgbToHex
|
validation
|
function rgbToHex(rgb) {
function componentToHex(c) {
var hex = c.toString(16).toUpperCase();
return hex.length === 1 ? "0" + hex : hex;
}
var color = rgb.map(function(component) {
return componentToHex(parseInt(component * 255));
});
color.unshift("0X");
color = color.join("");
return parseInt(color);
}
|
javascript
|
{
"resource": ""
}
|
q60430
|
addKnockoutArrayMutators
|
validation
|
function addKnockoutArrayMutators(ko, array, subscribable, signal) {
var fnNames = ['remove', 'removeAll', 'destroy', 'destroyAll', 'replace'];
fnNames.forEach(function(fnName) {
// Make it a non-enumerable property for consistency with standard Array
// functions
Object.defineProperty(array, fnName, {
enumerable: false,
value: function() {
var result;
// These additional array mutators are built using the underlying
// push/pop/etc. mutators, which are wrapped to trigger notifications.
// But we don't want to trigger multiple notifications, so pause the
// push/pop/etc. wrappers and delivery only one notification at the end
// of the process.
signal.pause = true;
try {
// Creates a temporary observableArray that can perform the operation.
var fn = ko.observableArray.fn[fnName];
result = fn.apply(ko.observableArray(array), arguments);
}
finally {
signal.pause = false;
}
subscribable.notifySubscribers(array);
return result;
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q60431
|
getSubscribableForArray
|
validation
|
function getSubscribableForArray(ko, array) {
var subscribable = array._subscribable;
var signal = {};
if (!subscribable) {
subscribable = array._subscribable = new ko.subscribable();
wrapStandardArrayMutators(array, subscribable, signal);
addKnockoutArrayMutators(ko, array, subscribable, signal);
}
return subscribable;
}
|
javascript
|
{
"resource": ""
}
|
q60432
|
startWatchingarray
|
validation
|
function startWatchingarray(ko, observable, array) {
var subscribable = getSubscribableForArray(ko, array);
return subscribable.subscribe(observable);
}
|
javascript
|
{
"resource": ""
}
|
q60433
|
notifyWhenPresentOrFutureArrayValuesMutate
|
validation
|
function notifyWhenPresentOrFutureArrayValuesMutate(ko, observable) {
var watchingArraySubscription = null;
ko.computed(function() {
// Unsubscribe to any earlier array instance
if (watchingArraySubscription) {
watchingArraySubscription.dispose();
watchingArraySubscription = null;
}
// Subscribe to the new array instance
var newarray = observable();
if (newarray instanceof Array) {
watchingArraySubscription = startWatchingarray(ko, observable, newarray);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q60434
|
deleteBackup
|
validation
|
function deleteBackup(config) {
return new Promise((resolve, reject) => {
const backupPath = path.join(process.cwd(), (config.backup !== undefined) ? config.backup : ".backup");
fs.remove(backupPath, (error) => {
(error === null) ? resolve(config) : reject(error);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q60435
|
inline
|
validation
|
function inline(config, files) {
return new Promise((resolve, reject) => {
let filesChanged = 0;
let i = 0;
(function proceed(result) {
if(result) {
filesChanged++;
}
if(i === files.length) {
resolve("Modified " + filesChanged + " files");
} else {
InlineImport.transform(files[i++], config.options).then(proceed).catch(reject);
}
}());
});
}
|
javascript
|
{
"resource": ""
}
|
q60436
|
getFiles
|
validation
|
function getFiles(config) {
return new Promise((resolve, reject) => {
const src = config.src;
let files = [];
let i = 0;
(function proceed(error, moreFiles) {
if(error !== null) {
reject(error);
} else {
files = files.concat(moreFiles);
if(i === src.length) {
if(files.length === 0) {
reject("No input files found");
} else {
resolve([config, files]);
}
} else {
glob(src[i++], proceed);
}
}
}(null, []));
});
}
|
javascript
|
{
"resource": ""
}
|
q60437
|
validateConfig
|
validation
|
function validateConfig(config) {
return new Promise((resolve, reject) => {
if(config.src !== undefined) {
if(!Array.isArray(config.src)) {
config.src = [config.src];
}
resolve(config);
} else {
reject("No source path specified");
}
});
}
|
javascript
|
{
"resource": ""
}
|
q60438
|
readConfig
|
validation
|
function readConfig() {
// Checks if the package file contains a configuration.
const pkgConfigPromise = new Promise((resolve, reject) => {
fs.readFile(path.join(process.cwd(), "package.json")).then((data) => {
try {
resolve(JSON.parse(data).inlineImport);
} catch(error) {
reject(error);
}
}).catch((error) => {
// There's no configuration in package.json.
resolve();
});
});
// Looks for a configuration file.
const configFilePromise = new Promise((resolve, reject) => {
fs.readFile(path.join(process.cwd(), argv.config)).then((data) => {
try {
resolve(JSON.parse(data));
} catch(error) {
reject(error);
}
}).catch((error) => {
if(error.code === "ENOENT") {
reject("No configuration found (" + argv.config + ")");
} else {
reject("Failed to read the configuration file (" + error + ")");
}
});
});
return new Promise((resolve, reject) => {
pkgConfigPromise.then((config) => {
return (config !== undefined) ? Promise.resolve(config) : configFilePromise;
}).then(resolve).catch(reject);
});
}
|
javascript
|
{
"resource": ""
}
|
q60439
|
readFile
|
validation
|
function readFile(file, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(file, encoding, (error, data) => error ? reject(error) : resolve(data));
});
}
|
javascript
|
{
"resource": ""
}
|
q60440
|
parseImports
|
validation
|
function parseImports(data, file, extensions) {
const imports = [];
let result = importRegExp.exec(data);
let encoding;
while(result !== null) {
encoding = extensions[path.extname(result[2])];
// Filter irrelevant imports.
if(encoding !== undefined) {
imports.push(new FileImport(
result.index,
importRegExp.lastIndex,
result[1],
path.resolve(path.dirname(file), result[2]),
encoding
));
}
result = importRegExp.exec(data);
}
return Promise.resolve([imports, data]);
}
|
javascript
|
{
"resource": ""
}
|
q60441
|
readImports
|
validation
|
function readImports(imports, data) {
return (imports.length === 0) ? Promise.resolve([imports, data]) : new Promise((resolve, reject) => {
let i = 0;
(function proceed(error, importData) {
if(importData) {
imports[i++].data = importData;
}
if(error) {
reject(error);
} else if(i === imports.length) {
resolve([imports, data]);
} else {
fs.readFile(imports[i].path, imports[i].encoding, proceed);
}
}());
});
}
|
javascript
|
{
"resource": ""
}
|
q60442
|
inlineImports
|
validation
|
function inlineImports(imports, data, declaration) {
let modified = imports.length > 0;
let i, item;
// Inline the imports in reverse order to keep the indices intact.
for(i = imports.length - 1; i >= 0; --i) {
item = imports[i];
data = data.substring(0, item.start) +
declaration + " " + item.name + " = " + JSON.stringify(item.data) +
data.substring(item.end);
}
return Promise.resolve([modified, data]);
}
|
javascript
|
{
"resource": ""
}
|
q60443
|
writeFile
|
validation
|
function writeFile(modified, data, file) {
return !modified ? Promise.resolve(false) : new Promise((resolve, reject) => {
fs.writeFile(file, data, (error) => {
error ? reject(error) : resolve(true);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q60444
|
validation
|
function (N, data, CART_OR_SPH, DIRECT_OR_PINV) {
var Ndirs = data.length, Nsh = (N+1)*(N+1);
var invY_N;
var mag = [,];
if (Nsh>Ndirs) {
console.log("The SHT degree is too high for the number of data points")
}
// Convert cartesian to spherical if needed
if (CART_OR_SPH==0) data = convertCart2Sph(data);
for (var i=0; i<data.length; i++) {
mag[i] = data[i][2];
}
// SH sampling matrix
Y_N = computeRealSH(N, data);
// Direct SHT
if (DIRECT_OR_PINV==0) {
invY_N = numeric.mul(1/Ndirs,Y_N);
}
else {
invY_N = pinv_direct(numeric.transpose(Y_N));
}
// Perform SHT
var coeffs = numeric.dotMV(invY_N, mag);
return coeffs;
}
|
javascript
|
{
"resource": ""
}
|
|
q60445
|
validation
|
function (coeffs, aziElev) {
var aziElevR = aziElev;
var N = Math.sqrt(coeffs.length)-1;
// SH sampling matrix
var Y_N = computeRealSH(N, aziElev);
// reconstruction
var data = numeric.dotVM(coeffs, Y_N);
// gather in data matrix
for (var i=0; i<aziElev.length; i++) {
aziElevR[i][2] = data[i];
}
return aziElevR;
}
|
javascript
|
{
"resource": ""
}
|
|
q60446
|
validation
|
function (xyz, OMIT_MAG) {
var azi, elev, r;
var aziElevR = new Array(xyz.length);
for (var i=0; i<xyz.length; i++) {
azi = Math.atan2( xyz[i][1], xyz[i][0] );
elev = Math.atan2( xyz[i][2], Math.sqrt(xyz[i][0]*xyz[i][0] + xyz[i][1]*xyz[i][1]) );
if (OMIT_MAG==1) {
aziElevR[i] = [azi,elev];
}
else {
r = Math.sqrt(xyz[i][0]*xyz[i][0] + xyz[i][1]*xyz[i][1] + xyz[i][2]*xyz[i][2]);
aziElevR[i] = [azi,elev,r];
}
}
return aziElevR;
}
|
javascript
|
{
"resource": ""
}
|
|
q60447
|
validation
|
function (aziElevR) {
var x,y,z;
var xyz = new Array(aziElevR.length);
for (var i=0; i<aziElevR.length; i++) {
x = Math.cos(aziElevR[i][0])*Math.cos(aziElevR[i][1]);
y = Math.sin(aziElevR[i][0])*Math.cos(aziElevR[i][1]);
z = Math.sin(aziElevR[i][1]);
if (aziElevR[0].length==2) xyz[i] = [x,y,z];
else if (aziElevR[0].length==3) xyz[i] = [aziElevR[i][2]*x,aziElevR[i][2]*y,aziElevR[i][2]*z];
}
return xyz;
}
|
javascript
|
{
"resource": ""
}
|
|
q60448
|
validation
|
function (N, data) {
var azi = new Array(data.length);
var elev = new Array(data.length);
for (var i=0; i<data.length; i++) {
azi[i] = data[i][0];
elev[i] = data[i][1];
}
var factorials = new Array(2*N+1);
var Ndirs = azi.length;
var Nsh = (N+1)*(N+1);
var leg_n_minus1 = 0;
var leg_n_minus2 = 0;
var leg_n;
var sinel = numeric.sin(elev);
var index_n = 0;
var Y_N = new Array(Nsh);
var Nn0, Nnm;
var cosmazi, sinmazi;
// precompute factorials
for (var i = 0; i < 2*N+1; i++) factorials[i] = factorial(i);
for (var n = 0; n<N+1; n++) {
if (n==0) {
var temp0 = new Array(azi.length);
temp0.fill(1);
Y_N[n] = temp0;
index_n = 1;
}
else {
leg_n = recurseLegendrePoly(n, sinel, leg_n_minus1, leg_n_minus2);
Nn0 = Math.sqrt(2*n+1);
for (var m = 0; m<n+1; m++) {
if (m==0) Y_N[index_n+n] = numeric.mul(Nn0,leg_n[m]);
else {
Nnm = Nn0*Math.sqrt( 2 * factorials[n-m]/factorials[n+m] );
cosmazi = numeric.cos(numeric.mul(m,azi));
sinmazi = numeric.sin(numeric.mul(m,azi));
Y_N[index_n+n-m] = numeric.mul(Nnm, numeric.mul(leg_n[m], sinmazi));
Y_N[index_n+n+m] = numeric.mul(Nnm, numeric.mul(leg_n[m], cosmazi));
}
}
index_n = index_n+2*n+1;
}
leg_n_minus2 = leg_n_minus1;
leg_n_minus1 = leg_n;
}
return Y_N;
}
|
javascript
|
{
"resource": ""
}
|
|
q60449
|
validation
|
function (n, x, Pnm_minus1, Pnm_minus2) {
var Pnm = new Array(n+1);
switch(n) {
case 1:
var x2 = numeric.mul(x,x);
var P10 = x;
var P11 = numeric.sqrt(numeric.sub(1,x2));
Pnm[0] = P10;
Pnm[1] = P11;
break;
case 2:
var x2 = numeric.mul(x,x);
var P20 = numeric.mul(3,x2);
P20 = numeric.sub(P20,1);
P20 = numeric.div(P20,2);
var P21 = numeric.sub(1,x2);
P21 = numeric.sqrt(P21);
P21 = numeric.mul(3,P21);
P21 = numeric.mul(P21,x);
var P22 = numeric.sub(1,x2);
P22 = numeric.mul(3,P22);
Pnm[0] = P20;
Pnm[1] = P21;
Pnm[2] = P22;
break;
default:
var x2 = numeric.mul(x,x);
var one_min_x2 = numeric.sub(1,x2);
// last term m=n
var k = 2*n-1;
var dfact_k = 1;
if ((k % 2) == 0) {
for (var kk=1; kk<k/2+1; kk++) dfact_k = dfact_k*2*kk;
}
else {
for (var kk=1; kk<(k+1)/2+1; kk++) dfact_k = dfact_k*(2*kk-1);
}
Pnm[n] = numeric.mul(dfact_k, numeric.pow(one_min_x2, n/2));
// before last term
Pnm[n-1] = numeric.mul(2*n-1, numeric.mul(x, Pnm_minus1[n-1])); // P_{n(n-1)} = (2*n-1)*x*P_{(n-1)(n-1)}
// three term recursence for the rest
for (var m=0; m<n-1; m++) {
var temp1 = numeric.mul( 2*n-1, numeric.mul(x, Pnm_minus1[m]) );
var temp2 = numeric.mul( n+m-1, Pnm_minus2[m] );
Pnm[m] = numeric.div( numeric.sub(temp1, temp2), n-m); // P_l = ( (2l-1)xP_(l-1) - (l+m-1)P_(l-2) )/(l-m)
}
}
return Pnm;
}
|
javascript
|
{
"resource": ""
}
|
|
q60450
|
validation
|
function (A) {
var z = numeric.svd(A), foo = z.S[0];
var U = z.U, S = z.S, V = z.V;
var m = A.length, n = A[0].length, tol = Math.max(m,n)*numeric.epsilon*foo,M = S.length;
var Sinv = new Array(M);
for(var i=M-1;i!==-1;i--) { if(S[i]>tol) Sinv[i] = 1/S[i]; else Sinv[i] = 0; }
return numeric.dot(numeric.dot(V,numeric.diag(Sinv)),numeric.transpose(U))
}
|
javascript
|
{
"resource": ""
}
|
|
q60451
|
validation
|
function (A) {
var AT = numeric.transpose(A);
return numeric.dot(numeric.inv(numeric.dot(AT,A)),AT);
}
|
javascript
|
{
"resource": ""
}
|
|
q60452
|
validation
|
function (yaw, pitch, roll) {
var Rx, Ry, Rz;
if (roll == 0) Rx = [[1,0,0],[0,1,0],[0,0,1]];
else Rx = [[1, 0, 0], [0, Math.cos(roll), Math.sin(roll)], [0, -Math.sin(roll), Math.cos(roll)]];
if (pitch == 0) Ry = [[1,0,0],[0,1,0],[0,0,1]];
else Ry = [[Math.cos(pitch), 0, -Math.sin(pitch)], [0, 1, 0], [Math.sin(pitch), 0, Math.cos(pitch)]];
if (yaw == 0) Rz = [[1,0,0],[0,1,0],[0,0,1]];
else Rz = [[Math.cos(yaw), Math.sin(yaw), 0], [-Math.sin(yaw), Math.cos(yaw), 0], [0, 0, 1]];
var R = numeric.dotMMsmall(Ry,Rz);
R = numeric.dotMMsmall(Rx,R);
return R;
}
|
javascript
|
{
"resource": ""
}
|
|
q60453
|
siftdown
|
validation
|
function siftdown(compare, a, i, j, k) {
var current = k - i;
while (true) {
// address of the first child in a zero-based
// binary heap
var firstchild = 2 * current + 1;
// if current node has no children
// then we are done
if (firstchild >= j - i) break;
// if current value is smaller than its smallest
// child then we are done
var candidate = (0, _nextchild2.default)(compare, a, i + firstchild, j);
if (compare(a[i + current], a[candidate]) <= 0) break;
// otherwise
// swap with smallest child
var tmp = a[i + current];
a[i + current] = a[candidate];
a[candidate] = tmp;
current = candidate - i;
}
return i + current;
}
|
javascript
|
{
"resource": ""
}
|
q60454
|
nextchild
|
validation
|
function nextchild(compare, a, i, j) {
if (j - i < 2) return i;
if (compare(a[i], a[i + 1]) <= 0) return i;
return i + 1;
}
|
javascript
|
{
"resource": ""
}
|
q60455
|
siftup
|
validation
|
function siftup(compare, a, i, j, k) {
var current = k - i;
// while we are not the root
while (current !== 0) {
// address of the parent in a zero-based
// d-ary heap
var parent = i + (current - 1 >>> 1);
// if current value is greater than its parent
// then we are done
if (compare(a[i + current], a[parent]) >= 0) return i + current;
// otherwise
// swap with parent
var tmp = a[i + current];
a[i + current] = a[parent];
a[parent] = tmp;
current = parent - i;
}
return i + current;
}
|
javascript
|
{
"resource": ""
}
|
q60456
|
exec
|
validation
|
function exec(command, options) {
return new PromiseWithEvents_1.PromiseWithEvents(function (resolve, reject, eventEmitter) {
var childProcess = cp.exec(command, options, function (err, stdout, stderr) {
if (err) {
reject(err);
}
else {
resolve({
stdout: stdout.toString(),
stderr: stderr.toString()
});
}
});
process.nextTick(function () { return eventEmitter.emit('process', childProcess); });
});
}
|
javascript
|
{
"resource": ""
}
|
q60457
|
field
|
validation
|
function field(query) {
var queryDefinition;
if (query instanceof Function) {
queryDefinition = query();
}
else {
queryDefinition = query;
}
var customField = queryDefinition.select;
customField = customField.addSubQuery(queryDefinition);
// Field query cannot be joined to any other query so don't have set the positional fields
return customField;
}
|
javascript
|
{
"resource": ""
}
|
q60458
|
ManyToOne
|
validation
|
function ManyToOne(elements) {
return function (targetObject, propertyKey) {
var entityMetadata = targetObject;
if (!entityMetadata.manyToOneMap) {
entityMetadata.manyToOneMap = {};
}
entityMetadata.manyToOneMap[propertyKey] = elements;
};
}
|
javascript
|
{
"resource": ""
}
|
q60459
|
OneToMany
|
validation
|
function OneToMany(elements) {
return function (targetObject, propertyKey) {
var entityMetadata = targetObject;
if (!entityMetadata.oneToManyMap) {
entityMetadata.oneToManyMap = {};
}
entityMetadata.oneToManyMap[propertyKey] = elements;
};
}
|
javascript
|
{
"resource": ""
}
|
q60460
|
Entity
|
validation
|
function Entity(entityConfiguration) {
return function (constructor) {
var entityMetadata = constructor;
if (entityMetadata.entity) {
throw "Cannot set @Table, it is already set to '" + JSON.stringify(entityMetadata.entity) + "'";
}
// FIXME: verify this works! (that it's not constructor.name)
entityMetadata.name = constructor.prototype.name;
if (!entityConfiguration) {
entityConfiguration = true;
}
entityMetadata.entity = entityConfiguration;
};
}
|
javascript
|
{
"resource": ""
}
|
q60461
|
Table
|
validation
|
function Table(tableConfiguration) {
return function (constructor) {
var entityMetadata = constructor;
if (entityMetadata.table) {
throw "Cannot set @Table, it is already set to '" + JSON.stringify(entityMetadata.table) + "'";
}
entityMetadata.table = tableConfiguration;
};
}
|
javascript
|
{
"resource": ""
}
|
q60462
|
observeResize
|
validation
|
function observeResize (el, cb) {
assert.ok(isDom(el), 'observe-resize: el should be a valid DOM element')
assert.equal(typeof cb, 'function', 'observe-resize: cb should be type function')
// Make this function a noop in non-browser environments
if (typeof window !== 'object') return
var called = false
var frame = document.createElement('iframe')
frame.setAttribute('class', '__observe-resize__')
el.appendChild(frame)
assert.ok(frame.contentWindow, 'observe-resize: no contentWindow detected - cannot start observing')
frame.contentWindow.onresize = handleResize
return function stopObserving () {
if (frame.parentNode) frame.parentNode.removeChild(frame)
}
function handleResize () {
if (called) return
called = true
window.requestAnimationFrame(function () {
called = false
cb(el)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q60463
|
getTasks
|
validation
|
function getTasks() {
const tasks = {},
tmp = {},
mods = {},
exec = Object.assign({}, execStack);
let total = 0,
count = 0;
(0, _core2.default)(exec).forEach((el, key) => {
tmp[key] = (0, _core2.default)(el).map((el, key) => key);
mods[key] = 0;
count++;
}, el => el.length);
/* eslint-disable no-loop-func */
const sort = (a, b) => b.value - a.value;
while (total <= _thread.MAX_PRIORITY) {
const rands = [];
(0, _core2.default)(exec).forEach((el, key) => {
rands.push({
key,
value: _thread.PRIORITY[key]
});
}, el => el.length);
rands.sort(sort);
let pos = rands.length - 1,
max = 0;
(0, _core2.default)(rands).forEach((el, i) => {
const interval = intervals[pos];
if (interval[1] > max) {
max = interval[1];
}
rands[i].value = interval;
pos--;
});
const rand = (0, _math.getRandomInt)(0, max);
(0, _core2.default)(rands).forEach(({ key, value }) => {
const arr = tmp[key];
if (rand >= value[0] && rand <= value[1]) {
tasks[key] = tasks[key] || [];
let pos = lastPos[key];
if (arr[pos] == null) {
lastPos[key] = pos = 0;
mods[key] = 0;
}
const point = exec[key][arr[pos]];
if (point && !point.pause) {
mods[key]++;
tasks[key].push(arr[pos]);
total += _thread.PRIORITY[key];
}
arr.splice(pos, 1);
if (!arr.length) {
delete exec[key];
count--;
}
return false;
}
});
if (!count) {
break;
}
}
/* eslint-enable no-loop-func */
(0, _core2.default)(mods).forEach((el, key) => {
lastPos[key] += el;
});
return tasks;
}
|
javascript
|
{
"resource": ""
}
|
q60464
|
checkTile
|
validation
|
function checkTile(tile) {
// No tile, ignore
if (!tile) return false;
// If an array of indices was provided, tile's index must be in that array
if (tileIndices && tileIndices.includes(tile.index)) return true;
// If a tile property was provided, the tile must have a truthy value for that property
if (tileProperty && tile.properties[tileProperty]) return true;
// If we only care about colliding tiles, make sure the tile collides
if (checkCollide && tile.collides) return true;
// Tile didn't pass any checks, ignore
return false;
}
|
javascript
|
{
"resource": ""
}
|
q60465
|
returnCache
|
validation
|
function returnCache(cache) {
let text = '';
for (const key in cache) {
if (!cache.hasOwnProperty(key)) {
continue;
}
text += cache[key];
}
return text;
}
|
javascript
|
{
"resource": ""
}
|
q60466
|
__encode
|
validation
|
function __encode(raw, key) {
var len = _.size(key);
var cc = len; // key switch counter
return new Buffer(_.map(raw, function(num, index) {
if (cc-- > 0) {
return (num + key.shift()) % 256;
}
return (num + raw[index - len]) % 256;
}));
}
|
javascript
|
{
"resource": ""
}
|
q60467
|
__decode
|
validation
|
function __decode(raw, key) {
var res = []; // output buffer
var len = _.size(key);
var cc = len; // key switch counter
for (var i = 0, ii = _.size(raw); i < ii; ++i) {
if (cc-- > 0) {
res[i] = (raw[i] - key.shift()) % 256;
} else {
res[i] = (raw[i] - res[i - len]) % 256;
}
}
return new Buffer(res);
}
|
javascript
|
{
"resource": ""
}
|
q60468
|
process
|
validation
|
function process (rawXLSX, options) {
// if no options are passed, set an empty Object as default
options = options || {}
// check for errors in the options, and clean up if needed
options = validateOptions(options)
// if no processor is set, assume `keyvalue`
const defaultProcessor = options.processor || 'keyvalue'
// if no overrides were set, assume there are none
const overrides = options.overrides || {}
// if the XLSX file came over as a Buffer, read it differently
const workbook = rawXLSX instanceof Buffer ? XLSX.read(rawXLSX, {type: 'buffer'}) : XLSX.readFile(rawXLSX)
// get the names of all the sheets in an Array
let sheets = workbook.SheetNames
if (options.includeSheets) {
sheets = sheets.filter((s) => options.includeSheets.indexOf(s) !== -1)
}
if (options.excludeSheets) {
sheets = sheets.filter((s) => options.excludeSheets.indexOf(s) === -1)
}
// the eventual payload returned to the callback
let payload = {}
// for each sheet in the workbook process its contents
sheets.forEach(function (sheet) {
// determine the appropriate processor, using the override if it exists
const processor = overrides.hasOwnProperty(sheet) ? overrides[sheet] : defaultProcessor
// pass pass the sheet on to the process script with the correct processor
payload[sheet] = getProcessor(processor)(workbook.Sheets[sheet])
})
// return the processed data
return payload
}
|
javascript
|
{
"resource": ""
}
|
q60469
|
validateOptions
|
validation
|
function validateOptions (options) {
// doesn't make sense to pass both, so prevent it
if (options.includeSheets && options.excludeSheets) {
throw new Error("Do not pass both `includeSheets` and `excludeSheets`. It's confusing.")
}
// if `includeSheets` exists and isn't an Array, make it so
if (options.includeSheets) {
if (!Array.isArray(options.includeSheets)) options.includeSheets = [options.includeSheets]
}
// if `excludeSheets` exists and isn't an Array, make it so
if (options.excludeSheets) {
if (!Array.isArray(options.excludeSheets)) options.excludeSheets = [options.excludeSheets]
}
// if `excludeSheets` is set and one of them show up in `overrides`, it won't
// break anything, but the user should be aware it won't work
if (options.excludeSheets && options.overrides) {
const overrides = Object.keys(options.overrides)
overrides.forEach((override) => {
if (options.excludeSheets.indexOf(override) !== -1) {
console.warn(`\`${override}\` has an override, but it is also being excluded in \`excludeSheets\`.`)
}
})
}
return options
}
|
javascript
|
{
"resource": ""
}
|
q60470
|
isLikeArray
|
validation
|
function isLikeArray(obj) {
const res = isArray(obj) || obj &&
// The hack for PhantomJS,
// because it has strange bug for HTMLCollection and NodeList:
// typeof 'function' && instanceof Function = false
isObjectInstance(obj) && !isFuncRgxp.test(toString.call(obj)) && (
// If the object is like an array
obj.length > 0 && 0 in obj || obj.length === 0);
return Boolean(res);
}
|
javascript
|
{
"resource": ""
}
|
q60471
|
isIterator
|
validation
|
function isIterator(obj) {
return Boolean(obj && (typeof Symbol === 'function' ? obj[Symbol.iterator] : isFunction(obj['@@iterator'])));
}
|
javascript
|
{
"resource": ""
}
|
q60472
|
isStream
|
validation
|
function isStream(obj) {
return Boolean(obj && isFunction(obj.addListener) && isFunction(obj.removeListener) && isFunction(obj.destroy) && (isFunction(obj.write) && isFunction(obj.end) || isFunction(obj.pipe) && isFunction(obj.read) && isFunction(obj.pause) && isFunction(obj.resume)));
}
|
javascript
|
{
"resource": ""
}
|
q60473
|
getType
|
validation
|
function getType(obj, opt_use) {
if (!obj) {
return null;
}
switch (opt_use) {
case 'for':
return 'array';
case 'for in':
return 'object';
case 'for of':
return 'iterator';
case 'async for of':
return 'asyncIterator';
default:
if (obj === Empty) {
return null;
}
if (isMap(obj)) {
return 'map';
}
if (isWeakMap(obj)) {
return 'weakMap';
}
if (isSet(obj)) {
return 'set';
}
if (isWeakSet(obj)) {
return 'weakSet';
}
if (isGenerator(obj)) {
return 'generator';
}
if (isLikeArray(obj)) {
return 'array';
}
if (isIterator(obj)) {
return 'iterator';
}
if (isIDBRequest(obj)) {
return 'idbRequest';
}
if (isStream(obj)) {
return 'stream';
}
}
return 'object';
}
|
javascript
|
{
"resource": ""
}
|
q60474
|
getSameAs
|
validation
|
function getSameAs(obj) {
if (!obj) {
return false;
}
if (isArray(obj)) {
return [];
}
if (isPlainObject(obj)) {
return {};
}
if (isMap(obj)) {
return new Map();
}
if (isSet(obj)) {
return new Set();
}
return isFunction(obj.constructor) && !isNative.test(obj.constructor.toString()) ? {} : false;
}
|
javascript
|
{
"resource": ""
}
|
q60475
|
isStructure
|
validation
|
function isStructure(obj) {
if (!obj) {
return false;
}
if (isArray(obj) || isPlainObject(obj) || isMap(obj) || isSet(obj)) {
return true;
}
return isFunction(obj.constructor) && !isNative.test(obj.constructor.toString());
}
|
javascript
|
{
"resource": ""
}
|
q60476
|
canExtendProto
|
validation
|
function canExtendProto(obj) {
if (!obj) {
return false;
}
if (isArray(obj) || isPlainObject(obj)) {
return true;
}
return isFunction(obj.constructor) && !isNative.test(obj.constructor.toString());
}
|
javascript
|
{
"resource": ""
}
|
q60477
|
asyncRoute
|
validation
|
async function asyncRoute(req, res) {
await fakeWait();
res.send({ ok: true });
}
|
javascript
|
{
"resource": ""
}
|
q60478
|
validation
|
async function (query, options) {
try {
let response = await fetch(`http://www.ondemandkorea.com/includes15/search?q=${query}`, options);
let json = await response.json();
return json;
} catch (err) {
return err;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60479
|
wrapRoute
|
validation
|
function wrapRoute(fn) {
if (!_lodash2.default.isFunction(fn)) {
throw new Error('fn should be a function');
}
return function (req, res, next) {
try {
var result = fn(req, res, next);
if (result && result.catch) {
result.catch(next);
}
} catch (e) {
next(e);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q60480
|
validation
|
function(msg, flags) {
if (flags.exact) {
seneca.add(_.extend({}, msg, { role: 'entity', cmd: 'save' }), save)
seneca.add(_.extend({}, msg, { role: 'entity', cmd: 'load' }), load)
seneca.add(_.extend({}, msg, { role: 'entity', cmd: 'list' }), list)
seneca.add(_.extend({}, msg, { role: 'entity', cmd: 'remove' }), remove)
return
}
var actions = {
save: save,
load: load,
list: list,
remove: remove
}
var core_patterns = [
{ role: 'entity', cmd: 'save' },
{ role: 'entity', cmd: 'load' },
{ role: 'entity', cmd: 'list' },
{ role: 'entity', cmd: 'remove' }
]
_.each(core_patterns, function(core_pat) {
var pats = seneca.list(core_pat)
_.each(pats, function(pat) {
seneca.add(pat, actions[core_pat.cmd])
})
})
}
|
javascript
|
{
"resource": ""
}
|
|
q60481
|
FBOAuth2
|
validation
|
function FBOAuth2(appId, appSecret, redirectURL){
this._appId = appId;
this._appSecret = appSecret;
this._redirectURL = redirectURL;
this._authURL = 'https://www.facebook.com/dialog/oauth';
this._graphAPIURL = 'https://graph.facebook.com';
this._accessTokenURI = '/oauth/access_token';
this._profileURI = '/me';
}
|
javascript
|
{
"resource": ""
}
|
q60482
|
validation
|
function(options) {
EventEmitter.apply(this, arguments);
options = options || {};
this.limit = options.limit || 16;
this.json = options.json || false;
this.records = options.records || [];
}
|
javascript
|
{
"resource": ""
}
|
|
q60483
|
spy
|
validation
|
function spy(obj, method) {
if (!obj && !method) {
obj = { spy: function(){} };
method = 'spy';
}
return double(obj, method);
}
|
javascript
|
{
"resource": ""
}
|
q60484
|
validation
|
function(conf, bitwise, parent) {
EventEmitter.call(this);
conf = conf || {};
constants(this);
this.keys = keys;
this.bitwise = (bitwise === true);
this.configure();
var cstreams = parent && conf.streams;
var streams = conf.streams, stream = conf.stream;
streams = streams || this.getDefaultStream(conf);
delete conf.streams;
delete conf.stream;
var target = parent ? merge(parent.conf, {}) : merge(defaults, {});
this.conf = merge(conf, target);
if(typeof this.conf.name !== 'string' || !this.conf.name.length) {
throw new Error('Logger name \'' + this.conf.name + '\' is invalid');
}
this.name = this.conf.name;
conf.streams = streams;
if(stream) conf.stream = stream;
this.pid = this.conf.pid || process.pid;
this.hostname = this.conf.hostname || os.hostname();
this.fields = {};
this.streams = [];
if(parent && cstreams) {
streams = Array.isArray(streams) ? streams : [streams];
streams = streams.concat(conf.streams);
}
this.initialize(streams);
}
|
javascript
|
{
"resource": ""
}
|
|
q60485
|
createLogger
|
validation
|
function createLogger(conf, bitwise) {
conf = conf || {};
if(conf.json === undefined) conf.json = true;
return new Logger(conf, bitwise);
}
|
javascript
|
{
"resource": ""
}
|
q60486
|
validation
|
function(id, type, attributes, relationships) {
var _this = this;
JsonApiResource.call(_this, id, type);
BaseAttributesCreatedUpdated.call(_this);
_this['type'] = type;
_this['attributes'] = attributes;
_this['relationships'] = relationships;
}
|
javascript
|
{
"resource": ""
}
|
|
q60487
|
mergeModels
|
validation
|
function mergeModels(value, model) {
const newModel = Object.assign({}, model);
tools_1.deepExtend(newModel, value);
return { model: newModel, isChanged: deepEqual(model, newModel) };
}
|
javascript
|
{
"resource": ""
}
|
q60488
|
validation
|
function(name, obj) {
obj._namespace = name;
observers = observers.concat(obj._observers);
obj._emitter = caramel;
}
|
javascript
|
{
"resource": ""
}
|
|
q60489
|
validation
|
function(name, obj, after) {
if (typeof after === 'string' && !inject(after)()) {
caramel.once('register:' + after, function() {
register(name, obj);
});
return;
}
var path = name.split('.');
var ref = container;
for (var i = 0; i < path.length - 1; i++) {
if (!ref[path[i]]) {
ref = ref[path[i]] = {};
} else {
ref = ref[path[i]];
}
}
if (!ref[path[path.length - 1]]) {
ref[path[path.length - 1]] = { cream : obj };
} else {
ref[path[path.length - 1]].cream = obj;
}
createCream(name, obj);
caramel.emit('register:' + name);
}
|
javascript
|
{
"resource": ""
}
|
|
q60490
|
validation
|
function(name) {
var path = name.split('.');
var ref = container;
for (var i = 0; i < path.length - 1; i++) {
if (!(ref = ref[path[i]])) {
return;
}
}
if (typeof ref[path[path.length - 1]] === 'object') {
/**
* Destroy registered Cream
*/
if (ref[path[path.length - 1]]._type === 'Cream') {
removeCream(name, ref[path[path.length - 1]].cream);
} else if (ref[path[path.length - 1]].cream &&
ref[path[path.length - 1]].cream._type === 'Cream') {
removeCream(name, ref[path[path.length - 1]].cream);
delete ref[path[path.length - 1]].cream;
}
delete ref[path[path.length - 1]];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60491
|
_reduceStream
|
validation
|
function _reduceStream (stream$, reducer, cb) {
stream$
.pipe(reduce(reducer.fn, reducer.memo))
.once('data', function (reduction) {
cb(null, reduction);
})
.once('error', cb);
}
|
javascript
|
{
"resource": ""
}
|
q60492
|
reduceHooks
|
validation
|
function reduceHooks (hooks) {
return msg => {
let tmp
return hooks.reduce((prev, hook) => {
tmp = hook(prev)
if (tmp === undefined || tmp === null) { return prev }
return tmp
}, msg)
}
}
|
javascript
|
{
"resource": ""
}
|
q60493
|
pcomp
|
validation
|
function pcomp(f, g) {
return function () {
return f.apply(null, arguments) && g.apply(null, arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
q60494
|
replace
|
validation
|
function replace (regex, replacement, fileFilter) {
if (fileFilter instanceof Array) {
fileFilter = fileFilter.reduce(pcomp);
} else if (!fileFilter) {
fileFilter = () => true;
}
return files => {
_.forEach(files, (file, path) => {
if (fileFilter(file, path)) {
file.contents = new Buffer(file.contents.toString().replace(regex, replacement));
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q60495
|
paragraph
|
validation
|
function paragraph(dict, wordCount, startWithCommon) {
const result = [];
let totalWords = 0;
let words;
if (startWithCommon && dict.common) {
words = dict.common.slice(0, wordCount);
totalWords += words.length;
result.push(sentence(insertCommas(words), '.'));
}
while (totalWords < wordCount) {
words = sample(dict.words, Math.min(rand(2, 30), wordCount - totalWords));
totalWords += words.length;
result.push(sentence(insertCommas(words)));
}
return result.join(' ');
}
|
javascript
|
{
"resource": ""
}
|
q60496
|
validation
|
function (scriptOrLink) {
for(var p= 0, len = options.ignorePatterns.length; p < len; p++){
if(options.ignorePatterns[p].test(scriptOrLink)){
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q60497
|
render
|
validation
|
function render(activities, highlight) {
// Top verbs plus 'other'.
var verbs = topVerbs(activities);
var selection = d3.select(selector)
.selectAll("li")
.data(filterVerbs(activities), function(activity) { return activity.id });
var li = selection.enter().append("li");
li.html(function(activity) {
return activity.html.replace(/(<time.*>).*(<\/time>)/, function(_, head, tail) {
var date = Date.create(activity.published)
.format("{Weekday}, {Mon} {d} {h}:{mm} {TT}");
return head + date + tail;
})
});
li.selectAll("div")
.append("span").attr("class", "color");
if (highlight)
li.attr("class", "highlight").transition()
.delay(1).attr("class", "");
selection.exit().remove();
// Set the color of each activity based on its verb.
selection.select(".color")
.style("background-color", function(d) { return verbColor(verbs, d.verb); })
selection.order();
renderVerbs(verbs);
}
|
javascript
|
{
"resource": ""
}
|
q60498
|
topVerbs
|
validation
|
function topVerbs(activities, count) {
var counts = {},
list = [],
top;
for (var i in activities) {
var verb = activities[i].verb;
counts[verb] = (counts[verb] || 0) + 1;
}
for (key in counts)
list.push({ key: key, values: counts[key] });
top = list.sort(function(a, b) { return b.values - a.values })
.slice(0, count)
.map(function(verb) { return verb.key })
.concat("other");
// Make sure all verbs are showing by default.
verbsShowing = top.reduce(function(showing, verb) {
showing[verb.key] = verbsShowing[verb];
if (showing[verb] == undefined)
showing[verb] = true;
return showing;
}, {});
return top;
}
|
javascript
|
{
"resource": ""
}
|
q60499
|
filterVerbs
|
validation
|
function filterVerbs(activities) {
return activities.filter(function(activity) {
var showing = verbsShowing[activity.verb];
if (showing == undefined)
showing = verbsShowing["other"];
return showing;
})
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.