_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q32000 | date | train | function date(value) {
var parsedDate = Date.parse(value);
// couldn't parse it
if (typeOf(parsedDate) != 'number') {
return throwModifierError('date', value, {message: 'Invalid Date'});
}
return new Date(parsedDate);
} | javascript | {
"resource": ""
} |
q32001 | float | train | function float(value) {
var parsedFloat = Number.parseFloat(value);
// couldn't parse it
if (typeOf(parsedFloat) != 'number') {
return throwModifierError('float', value, {message: 'Invalid Float'});
}
return parsedFloat;
} | javascript | {
"resource": ""
} |
q32002 | favicoIntegration | train | function favicoIntegration(options = defaultFavicoOptions) {
// Create a new Favico integration.
// Initially this was going to be a singleton object, but I realized there
// may be cases where you want several different types of notifications.
// The middleware does not yet support multiple instances, but it should
// be easy to add if there's demand :)
//
// Not using the constructor pattern, because it obfuscates JS' prototypal
// nature, and there's no need for inheritance here, so this is equivalent.
const favico = new Favico(options);
return {
currentVal: 0,
update(value, callback) {
if ( typeof value === 'number' ) {
// Don't allow non-integer values
if ( value % 1 !== 0 ) {
return callback(`
Warning: Favico not affected.
You provided a floating-point value: ${value}.
You need to provide an integer, or a keyword value.
See https://github.com/joshwcomeau/redux-favicon#troubleshooting for more information.
`);
}
this.currentVal = value;
} else if ( typeof value === 'string' ) {
switch ( value.toLowerCase() ) {
case 'increment': this.currentVal++; break;
case 'decrement': this.currentVal--; break;
case 'reset': this.currentVal=0; break;
default:
return callback(`
Warning: Favico not affected.
You provided a string value: ${value}.
The only strings we accept are: ${favicoEnumValues.join(', ')}.
See https://github.com/joshwcomeau/redux-favicon#troubleshooting for more information.
`);
}
} else {
// Annoyingly, istanbul won't give me 100% coverage unless all possible
// typeof values are checked. It is not possible for all types to make
// it to this check; `undefined` aborts earlier.
/* istanbul ignore next */
const provided_type = typeof value;
return callback(`
Warning: Favico provided an illegal type.
You provided a a value of type: ${provided_type}.
We only accept integers or strings.
See https://github.com/joshwcomeau/redux-favicon#troubleshooting for more information.
`);
}
// Don't allow negative numbers
this.currentVal = ( this.currentVal < 0 ) ? 0 : this.currentVal;
// Set the 'badge' to be our derived value.
// The favico.js library will show it if it's truthy, hide it if falsy.
favico.badge(this.currentVal);
return callback();
}
};
} | javascript | {
"resource": ""
} |
q32003 | parseTokens | train | function parseTokens(entry, env)
{
var found = 0;
if (entry.indexOf('${') > -1)
{
entry = entry.replace(/\$\{([^}]+)\}/g, function(match, token)
{
var value = getVar.call(this, token, env);
// need to have `found` counter
// to see if any of the variables
// in the string were resolved
if (hasValue(value))
{
found++;
}
return value;
}.bind(this));
}
// reset entry if no variables were resolved
if (!found) entry = '';
return entry;
} | javascript | {
"resource": ""
} |
q32004 | globs | train | function globs(sourcePath, ignore, commands, done) {
var expression = /\$g\[(.+?)\]/g;
var result = [];
each(commands, function(command, next) {
var map = {};
var match;
var matches = [];
while ((match = expression.exec(command))) matches.push(match);
each(matches, function(patternMatch, next) {
find(patternMatch[1], sourcePath, ignore, function(err, relativePaths) {
if (err) return next(err);
map[patternMatch[1]] = relativePaths;
next();
});
}, function(err) {
if (err) return next(err);
result.push(command.replace(expression, function(match, matchKey) {
return map[matchKey].join(' ');
}));
next();
});
}, function(err) {
if (err) return done(err);
done(undefined, result);
});
} | javascript | {
"resource": ""
} |
q32005 | loadConfig | train | function loadConfig(done) {
fs.stat('package.json', function(err) {
if (err) return done(undefined, {});
fs.readFile('package.json', function(err, contents) {
if (err) return done(err);
try {
done(undefined, JSON.parse(contents).config || {});
} catch(err) {
done(err);
}
});
});
} | javascript | {
"resource": ""
} |
q32006 | loadOptions | train | function loadOptions(entries) {
var options = new Command().version(require('../../package').version);
entries.forEach(function(entry) {
options.option(entry.option, entry.text, entry.parse);
});
return options.parse(process.argv);
} | javascript | {
"resource": ""
} |
q32007 | variables | train | function variables(root, config, done) {
var expression = /\$v\[(.+?)\]/g;
each(Object.keys(root), function(key, next) {
var value = root[key];
if (typeof value === 'object') return variables(value, config, next);
if (typeof value !== 'string') return next();
root[key] = value.replace(expression, function(match, matchKey) {
return config[matchKey] || match;
});
next();
}, done);
} | javascript | {
"resource": ""
} |
q32008 | Observable | train | function Observable (subject, parent, prefix) {
if ('object' != typeof subject)
throw new TypeError('object expected. got: ' + typeof subject);
if (!(this instanceof Observable))
return new Observable(subject, parent, prefix);
debug('new', subject, !!parent, prefix);
Emitter.call(this);
this._bind(subject, parent, prefix);
} | javascript | {
"resource": ""
} |
q32009 | to64 | train | function to64(index, count) {
let result = '';
while (--count >= 0) { // Result char count.
result += itoa64[index & 63]; // Get corresponding char.
index = index >> 6; // Move to next one.
}
return result;
} | javascript | {
"resource": ""
} |
q32010 | getSalt | train | function getSalt(inputSalt) {
let salt = '';
if (inputSalt) {
// Remove $apr1$ token and extract salt.
salt = inputSalt.split('$')[2];
} else {
while(salt.length < 8) { // Random 8 chars.
let rchIndex = Math.floor((Math.random() * 64));
salt += itoa64[rchIndex];
}
}
return salt;
} | javascript | {
"resource": ""
} |
q32011 | getPassword | train | function getPassword(final) {
// Encrypted pass.
let epass = '';
epass += to64((final.charCodeAt(0) << 16) | (final.charCodeAt(6) << 8) | final.charCodeAt(12), 4);
epass += to64((final.charCodeAt(1) << 16) | (final.charCodeAt(7) << 8) | final.charCodeAt(13), 4);
epass += to64((final.charCodeAt(2) << 16) | (final.charCodeAt(8) << 8) | final.charCodeAt(14), 4);
epass += to64((final.charCodeAt(3) << 16) | (final.charCodeAt(9) << 8) | final.charCodeAt(15), 4);
epass += to64((final.charCodeAt(4) << 16) | (final.charCodeAt(10) << 8) | final.charCodeAt(5), 4);
epass += to64(final.charCodeAt(11), 2);
return epass;
} | javascript | {
"resource": ""
} |
q32012 | getElementTag | train | function getElementTag(node) {
if (node.openingElement && t.isJSXIdentifier(node.openingElement.name)) {
return node.openingElement.name.name;
} else {
error(node.openingElement, "Unable to parse opening tag.");
}
} | javascript | {
"resource": ""
} |
q32013 | transformSpecialAttribute | train | function transformSpecialAttribute(name, attribute) {
if (t.isJSXExpressionContainer(attribute.value)) {
let value = attribute.value.expression;
switch (name) {
case "ui5ControlData":
renderer.renderControlData(value);
break;
case "ui5ElementData":
renderer.renderElementData(value);
break;
case "ui5AccessibilityData":
renderer.handleAccessibilityData(value);
break;
default:
error(attribute, "Unknown special attribute: '" + name + "'.");
}
} else {
error(attribute, "Only expressions supported in special attributes.");
}
} | javascript | {
"resource": ""
} |
q32014 | transformStyles | train | function transformStyles(value) {
if (t.isStringLiteral(value)) {
renderer.renderAttributeExpression("style", value);
} else if (t.isJSXExpressionContainer(value)){
renderer.handleStyles(value.expression);
} else {
error(value, "Unknown style specification type.");
}
} | javascript | {
"resource": ""
} |
q32015 | transformClasses | train | function transformClasses(value) {
if (t.isStringLiteral(value)) {
value.value.split(" ").forEach(function(cls) {
renderer.addClass(cls);
});
} else if (t.isJSXExpressionContainer(value)){
renderer.handleClasses(value.expression);
} else {
error(value, "Unknown class specification type.");
}
} | javascript | {
"resource": ""
} |
q32016 | draw | train | function draw(c, frame)
{
const pixels = frame.data
for (let y = 0; y < frame.height; y++)
{
for (let x = 0; x < frame.width; x++)
{
const color = pixels[x + y * frame.width]
if (typeof color !== 'undefined')
{
let hex = color.toString(16)
while (hex.length < 6)
{
hex = '0' + hex
}
c.fillStyle = '#' + hex
c.beginPath()
c.fillRect(x, y, 1, 1)
}
}
}
} | javascript | {
"resource": ""
} |
q32017 | taskNameFunc | train | function taskNameFunc() {
var validParts = _.dropWhile(_.flatten([this.prefix,arguments]),function(item) {
return !item;
});
return validParts.join(this.separator);
} | javascript | {
"resource": ""
} |
q32018 | sourceString | train | function sourceString(source) {
var message = "<css input>"
if (source) {
if (source.input && source.input.file) {
message = source.input.file
}
if (source.start) {
message += ":" + source.start.line + ":" + source.start.column
}
}
return message
} | javascript | {
"resource": ""
} |
q32019 | scrollToBottom | train | function scrollToBottom(){
var it= jQuery('#testit');
var message= jQuery('#messages');
var newMessage= message.children('li:last-child')
var clientH= it.prop('clientHeight');
var scrollTop=it.prop('scrollTop');
var scrollH=it.prop('scrollHeight');
var newMessageH= newMessage.innerHeight();
var prevmessageH=newMessage.prev().innerHeight();
var t=clientH+scrollTop+newMessageH+prevmessageH;
if(clientH+scrollTop+newMessageH+prevmessageH>=scrollH){
it.scrollTop(scrollH);
}
} | javascript | {
"resource": ""
} |
q32020 | train | function(res) {
var author = _.get(res, 'envelope.user.id') || 'bot'
return _.zipObject(cons.mandatoryFields, ['hash', 'test', author, cons.now()])
} | javascript | {
"resource": ""
} | |
q32021 | train | function(str) {
var startsWith = !_.isNull(str.match(wOpsHeadRe))
return startsWith & cons.isLegalSentence(str)
} | javascript | {
"resource": ""
} | |
q32022 | train | function(str) {
var startsWith = !_.isNull(str.match(sOpsHeadRe))
return startsWith & cons.isLegalSentence(str)
} | javascript | {
"resource": ""
} | |
q32023 | train | function(str) {
var startsWith = !_.isNull(str.match(rOpsHeadRe))
return startsWith & cons.isLegalSentence(str)
} | javascript | {
"resource": ""
} | |
q32024 | train | function(str) {
var startsWith = !_.isNull(str.match(pOpsHeadRe))
return startsWith & cons.isLegalSentence(str)
} | javascript | {
"resource": ""
} | |
q32025 | run | train | function run(commands, done) {
var children = [];
var pending = commands.length || 1;
var err;
each(commands, function(command, next) {
children.push(childProcess.spawn(shell[0], [shell[1], command], {
stdio: ['pipe', process.stdout, process.stderr]
}).on('exit', function(code) {
if (!err && code > 0) {
err = new Error('`' + command + '` failed with exit code ' + code);
children.forEach(function(child) {
if (child.connected) child.kill();
});
}
pending -= 1;
if (pending === 0) done(err);
}));
next();
});
} | javascript | {
"resource": ""
} |
q32026 | watch | train | function watch(sourcePath, patterns, commands) {
var isBusy = false;
var isPending = false;
var runnable = function() {
if (isBusy) return (isPending = true);
isBusy = true;
run(commands, function(err) {
if (err) console.error(err.stack || err);
isBusy = false;
if (isPending) runnable(isPending = false);
});
};
chokidar.watch(patterns, {
cwd: sourcePath,
ignoreInitial: true
}).on('add', runnable).on('change', runnable).on('unlink', runnable);
} | javascript | {
"resource": ""
} |
q32027 | fail | train | function fail(status, description, response) {
let body = status + ' ' + description;
console.log(body);
response.writeHead(status, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*',
'Content-Length': body.length
});
response.write(body);
response.end();
} | javascript | {
"resource": ""
} |
q32028 | authorised | train | function authorised(request) {
// JWT is usually passed via an HTTP header
let token = request.headers.authorization;
// For EventSource and WebSocket, JWT is passed as a URL parameter
if (token === undefined) {
let url = URL.parse(request.url, true);
if (url.query)
token = url.query.jwt;
}
// ask app to validate JWT authorisation token
return (!token || config.validateJWT(token, request.url));
} | javascript | {
"resource": ""
} |
q32029 | ws_send | train | function ws_send(socket, data) {
//console.log("send: " + data);
let header;
let payload = new Buffer.from(data);
const len = payload.length;
if (len <= 125) {
header = new Buffer.alloc(2);
header[1] = len;
} else if (len <= 0xffff) {
header = new Buffer.alloc(4);
header[1] = 126;
header[2] = (len >> 8) & 0xff;
header[3] = len & 0xff;
} else { /* 0xffff < len <= 2^63 */
header = new Buffer(10);
header[1] = 127;
header[2] = (len >> 56) & 0xff;
header[3] = (len >> 48) & 0xff;
header[4] = (len >> 40) & 0xff;
header[5] = (len >> 32) & 0xff;
header[6] = (len >> 24) & 0xff;
header[7] = (len >> 16) & 0xff;
header[8] = (len >> 8) & 0xff;
header[9] = len & 0xff;
}
header[0] = 0x81;
socket.write(Buffer.concat([header, payload],
header.length + payload.length), 'binary');
//console.log('sent ' + data.length + ' bytes');
} | javascript | {
"resource": ""
} |
q32030 | ws_receive | train | function ws_receive(raw)
{
let data = unpack(raw); // string to byte array
let fin = (data[0] & 128) == 128;
let opcode = data[0] & 15;
let isMasked = (data[1] & 128) == 128;
let dataLength = data[1] & 127;
let start = 2;
let length = data.length;
let output = "";
if (dataLength == 126)
start = 4;
else if (dataLength == 127)
start = 10;
if (isMasked) {
let i = start + 4;
let masks = data.slice(start, i);
let index = 0;
while (i < length) {
output += String.fromCharCode(data[i++] ^ masks[index++ % 4]);
}
} else {
let i = start;
while (i < length) {
output += String.fromCharCode(data[i++]);
}
}
//console.log("decode message: " + output);
return output;
} | javascript | {
"resource": ""
} |
q32031 | concat | train | function concat(divider, sourcePath, relativePaths, done) {
var writeDivider = false;
each(relativePaths, function(relativePath, next) {
var absoluteSourcePath = path.resolve(sourcePath, relativePath);
var readStream = fs.createReadStream(absoluteSourcePath);
if (writeDivider) process.stdout.write(divider);
writeDivider = true;
readStream.on('close', next).on('error', next).pipe(process.stdout);
}, done);
} | javascript | {
"resource": ""
} |
q32032 | train | function (path) {
//There has to be an easier way to do this.
var i, part, ary,
firstChar = path.charAt(0);
if (firstChar !== '/' &&
firstChar !== '\\' &&
path.indexOf(':') === -1) {
//A relative path. Use the current working directory.
path = xpcUtil.cwd() + '/' + path;
}
ary = path.replace(/\\/g, '/').split('/');
for (i = 0; i < ary.length; i += 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
ary.splice(i - 1, 2);
i -= 2;
}
}
return ary.join('/');
} | javascript | {
"resource": ""
} | |
q32033 | train | function(dest, source) {
lang.eachProp(source, function (value, prop) {
if (typeof value === 'object' && value &&
!lang.isArray(value) && !lang.isFunction(value) &&
!(value instanceof RegExp)) {
if (!dest[prop]) {
dest[prop] = {};
}
lang.deepMix(dest[prop], value);
} else {
dest[prop] = value;
}
});
return dest;
} | javascript | {
"resource": ""
} | |
q32034 | SourceMap | train | function SourceMap(options) {
options = defaults(options, {
file : null,
root : null,
orig : null,
orig_line_diff : 0,
dest_line_diff : 0,
});
var generator = new MOZ_SourceMap.SourceMapGenerator({
file : options.file,
sourceRoot : options.root
});
var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
if (orig_map && Array.isArray(options.orig.sources)) {
orig_map._sources.toArray().forEach(function(source) {
var sourceContent = orig_map.sourceContentFor(source, true);
if (sourceContent) {
generator.setSourceContent(source, sourceContent);
}
});
}
function add(source, gen_line, gen_col, orig_line, orig_col, name) {
if (orig_map) {
var info = orig_map.originalPositionFor({
line: orig_line,
column: orig_col
});
if (info.source === null) {
return;
}
source = info.source;
orig_line = info.line;
orig_col = info.column;
name = info.name || name;
}
generator.addMapping({
generated : { line: gen_line + options.dest_line_diff, column: gen_col },
original : { line: orig_line + options.orig_line_diff, column: orig_col },
source : source,
name : name
});
};
return {
add : add,
get : function() { return generator },
toString : function() { return JSON.stringify(generator.toJSON()); }
};
} | javascript | {
"resource": ""
} |
q32035 | can_mangle | train | function can_mangle(name) {
if (unmangleable.indexOf(name) >= 0) return false;
if (reserved.indexOf(name) >= 0) return false;
if (options.only_cache) {
return cache.props.has(name);
}
if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false;
return true;
} | javascript | {
"resource": ""
} |
q32036 | traverse | train | function traverse(object, visitor) {
var child;
if (!object) {
return;
}
if (visitor.call(null, object) === false) {
return false;
}
for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
child = object[keys[i]];
if (typeof child === 'object' && child !== null) {
if (traverse(child, visitor) === false) {
return false;
}
}
}
} | javascript | {
"resource": ""
} |
q32037 | getValidDeps | train | function getValidDeps(node) {
if (!node || node.type !== 'ArrayExpression' || !node.elements) {
return;
}
var deps = [];
node.elements.some(function (elem) {
if (elem.type === 'Literal') {
deps.push(elem.value);
}
});
return deps.length ? deps : undefined;
} | javascript | {
"resource": ""
} |
q32038 | train | function (obj, options, totalIndent) {
var startBrace, endBrace, nextIndent,
first = true,
value = '',
lineReturn = options.lineReturn,
indent = options.indent,
outDentRegExp = options.outDentRegExp,
quote = options.quote || '"';
totalIndent = totalIndent || '';
nextIndent = totalIndent + indent;
if (obj === null) {
value = 'null';
} else if (obj === undefined) {
value = 'undefined';
} else if (typeof obj === 'number' || typeof obj === 'boolean') {
value = obj;
} else if (typeof obj === 'string') {
//Use double quotes in case the config may also work as JSON.
value = quote + lang.jsEscape(obj) + quote;
} else if (lang.isArray(obj)) {
lang.each(obj, function (item, i) {
value += (i !== 0 ? ',' + lineReturn : '' ) +
nextIndent +
transform.objectToString(item,
options,
nextIndent);
});
startBrace = '[';
endBrace = ']';
} else if (lang.isFunction(obj) || lang.isRegExp(obj)) {
//The outdent regexp just helps pretty up the conversion
//just in node. Rhino strips comments and does a different
//indent scheme for Function toString, so not really helpful
//there.
value = obj.toString().replace(outDentRegExp, '$1');
} else {
//An object
lang.eachProp(obj, function (v, prop) {
value += (first ? '': ',' + lineReturn) +
nextIndent +
(keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+
': ' +
transform.objectToString(v,
options,
nextIndent);
first = false;
});
startBrace = '{';
endBrace = '}';
}
if (startBrace) {
value = startBrace +
lineReturn +
value +
lineReturn + totalIndent +
endBrace;
}
return value;
} | javascript | {
"resource": ""
} | |
q32039 | addSemiColon | train | function addSemiColon(text, config) {
if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) {
return text;
} else {
return text + ";";
}
} | javascript | {
"resource": ""
} |
q32040 | appendToFileContents | train | function appendToFileContents(fileContents, singleContents, path, config, module, sourceMapGenerator) {
var refPath, sourceMapPath, resourcePath, pluginId, sourceMapLineNumber, lineCount, parts, i;
if (sourceMapGenerator) {
if (config.out) {
refPath = config.baseUrl;
} else if (module && module._buildPath) {
refPath = module._buildPath;
} else {
refPath = "";
}
parts = path.split('!');
if (parts.length === 1) {
//Not a plugin resource, fix the path
sourceMapPath = build.makeRelativeFilePath(refPath, path);
} else {
//Plugin resource. If it looks like just a plugin
//followed by a module ID, pull off the plugin
//and put it at the end of the name, otherwise
//just leave it alone.
pluginId = parts.shift();
resourcePath = parts.join('!');
if (resourceIsModuleIdRegExp.test(resourcePath)) {
sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) +
'!' + pluginId;
} else {
sourceMapPath = path;
}
}
sourceMapLineNumber = fileContents.split('\n').length - 1;
lineCount = singleContents.split('\n').length;
for (i = 1; i <= lineCount; i += 1) {
sourceMapGenerator.addMapping({
generated: {
line: sourceMapLineNumber + i,
column: 0
},
original: {
line: i,
column: 0
},
source: sourceMapPath
});
}
//Store the content of the original in the source
//map since other transforms later like minification
//can mess up translating back to the original
//source.
sourceMapGenerator.setSourceContent(sourceMapPath, singleContents);
}
fileContents += singleContents;
return fileContents;
} | javascript | {
"resource": ""
} |
q32041 | onError | train | function onError(error) {
if (error.syscall !== 'listen') throw error;
const bind = (typeof port === 'string')
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
} | javascript | {
"resource": ""
} |
q32042 | addMultipartData | train | function addMultipartData (formData, data) {
var key, arr, i;
for (key in data) {
if (data.hasOwnProperty(key) && key !== 'files') {
if (data[key] instanceof Array) {
arr = data[key];
for (i = 0; i < arr.length; i += 1) {
formData.append(key + '[' + i + ']', exports.stringifyIfObject(arr[i]));
}
} else {
formData.append(key, exports.stringifyIfObject(data[key]));
}
}
}
} | javascript | {
"resource": ""
} |
q32043 | addFiles | train | function addFiles (formData, files) {
var file, arr, key, i = 0, filename;
for (key in files) {
if (files.hasOwnProperty(key) && files[key]) {
if (files[key] instanceof Array) {
arr = files[key];
filename = getFilename(arr[i]) || null;
for (i = 0; i < arr.length; i += 1) {
formData.append(key + '[' + i + ']', arr[i]);
}
} else {
file = files[key];
filename = getFilename(file) || null;
formData.append(key, file, filename);
}
}
}
} | javascript | {
"resource": ""
} |
q32044 | wrap | train | function wrap (factory, node, tag) {
// If there is a previous node that is not text, insert a new line to
// for
if (node.previousSibling != null && node.previousSibling.nodeType != 3) {
var newline = factory.createTextNode("\n");
body.insertBefore(newline, node);
}
var wrapper = factory.createElement(tag);
node.parentNode.insertBefore(wrapper, node);
wrapper.appendChild(node);
return wrapper;
} | javascript | {
"resource": ""
} |
q32045 | text | train | function text (factory, node, cursor) {
// Process a text node.
var parentNode = node.parentNode;
// If the node is CDATA convert it to text.
if (node.nodeType == 4) {
var text = factory.createTextNode(node.data);
parentNode.insertBefore(text, node);
parentNode.removeChild(node);
node = text;
}
var prev = node.previousSibling;
if (node.nodeType == 3) {
// Combine adjacent text nodes. You'll notice that this means that we
// might be reaching outside the range givne to us to normalize. That is
// if fine. The boundary is guidance to save time, not a firewall.
if (prev != null && prev.nodeType == 3) {
var text = factory.createTextNode(prev.data + node.data);
if (prev == cursor.node) {
cursor.node = text;
}
parentNode.insertBefore(text, prev);
parentNode.removeChild(prev);
parentNode.removeChild(node);
node = text;
}
// Remove duplicate whitespace.
if (/\s\s/.test(node.data)) {
var text = factory.createTextNode(node.data.replace(/\s\s+/g, " "));
parentNode.insertBefore(text, node);
parentNode.removeChild(node);
node = text;
}
}
return node;
} | javascript | {
"resource": ""
} |
q32046 | train | function (selector, context) {
if (typeof selector === 'string') {
if (context) {
var cont;
if (context.jquery) {
cont = context[0];
if (!cont) {
return context;
}
} else {
cont = context;
}
return $(cont.querySelectorAll(selector));
}
return $(document.querySelectorAll(selector));
}
return $(selector, context);
} | javascript | {
"resource": ""
} | |
q32047 | train | function (init) {
var arr = [];
if (!init) {
arr.push('data');
}
if (this.namespace.length > 0) {
arr.push(this.namespace);
}
arr.push(this.name);
return arr.join('-');
} | javascript | {
"resource": ""
} | |
q32048 | train | function (dropdown, target, settings, position) {
var sheet = Foundation.stylesheet,
pip_offset_base = 8;
if (dropdown.hasClass(settings.mega_class)) {
pip_offset_base = position.left + (target.outerWidth() / 2) - 8;
} else if (this.small()) {
pip_offset_base += position.left - 8;
}
this.rule_idx = sheet.cssRules.length;
//default
var sel_before = '.f-dropdown.open:before',
sel_after = '.f-dropdown.open:after',
css_before = 'left: ' + pip_offset_base + 'px;',
css_after = 'left: ' + (pip_offset_base - 1) + 'px;';
if (position.missRight == true) {
pip_offset_base = dropdown.outerWidth() - 23;
sel_before = '.f-dropdown.open:before',
sel_after = '.f-dropdown.open:after',
css_before = 'left: ' + pip_offset_base + 'px;',
css_after = 'left: ' + (pip_offset_base - 1) + 'px;';
}
//just a case where right is fired, but its not missing right
if (position.triggeredRight == true) {
sel_before = '.f-dropdown.open:before',
sel_after = '.f-dropdown.open:after',
css_before = 'left:-12px;',
css_after = 'left:-14px;';
}
if (sheet.insertRule) {
sheet.insertRule([sel_before, '{', css_before, '}'].join(' '), this.rule_idx);
sheet.insertRule([sel_after, '{', css_after, '}'].join(' '), this.rule_idx + 1);
} else {
sheet.addRule(sel_before, css_before, this.rule_idx);
sheet.addRule(sel_after, css_after, this.rule_idx + 1);
}
} | javascript | {
"resource": ""
} | |
q32049 | train | function (x1, y1, w, h, color, c)
{
_c = c || _c
if (color)
{
_c.fillStyle = color
}
box(x1 * _scale, y1 * _scale, w * _scale, h * _scale)
} | javascript | {
"resource": ""
} | |
q32050 | train | function (x0, y0, radius, color, c)
{
_c = c || _c
if (color)
{
_c.fillStyle = color
}
x0 *= _scale
y0 *= _scale
radius *= _scale
let x = radius
let y = 0
let decisionOver2 = 1 - x // Decision criterion divided by 2 evaluated at x=r, y=0
while (x >= y)
{
box(-x + x0, y + y0, x * 2, 1)
box(-y + x0, x + y0, y * 2, 1)
box(-x + x0, -y + y0, x * 2, 1)
box(-y + x0, -x + y0, y * 2, 1)
y++
if (decisionOver2 <= 0)
{
decisionOver2 += 2 * y + 1 // Change in decision criterion for y -> y+1
} else
{
x--
decisionOver2 += 2 * (y - x) + 1 // Change for y -> y+1, x -> x-1
}
}
} | javascript | {
"resource": ""
} | |
q32051 | train | function (x0, y0, width, height, c)
{
_c = c || _c
const data = _c.getImageData(x0, y0, width, height)
const bits = data.data
const pixels = []
for (let y = 0; y < height; y += _scale)
{
for (let x = 0; x < width; x += _scale)
{
const index = x * 4 + y * width * 4
if (bits[index + 3] === 0)
{
pixels.push(null)
}
else
{
const color = Color.rgbToHex(bits[index], bits[index + 1], bits[index + 2])
pixels.push(parseInt(color, 16))
}
}
}
return pixels
} | javascript | {
"resource": ""
} | |
q32052 | log | train | function log(arg) {
var str = JSON.stringify(arg)
console.log(str)
return str;
} | javascript | {
"resource": ""
} |
q32053 | picker | train | function picker(iteratees) {
iteratees = iteratees || ['name']
return _.partial(_.pick, _, iteratees)
} | javascript | {
"resource": ""
} |
q32054 | combineSplitters | train | function combineSplitters (splitters) {
var l = splitters.length
return function (str) {
for (var i = 0; i < l; i++) {
var result = splitters[i](str)
if (result) return result
}
}
} | javascript | {
"resource": ""
} |
q32055 | reducePlugins | train | function reducePlugins (plugins) {
var before = []
var split = []
var after = []
plugins.forEach(function (plugin) {
if (plugin.before) before.push(plugin.before)
if (plugin.split) split.push(plugin.split)
if (plugin.after) after.push(plugin.after)
})
return {
before: flow(before),
split: combineSplitters(split),
after: flow(after)
}
} | javascript | {
"resource": ""
} |
q32056 | getSongArtistTitle | train | function getSongArtistTitle (str, options, plugins) {
if (options) {
if (options.defaultArtist) {
plugins.push(fallBackToArtist(options.defaultArtist))
}
if (options.defaultTitle) {
plugins.push(fallBackToTitle(options.defaultTitle))
}
}
var plugin = reducePlugins(plugins)
checkPlugin(plugin)
var split = plugin.split(plugin.before(str))
if (!split) return
return plugin.after(split)
} | javascript | {
"resource": ""
} |
q32057 | flatten | train | function flatten(test) {
return {
title: test.title,
duration: test.duration,
err: test.err ? Object.assign({}, test.err) : null,
};
} | javascript | {
"resource": ""
} |
q32058 | BusinessRules | train | function BusinessRules(Data) {
this.Data = Data;
this.MainValidator = this.createMainValidator().CreateRule("Data");
this.ValidationResult = this.MainValidator.ValidationResult;
this.HobbiesNumberValidator = this.MainValidator.Validators["Hobbies"];
} | javascript | {
"resource": ""
} |
q32059 | clean | train | function clean(directoryPath, isRoot, done) {
fs.stat(directoryPath, function(err, stat) {
if (err) return done(isRoot ? undefined : err);
if (stat.isFile()) return fs.unlink(directoryPath, done);
fs.readdir(directoryPath, function(err, relativePaths) {
if (err) return done(err);
each(relativePaths, function(relativePath, next) {
var absolutePath = path.join(directoryPath, relativePath);
fs.stat(absolutePath, function(err, stats) {
if (err) return next(err);
if (!stats.isDirectory()) return fs.unlink(absolutePath, next);
clean(absolutePath, false, next);
});
}, function(err) {
if (err) return done(err);
fs.rmdir(directoryPath, done);
});
});
});
} | javascript | {
"resource": ""
} |
q32060 | getDirective | train | function getDirective (options, name) {
if (!options[name]) {
return null;
}
if (typeof options[name] === 'string') {
return name + ' ' + options[name];
}
if (Array.isArray(options[name])) {
let result = name + ' ';
options[name].forEach(value => {
result += value + ' ';
});
return result;
}
return null;
} | javascript | {
"resource": ""
} |
q32061 | train | function (file_system) {
if (file_system) {
if (successCallback) {
fileSystems.getFs(file_system.name, function (fs) {
// This should happen only on platforms that haven't implemented requestAllFileSystems (windows)
if (!fs) {
fs = new FileSystem(file_system.name, file_system.root);
}
successCallback(fs);
});
}
} else {
// no FileSystem object returned
fail(FileError.NOT_FOUND_ERR);
}
} | javascript | {
"resource": ""
} | |
q32062 | PiGlow | train | function PiGlow() {
var that = this;
this._wire = null;
this._currentState = null;
Emitter.call(this);
this._initialize(function (error) {
if (error) {
that.emit('error', error);
} else {
that.emit('initialize');
}
});
} | javascript | {
"resource": ""
} |
q32063 | buildErrorHandler | train | function buildErrorHandler(path) {
return function(node, text) {
throw path.hub.file.buildCodeFrameError(node, text);
}
} | javascript | {
"resource": ""
} |
q32064 | check_value | train | function check_value(val, min, max) {
val = +val;
if (typeof(val) != 'number' || val < min || val > max || Math.floor(val) !== val) {
throw new TypeError("\"value\" argument is out of bounds");
}
return val;
} | javascript | {
"resource": ""
} |
q32065 | check_bounds | train | function check_bounds(buf, offset, len) {
if (offset < 0 || offset + len > buf.length) {
throw new RangeError("Index out of range");
}
} | javascript | {
"resource": ""
} |
q32066 | compareAst | train | function compareAst(actualSrc, expectedSrc, options) {
var actualAst, expectedAst;
options = options || {};
if (!options.comparators) {
options.comparators = [];
}
/*
* A collection of comparator functions that recognize equivalent nodes
* that would otherwise be reported as unequal by simple object comparison.
* These may:
*
* - return `true` if the given nodes can be verified as equivalent with no
* further processing
* - return an instance of MatchError if the nodes are verified as
* uniquivalent
* - return any other value if equivalency cannot be determined
*/
Array.prototype.push.apply(options.comparators, [
require('./comparators/fuzzy-identifiers')(options),
require('./comparators/fuzzy-strings')(options)
]);
try {
actualAst = parse(actualSrc).body;
} catch(err) {
throw new Errors.ParseError();
}
try {
expectedAst = parse(expectedSrc).body;
} catch (err) {
throw new Errors.ParseError();
}
function _bind(actual, expected) {
var attr;
// Literal values
if (Object(actual) !== actual) {
if (actual !== expected) {
throw new Errors.MatchError(actualAst, expectedAst);
}
return;
}
// Arrays
if (Array.isArray(actual)) {
if (actual.length !== expected.length) {
throw new Errors.MatchError(actualAst, expectedAst);
}
actual.forEach(function(_, i) {
_bind(actual[i], expected[i]);
});
return;
}
// Nodes
normalizeMemberExpr(actual);
normalizeMemberExpr(expected);
if (checkEquivalency(options.comparators, actual, expected)) {
return;
}
// Either remove attributes or recurse on their values
for (attr in actual) {
if (expected && attr in expected) {
_bind(actual[attr], expected[attr]);
} else {
throw new Errors.MatchError(actualAst, expectedAst);
}
}
}
// Start recursing on the ASTs from the top level.
_bind(actualAst, expectedAst);
return null;
} | javascript | {
"resource": ""
} |
q32067 | plugin | train | function plugin() {
return function (files, metalsmith, done) {
Object.keys(files).forEach(function (file) {
setImmediate(done);
var pathslash = process.platform === 'win32' ? '\\' : '/';
var rootPath = '';
var levels = needles(file, pathslash);
for (var i = 0; i < levels; i++) {
rootPath += '../';
}
files[file].rootPath = rootPath;
});
};
} | javascript | {
"resource": ""
} |
q32068 | getDetailedObjectType | train | function getDetailedObjectType(thing) {
let prototype = Object.getPrototypeOf(thing)
if (!prototype) return NO_PROTOTYPE
return Object.getPrototypeOf(prototype)
? COMPLEX_OBJECT
: PLAIN_OBJECT
} | javascript | {
"resource": ""
} |
q32069 | BusinessRules | train | function BusinessRules(Data) {
this.Data = Data;
this.InvoiceValidator = this.createInvoiceValidator().CreateRule("Data");
this.ValidationResult = this.InvoiceValidator.ValidationResult;
} | javascript | {
"resource": ""
} |
q32070 | train | function (args) {
args.HasError = false;
args.ErrorMessage = "";
if (this.Items !== undefined && this.Items.length === 0) {
args.HasError = true;
args.ErrorMessage = "At least one item must be on invoice.";
args.TranslateArgs = { TranslateId: "AnyItem", MessageArgs: undefined };
return;
}
} | javascript | {
"resource": ""
} | |
q32071 | createPiGlow | train | function createPiGlow(callback) {
var myPiGlow = new PiGlowBackend();
var myInterface = piGlowInterface(myPiGlow);
myPiGlow
.on('initialize', function() {
callback(null, myInterface);
})
.on('error', function(error) {
callback(error, null);
});
} | javascript | {
"resource": ""
} |
q32072 | calcSteps | train | function calcSteps (min, max, room, width) {
var range = max - min
var i = 0, e
while(true) {
var e = Math.pow(10, i++)
if(e > 10000000000)
throw new Error('oops')
var re = range/e
var space = width*1.25
if(room / (re) > space) return e
if(room*2 / (re) > space) return e*2
if(room*2.5 / (re) > space) return e*2.5
if(room*5 / (re) > space) return e*5
}
} | javascript | {
"resource": ""
} |
q32073 | postQuery | train | function postQuery(statArr) {
var options = {
method: 'POST',
baseUrl: this.NEO4J_BASEURL,
url: this.NEO4J_ENDPT,
headers: {
'Accept': 'application/json; charset=UTF-8',
'Content-type': 'application/json'
},
json: {
statements: statArr
// [{statement: query, parameters: params},
// {statement: query, parameters: params}]
}
}
// call to the db server, returns a Promise
return request(options).then(resolver).catch(function(e) {
throw new Error(JSON.stringify(e))
})
} | javascript | {
"resource": ""
} |
q32074 | resolver | train | function resolver(obj) {
return new Promise(function(resolve, reject) {
_.isEmpty(obj.results) ? reject(new Error(JSON.stringify(obj.errors))) : resolve(obj.results);
})
} | javascript | {
"resource": ""
} |
q32075 | processValue | train | function processValue(value) {
if (isNaN(value)) return 0;
value = Math.max(MIN_VALUE, Math.min(value, MAX_VALUE));
//value is between 0 and 1, thus is interpreted as percentage
if (value < 1) value = value * MAX_VALUE;
value = parseInt(value, 10);
return value;
} | javascript | {
"resource": ""
} |
q32076 | train | function () {
if (this.Data.ExcludedDays == undefined || this.Data.ExcludedDays.length == 0)
return this.ExcludedWeekdays;
return _.union(this.ExcludedWeekdays, this.ExcludedDaysDatePart);
} | javascript | {
"resource": ""
} | |
q32077 | train | function (config, args) {
var msg = config["Msg"];
var format = config["Format"];
if (format != undefined) {
_.extend(args, {
FormatedFrom: moment(args.From).format(format),
FormatedTo: moment(args.To).format(format),
FormatedAttemptedValue: moment(args.AttemptedValue).format(format)
});
}
msg = msg.replace('From', 'FormatedFrom');
msg = msg.replace('To', 'FormatedTo');
msg = msg.replace('AttemptedValue', 'FormatedAttemptedValue');
return Utils.StringFce.format(msg, args);
} | javascript | {
"resource": ""
} | |
q32078 | train | function (args) {
args.HasError = false;
args.ErrorMessage = "";
//no dates - > nothing to validate
if (!_.isDate(this.From) || !_.isDate(this.To))
return;
if (self.FromDatePart.isAfter(self.ToDatePart)) {
args.HasError = true;
args.ErrorMessage = customErrorMessage({ Msg: "Date from '{From}' must be before date to '{To}'.", Format: 'MM/DD/YYYY' }, this);
args.TranslateArgs = { TranslateId: 'BeforeDate', MessageArgs: this, CustomMessage: customErrorMessage };
return;
}
var minDays = 1;
var maxDays = 25;
//maximal duration
if (self.IsOverLimitRange || (self.VacationDaysCount > maxDays || self.VacationDaysCount < minDays)) {
args.HasError = true;
var messageArgs = { MaxDays: maxDays, MinDays: minDays };
args.ErrorMessage = Utils.StringFce.format("Vacation duration value must be between {MinDays] and {MaxDays} days.", messageArgs);
args.TranslateArgs = { TranslateId: 'RangeDuration', MessageArgs: messageArgs };
return;
}
var diff = _.difference(self.ExcludedDaysDatePart, self.RangeDays);
if (diff.length != 0) {
args.HasError = true;
var messageArgs2 = { ExcludedDates: _.reduce(diff, function (memo, item) {
return memo + item.format("MM/DD/YYYY");
}) };
args.ErrorMessage = Utils.StringFce.format("Excluded days are not in range. '{ExcludedDates}'.", messageArgs2);
args.TranslateArgs = { TranslateId: 'ExcludedDaysMsg', MessageArgs: messageArgs2 };
return;
}
} | javascript | {
"resource": ""
} | |
q32079 | train | function (args) {
args.HasError = false;
args.ErrorMessage = "";
var greaterThanToday = new VacationApproval.FromToDateValidator();
greaterThanToday.FromOperator = 4 /* GreaterThanEqual */;
greaterThanToday.From = new Date();
greaterThanToday.ToOperator = 1 /* LessThanEqual */;
greaterThanToday.To = this.Duration.From;
greaterThanToday.IgnoreTime = true;
if (!greaterThanToday.isAcceptable(this.Approval.ApprovedDate)) {
args.HasError = true;
args.ErrorMessage = greaterThanToday.customMessage({
"Format": "MM/DD/YYYY",
"Msg": "Date must be between ('{From}' - '{To}')."
}, greaterThanToday);
args.TranslateArgs = { TranslateId: greaterThanToday.tagName, MessageArgs: greaterThanToday, CustomMessage: greaterThanToday.customMessage };
return;
}
} | javascript | {
"resource": ""
} | |
q32080 | onError | train | function onError (e) {
switch (e.target.errorCode) {
case 12:
console.log('Error - Attempt to open db with a lower version than the ' +
'current one.');
break;
default:
console.log('errorCode: ' + e.target.errorCode);
}
console.log(e, e.code, e.message);
} | javascript | {
"resource": ""
} |
q32081 | embed | train | function embed(sourcePath, relativePaths, name, done) {
var items = '';
each(relativePaths, function(relativePath, next) {
var fullPath = path.join(sourcePath, relativePath);
fs.readFile(fullPath, 'utf8', function(err, text) {
if (err) return next(err);
items += ' $templateCache.put(\'' +
inline(relativePath) + '\', \'' +
inline(text.trim()) + '\');\n';
next();
});
}, function(err) {
if (err) return done(err);
console.log(
'angular.module(\'' + inline(name) + '\', []).run([\'$templateCache\', function($templateCache) {\n' +
items +
'}]);');
done();
});
} | javascript | {
"resource": ""
} |
q32082 | inline | train | function inline(text) {
var result = '';
for (var i = 0; i < text.length; i += 1) {
var value = text.charAt(i);
if (value === '\'') result += '\\\'';
else if (value === '\\') result += '\\\\';
else if (value === '\b') result += '\\b';
else if (value === '\f') result += '\\f';
else if (value === '\n') result += '\\n';
else if (value === '\r') result += '\\r';
else if (value === '\t') result += '\\t';
else result += value;
}
return result;
} | javascript | {
"resource": ""
} |
q32083 | parseArray | train | function parseArray(str) {
return R.filter(R.identity, str.split(',').map(R.invoker(0, 'trim')))
} | javascript | {
"resource": ""
} |
q32084 | stringifyIndented | train | function stringifyIndented(value, chr, n) {
return indent(JSON.stringify(value, null, n), chr, n).slice(chr.length * n)
} | javascript | {
"resource": ""
} |
q32085 | train | function () {
var done = this.async();
if(this.createMode) {
// copy yoga-generator itself
this.fs.copy(path.join(__dirname, '../'), this.destinationPath(), {
globOptions: {
dot: true,
ignore: [
'**/.DS_Store',
'**/.git',
'**/.git/**/*',
'**/node_modules',
'**/node_modules/**/*',
'**/test/**/*',
'**/create/**/*'
]
}
})
// copy the package.json and README
this.fs.copyTpl(path.join(__dirname, '../create/{}package.json'), this.destinationPath('package.json'), this.viewData)
this.fs.copyTpl(path.join(__dirname, '../create/README.md'), this.destinationPath('README.md'), this.viewData)
done()
}
else {
this.registerTransformStream(striate(this.viewData))
prefixnote.parseFiles(this.templatePath(), this.viewData)
// copy each file that is traversed
.on('data', function (file) {
var filename = path.basename(file.original)
// always ignore files like .DS_Store
if(ignore.indexOf(filename) === -1) {
var from = file.original
var to = this.destinationPath(path.relative(this.templatePath(), file.parsed))
// copy the file with templating
this.fs.copyTpl(from, to, this.viewData)
}
}.bind(this))
.on('end', done)
.on('error', done)
}
} | javascript | {
"resource": ""
} | |
q32086 | parseManifest | train | function parseManifest(manifest, docroot, callback)
{
var inCache = false
, lines = [];
// get manifest file data
fs.readFile(manifest, 'ascii', function(err, data)
{
var counter = 0;
if (err)
{
// to prevent sudden continuation
return callback(err);
}
cache[manifest] =
{
version: 0,
files: [],
manifest: data
};
lines = data.split('\n');
lines.forEach(function(line)
{
var match;
line = line.trim();
// empty lines
if (line.substr(0, 1) == '') return;
// skip comments
if (line.substr(0, 1) == '#') return;
// process control keywords
switch (line)
{
case 'CACHE MANIFEST':
case 'CACHE:':
inCache = true;
return;
break;
// TODO: Add proper support for fallbacks
case 'NETWORK:':
case 'FALLBACK:':
inCache = false;
return;
break;
}
// do nothing for network files
if (!inCache) return;
// check the file and setup monitoring
if (!line.match(/^http(s)?:\/\//))
{
addWatcher(docroot+line, watcher(manifest), function(added, mtime)
{
// undo counter
counter--;
if (!added)
{
// check if everything is done
if (counter == 0) callback();
return;
}
if (mtime > cache[manifest].version) cache[manifest].version = mtime;
cache[manifest].files.push(line);
// check if everything is done
if (counter == 0) callback();
});
// track inception
counter++;
}
});
});
} | javascript | {
"resource": ""
} |
q32087 | addWatcher | train | function addWatcher(file, handler, callback)
{
fs.stat(file, function(err, stat)
{
if (err) return callback(false);
fs.watch(file, handler(file));
callback(true, stat.mtime.getTime());
});
} | javascript | {
"resource": ""
} |
q32088 | watcher | train | function watcher(manifest)
{
return function(file)
{
return function(event)
{
if (event == 'change')
{
fs.stat(file, function(err, stat)
{
if (err) return; // do nothing at this point
var mtime = stat.mtime.getTime();
if (cache[manifest].version < mtime) cache[manifest].version = mtime;
});
}
// TODO: add support for rename, maybe
};
}
} | javascript | {
"resource": ""
} |
q32089 | Agent | train | function Agent (plugin) {
var events = require('events')
var util = require('util')
var eventEmitter = new events.EventEmitter()
var cluster = require('cluster')
var workerId = 0 + '-' + process.pid // 0 == Master, default
if (!cluster.isMaster) {
workerId = cluster.worker.id + '-' + process.pid
}
var agentSuperClass = {
plugin: plugin,
defaultType: 'njs',
defaultFilters: function () {
return [workerId || 0, process.pid || 0]
},
metricBuffer: [],
/**
* Adds a metric value and emits event to listeners on 'metric' or metric.name
* @param metric
*/
addMetrics: function (metric) {
metric.workerId = workerId
metric.pid = process.pid
if (!metric.sct) {
if (metric.name && /collectd/.test(metric.name)) {
metric.sct = 'OS'
} else {
metric.sct = 'APP'
}
}
if (!metric.ts) {
metric.ts = new Date().getTime()
}
if (!metric.type) {
metric.type = this.defaultType
}
if (!metric.filters && metric.type === 'njs') {
metric.filters = this.defaultFilters()
}
metric.spmLine = this.formatLine(metric)
this.emit('metric', metric)
if (metric.name) {
this.emit(metric.name, metric)
}
},
collectdFormatLine: function (metric) {
var now = (new Date().getTime()).toFixed(0)
var metricsTs = (metric.ts).toFixed(0)
var metricsTs2 = (metric.ts / 1000).toFixed(0)
var dateString = moment(metric.ts).format('YYYY-MM-DD')
var line = ''
if ((/collectd.*\-/.test(metric.name))) {
if (/collectd\-cpu/.test(metric.name) || /collectd\-io\-octets/.test(metric.name)) {
line = (now + '\t' + metric.name + '-' + dateString + ',' + metricsTs2 + ',' + metric.value)
} else if (/disk/.test(metric.name)) {
line = (now + '\t' + metric.name + '-' + dateString + ',' + metricsTs2 + ',' + metric.value.toFixed(6))
} else {
line = now + '\t' + metric.name + '\t' + metricsTs2 + ',' + metric.value
}
} else {
line = now + '\t' + metric.name + '\t' + metricsTs + ',' + metric.value
}
return line
},
defaultFormatLine: function (metric) {
var now = (new Date().getTime()).toFixed(0)
var line = null
if (metric.sct === 'OS') {
line = this.collectdFormatLine(metric)
} else {
line = util.format('%d\t%s\t%d\t%s\t%s', now, (metric.type || this.defaultType) + '-' + metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value))
logger.log(line)
}
return line
},
/**
* formats a line for SPM sender, if the plugin does not support this method the default formatter for nodejs and OP metrics is used
* @maram metric to format
*/
formatLine: function (metric) {
if (!this.plugin.formatLine) {
return this.defaultFormatLine(metric)
} else {
return this.plugin.formatLine(metric)
}
},
/**
* Starts the agent - typically thy create listeners or interval checks for metrics, and use 'addMetrics' to inform listeners
*/
start: function () {
if (this.plugin && this.plugin.start) {
// this is the place to register for external events that return metrics
this.plugin.start(this)
} else {
console.log('NOT called start')
}
},
/**
* Stops the plugin - timers could be pushed to plugins 'timers' Array, if timers exists it tries to clearInterval(timerId)
* if no timers are defined it tries to call stop method of the plugin
*/
stop: function () {
if (this.plugin.timers) {
this.plugin.timers.forEach(function (tid) {
clearInterval(tid)
})
} else {
if (this.plugin.stop) {
this.plugin.stop()
} else {
logger.warn('could not stop agent')
}
}
}
}
return util._extend(eventEmitter, agentSuperClass)
} | javascript | {
"resource": ""
} |
q32090 | train | function (metric) {
metric.workerId = workerId
metric.pid = process.pid
if (!metric.sct) {
if (metric.name && /collectd/.test(metric.name)) {
metric.sct = 'OS'
} else {
metric.sct = 'APP'
}
}
if (!metric.ts) {
metric.ts = new Date().getTime()
}
if (!metric.type) {
metric.type = this.defaultType
}
if (!metric.filters && metric.type === 'njs') {
metric.filters = this.defaultFilters()
}
metric.spmLine = this.formatLine(metric)
this.emit('metric', metric)
if (metric.name) {
this.emit(metric.name, metric)
}
} | javascript | {
"resource": ""
} | |
q32091 | redirect | train | function redirect(id, prefix, suffix, res) {
var validatedID = reelib.identifier.toIdentifierString(id);
if(validatedID && (validatedID !== id)) {
res.redirect(prefix + validatedID + suffix);
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q32092 | main | train | function main(program) {
program || (program = { args: [] });
if(program.args.length === 0) {
program.outputHelp();
return process.exit(1);
}
return Promise
.map(program.args, _.partial(exports.downloadPosting, program))
.map(function(html) {
return cheerio.load(html);
})
.map(exports.extractInfo)
.then(_.partial(exports.outputInfo, program));
} | javascript | {
"resource": ""
} |
q32093 | mixAppend | train | function mixAppend(to)
{
var args = Array.prototype.slice.call(arguments)
, i = 0
;
// it will start with `1` – second argument
// leaving `to` out of the loop
while (++i < args.length)
{
copy(to, args[i]);
}
return to;
} | javascript | {
"resource": ""
} |
q32094 | train | function(rec, key) {
return (function() {
if (typeof key === "symbol") {
return undefined;
}
if (key === scopeName) {
return scope;
}
if (key === indicator) {
return proxy;
}
if (key.slice(-1) === indicator) {
builder.pushSingleToken(key.slice(0,key.length-1));
var classproxy = makeProxy({
get: function(rec, key) {
if (typeof key === "symbol") {
return undefined;
}
builder.addClass(key);
return classproxy;
}
},
function(obj) {
builder.rewriteSingleTokenAttributes(obj);
return classproxy;
});
return classproxy;
} else if (key.slice(0,1) === indicator) {
builder.pushEndToken(key.slice(1));
return {
valueOf: function() {
if (shortcuts.hasOwnProperty(key)) {
var args = builder.dropLastToken();
shortcuts[key](builder, scope, args);
} else {
throw new Error('Attempted to call nonexistant shortcut');
}
return 0;
}
}
} else {
builder.pushStartToken(key);
var classproxy = makeProxy({
get: function(rec, nkey) {
if (typeof nkey === "symbol") {
return undefined;
}
if (nkey === 'valueOf') {
if (shortcuts.hasOwnProperty(key)) {
var args = builder.dropLastToken();
shortcuts[key](builder, scope, args);
} else {
throw new Error('Attempted to call nonexistant shortcut');
}
return function() {return 0};
}
builder.addClass(nkey);
return classproxy;
}
},
function(obj) {
builder.rewriteStartTokenAttributes(obj);
return classproxy;
});
return classproxy;
}
})();
} | javascript | {
"resource": ""
} | |
q32095 | prepareFunc | train | function prepareFunc(func, builder, basepath) { //Prepare an implied function for repeated use
funcStringCache[func] = funcStringCache[func] || ('(function() { with (proxy(scope)) { return ('+func.toString()+')('+defaultScopeName+'); } })()');
return function(scope) {
var scope = scope || {};
var builder = builder || stringBuilder;
var proxy = jshtmlProxy(new builder(basepath));
var ret = eval(funcStringCache[func]);
if (ret && typeof(ret.then) === 'function') { //looks like a promise. Let's use it why don't we?
ret.proxy = proxy;
return ret;
}
return proxy.collect();
}
} | javascript | {
"resource": ""
} |
q32096 | mixChain | train | function mixChain()
{
var args = Array.prototype.slice.call(arguments)
, i = args.length
;
while (--i > 0)
{
args[i-1].__proto__ = args[i];
}
return args[i];
} | javascript | {
"resource": ""
} |
q32097 | train | function (remoteUrl) {
if (remoteUrl.indexOf('http') !== 0) {
grunt.log.error('Something seems wrong with this remote url: ' + remoteUrl);
}
return remoteUrl.toLowerCase().replace('://', '@@').replace(/\?/g, '@');
} | javascript | {
"resource": ""
} | |
q32098 | train | function (tplUrl, data) {
if (urlPrefix) {
tplUrl = urlPrefix + tplUrl;
}
if (urlSuffix) {
tplUrl += urlSuffix;
}
var html = '';
debug(' retrieve remote content from ' + tplUrl);
var remoteFragmentKey = getTemplateCacheKeyFromRemoteUrl(tplUrl);
if (data && !data.cache) {
html = retrieveFromUrl(tplUrl, remoteFragmentKey, true);
} else {
if (!_.has(cache, remoteFragmentKey)) {
cache[remoteFragmentKey] = retrieveFromUrl(tplUrl, remoteFragmentKey, false);
debug(' stash content in memory');
} else {
debug(' get content from memory');
}
html = getTemplateFromCache(remoteFragmentKey);
}
return html;
} | javascript | {
"resource": ""
} | |
q32099 | train | function (tplName, data, ignoreEvaluation) {
var files, templateData, html = '';
if (typeof data !== 'object') {
ignoreEvaluation = data;
data = {};
}
data = _.extend({}, options.data, data);
if (_.has(templates, tplName)) {
debug(' include ' + templates[tplName].filepath);
files = _.clone(this.files);
files.push(templates[tplName].filepath);
templateData = {
files: files
};
data.include = include.bind(templateData);
try {
if (ignoreEvaluation) {
html = templates[tplName].content;
} else {
html = _.template(templates[tplName].content, options.templateSettings)(data);
}
} catch (error) {
grunt.log.error(error.message);
backtrace(files);
}
} else {
grunt.log.writeln('Template "' + tplName + '" does not exists.');
backtrace(this.files);
}
return html;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.