_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q34100 | remove_script_tags | train | function remove_script_tags(){
html = html.replace(/<script[^>]*>.*?<\/script>/g, function(str){
if (str.match(/ type=/) && ! str.match(/text\/javascript/)) { return str; }
else if (str.match(/src=['"]?(https?)/)) { return str; }
else if (str.match(/src=['"]?\/\//)) { return str; }
else if (! options.clean_scripts && str.match(/src=['"]/)) { return str; }
else { return ""; }
});
} | javascript | {
"resource": ""
} |
q34101 | remove_stylesheet_tags | train | function remove_stylesheet_tags() {
// We can remove the style tag with impunity, it is always inlining.
html = html.replace(/<style.+?<\/style>/g, "");
// External style resources use the link tag, check again for externals.
if (options.clean_stylesheets) {
html = html.replace(/<link[^>]+>/g, function(str){
if (str.match(/src=/)) {
grunt.log.warn('Found LINK tag with SRC attribute.');
return str;
}
else if (! str.match(/ rel=['"]?stylesheet/)) { return str; }
else if (str.match(/href=['"]?https?/)) { return str; }
else if (str.match(/href=['"]?\/\//)) { return str; }
else { return ""; }
});
}
} | javascript | {
"resource": ""
} |
q34102 | remove_comments | train | function remove_comments(){
if (options.clean_comments) {
html = html.replace(/<!--[\s\S]*?-->/g, function(str){
if (str.match(/<!--\[if /)) { return str; }
if (str.match(/\n/)) { return str; }
else { return ""; }
});
}
} | javascript | {
"resource": ""
} |
q34103 | inject | train | function inject (tag, shims){
var added = shims.some(function(shim){
var i = html.lastIndexOf(shim);
if (i !== -1) {
html = html.substr(0, i) + tag + html.substr(i);
return true;
}
return false;
});
// Failing that, just append it.
if (! added) {
html += tag;
}
} | javascript | {
"resource": ""
} |
q34104 | inject_script_shim | train | function inject_script_shim () {
if (options.include_js) {
var script_tag = '<script type="text/javascript" src="' + options.include_js + '"></script>';
if (options.js_insert_marker && html.indexOf(options.js_insert_marker) !== -1) {
html = html.replace(options.js_insert_marker, script_tag);
}
else {
var shims = ["</body>", "</html>", "</head>"];
inject(script_tag, shims);
}
}
} | javascript | {
"resource": ""
} |
q34105 | inject_stylesheet_shim | train | function inject_stylesheet_shim () {
if (options.include_css) {
var style_tag = '<link rel="stylesheet" type="text/css" href="' + options.include_css + '">';
if (options.css_insert_marker && html.indexOf(options.css_insert_marker) !== -1) {
html = html.replace(options.css_insert_marker, style_tag);
}
else {
var shims = ["</head>", "<body>", "</html>"];
inject(style_tag, shims);
}
}
} | javascript | {
"resource": ""
} |
q34106 | write_css | train | function write_css () {
if (dest.dest_css) {
grunt.file.write(dest.dest_css, strip_whitespace(styles.join("\n")));
grunt.log.writeln('Stylesheet ' + dest.dest_css + '" extracted.');
}
} | javascript | {
"resource": ""
} |
q34107 | write_js | train | function write_js () {
if (dest.dest_js) {
grunt.file.write(dest.dest_js, strip_whitespace(scripts.join(";\n")));
grunt.log.writeln('Script "' + dest.dest_js + '" extracted.');
}
} | javascript | {
"resource": ""
} |
q34108 | write_html | train | function write_html () {
if (dest.dest_html) {
grunt.file.write(dest.dest_html, strip_whitespace(html));
grunt.log.writeln('Document "' + dest.dest_html + '" extracted.');
}
} | javascript | {
"resource": ""
} |
q34109 | run_dentist | train | function run_dentist() {
if (load_files() && parse_html()) {
if (dest.dest_html) {
if (dest.dest_js) {
remove_inline_scripts();
remove_script_tags();
inject_script_shim();
}
if (dest.dest_css) {
remove_inline_stylesheets();
remove_stylesheet_tags();
inject_stylesheet_shim();
}
}
remove_comments();
write_js();
write_css();
write_html();
return true;
}
else {
return false;
}
} | javascript | {
"resource": ""
} |
q34110 | scrapeEnergies | train | function scrapeEnergies(el, $, func) {
const $el = $(el);
$el.find("li").each(function (i, val) {
const $val = $(val);
const type = $val.attr("title");
func(type, $val);
});
} | javascript | {
"resource": ""
} |
q34111 | scrapeAll | train | function scrapeAll(query, scrapeDetails) {
return co(function *() {
//By default, scrape the card details
scrapeDetails = scrapeDetails === undefined ? true : scrapeDetails;
//Load the HTML page
const scrapeURL = makeUrl(SCRAPE_URL, query);
const search = yield scrapeSearchPage(scrapeURL);
//Recurring variables
var cards = search.cards;
var i;
//Scrape all of the pages sequentially;
for (i = 2; i <= search.numPages; i++) {
const scrapeURL = makeUrl(Url.resolve(SCRAPE_URL, i.toString()), query);
const results = yield scrapeSearchPage(scrapeURL);
cards = cards.concat(results.cards);
}
//Scrape all of the cards sequentially if requested
if (scrapeDetails) {
for (i = 0; i < cards.length; i++) {
const card = cards[i];
_.assign(card, yield scrapeCard(card.url));
}
}
return cards;
})();
} | javascript | {
"resource": ""
} |
q34112 | matchSQLFilter | train | function matchSQLFilter(tableSchema, whereCol) {
for (var i in whereCol) {
var col = whereCol[i],
schema = tableSchema[col.tbName];
if (!schema)
throw new Error('A filter column refers to an unknown table [' + col.tbName + ']');
if (schema.columns.indexOf(col.col) < 0)
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q34113 | collectFilterColumns | train | function collectFilterColumns(dftTable, filter, col) {
var isLogical = false;
if (filter.op === 'AND' || filter.op === 'and' || filter.op === 'OR' || filter.op === 'or') {
filter.op = filter.op.toLowerCase();
isLogical = true;
}
if (isLogical) {
filter.filters.forEach(function(f) {
collectFilterColumns(dftTable, f, col);
});
}
else {
var colName = filter.field || filter.name,
fc = {tbName: dftTable, col: colName, orig: colName},
idx = colName.indexOf('.');
if (idx > 0) {
fc.tbName = colName.substring(0, idx);
fc.col = colName.substring(idx+1);
}
if (_.findIndex(col, fc) < 0)
col.push(fc);
}
} | javascript | {
"resource": ""
} |
q34114 | buildSqlFilter | train | function buildSqlFilter(filter, columns) {
if (filter.op === 'and') {
var clones = [];
filter.filters.forEach(function(f) {
var cf = buildSqlFilter(f, columns);
if (cf)
clones.push( cf );
});
var len = clones.length;
if (len < 1)
return null;
else
return len > 1 ? {op: 'and', filters: clones} : clones[0];
}
else if (filter.op === 'or') {
var clones = [];
filter.filters.forEach(function(f) {
var cf = buildSqlFilter(f, columns);
if (cf)
clones.push( cf );
});
return clones.length === filter.filters.length ? {op: 'or', filters: clones} : null;
}
var cf = null,
colName = filter.name;
if (columns.indexOf(colName) >= 0)
cf = filter; //cloneObj( filter );
return cf;
} | javascript | {
"resource": ""
} |
q34115 | writeFile | train | function writeFile(file, content) {
fs.writeFileSync(file, content);
files.push(path.relative(app.components.get('path'), file));
} | javascript | {
"resource": ""
} |
q34116 | configureComponent | train | function configureComponent(configPath, component, componentPath) {
let config;
try {
config = require(configPath);
// If this is the default variant
if (!component.variant) {
config.title = component.name;
config.status = component.status;
config.context = config.context || {};
config.context.type = component.type;
}
config.variants = config.variants || [];
} catch (e) {
config = {
title: component.name,
status: component.status,
context: {
type: component.type,
},
variants: [],
};
}
// Register the preview component
if (component.preview) {
config.preview = `@${[...componentPath, dashify(component.name), 'preview'].join('-')}`;
}
// Remove the variant if already present
const variant = component.variant || 'default';
config.variants = config.variants.filter(vt => vt.name !== variant);
// Register the variant
config.variants.push({
name: variant,
label: component.label || ((variant === 'default') ? component.name : variant),
context: {
config: component.config,
parameters: component.parameters || {},
request: component.request,
component: component.class,
},
});
config.variants = config.variants.sort((a, b) => {
const aName = a.label.toLowerCase();
const bName = b.label.toLowerCase();
if (aName > bName) {
return 1;
}
return (aName < bName) ? -1 : 0;
});
config.variants.forEach((v, i) => {
config.variants[i].order = i;
});
// Write the configuration file
writeFile(configPath, JSON.stringify(config, null, 4));
// If there's a component note
if ((variant === 'default') && component.notice) {
const readme = path.join(path.dirname(configPath), 'README.md');
writeFile(readme, component.notice);
}
} | javascript | {
"resource": ""
} |
q34117 | createCollection | train | function createCollection(dirPrefix, dirPath, dirConfigs) {
const dir = dirPath.shift();
const dirConfig = dirConfigs.shift() || {};
const absDir = path.join(dirPrefix, dir);
// Create the collection directory
try {
if (!fs.statSync(absDir).isDirectory()) {
throw new Error('1');
}
} catch (e) {
try {
if (!mkdirp(absDir)) {
throw new Error('2');
}
} catch (f) {
return false;
}
}
// Configure the collection prefix
const configPath = path.join(absDir, `${dir.replace(/^\d{2}-/, '')}.config.json`);
const prefix = path.relative(app.components.get('path'), absDir).split(path.sep).map(p => p.replace(/^\d{2}-/, '')).join('-');
let config;
try {
config = require(configPath);
config.prefix = prefix;
} catch (e) {
config = { prefix };
}
['label'].forEach(c => {
if (c in dirConfig) {
config[c] = dirConfig[c];
}
})
writeFile(configPath, JSON.stringify(config, null, 4));
// Recurse
return dirPath.length ? createCollection(absDir, dirPath, dirConfigs) : true;
} | javascript | {
"resource": ""
} |
q34118 | registerComponent | train | function registerComponent(component) {
const componentName = dashify(component.name);
const componentLocalConfig = (component.local instanceof Array) ? component.local : [];
while (componentLocalConfig.length < component.path.length) {
componentLocalConfig.push([]);
}
const componentPath = component.path.slice(0).map(p => dashify(p));
const componentRealPath = componentPath.map((p, i) => {
return componentLocalConfig[i].dirsort ?
`${(new String(componentLocalConfig[i].dirsort)).padStart(2, '0')}-${p}` : p;
});
const componentParent = path.join(app.components.get('path'), ...componentRealPath);
const componentDirectory = path.join(componentParent, componentName);
// Create the component directory
if (!createCollection(app.components.get('path'), [...componentRealPath, componentName], componentLocalConfig)) {
throw new Error(`Could not create component directory ${componentDirectory}`);
}
// Write out the template file
const componentVariantName = componentName + (component.variant ? `--${dashify(component.variant)}` : '');
const componentTemplate = path.join(componentDirectory, `${componentVariantName}.${component.extension}`);
writeFile(componentTemplate, component.template);
// Write out the preview template
if (component.preview) {
writeFile(path.join(componentParent, `_${componentName}-preview.t3s`), component.preview);
}
// Configure the component
configureComponent(path.join(componentDirectory, `${componentName}.config.json`), component, componentPath);
} | javascript | {
"resource": ""
} |
q34119 | update | train | function update(args, done) {
app = this.fractal;
let typo3cli = path.join(typo3path, '../vendor/bin/typo3');
let typo3args = ['extbase', 'component:discover'];
try {
if (fs.statSync(typo3cli).isFile()) {
typo3args.shift();
}
} catch (e) {
typo3cli = path.join(typo3path, 'typo3/cli_dispatch.phpsh');
}
try {
if (fs.statSync(typo3cli).isFile()) {
typo3args.unshift(typo3cli);
const componentsJSON = execFileSync('php', typo3args).toString();
const components = JSON.parse(componentsJSON);
for (const component of components) {
processComponent(component);
}
// Write the general shared context
const context = { context: { typo3: typo3url } };
writeFile(path.resolve(app.components.get('path'), 'components.config.json'), JSON.stringify(context, null, 4));
// See if there's a component file manifest
const manifest = path.resolve(app.components.get('path'), 'components.files.json');
try {
if (fs.statSync(manifest).isFile()) {
const currentFiles = new Set(files);
const prevFiles = new Set(JSON.parse(fs.readFileSync(manifest)));
// Delete all redundant files
[...prevFiles].filter(f => !currentFiles.has(f)).forEach(f => fs.unlinkSync(path.resolve(app.components.get('path'), f)));
}
} catch (e) {
// Ignore errors
} finally {
writeFile(manifest, JSON.stringify(files));
deleteEmpty.sync(app.components.get('path'));
}
}
done();
} catch (e) {
console.log(e);
process.exit(1);
}
} | javascript | {
"resource": ""
} |
q34120 | encodeURIParams | train | function encodeURIParams(params, prefix) {
let parts = [];
for (const name in params) {
if (Object.prototype.hasOwnProperty.call(params, name)) {
const paramName = prefix ? (`${prefix}[${encodeURIComponent(name)}]`) : encodeURIComponent(name);
if (typeof params[name] === 'object') {
parts = Array.prototype.concat.apply(parts,
encodeURIParams(params[name], paramName));
} else {
parts.push(`${paramName}=${encodeURIComponent(params[name])}`);
}
}
}
return parts;
} | javascript | {
"resource": ""
} |
q34121 | componentGraphUrl | train | function componentGraphUrl(component) {
const context = ('variants' in component) ? component.variants().default().context : component.context;
const graphUrl = url.parse(context.typo3);
graphUrl.search = `?${encodeURIParams(Object.assign(context.request.arguments, {
tx_twcomponentlibrary_component: { component: context.component },
type: 2401,
})).join('&')}`;
return url.format(graphUrl);
} | javascript | {
"resource": ""
} |
q34122 | configure | train | function configure(t3path, t3url, t3theme) {
typo3path = t3path;
typo3url = t3url;
// If a Fractal theme is given
if ((typeof t3theme === 'object') && (typeof t3theme.options === 'function')) {
t3theme.addLoadPath(path.resolve(__dirname, 'lib', 'views'));
// Add the graph panel
const options = t3theme.options();
if (options.panels.indexOf('graph') < 0) {
options.panels.push('graph');
}
t3theme.options(options);
t3theme.addListener('init', (engine) => {
engine._engine.addFilter('componentGraphUrl', componentGraphUrl);
});
}
} | javascript | {
"resource": ""
} |
q34123 | engine | train | function engine() {
return {
register(source, gapp) {
const typo3Engine = require('./lib/typo3.js');
const handlebars = require('@frctl/handlebars');
typo3Engine.handlebars = handlebars({}).register(source, gapp);
typo3Engine.handlebars.load();
return new TYPO3Adapter(typo3Engine, source); // , gapp
},
};
} | javascript | {
"resource": ""
} |
q34124 | drawUpperTriangle | train | function drawUpperTriangle(d, loc) {
if (d == "r") {
var first = {x: 50, y: 0};
var second = {x: 50, y: 50};
} else {
var first = {x: 50, y: 0};
var second = {x: 0, y: 50};
}
context.beginPath();
context.moveTo(loc.x, loc.y);
context.lineTo(loc.x + first.x, loc.y + first.y);
context.lineTo(loc.x + second.x, loc.y + second.y);
context.lineTo(loc.x, loc.y);
context.lineWidth = 1;
context.strokeStyle = 'black';
context.stroke();
context.fillStyle = fill;
context.fill();
context.closePath();
} | javascript | {
"resource": ""
} |
q34125 | drawBadCells | train | function drawBadCells(cells) {
var context = c.getContext('2d');
var canvas = c; // from global.
// Drawing bad cells
var draw_loc = {x: 0, y: 0};
for (var i = 0; i < cells.length; i++) {
var cell_info = cells[i];
var cell = cell_info[0];
var matched_entrances = cell_info[1];
var matched_exits = cell_info[2]
// Write information.
context.fillStyle = 'black';
context.fillText(cell.toString(), draw_loc.x + 5, draw_loc.y + 10)
context.fillText("ents:" + matched_entrances.length, draw_loc.x + 5, draw_loc.y + 20)
context.fillText("exts:" + matched_exits.length, draw_loc.x + 5, draw_loc.y + 35)
drawCell(cell, canvas, {x: draw_loc.x + text_width, y: draw_loc.y});
// Increment drawing location.
if ((i % 5) == 4) {
draw_loc = {x: 0, y: draw_loc.y + total_width};
} else {
draw_loc = {x: draw_loc.x + total_width, y: draw_loc.y};
}
}
} | javascript | {
"resource": ""
} |
q34126 | getIndexForLoc | train | function getIndexForLoc(loc) {
var col = Math.floor(loc.x / total_width);
var row = Math.floor(loc.y / total_width);
var index = col + (row * 5);
return index;
} | javascript | {
"resource": ""
} |
q34127 | handleIncomingMessage | train | function handleIncomingMessage(event, message, source) {
var blocks = event.split(':'),
id = blocks[2] || blocks[1];
if (id in self.transactions && source in self.transactions[id]) {
self.transactions[id][source].resolve([message, source]);
}
} | javascript | {
"resource": ""
} |
q34128 | handleControlConnection | train | function handleControlConnection(connection) {
connection.on('data', function (data) {
console.log('Got command:', data.toString().trim());
var request = data.toString().trim().split(' '),
cmd = request[0],
target = request[1],
newline = '\r\n',
response;
console.log('Command is:', cmd);
switch (cmd) {
case 'start':
console.log('got here');
self.store.broadcast('worker:start', target);
response = lib.format('Starting {0} servers.', (target || 'all'));
break;
case 'pause':
self.store.broadcast('worker:pause', target);
response = lib.format('Pausing {0} servers.', (target || 'all'));
break;
case 'stop':
self.store.broadcast('worker:stop', target);
response = lib.format('Stopping {0} servers.', (target || 'all'));
break;
case 'resume':
self.store.broadcast('worker:resume', target);
response = lib.format('Resuming {0} servers.', (target || 'all'));
break;
case 'heartbeat':
var id = lib.guid();
self.store.broadcast('worker:heartbeat', id);
wait(id, function () {
var args = Array.prototype.slice.call(arguments),
response = {};
lib.each(args, function (data) {
var message = data[0],
worker = data[1];
response[worker] = message;
});
connection.write(JSON.stringify(response));
connection.end(newline);
});
break;
case 'stats':
var id = lib.guid();
self.store.broadcast('worker:stats', id);
wait(id, function () {
var args = Array.prototype.slice.call(arguments),
response = {};
lib.each(args, function (data) {
var message = data[0],
worker = data[1];
response[worker] = message;
});
connection.write(JSON.stringify(response));
connection.end(newline);
});
break;
default:
response = lib.format('Unknown command: {0}.', cmd);
break;
}
if (response) {
connection.write(response);
connection.end(newline);
}
});
} | javascript | {
"resource": ""
} |
q34129 | handleWorkerRestart | train | function handleWorkerRestart(worker, code, signal) {
delete self.workers[worker.id];
if (self.reviveWorkers) {
var zombie = cluster.fork({
config: JSON.stringify(self.config)
});
self.workers[zombie.id] = zombie;
}
} | javascript | {
"resource": ""
} |
q34130 | wait | train | function wait(id, callback) {
var promises = [];
self.transactions[id] = {};
lib.each(self.workers, function (worker) {
var deferred = Q.defer();
self.transactions[id][worker.id] = deferred;
promises.push(deferred.promise);
});
Q.spread(promises, callback);
} | javascript | {
"resource": ""
} |
q34131 | pton | train | function pton(af, addr, dest, index) {
switch (af) {
case IPV4_OCTETS:
return pton4(addr, dest, index)
case IPV6_OCTETS:
return pton6(addr, dest, index)
default:
throw new Error('Unsupported ip address.')
}
} | javascript | {
"resource": ""
} |
q34132 | copycontext | train | function copycontext(context) {
var t = {};
var keys = context.keys();
var i = keys.length;
var k, v, j;
while (i--) {
k = keys[i];
if (k[0] == '_')
continue;
v = context.get(k);
if (v && {}.toString.call(v) === '[object Function]')
continue;
try {
j = JSON.stringify(v);
t[k] = JSON.parse(j);
} catch(err) {
t[k] = "Exception: " + err;
}
}
return t;
} | javascript | {
"resource": ""
} |
q34133 | parseLine | train | function parseLine(line) {
// except for the command, no field has a space, so we split by that and piece the command back together
var parts = line.split(/ +/);
return {
user : parts[0]
, pid : parseInt(parts[1])
, '%cpu' : parseFloat(parts[2])
, '%mem' : parseFloat(parts[3])
, vsz : parseInt(parts[4])
, rss : parseInt(parts[5])
, tty : parts[6]
, state : parts[7]
, started : parts[8]
, time : parts[9]
, command : parts.slice(10).join(' ')
}
} | javascript | {
"resource": ""
} |
q34134 | proxiedMethod | train | function proxiedMethod(params, path) {
// Get the arguments that should be passed to the server
var payload = Array.prototype.slice.call(arguments).slice(2);
// Save the callback function for later use
var callback = util.firstFunction(payload);
// Transform the callback function in the arguments into a special key
// that will be used in the server to signal the client-side callback call
payload = util.serializeCallback(payload);
var endpoint = buildEndpoint(params, path);
if (callback) {
return doRequest(endpoint, payload, params, callback);
} else {
return util.promisify(doRequest)(endpoint, payload, params);
}
} | javascript | {
"resource": ""
} |
q34135 | doRequest | train | function doRequest(endpoint, payload, params, callback) {
debug('Calling API endpoint: ' + endpoint + '.');
request
.post(endpoint)
.send({ payload: payload })
.set('Accept', 'application/json')
.end(function(err, res) {
if ((!res || !res.body) && !err) {
err = new Error('No response from server. ' +
'(Hint: Have you mounted isomorphine.router() in your app?)');
}
if (err) {
return handleError(err, params, callback);
}
var values = res.body.values;
if (!values || values.constructor !== Array) {
err = new Error('Fetched payload is not an array.');
return handleError(err, params, callback);
}
debug('Resolving callback with ' + JSON.stringify(values, null, 3));
// Sets the error argument to null
values.unshift(null);
callback.apply(this, values);
});
} | javascript | {
"resource": ""
} |
q34136 | buildEndpoint | train | function buildEndpoint(config, path) {
var host = config.host;
var port = config.port;
if (!host) throw new Error('No host is specified in proxied method config');
var base = host + (port ? ':' + port : '');
var fullpath = '/isomorphine/' + path;
var endpoint = base + fullpath;
debug('Built endpoint: ' + endpoint);
return endpoint;
} | javascript | {
"resource": ""
} |
q34137 | some | train | function some (list, test, cb) {
assert("length" in list, "array must be arraylike")
assert.equal(typeof test, "function", "predicate must be callable")
assert.equal(typeof cb, "function", "callback must be callable")
var array = slice(list)
, index = 0
, length = array.length
, hecomes = dezalgoify(cb)
map()
function map () {
if (index >= length) return hecomes(null, false)
test(array[index], reduce)
}
function reduce (er, result) {
if (er) return hecomes(er, false)
if (result) return hecomes(null, result)
index++
map()
}
} | javascript | {
"resource": ""
} |
q34138 | slice | train | function slice(args) {
var l = args.length, a = [], i
for (i = 0; i < l; i++) a[i] = args[i]
return a
} | javascript | {
"resource": ""
} |
q34139 | Column | train | function Column (table, header, i) {
this._table = table, this._header = header, this._i = i
} | javascript | {
"resource": ""
} |
q34140 | train | function (file, enc, cb) {
var yaml_files = options.src;
if (typeof yaml_files === 'string') {
yaml_files = [yaml_files];
}
var yaml_data = {};
// Read all files in order, and override if later files contain same values.
for (var i = 0; i < yaml_files.length; i++) {
yaml_data = Object.assign(yaml_data, readYamlFile(yaml_files[i]));
}
var current_data = file[options.property];
var new_data = null;
// Merge with possible previous data.
if (options.override) {
new_data = Object.assign(current_data, yaml_data);
} else {
new_data = Object.assign(yaml_data, current_data);
}
file[options.property] = new_data;
cb(null, file);
} | javascript | {
"resource": ""
} | |
q34141 | GLTFDracoMeshCompressionExtension | train | function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
if ( !dracoLoader ) {
throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
}
this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
this.json = json;
this.dracoLoader = dracoLoader;
THREE.DRACOLoader.getDecoderModule();
} | javascript | {
"resource": ""
} |
q34142 | train | function(iteratee, context) {
context = context || this;
for (var x = this.origin.x, x2 = this.corner.x; x < x2; x++) {
for (var y = this.origin.y, y2 = this.corner.y; y < y2; y++) {
iteratee.call(context, x, y);
}
}
} | javascript | {
"resource": ""
} | |
q34143 | makeRouter | train | function makeRouter() {
// Solving arguments
var args = [].slice.call(arguments);
var beforeMiddlewares = args.slice(0, -1),
routes = args[args.length - 1];
var router = express.Router();
routes.forEach(function(route) {
if (!route.url)
throw Error('dolman.router: one route has no url: ' + util.inspect(route));
if (!route.action)
throw Error('dolman.router: the route for url ' + route.url + ' has no action.');
var actions = [].concat(route.action);
// Storing the route
routesMap.set(actions[0], route);
// Applying before middlewares
var routeMiddlewares = beforeMiddlewares.slice();
// Validation
if (route.validate)
routeMiddlewares.push(middlewares.validate(types, route.validate));
// Mask
if (route.mask)
routeMiddlewares.push(middlewares.mask(route.mask));
// RAM cache
if (route.cache)
routeMiddlewares.push(middlewares.cache(cache, route.cache));
// HTTP cache
if (route.httpCache)
routeMiddlewares.push(middlewares.httpCache(route.httpCache));
// Determining the method
var methods = [].concat(route.method || route.methods || 'ALL');
methods.forEach(function(method) {
router[method.toLowerCase()].apply(
router,
[route.url]
.concat(routeMiddlewares)
.concat(actions)
);
});
});
return router;
} | javascript | {
"resource": ""
} |
q34144 | specs | train | function specs() {
var routes = {};
// Reducing the app's recursive stack
function reduceStack(path, items, item) {
var nextPath;
if (item.handle && item.handle.stack) {
nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || ''));
return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), []));
}
if (item.route) {
nextPath = join(path, (item.route.path || ''));
return items.concat(item.route.stack.reduce(reduceStack.bind(null, nextPath), []));
}
return items.concat({
handle: item.handle,
path: path
});
}
// Filtering the actions coming from dolman
app._router.stack
.reduce(reduceStack.bind(null, ''), [])
.map(function(item) {
return {
route: routesMap.get(item.handle),
path: item.path
};
})
.filter(function(item) {
return item.route && item.route.name;
})
.forEach(function(item) {
var route = item.route,
method = [].concat(route.method || route.methods)[0];
var routeData = {
path: item.path,
name: route.name,
method: !method || method === 'ALL' ? 'GET' : method
};
['description'].forEach(function(k) {
if (route[k])
routeData[k] = route[k];
});
routes[route.name] = routeData;
});
return {
formats: ['json'],
methods: routes
};
} | javascript | {
"resource": ""
} |
q34145 | reduceStack | train | function reduceStack(path, items, item) {
var nextPath;
if (item.handle && item.handle.stack) {
nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || ''));
return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), []));
}
if (item.route) {
nextPath = join(path, (item.route.path || ''));
return items.concat(item.route.stack.reduce(reduceStack.bind(null, nextPath), []));
}
return items.concat({
handle: item.handle,
path: path
});
} | javascript | {
"resource": ""
} |
q34146 | GruntHorde | train | function GruntHorde(grunt) {
this.cwd = process.cwd();
this.config = {
initConfig: {},
loadNpmTasks: {},
loadTasks: {},
registerMultiTask: {},
registerTask: {}
};
this.frozenConfig = {};
this.grunt = grunt;
this.lootBatch = [];
} | javascript | {
"resource": ""
} |
q34147 | createRouter | train | function createRouter(modules) {
debug('Creating a new router. Modules: ' + JSON.stringify(modules, null, 3));
var router = express();
router.use(bodyParser.json());
// Map the requested entity path with the actual serverside entity
router.use('/isomorphine', methodLoader(modules));
// Proxy request pipeline
router.post('/isomorphine/*', getPayload, callEntityMethod, serve);
return router;
} | javascript | {
"resource": ""
} |
q34148 | methodLoader | train | function methodLoader(modules) {
return function(req, res, next) {
if (req.path === '/') return next();
var path = req.path.substr(1).split('/');
var currModule = modules;
var isLastIndex, p, method;
debug('Looking for isomorphine entity in: ' + path.join('.'));
for (var i = 0, len = path.length; i < len; i++) {
isLastIndex = i === (len - 1);
p = path[i];
// Expect a function when last index
if (isLastIndex && isES6Function(currModule[p])) {
method = getES6Function(currModule[p]);
}
// Expect an object when not last index
else if (!isLastIndex && isObject(currModule[p])) {
currModule = currModule[p];
}
// Return a 404 if the entity was not found
else {
return next(createError(404, 'No method found at this path'));
}
}
// Reference the serverside method in req
debug('Entity found');
req.serversideMethod = method;
next();
};
} | javascript | {
"resource": ""
} |
q34149 | checkFallback | train | function checkFallback(obj) {
var props = [];
var hasFallback = [];
var values = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var pro = obj[prop].prop;
if (obj[prop].type === 'comment') {
continue;
}
if (props.indexOf(pro) === -1) {
props.push(pro);
values.push({prop: pro, val:obj[prop].value});
} else {
var lookup = {};
for (var i = 0, len = values.length; i < len; i++) {
lookup[values[i].prop] = values[i].val;
}
if (lookup[pro].search('px') === -1 && obj[prop].value.search('rem') === -1 ||
lookup[pro].search('rem') === -1 && obj[prop].value.search('px') === -1) {
hasFallback.push(pro);
}
}
}
}
return hasFallback;
} | javascript | {
"resource": ""
} |
q34150 | train | function () {
if (this.auth_url) {
return this.auth_url;
}
var self = this,
destination = {
protocol: 'https',
host: 'www.box.com',
pathname: '/api/oauth2/authorize',
search: querystring.stringify({
response_type: 'code',
client_id: self.client_id,
state: self.csrf,
redirect_uri: 'http://' + self.host + ':' + self.port + '/authorize?id=' + self.email
})
};
self.auth_url = url.format(destination);
return self.auth_url;
} | javascript | {
"resource": ""
} | |
q34151 | getAbcKey | train | function getAbcKey(fifths, mode) {
if (typeof mode === 'undefined' || mode === null) mode = 'major';
return circleOfFifths[mode][fifths];
} | javascript | {
"resource": ""
} |
q34152 | getJSONId | train | function getJSONId(data) {
var lines = data.split('\n');
for (var i = 0; i < lines.length; i++) {
if (lines[i].indexOf('T:') > -1) {
return lines[i].substr(lines[i].indexOf(':') + 1, lines[i].length);
}
}
throw new Error('Could not determine "T:" field');
} | javascript | {
"resource": ""
} |
q34153 | train | function(tune) {
var ret = {
attributes: {
divisions: 1 /tune.getBeatLength(),
clef: {
line: 2
},
key: {},
time: {}
}
};
var measures = [];
var measureCounter = 0;
var barlineCounter = 0;
// parse lines
for (var l = 0; l < tune.lines.length; l++) {
for (var s = 0; s < tune.lines[l].staff.length; s++) {
var staff = tune.lines[l].staff[s];
// parse default clef, key, meter
if (l === 0 && s === 0) {
ret.attributes.clef.sign = getKeyByValue(clefs, staff.clef.type);
ret.attributes.clef.line = staff.clef.clefPos / 2;
ret.attributes.key.fifths = parseInt(getKeyByValue(circleOfFifths, staff.key.root));
ret.attributes.time.beats = staff.meter.value[0].num;
ret.attributes.time['beat-type'] = staff.meter.value[0].den;
}
for (var v = 0; v < staff.voices.length; v++) {
for (var t = 0; t < staff.voices[v].length; t++) {
var token = staff.voices[v][t];
// init measure if none exists
if (measures[measureCounter] === undefined) {
measures[measureCounter] = new Measure();
}
switch (token.el_type) {
case "note":
measures[measureCounter].addNote(token, ret.attributes.divisions, ret.attributes.time['beat-type']);
break;
case "bar":
if (token.type === 'bar_right_repeat') {
measures[measureCounter].setRepeatRight();
}
measureCounter++;
if (measures[measureCounter] === undefined) {
measures[measureCounter] = new Measure();
}
if (token.type === 'bar_left_repeat') {
measures[measureCounter].setRepeatLeft();
}
break;
default:
console.log(token);
break;
}
}
}
}
}
// put measures together
ret.measures = [];
for (var i = 0; i < measures.length; i++) {
var measure = measures[i].get();
if (measure.notes.length > 0) {
ret.measures.push(measure);
}
}
return ret;
} | javascript | {
"resource": ""
} | |
q34154 | train | function() {
var attributes = {
repeat: {
left: false,
right: false
}
};
var notes = [];
/**
* Set repeat left for measure
*/
this.setRepeatLeft = function () {
attributes.repeat.left = true;
};
/**
* Set repeat right for measure
*/
this.setRepeatRight = function () {
attributes.repeat.right = true;
};
/**
* Add note to measure
* @param {object} note - The note object
* @param {Number} divisions - The calculated divisions
* @param {Number} beatType - The beat type
*/
this.addNote = function(note, divisions, beatType) {
var _note = {pitch:{}};
var _octave = 5, _step, _alter = 0;
if (note.hasOwnProperty('pitches')) {
_octave--;
_step = note.pitches[0].pitch;
while (_step > 6) {
_octave++;
_step -= 7;
}
while (_step < 0) {
_octave--;
_step +=7
}
_note.pitch.step = pitches.abc[_step];
_note.rest = false;
if (note.pitches[0].hasOwnProperty('accidental')) {
_alter = accidental.abc[note.pitches[0].accidental];
_note.pitch.accidental = note.pitches[0].accidental;
}
} else {
_note.pitch.step = "C";
_note.pitch.octave = 5;
_note.rest = true;
_note.pitch.alter = 0;
}
_note.pitch.octave = _octave;
_note.pitch.alter = _alter;
for (var i = 0; i < durations.length; i++) {
if (typeof durations[i+1] !== 'undefined') {
if (durations[i].duration > note.duration && durations[i+1].duration <= note.duration) {
var diff = note.duration - durations[i+1].duration;
_note.duration = durations[i+1].duration * divisions * beatType;
_note.type = durations[i+1].type;
if (diff > 0) {
if ((diff / durations[i+1].duration) === 0.5) {
_note.dot = true;
} else {
throw new Error('Unknown duration: ' + note.duration);
}
}
break;
}
} else {
throw new Error('Unknown duration: ' + note.duration);
}
}
notes.push(_note);
};
/**
* Get measure object
* @returns {{attributes: {repeat: {left: boolean, right: boolean}}, notes: Array}}
*/
this.get = function() {
return {
attributes: attributes,
notes: notes
};
};
} | javascript | {
"resource": ""
} | |
q34155 | HeadCornerChartParser | train | function HeadCornerChartParser(grammar) {
this.grammar = grammar;
this.grammar.computeHCRelation();
logger.debug("HeadCornerChartParser: " + JSON.stringify(grammar.hc));
} | javascript | {
"resource": ""
} |
q34156 | requireMethods | train | function requireMethods(dir) {
if (!dir) dir = getCallerDirname();
var modules = {};
fs
.readdirSync(dir)
.filter(function(filename) {
return filename !== 'index.js';
})
.forEach(function(filename) {
var filePath = path.join(dir, filename);
var Stats = fs.lstatSync(filePath);
var isLink = Stats.isSymbolicLink();
var isDir = Stats.isDirectory();
var isFile = Stats.isFile();
var isJS = filename.indexOf('.js') > -1;
if (!isLink && isDir) {
modules[filename] = requireMethods(filePath);
}
else if (!isLink && isFile && isJS) {
var entityName = filename.replace('.js', '');
modules[entityName] = require(filePath);
var hasES6Default = isObject(modules[entityName])
&& isFunction(modules[entityName].default);
if (hasES6Default) {
modules[entityName] = modules[entityName].default;
}
}
});
return modules;
} | javascript | {
"resource": ""
} |
q34157 | getCallerDirname | train | function getCallerDirname() {
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack){ return stack; };
var err = new Error();
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
var requester = stack[2].getFileName();
return path.dirname(requester);
} | javascript | {
"resource": ""
} |
q34158 | train | function (name, parent_id, done, config) {
if (!_.isString(name) || !_.isNumber(parseInt(parent_id, 10))) {
return done(new Error('Invalid params. Required - name: string, parent_id: number'));
}
this._request(['folders'], 'POST', done, null, {
name: name,
parent: {
id: parent_id.toString()
}
}, null, null, null, config);
} | javascript | {
"resource": ""
} | |
q34159 | NixAttrReference | train | function NixAttrReference(args) {
this.attrSetExpr = args.attrSetExpr;
this.refExpr = args.refExpr;
this.orExpr = args.orExpr;
} | javascript | {
"resource": ""
} |
q34160 | throwUnexpected | train | function throwUnexpected (attr, obj) {
var e = Unexpected(attr, obj);
Error.captureStackTrace(e, throwUnexpected);
throw e;
} | javascript | {
"resource": ""
} |
q34161 | targz | train | function targz(stream, opts) {
return exports.tar(stream.pipe(zlib.createGunzip()), opts);
} | javascript | {
"resource": ""
} |
q34162 | train | function( state ) {
var key,
clonedState = {};
for( key in state ) {
if( key !== LOCAL ) {
clonedState[ key ] = state[ key ];
}
}
return clonedState;
} | javascript | {
"resource": ""
} | |
q34163 | train | function() {
if( this.dsRecord && this.dsRecord.isReady && Object.keys( this.dsRecord.get() ).length === 0 && this.state ) {
this.dsRecord.set( this.state );
}
} | javascript | {
"resource": ""
} | |
q34164 | encrypt | train | function encrypt(salt, password) {
var hash = crypto.createHash('sha256').update(salt + password).digest('base64');
return salt + hash;
} | javascript | {
"resource": ""
} |
q34165 | _toCamelCase | train | function _toCamelCase(str) {
var newString = '';
var insideParens = false;
newString += str[0].toLowerCase();
for (var i = 1; i < str.length; i++) {
var char = str[i];
switch (char) {
case ')':
case '_':
break;
case '(':
insideParens = true;
break;
default:
if (insideParens) {
insideParens = false;
newString += char.toUpperCase();
} else {
newString += char;
}
break;
}
}
return newString;
} | javascript | {
"resource": ""
} |
q34166 | GithubBot | train | function GithubBot(options) {
if (!(this instanceof GithubBot)) {
return new GithubBot(options);
}
BaseBot.call(this, options);
this.handlers(events);
this.define('events', events);
} | javascript | {
"resource": ""
} |
q34167 | train | function () {
var self = this;
async.waterfall([
function (next) {
if (!self.events) {
self.events = new Datastore();
self.events.ensureIndex({
fieldName: 'event_id',
unique: true
});
self.events.ensureIndex({
fieldName: 'recorded_at',
sparse: true
});
self.events.ensureIndex({
fieldName: 'created_at',
}, next);
} else {
next();
}
},
function (next) {
if (!self.keepPolling) {
self.keepPolling = true;
async.whilst(function () {
return self.keepPolling;
}, _.bind(self._emit, self), _.noop);
next(null, true);
} else {
next(null, false);
}
},
function (doLongPoll, next) {
if (doLongPoll) {
async.whilst(function () {
return self.keepPolling;
}, _.bind(self._longPoll, self), function (err) {
if (err) {
/**
* Fires when an error occurs during long-polling.
* @event Connection#"polling.error"
* @type {Error}
* @see {@link Connection#startLongPolling}
*/
self.emit('polling.error', err);
} else if (!self.keepPolling) {
/**
* Fires when a running long-polling process ends.
* @event Connection#"polling.end"
* @see {@link Connection#stopLongPolling}
*/
self.emit('polling.end');
}
});
}
next();
}
], _.noop);
} | javascript | {
"resource": ""
} | |
q34168 | train | function (query, opts, done, config) {
if (!_.isString(query)) {
return done(new Error('query must be a string.'));
}
opts = opts || {};
opts.query = query;
this._request(['search'], 'GET', done, opts, null, null, null, null, config);
} | javascript | {
"resource": ""
} | |
q34169 | hasExample | train | function hasExample ({ optional, example, details } = {}) {
if (optional || example !== undefined) {
return true;
}
if (details !== undefined) {
const values = Object.keys(details).map((key) => details[key]);
return values.every(hasExample);
}
return false;
} | javascript | {
"resource": ""
} |
q34170 | getExample | train | function getExample (obj) {
if (isArray(obj)) {
return removeOptionalWithoutExamples(obj).map(getExample);
}
const { example, details } = obj;
if (example === undefined && details !== undefined) {
const nested = {};
Object.keys(details).forEach((key) => {
nested[key] = getExample(details[key]);
});
return nested;
}
return example;
} | javascript | {
"resource": ""
} |
q34171 | methodComparator | train | function methodComparator (a, b) {
const sectionA = spec[a].section || '';
const sectionB = spec[b].section || '';
return sectionA.localeCompare(sectionB) || a.localeCompare(b);
} | javascript | {
"resource": ""
} |
q34172 | group | train | function group (frame) {
let v, name, op;
const entries = fields.map((field, index) => {
name = ops[index];
op = scalar_operations.get('count');
if (name) {
op = scalar_operations.get(name);
if (!op) {
op = scalar_operations.get('count');
warn(`Operation ${name} is not supported, use count`);
}
}
return {
field: field,
as: as[index] || field,
op: op
};
});
return frame.dimension(groupby).group().reduce((o, record) => {
return entries.reduce((oo, entry) => {
v = 0;
if (entry.as in oo) v = oo[entry.as];
oo[entry.as] = entry.op(v, record[entry.field]);
return oo;
}, o);
}, null, Object).all().map(d => {
d.value[groupby] = d.key;
return d.value;
});
} | javascript | {
"resource": ""
} |
q34173 | train | function(func, name) {
return proxy.createProxy(func, handlers.beforeFunc, handlers.afterFunc, {attachMonitor: true}, name);
} | javascript | {
"resource": ""
} | |
q34174 | train | function(name, args) {
var callInstance = {name: name};
handlers.beforeFunc({name: name}, null, args, callInstance);
return callInstance;
} | javascript | {
"resource": ""
} | |
q34175 | train | function(args, callInstance) {
handlers.afterFunc({name: callInstance.name}, null, args, callInstance);
} | javascript | {
"resource": ""
} | |
q34176 | UploadButton | train | function UploadButton(props) {
var onClick = function onClick() {
var inputStyle = 'display:block;visibility:hidden;width:0;height:0';
var input = $('<input style="' + inputStyle + '" type="file" name="somename" size="chars">');
input.appendTo($('body'));
input.change(function () {
console.log('uploading...');
var files = input[0].files;
console.log(files);
var file = files[0];
input.remove();
uploadFile(file, function (data, err) {
if (err) {
if (_lodash2.default.isFunction(props.onError)) {
props.onError(err);
}
return;
}
if (_lodash2.default.isFunction(props.onSuccess)) {
props.onSuccess(data);
}
});
});
input.click();
};
var btnProps = {
className: _style2.default.upload_button,
title: 'Upload files',
'data-toggle': 'tooltip',
onMouseDown: onClick
};
return _react2.default.createElement(
'a',
btnProps,
_react2.default.createElement('i', { className: 'ion-camera' })
);
} | javascript | {
"resource": ""
} |
q34177 | createProxies | train | function createProxies(config, map, parentPath) {
parentPath = parentPath || [];
var isBase = parentPath.length === 0;
var proxies = {};
var path;
for (var key in map) {
if (map.hasOwnProperty(key)) {
if (isObject(map[key])) {
proxies[key] = createProxies(config, map[key], parentPath.concat([key]));
}
else if (isBoolean(map[key])) {
path = parentPath.join('/') + (isBase ? '' : '/') + key;
proxies[key] = createProxiedMethod(config, path);
}
}
}
return proxies;
} | javascript | {
"resource": ""
} |
q34178 | getConfigFromBrowser | train | function getConfigFromBrowser() {
var defaultLocation = {
port: '80',
hostname: 'localhost',
protocol: 'http:'
};
var wLocation = (global.location)
? global.location
: defaultLocation;
var location = {
port: wLocation.port,
host: wLocation.protocol + '//' + wLocation.hostname
};
var config = {
port: location.port,
host: location.host,
errorHandlers: []
};
return config;
} | javascript | {
"resource": ""
} |
q34179 | withPreamble | train | function withPreamble (preamble, spec) {
Object.defineProperty(spec, '_preamble', {
value: preamble.trim(),
enumerable: false
});
return spec;
} | javascript | {
"resource": ""
} |
q34180 | withComment | train | function withComment (example, comment) {
const constructor = example == null ? null : example.constructor;
if (constructor === Object || constructor === Array) {
Object.defineProperty(example, '_comment', {
value: comment,
enumerable: false
});
return example;
}
// Convert primitives
return new PrimitiveWithComment(example, comment);
} | javascript | {
"resource": ""
} |
q34181 | getDelay | train | function getDelay(start, interval) {
const delta = process.hrtime(start);
const nanosec = (delta[0] * 1e9) + delta[1];
/* eslint no-bitwise: ["error", { "int32Hint": true }] */
return Math.max((nanosec / 1e6 | 0) - interval, 0);
} | javascript | {
"resource": ""
} |
q34182 | format | train | function format(value, unitInfo) {
const unit = unitInfo.unit;
const precision = unitInfo.precision || 0;
let v = 0;
switch (unit) {
case 'GB':
v = value / GB;
break;
case 'MB':
v = value / MB;
break;
default:
v = value;
break;
}
v = parseFloat(Number(v).toFixed(precision));
return v;
} | javascript | {
"resource": ""
} |
q34183 | getHeapStatistics | train | function getHeapStatistics(unitInfo) {
const data = v8.getHeapStatistics();
const keys = Object.keys(data);
const result = {};
keys.forEach((key) => {
result[key] = format(data[key], unitInfo);
});
return result;
} | javascript | {
"resource": ""
} |
q34184 | getHeapSpaceStatistics | train | function getHeapSpaceStatistics(unitInfo) {
const arr = v8.getHeapSpaceStatistics();
const result = {};
arr.forEach((item) => {
const data = {};
const keys = Object.keys(item);
keys.forEach((key) => {
if (key === 'space_name') {
return;
}
// replace the space_ key prefix
data[key.replace('space_', '')] = format(item[key], unitInfo);
});
result[item.space_name] = data;
});
return result;
} | javascript | {
"resource": ""
} |
q34185 | getMemoryUsage | train | function getMemoryUsage(unitInfo) {
const data = process.memoryUsage();
const keys = Object.keys(data);
const result = {};
keys.forEach((key) => {
result[key] = format(data[key], unitInfo);
});
return result;
} | javascript | {
"resource": ""
} |
q34186 | get | train | function get(arr, filter, defaultValue) {
let result;
arr.forEach((tmp) => {
if (tmp && filter(tmp)) {
result = tmp;
}
});
return result || defaultValue;
} | javascript | {
"resource": ""
} |
q34187 | convertUnit | train | function convertUnit(str) {
const reg = /\.\d*/;
const result = reg.exec(str);
if (result && result[0]) {
return {
precision: result[0].length - 1,
unit: str.substring(result[0].length + 1),
};
}
return {
unit: str,
};
} | javascript | {
"resource": ""
} |
q34188 | getCpuUsage | train | function getCpuUsage(previousValue, start) {
if (!previousValue) {
return null;
}
const usage = process.cpuUsage(previousValue);
const delta = process.hrtime(start);
const total = Math.ceil(((delta[0] * 1e9) + delta[1]) / 1000);
const usedPercent = Math.round(((usage.user + usage.system) / total) * 100);
usage.usedPercent = usedPercent;
usage.userUsedPercent = Math.round((usage.user / total) * 100);
usage.systemUsedPercent = Math.round((usage.system / total) * 100);
usage.total = total;
return usage;
} | javascript | {
"resource": ""
} |
q34189 | camelCaseData | train | function camelCaseData(data) {
const result = {};
const keys = Object.keys(data);
keys.forEach((k) => {
const key = camelCase(k);
const value = data[k];
if (isObject(value)) {
result[key] = camelCaseData(value);
} else {
result[key] = value;
}
});
return result;
} | javascript | {
"resource": ""
} |
q34190 | flatten | train | function flatten(data, pre) {
const prefix = pre || '';
const keys = Object.keys(data);
const result = {};
keys.forEach((k) => {
const value = data[k];
const key = [prefix, k].join('-');
if (isObject(value)) {
Object.assign(result, flatten(value, key));
} else {
result[key] = value;
}
});
return result;
} | javascript | {
"resource": ""
} |
q34191 | performance | train | function performance() {
/* eslint prefer-rest-params: 0 */
const args = Array.from(arguments);
const interval = get(args, isNumber, 100);
const fn = get(args, isFunction, noop);
const unitInfo = convertUnit(get(args, isString, 'B').toUpperCase());
let start = process.hrtime();
let cpuUsage = process.cpuUsage && process.cpuUsage();
const timer = setInterval(() => {
let result = {
lag: getDelay(start, interval),
heap: getHeapStatistics(unitInfo),
memoryUsage: getMemoryUsage(unitInfo),
};
if (cpuUsage) {
result.cpuUsage = getCpuUsage(cpuUsage, start);
}
if (v8.getHeapSpaceStatistics) {
result.heapSpace = getHeapSpaceStatistics(unitInfo);
}
if (performance.flatten) {
result = flatten(result);
}
if (performance.camelCase) {
result = camelCaseData(result);
}
fn(result);
start = process.hrtime();
cpuUsage = process.cpuUsage && process.cpuUsage();
}, interval);
timer.unref();
return timer;
} | javascript | {
"resource": ""
} |
q34192 | consoleProxy | train | function consoleProxy(ob){
// list from http://nodejs.org/api/stdio.html
var methods = ["dir", "time", "timeEnd", "trace", "assert"];
methods.forEach(function(method){
if (ob[method]) return;
ob[method] = function(){
return console[method].apply(console, arguments);
};
});
} | javascript | {
"resource": ""
} |
q34193 | getOveruse | train | function getOveruse(duplicates, limit) {
var duplicate;
for (duplicate in duplicates) {
if (duplicates[duplicate] < limit) {
delete duplicates[duplicate]
}
}
return keys(duplicates);
} | javascript | {
"resource": ""
} |
q34194 | use | train | function use (filepath, destination) {
var startTime = Date.now();
var text = read(filepath);
if (text !== false) {
fs.writeFile(destination, jsx(text), function (err) {
if (err) { throw err; }
var endTime = Date.now();
log('[Finished in ' + (endTime - startTime) + 'ms]');
});
} else {
log('no such file exits, ' + filepath);
}
} | javascript | {
"resource": ""
} |
q34195 | envar | train | function envar(key)
{
var i, value;
// be extra paranoid
if (typeof key != 'string' || !key) return undefined;
// lookup according to the order
for (i=0; i<state.order.length; i++)
{
if ((value = lookup[state.order[i]](key)) !== undefined)
{
return value;
}
}
// nothing found
return undefined;
} | javascript | {
"resource": ""
} |
q34196 | roundedCorners | train | function roundedCorners(side, radius) {
if (!radius) {
radius = side || 10;
side = 'all';
}
if (side == 'all') {
if (browserInfo().msie) {
return {
'border-radius': radius,
behavior: 'url(border-radius-ie.htc)',
visibility: 'hidden'
}
} else if (browserInfo().mozilla) {
return {
'-moz-border-radius': radius
}
} else {
return {
'border-radius': radius,
'-webkit-border-radius': radius
}
}
} else {
var rules = {};
if (side == 'tl' || side == 'top' || side == 'left') {
rules['-moz-border-radius-topleft'] = radius;
rules['-webkit-border-top-left-radius'] = radius;
rules['border-top-left-radius'] = radius;
}
if (side == 'tr' || side == 'top' || side == 'right') {
rules['-webkit-border-top-right-radius'] = radius;
rules['-moz-border-radius-topright'] = radius;
rules['border-top-right-radius'] = radius;
}
if (side == 'bl' || side == 'bottom' || side == 'left') {
rules['-webkit-border-bottom-left-radius'] = radius;
rules['-moz-border-radius-bottomleft'] = radius;
rules['border-bottom-left-radius'] = radius;
}
if (side == 'br' || side == 'bottom' || side == 'right') {
rules['-webkit-border-bottom-right-radius'] = radius;
rules['-moz-border-radius-bottomright'] = radius;
rules['border-bottom-right-radius'] = radius;
}
return rules;
}
} | javascript | {
"resource": ""
} |
q34197 | transpose | train | function transpose(matrix) {
// For NxN matrix
var n = matrix[0].length;
var temp;
// Walk through columns
for (var i = 0, j = 0; i < n; i++) {
j = i;
// Walk through rows
while (j < n) {
if (i !== j) {
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
j++;
}
}
} | javascript | {
"resource": ""
} |
q34198 | getConfig | train | function getConfig(react) {
const loaders = [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: _util.babelFEOptions
}, {
test: /\.json$/,
loader: 'json'
}, {
test: /jsdom/,
loader: 'null'
}];
if (react) {
loaders.unshift({
test: /\.js$/,
exclude: /node_modules/,
loader: 'react-hot'
});
}
return {
cache,
debug: true,
node: { fs: 'empty' },
module: { loaders },
// temporary hack while `react-hot-loader` v3 is not out
resolve: {
alias: {
'react/lib/ReactMount': 'react-dom/lib/ReactMount'
}
}
};
} | javascript | {
"resource": ""
} |
q34199 | getCompiler | train | function getCompiler(inPath, outPath, { library, libraryTarget }) {
const compiler = (0, _webpack2.default)(_extends({}, getConfig(false), {
devtool: _util.isProduction ? 'source-map' : 'eval-source-map',
entry: ['babel-polyfill', inPath],
output: { path: (0, _path.dirname)(outPath), filename: (0, _path.basename)(outPath), publicPath: '/', library, libraryTarget },
plugins: _util.isProduction ? productionPlugins : []
}));
compiler.outputFileSystem = fakeFS;
return compiler;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.