_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q12800
|
prefixLength
|
train
|
function prefixLength(text, prefix) {
const exp = new RegExp(`^${prefix.pattern}`);
return matchLength(text, exp);
}
|
javascript
|
{
"resource": ""
}
|
q12801
|
suffixLength
|
train
|
function suffixLength(text, suffix) {
let exp = new RegExp(`${suffix.pattern}$`);
return matchLength(text, exp);
}
|
javascript
|
{
"resource": ""
}
|
q12802
|
normalizeFormat
|
train
|
function normalizeFormat(format) {
const clone = Object.assign({}, format);
clone.prefix = normalizePrefixSuffix(format.prefix);
clone.suffix = normalizePrefixSuffix(format.suffix);
return clone;
}
|
javascript
|
{
"resource": ""
}
|
q12803
|
scaleImage
|
train
|
function scaleImage(img,prop,obj) {
var scale = Math.min(sw/img.w,sh/img.h);
obj.sx(scale).sy(scale);
}
|
javascript
|
{
"resource": ""
}
|
q12804
|
swap
|
train
|
function swap() {
iv1.x.anim().delay(1000).from(0).to(-sw).dur(3000).start();
iv2.x.anim().delay(1000).from(sw).to(0).dur(3000)
.then(afterAnim).start();
}
|
javascript
|
{
"resource": ""
}
|
q12805
|
updatePolys
|
train
|
function updatePolys() {
border.geometry([0,200,
adsr.a(),50,
adsr.d(),adsr.s(),
adsr.r(),adsr.s(),
300,200]);
aPoly.geometry([
0,200,
adsr.a(),50,
adsr.a(),200
]);
dPoly.geometry([
adsr.a(),200,
adsr.a(),50,
adsr.d(),adsr.s(),
adsr.d(),200,
]);
sPoly.geometry([
adsr.d(),200,
adsr.d(),adsr.s(),
adsr.r(),adsr.s(),
adsr.r(),200,
])
rPoly.geometry([
adsr.r(),200,
adsr.r(),adsr.s(),
300,200
]);
}
|
javascript
|
{
"resource": ""
}
|
q12806
|
extend
|
train
|
function extend(dst) {
Array.prototype.forEach.call(arguments, function(obj) {
if (obj && obj !== dst) {
Object.keys(obj).forEach(function(key) {
dst[key] = obj[key]
})
}
})
return dst
}
|
javascript
|
{
"resource": ""
}
|
q12807
|
hasIn
|
train
|
function hasIn(obj, keys) {
var k = keys[0],
ks = keys.slice(1);
if (ks.length) return !(k in obj) ? false : hasIn(obj[k], ks);
return (k in obj);
}
|
javascript
|
{
"resource": ""
}
|
q12808
|
getIn
|
train
|
function getIn(obj, keys, orValue) {
var k = keys[0],
ks = keys.slice(1);
return get(obj, k) && ks.length ? getIn(obj[k], ks, orValue) : get(obj, k, orValue);
}
|
javascript
|
{
"resource": ""
}
|
q12809
|
pluck
|
train
|
function pluck (recordset, property) {
recordset = arrayify(recordset)
var properties = arrayify(property)
return recordset
.map(function (record) {
for (var i = 0; i < properties.length; i++) {
var propValue = objectGet(record, properties[i])
if (propValue) return propValue
}
})
.filter(function (record) {
return typeof record !== 'undefined'
})
}
|
javascript
|
{
"resource": ""
}
|
q12810
|
spliceWhile
|
train
|
function spliceWhile (array, index, test) {
for (var i = 0; i < array.length; i++) {
if (!testValue(array[i], test)) break
}
var spliceArgs = [ index, i ]
spliceArgs = spliceArgs.concat(arrayify(arguments).slice(3))
return array.splice.apply(array, spliceArgs)
}
|
javascript
|
{
"resource": ""
}
|
q12811
|
forkTimeoutHandler
|
train
|
function forkTimeoutHandler(worker, cluster) {
verbose('worker %d is stuck in fork', worker.process.pid);
if (!cluster.workers[worker.id]) {
return;
}
// something is wrong with this worker. Kill it!
master.suicideOverrides[worker.id] = worker.id;
master.isRunning(worker, function(running) {
if (!running) {
return;
}
try {
debug('sending SIGKILL to worker %d', worker.process.pid);
process.kill(worker.process.pid, 'SIGKILL');
} catch (e) {
// this can happen. don't crash!!
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12812
|
disconnectTimeoutHandler
|
train
|
function disconnectTimeoutHandler(worker, cluster) {
verbose('worker %d is stuck in disconnect', worker.process.pid);
// if this is not a suicide we need to preserve that as worker.kill() will make this a suicide
if (!worker.suicide) {
master.suicideOverrides[worker.id] = worker.id;
}
master.isRunning(worker, function(running) {
if (!running) {
return;
}
try {
debug('sending SIGKILL to worker %d', worker.process.pid);
process.kill(worker.process.pid, 'SIGKILL');
} catch (e) {
// this can happen. don't crash!!
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12813
|
makeThrottle
|
train
|
function makeThrottle(fps){
var delay = 1000/fps;
var lastTime = Date.now();
if( fps<=0 || fps === Infinity ){
return returnTrue;
}
//if an fps throttle has been set then we'll assume
//it natively runs at 60fps,
var half = Math.ceil(1000 / 60) / 2;
return function(){
//if a custom fps is requested
var now = Date.now();
//is this frame within 8.5ms of the target?
//if so then next frame is gonna be too late
if(now - lastTime < delay - half){
return false;
}
lastTime = now;
return true;
};
}
|
javascript
|
{
"resource": ""
}
|
q12814
|
Animitter
|
train
|
function Animitter( opts ){
opts = opts || {};
this.__delay = opts.delay || 0;
/** @expose */
this.fixedDelta = !!opts.fixedDelta;
/** @expose */
this.frameCount = 0;
/** @expose */
this.deltaTime = 0;
/** @expose */
this.elapsedTime = 0;
/** @private */
this.__running = false;
/** @private */
this.__completed = false;
this.setFPS(opts.fps || Infinity);
this.setRequestAnimationFrameObject(opts.requestAnimationFrameObject || defaultRAFObject);
}
|
javascript
|
{
"resource": ""
}
|
q12815
|
train
|
function(){
this.frameCount++;
/** @private */
var now = Date.now();
this.__lastTime = this.__lastTime || now;
this.deltaTime = (this.fixedDelta || exports.globalFixedDelta) ? 1000/Math.min(60, this.__fps) : now - this.__lastTime;
this.elapsedTime += this.deltaTime;
this.__lastTime = now;
this.emit('update', this.deltaTime, this.elapsedTime, this.frameCount);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q12816
|
createAnimitter
|
train
|
function createAnimitter(options, fn){
if( arguments.length === 1 && typeof options === 'function'){
fn = options;
options = {};
}
var _instance = new Animitter( options );
if( fn ){
_instance.on('update', fn);
}
return _instance;
}
|
javascript
|
{
"resource": ""
}
|
q12817
|
fork
|
train
|
function fork(number) {
var numProc = number || require('os').cpus().length;
config.n = numProc;
debug('forking %d workers', numProc);
forkLoopProtect();
for (var i = 0; i < numProc; i++) {
cluster.fork({PWD: config.CWD});
}
}
|
javascript
|
{
"resource": ""
}
|
q12818
|
lifecycleTimeoutHandler
|
train
|
function lifecycleTimeoutHandler() {
if (shutdownCalled) {
return;
}
verbose('workers have reached the end of their life');
master.restart(function () {
if (!shutdownCalled) {
lifecycleTimer = setTimeout(lifecycleTimeoutHandler.bind(master), config.timeouts.maxAge);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12819
|
subscribe
|
train
|
function subscribe(observable, observer, options) {
if (typeof observable !== 'object' || !observable)
throw new TypeError('observable argument must be an Object');
if (typeof observable.on !== 'function')
throw new TypeError('observable.on must be a Function');
if (typeof observer !== 'object' || !observer)
throw new TypeError('observer argument must be an Object');
const { masterHandler, messageTypes, queueName } = options;
if (masterHandler && typeof masterHandler !== 'function')
throw new TypeError('masterHandler parameter, when provided, must be a Function');
if (queueName && typeof observable.queue !== 'function')
throw new TypeError('observable.queue, when queueName is specified, must be a Function');
const subscribeTo = messageTypes
|| observer.handles
|| Object.getPrototypeOf(observer).constructor.handles;
if (!Array.isArray(subscribeTo))
throw new TypeError('either options.messageTypes, observer.handles or ObserverType.handles is required');
unique(subscribeTo).forEach(messageType => {
const handler = masterHandler || getHandler(observer, messageType);
if (!handler)
throw new Error(`'${messageType}' handler is not defined or not a function`);
if (queueName)
observable.queue(queueName).on(messageType, handler.bind(observer));
else
observable.on(messageType, handler.bind(observer));
});
}
|
javascript
|
{
"resource": ""
}
|
q12820
|
recursiveReaddirSync
|
train
|
function recursiveReaddirSync(path) {
var list = []
, files = fs.readdirSync(path)
, stats
;
files.forEach(function (file) {
stats = fs.lstatSync(p.join(path, file));
if(stats.isDirectory()) {
list = list.concat(recursiveReaddirSync(p.join(path, file)));
} else {
list.push(p.join(path, file));
}
});
return list;
}
|
javascript
|
{
"resource": ""
}
|
q12821
|
validateEvent
|
train
|
function validateEvent(event) {
if (typeof event !== 'object' || !event) throw new TypeError('event must be an Object');
if (typeof event.type !== 'string' || !event.type.length) throw new TypeError('event.type must be a non-empty String');
if (!event.aggregateId && !event.sagaId) throw new TypeError('either event.aggregateId or event.sagaId is required');
if (event.sagaId && typeof event.sagaVersion === 'undefined') throw new TypeError('event.sagaVersion is required, when event.sagaId is defined');
}
|
javascript
|
{
"resource": ""
}
|
q12822
|
validateEventStorage
|
train
|
function validateEventStorage(storage) {
if (!storage) throw new TypeError('storage argument required');
if (typeof storage !== 'object') throw new TypeError('storage argument must be an Object');
if (typeof storage.commitEvents !== 'function') throw new TypeError('storage.commitEvents must be a Function');
if (typeof storage.getEvents !== 'function') throw new TypeError('storage.getEvents must be a Function');
if (typeof storage.getAggregateEvents !== 'function') throw new TypeError('storage.getAggregateEvents must be a Function');
if (typeof storage.getSagaEvents !== 'function') throw new TypeError('storage.getSagaEvents must be a Function');
if (typeof storage.getNewId !== 'function') throw new TypeError('storage.getNewId must be a Function');
}
|
javascript
|
{
"resource": ""
}
|
q12823
|
validateSnapshotStorage
|
train
|
function validateSnapshotStorage(snapshotStorage) {
if (typeof snapshotStorage !== 'object' || !snapshotStorage)
throw new TypeError('snapshotStorage argument must be an Object');
if (typeof snapshotStorage.getAggregateSnapshot !== 'function')
throw new TypeError('snapshotStorage.getAggregateSnapshot argument must be a Function');
if (typeof snapshotStorage.saveAggregateSnapshot !== 'function')
throw new TypeError('snapshotStorage.saveAggregateSnapshot argument must be a Function');
}
|
javascript
|
{
"resource": ""
}
|
q12824
|
validateMessageBus
|
train
|
function validateMessageBus(messageBus) {
if (typeof messageBus !== 'object' || !messageBus)
throw new TypeError('messageBus argument must be an Object');
if (typeof messageBus.on !== 'function')
throw new TypeError('messageBus.on argument must be a Function');
if (typeof messageBus.publish !== 'function')
throw new TypeError('messageBus.publish argument must be a Function');
}
|
javascript
|
{
"resource": ""
}
|
q12825
|
setupOneTimeEmitterSubscription
|
train
|
function setupOneTimeEmitterSubscription(emitter, messageTypes, filter, handler) {
if (typeof emitter !== 'object' || !emitter)
throw new TypeError('emitter argument must be an Object');
if (!Array.isArray(messageTypes) || messageTypes.some(m => !m || typeof m !== 'string'))
throw new TypeError('messageTypes argument must be an Array of non-empty Strings');
if (handler && typeof handler !== 'function')
throw new TypeError('handler argument, when specified, must be a Function');
if (filter && typeof filter !== 'function')
throw new TypeError('filter argument, when specified, must be a Function');
return new Promise(resolve => {
// handler will be invoked only once,
// even if multiple events have been emitted before subscription was destroyed
// https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener
let handled = false;
function filteredHandler(event) {
if (filter && !filter(event)) return;
if (handled) return;
handled = true;
for (const messageType of messageTypes)
emitter.off(messageType, filteredHandler);
debug('\'%s\' received, one-time subscription to \'%s\' removed', event.type, messageTypes.join(','));
if (handler)
handler(event);
resolve(event);
}
for (const messageType of messageTypes)
emitter.on(messageType, filteredHandler);
debug('set up one-time %s to \'%s\'', filter ? 'filtered subscription' : 'subscription', messageTypes.join(','));
});
}
|
javascript
|
{
"resource": ""
}
|
q12826
|
train
|
function(settings, callback) {
"use strict";
if (typeof settings === 'function') {
callback = settings;
settings = {};
}
if (typeof settings === 'undefined') {
settings = {};
}
if (typeof callback !== 'function') {
callback = function () {};
}
getLogFiles(function () {
parseOptions(settings, function () {
setupLogger();
require('./Logger').verbose('Starting worker manager');
// Start the Master
master = require('./master');
registerListeners(master);
master.start();
callback();
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12827
|
log
|
train
|
function log(logLevel, prefix, args) {
"use strict";
if (logLevel > level) {
return;
}
args = Array.prototype.slice.call(args);
if (typeof args[0] === 'undefined') {
return;
}
var message = args[0];
args.splice(0, 1, prefix + message);
console.log.apply(this, args);
}
|
javascript
|
{
"resource": ""
}
|
q12828
|
append
|
train
|
function append(arrlike /* , items... */) {
return Array.prototype.slice.call(arrlike, 0).concat(Array.prototype.slice.call(arguments, 1));
}
|
javascript
|
{
"resource": ""
}
|
q12829
|
promisify_value
|
train
|
function promisify_value(result_transformer) {
result_transformer = result_transformer || identity;
var transformer = function (promise) {
result_transformer(promise);
};
transformer.for_property = function (obj_promise, prop) {
return when(obj_promise, function (obj) {
result_transformer(obj[prop]);
});
};
return transformer;
}
|
javascript
|
{
"resource": ""
}
|
q12830
|
promisify_func
|
train
|
function promisify_func(result_transformer) {
result_transformer = result_transformer || identity;
var transformer = function (func_promise) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(func_promise, function (func) {
return func.apply(null, args);
}));
};
};
transformer.for_property = function (obj_promise, prop) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(obj_promise, function (obj) {
return obj[prop].apply(obj, args);
}));
};
};
return transformer;
}
|
javascript
|
{
"resource": ""
}
|
q12831
|
promisify_cb_func_generic
|
train
|
function promisify_cb_func_generic(result_transformer, cb_generator) {
result_transformer = result_transformer || identity;
var transformer = function (func_promise) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(func_promise, function (func) {
var d = when.defer();
func.apply(null, append(args, cb_generator(d)));
return d.promise;
}));
};
};
transformer.for_property = function (obj_promise, prop) {
return function(/* ... */) {
var args = arguments;
return result_transformer(when(obj_promise, function (obj) {
var d = when.defer();
obj[prop].apply(obj, append(args, cb_generator(d)));
return d.promise;
}));
};
};
return transformer;
}
|
javascript
|
{
"resource": ""
}
|
q12832
|
promisify_object
|
train
|
function promisify_object(template, object_creator) {
object_creator = object_creator || new_object;
var transformer = function (obj_promise) {
var res = object_creator(obj_promise);
for (var prop in template) {
res[prop] = template[prop].for_property(obj_promise, prop);
}
return res;
};
transformer.for_property = function (parent_promise, prop) {
return transformer(when(parent_promise, function (obj) {
return obj[prop];
}));
};
return transformer;
}
|
javascript
|
{
"resource": ""
}
|
q12833
|
promisify_read_stream
|
train
|
function promisify_read_stream() {
var transformer = function (stream_promise) {
var res = new PStream();
res.to = function (dest) {
when(stream_promise, function (stream) {
PStream.wrap_read_stream(stream).to(dest);
}, function (err) {
dest.error(err);
});
};
return res.sanitize();
};
transformer.for_property = function (obj_promise, prop) {
return transformer(when(obj_promise, function (obj) {
return obj[prop];
}));
};
return transformer;
}
|
javascript
|
{
"resource": ""
}
|
q12834
|
train
|
function() {
let xcConfigBuildFilePath = path.join(cwd, 'platforms', 'ios', 'cordova', 'build.xcconfig');
try {
let xcConfigBuildFileExists = fs.accessSync(xcConfigBuildFilePath);
}
catch(e) {
console.log('Could not locate build.xcconfig, you will need to set HEADER_SEARCH_PATHS manually');
return;
}
console.log(`xcConfigBuildFilePath: ${xcConfigBuildFilePath}`);
addHeaderSearchPaths(xcConfigBuildFilePath);
}
|
javascript
|
{
"resource": ""
}
|
|
q12835
|
train
|
function(xcConfigBuildFilePath) {
let lines = fs.readFileSync(xcConfigBuildFilePath, 'utf8').split('\n');
let paths = hookData.headerPaths;
let headerSearchPathLineNumber;
lines.forEach((l, i) => {
if (l.indexOf('HEADER_SEARCH_PATHS') > -1) {
headerSearchPathLineNumber = i;
}
});
if (headerSearchPathLineNumber) {
for(let actualPath of paths) {
if (lines[headerSearchPathLineNumber].indexOf(actualPath) == -1) {
lines[headerSearchPathLineNumber] += ` ${actualPath}`;
console.log(`${actualPath} was added to the search paths`);
}
else {
console.log(`${actualPath} was already setup in build.xcconfig`);
}
}
}
else {
lines[lines.length - 1] = 'HEADER_SEARCH_PATHS = ';
for(let actualPath of paths) {
lines[lines.length - 1] += actualPath;
}
}
let newConfig = lines.join('\n');
fs.writeFile(xcConfigBuildFilePath, newConfig, function (err) {
if (err) {
console.log(`Error updating build.xcconfig: ${err}`);
return;
}
console.log('Successfully updated HEADER_SEARCH_PATHS in build.xcconfig');
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12836
|
getImpliedVolatility
|
train
|
function getImpliedVolatility(expectedCost, s, k, t, r, callPut, estimate)
{
estimate = estimate || .1;
var low = 0;
var high = Infinity;
// perform 100 iterations max
for(var i = 0; i < 100; i++)
{
var actualCost = bs.blackScholes(s, k, t, estimate, r, callPut);
// compare the price down to the cent
if(expectedCost * 100 == Math.floor(actualCost * 100))
{
break;
}
else if(actualCost > expectedCost)
{
high = estimate;
estimate = (estimate - low) / 2 + low
}
else
{
low = estimate;
estimate = (high - estimate) / 2 + estimate;
if(!isFinite(estimate)) estimate = low * 2;
}
}
return estimate;
}
|
javascript
|
{
"resource": ""
}
|
q12837
|
getPointedValue
|
train
|
function getPointedValue(target, opt_pointer) {
// .get() method implementation.
// First argument must be either string or object.
if (isString(target)) {
// If string it must be valid JSON document.
try {
// Let's try to parse it as JSON.
target = JSON.parse(target);
}
catch (e) {
// If parsing failed, an exception will be thrown.
throw getError(ErrorMessage.INVALID_DOCUMENT);
}
}
else if (!isObject(target)) {
// If not object or string, an exception will be thrown.
throw getError(ErrorMessage.INVALID_DOCUMENT_TYPE);
}
// |target| is already parsed, let's create evaluator function for it.
var evaluator = createPointerEvaluator(target);
if (isUndefined(opt_pointer)) {
// If pointer was not provided, return evaluator function.
return evaluator;
}
else {
// If pointer is provided, return evaluation result.
return evaluator(opt_pointer);
}
}
|
javascript
|
{
"resource": ""
}
|
q12838
|
isValidJSONPointer
|
train
|
function isValidJSONPointer(pointer) {
// Validates JSON pointer string.
if (!isString(pointer)) {
// If it's not a string, it obviously is not valid.
return false;
}
if ('' === pointer) {
// If it is string and is an empty string, it's valid.
return true;
}
// If it is non-empty string, it must match spec defined format.
// Check Section 3 of specification for concrete syntax.
return NON_EMPTY_POINTER_REGEXP.test(pointer);
}
|
javascript
|
{
"resource": ""
}
|
q12839
|
getDrives
|
train
|
function getDrives(command, callback) {
var child = exec(
command,
function (err, stdout, stderr) {
if (err) return callback(err);
var drives = stdout.split('\n');
drives.splice(0, 1);
drives.splice(-1, 1);
// Removes ram drives
drives = drives.filter(function(item){ return item != "none"});
callback(null, drives);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q12840
|
detail
|
train
|
function detail(drive, callback) {
async.series(
{
used: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetail('df -kl | grep ' + drive + ' | awk \'{print $3}\'', callback);
break;
case'linux':
default:
getDetail('df -P | grep ' + drive + ' | awk \'{print $3}\'', callback);
}
},
available: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetail('df -kl | grep ' + drive + ' | awk \'{print $4}\'', callback);
break;
case'linux':
default:
getDetail('df -P | grep ' + drive + ' | awk \'{print $4}\'', callback);
}
},
mountpoint: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetailNaN('df -kl | grep ' + drive + ' | awk \'{print $9}\'', function(e, d){
if (d) d = d.trim();
callback(e, d);
});
break;
case'linux':
default:
getDetailNaN('df -P | grep ' + drive + ' | awk \'{print $6}\'', function(e, d){
if (d) d = d.trim();
callback(e, d);
});
}
}
},
function (err, results) {
if (err) return callback(err);
results.freePer = Number(results.available / (results.used + results.available) * 100);
results.usedPer = Number(results.used / (results.used + results.available) * 100);
results.total = numeral(results.used + results.available).format('0.00 b');
results.used = numeral(results.used).format('0.00 b');
results.available = numeral(results.available).format('0.00 b');
results.drive = drive;
callback(null, results);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q12841
|
writeLock
|
train
|
function writeLock(key, callback, options) {
var lock;
if (typeof key !== 'function') {
if (!table.hasOwnProperty(key)) {
table[key] = new Lock();
}
lock = table[key];
} else {
options = callback;
callback = key;
lock = defaultLock;
}
if (!options) {
options = {};
}
var scope = null;
if (options.hasOwnProperty('scope')) {
scope = options.scope;
}
var release = (function () {
var released = false;
return function () {
if (!released) {
released = true;
lock.readers = 0;
if (lock.queue.length) {
lock.queue[0]();
}
}
};
}());
if (lock.readers || lock.queue.length) {
var terminated = false;
lock.queue.push(function () {
if (!terminated && !lock.readers) {
terminated = true;
lock.queue.shift();
lock.readers = -1;
callback.call(options.scope, release);
}
});
if (options.hasOwnProperty('timeout')) {
var timeoutCallback = null;
if (options.hasOwnProperty('timeoutCallback')) {
timeoutCallback = options.timeoutCallback;
}
setTimeout(function () {
if (!terminated) {
terminated = true;
lock.queue.shift();
if (timeoutCallback) {
timeoutCallback.call(scope);
}
}
}, options.timeout);
}
} else {
lock.readers = -1;
callback.call(options.scope, release);
}
}
|
javascript
|
{
"resource": ""
}
|
q12842
|
readPassword
|
train
|
function readPassword(program) {
prompt.message = "";
prompt.delimiter = "";
const passportOption = [{name: 'password', description: 'New password:', hidden: true}];
const rePassportOption = [{name: 'rePassword', description: 'Re-type new password:', hidden: true}];
// Try to read password.
prompt.get(passportOption, (err, result) => {
if (!err) {
const password = result.password;
setTimeout(function () {
prompt.get(rePassportOption, (err, result) => {
if (!err && password == result.rePassword) {
program.args.push(password);
try {
processor.syncFile(program);
} catch (err) {
console.error(err.message);
}
} else {
console.error("\nPassword verification error.");
}
});
}, 50);
} else {
console.error("\nPassword verification error.");
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12843
|
observableChanged
|
train
|
function observableChanged(change) {
const store = this;
action(() => {
store.dataChanges.set(change.name, change.newValue);
if (store.isSame(store.dataChanges.get(change.name), store.dataServer[change.name])) {
store.dataChanges.delete(change.name);
}
})();
}
|
javascript
|
{
"resource": ""
}
|
q12844
|
processSaveResponse
|
train
|
async function processSaveResponse(store, updates, response) {
store.options.log(`[${store.options.name}] Response received from server.`);
if (response.status === 'error') {
action(() => {
let errorFields = [];
if (response.error) {
if (typeof response.error === 'string') {
store.serverError = response.error;
} else {
Object.assign(store.dataErrors, response.error);
errorFields = Object.keys(response.error);
}
}
// Supports an array of field names in error_field or a string
errorFields = errorFields.concat(response.error_field);
errorFields.forEach((field) => {
if (store.options.autoSaveInterval && !store.dataErrors[field] && store.isSame(updates[field], store.data[field])) {
store.data[field] = store.dataServer[field]; // revert or it'll keep trying to autosave it
}
delete updates[field]; // don't save it as the new dataServer value
});
})();
} else {
store.serverError = null;
}
Object.assign(store.dataServer, updates);
action(() => {
if (response.data) {
Object.assign(store.dataServer, response.data);
Object.assign(store.data, response.data);
}
store.dataChanges.forEach((value, key) => {
if (store.isSame(value, store.dataServer[key])) {
store.dataChanges.delete(key);
}
});
})();
if (typeof store.options.afterSave === 'function') {
await store.options.afterSave(store, updates, response);
}
return response.status;
}
|
javascript
|
{
"resource": ""
}
|
q12845
|
buildRouter
|
train
|
function buildRouter () {
var args = g.argsToArray( arguments )
, simpleConf = {}
, regexpConf = []
, reLength
, i, len, route, handlers;
if ( (args.length === 0) || (args.length % 2 !== 0) )
throw new Error( 'Wrong number of arguments!' );
for ( i = 0, len = args.length; i < len; i+=2 ) {
route = args[ i ];
handlers = args[ i + 1 ];
if ( route instanceof RegExp )
regexpConf.push([ route, handlers ]);
else
simpleConf[ route ] = handlers;
}
reLength = regexpConf.length;
/**
* Search path in `simpleConf` and `regexpConf`
* and runs all handlers of mathed path.
* @param {String} path - path to route.
*/
return function route ( path ) {
var values = g.argsToArray( arguments ).slice( 1 )
, checkedPath, handlers
, i, len;
/** Checks simple routes first. */
handlers = simpleConf[ path ];
/** Checks regexp routes last. */
if ( !g.getOrNull( handlers, 'length' ) )
for ( i = 0; i < reLength; i++ ) {
checkedPath = regexpConf[ i ][ 0 ];
if ( checkedPath.test(path) ) {
handlers = regexpConf[ i ][ 1 ];
break;
}
}
/** Run each handler of matched route. */
if ( handlers && handlers.length )
for ( i = 0, len = handlers.length; i < len; i++ ) {
handlers[ i ].apply( this, values );
}
};
}
|
javascript
|
{
"resource": ""
}
|
q12846
|
composite
|
train
|
function composite ( comb, zero ) {
return function ( conf, value, fieldMeta ) {
var validators = conf.value;
return reduce(function ( acc, v ) {
var f = VALIDATORS[ v.rule ];
checkRuleExistence( f, v.rule );
return comb( acc, f( v, value, fieldMeta ) );
}, zero, validators );
};
}
|
javascript
|
{
"resource": ""
}
|
q12847
|
checkByRule
|
train
|
function checkByRule ( ruleInfo, value, fieldMeta ) {
var rule = ruleInfo.rule
, isValid = VALIDATORS[ rule ];
checkRuleExistence( isValid, rule );
return isValid( ruleInfo, value, fieldMeta ) ? null : ruleInfo;
}
|
javascript
|
{
"resource": ""
}
|
q12848
|
checkByAll
|
train
|
function checkByAll ( rules, value, fieldMeta ) {
return (rules || [])
.map(function ( rule ) {
return checkByRule( rule, value, fieldMeta );
})
.filter(function ( el ) { return null !== el; });
}
|
javascript
|
{
"resource": ""
}
|
q12849
|
validateField
|
train
|
function validateField ( fldID, fieldMeta, value ) {
var res = {}
, errs = checkByAll( fieldMeta.validators, value, fieldMeta );
res[ fldID ] = errs.length ? errs : null;
return res;
}
|
javascript
|
{
"resource": ""
}
|
q12850
|
validateFields
|
train
|
function validateFields ( fldsMeta, fldsValue ) {
return reduce(function ( acc, fldMeta, fldID ) {
var value = getOrNull( fldsValue, fldID )
, errors = validateField( fldID, fldMeta, value );
return t.merge( acc, errors );
}, {}, fldsMeta );
}
|
javascript
|
{
"resource": ""
}
|
q12851
|
validateForm
|
train
|
function validateForm ( formMeta, formValue ) {
var fields = getOrNull( formMeta, 'fields' )
, validable = reduce(function ( acc, fld, fldID ) {
var noValidate = !t.isDefined( fld.validators )
|| fld.isHidden
|| fld.isReadOnly
, fldMeta = {};
if ( noValidate ) return acc;
else {
fldMeta[ fldID ] = fld;
return t.merge( acc, fldMeta );
}
}, {}, fields );
return validateFields( validable, formValue );
}
|
javascript
|
{
"resource": ""
}
|
q12852
|
isFormValid
|
train
|
function isFormValid ( formErrors ) {
return t.reduce(function ( acc, v, k ) {
return acc && !(v && v.length);
}, true, formErrors );
}
|
javascript
|
{
"resource": ""
}
|
q12853
|
setTimeoutWithTimestamp
|
train
|
function setTimeoutWithTimestamp(callback) {
const immediateTime = Date.now();
let lapsedTime = Math.max(previousTime + 16, immediateTime);
return setTimeout(function () {
callback(previousTime = lapsedTime);
}, lapsedTime - immediateTime);
}
|
javascript
|
{
"resource": ""
}
|
q12854
|
debounce
|
train
|
function debounce(callback, delay, lead) {
var debounceRange = 0;
var currentTime;
var lastCall;
var setDelay;
var timeoutId;
const call = parameters => {
callback(parameters);
};
return parameters => {
if (lead) {
currentTime = Date.now();
if (currentTime > debounceRange) {
callback(parameters);
}
debounceRange = currentTime + delay;
} else {
/**
* setTimeout is only used with the trail option.
*/
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
call(parameters);
}, delay);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q12855
|
uriEncodeParams
|
train
|
function uriEncodeParams( obj ){
var pairs = [], key;
for( key in obj ){
pairs.push( uriEncodeString(key) +'='+ uriEncodeString(obj[key]) );
}
return pairs.join('&');
}
|
javascript
|
{
"resource": ""
}
|
q12856
|
OAuthToken
|
train
|
function OAuthToken( key, secret ){
if( ! key || ! secret ){
throw new Error('OAuthToken params must not be empty');
}
this.key = key;
this.secret = secret;
}
|
javascript
|
{
"resource": ""
}
|
q12857
|
train
|
function (cb) {
async.map(self._repos, function (repo, repoCb) {
self._client.gitdata.getReference({
user: self._repoParts[repo].org,
repo: self._repoParts[repo].repo,
ref: branchSrcFull
}, function (err, res) {
if (self._checkAndHandleError(err, repo, repoCb)) { return; }
repoCb(null, {
repo: repo,
sha: res.object.sha
});
});
}, cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q12858
|
train
|
function (cb) {
async.map(self._repos, function (repo, repoCb) {
self._client.gitdata.getReference({
user: self._repoParts[repo].org,
repo: self._repoParts[repo].repo,
ref: branchDestFull
}, function (err, res) {
// Allow not found.
if (err && err.code === NOT_FOUND) {
repoCb(null, {
repo: repo,
exists: false,
sha: null
});
return;
}
// Real error.
if (self._checkAndHandleError(err, "branch.getDestRefs - " + repo, repoCb)) {
return;
}
// Error if existing branches are not allowed.
var sha = res.object.sha;
if (!self._allowExisting) {
self._checkAndHandleError(
new Error("Found existing dest branch in repo: " + repo + " with sha: " + sha),
null,
repoCb);
return;
}
// Have an allowed, existing branch.
repoCb(null, {
repo: repo,
exists: true,
sha: sha
});
});
}, cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q12859
|
ajax
|
train
|
function ajax(opts, cb) {
opts = opts || {};
var xmlhttp;
if (typeof window === 'undefined') {
// TODO: refactor node usage to live in here
return cb();
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);
}
};
xmlhttp.open(opts.method, opts.url, true);
xmlhttp.send();
return xmlhttp;
}
|
javascript
|
{
"resource": ""
}
|
q12860
|
getOrDefault
|
train
|
function getOrDefault ( source, path, defaultVal ) {
var isAlreadySplitted = isArray( path );
if ( !isDefined(source) ) return defaultVal;
if ( !isString(path) && !isAlreadySplitted ) return defaultVal;
var tokens = isAlreadySplitted ? path : path.split( '.' )
, idx, key;
for ( idx in tokens ) {
key = tokens[ idx ];
if ( isDefined( source[key] ) )
source = source[ key ];
else
return defaultVal;
}
return source;
}
|
javascript
|
{
"resource": ""
}
|
q12861
|
arrayToObject
|
train
|
function arrayToObject ( keyPath, arr ) {
var res = {}, key, element;
for ( var i = 0, len = arr.length; i < len; i++ ) {
element = arr[ i ];
key = getOrNull( element, keyPath );
if ( key ) res[ key ] = element;
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q12862
|
createPropertyProvider
|
train
|
function createPropertyProvider(getValue, onchange) {
var ret = new Object();
ret.getValue = getValue;
ret.onchange = onchange;
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q12863
|
train
|
function (fn) {
return function () {
var tokens = arguments;
var i;
for (i = 0; i < tokens.length; i += 1) {
fn.call(this, tokens[i]);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q12864
|
train
|
function (methods) {
methods = [].concat(methods);
var i = methods.length - 1;
for (i; i >= 0; i -= 1) {
this[methods[i]] = proxy(this[methods[i]], this);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q12865
|
createVoxelMesh
|
train
|
function createVoxelMesh(gl, voxels, voxelSideTextureIDs, voxelSideTextureSizes, position, pad, that) {
//Create mesh
var vert_data = createAOMesh(voxels, voxelSideTextureIDs, voxelSideTextureSizes)
var vertexArrayObjects = {}
if (vert_data === null) {
// no vertices allocated
} else {
//Upload triangle mesh to WebGL
var vert_buf = createBuffer(gl, vert_data)
var triangleVAO = createVAO(gl, [
{ "buffer": vert_buf,
"type": gl.UNSIGNED_BYTE,
"size": 4,
"offset": 0,
"stride": 8,
"normalized": false
},
{ "buffer": vert_buf,
"type": gl.UNSIGNED_BYTE,
"size": 4,
"offset": 4,
"stride": 8,
"normalized": false
}
])
triangleVAO.length = Math.floor(vert_data.length/8)
vertexArrayObjects.surface = triangleVAO
}
// move the chunk into place
var modelMatrix = mat4.create()
var w = voxels.shape[2] - pad // =[1]=[0]=game.chunkSize
var translateVector = [
position[0] * w,
position[1] * w,
position[2] * w]
mat4.translate(modelMatrix, modelMatrix, translateVector)
//Bundle result and return
var result = {
vertexArrayObjects: vertexArrayObjects, // other plugins can add their own VAOs
center: [w>>1, w>>1, w>>1],
radius: w,
modelMatrix: modelMatrix
}
if (that) that.emit('meshed', result, gl, vert_data, voxels)
return result
}
|
javascript
|
{
"resource": ""
}
|
q12866
|
train
|
function(req, res, next){
// Search for ID if requested
var id = req.param('id');
findAssociated(id, finishRendering);
// Render JSON content
function finishRendering(data){
// If none object found with given id return error
if(id && !data[0])
return next();
// If querying for id, then returns only the object
if(id)
data = data[0];
// Render the json
res.send(data);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12867
|
finishRendering
|
train
|
function finishRendering(data){
// If none object found with given id return error
if(id && !data[0])
return next();
// If querying for id, then returns only the object
if(id)
data = data[0];
// Render the json
res.send(data);
}
|
javascript
|
{
"resource": ""
}
|
q12868
|
afterFindGroups
|
train
|
function afterFindGroups(models){
data = models;
completed = 0;
if(data.length <= 0)
return next([]);
// Load Matches for each Group and associates
data.forEach(function(group){
app.models.Match.find()
.where({'groupId': group.id})
.sort('state DESC')
.sort('day ASC')
.sort('hour ASC')
.sort('id')
.then(function(matches){
// Associate matches with groups
group.matches = matches;
// Compute scoring table for each group
// (must be computed AFTER associating matches with it)
group.table = group.table();
// Callback
loadedModel();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q12869
|
afterFindTeams
|
train
|
function afterFindTeams(err, teamData){
var teamList = {};
// Load teams and assing it's key as it's id
teamData.forEach(function(team){
teamList[team.id] = team;
});
// Includes team object in 'table' data
data.forEach(function(group){
// console.log(group);
// Go trough all the table adding key 'team' with team data
_.forEach(group.table, function(row){
row.team = teamList[row.teamId];
});
});
// Includes team object in 'match' data
data.forEach(function(group){
// console.log(group);
// Go trough all the table adding key 'team' with team data
_.forEach(group.matches, function(row){
row.teamA = teamList[row.teamAId];
row.teamB = teamList[row.teamBId];
});
});
next(data);
}
|
javascript
|
{
"resource": ""
}
|
q12870
|
RequestSSLError
|
train
|
function RequestSSLError(message, id) {
Error.call(this);
Error.captureStackTrace(this, RequestSSLError);
this.id = id;
this.name = 'RequestSSLError';
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
q12871
|
createErrorMessage
|
train
|
function createErrorMessage(errorcode) {
if (errorcode in ERRORS) {
var args = Array.prototype.slice.call(arguments,1);
var entry = ERRORS[errorcode];
if (entry.argcount && entry.argcount!==args.length) {
// this should only ever get called if we have a bug in this library
throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid args) to the developer with the following stack trace:"+new Error().stack);
}
return new RequestSSLError((args.length ? util.format.apply(util.format,[entry.message].concat(args)) : entry.message), errorcode);
}
else {
// this should only ever get called if we have a bug in this library
throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid error code) to the developer with the following stack trace:"+new Error().stack);
}
}
|
javascript
|
{
"resource": ""
}
|
q12872
|
getDomain
|
train
|
function getDomain(url) {
var domain = _.isObject(url) ? url.host : urlib.parse(url).host;
return domain || url;
}
|
javascript
|
{
"resource": ""
}
|
q12873
|
getFingerprintForURL
|
train
|
function getFingerprintForURL(url) {
var domain = getDomain(url);
var found = global.requestSSLFingerprints[domain];
debug('getFingerprintForURL %s -> %s=%s',url,domain,found);
if (!found) {
// try a wildcard search
var u = urlib.parse(domain),
tokens = (u && u.host || domain).split('.');
domain = '*.'+tokens.splice(tokens.length > 1 ? 0 : 1).join('.');
found = global.requestSSLFingerprints[domain];
debug('getFingerprintForURL (wildcard) %s -> %s=%s',url,domain,found);
}
return found;
}
|
javascript
|
{
"resource": ""
}
|
q12874
|
Connect
|
train
|
function Connect(username, password, options) {
// Default Options
this.options = {
baseURL : "https://itunesconnect.apple.com",
apiURL : "https://reportingitc2.apple.com/api/",
loginURL : "https://idmsa.apple.com/appleauth/auth/signin",
appleWidgetKey : "22d448248055bab0dc197c6271d738c3",
concurrentRequests : 2,
errorCallback : function(e) {},
loginCallback : function(c) {}
};
// Extend options
_.extend(this.options, options);
// Set cookies
this._cookies = [];
// Task Executor
this._queue = async.queue(
this.executeRequest.bind(this),
this.options.concurrentRequests
);
// Pasue queue and wait for login to complete
this._queue.pause();
// Login to iTunes Connect
if(typeof this.options["cookies"] !== 'undefined') {
this._cookies = this.options.cookies;
this._queue.resume();
}
else {
this.login(username, password);
}
}
|
javascript
|
{
"resource": ""
}
|
q12875
|
Report
|
train
|
function Report(type, config) {
var fn = Query.prototype[type];
if(typeof fn !== 'function') {
throw new Error('Unknown Report type: ' + type);
}
return new Query(config)[type]();
}
|
javascript
|
{
"resource": ""
}
|
q12876
|
Query
|
train
|
function Query(config) {
this.type = null;
this.endpoint = null;
this.config = {
start : moment(),
end : moment(),
filters : {},
measures : ['units'],
limit : 100
};
// Extend options with user stuff
_.extend(this.config, config);
// Private Options
this._time = null;
this._body = {};
}
|
javascript
|
{
"resource": ""
}
|
q12877
|
afterFindMatch
|
train
|
function afterFindMatch(models){
if(models.length != 1) return next(404);
model = models[0];
// Fetch Both Teams
app.models.Team.findById(model.teamAId).exec(function(err, models){
model.teamA = models.length ? models[0] : null;
checkFetch();
});
app.models.Team.findById(model.teamBId).exec(function(err, models){
model.teamB = models.length ? models[0] : null;
checkFetch();
});
// Fetch Group
app.models.Group.findById(model.groupId).exec(function(err, models){
model.group = models.length ? models[0] : null;
checkFetch();
});
}
|
javascript
|
{
"resource": ""
}
|
q12878
|
computeMesh
|
train
|
function computeMesh(array, voxelSideTextureIDs, voxelSideTextureSizes) {
var shp = array.shape.slice(0)
var nx = (shp[0]-2)|0
var ny = (shp[1]-2)|0
var nz = (shp[2]-2)|0
var sz = nx * ny * nz
var scratch0 = pool.mallocInt32(sz)
var scratch1 = pool.mallocInt32(sz)
var scratch2 = pool.mallocInt32(sz)
var rshp = [nx, ny, nz]
var ao0 = ndarray(scratch0, rshp)
var ao1 = ndarray(scratch1, rshp)
var ao2 = ndarray(scratch2, rshp)
//Calculate ao fields
surfaceStencil(ao0, ao1, ao2, array)
//Build mesh slices
meshBuilder.ptr = 0
meshBuilder.voxelSideTextureIDs = voxelSideTextureIDs
meshBuilder.voxelSideTextureSizes = voxelSideTextureSizes
var buffers = [ao0, ao1, ao2]
for(var d=0; d<3; ++d) {
var u = (d+1)%3
var v = (d+2)%3
//Create slice
var st = buffers[d].transpose(d, u, v)
var slice = st.pick(0)
var n = rshp[d]|0
meshBuilder.d = d
meshBuilder.u = v
meshBuilder.v = u
//Generate slices
for(var i=0; i<n; ++i) {
meshBuilder.z = i
meshSlice(slice)
slice.offset += st.stride[0]
}
}
//Release buffers
pool.freeInt32(scratch0)
pool.freeInt32(scratch1)
pool.freeInt32(scratch2)
//Release uint8 array if no vertices were allocated
if(meshBuilder.ptr === 0) {
return null
}
//Slice out buffer
var rbuffer = meshBuilder.buffer
var rptr = meshBuilder.ptr
meshBuilder.buffer = pool.mallocUint8(1024)
meshBuilder.ptr = 0
return rbuffer.subarray(0, rptr)
}
|
javascript
|
{
"resource": ""
}
|
q12879
|
train
|
function () {
var self = this
pb.toJSON().enums.forEach(function (e) {
self[e.name] = e.values
})
pb.toJSON().messages.forEach(function (m) {
var message = {}
m.enums.forEach(function (e) {
message[e.name] = e
})
message.name = m.name
message.encode = encoder(m, pb)
message.decode = decoder(m, pb)
self[m.name] = message
})
}
|
javascript
|
{
"resource": ""
}
|
|
q12880
|
train
|
function($root) {
var match = this.model.get('data');
this.updateScore(match.teamAScore, $root.find('.team.left .team-score'));
this.updateScore(match.teamBScore, $root.find('.team.right .team-score'));
}
|
javascript
|
{
"resource": ""
}
|
|
q12881
|
train
|
function(state){
var match = this.model.get('data');
var countryA = match.teamA ? match.teamA.country : null;
this.setFlagsState(state, countryA, this.$('.flag-3d-left'));
var countryB = match.teamB ? match.teamB.country : null;
this.setFlagsState(state, countryB, this.$('.flag-3d-right'));
}
|
javascript
|
{
"resource": ""
}
|
|
q12882
|
tag
|
train
|
function tag (chrSource) {
var program
var replacements
// Examine caller format
if (typeof chrSource === 'object' && chrSource.type && chrSource.type === 'Program') {
// called with already parsed source code
// e.g. tag({ type: 'Program', body: [ ... ] })
program = chrSource
replacements = []
// allow to specify replacements as second argument
if (arguments[1] && typeof arguments[1] === 'object' && arguments[1] instanceof Array) {
replacements = arguments[1]
}
} else if (typeof chrSource === 'object' && chrSource instanceof Array && typeof chrSource[0] === 'string') {
// called as template tag
// e.g. tag`a ==> b`
// or tag`a ==> ${ function() { console.log('Replacement test') } }`
var combined = [
chrSource[0]
]
Array.prototype.slice.call(arguments, 1).forEach(function (repl, ix) {
combined.push(repl)
combined.push(chrSource[ix + 1])
})
chrSource = joinParts(combined)
replacements = Array.prototype.slice.call(arguments, 1)
program = parse(chrSource)
} else if (typeof chrSource === 'string' && arguments[1] && arguments[1] instanceof Array) {
// called with program and replacements array
// e.g. tag(
// 'a ==> ${ function() { console.log("Replacement test") } }',
// [ eval('( function() { console.log("Replacement test") } )') ]
// )
// this is useful to ensure the scope of the given replacements
program = parse(chrSource)
replacements = arguments[1]
} else if (typeof chrSource === 'string') {
// called as normal function
// e.g. tag('a ==> b')
// or tag('a ==> ', function() { console.log('Replacement test') })
replacements = Array.prototype.filter.call(arguments, isFunction)
chrSource = joinParts(Array.prototype.slice.call(arguments))
program = parse(chrSource)
}
var rules = program.body
rules.forEach(function (rule) {
tag.Rules.Add(rule, replacements)
})
}
|
javascript
|
{
"resource": ""
}
|
q12883
|
associateWithTeams
|
train
|
function associateWithTeams(teams, tableModel){
// Go through all team rows inside the table's data, and add's team object
// _.forEach(tableModel.table, function(teamRow){
// teamRow['team'] = teams[teamRow.teamId] || {};
// });
// Go through all team rows inside scores, and add's a team object
_.forEach(tableModel.scores, function(teamRow){
teamRow['team'] = teams[teamRow.teamId] || {};
});
}
|
javascript
|
{
"resource": ""
}
|
q12884
|
checkPort
|
train
|
function checkPort(port, host, callback) {
var socket = new Socket(),
status = null;
socket.on('connect', () => {
status = 'open';
socket.end();
});
socket.setTimeout(1500);
socket.on('timeout', () => {
status = 'closed';
socket.destroy();
});
socket.on('error', (exception) => {
status = 'closed';
});
socket.on('close', (exception) => {
callback(null, status,host,port);
});
socket.connect(port, host);
}
|
javascript
|
{
"resource": ""
}
|
q12885
|
getNextID
|
train
|
function getNextID () {
var max = 0;
_.forEach(newPages, function(page){
if(page.id) max = Math.max(max, page.id*1);
});
var next = max*1+1;
return next;
}
|
javascript
|
{
"resource": ""
}
|
q12886
|
checkText
|
train
|
function checkText(text, callback, settings) {
const form = prepareSettings(settings);
form.text = text;
post({
host: YASPELLER_HOST,
path: YASPELLER_PATH + 'checkText',
form: form,
}, function(error, response, body) {
if (error) {
callback(error, null);
} else {
if (response.statusCode === 200) {
callback(null, body);
} else {
callback(
Error('Yandex.Speller API returns status code is ' +
response.statusCode, null)
);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12887
|
resolveMethod
|
train
|
function resolveMethod(wrapedMethod, methodRaw){
// Get method string and `methodify` it recursivelly
var method = getMethodFor(methodRaw);
// Check if method is ok to continue, or, return null
if(!method) throw new Error('Could not parse method: '+methodRaw);
// Create a wrapped method of the current one, with this one
return function(scores){
return wrapedMethod(method(scores));
}
}
|
javascript
|
{
"resource": ""
}
|
q12888
|
train
|
function(match){
/*
Depending on the match state, we shall render
a different match view. Templates are:
+ pageview-group.match.scheduled
+ pageview-group.match.playing
+ pageview-group.match.endend
*/
var templates = {
'scheduled': JST['pageview-group.match.scheduled'],
'playing': JST['pageview-group.match.playing'],
'ended': JST['pageview-group.match.ended'],
};
if(match.state == 'scheduled'){
return JST['pageview-group.match.scheduled']({match: match});
}else if(match.state == 'playing'){
return JST['pageview-group.match.playing']({match: match});
}else if(match.state == 'ended'){
// In this case, we need to set the class for A and B.
// (teamAClass and teamBClass to null, team-win, team-loose)
return JST['pageview-group.match.ended']({
match: match,
teamAClass: (match.teamAScore > match.teamBScore ? 'team-win'
:match.teamAScore < match.teamBScore ? 'team-loose' : ''),
teamBClass: (match.teamBScore > match.teamAScore ? 'team-win'
:match.teamBScore < match.teamAScore ? 'team-loose' : ''),
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12889
|
draggableDirective
|
train
|
function draggableDirective() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var domElement = element[0];
var effectAllowed = attrs.effectAllowed;
var draggableData = attrs.draggableData;
var draggableType = attrs.draggableType;
var draggable = attrs.draggable === 'false' ? false : true;
// Make element draggable or not.
domElement.draggable = draggable;
if (! draggable) return ;
domElement.addEventListener('dragstart', function (e) {
// Restrict drag effect.
e.dataTransfer.effectAllowed = effectAllowed || e.dataTransfer.effectAllowed;
// Eval and serialize data.
var data = scope.$eval(draggableData);
var jsonData = angular.toJson(data);
// Set drag data and drag type.
e.dataTransfer.setData('json/' + draggableType, jsonData);
e.stopPropagation();
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
q12890
|
accepts
|
train
|
function accepts(type, event) {
if (typeof type === 'boolean') return type;
if (typeof type === 'string') return accepts([type], event);
if (Array.isArray(type)) {
return accepts(function (types) {
return types.some(function (_type) {
return type.indexOf(_type) !== -1;
});
}, event);
}
if (typeof type === 'function') return type(toArray(event.dataTransfer.types));
return false;
}
|
javascript
|
{
"resource": ""
}
|
q12891
|
getData
|
train
|
function getData(event) {
var types = toArray(event.dataTransfer.types);
return types.reduce(function (collection, type) {
// Get data.
var data = event.dataTransfer.getData(type);
// Get data format.
var format = /(.*)\//.exec(type);
format = format ? format[1] : null;
// Parse data.
if (format === 'json') data = JSON.parse(data);
collection[type] = data;
return collection;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q12892
|
train
|
function(el){
if(!el)
el = this.$el.last();
else
el = $(el);
el.fadeOut(el.remove);
}
|
javascript
|
{
"resource": ""
}
|
|
q12893
|
sortDocs
|
train
|
function sortDocs(docs, sortType) {
if (!sortType) return;
const fnSorter = sorter.getSymbolsComparer(sortType, '$longname');
const fnPropSorter = sorter.getSymbolsComparer(sortType, 'name');
docs.sort(fnSorter);
docs.forEach(symbol => {
if (symbol && Array.isArray(symbol.properties)) {
symbol.properties.sort(fnPropSorter);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12894
|
filterTasks
|
train
|
function filterTasks (type, tasks, alltasks) {
var contains = function (task) {
return _.includes(tasks, task.name);
};
if (type === 'include') {
return _.filter(alltasks, contains);
} else if (type === 'exclude') {
return _.reject(alltasks, contains);
}
return alltasks;
}
|
javascript
|
{
"resource": ""
}
|
q12895
|
InternalAuthError
|
train
|
function InternalAuthError(message, err) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
this.authError = err;
}
|
javascript
|
{
"resource": ""
}
|
q12896
|
encodeCharacter
|
train
|
function encodeCharacter (chr) {
var
result = '',
octets = utf8.encode(chr),
octet,
index;
for (index = 0; index < octets.length; index += 1) {
octet = octets.charCodeAt(index);
result += '%' + (octet < 0x10 ? '0' : '') + octet.toString(16).toUpperCase();
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q12897
|
isPercentDigitDigit
|
train
|
function isPercentDigitDigit (text, start) {
return text.charAt(start) === '%' && charHelper.isHexDigit(text.charAt(start + 1)) && charHelper.isHexDigit(text.charAt(start + 2));
}
|
javascript
|
{
"resource": ""
}
|
q12898
|
isPctEncoded
|
train
|
function isPctEncoded (chr) {
if (!isPercentDigitDigit(chr, 0)) {
return false;
}
var firstCharCode = parseHex2(chr, 1);
var numBytes = utf8.numBytes(firstCharCode);
if (numBytes === 0) {
return false;
}
for (var byteNumber = 1; byteNumber < numBytes; byteNumber += 1) {
if (!isPercentDigitDigit(chr, 3*byteNumber) || !utf8.isValidFollowingCharCode(parseHex2(chr, 3*byteNumber + 1))) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q12899
|
isVarchar
|
train
|
function isVarchar (chr) {
return charHelper.isAlpha(chr) || charHelper.isDigit(chr) || chr === '_' || pctEncoder.isPctEncoded(chr);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.