language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | handleKeyDown(keyEvent) {
if (!this.isCurrentLevelEvent(keyEvent)) {
return;
}
let eventHandled = false;
// Pass all events to parent to manage
if(this.props.onKeyEvent ) {
eventHandled = this.props.onKeyEvent(keyEvent, this.props.index);
}
if(!eventHandled) {
this.handleSliderKeyEvents(keyEvent);
}
} | handleKeyDown(keyEvent) {
if (!this.isCurrentLevelEvent(keyEvent)) {
return;
}
let eventHandled = false;
// Pass all events to parent to manage
if(this.props.onKeyEvent ) {
eventHandled = this.props.onKeyEvent(keyEvent, this.props.index);
}
if(!eventHandled) {
this.handleSliderKeyEvents(keyEvent);
}
} |
JavaScript | handleSliderKeyEvents(keyEvent) {
const keyCode = keyEvent.which;
if(this.subMenuElement && ALL_KEY_EVENTS.indexOf(keyCode) > -1) {
const displayChild = OPEN_KEY_EVENTS.indexOf(keyCode) > -1;
this.handleChildDisplay(displayChild, keyCode);
keyEvent.preventDefault();
}
} | handleSliderKeyEvents(keyEvent) {
const keyCode = keyEvent.which;
if(this.subMenuElement && ALL_KEY_EVENTS.indexOf(keyCode) > -1) {
const displayChild = OPEN_KEY_EVENTS.indexOf(keyCode) > -1;
this.handleChildDisplay(displayChild, keyCode);
keyEvent.preventDefault();
}
} |
JavaScript | handleChildDisplay(displayChild, parentKeyCode) {
const state = {
displayChild: displayChild,
parentKeyCode: parentKeyCode || -1
};
this.setState(state)
} | handleChildDisplay(displayChild, parentKeyCode) {
const state = {
displayChild: displayChild,
parentKeyCode: parentKeyCode || -1
};
this.setState(state)
} |
JavaScript | componentDidUpdate() {
// not make this nav item focused if child is supposed to be displayed
if(this.props.activeIndex === this.props.index && !this.state.displayChild) {
if(this.linkElement) {
this.linkElement.focus();
}
if(this.subMenuElement) {
this.subMenuElement.focus();
}
}
} | componentDidUpdate() {
// not make this nav item focused if child is supposed to be displayed
if(this.props.activeIndex === this.props.index && !this.state.displayChild) {
if(this.linkElement) {
this.linkElement.focus();
}
if(this.subMenuElement) {
this.subMenuElement.focus();
}
}
} |
JavaScript | function organizeDesktopChildren(children) {
const newChildren = [];
children.forEach((child, index) => {
if(child.type === NavigationList) {
newChildren.push(ReactHelper.getMainNav(child));
} else {
newChildren.push(React.cloneElement(child, {key: index}));
}
});
return newChildren;
} | function organizeDesktopChildren(children) {
const newChildren = [];
children.forEach((child, index) => {
if(child.type === NavigationList) {
newChildren.push(ReactHelper.getMainNav(child));
} else {
newChildren.push(React.cloneElement(child, {key: index}));
}
});
return newChildren;
} |
JavaScript | addPropsToChildren(children, props, addIndex = false) {
return React.Children.map(children, (child, index) => {
const finalProps = addIndex ? ObjectHelper.assignProperties({}, props, {index: index}) : props;
return React.cloneElement(child, finalProps)
});
} | addPropsToChildren(children, props, addIndex = false) {
return React.Children.map(children, (child, index) => {
const finalProps = addIndex ? ObjectHelper.assignProperties({}, props, {index: index}) : props;
return React.cloneElement(child, finalProps)
});
} |
JavaScript | function debounce(func, wait, immediate){
var timeout, args, context, timestamp, result;
if (null == wait) wait = 100;
function later() {
var last = nowTS() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
}
}
}
var debounced = function(){
context = this;
args = arguments;
timestamp = nowTS();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
debounced.clear = function() {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
};
return debounced;
} | function debounce(func, wait, immediate){
var timeout, args, context, timestamp, result;
if (null == wait) wait = 100;
function later() {
var last = nowTS() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
}
}
}
var debounced = function(){
context = this;
args = arguments;
timestamp = nowTS();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
debounced.clear = function() {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
};
return debounced;
} |
JavaScript | assignProperties(target, ...sources) {
if(Object.assign) {
Object.assign(target, ...sources);
return target;
}
for (var index = 0; index < sources.length; index++) {
var source = sources[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
} | assignProperties(target, ...sources) {
if(Object.assign) {
Object.assign(target, ...sources);
return target;
}
for (var index = 0; index < sources.length; index++) {
var source = sources[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
} |
JavaScript | handleClick() {
if (this.props.handleClick) {
this.props.handleClick();
}
} | handleClick() {
if (this.props.handleClick) {
this.props.handleClick();
}
} |
JavaScript | function makeCustomConsole() {
var console = (function () {
function postConsoleMessage(prefix, args) {
postMessage({
target: "console-" + prefix,
content: JSON.stringify(Array.prototype.slice.call(args)),
})
}
return {
log: function() {
postConsoleMessage("log", arguments);
},
debug: function() {
postConsoleMessage("debug", arguments);
},
info: function() {
postConsoleMessage("info", arguments);
},
warn: function() {
postConsoleMessage("warn", arguments);
},
error: function() {
postConsoleMessage("error", arguments);
}
}
})();
return console;
} | function makeCustomConsole() {
var console = (function () {
function postConsoleMessage(prefix, args) {
postMessage({
target: "console-" + prefix,
content: JSON.stringify(Array.prototype.slice.call(args)),
})
}
return {
log: function() {
postConsoleMessage("log", arguments);
},
debug: function() {
postConsoleMessage("debug", arguments);
},
info: function() {
postConsoleMessage("info", arguments);
},
warn: function() {
postConsoleMessage("warn", arguments);
},
error: function() {
postConsoleMessage("error", arguments);
}
}
})();
return console;
} |
JavaScript | replaceModule(dest, source) {
let mod = this.require(dest);
if (!mod) {
console.error(`The module ${dest} does not exist`);
throw new Error(`The module ${dest} does not exist`);
}
if (mod === source) {
return;
}
Misc.replaceObjectProps(mod, source);
} | replaceModule(dest, source) {
let mod = this.require(dest);
if (!mod) {
console.error(`The module ${dest} does not exist`);
throw new Error(`The module ${dest} does not exist`);
}
if (mod === source) {
return;
}
Misc.replaceObjectProps(mod, source);
} |
JavaScript | function signIt(params) {
const mapkitServer = `https://snapshot.apple-mapkit.com`
const snapshotPath = `/api/v1/snapshot?${params}`;
var completePath = `${snapshotPath}&teamId=${teamId}&keyId=${keyId}`;
const signature = sign(completePath, privateKey);
// Append the signature to the end of the request URL, and return.
url = `${mapkitServer}${completePath}&signature=${signature}`
// Optionally open the result in the default browser using `opn`
// opn(url);
//console.log(url);
return url;
} | function signIt(params) {
const mapkitServer = `https://snapshot.apple-mapkit.com`
const snapshotPath = `/api/v1/snapshot?${params}`;
var completePath = `${snapshotPath}&teamId=${teamId}&keyId=${keyId}`;
const signature = sign(completePath, privateKey);
// Append the signature to the end of the request URL, and return.
url = `${mapkitServer}${completePath}&signature=${signature}`
// Optionally open the result in the default browser using `opn`
// opn(url);
//console.log(url);
return url;
} |
JavaScript | returnStyleValues() {
/** @type {?} */
let pageUnit = this.pageMarginUnit == null ? "mm" : this.pageMarginUnit;
/** @type {?} */
let pageStyles = [];
if (this.pageMarginLeft)
pageStyles.push("margin-left:" + this.pageMarginLeft + pageUnit + ";");
if (this.pageMarginRight)
pageStyles.push("margin-right:" + this.pageMarginRight + pageUnit + ";");
if (this.pageMarginTop)
pageStyles.push("margin-top:" + this.pageMarginTop + pageUnit + ";");
if (this.pageMarginBottom)
pageStyles.push("margin-bottom:" + this.pageMarginBottom + pageUnit + ";");
/** @type {?} */
let style = `<style>@page{ ${pageStyles.join(' ')} }</style>` + `<style> ${this._printStyle.join(' ').replace(/,/g, ';')} </style>`;
console.log(style);
} | returnStyleValues() {
/** @type {?} */
let pageUnit = this.pageMarginUnit == null ? "mm" : this.pageMarginUnit;
/** @type {?} */
let pageStyles = [];
if (this.pageMarginLeft)
pageStyles.push("margin-left:" + this.pageMarginLeft + pageUnit + ";");
if (this.pageMarginRight)
pageStyles.push("margin-right:" + this.pageMarginRight + pageUnit + ";");
if (this.pageMarginTop)
pageStyles.push("margin-top:" + this.pageMarginTop + pageUnit + ";");
if (this.pageMarginBottom)
pageStyles.push("margin-bottom:" + this.pageMarginBottom + pageUnit + ";");
/** @type {?} */
let style = `<style>@page{ ${pageStyles.join(' ')} }</style>` + `<style> ${this._printStyle.join(' ').replace(/,/g, ';')} </style>`;
console.log(style);
} |
JavaScript | insertDocument(collectionName, document, options) {
return new Promise((resolve, reject) => {
this.insertOne(collectionName, document, options)
.then((result) => {
resolve(result);
})
.catch(reject);
});
} | insertDocument(collectionName, document, options) {
return new Promise((resolve, reject) => {
this.insertOne(collectionName, document, options)
.then((result) => {
resolve(result);
})
.catch(reject);
});
} |
JavaScript | function reject(err) {
if(err) {
return callback(err);
}
callback(null, false);
} | function reject(err) {
if(err) {
return callback(err);
}
callback(null, false);
} |
JavaScript | function processPage(building, bridge, page, lastReading, state) {
return new Promise(function(resolve, reject) {
// Fetch readings.
Reading.find({
order: 'timestamp asc',
skip: page * amountPerPage,
limit: amountPerPage,
where: ReadingProcessing.getReadingWhereFilter(building, bridge.id)
}, function(error, readings) {
if (error) {
reject(error);
} else {
// Process the readings.
ReadingProcessing.processReadingsSerially(building, readings, lastReading, state).then(function(processResult) {
var pageResult = {
numberOfSuccessfulReadings : readings.length - processResult.numberOfFailedReadings,
numberOfFailedReadings: processResult.numberOfFailedReadings
};
if (readings.length === 0) {
// If this is a blank page, we are at the end so just return this page's result.
resolve(pageResult);
} else {
// Provide details from this page to the next page.
processPage(processResult.building, bridge, page + 1, processResult.lastReading, processResult.currentState).then(function(recurseResult) {
// Add to the result of the next page.
pageResult.numberOfSuccessfulReadings += recurseResult.numberOfSuccessfulReadings;
pageResult.numberOfFailedReadings += recurseResult.numberOfFailedReadings;
resolve(pageResult);
}, reject);
}
}, reject);
}
});
});
} | function processPage(building, bridge, page, lastReading, state) {
return new Promise(function(resolve, reject) {
// Fetch readings.
Reading.find({
order: 'timestamp asc',
skip: page * amountPerPage,
limit: amountPerPage,
where: ReadingProcessing.getReadingWhereFilter(building, bridge.id)
}, function(error, readings) {
if (error) {
reject(error);
} else {
// Process the readings.
ReadingProcessing.processReadingsSerially(building, readings, lastReading, state).then(function(processResult) {
var pageResult = {
numberOfSuccessfulReadings : readings.length - processResult.numberOfFailedReadings,
numberOfFailedReadings: processResult.numberOfFailedReadings
};
if (readings.length === 0) {
// If this is a blank page, we are at the end so just return this page's result.
resolve(pageResult);
} else {
// Provide details from this page to the next page.
processPage(processResult.building, bridge, page + 1, processResult.lastReading, processResult.currentState).then(function(recurseResult) {
// Add to the result of the next page.
pageResult.numberOfSuccessfulReadings += recurseResult.numberOfSuccessfulReadings;
pageResult.numberOfFailedReadings += recurseResult.numberOfFailedReadings;
resolve(pageResult);
}, reject);
}
}, reject);
}
});
});
} |
JavaScript | function isPersonBuildingOwner(buildingOwners, userId) {
// Check if the current user is one of the people allowed in the building.
for (var i = 0; i < buildingOwners.length; i++) {
if (JSON.stringify(buildingOwners[i].id) === JSON.stringify(userId)) {
return true;
}
}
return false;
} | function isPersonBuildingOwner(buildingOwners, userId) {
// Check if the current user is one of the people allowed in the building.
for (var i = 0; i < buildingOwners.length; i++) {
if (JSON.stringify(buildingOwners[i].id) === JSON.stringify(userId)) {
return true;
}
}
return false;
} |
JavaScript | function Plan(name, pod, logbook, entries = []) {
this.pod = pod;
this.onPlanUpdateFns = [];
this.name = name;
/* keep track of the first entry that is not logged */
this.firstPlanned = -1;
this.entries = entries;
/* keep track of how many times a leg is planned */
this.nlegs = {};
/* total planned distance, in 1/10 M */
this.totalDist = 0;
this.attachLogBook(logbook);
} | function Plan(name, pod, logbook, entries = []) {
this.pod = pod;
this.onPlanUpdateFns = [];
this.name = name;
/* keep track of the first entry that is not logged */
this.firstPlanned = -1;
this.entries = entries;
/* keep track of how many times a leg is planned */
this.nlegs = {};
/* total planned distance, in 1/10 M */
this.totalDist = 0;
this.attachLogBook(logbook);
} |
JavaScript | function initP(clientIdV, defaultPod) {
var m;
// My teams in the races I am participating in.
m = getCachedMyTeams() || {data: [], etags: null};
myTeams = m.data;
myTeamsETag = m.etag;
// The regatta ids in the regattas I am participating in.
myRegattaIds = getRegattaIds(myTeams);
// All races in the regattas I am participating in.
m = getCachedRaces() || {data: {}, etags: {}};
races = m.data;
racesETags = m.etags;
// All teams in the regattas I am participating in.
m = getCachedTeams() || {data: {}, etags: {}};
teams = m.data;
teamsETags = m.etags;
clientId = clientIdV;
// All pods for the regattas I am participating in.
pods[defaultPod.getTerrain().id] = defaultPod;
return initCachedPodsP();
} | function initP(clientIdV, defaultPod) {
var m;
// My teams in the races I am participating in.
m = getCachedMyTeams() || {data: [], etags: null};
myTeams = m.data;
myTeamsETag = m.etag;
// The regatta ids in the regattas I am participating in.
myRegattaIds = getRegattaIds(myTeams);
// All races in the regattas I am participating in.
m = getCachedRaces() || {data: {}, etags: {}};
races = m.data;
racesETags = m.etags;
// All teams in the regattas I am participating in.
m = getCachedTeams() || {data: {}, etags: {}};
teams = m.data;
teamsETags = m.etags;
clientId = clientIdV;
// All pods for the regattas I am participating in.
pods[defaultPod.getTerrain().id] = defaultPod;
return initCachedPodsP();
} |
JavaScript | function mkTeamData(s) {
var r = {
id: s.id, // int
start_number: s.start_number, // int
start_point: s.start_point, // int
race_id: s.race_id, // int
regatta_id: s.regatta_id, // int
boat_name: s.boat_name, // string
boat_type_name: s.boat_type_name, // string
boat_sail_number: s.boat_sail_number, // string
skipper_id: s.skipper_id, // int (person.id)
skipper_first_name: s.skipper_first_name, // string
skipper_last_name: s.skipper_last_name, // string
sxk_handicap: s.sxk || 2 // float
};
return r;
} | function mkTeamData(s) {
var r = {
id: s.id, // int
start_number: s.start_number, // int
start_point: s.start_point, // int
race_id: s.race_id, // int
regatta_id: s.regatta_id, // int
boat_name: s.boat_name, // string
boat_type_name: s.boat_type_name, // string
boat_sail_number: s.boat_sail_number, // string
skipper_id: s.skipper_id, // int (person.id)
skipper_first_name: s.skipper_first_name, // string
skipper_last_name: s.skipper_last_name, // string
sxk_handicap: s.sxk || 2 // float
};
return r;
} |
JavaScript | function mkServerLogData(r, teamId) {
// never include the log id in the payload
// 'user_id' and 'updated_at' are filled in by the server
var s = {
// always add our client identifier to entries modified by us
client: clientId.get(),
};
if (teamId) { // not set on patch
s.team_id = teamId;
}
if (r.type) {
s.log_type = r.type;
}
if (r.class) {
s.type = r.class;
}
if (r.time) {
s.time = r.time.toISOString();
}
if (r.deleted) {
s.deleted = r.deleted;
}
if (r.gen) {
s.gen = r.gen;
}
var data = {};
if (r.comment) {
data.comment = r.comment;
}
switch (r.type) {
case 'round':
s.point = r.point;
data.wind = r.wind;
if (r.sails) {
data.sails = r.sails;
}
if (r.finish) {
data.finish = r.finish;
}
data.teams = r.teams;
break;
case 'endOfRace':
data.position = r.position;
break;
case 'seeOtherTeams':
data.position = r.position;
data.teams = r.teams;
break;
case 'seeOtherBoats': // OBSOLETE
data.boats = r.boats;
break;
case 'protest':
data.position = r.position;
data.protest = r.protest;
break;
case 'interrupt':
data.position = r.position;
data.interrupt = r.interrupt;
break;
case 'changeSails':
data.wind = r.wind;
data.sails = r.sails;
break;
case 'engine':
data.engine = r.engine;
break;
case 'lanterns':
data.position = r.position;
data.lanterns = r.lanterns;
break;
case 'retire':
data.position = r.position;
break;
case 'sign':
break;
case 'other':
break;
// AdminLog follows
case 'adminNote':
break;
case 'adminDSQ':
break;
case 'adminDist':
data.admin_dist = r.admin_dist;
break;
case 'adminTime':
data.admin_time = r.admin_time;
break;
}
s.data = JSON.stringify(data);
return s;
} | function mkServerLogData(r, teamId) {
// never include the log id in the payload
// 'user_id' and 'updated_at' are filled in by the server
var s = {
// always add our client identifier to entries modified by us
client: clientId.get(),
};
if (teamId) { // not set on patch
s.team_id = teamId;
}
if (r.type) {
s.log_type = r.type;
}
if (r.class) {
s.type = r.class;
}
if (r.time) {
s.time = r.time.toISOString();
}
if (r.deleted) {
s.deleted = r.deleted;
}
if (r.gen) {
s.gen = r.gen;
}
var data = {};
if (r.comment) {
data.comment = r.comment;
}
switch (r.type) {
case 'round':
s.point = r.point;
data.wind = r.wind;
if (r.sails) {
data.sails = r.sails;
}
if (r.finish) {
data.finish = r.finish;
}
data.teams = r.teams;
break;
case 'endOfRace':
data.position = r.position;
break;
case 'seeOtherTeams':
data.position = r.position;
data.teams = r.teams;
break;
case 'seeOtherBoats': // OBSOLETE
data.boats = r.boats;
break;
case 'protest':
data.position = r.position;
data.protest = r.protest;
break;
case 'interrupt':
data.position = r.position;
data.interrupt = r.interrupt;
break;
case 'changeSails':
data.wind = r.wind;
data.sails = r.sails;
break;
case 'engine':
data.engine = r.engine;
break;
case 'lanterns':
data.position = r.position;
data.lanterns = r.lanterns;
break;
case 'retire':
data.position = r.position;
break;
case 'sign':
break;
case 'other':
break;
// AdminLog follows
case 'adminNote':
break;
case 'adminDSQ':
break;
case 'adminDist':
data.admin_dist = r.admin_dist;
break;
case 'adminTime':
data.admin_time = r.admin_time;
break;
}
s.data = JSON.stringify(data);
return s;
} |
JavaScript | function updateRadioLikeGroup(element, g) {
var found = false;
for (var i = 0; !found && i < g.length; i++) {
if (element.id == g[i]) {
found = true;
for (var j = 0; j < g.length; j++) {
if (i != j) {
document.getElementById(g[j]).checked = false;
}
}
}
}
return found;
} | function updateRadioLikeGroup(element, g) {
var found = false;
for (var i = 0; !found && i < g.length; i++) {
if (element.id == g[i]) {
found = true;
for (var j = 0; j < g.length; j++) {
if (i != j) {
document.getElementById(g[j]).checked = false;
}
}
}
}
return found;
} |
JavaScript | function gcTerrainsP(keepTerrainIds, retval) {
var removeTerrainIds = [];
for (var id in cachedTerrains) {
// NOTE: cachedTerrains is an object and the key of an object is
// converted to string, so we need to convert it back to an int
// for "includes" to work
var i = id;
if (typeof(id) == 'string') {
i = parseInt(id);
}
if (!keepTerrainIds.includes(i)) {
removeTerrainIds.push(id);
}
}
// sort the terrains to remove in ascending order
removeTerrainIds.sort(function(a, b) { return a-b; });
// then pop the last one; this means that we keep all the ones that
// we need to keep + one more
removeTerrainIds.pop();
if (removeTerrainIds.length > 0) {
dbg('removing terrains ' + removeTerrainIds);
}
return removeTerrainIdsP(removeTerrainIds, retval);
} | function gcTerrainsP(keepTerrainIds, retval) {
var removeTerrainIds = [];
for (var id in cachedTerrains) {
// NOTE: cachedTerrains is an object and the key of an object is
// converted to string, so we need to convert it back to an int
// for "includes" to work
var i = id;
if (typeof(id) == 'string') {
i = parseInt(id);
}
if (!keepTerrainIds.includes(i)) {
removeTerrainIds.push(id);
}
}
// sort the terrains to remove in ascending order
removeTerrainIds.sort(function(a, b) { return a-b; });
// then pop the last one; this means that we keep all the ones that
// we need to keep + one more
removeTerrainIds.pop();
if (removeTerrainIds.length > 0) {
dbg('removing terrains ' + removeTerrainIds);
}
return removeTerrainIdsP(removeTerrainIds, retval);
} |
JavaScript | function isTouchDevice() {
try {
document.createEvent('TouchEvent');
return true;
} catch(e) {
return false;
}
} | function isTouchDevice() {
try {
document.createEvent('TouchEvent');
return true;
} catch(e) {
return false;
}
} |
JavaScript | function enableTouchScroll(elm) {
if (isTouchDevice()) {
var scrollStartPos = 0;
elm.addEventListener('touchstart', function(event) {
scrollStartPos = this.scrollTop + event.touches[0].pageY;
}, false);
elm.addEventListener('touchmove', function(event) {
this.scrollTop = scrollStartPos - event.touches[0].pageY;
}, false);
}
} | function enableTouchScroll(elm) {
if (isTouchDevice()) {
var scrollStartPos = 0;
elm.addEventListener('touchstart', function(event) {
scrollStartPos = this.scrollTop + event.touches[0].pageY;
}, false);
elm.addEventListener('touchmove', function(event) {
this.scrollTop = scrollStartPos - event.touches[0].pageY;
}, false);
}
} |
JavaScript | function initP() {
// initialize local storage handler
return initStorageP(false)
.then(function() {
init();
// initialize server data; doesn't read from the server, but will
// read cached data from local storage.
return initServerDataP(curState.clientId, curState.defaultPod);
})
.then(function() {
if (!hasNetwork()) {
return null;
} else {
return getTerrainP('latest')
.then(function(data) {
if (data.id) {
return getPodP(data.id, true);
} else {
return null;
}
})
.then(function(pod) {
if (pod) {
curState.defaultPod = pod;
}
return true;
})
.catch(function() {
return null;
});
}
})
.then(function() {
return null;
});
} | function initP() {
// initialize local storage handler
return initStorageP(false)
.then(function() {
init();
// initialize server data; doesn't read from the server, but will
// read cached data from local storage.
return initServerDataP(curState.clientId, curState.defaultPod);
})
.then(function() {
if (!hasNetwork()) {
return null;
} else {
return getTerrainP('latest')
.then(function(data) {
if (data.id) {
return getPodP(data.id, true);
} else {
return null;
}
})
.then(function(pod) {
if (pod) {
curState.defaultPod = pod;
}
return true;
})
.catch(function() {
return null;
});
}
})
.then(function() {
return null;
});
} |
JavaScript | function alert(html, continueFn) {
$('#alert-body').html(html);
$('#alert-ok').on('click', function() {
// remove the dynamic 'on' handler (actually, remove _all_ handlers,
// but we just have one)
$('#alert-ok').off();
popPage(continueFn);
return false;
});
pushPage(function() { $('#alert-page').modal({backdrop: 'static'}); },
function() { $('#alert-page').modal('hide'); });
} | function alert(html, continueFn) {
$('#alert-body').html(html);
$('#alert-ok').on('click', function() {
// remove the dynamic 'on' handler (actually, remove _all_ handlers,
// but we just have one)
$('#alert-ok').off();
popPage(continueFn);
return false;
});
pushPage(function() { $('#alert-page').modal({backdrop: 'static'}); },
function() { $('#alert-page').modal('hide'); });
} |
JavaScript | function mkMapLayer() {
var mapSource = new XYZ({
url: mapURL
});
return new Tile({
source: mapSource,
preload: 7
});
} | function mkMapLayer() {
var mapSource = new XYZ({
url: mapURL
});
return new Tile({
source: mapSource,
preload: 7
});
} |
JavaScript | function pushPage(openfn, closefn, mainPage) {
// close current page, if there is one
if (pageStack.length > 0) {
var cur = pageStack[pageStack.length - 1];
cur.closefn();
}
pageStack.push({openfn: openfn,
closefn: closefn});
if (mainPage) {
history.replaceState(pageStack.length, document.title, location.href);
} else {
history.pushState(pageStack.length, document.title, location.href);
}
openfn();
} | function pushPage(openfn, closefn, mainPage) {
// close current page, if there is one
if (pageStack.length > 0) {
var cur = pageStack[pageStack.length - 1];
cur.closefn();
}
pageStack.push({openfn: openfn,
closefn: closefn});
if (mainPage) {
history.replaceState(pageStack.length, document.title, location.href);
} else {
history.pushState(pageStack.length, document.title, location.href);
}
openfn();
} |
JavaScript | function popPage(continueFn) {
if (continueFn) {
// ensure that we run both the original closefn, and the
// continueFn when the history.back's popstate event actually
// triggers.
var prev = pageStack.pop();
pageStack.push({openfn: prev.openfn,
closefn: function() {
prev.closefn();
return continueFn();
}});
}
history.back();
} | function popPage(continueFn) {
if (continueFn) {
// ensure that we run both the original closefn, and the
// continueFn when the history.back's popstate event actually
// triggers.
var prev = pageStack.pop();
pageStack.push({openfn: prev.openfn,
closefn: function() {
prev.closefn();
return continueFn();
}});
}
history.back();
} |
JavaScript | function activateAnimations() {
var categories = JSON.parse(fs.readFileSync("effects-config.json")),
category,
files,
file,
target = [],
count = 0;
for (category in categories) {
if (categories.hasOwnProperty(category)) {
files = categories[category];
for (file in files) {
if (files[file]) {
// marked as true
target.push("sources/" + category + "/" + file + ".css");
count += 1;
}
}
}
}
// prepend base CSS
target.push("sources/effects-core.css");
if (!count) {
gutil.log("No animations activated.");
} else {
gutil.log(count + (count > 1 ? " animations" : " animation") + " activated.");
}
return target;
} | function activateAnimations() {
var categories = JSON.parse(fs.readFileSync("effects-config.json")),
category,
files,
file,
target = [],
count = 0;
for (category in categories) {
if (categories.hasOwnProperty(category)) {
files = categories[category];
for (file in files) {
if (files[file]) {
// marked as true
target.push("sources/" + category + "/" + file + ".css");
count += 1;
}
}
}
}
// prepend base CSS
target.push("sources/effects-core.css");
if (!count) {
gutil.log("No animations activated.");
} else {
gutil.log(count + (count > 1 ? " animations" : " animation") + " activated.");
}
return target;
} |
JavaScript | bindDetector(md, notifiers, force = false){
super.bindDetector(md, notifiers, force);
let e = this;
if(md instanceof RequestDetector) {
log.info(`Adding route: ${md.route} with verb: ${md.verb}`);
switch (md.verb)
{
case "GET":
app.get(md.route, (req, res) => {
md.send(req.url, e)
md.handler(req, res, e)
});
console.log(`Added ${md.verb}: ${md.route}`)
break;
case "POST":
app.post(md.route, (req, res) => {
md.send(req.url, e)
md.handler(req, res, e)
});
break;
default:
throw new Error (`Verb ${md.verb} is not implemented.`)
break;
}
}
} | bindDetector(md, notifiers, force = false){
super.bindDetector(md, notifiers, force);
let e = this;
if(md instanceof RequestDetector) {
log.info(`Adding route: ${md.route} with verb: ${md.verb}`);
switch (md.verb)
{
case "GET":
app.get(md.route, (req, res) => {
md.send(req.url, e)
md.handler(req, res, e)
});
console.log(`Added ${md.verb}: ${md.route}`)
break;
case "POST":
app.post(md.route, (req, res) => {
md.send(req.url, e)
md.handler(req, res, e)
});
break;
default:
throw new Error (`Verb ${md.verb} is not implemented.`)
break;
}
}
} |
JavaScript | addNode(node, truthy = true){
if(node && (node instanceof DecisionNodeDetector)){
if(this.nodes.length < MAX_NODES){
//If a node already exists will add it as left/right
if (this.nodes.length > 0){
if(truthy){
this.getLastNode().goToIfTrue(node);
} else {
this.getLastNode().goToIfFalse(node);
}
}
this.nodes.push(node);
return true;
}
return false;
} else{
throw new Error("ERROR: Parameter of 'addNode' method must be of instance DecisionNodeDetector.");
}
//Also adds as Detector
super.bindDetector(node);
} | addNode(node, truthy = true){
if(node && (node instanceof DecisionNodeDetector)){
if(this.nodes.length < MAX_NODES){
//If a node already exists will add it as left/right
if (this.nodes.length > 0){
if(truthy){
this.getLastNode().goToIfTrue(node);
} else {
this.getLastNode().goToIfFalse(node);
}
}
this.nodes.push(node);
return true;
}
return false;
} else{
throw new Error("ERROR: Parameter of 'addNode' method must be of instance DecisionNodeDetector.");
}
//Also adds as Detector
super.bindDetector(node);
} |
JavaScript | process(){
let result = {
next: this.fn() ? this.nextLeft : this.nextRight,
value: this.fn(),
step: this.fn() ? `(TRUE) -> ${this.nextLeft.descriptor}` : "(FALSE) -> ${this.nextRight.descriptor}"
}
if (result.value === undefined) throw new Error(`No node was defined as result, please add a decision node: Left: ${this.nextLeft}, Right: ${this.nextRight}`);
return result;
} | process(){
let result = {
next: this.fn() ? this.nextLeft : this.nextRight,
value: this.fn(),
step: this.fn() ? `(TRUE) -> ${this.nextLeft.descriptor}` : "(FALSE) -> ${this.nextRight.descriptor}"
}
if (result.value === undefined) throw new Error(`No node was defined as result, please add a decision node: Left: ${this.nextLeft}, Right: ${this.nextRight}`);
return result;
} |
JavaScript | _constructEndPoint(key, value){
this._query = {
url: "/" + value.id,
key: key,
value: value
}
value.api_key = this._key
return endpoints.format(this._endpoint, value)
} | _constructEndPoint(key, value){
this._query = {
url: "/" + value.id,
key: key,
value: value
}
value.api_key = this._key
return endpoints.format(this._endpoint, value)
} |
JavaScript | function _GetFuncResult(fn_name, args){
log.info(`Calling function ${fn_name}(${args})...`)
if (getParent()[fn_name]) {
log.info('Function exists, will run it now...')
return getParent()[fn_name](args);
} else {
log.error(`Function ${fn_name} does not exist in ${m}!`)
}
} | function _GetFuncResult(fn_name, args){
log.info(`Calling function ${fn_name}(${args})...`)
if (getParent()[fn_name]) {
log.info('Function exists, will run it now...')
return getParent()[fn_name](args);
} else {
log.error(`Function ${fn_name} does not exist in ${m}!`)
}
} |
JavaScript | function Start(e,m,n,f,config){
_.Start({
//Config is missing!
environment: e ? e : mainEnv
});
log.info("PLUGIN: Checking if any motion detector was passed via config to this environment...");
if (m && m.length > 0){
//Will add detectors only if passed as parameter
log.info(`PLUGIN: Yes, found ${m.length} plugin(s)`);
log.info(` first is ${m[0].constructor.name}:${m[0].name}. Adding...`);
_.AddDetector(m);
} else {
log.info("PLUGIN: No. Adding default detectors and notifiers.");
_.AddDetector(routeAddDetector);
_.AddDetector(routeAddNotifier);
_.AddDetector(routeRemoveNotifier);
_.AddDetector(routeGetDetectors);
_.AddDetector(routeGetNotifiers);
_.AddDetector(routeDeactivateDetector);
_.AddDetector(routeActivateDetector);
_.AddDetector(routeGetEnvironment);
//Assumes no constructor was added so forces listen
_.GetEnvironment().listen();
}
if (n) _.AddNotifier(n);
//TO DELETE
let key = new _.Config().slackHook();
let sn = new _.Extensions.SlackNotifier("My slack notifier", key);
_.AddNotifier(sn);
log.info(`Attempting to verify which port is being used from ${GetExpressEnvironment().constructor.name}...`);
port = GetExpressEnvironment().port ? GetExpressEnvironment().getPort() : port;
console.log("##########################################");
console.log(`## STARTING WEB SERVER on port ${port}... ##`);
console.log("##########################################");
} | function Start(e,m,n,f,config){
_.Start({
//Config is missing!
environment: e ? e : mainEnv
});
log.info("PLUGIN: Checking if any motion detector was passed via config to this environment...");
if (m && m.length > 0){
//Will add detectors only if passed as parameter
log.info(`PLUGIN: Yes, found ${m.length} plugin(s)`);
log.info(` first is ${m[0].constructor.name}:${m[0].name}. Adding...`);
_.AddDetector(m);
} else {
log.info("PLUGIN: No. Adding default detectors and notifiers.");
_.AddDetector(routeAddDetector);
_.AddDetector(routeAddNotifier);
_.AddDetector(routeRemoveNotifier);
_.AddDetector(routeGetDetectors);
_.AddDetector(routeGetNotifiers);
_.AddDetector(routeDeactivateDetector);
_.AddDetector(routeActivateDetector);
_.AddDetector(routeGetEnvironment);
//Assumes no constructor was added so forces listen
_.GetEnvironment().listen();
}
if (n) _.AddNotifier(n);
//TO DELETE
let key = new _.Config().slackHook();
let sn = new _.Extensions.SlackNotifier("My slack notifier", key);
_.AddNotifier(sn);
log.info(`Attempting to verify which port is being used from ${GetExpressEnvironment().constructor.name}...`);
port = GetExpressEnvironment().port ? GetExpressEnvironment().getPort() : port;
console.log("##########################################");
console.log(`## STARTING WEB SERVER on port ${port}... ##`);
console.log("##########################################");
} |
JavaScript | function GetExpressEnvironment()
{
let _env = _.GetEnvironment();
//When checking for instances I'm using the constructor name since we've had wrong false instanceof;
if(_env.constructor.name == "MultiEnvironment") {
let _candidates = _env.getCurrentState();
for(let c in _candidates)
{
if(_candidates[c].constructor.name == "ExpressEnvironment"){
return _candidates[c];
}
}
}else{
//Assumes that the only environment is already an ExpressEnvironment
return _env;
}
} | function GetExpressEnvironment()
{
let _env = _.GetEnvironment();
//When checking for instances I'm using the constructor name since we've had wrong false instanceof;
if(_env.constructor.name == "MultiEnvironment") {
let _candidates = _env.getCurrentState();
for(let c in _candidates)
{
if(_candidates[c].constructor.name == "ExpressEnvironment"){
return _candidates[c];
}
}
}else{
//Assumes that the only environment is already an ExpressEnvironment
return _env;
}
} |
JavaScript | function AdminExists(){
let lineReader = require('readline').createInterface({
input: require('fs').createReadStream('.tmotion')
});
lineReader.on('line', function (line) {
throw new Error("READ MAN!!!");
});
} | function AdminExists(){
let lineReader = require('readline').createInterface({
input: require('fs').createReadStream('.tmotion')
});
lineReader.on('line', function (line) {
throw new Error("READ MAN!!!");
});
} |
JavaScript | function mapHighlightReset() {
for (var collectionName in mapLayerCollection) {
// Loop through collection and and reset properties to stored defaults
for (var i = 0; i < mapLayerCollection[collectionName].length; i++) {
var obj = mapLayerCollection[collectionName][i];
var prop;
// Choose an appropriate property to change
if (map.getLayer(obj).type == 'fill')
prop = 'fill-color';
if (map.getLayer(obj).type == 'line')
prop = 'line-color';
if (map.getLayer(obj).type == 'circle')
prop = 'circle-color';
// Revert to default style if known
try{
if (defaultStyle[obj][prop])
map.setPaintProperty(obj, prop, defaultStyle[obj][prop]);
}
catch(e){}
}
}
} | function mapHighlightReset() {
for (var collectionName in mapLayerCollection) {
// Loop through collection and and reset properties to stored defaults
for (var i = 0; i < mapLayerCollection[collectionName].length; i++) {
var obj = mapLayerCollection[collectionName][i];
var prop;
// Choose an appropriate property to change
if (map.getLayer(obj).type == 'fill')
prop = 'fill-color';
if (map.getLayer(obj).type == 'line')
prop = 'line-color';
if (map.getLayer(obj).type == 'circle')
prop = 'circle-color';
// Revert to default style if known
try{
if (defaultStyle[obj][prop])
map.setPaintProperty(obj, prop, defaultStyle[obj][prop]);
}
catch(e){}
}
}
} |
JavaScript | function mapToggle(item) {
var collectionName = $(item).attr('data-map-layer');
// Loop through collection and toggle visibility
for (var i = 0; i < mapLayerCollection[collectionName].length; i++) {
var obj = mapLayerCollection[collectionName][i];
var prop;
// Choose an appropriate property to change
if (map.getLayer(obj).type == 'raster')
prop = 'raster-opacity';
if (map.getLayer(obj).type == 'fill')
prop = 'fill-opacity';
if (map.getLayer(obj).type == 'line')
prop = 'line-opacity';
if (map.getLayer(obj).type == 'circle')
prop = 'circle-opacity';
try {
map.setPaintProperty(obj, prop, !map.getPaintProperty(obj, prop));
} catch (e) {
map.setPaintProperty(obj, prop, 0);
}
}
} | function mapToggle(item) {
var collectionName = $(item).attr('data-map-layer');
// Loop through collection and toggle visibility
for (var i = 0; i < mapLayerCollection[collectionName].length; i++) {
var obj = mapLayerCollection[collectionName][i];
var prop;
// Choose an appropriate property to change
if (map.getLayer(obj).type == 'raster')
prop = 'raster-opacity';
if (map.getLayer(obj).type == 'fill')
prop = 'fill-opacity';
if (map.getLayer(obj).type == 'line')
prop = 'line-opacity';
if (map.getLayer(obj).type == 'circle')
prop = 'circle-opacity';
try {
map.setPaintProperty(obj, prop, !map.getPaintProperty(obj, prop));
} catch (e) {
map.setPaintProperty(obj, prop, 0);
}
}
} |
JavaScript | function mapLocate(location) {
map.setPitch(mapLocation[location].pitch);
map.flyTo(mapLocation[location]);
if(location == "reset"){}
} | function mapLocate(location) {
map.setPitch(mapLocation[location].pitch);
map.flyTo(mapLocation[location]);
if(location == "reset"){}
} |
JavaScript | function SortedIndex() {
var index = array32(0),
value = [],
size = 0;
function insert(key, data, base) {
if (!data.length) return [];
var n0 = size,
n1 = data.length,
addv = Array(n1),
addi = array32(n1),
oldv, oldi, i;
for (i=0; i<n1; ++i) {
addv[i] = key(data[i]);
addi[i] = i;
}
addv = sort(addv, addi);
if (n0) {
oldv = value;
oldi = index;
value = Array(n0 + n1);
index = array32(n0 + n1);
merge(base, oldv, oldi, n0, addv, addi, n1, value, index);
} else {
if (base > 0) for (i=0; i<n1; ++i) {
addi[i] += base;
}
value = addv;
index = addi;
}
size = n0 + n1;
return {index: addi, value: addv};
}
function remove(num, map) {
// map: index -> remove
var n = size,
idx, i, j;
// seek forward to first removal
for (i=0; !map[index[i]] && i<n; ++i);
// condense index and value arrays
for (j=i; i<n; ++i) {
if (!map[idx=index[i]]) {
index[j] = idx;
value[j] = value[i];
++j;
}
}
size = n - num;
}
function reindex(map) {
for (var i=0, n=size; i<n; ++i) {
index[i] = map[index[i]];
}
}
function bisect(range, array) {
var n;
if (array) {
n = array.length;
} else {
array = value;
n = size;
}
return [
d3Array.bisectLeft(array, range[0], 0, n),
d3Array.bisectRight(array, range[1], 0, n)
];
}
return {
insert: insert,
remove: remove,
bisect: bisect,
reindex: reindex,
index: function() { return index; },
size: function() { return size; }
};
} | function SortedIndex() {
var index = array32(0),
value = [],
size = 0;
function insert(key, data, base) {
if (!data.length) return [];
var n0 = size,
n1 = data.length,
addv = Array(n1),
addi = array32(n1),
oldv, oldi, i;
for (i=0; i<n1; ++i) {
addv[i] = key(data[i]);
addi[i] = i;
}
addv = sort(addv, addi);
if (n0) {
oldv = value;
oldi = index;
value = Array(n0 + n1);
index = array32(n0 + n1);
merge(base, oldv, oldi, n0, addv, addi, n1, value, index);
} else {
if (base > 0) for (i=0; i<n1; ++i) {
addi[i] += base;
}
value = addv;
index = addi;
}
size = n0 + n1;
return {index: addi, value: addv};
}
function remove(num, map) {
// map: index -> remove
var n = size,
idx, i, j;
// seek forward to first removal
for (i=0; !map[index[i]] && i<n; ++i);
// condense index and value arrays
for (j=i; i<n; ++i) {
if (!map[idx=index[i]]) {
index[j] = idx;
value[j] = value[i];
++j;
}
}
size = n - num;
}
function reindex(map) {
for (var i=0, n=size; i<n; ++i) {
index[i] = map[index[i]];
}
}
function bisect(range, array) {
var n;
if (array) {
n = array.length;
} else {
array = value;
n = size;
}
return [
d3Array.bisectLeft(array, range[0], 0, n),
d3Array.bisectRight(array, range[1], 0, n)
];
}
return {
insert: insert,
remove: remove,
bisect: bisect,
reindex: reindex,
index: function() { return index; },
size: function() { return size; }
};
} |
JavaScript | function cumulativeNormal(value, mean, stdev) {
mean = mean || 0;
stdev = stdev == null ? 1 : stdev;
let cd,
z = (value - mean) / stdev,
Z = Math.abs(z);
if (Z > 37) {
cd = 0;
} else {
let sum, exp = Math.exp(-Z * Z / 2);
if (Z < 7.07106781186547) {
sum = 3.52624965998911e-02 * Z + 0.700383064443688;
sum = sum * Z + 6.37396220353165;
sum = sum * Z + 33.912866078383;
sum = sum * Z + 112.079291497871;
sum = sum * Z + 221.213596169931;
sum = sum * Z + 220.206867912376;
cd = exp * sum;
sum = 8.83883476483184e-02 * Z + 1.75566716318264;
sum = sum * Z + 16.064177579207;
sum = sum * Z + 86.7807322029461;
sum = sum * Z + 296.564248779674;
sum = sum * Z + 637.333633378831;
sum = sum * Z + 793.826512519948;
sum = sum * Z + 440.413735824752;
cd = cd / sum;
} else {
sum = Z + 0.65;
sum = Z + 4 / sum;
sum = Z + 3 / sum;
sum = Z + 2 / sum;
sum = Z + 1 / sum;
cd = exp / sum / 2.506628274631;
}
}
return z > 0 ? 1 - cd : cd;
} | function cumulativeNormal(value, mean, stdev) {
mean = mean || 0;
stdev = stdev == null ? 1 : stdev;
let cd,
z = (value - mean) / stdev,
Z = Math.abs(z);
if (Z > 37) {
cd = 0;
} else {
let sum, exp = Math.exp(-Z * Z / 2);
if (Z < 7.07106781186547) {
sum = 3.52624965998911e-02 * Z + 0.700383064443688;
sum = sum * Z + 6.37396220353165;
sum = sum * Z + 33.912866078383;
sum = sum * Z + 112.079291497871;
sum = sum * Z + 221.213596169931;
sum = sum * Z + 220.206867912376;
cd = exp * sum;
sum = 8.83883476483184e-02 * Z + 1.75566716318264;
sum = sum * Z + 16.064177579207;
sum = sum * Z + 86.7807322029461;
sum = sum * Z + 296.564248779674;
sum = sum * Z + 637.333633378831;
sum = sum * Z + 793.826512519948;
sum = sum * Z + 440.413735824752;
cd = cd / sum;
} else {
sum = Z + 0.65;
sum = Z + 4 / sum;
sum = Z + 3 / sum;
sum = Z + 2 / sum;
sum = Z + 1 / sum;
cd = exp / sum / 2.506628274631;
}
}
return z > 0 ? 1 - cd : cd;
} |
JavaScript | function gaussianElimination(matrix) {
const n = matrix.length - 1,
coef = [];
let i, j, k, r, t;
for (i = 0; i < n; ++i) {
r = i; // max row
for (j = i + 1; j < n; ++j) {
if (Math.abs(matrix[i][j]) > Math.abs(matrix[i][r])) {
r = j;
}
}
for (k = i; k < n + 1; ++k) {
t = matrix[k][i];
matrix[k][i] = matrix[k][r];
matrix[k][r] = t;
}
for (j = i + 1; j < n; ++j) {
for (k = n; k >= i; k--) {
matrix[k][j] -= (matrix[k][i] * matrix[i][j]) / matrix[i][i];
}
}
}
for (j = n - 1; j >= 0; --j) {
t = 0;
for (k = j + 1; k < n; ++k) {
t += matrix[k][j] * coef[k];
}
coef[j] = (matrix[n][j] - t) / matrix[j][j];
}
return coef;
} | function gaussianElimination(matrix) {
const n = matrix.length - 1,
coef = [];
let i, j, k, r, t;
for (i = 0; i < n; ++i) {
r = i; // max row
for (j = i + 1; j < n; ++j) {
if (Math.abs(matrix[i][j]) > Math.abs(matrix[i][r])) {
r = j;
}
}
for (k = i; k < n + 1; ++k) {
t = matrix[k][i];
matrix[k][i] = matrix[k][r];
matrix[k][r] = t;
}
for (j = i + 1; j < n; ++j) {
for (k = n; k >= i; k--) {
matrix[k][j] -= (matrix[k][i] * matrix[i][j]) / matrix[i][i];
}
}
}
for (j = n - 1; j >= 0; --j) {
t = 0;
for (k = j + 1; k < n; ++k) {
t += matrix[k][j] * coef[k];
}
coef[j] = (matrix[n][j] - t) / matrix[j][j];
}
return coef;
} |
JavaScript | function updateInterval(xv, i, interval) {
let val = xv[i],
left = interval[0],
right = interval[1] + 1;
if (right >= xv.length) return;
// step right if distance to new right edge is <= distance to old left edge
// step when distance is equal to ensure movement over duplicate x values
while (i > left && (xv[right] - val) <= (val - xv[left])) {
interval[0] = ++left;
interval[1] = right;
++right;
}
} | function updateInterval(xv, i, interval) {
let val = xv[i],
left = interval[0],
right = interval[1] + 1;
if (right >= xv.length) return;
// step right if distance to new right edge is <= distance to old left edge
// step when distance is equal to ensure movement over duplicate x values
while (i > left && (xv[right] - val) <= (val - xv[left])) {
interval[0] = ++left;
interval[1] = right;
++right;
}
} |
JavaScript | function output(xv, yhat, ux, uy) {
const n = xv.length, out = [];
let i = 0, cnt = 0, prev = [], v;
for (; i<n; ++i) {
v = xv[i] + ux;
if (prev[0] === v) {
// average output values via online update
prev[1] += (yhat[i] - prev[1]) / (++cnt);
} else {
// add new output point
cnt = 0;
prev[1] += uy;
prev = [v, yhat[i]];
out.push(prev);
}
}
prev[1] += uy;
return out;
} | function output(xv, yhat, ux, uy) {
const n = xv.length, out = [];
let i = 0, cnt = 0, prev = [], v;
for (; i<n; ++i) {
v = xv[i] + ux;
if (prev[0] === v) {
// average output values via online update
prev[1] += (yhat[i] - prev[1]) / (++cnt);
} else {
// add new output point
cnt = 0;
prev[1] += uy;
prev = [v, yhat[i]];
out.push(prev);
}
}
prev[1] += uy;
return out;
} |
JavaScript | function sampleCurve(f, extent, minSteps, maxSteps) {
minSteps = minSteps || 25;
maxSteps = Math.max(minSteps, maxSteps || 200);
const point = x => [x, f(x)],
minX = extent[0],
maxX = extent[1],
span = maxX - minX,
stop = span / maxSteps,
prev = [point(minX)],
next = [];
if (minSteps === maxSteps) {
// no adaptation, sample uniform grid directly and return
for (let i = 1; i < maxSteps; ++i) {
prev.push(point(minX + (i / minSteps) * span));
}
prev.push(point(maxX));
return prev;
} else {
// sample minimum points on uniform grid
// then move on to perform adaptive refinement
next.push(point(maxX));
for (let i = minSteps; --i > 0;) {
next.push(point(minX + (i / minSteps) * span));
}
}
let p0 = prev[0],
p1 = next[next.length - 1];
while (p1) {
// midpoint for potential curve subdivision
const pm = point((p0[0] + p1[0]) / 2);
if (pm[0] - p0[0] >= stop && angleDelta(p0, pm, p1) > MIN_RADIANS) {
// maximum resolution has not yet been met, and
// subdivision midpoint sufficiently different from endpoint
// save subdivision, push midpoint onto the visitation stack
next.push(pm);
} else {
// subdivision midpoint sufficiently similar to endpoint
// skip subdivision, store endpoint, move to next point on the stack
p0 = p1;
prev.push(p1);
next.pop();
}
p1 = next[next.length - 1];
}
return prev;
} | function sampleCurve(f, extent, minSteps, maxSteps) {
minSteps = minSteps || 25;
maxSteps = Math.max(minSteps, maxSteps || 200);
const point = x => [x, f(x)],
minX = extent[0],
maxX = extent[1],
span = maxX - minX,
stop = span / maxSteps,
prev = [point(minX)],
next = [];
if (minSteps === maxSteps) {
// no adaptation, sample uniform grid directly and return
for (let i = 1; i < maxSteps; ++i) {
prev.push(point(minX + (i / minSteps) * span));
}
prev.push(point(maxX));
return prev;
} else {
// sample minimum points on uniform grid
// then move on to perform adaptive refinement
next.push(point(maxX));
for (let i = minSteps; --i > 0;) {
next.push(point(minX + (i / minSteps) * span));
}
}
let p0 = prev[0],
p1 = next[next.length - 1];
while (p1) {
// midpoint for potential curve subdivision
const pm = point((p0[0] + p1[0]) / 2);
if (pm[0] - p0[0] >= stop && angleDelta(p0, pm, p1) > MIN_RADIANS) {
// maximum resolution has not yet been met, and
// subdivision midpoint sufficiently different from endpoint
// save subdivision, push midpoint onto the visitation stack
next.push(pm);
} else {
// subdivision midpoint sufficiently similar to endpoint
// skip subdivision, store endpoint, move to next point on the stack
p0 = p1;
prev.push(p1);
next.pop();
}
p1 = next[next.length - 1];
}
return prev;
} |
JavaScript | function extractBaseClassName(value) {
let constructorName = 'Object';
while (Object.getPrototypeOf(value) !== Object.prototype) {
value = Object.getPrototypeOf(value);
constructorName = value.constructor.name;
}
return constructorName;
} | function extractBaseClassName(value) {
let constructorName = 'Object';
while (Object.getPrototypeOf(value) !== Object.prototype) {
value = Object.getPrototypeOf(value);
constructorName = value.constructor.name;
}
return constructorName;
} |
JavaScript | function customObjectMessage(arg, value, path) {
const fieldPathMessage = path ? ` (found in field ${path})` : '';
if (util_1.isObject(value)) {
// We use the base class name as the type name as the sentinel classes
// returned by the public FieldValue API are subclasses of FieldValue. By
// using the base name, we reduce the number of special cases below.
const typeName = extractBaseClassName(value);
switch (typeName) {
case 'DocumentReference':
case 'FieldPath':
case 'FieldValue':
case 'GeoPoint':
case 'Timestamp':
return (`${invalidArgumentMessage(arg, 'Firestore document')} Detected an object of type "${typeName}" that doesn't match the ` +
`expected instance${fieldPathMessage}. Please ensure that the ` +
'Firestore types you are using are from the same NPM package.)');
case 'Object':
return `${invalidArgumentMessage(arg, 'Firestore document')} Invalid use of type "${typeof value}" as a Firestore argument${fieldPathMessage}.`;
default:
return (`${invalidArgumentMessage(arg, 'Firestore document')} Couldn't serialize object of type "${typeName}"${fieldPathMessage}. Firestore doesn't support JavaScript ` +
'objects with custom prototypes (i.e. objects that were created ' +
'via the "new" operator).');
}
}
else {
return `${invalidArgumentMessage(arg, 'Firestore document')} Input is not a plain JavaScript object${fieldPathMessage}.`;
}
} | function customObjectMessage(arg, value, path) {
const fieldPathMessage = path ? ` (found in field ${path})` : '';
if (util_1.isObject(value)) {
// We use the base class name as the type name as the sentinel classes
// returned by the public FieldValue API are subclasses of FieldValue. By
// using the base name, we reduce the number of special cases below.
const typeName = extractBaseClassName(value);
switch (typeName) {
case 'DocumentReference':
case 'FieldPath':
case 'FieldValue':
case 'GeoPoint':
case 'Timestamp':
return (`${invalidArgumentMessage(arg, 'Firestore document')} Detected an object of type "${typeName}" that doesn't match the ` +
`expected instance${fieldPathMessage}. Please ensure that the ` +
'Firestore types you are using are from the same NPM package.)');
case 'Object':
return `${invalidArgumentMessage(arg, 'Firestore document')} Invalid use of type "${typeof value}" as a Firestore argument${fieldPathMessage}.`;
default:
return (`${invalidArgumentMessage(arg, 'Firestore document')} Couldn't serialize object of type "${typeName}"${fieldPathMessage}. Firestore doesn't support JavaScript ` +
'objects with custom prototypes (i.e. objects that were created ' +
'via the "new" operator).');
}
}
else {
return `${invalidArgumentMessage(arg, 'Firestore document')} Input is not a plain JavaScript object${fieldPathMessage}.`;
}
} |
JavaScript | function validateFunction(arg, value, options) {
if (!validateOptional(value, options)) {
if (!util_1.isFunction(value)) {
throw new Error(invalidArgumentMessage(arg, 'function'));
}
}
} | function validateFunction(arg, value, options) {
if (!validateOptional(value, options)) {
if (!util_1.isFunction(value)) {
throw new Error(invalidArgumentMessage(arg, 'function'));
}
}
} |
JavaScript | function validateObject(arg, value, options) {
if (!validateOptional(value, options)) {
if (!util_1.isObject(value)) {
throw new Error(invalidArgumentMessage(arg, 'object'));
}
}
} | function validateObject(arg, value, options) {
if (!validateOptional(value, options)) {
if (!util_1.isObject(value)) {
throw new Error(invalidArgumentMessage(arg, 'object'));
}
}
} |
JavaScript | function validateString(arg, value, options) {
if (!validateOptional(value, options)) {
if (typeof value !== 'string') {
throw new Error(invalidArgumentMessage(arg, 'string'));
}
}
} | function validateString(arg, value, options) {
if (!validateOptional(value, options)) {
if (typeof value !== 'string') {
throw new Error(invalidArgumentMessage(arg, 'string'));
}
}
} |
JavaScript | function validateHost(arg, value, options) {
if (!validateOptional(value, options)) {
validateString(arg, value);
const urlString = `http://${value}/`;
let parsed;
try {
parsed = new url_1.URL(urlString);
}
catch (e) {
throw new Error(invalidArgumentMessage(arg, 'host'));
}
if (parsed.search !== '' ||
parsed.pathname !== '/' ||
parsed.username !== '') {
throw new Error(invalidArgumentMessage(arg, 'host'));
}
}
} | function validateHost(arg, value, options) {
if (!validateOptional(value, options)) {
validateString(arg, value);
const urlString = `http://${value}/`;
let parsed;
try {
parsed = new url_1.URL(urlString);
}
catch (e) {
throw new Error(invalidArgumentMessage(arg, 'host'));
}
if (parsed.search !== '' ||
parsed.pathname !== '/' ||
parsed.username !== '') {
throw new Error(invalidArgumentMessage(arg, 'host'));
}
}
} |
JavaScript | function validateBoolean(arg, value, options) {
if (!validateOptional(value, options)) {
if (typeof value !== 'boolean') {
throw new Error(invalidArgumentMessage(arg, 'boolean'));
}
}
} | function validateBoolean(arg, value, options) {
if (!validateOptional(value, options)) {
if (typeof value !== 'boolean') {
throw new Error(invalidArgumentMessage(arg, 'boolean'));
}
}
} |
JavaScript | function validateNumber(arg, value, options) {
const min = options !== undefined && options.minValue !== undefined
? options.minValue
: -Infinity;
const max = options !== undefined && options.maxValue !== undefined
? options.maxValue
: Infinity;
if (!validateOptional(value, options)) {
if (typeof value !== 'number' || isNaN(value)) {
throw new Error(invalidArgumentMessage(arg, 'number'));
}
else if (value < min || value > max) {
throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`);
}
}
} | function validateNumber(arg, value, options) {
const min = options !== undefined && options.minValue !== undefined
? options.minValue
: -Infinity;
const max = options !== undefined && options.maxValue !== undefined
? options.maxValue
: Infinity;
if (!validateOptional(value, options)) {
if (typeof value !== 'number' || isNaN(value)) {
throw new Error(invalidArgumentMessage(arg, 'number'));
}
else if (value < min || value > max) {
throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`);
}
}
} |
JavaScript | function validateInteger(arg, value, options) {
const min = options !== undefined && options.minValue !== undefined
? options.minValue
: -Infinity;
const max = options !== undefined && options.maxValue !== undefined
? options.maxValue
: Infinity;
if (!validateOptional(value, options)) {
if (typeof value !== 'number' || isNaN(value) || value % 1 !== 0) {
throw new Error(invalidArgumentMessage(arg, 'integer'));
}
else if (value < min || value > max) {
throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`);
}
}
} | function validateInteger(arg, value, options) {
const min = options !== undefined && options.minValue !== undefined
? options.minValue
: -Infinity;
const max = options !== undefined && options.maxValue !== undefined
? options.maxValue
: Infinity;
if (!validateOptional(value, options)) {
if (typeof value !== 'number' || isNaN(value) || value % 1 !== 0) {
throw new Error(invalidArgumentMessage(arg, 'integer'));
}
else if (value < min || value > max) {
throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`);
}
}
} |
JavaScript | function formatArgumentName(arg) {
return typeof arg === 'string'
? `Value for argument "${arg}"`
: `Element at index ${arg}`;
} | function formatArgumentName(arg) {
return typeof arg === 'string'
? `Value for argument "${arg}"`
: `Element at index ${arg}`;
} |
JavaScript | function validateMinNumberOfArguments(funcName, args, minSize) {
if (args.length < minSize) {
throw new Error(`Function "${funcName}()" requires at least ` +
`${formatPlural(minSize, 'argument')}.`);
}
} | function validateMinNumberOfArguments(funcName, args, minSize) {
if (args.length < minSize) {
throw new Error(`Function "${funcName}()" requires at least ` +
`${formatPlural(minSize, 'argument')}.`);
}
} |
JavaScript | function validateMaxNumberOfArguments(funcName, args, maxSize) {
if (args.length > maxSize) {
throw new Error(`Function "${funcName}()" accepts at most ` +
`${formatPlural(maxSize, 'argument')}.`);
}
} | function validateMaxNumberOfArguments(funcName, args, maxSize) {
if (args.length > maxSize) {
throw new Error(`Function "${funcName}()" accepts at most ` +
`${formatPlural(maxSize, 'argument')}.`);
}
} |
JavaScript | function validateEnumValue(arg, value, allowedValues, options) {
if (!validateOptional(value, options)) {
const expectedDescription = [];
for (const allowed of allowedValues) {
if (allowed === value) {
return;
}
expectedDescription.push(allowed);
}
throw new Error(`${formatArgumentName(arg)} is invalid. Acceptable values are: ${expectedDescription.join(', ')}`);
}
} | function validateEnumValue(arg, value, allowedValues, options) {
if (!validateOptional(value, options)) {
const expectedDescription = [];
for (const allowed of allowedValues) {
if (allowed === value) {
return;
}
expectedDescription.push(allowed);
}
throw new Error(`${formatArgumentName(arg)} is invalid. Acceptable values are: ${expectedDescription.join(', ')}`);
}
} |
JavaScript | createScoped(scopes) {
return new JWT({
email: this.email,
keyFile: this.keyFile,
key: this.key,
keyId: this.keyId,
scopes,
subject: this.subject,
additionalClaims: this.additionalClaims,
});
} | createScoped(scopes) {
return new JWT({
email: this.email,
keyFile: this.keyFile,
key: this.key,
keyId: this.keyId,
scopes,
subject: this.subject,
additionalClaims: this.additionalClaims,
});
} |
JavaScript | hasScopes() {
if (!this.scopes) {
return false;
}
// For arrays, check the array length.
if (this.scopes instanceof Array) {
return this.scopes.length > 0;
}
// For others, convert to a string and check the length.
return String(this.scopes).length > 0;
} | hasScopes() {
if (!this.scopes) {
return false;
}
// For arrays, check the array length.
if (this.scopes instanceof Array) {
return this.scopes.length > 0;
}
// For others, convert to a string and check the length.
return String(this.scopes).length > 0;
} |
JavaScript | async refreshTokenNoCache(refreshToken) {
const gtoken = this.createGToken();
const token = await gtoken.getToken({
forceRefresh: this.isTokenExpiring(),
});
const tokens = {
access_token: token.access_token,
token_type: 'Bearer',
expiry_date: gtoken.expiresAt,
id_token: gtoken.idToken,
};
this.emit('tokens', tokens);
return { res: null, tokens };
} | async refreshTokenNoCache(refreshToken) {
const gtoken = this.createGToken();
const token = await gtoken.getToken({
forceRefresh: this.isTokenExpiring(),
});
const tokens = {
access_token: token.access_token,
token_type: 'Bearer',
expiry_date: gtoken.expiresAt,
id_token: gtoken.idToken,
};
this.emit('tokens', tokens);
return { res: null, tokens };
} |
JavaScript | createGToken() {
if (!this.gtoken) {
this.gtoken = new gtoken_1.GoogleToken({
iss: this.email,
sub: this.subject,
scope: this.scopes,
keyFile: this.keyFile,
key: this.key,
additionalClaims: this.additionalClaims,
});
}
return this.gtoken;
} | createGToken() {
if (!this.gtoken) {
this.gtoken = new gtoken_1.GoogleToken({
iss: this.email,
sub: this.subject,
scope: this.scopes,
keyFile: this.keyFile,
key: this.key,
additionalClaims: this.additionalClaims,
});
}
return this.gtoken;
} |
JavaScript | fromJSON(json) {
if (!json) {
throw new Error('Must pass in a JSON object containing the service account auth settings.');
}
if (!json.client_email) {
throw new Error('The incoming JSON object does not contain a client_email field');
}
if (!json.private_key) {
throw new Error('The incoming JSON object does not contain a private_key field');
}
// Extract the relevant information from the json key file.
this.email = json.client_email;
this.key = json.private_key;
this.keyId = json.private_key_id;
this.projectId = json.project_id;
this.quotaProjectId = json.quota_project_id;
} | fromJSON(json) {
if (!json) {
throw new Error('Must pass in a JSON object containing the service account auth settings.');
}
if (!json.client_email) {
throw new Error('The incoming JSON object does not contain a client_email field');
}
if (!json.private_key) {
throw new Error('The incoming JSON object does not contain a private_key field');
}
// Extract the relevant information from the json key file.
this.email = json.client_email;
this.key = json.private_key;
this.keyId = json.private_key_id;
this.projectId = json.project_id;
this.quotaProjectId = json.quota_project_id;
} |
JavaScript | fromAPIKey(apiKey) {
if (typeof apiKey !== 'string') {
throw new Error('Must provide an API Key string.');
}
this.apiKey = apiKey;
} | fromAPIKey(apiKey) {
if (typeof apiKey !== 'string') {
throw new Error('Must provide an API Key string.');
}
this.apiKey = apiKey;
} |
JavaScript | function autoId() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let autoId = '';
for (let i = 0; i < 20; i++) {
autoId += chars.charAt(Math.floor(Math.random() * chars.length));
}
return autoId;
} | function autoId() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let autoId = '';
for (let i = 0; i < 20; i++) {
autoId += chars.charAt(Math.floor(Math.random() * chars.length));
}
return autoId;
} |
JavaScript | function merge(target, value, path, pos) {
const key = path[pos];
const isLast = pos === path.length - 1;
if (target[key] === undefined) {
if (isLast) {
if (value instanceof field_value_1.FieldTransform) {
// If there is already data at this path, we need to retain it.
// Otherwise, we don't include it in the DocumentSnapshot.
return !util_1.isEmpty(target) ? target : null;
}
// The merge is done.
const leafNode = serializer.encodeValue(value);
if (leafNode) {
target[key] = leafNode;
}
return target;
}
else {
// We need to expand the target object.
const childNode = {
mapValue: {
fields: {},
},
};
const nestedValue = merge(childNode.mapValue.fields, value, path, pos + 1);
if (nestedValue) {
childNode.mapValue.fields = nestedValue;
target[key] = childNode;
return target;
}
else {
return !util_1.isEmpty(target) ? target : null;
}
}
}
else {
assert(!isLast, "Can't merge current value into a nested object");
target[key].mapValue.fields = merge(target[key].mapValue.fields, value, path, pos + 1);
return target;
}
} | function merge(target, value, path, pos) {
const key = path[pos];
const isLast = pos === path.length - 1;
if (target[key] === undefined) {
if (isLast) {
if (value instanceof field_value_1.FieldTransform) {
// If there is already data at this path, we need to retain it.
// Otherwise, we don't include it in the DocumentSnapshot.
return !util_1.isEmpty(target) ? target : null;
}
// The merge is done.
const leafNode = serializer.encodeValue(value);
if (leafNode) {
target[key] = leafNode;
}
return target;
}
else {
// We need to expand the target object.
const childNode = {
mapValue: {
fields: {},
},
};
const nestedValue = merge(childNode.mapValue.fields, value, path, pos + 1);
if (nestedValue) {
childNode.mapValue.fields = nestedValue;
target[key] = childNode;
return target;
}
else {
return !util_1.isEmpty(target) ? target : null;
}
}
}
else {
assert(!isLast, "Can't merge current value into a nested object");
target[key].mapValue.fields = merge(target[key].mapValue.fields, value, path, pos + 1);
return target;
}
} |
JavaScript | protoField(field) {
let fields = this._fieldsProto;
if (fields === undefined) {
return undefined;
}
const components = path_1.FieldPath.fromArgument(field).toArray();
while (components.length > 1) {
fields = fields[components.shift()];
if (!fields || !fields.mapValue) {
return undefined;
}
fields = fields.mapValue.fields;
}
return fields[components[0]];
} | protoField(field) {
let fields = this._fieldsProto;
if (fields === undefined) {
return undefined;
}
const components = path_1.FieldPath.fromArgument(field).toArray();
while (components.length > 1) {
fields = fields[components.shift()];
if (!fields || !fields.mapValue) {
return undefined;
}
fields = fields.mapValue.fields;
}
return fields[components[0]];
} |
JavaScript | toProto() {
return {
update: {
name: this._ref.formattedName,
fields: this._fieldsProto,
},
};
} | toProto() {
return {
update: {
name: this._ref.formattedName,
fields: this._fieldsProto,
},
};
} |
JavaScript | isEqual(other) {
// Since the read time is different on every document read, we explicitly
// ignore all document metadata in this comparison.
return (this === other ||
(other instanceof DocumentSnapshot &&
this._ref.isEqual(other._ref) &&
deepEqual(this._fieldsProto, other._fieldsProto, { strict: true })));
} | isEqual(other) {
// Since the read time is different on every document read, we explicitly
// ignore all document metadata in this comparison.
return (this === other ||
(other instanceof DocumentSnapshot &&
this._ref.isEqual(other._ref) &&
deepEqual(this._fieldsProto, other._fieldsProto, { strict: true })));
} |
JavaScript | static fromUpdateMap(data) {
const fieldPaths = [];
data.forEach((value, key) => {
if (!(value instanceof field_value_1.FieldTransform) || value.includeInDocumentMask) {
fieldPaths.push(path_1.FieldPath.fromArgument(key));
}
});
return new DocumentMask(fieldPaths);
} | static fromUpdateMap(data) {
const fieldPaths = [];
data.forEach((value, key) => {
if (!(value instanceof field_value_1.FieldTransform) || value.includeInDocumentMask) {
fieldPaths.push(path_1.FieldPath.fromArgument(key));
}
});
return new DocumentMask(fieldPaths);
} |
JavaScript | static fromFieldMask(fieldMask) {
const fieldPaths = [];
for (const fieldPath of fieldMask) {
fieldPaths.push(path_1.FieldPath.fromArgument(fieldPath));
}
return new DocumentMask(fieldPaths);
} | static fromFieldMask(fieldMask) {
const fieldPaths = [];
for (const fieldPath of fieldMask) {
fieldPaths.push(path_1.FieldPath.fromArgument(fieldPath));
}
return new DocumentMask(fieldPaths);
} |
JavaScript | static fromObject(data) {
const fieldPaths = [];
function extractFieldPaths(currentData, currentPath) {
let isEmpty = true;
for (const key of Object.keys(currentData)) {
isEmpty = false;
// We don't split on dots since fromObject is called with
// DocumentData.
const childSegment = new path_1.FieldPath(key);
const childPath = currentPath
? currentPath.append(childSegment)
: childSegment;
const value = currentData[key];
if (value instanceof field_value_1.FieldTransform) {
if (value.includeInDocumentMask) {
fieldPaths.push(childPath);
}
}
else if (serializer_1.isPlainObject(value)) {
extractFieldPaths(value, childPath);
}
else {
fieldPaths.push(childPath);
}
}
// Add a field path for an explicitly updated empty map.
if (currentPath && isEmpty) {
fieldPaths.push(currentPath);
}
}
extractFieldPaths(data);
return new DocumentMask(fieldPaths);
} | static fromObject(data) {
const fieldPaths = [];
function extractFieldPaths(currentData, currentPath) {
let isEmpty = true;
for (const key of Object.keys(currentData)) {
isEmpty = false;
// We don't split on dots since fromObject is called with
// DocumentData.
const childSegment = new path_1.FieldPath(key);
const childPath = currentPath
? currentPath.append(childSegment)
: childSegment;
const value = currentData[key];
if (value instanceof field_value_1.FieldTransform) {
if (value.includeInDocumentMask) {
fieldPaths.push(childPath);
}
}
else if (serializer_1.isPlainObject(value)) {
extractFieldPaths(value, childPath);
}
else {
fieldPaths.push(childPath);
}
}
// Add a field path for an explicitly updated empty map.
if (currentPath && isEmpty) {
fieldPaths.push(currentPath);
}
}
extractFieldPaths(data);
return new DocumentMask(fieldPaths);
} |
JavaScript | static removeFromSortedArray(input, values) {
for (let i = 0; i < input.length;) {
let removed = false;
for (const fieldPath of values) {
if (input[i].isEqual(fieldPath)) {
input.splice(i, 1);
removed = true;
break;
}
}
if (!removed) {
++i;
}
}
} | static removeFromSortedArray(input, values) {
for (let i = 0; i < input.length;) {
let removed = false;
for (const fieldPath of values) {
if (input[i].isEqual(fieldPath)) {
input.splice(i, 1);
removed = true;
break;
}
}
if (!removed) {
++i;
}
}
} |
JavaScript | contains(fieldPath) {
for (const sortedPath of this._sortedPaths) {
const cmp = sortedPath.compareTo(fieldPath);
if (cmp === 0) {
return true;
}
else if (cmp > 0) {
return false;
}
}
return false;
} | contains(fieldPath) {
for (const sortedPath of this._sortedPaths) {
const cmp = sortedPath.compareTo(fieldPath);
if (cmp === 0) {
return true;
}
else if (cmp > 0) {
return false;
}
}
return false;
} |
JavaScript | applyTo(data) {
/*!
* Applies this DocumentMask to 'data' and computes the list of field paths
* that were specified in the mask but are not present in 'data'.
*/
const applyDocumentMask = (data) => {
const remainingPaths = this._sortedPaths.slice(0);
const processObject = (currentData, currentPath) => {
let result = null;
Object.keys(currentData).forEach(key => {
const childPath = currentPath
? currentPath.append(key)
: new path_1.FieldPath(key);
if (this.contains(childPath)) {
DocumentMask.removeFromSortedArray(remainingPaths, [childPath]);
result = result || {};
result[key] = currentData[key];
}
else if (util_1.isObject(currentData[key])) {
const childObject = processObject(currentData[key], childPath);
if (childObject) {
result = result || {};
result[key] = childObject;
}
}
});
return result;
};
// processObject() returns 'null' if the DocumentMask is empty.
const filteredData = processObject(data) || {};
return {
filteredData,
remainingPaths,
};
};
const result = applyDocumentMask(data);
if (result.remainingPaths.length !== 0) {
throw new Error(`Input data is missing for field "${result.remainingPaths[0]}".`);
}
return result.filteredData;
} | applyTo(data) {
/*!
* Applies this DocumentMask to 'data' and computes the list of field paths
* that were specified in the mask but are not present in 'data'.
*/
const applyDocumentMask = (data) => {
const remainingPaths = this._sortedPaths.slice(0);
const processObject = (currentData, currentPath) => {
let result = null;
Object.keys(currentData).forEach(key => {
const childPath = currentPath
? currentPath.append(key)
: new path_1.FieldPath(key);
if (this.contains(childPath)) {
DocumentMask.removeFromSortedArray(remainingPaths, [childPath]);
result = result || {};
result[key] = currentData[key];
}
else if (util_1.isObject(currentData[key])) {
const childObject = processObject(currentData[key], childPath);
if (childObject) {
result = result || {};
result[key] = childObject;
}
}
});
return result;
};
// processObject() returns 'null' if the DocumentMask is empty.
const filteredData = processObject(data) || {};
return {
filteredData,
remainingPaths,
};
};
const result = applyDocumentMask(data);
if (result.remainingPaths.length !== 0) {
throw new Error(`Input data is missing for field "${result.remainingPaths[0]}".`);
}
return result.filteredData;
} |
JavaScript | toProto() {
if (this.isEmpty) {
return {};
}
const encodedPaths = [];
for (const fieldPath of this._sortedPaths) {
encodedPaths.push(fieldPath.formattedName);
}
return {
fieldPaths: encodedPaths,
};
} | toProto() {
if (this.isEmpty) {
return {};
}
const encodedPaths = [];
for (const fieldPath of this._sortedPaths) {
encodedPaths.push(fieldPath.formattedName);
}
return {
fieldPaths: encodedPaths,
};
} |
JavaScript | static fromObject(ref, obj) {
const updateMap = new Map();
for (const prop of Object.keys(obj)) {
updateMap.set(new path_1.FieldPath(prop), obj[prop]);
}
return DocumentTransform.fromUpdateMap(ref, updateMap);
} | static fromObject(ref, obj) {
const updateMap = new Map();
for (const prop of Object.keys(obj)) {
updateMap.set(new path_1.FieldPath(prop), obj[prop]);
}
return DocumentTransform.fromUpdateMap(ref, updateMap);
} |
JavaScript | static fromUpdateMap(ref, data) {
const transforms = new Map();
function encode_(val, path, allowTransforms) {
if (val instanceof field_value_1.FieldTransform && val.includeInDocumentTransform) {
if (allowTransforms) {
transforms.set(path, val);
}
else {
throw new Error(`${val.methodName}() is not supported inside of array values.`);
}
}
else if (Array.isArray(val)) {
for (let i = 0; i < val.length; ++i) {
// We need to verify that no array value contains a document transform
encode_(val[i], path.append(String(i)), false);
}
}
else if (serializer_1.isPlainObject(val)) {
for (const prop of Object.keys(val)) {
encode_(val[prop], path.append(new path_1.FieldPath(prop)), allowTransforms);
}
}
}
data.forEach((value, key) => {
encode_(value, path_1.FieldPath.fromArgument(key), true);
});
return new DocumentTransform(ref, transforms);
} | static fromUpdateMap(ref, data) {
const transforms = new Map();
function encode_(val, path, allowTransforms) {
if (val instanceof field_value_1.FieldTransform && val.includeInDocumentTransform) {
if (allowTransforms) {
transforms.set(path, val);
}
else {
throw new Error(`${val.methodName}() is not supported inside of array values.`);
}
}
else if (Array.isArray(val)) {
for (let i = 0; i < val.length; ++i) {
// We need to verify that no array value contains a document transform
encode_(val[i], path.append(String(i)), false);
}
}
else if (serializer_1.isPlainObject(val)) {
for (const prop of Object.keys(val)) {
encode_(val[prop], path.append(new path_1.FieldPath(prop)), allowTransforms);
}
}
}
data.forEach((value, key) => {
encode_(value, path_1.FieldPath.fromArgument(key), true);
});
return new DocumentTransform(ref, transforms);
} |
JavaScript | toProto(serializer) {
if (this.isEmpty) {
return null;
}
const fieldTransforms = [];
for (const [path, transform] of this.transforms) {
fieldTransforms.push(transform.toProto(serializer, path));
}
return {
transform: {
document: this.ref.formattedName,
fieldTransforms,
},
};
} | toProto(serializer) {
if (this.isEmpty) {
return null;
}
const fieldTransforms = [];
for (const [path, transform] of this.transforms) {
fieldTransforms.push(transform.toProto(serializer, path));
}
return {
transform: {
document: this.ref.formattedName,
fieldTransforms,
},
};
} |
JavaScript | toProto() {
if (this.isEmpty) {
return null;
}
const proto = {};
if (this._lastUpdateTime !== undefined) {
const valueProto = this._lastUpdateTime.toProto();
proto.updateTime = valueProto.timestampValue;
}
else {
proto.exists = this._exists;
}
return proto;
} | toProto() {
if (this.isEmpty) {
return null;
}
const proto = {};
if (this._lastUpdateTime !== undefined) {
const valueProto = this._lastUpdateTime.toProto();
proto.updateTime = valueProto.timestampValue;
}
else {
proto.exists = this._exists;
}
return proto;
} |
JavaScript | function expression(args, code, ctx) {
// wrap code in return statement if expression does not terminate
if (code[code.length-1] !== ';') {
code = 'return(' + code + ');';
}
var fn = Function.apply(null, args.concat(code));
return ctx && ctx.functions ? fn.bind(ctx.functions) : fn;
} | function expression(args, code, ctx) {
// wrap code in return statement if expression does not terminate
if (code[code.length-1] !== ';') {
code = 'return(' + code + ');';
}
var fn = Function.apply(null, args.concat(code));
return ctx && ctx.functions ? fn.bind(ctx.functions) : fn;
} |
JavaScript | function parseParameters(spec, ctx, params) {
params = params || {};
var key, value;
for (key in spec) {
value = spec[key];
params[key] = vegaUtil.isArray(value)
? value.map(function(v) { return parseParameter(v, ctx, params); })
: parseParameter(value, ctx, params);
}
return params;
} | function parseParameters(spec, ctx, params) {
params = params || {};
var key, value;
for (key in spec) {
value = spec[key];
params[key] = vegaUtil.isArray(value)
? value.map(function(v) { return parseParameter(v, ctx, params); })
: parseParameter(value, ctx, params);
}
return params;
} |
JavaScript | function parseOperatorParameters(spec, ctx) {
if (spec.params) {
var op = ctx.get(spec.id);
if (!op) vegaUtil.error('Invalid operator id: ' + spec.id);
ctx.dataflow.connect(op, op.parameters(
parseParameters(spec.params, ctx),
spec.react,
spec.initonly
));
}
} | function parseOperatorParameters(spec, ctx) {
if (spec.params) {
var op = ctx.get(spec.id);
if (!op) vegaUtil.error('Invalid operator id: ' + spec.id);
ctx.dataflow.connect(op, op.parameters(
parseParameters(spec.params, ctx),
spec.react,
spec.initonly
));
}
} |
JavaScript | function parseStream(spec, ctx) {
var filter = spec.filter != null ? eventExpression(spec.filter, ctx) : undefined,
stream = spec.stream != null ? ctx.get(spec.stream) : undefined,
args;
if (spec.source) {
stream = ctx.events(spec.source, spec.type, filter);
}
else if (spec.merge) {
args = spec.merge.map(ctx.get.bind(ctx));
stream = args[0].merge.apply(args[0], args.slice(1));
}
if (spec.between) {
args = spec.between.map(ctx.get.bind(ctx));
stream = stream.between(args[0], args[1]);
}
if (spec.filter) {
stream = stream.filter(filter);
}
if (spec.throttle != null) {
stream = stream.throttle(+spec.throttle);
}
if (spec.debounce != null) {
stream = stream.debounce(+spec.debounce);
}
if (stream == null) {
vegaUtil.error('Invalid stream definition: ' + JSON.stringify(spec));
}
if (spec.consume) stream.consume(true);
ctx.stream(spec, stream);
} | function parseStream(spec, ctx) {
var filter = spec.filter != null ? eventExpression(spec.filter, ctx) : undefined,
stream = spec.stream != null ? ctx.get(spec.stream) : undefined,
args;
if (spec.source) {
stream = ctx.events(spec.source, spec.type, filter);
}
else if (spec.merge) {
args = spec.merge.map(ctx.get.bind(ctx));
stream = args[0].merge.apply(args[0], args.slice(1));
}
if (spec.between) {
args = spec.between.map(ctx.get.bind(ctx));
stream = stream.between(args[0], args[1]);
}
if (spec.filter) {
stream = stream.filter(filter);
}
if (spec.throttle != null) {
stream = stream.throttle(+spec.throttle);
}
if (spec.debounce != null) {
stream = stream.debounce(+spec.debounce);
}
if (stream == null) {
vegaUtil.error('Invalid stream definition: ' + JSON.stringify(spec));
}
if (spec.consume) stream.consume(true);
ctx.stream(spec, stream);
} |
JavaScript | function parseUpdate(spec, ctx) {
var srcid = vegaUtil.isObject(srcid = spec.source) ? srcid.$ref : srcid,
source = ctx.get(srcid),
target = null,
update = spec.update,
params = undefined;
if (!source) vegaUtil.error('Source not defined: ' + spec.source);
if (spec.target && spec.target.$expr) {
target = eventExpression(spec.target.$expr, ctx);
} else {
target = ctx.get(spec.target);
}
if (update && update.$expr) {
if (update.$params) {
params = parseParameters(update.$params, ctx);
}
update = handlerExpression(update.$expr, ctx);
}
ctx.update(spec, source, target, update, params);
} | function parseUpdate(spec, ctx) {
var srcid = vegaUtil.isObject(srcid = spec.source) ? srcid.$ref : srcid,
source = ctx.get(srcid),
target = null,
update = spec.update,
params = undefined;
if (!source) vegaUtil.error('Source not defined: ' + spec.source);
if (spec.target && spec.target.$expr) {
target = eventExpression(spec.target.$expr, ctx);
} else {
target = ctx.get(spec.target);
}
if (update && update.$expr) {
if (update.$params) {
params = parseParameters(update.$params, ctx);
}
update = handlerExpression(update.$expr, ctx);
}
ctx.update(spec, source, target, update, params);
} |
JavaScript | function parseDataflow(spec, ctx) {
var operators = spec.operators || [];
// parse background
if (spec.background) {
ctx.background = spec.background;
}
// parse event configuration
if (spec.eventConfig) {
ctx.eventConfig = spec.eventConfig;
}
// parse operators
operators.forEach(function(entry) {
parseOperator(entry, ctx);
});
// parse operator parameters
operators.forEach(function(entry) {
parseOperatorParameters(entry, ctx);
});
// parse streams
(spec.streams || []).forEach(function(entry) {
parseStream(entry, ctx);
});
// parse updates
(spec.updates || []).forEach(function(entry) {
parseUpdate(entry, ctx);
});
return ctx.resolve();
} | function parseDataflow(spec, ctx) {
var operators = spec.operators || [];
// parse background
if (spec.background) {
ctx.background = spec.background;
}
// parse event configuration
if (spec.eventConfig) {
ctx.eventConfig = spec.eventConfig;
}
// parse operators
operators.forEach(function(entry) {
parseOperator(entry, ctx);
});
// parse operator parameters
operators.forEach(function(entry) {
parseOperatorParameters(entry, ctx);
});
// parse streams
(spec.streams || []).forEach(function(entry) {
parseStream(entry, ctx);
});
// parse updates
(spec.updates || []).forEach(function(entry) {
parseUpdate(entry, ctx);
});
return ctx.resolve();
} |
JavaScript | onSnapshot(onNext, onError) {
assert(this.onNext === EMPTY_FUNCTION, 'onNext should not already be defined.');
assert(this.onError === EMPTY_FUNCTION, 'onError should not already be defined.');
assert(this.docTree === undefined, 'docTree should not already be defined.');
this.onNext = onNext;
this.onError = onError;
this.docTree = rbtree(this.getComparator());
this.initStream();
return () => {
logger_1.logger('Watch.onSnapshot', this.requestTag, 'Ending stream');
// Prevent further callbacks.
this.isActive = false;
this.onNext = () => { };
this.onError = () => { };
if (this.currentStream) {
this.currentStream.end();
}
};
} | onSnapshot(onNext, onError) {
assert(this.onNext === EMPTY_FUNCTION, 'onNext should not already be defined.');
assert(this.onError === EMPTY_FUNCTION, 'onError should not already be defined.');
assert(this.docTree === undefined, 'docTree should not already be defined.');
this.onNext = onNext;
this.onError = onError;
this.docTree = rbtree(this.getComparator());
this.initStream();
return () => {
logger_1.logger('Watch.onSnapshot', this.requestTag, 'Ending stream');
// Prevent further callbacks.
this.isActive = false;
this.onNext = () => { };
this.onError = () => { };
if (this.currentStream) {
this.currentStream.end();
}
};
} |
JavaScript | extractCurrentChanges(readTime) {
const deletes = [];
const adds = [];
const updates = [];
this.changeMap.forEach((value, name) => {
if (value === REMOVED) {
if (this.docMap.has(name)) {
deletes.push(name);
}
}
else if (this.docMap.has(name)) {
value.readTime = readTime;
updates.push(value.build());
}
else {
value.readTime = readTime;
adds.push(value.build());
}
});
return { deletes, adds, updates };
} | extractCurrentChanges(readTime) {
const deletes = [];
const adds = [];
const updates = [];
this.changeMap.forEach((value, name) => {
if (value === REMOVED) {
if (this.docMap.has(name)) {
deletes.push(name);
}
}
else if (this.docMap.has(name)) {
value.readTime = readTime;
updates.push(value.build());
}
else {
value.readTime = readTime;
adds.push(value.build());
}
});
return { deletes, adds, updates };
} |
JavaScript | resetDocs() {
logger_1.logger('Watch.resetDocs', this.requestTag, 'Resetting documents');
this.changeMap.clear();
this.resumeToken = undefined;
this.docTree.forEach((snapshot) => {
// Mark each document as deleted. If documents are not deleted, they
// will be send again by the server.
this.changeMap.set(snapshot.ref.path, REMOVED);
});
this.current = false;
} | resetDocs() {
logger_1.logger('Watch.resetDocs', this.requestTag, 'Resetting documents');
this.changeMap.clear();
this.resumeToken = undefined;
this.docTree.forEach((snapshot) => {
// Mark each document as deleted. If documents are not deleted, they
// will be send again by the server.
this.changeMap.set(snapshot.ref.path, REMOVED);
});
this.current = false;
} |
JavaScript | closeStream(err) {
if (this.currentStream) {
this.currentStream.end();
this.currentStream = null;
}
if (this.isActive) {
this.isActive = false;
logger_1.logger('Watch.closeStream', this.requestTag, 'Invoking onError: ', err);
this.onError(err);
}
} | closeStream(err) {
if (this.currentStream) {
this.currentStream.end();
this.currentStream = null;
}
if (this.isActive) {
this.isActive = false;
logger_1.logger('Watch.closeStream', this.requestTag, 'Invoking onError: ', err);
this.onError(err);
}
} |
JavaScript | maybeReopenStream(err) {
if (this.isActive && !this.isPermanentError(err)) {
logger_1.logger('Watch.maybeReopenStream', this.requestTag, 'Stream ended, re-opening after retryable error: ', err);
this.changeMap.clear();
if (this.isResourceExhaustedError(err)) {
this.backoff.resetToMax();
}
this.initStream();
}
else {
this.closeStream(err);
}
} | maybeReopenStream(err) {
if (this.isActive && !this.isPermanentError(err)) {
logger_1.logger('Watch.maybeReopenStream', this.requestTag, 'Stream ended, re-opening after retryable error: ', err);
this.changeMap.clear();
if (this.isResourceExhaustedError(err)) {
this.backoff.resetToMax();
}
this.initStream();
}
else {
this.closeStream(err);
}
} |
JavaScript | resetStream() {
logger_1.logger('Watch.resetStream', this.requestTag, 'Restarting stream');
if (this.currentStream) {
this.currentStream.end();
this.currentStream = null;
}
this.initStream();
} | resetStream() {
logger_1.logger('Watch.resetStream', this.requestTag, 'Restarting stream');
if (this.currentStream) {
this.currentStream.end();
this.currentStream = null;
}
this.initStream();
} |
JavaScript | initStream() {
this.backoff
.backoffAndWait()
.then(async () => {
if (!this.isActive) {
logger_1.logger('Watch.initStream', this.requestTag, 'Not initializing inactive stream');
return;
}
await this.firestore.initializeIfNeeded(this.requestTag);
const request = {};
request.database = this.firestore.formattedName;
request.addTarget = this.getTarget(this.resumeToken);
// Note that we need to call the internal _listen API to pass additional
// header values in readWriteStream.
return this.firestore
.readWriteStream('listen', request, this.requestTag, true)
.then(backendStream => {
if (!this.isActive) {
logger_1.logger('Watch.initStream', this.requestTag, 'Closing inactive stream');
backendStream.end();
return;
}
logger_1.logger('Watch.initStream', this.requestTag, 'Opened new stream');
this.currentStream = backendStream;
this.currentStream.on('data', (proto) => {
this.onData(proto);
})
.on('error', err => {
if (this.currentStream === backendStream) {
this.currentStream = null;
this.maybeReopenStream(err);
}
})
.on('end', () => {
if (this.currentStream === backendStream) {
this.currentStream = null;
const err = new types_1.GrpcError('Stream ended unexpectedly');
err.code = GRPC_STATUS_CODE.UNKNOWN;
this.maybeReopenStream(err);
}
});
this.currentStream.resume();
});
})
.catch(err => {
this.closeStream(err);
});
} | initStream() {
this.backoff
.backoffAndWait()
.then(async () => {
if (!this.isActive) {
logger_1.logger('Watch.initStream', this.requestTag, 'Not initializing inactive stream');
return;
}
await this.firestore.initializeIfNeeded(this.requestTag);
const request = {};
request.database = this.firestore.formattedName;
request.addTarget = this.getTarget(this.resumeToken);
// Note that we need to call the internal _listen API to pass additional
// header values in readWriteStream.
return this.firestore
.readWriteStream('listen', request, this.requestTag, true)
.then(backendStream => {
if (!this.isActive) {
logger_1.logger('Watch.initStream', this.requestTag, 'Closing inactive stream');
backendStream.end();
return;
}
logger_1.logger('Watch.initStream', this.requestTag, 'Opened new stream');
this.currentStream = backendStream;
this.currentStream.on('data', (proto) => {
this.onData(proto);
})
.on('error', err => {
if (this.currentStream === backendStream) {
this.currentStream = null;
this.maybeReopenStream(err);
}
})
.on('end', () => {
if (this.currentStream === backendStream) {
this.currentStream = null;
const err = new types_1.GrpcError('Stream ended unexpectedly');
err.code = GRPC_STATUS_CODE.UNKNOWN;
this.maybeReopenStream(err);
}
});
this.currentStream.resume();
});
})
.catch(err => {
this.closeStream(err);
});
} |
JavaScript | onData(proto) {
if (proto.targetChange) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing target change');
const change = proto.targetChange;
const noTargetIds = !change.targetIds || change.targetIds.length === 0;
if (change.targetChangeType === 'NO_CHANGE') {
if (noTargetIds && change.readTime && this.current) {
// This means everything is up-to-date, so emit the current
// set of docs as a snapshot, if there were changes.
this.pushSnapshot(timestamp_1.Timestamp.fromProto(change.readTime), change.resumeToken);
}
}
else if (change.targetChangeType === 'ADD') {
if (WATCH_TARGET_ID !== change.targetIds[0]) {
this.closeStream(Error('Unexpected target ID sent by server'));
}
}
else if (change.targetChangeType === 'REMOVE') {
let code = 13;
let message = 'internal error';
if (change.cause) {
code = change.cause.code;
message = change.cause.message;
}
// @todo: Surface a .code property on the exception.
this.closeStream(new Error('Error ' + code + ': ' + message));
}
else if (change.targetChangeType === 'RESET') {
// Whatever changes have happened so far no longer matter.
this.resetDocs();
}
else if (change.targetChangeType === 'CURRENT') {
this.current = true;
}
else {
this.closeStream(new Error('Unknown target change type: ' + JSON.stringify(change)));
}
if (change.resumeToken &&
this.affectsTarget(change.targetIds, WATCH_TARGET_ID)) {
this.backoff.reset();
}
}
else if (proto.documentChange) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing change event');
// No other targetIds can show up here, but we still need to see
// if the targetId was in the added list or removed list.
const targetIds = proto.documentChange.targetIds || [];
const removedTargetIds = proto.documentChange.removedTargetIds || [];
let changed = false;
let removed = false;
for (let i = 0; i < targetIds.length; i++) {
if (targetIds[i] === WATCH_TARGET_ID) {
changed = true;
}
}
for (let i = 0; i < removedTargetIds.length; i++) {
if (removedTargetIds[i] === WATCH_TARGET_ID) {
removed = true;
}
}
const document = proto.documentChange.document;
const name = document.name;
const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name)
.relativeName;
if (changed) {
logger_1.logger('Watch.onData', this.requestTag, 'Received document change');
const snapshot = new document_1.DocumentSnapshotBuilder();
snapshot.ref = this.firestore.doc(relativeName);
snapshot.fieldsProto = document.fields || {};
snapshot.createTime = timestamp_1.Timestamp.fromProto(document.createTime);
snapshot.updateTime = timestamp_1.Timestamp.fromProto(document.updateTime);
this.changeMap.set(relativeName, snapshot);
}
else if (removed) {
logger_1.logger('Watch.onData', this.requestTag, 'Received document remove');
this.changeMap.set(relativeName, REMOVED);
}
}
else if (proto.documentDelete || proto.documentRemove) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing remove event');
const name = (proto.documentDelete || proto.documentRemove).document;
const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name)
.relativeName;
this.changeMap.set(relativeName, REMOVED);
}
else if (proto.filter) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing filter update');
if (proto.filter.count !== this.currentSize()) {
// We need to remove all the current results.
this.resetDocs();
// The filter didn't match, so re-issue the query.
this.resetStream();
}
}
else {
this.closeStream(new Error('Unknown listen response type: ' + JSON.stringify(proto)));
}
} | onData(proto) {
if (proto.targetChange) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing target change');
const change = proto.targetChange;
const noTargetIds = !change.targetIds || change.targetIds.length === 0;
if (change.targetChangeType === 'NO_CHANGE') {
if (noTargetIds && change.readTime && this.current) {
// This means everything is up-to-date, so emit the current
// set of docs as a snapshot, if there were changes.
this.pushSnapshot(timestamp_1.Timestamp.fromProto(change.readTime), change.resumeToken);
}
}
else if (change.targetChangeType === 'ADD') {
if (WATCH_TARGET_ID !== change.targetIds[0]) {
this.closeStream(Error('Unexpected target ID sent by server'));
}
}
else if (change.targetChangeType === 'REMOVE') {
let code = 13;
let message = 'internal error';
if (change.cause) {
code = change.cause.code;
message = change.cause.message;
}
// @todo: Surface a .code property on the exception.
this.closeStream(new Error('Error ' + code + ': ' + message));
}
else if (change.targetChangeType === 'RESET') {
// Whatever changes have happened so far no longer matter.
this.resetDocs();
}
else if (change.targetChangeType === 'CURRENT') {
this.current = true;
}
else {
this.closeStream(new Error('Unknown target change type: ' + JSON.stringify(change)));
}
if (change.resumeToken &&
this.affectsTarget(change.targetIds, WATCH_TARGET_ID)) {
this.backoff.reset();
}
}
else if (proto.documentChange) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing change event');
// No other targetIds can show up here, but we still need to see
// if the targetId was in the added list or removed list.
const targetIds = proto.documentChange.targetIds || [];
const removedTargetIds = proto.documentChange.removedTargetIds || [];
let changed = false;
let removed = false;
for (let i = 0; i < targetIds.length; i++) {
if (targetIds[i] === WATCH_TARGET_ID) {
changed = true;
}
}
for (let i = 0; i < removedTargetIds.length; i++) {
if (removedTargetIds[i] === WATCH_TARGET_ID) {
removed = true;
}
}
const document = proto.documentChange.document;
const name = document.name;
const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name)
.relativeName;
if (changed) {
logger_1.logger('Watch.onData', this.requestTag, 'Received document change');
const snapshot = new document_1.DocumentSnapshotBuilder();
snapshot.ref = this.firestore.doc(relativeName);
snapshot.fieldsProto = document.fields || {};
snapshot.createTime = timestamp_1.Timestamp.fromProto(document.createTime);
snapshot.updateTime = timestamp_1.Timestamp.fromProto(document.updateTime);
this.changeMap.set(relativeName, snapshot);
}
else if (removed) {
logger_1.logger('Watch.onData', this.requestTag, 'Received document remove');
this.changeMap.set(relativeName, REMOVED);
}
}
else if (proto.documentDelete || proto.documentRemove) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing remove event');
const name = (proto.documentDelete || proto.documentRemove).document;
const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name)
.relativeName;
this.changeMap.set(relativeName, REMOVED);
}
else if (proto.filter) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing filter update');
if (proto.filter.count !== this.currentSize()) {
// We need to remove all the current results.
this.resetDocs();
// The filter didn't match, so re-issue the query.
this.resetStream();
}
}
else {
this.closeStream(new Error('Unknown listen response type: ' + JSON.stringify(proto)));
}
} |
JavaScript | affectsTarget(targetIds, currentId) {
if (targetIds === undefined || targetIds.length === 0) {
return true;
}
for (const targetId of targetIds) {
if (targetId === currentId) {
return true;
}
}
return false;
} | affectsTarget(targetIds, currentId) {
if (targetIds === undefined || targetIds.length === 0) {
return true;
}
for (const targetId of targetIds) {
if (targetId === currentId) {
return true;
}
}
return false;
} |
JavaScript | pushSnapshot(readTime, nextResumeToken) {
const appliedChanges = this.computeSnapshot(readTime);
if (!this.hasPushed || appliedChanges.length > 0) {
logger_1.logger('Watch.pushSnapshot', this.requestTag, 'Sending snapshot with %d changes and %d documents', String(appliedChanges.length), this.docTree.length);
// We pass the current set of changes, even if `docTree` is modified later.
const currentTree = this.docTree;
this.onNext(readTime, currentTree.length, () => currentTree.keys, () => appliedChanges);
this.hasPushed = true;
}
this.changeMap.clear();
this.resumeToken = nextResumeToken;
} | pushSnapshot(readTime, nextResumeToken) {
const appliedChanges = this.computeSnapshot(readTime);
if (!this.hasPushed || appliedChanges.length > 0) {
logger_1.logger('Watch.pushSnapshot', this.requestTag, 'Sending snapshot with %d changes and %d documents', String(appliedChanges.length), this.docTree.length);
// We pass the current set of changes, even if `docTree` is modified later.
const currentTree = this.docTree;
this.onNext(readTime, currentTree.length, () => currentTree.keys, () => appliedChanges);
this.hasPushed = true;
}
this.changeMap.clear();
this.resumeToken = nextResumeToken;
} |
JavaScript | deleteDoc(name) {
assert(this.docMap.has(name), 'Document to delete does not exist');
const oldDocument = this.docMap.get(name);
const existing = this.docTree.find(oldDocument);
const oldIndex = existing.index;
this.docTree = existing.remove();
this.docMap.delete(name);
return new document_change_1.DocumentChange(ChangeType.removed, oldDocument, oldIndex, -1);
} | deleteDoc(name) {
assert(this.docMap.has(name), 'Document to delete does not exist');
const oldDocument = this.docMap.get(name);
const existing = this.docTree.find(oldDocument);
const oldIndex = existing.index;
this.docTree = existing.remove();
this.docMap.delete(name);
return new document_change_1.DocumentChange(ChangeType.removed, oldDocument, oldIndex, -1);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.