_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q33900
TimeWindow
train
function TimeWindow(connection, locationId, twId) { this.connection = connection; this.locationId = locationId; this.twId = twId; }
javascript
{ "resource": "" }
q33901
ascli
train
function ascli(title, appendix) { title = title || ascli.appName; appendix = appendix || ""; var lines = ["", "", ""], c, a, j, ac = ""; for (var i=0; i<title.length; i++) { c = title.charAt(i); if (c == '\x1B') { while ((c=title.charAt(i)) != 'm') { ac += c; i++; } ac += c; } else if ((a=alphabet[c])||(a=alphabet[c.toLowerCase()])) for (j=0; j<3; j++) lines[j] += ac+a[j]; } for (i=0; i<lines.length; i++) lines[i] = lines[i]+"\x1B[0m"; lines[1] += " "+appendix; if (lines[lines.length-1].strip.trim().length == 0) { lines.pop(); } return '\n'+lines.join('\n')+'\n'; }
javascript
{ "resource": "" }
q33902
train
function(config) { // get the options for the right server setup var out = {}, serverMode = (process.env.NODE_ENV) ? process.env.NODE_ENV : 'development'; // loop object properties and add them to root of out object for (var key in config.environments[serverMode]) { if (config.environments[serverMode].hasOwnProperty(key)) { out[key] = config.environments[serverMode][key]; } } if (process.env.HOST) { out.server.host = process.env.HOST; } if (process.env.PORT) { out.server.port = parseInt(process.env.PORT, 10); } // add modulus information if (process.env.SERVO_ID && process.env.CLOUD_DIR) { this.host = this.host ? this.host : {}; this.host.clouddir = process.env.CLOUD_DIR; this.host.servoid = process.env.SERVO_ID; } return out; }
javascript
{ "resource": "" }
q33903
train
function(path, callback) { fs.readFile(path, 'utf8', function(err, data) { if (!err) { marked.setOptions({ gfm: true, tables: true, breaks: false, pedantic: false, sanitize: true, smartLists: true, smartypants: false, langPrefix: 'language-', highlight: function(code, lang) { return code; } }); data = marked(data); } callback(err, data); }); }
javascript
{ "resource": "" }
q33904
train
function(code, err, message) { code = (code || isNaN(code)) ? code : 500; err = (err) ? err : ''; message = (message) ? message : ''; return { 'code': code, 'error': err, 'message': message }; }
javascript
{ "resource": "" }
q33905
checkEnv
train
function checkEnv() { async.series([ function(cb) { childProcess.exec( 'python -c "import django; print(django.get_version())"', function(err, version) { if (err || !/^1\.7/.test(version)) { return cb(new Error( 'Django 1.7 environment is not working' )); } cb(); }); } ], function(err) { if (err) { console.error(chalk.red('\nFATAL: ' + err.message + '\n')); } }); }
javascript
{ "resource": "" }
q33906
innerRender
train
function innerRender(from, template, data, callback) { var args, proc, out = '', err = '', base, strData; if (arguments.length < 4) { callback = data; data = {}; } if (!template || template.constructor !== String) { return callback(new Error('"template" requires a non-empty string')); } if ('function' !== typeof callback) { throw new Error('"callback" requires a function'); } try { //Make sure mock data could be stringified strData = JSON.stringify(data); } catch (e) { return callback(e); } base = gConfigurations.template_dirs; //If no template_dirs defined and is rendering a file, //we reset the template_dirs to the dirname of the file, //and set template as its basename // //e.g, // //django.configure({ // template_dirs: null // }); //django.renderFile('test/case/index.html'); // //equals // //django.configure({ // template_dirs: 'test/case' // }); //django.renderFile('index.html') // //That affects @include tag in Django, //see https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#include // if (('file' === from) && !base) { base = path.resolve(path.dirname(template)); template = path.basename(template); } args = (('source' === from) ? [PYTHON] : [PYTHON, base, template]).map(function(item, idx) { return idx ? encodeURIComponent(item) : item; }); proc = childProcess.spawn('python', args); //We use stdin to pass the mock data to avoid long shell arguments proc.stdin.write(('source' === from ? (encodeURIComponent(template) + '\n') : '') + strData + '\n'); //For python reading a line. proc.stdout.on('data', function(data) { //Here we get no string but buffer out += data.toString('utf-8'); }); proc.stderr.on('data', function(data) { err += data.toString('utf-8'); }); //What if blocked? We ignored it because this is not for production. proc.on('exit', function() { if (err) { return callback(new Error(err)); } else { return callback(null, out.replace(/\r(?=\r\n)/mg, '')); //A \r will always be prepend to \r\n } }); }
javascript
{ "resource": "" }
q33907
untgz
train
function untgz(istream, dst){ // decompress const tarStream = istream.pipe(_zlib.createGunzip()); // unpack return _untar(tarStream, dst); }
javascript
{ "resource": "" }
q33908
encodeInputs
train
function encodeInputs(inputs, add_address_to_previous_output_index) { //Initialize buffer and offset let offset = 0; var buffer = Buffer.allocUnsafe(100000); //Write number of inputs offset += bufferutils.writeVarInt(buffer, inputs.length, offset); inputs.forEach((input, index) => { //Write reversed hash offset += Buffer.from(input.previous_output.hash, 'hex').reverse().copy(buffer, offset); //Index offset = buffer.writeUInt32LE(input.previous_output.index, offset); if (add_address_to_previous_output_index !== undefined) { if (index == add_address_to_previous_output_index) { let lockregex = /^\[\ ([a-f0-9]+)\ \]\ numequalverify dup\ hash160\ \[ [a-f0-9]+\ \]\ equalverify\ checksig$/gi; if (input.previous_output.script && input.previous_output.script.match(lockregex)) { let locktime = lockregex.exec(input.previous_output.script.match(lockregex)[0])[1]; offset = writeScriptLockedPayToPubKeyHash(input.previous_output.address, locktime, buffer, offset); } else { if (Script.hasAttenuationModel(input.previous_output.script)) { let params = Script.getAttenuationParams(input.previous_output.script); offset = writeAttenuationScript(params.model, (params.hash !== '0000000000000000000000000000000000000000000000000000000000000000') ? params.hash : undefined, (params.index >= 0) ? params.index : undefined, input.previous_output.address, buffer, offset); } else { if (Script.isP2SH(input.previous_output.script)) { let script_buffer = Buffer.from(input.redeem, 'hex'); offset += bufferutils.writeVarInt(buffer, script_buffer.length, offset); offset += script_buffer.copy(buffer, offset); } else { if (input.previous_output.script) { let script_buffer = Script.fromASM(input.previous_output.script).toBuffer() offset += bufferutils.writeVarInt(buffer, script_buffer.length, offset); offset += script_buffer.copy(buffer, offset); } else { offset = writeScriptPayToPubKeyHash(input.previous_output.address, buffer, offset); } } } } } else { offset = buffer.writeUInt8(0, offset); } } else { //input script let script_buffer = encodeInputScript(input.script); offset += bufferutils.writeVarInt(buffer, script_buffer.length, offset); offset += script_buffer.copy(buffer, offset); } offset = buffer.writeUInt32LE(input.sequence, offset); }); return buffer.slice(0, offset); }
javascript
{ "resource": "" }
q33909
encodeAttachmentMessage
train
function encodeAttachmentMessage(buffer, offset, message) { if (message == undefined) throw Error('Specify message'); offset += encodeString(buffer, message, offset); return offset; }
javascript
{ "resource": "" }
q33910
encodeAttachmentMSTTransfer
train
function encodeAttachmentMSTTransfer(buffer, offset, symbol, quantity) { if (symbol == undefined) throw Error('Specify output asset'); if (quantity == undefined) throw Error('Specify output quanity'); offset = buffer.writeUInt32LE(Constants.MST.STATUS.TRANSFER, offset); offset += encodeString(buffer, symbol, offset); offset = bufferutils.writeUInt64LE(buffer, quantity, offset); return offset; }
javascript
{ "resource": "" }
q33911
encodeAttachmentDid
train
function encodeAttachmentDid(buffer, offset, attachment_data) { offset = buffer.writeUInt32LE(attachment_data.status, offset); offset += encodeString(buffer, attachment_data.symbol, offset); offset += encodeString(buffer, attachment_data.address, offset); return offset; }
javascript
{ "resource": "" }
q33912
encodeAttachmentCert
train
function encodeAttachmentCert(buffer, offset, attachment_data) { offset += encodeString(buffer, attachment_data.symbol, offset); offset += encodeString(buffer, attachment_data.owner, offset); offset += encodeString(buffer, attachment_data.address, offset); offset = buffer.writeUInt32LE(attachment_data.cert, offset); offset = buffer.writeUInt8(attachment_data.status, offset); if (attachment_data.content) { offset += encodeString(buffer, attachment_data.content, offset); } return offset; }
javascript
{ "resource": "" }
q33913
encodeAttachmentAssetIssue
train
function encodeAttachmentAssetIssue(buffer, offset, attachment_data) { offset = buffer.writeUInt32LE(attachment_data.status, offset); //Encode symbol offset += encodeString(buffer, attachment_data.symbol, offset); //Encode maximum supply offset = bufferutils.writeUInt64LE(buffer, attachment_data.max_supply, offset); //Encode precision offset = buffer.writeUInt8(attachment_data.precision, offset); //Encode secondary issue threshold offset = buffer.writeUInt8((attachment_data.secondaryissue_threshold) ? attachment_data.secondaryissue_threshold : 0, offset); offset += buffer.write("0000", offset, 2, 'hex'); //Encode issuer offset += encodeString(buffer, attachment_data.issuer, offset); //Encode recipient address offset += encodeString(buffer, attachment_data.address, offset); //Encode description offset += encodeString(buffer, attachment_data.description, offset); return offset; }
javascript
{ "resource": "" }
q33914
writeScriptPayToScriptHash
train
function writeScriptPayToScriptHash(scripthash, buffer, offset) { offset = buffer.writeUInt8(23, offset); //Script length offset = buffer.writeUInt8(OPS.OP_HASH160, offset); //Write previous output address offset = buffer.writeUInt8(20, offset); //Address length offset += Buffer.from(base58check.decode(scripthash, 'hex').data, 'hex').copy(buffer, offset); //Static transfer stuff offset = buffer.writeUInt8(OPS.OP_EQUAL, offset); return offset; }
javascript
{ "resource": "" }
q33915
writeScriptPayToPubKeyHash
train
function writeScriptPayToPubKeyHash(address, buffer, offset) { offset = buffer.writeUInt8(25, offset); //Script length offset = buffer.writeUInt8(OPS.OP_DUP, offset); offset = buffer.writeUInt8(OPS.OP_HASH160, offset); //Write previous output address offset = buffer.writeUInt8(20, offset); //Address length offset += Buffer.from(base58check.decode(address, 'hex').data, 'hex').copy(buffer, offset); //Static transfer stuff offset = buffer.writeUInt8(OPS.OP_EQUALVERIFY, offset); offset = buffer.writeUInt8(OPS.OP_CHECKSIG, offset); return offset; }
javascript
{ "resource": "" }
q33916
writeAttenuationScript
train
function writeAttenuationScript(attenuation_string, from_tx, from_index, address, buffer, offset) { let attenuation_buffer = Buffer.from(attenuation_string.toString('hex')); offset += bufferutils.writeVarInt(buffer, 26 + attenuation_string.length + 40, offset); offset = buffer.writeUInt8(77, offset); offset = buffer.writeInt16LE(attenuation_string.length, offset); offset += attenuation_buffer.copy(buffer, offset); offset = buffer.writeUInt8(36, offset); let hash = Buffer.from((from_tx != undefined) ? from_tx : '0000000000000000000000000000000000000000000000000000000000000000', 'hex').reverse(); let index = Buffer.from('ffffffff', 'hex'); if (from_index != undefined) index.writeInt32LE(from_index, 0); offset += Buffer.concat([hash, index]).copy(buffer, offset); offset = buffer.writeUInt8(178, offset); offset = buffer.writeUInt8(OPS.OP_DUP, offset); offset = buffer.writeUInt8(OPS.OP_HASH160, offset); //Write previous output address offset = buffer.writeUInt8(20, offset); //Address length offset += Buffer.from(base58check.decode(address, 'hex').data, 'hex').copy(buffer, offset); //Static transfer stuff offset = buffer.writeUInt8(OPS.OP_EQUALVERIFY, offset); offset = buffer.writeUInt8(OPS.OP_CHECKSIG, offset); return offset; }
javascript
{ "resource": "" }
q33917
writeScriptLockedPayToPubKeyHash
train
function writeScriptLockedPayToPubKeyHash(address, locktime, buffer, offset) { let locktime_buffer = Buffer.from(locktime, 'hex'); offset = buffer.writeUInt8(27 + locktime_buffer.length, offset); //Script length offset = buffer.writeUInt8(locktime_buffer.length, offset); //Length of locktime offset += locktime_buffer.copy(buffer, offset); offset = buffer.writeUInt8(OPS.OP_NUMEQUALVERIFY, offset); offset = buffer.writeUInt8(OPS.OP_DUP, offset); offset = buffer.writeUInt8(OPS.OP_HASH160, offset); //Write previous output address offset = buffer.writeUInt8(20, offset); //Address length offset += Buffer.from(base58check.decode(address, 'hex').data, 'hex').copy(buffer, offset); offset = buffer.writeUInt8(OPS.OP_EQUALVERIFY, offset); offset = buffer.writeUInt8(OPS.OP_CHECKSIG, offset); return offset; }
javascript
{ "resource": "" }
q33918
loadScript
train
async function loadScript(src) { let script = document.createElement('script'); script.type = 'text/javascript'; let rs, rj, timer; script.onload = () => { script.onload = null; clearTimeout(timer); rs(); }; let prom = new Promise((resolve, reject) => { rs = resolve; rj = reject; }); script.src = src; document.head.appendChild(script); timer = setTimeout(() => rj('load ' + src + ' time out'), 10000); return prom; }
javascript
{ "resource": "" }
q33919
beforeEachHook
train
async function beforeEachHook(done) { browser.__autoStart = browser.__prom = browser.__rejectSerial = browser.__resolveSerial = null; done && done(); }
javascript
{ "resource": "" }
q33920
applicableMessages
train
function applicableMessages(messages, options) { var length = messages.length var index = -1 var result = [] if (options.silent) { while (++index < length) { if (messages[index].fatal) { result.push(messages[index]) } } } else { result = messages.concat() } return result }
javascript
{ "resource": "" }
q33921
copyAttributes
train
function copyAttributes (src, dst, ignored) { ignored = ignored || []; const srcAttribs = Object.keys(src.attribs || src.attributes); for (let i = 0; i < srcAttribs.length; ++i) { if (!ignored.test(srcAttribs[i], $(dst), $(src))) { dst.attribs[srcAttribs[i]] = src.attribs[srcAttribs[i]]; } } }
javascript
{ "resource": "" }
q33922
tableShouldBeSkipped
train
function tableShouldBeSkipped(tableNode) { if (!tableNode) return true; if (!tableNode.rows) return true; if (tableNode.rows.length <= 1 && tableNode.rows[0].childNodes.length <= 1) return true; // Table with only one cell if (nodeContainsTable(tableNode)) return true; return false; }
javascript
{ "resource": "" }
q33923
gzip
train
async function gzip(input, dst, level=4){ // is input a filename or stream ? if (typeof input === 'string'){ input = await _fileInputStream(input); } // compress const gzipStream = input.pipe(_zlib.createGzip({ level: level })); // write content to file return _fileOutputStream(gzipStream, dst); }
javascript
{ "resource": "" }
q33924
train
function(html) { if (!html) { return ''; } var re = new RegExp('(' + Object.keys(chars).join('|') + ')', 'g'); return String(html).replace(re, function(match) { return chars[match]; }); }
javascript
{ "resource": "" }
q33925
isInsideDir
train
function isInsideDir(dir, targetDir) { if (targetDir == dir) return false if (targetDir == '.') return dir const relative = path.relative(targetDir, dir) if (/^\.\./.test(relative)) return false return relative }
javascript
{ "resource": "" }
q33926
injectElementWithStyles
train
function injectElementWithStyles( rule, callback, nodes, testnames ) { var mod = 'modernizr'; var style; var ret; var node; var docOverflow; var div = createElement('div'); var body = getBody(); if ( parseInt(nodes, 10) ) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while ( nodes-- ) { node = createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements. // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx // Documents served as xml will throw if using &shy; so use xml friendly encoded version. See issue #277 style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join(''); div.id = mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 (!body.fake ? div : body).innerHTML += style; body.appendChild(div); if ( body.fake ) { //avoid crashing IE8, if background image is used body.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible body.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(body); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists if ( body.fake ) { body.parentNode.removeChild(body); docElement.style.overflow = docOverflow; // Trigger layout so kinetic scrolling isn't disabled in iOS6+ docElement.offsetHeight; } else { div.parentNode.removeChild(div); } return !!ret; }
javascript
{ "resource": "" }
q33927
legalStyle
train
function legalStyle(localStyle, legalSet) { //flatten array, easy for manipulating data let tmp = flattenArray(localStyle) let obj = {} for (let k in tmp) { //save legal declaration to output if (legalSet.has(k)) obj[k] = tmp[k]; } return obj; }
javascript
{ "resource": "" }
q33928
flattenArray
train
function flattenArray(input, ans = {}) { if (!input || !Array.isArray(input)) return input || {} for (let k in input) { //recursive logic if (Array.isArray(input[k])) { ans = flattenArray(input[k], ans) } else { ans = Object.assign({}, ans, input[k]) } } return ans }
javascript
{ "resource": "" }
q33929
countCharFromStr
train
function countCharFromStr(str, ch) { let strArr = [...str]; let count = 0; for (let k in strArr) { if (strArr[k] === ch) { count++ } } return count }
javascript
{ "resource": "" }
q33930
setupProcess
train
function setupProcess(aLogger, aDaemonize, aLogFile) { aLogger.log('Setting up process. Run as a daemon:', aDaemonize, 'Logfile:', aLogFile); // Since we might need to open some files, and that's an asynchronous operation, // we will return a promise here that will never resolve on the parent (process will die instead) // and will resolve on the child return new Promise((resolve) => { if (!aDaemonize) { return resolve(); } if (!aLogFile) { return resolve({ stdout: process.stdout, stderr: process.stderr }); } const fs = require('fs'); const outputStream = fs.createWriteStream(aLogFile); outputStream.on('open', () => resolve({ stdout: outputStream, stderr: outputStream, cwd: process.cwd(), })); return null; }).then((daemonOpts) => { // No need to continue, let's make ourselves a daemon. if (daemonOpts) { require('daemon')(daemonOpts); } const signals = [ 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGALRM', 'SIGTERM', ]; process.on( 'uncaughtException', err => aLogger.error('Got an uncaught exception:', err, err.stack)); process.on('unhandledRejection', (aReason) => { aLogger.error('Unhandled Rejection:', aReason); if (aReason.message && aReason.message.startsWith('FATAL:')) { aLogger.error('Exiting because of a fatal error:', aReason); process.exit(1); } }); process.on('SIGHUP', () => { if (sighup.handler && sighup.handler instanceof Function) { aLogger.log('Got SIGHUP. Reloading config!'); sighup.handler(); } else { aLogger.log('Got SIGHUP. Ignoring!'); } }); // Sometime we get a SIGPIPE for some unknown reason. Just log and ignore it. process.on('SIGPIPE', () => { aLogger.log('Got SIGPIPE. Ignoring'); }); process.on('exit', () => { aLogger.log('Node process exiting!'); }); const SIGNAL_TEMPLATE_FN = (aSignal) => { aLogger.log(aSignal, 'captured! Exiting now.'); process.exit(1); }; signals.forEach((aSignalName) => { aLogger.trace('Setting handler', aSignalName); process.on(aSignalName, SIGNAL_TEMPLATE_FN.bind(undefined, aSignalName)); }); }); }
javascript
{ "resource": "" }
q33931
parseUrls
train
function parseUrls(text, options, callback) { var urls = [], words, x = 0, i; // is a text string if (text && utils.isString(text) && text !== '') { // break texts into words words = [text]; if (text.indexOf(' ') > -1) { words = text.split(' '); } // finds urls in text i = words.length; while (x < i) { var word = utils.trim(words[x]); if (word.indexOf('http:') === 0 || word.indexOf('https:') === 0) { urls.push({ match: word, url: word }); } else if (word.indexOf('pic.twitter.com/') === 0) { urls.push({ match: word, url: 'https://' + word }); } else if (word.indexOf('vine.co/v/') === 0) { urls.push({ match: word, url: 'https://' + word }); } x++; } } callback(null, urls); }
javascript
{ "resource": "" }
q33932
getExpandedUrl
train
function getExpandedUrl(url, options) { var x = 0, i; if (options.urls) { i = options.urls.length; while (x < i) { if (options.urls[x].match === url) { if (options.urls[x].expanded) { return options.urls[x].expanded; } return null; } x++; } } return null; }
javascript
{ "resource": "" }
q33933
constainRestrictedWords
train
function constainRestrictedWords(text) { var i, restictedWords = ['today', 'tomorrow', 'yesterday', 'tonight']; text = text.toLowerCase(); i = restictedWords.length; while (i--) { if (text.indexOf(restictedWords[i]) > -1) { return true; } } return false; }
javascript
{ "resource": "" }
q33934
buildISOLocalDate
train
function buildISOLocalDate (date) { var out; if (date.year !== undefined) { out = date.year; } if (date.month !== undefined) { out += '-' + pad(date.month + 1); } if (date.day !== undefined) { out += '-' + pad(date.day); } if (date.hour !== undefined) { out += 'T' + pad(date.hour); } if (date.minute !== undefined) { out += ':' + pad(date.minute); } if (date.second !== undefined) { out += ':' + pad(date.second); } return out; function pad(number) { if (number < 10) { return '0' + number; } return number; } }
javascript
{ "resource": "" }
q33935
FileOutputStream
train
function FileOutputStream(istream, destinationFilename, mode=false){ // wrap into Promise return new Promise(function(resolve, reject){ // file output stream let ostream = null; // on complete - chmod const onComplete = function(){ // file mode defined ? if (mode){ // set mode of destination file _fs.chmod(destinationFilename, mode, function(err){ if (err){ reject(err); }else{ resolve(); } }); }else{ // finish resolve(); } } // cleanup const onError = function(e){ // detach finish listener! if (ostream){ ostream.removeListener('finish', onComplete); } // close streams if (istream){ istream.destroy(); } if (ostream){ ostream.end(); } // throw error reject(e); } // add additional error listener to input stream istream.on('error', onError); // open write stream ostream = _fs.createWriteStream(destinationFilename); ostream.on('error', onError); ostream.on('finish', onComplete); // pipe in to out istream.pipe(ostream); }); }
javascript
{ "resource": "" }
q33936
train
function(){ // file mode defined ? if (mode){ // set mode of destination file _fs.chmod(destinationFilename, mode, function(err){ if (err){ reject(err); }else{ resolve(); } }); }else{ // finish resolve(); } }
javascript
{ "resource": "" }
q33937
getServerConfig
train
function getServerConfig(aCertDir) { const certFileRead = readFile(aCertDir + '/serverCert.pem'); const keyFileRead = readFile(aCertDir + '/serverKey.pem'); return Promise.all([certFileRead, keyFileRead]). then(files => [{ cert: files[0], key: files[1] }]); }
javascript
{ "resource": "" }
q33938
train
function( skipParents ){ skipParents = !!skipParents; this.updateMatrix(); var invalidWorldMatrix = this._hasInvalidWorldMatrix( skipParents ); if( invalidWorldMatrix ) { this._computeWorldMatrix( skipParents ); } for (var i = 0; i < this._children.length; i++) { var c = this._children[i]; c._invalidW = c._invalidW || invalidWorldMatrix; c.updateWorldMatrix( true ); } }
javascript
{ "resource": "" }
q33939
execCmd
train
function execCmd(cmd, allowedErrors = []) { debug(`About to execute cmd: ${cmd} with allowed errors: ${JSON.stringify(allowedErrors)}`); return exec(cmd, {}) .then((result) => { debug(`Executed successfully cmd: ${cmd}: `, result.stdout); const { stdout } = result; return stdout; }) .catch((error) => { debug(`Executed with error cmd: ${cmd}: `, error.stdout, error.stderr); if (allowedErrors.some(allowedError => allowedError.test(error.stderr))) { return Promise.resolve(error.stderr); } return Promise.reject(error); }); }
javascript
{ "resource": "" }
q33940
LineColumnFinder
train
function LineColumnFinder(str, options) { if (!(this instanceof LineColumnFinder)) { if (typeof options === "number") { return (new LineColumnFinder(str)).fromIndex(options); } return new LineColumnFinder(str, options); } this.str = str || ""; this.lineToIndex = buildLineToIndex(this.str); options = options || {}; this.origin = typeof options.origin === "undefined" ? 1 : options.origin; }
javascript
{ "resource": "" }
q33941
buildLineToIndex
train
function buildLineToIndex(str) { var lines = str.split("\n"), lineToIndex = new Array(lines.length), index = 0; for (var i = 0, l = lines.length; i < l; i++) { lineToIndex[i] = index; index += lines[i].length + /* "\n".length */ 1; } return lineToIndex; }
javascript
{ "resource": "" }
q33942
findLowerIndexInRangeArray
train
function findLowerIndexInRangeArray(value, arr) { if (value >= arr[arr.length - 1]) { return arr.length - 1; } var min = 0, max = arr.length - 2, mid; while (min < max) { mid = min + ((max - min) >> 1); if (value < arr[mid]) { max = mid - 1; } else if (value >= arr[mid + 1]) { min = mid + 1; } else { // value >= arr[mid] && value < arr[mid + 1] min = mid; break; } } return min; }
javascript
{ "resource": "" }
q33943
scandir
train
async function scandir(dir, recursive=true, absolutePaths=false){ // get absolute path const absPath = _path.resolve(dir); // stats command executable ? dir/file exists const stats = await _fs.stat(absPath); // check if its a directory if (!stats.isDirectory()){ throw new Error('Requested directory <' + absPath + '> is not of type directory'); } // use absolute paths ? if (absolutePaths){ dir = absPath; } // stack of directories to scan const dirstack = [dir]; // list of files const files = []; // list of directories const directories = []; // iterative scan files while (dirstack.length > 0){ // get current directory const currentDir = dirstack.pop(); // get current dir items const itemNames = await _fs.readdir(currentDir); // get item stats (parallel) const itemStats = await Promise.all(itemNames.map((item) => _fs.stat(_path.join(currentDir, item)))); // process item stats for (let i=0;i<itemNames.length;i++){ // prepend current path const currentItem = _path.join(currentDir, itemNames[i]); // directory ? push to stack and directory list if (itemStats[i].isDirectory()){ // recursive mode ? if (recursive){ dirstack.push(currentItem); } // store dir entry directories.push(currentItem); // file, socket, symlink, device.. }else{ // push to filelist files.push(currentItem); } } } // return file and directory list return [files, directories]; }
javascript
{ "resource": "" }
q33944
fetch
train
function fetch(request, maxCacheAge) { if (maxCacheAge === void 0) { maxCacheAge = 60 * 60 * 1000; } return tslib_1.__awaiter(this, void 0, void 0, function () { var promise; return tslib_1.__generator(this, function (_a) { switch (_a.label) { case 0: if (!(!cache.has(request) || cache.get(request)[1].getTime() + maxCacheAge - new Date().getTime() < 0)) return [3 /*break*/, 2]; promise = window.fetch(request).then(function(res){return res.json()}).catch(function(err){return window.fetch(`https://lergin.de/api/cors/${request}`).then(function(res){return res.json()})}); cache.set(request, [promise, new Date()]); return [4 /*yield*/, promise]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [4 /*yield*/, cache.get(request)[0]]; case 3: return [2 /*return*/, _a.sent()]; } }); }); }
javascript
{ "resource": "" }
q33945
expandToObject
train
function expandToObject(input) { // If the input is a string, encapsulate it as an array var retObj = input; if (typeof retObj === 'string') { retObj = [input]; } // If the retObj is an array if (Array.isArray(retObj)) { // Collect the inputs into an object var inputArr = retObj; retObj = {}; // Iterate over the inputs inputArr.forEach(function (inputStr) { // Break down any brace exapansions var inputPaths = braceExpand(inputStr); // Iterate over the paths inputPaths.forEach(function (filepath) { // Grab the extension and save it under its key // TODO: Deal with observer pattern here. // TODO: Will probably go `classical` here var ext = path.extname(filepath).slice(1); retObj[ext] = filepath; }); }); } // Return the objectified src return retObj; }
javascript
{ "resource": "" }
q33946
exists
train
function exists(filedir){ // promise wrapper return new Promise(function(resolve){ // try to stat the file _fs.stat(filedir, function(err){ resolve(!err) }); }); }
javascript
{ "resource": "" }
q33947
trace
train
function trace() { var args = Array.prototype.slice.call(arguments); var traceLevel = args.shift(); if (traceLevel.level & enabledLevels) { args.unshift('[' + traceLevel.name + '] ' + new Date().toISOString() + ' - ' + aName + ':'); console.log.apply(console, args); } }
javascript
{ "resource": "" }
q33948
FilterloadMessage
train
function FilterloadMessage(arg, options) { Message.call(this, options); this.command = 'filterload'; $.checkArgument( _.isUndefined(arg) || arg instanceof BloomFilter, 'An instance of BloomFilter or undefined is expected' ); this.filter = arg; }
javascript
{ "resource": "" }
q33949
extendErrorBody
train
function extendErrorBody(ctor) { /** * Parse errror's arguments to extract the 'options' object. * Extracted from https://github.com/restify/errors/blob/master/lib/helpers.js#L30 * @param {} ctorArgs Arguments of the error. */ function parseOptions(ctorArgs) { function parse() { let options = null; if (_.isPlainObject(arguments[0])) { // See https://github.com/restify/errors#new-erroroptions--printf-args options = arguments[0] || {}; } else if ( arguments[0] instanceof Error && _.isPlainObject(arguments[1]) ) { // See https://github.com/restify/errors#new-errorpriorerr-options--printf-args options = arguments[1] || {}; } return options; } // Calls constructor args. return parse.apply(null, ctorArgs); } /** * Dynamically create a constructor. * Must be anonymous fn. * @constructor */ // Use an object because otherwise the variable name is shown as function name. const anonymous = {}; anonymous.hook = function() { const options = parseOptions(arguments) || {}; // Calls the parent constructor with itself as scope. ctor.apply(this, arguments); // Adds custom options to itself patchErrorBody(this, options); }; // Inherits from the original error. // Is that necessary?? util.inherits(anonymous.hook, ctor); // Make the prototype an instance of the old class. anonymous.hook.prototype = ctor.prototype; // Assign display name anonymous.hook.displayName = ctor.displayName + 'Hook'; return anonymous.hook; }
javascript
{ "resource": "" }
q33950
patchErrorBody
train
function patchErrorBody(err, options) { // Gets the current toJSON to be extended. const json = err.toJSON(); Object.keys(customOptions).forEach(optName => { let value = options[optName]; if (value === undefined) { value = err.body[optName]; if (value === '' || value === undefined) { value = customOptions[optName]( err.body.code, err.statusCode, err.body.message ); } } if (value !== undefined) { // Adds the option to the body of the error. err.body[optName] = value; // Adds the option to the json representation of the error. json[optName] = value; } }); // Patchs the toJSON method. err.toJSON = () => json; }
javascript
{ "resource": "" }
q33951
patchMakeConstructor
train
function patchMakeConstructor() { const func = errors.makeConstructor; function makeConstructorHook() { func.apply(null, arguments); patchError(arguments[0]); } errors.makeConstructor = makeConstructorHook; }
javascript
{ "resource": "" }
q33952
patchMakeErrFromCode
train
function patchMakeErrFromCode() { const func = errors.makeErrFromCode; function makeErrFromCodeHook() { const err = func.apply(null, arguments); patchErrorBody(err, {}); return err; } errors.makeErrFromCode = makeErrFromCodeHook; // Deprecated. // See https://github.com/restify/errors/blob/master/lib/index.js#L126 errors.codeToHttpError = makeErrFromCodeHook; }
javascript
{ "resource": "" }
q33953
addOption
train
function addOption(optName, optDefault) { if (typeof optDefault !== 'function') { const val = optDefault; optDefault = () => val; } customOptions[optName] = optDefault; }
javascript
{ "resource": "" }
q33954
LocalfsStorageAttachments
train
function LocalfsStorageAttachments(options) { if(options.removePrefix) { this.prefix = options.removePrefix; } attachments.StorageProvider.call(this, options); }
javascript
{ "resource": "" }
q33955
getMemory
train
function getMemory(size) { if (!staticSealed) return staticAlloc(size); if (!runtimeInitialized) return dynamicAlloc(size); return _malloc(size); }
javascript
{ "resource": "" }
q33956
isDataURI
train
function isDataURI(filename) { return String.prototype.startsWith ? filename.startsWith(dataURIPrefix) : filename.indexOf(dataURIPrefix) === 0; }
javascript
{ "resource": "" }
q33957
useRequest
train
function useRequest() { var request = Module['memoryInitializerRequest']; var response = request.response; if (request.status !== 200 && request.status !== 0) { var data = tryParseAsDataURI(Module['memoryInitializerRequestURL']); if (data) { response = data.buffer; } else { // If you see this warning, the issue may be that you are using locateFile or memoryInitializerPrefixURL, and defining them in JS. That // means that the HTML file doesn't know about them, and when it tries to create the mem init request early, does it to the wrong place. // Look in your browser's devtools network console to see what's going on. console.warn('a problem seems to have happened with Module.memoryInitializerRequest, status: ' + request.status + ', retrying ' + memoryInitializer); doBrowserLoad(); return; } } applyMemoryInitializer(response); }
javascript
{ "resource": "" }
q33958
train
function (axis, row) { var returnField = []; if (axis !== null) { if (axis._hasTimeField()) { returnField.push(axis._parseDate(row[axis.timeField])); } else if (axis._hasCategories()) { axis.categoryFields.forEach(function (cat) { returnField.push(row[cat]); }, this); } } return returnField; }
javascript
{ "resource": "" }
q33959
train
function (d, chart, series) { var returnCx = 0; if (series.x.measure !== null && series.x.measure !== undefined) { returnCx = series.x._scale(d.cx); } else if (series.x._hasCategories() && series.x.categoryFields.length >= 2) { returnCx = series.x._scale(d.cx) + dimple._helpers.xGap(chart, series) + ((d.xOffset + 0.5) * (((chart._widthPixels() / series.x._max) - 2 * dimple._helpers.xGap(chart, series)) * d.width)); } else { returnCx = series.x._scale(d.cx) + ((chart._widthPixels() / series.x._max) / 2); } return returnCx; }
javascript
{ "resource": "" }
q33960
train
function (d, chart, series) { var returnCy = 0; if (series.y.measure !== null && series.y.measure !== undefined) { returnCy = series.y._scale(d.cy); } else if (series.y.categoryFields !== null && series.y.categoryFields !== undefined && series.y.categoryFields.length >= 2) { returnCy = (series.y._scale(d.cy) - (chart._heightPixels() / series.y._max)) + dimple._helpers.yGap(chart, series) + ((d.yOffset + 0.5) * (((chart._heightPixels() / series.y._max) - 2 * dimple._helpers.yGap(chart, series)) * d.height)); } else { returnCy = series.y._scale(d.cy) - ((chart._heightPixels() / series.y._max) / 2); } return returnCy; }
javascript
{ "resource": "" }
q33961
train
function (chart, series) { var returnXGap = 0; if ((series.x.measure === null || series.x.measure === undefined) && series.barGap > 0) { returnXGap = ((chart._widthPixels() / series.x._max) * (series.barGap > 0.99 ? 0.99 : series.barGap)) / 2; } return returnXGap; }
javascript
{ "resource": "" }
q33962
train
function (d, chart, series) { var returnXClusterGap = 0; if (series.x.categoryFields !== null && series.x.categoryFields !== undefined && series.x.categoryFields.length >= 2 && series.clusterBarGap > 0 && !series.x._hasMeasure()) { returnXClusterGap = (d.width * ((chart._widthPixels() / series.x._max) - (dimple._helpers.xGap(chart, series) * 2)) * (series.clusterBarGap > 0.99 ? 0.99 : series.clusterBarGap)) / 2; } return returnXClusterGap; }
javascript
{ "resource": "" }
q33963
train
function (chart, series) { var returnYGap = 0; if ((series.y.measure === null || series.y.measure === undefined) && series.barGap > 0) { returnYGap = ((chart._heightPixels() / series.y._max) * (series.barGap > 0.99 ? 0.99 : series.barGap)) / 2; } return returnYGap; }
javascript
{ "resource": "" }
q33964
train
function (d, chart, series) { var returnYClusterGap = 0; if (series.y.categoryFields !== null && series.y.categoryFields !== undefined && series.y.categoryFields.length >= 2 && series.clusterBarGap > 0 && !series.y._hasMeasure()) { returnYClusterGap = (d.height * ((chart._heightPixels() / series.y._max) - (dimple._helpers.yGap(chart, series) * 2)) * (series.clusterBarGap > 0.99 ? 0.99 : series.clusterBarGap)) / 2; } return returnYClusterGap; }
javascript
{ "resource": "" }
q33965
train
function (d, chart, series) { var returnX = 0; if (series.x._hasTimeField()) { returnX = series.x._scale(d.x) - (dimple._helpers.width(d, chart, series) / 2); } else if (series.x.measure !== null && series.x.measure !== undefined) { returnX = series.x._scale(d.x); } else { returnX = series.x._scale(d.x) + dimple._helpers.xGap(chart, series) + (d.xOffset * (dimple._helpers.width(d, chart, series) + 2 * dimple._helpers.xClusterGap(d, chart, series))) + dimple._helpers.xClusterGap(d, chart, series); } return returnX; }
javascript
{ "resource": "" }
q33966
train
function (d, chart, series) { var returnY = 0; if (series.y._hasTimeField()) { returnY = series.y._scale(d.y) - (dimple._helpers.height(d, chart, series) / 2); } else if (series.y.measure !== null && series.y.measure !== undefined) { returnY = series.y._scale(d.y); } else { returnY = (series.y._scale(d.y) - (chart._heightPixels() / series.y._max)) + dimple._helpers.yGap(chart, series) + (d.yOffset * (dimple._helpers.height(d, chart, series) + 2 * dimple._helpers.yClusterGap(d, chart, series))) + dimple._helpers.yClusterGap(d, chart, series); } return returnY; }
javascript
{ "resource": "" }
q33967
train
function (d, chart, series) { var returnWidth = 0; if (series.x.measure !== null && series.x.measure !== undefined) { returnWidth = Math.abs(series.x._scale((d.x < 0 ? d.x - d.width : d.x + d.width)) - series.x._scale(d.x)); } else if (series.x._hasTimeField()) { returnWidth = series.x.floatingBarWidth; } else { returnWidth = d.width * ((chart._widthPixels() / series.x._max) - (dimple._helpers.xGap(chart, series) * 2)) - (dimple._helpers.xClusterGap(d, chart, series) * 2); } return returnWidth; }
javascript
{ "resource": "" }
q33968
train
function (d, chart, series) { var returnHeight = 0; if (series.y._hasTimeField()) { returnHeight = series.y.floatingBarWidth; } else if (series.y.measure !== null && series.y.measure !== undefined) { returnHeight = Math.abs(series.y._scale(d.y) - series.y._scale((d.y <= 0 ? d.y + d.height : d.y - d.height))); } else { returnHeight = d.height * ((chart._heightPixels() / series.y._max) - (dimple._helpers.yGap(chart, series) * 2)) - (dimple._helpers.yClusterGap(d, chart, series) * 2); } return returnHeight; }
javascript
{ "resource": "" }
q33969
train
function (d, chart, series) { var returnOpacity = 0; if (series.c !== null && series.c !== undefined) { returnOpacity = d.opacity; } else { returnOpacity = chart.getColor(d.aggField.slice(-1)[0]).opacity; } return returnOpacity; }
javascript
{ "resource": "" }
q33970
train
function (d, chart, series) { var returnFill = 0; if (series.c !== null && series.c !== undefined) { returnFill = d.fill; } else { returnFill = chart.getColor(d.aggField.slice(-1)[0]).fill; } return returnFill; }
javascript
{ "resource": "" }
q33971
train
function (d, chart, series) { var stroke = 0; if (series.c !== null && series.c !== undefined) { stroke = d.stroke; } else { stroke = chart.getColor(d.aggField.slice(-1)[0]).stroke; } return stroke; }
javascript
{ "resource": "" }
q33972
train
function (x, y) { var matrix = selectedShape.node().getCTM(), position = chart.svg.node().createSVGPoint(); position.x = x || 0; position.y = y || 0; return position.matrixTransform(matrix); }
javascript
{ "resource": "" }
q33973
train
function() { // locale InsFrame root folder homeFolder = __dirname; console.log(" info -".cyan, "InsFrame root".yellow, homeFolder); // express config app.set("view engine", "ejs"); app.set("views", homeFolder + "/views"); app.set("views"); app.set("view options", { layout: null }); // static resources app.use("/js", express.static(homeFolder + "/js")); app.use("/css", express.static(homeFolder + "/css")); app.use("/images", express.static(homeFolder + "/images")); // port port = this.port || parseInt(process.argv[2]) || PORT; // Timer to send close requests when timeout occurs. setInterval(function() { for (var id in urlData) { urlData[id].timeout -= CHECK_INTERVAL; if (urlData[id].timeout <= 0) { io.sockets.emit("close", { id: id, url: urlData[id].url }); console.log(" info -".cyan, "close/timeout".yellow, JSON.stringify(urlData[id])); delete urlData[id]; } } }, CHECK_INTERVAL); }
javascript
{ "resource": "" }
q33974
train
function() { io = io.listen(app); io.set("log level", 1); io.sockets.on("connection", function(socket) { connections += 1; console.log(" info -".cyan, ("new connection. Connections: " + connections).yellow); socket.on("disconnect", function() { connections -= 1; console.log(" info -".cyan, ("connection closed. Connections: " + connections).yellow); }); socket.on("iframe-loaded", function(data) { urlData[data.id].counter--; console.log(" info -".cyan, ("client sends event iframe-loaded").yellow, JSON.stringify(data)); }); }); }
javascript
{ "resource": "" }
q33975
PongMessage
train
function PongMessage(arg, options) { Message.call(this, options); this.command = 'pong'; $.checkArgument( _.isUndefined(arg) || (BufferUtil.isBuffer(arg) && arg.length === 8), 'First argument is expected to be an 8 byte buffer' ); this.nonce = arg || utils.getNonce(); }
javascript
{ "resource": "" }
q33976
txt
train
function txt(text) { var name = '"' + text.replace(/"/gm, '\\"') + '"'; return new Pattern(name, function (str, pos) { if (str.substr(pos, text.length) == text) return { res: text, end: pos + text.length }; }); }
javascript
{ "resource": "" }
q33977
rgx
train
function rgx(regexp) { return new Pattern(regexp + '', function (str, pos) { var m = regexp.exec(str.slice(pos)); if (m && m.index === 0) // regex must match at the beginning, so index must be 0 return { res: m[0], end: pos + m[0].length }; }); }
javascript
{ "resource": "" }
q33978
opt
train
function opt(pattern, defval) { return new Pattern(pattern + '?', function (str, pos) { return pattern.exec(str, pos) || { res: defval, end: pos }; }); }
javascript
{ "resource": "" }
q33979
exc
train
function exc(pattern, except) { var name = pattern + ' ~ ' + except; return new Pattern(name, function (str, pos) { return !except.exec(str, pos) && pattern.exec(str, pos); }); }
javascript
{ "resource": "" }
q33980
any
train
function any(/* patterns... */) { var patterns = [].slice.call(arguments, 0); var name = '(' + patterns.join(' | ') + ')'; return new Pattern(name, function (str, pos) { var r, i; for (i = 0; i < patterns.length && !r; i++) r = patterns[i].exec(str, pos); return r; }); }
javascript
{ "resource": "" }
q33981
seq
train
function seq(/* patterns... */) { var patterns = [].slice.call(arguments, 0); var name = '(' + patterns.join(' ') + ')'; return new Pattern(name, function (str, pos) { var i, r, end = pos, res = []; for (i = 0; i < patterns.length; i++) { r = patterns[i].exec(str, end); if (!r) return; res.push(r.res); end = r.end; } return { res: res, end: end }; }); }
javascript
{ "resource": "" }
q33982
GetblocksMessage
train
function GetblocksMessage(arg, options) { Message.call(this, options); this.command = 'getblocks'; this.version = options.protocolVersion; if (!arg) { arg = {}; } arg = utils.sanitizeStartStop(arg); this.starts = arg.starts; this.stop = arg.stop; }
javascript
{ "resource": "" }
q33983
MnListDiffMessage
train
function MnListDiffMessage(arg, options) { Message.call(this, options); this.MnListDiff = options.MnListDiff; this.command = 'mnlistdiff'; $.checkArgument( _.isUndefined(arg) || arg instanceof this.MnListDiff, 'An instance of MnListDiff or undefined is expected' ); this.mnlistdiff = arg; }
javascript
{ "resource": "" }
q33984
Pool
train
function Pool(options) { /* jshint maxcomplexity: 10 */ /* jshint maxstatements: 20 */ var self = this; options = options || {}; this.keepalive = false; this._connectedPeers = {}; this._addrs = []; this.listenAddr = options.listenAddr !== false; this.dnsSeed = options.dnsSeed !== false; this.maxSize = options.maxSize || Pool.MaxConnectedPeers; this.messages = options.messages; this.network = Networks.get(options.network) || Networks.defaultNetwork; this.relay = options.relay === false ? false : true; if (options.addrs) { for(var i = 0; i < options.addrs.length; i++) { this._addAddr(options.addrs[i]); } } if (this.listenAddr) { this.on('peeraddr', function peerAddrEvent(peer, message) { var addrs = message.addresses; var length = addrs.length; for (var i = 0; i < length; i++) { var addr = addrs[i]; var future = new Date().getTime() + (10 * 60 * 1000); if (addr.time.getTime() <= 100000000000 || addr.time.getTime() > future) { // In case of an invalid time, assume "5 days ago" var past = new Date(new Date().getTime() - 5 * 24 * 60 * 60 * 1000); addr.time = past; } this._addAddr(addr); } }); } this.on('seed', function seedEvent(ips) { ips.forEach(function(ip) { self._addAddr({ ip: { v4: ip } }); }); if (self.keepalive) { self._fillConnections(); } }); this.on('peerdisconnect', function peerDisconnectEvent(peer, addr) { self._deprioritizeAddr(addr); self._removeConnectedPeer(addr); if (self.keepalive) { self._fillConnections(); } }); return this; }
javascript
{ "resource": "" }
q33985
train
function (keyData) { this.shift = {}; this.names = Util.clone(Util.whenUndefined(keyData.names, [])); this.character = Util.whenUndefined(keyData.char, null); this.shift.character = Util.whenUndefined(keyData.shift, Util.whenUndefined(keyData.char, null)); this.keyCode = { ie: keyData.ie, mozilla: Util.whenUndefined(keyData.moz, keyData.ie) }; this.charCode = null; this.shift.charCode = null; if (!Util.isUndefined(keyData.ascii)) { this.charCode = Util.whenUndefined(keyData.ascii.norm, null); this.shift.charCode = Util.whenUndefined(keyData.ascii.shift, Util.whenUndefined(keyData.ascii.norm, null)); } }
javascript
{ "resource": "" }
q33986
Barrett
train
function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); Int128.ONE.dlShiftTo(2 * m.t, this.r2); this.mu = this.r2.divide(m); this.m = m; }
javascript
{ "resource": "" }
q33987
Messages
train
function Messages(options) { this.builder = Messages.builder(options); // map message constructors by name for(var key in this.builder.commandsMap) { var name = this.builder.commandsMap[key]; this[name] = this.builder.commands[key]; } if (!options) { options = {}; } this.network = options.network || axecore.Networks.defaultNetwork; }
javascript
{ "resource": "" }
q33988
showExtensionTab
train
async function showExtensionTab(url, match = url) { match = extension.getURL(match || url); url = extension.getURL(url); for (const view of extension.getViews({ type: 'tab', })) { if (view && (typeof match === 'string' ? view.location.href === match : match.test(view.location.href)) && view.tabId != null) { const tab = (await new Promise(got => (view.browser || view.chrome).tabs.getCurrent(got))); if (tab) { (await Tabs.update(tab.id, { active: true, })); (await Windows.update(tab.windowId, { focused: true, })); return tab; } } } return Tabs.create({ url, }); }
javascript
{ "resource": "" }
q33989
Inventory
train
function Inventory(obj) { this.type = obj.type; if (!BufferUtil.isBuffer(obj.hash)) { throw new TypeError('Unexpected hash, expected to be a buffer'); } this.hash = obj.hash; }
javascript
{ "resource": "" }
q33990
defineLinkedProperty
train
function defineLinkedProperty(obj, prop, srcProp, readOnly) { let propName, srcKey; if (Array.isArray(prop)) { propName = prop[0]; srcKey = prop[1]; } else { propName = srcKey = prop; } if (typeof srcProp === 'boolean') { readOnly = srcProp; srcProp = undefined; } if (! srcProp) srcProp = 'data'; let descriptor = { enumerable: true, get: function() { return obj[srcProp][srcKey] } }; if (! readOnly) { descriptor.set = function(val) { let oldVal = obj[srcProp][srcKey]; if (! deepEqual(val, oldVal)) { obj[srcKey][srcKey] = val; if (obj instanceof EventEmitter) { obj.emit('update', obj, propName, val); } } }; } Object.defineProperty(obj, propName, descriptor); }
javascript
{ "resource": "" }
q33991
createFilter
train
function createFilter(jsonQuery) { if ('function' === typeof jsonQuery) return jsonQuery; if ((!jsonQuery) || (Object.keys(jsonQuery).length === 0)) { return () => true; } jsonQuery = Object.assign({}, jsonQuery); // protect against side effects return function(obj) { for (let key of Object.keys(jsonQuery)) { if (! Object.is(obj[key], jsonQuery[key])) return false; } return true; }; }
javascript
{ "resource": "" }
q33992
envToObject
train
function envToObject(fullPath) { return fs.readFileAsync(fullPath) .then((file) => { let envVars = {}; file = file.toString('utf8'); file = file.replace(/ /g, ""); let keyvals = file.split(os.EOL) for (let i = 0; i <= keyvals.length - 1; ++i) { let line = keyvals[i]; let value = line.substring(line.indexOf('=')+1); let key = keyvals[i].split('=')[0]; if(key !== '') { envVars[key] = value; } } return envVars }); }
javascript
{ "resource": "" }
q33993
setValue
train
function setValue(name, stat, value, gran, timestamp, callback) { if(typeof gran == 'string') { gran = util.getUnitDesc(gran) } var key = getGranKey(name, gran, timestamp); redis.hset(key, stat, value, callback) }
javascript
{ "resource": "" }
q33994
recordUnique
train
function recordUnique(name, uniqueId, statistics, aggregations, timestamp, callback) { timestamp = timestamp || Date.now(); // normal record if(statistics) { var num = Array.isArray(uniqueId) ? uniqueId.length : 1; record(name, num, statistics, aggregations, timestamp); } // record unique var multi = redis.multi(); granularities.forEach(function(gran) { var key = getGranKey(name, gran, timestamp); var expireTime = util.getExpireTime(gran, timestamp); var pfkey = key + ':pf'; multi.hset(keyPFKeys, pfkey, expireTime); if(Array.isArray(uniqueId)) { multi.pfadd.apply(multi, [pfkey].concat(uniqueId)); } else { multi.pfadd(pfkey, uniqueId); } // recordStats(key); var unitPeriod = gran[0]; multi.hincrby(key, 'uni', 0); multi.expire(key, points * unitPeriod / 1000); }); multi.exec(callback || log); }
javascript
{ "resource": "" }
q33995
getStat
train
function getStat(type, name, granCode, fromDate, toDate, callback) { if(!granCode) throw new Error('granCode is required'); if(!callback && typeof toDate == 'function') { callback = toDate; toDate = Date.now(); } var gran = granMap[granCode] || util.getUnitDesc(granCode); if(!gran) throw new Error('Granualrity is not defined ' + granCode); if(fromDate instanceof Date) fromDate = fromDate.getTime(); if(toDate instanceof Date) toDate = toDate.getTime(); toDate = toDate || Date.now() fromDate = fromDate || (toDate - util.getTimePeriod(gran, points)); var unitPeriod = gran[0]; var multi = redis.multi(); var _points = []; for(var d = fromDate; d <= toDate; d += unitPeriod) { var key = getGranKey(name, gran, d); _points.push(util.getKeyTime(gran, d)); multi.hget(key, type); } multi.exec(function(err, results) { if(err) return callback(err); var merged = []; for (var i = 0, l = _points.length, p; i < l; i ++) { p = _points[i]; merged[i] = [p, Number(results[i])]; } callback(null, { step: unitPeriod , unitType: gran[3] , data: merged }); }); }
javascript
{ "resource": "" }
q33996
RejectMessage
train
function RejectMessage(arg, options) { if (!arg) { arg = {}; } Message.call(this, options); this.command = 'reject'; this.message = arg.message; this.ccode = arg.ccode; this.reason = arg.reason; this.data = arg.data; }
javascript
{ "resource": "" }
q33997
join
train
function join() { var path = ''; var args = slice.call(arguments, 0); if (arguments.length <= 1) args.unshift(cwd()); for (var i = 0; i < args.length; i += 1) { var segment = args[i]; if (!isString(segment)) { throw new TypeError ('Arguemnts to path.join must be strings'); } if (segment) { if (!path) { path += segment; } else { path += '/' + segment; } } } return normalize(path); }
javascript
{ "resource": "" }
q33998
makeSubfieldPairs
train
function makeSubfieldPairs(subfields1, subfields2, fn_comparator) { var pairs = []; if (subfields1.length === subfields2.length) { subfields2.forEach(function(subfield2) { return subfields1.some(function(subfield1) { if (fn_comparator(subfield1, subfield2)) { pairs.push([subfield1, subfield2]); return true; } }); }); } else { throw new Error('Number of subfields are not equal'); } return pairs; }
javascript
{ "resource": "" }
q33999
addWeight
train
function addWeight (canonicalNodeWithPath, query) { const cnwp = canonicalNodeWithPath const name = presentableName(cnwp.node, preferredLocale) const synonym = cnwp.path .map(pathNode => presentableName(pathNode.node, pathNode.locale)) .map(nameInPath => nameInPath.toLowerCase()) .pop() const indexOfQuery = indexOfLowerCase(name, query) const isUk = name === 'United Kingdom' const isUs = name === 'United States' // Temporary country weighting const ukBias = 2 const usBias = 1.5 const defaultCountryBias = 1 const isExactMatchToCanonicalName = name.toLowerCase() === query.toLowerCase() const canonicalNameStartsWithQuery = indexOfQuery === 0 const wordInCanonicalNameStartsWithQuery = name .split(' ') .filter(w => w.toLowerCase().indexOf(query.toLowerCase()) === 0) .length > 0 // TODO: make these const var synonymIsExactMatch = false var synonymStartsWithQuery = false var wordInSynonymStartsWith = false var indexOfSynonymQuery = false var synonymContainsQuery = false if (synonym) { synonymIsExactMatch = synonym === query.toLowerCase() synonymStartsWithQuery = synonym .indexOf(query.toLowerCase()) === 0 wordInSynonymStartsWith = synonym .split(' ') .filter(w => w.toLowerCase().indexOf(query.toLowerCase()) === 0) .length > 0 indexOfSynonymQuery = indexOfLowerCase(synonym, query) } // TODO: Contains consts don't work const canonicalNameContainsQuery = indexOfQuery > 0 synonymContainsQuery = indexOfSynonymQuery > 0 // Canonical name matches if (isExactMatchToCanonicalName) { cnwp.weight = 100 } else if (canonicalNameStartsWithQuery) { cnwp.weight = 76 } else if (wordInCanonicalNameStartsWithQuery) { cnwp.weight = 60 } else if (synonymIsExactMatch) { // Synonmn matches cnwp.weight = 50 } else if (synonymStartsWithQuery) { cnwp.weight = 45 } else if (wordInSynonymStartsWith) { cnwp.weight = 37 } else if (canonicalNameContainsQuery) { // Contains (DOES NOT WORK YET) cnwp.weight = 25 } else if (synonymContainsQuery) { cnwp.weight = 22 } else { // Not sure if else is possible cnwp.weight = 15 } // Longer paths mean canonical node is further from matched synonym, so rank it lower. // TODO - pruning multiple matches should happen elsewhere cnwp.weight -= cnwp.path.length var countryBias = isUk ? ukBias : defaultCountryBias countryBias = isUs ? usBias : countryBias cnwp.weight *= countryBias return cnwp }
javascript
{ "resource": "" }