_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2900
|
train
|
function(client, relayServer, id) {
this.client = client;
this.relayServer = relayServer;
this.id = id;
debug("" + id + ": start player");
var addPlayerToGame = function(data) {
var game = this.relayServer.addPlayerToGame(this, data.gameId, data.data);
if (!game) {
// TODO: Make this URL set from some global so we can set it some place else.
debug("game does not exist:", data.gameId);
this.disconnect();
} else {
this.setGame(game);
}
}.bind(this);
this.setGame = function(game) {
this.game = game;
}.bind(this);
var assignAsServerForGame = function(data) {
this.client.on('message', undefined);
this.client.on('disconnect', undefined);
this.relayServer.assignAsClientForGame(data, this.client);
}.bind(this);
var passMessageFromPlayerToGame = function(data) {
if (!this.game) {
console.warn("player " + this.id + " has no game");
return;
}
this.game.send(this, {
cmd: 'update',
id: this.id,
data: data,
});
}.bind(this);
var messageHandlers = {
'join': addPlayerToGame,
'server': assignAsServerForGame,
'update': passMessageFromPlayerToGame,
};
var onMessage = function(message) {
var cmd = message.cmd;
var handler = messageHandlers[cmd];
if (!handler) {
console.error("unknown player message: " + cmd);
return;
}
handler(message.data);
};
var onDisconnect = function() {
debug("" + this.id + ": disconnected");
if (this.game) {
this.game.removePlayer(this);
}
this.disconnect();
}.bind(this);
client.on('message', onMessage);
client.on('disconnect', onDisconnect);
}
|
javascript
|
{
"resource": ""
}
|
|
q2901
|
train
|
function(gameId, relayServer, options) {
options = options || {};
this.options = options;
this.gameId = gameId;
this.relayServer = relayServer;
this.games = []; // first game is the "master"
this.nextGameId = 0; // start at 0 because it's easy to switch games with (gameNum + numGames + dir) % numGames
}
|
javascript
|
{
"resource": ""
}
|
|
q2902
|
train
|
function(str, opt_obj) {
var dst = opt_obj || {};
try {
var q = str.indexOf("?");
var e = str.indexOf("#");
if (e < 0) {
e = str.length;
}
var query = str.substring(q + 1, e);
searchStringToObject(query, dst);
} catch (e) {
console.error(e);
}
return dst;
}
|
javascript
|
{
"resource": ""
}
|
|
q2903
|
gotoIFrame
|
train
|
function gotoIFrame(src) {
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = src;
document.body.appendChild(iframe);
return iframe;
}
|
javascript
|
{
"resource": ""
}
|
q2904
|
train
|
function(opt_randFunc) {
var randFunc = opt_randFunc || randInt;
var strong = randFunc(3);
var colors = [];
for (var ii = 0; ii < 3; ++ii) {
colors.push(randFunc(128) + (ii === strong ? 128 : 64));
}
return "rgb(" + colors.join(",") + ")";
}
|
javascript
|
{
"resource": ""
}
|
|
q2905
|
train
|
function(opt_randFunc) {
var randFunc = opt_randFunc || randInt;
var strong = randFunc(3);
var color = 0xFF;
for (var ii = 0; ii < 3; ++ii) {
color = (color << 8) | (randFunc(128) + (ii === strong ? 128 : 64));
}
return color;
}
|
javascript
|
{
"resource": ""
}
|
|
q2906
|
train
|
function(selector) {
for (var ii = 0; ii < document.styleSheets.length; ++ii) {
var styleSheet = document.styleSheets[ii];
var rules = styleSheet.cssRules || styleSheet.rules;
if (rules) {
for (var rr = 0; rr < rules.length; ++rr) {
var rule = rules[rr];
if (rule.selectorText === selector) {
return rule;
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2907
|
train
|
function(element) {
var r = { x: element.offsetLeft, y: element.offsetTop };
if (element.offsetParent) {
var tmp = getAbsolutePosition(element.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q2908
|
train
|
function(canvas, useDevicePixelRatio) {
var mult = useDevicePixelRatio ? window.devicePixelRatio : 1;
mult = mult || 1;
var width = Math.floor(canvas.clientWidth * mult);
var height = Math.floor(canvas.clientHeight * mult);
if (canvas.width !== width ||
canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2909
|
applyObject
|
train
|
function applyObject(src, dst) {
Object.keys(src).forEach(function(key) {
dst[key] = src[key];
});
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q2910
|
makeRandomId
|
train
|
function makeRandomId(digits) {
digits = digits || 16;
var id = "";
for (var ii = 0; ii < digits; ++ii) {
id = id + ((Math.random() * 16 | 0)).toString(16);
}
return id;
}
|
javascript
|
{
"resource": ""
}
|
q2911
|
applyListeners
|
train
|
function applyListeners(emitter, listeners) {
Object.keys(listeners).forEach(function(name) {
emitter.addEventListener(name, listeners[name]);
});
}
|
javascript
|
{
"resource": ""
}
|
q2912
|
train
|
function(opt_syncRateSeconds, callback) {
var query = misc.parseUrlQuery();
var url = (query.hftUrl || window.location.href).replace("ws:", "http:");
var syncRateMS = (opt_syncRateSeconds || 10) * 1000;
var timeOffset = 0;
var syncToServer = function(queueNext) {
var sendTime = getLocalTime();
io.sendJSON(url, {cmd: 'time'}, function(exception, obj) {
if (exception) {
console.error("syncToServer: " + exception);
} else {
var receiveTime = getLocalTime();
var duration = receiveTime - sendTime;
var serverTime = obj.time + duration * 0.5;
timeOffset = serverTime - receiveTime;
if (callback) {
callback();
callback = undefined;
}
//g_services.logger.log("duration: ", duration, " timeOff:", timeOffset);
}
if (queueNext) {
setTimeout(function() {
syncToServer(true);
}, syncRateMS);
}
});
};
var syncToServerNoQueue = function() {
syncToServer(false);
};
syncToServer(true);
setTimeout(syncToServerNoQueue, 1000);
setTimeout(syncToServerNoQueue, 2000);
setTimeout(syncToServerNoQueue, 4000);
/**
* Gets the current time in seconds.
* @private
*/
this.getTime = function() {
return getLocalTime() + timeOffset;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q2913
|
train
|
function(url, jsonObject, callback, options) {
var options = JSON.parse(JSON.stringify(options || {}));
options.headers = options.headers || {};
options.headers["Content-type"] = "application/json";
return request(
url,
JSON.stringify(jsonObject),
function(err, content) {
if (err) {
return callback(err);
}
try {
var json = JSON.parse(content);
} catch (e) {
return callback(e);
}
callback(null, json);
},
options);
}
|
javascript
|
{
"resource": ""
}
|
|
q2914
|
ReadableSerial
|
train
|
function ReadableSerial(list, iterator, callback)
{
if (!(this instanceof ReadableSerial))
{
return new ReadableSerial(list, iterator, callback);
}
// turn on object mode
ReadableSerial.super_.call(this, {objectMode: true});
this._start(serial, list, iterator, callback);
}
|
javascript
|
{
"resource": ""
}
|
q2915
|
wrapIterator
|
train
|
function wrapIterator(iterator)
{
var stream = this;
return function(item, key, cb)
{
var aborter
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
;
stream.jobs[key] = wrappedCb;
// it's either shortcut (item, cb)
if (iterator.length == 2)
{
aborter = iterator(item, wrappedCb);
}
// or long format (item, key, cb)
else
{
aborter = iterator(item, key, wrappedCb);
}
return aborter;
};
}
|
javascript
|
{
"resource": ""
}
|
q2916
|
wrapCallback
|
train
|
function wrapCallback(callback)
{
var stream = this;
var wrapped = function(error, result)
{
return finisher.call(stream, error, result, callback);
};
return wrapped;
}
|
javascript
|
{
"resource": ""
}
|
q2917
|
wrapIteratorCallback
|
train
|
function wrapIteratorCallback(callback, key)
{
var stream = this;
return function(error, output)
{
// don't repeat yourself
if (!(key in stream.jobs))
{
callback(error, output);
return;
}
// clean up jobs
delete stream.jobs[key];
return streamer.call(stream, error, {key: key, value: output}, callback);
};
}
|
javascript
|
{
"resource": ""
}
|
q2918
|
streamer
|
train
|
function streamer(error, output, callback)
{
if (error && !this.error)
{
this.error = error;
this.pause();
this.emit('error', error);
// send back value only, as expected
callback(error, output && output.value);
return;
}
// stream stuff
this.push(output);
// back to original track
// send back value only, as expected
callback(error, output && output.value);
}
|
javascript
|
{
"resource": ""
}
|
q2919
|
finisher
|
train
|
function finisher(error, output, callback)
{
// signal end of the stream
// only for successfully finished streams
if (!error)
{
this.push(null);
}
// back to original track
callback(error, output);
}
|
javascript
|
{
"resource": ""
}
|
q2920
|
iterate
|
train
|
function iterate(list, iterator, state, callback)
{
// store current index
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
{
// don't repeat yourself
// skip secondary callbacks
if (!(key in state.jobs))
{
return;
}
// clean up jobs
delete state.jobs[key];
if (error)
{
// don't process rest of the results
// stop still active jobs
// and reset the list
abort(state);
}
else
{
state.results[key] = output;
}
// return salvaged results
callback(error, state.results);
});
}
|
javascript
|
{
"resource": ""
}
|
q2921
|
runJob
|
train
|
function runJob(iterator, key, item, callback)
{
var aborter;
// allow shortcut if iterator expects only two arguments
if (iterator.length == 2)
{
aborter = iterator(item, async(callback));
}
// otherwise go with full three arguments
else
{
aborter = iterator(item, key, async(callback));
}
return aborter;
}
|
javascript
|
{
"resource": ""
}
|
q2922
|
serialOrdered
|
train
|
function serialOrdered(list, iterator, sortMethod, callback)
{
var state = initState(list, sortMethod);
iterate(list, iterator, state, function iteratorHandler(error, result)
{
if (error)
{
callback(error, result);
return;
}
state.index++;
// are we there yet?
if (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, iteratorHandler);
return;
}
// done here
callback(null, state.results);
});
return terminator.bind(state, callback);
}
|
javascript
|
{
"resource": ""
}
|
q2923
|
ReadableParallel
|
train
|
function ReadableParallel(list, iterator, callback)
{
if (!(this instanceof ReadableParallel))
{
return new ReadableParallel(list, iterator, callback);
}
// turn on object mode
ReadableParallel.super_.call(this, {objectMode: true});
this._start(parallel, list, iterator, callback);
}
|
javascript
|
{
"resource": ""
}
|
q2924
|
ReadableSerialOrdered
|
train
|
function ReadableSerialOrdered(list, iterator, sortMethod, callback)
{
if (!(this instanceof ReadableSerialOrdered))
{
return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
}
// turn on object mode
ReadableSerialOrdered.super_.call(this, {objectMode: true});
this._start(serialOrdered, list, iterator, sortMethod, callback);
}
|
javascript
|
{
"resource": ""
}
|
q2925
|
_start
|
train
|
function _start()
{
// first argument – runner function
var runner = arguments[0]
// take away first argument
, args = Array.prototype.slice.call(arguments, 1)
// second argument - input data
, input = args[0]
// last argument - result callback
, endCb = streamify.callback.call(this, args[args.length - 1])
;
args[args.length - 1] = endCb;
// third argument - iterator
args[1] = streamify.iterator.call(this, args[1]);
// allow time for proper setup
defer(function()
{
if (!this.destroyed)
{
this.terminator = runner.apply(null, args);
}
else
{
endCb(null, Array.isArray(input) ? [] : {});
}
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q2926
|
state
|
train
|
function state(list, sortMethod)
{
var isNamedList = !Array.isArray(list)
, initState =
{
index : 0,
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
jobs : {},
results : isNamedList ? {} : [],
size : isNamedList ? Object.keys(list).length : list.length
}
;
if (sortMethod)
{
// sort array keys based on it's values
// sort object's keys just on own merit
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
{
return sortMethod(list[a], list[b]);
});
}
return initState;
}
|
javascript
|
{
"resource": ""
}
|
q2927
|
abort
|
train
|
function abort(state)
{
Object.keys(state.jobs).forEach(clean.bind(state));
// reset leftover jobs
state.jobs = {};
}
|
javascript
|
{
"resource": ""
}
|
q2928
|
async
|
train
|
function async(callback)
{
var isAsync = false;
// check if async happened
defer(function() { isAsync = true; });
return function async_callback(err, result)
{
if (isAsync)
{
callback(err, result);
}
else
{
defer(function nextTick_callback()
{
callback(err, result);
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
q2929
|
parallel
|
train
|
function parallel(list, iterator, callback)
{
var state = initState(list);
while (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, function(error, result)
{
if (error)
{
callback(error, result);
return;
}
// looks like it's the last one
if (Object.keys(state.jobs).length === 0)
{
callback(null, state.results);
return;
}
});
state.index++;
}
return terminator.bind(state, callback);
}
|
javascript
|
{
"resource": ""
}
|
q2930
|
terminator
|
train
|
function terminator(callback)
{
if (!Object.keys(this.jobs).length)
{
return;
}
// fast forward iteration index
this.index = this.size;
// abort jobs
abort(this);
// send back results we have so far
async(callback)(null, this.results);
}
|
javascript
|
{
"resource": ""
}
|
q2931
|
train
|
function(serverName, config, options) {
this.methods[serverName] = {};
this.config.servers[serverName] = config;
var self = this;
['valid_grant', 'treat_access_token', 'transform_token_response'].forEach(function(fctName) {
self.methods[serverName][fctName] = options[fctName] || self[fctName].bind(self);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2932
|
train
|
function(data, code, callback) {
var self = this;
var cconfig = this.config.client;
var sconfig = this.config.servers[data.oauth2_server_id];
request.post({uri: sconfig.server_token_endpoint,
headers: {'content-type': 'application/x-www-form-urlencoded'},
body: querystring.stringify({
grant_type: "authorization_code",
client_id: sconfig.client_id,
code: code,
client_secret: sconfig.client_secret,
redirect_uri: cconfig.redirect_uri
})
}, function(error, response, body) {
console.log(body);
if (!error && response.statusCode == 200) {
try {
var methods = self.methods[data.oauth2_server_id];
var token = methods.transform_token_response(body)
callback(null, token);
} catch(err) {
callback(err);
}
} else {
// TODO: check if error code indicates problem on the client,
console.error(error, body);
callback(error);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2933
|
train
|
function(req, res) {
var params = URL.parse(req.url, true).query
, code = params.code
, state = params.state
;
if(!code) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "code" parameter is missing.');
}
if(!state) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "state" parameter is missing.');
}
try {
state = this.serializer.parse(state);
} catch(err) {
res.writeHead(400, {'Content-Type': 'text/plain'});
return res.end('The "state" parameter is invalid.');
}
var data = {
oauth2_server_id: state[0]
, next_url: state[1]
, state: state[2]
}
var methods = this.methods[data.oauth2_server_id];
methods.valid_grant(data, code, function(err, token) {
if (err) return server_error(res, err);
if(!token) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('Invalid grant.');
return;
}
data.token = token;
methods.treat_access_token(data, req, res, function() {
redirect(res, data.next_url);
}, function(err){server_error(res, err)});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2934
|
train
|
function(oauth2_server_id, res, next_url, state) {
var sconfig = this.config.servers[oauth2_server_id];
var cconfig = this.config.client;
var data = {
client_id: sconfig.client_id,
redirect_uri: cconfig.redirect_uri,
response_type: 'code',
state: this.serializer.stringify([oauth2_server_id, next_url, state || null])
};
var url = sconfig.server_authorize_endpoint +'?'+ querystring.stringify(data);
redirect(res, url);
}
|
javascript
|
{
"resource": ""
}
|
|
q2935
|
train
|
function(req, params) {
if(!params) {
params = URL.parse(req.url, true).query;
}
var cconfig = this.config.client;
var next = params.next || cconfig.default_redirection_url;
var url = cconfig.base_url + next;
return url;
}
|
javascript
|
{
"resource": ""
}
|
|
q2936
|
train
|
function(req, res) {
var params = URL.parse(req.url, true).query;
var oauth2_server_id = params.provider || this.config.default_server;
var next_url = this.nexturl_query(req, params);
this.redirects_for_login(oauth2_server_id, res, next_url);
}
|
javascript
|
{
"resource": ""
}
|
|
q2937
|
train
|
function() {
var client = this;
var cconf = this.config.client;
return router(function(app) {
app.get(cconf.process_login_url, client.auth_process_login.bind(client));
app.get(cconf.login_url, client.login.bind(client));
app.get(cconf.logout_url, client.logout.bind(client));
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2938
|
createClient
|
train
|
function createClient(conf, options) {
conf.default_redirection_url = conf.default_redirection_url || '/';
options = options || {};
return new OAuth2Client(conf, options);
}
|
javascript
|
{
"resource": ""
}
|
q2939
|
Loop
|
train
|
function Loop(messenger)
{
// Messenger we'll use for clock signals
this.messenger = messenger || new Messenger();
this.fixedDuration = 8;
this.started = false;
// Live stats
this.currentTime = 0;
this.fixedStepsPerFrame = 0;
this.fixedTimePerFrame = 0;
this.renderTimePerFrame = 0;
this.frameTime = 0;
}
|
javascript
|
{
"resource": ""
}
|
q2940
|
kepler
|
train
|
function kepler (m, ecc) {
const epsilon = 1e-6
m = torad(m)
let e = m
while (1) {
const delta = e - ecc * Math.sin(e) - m
e -= delta / (1.0 - ecc * Math.cos(e))
if (Math.abs(delta) <= epsilon) {
break
}
}
return e
}
|
javascript
|
{
"resource": ""
}
|
q2941
|
phase
|
train
|
function phase (phase_date) {
if (!phase_date) {
phase_date = new Date()
}
phase_date = julian.fromDate(phase_date)
const day = phase_date - EPOCH
// calculate sun position
const sun_mean_anomaly =
(360.0 / 365.2422) * day +
(ECLIPTIC_LONGITUDE_EPOCH - ECLIPTIC_LONGITUDE_PERIGEE)
const sun_true_anomaly =
2 * todeg(Math.atan(
Math.sqrt((1.0 + ECCENTRICITY) / (1.0 - ECCENTRICITY)) *
Math.tan(0.5 * kepler(sun_mean_anomaly, ECCENTRICITY))
))
const sun_ecliptic_longitude =
ECLIPTIC_LONGITUDE_PERIGEE + sun_true_anomaly
const sun_orbital_distance_factor =
(1 + ECCENTRICITY * dcos(sun_true_anomaly)) /
(1 - ECCENTRICITY * ECCENTRICITY)
// calculate moon position
const moon_mean_longitude =
MOON_MEAN_LONGITUDE_EPOCH + 13.1763966 * day
const moon_mean_anomaly =
moon_mean_longitude - 0.1114041 * day - MOON_MEAN_PERIGEE_EPOCH
const moon_evection =
1.2739 * dsin(
2 * (moon_mean_longitude - sun_ecliptic_longitude) - moon_mean_anomaly
)
const moon_annual_equation =
0.1858 * dsin(sun_mean_anomaly)
// XXX: what is the proper name for this value?
const moon_mp =
moon_mean_anomaly +
moon_evection -
moon_annual_equation -
0.37 * dsin(sun_mean_anomaly)
const moon_equation_center_correction =
6.2886 * dsin(moon_mp)
const moon_corrected_longitude =
moon_mean_longitude +
moon_evection +
moon_equation_center_correction -
moon_annual_equation +
0.214 * dsin(2.0 * moon_mp)
const moon_age =
fixangle(
moon_corrected_longitude -
sun_ecliptic_longitude +
0.6583 * dsin(
2 * (moon_corrected_longitude - sun_ecliptic_longitude)
)
)
const moon_distance =
(MOON_SMAXIS * (1.0 - MOON_ECCENTRICITY * MOON_ECCENTRICITY)) /
(1.0 + MOON_ECCENTRICITY * dcos(moon_mp + moon_equation_center_correction))
return {
phase: (1.0 / 360.0) * moon_age,
illuminated: 0.5 * (1.0 - dcos(moon_age)),
age: (SYNODIC_MONTH / 360.0) * moon_age,
distance: moon_distance,
angular_diameter: MOON_ANGULAR_SIZE_SMAXIS / moon_distance,
sun_distance: SUN_SMAXIS / sun_orbital_distance_factor,
sun_angular_diameter: SUN_ANGULAR_SIZE_SMAXIS * sun_orbital_distance_factor
}
}
|
javascript
|
{
"resource": ""
}
|
q2942
|
phase_hunt
|
train
|
function phase_hunt (sdate) {
if (!sdate) {
sdate = new Date()
}
let adate = new Date(sdate.getTime() - (45 * 86400000)) // 45 days prior
let k1 = Math.floor(12.3685 * (adate.getFullYear() + (1.0 / 12.0) * adate.getMonth() - 1900))
let nt1 = meanphase(adate.getTime(), k1)
sdate = julian.fromDate(sdate)
adate = nt1 + SYNODIC_MONTH
let k2 = k1 + 1
let nt2 = meanphase(adate, k2)
while (nt1 > sdate || sdate >= nt2) {
adate += SYNODIC_MONTH
k1++
k2++
nt1 = nt2
nt2 = meanphase(adate, k2)
}
return {
new_date: truephase(k1, NEW),
q1_date: truephase(k1, FIRST),
full_date: truephase(k1, FULL),
q3_date: truephase(k1, LAST),
nextnew_date: truephase(k2, NEW)
}
}
|
javascript
|
{
"resource": ""
}
|
q2943
|
generateTable
|
train
|
function generateTable() {
var data = []
for (var i=0; i<30; i++) {
var row = []
row.push(commands[Math.round(Math.random()*(commands.length-1))])
row.push(Math.round(Math.random()*5))
row.push(Math.round(Math.random()*100))
data.push(row)
}
return {headers: ['Process', 'Cpu (%)', 'Memory'], data: data};
}
|
javascript
|
{
"resource": ""
}
|
q2944
|
Grid
|
train
|
function Grid(props) {
const grid = new contrib.grid({...props, screen: { append: () => {} }});
const children = props.children instanceof Array ? props.children : [props.children];
return React.createElement(props.component || 'element', {}, children.map((child, key) => {
const props = child.props;
const options = grid.set(props.row, props.col, props.rowSpan || 1, props.colSpan || 1, x => x, props.options);
options.key = key;
return React.cloneElement(child, options);
}));
}
|
javascript
|
{
"resource": ""
}
|
q2945
|
parse
|
train
|
function parse (input, opts) {
// Wrap parser.parse to allow specifying the start rule
// as a shorthand option
if (!opts) {
opts = {}
}
else if (typeof opts == 'string') {
opts = { startRule: opts }
}
return parser.parse(input, opts)
}
|
javascript
|
{
"resource": ""
}
|
q2946
|
partial
|
train
|
function partial(area) {
var allFilter = null;
for (var _len2 = arguments.length, filters = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
filters[_key2 - 1] = arguments[_key2];
}
if (filters.length == 1 && typeof filters[0] === 'string') {
allFilter = filter$1(filters[0]);
} else {
allFilter = merge$1(filters);
}
return function (bitmap, done) {
var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
allFilter(getBitmap(bitmap, area), function (newBitmap) {
done(putBitmap(bitmap, newBitmap, area));
}, opt);
};
}
|
javascript
|
{
"resource": ""
}
|
q2947
|
train
|
function(regex) {
var self = this; var re = new RegExp(regex);
var keys = {};
self.init = function() { keys = {}; };
self.accumulate = function(line) {
var m = re.exec(line);
if (m == null) return;
var k = m[1]; // use 1st group as key
var v = keys[k];
if (v) keys[k] = v+1; else keys[k] = 1; // count by key
};
self.compensate = function(line) {
var m = re.exec(line);
if (m == null) return;
var k = m[1]; // use 1st group as key
var v = keys[k];
if (v) keys[k] = v-1; else keys[k] = 1;
};
self.emit = function() {
return keys;
};
self.make = function() { return new WideFinderFunction(regex); };
}
|
javascript
|
{
"resource": ""
}
|
|
q2948
|
AggregateFunction
|
train
|
function AggregateFunction() {
var self = this;
// function type can be one of
// - simple (default)
// - ordered - will require window to store elements in arrival and sorted order
//
self.type = "simple";
// invoked when a window opens - should 'reset' or 'zero' a windows internal state
self.init = function() { throw "Must subclass"; };
// invoked when an event is enqueued into a window
self.accumulate = function(value) { throw "Must subclass"; };
// invoked to compensate sliding window overwrite
self.compensate = function(value) { throw "Must subclass"; };
// invoked when a window closes
self.emit = function() { throw "Must subclass"; };
// used by window implementations variously to preallocate function instances - makes things 'fast', basically
self.make = function(win) { throw "Must subclass"; };
}
|
javascript
|
{
"resource": ""
}
|
q2949
|
CountFunction
|
train
|
function CountFunction(win) {
var self = this, n;
self.name = "count";
self.type = "simple";
self.init = function() { n = 0; };
self.accumulate = function(ignored) { n += 1; };
self.compensate = function(ignored) { n -= 1; };
self.emit = function() { return n; };
self.make = function(win) { return new CountFunction(win); };
}
|
javascript
|
{
"resource": ""
}
|
q2950
|
SumFunction
|
train
|
function SumFunction(win) {
var self = this, s;
self.name = "sum";
self.type = "simple";
self.init = function() { s = 0; };
self.accumulate = function(v) { s += v; };
self.compensate = function(v) { s -= v; };
self.emit = function() { return s; };
self.make = function(win) { return new SumFunction(win); };
}
|
javascript
|
{
"resource": ""
}
|
q2951
|
MinFunction
|
train
|
function MinFunction(win) {
var self = this, r;
self.win = win;
self.name = "min";
self.type = "ordered_reverse";
self.init = function() { r = null; };
self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v < r) ? v : r; };
self.compensate = function(v) { r = self.win.min(); };
self.emit = function() { return r; };
self.make = function(win) { return new MinFunction(win); };
}
|
javascript
|
{
"resource": ""
}
|
q2952
|
MaxFunction
|
train
|
function MaxFunction(win) {
var self = this, r;
self.win = win;
self.name = "max";
self.type = "ordered_reverse";
self.init = function() { r = null; };
self.accumulate = function(v) { if (v == null) { return; } if (r == null) { r = v; return; } r = (v > r) ? v : r; };
self.compensate = function(v) { r = self.win.max(); };
self.emit = function() { return r; };
self.make = function(win) { return new MaxFunction(win); };
}
|
javascript
|
{
"resource": ""
}
|
q2953
|
VarianceFunction
|
train
|
function VarianceFunction(win) {
var self = this, m, m2, d, n;
self.name = "vars";
self.type = "simple";
self.init = function() { m = 0; m2 = 0; d = 0; n = 0; };
self.accumulate = function(v) { n+=1; d = v - m; m = d/n + m; m2 = m2 + d*(v - m); };
self.compensate = function(v) { n-=1; d = m - v; m = m + d/n; m2 = d*(v - m) + m2; };
self.emit = function() { return m2/(n-1); };
self.make = function(win) { return new VarianceFunction(win); };
}
|
javascript
|
{
"resource": ""
}
|
q2954
|
StdevFunction
|
train
|
function StdevFunction(win) {
var self = this, m, m2, d, n;
self.name = "stdevs";
self.type = "simple";
self.init = function() { m = 0, m2 = 0, d = 0, n = 0; };
self.accumulate = function(v) {
n+=1;
d = v - m;
m = m + d/n;
m2 = m2 + d*(v-m);
};
self.compensate = function(v) {
n-=1;
d = m - v;
m = d/n + m;
m2 = d*(v-m) + m2;
};
self.emit = function() { return Math.sqrt(m2/(n-1)); };
self.make = function(win) { return new StdevFunction(win); };
}
|
javascript
|
{
"resource": ""
}
|
q2955
|
CountingClock
|
train
|
function CountingClock() {
var self = this, at, mark = null;
self.at = function() {
return at;
};
self.init = function() {
at = mark = 0;
return at;
};
self.inc = function() {
at += 1;
};
self.tick = function() {
if (mark === null) {
mark = at + 1;
}
return ((at - mark) >= 1);
};
self.tock = function(elapsed) {
var d = at - elapsed;
if ( d >= 1) {
mark += 1;
return true;
}
return false;
};
}
|
javascript
|
{
"resource": ""
}
|
q2956
|
getFolders
|
train
|
function getFolders(dir) {
try {
return fs.readdirSync(dir)
.filter(function (file) {
return exports.isDirectory(path.join(dir, file));
});
} catch (ex) {
return [];
}
}
|
javascript
|
{
"resource": ""
}
|
q2957
|
tryRequire
|
train
|
function tryRequire(filePath) {
let resolvedPath = req.resolve(filePath);
if (resolvedPath) {
return req(resolvedPath);
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q2958
|
tryRequireEach
|
train
|
function tryRequireEach(paths) {
let result;
while (!result && paths.length) {
result = tryRequire(paths.shift());
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q2959
|
memoize
|
train
|
function memoize(fn) {
const dataProp = '__data__.string.__data__',
memFn = _.memoize.apply(_, _.slice(arguments)),
report = _.throttle(reportMemoryLeak, minute),
controlFn = function () {
const result = memFn.apply(null, _.slice(arguments));
if (_.size(_.get(memFn, `cache.${dataProp}`)) >= memoryLeakThreshold) {
report(fn, _.get(memFn, `cache.${dataProp}`));
}
return result;
};
Object.defineProperty(controlFn, 'cache', defineWritable({
get() { return memFn.cache; },
set(value) { memFn.cache = value; }
}));
return controlFn;
}
|
javascript
|
{
"resource": ""
}
|
q2960
|
iterateObject
|
train
|
function iterateObject(obj, fn) {
var i = 0
, keys = []
;
if (Array.isArray(obj)) {
for (; i < obj.length; ++i) {
if (fn(obj[i], i, obj) === false) {
break;
}
}
} else if (typeof obj === "object" && obj !== null) {
keys = Object.keys(obj);
for (; i < keys.length; ++i) {
if (fn(obj[keys[i]], keys[i], obj) === false) {
break;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q2961
|
compareMappingsDeep
|
train
|
function compareMappingsDeep(mapping1, mapping2) {
return _.isEqualWith(mapping1, mapping2, (object1, object2, prop) => {
let mapping1 = { [prop]: object1 }
let mapping2 = { [prop]: object2 }
if (prop == "from" || prop == "to") {
if (!_.isEqual(Object.getOwnPropertyNames(_.get(object1, prop, {})), Object.getOwnPropertyNames(_.get(object2, prop, {})))) {
return false
}
return _.isEqualWith(conceptsOfMapping(mapping1, prop), conceptsOfMapping(mapping2, prop), (concept1, concept2, index) => {
if (index != undefined) {
return compare(concept1, concept2)
}
return undefined
})
}
if (prop == "fromScheme" || prop == "toScheme") {
return compare(object1, object2)
}
// Let lodash's isEqual do the comparison
return undefined
})
}
|
javascript
|
{
"resource": ""
}
|
q2962
|
toBemjson
|
train
|
function toBemjson(tree, options) {
const transform = transformFactory(tree, options);
return traverse(transform, tree);
}
|
javascript
|
{
"resource": ""
}
|
q2963
|
makeLoginHandler
|
train
|
function makeLoginHandler(provider, providerAccounts) {
return function (accessToken, refreshToken, profile, done) {
log.debug('Authentiated for ' + provider);
log.debug(profile);
profile.provider = provider;
profile.idWithProvider = profile.id;
exports.getUserFromProfile(providerAccounts, profile)
.then(function (userRecord) {
// Save the user if they are new.
var fieldsToCopy = ['provider', 'displayName', 'emails'];
if (userRecord && userRecord.data) {
return userRecord;
} else {
userRecord = {
isAuthenticated: true
};
userRecord.meta = {
isRegistered: false
};
userRecord.data = {
idWithProvider: profile.id,
};
fieldsToCopy.forEach(function (key) {
userRecord.data[key] = profile[key];
});
return providerAccounts.create(userRecord.data)
.then(function () {
return userRecord;
});
}
})
.then(function (userRecord) {
done(null, userRecord);
})
.then(null, function (error) {
log.error(error);
done(error);
})
.then(null, log.error);
};
}
|
javascript
|
{
"resource": ""
}
|
q2964
|
redirectToNext
|
train
|
function redirectToNext(req, res) {
var redirectTo = req.session.next || '';
req.session.next = null; // Null it so that we do not use it again.
res.redirect(redirectTo);
}
|
javascript
|
{
"resource": ""
}
|
q2965
|
setupStrategies
|
train
|
function setupStrategies(auth) {
var result = {};
if (auth.maintenance === 'token') {
result = {
facebook: require('passport-facebook').Strategy,
twitter: require('passport-twitter').Strategy
};
} else {
result = {
google: require('passport-google-oauth').OAuth2Strategy,
facebook: require('passport-facebook').Strategy,
twitter: require('passport-twitter').Strategy
};
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q2966
|
d3_svg_lineHermite
|
train
|
function d3_svg_lineHermite(points, tangents) {
if (tangents.length < 1 || (points.length !== tangents.length && points.length !== tangents.length + 2)) {
return points;
}
var quad = points.length !== tangents.length,
commands = [],
p0 = points[0],
p = points[1],
t0 = tangents[0],
t = t0,
pi = 1;
if (quad) {
commands.push([
p[0] - t0[0] * 2 / 3,
p[1] - t0[1] * 2 / 3,
p[0],
p[1]
]);
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
commands.push([
p0[0] + t0[0],
p0[1] + t0[1],
p[0] - t[0],
p[1] - t[1],
p[0],
p[1]
]);
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
let lt = tangents[i - 1];
let lp = points[i - 1];
commands.push([
lp[0] + lt[0], // Add the last tangent but reflected
lp[1] + lt[1],
p[0] - t[0],
p[1] - t[1],
p[0],
p[1]
]);
}
}
if (quad) {
var lp = points[pi];
commands.push([
p[0] + t[0] * 2 / 3,
p[1] + t[1] * 2 / 3,
lp[0],
lp[1]
]);
}
return commands;
}
|
javascript
|
{
"resource": ""
}
|
q2967
|
Model
|
train
|
function Model(name, table) {
this.model = this;
if(!name || typeof name !== "string"){
throw new Error("Attempting to instantiate a model without a valid name. Create models using the Cassanova.model API.");
}
if(!table){
throw new Error("Attempting to instantiate a model, " + name + ", without a valid table. Create models using the Cassanova.model API.");
}
this.name = name;
this.table = table;
}
|
javascript
|
{
"resource": ""
}
|
q2968
|
off
|
train
|
function off (state, eventName, handler) {
if (arguments.length === 2) {
state.emitter.removeAllListeners(eventName)
} else {
state.emitter.removeListener(eventName, handler)
}
return state.api
}
|
javascript
|
{
"resource": ""
}
|
q2969
|
augmentFactory
|
train
|
function augmentFactory(options) {
/**
* Apply custom augmentation
*
* @param {Object} bemNode - representation of bem entity
* @returns {Object} bemNode
*/
function augment(bemNode) {
if (bemNode.block === 'md-root') {
bemNode.isRoot = true;
}
if (options.html) {
bemNode = augmentHtml(bemNode, options.html);
}
if (options.map) {
bemNode = augmentMap(bemNode, options.map);
}
if (options.prefix) {
bemNode = augmentPrefix(bemNode, options.prefix);
}
if (options.scope) {
bemNode = augmentScope(bemNode, options.scope);
}
if (bemNode.isRoot) delete bemNode.isRoot;
return bemNode;
}
return augment;
}
|
javascript
|
{
"resource": ""
}
|
q2970
|
augmentScope
|
train
|
function augmentScope(bemNode, scope) {
assert(typeof scope === 'string', 'options.scope must be string');
if (bemNode.isRoot) {
bemNode.block = scope;
} else {
bemNode.elem = bemNode.block;
bemNode.elemMods = bemNode.mods;
delete bemNode.block;
delete bemNode.mods;
}
return bemNode;
}
|
javascript
|
{
"resource": ""
}
|
q2971
|
augmentMap
|
train
|
function augmentMap(bemNode, map) {
const name = bemNode.block;
if (map[name]) {
assert(typeof map[name] === 'string', `options.map: new name of ${name} must be string`);
bemNode.block = map[name];
}
return bemNode;
}
|
javascript
|
{
"resource": ""
}
|
q2972
|
intersperse
|
train
|
function intersperse(sep, xs) {
return concat(xs.map(x => [sep, x])).slice(1);
}
|
javascript
|
{
"resource": ""
}
|
q2973
|
groupBy
|
train
|
function groupBy(f, xs) {
const groups = [];
for (const x of xs) {
if (groups.length !== 0 && f(groups[groups.length - 1][0], x)) {
groups[groups.length - 1].push(x);
}
else {
groups.push([x]);
}
}
return groups;
}
|
javascript
|
{
"resource": ""
}
|
q2974
|
groupOn
|
train
|
function groupOn(f, xs) {
return groupBy((a, b) => f(a) === f(b), xs);
}
|
javascript
|
{
"resource": ""
}
|
q2975
|
lessThan
|
train
|
function lessThan(xs, ys) {
for (let i = 0; i < Math.min(xs.length, ys.length); i++) {
if (xs[i] < ys[i])
return true;
if (xs[i] > ys[i])
return false;
}
return xs.length < ys.length;
}
|
javascript
|
{
"resource": ""
}
|
q2976
|
takeWhile
|
train
|
function takeWhile(f, xs) {
const ys = [];
for (const x of xs) {
if (f(x)) {
ys.push(x);
}
else {
break;
}
}
return ys;
}
|
javascript
|
{
"resource": ""
}
|
q2977
|
train
|
function(){
return {
collection: configCollection,
data: config.data,
query: config.query,
offset: config.offset,
limit: config.limit,
where: config.where,
filter: config.filter,
filters: config.filters,
watch: config.watch,
sort: config.sort
};
}
|
javascript
|
{
"resource": ""
}
|
|
q2978
|
train
|
function(props) {
if (typeof props !== 'object') {
throw new Error('_configureItems called with invalid props');
}
// not initialized yet
if (!this._items) {
return;
}
this._items.configure({
where: bindIfFn(props.where, this),
filter: bindIfFn(props.filter, this),
limit: bindIfFn(props.limit, this),
offset: bindIfFn(props.offset, this),
comparator: bindIfFn(props.sort, this)
}, true);
}
|
javascript
|
{
"resource": ""
}
|
|
q2979
|
reposition
|
train
|
function reposition(marker) {
// remember the tile coordinate so we don't have to reproject every time
if (!marker.coord) marker.coord = m.map.locationCoordinate(marker.location);
var pos = m.map.coordinatePoint(marker.coord);
var pos_loc, new_pos;
// If this point has wound around the world, adjust its position
// to the new, onscreen location
if (pos.x < 0) {
pos_loc = new MM.Location(marker.location.lat, marker.location.lon);
pos_loc.lon += Math.ceil((left.lon - marker.location.lon) / 360) * 360;
new_pos = m.map.locationPoint(pos_loc);
if (new_pos.x < m.map.dimensions.x) {
pos = new_pos;
marker.coord = m.map.locationCoordinate(pos_loc);
}
} else if (pos.x > m.map.dimensions.x) {
pos_loc = new MM.Location(marker.location.lat, marker.location.lon);
pos_loc.lon -= Math.ceil((marker.location.lon - right.lon) / 360) * 360;
new_pos = m.map.locationPoint(pos_loc);
if (new_pos.x > 0) {
pos = new_pos;
marker.coord = m.map.locationCoordinate(pos_loc);
}
}
pos.scale = 1;
pos.width = pos.height = 0;
MM.moveElement(marker.element, pos);
}
|
javascript
|
{
"resource": ""
}
|
q2980
|
stopPropagation
|
train
|
function stopPropagation(e) {
e.cancelBubble = true;
if (e.stopPropagation) { e.stopPropagation(); }
return false;
}
|
javascript
|
{
"resource": ""
}
|
q2981
|
csv_parse
|
train
|
function csv_parse(text) {
var header;
return csv_parseRows(text, function(row, i) {
if (i) {
var o = {}, j = -1, m = header.length;
while (++j < m) o[header[j]] = row[j];
return o;
} else {
header = row;
return null;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q2982
|
swagger20TypeFor
|
train
|
function swagger20TypeFor(type) {
if (!type) { return null; }
if (type === Number) { return 'number'; }
if (type === Boolean) { return 'boolean'; }
if (type === String ||
type === Date ||
type === mongoose.Schema.Types.ObjectId ||
type === mongoose.Schema.Types.Oid) {
return 'string';
}
if (type === mongoose.Schema.Types.Array ||
Array.isArray(type) ||
type.name === "Array") {
return 'array';
}
if (type === Object ||
type instanceof Object ||
type === mongoose.Schema.Types.Mixed ||
type === mongoose.Schema.Types.Buffer) {
return null;
}
throw new Error('Unrecognized type: ' + type);
}
|
javascript
|
{
"resource": ""
}
|
q2983
|
generatePropertyDefinition
|
train
|
function generatePropertyDefinition(name, path, definitionName) {
var property = {};
var type = path.options.type ? swagger20TypeFor(path.options.type) : 'string'; // virtuals don't have type
if (skipProperty(name, path, controller)) {
return;
}
// Configure the property
if (path.options.type === mongoose.Schema.Types.ObjectId) {
if ("_id" === name) {
property.type = 'string';
}
else if (path.options.ref) {
property.$ref = '#/definitions/' + utils.capitalize(path.options.ref);
}
}
else if (path.schema) {
//Choice (1. embed schema here or 2. reference and publish as a root definition)
property.type = 'array';
property.items = {
//2. reference
$ref: '#/definitions/'+ definitionName + utils.capitalize(name)
};
}
else {
property.type = type;
if ('array' === type) {
if (isArrayOfRefs(path.options.type)) {
property.items = {
type: 'string' //handle references as string (serialization for objectId)
};
}
else {
var resolvedType = referenceForType(path.options.type);
if (resolvedType.isPrimitive) {
property.items = {
type: resolvedType.type
};
}
else {
property.items = {
$ref: resolvedType.type
};
}
}
}
var format = swagger20TypeFormatFor(path.options.type);
if (format) {
property.format = format;
}
if ('__v' === name) {
property.format = 'int32';
}
}
/*
// Set enum values if applicable
if (path.enumValues && path.enumValues.length > 0) {
// Pending: property.allowableValues = { valueType: 'LIST', values: path.enumValues };
}
// Set allowable values range if min or max is present
if (!isNaN(path.options.min) || !isNaN(path.options.max)) {
// Pending: property.allowableValues = { valueType: 'RANGE' };
}
if (!isNaN(path.options.min)) {
// Pending: property.allowableValues.min = path.options.min;
}
if (!isNaN(path.options.max)) {
// Pending: property.allowableValues.max = path.options.max;
}
*/
if (!property.type && !property.$ref) {
warnInvalidType(name, path);
property.type = 'string';
}
return property;
}
|
javascript
|
{
"resource": ""
}
|
q2984
|
processPartitionKeys
|
train
|
function processPartitionKeys(keys){
var result = "(",
j,
len,
keyGroup;
if(typeof keys === 'string'){
return result += keys + ")";
}
len = keys.length;
for(j = 0; j< keys.length; j++){
keyGroup = keys[j];
if(keyGroup instanceof Array){
result += "(";
result += keyGroup.join(", ");
result += ")";
}else{
result += keyGroup;
}
result += (j < len-1) ? ", " : "";
}
result += ")";
return result;
}
|
javascript
|
{
"resource": ""
}
|
q2985
|
train
|
function(collection, blacklist){
var obj,
result = [],
prop,
i,
j,
collLen,
listLen;
blacklist = blacklist || ["__columns"];
if(!collection || !collection.length){
return result;
}
collLen = collection.length;
for(i=0; i<collLen; i++){
obj = collection[i];
//delete null properties
for(prop in obj){
if(obj[prop] === null){
delete obj[prop];
}
}
listLen = blacklist.length;
for(j=0; j<listLen; j++){
delete obj[blacklist[j]];
}
//These are javascript objects and not json, so we have to do this magic to strip it of get methods.
result.push(JSON.parse(JSON.stringify(obj)));
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q2986
|
one
|
train
|
function one (state, eventName, handler) {
state.emitter.once(eventName, handler)
return state.api
}
|
javascript
|
{
"resource": ""
}
|
q2987
|
JugglingStore
|
train
|
function JugglingStore(schema, options) {
options = options || {};
Store.call(this, options);
this.maxAge = options.maxAge || defaults.maxAge;
var coll = this.collection = schema.define('Session', {
sid: {
type: String,
index: true
},
expires: {
type: Date,
index: true
},
session: schema.constructor.JSON
}, {
table: options.table || defaults.table
});
coll.validatesUniquenessOf('sid');
// destroy all expired sessions after each create/update
coll.afterSave = function(next) {
coll.iterate({where: {
expires: {lte: new Date()}
}}, function(obj, nexti, i) {
obj.destroy(nexti);
}, next);
};
}
|
javascript
|
{
"resource": ""
}
|
q2988
|
validateRouteDefinition
|
train
|
function validateRouteDefinition(routeDef) {
var expectedKeys = ['route', 'type', 'module', 'path'];
var expectedTypes = ['static', 'module'];
var expectedTypeMap = {
'static': 'path',
'module': 'module'
};
var keys = Object.keys(routeDef);
var EXPECTED_NUMBER_OF_PROPERTIES = 3;
//Handle warnings first;
if (routeDef.route && routeDef.route.substr(0, 1) !== '/') {
log.warn('Route path does not start with a slash:', routeDef.route);
}
if(keys.length !== EXPECTED_NUMBER_OF_PROPERTIES) {
throw new Error('Route definition does not contain all required properties');
}
_.map(keys, function compareAgainstExpected(key) {
if (expectedKeys.indexOf(key) === -1) {
throw new Error('Unexpected property found in route definition. Please check the spelling');
}
});
if (expectedTypes.indexOf(routeDef.type) === -1) {
throw new Error('Unknown type of route. Please check your configuration');
}
if (keys.indexOf(expectedTypeMap[routeDef.type]) === -1) {
throw new Error('Route type ' + routeDef.type + ' requires ' + expectedTypeMap[routeDef.type] + ' to be defined');
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q2989
|
ConstantAggregateExpression
|
train
|
function ConstantAggregateExpression(number) {
if(!Number.isFinite(number))
this.number = parseFloat(number);
else
this.number = number;
}
|
javascript
|
{
"resource": ""
}
|
q2990
|
reduceSet
|
train
|
function reduceSet(set) {
return set.map(member => member && member.uri).filter(Boolean)
}
|
javascript
|
{
"resource": ""
}
|
q2991
|
mappingContent
|
train
|
function mappingContent(mapping) {
const { from, to, type } = mapping
let result = {
from: reduceBundle(from || {}),
to: reduceBundle(to || {}),
type: [
type && type[0] || "http://www.w3.org/2004/02/skos/core#mappingRelation"
]
}
for (let side of ["from", "to"]) {
if ((result[side][memberField(result[side])] || []).length == 0) {
let scheme = mapping[side + "Scheme"]
if (scheme && scheme.uri) {
// Create new object to remove all unnecessary properties.
result[side + "Scheme"] = { uri: scheme.uri }
}
}
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q2992
|
mappingMembers
|
train
|
function mappingMembers(mapping) {
const { from, to } = mapping
const memberUris = [ from, to ].filter(Boolean)
.map(bundle => reduceSet(bundle[memberField(bundle)] || []))
return [].concat(...memberUris).sort()
}
|
javascript
|
{
"resource": ""
}
|
q2993
|
on
|
train
|
function on (state, eventName, handler) {
state.emitter.on(eventName, handler)
return state.api
}
|
javascript
|
{
"resource": ""
}
|
q2994
|
bridgeCommand
|
train
|
function bridgeCommand(command,cb){
if(!connected) return setImmediate(function(){
cb('killed');
});
if(!connected.pings) connected.pings = {};
var id = ++pingid;
var timer;
connected.pings[id] = function(err,data){
clearTimeout(timer);
delete connected.pings[id]
cb(err,data);
};
connected.send({command:command,cb:id});
// set 5 second time limit for callback.
timer = setTimeout(function(){
cb("timeout");
},5000);
}
|
javascript
|
{
"resource": ""
}
|
q2995
|
deviceScan
|
train
|
function deviceScan(){
shuffle(Object.keys(watchs.boards)).forEach(function(id){
plugHandler({event:'plug',device:watchs.boards[id]});
});
}
|
javascript
|
{
"resource": ""
}
|
q2996
|
sync
|
train
|
function sync (state, docsOrIds) {
var syncedObjects = []
var errors = state.db.constructor.Errors
return Promise.resolve(state.remote)
.then(function (remote) {
return new Promise(function (resolve, reject) {
if (Array.isArray(docsOrIds)) {
docsOrIds = docsOrIds.map(toId)
} else {
docsOrIds = docsOrIds && [toId(docsOrIds)]
}
if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) {
return Promise.reject(errors.NOT_AN_OBJECT)
}
var replication = state.db.sync(remote, {
doc_ids: docsOrIds,
include_docs: true
})
/* istanbul ignore next */
replication.catch(function () {
// handled trough 'error' event
})
replication.on('complete', function () {
resolve(syncedObjects)
})
replication.on('error', reject)
replication.on('change', function (change) {
syncedObjects = syncedObjects.concat(change.change.docs)
for (var i = 0; i < change.change.docs.length; i++) {
state.emitter.emit(change.direction, change.change.docs[i])
}
})
})
})
}
|
javascript
|
{
"resource": ""
}
|
q2997
|
createExport
|
train
|
function createExport(exportOptions, content) {
if (!content) return content;
const type = exportOptions.type;
const name = exportOptions.name;
const exportFunction = exportFabric(type);
return exportFunction(name, content);
}
|
javascript
|
{
"resource": ""
}
|
q2998
|
createVpcNetwork
|
train
|
function createVpcNetwork(mCb) {
let networksOptions = Object.assign({}, options);
networksOptions.params = {
name,
returnGlobalOperation: true
};
networks.add(networksOptions, (error, globalOperationResponse) => {
if (error) return cb(error);
//assign network name to deployment entry
oneDeployment.options.network = name;
//check if network is ready then update firewall rules
checkVpcNetwork(globalOperationResponse, mCb);
});
function checkVpcNetwork(globalOperationResponse, mCb) {
function globalOperations(miniCB) {
options.soajs.log.debug("Checking network Create Status");
//Ref https://cloud.google.com/compute/docs/reference/latest/globalOperations/get
let request = getConnector(options.infra.api);
delete request.projectId;
request.operation = globalOperationResponse.name;
v1Compute().globalOperations.get(request, (error, response) => {
if (error) {
return miniCB(error);
}
if (!response || response.status !== "DONE") {
setTimeout(function () {
globalOperations(miniCB);
}, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5000);
} else {
return miniCB(null, response);
}
});
}
globalOperations(function (err) {
if (err) {
return mCb(err);
} else {
//Ref: https://cloud.google.com/compute/docs/reference/latest/firewalls/insert
let firewallRules = getFirewallRules(oneDeployment.options.network);
let request = getConnector(options.infra.api);
async.eachSeries(firewallRules, (oneRule, vCb) => {
options.soajs.log.debug("Registering new firewall rule:", oneRule.name);
request.resource = oneRule;
v1Compute().firewalls.insert(request, vCb);
}, mCb);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q2999
|
useVpcNetwork
|
train
|
function useVpcNetwork(mCb) {
//assign network name to deployment entry
oneDeployment.options.network = name;
function patchFirewall() {
let firewallRules = getFirewallRules(oneDeployment.options.network);
let request = getConnector(options.infra.api);
request.filter = `network eq .*${oneDeployment.options.network}`;
request.project = options.infra.api.project;
//list firewalls
//Ref: https://cloud.google.com/compute/docs/reference/rest/v1/firewalls/list
v1Compute().firewalls.list(request, function (error, firewalls) {
if (error) return mCb(error);
if (!firewalls.items) firewalls.items = [];
async.eachSeries(firewallRules, (oneRule, vCb) => {
let foundFirewall = firewalls.items.find((oneEntry) => {
return oneEntry.name === oneRule.name
});
if (foundFirewall) {
options.soajs.log.debug("Firewall rule:", oneRule.name, "already exists, skipping");
return vCb();
} else {
options.soajs.log.debug("Creating firewall rule:", oneRule.name);
request.resource = oneRule;
return v1Compute().firewalls.insert(request, vCb);
}
}, mCb);
});
}
patchFirewall();
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.