_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q43000 | init | train | function init (directory, callback) {
var source = path.join(__dirname, 'template');
ncp(source, directory, callback);
} | javascript | {
"resource": ""
} |
q43001 | start | train | function start (outputFunction) {
startTime = new Date()
failures = []
count = 0
stats = {success: 0, failure: 0, skipped: 0}
log = outputFunction || log
} | javascript | {
"resource": ""
} |
q43002 | result | train | function result (type, error) {
if (count % 40 === 0) {
log('\n ')
}
count++
stats[type]++
log(SYMBOLS[type] + ' ')
if (type === 'failure') {
failures.push(error)
}
} | javascript | {
"resource": ""
} |
q43003 | end | train | function end () {
var diff = new Date() - startTime
log('\n\n')
log(' ' + SYMBOLS.success + ' ' + (stats.success + ' passing ').green)
log(('(' + diff + 'ms)').grey)
if (stats.skipped) {
log('\n ' + SYMBOLS.skipped + ' ' + (stats.skipped + ' pending').cyan)
}
if (stats.failure) {
log('\n ' +... | javascript | {
"resource": ""
} |
q43004 | logError | train | function logError (failure, index) {
index = index + 1
if (index > 1) {
log('\n\n')
}
log(' ' + index + ') ' + failure.description + ': ')
if (failure.environment) {
log(('(' + failure.environment + ')').grey)
}
log('\n\n')
// Log the actual error message / stack trace / diffs
var intend... | javascript | {
"resource": ""
} |
q43005 | intendLines | train | function intendLines (string, trim, intend) {
var intendStr = new Array(intend + 1).join(' ')
return string
.split('\n')
.map(function (s) {
return trim ? s.trim() : s
})
.join('\n')
.replace(/^/gm, intendStr)
} | javascript | {
"resource": ""
} |
q43006 | registerComponents | train | function registerComponents (newComponents) {
var config = Vue$2.config;
var newConfig = {};
if (Array.isArray(newComponents)) {
newComponents.forEach(function (component) {
if (!component) {
return
}
if (typeof component === 'string') {
components[component] = true;
... | javascript | {
"resource": ""
} |
q43007 | ensureLogsRotated | train | function ensureLogsRotated(stats){
// TODO: other writes should wait until this is done
var today = new Date(),
modifiedDate = new Date(stats.mtime),
archivedFileName;
if(!_logDatesMatch(today, modifiedDate)){
archivedFileName = _createRotatedLogName(this.config.path, modifiedDate);... | javascript | {
"resource": ""
} |
q43008 | _logDatesMatch | train | function _logDatesMatch(d1, d2){
return ((d1.getFullYear()===d2.getFullYear())&&(d1.getMonth()===d2.getMonth())&&(d1.getDate()===d2.getDate()));
} | javascript | {
"resource": ""
} |
q43009 | _createRotatedLogName | train | function _createRotatedLogName(logPath, modifiedDate){
var logName = logPath,
suffixIdx = logPath.lastIndexOf('.'),
suffix = '';
if(suffixIdx > -1){
suffix = logName.substr(suffixIdx, logName.length);
logName = logName.replace(
suffix, ('.' +
modified... | javascript | {
"resource": ""
} |
q43010 | getStackTraceArray | train | function getStackTraceArray() {
var origStackTraceLimit = Error.stackTraceLimit
var origPrepareStackTrace = Error.prepareStackTrace
// Collect all stack frames.
Error.stackTraceLimit = Infinity
// Get a structured stack trace as an `Array` of `CallSite` objects, each of which represents a stack frame, with ... | javascript | {
"resource": ""
} |
q43011 | writeToProcessStream | train | function writeToProcessStream(processStreamName, string) {
var writableStream = process[processStreamName]
if (writableStream) {
writableStream.write(string + '\n')
} else {
throw new Error('Unrecognized process stream: ' + exports.stylize(processStreamName))
}
} | javascript | {
"resource": ""
} |
q43012 | prettify | train | function prettify(args, options) {
if (!options) {
options = {}
}
var stylizeOptions = {
// Number of times to recurse while formatting; defaults to 2.
depth: options.depth,
// Format in color if the terminal supports color.
colors: exports.colors.supportsColor,
}
// Use `RegExp()` to ge... | javascript | {
"resource": ""
} |
q43013 | stringifyStackFrame | train | function stringifyStackFrame(stackFrame, label) {
var frameString = stackFrame.toString()
// Colorize function name (or `label`, if provided).
var lastSpaceIndex = frameString.lastIndexOf(' ')
if (lastSpaceIndex !== -1) {
return exports.colors.cyan(label || frameString.slice(0, lastSpaceIndex)) + frameStri... | javascript | {
"resource": ""
} |
q43014 | ProcessWatcher | train | function ProcessWatcher(pid, parent) {
var self = this;
this.dead = false;
// check first if process is alive
if (exports.alive(pid) === false) {
process.nextTick(function () {
self.dead = true;
self.emit('dead');
});
return self;
}
// use disconnect to detec... | javascript | {
"resource": ""
} |
q43015 | validate | train | function validate (config) {
/** Make sure the config object was passed. */
if (!config) {
throw new TypeError('Missing configuration object.');
}
/** Make sure the panic url is provided. */
if (typeof config.panic !== 'string') {
throw new TypeError('Panic server URL "config.panic" not provided.');
}
/**... | javascript | {
"resource": ""
} |
q43016 | Manager | train | function Manager (remote) {
/** Allow usage without `new`. */
if (!(this instanceof Manager)) {
return new Manager(remote);
}
/**
* @property {Boolean} isRemote
* Whether the manager is remote.
*/
this.isRemote = false;
/**
* @property {Socket} socket
* A socket.io instance, or `null` if using loca... | javascript | {
"resource": ""
} |
q43017 | recent | train | function recent(views, options) {
options = options || {};
var prop = options.prop || 'data.date';
var limit = options.limit || 10;
var res = {};
for (var key in views) {
if (views.hasOwnProperty(key)) {
var date = createdDate(key, views[key], prop);
res[date] = res[date] || [];
res[da... | javascript | {
"resource": ""
} |
q43018 | createdDate | train | function createdDate(key, value, prop) {
var val = prop ? get(value, prop) : value;
var str = val || key;
var re = /^(\d{4})-(\d{2})-(\d{2})/;
var m = re.exec(str);
if (!m) return null;
return String(m[1]) + String(m[2]) + String(m[3]);
} | javascript | {
"resource": ""
} |
q43019 | printError | train | function printError(error) {
process.stderr.write(red);
console.error(error.trace);
process.stderr.write(yellow);
console.error('an error occurred, please file an issue');
process.stderr.write(reset);
process.exit(1);
} | javascript | {
"resource": ""
} |
q43020 | routes | train | function routes(app) {
this.app = app;
var seminarjs = this;
app.get('/version', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({
'name': seminarjs.get('name'),
'seminarjsVersion': seminarjs.version
}));
});
return this;
} | javascript | {
"resource": ""
} |
q43021 | getSimiliarString | train | function getSimiliarString(base, relation) {
var length = Math.round(base.length * relation),
r = '',
i, str
do {
str = getRandomString(base.length - length)
} while (str && str[0] === base[length])
for (i = 0; i < length; i++) {
r += base[i] // substr(...) seems to be optimized
}
return r + str
} | javascript | {
"resource": ""
} |
q43022 | compare | train | function compare(a, b, n) {
var n2 = n,
then = Date.now()
while (n2--) {
a === b
}
return (Date.now() - then) * 1e6 / n
} | javascript | {
"resource": ""
} |
q43023 | constantCompare | train | function constantCompare(a, b, n) {
var n2 = n,
then = Date.now(),
eq = false,
len, i
while (n2--) {
len = Math.max(a.length, b.length)
for (i = 0; i < len; i++) {
if (a.length >= i && b.length >= i && a[i] !== b[i]) {
eq = false
}
}
}
return (Date.now() - then) * 1e6 / n
} | javascript | {
"resource": ""
} |
q43024 | stat | train | function stat(fn, n) {
var n2 = n,
times = [],
sum = 0,
t, avg, median
while (n2--) {
t = fn()
sum += t
times.push(t)
}
avg = sum / n
times.sort(function (a, b) {
return a - b
})
median = times[Math.floor(times.length / 2)]
if (times.length % 2 === 0) {
median = (median + times[times.length / 2 ... | javascript | {
"resource": ""
} |
q43025 | merge | train | function merge() {
var res = {};
for (var i = 0; i < arguments.length; i++) {
if (arguments[i]) {
Object.assign(res, arguments[i]);
} else {
if (typeof arguments[i] === 'undefined') {
throw new Error('m(): argument ' + i + ' undefined');
}
}
}
return res;
} | javascript | {
"resource": ""
} |
q43026 | publish | train | function publish(opts) {
// stream options
var defaults = {
enableResolve: false,
directory: './build',
debug: false
};
var options = utils.shallowMerge(opts, defaults);
return through(function(file, enc, callback) {
if (file.isNull()) return callback(null, file);
// emit error event whe... | javascript | {
"resource": ""
} |
q43027 | multiple | train | function multiple(pool, fn, queries, callback) {
let queryObjects = queries.map(query => {
if (typeof query === 'string') {
return { text: query, values: [] };
}
return Object.assign({ values: [] }, query);
});
if (callback && typeof callback === 'function') {
return fn(pool, queryObjects,... | javascript | {
"resource": ""
} |
q43028 | normalize | train | function normalize(args) {
let result = {
queries: null,
callback: null
};
if (args.length === 1 && Array.isArray(args[0])) {
result.queries = args[0];
} else if (args.length === 2 && Array.isArray(args[0])) {
result.queries = args[0];
if (typeof args[1] === 'function') {
result.cal... | javascript | {
"resource": ""
} |
q43029 | performParallel | train | function performParallel(pool, queries, callback) {
let count = 0,
results = new Array(queries.length);
queries.forEach((query, index) => {
pool.query(query, (error, result) => {
if (error) {
return callback(error, results);
}
results[index] = result;
if (++count === q... | javascript | {
"resource": ""
} |
q43030 | performTransaction | train | function performTransaction(pool, queries, callback) {
pool.connect((error, client, done) => {
if (error) {
done(client);
return callback(error, null);
}
client.query('BEGIN', error => {
if (error) {
return rollback(client, done, error, callback);
}
sequence(queries... | javascript | {
"resource": ""
} |
q43031 | rollback | train | function rollback(client, done, error, callback) {
client.query('ROLLBACK', rollbackError => {
done(rollbackError);
return callback(rollbackError || error, null);
});
} | javascript | {
"resource": ""
} |
q43032 | flatten | train | function flatten(source, opts) {
opts = opts || {};
var delimiter = opts.delimiter = opts.delimiter || '.';
var o = {};
function iterate(source, parts) {
var k, v;
parts = parts || [];
for(k in source) {
v = source[k];
if(v && typeof v === 'object' && Object.keys(v).length) {
ite... | javascript | {
"resource": ""
} |
q43033 | isValidLevel | train | function isValidLevel ( level ) {
return reLevel.test( level ) || isFunction( level ) || Array.isArray( level );
} | javascript | {
"resource": ""
} |
q43034 | printMsg | train | function printMsg ( msgId, data ) {
var outputFn;
if ( messages.hasOwnProperty( msgId) ) {
switch ( msgId.match( /^[A-Z]+/ )[0] ) {
case 'INFO':
outputFn = grunt.log.writeln;
break;
case 'VERBOSE':
outputFn = grunt.verbose.writeln;
break;
... | javascript | {
"resource": ""
} |
q43035 | formatMessage | train | function formatMessage (message) {
return '<error' +
attr(message, 'line') +
attr(message, 'column') +
attr(message, 'severity') +
attr(message, 'message') +
('source' in message ? attr(message, 'source') : '') +
' />'
} | javascript | {
"resource": ""
} |
q43036 | formatResult | train | function formatResult (result) {
return [
'<file name="' + result.filename + '">',
result.messages.map(formatMessage).join('\n'),
'</file>'
].join('\n')
} | javascript | {
"resource": ""
} |
q43037 | restoreLib | train | function restoreLib(err1)
{
fs.move(ORIG, LIB, {clobber: true}, function(err2)
{
callback(err1 || err2)
})
} | javascript | {
"resource": ""
} |
q43038 | train | function(chunk) {
var patsy = this;
chunk = chunk.trim();
if(chunk == 'exit'){
this.scripture.print('[King Arthur]'.magenta + ': On second thought, let\'s not go to Camelot, it\'s a silly place. I am leaving you behind squire!\n');
program.prompt('[Patsy]'.cyan + ': Sire, do you ... | javascript | {
"resource": ""
} | |
q43039 | train | function(relativeProjectPath, relative){
var src = [];
var complete_path;
var patsy = this;
if(patsy.utils.isArray(relative)){
// For each path, check if path is negated, if it is, remove negation
relative.forEach(function(_path){
if(patsy.utils.isPathNegated(_path))... | javascript | {
"resource": ""
} | |
q43040 | train | function(how){
var _child, _cfg, patsy = this;
var _execCmd = [];
if(typeof this.project_cfg.project === 'undefined'){
/**
* Require config from the library
*
* @var Object
* @source patsy
*/
var config = require('./config')({
... | javascript | {
"resource": ""
} | |
q43041 | Image | train | function Image(src) {
if (!(this instanceof Image)) {
return new Image(src)
}
if (typeof src !== 'string') {
throw new Error('param `src` must be a string')
}
var ret = reg.exec(src)
if (!ret) {
throw new Error('invalid param `src`')
}
this.src = src
this.host = ret[1] || defaultHost
... | javascript | {
"resource": ""
} |
q43042 | train | function ($placeholder, file, that) {
$.ajax({
type: "post",
url: that.options.imagesUploadScript,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = that.updateProgressBar;
return xhr;
},
cache: false,
contentType: false,
complete: functi... | javascript | {
"resource": ""
} | |
q43043 | train | function (file, that) {
$.ajax({
type: "post",
url: that.options.imagesDeleteScript,
data: {
file: file
}
});
} | javascript | {
"resource": ""
} | |
q43044 | train | function (options) {
if (options && options.$el) {
this.$el = options.$el;
}
this.options = $.extend(this.defaults, options);
this.setImageEvents();
if (this.options.useDragAndDrop === true){
this.setDragAndDropEvents();
}
this.preparePreviousImages();
} | javascript | {
"resource": ""
} | |
q43045 | train | function(buttonLabels){
var label = 'Img';
if (buttonLabels === 'fontawesome' || typeof buttonLabels === 'object' && !!(buttonLabels.fontawesome)) {
label = '<i class="fa fa-picture-o"></i>';
}
if (typeof buttonLabels === 'object' && buttonLabels.img) {
label = buttonLabels.img;
}
return ... | javascript | {
"resource": ""
} | |
q43046 | train | function ($placeholder) {
var that = this,
$selectFile, files;
$selectFile = $('<input type="file" multiple="multiple">').click();
$selectFile.change(function () {
files = this.files;
that.uploadFiles($placeholder, files, that);
});
$.fn.mediumInsert.insert.deselect();
return $selectFi... | javascript | {
"resource": ""
} | |
q43047 | train | function (e) {
var $progress = $('.progress:first', this.$el),
complete;
if (e.lengthComputable) {
complete = e.loaded / e.total * 100;
complete = complete ? complete : 0;
$progress.attr('value', complete);
$progress.html(complete);
}
} | javascript | {
"resource": ""
} | |
q43048 | train | function (jqxhr, $placeholder) {
var $progress = $('.progress:first', $placeholder),
$img;
$progress.attr('value', 100);
$progress.html(100);
if (jqxhr.responseText) {
$progress.before('<figure class="mediumInsert-images"><img src="'+ jqxhr.responseText +'" draggable="true" alt=""></figure>');
... | javascript | {
"resource": ""
} | |
q43049 | train | function(key, callback) {
if (key) {
this.store.proxy.remove(this.prefix + key);
if (callback) {
callback(null, key);
}
} else {
if (callback) {
callback('missing key');
}
}
} | javascript | {
"resource": ""
} | |
q43050 | train | function(key, callback) {
if (key) {
var _data = this.store.proxy.get(this.prefix + key),
data;
if ('undefined' !== typeof window) {
// browser
try {
data = JSON.parse(_data);
} catch (e) {
data = _data;
}
} else {... | javascript | {
"resource": ""
} | |
q43051 | train | function(key, data, callback) {
if (key) {
if (data) {
var _data = data;
if ('undefined' !== typeof window && 'object' === typeof data) {
_data = JSON.stringify(_data);
}
this.store.proxy.set(this.prefix + key, _data);
callback(null);
}... | javascript | {
"resource": ""
} | |
q43052 | list | train | function list() {
return installer.listPlugins(function(listErr, plugins) {
if (listErr) {
return out.error("error listing installed plugins: %s", listErr);
}
if (plugins.length === 0) {
return out.success("no plugins found");
}
var string = "";
for (var idx = 0; idx < plugins.leng... | javascript | {
"resource": ""
} |
q43053 | resolveId | train | function resolveId (prop) {
if (rule[prop] === null || typeof rule[prop] === 'number') return
// Resolve the property to an index
var j = self._getRuleIndex(rule.id)
if (j < 0)
self._error( new Error('Atok#_resolveRules: ' + prop + '() value not found: ' + rule.id) )
rule[prop] = i - j... | javascript | {
"resource": ""
} |
q43054 | train | function (options) {
events.EventEmitter.call(this);
// this.el = el;
this.options = extend(this.options, options);
// console.log(this.options);
this._init();
this.show = this._show;
this.hide = this._hide;
} | javascript | {
"resource": ""
} | |
q43055 | createFunctions | train | function createFunctions() {
const result = [];
for (let i = 0; i < count; i++) {
result.push(number => Promise.resolve(number + 1));
}
return result;
} | javascript | {
"resource": ""
} |
q43056 | train | function(filepath, req, res) {
var path = require("path"),
config = module.exports.config,
result = false,
parentdir;
do {
var defaultdir = path.resolve(path.join(config.responsesdefault, filepath));
parentdir = path.resolve(path.join(config.responses, filepath));
... | javascript | {
"resource": ""
} | |
q43057 | convert | train | function convert(swagger, done) {
fury.parse({source: swagger}, function (parseErr, res) {
if (parseErr) {
return done(parseErr);
}
fury.serialize({api: res.api}, function (serializeErr, blueprint) {
if (serializeErr) {
return done(serializeErr);
}
done(null, blueprint);
... | javascript | {
"resource": ""
} |
q43058 | run | train | function run(argv, done) {
if (!argv) {
argv = parser.argv;
}
if (argv.h) {
parser.showHelp();
return done(null);
}
if (!argv._.length) {
return done(new Error('Requires an input argument'));
} else if (argv._.length > 2) {
return done(new Error('Too many arguments given!'));
}
va... | javascript | {
"resource": ""
} |
q43059 | ModuleResource | train | function ModuleResource( pkg, config ) {
// Parent constructor
ModuleResource.super.call( this, pkg, config );
// Properties
this.imports = config.imports || null;
this.exports = config.exports || null;
this.propertyNamePattern = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
} | javascript | {
"resource": ""
} |
q43060 | init | train | function init (done) {
var node = tools.match_ext(filename, 'node')
var json = tools.match_ext(filename, 'json')
done(null, {
content: content,
json: json,
node: node,
// all other files are considered as javascript files.
js: !node && !json,
})
} | javascript | {
"resource": ""
} |
q43061 | train | function(db, auditDb) {
var dbWrapper = getDbWrapper(db);
var auditDbWrapper;
if (auditDb) {
auditDbWrapper = getDbWrapper(auditDb);
} else {
auditDbWrapper = dbWrapper;
}
var clientWrapper = {
uuids: function(count, callback) {
db.newUUID.call(db, 100, function(err, i... | javascript | {
"resource": ""
} | |
q43062 | domIndexOf | train | function domIndexOf(nodes, domNode) {
var index = -1;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.type !== 'TextNode' && node.type !== 'ElementNode') {
continue;
} else {
index++;
}
if (node === domNode) {
re... | javascript | {
"resource": ""
} |
q43063 | parseComponentBlockParams | train | function parseComponentBlockParams(element, program) {
var l = element.attributes.length;
var attrNames = [];
for (var i = 0; i < l; i++) {
attrNames.push(element.attributes[i].name);
}
var asIndex = attrNames.indexOf('as');
if (asIndex !== -1 && l > asIndex && attrNames[a... | javascript | {
"resource": ""
} |
q43064 | onLinkClick | train | function onLinkClick(event) {
// Resolve anchor link
var page = url.format( url.resolve(location, this.getAttribute('href')) );
// Load new page
piccolo.loadPage( page );
event.preventDefault();
return false;
} | javascript | {
"resource": ""
} |
q43065 | renderPage | train | function renderPage(state) {
// Get presenter object
piccolo.require(state.resolved.name, function (error, Resource) {
if (error) return piccolo.emit('error', error);
var presenter = new Resource(state.query.href, document);
presenter[state.resolved.method].apply(presenter, state.resolved... | javascript | {
"resource": ""
} |
q43066 | createStateObject | train | function createStateObject(page, callback) {
// This callback function will create a change table state object
var create = function () {
var query = url.parse(page);
var presenter = piccolo.build.router.parse(query.pathname);
var state = {
'resolved': presenter,
'namespace':... | javascript | {
"resource": ""
} |
q43067 | train | function () {
var query = url.parse(page);
var presenter = piccolo.build.router.parse(query.pathname);
var state = {
'resolved': presenter,
'namespace': 'piccolo',
'query': query
};
callback(state);
} | javascript | {
"resource": ""
} | |
q43068 | createChain | train | function createChain(descriptor, callback) {
if (typeof descriptor !== 'object') {
throw new TypeError('createChain: descriptor is not an object: ' +
descriptor);
}
//Create the Chain class.
function CustomChain(callback) {
if (!(this instanceof CustomChain))... | javascript | {
"resource": ""
} |
q43069 | CustomChain | train | function CustomChain(callback) {
if (!(this instanceof CustomChain)) {
return new CustomChain(callback);
}
CustomChain.super_.call(this, callback);
CustomChain._lists.forEach(function(listName) {
this._result[listName] = [];
}, this);
} | javascript | {
"resource": ""
} |
q43070 | includedFiles | train | function includedFiles(name){
let includes=this.getIncludes(this.getFile(name));
let ret=includes.map(include => {
let ret = {
absolute:path.join(name,"../",include.relPath),
relative:include.relPath,
match:include.match
}
return ret;
})
return... | javascript | {
"resource": ""
} |
q43071 | SquiddioTokenError | train | function SquiddioTokenError(message, type, code, subcode) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'SquiddioTokenError';
this.message = message;
this.type = type;
this.code = code;
this.subcode = subcode;
this.status = 500;
} | javascript | {
"resource": ""
} |
q43072 | onNextTransform | train | function onNextTransform (transform, next) {
// check if we should handle this filePath
function shouldProcess (filePath, done) {
done(!!multimatch(filePath, transform.pattern, transform.opts).length)
}
// transform the path
function process (filePath, complete) {
... | javascript | {
"resource": ""
} |
q43073 | shouldProcess | train | function shouldProcess (filePath, done) {
done(!!multimatch(filePath, transform.pattern, transform.opts).length)
} | javascript | {
"resource": ""
} |
q43074 | process | train | function process (filePath, complete) {
var filename = path.basename(filePath),
pathParts = path.dirname(filePath).split(path.sep)
// we'll get an empty arrary if we overslice
pathParts = pathParts.slice(transform.by)
pathParts.push(filename)
var newPath = p... | javascript | {
"resource": ""
} |
q43075 | Response | train | function Response(request, key) {
// define private store
const store = {
body: '',
cookies: [],
headers: {},
key: key,
sent: false,
statusCode: 0
};
this[STORE] = store;
/**
* The request that is tied to this response.
* @name Response#re... | javascript | {
"resource": ""
} |
q43076 | text | train | function text(el, str) {
if (el.textContent) {
el.textContent = str;
} else {
el.innerText = str;
}
} | javascript | {
"resource": ""
} |
q43077 | map | train | function map(cov) {
var ret = {
instrumentation: 'node-jscoverage'
, sloc: 0
, hits: 0
, misses: 0
, coverage: 0
, files: []
};
for (var filename in cov) {
var data = coverage(filename, cov[filename]);
ret.files.push(data);
ret.hits += data.hits;
ret.misses += data.misse... | javascript | {
"resource": ""
} |
q43078 | coverage | train | function coverage(filename, data) {
var ret = {
filename: filename,
coverage: 0,
hits: 0,
misses: 0,
sloc: 0,
source: {}
};
data.source.forEach(function(line, num){
num++;
if (data[num] === 0) {
ret.misses++;
ret.sloc++;
} else if (data[num] !== undefined) {
... | javascript | {
"resource": ""
} |
q43079 | TAP | train | function TAP(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, n = 1
, passes = 0
, failures = 0;
runner.on('start', function(){
var total = runner.grepTotal(runner.suite);
console.log('%d..%d', 1, total);
});
runner.on('test end', function(){
++n;
});
... | javascript | {
"resource": ""
} |
q43080 | Teamcity | train | function Teamcity(runner) {
Base.call(this, runner);
var stats = this.stats;
runner.on('start', function() {
console.log("##teamcity[testSuiteStarted name='mocha.suite']");
});
runner.on('test', function(test) {
console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']");
});
... | javascript | {
"resource": ""
} |
q43081 | XUnit | train | function XUnit(runner) {
Base.call(this, runner);
var stats = this.stats
, tests = []
, self = this;
runner.on('pass', function(test){
tests.push(test);
});
runner.on('fail', function(test){
tests.push(test);
});
runner.on('end', function(){
console.log(tag('testsuite', {
... | javascript | {
"resource": ""
} |
q43082 | Runner | train | function Runner(suite) {
var self = this;
this._globals = [];
this.suite = suite;
this.total = suite.total();
this.failures = 0;
this.on('test end', function(test){ self.checkGlobals(test); });
this.on('hook end', function(hook){ self.checkGlobals(hook); });
this.grep(/.*/);
this.globals(this.globalPr... | javascript | {
"resource": ""
} |
q43083 | train | function( filter, context ) {
var comment = this.value;
if ( !( comment = filter.onComment( context, comment, this ) ) ) {
this.remove();
return false;
}
if ( typeof comment != 'string' ) {
this.replaceWith( comment );
return false;
}
this.value = comment;
return true;
} | javascript | {
"resource": ""
} | |
q43084 | getExistsSync | train | function getExistsSync(path, exts) {
for (var i=0,len=exts.length; i<len; i++) {
if (fs.existsSync(path + exts[i])) {
return path + exts[i];
}
}
return false;
} | javascript | {
"resource": ""
} |
q43085 | extend | train | function extend(a,b) {
var c = clone(a);
for (var key in b) {
c[key] = b[key];
}
return c;
} | javascript | {
"resource": ""
} |
q43086 | randomize | train | function randomize( obj ) {
var j = 0,
i = Math.floor(Math.random() * (Object.keys(obj).length)),
result;
for(var property in obj) {
if(j === i) {
result = property;
break;
}
j++;
}
return result;
} | javascript | {
"resource": ""
} |
q43087 | _createEventRangeValidator | train | function _createEventRangeValidator(range) {
var ctxRange = _createRangeArray(range);
return function rangeValidator(range) {
var leftIndex = 0;
var rightIndex = 0;
var left;
var right;
for (; leftIndex < ctxRange.length && rightIndex < range.length; ) {
left = ctxRange[leftIndex];
... | javascript | {
"resource": ""
} |
q43088 | sendSPrintFError | train | function sendSPrintFError(res, errorArray, code, internalCode) {
var obj = { success: false };
obj[res ? 'description' : 'reason'] = errorArray;
return sendError(res, obj, code, internalCode);
} | javascript | {
"resource": ""
} |
q43089 | sendStringError | train | function sendStringError(res, error, code, internalCode) {
var obj = { success: false };
obj[res ? 'description' : 'reason'] = error;
return sendError(res, obj, code, internalCode);
} | javascript | {
"resource": ""
} |
q43090 | Device | train | function Device(key, params) {
var p = params || {};
// The primary key of the device [String]
this.key = key;
// Human readable name of the device [String] EG - "My Device"
this.name = p.name || "";
// Indexable attributes. Useful for grouping related Devices.
// EG - {location: '445-w-Erie', model: 'T... | javascript | {
"resource": ""
} |
q43091 | train | function(err, httpRes, body) {
if (err) _callback(err)
else {
try { var res = JSON.parse(body) }
catch(err) { _callback(null, body) }
if (httpRes && httpRes.statusCode !== 200) {
maybeRetry(res, IOD, IODOpts, apiType, _callback)
}
else _callback(null, res)
}
} | javascript | {
"resource": ""
} | |
q43092 | maybeRetry | train | function maybeRetry(err, IOD, IODOpts, apiType, callback) {
var retryApiReq = apiType !== IOD.TYPES.SYNC &&
apiType !== IOD.TYPES.RESULT &&
apiType !== IOD.TYPES.DISCOVERY
if (IODOpts.retries == null || retryApiReq) callback(err)
else if (!--IODOpts.retries) callback(err)
var reqTypeDontRetry = apiType !== IO... | javascript | {
"resource": ""
} |
q43093 | makeOptions | train | function makeOptions(IOD, IODOpts, apiType, reqOpts) {
var path = IodU.makePath(IOD, IODOpts, apiType)
var method = apiType === IOD.TYPES.JOB || !_.isEmpty(IODOpts.files) ?
'post' : IODOpts.method.toLowerCase()
return _.defaults({
url: IOD.host + ':' + IOD.port + path,
path: path,
method: method,
// For ... | javascript | {
"resource": ""
} |
q43094 | addParamsToData | train | function addParamsToData(IOD, IODOpts, form) {
form.append('apiKey', IOD.apiKey)
_.each(exports.prepareParams(IODOpts.params), function(paramVal, paramName) {
_.each(T.maybeToArray(paramVal), function(val) {
form.append(paramName, val)
})
})
} | javascript | {
"resource": ""
} |
q43095 | addFilesToData | train | function addFilesToData(IOD, IODOpts, apiType, form) {
_.each(T.maybeToArray(IODOpts.files), function(file) {
if (apiType === IOD.TYPES.JOB) {
form.append(file.name, fs.createReadStream(file.path))
}
else form.append('file', fs.createReadStream(file))
})
} | javascript | {
"resource": ""
} |
q43096 | replaceCssLength | train | function replaceCssLength( length1, length2 ) {
var parts1 = cssLengthRegex.exec( length1 ),
parts2 = cssLengthRegex.exec( length2 );
// Omit pixel length unit when necessary,
// e.g. replaceCssLength( 10, '20px' ) -> 20
if ( parts1 ) {
if ( !parts1[ 2 ] && parts2[ 2 ] == 'px' )
return parts2... | javascript | {
"resource": ""
} |
q43097 | train | function() {
var results = [];
for (var i=0, cs=this.controls, c; c=cs[i]; i++) {
if (!c.isChrome) {
results.push(c);
}
}
return results;
} | javascript | {
"resource": ""
} | |
q43098 | train | function() {
var c$ = this.getClientControls();
for (var i=0, c; c=c$[i]; i++) {
c.destroy();
}
} | javascript | {
"resource": ""
} | |
q43099 | train | function(inMessage, inPayload, inSender) {
// Note: Controls will generally be both in a $ hash and a child list somewhere.
// Attempt to avoid duplicated messages by sending only to components that are not
// UiComponent, as those components are guaranteed not to be in a child list.
// May cause a problem if t... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.