_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 rows underneath const largestElem = me[(i * 3) + i]; if (!Compare.isZero(largestElem, TOL)) { scaleRow(M, i, 1.0 / largestElem); for (let j = i + 1; j < 3; ++j) { const scaleElem = me[(i * 3) + j]; if (!Compare.isZero(scaleElem, TOL)) { scaleAndAddRow(M, i, j, -scaleElem); } } } } // iterate back through to get RREF since everything on diagonals should be 1 or 0 for (let i = 2; i >= 0; --i) { const val = me[(i * 3) + i]; if (!Compare.isZero(val, TOL)) { for (let j = i - 1; j >= 0; --j) { const scaleElem = me[(i * 3) + j]; if (!Compare.isZero(scaleElem, TOL)) { scaleAndAddRow(M, i, j, -scaleElem); } } } } return M; }
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); if (ti > max) { max = ti; rowCol.row = j; rowCol.column = i; rowCol.value = val; } } } return rowCol; }
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; lrgElem = val; } } return lrgCol; }
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; maxVal = val; } } return maxIdx; }
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.isZero(val, TOL)) { rowCol.row = j; rowCol.column = i; rowCol.value = val; return rowCol; } } } } return rowCol; }
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); } const xi = b.getComponent(P[i]) - sum; X.setComponent(i, xi); } // U * x = y ==> i = n-1 -> 0, j = 0 for (let i = n - 1; i >= 0; --i) { let sum = 0; for (let j = i + 1; j < n; ++j) { sum += a[i + j * n] * X.getComponent(j); } const scale = a[i + i * n]; // if (scale === 0) { // consoleWarning(`luSolve(): x[${i}] is free.`); // } X.setComponent(i, (X.getComponent(i) - sum) / scale); } return X; }
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 + i]; // row scaling if (scaler === 0) { throw new Error('luDecomposition(): matrix is singular and cannot be LU factorized.'); } rowScalers[i] = scaler; // don't actually want to scale the matrix or else (PA != LU). } // iterate over columns to reduce the matrix // implicitly reduce the matrix for (let j = 0; j < n; ++j) { for (let i = 0; i < j; ++i) { // compute upper tri, computes values across the row let sum = 0; for (let k = 0; k < i; ++k) { sum += a[i + k * n] * a[k + j * n]; // avoid big + small roundoffs } a[i + j * n] = a[i + j * n] - sum; } let pivotLrgElem = 0; let pivotIndex = j; for (let i = j; i < n; ++i) { // compute lower tri and diagonal, computes values down the column let sum = 0; for (let k = 0; k < j; ++k) { sum += a[i + k * n] * a[k + j * n]; // avoid big + small roundoffs } a[i + j * n] = a[i + j * n] - sum; // find the pivot element const pivotTest = rowScalers[i] * Math.abs(a[i + j * n]); if (pivotTest > pivotLrgElem) { pivotLrgElem = pivotTest; pivotIndex = i; } } swapRowsInPlace(A, j, pivotIndex); swapValuesInArray(P, j, pivotIndex); swapValuesInArray(rowScalers, j, pivotIndex); if (j < n - 1) { const pivotScale = a[j + j * n]; for (let i = j + 1; i < n; ++i) { a[i + j * n] /= pivotScale; } } } return { P, A }; }
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 u2 = u2t.sub(proj(u1, u2t)); if (n === 3) { m.setColumns(u0, u1, u2); // return; } }
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) { c = 0; s = _Math.sign(b); r = _Math.abs(b); } else if (_Math.abs(a) > _Math.abs(b)) { t = b / a; u = _Math.sign(a) * _Math.sqrt(1 + t * t); c = 1 / u; s = t * c; r = a * u; } else { t = a / b; u = _Math.sign(a) * _Math.sqrt(1 + t * t); s = 1 / u; c = t * s; r = b * u; } // try to save some unnecessary object creation if (csr !== undefined && csr.length > 2) { csr[0] = c; csr[1] = s; csr[2] = r; } else { return [c, s, r]; } }
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) { const a = re[n * j + (i - 1)]; // R.get(i - 1, j); const b = re[n * j + i]; // R.get(i, j); if (a === 0 && b === 0) { continue; } rotg(a, b, csr); const c = csr[0]; const s = csr[1]; let tmp1 = 0; let tmp2 = 0; // R' = G * R for (let x = 0; x < n; ++x) { tmp1 = re[n * x + (i - 1)]; // R.get(i - 1, x); tmp2 = re[n * x + i]; // R.get(i, x); re[n * x + (i - 1)] = tmp1 * c + tmp2 * s; // R.set(i - 1, x, tmp1 * c + tmp2 * s); re[n * x + i] = -tmp1 * s + tmp2 * c; // R.set(i, x, -tmp1 * s + tmp2 * c); } re[n * j + (i - 1)] = csr[2]; // R.set(i - 1, j, csr[2]); re[n * j + i] = 0; // R.set(i, j, 0); // Q' = Q * G^T for (let x = 0; x < m; ++x) { tmp1 = qe[n * (i - 1) + x]; // Q.get(x, i - 1); tmp2 = qe[n * i + x]; // Q.get(x, i); qe[n * (i - 1) + x] = tmp1 * c + tmp2 * s; // Q.set(x, i - 1, tmp1 * c + tmp2 * s); qe[n * i + x] = -tmp1 * s + tmp2 * c; // Q.set(x, i, -tmp1 * s + tmp2 * c); } } } return { Q, R }; }
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; const mu = _Math.sqrt(x1 * x1 + sigma); const v1 = (x1 <= 0 ? x1 - mu : -sigma / (x1 + mu)); v.x = v1; beta = 2 * v1 * v1 / (sigma + v1 * v1); v.multiplyScalar(1.0 / v1); } return { v, beta }; }
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 c = csr[0]; const s = csr[1]; const r = csr[2]; cs[k] = [c, s]; for (let x = k; x < n; ++x) { const colX = x * n; const tmp1 = me[row1 + colX]; const tmp2 = me[row2 + colX]; me[row1 + colX] = c * tmp1 + s * tmp2; me[row2 + colX] = -s * tmp1 + c * tmp2; } me[row1 + colK] = r; me[row2 + colK] = 0; } for (let k = 0; k < n - 1; ++k) { const col1 = k * n; const col2 = (k + 1) * n; const [c, s] = cs[k]; for (let x = 0; x <= k + 1; ++x) { const rowX = x; const tmp1 = me[rowX + col1]; const tmp2 = me[rowX + col2]; me[rowX + col1] = tmp1 * c + tmp2 * s; me[rowX + col2] = -tmp1 * s + tmp2 * c; } } return M; }
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 = new Array(l); i < l; i++) { args[i] = arguments[i]; } (global.setImmediate || global.setTimeout)(function delay() { fn.apply(self, args); self = args = null; }, 0); }
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; return false; }
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 clone into. var tmp_dir = clone_dir; if(!tmp_dir){ tmp_dir = path.join(os.tmpdir(), 'git', String((new Date()).valueOf())); } shell.rm('-rf', tmp_dir); shell.mkdir('-p', tmp_dir); var cloneArgs = ['clone']; if(!needsGitCheckout) { // only get depth of 1 if there is no branch/commit specified cloneArgs.push('--depth=1'); } cloneArgs.push(git_url, tmp_dir); return superspawn.spawn('git', cloneArgs) .then(function() { if (needsGitCheckout){ return superspawn.spawn('git', ['checkout', git_ref], { cwd: tmp_dir }); } }) .then(function(){ events.emit('log', 'Repository "' + git_url + '" checked out to git ref "' + (git_ref || 'master') + '".'); return tmp_dir; }) .fail(function (err) { shell.rm('-rf', tmp_dir); return Q.reject(err); }); }
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 = this.options.viewCacheDir; fs.ensureDir(viewCacheDir,function(err){ if(err){ console.error(err); } }); }
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 if(!PTN.test(args[i])) { out.file = args[i]; i++; } function add(key, value) { if(!key || value === null) return; if(!out.directives[key]) { out.directives[key] = value; // handle repeated directives, create an array }else if(out.directives[key] && !Array.isArray(out.directives[key])){ out.directives[key] = [out.directives[key]]; out.directives[key].push(value) // append to existing array value }else{ out.directives[key].push(value) } } function gobble(arg, key, value) { if(arg === undefined) return add(key, value); value = value || ''; if(PTN.test(arg)) { key = arg.replace(PTN, ''); // gobble up value arguments while((arg = args[i++]) !== undefined && !PTN.test(arg)) { if(value) value += ' '; value += arg; } if(PTN.test(arg)) i--; add(key, value); value = null; }else{ if(value) value += ' '; value += arg; } gobble(args[i++], key, value); } gobble(args[i]); return out; }
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 = new Client(socket); this.data = this.data.bind(this); this._socket.once('close', this._close.bind(this)); this._socket.on('data', this.data); // using a tcp socket connection if(this._tcp) { this.encoder = new Encoder({return_buffers: true}) this.encoder.on('push', onPush.bind(this)); this.encoder.pipe(this._socket); this.decoder = new Decoder({return_buffers: true}); this.decoder.on('reply', this.decoded.bind(this)); this.decoder.on('error', this.decoded.bind(this)); function onSocketError(err) { log.warning(err.message); } this._socket.on('error', onSocketError.bind(this)); } this.onWrite = this.onWrite.bind(this); }
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 change with key %s', key); //console.error('got change with value %s', value); //console.error('got change with conn id %j', req.conn.id); if(~this.watched.indexOf(key)) { //console.error('setting conflict on %s', keys[i]); //console.error('setting conflict from %s', req.conn.id); this.transaction.conflict = true; return true; } } }
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.watched = keys; }
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! // not actually a buffer for internal sockets // rather the raw request itself, ie: array with command // and arguments this.decoded(null, buf); } }
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.monitor = true; server.on('monitor', listener); }
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(!Array.isArray(reply)) { return res.send(new Error('bad request, array expected')); }else if(!reply.length) { return res.send(new Error('bad request, empty array invalid')); } cmd = reply.shift(); if(cmd instanceof Buffer) cmd = cmd.toString(); if(typeof cmd !== 'string') { return res.send(new Error('bad request, string command expected')); } cmd = cmd.toLowerCase(); // keep track of last command this._client.cmd = cmd; //console.error('got decoder cmd %s', cmd ); //console.error('got decoder args %j', reply ); req = new Request(this, cmd, reply); this.emit('command', req, res); }
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('writing buffer to decoder..'); this.decoder.write(buf); }else{ try { cli = itr.interpret(buf.toString()); }catch(e) { // ignore empty command strings return; } cmd = (cli.shift() + '').toLowerCase(); req = new Request(this, cmd, cli); res = new Response(this); this.emit('command', req, res); } }
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; // the package is invalid or uninstalled if (error || 0 !== status) { return ''; } return JSON.parse(stdout)['version']; }
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] || !schemaDefinitions[collectionName][fieldName]) { log.error('No schemaDefinitions for : ' + path, null); return {}; } return schemaDefinitions[collectionName][fieldName]; }
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; } // if validateAttr is a string, then assume it is field reference if (_.isString(validateAttr)) { _.extend(schema, getSchema(validateAttr)); } else if (_.isFunction(validateAttr)) { validateFns.push(wrapFn(validateAttr)); } else if (_.isObject(validateAttr)) { _.extend(schema, validateAttr); } }
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; var i, key, originalKey; for (i = 0; i < keys.length; i++) { key = originalKey = keys[i]; if (key.indexOf('ui-') === 0) { key = key.substring(3); } // if validation function exists but it returns false then we have error if (check[key] && !check[key](schema, req.value)) { var errMsg = schema[key + 'Desc'] || errorMessage[key] || 'Invalid input'; req.error = errMsg .replace('{' + key + '}', schema[originalKey]) .replace('{value}', req.value) .replace('{length}', len); break; } } return req; }; }
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; } else if (defaultOptions.hasOwnProperty(opt)) { var defaultOpt = defaultOptions[opt]; options[opt] = typeof defaultOpt === 'function' ? defaultOpt() : defaultOpt; } } return options; }
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 Error"; var httpCode = params.httpCode || 500; //Custom Error Code var code = params.code || "FH-MBAAS-ERROR"; var response = { errorFields: { userDetail: msg, systemDetail: msg + ' - ' + util.inspect(err), code: code }, httpCode: httpCode }; if (params.explain) { response.errorFields.explain = params.explain; } return response; }
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 val = {}; val[key] = obj[key]; sortedObjs.push(val); }); return sortedObjs; }
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)) return 1; return 0; }); return allTags; }) .then(infoOfTags => { const tagsHolder = {}; let currentMajor = 1; let nextMajor = 2; let groups = []; infoOfTags.push(newTag); infoOfTags.forEach((tag, idx) => { groups.push({ tag, date: tag === newTag ? date.substring(0, date.indexOf('T')) : gitDateOf(tag) }); if (Semver.valid(infoOfTags[idx + 1])) { if (Semver.major(infoOfTags[idx + 1]) === nextMajor) { tagsHolder[`v${currentMajor}`] = groups; currentMajor += 1; nextMajor += 1; groups = []; } } else { tagsHolder[`v${currentMajor}`] = groups; } }); return tagsHolder; }) .catch(log.error), git('rev-list HEAD | tail -n 1') ]); }
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->'" + parts.slice(0, parts.length-1).join("'->'") + "'->>'" + parts[parts.length-1] + "'"; }
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.query; } }).join(', ')+" FROM documents WHERE type = $1 AND "+get_pg_prop(type_prop)+" = $2"; var rows = plv8.execute(query, [type_name, parent.id]); if(!is_array(rows)) { return rows; } var errors = []; rows = rows.map(function(obj) { Object.keys(obj).forEach(function(key) { if(!map.hasOwnProperty(key)) { return; } var spec = map[key]; if(!is_object(spec)) { errors.push( error('mapped resource missing') ); return; } if(!is_string(spec.key)) { errors.push( error('key missing') ); return; } var value = obj[key]; delete obj[key]; if(is_string(spec.datakey)) { if(!obj[spec.datakey]) { obj[spec.datakey] = {}; } obj[spec.datakey][spec.key] = value; } else { obj[spec.key] = value; } }); return obj; }); if(errors.length >= 1) { return errors.shift(); } return rows; }
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: this.filesMaxSize }); this.writer.on('error', function(exception) { me.emit('error', exception); }); Syslog.call(this, config); }
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; body.appendChild( div ); }); // Ugly trick: juste wait 1.5 second. window.setTimeout(function () { divs.forEach(function (d) { body.removeChild( d ); }); resolve( fonts ); }, 1500); }); }
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 message + "'"); } if (innerException === undefined && typeof message !== 'string') { innerException = message; message = innerException.message || innerException.toString(); } this.message = message; this.innerException = innerException; this.toString = function () { return message; }; }
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 there's another issue. Allwrite will // only return these two statuses. if (statusCode !== 200 && statusCode !== 404) { const error = new Error('Allwrite: Request Failed.\n' + `Status Code: ${statusCode}`); error.code = statusCode; return reject(error); } else if (!/^application\/json/.test(contentType)) { const error = new Error('Allwrite: Invalid content-type.\n' + `Expected application/json but got ${contentType}`); return reject(error); } res.setEncoding("utf8"); res.on("data", chunk => rawData += chunk); res.on("end", () => { try { resolve(JSON.parse(rawData)); } catch (e) { reject(new Error("Allwrite response parsing error: " + e.message)); } }); }); }); }
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') { promisifiedObj[key] = deepPromisify(value); } else { promisifiedObj[key] = value; } }); }
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 number of tasks on this tag if(tasks[name].handlers.length === 0) { //Delete this path object delete tasks[name]; } else { //Get the function to run var handler = tasks[name].handlers.shift(); //Run this task return handler.call(null, function() { //Continue with the next task return process.nextTick(function() { //Continue with the next task in the queue return task_run(name); }); }); } } }
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 group the duplicates into bundles, grouped by the set of mains that // share them. var bundles = {}; _.forIn(duplicates, function(dependentMains, dependencyPath) { // If we don't convert to a module ID, the output bundles config // doesn't match anything when it comes to loading the shared modules... var dependencyId = amd.modulePathToId(dependencyPath); // This is necessary because the RequireJS optimizer breaks when it // sees more than one kind of reference to a module -- and this includes // references in the bundle config. dependencyId = amd.convertToAlias(dependencyId, loaderConfig.paths); // Bundle name must be unique for each set of dependent mains, that's // how we group them. var bundleName = bundle.generateBundleName(dependentMains); // If the bundle doesn't exist yet, create one. if (!bundles[bundleName]) { bundles[bundleName] = { name: bundleName, dependentMains: [], dependencies: [], size: 0 }; } bundles[bundleName].dependencies.push(dependencyId); bundles[bundleName].dependentMains = _.union( bundles[bundleName].dependentMains, dependentMains ); // Remember all dependencies. allDependencies[dependencyId] = { mains: dependentMains, size: amd.moduleSize(dependencyPath, loaderConfig.paths) || 1024 }; }); // Reduce the number of bundles. bundles = reduce.reduceBundles( bundles, allDependencies, maxBundles ); // Exclude contents of all bundles, from each of the mains. This prevents // including of the bundled shared modules into the mains. var bundleNames = _.keys(bundles); _.forEach(modules, function(module) { if (!module.exclude) { module.exclude = []; } module.exclude = module.exclude.concat(bundleNames); }); // Register each of the bundles as a module. This tells the optimizer to // create each bundle, and to package the right shared modules into it. // To prevent shared modules being duplicated inbetween bundles, we // exclude all other dependencies not belonging to this bundle. var allDependencyIds = _.keys(allDependencies); _.forIn(bundles, function(bundle, bundleName) { modules.unshift({ create: true, name: bundleName, include: bundle.dependencies, excludeShallow: _.difference(allDependencyIds, bundle.dependencies) }); }); // And we're done. return { bundles: bundles, modules: modules } }
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, instead reject //return error(err); } var collectionData = results[0] && JSON.parse(results[0]), queryData = results[1] && JSON.parse(results[1]); //debug('redis cache object size', queryKey, helpers.getObjectSize(queryData)); // special cache miss where it is out of date if (queryData && collectionData && collectionData.lastWrite > queryData.metadata.lastWrite) { debug('mongoose cache out of date: ', queryKey); queryData = null; } ok([collectionData, queryData]); }); }); }
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) delta = event.wheelDelta / 120; else if (event.detail) delta = -event.detail / 3; hb.sTop = jQuery(window).scrollTop(); hb.sDelta = hb.sDelta + delta * distance; jQuery(hb).stop().animate({ sTop: jQuery(window).scrollTop() - hb.sDelta, sDelta: 0 }, { duration: 200, easing: 'linear', step: function(now, ex) { if (ex.prop == 'sTop') jQuery('html, body').scrollTop(now) }, }); if (event.preventDefault) event.preventDefault(); event.returnValue = false } }
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 += "[" + key + "]"; output += os.EOL; Object.keys(obj[key]).forEach(function (innerKey) { var value = obj[key][innerKey]; if (typeof value === "string") { // if value can ber converted to number or boolean, // but it should be a string, // so keep the quotes to indicate its type if (!isNaN(value) || value.toLowerCase() === "true" || value.toLowerCase() === "false") { value = "\"" + value + "\""; } } output += innerKey + "=" + value; output += os.EOL; }); } }); return 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" + "Did you forget to include it?" ); } // Création de la classe à partir de sa définition. cls = function () {}; var superclass = TFW3Object; if (def.superclass) { superclass = loadClass(def.superclass); } // Héritage cls.prototype = new superclass(); // Eviter que le constructeur de cette classe soit celui de la super classe. cls.prototype.constructor = cls; // Définition de l'attribut $parent pour accéder aux méthodes parentes. cls.prototype.$parent = superclass.prototype; // Multilangues. if (typeof def.lang === "object") { cls.prototype.$lang = def.lang; for (k in def.lang) { cls.prototype.$defLang = k; break; } } else { cls.prototype.$lang = superclass.prototype.$lang || {}; cls.prototype.$defLang = superclass.prototype.$defLang || "en"; } // Conserver le nom de la super classe. cls.prototype.$superclass = superclass.prototype.$classname; // Conserver le nom de la classe. cls.prototype.$classname = className; // Les noms des signals. cls.prototype.$signals = def.signals; // Est-ce un singleton ? cls.prototype.$singleton = def.singleton; // Espace réservé aux membres statiques de la classe. var staticVars = {className: className}; _statics[className] = staticVars; cls.prototype.$static = staticVars; // Valeurs par défaut des attributs. if (def.attributes) { for (k in def.attributes) { cls.prototype["_" + k] = def.attributes[k]; } } // Déclaration du constructeur. cls.prototype.$init = def.init; // Définition des méthodes liées aux signaux. if (def.signals) { for (i in def.signals) { declareSignal( cls, def.signals[i] ); } } // Assigner toutes les méthodes. for (name in def.functions) { if (def.superclass && cls.prototype[name]) { // This is an ovveride. cls.prototype[def.superclass + "$" + name] = cls.prototype[name]; } cls.prototype[name] = def.functions[name]; } // Mise en cache de la classe. _classes[className] = cls; // Appel d'un éventuel constructeur de classe. if (typeof def.classInit === "function") { def.classInit(staticVars); } } return cls; }
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 || obj.href, obj, []); return obj; }
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 (roundToFiveSignificantDigits((y - beginY) * (y - endY)) === 0) { return TANGENT; } else { return OUTSIDE; } } if (beginY === endY) { if (roundToFiveSignificantDigits((x - beginX) * (x - endX)) < 0) { return INSIDE; } else if (roundToFiveSignificantDigits((x - beginX) * (x - endX)) === 0) { return TANGENT; } else { return OUTSIDE; } } if (roundToFiveSignificantDigits((x - beginX) * (x - endX)) < 0 && roundToFiveSignificantDigits((y - beginY) * (y - endY)) < 0) { return INSIDE; } else if (x === beginX && y === beginY || (x === endX && y === endY)) { return TANGENT; } else { return OUTSIDE; } }
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)) { throw new XError(XError.INVALID_ARGUMENT, 'start and end point of line must not be the same'); } let slope1 = roundToFiveSignificantDigits((y1Begin - y1End) / (x1Begin - x1End)); let intercept1; if (x1Begin === x1End) { intercept1 = x1Begin; } else if (y1Begin === y1End) { intercept1 = y1Begin; } else { intercept1 = roundToFiveSignificantDigits((y1Begin * x1End - y1End * x1Begin) / (x1End - x1Begin)); } let slope2 = roundToFiveSignificantDigits((y2Begin - y2End) / (x2Begin - x2End)); let intercept2; if (x2Begin === x2End) { intercept2 = x2Begin; } else if (y2Begin === y2End) { intercept2 = y2Begin; } else { intercept2 = roundToFiveSignificantDigits((y2Begin * x2End - y2End * x2Begin) / (x2End - x2Begin)); } let intersectX, intersectY; if (slope1 === slope2 || (Math.abs(slope1) === Infinity && Math.abs(slope2) === Infinity)) { throw new XError(XError.INVALID_ARGUMENT, 'Can\'t get intersect of lines with the same slope'); } else { if (Math.abs(slope1) === Infinity) { intersectX = x1Begin; intersectY = roundToFiveSignificantDigits(slope2 * x1Begin + intercept2); } else if (Math.abs(slope2) === Infinity) { intersectX = x2Begin; intersectY = roundToFiveSignificantDigits(slope1 * x2Begin + intercept1); } else if (slope1 === 0) { intersectY = y1Begin; intersectX = roundToFiveSignificantDigits((intersectY - intercept2) / slope2); } else if (slope2 === 0) { intersectY = y2Begin; intersectX = roundToFiveSignificantDigits((intersectY - intercept1) / slope1); } else { intersectX = roundToFiveSignificantDigits((intercept2 - intercept1) / (slope1 - slope2)); intersectY = roundToFiveSignificantDigits(((slope1 * intercept2) - (slope2 * intercept1)) / (slope1 - slope2)); } } return [ intersectX, intersectY ]; }
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 === y2End)) { throw new XError(XError.INVALID_ARGUMENT, 'start and end point of line must not be the same'); } let slope1 = roundToFiveSignificantDigits((y1Begin - y1End) / (x1Begin - x1End)); let intercept1; if (x1Begin === x1End) { intercept1 = x1Begin; } else if (y1Begin === y1End) { intercept1 = y1Begin; } else { intercept1 = roundToFiveSignificantDigits((y1Begin * x1End - y1End * x1Begin) / (x1End - x1Begin)); } let slope2 = roundToFiveSignificantDigits((y2Begin - y2End) / (x2Begin - x2End)); let intercept2; if (x2Begin === x2End) { intercept2 = x2Begin; } else if (y2Begin === y2End) { intercept2 = y2Begin; } else { intercept2 = roundToFiveSignificantDigits((y2Begin * x2End - y2End * x2Begin) / (x2End - x2Begin)); } if (slope1 === slope2 || (Math.abs(slope1) === Infinity && Math.abs(slope2) === Infinity)) { if (intercept1 !== intercept2) { return UNINTERSECT; } else if (getPointLineSegmentState(line2Begin, [ line1Begin, line1End ]) !== OUTSIDE && getPointLineSegmentState(line2End, [ line1Begin, line1End ]) !== OUTSIDE ) { return INCLUDED; } else if (getPointLineSegmentState(line2Begin, [ line1Begin, line1End ]) === OUTSIDE && getPointLineSegmentState(line2End, [ line1Begin, line1End ]) === OUTSIDE ) { if ((line2Begin - line1Begin) * (line2End - line1Begin) > 0) { return UNINTERSECT; } else { return OVERLAP; } } else if (getPointLineSegmentState(line2Begin, [ line1Begin, line1End ]) === TANGENT || getPointLineSegmentState(line2End, [ line1Begin, line1End ]) === TANGENT ) { return TANGENT; } else { return OVERLAP; } } else { let intersect = getLineIntersect([ line1Begin, line1End ], [ line2Begin, line2End ]); let line1State = getPointLineSegmentState(intersect, [ line1Begin, line1End ]); let line2State = getPointLineSegmentState(intersect, [ line2Begin, line2End ]); if (line1State === OUTSIDE || line2State === OUTSIDE) return UNINTERSECT; if (line1State === TANGENT || line2State === TANGENT) return TANGENT; return INTERSECT; } }
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(smallX + Math.random() * (largeX - smallX)), beginY ]; if (beginX === endX) return [ beginX, roundToFiveSignificantDigits(smallY + Math.random() * (largeY - smallY)) ]; let slope = roundToFiveSignificantDigits((beginY - endY) / (beginX - endX)); let intercept = roundToFiveSignificantDigits((beginX * endY - endX * beginY) / (beginX - endX)); let randX = roundToFiveSignificantDigits(smallX + Math.random() * (largeX - smallX)); let randY = roundToFiveSignificantDigits(slope * randX + intercept); return [ randX, randY ]; }
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], linearRing1[i + 1] ]); // the two linearRings intersect with each other if (state === INTERSECT) { return INTERSECT; } if (state !== UNINTERSECT) { isLinearRingsTouching = true; } } } if (!isLinearRingsTouching) { let foundOutside = false, foundInside = false; for (let i = 0; i < linearRing2.length - 1; i++) { let state = pointLinearRingState(linearRing2[i], linearRing1); if (state === OUTSIDE) { foundOutside = true; } else if (state === INSIDE) { foundInside = true; } if (foundInside && foundOutside) break; } if (foundOutside && foundInside) { return INTERSECT; } else if (foundInside) { return INSIDE; } else { return OUTSIDE; } } else { let foundOutside = false, foundInside = false; for (let i = 0; i < linearRing2.length - 1; i++) { for (let j = 0; j < 250; j++) { let randPoint = getRandPointInLineSegment([ linearRing2[i], linearRing2[i + 1] ]); let state = pointLinearRingState(randPoint, linearRing1); if (state === OUTSIDE) { foundOutside = true; } else if (state === INSIDE) { foundInside = true; } if (foundInside && foundInside) break; } } // The two linear rings are identical if all points of three levels are on the edges of linearRing1. // We mark identical linear ring as INSIDE if (!foundOutside && !foundInside) return INSIDE; if (foundOutside && foundInside) return INTERSECT; if (foundInside) return INSIDE; return OUTSIDE; } }
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, rayOrigin), dRay) === 0) { // Lines are parallel and collinear // Find out if any part of the ray intersects with the line segment let t1 = vectorDot(vectorSubtract(lineEnd, rayOrigin), dRay) / vectorDot(dRay, dRay); if (t1 >= 0) { return OVERLAP; } else { return UNINTERSECT; } } else { // Lines are parallel and not collinear return UNINTERSECT; } } else { // Find solution to parametrized line intersect equations let tRay = vectorCross(vectorSubtract(lineBegin, rayOrigin), dLine) / vectorCross(dRay, dLine); let tLine = vectorCross(vectorSubtract(rayOrigin, lineBegin), dRay) / vectorCross(dLine, dRay); if (tRay > 0 && tLine > 0 && tLine < 1) { return INTERSECT; } else if (tRay > 0 && (tLine === 0 || tLine === 1)) { // Intersects at an endpoint of the line return TANGENT; } else { return UNINTERSECT; } } }
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 < linearRing.length - 1; i++) { if (isPointInLine(point, [ linearRing[i], linearRing[i + 1] ])) { if (getPointLineSegmentState(point, [ linearRing[i], linearRing[i + 1] ])) { return TANGENT; } } } let numIntersect = 0; let slope = 0; let determinedState = false; while (!determinedState) { let state; let intercept = roundToFiveSignificantDigits(point[1] - slope * point[0]); let point2 = [ roundToFiveSignificantDigits(point[0] + 1), roundToFiveSignificantDigits(slope * (point[0] + 1) + intercept) ]; for (let i = 0; i < linearRing.length - 1; i++) { state = getRayLineSegmentIntersectState([ point, point2 ], [ linearRing[i], linearRing[i + 1] ]); if (state === TANGENT || state === OVERLAP) { break; } else if (state === INTERSECT) { numIntersect++; } } if (state === INTERSECT || state === UNINTERSECT) { determinedState = true; } else { numIntersect = 0; slope += 0.01; } } return numIntersect % 2 === 1 ? INSIDE : OUTSIDE; }
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.length !== 2 || point.some((coord) => typeof coord !== 'number')) { throw new XError(XError.INVALID_ARGUMENT, 'invalid point in linear ring'); } let [ x, y ] = point; if (x < leftX) leftX = x; if (x > rightX) rightX = x; if (y < bottomY) bottomY = y; if (y > topY) topY = y; } return { topLeftVertex: [ leftX, topY ], width: rightX - leftX, height: topY - bottomY }; }
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 ]; let squareLinearRing = [ topLeftVertex, topRightVertex, bottomRightVertex, bottomLeftVertex, topLeftVertex ]; return getLinearRingsIntersectState(linearRing, squareLinearRing); }
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 modified the id if (this.attr('id') == 'id') { var url = '/user?id=' + encodeURIComponent(this.val()); // update the link in the header... $('#user-link') .text(this.val()) .attr('href', url); // ...and the url in the adress bar history.pushState(null, null, url); } } else { // Add a red X to the right var elem = this; elem.parent().next() .html('X') .css('color', 'red') .attr('title', data.message) .one('click', function() { // if the X is clicked, restore original data elem.val(elem.data('old-value')); $(this) .empty() .removeAttr('title'); }); } // reactivate the control this.prop('disabled', false); }
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 { log.logger.error('Mongo error: ' + util.inspect(err)); return cb(err); } }); connection.once('open', function callback() { if (firstCallback) { log.logger.debug('Mongoose connected.'); firstCallback = false; return cb(null,connection); } else { return cb(); } }); connection.on('disconnected', function() { log.logger.debug('Mongoose event - disconnect'); }); // Load schemas models.Mbaas = connection.model('Mbaas', require('./models/mbaas.js')); models.AppMbaas = connection.model('AppMbaas', require('./models/appMbaas.js')); models.Event = connection.model('Events', require('./models/events.js').EventSchema); models.Alert = connection.model('Alerts', require('./models/alerts.js').AlertSchema); models.Notification = connection.model("Notification",require('./models/notifications').NotificationSchema); models.Crash = connection.model("Crash",require('./models/crash').CrashSchema); }
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 currentTarget = targets.shift(); let c = childRegistry[currentTarget]; if (targets.length > 0) { if (c instanceof Array) { let n = c.length; for (let i = 0; i < n; i++) removeFromChildRegistry(getChildRegistry(c[i]), targets); } else { removeFromChildRegistry(getChildRegistry(c), targets); } } else { delete childRegistry[currentTarget]; } } else { for (let key in childRegistry) { let value = childRegistry[key]; if (value instanceof Array) { let n = value.length; let t = -1; for (let i = 0; i < n; i++) { let e = value[i]; if (e === child) { t = i; break; } } if (~t) value.splice(t, 1); if (value.length === 0) delete childRegistry[key]; } else { if (value === child) { delete childRegistry[key]; } else { removeFromChildRegistry(getChildRegistry(child), value); } } } } }
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]; gulpUtil.log( " in " + gulpUtil.colors.blue("line " + error.line + " @ char " + error.character) + ": " + error.reason + " (" + error.code + ")" ); if (typeof error.evidence === "string") { gulpUtil.log( " " + gulpUtil.colors.gray(error.evidence.replace(/^\s*|\s*$/, "")) ); } gulpUtil.log(""); } }
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 time a file has been modified while it is being watched totalIssues = 0; }
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; } else { indexWithOffset -= offsetCount; } } return { indexWithOffset, stringLength, }; }
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); if (deleted) { ++deletedCount; } next = iter.next(); } return deletedCount; }
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+' '+xhr.statusText+' <small>'+url+'</small></p>'); } else if(status == "success"){ cloak.message('loaded', url); // Respond back to server with 'loaded' message } }); }
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 ).serializeArray() ); data[$(this).attr('id')] = $( this ).serializeArray(); // Add each form's data to the data object. }); if(isEmpty(data)) cloak.message('next'); else cloak.message('next', data); }
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 (parsed === false || parsed.user !== publisher) { respond401(response) } else { checkPassword(publisher, parsed.password, function(error, valid) { if (error) { respond500(request, response, error) } else { if (valid) { handler.apply(this, handlerArguments) } else { respond401(response) } } }) } } else { respond401(response) } } }
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, resource, appName); return templateModel ? this.template(templateModel) : null; }
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 template _.each(resource.api, function (urlMappings, httpMethod) { _.each(urlMappings, function (methodName, url) { methods[methodName] = { httpMethod: httpMethod, url: url }; }); }); return { resourceName: resource.name, appName: this.getAppModuleName(prefix, appName), serviceName: this.pancakes.utils.getCamelCase(resource.name + '.service'), modelName: this.pancakes.utils.getPascalCase(resource.name), methods: JSON.stringify(methods) }; }
javascript
{ "resource": "" }