_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q39700 | hookInstanbul | train | function hookInstanbul(opts) {
return loadJspmConfig(opts).then(loader => {
sh.echo('Registering instrumentation hook to loader...');
systemIstanbul.hookSystemJS(loader, opts.exclude(loader.baseURL));
return loader;
});
} | javascript | {
"resource": ""
} |
q39701 | createReport | train | function createReport(coverage, opts) {
const collector = new istanbul.Collector();
const reporter = new istanbul.Reporter(null, opts.coverage);
const sync = true;
sh.echo('Creating reports...');
collector.add(coverage);
reporter.addAll(opts.reports);
reporter.write(collector, sync, () => sh.echo('Reports created.'));
} | javascript | {
"resource": ""
} |
q39702 | rejectHandler | train | function rejectHandler(err) {
process.stderr.write(`${err.stack || err}\n`);
if (sh.config.fatal) {
sh.exit(1);
}
return Promise.reject(err);
} | javascript | {
"resource": ""
} |
q39703 | execute | train | function execute(req, res) {
Persistence.save(this.state.store, this.state.conf);
res.send(null, Constants.OK);
} | javascript | {
"resource": ""
} |
q39704 | train | function( path ) {
var normalized = [];
var parts = path.split( '/' );
for( var i = 0; i < parts.length; i++ ) {
if( parts[i] === '.' ) {
continue;
}
if( parts[i] === '..' && normalized.length && normalized[normalized.length - 1] !== '..' ) {
normalized.pop();
continue;
}
normalized.push( parts[i] );
}
return normalized.join( '/' );
} | javascript | {
"resource": ""
} | |
q39705 | train | function(queryRunner, options) {
options = options || {};
this.queryParser = new QueryParser(options.paramValueRegEx);
var indexNameBuilder = options.indexNameBuilder || new DefaultIndexNameBuilder();
this.queryBuilder = new EsQueryBuilder(indexNameBuilder, {
defaults: options.queryDefaults
});
this.queryRunner = queryRunner;
} | javascript | {
"resource": ""
} | |
q39706 | firstCommit | train | function firstCommit(dir, cb) {
if (typeof dir === 'function') {
return firstCommit(process.cwd(), dir);
}
if (typeof cb !== 'function') {
throw new TypeError('expected callback to be a function');
}
lazy.git(dir).log(function(err, history) {
if (err) return cb(err);
history.sort(function(a, b) {
return b.date.localeCompare(a.date);
});
cb(null, history[history.length - 1]);
});
} | javascript | {
"resource": ""
} |
q39707 | _readJSONFile | train | function _readJSONFile (file, callback) {
if ("undefined" === typeof file) {
throw new ReferenceError("missing \"file\" argument");
}
else if ("string" !== typeof file) {
throw new TypeError("\"file\" argument is not a string");
}
else if ("" === file.trim()) {
throw new Error("\"file\" argument is empty");
}
else if ("undefined" === typeof callback) {
throw new ReferenceError("missing \"callback\" argument");
}
else if ("function" !== typeof callback) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
isFileProm(file).then((exists) => {
return !exists ?
Promise.reject(new Error("The file does not exist")) :
new Promise((resolve, reject) => {
readFile(file, (err, content) => {
return err ? reject(err) : resolve(content);
});
});
}).then((content) => {
callback(null, JSON.parse(content));
}).catch(callback);
}
} | javascript | {
"resource": ""
} |
q39708 | QuestionsStore | train | function QuestionsStore(options) {
debug('initializing from <%s>', __filename);
Cache.call(this, options);
this.createStores(this, this.options);
this.listen(this);
} | javascript | {
"resource": ""
} |
q39709 | error | train | function error(scope, err, parameters) {
if(err.code == 'EACCES') {
scope.raise(scope.errors.EPERM, parameters);
}
} | javascript | {
"resource": ""
} |
q39710 | execute | train | function execute(argv, bin, args, req) {
var config = this.configure();
var errors = this.errors, scope = this, e;
var dir = config.bin || dirname(argv[1]);
var local = path.join(dir, bin);
var exists = fs.existsSync(local);
var data = {bin: bin, dir: dir, local: local, args: args};
if(!exists) {
e = new ExecError(errors.EEXEC_NOENT.message, [bin], errors.EEXEC_NOENT.code);
e.data = data;
throw e;
}
var stat = fs.statSync(local);
var ps = spawn(local, args, {stdio: [0, 1, 'pipe']});
req.process = ps;
this.emit('exec', ps, local, args, req);
ps.on('error', function(err){
error(scope, err, [bin]);
});
// suppress the execvp() error so we can cleanly
// present our own error message
ps.stderr.on('data', function(data) {
if(!/^execvp\(\)/.test(data.toString())) {
process.stderr.write(data);
}
})
ps.on('close', function (code, signal) {
// NOTE: workaround for https://github.com/joyent/node/issues/3222
// NOTE: assume child process exited gracefully on SIGINT
if(signal == 'SIGINT') {
return process.exit(0);
}
// TODO: remove this event?
scope.emit('close', code, signal);
if(config.exit) process.exit(code);
});
return ps;
} | javascript | {
"resource": ""
} |
q39711 | stringMatch | train | function stringMatch(stringValues) {
return function(testValue) {
for (var i = stringValues.length - 1; i >= 0; i--) {
if (stringValues[i] === testValue) {
return true;
}
}
return false;
};
} | javascript | {
"resource": ""
} |
q39712 | train | function (data) {
var q = _q.defer();
data = data.replace(/\'/g,"\\\'");
data = data.replace(/\"/g,'\\\"');
exec(`echo "${data}" | crontab -`, (err, stdout, stderr) => {
if (err) q.reject(err);
if(stdout)q.resolve(stdout);
else q.resolve(stderr);
});
return q.promise;
} | javascript | {
"resource": ""
} | |
q39713 | train | function(cb) {
if (typeof cb === "function") {
var opts = {
url: uri + 'user',
method: 'GET',
qs: qs,
json: true
};
request(opts,function(e,r,b) {
if (e) cb(e)
else {
if (r.statusCode==200) cb(null, b)
else {
cb({statusCode:r.statusCode,error:b.error})
}
}
});
return;
}
return {
/**
* Fetches the user's stream
*
* Example:
* app.user().stream(function(err,data){ ... })
*
* @param {Function} cb
* @api public
*/
stream: function(cb) {
var opts = {
url: uri + 'user/stream',
method: 'GET',
qs: qs,
json: true
};
request(opts,function(e,r,b) {
if (e) cb(e)
else {
if (r.statusCode==200) cb(null, b)
else {
cb({statusCode:r.statusCode,error:b.error})
}
}
});
},
/**
* Fetches the user's pucher channel
*
* Example:
* app.user().pusher_channel(function(err,data){ ... })
*
* @param {Function} cb
* @api public
*/
pusher_channel: function(cb) {
var opts = {
url: uri + 'user/pusherchannel',
method: 'GET',
qs: qs,
json: true
};
request(opts,function(e,r,b) {
if (e) cb(e)
else {
if (r.statusCode==200) cb(null, b.data)
else {
cb({statusCode:b.id||200,error:b.error})
}
}
});
},
}
} | javascript | {
"resource": ""
} | |
q39714 | train | function(cb) {
var opts = {
url: uri + 'user/stream',
method: 'GET',
qs: qs,
json: true
};
request(opts,function(e,r,b) {
if (e) cb(e)
else {
if (r.statusCode==200) cb(null, b)
else {
cb({statusCode:r.statusCode,error:b.error})
}
}
});
} | javascript | {
"resource": ""
} | |
q39715 | train | function(url,overwrite,cb) {
if (typeof overwrite === "function") {
cb = overwrite;
overwrite = false;
}
var opts = {
url: uri + 'device/'+device+'/callback',
method: 'POST',
qs: qs,
json: { url:url }
};
request(opts,function(e,r,b) {
if (!cb && !overwrite && b && b.id !== 409 ) return;
if (e) cb(e)
else if (b.result===1) cb(null)
else if (b.id===409 && overwrite) {
// A url already exists, let's update it
var opts = {
url: uri + 'device/'+device+'/callback',
method: 'PUT',
qs: qs,
json: { url:url }
};
request(opts,function(e,r,b) {
if (!cb) return;
if (e) cb(e)
else if (b.result===1) cb(null)
else cb({statusCode:b.id||200,error:b.error})
});
}
else {
cb({statusCode:b.id||200,error:b.error})
}
});
} | javascript | {
"resource": ""
} | |
q39716 | train | function(start, end, cb) {
if (typeof start === "function") {
cb = start;
start = false;
} else if (typeof end === "function") {
cb = end;
end = false;
}
if (start instanceof Date) start = start.getTime();
if (start) qs.from = start;
if (end instanceof Date) end = end.getTime();
if (end) qs.to = end;
var opts = {
url: uri + 'device/'+device+'/data',
method: 'GET',
qs: qs,
json: true
};
request(opts,function(e,r,b) {
if (e) cb(e)
else if (b.result===1) cb(null, b.data)
else cb({statusCode:b.id||200,error:b.error})
});
} | javascript | {
"resource": ""
} | |
q39717 | train | function(filter,cb) {
if (!filter) {
filter = {};
} else if (typeof filter == "function") {
cb = filter;
filter = {};
} else if (typeof filter == "string") {
filter = {device_type:filter}; // Backwards compatibility
}
var opts = {
url: uri + 'devices',
method: 'GET',
qs: qs,
json: true
};
request(opts,function(e,r,b) {
if (e) cb(e)
else if (b.result===1) cb(null, utils.filter(filter,b.data))
else cb({statusCode:b.id||200,error:b.error})
});
} | javascript | {
"resource": ""
} | |
q39718 | getPrimes | train | function getPrimes(limit) {
var sieve = new Array(limit);
var n, j, k;
var last = Math.floor(Math.sqrt(limit));
for (n=2; n < limit; n++) {
sieve[n] = true;
}
for (n=2; n <= last;) {
for (j= n+n; j < limit; j += n) {
sieve[j] = false;
}
for (j=1; j < last; j++) {
k = n+j;
if (sieve[k]) {
n = k;
break;
}
}
}
var primes = [];
for (n=2; n < limit; n++) {
if (sieve[n]) {
primes.push(n);
}
}
return primes;
} | javascript | {
"resource": ""
} |
q39719 | fill | train | function fill(size, seed, multiplier) {
var hash = new HashTable(size, seed, multiplier);
var x = agentdb.getX(1, 1); // dummy data Unknown, Unknown
agents.forEach(function (agent) {
if (agent.status < 2) {
var obj = { "a": agent.agent, "x": x };
hash.add('a', obj);
}
});
return hash.getHistory();
} | javascript | {
"resource": ""
} |
q39720 | dumpHistory | train | function dumpHistory(history, size, depth) {
console.log("Hash table history, size="+size+", average depth="+depth);
for (var n=0; n < history.length; n++) {
console.log(" Depth=" + n + ", count=" + history[n] + ", percent=" + (history[n] / size));
}
console.log("");
} | javascript | {
"resource": ""
} |
q39721 | getDepth | train | function getDepth(history) {
var total= history[0];
for (var n=1; n < history.length; n++) {
total = total + (n * n * history[n]);
}
var result = total / agents.length;
// console.log("total=" + total+", result=" + result);
return result;
} | javascript | {
"resource": ""
} |
q39722 | main | train | function main() {
if (verbose) { console.log("Finding primes to " + UPPER); }
var primes = getPrimes(UPPER);
if (verbose) { console.log("Done."); }
var bestSize = varySize(LOWER, UPPER, 5381, 33, primes);
var bestSeed = varySeed(0, 8192, bestSize, 33);
var bestMult = varyMultiplier(2, 256, bestSize, bestSeed);
bestSize = varySize(LOWER, UPPER, bestSeed, bestMult, primes);
} | javascript | {
"resource": ""
} |
q39723 | include | train | function include(list) {
var cmd, clazz, i, file, j, name, newname;
for(i = 0;i < list.length;i++) {
file = list[i];
try {
clazz = require(file);
// assume it is already instantiated
if(typeof clazz === 'object') {
cmd = clazz;
}else{
cmd = new clazz(clazz.definition);
}
// rename and delete commands
if(cmd && cmd.definition && cmd.definition.name) {
for(j = 0;j < rename.length;j++) {
name = rename[j][0];
newname = rename[j][1];
if(name
&& name.toLowerCase() === cmd.definition.name.toLowerCase()) {
newname = (newname || '').toLowerCase();
// actually renaming
if(newname) {
log.warning(
'rename command %s -> %s', cmd.definition.name, newname);
cmd.definition.name = newname;
// deleting the command, mark as deleted with false
}else{
log.warning(
'deleted command %s (%s)', cmd.definition.name, file);
commands[cmd.definition.name] = false;
// clear the module cache
delete require.cache[file];
}
break;
}
}
}
// deleted the command
if(!require.cache[file]) continue;
// sanity checks
if(!(cmd instanceof CommandExec)) {
throw new Error(
util.format(
'module does not export a command exec instance (%s)', file));
}else if(
!cmd.definition
|| !cmd.definition.constructor
|| cmd.definition.constructor.name !== Command.name) {
throw new Error(
util.format(
'command does not have a valid definition (%s)', file));
}else if(!cmd.definition.name) {
throw new Error(
util.format(
'command definition does not have a name (%s)', file));
}
if(opts.override !== true && commands[cmd.definition.name]) {
throw new Error(util.format(
'duplicate command %s (%s)', cmd.definition.name, file));
}
log.debug('loaded %s (%s)', cmd.definition.name, file);
// map of command names to command exec handlers
commands[cmd.definition.name] = cmd;
}catch(e) {
return complete(e);
}
}
complete();
} | javascript | {
"resource": ""
} |
q39724 | walk | train | function walk(files, cb, list) {
var i = 0;
list = list || [];
function check(file, cb) {
fs.stat(file, function onStat(err, stats) {
if(err) return cb(err);
if(stats.isFile() && !/\.js$/.test(file)) {
log.warning('ignoring %s', file);
return cb();
}
if(stats.isFile()) {
list.push(file);
return cb(null, list);
}else{
return fs.readdir(file, function onRead(err, files) {
if(err) return cb(err);
if(!files.length) return cb();
files = files.map(function(nm) {
return path.join(file, nm);
})
//files.forEach()
return walk(files, cb, list);
})
}
});
}
check(files[i], function onCheck(err, list) {
if(err) return cb(err);
if(i === files.length - 1) {
return cb(null, list);
}
i++;
check(files[i], onCheck);
});
} | javascript | {
"resource": ""
} |
q39725 | validateTextOperationJSON | train | function validateTextOperationJSON (op) {
debug('validateTextOperationJSON %o', op)
assertErr(Array.isArray(op), Error, 'operation must be an array', { op: op })
assertErr(op.length, Error, 'operation cannot be empty', { op: op })
var type
var lastType = ''
op.forEach(function (item) {
if (typeof item === 'string') {
// valid
type = 'string'
assertErr(lastType !== type, Error, 'invalid operation: cannot have repeating ' + type + 's')
lastType = type
return
} else if (typeof item === 'number') {
var isIntegerOrZero = (item === (item | 0))
assertErr(isIntegerOrZero, Error, 'invalid operation: numbers must be integers')
type = item === 0
? 'zero'
: item > 0
? 'positive integer'
: 'negative integer'
assertErr(lastType !== type, Error, 'invalid operation: cannot have repeating ' + type + 's')
lastType = type
} else {
throw new Error('invalid operation: must be an array of strings and numbers')
}
})
} | javascript | {
"resource": ""
} |
q39726 | trim | train | function trim(str) {
var input = str.replace(/\s\s+/g, ' ').trim();
var words = input.split(' ');
if (_.contains(LANG_WORDS, _.first(words))) {
return words.slice(1).join(' ');
}
return input;
} | javascript | {
"resource": ""
} |
q39727 | InvertFilter | train | function InvertFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
fs.readFileSync(__dirname + '/invert.frag', 'utf8'),
// custom uniforms
{
invert: { type: '1f', value: 1 }
}
);
} | javascript | {
"resource": ""
} |
q39728 | train | function (req, res, next) {
req.mounted = true
req.url = req.url.replace(remove, '')
// clear cached req.path
delete req._path
delete req._pathLength
next()
} | javascript | {
"resource": ""
} | |
q39729 | deleteSelf | train | function deleteSelf(callback) {
var _this = this;
_flowsync2["default"].series([function (done) {
_this.beforeDelete(done);
}, function (done) {
if (_this.constructor.useSoftDelete !== undefined) {
_this.softDestroy(done);
} else {
_this.destroy(done);
}
}, function (done) {
_this.afterDelete(done);
}], function (errors) {
callback(errors);
});
} | javascript | {
"resource": ""
} |
q39730 | inject | train | function inject(PromiseConstructor, extName) {
if (typeof PromiseConstructor === 'string') {
extName = PromiseConstructor;
}
extName = typeof extName === 'string' ? extName : 'delay';
PromiseConstructor =
(typeof PromiseConstructor === 'function' && PromiseConstructor) ||
(typeof Promise === 'function' && Promise) || null;
if (!PromiseConstructor) {
throw new Error('Wrong constructor is passed or browser doesn\'t support promises');
}
/**
* Delay promise
* Will be resolved after `ms` milliseconds. 1000 by default
*
* @param {number=} ms
*
* @return {Promise}
*/
PromiseConstructor[extName] = function(ms) {
ms = ms || 1000;
if (this instanceof PromiseConstructor) {
return this.then(function(value) {
return PromiseConstructor[extName](ms).then(function() {
return value;
});
});
} else {
return new PromiseConstructor(function(resolve) {
setTimeout(resolve, ms);
});
}
};
if (typeof PromiseConstructor === 'function' && PromiseConstructor.prototype && PromiseConstructor.prototype.constructor === PromiseConstructor) {
PromiseConstructor.prototype[extName] = PromiseConstructor[extName];
}
return PromiseConstructor;
} | javascript | {
"resource": ""
} |
q39731 | generate | train | function generate( arr, comment, _indent ) {
try {
const indent = typeof _indent !== "undefined" ? _indent : " ";
if ( arr.length === 0 ) return "";
let out = '';
if ( comment && comment.length > 0 ) {
let
len = comment.length + 3,
dashes = '';
while ( len-- > 0 ) dashes += "-";
out += `${indent}//${dashes}\n${indent}// ${comment}.\n`;
}
arr.forEach( function ( line ) {
if ( Array.isArray( line ) ) {
out += generate( line, null, ` ${indent}` );
} else {
out += `${indent}${line}\n`;
}
} );
return out;
} catch ( ex ) {
throw ex + "\n...in generate: " + JSON.stringify( comment );
}
} | javascript | {
"resource": ""
} |
q39732 | buildViewStatics | train | function buildViewStatics( def, code ) {
try {
let statics = def[ "view.statics" ];
if ( typeof statics === 'undefined' ) return;
if ( typeof statics === 'string' ) statics = [ statics ];
else if ( !Array.isArray( statics ) ) {
throw Error( "view.statics must be a string or an array of strings!" );
}
statics.forEach( function ( name ) {
code.addNeededBehindFunction( name );
code.section.statics.push(
"ViewClass" + keySyntax( name ) + " = CODE_BEHIND" + keySyntax( name ) + ".bind(ViewClass);"
);
} );
} catch ( ex ) {
throw ex + "\n...in view.statics: " + JSON.stringify( statics );
}
} | javascript | {
"resource": ""
} |
q39733 | buildViewAttribsFire | train | function buildViewAttribsFire( def, code ) {
code.pm = true;
const attribs = def[ "view.attribs" ];
if ( typeof attribs !== 'object' ) return;
try {
for ( const attName of Object.keys( attribs ) ) {
const camelCaseAttName = camelCase( attName );
if ( !code.isAction( attName ) ) {
buildViewAttribsInitFire( camelCaseAttName, code );
}
}
} catch ( ex ) {
bubble( ex, `...in buildViewAttribsFire - view.attribs: ${JSON.stringify(attribs, null, " ")}` );
}
} | javascript | {
"resource": ""
} |
q39734 | buildViewAttribsSpecial | train | function buildViewAttribsSpecial( attName, attValue, code ) {
const
type = attValue[ 0 ],
init = attValue[ 1 ];
let requireConverter = false;
try {
if ( typeof attValue.behind !== 'undefined' ) {
buildViewAttribsSpecialCodeBehind( attName, attValue.behind, code );
}
if ( typeof attValue.debug !== 'undefined' ) {
buildViewAttribsSpecialDebug( attName, attValue.debug, code );
}
if ( Array.isArray( type ) ) {
// Enumerate.
code.addCast( "enum" );
code.section.attribs.define.push(
"pm.create(" + JSON.stringify( attName ) +
`, { cast: conv_enum(${JSON.stringify(type)}), init: ${JSON.stringify(init)} });` );
buildViewAttribsInit( attName, init, code );
} else {
switch ( type ) {
case 'action':
code.actions.push( attName );
code.section.attribs.define.push(
"pm.createAction(" + JSON.stringify( attName ) + ")" );
break;
case 'any':
code.section.attribs.define.push(
"pm.create(" + JSON.stringify( attName ) + ");" );
buildViewAttribsInit( attName, init, code );
break;
case 'boolean':
case 'booleans':
case 'date':
case 'color':
case 'string':
case 'strings':
case 'array':
case 'list':
case 'intl':
case 'time':
case 'unit':
case 'units':
case 'multilang':
case 'validator':
requireConverter = true;
code.vars[ "conv_" + type ] = "Converters.get('" + type + "')";
code.section.attribs.define.push(
"pm.create(" + JSON.stringify( attName ) +
", { cast: conv_" + type + " });" );
buildViewAttribsInit( attName, init, code );
break;
case 'integer':
case 'float':
requireConverter = true;
code.vars[ "conv_" + type ] = "Converters.get('" + type + "')";
// Is Not a number, take this default value.
let nanValue = attValue.default;
if ( typeof nanValue !== 'number' || isNaN( nanValue ) ) {
nanValue = 0;
}
code.section.attribs.define.push(
"pm.create(" + JSON.stringify( attName ) +
", { cast: conv_" + type + "(" + nanValue + ") });" );
buildViewAttribsInit( attName, init, code );
break;
default:
throw "Unknown type \"" + type + "\" for attribute \"" + attName + "\"!";
}
}
if ( requireConverter ) {
code.requires.Converters = "require('tfw.binding.converters')";
}
} catch ( ex ) {
bubble(
ex,
`buildViewAttribsSpecial(${attName}: ${JSON.stringify(attValue)})`
);
}
} | javascript | {
"resource": ""
} |
q39735 | buildViewAttribsInit | train | function buildViewAttribsInit( attName, attValue, code ) {
try {
if ( typeof attValue === "undefined" ) {
// code.section.attribs.init.push(`this.${attName} = args[${JSON.stringify(attName)}];`);
code.section.attribs.init
.push( `pm.set("${attName}", args[${JSON.stringify(attName)}]);` );
} else {
code.functions.defVal = "(args, attName, attValue) " +
"{ return args[attName] === undefined ? attValue : args[attName]; }";
// code.section.attribs.init.push( "this." + attName + " = defVal(args, " +
// JSON.stringify( attName ) + ", " + JSON.stringify( attValue ) +
// ");" );
code.section.attribs.init
.push( `pm.set("${attName}", defVal(args, "${attName}", ${JSON.stringify( attValue )}));` );
}
} catch ( ex ) {
bubble(
ex,
`buildViewAttribsInit(${attName}, ${JSON.stringify(attValue)})`
);
}
} | javascript | {
"resource": ""
} |
q39736 | buildViewAttribsInitFire | train | function buildViewAttribsInitFire( attName, code ) {
try {
code.section.attribs.init
.push( `pm.fire("${attName}");` );
} catch ( ex ) {
bubble(
ex,
`buildViewAttribsInitFire(${attName})`
);
}
} | javascript | {
"resource": ""
} |
q39737 | buildFunction | train | function buildFunction( def, code, varName ) {
if ( isSpecial( def, "behind" ) ) {
const behindFunctionName = def[ 1 ];
code.addNeededBehindFunction( behindFunctionName );
code.that = true;
return [
"value => {",
" try {",
` CODE_BEHIND${keySyntax(behindFunctionName)}.call(that, value, ${varName});`,
" }",
" catch( ex ) {",
" console.error(`Exception in code behind \"" +
behindFunctionName + "\" of module \"" +
code.moduleName + "\": ${ex}`);",
" }",
"}"
];
}
if ( isSpecial( def, "toggle" ) ) {
const nameOfTheBooleanToToggle = def[ 1 ];
const namesOfTheBooleanToToggle = Array.isArray( nameOfTheBooleanToToggle ) ?
nameOfTheBooleanToToggle : [ nameOfTheBooleanToToggle ];
const body = namesOfTheBooleanToToggle
.map( name => `${getElemVarFromPath(name)} = !${getElemVarFromPath(name)};` );
return [
"() => {",
body,
"}"
];
}
throw Error( `Function definition expected, but found ${JSON.stringify(def)}!` );
} | javascript | {
"resource": ""
} |
q39738 | extractAttribs | train | function extractAttribs( def ) {
var key, val, attribs = { standard: {}, special: {}, implicit: [] };
for ( key in def ) {
val = def[ key ];
if ( RX_INTEGER.test( key ) ) {
attribs.implicit.push( val );
} else if ( RX_STD_ATT.test( key ) ) {
attribs.standard[ key ] = val;
} else {
attribs.special[ key ] = val;
}
}
return attribs;
} | javascript | {
"resource": ""
} |
q39739 | declareRootElement | train | function declareRootElement( def, code ) {
const rootElementName = buildElement( def, code );
code.section.elements.define.push( "//-----------------------" );
code.section.elements.define.push( "// Declare root element." );
code.section.elements.define.push(
"Object.defineProperty( this, '$', {",
[
`value: ${rootElementName}.$,`,
"writable: false, ",
"enumerable: false, ",
"configurable: false"
],
"});"
);
} | javascript | {
"resource": ""
} |
q39740 | outputAll | train | function outputAll( code, moduleName ) {
try {
let out = outputComments( code );
out += " module.exports = function() {\n";
out += outputNeededConstants( code );
out += ` //-------------------
// Class definition.
const ViewClass = function( args ) {
try {
if( typeof args === 'undefined' ) args = {};
this.$elements = {};
${outputClassBody(code)}
}
catch( ex ) {
console.error('${moduleName}', ex);
throw Error('Instantiation error in XJS of ${JSON.stringify(moduleName)}:\\n' + ex)
}
};\n`;
out += generate( code.section.statics, "Static members.", " " );
out += " return ViewClass;\n";
out += " }();\n";
return out;
} catch ( ex ) {
bubble( ex, "outputAll()" );
return null;
}
} | javascript | {
"resource": ""
} |
q39741 | outputComments | train | function outputComments( code ) {
try {
let out = '';
if ( code.section.comments.length > 0 ) {
out += ` /**\n * ${code.section.comments.join("\n * ")}\n */\n`;
}
return out;
} catch ( ex ) {
bubble( ex, "outputComments" );
return null;
}
} | javascript | {
"resource": ""
} |
q39742 | outputNeededConstants | train | function outputNeededConstants( code ) {
try {
let out = arrayToCodeWithNewLine( code.generateRequires(), " " );
out += arrayToCodeWithNewLine( code.generateNeededBehindFunctions(), " " );
out += arrayToCodeWithNewLine( code.generateFunctions(), " " );
out += arrayToCodeWithNewLine( code.generateGlobalVariables(), " " );
return out;
} catch ( ex ) {
bubble( ex, "outputNeededConstants" );
return null;
}
} | javascript | {
"resource": ""
} |
q39743 | outputClassBody | train | function outputClassBody( code ) {
try {
let out = '';
if ( code.that ) out += " const that = this;\n";
if ( code.pm ) out += " const pm = PM(this);\n";
out += generate( code.section.attribs.define, "Create attributes", " " );
out += generate( code.section.elements.define, "Create elements", " " );
out += generate( code.section.events, "Events", " " );
out += arrayToCodeWithNewLine( code.generateLinks(), " " );
out += generate( code.section.ons, "On attribute changed", " " );
out += generate( code.section.elements.init, "Initialize elements", " " );
out += generate( code.section.attribs.init, "Initialize attributes", " " );
if ( code.section.init ) {
out += " // Initialization.\n";
out += ` CODE_BEHIND.${code.section.init}.call( this );\n`;
}
out += " $.addClass(this, 'view', 'custom');\n";
return out;
} catch ( ex ) {
bubble( ex, "outputClassBody" );
return null;
}
} | javascript | {
"resource": ""
} |
q39744 | bubble | train | function bubble( ex, origin ) {
if ( typeof ex === 'string' ) {
throw Error( `${ex}\n...in ${origin}` );
}
throw Error( `${ex.message}\n...in ${origin}` );
} | javascript | {
"resource": ""
} |
q39745 | MongoStore | train | function MongoStore(uri, options) {
var self = this;
this.options = options || (options = {});
options.collectionName = options.collectionName || 'sessions';
// 1 day
options.ttl = options.ttl || 24 * 60 * 60 * 1000;
// 60 s
options.cleanupInterval = options.cleanupInterval || 60 * 1000;
options.server = options.server || {};
options.server.auto_reconnect = options.server.auto_reconnect != null ? options.server.auto_reconnect : true;
this._error = function(err) {
if (err) { self.emit('error', err); }
};
// It's a Db instance.
if (uri.collection) {
this.db = uri;
this._setup();
} else {
MongoClient.connect(uri, options, function(err, db) {
if (err) { return self._error(err); }
self.db = db;
self._setup();
});
}
} | javascript | {
"resource": ""
} |
q39746 | Message | train | function Message(message, headers, deliveryInfo, obj) {
// Crane uses slash ('/') separators rather than period ('.')
this.topic = deliveryInfo.routingKey.replace(/\./g, '/');
this.headers = headers;
if (deliveryInfo.contentType) { this.headers['content-type'] = deliveryInfo.contentType; }
if (Buffer.isBuffer(message.data)) {
this.data = message.data;
} else {
this.body = message;
}
this.__msg = obj;
} | javascript | {
"resource": ""
} |
q39747 | train | function(processingQueue, phase) {
var that = this;
verbose && console.log('phase is: ' + phase, processors);
processingQueue.forEach(function(context) {
var processor = processors[phase][context.fileType];
verbose && console.log('runProcessor with ', that, context );
context.graph = processor.apply(that, [context]);
});
return that;
} | javascript | {
"resource": ""
} | |
q39748 | getRoomSlots | train | function getRoomSlots (semester, minRequestSpace = 1000, verbose = false, departments = []) {
validateInput("semester", semester, [1, 2], "set");
validateInput("minRequestSpace", minRequestSpace, [0, 100000], "range");
validateInput("verbose", verbose, [true, false], "set");
validateInput("departments", departments, "Array", "type");
return scrapeRS(semester, verbose, minRequestSpace, departments);
} | javascript | {
"resource": ""
} |
q39749 | getHours | train | function getHours (verbose = false, minRequestSpace = 500) {
validateInput("verbose", verbose, [true, false], "set");
validateInput("minRequestSpace", minRequestSpace, [0, 100000], "range");
return scrapeBuildings(verbose, minRequestSpace);
} | javascript | {
"resource": ""
} |
q39750 | validateInput | train | function validateInput(inputName, input, acceptableValues, acceptableValueType) {
let validInput = true;
if (acceptableValueType == "range") {
if (input < Math.min(...acceptableValues) || input > Math.max(...acceptableValues)) {
validInput = false;
}
} else if (acceptableValueType == "set") {
if (acceptableValues.indexOf(input) == -1) {
validInput = false;
}
} else if (acceptableValueType == "type") {
if (!typeof input == acceptableValues) {
validInput = false;
}
}
if (!validInput) {
throw(`Invalid ${inputName} given, valid options are: ${acceptableValues}`);
}
} | javascript | {
"resource": ""
} |
q39751 | parseLine | train | function parseLine(line, lineno, options) {
let command = null;
const lineContinuationRegex = (options && options.lineContinuationRegex
|| TOKEN_LINE_CONTINUATION);
line = line.trim();
if (!line) {
// Ignore empty lines
return { command: null, remainder: '' };
}
if (isComment(line)) {
// Handle comment lines.
command = { name: 'COMMENT', args: line, lineno: lineno };
return { command: command, remainder: '' };
}
if (line.match(lineContinuationRegex)) {
// Line continues on next line.
const remainder = line.replace(lineContinuationRegex, '', 'g');
return { command: null, remainder: remainder };
}
command = splitCommand(line);
command.lineno = lineno;
let commandParserFn = commandParsers[command.name];
if (!commandParserFn) {
// Invalid Dockerfile instruction, but allow it and move on.
// log.debug('Invalid Dockerfile command:', command.name);
commandParserFn = parseString;
}
if (commandParserFn(command)) {
// Successfully converted the arguments.
command.raw = line;
delete command.rest;
}
return { command: command, remainder: '' };
} | javascript | {
"resource": ""
} |
q39752 | dig | train | function dig(obj) {
var iterateeFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (val, key, iterableParent) {
return val;
};
// eslint-disable-line no-unused-vars
// modifierFn = v => v,
return (0, _each2.default)(obj, function iterator(itValue, key, itObj) {
var processedItValue = itValue;
// console.log("processedItValue (before)", processedItValue)
if ((0, _is.isIterable)(itValue, { objects: true })) {
// console.log("Is iterable, key:", key)
processedItValue = (0, _each2.default)(itValue, iterator); // , iterateeFn
}
var iterateeReturnedValue = iterateeFn(processedItValue, key, itObj);
// console.log("iterateeReturnedValue", iterateeReturnedValue)
if ((0, _is.isObject)(iterateeReturnedValue) && (0, _is.isLength)((0, _toKeys2.default)(iterateeReturnedValue), 1) && (0, _get2.default)(iterateeReturnedValue, "$remove", false) === true) {
return { $remove: true };
} else if ((0, _is.isDefined)(iterateeReturnedValue)) {
return iterateeReturnedValue;
} else {
// console.log("processedItValue (after)", processedItValue)
return processedItValue;
}
}
//, iterateeFn
);
} | javascript | {
"resource": ""
} |
q39753 | train | function (bbsource) {
var parts = {
Header: '',
Setup: '// Initial Setup',
Events: '// Backbone.Events',
Model: '// Backbone.Model',
Collection: '// Backbone.Collection',
Router: '// Backbone.Router',
History: '// Backbone.History',
View: '// Backbone.View',
Sync: '// Backbone.sync',
Helpers: '// Helpers'
};
// index & module helper
var lastPos = 0;
var temp = 0;
var keys = Object.keys(parts);
// extract every module
keys.forEach(function (key, idx) {
temp = typeof keys[idx + 1] !== 'undefined' ? bbsource.search(parts[keys[idx + 1]]) : bbsource.length;
parts[key] = extract(bbsource, lastPos, temp);
lastPos = temp;
});
return parts;
} | javascript | {
"resource": ""
} | |
q39754 | train | function (combinations, parts, backboneSrc) {
var src = '';
var allCombinations = [];
parts.forEach(function (part) {
allCombinations.push(combinations[_.str.capitalize(part.toLowerCase())]);
});
var neededParts = _.union.apply(_, allCombinations);
var backboneParts = getBackboneParts(backboneSrc);
var finalCombination = _.intersection(combinations.All, neededParts);
finalCombination.forEach(function (part) {
src += backboneParts[_.str.capitalize(part.toLowerCase())];
if (part.toLowerCase() === 'view') {
src = src.replace('Model.extend = Collection.extend = Router.extend = View.extend = extend;', '');
}
});
var extender = '';
if(!_.contains(finalCombination, 'View') && !_.contains(finalCombination, 'view')) {
extender += ' var extend = function (protoProps, classProps) {\n';
extender += ' var child = inherits(this, protoProps, classProps)\n';
extender += ' child.extend = this.extend;\n';
extender += ' return child;\n';
extender += ' };\n\n';
}
// add the extend chain
finalCombination.forEach(function (extendo) {
var lowerEx = extendo.toLowerCase();
if (lowerEx === 'model') {
extender += 'Model.extend = ';
}
if (lowerEx === 'collection') {
extender += 'Collection.extend = ';
}
if (lowerEx === 'router') {
extender += 'Router.extend = ';
}
if (lowerEx === 'view') {
extender += 'View.extend = ';
}
});
extender += 'extend;';
src = src.replace('// Helpers', extender + '\n\n // Helpers');
return src;
} | javascript | {
"resource": ""
} | |
q39755 | namedLevelStore | train | function namedLevelStore (name) {
assert.equal(typeof name, 'string', 'named-level-store: name should be a string')
const location = path.join(process.env.HOME, '.leveldb', name)
mkdirp.sync(location)
const db = level(location)
db.location = location
return db
} | javascript | {
"resource": ""
} |
q39756 | removeSrcDirPrefixFromFile | train | function removeSrcDirPrefixFromFile( srcDir, file ) {
if ( typeof srcDir !== 'string' ) return file;
if ( typeof file !== 'string' ) return file;
if ( file.substr( 0, srcDir.length ) !== srcDir ) {
return file;
}
return file.substr( srcDir.length );
} | javascript | {
"resource": ""
} |
q39757 | train | function (value) {
if (value === null) {
return '';
}
if (value === undefined) {
return '';
}
switch (typeof value) {
case 'object' :
if (value instanceof Blob) {
return value;
} else {
return JSON.stringify(value);
}
break;
case 'string':
return value;
default :
return value;
}
} | javascript | {
"resource": ""
} | |
q39758 | createConfig | train | async function createConfig(optionsArgs) {
const options = {
...DEFAULT_OPTIONS,
...optionsArgs,
};
const { rules, base } = options;
const config = {
...base,
rules: base.rules || {},
};
return Object.keys(config)
.reduce(async (collection, key) => {
const previous = await collection;
if (key === 'rules') {
const combinedRules = await combineRules(rules);
return {
...previous,
rules: {
...combinedRules,
...config.rules,
},
};
}
return {
...previous,
[key]: config[key],
};
}, Promise.resolve({}));
} | javascript | {
"resource": ""
} |
q39759 | SimpleCommand | train | function SimpleCommand(exec, args, workdir) {
this.exec = /^win/.test(process.platform) ? findWindowsExec(exec) : exec;
this.args = args;
this.workdir = workdir;
this.setOptions();
this.commandLine = util.format('%s %s', this.exec, this.args.join(' '));
} | javascript | {
"resource": ""
} |
q39760 | train | function() {
var items = _utils.getArgArray(arguments);
if (items.length === 0) {
throw new Error('no folders specified to create');
}
items.forEach(function(item) {
try {
_fs.mkdirSync(item);
} catch (e) {
// Eat the exception.
}
});
} | javascript | {
"resource": ""
} | |
q39761 | train | function() {
var items = _utils.getArgArray(arguments);
if (items.length === 0) {
throw new Error('no files specified to create');
}
items.forEach(function(item) {
var contents;
var linkTarget;
var filePath;
if (typeof item === 'object') {
filePath = item.path;
contents = item.contents || '';
linkTarget = item.linkTo;
} else if (typeof item === 'string') {
filePath = item;
contents = '';
}
if (typeof filePath !== 'string' || filePath.length === 0) {
throw new Error('file path not specified');
}
contents = contents || '';
try {
if (!!linkTarget) {
_fs.symlinkSync(linkTarget, filePath);
} else {
_fs.writeFileSync(filePath, contents);
}
} catch (e) {
// Eat the exception.
}
});
} | javascript | {
"resource": ""
} | |
q39762 | train | function() {
var items = _utils.getArgArray(arguments);
if (items.length === 0) {
throw new Error('no files specified to clean up');
}
items.forEach(function(item) {
try {
var path = (typeof item === 'string') ? item : item.path;
_fs.unlinkSync(path);
} catch (e) {
// Eat the exception.
}
});
} | javascript | {
"resource": ""
} | |
q39763 | train | function(options) {
// Ensure an instance is created
if (!(this instanceof TimeChunkedStream)) {
return new TimeChunkedStream(options);
}
// Always decode strings
options.decodeStrings = true;
// Initialize base class
Transform.call(this, options);
// Create internal buffer
this._buffer = new BufferBuilder();
this._timeout = options.timeout;
this._timer = null;
} | javascript | {
"resource": ""
} | |
q39764 | linkBootstrap | train | function linkBootstrap() {
fs.symlink(bootstrap, path.resolve(yeoman, 'bootstrap-less'), 'dir', function(err) {
if (err) return console.log('symlink error:', err);
return console.log('Successfully installed yeoman-bootstrap in', bootstrap,
' and created a symlink in', yeoman);
});
} | javascript | {
"resource": ""
} |
q39765 | toPropertyNamesArray | train | function toPropertyNamesArray(propertyNamesString, separator) {
return propertyNamesString.split(separator || PROPERTY_NAME_SEPARATOR).map(s => trim(s)).filter(s => !!s);
} | javascript | {
"resource": ""
} |
q39766 | linsert | train | function linsert(key, beforeAfter, pivot, value, req) {
var val = this.getKey(key, req);
if(val === undefined) return 0;
return val.linsert(beforeAfter, pivot, value);
} | javascript | {
"resource": ""
} |
q39767 | lindex | train | function lindex(key, index, req) {
var val = this.getKey(key, req);
if(!val) return null;
return val.lindex(index);
} | javascript | {
"resource": ""
} |
q39768 | lpush | train | function lpush(key /*value-1, value-N, req*/) {
var val = this.getKey(key, req)
, args = slice.call(arguments, 1)
, req;
if(typeof args[args.length - 1] === 'object') {
req = args.pop();
}
if(val === undefined) {
val = new List();
this.setKey(key, val, undefined, undefined, undefined, req);
}
return val.lpush(args);
} | javascript | {
"resource": ""
} |
q39769 | lpushx | train | function lpushx(key, value, req) {
var val = this.getKey(key, req);
if(val === undefined) {
return 0;
}
return val.lpush([value]);
} | javascript | {
"resource": ""
} |
q39770 | rpushx | train | function rpushx(key, value, req) {
var val = this.getKey(key, req);
if(val === undefined) {
return 0;
}
return val.rpush([value]);
} | javascript | {
"resource": ""
} |
q39771 | lpop | train | function lpop(key, req) {
var val = this.getKey(key, req);
if(val === undefined) return null;
var element = val.lpop();
if(val.llen() === 0) {
this.delKey(key, req);
}
return element;
} | javascript | {
"resource": ""
} |
q39772 | lrem | train | function lrem(key, count, value, req) {
var val = this.getKey(key, req);
if(val === undefined) return 0;
var deleted = val.lrem(count, value);
if(val.llen() === 0) {
this.delKey(key, req);
}
return deleted;
} | javascript | {
"resource": ""
} |
q39773 | ltrim | train | function ltrim(key, start, stop, req) {
var val = this.getKey(key, req);
if(val === undefined) return null;
val.ltrim(start, stop);
if(val.llen() === 0) {
this.delKey(key, req);
}
return OK;
} | javascript | {
"resource": ""
} |
q39774 | lrange | train | function lrange(key, start, stop, req) {
var val = this.getKey(key, req);
if(val === undefined) return null;
return val.lrange(start, stop);
} | javascript | {
"resource": ""
} |
q39775 | llen | train | function llen(key, req) {
var val = this.getKey(key, req);
if(val === undefined) return 0;
return val.llen();
} | javascript | {
"resource": ""
} |
q39776 | processToken | train | function processToken(token, done) {
var user = _.find(users, function (item) {
return item.username === token[claims.username];
});
if (!user) {
user = {
id : token[claims.id] || currId++,
username : token[claims.username],
email : token[claims.email],
firstName : token[claims.firstName],
lastName : token[claims.lastName]
};
var roles = token[claims.role];
if (!roles) {
roles = ["guest"];
} else if (!(roles instanceof Array)) {
roles = [roles];
}
user.roles = roles;
users.push(user);
}
done(null, user);
} | javascript | {
"resource": ""
} |
q39777 | train | function (options) {
winston.Transport.call(this, options);
options = options || {};
var apiKey = options.apiKey;
var projectId = options.projectId;
var apiHostName = options.apiHostName;
var formatter = options.formatter || 'kvp';
if (!apiKey || !projectId || !apiHostName) {
throw new Error('apiKey, projectId and apiHostName are neccessary');
}
this._storm = new SplunkStorm({
apiKey: apiKey,
projectId: projectId,
apiHostName: apiHostName,
formatter: formatter
});
this._sourceType = options.sourceType || 'syslog';
this._source = options.source || '';
this._host = options.host || os.hostname();
this._options = options;
} | javascript | {
"resource": ""
} | |
q39778 | stringify | train | function stringify(js, indent, indentUnit) {
if (typeof indent === 'undefined') indent = '';
if (typeof indentUnit === 'undefined') indentUnit = ' ';
var t = typeof js;
if (t === 'string') {
return JSON.stringify(js);
}
if (t === 'number') {
return js;
}
if (t === 'boolean') {
return js ? "true" : "false";
}
var out = '', txt, small, lastIndent;
if (Array.isArray(js)) {
out = '[';
txt = JSON.stringify(js);
small = txt.length < 40;
if (!small) out += "\n" + indent;
js.forEach(
function(itm, idx) {
if (idx > 0) {
out += "," + (small ? " " : "\n" + indent);
}
out += stringify(itm, indent + indentUnit);
}
);
out += ']';
return out;
}
if (t === 'object') {
lastIndent = indent;
indent += indentUnit;
out = '{';
txt = JSON.stringify(js);
small = txt.length < 40;
if (!small) out += "\n" + indent;
var k, v, idx = 0;
for (k in js) {
v = js[k];
if (idx > 0) {
out += "," + (small ? " " : "\n" + indent);
}
out += JSON.stringify(k) + ": " + stringify(v, indent);
idx++;
}
out += (small ? "" : "\n" + lastIndent) + '}';
return out;
}
return '"<' + t + '>"';
} | javascript | {
"resource": ""
} |
q39779 | main | train | function main (action, argv, options) {
options = options || {}
const cli = new CliDispatch(action, options.actions || 'actions', options.base || callersDir())
setImmediate(() => cli.dispatch(argv))
return cli
} | javascript | {
"resource": ""
} |
q39780 | lookup | train | function lookup (action, options) {
options = options || {}
const cli = new CliDispatch(action, options.actions || 'actions', options.base || callersDir())
return cli.lookup()
} | javascript | {
"resource": ""
} |
q39781 | CliDispatch | train | function CliDispatch (action, dir, baseDir) {
this.action = action
this.dir = dir
this.baseDir = baseDir
} | javascript | {
"resource": ""
} |
q39782 | getCliendIdFromCert | train | function getCliendIdFromCert() {
var x509 = require('x509');
var certJson = x509.parseCert(fs.readFileSync(process.cwd()+Constant.CERTIFICATE_PATH).toString());
var cliendId = cert && cert.subject && cert.subject.commonName;
return clientId;
} | javascript | {
"resource": ""
} |
q39783 | verifyPermission | train | function verifyPermission(appId,uaaCredential) {
var deferred = Q.defer();
var cloudControllerUrl = process.env.cloudControllerUrl;
if (!cloudControllerUrl) {
var errMsg = "The system variable 'cloudControllerUrl' is missing.";
ibmlogger.getLogger().error(errMsg);
deferred.reject({code:Constant.MISSING_CLOUDCONTROLLERURL_ERROR,message:errMsg});
return;
}
if (cloudControllerUrl[cloudControllerUrl.length-1]!='/') {
cloudControllerUrl += '/';
}
cloudControllerUrl += 'v2/apps/'+appId+'/summary';
var requestOptions = {url: cloudControllerUrl,headers: {'Authorization': uaaCredential}};
request.get(requestOptions, function(error,response,body){
if (error || response.statusCode != 200) {
var errMsg = error?"["+error+"]":"["+response.statusCode+":"+body+"] Access Url '"+requestUrl+"' failed";
ibmlogger.getLogger().error(errMsg);
return deferred.reject(false);
}
else {
return deferred.resolve(true);
}
});
return deferred.promise;
} | javascript | {
"resource": ""
} |
q39784 | getOAuthAccessToken | train | function getOAuthAccessToken(appId,clientId,imfCert,properties) {
var deferred = Q.defer();
var imfServiceUrl = process.env.imfServiceUrl;
var requestUrl = imfServiceUrl+"/authorization/v1/apps/"+appId+"/token";
var requestOptions = {url: requestUrl,headers: {'Authorization': 'IMFCert '+imfCert}, form:{'grant_type':'client_credentials','client_id':clientId,'properties':properties}};
request.post(requestOptions, function(error,response,body){
if (error || response.statusCode != 200) {
requestUrl = requestUrl ? requestUrl : "";
body = body ? body : "";
var errMsg = error?"["+error+"]":"["+response.statusCode+":"+body+"] Generate IMF Token from '"+requestUrl+"' failed.";
ibmlogger.getLogger().error(errMsg);
return deferred.reject({code:Constant.TOKEN_GENERATE_ERROR,message:errMsg});
}
else {
var tokenJson = Util.getJson(body);
return deferred.resolve(tokenJson);
}
});
return deferred.promise;
} | javascript | {
"resource": ""
} |
q39785 | CommandLine | train | function CommandLine(commands) {
this.keys = Object.keys(commands);
this.commands = commands;
this.args = process.argv.slice(2);
this.context = this.args[0] || null;
this.help = {
before: '',
after: ''
}
} | javascript | {
"resource": ""
} |
q39786 | padString | train | function padString(str, len) {
return str.split().concat(new Array(len-str.length)).join(' ');
} | javascript | {
"resource": ""
} |
q39787 | train | function () {
if (this.options.switchRowsAndColumns) {
this.columns = this.rowsToColumns(this.columns);
}
// Interpret the info about series and columns
this.getColumnDistribution();
// Interpret the values into right types
this.parseTypes();
// Handle columns if a handleColumns callback is given
if (this.parsed() !== false) {
// Complete if a complete callback is given
this.complete();
}
} | javascript | {
"resource": ""
} | |
q39788 | train | function (str, inside) {
if (typeof str === 'string') {
str = str.replace(/^\s+|\s+$/g, '');
// Clear white space insdie the string, like thousands separators
if (inside && /^[0-9\s]+$/.test(str)) {
str = str.replace(/\s/g, '');
}
if (this.decimalRegex) {
str = str.replace(this.decimalRegex, '$1.$2');
}
}
return str;
} | javascript | {
"resource": ""
} | |
q39789 | doAction | train | function doAction() {
var now = (new Date()).getTime();
var diff = now - lastTapTime;
var isDiffElemSafeDelay = elem !== lastElemTapped && diff > 200;
var isSameElemSafeDelay = elem === lastElemTapped && diff > sameElemSafeDelay;
if (tapped && (isDiffElemSafeDelay || isSameElemSafeDelay)) {
lastElemTapped = elem;
lastTapTime = now;
safeApply(action, scope);
}
// reset tapped at end
tapped = false;
} | javascript | {
"resource": ""
} |
q39790 | getComparator | train | function getComparator(sortOrder) {
if (typeof sortOrder === 'function') {
return sortOrder;
}
const comparators = {
[ASC]: ascendingSort,
[DESC]: descendingSort,
[ASC_LENGTH]: lengthSort,
[DESC_LENGTH]: lengthReverseSort
};
return comparators[sortOrder];
} | javascript | {
"resource": ""
} |
q39791 | stripAndSerializeComment | train | function stripAndSerializeComment( lineNumber, sourceStr ) {
// Strip comment delimiter tokens
let stripped = sourceStr
.replace( patterns.commentBegin, '' )
.replace( patterns.commentEnd, '' )
.split( '\n' )
.map( line => line.replace( rCommentLinePrefix, '' ) );
// Determine the number of leading spaces to strip
const prefixSpaces = stripped.reduce( function ( accum, line ) {
if ( !accum.length && line.match( /\s*\S|\n/ ) ) {
accum = line.match( /\s*/ )[0];
}
return accum;
});
// Strip leading spaces
stripped = stripped.map( line => line.replace( prefixSpaces, '' ) );
// Get line number for first tag
const firstTagLineNumber = stripped.reduce( function ( accum, line, index ) {
if ( isNaN( accum ) && line.match( rTagName ) ) {
accum = index;
}
return accum;
}, undefined );
const comment = stripped.join( '\n' ).trim();
const tags = stripped.splice( firstTagLineNumber ).join( '\n' );
const preface = stripped.join( '\n' ).trim();
return {
preface,
content: comment,
tags: serializeTags( lineNumber + firstTagLineNumber, tags )
};
} | javascript | {
"resource": ""
} |
q39792 | serializeTags | train | function serializeTags( lineNumber, tags ) {
return tags.split( /\n/ )
.reduce( function ( acc, line, index ) {
if ( !index || rTagName.test( line ) ) {
acc.push( `${line}\n` );
}
else {
acc[ acc.length - 1 ] += `${line}\n`;
}
return acc;
}, [] )
.map( function ( block ) {
const trimmed = block.trim();
const tag = block.match( rTagName )[0];
const result = {
line: lineNumber,
tag: tag.replace( patterns.tagPrefix, '' ),
value: trimmed.replace( tag, '' ).replace( rLeadSpaces, '' ),
valueParsed: [],
source: trimmed
};
lineNumber = lineNumber + getLinesLength( block );
return result;
})
.map( function ( tag ) {
const parser = parsers[ tag.tag ];
if ( parser ) {
try {
tag.valueParsed = parser( tag.value );
}
catch ( err ) {
tag.error = err;
}
}
return tag;
});
} | javascript | {
"resource": ""
} |
q39793 | StubServer | train | function StubServer(app) {
_classCallCheck(this, StubServer);
this._app = app;
app.createServer = this.createServer_.bind(this, app.createServer || function () { throw new Error("no registered transport provider"); });
} | javascript | {
"resource": ""
} |
q39794 | getValueAt | train | function getValueAt(dataObject, path)
{
if (_.isUndefined(dataObject)) {
return undefined;
}
if (!_.isString(path)) {
return dataObject;
}
var tokens = path.split('.');
var property = tokens[0];
var subpath = tokens.slice(1).join('.');
var data = dataObject[property];
if (tokens.length > 1 && !_.isUndefined(data))
{
return getValueAt(data, subpath);
} else {
return data;
}
} | javascript | {
"resource": ""
} |
q39795 | matchGroups | train | function matchGroups(groupsConfig, wantedGroups)
{
var defaultGroups = ['default'];
var groups = _.map([groupsConfig, wantedGroups], function(grp) {
if (_.isUndefined(grp)) {
return defaultGroups;
} else if (_.isString(grp)) {
return [grp];
} else if (_.isArray(grp)) {
return grp;
}else if (_.isFunction(grp)) {
var r = grp();
if (_.isString(r)) {
return [r];
} else if (_.isArray(r)) {
return r;
}
}
return defaultGroups;
});
return _.intersection(groups[0], groups[1]).length > 0;
} | javascript | {
"resource": ""
} |
q39796 | RulesConfigurationError | train | function RulesConfigurationError(message, path)
{
var self = new Error();
self.path = path;
self.message = "Rules configuration error : "+message+(path ? " at path : "+path : "");
self.name = 'RulesConfigurationError';
self.__proto__ = RulesConfigurationError.prototype;
return self;
} | javascript | {
"resource": ""
} |
q39797 | train | function(path, fieldValue, errors, errorsContent)
{
var e = {};
var er = {};
if (_.isArray(errors) && errors.length > 0) {
er.errors = errors;
}
if (_.isArray(errorsContent) && errorsContent.length > 0) {
er.content = errorsContent;
}
var self = new Error();
self.__proto__ = FieldValidatorError.prototype;
self.message = er;
self.name = 'FieldValidatorError';
self.path = path;
self.fieldValue = fieldValue;
self.errors = errors || [];
self.errorsContent = errorsContent || [];
return self;
} | javascript | {
"resource": ""
} | |
q39798 | FieldValidator | train | function FieldValidator(rules, config)
{
this.rules = rules;
this.fieldLabel = undefined;
if (config) {
this.setConfig(config);
}
} | javascript | {
"resource": ""
} |
q39799 | Validator | train | function Validator(type, config)
{
this.type = type;
this.message = undefined;
this.value = undefined;
this.groups = undefined;
this.fieldValidator = undefined;
this.parent = undefined;
if (typeof(config) === 'object') {
this.groups = config.groups;
if (_.has(config, 'message'))
this.message = config.message;
if (_.has(config, 'value') && !_.isUndefined(config.value))
this.value = config.value;
} else if (!_.isUndefined(config)) {
this.value = config;
}
return this;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.