_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q5000
RecordKey
train
function RecordKey(path, recordType, name) { this.path = LedgerPath.parse(path); this.recordType = recordType; this.name = name; }
javascript
{ "resource": "" }
q5001
pending
train
function pending(options) { options = options || {}; var store = options.store; var autoRemove = (typeof options.autoRemove === 'undefined') ? true : options.autoRemove; if (!store) throw new Error('pending middleware requires a store'); return function pending(stanza, next) { if (!stanza.id || !(stanza.type == 'result' || stanza.type == 'error')) { return next(); } var key = stanza.from + ':' + stanza.id; store.get(key, function(err, data) { if (err) { next(err); } else if (!data) { next(); } else { stanza.irt = stanza.inReplyTo = stanza.inResponseTo = stanza.regarding = data; if (autoRemove) { store.remove(key); } next(); } }); } }
javascript
{ "resource": "" }
q5002
train
function() { var dest = gulp.dest('tmp/'); dest.on('end', function() { grunt.log.ok('Created tmp/fn.js'); }); return gulp.src('test/fixtures/*.coffee') .pipe(coffee()) .pipe(concat('fn.js')) .pipe(dest); }
javascript
{ "resource": "" }
q5003
CoapServerNode
train
function CoapServerNode(n) { // Create a RED node RED.nodes.createNode(this,n); var node = this; // Store local copies of the node configuration (as defined in the .html) node.options = {}; node.options.name = n.name; node.options.port = n.port; node._inputNodes = []; // collection of "coap in" nodes that represent coap resources // Setup node-coap server and start node.server = new coap.createServer(); node.server.on('request', function(req, res) { node.handleRequest(req, res); res.on('error', function(err) { node.log('server error'); node.log(err); }); }); node.server.listen(node.options.port, function() { //console.log('server started'); node.log('CoAP Server Started'); }); node.on("close", function() { node._inputNodes = []; node.server.close(); }); }
javascript
{ "resource": "" }
q5004
train
function (showSignal) { return function (msg) { var b = new Buffer(1); b.writeUInt8(showSignal ? 1 : 0, 0); msg.addOption(new Option(Message.Option.URI_PATH, new Buffer("s"))); msg.addOption(new Option(Message.Option.URI_QUERY, b)); return msg; }; }
javascript
{ "resource": "" }
q5005
pause
train
function pause (stream) { var events = [] var onData = createEventListener('data', events) var onEnd = createEventListener('end', events) // buffer data stream.on('data', onData) // buffer end stream.on('end', onEnd) return { end: function end () { stream.removeListener('data', onData) stream.removeListener('end', onEnd) }, resume: function resume () { this.end() for (var i = 0; i < events.length; i++) { stream.emit.apply(stream, events[i]) } } } }
javascript
{ "resource": "" }
q5006
train
function (data) { var that = this; if (!data) { if (this._socketTimeout) { clearTimeout(this._socketTimeout); //just in case } //waiting on data. //logger.log("server: waiting on hello"); this._socketTimeout = setTimeout(function () { that.handshakeFail("get_hello timed out"); }, 30 * 1000); return; } clearTimeout(this._socketTimeout); var env = this.client.parseMessage(data); var msg = (env && env.hello) ? env.hello : env; if (!msg) { this.handshakeFail("failed to parse hello"); return; } this.client.recvCounter = msg.getId(); //logger.log("server: got a good hello! Counter was: " + msg.getId()); try { if (msg.getPayload) { var payload = msg.getPayload(); if (payload.length > 0) { var r = new buffers.BufferReader(payload); this.client.spark_product_id = r.shiftUInt16(); this.client.product_firmware_version = r.shiftUInt16(); //logger.log('version of core firmware is ', this.client.spark_product_id, this.client.product_firmware_version); } } else { logger.log('msg object had no getPayload fn'); } } catch (ex) { logger.log('error while parsing hello payload ', ex); } // //remind ourselves later that this key worked. // if (that.corePublicKeyWasUncertain) { // process.nextTick(function () { // try { // //set preferred key for device // //that.coreFullPublicKeyObject // } // catch (ex) { // logger.error("error marking key as valid " + ex); // } // }); // } this.stage++; this.nextStep(); }
javascript
{ "resource": "" }
q5007
train
function () { //client will set the counter property on the message //logger.log("server: send hello"); this.client.secureOut = this.secureOut; this.client.sendCounter = CryptoLib.getRandomUINT16(); this.client.sendMessage("Hello", {}, null, null); this.stage++; this.nextStep(); }
javascript
{ "resource": "" }
q5008
train
function () { var that = this; this.socket.setNoDelay(true); this.socket.setKeepAlive(true, 15 * 1000); //every 15 second(s) this.socket.on('error', function (err) { that.disconnect("socket error " + err); }); this.socket.on('close', function (err) { that.disconnect("socket close " + err); }); this.socket.on('timeout', function (err) { that.disconnect("socket timeout " + err); }); this.handshake(); }
javascript
{ "resource": "" }
q5009
train
function (data) { var msg = messages.unwrap(data); if (!msg) { logger.error("routeMessage got a NULL coap message ", { coreID: this.getHexCoreID() }); return; } this._lastMessageTime = new Date(); //should be adequate var msgCode = msg.getCode(); if ((msgCode > Message.Code.EMPTY) && (msgCode <= Message.Code.DELETE)) { //probably a request msg._type = messages.getRequestType(msg); } if (!msg._type) { msg._type = this.getResponseType(msg.getTokenString()); } //console.log("core got message of type " + msg._type + " with token " + msg.getTokenString() + " " + messages.getRequestType(msg)); if (msg.isAcknowledgement()) { if (!msg._type) { //no type, can't route it. msg._type = 'PingAck'; } this.emit(('msg_' + msg._type).toLowerCase(), msg); return; } var nextPeerCounter = ++this.recvCounter; if (nextPeerCounter > 65535) { //TODO: clean me up! (I need settings, and maybe belong elsewhere) this.recvCounter = nextPeerCounter = 0; } if (msg.isEmpty() && msg.isConfirmable()) { this._lastCorePing = new Date(); //var delta = (this._lastCorePing - this._connStartTime) / 1000.0; //logger.log("core ping @ ", delta, " seconds ", { coreID: this.getHexCoreID() }); this.sendReply("PingAck", msg.getId()); return; } if (!msg || (msg.getId() != nextPeerCounter)) { logger.log("got counter ", msg.getId(), " expecting ", nextPeerCounter, { coreID: this.getHexCoreID() }); if (msg._type == "Ignored") { //don't ignore an ignore... this.disconnect("Got an Ignore"); return; } //this.sendMessage("Ignored", null, {}, null, null); this.disconnect("Bad Counter"); return; } this.emit(('msg_' + msg._type).toLowerCase(), msg); }
javascript
{ "resource": "" }
q5010
train
function (name, uri, token, callback, once) { var tokenHex = (token) ? utilities.toHexString(token) : null; var beVerbose = settings.showVerboseCoreLogs; //TODO: failWatch? What kind of timeout do we want here? //adds a one time event var that = this, evtName = ('msg_' + name).toLowerCase(), handler = function (msg) { if (uri && (msg.getUriPath().indexOf(uri) != 0)) { if (beVerbose) { logger.log("uri filter did not match", uri, msg.getUriPath(), { coreID: that.getHexCoreID() }); } return; } if (tokenHex && (tokenHex != msg.getTokenString())) { if (beVerbose) { logger.log("Tokens did not match ", tokenHex, msg.getTokenString(), { coreID: that.getHexCoreID() }); } return; } if (once) { that.removeListener(evtName, handler); } process.nextTick(function () { try { if (beVerbose) { logger.log('heard ', name, { coreID: that.coreID }); } callback(msg); } catch (ex) { logger.error("listenFor - caught error: ", ex, ex.stack, { coreID: that.getHexCoreID() }); } }); }; //logger.log('listening for ', evtName); this.on(evtName, handler); return handler; }
javascript
{ "resource": "" }
q5011
train
function (name, type, callback) { var that = this; var performRequest = function () { if (!that.HasSparkVariable(name)) { callback(null, null, "Variable not found"); return; } var token = this.sendMessage("VariableRequest", { name: name }); var varTransformer = this.transformVariableGenerator(name, callback); this.listenFor("VariableValue", null, token, varTransformer, true); }.bind(this); if (this.hasFnState()) { //slight short-circuit, saves ~5 seconds every 100,000 requests... performRequest(); } else { when(this.ensureWeHaveIntrospectionData()) .then( performRequest, function (err) { callback(null, null, "Problem requesting variable: " + err); }); } }
javascript
{ "resource": "" }
q5012
train
function (showSignal, callback) { var timer = setTimeout(function () { callback(false); }, 30 * 1000); //TODO: that.stopListeningFor("RaiseYourHandReturn", listenHandler); //TODO: var listenHandler = this.listenFor("RaiseYourHandReturn", ... ); //logger.log("RaiseYourHand: asking core to signal? " + showSignal); var token = this.sendMessage("RaiseYourHand", { _writeCoapUri: messages.raiseYourHandUrlGenerator(showSignal) }, null); this.listenFor("RaiseYourHandReturn", null, token, function () { clearTimeout(timer); callback(true); }, true); }
javascript
{ "resource": "" }
q5013
train
function (name, args) { var ready = when.defer(); var that = this; when(this.ensureWeHaveIntrospectionData()).then( function () { var buf = that._transformArguments(name, args); if (buf) { ready.resolve(buf); } else { //NOTE! The API looks for "Unknown Function" in the error response. ready.reject("Unknown Function: " + name); } }, function (msg) { ready.reject(msg); } ); return ready.promise; }
javascript
{ "resource": "" }
q5014
train
function (name, msg, callback) { var varType = "int32"; //if the core doesn't specify, assume it's a "uint32" //var fnState = (this.coreFnState) ? this.coreFnState.f : null; //if (fnState && fnState[name] && fnState[name].returns) { // varType = fnState[name].returns; //} var niceResult = null; try { if (msg && msg.getPayload) { niceResult = messages.FromBinary(msg.getPayload(), varType); } } catch (ex) { logger.error("transformFunctionResult - error transforming response " + ex); } process.nextTick(function () { try { callback(niceResult); } catch (ex) { logger.error("transformFunctionResult - error in callback " + ex); } }); return null; }
javascript
{ "resource": "" }
q5015
train
function (name, args) { //logger.log('transform args', { coreID: this.getHexCoreID() }); if (!args) { return null; } if (!this.hasFnState()) { logger.error("_transformArguments called without any function state!", { coreID: this.getHexCoreID() }); return null; } //TODO: lowercase function keys on new state format name = name.toLowerCase(); var fn = this.coreFnState[name]; if (!fn || !fn.args) { //maybe it's the old protocol? var f = this.coreFnState.f; if (f && utilities.arrayContainsLower(f, name)) { //logger.log("_transformArguments - using old format", { coreID: this.getHexCoreID() }); //current / simplified function format (one string arg, int return type) fn = { returns: "int", args: [ [null, "string" ] ] }; } } if (!fn || !fn.args) { //logger.error("_transformArguments: core doesn't know fn: ", { coreID: this.getHexCoreID(), name: name, state: this.coreFnState }); return null; } // "HelloWorld": { returns: "string", args: [ {"name": "string"}, {"adjective": "string"} ]} }; return messages.buildArguments(args, fn.args); }
javascript
{ "resource": "" }
q5016
train
function () { if (this.hasFnState()) { return when.resolve(); } //if we don't have a message pending, send one. if (!this._describeDfd) { this.sendMessage("Describe"); this._describeDfd = when.defer(); } //let everybody else queue up on this promise return this._describeDfd.promise; }
javascript
{ "resource": "" }
q5017
train
function(msg) { //got a description, is it any good? var loaded = (this.loadFnState(msg.getPayload())); if (this._describeDfd) { if (loaded) { this._describeDfd.resolve(); } else { this._describeDfd.reject("something went wrong parsing function state") } } //else { //hmm, unsolicited response, that's okay. } }
javascript
{ "resource": "" }
q5018
train
function(msg) { //moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch). var stamp = moment().utc().unix(); var binVal = messages.ToBinary(stamp, "uint32"); this.sendReply("GetTimeReturn", msg.getId(), binVal, msg.getToken()); }
javascript
{ "resource": "" }
q5019
train
function (isPublic, name, data, ttl, published_at, coreid) { var rawFn = function (msg) { try { msg.setMaxAge(parseInt((ttl && (ttl >= 0)) ? ttl : 60)); if (published_at) { msg.setTimestamp(moment(published_at).toDate()); } } catch (ex) { logger.error("onCoreHeard - " + ex); } return msg; }; var msgName = (isPublic) ? "PublicEvent" : "PrivateEvent"; var userID = (this.userID || "").toLowerCase() + "/"; name = (name) ? name.toString() : name; if (name && name.indexOf && (name.indexOf(userID) == 0)) { name = name.substring(userID.length); } data = (data) ? data.toString() : data; this.sendNONTypeMessage(msgName, { event_name: name, _raw: rawFn }, data); }
javascript
{ "resource": "" }
q5020
train
function() { if (this._chunkReceivedHandler) { this.client.removeListener("ChunkReceived", this._chunkReceivedHandler); } this._chunkReceivedHandler = null; // logger.log("HERE - _waitForMissedChunks done waiting! ", this.getLogInfo()); this.clearWatch("CompleteTransfer"); this.stage = Flasher.stages.TEARDOWN; this.nextStep(); }
javascript
{ "resource": "" }
q5021
train
function (name, seconds, callback) { if (!this._timers) { this._timers = {}; } if (!seconds) { clearTimeout(this._timers[name]); delete this._timers[name]; } else { this._timers[name] = setTimeout(function () { //logger.error("Flasher failWatch failed waiting on " + name); if (callback) { callback("failed waiting on " + name); } }, seconds * 1000); } }
javascript
{ "resource": "" }
q5022
train
function (fn, scope) { return function () { try { return fn.apply(scope, arguments); } catch (ex) { logger.error(ex); logger.error(ex.stack); logger.log('error bubbled up ' + ex); } }; }
javascript
{ "resource": "" }
q5023
train
function (left, right) { if (!left && !right) { return true; } var matches = true; for (var prop in right) { if (!right.hasOwnProperty(prop)) { continue; } matches &= (left[prop] == right[prop]); } return matches; }
javascript
{ "resource": "" }
q5024
train
function (dir, search, excludedDirs) { excludedDirs = excludedDirs || []; var result = []; var files = fs.readdirSync(dir); for (var i = 0; i < files.length; i++) { var fullpath = path.join(dir, files[i]); var stat = fs.statSync(fullpath); if (stat.isDirectory() && (!excludedDirs.contains(fullpath))) { result = result.concat(utilities.recursiveFindFiles(fullpath, search)); } else if (!search || (fullpath.indexOf(search) >= 0)) { result.push(fullpath); } } return result; }
javascript
{ "resource": "" }
q5025
train
function (arr, handler) { var tmp = when.defer(); var index = -1; var results = []; var doNext = function () { try { index++; if (index > arr.length) { tmp.resolve(results); } var file = arr[index]; var promise = handler(file); if (promise) { when(promise).then(function (result) { results.push(result); process.nextTick(doNext); }, function () { process.nextTick(doNext); }); // when(promise).ensure(function () { // process.nextTick(doNext); // }); } else { //logger.log('skipping bad promise'); process.nextTick(doNext); } } catch (ex) { logger.error("pdas error: " + ex); } }; process.nextTick(doNext); return tmp.promise; }
javascript
{ "resource": "" }
q5026
train
function(a, b) { var keys = Object.keys(b) , i = 0 , l = keys.length , val; for (; i < l; i++) { val = b[keys[i]]; if (has(a, val)) return true; } return false; }
javascript
{ "resource": "" }
q5027
train
function(a, b) { var found = 0 , keys = Object.keys(b) , i = 0 , l = keys.length , val; for (; i < l; i++) { val = b[keys[i]]; if (has(a, val)) found++; } return found === l; }
javascript
{ "resource": "" }
q5028
getAttributes
train
function getAttributes(tag) { let running = true; const attributes = []; const regexp = /(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/g; while (running) { const match = regexp.exec(tag); if (match) { attributes.push({ key: match[1], value: match[2] }) } else { running = false; } } return attributes; }
javascript
{ "resource": "" }
q5029
getPartial
train
function getPartial(attributes) { const splitAttr = partition(attributes, (attribute) => attribute.key === 'src'); const sourcePath = splitAttr[0][0] && splitAttr[0][0].value; let file; if (sourcePath && fs.existsSync(options.basePath + sourcePath)) { file = injectHTML(fs.readFileSync(options.basePath + sourcePath)) } else if (!sourcePath) { gutil.log(`${pluginName}:`, new gutil.PluginError(pluginName, gutil.colors.red(`Some partial does not have 'src' attribute`)).message); } else { gutil.log(`${pluginName}:`, new gutil.PluginError(pluginName, gutil.colors.red(`File ${options.basePath + sourcePath} does not exist.`)).message); } return replaceAttributes(file, splitAttr[1]); }
javascript
{ "resource": "" }
q5030
replaceAttributes
train
function replaceAttributes(file, attributes) { return (attributes || []).reduce((html, attrObj) => html.replace(options.variablePrefix + attrObj.key, attrObj.value), file && file.toString() || ''); }
javascript
{ "resource": "" }
q5031
getPagesConfig
train
function getPagesConfig(entry) { const pages = {} // 规范中定义每个单页文件结构 // index.html,main.js,App.vue glob.sync(PAGE_PATH + '/*/main.js') .forEach(filePath => { const pageName = path.basename(path.dirname(filePath)) if (entry && entry !== pageName) return pages[pageName] = { entry: filePath, // 除了首页,其他按第二级目录输出 // 浏览器中直接访问/news,省去/news.html fileName: `${pageName === 'index' ? '' : pageName + '/'}index.html`, template: path.dirname(filePath) + '/index.html', chunks: ['vue-common', 'iview', 'echarts', 'vendors', 'manifest', pageName] } }) return pages }
javascript
{ "resource": "" }
q5032
getHandler
train
function getHandler (method, getArgs, trans, domain = 'feathers') { return function (req, res, next) { res.setHeader('Allow', Object.values(allowedMethods).join(',')); let params = Object.assign({}, req.params || {}); delete params.service; delete params.id; delete params.subresources; delete params[0]; req.feathers = { provider: 'rest' }; // Grab the service parameters. Use req.feathers and set the query to req.query let query = req.query || {}; let headers = fp.dissoc('cookie', req.headers || {}); let cookies = req.cookies || {}; params = Object.assign({ query, headers }, params, req.feathers); // Transfer the received file if (req.file) { params.file = req.file; } // method override if ((method === 'update' || method === 'patch') && params.query.$method && params.query.$method.toLowerCase() === 'patch') { method = 'patch' delete params.query.$method } // Run the getArgs callback, if available, for additional parameters const [service, ...args] = getArgs(req, res, next); debug(`REST handler calling service \'${service}\'`, { cmd: method, path: req.path, //args: args, //params: params, //feathers: req.feathers }); // The service success callback which sets res.data or calls next() with the error const callback = function (err, data) { debug(`${service}.${method} response:`, err || { status: data && data.status, size: data && JSON.stringify(data).length }); if (err) return next(err.cause || err); res.data = data; if (!data) { debug(`No content returned for '${req.url}'`); res.status(statusCodes.noContent); } else if (method === 'create') { res.status(statusCodes.created); } return next(); }; trans.act({ topic: `${domain}.${service}`, cmd: method, path: req.path, args: args, params: params, feathers: req.feathers }, callback); }; }
javascript
{ "resource": "" }
q5033
info
train
function info (cb) { var data = { name: pjson.name, message: 'pong', version: pjson.version, node_env: process.env.NODE_ENV, node_ver: process.versions.node, timestamp: Date.now(), hostname: os.hostname(), uptime: process.uptime(), loadavg: os.loadavg()[0] }; cb(null, data); }
javascript
{ "resource": "" }
q5034
parseCaseStatements
train
function parseCaseStatements (spec) { return _(spec) .remove(statement => !_.isUndefined(statement.case)) .map(parseCaseStatement) .value() }
javascript
{ "resource": "" }
q5035
create
train
function create (spec) { const accumulator = new Accumulator() accumulator.value = spec.value accumulator.context = spec.context accumulator.reducer = { spec: spec.context } accumulator.entityOverrides = merge({}, spec.entityOverrides) accumulator.locals = merge({}, spec.locals) accumulator.values = spec.values accumulator.trace = spec.trace accumulator.debug = debug return accumulator }
javascript
{ "resource": "" }
q5036
calculateCountOfReplacementChar
train
function calculateCountOfReplacementChar(string, replaceByChar = ' ') { var characters = 0 string .split('') .forEach(char => { var size = charSizes.get(char) || 1 characters += size }) // All sizes were measured against space char. Recalculate if needed. if (replaceByChar !== ' ') characters = characters / charSizes.get(replaceByChar) return Math.round(characters) }
javascript
{ "resource": "" }
q5037
sanitizeLines
train
function sanitizeLines(frame) { // Sanitize newlines & replace tabs. lines = stripAnsi(frame) .replace(/\r/g, '') .split('\n') .map(l => l.replace(/\t/g, ' ')) // Remove left caret. var leftCaretLine = lines.find(l => l.startsWith('>')) if (leftCaretLine) { lines[lines.indexOf(leftCaretLine)] = leftCaretLine.replace('>', ' ') } // Remove left padding. // Loop while all lines start with space and strip the space from all lines. while (lines.find(l => !l.startsWith(' ')) == undefined) { lines = lines.map(l => l.slice(1)) } return lines }
javascript
{ "resource": "" }
q5038
extractMessage
train
function extractMessage(error) { var {message} = error if (error.plugin === 'babel') { // Hey Babel, you're not helping! var filepath = error.id var message = error.message function stripFilePath() { var index = message.indexOf(filepath) console.log(index, filepath.length) message = message.slice(0, index) + message.slice(filepath.length + 1) message = message.trim() } if (message.includes(filepath)) { stripFilePath() } else { filepath = filepath.replace(/\\/g, '/') if (message.includes(filepath)) stripFilePath() } } return message }
javascript
{ "resource": "" }
q5039
readSync
train
function readSync(description, options) { var file = vfile(description) file.contents = fs.readFileSync(path.resolve(file.cwd, file.path), options) return file }
javascript
{ "resource": "" }
q5040
writeSync
train
function writeSync(description, options) { var file = vfile(description) fs.writeFileSync( path.resolve(file.cwd, file.path), file.contents || '', options ) }
javascript
{ "resource": "" }
q5041
set
train
function set (target, key, value) { const obj = {} obj[key] = value return Object.assign({}, target, obj) }
javascript
{ "resource": "" }
q5042
train
function (certparams) { var keys = forge.pki.rsa.generateKeyPair(2048); this.publicKey = keys.publicKey; this.privateKey = keys.privateKey; this.cert = this.createCertificate(certparams); this.keycred = null; this.digest = null; }
javascript
{ "resource": "" }
q5043
clear
train
function clear (store) { const forDeletion = [] const now = Date.now() for (const [key, entry] of store) { // mark for deletion entries that have timed out if (now - entry.created > entry.ttl) { forDeletion.push(key) } } const forDeletionLength = forDeletion.length // if nothing to clean then exit if (forDeletionLength === 0) { return 0 } debug(`local revalidation flags that timed out: ${forDeletion}`) forDeletion.forEach(key => store.delete(key)) return forDeletionLength }
javascript
{ "resource": "" }
q5044
exists
train
function exists (store, key) { const entry = store.get(key) // checks entry exists and it has not timed-out return !!entry && Date.now() - entry.created < entry.ttl }
javascript
{ "resource": "" }
q5045
assignParamsHelper
train
function assignParamsHelper (accumulator, entity) { if (accumulator.entityOverrides[entity.entityType]) { return merge( {}, entity.params, accumulator.entityOverrides[entity.entityType].params ) } return entity.params }
javascript
{ "resource": "" }
q5046
get
train
function get (manager, errorInfoCb, id) { const value = manager.store.get(id) if (_.isUndefined(value)) { const errorInfo = errorInfoCb(id) const e = new Error(errorInfo.message) e.name = errorInfo.name throw e } return value }
javascript
{ "resource": "" }
q5047
isRevalidatingCacheKey
train
function isRevalidatingCacheKey (ctx, currentEntryKey) { const revalidatingCache = ctx.locals.revalidatingCache return (revalidatingCache && revalidatingCache.entryKey) === currentEntryKey }
javascript
{ "resource": "" }
q5048
resolveStaleWhileRevalidateEntry
train
function resolveStaleWhileRevalidateEntry (service, entryKey, cache, ctx) { // NOTE: pulling through module.exports allows us to test if they were called const { resolveStaleWhileRevalidate, isRevalidatingCacheKey, shouldTriggerRevalidate, revalidateEntry } = module.exports // IMPORTANT: we only want to bypass an entity that is being revalidated and // that matches the same cache entry key, otherwise all child entities will // be needlesly resolved if (isRevalidatingCacheKey(ctx, entryKey)) { // bypass the rest forces entity to get resolved return undefined } const staleWhileRevalidate = resolveStaleWhileRevalidate(service) // cleanup on a new tick so it does not block current process, the clear // method is throttled for performance setTimeout(staleWhileRevalidate.invalidateLocalFlags, 0) const tasks = [ staleWhileRevalidate.getRevalidationState(entryKey), staleWhileRevalidate.getEntry(entryKey) ] return Promise.all(tasks).then(results => { const revalidationState = results[0] const staleEntry = results[1] if (shouldTriggerRevalidate(staleEntry, revalidationState)) { // IMPORTANT: revalidateEntry operates on a new thread revalidateEntry(service, entryKey, cache, ctx) } // Otherwise means its a cold start and must be resolved outside // return stale entry regardless return staleEntry }) }
javascript
{ "resource": "" }
q5049
train
function(a){ // Copy prototype properties. for(var b in a.prototype){var c=b.match(/^(.*?[A-Z]{2,})(.*)$/),d=j(b);null!==c&&(d=c[1]+j(c[2])),d!==b&&( // Add static methods as aliases. d in a||(a[d]=function(b){return function(){var c=new a;return c[b].apply(c,arguments)}}(b),l(a,d,b)), // Create `camelCase` aliases. d in a.prototype||l(a.prototype,b,d))}return a}
javascript
{ "resource": "" }
q5050
setSWRStaleEntry
train
function setSWRStaleEntry (service, key, value, ttl) { return setEntry(service, createSWRStaleKey(key), value, ttl) }
javascript
{ "resource": "" }
q5051
_getLocalPositionFromWorldPosition
train
function _getLocalPositionFromWorldPosition(transform) { if (transform.parent === undefined) return transform.position; else return transform.parent.rotation.inverse().mulVector3(transform.position.sub(transform.parent.position)); }
javascript
{ "resource": "" }
q5052
_getWorldPositionFromLocalPosition
train
function _getWorldPositionFromLocalPosition(transform) { if (transform.parent === undefined) return transform.localPosition; else return transform.parent.position.add(transform.parent.rotation.mulVector3(transform.localPosition)); }
javascript
{ "resource": "" }
q5053
_getLocalRotationFromWorldRotation
train
function _getLocalRotationFromWorldRotation(transform) { if(transform.parent === undefined) return transform.rotation; else return transform.parent.rotation.inverse().mul(transform.rotation); }
javascript
{ "resource": "" }
q5054
_getWorldRotationFromLocalRotation
train
function _getWorldRotationFromLocalRotation(transform) { if(transform.parent === undefined) return transform.localRotation; else return transform.parent.rotation.mul(transform.localRotation); }
javascript
{ "resource": "" }
q5055
_adjustChildren
train
function _adjustChildren(children) { children.forEach(function (child) { child.rotation = _getWorldRotationFromLocalRotation(child); child.position = _getWorldPositionFromLocalPosition(child); }); }
javascript
{ "resource": "" }
q5056
_getLocalToWorldMatrix
train
function _getLocalToWorldMatrix(transform) { return function() { return Matrix4x4.LocalToWorldMatrix(transform.position, transform.rotation, Vector3.one); } }
javascript
{ "resource": "" }
q5057
_getWorldtoLocalMatrix
train
function _getWorldtoLocalMatrix(transform) { return function() { return Matrix4x4.WorldToLocalMatrix(transform.position, transform.rotation, Vector3.one); } }
javascript
{ "resource": "" }
q5058
_getRoot
train
function _getRoot(transform) { return function() { var parent = transform.parent; return parent === undefined ? transform : parent.root; } }
javascript
{ "resource": "" }
q5059
disposeInactiveEntries
train
function disposeInactiveEntries( devMiddleware, entries, lastAccessPages, maxInactiveAge ) { const disposingPages = []; Object.keys(entries).forEach(page => { const { lastActiveTime, status } = entries[page]; // This means this entry is currently building or just added // We don't need to dispose those entries. if (status !== BUILT) return; // We should not build the last accessed page even we didn't get any pings // Sometimes, it's possible our XHR ping to wait before completing other requests. // In that case, we should not dispose the current viewing page if (lastAccessPages[0] === page) return; if (Date.now() - lastActiveTime > maxInactiveAge) { disposingPages.push(page); } }); if (disposingPages.length > 0) { disposingPages.forEach(page => { delete entries[page]; }); console.log(`> Disposing inactive page(s): ${disposingPages.join(', ')}`); devMiddleware.invalidate(); } }
javascript
{ "resource": "" }
q5060
resolveOptions
train
function resolveOptions (accumulator, resolveReducer) { const url = resolveUrl(accumulator) const specOptions = accumulator.reducer.spec.options return resolveReducer(accumulator, specOptions).then(acc => { const options = getRequestOptions(url, acc.value) return utils.assign(accumulator, { options }) }) }
javascript
{ "resource": "" }
q5061
train
function (p1x, p1y, p2x, p2y) { return Math.sqrt((p2x - p1x) * (p2x - p1x) + (p2y - p1y) * (p2y - p1y)); }
javascript
{ "resource": "" }
q5062
bootstrapAPI
train
function bootstrapAPI (cache) { cache.set = set.bind(null, cache) cache.get = get.bind(null, cache) cache.del = del.bind(null, cache) return cache }
javascript
{ "resource": "" }
q5063
_getRows
train
function _getRows(matrix) { var rows = []; for (var i=0; i<matrix.size.rows; i++) { rows.push([]); for (var j=0; j<matrix.size.columns; j++) rows[i].push(matrix.values[matrix.size.columns * i + j]); } return rows; }
javascript
{ "resource": "" }
q5064
_getColumns
train
function _getColumns(matrix) { var cols = []; for (var i=0; i<matrix.size.columns; i++) { cols.push([]); for (var j=0; j<matrix.size.rows; j++) cols[i].push(matrix.values[i + j * matrix.size.columns]); } return cols; }
javascript
{ "resource": "" }
q5065
_sizesMatch
train
function _sizesMatch(matrix1, matrix2) { return matrix1.size.rows == matrix2.size.rows && matrix1.size.columns == matrix2.size.columns; }
javascript
{ "resource": "" }
q5066
_fromVector
train
function _fromVector(vector) { return new _Vector4(vector.values[0], vector.values[1], vector.values[2], vector.values[3]); }
javascript
{ "resource": "" }
q5067
_normalizedCoordinates
train
function _normalizedCoordinates(x, y, z, w) { var magnitude = Math.sqrt(x * x + y * y + z * z + w * w); if (magnitude === 0) return this; return { "x": x / magnitude, "y": y / magnitude, "z": z / magnitude, "w": w / magnitude}; }
javascript
{ "resource": "" }
q5068
_fromAngleAxis
train
function _fromAngleAxis(axis, angle) { var s = Math.sin(angle/2); var c = Math.cos(angle/2); return new _Quaternion(axis.x * s, axis.y * s, axis.z * s, c); }
javascript
{ "resource": "" }
q5069
_getAngleAxis
train
function _getAngleAxis(quaternion) { return function() { var sqrt = Math.sqrt(1 - quaternion.w * quaternion.w); return { axis: new Vector3(quaternion.x / sqrt, quaternion.y / sqrt, quaternion.z / sqrt), angle: 2 * Math.acos(quaternion.w) * radToDeg }; } }
javascript
{ "resource": "" }
q5070
normalizeInput
train
function normalizeInput (source) { let result = ReducerList.parse(source) if (result.length === 1) { // do not create a ReducerList that only contains a single reducer result = result[0] } return result }
javascript
{ "resource": "" }
q5071
resolveReducer
train
function resolveReducer (manager, accumulator, reducer) { // this conditional is here because BaseEntity#resolve // does not check that lifecycle methods are defined // before trying to resolve them if (!reducer) { return Promise.resolve(accumulator) } const isTracing = accumulator.trace const acc = isTracing ? trace.augmentAccumulatorTrace(accumulator, reducer) : accumulator const traceNode = acc.traceNode const resolve = getResolveFunction(reducer) // NOTE: recursive call let result = resolve(manager, resolveReducer, acc, reducer) if (hasDefault(reducer)) { const _default = reducer[DEFAULT_VALUE].value const resolveDefault = reducers.ReducerDefault.resolve result = result.then(acc => resolveDefault(acc, _default)) } if (isTracing) { result = result.then(trace.augmentTraceNodeDuration(traceNode)) } return result }
javascript
{ "resource": "" }
q5072
_magnitudeOf
train
function _magnitudeOf(values) { var result = 0; for (var i = 0; i < values.length; i++) result += values[i] * values[i]; return Math.sqrt(result); }
javascript
{ "resource": "" }
q5073
augmentAccumulatorTrace
train
function augmentAccumulatorTrace (accumulator, reducer) { const acc = module.exports.createTracedAccumulator(accumulator, reducer) acc.traceGraph.push(acc.traceNode) return acc }
javascript
{ "resource": "" }
q5074
read
train
function read(description, options, callback) { var file = vfile(description) if (!callback && typeof options === 'function') { callback = options options = null } if (!callback) { return new Promise(executor) } executor(resolve, callback) function resolve(result) { callback(null, result) } function executor(resolve, reject) { var fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.readFile(fp, options, done) function done(error, res) { if (error) { reject(error) } else { file.contents = res resolve(file) } } } }
javascript
{ "resource": "" }
q5075
write
train
function write(description, options, callback) { var file = vfile(description) // Weird, right? Otherwise `fs` doesn’t accept it. if (!callback && typeof options === 'function') { callback = options options = undefined } if (!callback) { return new Promise(executor) } executor(resolve, callback) function resolve(result) { callback(null, result) } function executor(resolve, reject) { var fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.writeFile(fp, file.contents || '', options, done) function done(error) { if (error) { reject(error) } else { resolve() } } } }
javascript
{ "resource": "" }
q5076
warnLooseParamsCacheDeprecation
train
function warnLooseParamsCacheDeprecation (params) { if (params.ttl || params.cacheKey || params.staleWhileRevalidate) { module.exports.looseCacheParamsDeprecationWarning() } }
javascript
{ "resource": "" }
q5077
_shutdownNextServices
train
async function _shutdownNextServices(reversedServiceSequence) { if (0 === reversedServiceSequence.length) { return; } await Promise.all( reversedServiceSequence.pop().map(async serviceName => { const singletonServiceDescriptor = await _this._pickupSingletonServiceDescriptorPromise( serviceName, ); const serviceDescriptor = singletonServiceDescriptor || (await siloContext.servicesDescriptors.get(serviceName)); let serviceShutdownPromise = _this._singletonsServicesShutdownsPromises.get(serviceName) || siloContext.servicesShutdownsPromises.get(serviceName); if (serviceShutdownPromise) { debug('Reusing a service shutdown promise:', serviceName); return serviceShutdownPromise; } if ( reversedServiceSequence.some(servicesDeclarations => servicesDeclarations.includes(serviceName), ) ) { debug('Delaying service shutdown:', serviceName); return Promise.resolve(); } if (singletonServiceDescriptor) { const handleSet = _this._singletonsServicesHandles.get( serviceName, ); handleSet.delete(siloContext.name); if (handleSet.size) { debug('Singleton is used elsewhere:', serviceName, handleSet); return Promise.resolve(); } _this._singletonsServicesDescriptors.delete(serviceName); } debug('Shutting down a service:', serviceName); serviceShutdownPromise = serviceDescriptor.dispose ? serviceDescriptor.dispose() : Promise.resolve(); if (singletonServiceDescriptor) { _this._singletonsServicesShutdownsPromises.set( serviceName, serviceShutdownPromise, ); } siloContext.servicesShutdownsPromises.set( serviceName, serviceShutdownPromise, ); return serviceShutdownPromise; }), ); await _shutdownNextServices(reversedServiceSequence); }
javascript
{ "resource": "" }
q5078
List
train
function List(options) { if (!(this instanceof List)) { return new List(options); } Base.call(this); this.is('list'); this.define('isCollection', true); this.use(utils.option()); this.use(utils.plugin()); this.init(options || {}); }
javascript
{ "resource": "" }
q5079
decorate
train
function decorate(list, method, prop) { utils.define(list.items, method, function() { var res = list[method].apply(list, arguments); return prop ? res[prop] : res; }); }
javascript
{ "resource": "" }
q5080
handleLayout
train
function handleLayout(obj, stats, depth) { var layoutName = obj.layout.basename; debug('applied layout (#%d) "%s", to file "%s"', depth, layoutName, file.path); file.currentLayout = obj.layout; file.define('layoutStack', stats.history); app.handleOnce('onLayout', file); delete file.currentLayout; }
javascript
{ "resource": "" }
q5081
buildStack
train
function buildStack(app, name, view) { var layoutExists = false; var registered = 0; var layouts = {}; // get all collections with `viewType` layout var collections = app.viewTypes.layout; var len = collections.length; var idx = -1; while (++idx < len) { var collection = app[collections[idx]]; // detect if at least one of the collections has // our starting layout if (!layoutExists && collection.getView(name)) { layoutExists = true; } // add the collection views to the layouts object for (var key in collection.views) { layouts[key] = collection.views[key]; registered++; } } if (registered === 0) { throw app.formatError('layouts', 'registered', name, view); } if (layoutExists === false) { throw app.formatError('layouts', 'notfound', name, view); } return layouts; }
javascript
{ "resource": "" }
q5082
Collection
train
function Collection(options) { if (!(this instanceof Collection)) { return new Collection(options); } Base.call(this, {}, options); this.is('Collection'); this.items = {}; this.use(utils.option()); this.use(utils.plugin()); this.init(options || {}); }
javascript
{ "resource": "" }
q5083
Templates
train
function Templates(options) { if (!(this instanceof Templates)) { return new Templates(options); } Base.call(this, null, options); this.is('templates'); this.define('isApp', true); this.use(utils.option()); this.use(utils.plugin()); this.initTemplates(); }
javascript
{ "resource": "" }
q5084
setHelperOptions
train
function setHelperOptions(context, key) { var optsHelper = context.options.helper || {}; if (optsHelper.hasOwnProperty(key)) { context.helper.options = optsHelper[key]; } }
javascript
{ "resource": "" }
q5085
Context
train
function Context(app, view, context, helpers) { this.helper = {}; this.helper.options = createHelperOptions(app, view, helpers); this.context = context; utils.define(this.context, 'view', view); this.options = utils.merge({}, app.options, view.options, this.helper.options); // make `this.options.handled` non-enumberable utils.define(this.options, 'handled', this.options.handled); decorate(this.context); decorate(this.options); decorate(this); this.view = view; this.app = app; this.ctx = function() { return helperContext.apply(this, arguments); }; }
javascript
{ "resource": "" }
q5086
decorate
train
function decorate(obj) { utils.define(obj, 'merge', function() { var args = [].concat.apply([], [].slice.call(arguments)); var len = args.length; var idx = -1; while (++idx < len) { var val = args[idx]; if (!utils.isObject(val)) continue; if (val.hasOwnProperty('hash')) { // shallow clone and delete the `data` object val = utils.merge({}, val, val.hash); delete val.data; } utils.merge(obj, val); } // ensure methods aren't overwritten decorate(obj); if (obj.hasOwnProperty('app') && obj.hasOwnProperty('options')) { decorate(obj.options); } return obj; }); utils.define(obj, 'get', function(prop) { return utils.get(obj, prop); }); utils.define(obj, 'set', function(key, val) { return utils.set(obj, key, val); }); }
javascript
{ "resource": "" }
q5087
mergePartials
train
function mergePartials(options) { var opts = utils.merge({}, this.options, options); var names = opts.mergeTypes || this.viewTypes.partial; var partials = {}; var self = this; names.forEach(function(name) { var collection = self.views[name]; for (var key in collection) { var view = collection[key]; // handle `onMerge` middleware self.handleOnce('onMerge', view, function(err, res) { if (err) throw err; view = res; }); if (view.options.nomerge) continue; if (opts.mergePartials !== false) { name = 'partials'; } // convert the partial to: //=> {'foo.hbs': 'some content...'}; partials[name] = partials[name] || {}; partials[name][key] = view.content; } }); return partials; }
javascript
{ "resource": "" }
q5088
FixEncryptLength
train
function FixEncryptLength(text) { var len = text.length; var stdLens = [256, 512, 1024, 2048, 4096]; var stdLen, i, j; for (i = 0; i < stdLens.length; i++) { stdLen = stdLens[i]; if (len === stdLen) { return text; } else if (len < stdLen) { var times = stdLen - len; var preText = ''; for (j = 0; j < times; j++) { preText += '0'; } return preText + text; } } return text; }
javascript
{ "resource": "" }
q5089
Group
train
function Group(config) { if (!(this instanceof Group)) { return new Group(config); } Base.call(this, config); this.is('Group'); this.use(utils.option()); this.use(utils.plugin()); this.init(); }
javascript
{ "resource": "" }
q5090
handleErrors
train
function handleErrors(group, val) { if (utils.isObject(val)) { var List = group.List; var keys = Object.keys(List.prototype); keys.forEach(function(key) { if (typeof val[key] !== 'undefined') return; utils.define(val, key, function() { throw new Error(key + ' can only be used with an array of `List` items.'); }); }); } }
javascript
{ "resource": "" }
q5091
objectFactory
train
function objectFactory(data) { // if we are given an object Object, no-op and return it now. if (_.isPlainObject(data)) { return data; } // If we are given a byte Buffer, parse it as utf-8 if (data instanceof Buffer) { data = data.toString('utf-8'); } // If we now have a string, then assume it is a JSON string. if (_.isString(data)) { data = JSON.parse(data); } else { throw new Error( 'Could not convert data into an object. ' + 'Data must be a utf-8 byte buffer or a JSON string' ); } return data; }
javascript
{ "resource": "" }
q5092
createKafkaConsumerAsync
train
function createKafkaConsumerAsync(kafkaConfig) { let topicConfig = {}; if ('default_topic_config' in kafkaConfig) { topicConfig = kafkaConfig.default_topic_config; delete kafkaConfig.default_topic_config; } const consumer = P.promisifyAll( new kafka.KafkaConsumer(kafkaConfig, topicConfig) ); return consumer.connectAsync(undefined) .thenReturn(consumer); }
javascript
{ "resource": "" }
q5093
getAvailableTopics
train
function getAvailableTopics(topicsInfo, allowedTopics) { const existentTopics = topicsInfo.map( e => e.name ) .filter(t => t !== '__consumer_offsets'); if (allowedTopics) { return existentTopics.filter(t => _.includes(allowedTopics, t)); } else { return existentTopics; } }
javascript
{ "resource": "" }
q5094
assignmentsForTimesAsync
train
function assignmentsForTimesAsync(kafkaConsumer, assignments) { const assignmentsWithTimestamps = assignments.filter(a => 'timestamp' in a && !('offset' in a)).map((a) => { return {topic: a.topic, partition: a.partition, offset: a.timestamp }; }); // If there were no timestamps to resolve, just return assignments as is. if (assignmentsWithTimestamps.length == 0) { return new P((resolve, reject) => resolve(assignments)); } // Else resolve all timestamp assignments to offsets. else { // Get offsets for the timestamp based assignments. // If no offset was found for any timestamp, this will return -1, which // we can use for offset: -1 as end of partition. return kafkaConsumer.offsetsForTimesAsync(assignmentsWithTimestamps) .then(offsetsForTimes => { // console.log({ withTimestamps: assignmentsWithTimestamps, got: offsetsForTimes}, 'got offsets for times'); // merge offsetsForTimes with any non-timestamp based assignments. // This merged object will only have assignments with offsets specified, no timestamps. return _.flatten([ assignments.filter(a => !('timestamp' in a) && 'offset' in a), offsetsForTimes ]); }) } }
javascript
{ "resource": "" }
q5095
deserializeKafkaMessage
train
function deserializeKafkaMessage(kafkaMessage) { kafkaMessage.message = objectFactory(kafkaMessage.value); kafkaMessage.message._kafka = { topic: kafkaMessage.topic, partition: kafkaMessage.partition, offset: kafkaMessage.offset, timestamp: kafkaMessage.timestamp || null, key: kafkaMessage.key, }; return kafkaMessage; }
javascript
{ "resource": "" }
q5096
findView
train
function findView(app, name) { var keys = app.viewTypes.renderable; var len = keys.length; var i = -1; var res = null; while (++i < len) { res = app.find(name, keys[i]); if (res) { break; } } return res; }
javascript
{ "resource": "" }
q5097
getView
train
function getView(app, view) { if (typeof view !== 'string') { return view; } if (app.isCollection) { view = app.getView(view); } else if (app.isList) { view = app.getItem(view); } else { view = findView(app, view); } return view; }
javascript
{ "resource": "" }
q5098
Generator
train
function Generator (fn, opts) { if (fn instanceof Function) { if (typeof opts === 'number') { opts = {duration: opts}; } else { opts = opts || {}; } opts.generate = fn; } else { opts = fn || {}; } //sort out arguments opts = extend({ //total duration of a stream duration: Infinity, //time repeat period, in seconds, or 1/frequency period: Infinity, //inferred from period //frequency: 0, /** * Generate sample value for a time. * Returns [L, R, ...] or a number for each channel * * @param {number} time current time */ generate: Math.random }, pcm.defaults, opts); //align frequency/period if (opts.frequency != null) { opts.period = 1 / opts.frequency; } else { opts.frequency = 1 / opts.period; } let time = 0, count = 0; return generate; //return sync source/map function generate (buffer) { if (!buffer) buffer = util.create(opts.samplesPerFrame, opts.channels, opts.sampleRate); //get audio buffer channels data in array var data = util.data(buffer); //enough? if (time + buffer.length / opts.sampleRate > opts.duration) return null; //generate [channeled] samples for (var i = 0; i < buffer.length; i++) { var moment = time + i / opts.sampleRate; //rotate by period if (opts.period !== Infinity) { moment %= opts.period; } var gen = opts.generate(moment); //treat null as end if (gen === null) { return gen; } //wrap number value if (!Array.isArray(gen)) { gen = [gen || 0]; } //distribute generated data by channels for (var channel = 0; channel < buffer.numberOfChannels; channel++) { data[channel][i] = (gen[channel] == null ? gen[0] : gen[channel]); } } //update counters count += buffer.length; time = count / opts.sampleRate; return buffer; } }
javascript
{ "resource": "" }
q5099
deserializeQueryParam
train
function deserializeQueryParam(param) { if (!!param && (typeof param === 'object')) { if (param.__type === 'Date') { return new Date(param.iso); } } return param; }
javascript
{ "resource": "" }