_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q13700
|
emitObject
|
train
|
function emitObject() {
var item = {
type: types[type],
size: length,
body: bops.join(parts),
offset: start
};
if (ref) item.ref = ref;
parts.length = 0;
start = 0;
offset = 0;
type = 0;
length = 0;
ref = null;
emit(item);
}
|
javascript
|
{
"resource": ""
}
|
q13701
|
$body
|
train
|
function $body(byte, i, chunk) {
if (inf.write(byte)) return $body;
var buf = inf.flush();
inf.recycle();
if (buf.length) {
parts.push(buf);
}
emitObject();
// If this was all the objects, start calculating the sha1sum
if (--num) return $header;
sha1sum.update(bops.subarray(chunk, 0, i + 1));
return $checksum;
}
|
javascript
|
{
"resource": ""
}
|
q13702
|
typeOf
|
train
|
function typeOf (rule) {
var ruleType = typeof rule
return ruleType === 'function'
? ruleType
: ruleType !== 'object'
? (rule.length === 0
? 'noop'
: (rule === 0
? 'zero'
: ruleType
)
)
: Buffer.isBuffer(rule)
? 'buffer'
: !isArray(rule)
? ((has(rule, 'start') && has(rule, 'end')
? 'range'
: has(rule, 'start')
? 'rangestart'
: has(rule, 'end')
? 'rangeend'
: has(rule, 'firstOf')
? (( (isArray(rule.firstOf) && sameTypeArray(rule.firstOf) )
|| typeof rule.firstOf === 'string'
)
&& rule.firstOf.length > 1
)
? 'firstof'
: 'invalid firstof'
: 'invalid'
)
+ '_object'
)
: !sameTypeArray(rule)
? 'multi types array'
: ((Buffer.isBuffer( rule[0] )
? 'buffer'
: typeof rule[0]
)
+ '_array'
)
}
|
javascript
|
{
"resource": ""
}
|
q13703
|
encounter
|
train
|
function encounter(mood) {
//Sentence 1: The meeting
const familiar_people = wordLib.getWords("familiar_people");
const strange_people = wordLib.getWords("strange_people");
const locations = wordLib.getWords("locations");
const person = nu.chooseFrom(familiar_people.concat(strange_people));
let location = nu.chooseFrom(wordLib.getWords("locations"));
const preposition = location[0];
location = location[1];
const s1 = `You may meet ${person} ${preposition} ${location}.`;
// Sentence 2: The discussion
let discussions = wordLib.getWords("neutral_discussions");
discussions.concat(wordLib.getWords(mood + "_discussions"));
const feeling_nouns = wordLib.getWords(mood + "_feeling_nouns");
const emotive_nouns = wordLib.getWords(mood + "_emotive_nouns");
const conversation_topics = wordLib.getWords("conversation_topics");
const discussion = nu.chooseFrom(discussions);
const rnum = Math.floor(Math.random() * 10);
let feeling;
if (rnum <- 5) {
feeling = nu.chooseFrom(feeling_nouns);
feeling = "feelings of " + feeling;
} else {
feeling = nu.chooseFrom(emotive_nouns);
}
const topic = nu.chooseFrom(conversation_topics);
let s2 = `${nu.an(discussion)} about ${topic} may lead to ${feeling}.`;
s2 = nu.sentenceCase(s2);
return `${s1} ${s2}`;
}
|
javascript
|
{
"resource": ""
}
|
q13704
|
feeling
|
train
|
function feeling(mood) {
const rnum = Math.floor(Math.random() * 10);
const adjectives = wordLib.getWords(mood + "_feeling_adjs");
//var degrees = getWords("neutral_degrees") + getWords(mood + "_degrees");
const degrees = wordLib.getWords("neutral_degrees").concat(wordLib.getWords(mood + "_degrees"));
const adj = nu.ingToEd(nu.chooseFrom(adjectives));
const degree = nu.chooseFrom(degrees);
let ending;
if (mood === "good") {
ending = wordLib.positiveIntensify();
} else {
ending = wordLib.consolation();
}
const exciting = (mood === "GOOD" && rnum <= 5);
const are = nu.chooseFrom([" are", "'re"]);
const sentence = `You${are} feeling ${degree} ${adj}${ending}`;
return nu.sentenceCase(sentence, exciting);
}
|
javascript
|
{
"resource": ""
}
|
q13705
|
getGameAfterMove
|
train
|
function getGameAfterMove(game, move, backMove = false) {
if (!backMove && canNotMove(game, move))
return game;
const board = getBoardAfterMove(game.board, move);
return {
players: game.players,
board,
score: Score.getScore(game.board),
moves: backMove ? game.moves : game.moves.concat(getMoveXAndY(move))
};
}
|
javascript
|
{
"resource": ""
}
|
q13706
|
getGameBeforeLastMove
|
train
|
function getGameBeforeLastMove(game) {
// $Fix I do NOT know if it is the best way to make game immutable.
game = Object.assign({}, game);
let lastMove = game.moves.pop();
if (lastMove)
game = getGameAfterMove(game, getBackMove(lastMove), true);
if (Game.getPlayerTurn(game).isAi) {
lastMove = game.moves.pop();
if (lastMove) {
game = getGameAfterMove(game, getBackMove(lastMove), true);
}
}
return game;
}
|
javascript
|
{
"resource": ""
}
|
q13707
|
train
|
function (config) {
/**
* The iterator function, which is called on each component.
*
* @param {string} version the version of the component
* @param {string} component the name of the component
* @return {undefined}
*/
return function (version, component) {
var dep = config.get('global-dependencies').get(component) || {
main: '',
type: '',
name: '',
dependencies: {}
};
console.log(version, component);
var componentConfigFile = findComponentConfigFile(config, component);
var warnings = config.get('warnings');
var overrides = config.get('overrides');
if (overrides && overrides[component]) {
if (overrides[component].dependencies) {
componentConfigFile.dependencies = overrides[component].dependencies;
}
if (overrides[component].main) {
componentConfigFile.main = overrides[component].main;
}
}
var mains = findMainFiles(config, component, componentConfigFile);
var fileTypes = _.chain(mains).map(path.extname).unique().value();
dep.main = mains;
dep.type = fileTypes;
dep.name = componentConfigFile.name;
var depIsExcluded = _.find(config.get('exclude'), function (pattern) {
return path.join(config.get('bower-directory'), component).match(pattern);
});
if (dep.main.length === 0 && !depIsExcluded) {
// can't find the main file. this config file is useless!
warnings.push(component + ' was not injected in your file.');
warnings.push(
'Please go take a look in "' + path.join(config.get('bower-directory'), component) + '" for the file you need, then manually include it in your file.');
config.set('warnings', warnings);
return;
}
if (componentConfigFile.dependencies) {
dep.dependencies = componentConfigFile.dependencies;
_.each(componentConfigFile.dependencies, gatherInfo(config));
}
config.get('global-dependencies').set(component, dep);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q13708
|
train
|
function (a, b) {
var aNeedsB = false;
var bNeedsA = false;
aNeedsB = Object.
keys(a.dependencies).
some(function (dependency) {
return dependency === b.name;
});
if (aNeedsB) {
return 1;
}
bNeedsA = Object.
keys(b.dependencies).
some(function (dependency) {
return dependency === a.name;
});
if (bNeedsA) {
return -1;
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q13709
|
train
|
function (left, right) {
var result = [];
var leftIndex = 0;
var rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (dependencyComparator(left[leftIndex], right[rightIndex]) < 1) {
result.push(left[leftIndex++]);
} else {
result.push(right[rightIndex++]);
}
}
return result.
concat(left.slice(leftIndex)).
concat(right.slice(rightIndex));
}
|
javascript
|
{
"resource": ""
}
|
|
q13710
|
train
|
function (items) {
if (items.length < 2) {
return items;
}
var middle = Math.floor(items.length / 2);
return merge(
mergeSort(items.slice(0, middle)),
mergeSort(items.slice(middle))
);
}
|
javascript
|
{
"resource": ""
}
|
|
q13711
|
train
|
function (allDependencies, patterns) {
return _.transform(allDependencies, function (result, dependencies, fileType) {
result[fileType] = _.reject(dependencies, function (dependency) {
return _.find(patterns, function (pattern) {
return dependency.match(pattern);
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13712
|
proxy
|
train
|
function proxy (original, routes) {
return new Proxy(original, {
get(target, key, receiver) {
const method = target[key]
if (method) return method
else return function (path, ...args) {
const cb = args[0]
if (typeof cb === 'function') {
original.add(key, path, cb)
} else {
const fn = routes[key]
return fn && fn.exec(path, ...args)
}
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q13713
|
gen
|
train
|
function gen(path) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var config = assignConfig_1.default(option, path);
return globElements_1.default(config).then(readElements_1.default(config)).then(optimize_1.default()).then(render_1.default(config));
}
|
javascript
|
{
"resource": ""
}
|
q13714
|
toStriderProxy
|
train
|
function toStriderProxy(instance) {
debug(`Proxying async plugin: ${instance.constructor.name}`);
const functionsInInstance = Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).filter(propertyName => {
return typeof instance[propertyName] === 'function' && propertyName !== 'constructor';
});
functionsInInstance.forEach(functionInInstance => {
instance[`${functionInInstance}Async`] = instance[functionInInstance];
instance[functionInInstance] = function () {
const args = Array.from(arguments);
const done = args.pop();
return instance[`${functionInInstance}Async`].apply(instance, args)
.then(result => done(null, result))
.catch(errors.ExtensionConfigurationError, error => {
debug(`Extension configuration error:${error.message}` || error.info);
return done(error);
})
.catch(error => done(error));
};
Object.defineProperty(instance[functionInInstance], 'length', {
value: instance[`${functionInInstance}Async`].length
});
});
return instance;
}
|
javascript
|
{
"resource": ""
}
|
q13715
|
train
|
function(inShowing) {
if (inShowing && inShowing != this.showing) {
if (this.scrollBounds[this.sizeDimension] >= this.scrollBounds[this.dimension]) {
return;
}
}
if (this.hasNode()) {
this.cancelDelayHide();
}
if (inShowing != this.showing) {
var last = this.showing;
this.showing = inShowing;
this.showingChanged(last);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13716
|
extend
|
train
|
function extend(obj) {
var slice = Array.prototype.slice;
slice.call(arguments, 1).forEach(function(source) {
var getter
, setter;
for (var key in source) {
getter = source.__lookupGetter__(key);
setter = source.__lookupSetter__(key);
if (getter || setter) {
getter && obj.__defineGetter__(key, getter);
setter && obj.__defineSetter__(key, setter);
}
else {
obj[key] = source[key];
}
}
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q13717
|
setCursorDeadAndNotified
|
train
|
function setCursorDeadAndNotified(cursor, callback) {
cursor.s.dead = true;
setCursorNotified(cursor, callback);
}
|
javascript
|
{
"resource": ""
}
|
q13718
|
RTCOutboundRTPStreamStats
|
train
|
function RTCOutboundRTPStreamStats(rTCOutboundRTPStreamStatsDict){
if(!(this instanceof RTCOutboundRTPStreamStats))
return new RTCOutboundRTPStreamStats(rTCOutboundRTPStreamStatsDict)
// Check rTCOutboundRTPStreamStatsDict has the required fields
checkType('int', 'rTCOutboundRTPStreamStatsDict.packetsSent', rTCOutboundRTPStreamStatsDict.packetsSent, {required: true});
checkType('int', 'rTCOutboundRTPStreamStatsDict.bytesSent', rTCOutboundRTPStreamStatsDict.bytesSent, {required: true});
checkType('float', 'rTCOutboundRTPStreamStatsDict.targetBitrate', rTCOutboundRTPStreamStatsDict.targetBitrate, {required: true});
checkType('float', 'rTCOutboundRTPStreamStatsDict.roundTripTime', rTCOutboundRTPStreamStatsDict.roundTripTime, {required: true});
// Init parent class
RTCOutboundRTPStreamStats.super_.call(this, rTCOutboundRTPStreamStatsDict)
// Set object properties
Object.defineProperties(this, {
packetsSent: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.packetsSent
},
bytesSent: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.bytesSent
},
targetBitrate: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.targetBitrate
},
roundTripTime: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.roundTripTime
}
})
}
|
javascript
|
{
"resource": ""
}
|
q13719
|
inverse
|
train
|
function inverse(matrix) {
//http://www.wolframalpha.com/input/?i=Inverse+%5B%7B%7Ba,c,e%7D,%7Bb,d,f%7D,%7B0,0,1%7D%7D%5D
var a = matrix.a,
b = matrix.b,
c = matrix.c,
d = matrix.d,
e = matrix.e,
f = matrix.f;
var denom = a * d - b * c;
return {
a: d / denom,
b: b / -denom,
c: c / -denom,
d: a / denom,
e: (d * e - c * f) / -denom,
f: (b * e - a * f) / denom
};
}
|
javascript
|
{
"resource": ""
}
|
q13720
|
curry
|
train
|
function curry(fn, obj) {
// create a local copy of the function. don't apply anything yet
// optionally bind an object to the `this` of the function.
var newFunction = _.bind(fn, (obj || null));
// curried functions always take one argument
return function () {
// create another copy of the function with the arguments applied
var me = _.partial(newFunction, arguments);
// take advantage of the fact that bind changes the method signature:
// if we have no arguments left, run the method
if (!me.length) return me();
// otherwise, curry again and return that.
return curry(me);
};
}
|
javascript
|
{
"resource": ""
}
|
q13721
|
train
|
function (o, path) {
function iterator(m, p) { return _.getv(p)(m); }
return _.reduce(path, iterator, o);
}
|
javascript
|
{
"resource": ""
}
|
|
q13722
|
train
|
function (a) {
var elements = _.reject(_.rest(arguments), _.isMissing);
return a.push.apply(a, elements);
}
|
javascript
|
{
"resource": ""
}
|
|
q13723
|
train
|
function(opts) {
var opts = opts || {};
var shouldHash = typeof opts.hash != 'undefined' ? opts.hash : defaults.hash;
var prefix = _.flatten([defaults.prefix]);
var shouldPrefix = typeof opts.shouldPrefix != 'undefined' ? opts.shouldPrefix : true;
return through.obj(function(file, enc, cb) {
var originalPath = file.path;
// Get hash of contents
var hash = md5(opts, file.contents.toString());
// Construct new filename
var ext = path.extname(file.path);
var basePath = path.basename(file.path, ext);
var filename = typeof hash !== 'undefined' ? basePath + '-' + hash + ext : basePath + ext;
file.path = path.join(path.dirname(file.path), filename);
// Add to manifest
var base = path.join(file.cwd, defaults.src);
var key = originalPath.replace(base, '');
// @TODO: Instead of this it could use "glob" module to regex delete files
// Check for existing value and whether cleanup is set
var existing = manifest[key];
if (existing && existing.src && defaults.cleanup) {
// Delete the file
fs.unlink(path.join(file.cwd, defaults.dest, existing.src));
} else if (defaults.cleanup && shouldHash) {
// Check if cleanup and hash enabled then we can remove any non hashed version from dest directory
var nonHashPath = path.join(path.dirname(originalPath), basePath + ext).replace(base, '');
var absPath = path.join(file.cwd, defaults.dest, nonHashPath);
fs.exists(absPath, function(exists) {
if (!exists) return;
fs.unlink(absPath);
});
}
var filePrefix = shouldPrefix ? prefix[index % prefix.length] : '';
// Finally add new value to manifest
var src = file.path.replace(base, '');
manifest[key] = {
index: index++,
src: src,
dest: filePrefix + src
};
// Write manifest file
writeManifest();
// Return and continue
this.push(file);
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q13724
|
validateValue
|
train
|
function validateValue(key, valObj, list) {
let type; let valid; let range; let regex;
const object = list[key];
const val = hasKey(valObj, key) ? valObj[key] : 'value_not_defined';
let defaultValue = object;
if (object) {
type = object.type;
valid = object.valid;
range = object.range;
regex = object.regex;
defaultValue = hasKey(object, 'default') ? object.default : object;
}
if (isDeclared(val)) {
return defaultValue;
}
if (isMatch(key, val, regex)) {
return val;
}
if (isValid(key, val, valid, type)) {
return val;
}
isType(key, val, type);
inRange(key, val, range);
return val;
}
|
javascript
|
{
"resource": ""
}
|
q13725
|
classes
|
train
|
function classes(input) {
if (!input) return [];
assert.strictEqual(typeof input, 'string', 'expected a string for the class name');
if (!input.trim()) return [];
return input.trim().split(/\s+/g);
}
|
javascript
|
{
"resource": ""
}
|
q13726
|
deepChild
|
train
|
function deepChild(root, path) {
return path.reduce(function (node, index, x) {
assert(index in node.children, 'child does not exist at the given deep index ' + path.join('.'));
return node.children[index];
}, root);
}
|
javascript
|
{
"resource": ""
}
|
q13727
|
handler
|
train
|
function handler ( err, data ){
if ( callback != null ){
callback.apply( b9, arguments );
}
// only emit events when there is no error
if ( err == null ){
b9.emit.call( b9, method, data );
}
}
|
javascript
|
{
"resource": ""
}
|
q13728
|
Service
|
train
|
function Service(manager, name, port, heartbeat) {
var _name = name;
/**
* @property {String} name The name of the service
*/
Object.defineProperty(this, 'name', {
get: function get() {
return _name;
},
enumerable: true
});
var _port = port;
/**
* @property {Number} port The port claimed by the service
*/
Object.defineProperty(this, 'port', {
get: function get() {
return _port;
},
enumerable: true
});
var _heartbeatInterval;
if (heartbeat !== 0) {
debug('set heartbeat %d', heartbeat);
_heartbeatInterval = setInterval(heartbeatTest.call(this, manager), heartbeat);
}
/**
* @property {Number} heartbeat The heartbeat counter for the periodic port checking
*/
Object.defineProperty(this, 'heartbeat', {
get: function get() {
return _heartbeatInterval;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q13729
|
train
|
function(docs, callback) {
remaining = docs;
console.log('[ remove ] info: ' + remaining +' to remove.');
async.eachLimit(_.range(0, docs, 10000), 1, handleOneBlock, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q13730
|
train
|
function(teamId, req) {
const favoritesList = req.app.locals.favoritesList
const index = favoritesList.findIndex(t => t.id == teamId)
if(index < 0) {
const err = new Error('Team is not parte of Favorites!!!')
err.status = 409
throw err
}
favoritesList.splice(index, 1)
}
|
javascript
|
{
"resource": ""
}
|
|
q13731
|
click
|
train
|
function click(target, handler) {
target.addEventListener("click", function(evt) {
evt.stopPropagation();
evt.preventDefault();
handler.call(this);
});
}
|
javascript
|
{
"resource": ""
}
|
q13732
|
train
|
function(name, method) {
API.prototype[name] = function() {
var api = this;
var args = Array.prototype.slice.call(arguments);
this.chain(function(next) {
var cargs = [].slice.call(arguments);
cargs = args.concat(cargs);
// args.push(next);
method.apply(api, cargs);
});
return this;
};
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q13733
|
train
|
function(err) {
if (err) this._onError(err);
if (this._continueErrors || !err) {
var args = [].slice.call(arguments);
if (this._callbacks.length > 0) {
this._isQueueRunning = true;
var cb = this._callbacks.shift();
cb = cb.bind(this);
args = args.slice(1);
args.push(this.next);
cb.apply(this, args);
} else {
this._isQueueRunning = false;
this.start = (function() {
this.start = null;
this.next.apply(this, args);
}).bind(this);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q13734
|
train
|
function(name, value, immediate) {
if (immediate) {
this[name] = value;
} else this.chain(function() {
var args = Array.prototype.slice.call(arguments);
var next = args.pop();
this[name] = value;
args.unshift(null);
next.apply(this, args);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q13735
|
train
|
function(cb) {
cb = this.wrap(cb);
this._callbacks.push(cb);
if (!this._isQueueRunning) {
if (this.start) {
this.start();
} else this.next();
// this.start();
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q13736
|
parallel
|
train
|
function parallel(promises, limit) {
var d = Q.defer();
var total = promises.length;
var results = new Array(total);
var firstErr;
var running = 0;
var finished = 0;
var next = 0;
limit = limit || total;
function sched() {
while (next < total && running < limit) {
DEBUG && debug('*** sched #', next, '***', promises[next].inspect());
exec(next++);
}
}
function exec(id) {
running += 1;
var promise = promises[id];
DEBUG && debug('>>> running', running);
DEBUG && debug('*** run #', id, '***', promise.inspect());
promise.then(function (result) {
DEBUG && debug('#', id, 'then ***', result);
results[id] = result; // collect all result
d.notify(promise.inspect());
}).catch(function (err) {
DEBUG && debug('#', id, 'catch ***', err);
firstErr = firstErr || err; // keep the first error
}).finally(function () {
DEBUG && debug('#', id, 'finally ***', promise.inspect());
if (++finished === total) {
DEBUG && debug('>>> finished all ***', firstErr, results);
return firstErr ? d.reject(firstErr) : d.resolve(results);
}
DEBUG && debug('>>> finished', finished);
running -= 1;
sched();
});
}
sched();
return d.promise;
}
|
javascript
|
{
"resource": ""
}
|
q13737
|
addCommand
|
train
|
function addCommand(descriptor){
// Check descriptor type.
var err = {};
if( !checkDescriptor(descriptor, err) ){
logger.error(
'The command descriptor is invalid.',
new Error('[command.io] Invalid command descriptor ("'+err.key+'": expected "'+err.expect+'", have "'+err.type+'").')
);
logger.error('Please check this doc: https://github.com/Techniv/node-command-io/wiki/Command-descriptor-refactoring');
return module.exports;
}
var name = descriptor.name;
descriptor.controller = new CommandController(descriptor);
// Index the command descriptor
commandDescriptors[name] = descriptor;
// Chain addCommand
return module.exports;
}
|
javascript
|
{
"resource": ""
}
|
q13738
|
addCommands
|
train
|
function addCommands(commands){
for(var i in commands){
var commandObj = commands[i];
addCommand(commandObj);
}
return module.exports;
}
|
javascript
|
{
"resource": ""
}
|
q13739
|
CommandController
|
train
|
function CommandController(descriptor){
Object.defineProperties(this, {
name: {
get: function(){
return descriptor.name;
}
},
description: {
get: function(){
return descriptor.description;
}
},
CommandError: {
get: function(){
return LocalCommandError;
}
},
RuntimeCommandError: {
get: function (){
return LocalRuntimeCommandError;
}
},
errorLvl: {
get: function(){
return Object.create(CONST.errorLvl);
}
}
});
function LocalCommandError(message, level){
CommandError.call(this, message, descriptor.name, level);
}
LocalCommandError.prototype = Object.create(CommandError.prototype);
function LocalRuntimeCommandError(message){
RuntimeCommandError.call(this, message, descriptor.name);
}
LocalRuntimeCommandError.prototype = Object.create(RuntimeCommandError.prototype);
}
|
javascript
|
{
"resource": ""
}
|
q13740
|
checkDescriptor
|
train
|
function checkDescriptor(descriptor, err){
if(typeof descriptor != 'object') return false;
for(var key in CONST.descriptorType){
if(!checkType(descriptor[key], CONST.descriptorType[key])){
err.key = key;
err.expect = CONST.descriptorType[key];
err.type = typeof descriptor[key];
return false;
}
}
for(var key in CONST.descriptorOptType){
if(typeof descriptor[key] != 'undefined' && checkType(descriptor[key], CONST.descriptorOptType[key].type)) continue;
if(typeof descriptor[key] == 'undefined'){
if(typeof CONST.descriptorOptType[key].value != 'undefined') descriptor[key] = CONST.descriptorOptType[key].value;
continue;
}
err.key = key;
err.expect = CONST.descriptorOptType[key].type;
err.type = typeof descriptor[key];
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q13741
|
CommandError
|
train
|
function CommandError(message, command, level){
var that = this, error;
// Set the default level.
if( isNaN(level) || level < 1 || level > 3) level = CONST.errorLvl.error;
// Format the message
if(typeof command == 'string') message = '{'+command+'} '+message;
message = '[command.io] '+message;
// Create the native Error object.
error = new Error(message);
// Create the getter for native error properties and custom properties.
Object.defineProperties(this, {
'stack': {
get: function(){
return error.stack;
}
},
message: {
get: function(){
return error.message;
}
},
command: {
get: function(){
return command;
}
},
level: {
get: function(){
return level;
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q13742
|
substitute
|
train
|
function substitute(str, variables) {
// Based on Simple JavaScript Templating by
// John Resig - http://ejohn.org/blog/javascript-micro-templating/ - MIT Licensed
if (!cache[str]) {
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
try {
/*jshint -W054 */
cache[str] = new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'") +
"');}return p.join('');");
/*jshint +W054 */
} catch(e) {
grunt.fail.fatal("Failed to compile template:\n" + str);
}
}
return cache[str](variables || {});
}
|
javascript
|
{
"resource": ""
}
|
q13743
|
generate
|
train
|
function generate(tmpl, src, variables) {
variables = variables || {};
variables.FILES = {};
for (var i = 0; i < src.length; i++) {
var content = JSON.stringify(grunt.file.read(src[i]));
variables.FILES[src[i]] = content;
}
var template = grunt.file.read(tmpl);
return substitute(template, variables);
}
|
javascript
|
{
"resource": ""
}
|
q13744
|
putStorage
|
train
|
function putStorage(host, path, data, cert, callback) {
var protocol = 'https://'
var ldp = {
hostname: host,
rejectUnauthorized: false,
port: 443,
method: 'PUT',
headers: {'Content-Type': 'text/turtle'}
}
if (cert) {
ldp.key = fs.readFileSync(cert)
ldp.cert = fs.readFileSync(cert)
}
// put file to ldp
ldp.path = path
debug('sending to : ' + protocol + host + path)
var put = https.request(ldp, function(res) {
chunks = ''
debug('STATUS: ' + res.statusCode)
debug('HEADERS: ' + JSON.stringify(res.headers))
res.on('data', function (chunk) {
chunks += chunk
})
res.on('end', function (chunk) {
callback(null, chunks, ldp)
})
})
put.on('error', function(e) {
callback(e)
})
put.write(data)
put.end()
}
|
javascript
|
{
"resource": ""
}
|
q13745
|
is
|
train
|
function is(store, uri, type) {
var ret = false
var types = store.findTypeURIs($rdf.sym(uri))
if (types && types[type]) {
ret = true
}
return ret
}
|
javascript
|
{
"resource": ""
}
|
q13746
|
to_rgb
|
train
|
function to_rgb(obj){
return [obj.R, obj.G, obj.B].map(format_number).join('');
}
|
javascript
|
{
"resource": ""
}
|
q13747
|
train
|
function(results) {
// Only do so if `callback` is specified
if (IODOpts.callback) {
var options = { url: IODOpts.callback.uri }
var res = JSON.stringify(results)
// Url-encode use `form` property
if (IODOpts.callback.method === 'encoded') {
options.form = { results: res }
}
var r = request.post(options, function(err, res) {
// Emits `CbError` if any error occurs while sending results to callback
if (err) IOD.eventEmitter.emit('CbError', err)
else if (res.statusCode !== 200) {
IOD.eventEmitter.emit('CbError', 'Status Code: ' + res.statusCode)
}
})
// Multipart use form object
if (IODOpts.callback.method === 'multipart') {
var form = r.form()
form.append('results', res)
form.on('error', function(err) {
IOD.evenEmitter.emit('CBError', err)
})
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13748
|
train
|
function(jobId) {
var isFinished = function(res) {
return res && res.status &&
(res.status === 'finished' || res.status === 'failed')
}
var poll = function() {
IOD.status({ jobId: jobId }, function(err, res) {
// Emits err as first argument
if (err) IOD.eventEmitter.emit(jobId, err)
else if (isFinished(res)) {
IOD.eventEmitter.emit(jobId, null, res)
sendCallback(res)
}
else setTimeout(poll, IODOpts.pollInterval)
})
}
setTimeout(poll, IODOpts.pollInterval)
}
|
javascript
|
{
"resource": ""
}
|
|
q13749
|
train
|
function(asyncRes, callback) {
var jobId = asyncRes.jobID
if (!jobId) return callback(null, asyncRes)
else if (IODOpts.getResults) {
IOD.result({
jobId: jobId,
majorVersion: IODOpts.majorVersion,
retries: 3
}, callback)
}
else {
callback(null, asyncRes)
pollUntilDone(jobId)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13750
|
list
|
train
|
function list(scriptModule, agent, msg, cb) {
const servers = [];
const scripts = [];
const idMap = agent.idMap;
for (const sid in idMap) {
if (idMap.hasOwnProperty(sid)) {
servers.push(sid);
}
}
fs.readdir(scriptModule.root, (err, filenames) => {
if (err) {
filenames = [];
}
for (let i = 0, l = filenames.length; i < l; i++) {
scripts.push(filenames[i]);
}
cb(null, {
servers: servers,
scripts: scripts
});
});
}
|
javascript
|
{
"resource": ""
}
|
q13751
|
get
|
train
|
function get(scriptModule, agent, msg, cb) {
const filename = msg.filename;
if (!filename) {
cb('empty filename');
return;
}
fs.readFile(path.join(scriptModule.root, filename), 'utf-8', (err, data) => {
if (err) {
logger.error(`fail to read script file:${filename}, ${err.stack}`);
cb(`fail to read script with name:${filename}`);
}
cb(null, data);
});
}
|
javascript
|
{
"resource": ""
}
|
q13752
|
save
|
train
|
function save(scriptModule, agent, msg, cb) {
const filepath = path.join(scriptModule.root, msg.filename);
fs.writeFile(filepath, msg.body, (err) => {
if (err) {
logger.error(`fail to write script file:${msg.filename}, ${err.stack}`);
cb(`fail to write script file:${msg.filename}`);
return;
}
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
q13753
|
bin
|
train
|
function bin(argv) {
if (!argv[2]) {
console.error("url is required")
console.error("Usage : cat <url>")
process.exit(-1)
}
shell.cat(argv[2], function(err, res, uri) {
if (err) {
console.error(err)
} else {
console.log(res)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q13754
|
connectUser
|
train
|
function connectUser(name, pass, cb) {
loginUser(name, pass, function(err, user) {
if(err) return cb(err)
var nano = NANO(_ci.protocol+'//'+encodeURIComponent(name)+':'+encodeURIComponent(pass)+'@'+_ci.host+'/')
, db = nano.use(name)
;
function getObject(type, id, rev) {
var ctor = registry[type]
, obj = new ctor(id, rev)
obj.type(type)
if(ctor.dbname) {
obj.db = nano.use(ctor.dbname)
} else {
obj.db = db
}
obj.getObject = getObject
return obj
}
cb(null, user, getObject, db, nano)
})
}
|
javascript
|
{
"resource": ""
}
|
q13755
|
createDatabase
|
train
|
function createDatabase(name, cb) {
nano().db.create(name, function(err) {
if(err && err.status_code !== 412) return cb(err)
cb(null, err ? false : true)
})
}
|
javascript
|
{
"resource": ""
}
|
q13756
|
setDatabaseSecurity
|
train
|
function setDatabaseSecurity(name, cb) {
// Get _security first
getSecurity(name, function(err, d) {
if(err) return cb(err)
// Make name an admin
if(d.admins.names.indexOf(name) === -1) {
d.admins.names.push(name)
}
// Make name a reader
if(d.readers.names.indexOf(name) === -1) {
d.readers.names.push(name)
}
// Merge with _security template
d = mergeSecurity(_security, d)
// Apply changes
setSecurity(name, d, function(err) {
if(err) return cb(err)
cb()
})
})
}
|
javascript
|
{
"resource": ""
}
|
q13757
|
loginUser
|
train
|
function loginUser(name, pass, cb) {
// Get the user
var db = nano().use(user_dbname)
db.get(user_namespace+':'+name, function(err, doc) {
if(err) return cb(err)
// Check pass
var hash = crypto.createHash('sha1')
hash.update(pass)
hash.update(doc.salt)
var password_sha = hash.digest('hex')
if(doc.password_sha === password_sha) {
return cb(null, doc)
}
cb(new Error('Access denied.'))
})
}
|
javascript
|
{
"resource": ""
}
|
q13758
|
destroyDatabase
|
train
|
function destroyDatabase(name, cb) {
if(name === user_dbname)
throw new Error('We never ever delete that database.')
nano().db.destroy(name, function(err) {
if(err && err.status_code !== 404) return cb(err)
cb(null, err ? false : true)
})
}
|
javascript
|
{
"resource": ""
}
|
q13759
|
destroyUser
|
train
|
function destroyUser(name, pass, cb) {
loginUser(name, pass, function(err, user) {
if(err) return cb(err)
nano().use(user_dbname).destroy(user._id, user._rev, function(err, doc) {
if(err) return cb(err)
user._id = doc.id
user._rev = doc.rev
destroyDatabase(name, function(err) {
if(err) return cb(err)
cb(null, user)
})
})
})
// var db = nano().use(user_dbname)
// db.head(user_namespace+':'+name, function(err, b, h) {
// if(err) return cb(err)
// db.destroy(user_namespace+':'+name, JSON.parse(h.etag), function(err, doc) {
// if(err) return cb(err)
// destroyDatabase(name, function(err) {
// if(err) return cb(err)
// cb(null, doc)
// })
// })
// })
}
|
javascript
|
{
"resource": ""
}
|
q13760
|
JsonArray
|
train
|
function JsonArray (options) {
if (!(this instanceof JsonArray)) {
return new JsonArray(options)
}
this.options = Object.assign({}, options, { objectMode: true })
this.count = 0
this.map = ['[\n', ',\n', '\n]\n']
if (this.options.validJson === false) {
this.map = ['', '\n', '\n']
}
if (this.options.stringify) {
this._transform = this._stringify
this._flush = function (done) {
this.push(this.map[2])
setTimeout(function () {
done()
}, 2)
}
} else {
this._transform = this._parse
}
Transform.call(this, _omit(this.options, ['error', 'validJson', 'stringify']))
return this
}
|
javascript
|
{
"resource": ""
}
|
q13761
|
pr_parse
|
train
|
function pr_parse(options) {
this.traverse(options, function (dir, item, out) {
fs.readFile(dir + item, function(err, data) {
console.log('adding log ' + dir + item);
if (err) {
console.log(err);
console.log(data);
return;
}
var source = data.toString();
var output;
// if no match in the file
if (!source.match(regex)) {
return;
}
output = source.replace(regex, replacer);
fs.writeFile(out + item, output, function(err) {
if (err) {
console.log(err);
} else {
console.log(out + item + ' was saved!');
}
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q13762
|
pr_autolog
|
train
|
function pr_autolog(options) {
function espectRewrite(filepath, outpath, template) {
var autologret = require(template);
autologret(filepath, outpath);
}
function insertReturnLog(source, endLine) {
var sourceRet;
// Insert ending log at return statement.
sourceRet = source.replace(/(\s|;)return(\s|;)/g, "$1" + endLine + "return$2");
// Remove any ending log that added twice.
while(sourceRet.indexOf(endLine + endLine) !== -1) {
sourceRet = sourceRet.replace(endLine + endLine, endLine);
}
return sourceRet;
}
function insertEnterAndLeaveLog(item, node, functionName) {
var fnoutLine = 'var DEBOUT="debuguy,"' +
' + (new Date()).getTime() + ",' +
item.substring(0, item.lastIndexOf('.')) + '.' +
functionName + '@' +
node.loc.start.line + '";console.log(DEBOUT + ",ENTER," + Date.now());';
var fnEndLine = 'console.log(DEBOUT + ",LEAVE," + Date.now());';
var startLine = node.getSource().indexOf('{') + 1;
var endLine = node.getSource().lastIndexOf('}');
var source = node.getSource().substr(0, startLine) + fnoutLine +
node.getSource().substr(startLine, endLine - startLine) + fnEndLine +
node.getSource().substr(endLine);
source = insertReturnLog(source, fnEndLine);
return source;
}
function insertEnterLog(item, node, functionName) {
var fnoutLine = '\nconsole.log("debuguy,"' +
' + (new Date()).getTime() + ",' +
item.substring(0, item.lastIndexOf('.')) + '.' +
functionName + '@' +
node.loc.start.line + '");';
var startLine = node.getSource().indexOf('{') + 1;
var source = node.getSource().substr(0, startLine) + fnoutLine +
node.getSource().substr(startLine);
return source;
}
this.traverse(options, function insertLog (dir, item, out) {
if (options.xEspect) {
var templatefile = __dirname + '/autolog.esp.js';
if ('string' === typeof options.xEspect) {
templatefile = options.xEspect;
}
espectRewrite(dir + item, out + item, templatefile);
return;
}
fs.readFile(dir + item, function(err, data) {
console.log('adding log ' + dir + item);
if (err) {
console.log(err);
console.log(data);
return;
}
var text = data.toString();
var output;
try {
output = esprimaTraversal(text, {loc:true})
.traverse(function (node) {
if (node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression') {
// Get the name of the function
var functionName = 'anonymous';
if (node.id) {
functionName = node.id.name;
} else if (node.parent) {
switch (node.parent.type) {
case 'VariableDeclarator':
functionName = node.parent.id.name;
break;
case 'Property':
functionName = node.parent.key.name;
break;
case 'AssignmentExpression':
if (node.parent.left.type === 'MemberExpression') {
functionName = node.parent.left.property.name ||
node.parent.left.property.value;
}
else if (node.parent.left.type === 'Identifier') {
functionName = node.parent.left.name;
}
break;
}
}
// Build the console log output
var source;
if (options.callStackGraph) {
source = insertEnterAndLeaveLog(item, node, functionName);
} else {
source = insertEnterLog(item, node, functionName);
}
node.updateSource(source);
}
});
fs.writeFile(out + item, output, function(err) {
if (err) {
console.log(err);
} else {
console.log(out + item + ' was saved!');
}
});
}
catch (e) {
console.log('parsing failed: ' + dir + item);
console.log(e);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q13763
|
train
|
function(callback, timeInMs) {
var timeout = makeTimeout(callback);
setTriggerTime(timeout, timeInMs);
s_timeoutsToInsert.push(timeout);
return timeout.id;
}
|
javascript
|
{
"resource": ""
}
|
|
q13764
|
train
|
function(callback, timeInMs) {
var timeout = makeTimeout(function() {
setTriggerTime(timeout, timeout.timeInMs);
s_timeoutsToInsert.push(timeout);
callback();
});
timeout.timeInMs = timeInMs;
s_timeoutsToInsert.push(timeout);
return timeout.id;
}
|
javascript
|
{
"resource": ""
}
|
|
q13765
|
train
|
function(elapsedTimeInSeconds) {
// insert any unscheduled timeouts
if (s_timeoutsToInsert.length) {
s_timeoutsToInsert.forEach(insertTimeout);
s_timeoutsToInsert = [];
}
// Now remove any
if (s_timeoutsToRemoveById.length) {
s_timeoutsToRemoveById.forEach(removeTimeoutById);
s_timeoutsToRemoveById = [];
}
s_clockInMs += elapsedTimeInSeconds * 1000;
// process timeouts
for (var ii = 0; ii < s_timeouts.length; ++ii) {
var timeout = s_timeouts[ii];
if (s_clockInMs < timeout.timeToTrigger) {
break;
}
timeout.callback();
}
// remove expired timeouts
s_timeouts.splice(0, ii);
}
|
javascript
|
{
"resource": ""
}
|
|
q13766
|
train
|
function () {
const result = Array.prototype.pop.apply(arr)
fn('pop', arr, {
value: result
})
return result
}
|
javascript
|
{
"resource": ""
}
|
|
q13767
|
process
|
train
|
function process(data) {
//
// Apply previous post processing.
//
data = Pagelet.prototype.postprocess.call(this, data);
data.stats = {
outofdate: 0,
uptodate: 0,
pinned: 0
};
data.shrinkwrap.forEach(function shrinkwrap(module) {
if (module.pinned) data.stats.pinned++;
if (module.uptodate) data.stats.uptodate++;
else data.stats.outofdate++;
});
return data;
}
|
javascript
|
{
"resource": ""
}
|
q13768
|
Session
|
train
|
function Session(identity, connection, options) {
if (!(this instanceof Session)) {
return new Session(identity, connection, options);
}
assert(identity instanceof Identity, 'Invalid identity supplied');
if (!(connection instanceof Connection)) {
options = connection || {};
options.passive = true;
}
this.options = merge(Object.create(Session.DEFAULTS), options);
this.client = new Client(identity);
this._identity = identity;
if (!this.options.passive) {
this._connection = connection;
this._connection.open(this._onConnect.bind(this));
} else {
this._onConnect();
}
if (this.options.subscribe) {
this.client.on('message', this._onMessage.bind(this)).subscribe();
}
}
|
javascript
|
{
"resource": ""
}
|
q13769
|
train
|
function(){
var self = this,
logs = self._filterLogs(),
all = logs.all,
keys = logs.keys,
time = munit._relativeTime( self.end - self.start );
// Root module
if ( ! self.callback ) {
munit.color.green( "=== All submodules of " + self.nsPath + " have finished ===" );
return;
}
// Content
munit.color.blue( "\n" + self.nsPath );
munit.each( self.tests, function( test ) {
if ( keys[ test.name ] && keys[ test.name ].length ) {
keys[ test.name ].forEach(function( args ) {
munit.log.apply( munit, args );
});
}
if ( test.error ) {
munit.color.red( test.ns );
munit.log( "\n", test.error.stack );
munit.log( "\n" );
}
else if ( test.skip ) {
munit.color.gray( "[skipped] " + test.ns );
munit.color.gray( "\treason: " + test.skip );
}
else {
munit.color.green( test.ns );
}
});
// Logs made after the final test
if ( all.length ) {
all.forEach(function( args ) {
munit.log.apply( munit, args );
});
}
// Final Output
if ( self.failed ) {
munit.color.red( "\n-- " + self.failed + " tests failed on " + self.nsPath + " (" + time + ") --\n" );
}
else {
munit.color.green( "\n-- All " + self.passed + " tests passed on " + self.nsPath + " (" + time + ") --\n" );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13770
|
train
|
function(){
var self = this,
all = [],
keys = {},
current = null;
self._logs.reverse().forEach(function( log ) {
if ( log instanceof AssertResult ) {
current = log.name;
return;
}
var name = log[ 0 ];
if ( log.length > 1 && munit.isString( name ) && self.tests[ name ] ) {
if ( ! keys[ name ] ) {
keys[ name ] = [];
}
keys[ name ].unshift( log.slice( 1 ) );
}
else if ( current && self.tests[ current ] ) {
if ( ! keys[ current ] ) {
keys[ current ] = [];
}
keys[ current ].unshift( log );
}
else {
all.unshift( log );
}
});
return { all: all, keys: keys };
}
|
javascript
|
{
"resource": ""
}
|
|
q13771
|
train
|
function( name, error, skip ) {
var self = this,
now = Date.now(),
last = ! self.isAsync && self._lastTest ? self._lastTest : self.start,
result = new AssertResult( name, self.nsPath, now - last, error, skip );
self.tests[ name ] = result;
self.list.push( result );
self._logs.push( result );
self._lastTest = now;
}
|
javascript
|
{
"resource": ""
}
|
|
q13772
|
train
|
function( actual, expected, prefix ) {
var self = this, keys, expectedKeys;
prefix = prefix || '';
if ( munit.isArray( actual ) && munit.isArray( expected ) ) {
if ( actual.length !== expected.length ) {
throw "\nActual: actual" + prefix + ".length = " + actual.length +
"\nExpected: expected" + prefix + ".length = " + expected.length;
}
munit.each( actual, function( item, i ) {
if ( munit.isArray( item ) || munit.isObject( item ) ) {
self._objectMatch( item, expected[ i ], prefix + "[" + i + "]" );
}
else if ( item !== expected[ i ] ) {
throw "\nActual: actual" + prefix + "[" + i + "] = " + item +
"\nExpected: expected" + prefix + "[" + i + "] = " + expected[ i ];
}
});
}
else if ( munit.isObject( actual ) && munit.isObject( expected ) ) {
keys = Object.keys( actual );
expectedKeys = Object.keys( expected );
if ( keys.length !== expectedKeys.length ) {
throw "\nActual: actual" + prefix + ".length = " + keys.length +
"\nExpected: expected" + prefix + ".length = " + expectedKeys.length;
}
munit.each( keys, function( key ) {
var item = actual[ key ];
if ( munit.isArray( item ) || munit.isObject( item ) ) {
self._objectMatch( item, expected[ key ], prefix + "[" + key + "]" );
}
else if ( item !== expected[ key ] ) {
throw "\nActual: actual" + prefix + "[" + key + "] = " + item +
"\nExpected: expected" + prefix + "[" + key + "] = " + expected[ key ];
}
});
}
else if ( actual !== expected ) {
throw "\nActual: actual" + prefix + " = " + actual +
"\nExpected: expected" + prefix + " = " + expected;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13773
|
train
|
function( e, match ) {
var result = { passed: false }, message = '';
// Get a string for matching on the error
if ( munit.isError( e ) ) {
message = e.message;
}
else if ( munit.isString( e ) ) {
message = e;
}
// No match required
if ( match === undefined ) {
result.passed = true;
}
// Non Error/String error object, string matching required
else if ( ! munit.isError( e ) && ! munit.isString( e ) ) {
if ( e === match ) {
result.passed = true;
}
else {
result.extra = "Match object '" + match + "' does not match error '" + e + "'";
}
}
// Function error class matching
else if ( munit.isFunction( match ) ) {
if ( e instanceof match ) {
result.passed = true;
}
else {
result.extra = "Error does not match class '" + match.name + "'";
}
}
// Regex checking on the error message
else if ( munit.isRegExp( match ) ) {
if ( match.exec( message ) ) {
result.passed = true;
}
else {
result.extra = "Regex (" + match + ") could not find match on:\n" + message;
}
}
// String matching on the error message
else if ( munit.isString( match ) ) {
if ( match === message ) {
result.passed = true;
}
else {
result.extra = "Error message doesn't match:\nActual: " + message + "\nExpected: " + match;
}
}
// Unkown error type passed
else {
result.extra = "Unknown error match type '" + match + "'";
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q13774
|
train
|
function( name, startFunc, error ) {
var self = this, result;
// Assign proper error
if ( ! error ) {
error = new munit.AssertionError( "'" + name + "' test failed", startFunc );
}
else if ( ! ( error instanceof Error ) ) {
error = new munit.AssertionError( error, startFunc );
}
// Increment error count and jump
self._addResult( name, error );
self.failed++;
self.count++;
munit.failed++;
// Kill on test failure
if ( self.options.stopOnFail ) {
self._flush();
munit.exit( 1 );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13775
|
train
|
function( name ) {
var self = this;
self._addResult( name );
self.passed++;
self.count++;
munit.passed++;
}
|
javascript
|
{
"resource": ""
}
|
|
q13776
|
train
|
function( required, startFunc ) {
var self = this;
if ( required !== self.state ) {
self._stateError( startFunc || self.requireState );
}
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q13777
|
train
|
function( time, callback ) {
var self = this, timeid;
// Can only delay an active module
self.requireState( munit.ASSERT_STATE_ACTIVE, self.delay );
// Time parameter is required
if ( ! munit.isNumber( time ) ) {
throw new munit.AssertionError( "Time parameter not passed to assert.delay", self.delay );
}
// Module has yet to complete the callback cycle,
// Start async extension now
if ( ! self.isAsync ) {
self.isAsync = true;
self.options.timeout = time;
self._timerStart = Date.now();
self._timeid = timeid = setTimeout(function(){
if ( munit.isFunction( callback ) ) {
callback( self );
}
if ( timeid === self._timeid && self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, time );
}
// Only extend current timeout if it is less then requested delay
else if ( ( self._timerStart + self.options.timeout ) < ( Date.now() + time ) ) {
if ( self._timeid ) {
self._timeid = clearTimeout( self._timeid );
}
self.isAsync = true;
self._timerStart = Date.now();
self._timeid = timeid = setTimeout(function(){
if ( munit.isFunction( callback ) ) {
callback( self );
}
if ( timeid === self._timeid && self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, time );
}
// Force block any delay that does not extend longer than current timeout
else {
throw new munit.AssertionError( "delay time doesn't extend further than the current timeout", self.delay );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q13778
|
train
|
function( name, test, startFunc, extra ) {
var self = this;
// Require an active state for tests
self.requireState( munit.ASSERT_STATE_ACTIVE, startFunc || self.ok );
// Prevent non empty string names
if ( ! munit.isString( name ) || ! name.length ) {
throw new munit.AssertionError(
"Name not found for test on '" + self.nsPath + "'",
startFunc || self.ok
);
}
// Prevent duplicate tests
else if ( self.tests[ name ] ) {
throw new munit.AssertionError(
"Duplicate Test '" + name + "' on '" + self.nsPath + "'",
startFunc || self.ok
);
}
// Increment test count and mark it
self[ !!( test ) ? '_pass' : '_fail' ]( name, startFunc || self.ok, extra );
// Reached expected number of tests, close off
if ( self.options.expect > 0 && self.count >= self.options.expect ) {
self.close();
}
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q13779
|
train
|
function( name, startFunc, extra ) {
if ( extra === undefined && ! munit.isFunction( startFunc ) ) {
extra = startFunc;
startFunc = undefined;
}
if ( munit.isError( extra ) ) {
extra = extra.message;
}
return this.ok( name, false, startFunc || this.fail, extra );
}
|
javascript
|
{
"resource": ""
}
|
|
q13780
|
train
|
function( name, value, match ) {
var self = this,
result = munit.isError( value ) ?
self._errorMatch( value, match ) :
{ passed: false, extra: "Value is not an Error '" + value + "'" };
return self.ok( name, result.passed, self.isError, result.extra );
}
|
javascript
|
{
"resource": ""
}
|
|
q13781
|
train
|
function( name, actual, expected ) {
return this.ok( name, actual !== expected, this.notEqual, "\nValues should not match\nActual:" + actual + "\nExpected:" + expected );
}
|
javascript
|
{
"resource": ""
}
|
|
q13782
|
train
|
function( name, upper, lower ) {
return this.ok( name, upper > lower, this.greaterThan, "\nUpper Value '" + upper + "' is not greater than lower value '" + lower + "'" );
}
|
javascript
|
{
"resource": ""
}
|
|
q13783
|
train
|
function( name, lower, upper ) {
return this.ok( name, lower < upper, this.lessThan, "\nLower Value '" + lower + "' is not less than upper value '" + upper + "'" );
}
|
javascript
|
{
"resource": ""
}
|
|
q13784
|
train
|
function( name, value, lower, upper ) {
return this.ok(
name,
value > lower && value < upper,
this.between,
"\nValue '" + value + "' is not inbetween '" + lower + "' and '" + upper + "'"
);
}
|
javascript
|
{
"resource": ""
}
|
|
q13785
|
train
|
function( name, actual, expected ) {
var self = this, passed = true, extra = '';
try {
self._objectMatch( actual, expected );
}
catch ( e ) {
passed = false;
extra = e;
if ( ! munit.isString( e ) ) {
throw e;
}
}
return self.ok( name, passed, self.deepEqual, extra );
}
|
javascript
|
{
"resource": ""
}
|
|
q13786
|
train
|
function( name, actual, expected ) {
var self = this, passed = true;
try {
self._objectMatch( actual, expected );
passed = false;
}
catch ( e ) {
}
return self.ok( name, passed, self.notDeepEqual, 'Objects are not supposed to match' );
}
|
javascript
|
{
"resource": ""
}
|
|
q13787
|
train
|
function( name, match, block ) {
var self = this, result = { passed: false, extra: 'Block did not throw error' };
// Variable arguments
if ( block === undefined && munit.isFunction( match ) ) {
block = match;
match = undefined;
}
// Fail quick if block isn't a function
if ( ! munit.isFunction( block ) ) {
throw new Error( "Block passed to assert.throws is not a function: '" + block + "'" );
}
// test for throwing
try {
block();
}
catch ( e ) {
result = self._errorMatch( e, match );
}
return self.ok( name, result.passed, self.throws, result.extra );
}
|
javascript
|
{
"resource": ""
}
|
|
q13788
|
train
|
function( name, block ) {
var self = this, passed = true;
try {
block();
}
catch ( e ) {
passed = false;
}
return self.ok( name, passed, self.doesNotThrow, 'Block does throw error' );
}
|
javascript
|
{
"resource": ""
}
|
|
q13789
|
train
|
function( name, actual, expected ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( expected ) ) {
passed = actual.getTime() === expected.getTime();
message = "Date '" + actual + "' does not match '" + expected + "'";
}
else {
message = munit.isDate( actual ) ?
"Expected value is not a Date object '" + expected + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateEquals, message );
}
|
javascript
|
{
"resource": ""
}
|
|
q13790
|
train
|
function( name, actual, lower ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( lower ) ) {
passed = actual.getTime() > lower.getTime();
message = "Date '" + actual + "' is not after '" + lower + "'";
}
else {
message = munit.isDate( actual ) ?
"Lower value is not a Date object '" + lower + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateAfter, message );
}
|
javascript
|
{
"resource": ""
}
|
|
q13791
|
train
|
function( name, actual, upper ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( upper ) ) {
passed = actual.getTime() < upper.getTime();
message = "Date '" + actual + "' is not before '" + upper + "'";
}
else {
message = munit.isDate( actual ) ?
"Upper value is not a Date object '" + upper + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateBefore, message );
}
|
javascript
|
{
"resource": ""
}
|
|
q13792
|
train
|
function( name, actual, lower, upper ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( lower ) && munit.isDate( upper ) ) {
passed = actual.getTime() > lower.getTime() && actual.getTime() < upper.getTime();
message = "Date '" + actual + "' is not between '" + lower + "' and '" + upper + "'";
}
else {
message = ! munit.isDate( actual ) ? "Actual value is not a Date object '" + actual + "'" :
! munit.isDate( lower ) ? "Lower value is not a Date object '" + lower + "'" :
"Upper value is not a Date object '" + upper + "'";
}
return self.ok( name, passed, self.dateBetween, message );
}
|
javascript
|
{
"resource": ""
}
|
|
q13793
|
train
|
function( name, handle ) {
var self = this;
// Can only add custom assertions when module hasn't been triggered yet
self.requireMaxState( munit.ASSERT_STATE_DEFAULT, self.custom );
// Block on reserved words
if ( munit.customReserved.indexOf( name ) > -1 ) {
throw new Error( "'" + name + "' is a reserved name and cannot be added as a custom assertion test" );
}
// Attach handle to assertion module and all submodules
self[ name ] = handle;
munit.each( self.ns, function( mod ) {
mod.custom( name, handle );
});
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q13794
|
train
|
function(){
var self = this;
// Can only start a module that hasn't been started yet
self.requireState( munit.ASSERT_STATE_DEFAULT, self.trigger );
// Setup and trigger module
self.start = self.end = Date.now();
// Parent namespaces sometimes don't have tests
// Also close out paths that aren't part of the focus
if ( ! self.callback || ! munit.render.focusPath( self.nsPath ) ) {
self.state = munit.ASSERT_STATE_CLOSED;
return self._close();
}
// Trigger test setup first
self._setup(function( e, setupCallback ) {
if ( e ) {
self.fail( "[munit] Failed to setup '" + self.nsPath + "' module", setupCallback, e );
return self.close();
}
// Run test
self.callback( self, self.queue );
// If module isn't finished, then prove that it's supposed to be asynchronous
if ( self.state < munit.ASSERT_STATE_TEARDOWN ) {
// Only tear it down if no timeout is specified
if ( self.options.timeout < 1 ) {
self.close();
}
// Delayed close
else if ( ! self.isAsync ) {
self.isAsync = true;
self._timerStart = Date.now();
self._timeid = setTimeout(function(){
if ( self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, self.options.timeout );
}
}
});
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q13795
|
train
|
function(){
var self = this,
nodeVersion = process.version.replace( /\./g, '_' ),
xml = "<testsuite name='" + munit._xmlEncode( nodeVersion + self.nsPath ) + "' tests='" + self.count + "' failures='" + self.failed + "' skipped='" + self.skipped + "' time='" + ( ( self.end - self.start ) / 1000 ) + "'>";
self.list.forEach(function( result ) {
xml += result.junit();
});
xml += "</testsuite>";
return xml;
}
|
javascript
|
{
"resource": ""
}
|
|
q13796
|
train
|
function(){
var self = this;
return {
name: self.nsPath.split( '.' ).pop(),
nsPath: self.nsPath,
count: self.count,
passed: self.passed,
failed: self.failed,
skipped: self.skipped,
start: self.start,
end: self.end,
time: self.end - self.start,
tests: self.list,
ns: self.ns,
};
}
|
javascript
|
{
"resource": ""
}
|
|
q13797
|
train
|
function( startFunc, forced ) {
var self = this, i, mod;
// Can only close an active module
self.requireState( munit.ASSERT_STATE_ACTIVE, self.close );
// Add fail marker if no tests were ran
if ( self.count < 1 ) {
self.fail( "[munit] No tests ran in this module" );
}
// Auto close out any spies
self._spies.reverse().forEach(function( spy ) {
spy.restore();
});
// Proxy teardown to pass start function and forced state
self._teardown(function( e, teardownCallback ) {
if ( e ) {
self._fail( "[munit] failed to teardown '" + self.nsPath + "' module properly", teardownCallback );
}
self._close( startFunc || self.close, forced );
});
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q13798
|
train
|
function( startFunc, forced ) {
var self = this, i, mod;
// Handle invalid number of tests ran
if ( self.options.expect > 0 && self.count < self.options.expect && munit.render.focusPath( self.nsPath ) ) {
self._fail(
'[munit] Unexpected End',
startFunc || self._close,
'Expecting ' + self.options.expect + ' tests, only ' + self.count + ' ran.'
);
}
else if ( self.count < 1 && self.callback && munit.render.focusPath( self.nsPath ) ) {
self._fail(
"[munit] No Tests Found",
startFunc || self._close,
"Module closed without any tests being ran."
);
}
// Remove timer
if ( self._timeid ) {
self._timeid = clearTimeout( self._timeid );
}
// Meta
self.end = Date.now();
// Readd the queue back to the stack
if ( self.options.autoQueue && self.queue ) {
munit.queue.add( self.queue );
self.queue = null;
}
// Check to see if submodules have closed off yet
for ( i in self.ns ) {
mod = self.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_CLOSED ) {
// Force close them if needed
if ( forced ) {
mod.close( startFunc || self._close, forced );
}
else {
return self;
}
}
}
// All submodules have closed off, can mark this one as finished
return self.finish( startFunc, forced );
}
|
javascript
|
{
"resource": ""
}
|
|
q13799
|
train
|
function( startFunc, forced ) {
var self = this, i, mod;
// Can only finish an module that's in a closed state
self.requireState( munit.ASSERT_STATE_CLOSED, startFunc || self.finish );
// Flip state to finished
self.state = munit.ASSERT_STATE_FINISHED;
// Force close each submodule if necessary
for ( i in self.ns ) {
mod = self.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_CLOSED ) {
mod.close( startFunc || self.finish, true );
}
}
// Only print out results if on the focus path
if ( munit.render.focusPath( self.nsPath ) ) {
self._flush();
}
// Finish parent if not forced by it
if ( ! forced ) {
if ( self.parAssert ) {
if ( self.parAssert.state < munit.ASSERT_STATE_CLOSED ) {
munit.render.check();
return self;
}
for ( i in self.parAssert.ns ) {
mod = self.parAssert.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_FINISHED ) {
munit.render.check();
return self;
}
}
self.parAssert.finish();
}
else {
munit.render.check();
}
}
return self;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.