_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q39400 | rule | train | function rule(test, loaders, exclude) {
var rule = {
test: test,
use: loaders
};
if (exclude) {
rule.exclude = exclude;
}
return rule;
} | javascript | {
"resource": ""
} |
q39401 | rrefInPlace | train | function rrefInPlace (M, TOL = 1e-14) {
const me = M.elements;
// iterate through all rows to get to REF
for (let i = 0; i < 3; ++i) {
// search for largest in col and swap
const k = findLargestInCol(M, i, i);
if (k !== i) {
swapRowsInPlace(M, i, k);
}
// scale and add current row to all... | javascript | {
"resource": ""
} |
q39402 | isRowNonzero | train | function isRowNonzero (M, i, TOL = 1e-14) {
const me = M.elements;
return !(Compare.isZero(me[i], TOL) &&
Compare.isZero(me[i + 3], TOL) &&
Compare.isZero(me[i + 6], TOL));
} | javascript | {
"resource": ""
} |
q39403 | findLargestAbsElement | train | function findLargestAbsElement (M) {
const te = M.elements;
const n = M.dimension;
let max = _Math.abs(te[0]);
let rowCol = {
row: 0,
column: 0,
value: te[0]
};
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
const val = te[i * n + j];
const ti = _Math.abs(val);
... | javascript | {
"resource": ""
} |
q39404 | findLargestInRow | train | function findLargestInRow (M, i) {
// get the row:
const m = M.elements;
const n = M.dimension;
const offset = i;
let j = 0;
let lrgElem = _Math.abs(m[offset]);
let lrgCol = j;
for (j = 1; j < n; ++j) {
const val = _Math.abs(m[offset + j * n]);
if (val > lrgElem) {
lrgCol = j;
lrgEl... | javascript | {
"resource": ""
} |
q39405 | findLargestInCol | train | function findLargestInCol (M, i, startAtRow = 0) {
let me = M.elements;
let n = M.dimension;
let offset = i * n;
let maxIdx = startAtRow;
let maxVal = _Math.abs(me[offset + maxIdx]);
for (let i = maxIdx + 1; i < n; ++i) {
let val = _Math.abs(me[offset + i]);
if (val > maxVal) {
maxIdx = i;
... | javascript | {
"resource": ""
} |
q39406 | findFirstNonvanishing | train | function findFirstNonvanishing (M, TOL) {
const te = M.elements;
const n = M.dimension;
let rowCol = {
row: 0,
column: 0,
value: te[0]
};
if (Compare.isZero(te[0], TOL)) {
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
const val = te[i * n + j];
if (!Compare.... | javascript | {
"resource": ""
} |
q39407 | swapValuesInArray | train | function swapValuesInArray (A, i, j) {
if (i !== j) {
const tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
return A;
} | javascript | {
"resource": ""
} |
q39408 | swapRowsInPlace | train | function swapRowsInPlace (M, i, j) {
const me = M.elements;
let a1 = me[i];
let a2 = me[i + 3];
let a3 = me[i + 6];
me[i] = me[j];
me[i + 3] = me[j + 3];
me[i + 6] = me[j + 6];
me[j] = a1;
me[j + 3] = a2;
me[j + 6] = a3;
} | javascript | {
"resource": ""
} |
q39409 | scaleRow | train | function scaleRow (M, row, scale) {
const me = M.elements;
let i = row;
let alpha = (scale === undefined ? 1.0 : scale);
me[i] *= alpha;
me[i + 3] *= alpha;
me[i + 6] *= alpha;
} | javascript | {
"resource": ""
} |
q39410 | scaleAndAddRow | train | function scaleAndAddRow (m, srcRow, destRow, scale) {
const me = m.elements;
let i = destRow;
let j = srcRow;
let alpha = (scale === undefined ? 1.0 : scale);
me[i] += me[j] * alpha;
me[i + 3] += me[j + 3] * alpha;
me[i + 6] += me[j + 6] * alpha;
} | javascript | {
"resource": ""
} |
q39411 | thresholdToZero | train | function thresholdToZero (m, TOL) {
const me = m.elements;
for (let i = 0; i < 9; ++i) {
if (Compare.isZero(me[i], TOL)) {
me[i] = 0;
}
}
return m;
} | javascript | {
"resource": ""
} |
q39412 | luSolve | train | function luSolve (A, P, b, X) {
// Since PA = LU, then L(U x) = Pb
const a = A.elements;
const n = A.dimension;
// L * y = P * b, solve for y.
// Implicit 1's on the diagonal.
for (let i = 0; i < n; ++i) {
let sum = 0;
for (let j = 0; j < i; ++j) {
sum += a[i + j * n] * X.getComponent(j);
... | javascript | {
"resource": ""
} |
q39413 | luDecomposition | train | function luDecomposition (A, inPlace) {
const n = A.dimension;
const AA = inPlace ? A : A.clone();
const a = AA.elements; // indexed via a_ij = a[i + j * n]
const P = [];
const rowScalers = [];
for (let i = 0; i < n; ++i) {
P.push(i);
const col = findLargestInRow(A, i);
const scaler = a[col * n... | javascript | {
"resource": ""
} |
q39414 | proj | train | function proj (u, v) {
return u.clone().multiplyScalar(u.dot(v) / u.dot(u));
} | javascript | {
"resource": ""
} |
q39415 | modifiedGramSchmidt | train | function modifiedGramSchmidt (m) {
const n = m.dimension;
const v0 = m.getColumn(0);
const u0 = v0;
const v1 = m.getColumn(1);
const u1 = v1.clone().sub(proj(u0, v1));
if (n === 2) {
m.setColumns(v0, v1);
return;
}
const v2 = m.getColumn(2);
const u2t = v2.clone().sub(proj(u0, v2));
const u... | javascript | {
"resource": ""
} |
q39416 | rotg | train | function rotg (a, b, csr) {
// Based on Algorithm 4 from "Discontinuous Plane
// Rotations and the Symmetric Eigenvalue Problem"
// by Anderson, 2000.
let c = 0;
let s = 0;
let r = 0;
let t = 0;
let u = 0;
if (b === 0) {
c = _Math.sign(a);
s = 0;
r = _Math.abs(a);
} else if (a === 0) {
... | javascript | {
"resource": ""
} |
q39417 | qrDecomposition | train | function qrDecomposition (A, inPlace) {
const Q = A.clone().identity();
const R = inPlace ? A : A.clone();
const qe = Q.elements;
const re = R.elements;
const csr = [0, 0, 0];
const DIM = Q.dimension;
const m = DIM;
const n = DIM;
for (let j = 0; j < n; ++j) {
for (let i = m - 1; i >= j + 1; --i)... | javascript | {
"resource": ""
} |
q39418 | getRank | train | function getRank (M, EPS) {
const n = M.dimension;
const { R } = qrDecomposition(M);
// TODO: this is a bad way of doing this probably
R.thresholdEntriesToZero(100 * EPS);
let rank = 0;
rrefInPlace(R);
for (let i = 0; i < n; ++i) {
if (isRowNonzero(R, i)) {
rank++;
}
}
return rank;
} | javascript | {
"resource": ""
} |
q39419 | householderTransform | train | function householderTransform (x) {
// Based on "Matrix Computations" by Golub, Van Loan
const n = x.dimension;
const v = x.clone();
v.x = 1;
let sigma = 0;
for (let i = 1; i < n; ++i) {
const vi = v.getComponent(i);
sigma += vi * vi;
}
let beta = 0;
if (sigma !== 0) {
const x1 = x.x;
... | javascript | {
"resource": ""
} |
q39420 | hessenbergQRStep | train | function hessenbergQRStep (M) {
const n = M.dimension;
const me = M.elements;
const csr = [0, 0, 0];
const cs = [];
for (let k = 0; k < n - 1; ++k) {
const row1 = k;
const row2 = k + 1;
const colK = k * n;
const a = me[row1 + colK];
const b = me[row2 + colK];
rotg(a, b, csr);
const... | javascript | {
"resource": ""
} |
q39421 | bro | train | function bro() {
var self = this;
//
// Time has passed since we've generated this function so we're going to
// assume that this function is already executed async.
//
if (+(new Date()) > start) {
return fn.apply(self, arguments);
}
for (var i = 0, l = arguments.length, args = n... | javascript | {
"resource": ""
} |
q39422 | betterIndexOf | train | function betterIndexOf(arr, value) {
if (value != value || value === 0) { // eslint-disable-line eqeqeq
var i = arr.length;
while (i-- && !is(arr[i], value)) {
// eslint-disable-line no-empty
}
} else {
i = [].indexOf.call(arr, value);
}
return i;
} | javascript | {
"resource": ""
} |
q39423 | isCustomElement | train | function isCustomElement(element) {
assertType(element, Node, false, 'Invalid element specified');
let is = getAttribute(element, 'is');
let tag = element.tagName.toLowerCase();
if (is && (getElementRegistry(is) !== undefined)) return true;
if (tag && (getElementRegistry(tag) !== undefined)) return true;
... | javascript | {
"resource": ""
} |
q39424 | clone | train | function clone(git_url, git_ref, clone_dir){
var needsGitCheckout = !!git_ref;
if (!shell.which('git')) {
return Q.reject(new Error('"git" command line tool is not installed: make sure it is accessible on your PATH.'));
}
// If no clone_dir is specified, create a tmp dir which git will clo... | javascript | {
"resource": ""
} |
q39425 | train | function (options) {
var defaultOptions = {
viewCacheDir: viewCacheDir,
expires: 3600
};
this.type='flatfile';
this.prefix='flatfile';
this.driver = 'fs';
this._size = 0;
this._hits = 0;
this._misses = 0;
this.options = merge(defaultOptions,options);
this.expires = this.options.expires;
viewCacheDir = th... | javascript | {
"resource": ""
} | |
q39426 | setadd | train | function setadd(set, element) {
if (set.has(element)) return false;
set.add(element);
return true;
} | javascript | {
"resource": ""
} |
q39427 | argv | train | function argv(args) {
var out = {directives: {}}
, i = 0;
/* istanbul ignore next: never use process.argv in tests */
args = args || process.argv.slice(2);
if(!args.length) return out;
// read conf from stdin
if(args[i] === STDIN) {
out.stdin = true;
i++;
// conf should be first arg
}else ... | javascript | {
"resource": ""
} |
q39428 | Connection | train | function Connection(socket) {
events.EventEmitter.call(this);
// underlying socket
this._socket = socket;
// flag whether this connection is paused
this._paused = false;
// external or in-process client connection
this._tcp = (this._socket instanceof Socket);
// state information
this._client = ne... | javascript | {
"resource": ""
} |
q39429 | resume | train | function resume() {
this._paused = false;
if(this.client._qbuf.length) {
this.data(this.client._qbuf);
this.client._qbuf = new Buffer(0);
}
} | javascript | {
"resource": ""
} |
q39430 | onWrite | train | function onWrite(req) {
if(!this.transaction || !this.watched || req.conn.id === this.id) {
return false;
}
//console.dir(req.keys);
//console.dir(req.args);
var keys = req.keys || req.def.getKeys(req.args), i, key;
for(i = 0;i < keys.length;i++) {
key = '' + keys[i];
//console.error('got chan... | javascript | {
"resource": ""
} |
q39431 | watch | train | function watch(keys, database) {
keys = keys.map(function(k) {
if(k instanceof Buffer) return k.toString();
return k;
})
//console.dir(keys);
// watch can be called multiple times
// with the same keys, prevent listener leaks
this.unwatch(database);
database.on('write', this.onWrite);
this.w... | javascript | {
"resource": ""
} |
q39432 | data | train | function data(buf) {
if(this._tcp) {
if(this._paused) {
this.client._qbuf = Buffer.concat(
[this.client._qbuf, buf], this.client._qbuf.length + buf.length);
return false;
}
this.emit('input', buf.length);
this._process(buf);
}else{
// TODO: handle pausing internal connections... | javascript | {
"resource": ""
} |
q39433 | monitor | train | function monitor(server) {
// cannot receive data anymore we just send it
this.removeAllListeners('data');
var listener = this.request.bind(this);
// keep track of the monitor listeners
// for clean up
server._monitor[this.id] = listener;
// flag on the client for client list flags
this._client.monit... | javascript | {
"resource": ""
} |
q39434 | decoded | train | function decoded(err, reply) {
//console.error('got decoder err %s', err );
//console.error('got decoder reply %j',reply );
var res = new Response(this), req, cmd, args;
if(err) {
// return decoder errors to the client
return res.send(err);
}
// we should only be handling array request types
if(!... | javascript | {
"resource": ""
} |
q39435 | _process | train | function _process(buf) {
var b = buf[0], cli, cmd, req, res;
//console.dir('' + buf);
// does it look like a RESP message
if(b === STR
|| b === ERR
|| b === INT
|| b === BST
|| b === ARR
// already buffered some data, chunked request
|| (this.decoder.isBuffered())) {
//console.dir(... | javascript | {
"resource": ""
} |
q39436 | end | train | function end(cb) {
if(typeof cb === 'function') {
this.once('disconnect', cb);
}
if(this.tcp) {
// must call destroy to terminate immediately
this._socket.destroy();
}else{
this._socket.end();
}
} | javascript | {
"resource": ""
} |
q39437 | write | train | function write(data, cb) {
if(this._tcp) {
//this.emit('output', data);
this.encoder.write(data, cb);
}else{
this._socket.write.call(this._socket, data, cb);
}
} | javascript | {
"resource": ""
} |
q39438 | publishedVers | train | function publishedVers(name) {
var _child$spawnSync = _child_process2['default'].spawnSync(npmCommand, ['view', name, 'versions', '--json']);
var stdout = _child$spawnSync.stdout;
var error = _child$spawnSync.error;
if (error) throw error;
return JSON.parse(stdout.toString());... | javascript | {
"resource": ""
} |
q39439 | installVer | train | function installVer(name, ver, dir) {
var _child$spawnSync2 = _child_process2['default'].spawnSync(npmCommand, ['install', name + '@' + ver], { cwd: dir });
var error = _child$spawnSync2.error;
if (error) throw error;
} | javascript | {
"resource": ""
} |
q39440 | listInstalledVer | train | function listInstalledVer(name, dir) {
var _child$spawnSync3 = _child_process2['default'].spawnSync(npmCommand, ['list', name, '--depth', '0', '--json'], { cwd: dir });
var stdout = _child$spawnSync3.stdout;
var error = _child$spawnSync3.error;
var status = _child$spawnSync3.status;
... | javascript | {
"resource": ""
} |
q39441 | uninstalledVer | train | function uninstalledVer(name, ver, dir) {
var _child$spawnSync4 = _child_process2['default'].spawnSync(npmCommand, ['uninstall', ver.length === 0 ? name : name + '@' + ver], { cwd: dir });
var error = _child$spawnSync4.error;
if (error) throw error;
} | javascript | {
"resource": ""
} |
q39442 | getSchema | train | function getSchema(path) {
var parts = path.split('.');
var collectionName = parts[0];
var fieldName = parts[1];
// if format not user.field or field not in the schemaDefinitions object, then log error without breaking
if (parts.length !== 2 || !schemaDefinitions[collectionName]... | javascript | {
"resource": ""
} |
q39443 | parseValidateAttr | train | function parseValidateAttr(validateAttr, schema, validateFns) {
// if an array, loop through and recurse
if (_.isArray(validateAttr)) {
_.each(validateAttr, function (validator) {
parseValidateAttr(validator, schema, validateFns);
});
return;
... | javascript | {
"resource": ""
} |
q39444 | generateValidationFn | train | function generateValidationFn(schema) {
return function (req) {
// if already an error, return without doing any additional validation
if (req.error) { return req; }
var keys = Object.keys(schema);
var len = (req.value && req.value.trim().length) || 0;
... | javascript | {
"resource": ""
} |
q39445 | getCandidates | train | function getCandidates(moduleName, srcPath) {
const
candidates = [],
moduleNames = getSynonyms(moduleName);
for( const path of srcPath) {
for( const name of moduleNames) {
candidates.push( Path.resolve( path, "mod", name) );
}
}
return candidates;
} | javascript | {
"resource": ""
} |
q39446 | getFirstViableCandidate | train | function getFirstViableCandidate(candidates) {
for( const candidate of candidates) {
const fileJS = `${candidate}.js`;
if( Fs.existsSync(fileJS) ) return candidate;
const fileXJS = `${candidate}.xjs`;
if( Fs.existsSync(fileXJS) ) return candidate;
}
return candidates[0];
} | javascript | {
"resource": ""
} |
q39447 | setupOptions | train | function setupOptions(opts) {
var options = Object.create(null);
for (var opt in defaultOptions) {
if (opts && Object.prototype.hasOwnProperty.call(opts, opt)) {
var incomingOpt = opts[opt];
options[opt] = typeof incomingOpt === 'function' ? incomingOpt() : incomingOpt;
}... | javascript | {
"resource": ""
} |
q39448 | surroundExpression | train | function surroundExpression(c) {
return function(node, st, override, format) {
st.compiler.jsBuffer.concat("(");
c(node, st, override, format);
st.compiler.jsBuffer.concat(")");
}
} | javascript | {
"resource": ""
} |
q39449 | train | function(node, st, c) {
var compiler = st.compiler;
if (compiler.generate)
compiler.jsBuffer.concat(node.name, node);
} | javascript | {
"resource": ""
} | |
q39450 | buildErrorObject | train | function buildErrorObject(params){
params = params || {};
//If the userDetail is already set, not building the error object again.
if(params.err && params.err.userDetail){
return params;
}
var err = params.err || {message: "Unexpected Error"};
var msg = params.msg || params.err.message || "Unexpected ... | javascript | {
"resource": ""
} |
q39451 | setResponseHeaders | train | function setResponseHeaders(res) {
if(res.setHeader) {
var contentType = res.getHeader('content-type');
if (!contentType) {
res.setHeader('Content-Type', 'application/json');
}
}
} | javascript | {
"resource": ""
} |
q39452 | handleError | train | function handleError(err, msg, code, req, res){
logError(err, msg, code, req);
var response = buildErrorObject({
err: err,
msg: msg,
httpCode: code
});
res.statusCode = response.httpCode;
res.end(JSON.stringify(response.errorFields));
} | javascript | {
"resource": ""
} |
q39453 | sortObject | train | function sortObject(obj) {
assert.ok(_.isObject(obj), 'Parameter should be an object! - ' + util.inspect(obj));
assert.ok(!_.isArray(obj), 'Parameter should be an object, got array: ' + util.inspect(obj));
var sortedKeys = _.keys(obj).sort();
var sortedObjs = [];
_.each(sortedKeys, function(key) {
var v... | javascript | {
"resource": ""
} |
q39454 | gitTagsInfo | train | function gitTagsInfo(newTag) {
const date = new Date().toISOString();
return Promise.all([
git('git tag -l', stdout => {
const allTags = stdout
.toString()
.trim()
.split('\n')
.sort((a, b) => {
if (Semver.lt(a, b)) return -1;
if (Semver.gt(a, b)) retur... | javascript | {
"resource": ""
} |
q39455 | get_property | train | function get_property(obj, path) {
if(!is_object(obj)) { return error('get_property(obj, ...) not object: '+ obj); }
if(!is_string(path)) { return error('get_property(..., path) not string: '+ path); }
return path.split('.').reduce(get_property_step, obj);
} | javascript | {
"resource": ""
} |
q39456 | get_pg_prop | train | function get_pg_prop(name) {
if(name[0] === '$') {
return name.substr(1);
}
var parts = name.split('.');
if(parts.length === 1) {
return "content->>'" + name + "'";
}
if(parts.length === 2) {
return "content->'" + parts.join("'->>'") + "'";
}
return "content->'" + par... | javascript | {
"resource": ""
} |
q39457 | expression_query | train | function expression_query(parent, prop, type_name, type_prop, fields) {
fields = (fields || [{'query':'*'}]);
var map = {};
var query = "SELECT "+fields.map(function(f, i) {
var k;
if(f.key) {
k = 'p__' + i;
map[k] = f;
return f.query + ' AS ' + k;
} else {
return f... | javascript | {
"resource": ""
} |
q39458 | train | function (config) { // ctor
var
me = this;
config = config || {};
this.directory = config.directory;
this.output = config.output || process.stdout;
this.filesMaxSize = config.filesMaxSize || 1024 * 1024 * 1024 * 4 // 4 Go
this.writer = syslogwriter.create({
directory: this.directory,
filesMaxSize: t... | javascript | {
"resource": ""
} | |
q39459 | fontAPI | train | function fontAPI( fonts ) {
var promises = [];
fonts.forEach(function (font) {
var pro = document.fonts.load( '64px "' + font + '"' );
promises.push( pro );
});
return Promise.all( promises );
} | javascript | {
"resource": ""
} |
q39460 | fallback | train | function fallback( fonts ) {
return new Promise(function (resolve, reject) {
var divs = [];
var body = document.body;
fonts.forEach(function (font) {
var div = document.createElement( 'div' );
div.className = 'tfw-font-loader';
div.style.fontFamily = font;... | javascript | {
"resource": ""
} |
q39461 | Exception | train | function Exception(message, innerException) {
if (!message) {
throw new Exception("Argument 'message' is required but was '" +
(message === null ? "null" : "undefined") + "'");
}
if (typeof message !== 'string') {
throw new Exception("Argument 'message' must be of type 'string' but was '" + typeof m... | javascript | {
"resource": ""
} |
q39462 | request | train | function request(remoteUrl) {
return new Promise((resolve, reject) => {
const get = adapters[url.parse(remoteUrl).protocol].get;
get(remoteUrl, res => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let rawData = '';
// If it's not a 200 and not a 404 th... | javascript | {
"resource": ""
} |
q39463 | deepPromisify | train | function deepPromisify(obj) {
return _.transform(obj, function(promisifiedObj, value, key) {
if (blacklist.has(key)) {
promisifiedObj[key] = value;
return;
}
if (typeof value === 'function') {
promisifiedObj[key] = bluebird.promisify(value, obj);
} else if (typeof value === 'object'... | javascript | {
"resource": ""
} |
q39464 | rep | train | function rep (num, str) {
return function (arr, done) {
arr.forEach(function (i, idx) {
var s = ''
if (typeof i === 'string') s = i
if (idx === 0) return
else if (idx/num === Math.floor(idx/num)) arr[idx] = s + str
})
done()
}
} | javascript | {
"resource": ""
} |
q39465 | train | function (dirPath) {
var dirContents = fs.readdirSync(dirPath);
return dirContents.filter(function (subDirName) {
// Filter out non-directories.
var subDirPath = path.join(dirPath, subDirName);
return fs.lstatSync(subDirPath).isDirectory();
});
} | javascript | {
"resource": ""
} | |
q39466 | train | function(name)
{
//Check if the queue exists
if(typeof tasks[name] !== 'object'){ return; }
//Check if queue is paused
if(tasks[name].paused === true)
{
//Set task queue running false
tasks[name].running = false;
}
else
{
//Set queue running
tasks[name].running = true;
//Check the ... | javascript | {
"resource": ""
} | |
q39467 | OAuth2Error | train | function OAuth2Error(message, code, uri, status) {
Error.call(this);
this.message = message;
this.code = code || 'server_error';
this.uri = uri;
this.status = status || 500;
} | javascript | {
"resource": ""
} |
q39468 | factoriseBundles | train | function factoriseBundles(modules, duplicates, loaderConfig, maxBundles) {
// Remember all dependencies, along with related information.
// dependencyId -> { mains: [...], size: 123 }
var allDependencies = {};
// Each module that is duplicated, is a module shared by two or more mains.
// So we gro... | javascript | {
"resource": ""
} |
q39469 | train | function (collectionKey, queryKey) {
return new Promise(function (ok) {
redisClient.multi().get(collectionKey).get(queryKey).exec(function (err, results) {
if (err) {
err.message = util.format('mongoose cache error %s', queryKey);
debug(err);
ok([null, null]); // ignore error, instea... | javascript | {
"resource": ""
} | |
q39470 | smoothScroll | train | function smoothScroll() {
if (window.addEventListener)
window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;
var hb = {
sTop: 0,
sDelta: 0
};
function wheel(event) {
var distance = jQuery.browser.webkit ? 60 : 120;
if (event.wheelDelta)
delt... | javascript | {
"resource": ""
} |
q39471 | stringifySync | train | function stringifySync(obj) {
var output = "";
var firstOccur = true;
Object.keys(obj).forEach(function (key) {
if (typeof obj[key] === "string") {
output += key + "=" + obj[key];
output += os.EOL;
} else {
if (firstOccur) {
firstOccur = false;
} else {
output += os.EOL;
}
output += "... | javascript | {
"resource": ""
} |
q39472 | stringify | train | function stringify(obj, callback) {
process.nextTick(function () {
var str = stringifySync(obj);
callback(str);
});
} | javascript | {
"resource": ""
} |
q39473 | train | function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
} | javascript | {
"resource": ""
} | |
q39474 | emitSIGINT | train | function emitSIGINT() {
if (rl) {
rl.close()
rl = null
}
if (ipcListener) {
process.removeListener("message", ipcListener)
ipcListener = null
}
emitter.emit("SIGINT")
} | javascript | {
"resource": ""
} |
q39475 | train | function(className) {
var cls = _classes[className];
if (!cls) {
var k, name,
def = window["TFW::" + className];
if (!def) {
throw new Error(
"[TFW3] This class has not been defined: \"" + className + "\"!\n"
... | javascript | {
"resource": ""
} | |
q39476 | parse | train | function parse(base, key, value) {
var type = typeof value;
// resolve local JSON pointers
if (key === 'href' && type === 'string') return formatHref(base, value);
// TODO resolve "/" paths
if (!value || type !== 'object') return value;
var obj = copy(value);
if (key === '' || obj.href) seal(base || o... | javascript | {
"resource": ""
} |
q39477 | getPointLineSegmentState | train | function getPointLineSegmentState([ x, y ], [ [ beginX, beginY ], [ endX, endY ] ]) {
if (!isPointInLine([ x, y ], [ [ beginX, beginY ], [ endX, endY ] ])) {
return OUTSIDE;
}
if (beginX === endX) {
if (roundToFiveSignificantDigits((y - beginY) * (y - endY)) < 0) {
return INSIDE;
} else if (roundToFiveSigni... | javascript | {
"resource": ""
} |
q39478 | getLineIntersect | train | function getLineIntersect([ line1Begin, line1End ], [ line2Begin, line2End ]) {
let [ x1Begin, y1Begin ] = line1Begin;
let [ x1End, y1End ] = line1End;
let [ x2Begin, y2Begin ] = line2Begin;
let [ x2End, y2End ] = line2End;
if ((x1Begin === x1End && y1Begin === y1End) || (x2Begin === x2End && y2Begin === y2End)) {... | javascript | {
"resource": ""
} |
q39479 | getLineSegmentsIntersectState | train | function getLineSegmentsIntersectState([ line1Begin, line1End ], [ line2Begin, line2End ]) {
let [ x1Begin, y1Begin ] = line1Begin;
let [ x1End, y1End ] = line1End;
let [ x2Begin, y2Begin ] = line2Begin;
let [ x2End, y2End ] = line2End;
if ((x1Begin === x1End && y1Begin === y1End) || (x2Begin === x2End && y2Begin ... | javascript | {
"resource": ""
} |
q39480 | getRandPointInLineSegment | train | function getRandPointInLineSegment([ [ beginX, beginY ], [ endX, endY ] ]) {
let smallX = beginX <= endX ? beginX : endX;
let largeX = beginX >= endX ? beginX : endX;
let smallY = beginY <= endY ? beginY : endY;
let largeY = beginY >= endY ? beginY : endY;
if (beginY === endY) return [ roundToFiveSignificantDigits... | javascript | {
"resource": ""
} |
q39481 | getLinearRingsIntersectState | train | function getLinearRingsIntersectState(linearRing1, linearRing2) {
let isLinearRingsTouching = false;
for (let i = 0; i < linearRing1.length - 1; i++) {
for (let j = 0; j < linearRing2.length - 1; j++) {
let state = getLineSegmentsIntersectState(
[ linearRing2[j], linearRing2[j + 1] ], [ linearRing1[i], linea... | javascript | {
"resource": ""
} |
q39482 | getRayLineSegmentIntersectState | train | function getRayLineSegmentIntersectState([ rayOrigin, rayPoint ], [ lineBegin, lineEnd ]) {
// Find unit deviations for ray and point
let dRay = vectorSubtract(rayPoint, rayOrigin);
let dLine = vectorSubtract(lineEnd, lineBegin);
if (vectorCross(dRay, dLine) === 0) {
if (vectorCross(vectorSubtract(lineBegin, ray... | javascript | {
"resource": ""
} |
q39483 | pointLinearRingState | train | function pointLinearRingState(point, linearRing) {
let { topLeftVertex, width, height } = getBoundingBox(linearRing);
let [ minX, maxY ] = topLeftVertex;
let maxX = minX + width;
let minY = maxY - height;
let [ x, y ] = point;
if (x < minX || x > maxX || y < minY || y > maxY) return OUTSIDE;
for (let i = 0; i < ... | javascript | {
"resource": ""
} |
q39484 | getBoundingBox | train | function getBoundingBox(linearRing) {
if (!Array.isArray(linearRing)) {
throw new XError(XError.INVALID_ARGUMENT, 'linearRing must be an array');
}
let leftX = Infinity;
let rightX = -Infinity;
let bottomY = Infinity;
let topY = -Infinity;
for (let point of linearRing) {
if (!Array.isArray(point) || point.l... | javascript | {
"resource": ""
} |
q39485 | squareLinearRingIntersectState | train | function squareLinearRingIntersectState(linearRing, topLeftVertex, squareSize) {
let [ topLeftX, topLeftY ] = topLeftVertex;
let topRightVertex = [ topLeftX + squareSize, topLeftY ];
let bottomRightVertex = [ topLeftX + squareSize, topLeftY - squareSize ];
let bottomLeftVertex = [ topLeftX, topLeftY - squareSize ];... | javascript | {
"resource": ""
} |
q39486 | ajax_return | train | function ajax_return(data, status, xhr) {
// If the update was successfull
if (data.ok) {
// Forget old value
this.removeData('old-value');
// Add a green V to the right
this.parent().next()
.off('click')
.html('V')
.css('color', 'LimeGreen')
.attr('title', 'Update OK');
// If we modif... | javascript | {
"resource": ""
} |
q39487 | init | train | function init(config, cb) {
connection = mongoose.createConnection(config.mongoUrl);
var firstCallback = true;
connection.on('error', function(err) {
log.logger.error('Mongo error: ' + util.inspect(err));
if (firstCallback) {
firstCallback = false;
return cb(err);
} else ... | javascript | {
"resource": ""
} |
q39488 | disconnect | train | function disconnect(cb) {
if (connection) {
log.logger.debug('Mongoose disconnected');
connection.close(cb);
} else {
cb();
}
} | javascript | {
"resource": ""
} |
q39489 | removeFromChildRegistry | train | function removeFromChildRegistry(childRegistry, child) {
assertType(childRegistry, 'object', false, 'Invalid child registry specified');
assertType(child, [Node, Array, 'string'], false, 'Invalid child(ren) or name specified');
if (typeof child === 'string') {
let targets = child.split('.');
let currentT... | javascript | {
"resource": ""
} |
q39490 | train | function(path, contract) {
if (!contract) {
contract = path;
path = '/';
}
if (contract.handle) {
this.root.use(path, (req, res, next) => {
contract.handle(req, res, next)
});
} else {
this.root.use(path, contract);
}
return this;
} | javascript | {
"resource": ""
} | |
q39491 | logJsHintWarning | train | function logJsHintWarning (errors)
{
totalIssues += errors.length;
var sourceFile = pathHelper.makeRelative(this.resourcePath);
gulpUtil.log(gulpUtil.colors.yellow("jshint warning") + " in " + sourceFile);
for (var i = 0, l = errors.length; i < l; i++)
{
var error = errors[i];
gul... | javascript | {
"resource": ""
} |
q39492 | reportTotalIssueCount | train | function reportTotalIssueCount ()
{
var outputColor = gulpUtil.colors.green;
if (totalIssues > 0)
{
outputColor = gulpUtil.colors.red;
}
gulpUtil.log(gulpUtil.colors.yellow('»»'), 'Total JS issues:', outputColor(totalIssues));
// Reset the issue count so we don't increment it every tim... | javascript | {
"resource": ""
} |
q39493 | getTokenParameters | train | function getTokenParameters(index) {
let stringLength;
let indexWithOffset;
indexWithOffset = index;
for (stringLength = startLength; stringLength <= endLength; stringLength += 1) {
const offsetCount = variants.length ** stringLength;
if (indexWithOffset < offsetCount) {
break;
... | javascript | {
"resource": ""
} |
q39494 | clearCache | train | function clearCache() {
let deletedCount = 0;
const iter = eventSourceMappingKeysByFunctionAndStream.entries();
let next = iter.next();
while (!next.done) {
const [k, key] = next.value;
const deleted = eventSourceMappingPromisesByKey.delete(key);
eventSourceMappingKeysByFunctionAndStream.delete(k)... | javascript | {
"resource": ""
} |
q39495 | loadPage | train | function loadPage(url) {
$("#container").load(url+" #container > *", function(response, status, xhr){
$('html,body').scrollTop(0); // Scroll to the top when loading new page.
if(status == "error"){
$("#container").prepend('<p class="alert alert-danger" role="alert"><strong>'+msgError+'</strong> '+xhr.status... | javascript | {
"resource": ""
} |
q39496 | next | train | function next() {
var data = new Object();
// Submit content of all forms -- except those with class 'ignore-form' -- before going to next page.
$('#container form:not(.ignore-form)').each(function(index) {
//console.log("Form no. "+index + " with the ID #" + $(this).attr('id') );
//console.log($( this )... | javascript | {
"resource": ""
} |
q39497 | requireAuthorization | train | function requireAuthorization(handler) {
return function(request, response, store, parameters) {
var handlerArguments = arguments
var publisher = parameters.publisher
var authorization = request.headers.authorization
if (authorization) {
var parsed = parseAuthorization(authorization)
if (p... | javascript | {
"resource": ""
} |
q39498 | transform | train | function transform(flapjack, options) {
var moduleName = options.moduleName;
var filePath = options.filePath;
var appName = this.getAppName(filePath, options.appName);
var resource = this.pancakes.cook(moduleName, { flapjack: flapjack });
var templateModel = this.getTemplateModel(options.prefix, res... | javascript | {
"resource": ""
} |
q39499 | getTemplateModel | train | function getTemplateModel(prefix, resource, appName) {
var methods = {};
// if no api or browser apiclient, then return null since we will skip
if (!resource.api || resource.adapters.browser !== 'apiclient') {
return null;
}
// loop through API routes and create method objects for the temp... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.