_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q37700
interpolate
train
function interpolate(val, scope) { // if no scope or value with {{ then no interpolation and can just return translated if (!scope || !val || !val.match) { return val; } // first, we need to get all values with a {{ }} in the string var i18nVars = val.match(i18nVarExpr); // loop through {{ }} values _.each(i18nVars, function (i18nVar) { var field = i18nVar.substring(2, i18nVar.length - 2).trim(); var scopeVal = getScopeValue(scope, field); val = val.replace(i18nVar, scopeVal); }); return val; }
javascript
{ "resource": "" }
q37701
translate
train
function translate(val, scope, status) { var app = (scope && scope.appName) || context.get('app') || ''; var lang = (scope && scope.lang) || context.get('lang') || 'en'; var translated; // if just one character or is a number, don't do translation if (!val || val.length < 2 || !isNaN(val)) { return val; } // translations could be either nested (on the server) or at the root (on the client) translated = (translations[app] && translations[app][lang] && translations[app][lang][val]) || (_.isString(translations[val]) && translations[val]); // if no transation AND caller passed in status object AND lang is not default (i.e. not english), // set the status object values which the caller can use to record some info // note: this is kind of hacky, but we want the caller (i.e. jng.directives.js) to handle // it because jng.directives has more info about the translation than we do at this level if (!translated && config.i18nDebug && status && lang !== config.lang.default) { status.app = app; status.lang = lang; status.missing = true; } // attempt to interpolate and return the resulting value (val if no translation found) return interpolate(translated || val, scope); }
javascript
{ "resource": "" }
q37702
initialCheck
train
function initialCheck(attr_name) { var elements = document.querySelectorAll('[' + attr_name + ']'), element, value, i, l; for (i = 0; i < elements.length; i++) { element = elements[i]; value = element.getAttribute(attr_name); if (initial_seen.get(element)) { continue; } if (attributes[attr_name]) { initial_seen.set(element, true); for (l = 0; l < attributes[attr_name].length; l++) { attributes[attr_name][l](element, value, null, true); } } } }
javascript
{ "resource": "" }
q37703
checkChildren
train
function checkChildren(mutation, node, seen) { var attr, k, l; if (seen == null) { seen = initial_seen; } // Ignore text nodes if (node.nodeType === 3 || node.nodeType === 8) { return; } // Only check attributes for nodes that haven't been checked before if (!seen.get(node)) { // Indicate this node has been checked seen.set(node, true); // Go over every attribute if (node.attributes) { for (k = 0; k < node.attributes.length; k++) { attr = node.attributes[k]; if (attributes[attr.name]) { for (l = 0; l < attributes[attr.name].length; l++) { attributes[attr.name][l](node, attr.value, null, true); } } } } } // Now check the children for (k = 0; k < node.childNodes.length; k++) { checkChildren(mutation, node.childNodes[k], seen); } }
javascript
{ "resource": "" }
q37704
SimplePool
train
function SimplePool() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; this.current = 0; this.pool = args.length === 1 && Array.isArray(args[0]) ? args[0] : args; }
javascript
{ "resource": "" }
q37705
createBaseTransport
train
function createBaseTransport(req, res) { // A transport object. var self = new events.EventEmitter(); // Because HTTP transport consists of multiple exchanges, an universally // unique identifier is required. self.id = uuid.v4(); // A flag to check the transport is opened. var opened = true; self.on("close", function() { opened = false; }); self.send = function(data) { // Allows to send data only it is opened. If not, fires an error. if (opened) { self.write(data); } else { self.emit("error", new Error("notopened")); } return this; }; return self; }
javascript
{ "resource": "" }
q37706
createStreamTransport
train
function createStreamTransport(req, res) { // A transport object. var self = createBaseTransport(req, res); // Any error on request-response should propagate to transport. req.on("error", function(error) { self.emit("error", error); }); res.on("error", function(error) { self.emit("error", error); }); // When the underlying connection was terminated abnormally. res.on("close", function() { self.emit("close"); }); // When the complete response has been sent. res.on("finish", function() { self.emit("close"); }); // The response body should be formatted in the [event stream // format](http://www.w3.org/TR/eventsource/#parsing-an-event-stream). self.write = function(data) { // `data` should be either a `Buffer` or a string. if (typeof data === "string") { // A text message should be prefixed with `1`. data = "1" + data; } else { // A binary message should be encoded in Base64 and prefixed with // `2`. data = "2" + data.toString("base64"); } // According to the format, data should be broken up by `\r`, `\n`, or // `\r\n`. var payload = data.split(/\r\n|[\r\n]/).map(function(line) { // Each line should be prefixed with 'data: ' and postfixed with // `\n`. return "data: " + line + "\n"; }) // Prints `\n` as the last character of a message. .join("") + "\n"; // Writes it to response with `utf-8` encoding. res.write(payload, "utf-8"); }; // Ends the response. Accordingly, `res`'s `finish` event will be fired. self.close = function() { res.end(); return this; }; // The content-type headers should be `text/event-stream` for Server-Sent // Events and `text/plain` for others. Also the response should be encoded in `utf-8`. res.setHeader("content-type", "text/" + // If it's Server-Sent Events, `sse` param is `true`. (req.params.sse === "true" ? "event-stream" : "plain") + "; charset=utf-8"); // The padding is required, which makes the client-side transport on old // browsers be aware of change of the response. It should be greater // than 1KB, be composed of white space character and end with `\n`. var text2KB = Array(2048).join(" "); // Some host objects which are used to perform streaming transport can't or // don't allow to read response headers as well as write request headers. // That's why we uses the first message as a handshake output. The handshake // result should be formatted in URI. And transport id should be added as // `id` param. var uri = url.format({query: {id: self.id}}); // Likewise some host objects in old browsers, junk data is needed to make // themselves be aware of change of response. Prints the padding and the // first message following `text/event-stream` with `utf-8` encoding. res.write(text2KB + "\ndata: " + uri + "\n\n", "utf-8"); return self; }
javascript
{ "resource": "" }
q37707
toJSON
train
function toJSON() { var obj = { message: this.message, stack: this.stack }, key; for (key in this) { if ( has.call(this, key) && 'function' !== typeof this[key] ) { obj[key] = this[key]; } } return obj; }
javascript
{ "resource": "" }
q37708
train
function(session) { if (session && session.user) { if (session.user.roles) return { roles: session.user.roles }; return { roles: "user" }; } return { roles: "public" }; }
javascript
{ "resource": "" }
q37709
on_write
train
function on_write (metric, enc, done) { var name = metric.name var values = metric.values var tags = metric.tags locals.batch.list[name] = locals.batch.list[name] || [] locals.batch.list[name].push([values, tags]) locals.batch.count = locals.batch.count + 1 var exceeded = locals.batch.count >= locals.batch.max var expired = Date.now() > locals.batch.next if (exceeded || expired) { write_batch() } done() }
javascript
{ "resource": "" }
q37710
importerSync
train
function importerSync(options, handler) { var modulePath, recursive = false, parent = ''; if (typeof options === 'string') { modulePath = options; } else { modulePath = options.path; recursive = options.recursive || recursive; parent = options.parent || parent; if (!modulePath) throw new Error("module directory path must be given."); } // absolute path? or relevant path? if (modulePath.indexOf('/') != 0) { // relevant. join with parent module's path modulePath = path.join(path.dirname(module.parent.parent.filename), modulePath); } var files = fs.readdirSync(modulePath); for (var i in files) { var name = files[i]; if (recursive && fs.lstatSync(path.join(modulePath, name)).isDirectory()) { importerSync({ path: path.join(modulePath, name), recursive: true, parent: path.join(parent, name) }, handler); continue; } if (name.lastIndexOf('.js') != name.length - 3) continue; name = name.substring(0, name.lastIndexOf('.')); // remove ext var moduleObj = require(path.join(modulePath, name)); if (handler) handler(moduleObj, path.join(parent, name)); } }
javascript
{ "resource": "" }
q37711
train
function (prototypes, force) { var instance, proto, names, l, i, replaceMap, protectedMap, name, nameInProto, finalName, propDescriptor, extraInfo; if (!prototypes) { return; } instance = this; // the Class proto = instance.prototype; names = Object.getOwnPropertyNames(prototypes); l = names.length; i = -1; replaceMap = arguments[2] || REPLACE_CLASS_METHODS; // hidden feature, used by itags protectedMap = arguments[3] || PROTECTED_CLASS_METHODS; // hidden feature, used by itags while (++i < l) { name = names[i]; finalName = replaceMap[name] || name; nameInProto = (finalName in proto); if (!PROTO_RESERVED_NAMES[finalName] && !protectedMap[finalName] && (!nameInProto || force)) { // if nameInProto: set the property, but also backup for chaining using $$orig propDescriptor = Object.getOwnPropertyDescriptor(prototypes, name); if (!propDescriptor.writable) { console.info(NAME+'mergePrototypes will set property of '+name+' without its property-descriptor: for it is an unwritable property.'); proto[finalName] = prototypes[name]; } else { // adding prototypes[name] into $$orig: instance.$$orig[finalName] || (instance.$$orig[finalName]=[]); instance.$$orig[finalName][instance.$$orig[finalName].length] = prototypes[name]; if (typeof prototypes[name] === 'function') { /*jshint -W083 */ propDescriptor.value = (function (originalMethodName, finalMethodName) { return function () { /*jshint +W083 */ // this.$own = prot; // this.$origMethods = instance.$$orig[finalMethodName]; var context, classCarierBkp, methodClassCarierBkp, origPropBkp, returnValue; // in some specific situations, this method is called without context. // can't figure out why (it happens when itable changes some of its its item-values) // probably reasson is that itable.model.items is not the same as itable.getData('_items') // anyway: to prevent errors here, we must return when there is no context: context = this; if (!context) { return; } classCarierBkp = context.__classCarier__; methodClassCarierBkp = context.__methodClassCarier__; origPropBkp = context.__origProp__; context.__methodClassCarier__ = instance; context.__classCarier__ = null; context.__origProp__ = finalMethodName; returnValue = prototypes[originalMethodName].apply(context, arguments); context.__origProp__ = origPropBkp; context.__classCarier__ = classCarierBkp; context.__methodClassCarier__ = methodClassCarierBkp; return returnValue; }; })(name, finalName); } Object.defineProperty(proto, finalName, propDescriptor); } } else { extraInfo = ''; nameInProto && (extraInfo = 'property is already available (you might force it to be set)'); PROTO_RESERVED_NAMES[finalName] && (extraInfo = 'property is a protected property'); protectedMap[finalName] && (extraInfo = 'property is a private property'); console.warn(NAME+'mergePrototypes is not allowed to set the property: '+name+' --> '+extraInfo); } } return instance; }
javascript
{ "resource": "" }
q37712
train
function (properties) { var proto = this.prototype, replaceMap = arguments[1] || REPLACE_CLASS_METHODS; // hidden feature, used by itags Array.isArray(properties) || (properties=[properties]); properties.forEach(function(prop) { prop = replaceMap[prop] || prop; delete proto[prop]; }); return this; }
javascript
{ "resource": "" }
q37713
train
function(constructorFn, chainConstruct) { var instance = this; if (typeof constructorFn==='boolean') { chainConstruct = constructorFn; constructorFn = null; } (typeof chainConstruct === 'boolean') || (chainConstruct=DEFAULT_CHAIN_CONSTRUCT); instance.$$constrFn = constructorFn || NOOP; instance.$$chainConstructed = chainConstruct ? true : false; return instance; }
javascript
{ "resource": "" }
q37714
train
function (constructor, prototypes, chainConstruct) { var instance = this, constructorClosure = {}, baseProt, proto, constrFn; if (typeof constructor === 'boolean') { constructor = null; prototypes = null; chainConstruct = constructor; } else { if ((typeof constructor === 'object') && (constructor!==null)) { chainConstruct = prototypes; prototypes = constructor; constructor = null; } if (typeof prototypes === 'boolean') { chainConstruct = prototypes; prototypes = null; } } (typeof chainConstruct === 'boolean') || (chainConstruct=DEFAULT_CHAIN_CONSTRUCT); constrFn = constructor || NOOP; constructor = function() { constructorClosure.constructor.$$constrFn.apply(this, arguments); }; constructor = (function(originalConstructor) { return function() { var context = this; if (constructorClosure.constructor.$$chainConstructed) { context.__classCarier__ = constructorClosure.constructor.$$super.constructor; context.__origProp__ = 'constructor'; context.__classCarier__.apply(context, arguments); context.$origMethods = constructorClosure.constructor.$$orig.constructor; } context.__classCarier__ = constructorClosure.constructor; context.__origProp__ = 'constructor'; originalConstructor.apply(context, arguments); // only call aferInit on the last constructor of the chain: (constructorClosure.constructor===context.constructor) && context.afterInit(); }; })(constructor); baseProt = instance.prototype; proto = Object.create(baseProt); constructor.prototype = proto; // webkit doesn't let all objects to have their constructor redefined // when directly assigned. Using `defineProperty will work: Object.defineProperty(proto, 'constructor', {value: constructor}); constructor.$$chainConstructed = chainConstruct ? true : false; constructor.$$super = baseProt; constructor.$$orig = { constructor: constructor }; constructor.$$constrFn = constrFn; constructorClosure.constructor = constructor; prototypes && constructor.mergePrototypes(prototypes, true); return constructor; }
javascript
{ "resource": "" }
q37715
checkTransform3dSupport
train
function checkTransform3dSupport() { div.style[support.transform] = ''; div.style[support.transform] = 'rotateY(90deg)'; return div.style[support.transform] !== ''; }
javascript
{ "resource": "" }
q37716
train
function(elem, v) { var value = v; if (!(value instanceof Transform)) { value = new Transform(value); } // We've seen the 3D version of Scale() not work in Chrome when the // element being scaled extends outside of the viewport. Thus, we're // forcing Chrome to not use the 3d transforms as well. Not sure if // translate is affectede, but not risking it. Detection code from // http://davidwalsh.name/detecting-google-chrome-javascript if (support.transform === 'WebkitTransform' && !isChrome) { elem.style[support.transform] = value.toString(true); } else { elem.style[support.transform] = value.toString(); } $(elem).data('transform', value); }
javascript
{ "resource": "" }
q37717
train
function() { if (bound) { self.unbind(transitionEnd, cb); } if (i > 0) { self.each(function() { this.style[support.transition] = (oldTransitions[this] || null); }); } if (typeof callback === 'function') { callback.apply(self); } if (typeof nextCall === 'function') { nextCall(); } }
javascript
{ "resource": "" }
q37718
train
function(next) { var i = 0; // Durations that are too slow will get transitions mixed up. // (Tested on Mac/FF 7.0.1) if ((support.transition === 'MozTransition') && (i < 25)) { i = 25; } window.setTimeout(function() { run(next); }, i); }
javascript
{ "resource": "" }
q37719
Millipede
train
function Millipede(size, options) { options = options || {}; this.size = size; this.reverse = options.reverse; this.horizontal = options.horizontal; this.position = options.position || 0; this.top = options.top || 0; this.left = options.left || 0; this.validate(); }
javascript
{ "resource": "" }
q37720
rawBundleFromFile
train
function rawBundleFromFile (dir, filename) { return readFilePromise(path.join(dir, filename)) .then(content => { return { dest: filename, raw: content }; }); }
javascript
{ "resource": "" }
q37721
defRoute
train
function defRoute(session, msg, context, cb) { const list = context.getServersByType(msg.serverType); if (!list || !list.length) { cb(new Error(`can not find server info for type:${msg.serverType}`)); return; } const uid = session ? (session.uid || '') : ''; const index = Math.abs(crc.crc32(uid.toString())) % list.length; utils.invokeCallback(cb, null, list[index].id); }
javascript
{ "resource": "" }
q37722
rdRoute
train
function rdRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } const index = Math.floor(Math.random() * servers.length); utils.invokeCallback(cb, null, servers[index]); }
javascript
{ "resource": "" }
q37723
rrRoute
train
function rrRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let index; if (!client.rrParam) { client.rrParam = {}; } if (client.rrParam[serverType]) { index = client.rrParam[serverType]; } else { index = 0; } utils.invokeCallback(cb, null, servers[index % servers.length]); if (index++ === Number.MAX_VALUE) { index = 0; } client.rrParam[serverType] = index; }
javascript
{ "resource": "" }
q37724
wrrRoute
train
function wrrRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let index; let weight; if (!client.wrrParam) { client.wrrParam = {}; } if (client.wrrParam[serverType]) { index = client.wrrParam[serverType].index; weight = client.wrrParam[serverType].weight; } else { index = -1; weight = 0; } const getMaxWeight = () => { let maxWeight = -1; for (let i = 0; i < servers.length; i++) { const server = client._station.servers[servers[i]]; if (!!server.weight && server.weight > maxWeight) { maxWeight = server.weight; } } return maxWeight; }; while (true) { // eslint-disable-line index = (index + 1) % servers.length; if (index === 0) { weight -= 1; if (weight <= 0) { weight = getMaxWeight(); if (weight <= 0) { utils.invokeCallback(cb, new Error('rpc wrr route get invalid weight.')); return; } } } const server = client._station.servers[servers[index]]; if (server.weight >= weight) { client.wrrParam[serverType] = { index: index, weight: weight }; utils.invokeCallback(cb, null, server.id); return; } } }
javascript
{ "resource": "" }
q37725
laRoute
train
function laRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } const actives = []; if (!client.laParam) { client.laParam = {}; } if (client.laParam[serverType]) { for (let j = 0; j < servers.length; j++) { let count = client.laParam[serverType][servers[j]]; if (!count) { count = 0; client.laParam[servers[j]] = 0; } actives.push(count); } } else { client.laParam[serverType] = {}; for (let i = 0; i < servers.length; i++) { client.laParam[serverType][servers[i]] = 0; actives.push(0); } } let rs = []; let minInvoke = Number.MAX_VALUE; for (let k = 0; k < actives.length; k++) { if (actives[k] < minInvoke) { minInvoke = actives[k]; rs = []; rs.push(servers[k]); } else if (actives[k] === minInvoke) { rs.push(servers[k]); } } const index = Math.floor(Math.random() * rs.length); const serverId = rs[index]; client.laParam[serverType][serverId] += 1; utils.invokeCallback(cb, null, serverId); }
javascript
{ "resource": "" }
q37726
chRoute
train
function chRoute(client, serverType, msg, cb) { const servers = client._station.serversMap[serverType]; if (!servers || !servers.length) { utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`)); return; } let con; if (!client.chParam) { client.chParam = {}; } if (client.chParam[serverType]) { con = client.chParam[serverType].consistentHash; } else { client.opts.station = client._station; con = new ConsistentHash(servers, client.opts); } const hashFieldIndex = client.opts.hashFieldIndex; const field = msg.args[hashFieldIndex] || JSON.stringify(msg); utils.invokeCallback(cb, null, con.getNode(field)); client.chParam[serverType] = { consistentHash: con }; }
javascript
{ "resource": "" }
q37727
isValid
train
function isValid(options, key) { var value = _.isFunction(options) ? options(key) : options[key]; if (typeof value === 'undefined') { return false; } if (value === null) { return false; } if (value === '') { return false; } if (_.isNaN(value)) { return false; } return true; }
javascript
{ "resource": "" }
q37728
train
function(user, stage, method){ switch (method) { case 'withinRooms': var room = user.getRoom(); if(stageCount(stage, room) == room.size) { console.log("Finished syncronising in " + room.name + ". Enough members in stage " + stage); // Once all members are present start experiment for(var key in room.getMembers(true)) { user = cloak.getUser(room.getMembers(true)[key].id); nextStage(user); } } break; case 'acrossRooms': default: if(stageCount(stage) == members.length) { console.log("Finished syncronising. Enough members in stage " + stage); // Once all members are present start experiment for(var key in members) { user = cloak.getUser(members[key]); nextStage(user); } } break; } }
javascript
{ "resource": "" }
q37729
train
function(stage, room) { i = 0; var stagemembers = (typeof room === 'undefined') ? members : _.pluck(room.getMembers(true), 'id'); for(var key in stagemembers) if(cloak.getUser(stagemembers[key]).data._stage == stage) i++; return i; }
javascript
{ "resource": "" }
q37730
train
function(url) { i = 0; for(var key in members) if(cloak.getUser(members[key]).data._load == url) i++; return i; }
javascript
{ "resource": "" }
q37731
train
function(user){ // First time nextStage() is called set the stage to zero. Otherwise keep track when continuing to the next stage user.data._stage = (typeof user.data._stage === 'undefined') ? 0 : user.data._stage+1; // Next stage is which type? var type = (typeof experiment.stages[user.data._stage].type === 'undefined') ? null : experiment.stages[user.data._stage].type; // 'undefined' set to null. switch (type) { // Static page. User does not have to wait but can continue to next stage on his/her own. case null: case 'static': var stage = experiment.stages[user.data._stage]; // stage in json file load(user, stage.url); break; // Syncronise users. Such that they proceed, as a group, to the next stage. case 'sync': load(user, experiment.stages[user.data._stage].url); // load waiting stage syncStage(user, user.data._stage, experiment.stages[user.data._stage].method); // syncronise users (wait for others) break; case 'randomise': // We only want to randomise once. So we do it when the first user enters the stage. if(stageCount(user.data._stage) == 1) { randomRooms(experiment.stages[user.data._stage].method); } nextStage(user); break; } }
javascript
{ "resource": "" }
q37732
train
function(){ console.log("Last user has finished the experiment!"); var userdata = new Object(); for(var key in cloak.getUsers()) { cloak.getUsers()[key].data.device = parser.setUA(cloak.getUsers()[key].data._device).getResult(); // Parse the useragent before saving data. userdata[cloak.getUsers()[key].id] = cloak.getUsers()[key].data; } // Alternatively consider using async.series or RSVP.Promise. var saveDataSuccess = saveExperimentSuccess = saveLogSucess = saveIPSucess= false; var successSave = function (){ if(saveDataSuccess && saveExperimentSuccess && saveLogSucess && saveIPSucess) { // quit proccess console.log(typeof cloak); cloak.stop(function(){ console.log(" -- server closed -- "); process.exit(0); // quit node.js process with succes }) } } // Save user IPs if requireUniqueIP == TRUE, such that when running continues experiments (forever start xxx.js) users can only participate once. // TO-DO /*if(requireUniqueIP) { var experimentConfig = JSON.parse(fs.readFileSync(experimentURL[0], experimentURL[1])); for(var key in cloak.getUsers()) { experimentConfig.ExcludeIPs.push(cloak.getUsers()[key].data.ip); } fs.writeFileSync(experimentURL[0], JSON.stringify(experimentConfig, null, '\t')); console.log(experimentURL[0]); saveIPSucess = true; successSave(); } else { saveIPSucess = true; successSave(); }*/ saveIPSucess = true; // Save user data. fs.writeFile('data/data_'+initTime.valueOf()+'_user.json', JSON.stringify(userdata,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_user.json'); saveDataSuccess = true; successSave(); }); // Save additional experiment data. experiment.initTime = initTime.valueOf(); experiment.timeFinalGlobal = timeGlobal.getValue(); var experimentdata = experiment; fs.writeFile('data/data_'+initTime.valueOf()+'_experiment.json', JSON.stringify(experimentdata,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_experiment.json'); saveExperimentSuccess = true; successSave(); }); // Save log of all messages send by the users. fs.writeFile('data/data_'+initTime.valueOf()+'_messages.json', JSON.stringify(storeMessage,null,'\t'), function (err) { if (err) return console.log(err); console.log('data_'+initTime.valueOf()+'_message.json'); saveLogSucess = true; successSave(); }); }
javascript
{ "resource": "" }
q37733
train
function(ip) { var unique = true; for(var key in cloak.getLobby().getMembers()) { if(ip == cloak.getLobby().getMembers()[key].data.ip) unique = false; } return unique; }
javascript
{ "resource": "" }
q37734
start
train
function start(config, setDefaultREPLCommands, getAppInstance) { // Defines the IPC socket file path var socketAddr = path.join(process.cwd(), 'socket-ctl'); // Deletes the file if already exists if (fs.existsSync(socketAddr)) fs.unlinkSync(socketAddr); // Create and start the socket server socketServer = net.createServer(function(socket) { if(config.replStartMessage) socket.write(config.replStartMessage+"\n"); // Instantiates a new REPL for this socket var socketReplServer = repl.start({ prompt: config.promptSymbol, eval: replEvaluatorBuilder(getAppInstance()), input: socket, output: socket, writer: replWriter, terminal: true }) .on("exit", () => { socket.end(); }); socket.on("error", (err) => { console.error(err); }); socketReplServer.context.app = getAppInstance(); setDefaultREPLCommands(socketReplServer); }); socketServer.listen(socketAddr); }
javascript
{ "resource": "" }
q37735
calculatePositionDiff
train
function calculatePositionDiff(position) { if (!_lastDiffPosition) { return _lastDiffPosition = position; } var dx, dy, p1, p2; p1 = position; p2 = _lastDiffPosition; dx = p2.x - p1.x; dy = p2.y - p1.y; _calcMoveDiffX += dx; _calcMoveDiffY += dy; _overallMoveDiffY += dy; _overallMoveDiffX += dx; _lastDiffPosition = position; }
javascript
{ "resource": "" }
q37736
train
function(req, res) { var packages = {}; var appJSON = require('../../package.json'); packages[appJSON.name] = appJSON; packages['onm'] = require('../onm/package.json'); res.send(packages); }
javascript
{ "resource": "" }
q37737
train
function(req, res) { var stores = []; for (key in onmStoreDictionary) { stores.push({ dataModel: onmStoreDictionary[key].model.jsonTag, storeKey: key }); } res.send(200, stores); }
javascript
{ "resource": "" }
q37738
train
function(req, res) { if (!req._body || (req.body == null) || !req.body) { res.send(400, "Invalid POST missing required request body."); return; } if ((req.body.model == null) || !req.body.model) { res.send(400, "Invalid POST missing 'model' property in request body."); return; } var onmDataModelRecord = onmModelDictionary[req.body.model]; if ((onmDataModelRecord == null) || !onmDataModelRecord || (onmDataModelRecord.model == null) || !onmDataModelRecord.model) { res.send(403, "The specified onm data model '" + req.body.model + "' is unsupported by this server."); return; } var storeUuid = uuid.v4(); var store = onmStoreDictionary[storeUuid] = new onm.Store(onmDataModelRecord.model); var storeRecord = { dataModel: store.model.jsonTag, storeKey: storeUuid }; console.log("created in-memory data store '" + storeUuid + "'."); res.send(200, storeRecord); }
javascript
{ "resource": "" }
q37739
train
function(req, res) { if (!req._body || (req.body == null) || !req.body) { res.send(400, "Invalid POST missing required request body."); return; } if ((req.body.store == null) || !req.body.store) { res.send(400, "Invalid POST mising 'store' property in request body."); return; } if ((req.body.address == null) || !req.body.address) { res.send(400, "Invalid POST missing 'address' property in request body."); return; } var store = onmStoreDictionary[req.body.store]; if ((store == null) || !store) { res.send(404, "The specified onm data store '" + req.body.store + "' does not exist on this server."); return; } var address = undefined try { address = store.model.createAddressFromHashString(req.body.address); } catch (exception) { console.error(exception); res.send(403, "Invalid address '" + req.body.address + "' is outside of the data model's address space."); return; } try { var namespace = store.createComponent(address) var namespaceRecord = {}; namespaceRecord['address'] = namespace.getResolvedAddress().getHashString(); namespaceRecord[address.getModel().jsonTag] = namespace.implementation.dataReference; res.send(200, namespaceRecord); } catch (exception) { res.send(412, exception); } }
javascript
{ "resource": "" }
q37740
train
function(req, res) { if (!req._body || (req.body == null) || !req.body) { res.send(400, "Invalid POST missing required request body."); return; } if ((req.body.store == null) || !req.body.store) { res.send(400, "Invalid POST mising 'store' property in request body."); return; } if ((req.body.address == null) || !req.body.address) { res.send(400, "Invalid POST missing 'address' property in request body."); return; } if ((req.body.data == null) || !req.body.data) { res.send(400, "Invalid POST missing 'data' property in request body."); return; } var store = onmStoreDictionary[req.body.store]; if ((store == null) || !store) { res.send(404, "The specified onm data store '" + req.body.store + "' does not exist on this server."); return; } var address = undefined; try { address = store.model.createAddressFromHashString(req.body.address); } catch (exception) { console.error(exception); res.send(403, "Invalid address '" + req.body.address + "' is outside of the data model's address space."); return; } var namespace = undefined try { namespace = store.openNamespace(address); } catch (exception) { console.error(exception); res.send(404, "Data component '" + req.body.address + "' does not exist in store '" + req.body.store + "'."); return; } try { namespace.fromJSON(req.body.data); } catch (exception) { console.error(exception); res.send(400, "Unable to de-serialize JSON data in request."); return; } res.send(204); }
javascript
{ "resource": "" }
q37741
train
function(req, res) { if (!req._body || (req.body == null) || !req.body) { res.send(400, "Invalid POST missing required request body."); return; } if ((req.body.store == null) || !req.body.store) { res.send(400, "Invalid POST missing 'store' property in request body."); return; } var store = onmStoreDictionary[req.body.store]; if ((store == null) || !store) { res.send(404, "The specified onm data store '" + req.body.store + "' does not exist on this server."); return; } // Delete the store if an address was not specified in the request body. if ((req.body.address == null) || !req.body.address) { console.log("deleting in-memory data store '" + req.body.store + "'."); delete onmStoreDictionary[req.body.store]; res.send(204); return; } // Attempt to delete the specified data component. var addressHash = req.body.address var address = undefined try { address = store.model.createAddressFromHashString(addressHash); } catch (exception) { console.error(exception); res.send(403, "Invalid address '" + req.body.address + "' is outside of the data model's address space."); return; } try { store.removeComponent(address); console.log("removed data component '" + addressHash + "' from in-memory store '" + req.body.store + "'."); res.send(204); } catch (exception) { res.send(412, exception); } }
javascript
{ "resource": "" }
q37742
train
function(target, expectedInterface, ignoreExtra) { if (typeof target !== 'object' || target instanceof Array) { throw new Error('target object not specified, or is not valid (arg #1)'); } if (typeof expectedInterface !== 'object' || expectedInterface instanceof Array) { throw new Error('expected interface not specified, or is not valid (arg #2)'); } var errors = []; var prop; // Make sure that every expected member exists. for (prop in expectedInterface) { if (!target[prop]) { errors.push('Expected member not defined: [' + prop + ']'); } } // Make sure that every member has the correct type. This second // iteration will also ensure that no additional methods are // defined in the target. for (prop in target) { if (target.hasOwnProperty(prop)) { var expectedType = expectedInterface[prop] || 'undefined'; if (expectedType !== 'undefined' || !ignoreExtra) { var propertyType = (typeof target[prop]); if (expectedType !== 'ignore' && propertyType !== expectedType) { errors.push('Expected member [' + prop + '] to be of type [' + expectedType + '], but was of type [' + propertyType + '] instead'); } } } } return errors; }
javascript
{ "resource": "" }
q37743
train
function(ref, condition) { condition = condition || {}; utils.assert( condition.then || condition.otherwise , 'one of condition.then or condition.otherwise must be existed' ); utils.assert( !condition.then || (condition.then && condition.then.isOvt), 'condition.then must be a valid ovt schema' ); utils.assert( !condition.otherwise || (condition.otherwise && condition.otherwise.isOvt), 'condition.otherwise must be a valid ovt schema' ); if (utils.isString(ref)) ref = utils.ref(ref); utils.assert(utils.isRef(ref), 'ref must be a valid string or ref object'); // overwrite `then` and `otherwise` options to allow unknown and not stripped let options = { allowUnknown: true, stripUnknown: false }; if (condition.then) condition.then = condition.then.options(options); if (condition.otherwise) condition.otherwise = condition.otherwise.options(options); return [ref, condition]; }
javascript
{ "resource": "" }
q37744
getHref
train
function getHref() { return this.context.router.makeHref(this.props.to, this.props.params, this.props.query); }
javascript
{ "resource": "" }
q37745
makePath
train
function makePath(to, params, query) { return this.context.router.makePath(to, params, query); }
javascript
{ "resource": "" }
q37746
makeHref
train
function makeHref(to, params, query) { return this.context.router.makeHref(to, params, query); }
javascript
{ "resource": "" }
q37747
isActive
train
function isActive(to, params, query) { return this.context.router.isActive(to, params, query); }
javascript
{ "resource": "" }
q37748
appendChild
train
function appendChild(route) { invariant(route instanceof Route, 'route.appendChild must use a valid Route'); if (!this.childRoutes) this.childRoutes = []; this.childRoutes.push(route); }
javascript
{ "resource": "" }
q37749
makePath
train
function makePath(to, params, query) { var path; if (PathUtils.isAbsolute(to)) { path = to; } else { var route = to instanceof Route ? to : Router.namedRoutes[to]; invariant(route instanceof Route, 'Cannot find a route named "%s"', to); path = route.path; } return PathUtils.withQuery(PathUtils.injectParams(path, params), query); }
javascript
{ "resource": "" }
q37750
makeHref
train
function makeHref(to, params, query) { var path = Router.makePath(to, params, query); return location === HashLocation ? '#' + path : path; }
javascript
{ "resource": "" }
q37751
goBack
train
function goBack() { if (History.length > 1 || location === RefreshLocation) { location.pop(); return true; } warning(false, 'goBack() was ignored because there is no router history'); return false; }
javascript
{ "resource": "" }
q37752
isActive
train
function isActive(to, params, query) { if (PathUtils.isAbsolute(to)) { return to === state.path; }return routeIsActive(state.routes, to) && paramsAreActive(state.params, params) && (query == null || queryIsActive(state.query, query)); }
javascript
{ "resource": "" }
q37753
extractParams
train
function extractParams(pattern, path) { var _compilePattern = compilePattern(pattern); var matcher = _compilePattern.matcher; var paramNames = _compilePattern.paramNames; var match = path.match(matcher); if (!match) { return null; }var params = {}; paramNames.forEach(function (paramName, index) { params[paramName] = match[index + 1]; }); return params; }
javascript
{ "resource": "" }
q37754
injectParams
train
function injectParams(pattern, params) { params = params || {}; var splatIndex = 0; return pattern.replace(paramInjectMatcher, function (match, paramName) { paramName = paramName || 'splat'; // If param is optional don't check for existence if (paramName.slice(-1) === '?') { paramName = paramName.slice(0, -1); if (params[paramName] == null) return ''; } else { invariant(params[paramName] != null, 'Missing "%s" parameter for path "%s"', paramName, pattern); } var segment; if (paramName === 'splat' && Array.isArray(params[paramName])) { segment = params[paramName][splatIndex++]; invariant(segment != null, 'Missing splat # %s for path "%s"', splatIndex, pattern); } else { segment = params[paramName]; } return segment; }).replace(paramInjectTrailingSlashMatcher, '/'); }
javascript
{ "resource": "" }
q37755
extractQuery
train
function extractQuery(path) { var match = path.match(queryMatcher); return match && qs.parse(match[1]); }
javascript
{ "resource": "" }
q37756
withQuery
train
function withQuery(path, query) { var existingQuery = PathUtils.extractQuery(path); if (existingQuery) query = query ? assign(existingQuery, query) : existingQuery; var queryString = qs.stringify(query, { arrayFormat: 'brackets' }); if (queryString) { return PathUtils.withoutQuery(path) + '?' + queryString; }return PathUtils.withoutQuery(path); }
javascript
{ "resource": "" }
q37757
Transition
train
function Transition(path, retry) { this.path = path; this.abortReason = null; // TODO: Change this to router.retryTransition(transition) this.retry = retry.bind(this); }
javascript
{ "resource": "" }
q37758
findMatch
train
function findMatch(routes, path) { var pathname = PathUtils.withoutQuery(path); var query = PathUtils.extractQuery(path); var match = null; for (var i = 0, len = routes.length; match == null && i < len; ++i) match = deepSearch(routes[i], pathname, query); return match; }
javascript
{ "resource": "" }
q37759
bindAutoBindMethod
train
function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ("production" !== process.env.NODE_ENV) { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; /* eslint-disable block-scoped-var, no-undef */ boundMethod.bind = function(newThis ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { ("production" !== process.env.NODE_ENV ? warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ) : null); } else if (!args.length) { ("production" !== process.env.NODE_ENV ? warning( false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName ) : null); return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; /* eslint-enable */ }; } return boundMethod; }
javascript
{ "resource": "" }
q37760
train
function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== process.env.NODE_ENV) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }
javascript
{ "resource": "" }
q37761
getName
train
function getName(instance) { var publicInstance = instance && instance.getPublicInstance(); if (!publicInstance) { return undefined; } var constructor = publicInstance.constructor; if (!constructor) { return undefined; } return constructor.displayName || constructor.name || undefined; }
javascript
{ "resource": "" }
q37762
validateExplicitKey
train
function validateExplicitKey(element, parentType) { if (element._store.validated || element.key != null) { return; } element._store.validated = true; warnAndMonitorForKeyUse( 'Each child in an array or iterator should have a unique "key" prop.', element, parentType ); }
javascript
{ "resource": "" }
q37763
validatePropertyKey
train
function validatePropertyKey(name, element, parentType) { if (!NUMERIC_PROPERTY_REGEX.test(name)) { return; } warnAndMonitorForKeyUse( 'Child objects should have non-numeric keys so ordering is preserved.', element, parentType ); }
javascript
{ "resource": "" }
q37764
warnAndMonitorForKeyUse
train
function warnAndMonitorForKeyUse(message, element, parentType) { var ownerName = getCurrentOwnerDisplayName(); var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; var useName = ownerName || parentName; var memoizer = ownerHasKeyUseWarning[message] || ( (ownerHasKeyUseWarning[message] = {}) ); if (memoizer.hasOwnProperty(useName)) { return; } memoizer[useName] = true; var parentOrOwnerAddendum = ownerName ? (" Check the render method of " + ownerName + ".") : parentName ? (" Check the React.render call using <" + parentName + ">.") : ''; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwnerAddendum = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Name of the component that originally created this child. var childOwnerName = getName(element._owner); childOwnerAddendum = (" It was passed a child from " + childOwnerName + "."); } ("production" !== process.env.NODE_ENV ? warning( false, message + '%s%s See https://fb.me/react-warning-keys for more information.', parentOrOwnerAddendum, childOwnerAddendum ) : null); }
javascript
{ "resource": "" }
q37765
validateChildKeys
train
function validateChildKeys(node, parentType) { if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. node._store.validated = true; } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } else if (typeof node === 'object') { var fragment = ReactFragment.extractIfFragment(node); for (var key in fragment) { if (fragment.hasOwnProperty(key)) { validatePropertyKey(key, fragment[key], parentType); } } } } }
javascript
{ "resource": "" }
q37766
is
train
function is(a, b) { if (a !== a) { // NaN return b !== b; } if (a === 0 && b === 0) { // +-0 return 1 / a === 1 / b; } return a === b; }
javascript
{ "resource": "" }
q37767
isValidID
train
function isValidID(id) { return id === '' || ( id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR ); }
javascript
{ "resource": "" }
q37768
isAncestorIDOf
train
function isAncestorIDOf(ancestorID, descendantID) { return ( descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length) ); }
javascript
{ "resource": "" }
q37769
train
function(nextComponent, container) { ("production" !== process.env.NODE_ENV ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), '_registerComponent(...): Target container is not a DOM element.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }
javascript
{ "resource": "" }
q37770
train
function( nextElement, container, shouldReuseMarkup ) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. ("production" !== process.env.NODE_ENV ? warning( ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); var componentInstance = instantiateReactComponent(nextElement, null); var reactRootID = ReactMount._registerComponent( componentInstance, container ); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates( batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup ); if ("production" !== process.env.NODE_ENV) { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; }
javascript
{ "resource": "" }
q37771
train
function(constructor, props, container) { var element = ReactElement.createElement(constructor, props); return ReactMount.render(element, container); }
javascript
{ "resource": "" }
q37772
train
function(id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if ("production" !== process.env.NODE_ENV) { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { ("production" !== process.env.NODE_ENV ? invariant( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.' ) : invariant(// Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID)); var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { ("production" !== process.env.NODE_ENV ? warning( false, 'ReactMount: Root element has been removed from its original ' + 'container. New container:', rootElement.parentNode ) : null); } } } return container; }
javascript
{ "resource": "" }
q37773
train
function(node) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component return false; } var id = ReactMount.getID(node); return id ? id.charAt(0) === SEPARATOR : false; }
javascript
{ "resource": "" }
q37774
train
function(node) { var current = node; while (current && current.parentNode !== current) { if (ReactMount.isRenderedByReact(current)) { return current; } current = current.parentNode; } return null; }
javascript
{ "resource": "" }
q37775
train
function(publicInstance, partialProps) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'setProps' ); if (!internalInstance) { return; } ("production" !== process.env.NODE_ENV ? invariant( internalInstance._isTopLevel, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.' ) : invariant(internalInstance._isTopLevel)); // Merge with the pending element if it exists, otherwise with existing // element props. var element = internalInstance._pendingElement || internalInstance._currentElement; var props = assign({}, element.props, partialProps); internalInstance._pendingElement = ReactElement.cloneAndReplaceProps( element, props ); enqueueUpdate(internalInstance); }
javascript
{ "resource": "" }
q37776
train
function(transaction, prevElement, nextElement, context) { assertValidProps(this._currentElement.props); this._updateDOMProperties(prevElement.props, transaction); this._updateDOMChildren(prevElement.props, transaction, context); }
javascript
{ "resource": "" }
q37777
isNode
train
function isNode(object) { return !!(object && ( ((typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')) )); }
javascript
{ "resource": "" }
q37778
train
function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== process.env.NODE_ENV ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } }
javascript
{ "resource": "" }
q37779
train
function(id, styles) { var node = ReactMount.getNode(id); CSSPropertyOperations.setValueForStyles(node, styles); }
javascript
{ "resource": "" }
q37780
train
function(id, content) { var node = ReactMount.getNode(id); DOMChildrenOperations.updateTextContent(node, content); }
javascript
{ "resource": "" }
q37781
insertChildAt
train
function insertChildAt(parentNode, childNode, index) { // By exploiting arrays returning `undefined` for an undefined index, we can // rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. However, using `undefined` is not allowed by all // browsers so we must replace it with `null`. parentNode.insertBefore( childNode, parentNode.childNodes[index] || null ); }
javascript
{ "resource": "" }
q37782
findParent
train
function findParent(node) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; }
javascript
{ "resource": "" }
q37783
train
function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; }
javascript
{ "resource": "" }
q37784
isInternalComponentType
train
function isInternalComponentType(type) { return ( typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function' ); }
javascript
{ "resource": "" }
q37785
enqueueMarkup
train
function enqueueMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, textContent: null, fromIndex: null, toIndex: toIndex }); }
javascript
{ "resource": "" }
q37786
train
function(nextNestedChildren, transaction, context) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildren, transaction, context); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }
javascript
{ "resource": "" }
q37787
adler32
train
function adler32(data) { var a = 1; var b = 0; for (var i = 0; i < data.length; i++) { a = (a + data.charCodeAt(i)) % MOD; b = (b + a) % MOD; } return a | (b << 16); }
javascript
{ "resource": "" }
q37788
train
function(partialProps, callback) { // This is a deoptimized path. We optimize for always having an element. // This creates an extra internal element. var element = this._pendingElement || this._currentElement; this._pendingElement = ReactElement.cloneAndReplaceProps( element, assign({}, element.props, partialProps) ); ReactUpdates.enqueueUpdate(this, callback); }
javascript
{ "resource": "" }
q37789
Graphics
train
function Graphics() { Container.call(this); /** * The alpha value used when filling the Graphics object. * * @member {number} * @default 1 */ this.fillAlpha = 1; /** * The width (thickness) of any lines drawn. * * @member {number} * @default 0 */ this.lineWidth = 0; /** * The color of any lines drawn. * * @member {string} * @default 0 */ this.lineColor = 0; /** * Graphics data * * @member {GraphicsData[]} * @private */ this.graphicsData = []; /** * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint. * * @member {number} * @default 0xFFFFFF */ this.tint = 0xFFFFFF; /** * The previous tint applied to the graphic shape. Used to compare to the current tint and check if theres change. * * @member {number} * @private * @default 0xFFFFFF */ this._prevTint = 0xFFFFFF; /** * The blend mode to be applied to the graphic shape. Apply a value of blendModes.NORMAL to reset the blend mode. * * @member {number} * @default CONST.BLEND_MODES.NORMAL; */ this.blendMode = CONST.BLEND_MODES.NORMAL; /** * Current path * * @member {GraphicsData} * @private */ this.currentPath = null; /** * Array containing some WebGL-related properties used by the WebGL renderer. * * @member {object<number, object>} * @private */ // TODO - _webgl should use a prototype object, not a random undocumented object... this._webGL = {}; /** * Whether this shape is being used as a mask. * * @member {boolean} */ this.isMask = false; /** * The bounds' padding used for bounds calculation. * * @member {number} */ this.boundsPadding = 0; /** * A cache of the local bounds to prevent recalculation. * * @member {Rectangle} * @private */ this._localBounds = new math.Rectangle(0,0,1,1); /** * Used to detect if the graphics object has changed. If this is set to true then the graphics * object will be recalculated. * * @member {boolean} * @private */ this.dirty = true; /** * Used to detect if the WebGL graphics object has changed. If this is set to true then the * graphics object will be recalculated. * * @member {boolean} * @private */ this.glDirty = false; this.boundsDirty = true; /** * Used to detect if the cached sprite object needs to be updated. * * @member {boolean} * @private */ this.cachedSpriteDirty = false; }
javascript
{ "resource": "" }
q37790
train
function(opts) { EventEmitter.call(this); this.opts = opts; this.servers = {}; // remote server info map, key: server id, value: info this.serversMap = {}; // remote server info map, key: serverType, value: servers array this.onlines = {}; // remote server online map, key: server id, value: 0/offline 1/online this.mailboxFactory = opts.mailboxFactory || defaultMailboxFactory; // filters this.befores = []; this.afters = []; // pending request queues this.pendings = {}; this.pendingSize = opts.pendingSize || constants.DEFAULT_PARAM.DEFAULT_PENDING_SIZE; // connecting remote server mailbox map this.connecting = {}; // working mailbox map this.mailboxes = {}; this.state = STATE_INITED; }
javascript
{ "resource": "" }
q37791
couchdb
train
function couchdb (json) { return { prepareEndpoint (endpointOptions, sourceOptions) { return prepareEndpoint(json, endpointOptions, sourceOptions) }, async send (request) { return send(json, request) }, async serialize (data, request) { const serializedData = await serializeData(data, request, json) return json.serialize(serializedData, request) }, async normalize (data, request) { const normalizedData = await json.normalize(data, request) return normalizeData(normalizedData) } } }
javascript
{ "resource": "" }
q37792
train
function(zip, callback) { var queryString = "?postalCode="+zip; httpGet(queryString, function(err, results) { callback(err, results); }); }
javascript
{ "resource": "" }
q37793
train
function(lat, lon, callback) { var queryString = "?latitude="+lat+"&longitude="+lon; httpGet(queryString, function(err, results) { callback(err, results); }); }
javascript
{ "resource": "" }
q37794
hasClass
train
function hasClass(element, className) { if (!hasClassNameProperty(element)) { return false; } return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; }
javascript
{ "resource": "" }
q37795
goToUrl
train
function goToUrl(url) { if (!url) { return; } if (_.isArray(url)) { url = url.join('/'); } var hasHttp = url.indexOf('http') === 0; if (!hasHttp && url.indexOf('/') !== 0) { url = '/' + url; } hasHttp ? $window.location.href = url : $location.path(url); }
javascript
{ "resource": "" }
q37796
getQueryParams
train
function getQueryParams(params) { params = params || {}; var url = $location.url(); var idx = url.indexOf('?'); // if there is a query string if (idx < 0) { return {}; } // get the query string and split the keyvals var query = url.substring(idx + 1); var keyVals = query.split('&'); // put each key/val into the params object _.each(keyVals, function (keyVal) { var keyValArr = keyVal.split('='); params[keyValArr[0]] = keyValArr[1]; }); return params; }
javascript
{ "resource": "" }
q37797
save_config
train
function save_config(path, config) { debug.assert(path).is('string'); debug.assert(config).is('object'); return $Q.fcall(function stringify_json() { return JSON.stringify(config, null, 2); }).then(function write_to_file(data) { return FS.writeFile(path, data, {'encoding':'utf8'}); }); }
javascript
{ "resource": "" }
q37798
train
function (name) { var n = path.extname(name).length; return n === 0 ? name : name.slice(0, -n); }
javascript
{ "resource": "" }
q37799
walk
train
function walk(start, end, fn) { this.start = new Vec2(start); this.end = new Vec2(end); this.direction = calcDirection(this.start, this.end); // positive deltas go right and down this.cellStepDelta = { horizontal: 0, vertical: 0 } this.tMax = new Vec2(); this.tDelta = new Vec2(); this.currentCoord = positionToCoordinate(this.start, this.cellWidth, this.cellHeight); this.endCoord = positionToCoordinate(this.end, this.cellWidth, this.cellHeight); this.initStepMath(); while (!this.isPastEnd()) { fn(coord(this.currentCoord)); if (this.shouldMoveHorizontally()) { this.moveHorizontally(); } else { this.moveVertically(); } } }
javascript
{ "resource": "" }