_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q48500
createTableLayout
train
function createTableLayout(){ var tableItem = { type: 'component', componentName: 'Table' }; var stackItem = myLayout.root.getItemsById('stack-topleft')[0]; stackItem.addChild(tableItem); // get focus on the search tab stackItem.setActiveContentItem(myLayout.root.getItemsById('node-list')[0]); globalFunc.initTable(); }
javascript
{ "resource": "" }
q48501
initJQueryEvents
train
function initJQueryEvents(){ $('#searchDiv').parent().scroll(function() { if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight - 100) { globalFunc.addNodesInList(); } }); $('#toggleLayout').click(function() { toggleLayout(); }); $("#sliderText").html("Context with <strong>2</strong> hops"); $("#slider").slider({ range: "max", min: 0, max: 10, value: 2, slide: function (event, ui){ var strHops = " hop"; if (ui.value > 1){ strHops = " hops"; } $("#sliderText").html("Context with <strong>" + ui.value + "</strong>" + strHops); NB_HOPS = ui.value; } }); }
javascript
{ "resource": "" }
q48502
panToNode
train
function panToNode(node) { var pos = layout.getNodePosition(node._id); renderer.moveTo(pos.x, pos.y); highlightNodeWebGL(node); }
javascript
{ "resource": "" }
q48503
highlightNodeWebGL
train
function highlightNodeWebGL(node) { var ui = graphics.getNodeUI(node._id); if (prevNodeUI){ prevNodeUI.size = NODE_SIZE; //prevNodeUI.color = hexColorToWebGLColor(colorsByNodeType[node._type]); } prevNodeUI = ui; ui.size = NODE_SIZE * 4; //ui.color = 0xFFA500FF; //orange if (isPaused){ renderer.rerender(); } }
javascript
{ "resource": "" }
q48504
addToGlobalNodes
train
function addToGlobalNodes(node){ var nodeToAdd = { "_id": node.id(), "_world": node.world(), "_time": node.time(), "_type": (node.nodeTypeName() ? node.nodeTypeName() : "default") }; var containsRel = false; // add all the attributes of the node to the JSON graph.resolver().resolveState(node, false).each(function (attributeKey, elemType, elem) { var key = graph.resolver().hashToString(attributeKey); if(elemType == org.mwg.Type.BOOL || elemType == org.mwg.Type.STRING || elemType == org.mwg.Type.INT || elemType == org.mwg.Type.LONG || elemType == org.mwg.Type.DOUBLE) { //primitive types nodeToAdd[key] = elem; } else if(elemType == org.mwg.Type.RELATION) { //classic relation nodeToAdd[key] = []; for (var i = 0; i < elem.size(); ++i){ nodeToAdd[key].push(elem.get(i)); } containsRel = true; } else if(elemType == org.mwg.Type.LONG_TO_LONG_ARRAY_MAP) { //indexed relation nodeToAdd[key] = []; elem.each(function(relKey,relIdNode) { nodeToAdd[key].push(relIdNode); }); containsRel = true; } else { throw "Type(" + elemType + ") is not yet managed. Please update the debugger." } }); // if the node contains a relationship, we add them into a global variable to deal with the relationships later if (containsRel){ gNodesWithRel.push(nodeToAdd); } // we sort the nodes per type if (gNodesPerType[nodeToAdd._type] == null){ gNodesPerType[nodeToAdd._type] = []; colorsByNodeType[nodeToAdd._type] = getRandomColor(); // add the type of the node to the type list and assign a color to the type } gNodesPerType[nodeToAdd._type].push(nodeToAdd); // finally we add them to the global array containing all the nodes gAllNodes.push(nodeToAdd); }
javascript
{ "resource": "" }
q48505
addNodeToGraph
train
function addNodeToGraph(node){ gNodesDisplayed.push(node); g.addNode(node._id, node); if (contains(childrenNodes, node._id)){ var parentNode = getNodeFromId(nodesToBeLinked[node._id].from); if (contains(gNodesDisplayed, parentNode)){ addLinkToParent(node._id, parentNode._id); } } }
javascript
{ "resource": "" }
q48506
addRelToGraph
train
function addRelToGraph(node){ var children = []; for (var prop in node){ if(node.hasOwnProperty(prop)){ if (typeof node[prop] === 'object') { var linkedNodes = node[prop]; // same for links if (colorsByLinkType[prop] == null) { colorsByLinkType[prop] = getRandomColor(); } for (var i = 0; i < linkedNodes.length; i++) { //find node by id in the array (using jQuery) const linkedNode = linkedNodes[i]; var nodeResult = getNodeFromId(linkedNode); gChildrenNodes.push(nodeResult); children.push(nodeResult); //if the node is displayed, we add a link otherwise we will need to add it later if (contains(gNodesDisplayed, nodeResult)){ g.addLink(node._id, nodeResult._id, prop); } else { nodesToBeLinked[nodeResult._id] = delayLinkCreation(node._id, nodeResult._id, prop); } } } } } gNodesWithChildren[node._id] = children; }
javascript
{ "resource": "" }
q48507
getNodeFromId
train
function getNodeFromId(nodeId){ var res = $.grep(gAllNodes, function(e) { return e._id === nodeId; }); return res[0]; }
javascript
{ "resource": "" }
q48508
delayLinkCreation
train
function delayLinkCreation(idParent, idChild, relationName){ childrenNodes.push(idChild); return { from: idParent, name: relationName }; }
javascript
{ "resource": "" }
q48509
addLinkToParent
train
function addLinkToParent(idNode, idParentNode){ g.addLink(idParentNode, idNode, nodesToBeLinked[idNode].name); delete nodesToBeLinked[idNode]; //we remove the node from childrenNodes var index = childrenNodes.indexOf(idNode); if (index > -1) { childrenNodes.splice(index, 1); } }
javascript
{ "resource": "" }
q48510
toggleLayout
train
function toggleLayout() { $('.nodeLabel').remove(); isPaused = !isPaused; if (isPaused) { $('#toggleLayout').html('<i class="fa fa-play"></i>Resume layout'); renderer.pause(); } else { $('#toggleLayout').html('<i class="fa fa-pause"></i>Pause layout'); renderer.resume(); } return false; }
javascript
{ "resource": "" }
q48511
splitTickText
train
function splitTickText(d, maxWidth) { var tickText = textFormatted(d), subtext, spaceIndex, textWidth, splitted = []; if (Object.prototype.toString.call(tickText) === "[object Array]") { return tickText; } if (!maxWidth || maxWidth <= 0) { maxWidth = isVertical ? 95 : params.isCategory ? (Math.ceil(scale1(ticks[1]) - scale1(ticks[0])) - 12) : 110; } function split(splitted, text) { spaceIndex = undefined; for (var i = 1; i < text.length; i++) { if (text.charAt(i) === ' ') { spaceIndex = i; } subtext = text.substr(0, i + 1); textWidth = sizeFor1Char.w * subtext.length; // if text width gets over tick width, split by space index or crrent index if (maxWidth < textWidth) { return split( splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)), text.slice(spaceIndex ? spaceIndex + 1 : i) ); } } return splitted.concat(text); } return split(splitted, tickText + ""); }
javascript
{ "resource": "" }
q48512
createColumnsFromProperties
train
function createColumnsFromProperties(){ var res = []; for (var i = 0; i < nodeProperties.length; ++i){ var prop = nodeProperties[i]; var obj = { id: prop, name: prop, field: prop }; res.push(obj); } return res; }
javascript
{ "resource": "" }
q48513
gotMedia
train
function gotMedia(mediaStream) { // Extract video track. videoDevice = mediaStream.getVideoTracks()[0]; log('Using camera', videoDevice.label); const captureDevice = new ImageCapture(videoDevice, mediaStream); interval = setInterval(function () { captureDevice.grabFrame().then(processFrame).catch(error => { err((new Date()).toISOString(), 'Error while grabbing frame:', error); }); captureDevice.takePhoto().then(processPhoto).catch(error => { err((new Date()).toISOString(), 'Error while taking photo:', error); }); }, 300); }
javascript
{ "resource": "" }
q48514
findRoutes
train
function findRoutes (dir, fileExtensions) { let files = fs.readdirSync(dir) let resolve = f => path.join(dir, f) let routes = files.filter(f => fileExtensions.indexOf(path.extname(f)) !== -1).map(resolve) let dirs = files.filter(f => fs.statSync(path.join(dir, f)).isDirectory()).map(resolve) return routes.concat(...dirs.map(subdir => findRoutes(subdir, fileExtensions))) }
javascript
{ "resource": "" }
q48515
scheduleHandler
train
function scheduleHandler (p1, p2) { return setTimeout(function () { var x, handler = p1._s ? p2._onFulfilled : p2._onRejected; // 2.2.7.3 // 2.2.7.4 if (handler === void 0) { settlePromise(p2, p1._s, p1._v); return; } try { // 2.2.5 x = handler(p1._v); } catch (err) { // 2.2.7.2 settlePromise(p2, $rejected, err); return; } // 2.2.7.1 settleWithX(p2, x); }); }
javascript
{ "resource": "" }
q48516
settleWithX
train
function settleWithX (p, x) { // 2.3.1 if (x === p && x) { settlePromise(p, $rejected, new TypeError('promise_circular_chain')); return; } // 2.3.2 // 2.3.3 var xthen, type = typeof x; if (x !== null && (type === 'function' || type === 'object')) { try { // 2.3.2.1 xthen = x.then; } catch (err) { // 2.3.3.2 settlePromise(p, $rejected, err); return; } if (typeof xthen === 'function') { settleXthen(p, x, xthen); } else { // 2.3.3.4 settlePromise(p, $resolved, x); } } else { // 2.3.4 settlePromise(p, $resolved, x); } return p; }
javascript
{ "resource": "" }
q48517
train
function (onNext, onError) { var self = this, subscriber = new Observable(); subscriber._onNext = onNext; subscriber._onError = onError; subscriber._nextErr = genNextErr(subscriber.next); subscriber.publisher = self; self.subscribers.push(subscriber); return subscriber; }
javascript
{ "resource": "" }
q48518
genScheduler
train
function genScheduler (initQueueSize, fn) { /** * All async promise will be scheduled in * here, so that they can be execute on the next tick. * @private */ var fnQueue = Arr(initQueueSize) , fnQueueLen = 0; /** * Run all queued functions. * @private */ function flush () { var i = 0; while (i < fnQueueLen) { fn(fnQueue[i], fnQueue[i + 1]); fnQueue[i++] = $undefined; fnQueue[i++] = $undefined; } fnQueueLen = 0; if (fnQueue.length > initQueueSize) fnQueue.length = initQueueSize; } return function (v, arg) { fnQueue[fnQueueLen++] = v; fnQueue[fnQueueLen++] = arg; if (fnQueueLen === 2) nextTick(flush); }; }
javascript
{ "resource": "" }
q48519
flush
train
function flush () { var i = 0; while (i < fnQueueLen) { fn(fnQueue[i], fnQueue[i + 1]); fnQueue[i++] = $undefined; fnQueue[i++] = $undefined; } fnQueueLen = 0; if (fnQueue.length > initQueueSize) fnQueue.length = initQueueSize; }
javascript
{ "resource": "" }
q48520
settleWithX
train
function settleWithX (p, x) { // 2.3.1 if (x === p && x) { settlePromise(p, $rejected, genTypeError($promiseCircularChain)); return p; } // 2.3.2 // 2.3.3 if (x !== $null && (isFunction(x) || isObject(x))) { // 2.3.2.1 var xthen = genTryCatcher(getThen)(x); if (xthen === $tryErr) { // 2.3.3.2 settlePromise(p, $rejected, xthen.e); return p; } if (isFunction(xthen)) { // Fix https://bugs.chromium.org/p/v8/issues/detail?id=4162 if (isYaku(x)) settleXthen(p, x, xthen); else nextTick(function () { settleXthen(p, x, xthen); }); } else // 2.3.3.4 settlePromise(p, $resolved, x); } else // 2.3.4 settlePromise(p, $resolved, x); return p; }
javascript
{ "resource": "" }
q48521
saveUrl
train
function saveUrl(url) { fs.writeFile('serve-url.log', url, error => { if (error) { return console.log(error) } console.log('serve-url.log updated!') }) }
javascript
{ "resource": "" }
q48522
connectionDelay
train
function connectionDelay() { var delay = self.connectionWait; if (delay === 0) { if (self.connectedAt) { var t = 1000; var connectedFor = new Date().getTime() - self.connectedAt; if (connectedFor < t) { delay = t - connectedFor; } } } return delay; }
javascript
{ "resource": "" }
q48523
parseWebSocketEvent
train
function parseWebSocketEvent(event) { try { var params = JSON.parse(event.data); if (typeof params.data === 'string') { try { params.data = JSON.parse(params.data); } catch (e) { if (!(e instanceof SyntaxError)) { throw e; } } } return params; } catch (e) { self.emit('error', {type: 'MessageParseError', error: e, data: event.data}); } }
javascript
{ "resource": "" }
q48524
updateState
train
function updateState(newState, data) { var prevState = self.state; self.state = newState; // Only emit when the state changes if (prevState !== newState) { Pusher.debug('State changed', prevState + ' -> ' + newState); self.emit('state_change', {previous: prevState, current: newState}); self.emit(newState, data); } }
javascript
{ "resource": "" }
q48525
Spotify
train
function Spotify () { if (!(this instanceof Spotify)) return new Spotify(); EventEmitter.call(this); this.seq = 0; this.heartbeatInterval = 18E4; // 180s, from "spotify.web.client.js" this.agent = superagent.agent(); this.connected = false; // true after the WebSocket "connect" message is sent this._callbacks = Object.create(null); this.authServer = 'play.spotify.com'; this.authUrl = '/xhr/json/auth.php'; this.landingUrl = '/'; this.userAgent = 'Mozilla/5.0 (Chrome/13.37 compatible-ish) spotify-web/' + pkg.version; // base URLs for Image files like album artwork, artist prfiles, etc. // these values taken from "spotify.web.client.js" this.sourceUrl = 'https://d3rt1990lpmkn.cloudfront.net'; this.sourceUrls = { tiny: this.sourceUrl + '/60/', small: this.sourceUrl + '/120/', normal: this.sourceUrl + '/300/', large: this.sourceUrl + '/640/', avatar: this.sourceUrl + '/artist_image/' }; // mappings for the protobuf `enum Size` this.sourceUrls.DEFAULT = this.sourceUrls.normal; this.sourceUrls.SMALL = this.sourceUrls.tiny; this.sourceUrls.LARGE = this.sourceUrls.large; this.sourceUrls.XLARGE = this.sourceUrls.avatar; // WebSocket callbacks this._onopen = this._onopen.bind(this); this._onclose = this._onclose.bind(this); this._onmessage = this._onmessage.bind(this); // start the "heartbeat" once the WebSocket connection is established this.once('connect', this._startHeartbeat); // handle "message" commands... this.on('message', this._onmessagecommand); // needs to emulate Spotify's "CodeValidator" object this._context = vm.createContext(); this._context.reply = this._reply.bind(this); // binded callback for when user doesn't pass a callback function this._defaultCallback = this._defaultCallback.bind(this); }
javascript
{ "resource": "" }
q48526
train
function(schema, dontRecurse) { if ('string' === typeof schema) { var schemaName = schema.split("#"); schema = schemas.build(schemaName[0], schemaName[1]); if (!schema) throw new Error('Could not load schema: ' + schemaName.join('#')); } else if (schema && !dontRecurse && (!schema.hasOwnProperty('parse') && !schema.hasOwnProperty('serialize'))) { var keys = Object.keys(schema); keys.forEach(function(key) { schema[key] = loadSchema(schema[key], true); }); } return schema; }
javascript
{ "resource": "" }
q48527
SpotifyError
train
function SpotifyError (err) { this.domain = err[0] || 0; this.code = err[1] || 0; this.description = err[2] || ''; this.data = err[3] || null; // Error impl this.name = domains[this.domain]; var msg = codes[this.code]; if (this.description) msg += ' (' + this.description + ')'; this.message = msg; Error.captureStackTrace(this, SpotifyError); }
javascript
{ "resource": "" }
q48528
train
function(coords, done) { var tile = document.createElement("img"); tile.onerror = L.bind(this._tileOnError, this, done, tile); if (this.options.crossOrigin) { tile.crossOrigin = ""; } /* Alt tag is *set to empty string to keep screen readers from reading URL and for compliance reasons http://www.w3.org/TR/WCAG20-TECHS/H67 */ tile.alt = ""; var tileUrl = this.getTileUrl(coords); if (this.options.useCache) { this._db.get( tileUrl, { revs_info: true }, this._onCacheLookup(tile, tileUrl, done) ); } else { // Fall back to standard behaviour tile.onload = L.bind(this._tileOnLoad, this, done, tile); tile.src = tileUrl; } return tile; }
javascript
{ "resource": "" }
q48529
train
function(coords) { var zoom = coords.z; if (this.options.zoomReverse) { zoom = this.options.maxZoom - zoom; } zoom += this.options.zoomOffset; return L.Util.template( this._url, L.extend( { r: this.options.detectRetina && L.Browser.retina && this.options.maxZoom > 0 ? "@2x" : "", s: this._getSubdomain(coords), x: coords.x, y: this.options.tms ? this._globalTileRange.max.y - coords.y : coords.y, z: this.options.maxNativeZoom ? Math.min(zoom, this.options.maxNativeZoom) : zoom, }, this.options ) ); }
javascript
{ "resource": "" }
q48530
train
function(tile, remaining, seedData) { if (!remaining.length) { this.fire("seedend", seedData); return; } this.fire("seedprogress", { bbox: seedData.bbox, minZoom: seedData.minZoom, maxZoom: seedData.maxZoom, queueLength: seedData.queueLength, remainingLength: remaining.length, }); var url = remaining.shift(); this._db.get( url, function(err, data) { if (!data) { /// FIXME: Do something on tile error!! tile.onload = function(ev) { this._saveTile(tile, url, null); //(ev) this._seedOneTile(tile, remaining, seedData); }.bind(this); tile.crossOrigin = "Anonymous"; tile.src = url; } else { this._seedOneTile(tile, remaining, seedData); } }.bind(this) ); }
javascript
{ "resource": "" }
q48531
train
function(left, right, cost, identifier, allVars, joinVars) { this.left = left; this.right = right; this.cost = cost; this.i = identifier; this.vars = allVars; this.join = joinVars; }
javascript
{ "resource": "" }
q48532
train
function(vars, groupVars) { for(var j=0; j<vars.length; j++) { var thisVar = "/"+vars[j]+"/"; if(groupVars.indexOf(thisVar) != -1) { return true; } } return false; }
javascript
{ "resource": "" }
q48533
train
function(bgp, toJoin, newGroups, newGroupVars) { var acumGroups = []; var acumId = ""; var acumVars = ""; for(var gid in toJoin) { acumId = acumId+gid; // new group id acumGroups = acumGroups.concat(groups[gid]); acumVars = acumVars + groupVars[gid]; // @todo bug here? we were not adding... } acumVars = acumVars + vars.join("/") + "/"; acumGroups.push(bgp); newGroups[acumId] = acumGroups; newGroupVars[acumId] = acumVars; }
javascript
{ "resource": "" }
q48534
train
function (absolute) { var aPath, bPath, i = 0, j, resultPath = [], result = ''; if (typeof absolute === 'string') { absolute = $.uri(absolute, {}); } if (absolute.scheme !== this.scheme || absolute.authority !== this.authority) { return absolute.toString(); } if (absolute.path !== this.path) { aPath = absolute.path.split('/'); bPath = this.path.split('/'); if (aPath[1] !== bPath[1]) { result = absolute.path; } else { while (aPath[i] === bPath[i]) { i += 1; } j = i; for (; i < bPath.length - 1; i += 1) { resultPath.push('..'); } for (; j < aPath.length; j += 1) { resultPath.push(aPath[j]); } result = resultPath.join('/'); } result = absolute.query === undefined ? result : result + '?' + absolute.query; result = absolute.fragment === undefined ? result : result + '#' + absolute.fragment; return result; } if (absolute.query !== undefined && absolute.query !== this.query) { return '?' + absolute.query + (absolute.fragment === undefined ? '' : '#' + absolute.fragment); } if (absolute.fragment !== undefined && absolute.fragment !== this.fragment) { return '#' + absolute.fragment; } return ''; }
javascript
{ "resource": "" }
q48535
train
function () { var result = ''; if (this._string) { return this._string; } else { result = this.scheme === undefined ? result : (result + this.scheme + ':'); result = this.authority === undefined ? result : (result + '//' + this.authority); result = result + this.path; result = this.query === undefined ? result : (result + '?' + this.query); result = this.fragment === undefined ? result : (result + '#' + this.fragment); this._string = result; return result; } }
javascript
{ "resource": "" }
q48536
train
function (options) { options = $.extend({ namespaces: this.namespaces, base: this.base }, options || {}); return $.rdf.dump(this.triples(), options); }
javascript
{ "resource": "" }
q48537
train
function (triple) { var binding = {}; binding = testResource(triple.subject, this.subject, binding); if (binding === null) { return null; } binding = testResource(triple.property, this.property, binding); if (binding === null) { return null; } binding = testResource(triple.object, this.object, binding); return binding; }
javascript
{ "resource": "" }
q48538
train
function (bindings) { var t = this; if (!this.isFixed()) { t = this.fill(bindings); } if (t.isFixed()) { return $.rdf.triple(t.subject, t.property, t.object, { source: this.toString() }); } else { return null; } }
javascript
{ "resource": "" }
q48539
train
function(term) { try { if(term == null) { return ""; } if(term.token==='uri') { return "u"+term.value; } else if(term.token === 'blank') { return "b"+term.value; } else if(term.token === 'literal') { var l = "l"+term.value; l = l + (term.type || ""); l = l + (term.lang || ""); return l; } } catch(e) { if(typeof(term) === 'object') { var key = ""; for(p in term) { key = key + p + term[p]; } return key; } return term; } }
javascript
{ "resource": "" }
q48540
train
function(filename, charset, callback) { fs.readFile(filename, function (err, data) { if (err) throw err; zlib.gzip(data, function(err, result) { callback(result); }); }); }
javascript
{ "resource": "" }
q48541
train
function(){ if(arguments.length == 1) { return new Store(arguments[0]); } else if(arguments.length == 2) { return new Store(arguments[0], arguments[1]); } else { return new Store(); }; }
javascript
{ "resource": "" }
q48542
train
function (callback) { return function (new_method, assert_method, arity) { return function () { var message = arguments[arity - 1]; var a = exports.assertion({method: new_method, message: message}); try { assert[assert_method].apply(null, arguments); } catch (e) { a.error = e; } callback(a); }; }; }
javascript
{ "resource": "" }
q48543
train
function (setUp, tearDown, fn) { return function (test) { var context = {}; if (tearDown) { var done = test.done; test.done = function (err) { try { tearDown.call(context, function (err2) { if (err && err2) { test._assertion_list.push( types.assertion({error: err}) ); return done(err2); } done(err || err2); }); } catch (e) { done(e); } }; } if (setUp) { setUp.call(context, function (err) { if (err) { return test.done(err); } fn.call(context, test); }); } else { fn.call(context, test); } }; }
javascript
{ "resource": "" }
q48544
train
function (setUp, tearDown, group) { var tests = {}; var keys = _keys(group); for (var i = 0; i < keys.length; i += 1) { var k = keys[i]; if (typeof group[k] === 'function') { tests[k] = wrapTest(setUp, tearDown, group[k]); } else if (typeof group[k] === 'object') { tests[k] = wrapGroup(setUp, tearDown, group[k]); } } return tests; }
javascript
{ "resource": "" }
q48545
convertEntity
train
function convertEntity(entity) { switch (entity[0]) { case '"': { if(entity.indexOf("^^") > 0) { var parts = entity.split("^^"); return {literal: parts[0] + "^^<" + parts[1] + ">" }; } else { return { literal: entity }; } } case '_': return { blank: entity.replace('b', '') }; default: return { token: 'uri', value: entity, prefix: null, suffix: null }; } }
javascript
{ "resource": "" }
q48546
coerce
train
function coerce(scopes) { if (scopes instanceof ScopeSet) { return scopes; } // If we receive a string, assume it's a single scope. // We deliberately do not attempt to split the string on whitespace here, // because we want to force callers to explicitly choose between // exports.fromString() or exports.fromURLEncodedString depending on // what encoding they expect to have received the string in. if (typeof scopes === 'string') { return new ScopeSet([scopes]); } return new ScopeSet(scopes); }
javascript
{ "resource": "" }
q48547
initialise
train
function initialise (config, log, defaults) { const { interval, redis: redisConfig } = config; if (! (interval > 0 && interval < Infinity)) { throw new TypeError('Invalid interval'); } if (! log) { throw new TypeError('Missing log argument'); } const redis = require('../redis')({ ...redisConfig, enabled: true, prefix: FLAGS_PREFIX, }, log); let cache, timeout; refresh(); /** * @typedef {Object} FeatureFlags * * @property {Function} get * * @property {Function} terminate */ return { get, terminate }; async function refresh () { try { if (cache) { // Eliminate any latency during refresh by keeping the old cached result // until the refreshed promise has actually resolved. const result = await redis.get(FLAGS_KEY); cache = Promise.resolve(JSON.parse(result)); } else { cache = redis.get(FLAGS_KEY).then(result => JSON.parse(result)); // The positioning of `await` is deliberate here. // The initial value of `cache` must be a promise // so that callers can access it uniformly. // But we don't want `setTimeout` to be invoked // until after that promise has completed. await cache; } } catch (error) { } timeout = setTimeout(refresh, interval); } /** * Get the current state for all experiments. * Asynchronous, but returns the cached state * so it doesn't add latency, * except during initialisation. * * @returns {Promise} */ async function get () { try { return await cache || defaults || {}; } catch (error) { if (defaults) { return defaults; } throw error; } } /** * Terminate the refresh loop * and close all redis connections. * Useful for e.g. terminating tests cleanly. * * @returns {Promise} */ function terminate () { if (timeout) { clearTimeout(timeout); timeout = null; } return redis.close(); } }
javascript
{ "resource": "" }
q48548
getIfUtils
train
function getIfUtils(env, vars = ['production', 'prod', 'test', 'development', 'dev']) { env = typeof env === 'string' ? {[env]: true} : env if (typeof env !== 'object') { throw new Error( `webpack-config-utils:getIfUtils: env passed should be a string/Object. Was ${JSON.stringify(env)}` ) } return vars.reduce((utils, variable) => { const envValue = !!env[variable] const capitalVariable = capitalizeWord(variable) utils[`if${capitalVariable}`] = (value, alternate) => { return isUndefined(value) ? envValue : propIf(envValue, value, alternate) } utils[`ifNot${capitalVariable}`] = (value, alternate) => { return isUndefined(value) ? !envValue : propIfNot(envValue, value, alternate) } return utils }, {}) }
javascript
{ "resource": "" }
q48549
ListCache
train
function ListCache(entries) { var this$1 = this; var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this$1.set(entry[0], entry[1]); } }
javascript
{ "resource": "" }
q48550
findNodeFromPos
train
function findNodeFromPos(pos) { const lut = this.begins; assert(is.finitenumber(pos) && pos >= 0); let left = 0; let right = lut.length - 1; while (left < right) { const mid = Math.floor((left + right) / 2); assert(mid >= 0 && mid < lut.length); if (pos > lut[mid].range[0]) { left = mid + 1; } else { right = mid; } } if (left > right) { assert(last(lut).range[0] < pos); return null; } const found = left; const foundPos = lut[found].range[0]; assert(foundPos >= pos); if (found >= 1) { const prevPos = lut[found - 1].range[0]; assert(prevPos < pos); } return lut[found]; }
javascript
{ "resource": "" }
q48551
replaceNodeWith
train
function replaceNodeWith(node, newNode) { let done = false; const parent = node.$parent; const keys = Object.keys(parent); keys.forEach(function(key) { if (parent[key] === node) { parent[key] = newNode; done = true; } }); if (done) { return; } // second pass, now check arrays keys.forEach(function(key) { if (Array.isArray(parent[key])) { const arr = parent[key]; for (let i = 0; i < arr.length; i++) { if (arr[i] === node) { arr[i] = newNode; done = true; } } } }); assert(done); }
javascript
{ "resource": "" }
q48552
_escapeHtml
train
function _escapeHtml (input) { return String(input) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;'); }
javascript
{ "resource": "" }
q48553
_list
train
function _list (str, isOrdered) { if (!str) return str; var $ = cheerio.load(str); var listEl = isOrdered ? 'ol' : 'ul'; $(listEl).each(function (i, el) { var $out = cheerio.load('<p></p>'); var $el = $(el); $el.find('li').each(function (j, li) { var tick = isOrdered ? String(j + 1) + '.' : '-'; $out('p').append(tick + ' ' + _escapeHtml($(li).text()) + '<br />'); }); // avoid excess spacing coming off last element // (we are wrapping with a <p> anyway) $out('br').last().remove(); $el.replaceWith($out.html()); }); return $.html(); }
javascript
{ "resource": "" }
q48554
sendStats
train
function sendStats() { var key = req[options.requestKey]; key = key ? key + '.' : ''; // Status Code var statusCode = res.statusCode || 'unknown_status'; client.increment(key + 'status_code.' + statusCode); // Response Time var duration = new Date().getTime() - startTime; client.timing(key + 'response_time', duration); cleanup(); }
javascript
{ "resource": "" }
q48555
Auto
train
function Auto (data, options) { const converters = { FlatJSON, DSVStr, DSVArr }; const dataFormat = detectDataFormat(data); if (!dataFormat) { throw new Error('Couldn\'t detect the data format'); } return converters[dataFormat](data, options); }
javascript
{ "resource": "" }
q48556
DSVStr
train
function DSVStr (str, options) { const defaultOption = { firstRowHeader: true, fieldSeparator: ',' }; options = Object.assign({}, defaultOption, options); const dsv = d3Dsv(options.fieldSeparator); return DSVArr(dsv.parseRows(str), options); }
javascript
{ "resource": "" }
q48557
createUnitField
train
function createUnitField(data, schema) { data = data || []; let partialField; switch (schema.type) { case FieldType.MEASURE: switch (schema.subtype) { case MeasureSubtype.CONTINUOUS: partialField = new PartialField(schema.name, data, schema, new ContinuousParser()); return new Continuous(partialField, `0-${data.length - 1}`); default: partialField = new PartialField(schema.name, data, schema, new ContinuousParser()); return new Continuous(partialField, `0-${data.length - 1}`); } case FieldType.DIMENSION: switch (schema.subtype) { case DimensionSubtype.CATEGORICAL: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); case DimensionSubtype.TEMPORAL: partialField = new PartialField(schema.name, data, schema, new TemporalParser(schema)); return new Temporal(partialField, `0-${data.length - 1}`); case DimensionSubtype.BINNED: partialField = new PartialField(schema.name, data, schema, new BinnedParser()); return new Binned(partialField, `0-${data.length - 1}`); default: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); } default: partialField = new PartialField(schema.name, data, schema, new CategoricalParser()); return new Categorical(partialField, `0-${data.length - 1}`); } }
javascript
{ "resource": "" }
q48558
generateNestedMap
train
function generateNestedMap(objArray) { let mainMap = new Map(); objArray.forEach((obj) => { let params = obj.name.split('.'); let i = 0; let k = mainMap; while (k.has(params[i])) { k = k.get(params[i]); i++; } let kk = new Map(); kk.set('value', obj.description.replace(/(\r\n|\n|\r)/gm, ' ')); kk.set('type', obj.type.names.join('\n\n').replace(/\./gi, '')); k.set(params[i], kk); }); return mainMap; }
javascript
{ "resource": "" }
q48559
sum
train
function sum (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { const filteredNumber = getFilteredValues(arr); const totalSum = filteredNumber.length ? filteredNumber.reduce((acc, curr) => acc + curr, 0) : InvalidAwareTypes.NULL; return totalSum; } return InvalidAwareTypes.NULL; }
javascript
{ "resource": "" }
q48560
avg
train
function avg (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { const totalSum = sum(arr); const len = arr.length || 1; return (Number.isNaN(totalSum) || totalSum instanceof InvalidAwareTypes) ? InvalidAwareTypes.NULL : totalSum / len; } return InvalidAwareTypes.NULL; }
javascript
{ "resource": "" }
q48561
min
train
function min (arr) { if (isArray(arr) && !(arr[0] instanceof Array)) { // Filter out undefined, null and NaN values const filteredValues = getFilteredValues(arr); return (filteredValues.length) ? Math.min(...filteredValues) : InvalidAwareTypes.NULL; } return InvalidAwareTypes.NULL; }
javascript
{ "resource": "" }
q48562
variance
train
function variance (arr) { let mean = avg(arr); return avg(arr.map(num => (num - mean) ** 2)); }
javascript
{ "resource": "" }
q48563
getSortFn
train
function getSortFn (dataType, sortType, index) { let retFunc; switch (dataType) { case MeasureSubtype.CONTINUOUS: case DimensionSubtype.TEMPORAL: if (sortType === 'desc') { retFunc = (a, b) => b[index] - a[index]; } else { retFunc = (a, b) => a[index] - b[index]; } break; default: retFunc = (a, b) => { const a1 = `${a[index]}`; const b1 = `${b[index]}`; if (a1 < b1) { return sortType === 'desc' ? 1 : -1; } if (a1 > b1) { return sortType === 'desc' ? -1 : 1; } return 0; }; } return retFunc; }
javascript
{ "resource": "" }
q48564
groupData
train
function groupData(data, fieldIndex) { const hashMap = new Map(); const groupedData = []; data.forEach((datum) => { const fieldVal = datum[fieldIndex]; if (hashMap.has(fieldVal)) { groupedData[hashMap.get(fieldVal)][1].push(datum); } else { groupedData.push([fieldVal, [datum]]); hashMap.set(fieldVal, groupedData.length - 1); } }); return groupedData; }
javascript
{ "resource": "" }
q48565
createSortingFnArg
train
function createSortingFnArg(groupedDatum, targetFields, targetFieldDetails) { const arg = { label: groupedDatum[0] }; targetFields.reduce((acc, next, idx) => { acc[next] = groupedDatum[1].map(datum => datum[targetFieldDetails[idx].index]); return acc; }, arg); return arg; }
javascript
{ "resource": "" }
q48566
sortData
train
function sortData(dataObj, sortingDetails) { const { data, schema } = dataObj; let fieldName; let sortMeta; let fDetails; let i = sortingDetails.length - 1; for (; i >= 0; i--) { fieldName = sortingDetails[i][0]; sortMeta = sortingDetails[i][1]; fDetails = fieldInSchema(schema, fieldName); if (!fDetails) { // eslint-disable-next-line no-continue continue; } if (isCallable(sortMeta)) { // eslint-disable-next-line no-loop-func mergeSort(data, (a, b) => sortMeta(a[fDetails.index], b[fDetails.index])); } else if (isArray(sortMeta)) { const groupedData = groupData(data, fDetails.index); const sortingFn = sortMeta[sortMeta.length - 1]; const targetFields = sortMeta.slice(0, sortMeta.length - 1); const targetFieldDetails = targetFields.map(f => fieldInSchema(schema, f)); groupedData.forEach((groupedDatum) => { groupedDatum.push(createSortingFnArg(groupedDatum, targetFields, targetFieldDetails)); }); mergeSort(groupedData, (a, b) => { const m = a[2]; const n = b[2]; return sortingFn(m, n); }); // Empty the array data.length = 0; groupedData.forEach((datum) => { data.push(...datum[1]); }); } else { sortMeta = String(sortMeta).toLowerCase() === 'desc' ? 'desc' : 'asc'; mergeSort(data, getSortFn(fDetails.type, sortMeta, fDetails.index)); } } dataObj.uids = []; data.forEach((value) => { dataObj.uids.push(value.pop()); }); }
javascript
{ "resource": "" }
q48567
defSortFn
train
function defSortFn (a, b) { const a1 = `${a}`; const b1 = `${b}`; if (a1 < b1) { return -1; } if (a1 > b1) { return 1; } return 0; }
javascript
{ "resource": "" }
q48568
merge
train
function merge (arr, lo, mid, hi, sortFn) { const mainArr = arr; const auxArr = []; for (let i = lo; i <= hi; i += 1) { auxArr[i] = mainArr[i]; } let a = lo; let b = mid + 1; for (let i = lo; i <= hi; i += 1) { if (a > mid) { mainArr[i] = auxArr[b]; b += 1; } else if (b > hi) { mainArr[i] = auxArr[a]; a += 1; } else if (sortFn(auxArr[a], auxArr[b]) <= 0) { mainArr[i] = auxArr[a]; a += 1; } else { mainArr[i] = auxArr[b]; b += 1; } } }
javascript
{ "resource": "" }
q48569
sort
train
function sort (arr, lo, hi, sortFn) { if (hi === lo) { return arr; } const mid = lo + Math.floor((hi - lo) / 2); sort(arr, lo, mid, sortFn); sort(arr, mid + 1, hi, sortFn); merge(arr, lo, mid, hi, sortFn); return arr; }
javascript
{ "resource": "" }
q48570
getFieldArr
train
function getFieldArr (dataModel, fieldArr) { const retArr = []; const fieldStore = dataModel.getFieldspace(); const dimensions = fieldStore.getDimension(); Object.entries(dimensions).forEach(([key]) => { if (fieldArr && fieldArr.length) { if (fieldArr.indexOf(key) !== -1) { retArr.push(key); } } else { retArr.push(key); } }); return retArr; }
javascript
{ "resource": "" }
q48571
getReducerObj
train
function getReducerObj (dataModel, reducers = {}) { const retObj = {}; const fieldStore = dataModel.getFieldspace(); const measures = fieldStore.getMeasure(); const defReducer = reducerStore.defaultReducer(); Object.keys(measures).forEach((measureName) => { if (typeof reducers[measureName] !== 'string') { reducers[measureName] = measures[measureName].defAggFn(); } const reducerFn = reducerStore.resolve(reducers[measureName]); if (reducerFn) { retObj[measureName] = reducerFn; } else { retObj[measureName] = defReducer; reducers[measureName] = defaultReducerName; } }); return retObj; }
javascript
{ "resource": "" }
q48572
groupBy
train
function groupBy (dataModel, fieldArr, reducers, existingDataModel) { const sFieldArr = getFieldArr(dataModel, fieldArr); const reducerObj = getReducerObj(dataModel, reducers); const fieldStore = dataModel.getFieldspace(); const fieldStoreObj = fieldStore.fieldsObj(); const dbName = fieldStore.name; const dimensionArr = []; const measureArr = []; const schema = []; const hashMap = {}; const data = []; let newDataModel; // Prepare the schema Object.entries(fieldStoreObj).forEach(([key, value]) => { if (sFieldArr.indexOf(key) !== -1 || reducerObj[key]) { schema.push(extend2({}, value.schema())); switch (value.schema().type) { case FieldType.MEASURE: measureArr.push(key); break; default: case FieldType.DIMENSION: dimensionArr.push(key); } } }); // Prepare the data let rowCount = 0; rowDiffsetIterator(dataModel._rowDiffset, (i) => { let hash = ''; dimensionArr.forEach((_) => { hash = `${hash}-${fieldStoreObj[_].partialField.data[i]}`; }); if (hashMap[hash] === undefined) { hashMap[hash] = rowCount; data.push({}); dimensionArr.forEach((_) => { data[rowCount][_] = fieldStoreObj[_].partialField.data[i]; }); measureArr.forEach((_) => { data[rowCount][_] = [fieldStoreObj[_].partialField.data[i]]; }); rowCount += 1; } else { measureArr.forEach((_) => { data[hashMap[hash]][_].push(fieldStoreObj[_].partialField.data[i]); }); } }); // reduction let cachedStore = {}; let cloneProvider = () => dataModel.detachedRoot(); data.forEach((row) => { const tuple = row; measureArr.forEach((_) => { tuple[_] = reducerObj[_](row[_], cloneProvider, cachedStore); }); }); if (existingDataModel) { existingDataModel.__calculateFieldspace(); newDataModel = existingDataModel; } else { newDataModel = new DataModel(data, schema, { name: dbName }); } return newDataModel; }
javascript
{ "resource": "" }
q48573
FlatJSON
train
function FlatJSON (arr) { const header = {}; let i = 0; let insertionIndex; const columns = []; const push = columnMajor(columns); arr.forEach((item) => { const fields = []; for (let key in item) { if (key in header) { insertionIndex = header[key]; } else { header[key] = i++; insertionIndex = i - 1; } fields[insertionIndex] = item[key]; } push(...fields); }); return [Object.keys(header), columns]; }
javascript
{ "resource": "" }
q48574
prepareSelectionData
train
function prepareSelectionData (fields, i) { const resp = {}; for (let field of fields) { resp[field.name()] = new Value(field.partialField.data[i], field); } return resp; }
javascript
{ "resource": "" }
q48575
DSVArr
train
function DSVArr (arr, options) { const defaultOption = { firstRowHeader: true, }; options = Object.assign({}, defaultOption, options); let header; const columns = []; const push = columnMajor(columns); if (options.firstRowHeader) { // If header present then mutate the array. // Do in-place mutation to save space. header = arr.splice(0, 1)[0]; } else { header = []; } arr.forEach(field => push(...field)); return [header, columns]; }
javascript
{ "resource": "" }
q48576
getLanguages
train
function getLanguages(properties) { if (!Array.isArray(properties['wof:lang_x_official'])) { return []; } return properties['wof:lang_x_official'] .filter(l => (typeof l === 'string' && l.length === 3)) .map(l => l.toLowerCase()); }
javascript
{ "resource": "" }
q48577
concatArrayFields
train
function concatArrayFields(properties, fields){ let arr = []; fields.forEach(field => { if (Array.isArray(properties[field]) && properties[field].length) { arr = arr.concat(properties[field]); } }); // dedupe array return arr.filter((item, pos, self) => self.indexOf(item) === pos); }
javascript
{ "resource": "" }
q48578
extractDB
train
function extractDB( dbpath ){ let targetWofIds = Array.isArray(config.importPlace) ? config.importPlace: [config.importPlace]; // connect to sql db let db = new Sqlite3( dbpath, { readonly: true } ); // convert ids to integers and remove any which fail to convert let cleanIds = targetWofIds.map(id => parseInt(id, 10)).filter(id => !isNaN(id)); // placefilter is used to select only records targeted by the 'importPlace' config option // note: if no 'importPlace' ids are provided then we process all ids which aren't 0 let placefilter = (cleanIds.length > 0) ? sql.placefilter : '!= 0'; // note: we need to use replace instead of bound params in order to be able // to query an array of values using IN. let dataQuery = sql.data.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); let metaQuery = sql.meta.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); // extract all data to disk for( let row of db.prepare(dataQuery).iterate() ){ if( 'postalcode' === row.placetype && true !== config.importPostalcodes ){ return; } if( 'venue' === row.placetype && true !== config.importVenues ){ return; } if( 'constituency' === row.placetype && true !== config.importConstituencies ){ return; } if( 'intersection' === row.placetype && true !== config.importIntersections ){ return; } writeJson( row ); } // write meta data to disk for( let row of db.prepare(metaQuery).iterate() ){ if( 'postalcode' === row.placetype && true !== config.importPostalcodes ){ return; } if( 'venue' === row.placetype && true !== config.importVenues ){ return; } if( 'constituency' === row.placetype && true !== config.importConstituencies ){ return; } if( 'intersection' === row.placetype && true !== config.importIntersections ){ return; } if( !row.hasOwnProperty('path') ){ // ensure path property is present (required by some importers) row.path = wofIdToPath(row.id).concat(row.id+'.geojson').join(path.sep); } metafiles.write( row ); } // close connection db.close(); }
javascript
{ "resource": "" }
q48579
findSubdivisions
train
function findSubdivisions( filename ){ // load configuration variables const config = require('pelias-config').generate(require('../schema')).imports.whosonfirst; const sqliteDir = path.join(config.datapath, 'sqlite'); let targetWofIds = Array.isArray(config.importPlace) ? config.importPlace: [config.importPlace]; // connect to sql db let db = new Sqlite3( path.join( sqliteDir, filename ), { readonly: true } ); // convert ids to integers and remove any which fail to convert let cleanIds = targetWofIds.map(id => parseInt(id, 10)).filter(id => !isNaN(id)); // placefilter is used to select only records targeted by the 'importPlace' config option // note: if no 'importPlace' ids are provided then we process all ids which aren't 0 let placefilter = (cleanIds.length > 0) ? sql.placefilter : '!= 0'; // query db // note: we need to use replace instead of using bound params in order to // be able to query an array of values using IN. let query = sql.subdiv.replace(/@placefilter/g, placefilter).replace(/@wofids/g, cleanIds.join(',')); return db.prepare(query).all().map( row => row.subdivision.toLowerCase()); }
javascript
{ "resource": "" }
q48580
setupDocument
train
function setupDocument(record, hierarchy) { var wofDoc = new Document( 'whosonfirst', record.place_type, record.id ); if (record.name) { wofDoc.setName('default', record.name); // index a version of postcode which doesn't contain whitespace if (record.place_type === 'postalcode' && typeof record.name === 'string') { var sans_whitespace = record.name.replace(/\s/g, ''); if (sans_whitespace !== record.name) { wofDoc.setNameAlias('default', sans_whitespace); } } // index name aliases for all other records (where available) else if (record.name_aliases.length) { record.name_aliases.forEach(alias => { wofDoc.setNameAlias('default', alias); }); } } wofDoc.setCentroid({ lat: record.lat, lon: record.lon }); // only set population if available if (record.population) { wofDoc.setPopulation(record.population); } // only set popularity if available if (record.popularity) { wofDoc.setPopularity(record.popularity); } // WOF bbox is defined as: // lowerLeft.lon, lowerLeft.lat, upperRight.lon, upperRight.lat // so convert to what ES understands if (!_.isUndefined(record.bounding_box)) { var parsedBoundingBox = record.bounding_box.split(',').map(parseFloat); var marshaledBoundingBoxBox = { upperLeft: { lat: parsedBoundingBox[3], lon: parsedBoundingBox[0] }, lowerRight: { lat: parsedBoundingBox[1], lon: parsedBoundingBox[2] } }; wofDoc.setBoundingBox(marshaledBoundingBoxBox); } // a `hierarchy` is composed of potentially multiple WOF records, so iterate // and assign fields if (!_.isUndefined(hierarchy)) { hierarchy.forEach(function(hierarchyElement) { assignField(hierarchyElement, wofDoc); }); } // add self to parent hierarchy for postalcodes only if (record.place_type === 'postalcode') { assignField(record, wofDoc); } return wofDoc; }
javascript
{ "resource": "" }
q48581
wofIdToPath
train
function wofIdToPath( id ){ let strId = id.toString(); let parts = []; while( strId.length ){ let part = strId.substr(0, 3); parts.push(part); strId = strId.substr(3); } return parts; }
javascript
{ "resource": "" }
q48582
formatString
train
function formatString (string) { const separator = "\n"; return Array.isArray(string) ? string.reduce((acc, line) => acc.concat(line.split(separator)), []) : string.split(separator); }
javascript
{ "resource": "" }
q48583
from
train
function from (json) { const instance = exportableClasses[json.constructor].from(json); if (json.children) { instance.add(...json.children.map(child => from(child))); } return instance; }
javascript
{ "resource": "" }
q48584
sanitizeParameters
train
function sanitizeParameters (definition) { let scalar; try { // eslint-disable-next-line no-use-before-define const vector = Vector.from(definition); scalar = vector.getDelta(); } catch (e) { scalar = definition.getDelta ? definition.getDelta() : definition; } return scalar; }
javascript
{ "resource": "" }
q48585
logResponse
train
function logResponse(data, isRejection) { data = data || {}; // examine the data object if (data instanceof Error) { // log the Error object _this.defaults.error('FAILED: ' + (data.message || 'Unknown Error'), data); return DSUtils.Promise.reject(data); } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') { var str = start.toUTCString() + ' - ' + config.method + ' ' + config.url + ' - ' + data.status + ' ' + (new Date().getTime() - start.getTime()) + 'ms'; if (data.status >= 200 && data.status < 300 && !isRejection) { if (_this.defaults.log) { _this.defaults.log(str, data); } return data; } else { if (_this.defaults.error) { _this.defaults.error('FAILED: ' + str, data); } return DSUtils.Promise.reject(data); } } else { // unknown type for 'data' that is not an Object or Error _this.defaults.error('FAILED', data); return DSUtils.Promise.reject(data); } }
javascript
{ "resource": "" }
q48586
isClosingHeading
train
function isClosingHeading(node, depth) { return depth && node && node.type === HEADING && node.depth <= depth }
javascript
{ "resource": "" }
q48587
pickPrefix
train
function pickPrefix(prefix, object) { var length = prefix.length; var sub; return foldl( function(acc, val, key) { if (key.substr(0, length) === prefix) { sub = key.substr(length); acc[sub] = val; } return acc; }, {}, object ); }
javascript
{ "resource": "" }
q48588
normalize
train
function normalize(msg, list) { var lower = map(function(s) { return s.toLowerCase(); }, list); var opts = msg.options || {}; var integrations = opts.integrations || {}; var providers = opts.providers || {}; var context = opts.context || {}; var ret = {}; debug('<-', msg); // integrations. each(function(value, key) { if (!integration(key)) return; if (!has.call(integrations, key)) integrations[key] = value; delete opts[key]; }, opts); // providers. delete opts.providers; each(function(value, key) { if (!integration(key)) return; if (type(integrations[key]) === 'object') return; if (has.call(integrations, key) && typeof providers[key] === 'boolean') return; integrations[key] = value; }, providers); // move all toplevel options to msg // and the rest to context. each(function(value, key) { if (includes(key, toplevel)) { ret[key] = opts[key]; } else { context[key] = opts[key]; } }, opts); // generate and attach a messageId to msg msg.messageId = 'ajs-' + md5(json.stringify(msg) + uuid()); // cleanup delete msg.options; ret.integrations = integrations; ret.context = context; ret = defaults(ret, msg); debug('->', ret); return ret; function integration(name) { return !!( includes(name, list) || name.toLowerCase() === 'all' || includes(name.toLowerCase(), lower) ); } }
javascript
{ "resource": "" }
q48589
convertGeoPoints
train
function convertGeoPoints() { if (!{}.hasOwnProperty.call(this.schema.__meta, 'geoPointsProps')) { return; } this.schema.__meta.geoPointsProps.forEach((property) => { if ({}.hasOwnProperty.call(_this.entityData, property) && _this.entityData[property] !== null && _this.entityData[property].constructor.name !== 'GeoPoint') { _this.entityData[property] = _this.gstore.ds.geoPoint(_this.entityData[property]); } }); }
javascript
{ "resource": "" }
q48590
metaData
train
function metaData() { const meta = {}; Object.keys(schema.paths).forEach((k) => { switch (schema.paths[k].type) { case 'geoPoint': // This allows us to automatically convert valid lng/lat objects // to Datastore.geoPoints meta.geoPointsProps = meta.geoPointsProps || []; meta.geoPointsProps.push(k); break; case 'entityKey': meta.refProps = meta.refProps || {}; meta.refProps[k] = true; break; default: } }); return meta; }
javascript
{ "resource": "" }
q48591
applyMethods
train
function applyMethods(entity, schema) { Object.keys(schema.methods).forEach((method) => { entity[method] = schema.methods[method]; }); return entity; }
javascript
{ "resource": "" }
q48592
defaultOptions
train
function defaultOptions(options) { const optionsDefault = { validateBeforeSave: true, explicitOnly: true, queries: { readAll: false, format: queries.formats.JSON, }, }; options = extend(true, {}, optionsDefault, options); if (options.joi) { const joiOptionsDefault = { options: { allowUnknown: options.explicitOnly !== true, }, }; if (is.object(options.joi)) { options.joi = extend(true, {}, joiOptionsDefault, options.joi); } else { options.joi = Object.assign({}, joiOptionsDefault); } if (!Object.prototype.hasOwnProperty.call(options.joi.options, 'stripUnknown')) { options.joi.options.stripUnknown = options.joi.options.allowUnknown !== true; } } return options; }
javascript
{ "resource": "" }
q48593
createDataLoader
train
function createDataLoader(ds) { ds = typeof ds !== 'undefined' ? ds : this && this.ds; if (!ds) { throw new Error('A Datastore instance has to be passed'); } return new DataLoader(keys => ( ds.get(keys).then(([res]) => { // When providing an Array with 1 Key item, google-datastore // returns a single item. // For predictable results in gstore, all responses from Datastore.get() // calls return an Array const entities = arrify(res); const entitiesByKey = {}; entities.forEach((entity) => { entitiesByKey[keyToString(entity[ds.KEY])] = entity; }); return keys.map(key => entitiesByKey[keyToString(key)] || null); }) ), { cacheKeyFn: _key => keyToString(_key), maxBatchSize: 1000, }); }
javascript
{ "resource": "" }
q48594
train
function (type) { return function (opts) { var opt = opts || {}; var userAttrs = getUserAttrs(opt); var w = { classes: opt.classes, type: type, formatValue: function (value) { return (value || value === 0) ? value : null; } }; w.toHTML = function (name, field) { var f = field || {}; var attrs = { type: type, name: name, id: f.id === false ? false : (f.id || true), classes: w.classes, value: w.formatValue(f.value) }; return tag('input', [attrs, userAttrs, w.attrs || {}]); }; return w; }; }
javascript
{ "resource": "" }
q48595
sendRequestsSync
train
function sendRequestsSync(requests) { // only try to require optional dependency netlinkwrapper once if (!netLinkHasBeenRequired) { netLinkHasBeenRequired = true; try { netLink = require('netlinkwrapper')(); } catch (requireNetlinkError) { logger.warn( 'Failed to require optional dependency netlinkwrapper, uncaught exception will not be reported to Instana.' ); } } if (!netLink) { return; } var port = agentOpts.port; if (typeof port !== 'number') { try { port = parseInt(port, 10); } catch (nonNumericPortError) { logger.warn('Detected non-numeric port configuration value %s, uncaught exception will not be reported.', port); return; } } try { netLink.connect(port, agentOpts.host); netLink.blocking(false); requests.forEach(function(request) { sendHttpPostRequestSync(port, request.path, request.data); }); } catch (netLinkError) { logger.warn('Failed to report uncaught exception due to network error.', { error: netLinkError }); } finally { try { netLink.disconnect(); } catch (ignoreDisconnectError) { logger.debug('Failed to disconnect after trying to report uncaught exception.'); } } }
javascript
{ "resource": "" }
q48596
sendHttpPostRequestSync
train
function sendHttpPostRequestSync(port, path, data) { logger.debug({ payload: data }, 'Sending payload synchronously to %s', path); try { var payload = JSON.stringify(data); var payloadLength = buffer.fromString(payload, 'utf8').length; } catch (payloadSerializationError) { logger.warn('Could not serialize payload, uncaught exception will not be reported.', { error: payloadSerializationError }); return; } // prettier-ignore netLink.write( 'POST ' + path + ' HTTP/1.1\u000d\u000a' + 'Host: ' + agentOpts.host + '\u000d\u000a' + 'Content-Type: application/json; charset=UTF-8\u000d\u000a' + 'Content-Length: ' + payloadLength + '\u000d\u000a' + '\u000d\u000a' + // extra CRLF before body payload ); }
javascript
{ "resource": "" }
q48597
instrument
train
function instrument(build) { if (typeof build !== 'function') { return build; } // copy further exported properties Object.keys(build).forEach(function(k) { overwrittenBuild[k] = build[k]; }); return overwrittenBuild; function overwrittenBuild() { var app = build.apply(this, arguments); if (app.route) { var originalRoute = app.route; app.route = function shimmedRoute(opts) { if (opts.handler) { var originalHandler = opts.handler; opts.handler = function shimmedHandler() { annotateHttpEntrySpanWithPathTemplate(app, opts); return originalHandler.apply(this, arguments); }; } if (opts.beforeHandler) { var originalBeforeHandler = opts.beforeHandler; opts.beforeHandler = function shimmedBeforeHandler() { annotateHttpEntrySpanWithPathTemplate(app, opts); return originalBeforeHandler.apply(this, arguments); }; } return originalRoute.apply(this, arguments); }; } return app; } }
javascript
{ "resource": "" }
q48598
makePromise
train
function makePromise(requestInstance, promiseFactoryFn) { // Resolver function wich assigns the promise (resolve, reject) functions // to the requestInstance function Resolver(resolve, reject) { this._resolve = resolve; this._reject = reject; } return promiseFactoryFn(Resolver.bind(requestInstance)); }
javascript
{ "resource": "" }
q48599
makeHelper
train
function makeHelper(obj, verb) { obj[verb] = function helper(url, options, f) { // ('url') if(_.isString(url)){ // ('url', f) if(_.isFunction(options)){ f = options; } if(!_.isObject(options)){ options = {}; } // ('url', {object}) options.url = url; } if(_.isObject(url)){ if(_.isFunction(options)){ f = options; } options = url; } options.method = verb.toUpperCase(); return obj(options, f); }; }
javascript
{ "resource": "" }