_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49300
train
function () { var position = this._getCaretRelativePosition(); var offset = this.$el.offset(); // Calculate the left top corner of `this.option.appendTo` element. var $parent = this.option.appendTo; if ($parent) { if (!($parent instanceof $)) { $parent = $($parent); } var parentOffset = $parent.offsetParent().offset(); offset.top -= parentOffset.top; offset.left -= parentOffset.left; } position.top += offset.top; position.left += offset.left; return position; }
javascript
{ "resource": "" }
q49301
train
function (text, skipUnchangedTerm) { if (!this.dropdown) { this.initialize(); } text != null || (text = this.adapter.getTextFromHeadToCaret()); var searchQuery = this._extractSearchQuery(text); if (searchQuery.length) { var term = searchQuery[1]; // Ignore shift-key, ctrl-key and so on. if (skipUnchangedTerm && this._term === term && term !== "") { return; } this._term = term; this._search.apply(this, searchQuery); } else { this._term = null; this.dropdown.deactivate(); } }
javascript
{ "resource": "" }
q49302
train
function (value, strategy, e) { this._term = null; this.adapter.select(value, strategy, e); this.fire('change').fire('textComplete:select', value, strategy); this.adapter.focus(); }
javascript
{ "resource": "" }
q49303
train
function (text) { for (var i = 0; i < this.strategies.length; i++) { var strategy = this.strategies[i]; var context = strategy.context(text); if (context || context === '') { var matchRegexp = $.isFunction(strategy.match) ? strategy.match(text) : strategy.match; if (isString(context)) { text = context; } var match = text.match(matchRegexp); if (match) { return [strategy, match[strategy.index], match]; } } } return [] }
javascript
{ "resource": "" }
q49304
splitArgsFromString
train
function splitArgsFromString(argsString) { let result = []; const quoteSeparatedArgs = argsString.split(/(\x22[^\x22]*\x22)/).filter(x => x); quoteSeparatedArgs.forEach(arg => { if (arg.match('\x22')) { result.push(arg.replace(/\x22/g, '')); } else { result = result.concat(arg.trim().split(' ')); } }); return result; }
javascript
{ "resource": "" }
q49305
_request
train
function _request(url, opt) { opt = opt || {}; opt.method = (opt.method || 'GET').toUpperCase(); opt.headers = opt.headers || {}; if (matchUrl(url) && matchMethod(opt.method)) { const result = extend(true, {}, mockResult); const response = { status: result.status, statusCode: result.status, headers: result.headers, size: result.responseSize, aborted: false, rt: 1, keepAliveSocket: result.keepAliveSocket || false, }; httpclient.emit('response', { error: null, ctx: opt.ctx, req: { url, options: opt, size: result.requestSize, }, res: response, }); if (opt.dataType === 'json') { try { result.data = JSON.parse(result.data); } catch (err) { err.name = 'JSONResponseFormatError'; throw err; } } else if (opt.dataType === 'text') { result.data = result.data.toString(); } return Promise.resolve(result); } return rawRequest.call(httpclient, url, opt); }
javascript
{ "resource": "" }
q49306
train
function(data) { const seq = data.model.get("seq"); const selection = this._getSelection(data.model); // get the status of the upper and lower row const getNextPrev= this._getPrevNextSelection(data.model); const mPrevSel = getNextPrev[0]; const mNextSel = getNextPrev[1]; const boxWidth = this.g.zoomer.get("columnWidth"); const boxHeight = this.g.zoomer.get("rowHeight"); // avoid unnecessary loops if (selection.length === 0) { return; } let hiddenOffset = 0; return (() => { const result = []; const end = seq.length - 1; for (let n = 0; n <= end; n++) { result.push((() => { if (data.hidden.indexOf(n) >= 0) { return hiddenOffset++; } else { const k = n - hiddenOffset; // only if its a new selection if (selection.indexOf(n) >= 0 && (k === 0 || selection.indexOf(n - 1) < 0 )) { return this._renderSelection({n:n, k:k, selection: selection, mPrevSel: mPrevSel, mNextSel:mNextSel, xZero: data.xZero, yZero: data.yZero, model: data.model}); } } })()); } return result; })(); }
javascript
{ "resource": "" }
q49307
train
function(data) { let xZero = data.xZero; const yZero = data.yZero; const n = data.n; const k = data.k; const selection = data.selection; // and checks the prev and next row for selection -> no borders in a selection const mPrevSel= data.mPrevSel; const mNextSel = data.mNextSel; // get the length of this selection let selectionLength = 0; const end = data.model.get("seq").length - 1; for (let i = n; i <= end; i++) { if (selection.indexOf(i) >= 0) { selectionLength++; } else { break; } } // TODO: ugly! const boxWidth = this.g.zoomer.get("columnWidth"); const boxHeight = this.g.zoomer.get("rowHeight"); const totalWidth = (boxWidth * selectionLength) + 1; const hidden = this.g.columns.get('hidden'); this.ctx.beginPath(); const beforeWidth = this.ctx.lineWidth; this.ctx.lineWidth = 3; const beforeStyle = this.ctx.strokeStyle; this.ctx.strokeStyle = "#FF0000"; xZero += k * boxWidth; // split up the selection into single cells let xPart = 0; const end1 = selectionLength - 1; for (let i = 0; i <= end1; i++) { let xPos = n + i; if (hidden.indexOf(xPos) >= 0) { continue; } // upper line if (!((typeof mPrevSel !== "undefined" && mPrevSel !== null) && mPrevSel.indexOf(xPos) >= 0)) { this.ctx.moveTo(xZero + xPart, yZero); this.ctx.lineTo(xPart + boxWidth + xZero, yZero); } // lower line if (!((typeof mNextSel !== "undefined" && mNextSel !== null) && mNextSel.indexOf(xPos) >= 0)) { this.ctx.moveTo(xPart + xZero, boxHeight + yZero); this.ctx.lineTo(xPart + boxWidth + xZero, boxHeight + yZero); } xPart += boxWidth; } // left this.ctx.moveTo(xZero,yZero); this.ctx.lineTo(xZero, boxHeight + yZero); // right this.ctx.moveTo(xZero + totalWidth,yZero); this.ctx.lineTo(xZero + totalWidth, boxHeight + yZero); this.ctx.stroke(); this.ctx.strokeStyle = beforeStyle; return this.ctx.lineWidth = beforeWidth; }
javascript
{ "resource": "" }
q49308
train
function(model) { var maxLen = model.getMaxLength(); if (maxLen < 200 && model.length < 30) { this.defaults.boxRectWidth = this.defaults.boxRectHeight = 5; } return this; }
javascript
{ "resource": "" }
q49309
train
function(max) { // TODO! // make seqlogo height configurable var val = this.getMaxAlignmentHeight(); if (max !== undefined && max > 0) { val = Math.min(val, max); } return this.set("alignmentHeight", val); }
javascript
{ "resource": "" }
q49310
main
train
async function main({ isFragment, needsHelp, showVersion, useTabs }) { /* eslint-disable no-console */ const stdin = await getStdin() if (showVersion) { return console.log(version) } if (needsHelp || !stdin) { return console.log(help) } const pug = html2pug(stdin, { isFragment, useTabs }) return console.log(pug) /* eslint-enable no-console */ }
javascript
{ "resource": "" }
q49311
laravelLocalizationLoader
train
function laravelLocalizationLoader(source) { var isPHP = ~source.indexOf('<?php') if (isPHP) { return phpArrayLoader(source) } else { return jsonLoader(source) } }
javascript
{ "resource": "" }
q49312
createTile
train
function createTile(coords, done) { let key = this._tileCoordsToKey(coords); // console.log('Need:', key); if ( key in this._freshTiles ) { let tile = this._freshTiles[ key ].pop(); if ( !this._freshTiles[ key ].length ) { delete this._freshTiles[ key ]; } L.Util.requestAnimFrame(done); // console.log('Got ', key, ' from _freshTiles'); return tile; } let tileContainer = L.DomUtil.create("div"); this._tileCallbacks[ key ] = this._tileCallbacks[ key ] || []; this._tileCallbacks[ key ].push( (function(c /* , k*/) { return function(imgNode) { let parent = imgNode.parentNode; if ( parent ) { parent.removeChild(imgNode); parent.removeChild = L.Util.falseFn; // imgNode.parentNode.replaceChild(L.DomUtil.create('img'), imgNode); } c.appendChild(imgNode); done(); // console.log('Sent ', k, ' to _tileCallbacks'); }; })(tileContainer /* , key*/) ); return tileContainer; }
javascript
{ "resource": "" }
q49313
createTile
train
function createTile(coords, done) { let key = this._tileCoordsToKey(coords); let tileContainer = L.DomUtil.create("div"); tileContainer.dataset.pending = this._imagesPerTile; for ( let i = 0; i < this._imagesPerTile; i++ ) { let key2 = key + "/" + i; if ( key2 in this._freshTiles ) { tileContainer.appendChild(this._freshTiles[ key2 ].pop()); if ( !this._freshTiles[ key2 ].length ) { delete this._freshTiles[ key2 ]; } tileContainer.dataset.pending--; // console.log('Got ', key2, ' from _freshTiles'); } else { this._tileCallbacks[ key2 ] = this._tileCallbacks[ key2 ] || []; this._tileCallbacks[ key2 ].push( (function(c /* , k2*/) { return function(imgNode) { let parent = imgNode.parentNode; if ( parent ) { parent.removeChild(imgNode); parent.removeChild = L.Util.falseFn; // imgNode.parentNode.replaceChild(L.DomUtil.create('img'), imgNode); } c.appendChild(imgNode); c.dataset.pending--; if ( !parseInt(c.dataset.pending) ) { done(); } // console.log('Sent ', k2, ' to _tileCallbacks, still ', c.dataset.pending, ' images to go'); }; })(tileContainer /* , key2*/) ); } } if ( !parseInt(tileContainer.dataset.pending) ) { L.Util.requestAnimFrame(done); } return tileContainer; }
javascript
{ "resource": "" }
q49314
performGssapiCanonicalizeHostName
train
function performGssapiCanonicalizeHostName(canonicalizeHostName, host, callback) { if (!canonicalizeHostName) return callback(); // Attempt to resolve the host name dns.resolveCname(host, (err, r) => { if (err) return callback(err); // Get the first resolve host id if (Array.isArray(r) && r.length > 0) { self.host = r[0]; } callback(); }); }
javascript
{ "resource": "" }
q49315
defineOperation
train
function defineOperation(fn, paramDefs) { return function() { const args = Array.prototype.slice.call(arguments); const params = []; for (let i = 0, argIdx = 0; i < paramDefs.length; ++i, ++argIdx) { const def = paramDefs[i]; let arg = args[argIdx]; if (def.hasOwnProperty('default') && arg == null) arg = def.default; if (def.type === 'object' && def.default != null) { arg = Object.assign({}, def.default, arg); } // special case to allow `options` to be optional if (def.name === 'options' && (typeof arg === 'function' || arg == null)) { arg = {}; } if (validateParameter(arg, paramDefs, i)) { params.push(arg); } else { argIdx--; } } const callback = arguments[arguments.length - 1]; if (typeof callback !== 'function') { return new Promise((resolve, reject) => { params.push((err, response) => { if (err) return reject(err); resolve(response); }); fn.apply(this, params); }); } fn.apply(this, params); }; }
javascript
{ "resource": "" }
q49316
decrypt
train
function decrypt(env, callback) { if (!env.AWS_DEFAULT_REGION) return callback(new Error('AWS_DEFAULT_REGION env var must be set')); var kms = new AWS.KMS({ region: env.AWS_DEFAULT_REGION, maxRetries: 10 }); var q = queue(); for (var key in env) { if (!(/^secure:/).test(env[key])) continue; q.defer(function(key, val, done) { kms.decrypt({ CiphertextBlob: new Buffer(val, 'base64') }, function(err, data) { if (err) return done(err); done(null, { key: key, val: val, decrypted: (new Buffer(data.Plaintext, 'base64')).toString('utf8') }); }); }, key, env[key].replace(/^secure:/,'')); } q.awaitAll(function(err, results) { if (err) return callback(err); callback(null, results); }); }
javascript
{ "resource": "" }
q49317
configurePackageDir
train
function configurePackageDir(pkgs, currentPackages, dir) { var i, location, pkgObj; for (i = 0; (pkgObj = currentPackages[i]); i++) { pkgObj = typeof pkgObj === "string" ? { name: pkgObj } : pkgObj; location = pkgObj.location; //Add dir to the path, but avoid paths that start with a slash //or have a colon (indicates a protocol) if (dir && (!location || (location.indexOf("/") !== 0 && location.indexOf(":") === -1))) { location = dir + "/" + (location || pkgObj.name); } //Create a brand new object on pkgs, since currentPackages can //be passed in again, and config.pkgs is the internal transformed //state for all package configs. pkgs[pkgObj.name] = { name: pkgObj.name, location: location || pkgObj.name, //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. main: (pkgObj.main || "main") .replace(currDirRegExp, '') .replace(jsSuffixRegExp, '') }; } }
javascript
{ "resource": "" }
q49318
isPriorityDone
train
function isPriorityDone() { var priorityDone = true, priorityWait = config.priorityWait, priorityName, i; if (priorityWait) { for (i = 0; (priorityName = priorityWait[i]); i++) { if (!loaded[priorityName]) { priorityDone = false; break; } } if (priorityDone) { delete config.priorityWait; } } return priorityDone; }
javascript
{ "resource": "" }
q49319
updateNormalizedNames
train
function updateNormalizedNames(pluginName) { var oldFullName, oldModuleMap, moduleMap, fullName, callbacks, i, j, k, depArray, existingCallbacks, maps = normalizedWaiting[pluginName]; if (maps) { for (i = 0; (oldModuleMap = maps[i]); i++) { oldFullName = oldModuleMap.fullName; moduleMap = makeModuleMap(oldModuleMap.originalName, oldModuleMap.parentMap); fullName = moduleMap.fullName; //Callbacks could be undefined if the same plugin!name was //required twice in a row, so use empty array in that case. callbacks = managerCallbacks[oldFullName] || []; existingCallbacks = managerCallbacks[fullName]; if (fullName !== oldFullName) { //Update the specified object, but only if it is already //in there. In sync environments, it may not be yet. if (oldFullName in specified) { delete specified[oldFullName]; specified[fullName] = true; } //Update managerCallbacks to use the correct normalized name. //If there are already callbacks for the normalized name, //just add to them. if (existingCallbacks) { managerCallbacks[fullName] = existingCallbacks.concat(callbacks); } else { managerCallbacks[fullName] = callbacks; } delete managerCallbacks[oldFullName]; //In each manager callback, update the normalized name in the depArray. for (j = 0; j < callbacks.length; j++) { depArray = callbacks[j].depArray; for (k = 0; k < depArray.length; k++) { if (depArray[k] === oldFullName) { depArray[k] = fullName; } } } } } } delete normalizedWaiting[pluginName]; }
javascript
{ "resource": "" }
q49320
FlatToNested
train
function FlatToNested(config) { this.config = config = config || {}; this.config.id = config.id || 'id'; this.config.parent = config.parent || 'parent'; this.config.children = config.children || 'children'; this.config.options = config.options || { deleteParent: true }; }
javascript
{ "resource": "" }
q49321
train
function (input) { if (typeof input === 'string') { return farmhash.Hash32String(input); } if (Buffer.isBuffer(input)) { return farmhash.Hash32Buffer(input); } throw new Error('Expected a String or Buffer for input'); }
javascript
{ "resource": "" }
q49322
train
function (input) { if (typeof input === 'string') { return farmhash.Fingerprint32String(input); } if (Buffer.isBuffer(input)) { return farmhash.Fingerprint32Buffer(input); } throw new Error('Expected a String or Buffer for input'); }
javascript
{ "resource": "" }
q49323
runSuite
train
function runSuite() { execFile(flow, [ 'status', '--color', 'always' ], (err, stdout) => { process.stdout.write('\x1Bc') /* eslint-disable no-console */ console.log(stdout) /* eslint-enable no-console */ }) }
javascript
{ "resource": "" }
q49324
create_gamma_table
train
function create_gamma_table(steps, gamma, warning) { // used to build a gamma table for a particular value if (! warning && gamma == GAMMA_DEFAULT && ! global.IS_TEST_MODE) { console.info("INFO: Default gamma behaviour is changing"); console.info("0.9 - gamma=1.0 - consistent with pre-gamma values"); console.info("0.10 - gamma=2.8 - default fix for WS2812 LEDs"); warning = true; } var g_table = new Array(steps); for (let i = 0; i < steps; i++) { g_table[i] = Math.floor(Math.pow((i / 255.0), gamma) * 255 + 0.5); } return g_table; }
javascript
{ "resource": "" }
q49325
colorWheel
train
function colorWheel( WheelPos ){ var r,g,b; WheelPos = 255 - WheelPos; if ( WheelPos < 85 ) { r = 255 - WheelPos * 3; g = 0; b = WheelPos * 3; } else if (WheelPos < 170) { WheelPos -= 85; r = 0; g = WheelPos * 3; b = 255 - WheelPos * 3; } else { WheelPos -= 170; r = WheelPos * 3; g = 255 - WheelPos * 3; b = 0; } // returns a string with the rgb value to be used as the parameter return "rgb(" + r +"," + g + "," + b + ")"; }
javascript
{ "resource": "" }
q49326
renameOrDelete
train
async function renameOrDelete(srcPath, targetPath) { if (srcPath === targetPath) { return; } const srcExists = await fs.exists(srcPath); if (!srcExists) { return; } const targetExists = await fs.exists(targetPath); // if target file exists, then throw // because the target file always be renamed first. if (targetExists) { const err = new Error(`targetFile ${targetPath} exists!!!`); throw err; } await fs.rename(srcPath, targetPath); }
javascript
{ "resource": "" }
q49327
train
function(a, b) { var z = new Complex(a, b); // Infinity + Infinity = NaN if (this['isInfinite']() && z['isInfinite']()) { return Complex['NAN']; } // Infinity + z = Infinity { where z != Infinity } if (this['isInfinite']() || z['isInfinite']()) { return Complex['INFINITY']; } return new Complex( this['re'] + z['re'], this['im'] + z['im']); }
javascript
{ "resource": "" }
q49328
train
function(a, b) { var z = new Complex(a, b); // Infinity * 0 = NaN if ((this['isInfinite']() && z['isZero']()) || (this['isZero']() && z['isInfinite']())) { return Complex['NAN']; } // Infinity * z = Infinity { where z != 0 } if (this['isInfinite']() || z['isInfinite']()) { return Complex['INFINITY']; } // Short circuit for real values if (z['im'] === 0 && this['im'] === 0) { return new Complex(this['re'] * z['re'], 0); } return new Complex( this['re'] * z['re'] - this['im'] * z['im'], this['re'] * z['im'] + this['im'] * z['re']); }
javascript
{ "resource": "" }
q49329
train
function(a, b) { var z = new Complex(a, b); // 0 / 0 = NaN and Infinity / Infinity = NaN if ((this['isZero']() && z['isZero']()) || (this['isInfinite']() && z['isInfinite']())) { return Complex['NAN']; } // Infinity / 0 = Infinity if (this['isInfinite']() || z['isZero']()) { return Complex['INFINITY']; } // 0 / Infinity = 0 if (this['isZero']() || z['isInfinite']()) { return Complex['ZERO']; } a = this['re']; b = this['im']; var c = z['re']; var d = z['im']; var t, x; if (0 === d) { // Divisor is real return new Complex(a / c, b / c); } if (Math.abs(c) < Math.abs(d)) { x = c / d; t = c * x + d; return new Complex( (a * x + b) / t, (b * x - a) / t); } else { x = d / c; t = d * x + c; return new Complex( (a + b * x) / t, (b - a * x) / t); } }
javascript
{ "resource": "" }
q49330
train
function(a, b) { var z = new Complex(a, b); a = this['re']; b = this['im']; if (z['isZero']()) { return Complex['ONE']; } // If the exponent is real if (z['im'] === 0) { if (b === 0 && a >= 0) { return new Complex(Math.pow(a, z['re']), 0); } else if (a === 0) { // If base is fully imaginary switch ((z['re'] % 4 + 4) % 4) { case 0: return new Complex(Math.pow(b, z['re']), 0); case 1: return new Complex(0, Math.pow(b, z['re'])); case 2: return new Complex(-Math.pow(b, z['re']), 0); case 3: return new Complex(0, -Math.pow(b, z['re'])); } } } /* I couldn't find a good formula, so here is a derivation and optimization * * z_1^z_2 = (a + bi)^(c + di) * = exp((c + di) * log(a + bi) * = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a)) * =>... * Re = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * cos(d * log(a^2 + b^2) / 2 + c * atan2(b, a)) * Im = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * sin(d * log(a^2 + b^2) / 2 + c * atan2(b, a)) * * =>... * Re = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * cos(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a)) * Im = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * sin(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a)) * * => * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1)) * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1)) * */ if (a === 0 && b === 0 && z['re'] > 0 && z['im'] >= 0) { return Complex['ZERO']; } var arg = Math.atan2(b, a); var loh = logHypot(a, b); a = Math.exp(z['re'] * loh - z['im'] * arg); b = z['im'] * loh + z['re'] * arg; return new Complex( a * Math.cos(b), a * Math.sin(b)); }
javascript
{ "resource": "" }
q49331
train
function() { var a = this['re']; var b = this['im']; var r = this['abs'](); var re, im; if (a >= 0) { if (b === 0) { return new Complex(Math.sqrt(a), 0); } re = 0.5 * Math.sqrt(2.0 * (r + a)); } else { re = Math.abs(b) / Math.sqrt(2 * (r - a)); } if (a <= 0) { im = 0.5 * Math.sqrt(2.0 * (r - a)); } else { im = Math.abs(b) / Math.sqrt(2 * (r + a)); } return new Complex(re, b < 0 ? -im : im); }
javascript
{ "resource": "" }
q49332
train
function() { var tmp = Math.exp(this['re']); if (this['im'] === 0) { //return new Complex(tmp, 0); } return new Complex( tmp * Math.cos(this['im']), tmp * Math.sin(this['im'])); }
javascript
{ "resource": "" }
q49333
train
function() { /** * exp(a + i*b) - 1 = exp(a) * (cos(b) + j*sin(b)) - 1 = expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b) */ var a = this['re']; var b = this['im']; return new Complex( Math.expm1(a) * Math.cos(b) + cosm1(b), Math.exp(a) * Math.sin(b)); }
javascript
{ "resource": "" }
q49334
train
function() { var a = this['re']; var b = this['im']; if (b === 0 && a > 0) { //return new Complex(Math.log(a), 0); } return new Complex( logHypot(a, b), Math.atan2(b, a)); }
javascript
{ "resource": "" }
q49335
train
function() { // sin(c) = (e^b - e^(-b)) / (2i) var a = this['re']; var b = this['im']; return new Complex( Math.sin(a) * cosh(b), Math.cos(a) * sinh(b)); }
javascript
{ "resource": "" }
q49336
train
function() { // asin(c) = -i * log(ci + sqrt(1 - c^2)) var a = this['re']; var b = this['im']; var t1 = new Complex( b * b - a * a + 1, -2 * a * b)['sqrt'](); var t2 = new Complex( t1['re'] - b, t1['im'] + a)['log'](); return new Complex(t2['im'], -t2['re']); }
javascript
{ "resource": "" }
q49337
train
function() { // acos(c) = i * log(c - i * sqrt(1 - c^2)) var a = this['re']; var b = this['im']; var t1 = new Complex( b * b - a * a + 1, -2 * a * b)['sqrt'](); var t2 = new Complex( t1['re'] - b, t1['im'] + a)['log'](); return new Complex(Math.PI / 2 - t2['im'], t2['re']); }
javascript
{ "resource": "" }
q49338
train
function() { // atan(c) = i / 2 log((i + x) / (i - x)) var a = this['re']; var b = this['im']; if (a === 0) { if (b === 1) { return new Complex(0, Infinity); } if (b === -1) { return new Complex(0, -Infinity); } } var d = a * a + (1.0 - b) * (1.0 - b); var t1 = new Complex( (1 - b * b - a * a) / d, -2 * a / d).log(); return new Complex(-0.5 * t1['im'], 0.5 * t1['re']); }
javascript
{ "resource": "" }
q49339
train
function() { // acot(c) = i / 2 log((c - i) / (c + i)) var a = this['re']; var b = this['im']; if (b === 0) { return new Complex(Math.atan2(1, a), 0); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).atan() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ? -b / 0 : 0).atan(); }
javascript
{ "resource": "" }
q49340
train
function() { // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2)) var a = this['re']; var b = this['im']; if (a === 0 && b === 0) { return new Complex(0, Infinity); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).acos() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ? -b / 0 : 0).acos(); }
javascript
{ "resource": "" }
q49341
train
function() { // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2)) var a = this['re']; var b = this['im']; if (a === 0 && b === 0) { return new Complex(Math.PI / 2, Infinity); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).asin() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ? -b / 0 : 0).asin(); }
javascript
{ "resource": "" }
q49342
train
function() { // atanh(c) = log((1+c) / (1-c)) / 2 var a = this['re']; var b = this['im']; var noIM = a > 1 && b === 0; var oneMinus = 1 - a; var onePlus = 1 + a; var d = oneMinus * oneMinus + b * b; var x = (d !== 0) ? new Complex( (onePlus * oneMinus - b * b) / d, (b * oneMinus + onePlus * b) / d) : new Complex( (a !== -1) ? (a / 0) : 0, (b !== 0) ? (b / 0) : 0); var temp = x['re']; x['re'] = logHypot(x['re'], x['im']) / 2; x['im'] = Math.atan2(x['im'], temp) / 2; if (noIM) { x['im'] = -x['im']; } return x; }
javascript
{ "resource": "" }
q49343
train
function() { // acoth(c) = log((c+1) / (c-1)) / 2 var a = this['re']; var b = this['im']; if (a === 0 && b === 0) { return new Complex(0, Math.PI / 2); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).atanh() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ? -b / 0 : 0).atanh(); }
javascript
{ "resource": "" }
q49344
train
function() { // acsch(c) = log((1+sqrt(1+c^2))/c) var a = this['re']; var b = this['im']; if (b === 0) { return new Complex( (a !== 0) ? Math.log(a + Math.sqrt(a * a + 1)) : Infinity, 0); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).asinh() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ? -b / 0 : 0).asinh(); }
javascript
{ "resource": "" }
q49345
train
function() { // asech(c) = log((1+sqrt(1-c^2))/c) var a = this['re']; var b = this['im']; if (this['isZero']()) { return Complex['INFINITY']; } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).acosh() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ? -b / 0 : 0).acosh(); }
javascript
{ "resource": "" }
q49346
train
function(places) { places = Math.pow(10, places || 0); return new Complex( Math.floor(this['re'] * places) / places, Math.floor(this['im'] * places) / places); }
javascript
{ "resource": "" }
q49347
train
function(a, b) { var z = new Complex(a, b); return Math.abs(z['re'] - this['re']) <= Complex['EPSILON'] && Math.abs(z['im'] - this['im']) <= Complex['EPSILON']; }
javascript
{ "resource": "" }
q49348
train
function() { var a = this['re']; var b = this['im']; var ret = ''; if (this['isNaN']()) { return 'NaN'; } if (this['isZero']()) { return '0'; } if (this['isInfinite']()) { return 'Infinity'; } if (a !== 0) { ret += a; } if (b !== 0) { if (a !== 0) { ret += b < 0 ? ' - ' : ' + '; } else if (b < 0) { ret += '-'; } b = Math.abs(b); if (1 !== b) { ret += b; } ret += 'i'; } if (!ret) return '0'; return ret; }
javascript
{ "resource": "" }
q49349
Accepts
train
function Accepts (req) { if (!(this instanceof Accepts)) { return new Accepts(req) } this.headers = req.headers this.negotiator = new Negotiator(req) }
javascript
{ "resource": "" }
q49350
someAsyncFunction
train
function someAsyncFunction(file, callback) { // Here we just wrap the function body to make it synchronous inside // Sync will execute first argument 'fn' in synchronous way // and call second argument 'callback' when function returns // it also calls callback if exception will be thrown inside of 'fn' Sync(function(){ var source = require('fs').readFile.sync(null, __filename); return source; }, callback) }
javascript
{ "resource": "" }
q49351
asyncFunction
train
function asyncFunction(a, b, callback) { process.nextTick(function(){ callback(null, a + b); }) }
javascript
{ "resource": "" }
q49352
train
function (callbackError, callbackResult, otherArgs) { // forbid to call twice if (syncCallback.called) return; syncCallback.called = true; if (callbackError) { err = callbackError; } else if (otherArgs) { // Support multiple callback result values result = []; for (var i = 1, l = arguments.length; i < l; i++) { result.push(arguments[i]); } } else { result = callbackResult; } // Resume fiber if yielding if (yielded) fiber.run(); }
javascript
{ "resource": "" }
q49353
SyncFuture
train
function SyncFuture(timeout) { var self = this; this.resolved = false; this.fiber = Fiber.current; this.yielding = false; this.timeout = timeout; this.time = null; this._timeoutId = null; this._result = undefined; this._error = null; this._start = +new Date; Sync.stat.totalFutures++; Sync.stat.activeFutures++; // Create timeout error to capture stack trace correctly self.timeoutError = new Error(); Error.captureStackTrace(self.timeoutError, arguments.callee); this.ticket = function Future() { // clear timeout if present if (self._timeoutId) clearTimeout(self._timeoutId); // measure time self.time = new Date - self._start; // forbid to call twice if (self.resolved) return; self.resolved = true; // err returned as first argument var err = arguments[0]; if (err) { self._error = err; } else { self._result = arguments[1]; } // remove self from current fiber self.fiber.removeFuture(self.ticket); Sync.stat.activeFutures--; if (self.yielding && Fiber.current !== self.fiber) { self.yielding = false; self.fiber.run(); } else if (self._error) { throw self._error; } } this.ticket.__proto__ = this; this.ticket.yield = function() { while (!self.resolved) { self.yielding = true; if (self.timeout) { self._timeoutId = setTimeout(function(){ self.timeoutError.message = 'Future function timed out at ' + self.timeout + ' ms'; self.ticket(self.timeoutError); }, self.timeout) } Fiber.yield(); } if (self._error) throw self._error; return self._result; } this.ticket.__defineGetter__('result', function(){ return this.yield(); }); this.ticket.__defineGetter__('error', function(){ if (self._error) { return self._error; } try { this.result; } catch (e) { return e; } return null; }); this.ticket.__defineGetter__('timeout', function(){ return self.timeout; }); this.ticket.__defineSetter__('timeout', function(value){ self.timeout = value; }); // append self to current fiber this.fiber.addFuture(this.ticket); return this.ticket; }
javascript
{ "resource": "" }
q49354
smix
train
function smix (B, Bi, r, N, V, XY) { var Xi = 0 var Yi = 128 * r var i B.copy(XY, Xi, Bi, Bi + Yi) for (i = 0; i < N; i++) { XY.copy(V, i * Yi, Xi, Xi + Yi) blockmix_salsa8(XY, Xi, Yi, r) if (tickCallback) tickCallback() } for (i = 0; i < N; i++) { var offset = Xi + (2 * r - 1) * 64 var j = XY.readUInt32LE(offset) & (N - 1) blockxor(V, j * Yi, XY, Xi, Yi) blockmix_salsa8(XY, Xi, Yi, r) if (tickCallback) tickCallback() } XY.copy(B, Bi, Xi, Xi + Yi) }
javascript
{ "resource": "" }
q49355
_arrayProperties
train
function _arrayProperties (arr, mask) { var obj = _properties({_: arr}, {_: { type: 'array', properties: mask }}) return obj && obj._ }
javascript
{ "resource": "" }
q49356
padEnd
train
function padEnd (string, targetLength) { if (typeof string !== 'string' || typeof targetLength !== 'number') { return string } /* istanbul ignore next */ const fn = typeof String.prototype.padEnd === 'function' ? String.prototype.padEnd : polyfill return fn.call(string, targetLength) }
javascript
{ "resource": "" }
q49357
install
train
function install (presetName) { debug('run install from scripts, arguments: %o', arguments) const name = presetName || tryRequire(/elint-preset-/)[0] if (!name) { debug('can not fount preset, return') return } const nodeModulesDir = getNodeModulesDir() const keep = process.env.npm_config_keep || '' const presetModulePath = path.join(nodeModulesDir, name) link(presetModulePath, keep) }
javascript
{ "resource": "" }
q49358
reverse
train
function reverse(patch, previous, idx) { const op = patch.op; const path = patch.path; if (op === "copy" || (op === "add" && previous === undefined)) { if (idx === undefined) return { op: "remove", path: path }; // for item pushed to array with - const tokens = decode(path); tokens[tokens.length - 1] = idx.toString(); return { op: "remove", path: encode(tokens) }; } if (op === "replace") return { op: "replace", path: path, value: previous }; if (op === "move") return { op: "move", path: patch.from, from: path }; if (op === "add" || op === "remove") return { op: "add", path: path, value: previous }; if (op === "test") return { op: "test", path: path, value: patch.value }; }
javascript
{ "resource": "" }
q49359
apply
train
function apply(doc, patch, options) { if (!Array.isArray(patch)) throw new Error("Invalid argument, patch must be an array"); const done = []; for (let i = 0, len = patch.length; i < len; i++) { const p = patch[i]; let r; try { r = run(doc, p); } catch (err) { // restore document // does not use ./revert.js because it is a circular dependency const revertPatch = buildRevertPatch(done); apply(doc, revertPatch); throw err; } doc = r.doc; done.push([p, r.previous, r.idx]); } const result = { doc: doc }; if (options && typeof options === "object" && options.reversible === true) result.revert = done; return result; }
javascript
{ "resource": "" }
q49360
Blob
train
function Blob(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49361
BlobHeader
train
function BlobHeader(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49362
HeaderBlock
train
function HeaderBlock(properties) { this.requiredFeatures = []; this.optionalFeatures = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49363
HeaderBBox
train
function HeaderBBox(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49364
PrimitiveBlock
train
function PrimitiveBlock(properties) { this.primitivegroup = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49365
PrimitiveGroup
train
function PrimitiveGroup(properties) { this.nodes = []; this.ways = []; this.relations = []; this.changesets = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49366
DenseInfo
train
function DenseInfo(properties) { this.version = []; this.timestamp = []; this.changeset = []; this.uid = []; this.userSid = []; this.visible = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49367
ChangeSet
train
function ChangeSet(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49368
Node
train
function Node(properties) { this.keys = []; this.vals = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49369
DenseNodes
train
function DenseNodes(properties) { this.id = []; this.lat = []; this.lon = []; this.keysVals = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49370
Way
train
function Way(properties) { this.keys = []; this.vals = []; this.refs = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49371
Relation
train
function Relation(properties) { this.keys = []; this.vals = []; this.rolesSid = []; this.memids = []; this.types = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q49372
inquire
train
function inquire(moduleName) { try { var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval if (mod && (mod.length || Object.keys(mod).length)) return mod; } catch (e) {} // eslint-disable-line no-empty return null; }
javascript
{ "resource": "" }
q49373
merge
train
function merge(dst, src, ifNotSet) { // used by converters for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) if (dst[keys[i]] === undefined || !ifNotSet) dst[keys[i]] = src[keys[i]]; return dst; }
javascript
{ "resource": "" }
q49374
toProtoBuf
train
function toProtoBuf (node) { const pbn = {} if (node.data && node.data.length > 0) { pbn.Data = node.data } else { pbn.Data = null // new Buffer(0) } if (node.links.length > 0) { pbn.Links = node.links.map((link) => { return { Hash: link.hash, Name: link.name, Tsize: link.size } }) } else { pbn.Links = null } return pbn }
javascript
{ "resource": "" }
q49375
bindIndicators
train
function bindIndicators(indicator) { // Parent process will send three type of data const collectorHandler = { 'process': function (value) { indicator.rss = value.rss; indicator.heapTotal = value.heapTotal; indicator.heapUsed = value.heapUsed; }, 'os': function (value) { indicator.totalMem = value.totalMem; indicator.freeMem = value.freeMem; indicator.cpus = value.cpus; }, 'v8': function (value) { indicator.newSpace = value.heapSpace[0]; indicator.oldSpace = value.heapSpace[1]; indicator.codeSpace = value.heapSpace[2]; indicator.mapSpace = value.heapSpace[3]; indicator.largeObjectSpace = value.heapSpace[4]; } } process.on('message', (msg) => { if (Array.isArray(msg)) { msg.forEach((data) => { let handler = collectorHandler[data.type]; if (typeof handler === 'function') collectorHandler[data.type](data.value); }); } }); }
javascript
{ "resource": "" }
q49376
bindSocket
train
function bindSocket(io, indicator) { Object.keys(indicator.watch).forEach((key) => { let eventName = indicator.watch[key]; indicator.on(eventName, (msg) => io.emit(eventName, msg)); }); }
javascript
{ "resource": "" }
q49377
train
function(opacity) { return function(g, i) { gEnter.selectAll(".chord") .filter(function(d) { return d.source.index != i && d.target.index != i; }) .transition() .style("opacity", opacity); var groups = []; gEnter.selectAll(".chord") .filter(function(d) { if (d.source.index == i) { groups.push(d.target.index); } if (d.target.index == i) { groups.push(d.source.index); } }); groups.push(i); var length = groups.length; gEnter.selectAll('.group') .filter(function(d) { for (var i = 0; i < length; i++) { if(groups[i] == d.index) return false; } return true; }) .transition() .style("opacity", opacity); }; }
javascript
{ "resource": "" }
q49378
Wayfarer
train
function Wayfarer (dft) { if (!(this instanceof Wayfarer)) return new Wayfarer(dft) var _default = (dft || '').replace(/^\//, '') var _trie = trie() emit._trie = _trie emit.on = on emit.emit = emit emit.match = match emit._wayfarer = true return emit // define a route // (str, fn) -> obj function on (route, fn) { assert.equal(typeof route, 'string') assert.equal(typeof fn, 'function') var cb = fn._wayfarer && fn._trie ? fn : proxy route = route || '/' cb.route = route if (cb._wayfarer && cb._trie) { _trie.mount(route, cb._trie.trie) } else { var node = _trie.create(route) node.cb = cb } return emit function proxy () { return fn.apply(this, Array.prototype.slice.call(arguments)) } } // match and call a route // (str, obj?) -> null function emit (route) { var matched = match(route) var args = new Array(arguments.length) args[0] = matched.params for (var i = 1; i < args.length; i++) { args[i] = arguments[i] } return matched.cb.apply(matched.cb, args) } function match (route) { assert.notEqual(route, undefined, "'route' must be defined") var matched = _trie.match(route) if (matched && matched.cb) return new Route(matched) var dft = _trie.match(_default) if (dft && dft.cb) return new Route(dft) throw new Error("route '" + route + "' did not match") } function Route (matched) { this.cb = matched.cb this.route = matched.cb.route this.params = matched.params } }
javascript
{ "resource": "" }
q49379
bumpVersion
train
function bumpVersion(files, bumpType) { status('Bump', bumpType, 'version to files:', files.join(' ')); if (config.dryRun) return '[not available in dry run]'; var newVersion; var originalVersion; files.forEach(function(fileName) { var filePath = path.join(projectRoot, fileName); var data = JSON.parse(fs.readFileSync(filePath)); originalVersion = data.version; var currentVersion = data.version; if (!semver.valid(currentVersion)) { var msg = 'Invalid version ' + currentVersion + ' in file ' + fileName;; var err = new Error(msg); throw err; } if (S(currentVersion).endsWith(config.devSuffix)) { currentVersion = S(currentVersion).chompRight(config.devSuffix).s; } if (bumpType === 'dev') { newVersion = currentVersion + config.devSuffix; } else { newVersion = semver.inc(currentVersion, bumpType); } data.version = newVersion; var content = JSON.stringify(data, null, config.indentation); fs.writeFileSync(filePath, content); status('Bump', originalVersion, '->', newVersion, 'in', fileName); }); return newVersion; }
javascript
{ "resource": "" }
q49380
askForTableName
train
function askForTableName() { if (this.force) { return; } const validateTableName = dbh.validateTableName; const done = this.async(); this.prompt([ { type: 'input', name: 'dbhTableName', validate: ((input) => { const prodDatabaseType = this.jhipsterAppConfig.prodDatabaseType; return validateTableName(input, prodDatabaseType); }), message: 'What is the table name for this entity ?', default: this.entityTableName } ]).then((props) => { this.tableNameInput = props.dbhTableName; done(); }); }
javascript
{ "resource": "" }
q49381
askForColumnsName
train
function askForColumnsName() { // Don't ask columns name if there aren't any field // Or option --force if (this.fields === undefined || this.fields.length === 0 || this.force) { return; } this.log(chalk.green(`Asking column names for ${this.fields.length} field(s)`)); const done = this.async(); // work on a copy this.fieldsPile = this.fields.slice(); // feed the first item for the first question this.field = this.fieldsPile.shift(); askForColumnName.call(this, done); }
javascript
{ "resource": "" }
q49382
askForRelationshipsId
train
function askForRelationshipsId() { // Don't ask relationship id if there aren't any relationship // Or option --force if (this.relationships === undefined || this.relationships.length === 0 || this.force) { return; } // work only on owner relationship this.relationshipsPile = this.relationships.filter(relationshipItem => // We don't need to do anything about relationships which don't add any constraint. !(relationshipItem.relationshipType === 'one-to-many' || (relationshipItem.relationshipType === 'one-to-one' && !relationshipItem.ownerSide) || (relationshipItem.relationshipType === 'many-to-many' && !relationshipItem.ownerSide))); if (this.relationshipsPile.length === 0) { return; } this.log(chalk.green(`Asking column names for ${this.relationshipsPile.length} relationship(s)`)); const done = this.async(); this.relationship = this.relationshipsPile.shift(); askForRelationshipId.call(this, done); }
javascript
{ "resource": "" }
q49383
loadTranslation
train
function loadTranslation(localeFilePath) { if(typeof localeFilePath == "undefined"){ messages = defaultMessages; return null; } let fp = path.join(__dirname, localeFilePath); messages = require('jsonfile').readFileSync("." + fp); return messages; }
javascript
{ "resource": "" }
q49384
shallowWithIntl
train
function shallowWithIntl(node, options = { context: {}}) { const intlProvider = new IntlProvider({locale: locale, messages }, {}); const { intl } = intlProvider.getChildContext(); return shallow(React.cloneElement(node, { intl }), { ...options, context: { ...options.context, intl } }); }
javascript
{ "resource": "" }
q49385
mountWithIntl
train
function mountWithIntl (node, { context, childContextTypes } = {}) { const intlProvider = new IntlProvider({locale: locale, messages }, {}); const { intl } = intlProvider.getChildContext(); return mount(React.cloneElement(node, { intl }), { context: Object.assign({}, context, {intl}), childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes) }); }
javascript
{ "resource": "" }
q49386
renderWithIntl
train
function renderWithIntl (node, { context, childContextTypes } = {}) { const intlProvider = new IntlProvider({locale: locale, messages }, {}); const { intl } = intlProvider.getChildContext(); return render(React.cloneElement(node, { intl }), { context: Object.assign({}, context, {intl}), childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes) }); }
javascript
{ "resource": "" }
q49387
getMarker
train
function getMarker(options, callback) { // prevent .parsedTint from being attached to options options = xtend({}, options); if (options.tint) { // Expand hex shorthand (3 chars) to 6, e.g. 333 => 333333. // This is not done upstream in `node-tint` as some such // shorthand cannot be disambiguated from other tintspec strings, // e.g. 123 (rgb shorthand) vs. 123 (hue). if (options.tint.length === 3) { options.tint = options.tint[0] + options.tint[0] + options.tint[1] + options.tint[1] + options.tint[2] + options.tint[2]; } options.parsedTint = blend.parseTintString(options.tint); } if (!options.symbol || (options.symbol && options.symbol.length === 1) || (options.symbol.length === 2 && !isNaN(parseInt(options.symbol)))) { loadCached(options, callback); } else { loadMaki(options, callback); } }
javascript
{ "resource": "" }
q49388
loadMaki
train
function loadMaki(options, callback) { var base = options.base + '-' + options.size + (options.retina ? '@2x' : ''), size = options.size, symbol = options.symbol + '-' + sizes[size] + (options.retina ? '@2x' : ''); if (!base || !size) { return callback(errcode('Marker is invalid because it lacks base or size.', 'EINVALID')); } if (!makiAvailable[symbol]) { return callback(errcode('Marker symbol "' + options.symbol + '" is invalid.', 'EINVALID')); } fs.readFile(makiRenders + symbol + '.png', function(err, data) { if (err) return callback(new Error('Marker "' + JSON.stringify(options) + '" is invalid because the symbol is not found.')); // Base marker gets tint applied. var parts = [{ buffer: markerCache.base[base], tint: options.parsedTint }]; // If symbol is present, find correct offset (varies by marker size). if (symbol) { parts.push(xtend({ buffer: data, tint: blend.parseTintString('0x0;0x0;1.4x0'), }, offsets[size + (options.retina ? '@2x' : '')])); } // Add mask layer. parts.push({ buffer: markerCache.mask[base] }); // Extract width and height from the IHDR. The IHDR chunk must appear // first, so the location is always fixed. var width = markerCache.base[base].readUInt32BE(16), height = markerCache.base[base].readUInt32BE(20); // Combine base, (optional) symbol, to supply the final marker. blend(parts, { format: 'png', quality: 256, width: width, height: height }, function(err, data) { if (err) return callback(err); return callback(null, data); }); }); }
javascript
{ "resource": "" }
q49389
argsToArray
train
function argsToArray(args) { if (_.isArray(args[0])) return args[0]; else if (typeof args[0] == 'string' && args[0].indexOf(',') > -1) return _.invoke(args[0].split(','), 'trim'); else return _.toArray(args); }
javascript
{ "resource": "" }
q49390
formatString
train
function formatString(string, params) { return string.replace(/{(\d+)}/g, function (match, number) { return typeof params[number] !== undefined ? params[number] : match; }); }
javascript
{ "resource": "" }
q49391
tableHead
train
function tableHead () { var args = arrayify(arguments) var data = args.shift() if (!data) return args.pop() var cols = args var colHeaders = cols.map(function (col) { var spl = col.split('|') return spl[1] || spl[0] }) cols = cols.map(function (col) { return col.split('|')[0] }) var toSplice = [] cols = cols.filter(function (col, index) { var hasValue = data.some(function (row) { return typeof row[col] !== 'undefined' }) if (!hasValue) toSplice.push(index) return hasValue }) toSplice.reverse().forEach(function (index) { colHeaders.splice(index, 1) }) var table = '| ' + colHeaders.join(' | ') + ' |\n' table += cols.reduce(function (p) { return p + ' --- |' }, '|') + '\n' return table }
javascript
{ "resource": "" }
q49392
tableRow
train
function tableRow () { var args = arrayify(arguments) var rows = args.shift() if (!rows) return var options = args.pop() var cols = args var output = '' if (options.data) { var data = handlebars.createFrame(options.data) cols.forEach(function (col, index) { var colNumber = index + 1 data['col' + colNumber] = containsData(rows, col) }) } rows.forEach(function (row) { output += options.fn(row, { data: data }) }) return output }
javascript
{ "resource": "" }
q49393
_groupBy
train
function _groupBy (identifiers, groupByFields) { /* don't modify the input array */ groupByFields = groupByFields.slice(0) groupByFields.forEach(function (group) { var groupValues = identifiers .filter(function (identifier) { /* exclude constructors from grouping.. re-implement to work off a `null` group value */ return identifier.kind !== 'constructor' }) .map(function (i) { return i[group] }) .reduce(unique, []) if (groupValues.length <= 1) groupByFields = groupByFields.reduce(without(group), []) }) identifiers = _addGroup(identifiers, groupByFields) var inserts = [] var prevGroup = [] var level = 0 identifiers.forEach(function (identifier, index) { if (!deepEqual(identifier._group, prevGroup)) { var common = commonSequence(identifier._group, prevGroup) level = common.length identifier._group.forEach(function (group, i) { if (group !== common[i] && group !== null) { inserts.push({ index: index, _title: group, level: level++ }) } }) } identifier.level = level prevGroup = identifier._group delete identifier._group }) /* insert title items */ inserts.reverse().forEach(function (insert) { identifiers.splice(insert.index, 0, { _title: insert._title, level: insert.level }) }) return identifiers }
javascript
{ "resource": "" }
q49394
kindInThisContext
train
function kindInThisContext (options) { if (this.kind === 'function' && this.memberof) { return 'method' } else if (this.kind === 'member' && !this.isEnum && this.memberof) { return 'property' } else if (this.kind === 'member' && this.isEnum && this.memberof) { return 'enum property' } else if (this.kind === 'member' && this.isEnum && !this.memberof) { return 'enum' } else if (this.kind === 'member' && this.scope === 'global') { return 'variable' } else { return this.kind } }
javascript
{ "resource": "" }
q49395
params
train
function params (options) { if (this.params) { var list = this.params.map(function (param) { var nameSplit = param.name.split('.') var name = nameSplit[nameSplit.length - 1] if (nameSplit.length > 1) name = '.' + name if (param.variable) name = '...' + name if (param.optional) name = '[' + name + ']' return { indent: ' '.repeat(nameSplit.length - 1), name: name, type: param.type, defaultvalue: param.defaultvalue, description: param.description } }) return options.fn(list) } }
javascript
{ "resource": "" }
q49396
identifier
train
function identifier (options) { var result = ddata._identifier(options) return result ? options.fn(result) : 'ERROR, Cannot find identifier.' }
javascript
{ "resource": "" }
q49397
class_
train
function class_ (options) { options.hash.kind = 'class' var result = ddata._identifier(options) return result ? options.fn(result) : 'ERROR, Cannot find class.' }
javascript
{ "resource": "" }
q49398
dmd
train
function dmd (templateData, options) { options = new DmdOptions(options) if (skipCache(options)) { return generate(templateData, options) } else { const cached = dmd.cache.readSync([ templateData, options, dmdVersion ]) if (cached) { return cached } else { return generate(templateData, options) } } }
javascript
{ "resource": "" }
q49399
_globals
train
function _globals (options) { options.hash.scope = 'global' return _identifiers(options).filter(function (identifier) { if (identifier.kind === 'external') { return identifier.description && identifier.description.length > 0 } else { return true } }) }
javascript
{ "resource": "" }