language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class MainController {
constructor($http) {
this.$http = $http;
this.mainFeedbacks = [];
/**
* Getting all feedback on the home screen
*/
$http.get('/api/feedbacks').then(response => {
this.mainFeedbacks = response.data;
});
}
} |
JavaScript | class ParseError extends core_1.RequestError {
constructor(error, response) {
const { options } = response.request;
super(`${error.message} in "${options.url.toString()}"`, error, response.request);
this.name = 'ParseError';
}
} |
JavaScript | class CancelError extends core_1.RequestError {
constructor(request) {
super('Promise was canceled', {}, request);
this.name = 'CancelError';
}
get isCanceled() {
return true;
}
} |
JavaScript | class RequestError extends Error {
constructor(message, error, self) {
var _a;
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = 'RequestError';
this.code = error.code;
if (self instanceof Request) {
Object.defineProperty(this, 'request', {
enumerable: false,
value: self
});
Object.defineProperty(this, 'response', {
enumerable: false,
value: self[kResponse]
});
Object.defineProperty(this, 'options', {
// This fails because of TS 3.7.2 useDefineForClassFields
// Ref: https://github.com/microsoft/TypeScript/issues/34972
enumerable: false,
value: self.options
});
}
else {
Object.defineProperty(this, 'options', {
// This fails because of TS 3.7.2 useDefineForClassFields
// Ref: https://github.com/microsoft/TypeScript/issues/34972
enumerable: false,
value: self
});
}
this.timings = (_a = this.request) === null || _a === void 0 ? void 0 : _a.timings;
// Recover the original stacktrace
if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) {
const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;
const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse();
const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse();
// Remove duplicated traces
while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) {
thisStackTrace.shift();
}
this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`;
}
}
} |
JavaScript | class MaxRedirectsError extends RequestError {
constructor(request) {
super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);
this.name = 'MaxRedirectsError';
}
} |
JavaScript | class HTTPError extends RequestError {
constructor(response) {
super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request);
this.name = 'HTTPError';
}
} |
JavaScript | class CacheError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'CacheError';
}
} |
JavaScript | class UploadError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'UploadError';
}
} |
JavaScript | class TimeoutError extends RequestError {
constructor(error, timings, request) {
super(error.message, error, request);
this.name = 'TimeoutError';
this.event = error.event;
this.timings = timings;
}
} |
JavaScript | class ReadError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'ReadError';
}
} |
JavaScript | class UnsupportedProtocolError extends RequestError {
constructor(options) {
super(`Unsupported protocol "${options.url.protocol}"`, {}, options);
this.name = 'UnsupportedProtocolError';
}
} |
JavaScript | class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' }; /* everytime user types in the input, this.state.term becomes the value of the input */
}
/* by default, each class should have a render method */
render() {
/* never do 'this.state.term = event.target.value' ALWAYS USE 'set.State()' */
return (
<div className="search-bar">
<input
value={this.state.term} /* controlled form component, value only changes when state changes */
onChange={event => this.onInputChange(event.target.value)} />
</div>
);
/* we want to add an event listener to see when the text in the input changes. onChange is a special react defined property, there are different properties properties based on the event. Pass in the function that you want to occur when the input chages */
}
/* we want to handle changes to the input when user types something in */
// onInputChange(event) {
// console.log(event.target.value);
// }
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term); /* call back function */
}
} |
JavaScript | class AbribusManager {
/**
* AbribusManager constructor
* @param {Object} options The options as a JSON object.
* @param {DatabaseManager} database The database manager.
* @constructor
*/
constructor(options, database) {
options = options || {};
this.esClient = options.esClient;
this.database = database;
}
/**
* Retrieve an Abribus query.
* @param {String} type The type of query.
* @param {callback} callback Function to call on completion.
*/
retrieve(type, callback) {
switch(type) {
case 'minuteofhour':
queryMinuteOfHour(this.esClient, callback);
break;
case 'hourofday':
queryHourOfDay(this.esClient, callback);
break;
case 'dayofweek':
queryDayOfWeek(this.esClient, callback);
break;
case 'zonebytime':
queryZoneByTime(this.esClient, callback);
break;
default:
console.log('Unhandled abribus query:', type);
return callback();
}
}
} |
JavaScript | class Pickable {
/**
* Called by xeokit to get if it's possible to pick a triangle on the surface of this Drawable.
*/
canPickTriangle() {
}
/**
* Picks a triangle on this Pickable.
*/
drawPickTriangles(renderFlags, frameCtx) {
}
/**
* Given a {@link PickResult} that contains a {@link PickResult#primIndex}, which indicates that a primitive was picked on the Pickable, then add more information to the PickResult about the picked position on the surface of the Pickable.
*
* Architecturally, this delegates collection of that Pickable-specific info to the Pickable, allowing it to provide whatever info it's able to.
*
* @param {PickResult} pickResult The PickResult to augment with pick intersection information specific to this Mesh.
* @param [pickResult.primIndex] Index of the primitive that was picked on this Mesh.
* @param [pickResult.canvasPos] Canvas coordinates, provided when picking through the Canvas.
* @param [pickResult.origin] World-space 3D ray origin, when ray picking.
* @param [pickResult.direction] World-space 3D ray direction, provided when ray picking.
*/
pickTriangleSurface(pickResult) {
}
/**
* Called by xeokit to get if it's possible to pick a 3D point on the surface of this Pickable.
* Returns false if canPickTriangle returns true, and vice-versa.
*/
canPickWorldPos() {
}
/**
* Renders color-encoded fragment depths of this Pickable.
* @param frameCtx
*/
drawPickDepths(renderFlags, frameCtx) {
}
/**
* Delegates an {@link Entity} as representing what was actually picked in place of this Pickable.
* @returns {PerformanceNode}
*/
delegatePickedEntity() {
return this.parent;
}
/**
* 3D origin of the Pickable's vertex positions, if they are in relative-to-center (RTC) coordinates.
*
* When this is defined, then the positions are RTC, which means that they are relative to this position.
*
* @type {Float64Array}
*/
get rtcCenter() {
}
} |
JavaScript | class MudScrollListener {
constructor() {
this.throttleScrollHandlerId = -1;
}
// subscribe to throttled scroll event
listenForScroll(dotnetReference, selector) {
//if selector is null, attach to document
let element = selector
? document.querySelector(selector)
: document;
// add the event listener
element.addEventListener(
'scroll',
this.throttleScrollHandler.bind(this, dotnetReference),
false
);
}
// fire the event just once each 100 ms, **it's hardcoded**
throttleScrollHandler(dotnetReference, event) {
clearTimeout(this.throttleScrollHandlerId);
this.throttleScrollHandlerId = window.setTimeout(
this.scrollHandler.bind(this, dotnetReference, event),
100
);
}
// when scroll event is fired, pass this information to
// the RaiseOnScroll C# method of the ScrollListener
// We pass the scroll coordinates of the element and
// the boundingClientRect of the first child, because
// scrollTop of body is always 0. With this information,
// we can trigger C# events on different scroll situations
scrollHandler(dotnetReference, event) {
try {
let element = event.target;
//data to pass
let scrollTop = element.scrollTop;
let scrollHeight = element.scrollHeight;
let scrollWidth = element.scrollWidth;
let scrollLeft = element.scrollLeft;
let nodeName = element.nodeName;
//data to pass
let firstChild = element.firstElementChild;
let firstChildBoundingClientRect = firstChild.getBoundingClientRect();
//invoke C# method
dotnetReference.invokeMethodAsync('RaiseOnScroll', {
firstChildBoundingClientRect,
scrollLeft,
scrollTop,
scrollHeight,
scrollWidth,
nodeName,
});
} catch (error) {
console.log('[MudBlazor] Error in scrollHandler:', { error });
}
}
//remove event listener
cancelListener(selector) {
let element = selector
? document.querySelector(selector)
: document.documentElement;
element.removeEventListener('scroll', this.throttleScrollHandler);
}
} |
JavaScript | class DocumentSelectionState {
/**
* @param {number} anchor
* @param {number} focus
*/
constructor(anchor, focus) {
this._anchorOffset = anchor;
this._focusOffset = focus;
this._hasFocus = false;
}
/**
* Apply an update to the state. If either offset value has changed,
* set the values and emit the `change` event. Otherwise no-op.
*
* @param {number} anchor
* @param {number} focus
*/
update(anchor, focus) {
if (this._anchorOffset !== anchor || this._focusOffset !== focus) {
this._anchorOffset = anchor;
this._focusOffset = focus;
this.emit('update');
}
}
/**
* Given a max text length, constrain our selection offsets to ensure
* that the selection remains strictly within the text range.
*
* @param {number} maxLength
*/
constrainLength(maxLength) {
this.update(
Math.min(this._anchorOffset, maxLength),
Math.min(this._focusOffset, maxLength)
);
}
focus() {
if (!this._hasFocus) {
this._hasFocus = true;
this.emit('focus');
}
}
blur() {
if (this._hasFocus) {
this._hasFocus = false;
this.emit('blur');
}
}
/**
* @return {boolean}
*/
hasFocus() {
return this._hasFocus;
}
/**
* @return {boolean}
*/
isCollapsed() {
return this._anchorOffset === this._focusOffset;
}
/**
* @return {boolean}
*/
isBackward() {
return this._anchorOffset > this._focusOffset;
}
/**
* @return {?number}
*/
getAnchorOffset() {
return this._hasFocus ? this._anchorOffset : null;
}
/**
* @return {?number}
*/
getFocusOffset() {
return this._hasFocus ? this._focusOffset : null;
}
/**
* @return {?number}
*/
getStartOffset() {
return (
this._hasFocus ? Math.min(this._anchorOffset, this._focusOffset) : null
);
}
/**
* @return {?number}
*/
getEndOffset() {
return (
this._hasFocus ? Math.max(this._anchorOffset, this._focusOffset) : null
);
}
/**
* @param {number} start
* @param {number} end
* @return {boolean}
*/
overlaps(start, end) {
return (
this.hasFocus() &&
this.getStartOffset() <= end && start <= this.getEndOffset()
);
}
} |
JavaScript | class MTollsRechargesrequest extends BaseModel {
/**
* @constructor
* @param {Object} obj The object passed to constructor
*/
constructor(obj) {
super(obj);
if (obj === undefined || obj === null) return;
this.accountNumber = this.constructor.getValue(obj.accountNumber);
this.hexCardNumber = this.constructor.getValue(obj.hexCardNumber);
this.internalCounterHex = this.constructor.getValue(obj.internalCounterHex);
this.transactionPartnerNumber = this.constructor.getValue(obj.transactionPartnerNumber);
this.feeTollValue = this.constructor.getValue(obj.feeTollValue);
this.creditTollValue = this.constructor.getValue(obj.creditTollValue);
this.transactionCounter = this.constructor.getValue(obj.transactionCounter);
this.cardBalance = this.constructor.getValue(obj.cardBalance);
this.requestDate = this.constructor.getValue(obj.requestDate);
}
/**
* Function containing information about the fields of this model
* @return {array} Array of objects containing information about the fields
*/
static mappingInfo() {
return super.mappingInfo().concat([
{ name: 'accountNumber', realName: 'accountNumber' },
{ name: 'hexCardNumber', realName: 'hexCardNumber' },
{ name: 'internalCounterHex', realName: 'internalCounterHex' },
{ name: 'transactionPartnerNumber', realName: 'transactionPartnerNumber' },
{ name: 'feeTollValue', realName: 'feeTollValue' },
{ name: 'creditTollValue', realName: 'creditTollValue' },
{ name: 'transactionCounter', realName: 'transactionCounter' },
{ name: 'cardBalance', realName: 'cardBalance' },
{ name: 'requestDate', realName: 'requestDate' },
]);
}
/**
* Function containing information about discriminator values
* mapped with their corresponding model class names
*
* @return {object} Object containing Key-Value pairs mapping discriminator
* values with their corresponding model classes
*/
static discriminatorMap() {
return {};
}
} |
JavaScript | class Selafin{
constructor(buffer,options){
if(!options)options={};
this.debug = options.debug || false;
this.fromProj = options.fromProj || 'EPSG:4326';
this.toProj = options.toProj || 'EPSG:4326';
this.keepframes = (typeof options.keepframes==='undefined')?true:options.keepframes;
(buffer)?this.initialised(buffer):this.initialisedBlank();
}
initialisedBlank(){
this.file = {endian:'>',float:['f',4]};
this.TITLE = '';
this.NBV1 = 0; this.NBV2 = 0; this.NVAR = this.NBV1 + this.NBV2;
this.VARINDEX = range(this.NVAR);
this.IPARAM = [];
this.NELEM3 = 0; this.NPOIN3 = 0; this.NDP3 = 0; this.NPLAN = 1;
this.NELEM2 = 0; this.NPOIN2 = 0; this.NDP2 = 0;
this.NBV1 = 0; this.VARNAMES = []; this.VARUNITS = [];
this.NBV2 = 0; this.CLDNAMES = []; this.CLDUNITS = [];
this.IKLE3 = []; this.IKLE2 = []; this.IPOB2 = []; this.IPOB3 = []; this.MESHX = []; this.MESHY = [];
this.tags = {cores:[],times:[]};
this.NFRAME = 0;
}
initialised(buffer){
let debug = this.debug;
if (debug) console.time('Initialised selafin object');
// ~~> Convert buffer to uint8array
if (debug) console.time('Buffer to Uint8Array');
this.uint8array = new Uint8Array(buffer);
if (debug) console.timeEnd('Buffer to Uint8Array');
// ~~> Initialised file object and check endian encoding
this.file = {};
this.file.endian = this.getEndianFromChar(80);
// ~~> header parameters
let pos=this.getHeaderMetaDataSLF();
// ~~> connectivity
if (debug) console.time('Get connectivity matrix');
let posHeader=this.getHeaderIntegersSLF(pos);
if (debug) console.timeEnd('Get connectivity matrix');
// ~~> modify connectivity matrix : Change id to index
if (debug) console.time('Change connectivity matrix: id to index');
this.IKLE3.add(-1);
if (debug) console.timeEnd('Change connectivity matrix: id to index');
// ~~> modify connectivity matrix : Reordering matrix
if (debug) console.time('Reorder connectivity matrix');
this.IKLE3F = this.IKLE3;
this.IKLE3 = this.reshapeIKLE();
if (debug) console.timeEnd('Reorder connectivity matrix');
// ~~> checks float encoding
this.file.float = this.getFloatTypeFromFloat(posHeader);
// ~~> xy mesh
if (debug) console.time('Get mesh XY');
let posTS = this.getHeaderFloatsSLF(posHeader);
if (debug) console.timeEnd('Get mesh XY');
// ~~> frames
if (debug) console.time('Get frame tags');
this.tags =this.getTimeHistorySLF(posTS);
if (debug) console.timeEnd('Get frame tags');
// ~~> keeping buffer?
// if (!(keepbuffer)) this.uint8array = null;
if(this.keepframes)this.getFrames();
// ~~> transform xy mesh
if (debug) console.time('Transform mesh XY');
this.transform();
if (debug) console.timeEnd('Transform mesh XY');
// ~~> min/max values
// if (debug) console.time('Get min/max');
// this.minmax = this.getMinMax();
// if (debug) console.timeEnd('Get min/max');
this.initializeProperties();
if (debug) {
console.timeEnd('Initialised selafin object');
console.log("NELEM:%d,NPOIN:%d,NFRAME:%d",this.NELEM3,this.NPOIN3,this.NFRAME);
}
}
initializeProperties(){
// ~~> initialize dynamic properties
this._TRIXY = null;
this._TRIAREA = null;
this._CX = null;
this._CY = null;
this._EDGES = null;
this._BEDGES = null;
this._IEDGES = null;
}
getEndianFromChar(nchar){
let uint8array = this.uint8array;
let endian = ">"; // "<" means little-endian, ">" means big-endian
let l,c,chk;
[l,c,chk] = bufferpack.unpack(endian+'i'+ nchar +'si',uint8array,0);
if (chk!=nchar){
endian = "<";
[l,c,chk] = bufferpack.unpack(endian+'i'+ nchar +'si',uint8array,0);
}
if (l!=chk){
throw Error('... Cannot read '+ nchar +' characters from your binary file +> Maybe it is the wrong file format ?');
}
return endian;
}
getHeaderMetaDataSLF(){
let uint8array = this.uint8array;
let endian = this.file.endian;
let l,chk;
let pos=0;
// ~~ Read title ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[l,this.TITLE,chk] = bufferpack.unpack(endian+'i80si',uint8array,pos);
pos+=4+80+4;
// ~~ Read NBV(1) and NBV(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[l,this.NBV1,this.NBV2,chk] = bufferpack.unpack(endian+'iiii',uint8array,pos);
pos+=4+8+4;
this.NVAR = this.NBV1 + this.NBV2;
this.VARINDEX = range(this.NVAR,'Uint8Array');
// ~~ Read variable names and units ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this.VARNAMES = []; this.VARUNITS = [];
this.CLDNAMES = []; this.CLDUNITS = [];
for(let i=0;i<this.NBV1;i++){
let vn,vu;
[l,vn,vu,chk] = bufferpack.unpack(endian+'i16s16si',uint8array,pos);
pos+=4+16+16+4;
this.VARNAMES.push(vn);
this.VARUNITS.push(vu);
}
for(let i=0;i<this.NBV2;i++){
let vn,vu;
[l,vn,vu,chk] = bufferpack.unpack(endian+'i16s16si',uint8array,pos);
pos+=4+16+16+4;
this.CLDNAMES.push(vn);
this.CLDUNITS.push(vu);
}
// ~~ Read IPARAM array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let d = bufferpack.unpack(endian+'12i',uint8array,pos);
pos+=4+40+4;
this.IPARAM = d.slice(1, 11);
// ~~ Projection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this.PROJ = this.IPARAM[1];
// ~~ Read DATE/TIME array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this.DATETIME = new Uint16Array([1972,7,13,17,15,13]);
if (this.IPARAM[9] == 1){
d = bufferpack.unpack(endian+'8i',pos);
pos+=4+24+4;
this.DATETIME = d.slice(1, 9);
}
return pos;
}
getHeaderIntegersSLF(pos){
let uint8array = this.uint8array;
let endian = this.file.endian;
let l,chk;
// ~~ Read NELEM3, NPOIN3, NDP3, NPLAN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[l,this.NELEM3,this.NPOIN3,this.NDP3,this.NPLAN,chk] = bufferpack.unpack(endian+'6i',uint8array,pos);
pos+=4+16+4;
this.NELEM2 = this.NELEM3;
this.NPOIN2 = this.NPOIN3;
this.NDP2 = this.NDP3;
this.NPLAN = Math.max(1,this.NPLAN);
if (this.IPARAM[6] > 1){
this.NPLAN = this.IPARAM[6]; // /!\ How strange is that ?
this.NELEM2 = this.NELEM3 / (this.NPLAN - 1);
this.NPOIN2 = this.NPOIN3 / this.NPLAN;
this.NDP2 = this.NDP3 / 2;
}
// ~~ Read the IKLE array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pos+=4;
this.IKLE3 = new Uint32Array(bufferpack.unpack(endian+(this.NELEM3*this.NDP3)+'i',uint8array,pos));
pos+=4*this.NELEM3*this.NDP3;
pos+=4;
if (this.NPLAN > 1){
// this.IKLE2 = np.compress( np.repeat([True,False],this.NDP2), this.IKLE3[0:this.NELEM2], axis=1 )
throw Error("Check Javascript for 3D");
} else {
// WARNING - NOT SAVING IKLE2
// this.IKLE2 = this.IKLE3
}
// ~~ Read the IPOBO array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pos+=4;
// WARNING - NOT SAVING IPOB3
this.IPOB3 = new Uint32Array(bufferpack.unpack(endian+this.NPOIN3+'i',uint8array,pos));
pos+=4*this.NPOIN3;
pos+=4;
// this.IPOB2 = this.IPOB3.slice(0,this.NPOIN2);
return pos;
}
getFloatTypeFromFloat(pos){
let uint8array = this.uint8array;
let endian = this.file.endian;
let nfloat = this.NPOIN3;
let ifloat = 4;
let cfloat = 'f';
let l = bufferpack.unpack(endian+'i',uint8array,pos);
pos +=4;
if (l[0]!=ifloat*nfloat){
ifloat = 8;
cfloat = 'd';
}
pos +=ifloat*nfloat;
let chk = bufferpack.unpack(endian+'i',uint8array,pos);
if (l[0]!=chk[0])throw Error('... Cannot read '+nfloat+' floats from your binary file +> Maybe it is the wrong file format ?');
return [cfloat,ifloat];
}
getHeaderFloatsSLF(pos){
let uint8array = this.uint8array;
let endian = this.file.endian;
let [ftype,fsize] = this.file.float;
// ~~ Read the x-coordinates of the nodes ~~~~~~~~~~~~~~~~~~
pos +=4;
this.MESHX = new Float32Array(bufferpack.unpack(endian+this.NPOIN3+ftype,uint8array,pos));
pos +=fsize*this.NPOIN3;
pos +=4;
// ~~ Read the y-coordinates of the nodes ~~~~~~~~~~~~~~~~~~
pos +=4;
this.MESHY = new Float32Array(bufferpack.unpack(endian+this.NPOIN3+ftype,uint8array,pos));
pos +=fsize*this.NPOIN3;
pos +=4;
return pos;
}
getTimeHistorySLF(pos){
let uint8array = this.uint8array;
let endian = this.file.endian;
let [ftype,fsize] = this.file.float;
let ATs = [], ATt = [];
while (true){
try{
ATt.push(pos);
// ~~ Read AT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pos +=4;
ATs.push(bufferpack.unpack(endian+ftype,uint8array,pos)[0]);
pos +=fsize;
pos +=4;
// ~~ Skip Values ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pos+=this.NVAR*(4+fsize*this.NPOIN3+4);
}
catch(error){
ATt.pop(ATt.length-1); // since the last record failed the try
break;
}
}
this.NFRAME = ATs.length;
return { 'cores':ATt,'times':new Float32Array(ATs)};
}
writeHeaderSLF(){
let endian = this.file.endian;
let [ftype,fsize] = this.file.float;
let buffer = new Buffer(0);
// ~~ Write title ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
buffer = Buffer.concat([buffer,bufferpack.pack(endian+'i80si',[80,this.TITLE,80])]);
// ~~ Write NBV(1) and NBV(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'iiii',[4+4,this.NBV1,this.NBV2,4+4])]);
// ~~ Write variable names and units ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for(let i=0;i<this.NBV1;i++){
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i16s16si',[32,this.VARNAMES[i],this.VARUNITS[i],32])]);
}
for(let i=0;i<this.NBV2;i++){
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i16s16si',[32,this.CLDNAMES[i],this.CLDUNITS[i],32])]);
}
// ~~ Write IPARAM array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[4*10])]);
for(let i=0;i<this.IPARAM.length;i++){
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[this.IPARAM[i]])]);
}
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[4*10])]);
// ~~ Write DATE/TIME array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (this.IPARAM[9] == 1){
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[4*6])]);
for(let i=0;i<6;i++){
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[this.DATETIME[i]])]);
}
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[4*6])]);
}
// ~~ Write NELEM3, NPOIN3, NDP3, NPLAN ~~~~~~~~~~~~~~~~~~~~~~~~~~~
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'6i',[4*4,this.NELEM3,this.NPOIN3,this.NDP3,1,4*4])]); // /!\ TODO is NPLAN ?
// ~~ Write the IKLE array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[4*this.NELEM3*this.NDP3])]);
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'{0}i'.format(this.NELEM3*this.NDP3),this.IKLE3F.add(1))]); // TODO change IKLEF to IKLE ; index to id;
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[4*this.NELEM3*this.NDP3])]);
// ~~ Write the IPOBO array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[4*this.NPOIN3])]);
buffer=Buffer.concat([buffer,bufferpack.pack(endian+(this.NPOIN3+'i'),this.IPOB3)]);
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[4*this.NPOIN3])]);
// ~~ Write the x-coordinates of the nodes ~~~~~~~~~~~~~~~~~~~~~~~
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[fsize*this.NPOIN3])]);
//f.write(pack(endian+str(self.NPOIN3)+ftype,*(np.tile(self.MESHX,self.NPLAN))))
for(let i=0;i<this.NPLAN;i++){
buffer=Buffer.concat([buffer,bufferpack.pack(endian+(this.NPOIN2+ftype),this.MESHX)]);
}
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[fsize*this.NPOIN3])]);
// ~~ Write the y-coordinates of the nodes ~~~~~~~~~~~~~~~~~~~~~~~
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[fsize*this.NPOIN3])]);
//f.write(pack(endian+str(self.NPOIN3)+ftype,*(np.tile(self.MESHX,self.NPLAN))))
for(let i=0;i<this.NPLAN;i++){
buffer=Buffer.concat([buffer,bufferpack.pack(endian+(this.NPOIN2+ftype),this.MESHY)]);
}
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[fsize*this.NPOIN3])]);
return buffer;
}
writeCoreTimeSLF(buffer,t){
let endian = this.file.endian;
let [ftype,fsize] = this.file.float;
// Print time record
const _t = (this.tags['times'].length==0 || !this.tags['times'][t])?t:this.tags['times'][t];
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i'+ftype+'i',[fsize,_t,fsize])]);
return buffer;
}
writeCoreVarSLF(buffer,t){
let endian = this.file.endian;
let [ftype,fsize] = this.file.float;
// Print variable records
for(let i=0;i<this.NVAR;i++){
const frame = this.getFrame(t,i);
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[fsize*this.NPOIN3])]);
buffer=Buffer.concat([buffer,bufferpack.pack(endian+(this.NPOIN3+ftype),frame)]);
buffer=Buffer.concat([buffer,bufferpack.pack(endian+'i',[fsize*this.NPOIN3])]);
}
return buffer;
}
getBuffer(){
let buffer=this.writeHeaderSLF();
for(let i=0;i<this.NFRAME;i++){
buffer=this.writeCoreTimeSLF(buffer,i);
buffer=this.writeCoreVarSLF(buffer,i);
}
return buffer;
}
getFrames(){
let uint8array = this.uint8array;
let endian = this.file.endian;
let [ftype,fsize] = this.file.float;
let frames = this.FRAMES = new Float32Array(this.NFRAME * this.NVAR * this.NPOIN3);
for(let t=0;t<this.NFRAME;t++){
let pos=this.tags['cores'][t];
pos +=4+fsize+4;
for(let ivar=0;ivar<this.NVAR;ivar++){
pos +=4;
frames.set(bufferpack.unpack(endian+(this.NPOIN3)+ftype,uint8array,pos),(t * this.NVAR * this.NPOIN3)+ivar*this.NPOIN3);
pos +=fsize*this.NPOIN3;
pos +=4;
}
}
}
getFrame(t,v){
if(!this.FRAMES){
console.warn("this.FRAMES is null. Add keepframes=true in options");
return null;
}
t = (typeof t !== 'undefined') ? t : 0;
v = (typeof v !== 'undefined') ? v : 0;
if (!(t >= 0 && t < this.NFRAME)) throw Error("Check frame({0}) id={1} ".format(this.NFRAME,t));
if (!(v >= 0 && v < this.NVAR)) throw Error("Check variable id");
return this.FRAMES.subarray((t * this.NVAR * this.NPOIN3)+(v * this.NPOIN3),(t * this.NVAR * this.NPOIN3)+(v * this.NPOIN3)+this.NPOIN3);
}
getMinMax(){
let minmax = new Float32Array(this.NVAR * 2);
for(let ivar=0;ivar<this.NVAR;ivar++){
let max = Number.MIN_VALUE;
let min = Number.MAX_VALUE;
for(let i=0;i<this.NFRAME;i++){
const values = this.getFrame(i);
min = Math.min(min,values.min());
max = Math.max(max,values.max());
}
minmax[ivar*2] = min;
minmax[ivar*2+1] = max;
}
return minmax;
}
getVarMinMax(ivar){
return this.minmax.subarray(ivar*2,ivar*2+1);
}
getElements(indices){
if(!indices)return this.IKLE3F;
if(!Number.isInteger(indices) && !Array.isArray(indices))return this.IKLE3F;
indices = (Number.isInteger(indices)) ? [indices]:indices;
// ~~> get element
if (this.debug) console.time('Get elements');
let elements = new Uint32Array(indices.length*this.NDP3);
for(let i=0,j=0,n=indices.length;i<n;i++,j+=3){
elements[j+0] = this.IKLE3F[indices[i]];
elements[j+1] = this.IKLE3F[indices[i]+1];
elements[j+2] = this.IKLE3F[indices[i]+2];
}
if (this.debug) console.timeEnd('Get elements');
return elements;
}
getElementsW(indices){
if(!indices)return this.IKLE3F;
if(!Number.isInteger(indices) && !Array.isArray(indices))return this.IKLE3F;
indices = (Number.isInteger(indices)) ? [indices]:indices;
// ~~> get element
if (this.debug) console.time('Get elementsW');
let elements = new Uint32Array(indices.length*this.NDP3*2);
for(let i=0,j=0,k=0,n=indices.length;i<n;i++,j+=6,k+3){
elements[j+0] = this.IKLE3F[indices[i]];
elements[j+1] = this.IKLE3F[indices[i]+1];
elements[j+2] = this.IKLE3F[indices[i]+1];
elements[j+3] = this.IKLE3F[indices[i]+2];
elements[j+4] = this.IKLE3F[indices[i]+2];
elements[j+5] = this.IKLE3F[indices[i]];
}
if (this.debug) console.timeEnd('Get elementsW');
return elements;
}
reshapeIKLE(){
let newIKLE = new Uint32Array(this.NELEM3*this.NDP3);
for(let i=0,j=0;i<this.NELEM3;i++,j+=3){
newIKLE[i] = this.IKLE3[j];
newIKLE[i+this.NELEM3] = this.IKLE3[j+1];
newIKLE[i+2*this.NELEM3] = this.IKLE3[j+2];
}
return newIKLE;
}
changeProj(from,to){
this.fromProj = from;
this.toProj = to;
if(from !== to){
this.initializeProperties();
this.transform();
}
}
transform(){
const fromProj = this.fromProj;
const toProj = this.toProj;
if(fromProj !== toProj){
const transform = proj(fromProj,toProj);
let coord;
for(let i=0;i<this.NPOIN3;i++){
coord=transform.forward([this.MESHX[i],this.MESHY[i]]);
this.MESHX[i] = coord[0];
this.MESHY[i] = coord[1];
}
this.fromProj = toProj;
}
}
get TRIXY(){
if (!(this._TRIXY)) this.getTriXY();
return this._TRIXY;
}
get varnames(){
return this.VARNAMES.map(name=>name.replace(/\s/g, '').toLowerCase());
}
getVarIndex(id){return this.varnames.findIndex(name=>name==id);}
get XY(){
if (!(this._XY)) this.getXY();
return this._XY;
}
get IKLEW(){
if (!(this._IKLEW)) this.getIKLEW();
return this._IKLEW;
}
get EDGES(){
if (!(this._EDGES)) this.getEDGES();
return this._EDGES;
}
get BEDGES(){
if (!(this._BEDGES)) this.getBEDGES();
return this._BEDGES;
}
get IEDGES(){
if (!(this._IEDGES)) this.getIEDGES();
return this._IEDGES;
}
get CX(){
if(!(this._CX)) this.getTriAttributes();
return this._CX;
}
get CY(){
if (!(this._CY)) this.getTriAttributes();
return this._CY;
}
get TRIAREA(){
if (!(this._TRIAREA)) this.getTriAttributes();
return this._TRIAREA;
}
get TRIBBOX(){
if (!(this._TRIBBOX)) this.getTriAttributes();
return this._TRIBBOX;
}
get BBOX(){return this.EXTENT;}
get EXTENT(){
if (!(this._EXTENT))this.getExtent();
return this._EXTENT;
}
get POLYGON(){
if (!(this._POLYGON))this.getPolygon();
return this._POLYGON;
}
get EXTERIOR(){
if (!(this._EXTERIOR))this.getExtInt();
return this._EXTERIOR;
}
get INTERIORS(){
if (!(this._INTERIORS))this.getExtInt();
return this._INTERIORS;
}
get POLYGONS(){
if (!(this._POLYGONS))this.getPolygons();
return this._POLYGONS;
}
getExtent(){
if (this.debug) console.time('Get extent');
this._EXTENT=new Float32Array([this.MESHX.min(),this.MESHY.min(),this.MESHX.max(),this.MESHY.max()]);
if (this.debug) console.timeEnd('Get extent');
}
getExtInt(){
if (this.debug) console.time('Get exterior/interiors');
const polygons = this.POLYGONS;
const areas = polygons.map(pol=>area(pol));
const interiors = this._INTERIORS = areas.sortIndices(true).map(i=>polygons[i]);
this._EXTERIOR= interiors.shift();
if (this.debug) console.timeEnd('Get exterior/interiors');
}
getCoordinate(i){return [this.MESHX[i],this.MESHY[i]];}
getPolygon(){
if (this.debug) console.time('Get polygon');
if(this.INTERIORS.length==0){this._POLYGON =this.EXTERIOR;}
else{this._POLYGON = mask(featureCollection(this.INTERIORS),this.EXTERIOR);}
if (this.debug) console.timeEnd('Get polygon');
}
getPolygons(){
// ~~> get outlines (boundary edges)/polygons
if (this.debug) console.time('Get polygons');
const bedges=this.BEDGES;
const pols =this._POLYGONS= [];
let index,start,end=-1,pol=[];
while(bedges.length>0){
index=bedges.findIndex(item=>item.start==end || item.end==end);
if(index==-1){
if(pol.length>0){pols.push(turf_polygon([pol]));pol=[];}
start=bedges[0].start;
end=bedges[0].end;
pol.push(this.getCoordinate(start));
pol.push(this.getCoordinate(end));
bedges.splice(0,1);
} else {
end=(bedges[index].start==end)?bedges[index].end:bedges[index].start;
pol.push(this.getCoordinate(end));
bedges.splice(index,1);
if(bedges.length==0 && pol.length>0)pols.push(turf_polygon([pol]));
}
}
if (this.debug) console.timeEnd('Get polygons');
}
getIKLEW(){
if (this.debug) console.time('Get connectivity for wireframe');
let IKLEW = this._IKLEW = new Uint32Array(this.NELEM3*this.NDP3*2);
for(let i=0,j=0,k=0;i<this.NELEM3;i++,j+=6,k+=3){
IKLEW[j] = this.IKLE3F[k];
IKLEW[j+1] = this.IKLE3F[k+1];
IKLEW[j+2] = this.IKLE3F[k+1];
IKLEW[j+3] = this.IKLE3F[k+2];
IKLEW[j+4] = this.IKLE3F[k+2];
IKLEW[j+5] = this.IKLE3F[k];
}
if (this.debug) console.timeEnd('Get connectivity for wireframe');
}
getTriXY(){
// ~~> get element xy
if (this.debug) console.time('Get element xy');
let exy = this._TRIXY = new Float32Array(this.NELEM3*this.NDP3*3);
let n1,n2,n3;
for(let i=0,j=0,n=this.NELEM3;i<n;i++,j+=9){
n1 = this.IKLE3[i];
n2 = this.IKLE3[i+this.NELEM3];
n3 = this.IKLE3[i+2*this.NELEM3];
exy[j] = this.MESHX[n1];
exy[j+1] = this.MESHY[n1];
// z = 0.
exy[j+3] = this.MESHX[n2];
exy[j+4] = this.MESHY[n2];
// z = 0.
exy[j+6] = this.MESHX[n3];
exy[j+7] = this.MESHY[n3];
// z = 0.
}
if (this.debug) console.timeEnd('Get element xy');
}
getXY(){
// ~~> get points (x,y)
if (this.debug) console.time('Get points xy');
let xy = this._XY = new Float32Array(this.NPOIN3*3);
for(let i=0,j=0,n=this.NPOIN3;i<n;i++,j+=3){
xy[j] = this.MESHX[i];
xy[j+1] = this.MESHY[i];
// xy[j+2] = this.MESHZ[i];
}
if (this.debug) console.timeEnd('Get points xy');
}
getBEDGES(){
// ~~> get exterior edges
if (this.debug) console.time('Get boundary edges');
const edges = this.EDGES;
this._BEDGES = Object.keys(edges).filter(key=>!edges[key].boundary).map(key=>edges[key]);
if (this.debug) console.timeEnd('Get boundary edges');
}
getIEDGES(){
// ~~> get interior edges
if (this.debug) console.time('Get interior edges');
const edges = this.EDGES;
this._IEDGES = Object.keys(edges).filter(key=>edges[key].boundary).map(key=>edges[key]);
if (this.debug) console.timeEnd('Get interior edges');
}
getEDGES(){
// ~~> get edges
if (this.debug) console.time('Get edges');
const edges = this._EDGES = {};
let n1,n2,n3,_n1,_n2,_n3;
for (let e = 0; e < this.NELEM3; e++ )
{
n1 = this.IKLE3[e];
n2 = this.IKLE3[e+this.NELEM3];
n3 = this.IKLE3[e+2*this.NELEM3];
_n1 = '{0}-{1}'.format(Math.min(n1,n2),Math.max(n1,n2));
_n2 = '{0}-{1}'.format(Math.min(n2,n3),Math.max(n2,n3));
_n3 = '{0}-{1}'.format(Math.min(n3,n1),Math.max(n3,n1));
(typeof edges[_n1]!=='undefined')?edges[_n1].boundary=true:edges[_n1]={boundary:false,start:Math.min(n1,n2),end:Math.max(n1,n2)};
(typeof edges[_n2]!=='undefined')?edges[_n2].boundary=true:edges[_n2]={boundary:false,start:Math.min(n2,n3),end:Math.max(n2,n3)};
(typeof edges[_n3]!=='undefined')?edges[_n3].boundary=true:edges[_n3]={boundary:false,start:Math.min(n3,n1),end:Math.max(n3,n1)};
}
if (this.debug) console.timeEnd('Get edges');
}
getTriAttributes(){
if (this.debug) console.time('Get element attributes');
// Centroid is computed using mean of X and Y
// Area is computed using cross-product
let CX = this._CX = new Float32Array(this.NELEM3);
let CY = this._CY = new Float32Array(this.NELEM3);
let area = this._TRIAREA = new Float32Array(this.NELEM3);
let bbox = this._TRIBBOX = new Array(this.NELEM3);
let n1,n2,n3;
for(let i=0,n=this.NELEM3;i<n;i++){
n1 = this.IKLE3[i];
n2 = this.IKLE3[i+this.NELEM3];
n3 = this.IKLE3[i+2*this.NELEM3];
CX[i] = (this.MESHX[n1] + this.MESHX[n2] + this.MESHX[n3]) / 3.0;
CY[i] = (this.MESHY[n1] + this.MESHY[n2] + this.MESHY[n3]) / 3.0;
bbox[i] = {
minX:Math.min(this.MESHX[n1],Math.min(this.MESHX[n2],this.MESHX[n3])),
minY:Math.min(this.MESHY[n1],Math.min(this.MESHY[n2],this.MESHY[n3])),
maxX:Math.max(this.MESHX[n1],Math.max(this.MESHX[n2],this.MESHX[n3])),
maxY:Math.max(this.MESHY[n1],Math.max(this.MESHY[n2],this.MESHY[n3])),
index:i
};
// TODO : Assume cartesian coordinate system.
// If using lat/long, areas might be misleading for large elements (several kilometers).
// I'm not sure if there's an easy solution. I've seen ajustment for different latitudes (mourne wind map)
// area[i] = Math.abs(0.5 * ((this.MESHX[n2] - this.MESHX[n1]) * (this.MESHY[n3] - this.MESHY[n1]) -
// (this.MESHX[n3] - this.MESHX[n1]) * (this.MESHY[n2] - this.MESHY[n1])
// ));
// https://github.com/Turfjs/turf/tree/master/packages/turf-area
const points = [
[this.MESHX[n1],this.MESHY[n1]],
[this.MESHX[n2],this.MESHY[n2]],
[this.MESHX[n3],this.MESHY[n3]]
];
let total = 0.0;
total += (rad(points[2][0]) - rad(points[0][0])) * Math.sin(rad(points[1][1]));
total += (rad(points[1][0]) - rad(points[2][0])) * Math.sin(rad(points[0][1]));
total += (rad(points[0][0]) - rad(points[1][0])) * Math.sin(rad(points[2][1]));
area[i] = total * RADIUS * RADIUS * 0.5;
}
if (this.debug) console.timeEnd('Get element attributes');
}
//{STRING} title
addTITLE(title){
this.TITLE = '{0}'.format(title.rpad(" ", 80));
}
//{OBJECT (name:str,unit:str)}
addVAR(obj){
if(!obj)obj={};
const name = obj.name || 'NewVariable';
const unit = obj.unit || 'NewUnit';
this.NBV1 += 1;
this.NVAR = this.NBV1 + this.NBV2;
this.VARINDEX = range(this.NVAR);
this.VARNAMES.push('{0}'.format(name.rpad(" ", 16)));
this.VARUNITS.push('{0}'.format(unit.rpad(" ", 16)));
}
addPOINTS(x,y){
if(!x) throw new Error("Requires points");
this.IPOB3 = new Uint32Array(x.length).range();
this.IPOB2 = this.IPOB3;
this.IPARAM = new Uint8Array(10);
this.IPARAM[0] = 1;
this.NPOIN2 = x.length;
this.NPOIN3 =this.NPOIN2;
(y)?this._addXY(x,y):this._addPoints(x);
}
_addXY(x,y){
this.MESHX=x;
this.MESHY=y;
}
_addPoints(points){
this.MESHX = new Float32Array(this.NPOIN3);
this.MESHY = new Float32Array(this.NPOIN3);
for(let i=0;i<this.NPOIN3;i++){
this.MESHX[i]=points[i].x;
this.MESHY[i]=points[i].y;
}
}
//Uint32Array(NELEM3*NDP3)
addIKLE(ikle){
this.NDP2 = 3;
this.NDP3 = 3;
this.NELEM3 = ikle.length / this.NDP3;
this.NELEM2 = this.NELEM3;
this.IKLE2 = ikle;
this.IKLE3 = ikle;
this.IKLE3F = this.IKLE3;
this.IKLE3 = this.reshapeIKLE();
}
addFrame(array){
if(array.length !=this.NVAR * this.NPOIN3)throw new Error("Wrong array size");
this.NFRAME +=1;
if(!this.FRAMES)return this.FRAMES=array;
const oldFrames = this.FRAMES;
this.FRAMES = new Float32Array(this.NFRAME * this.NVAR * this.NPOIN3);
this.FRAMES.set(oldFrames,0);
this.FRAMES.set(array,(this.NFRAME-1) * this.NVAR * this.NPOIN3);
}
// {STRING} title
// {OBJECT (name:str,unit:str)} var
// {2D Array}
// {2D Array(NELEM,3}
addMesh(title,variable,points,ikle){
this.empty = false;
this.addTITLE(title);
this.addVAR(variable);
this.addPOINTS(points);
this.addIKLE(ikle);
}
// {String}
// writeSLF(self,output){
// // this.appendHeaderSLF()
// // // ~~> Time stepping
// // self.tags['times']=np.arange(self.values.shape[0])
// // for t in range(self.NFRAME):
// // self.appendCoreTimeSLF(t)
// // self.appendCoreVarsSLF(self.values[t])
// // self.fole['hook'].close()
// }
printAttributes(){
const attr = {
'NFRAME':this.NFRAME,
'NVAR':this.NVAR,
'NPOIN3':this.NPOIN3,
'NELEM3':this.NELEM3,
'EXTENT':this.EXTENT,
};
console.log(attr);
}
} |
JavaScript | class ReprojImage extends ImageBase {
/**
* @param {import("../proj/Projection.js").default} sourceProj Source projection (of the data).
* @param {import("../proj/Projection.js").default} targetProj Target projection.
* @param {import("../extent.js").Extent} targetExtent Target extent.
* @param {number} targetResolution Target resolution.
* @param {number} pixelRatio Pixel ratio.
* @param {FunctionType} getImageFunction
* Function returning source images (extent, resolution, pixelRatio).
* @param {object=} opt_contextOptions Properties to set on the canvas context.
*/
constructor(
sourceProj,
targetProj,
targetExtent,
targetResolution,
pixelRatio,
getImageFunction,
opt_contextOptions
) {
const maxSourceExtent = sourceProj.getExtent();
const maxTargetExtent = targetProj.getExtent();
const limitedTargetExtent = maxTargetExtent
? getIntersection(targetExtent, maxTargetExtent)
: targetExtent;
const targetCenter = getCenter(limitedTargetExtent);
const sourceResolution = calculateSourceResolution(
sourceProj,
targetProj,
targetCenter,
targetResolution
);
const errorThresholdInPixels = ERROR_THRESHOLD;
const triangulation = new Triangulation(
sourceProj,
targetProj,
limitedTargetExtent,
maxSourceExtent,
sourceResolution * errorThresholdInPixels,
targetResolution
);
const sourceExtent = triangulation.calculateSourceExtent();
const sourceImage = getImageFunction(
sourceExtent,
sourceResolution,
pixelRatio
);
const state = sourceImage ? ImageState.IDLE : ImageState.EMPTY;
const sourcePixelRatio = sourceImage ? sourceImage.getPixelRatio() : 1;
super(targetExtent, targetResolution, sourcePixelRatio, state);
/**
* @private
* @type {import("../proj/Projection.js").default}
*/
this.targetProj_ = targetProj;
/**
* @private
* @type {import("../extent.js").Extent}
*/
this.maxSourceExtent_ = maxSourceExtent;
/**
* @private
* @type {!import("./Triangulation.js").default}
*/
this.triangulation_ = triangulation;
/**
* @private
* @type {number}
*/
this.targetResolution_ = targetResolution;
/**
* @private
* @type {import("../extent.js").Extent}
*/
this.targetExtent_ = targetExtent;
/**
* @private
* @type {import("../ImageBase.js").default}
*/
this.sourceImage_ = sourceImage;
/**
* @private
* @type {number}
*/
this.sourcePixelRatio_ = sourcePixelRatio;
/**
* @private
* @type {object}
*/
this.contextOptions_ = opt_contextOptions;
/**
* @private
* @type {HTMLCanvasElement}
*/
this.canvas_ = null;
/**
* @private
* @type {?import("../events.js").EventsKey}
*/
this.sourceListenerKey_ = null;
}
/**
* Clean up.
*/
disposeInternal() {
if (this.state == ImageState.LOADING) {
this.unlistenSource_();
}
super.disposeInternal();
}
/**
* @return {HTMLCanvasElement} Image.
*/
getImage() {
return this.canvas_;
}
/**
* @return {import("../proj/Projection.js").default} Projection.
*/
getProjection() {
return this.targetProj_;
}
/**
* @private
*/
reproject_() {
const sourceState = this.sourceImage_.getState();
if (sourceState == ImageState.LOADED) {
const width = getWidth(this.targetExtent_) / this.targetResolution_;
const height = getHeight(this.targetExtent_) / this.targetResolution_;
this.canvas_ = renderReprojected(
width,
height,
this.sourcePixelRatio_,
this.sourceImage_.getResolution(),
this.maxSourceExtent_,
this.targetResolution_,
this.targetExtent_,
this.triangulation_,
[
{
extent: this.sourceImage_.getExtent(),
image: this.sourceImage_.getImage(),
},
],
0,
undefined,
this.contextOptions_
);
}
this.state = sourceState;
this.changed();
}
/**
* Load not yet loaded URI.
*/
load() {
if (this.state == ImageState.IDLE) {
this.state = ImageState.LOADING;
this.changed();
const sourceState = this.sourceImage_.getState();
if (sourceState == ImageState.LOADED || sourceState == ImageState.ERROR) {
this.reproject_();
} else {
this.sourceListenerKey_ = listen(
this.sourceImage_,
EventType.CHANGE,
function (e) {
const sourceState = this.sourceImage_.getState();
if (
sourceState == ImageState.LOADED ||
sourceState == ImageState.ERROR
) {
this.unlistenSource_();
this.reproject_();
}
},
this
);
this.sourceImage_.load();
}
}
}
/**
* @private
*/
unlistenSource_() {
unlistenByKey(
/** @type {!import("../events.js").EventsKey} */ (this.sourceListenerKey_)
);
this.sourceListenerKey_ = null;
}
} |
JavaScript | class ParticleBuffer
{
/**
* @private
* @param {object} properties - The properties to upload.
* @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic.
* @param {number} size - The size of the batch.
*/
constructor(properties, dynamicPropertyFlags, size)
{
this.geometry = new Geometry();
this.indexBuffer = null;
/**
* The number of particles the buffer can hold
*
* @private
* @member {number}
*/
this.size = size;
/**
* A list of the properties that are dynamic.
*
* @private
* @member {object[]}
*/
this.dynamicProperties = [];
/**
* A list of the properties that are static.
*
* @private
* @member {object[]}
*/
this.staticProperties = [];
for (let i = 0; i < properties.length; ++i)
{
let property = properties[i];
// Make copy of properties object so that when we edit the offset it doesn't
// change all other instances of the object literal
property = {
attributeName: property.attributeName,
size: property.size,
uploadFunction: property.uploadFunction,
type: property.type || TYPES.FLOAT,
offset: property.offset,
};
if (dynamicPropertyFlags[i])
{
this.dynamicProperties.push(property);
}
else
{
this.staticProperties.push(property);
}
}
this.staticStride = 0;
this.staticBuffer = null;
this.staticData = null;
this.staticDataUint32 = null;
this.dynamicStride = 0;
this.dynamicBuffer = null;
this.dynamicData = null;
this.dynamicDataUint32 = null;
this._updateID = 0;
this.initBuffers();
}
/**
* Sets up the renderer context and necessary buffers.
*
* @private
*/
initBuffers()
{
const geometry = this.geometry;
let dynamicOffset = 0;
/**
* Holds the indices of the geometry (quads) to draw
*
* @member {Uint16Array}
* @private
*/
this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true);
geometry.addIndex(this.indexBuffer);
this.dynamicStride = 0;
for (let i = 0; i < this.dynamicProperties.length; ++i)
{
const property = this.dynamicProperties[i];
property.offset = dynamicOffset;
dynamicOffset += property.size;
this.dynamicStride += property.size;
}
const dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4);
this.dynamicData = new Float32Array(dynBuffer);
this.dynamicDataUint32 = new Uint32Array(dynBuffer);
this.dynamicBuffer = new Buffer(this.dynamicData, false, false);
// static //
let staticOffset = 0;
this.staticStride = 0;
for (let i = 0; i < this.staticProperties.length; ++i)
{
const property = this.staticProperties[i];
property.offset = staticOffset;
staticOffset += property.size;
this.staticStride += property.size;
}
const statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4);
this.staticData = new Float32Array(statBuffer);
this.staticDataUint32 = new Uint32Array(statBuffer);
this.staticBuffer = new Buffer(this.staticData, true, false);
for (let i = 0; i < this.dynamicProperties.length; ++i)
{
const property = this.dynamicProperties[i];
geometry.addAttribute(
property.attributeName,
this.dynamicBuffer,
0,
property.type === TYPES.UNSIGNED_BYTE,
property.type,
this.dynamicStride * 4,
property.offset * 4
);
}
for (let i = 0; i < this.staticProperties.length; ++i)
{
const property = this.staticProperties[i];
geometry.addAttribute(
property.attributeName,
this.staticBuffer,
0,
property.type === TYPES.UNSIGNED_BYTE,
property.type,
this.staticStride * 4,
property.offset * 4
);
}
}
/**
* Uploads the dynamic properties.
*
* @private
* @param {PIXI.DisplayObject[]} children - The children to upload.
* @param {number} startIndex - The index to start at.
* @param {number} amount - The number to upload.
*/
uploadDynamic(children, startIndex, amount)
{
for (let i = 0; i < this.dynamicProperties.length; i++)
{
const property = this.dynamicProperties[i];
property.uploadFunction(children, startIndex, amount,
property.type === TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData,
this.dynamicStride, property.offset);
}
this.dynamicBuffer._updateID++;
}
/**
* Uploads the static properties.
*
* @private
* @param {PIXI.DisplayObject[]} children - The children to upload.
* @param {number} startIndex - The index to start at.
* @param {number} amount - The number to upload.
*/
uploadStatic(children, startIndex, amount)
{
for (let i = 0; i < this.staticProperties.length; i++)
{
const property = this.staticProperties[i];
property.uploadFunction(children, startIndex, amount,
property.type === TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData,
this.staticStride, property.offset);
}
this.staticBuffer._updateID++;
}
/**
* Destroys the ParticleBuffer.
*
* @private
*/
destroy()
{
this.indexBuffer = null;
this.dynamicProperties = null;
// this.dynamicBuffer.destroy();
this.dynamicBuffer = null;
this.dynamicData = null;
this.dynamicDataUint32 = null;
this.staticProperties = null;
// this.staticBuffer.destroy();
this.staticBuffer = null;
this.staticData = null;
this.staticDataUint32 = null;
// all buffers are destroyed inside geometry
this.geometry.destroy();
}
} |
JavaScript | class LdpcDecoder {
/**
* Constructor
* @param {object} code the current LDPC code for rate and length
*/
constructor(code) {
this.code = code;
this.createTanner();
this.maxIter = 100;
}
static calcVariance(samples) {
const n = samples.length;
let m = 0;
let s = 0;
for (let k = 0; k < n; ) {
const x = samples[k++];
const oldM = m;
m += (x - m) / k;
s += (x - m) * (x - oldM);
}
return s / (n - 1);
}
/**
* Check is the codeword passes check.
* @param {array} codeword the word to check
* @return {boolean} true if passes
*/
check(codeword) {
const code = this.code;
const checkVal = multiplySparse(code.H, codeword);
for (let i = 0, len = this.code.messageBits; i < len; i++) {
if (checkVal[i]) {
return false;
}
}
return true;
}
/**
* Check is the codeword passes check. Fails early
* for speed.
* @param {array} codeword the word to check
* @return {boolean} true if passes
*/
checkFast(codeword) {
const H = this.code.H;
for (let i = 0, hlen = H.length; i < hlen; i++) {
const row = H[i];
let sum = 0;
for (let j = 0, rlen = row.length; j < rlen; j++) {
const idx = row[j];
sum ^= codeword[idx];
}
if (sum) {
return false;
}
}
return true;
}
/**
* Set up the variable and check nodes,
* make the links between them.
*/
createTanner() {
const code = this.code;
const M = code.M;
const N = code.N;
const variableNodes = [];
for (let i = 0; i < N; i++) {
variableNodes[i] = {
clinks: [],
c: 0
};
}
const checkNodes = [];
const H = code.H;
for (let i = 0; i < M; i++) {
const row = H[i];
const vlinks = row.map(idx => ({
v: variableNodes[idx],
r: 0
}));
const cnode = {
vlinks
};
checkNodes[i] = cnode;
for (let v = 0, len = vlinks.length; v < len; v++) {
const vnode = vlinks[v].v;
const clink = {
c: cnode,
q: 0
};
vnode.clinks.push(clink);
}
}
this.checkNodes = checkNodes;
this.variableNodes = variableNodes;
}
/**
* Create an empty
*/
createTanner() {
const code = this.code;
const M = code.M;
const N = code.N;
const H = code.H;
const checkNodes = [];
const variableNodes = [];
/**
* First make two blank tables
*/
for (let i = 0; i < M; i++) {
checkNodes[i] = {
links: []
};
}
for (let i = 0; i < N; i++) {
variableNodes[i] = {
links: [],
ci: 0
};
}
/**
* Then interconnect then with link records,
* using the sparse array information from H
*/
for (let i = 0 ; i < M; i++) {
const row = H[i];
const cnode = checkNodes[i];
const rlen = row.length;
for (let j = 0; j < rlen; j++) {
const idx = row[j];
const vnode = variableNodes[idx];
const link = {
c: cnode,
v: vnode,
q: 0,
r: 0,
};
cnode.links.push(link);
vnode.links.push(link);
}
}
/**
* Attach to this instance
*/
this.checkNodes = checkNodes;
this.variableNodes = variableNodes;
}
/**
* Decode codeword bits to message bits
* @param {array} inBits message array of data from -1 -> 1
* @return decoded array of real -1's and 1's
*/
decode(inBits) {
const result = this.decodeSP(inBits);
return result;
}
/**
* Decode codeword bits to message bits
* @param {array} message array of data from -1 -> 1
* @return decoded array of message array of data from -1 -> 1
*/
/* eslint-disable max-lines-per-function */
decodeSP(inBits) {
// localize some values
const M = this.code.M;
const N = this.code.N;
const checkNodes = this.checkNodes;
const variableNodes = this.variableNodes;
/**
* Step 1. Initialization of c(ij) and q(ij)
*/
//const variance = LdpcDecoder.calcVariance(inBits);
//const weight = 2 / variance;
const weight = 1.0;
for (let i = 0; i < N; i++) {
const vnode = variableNodes[i];
const Lci = inBits[i] * weight;
vnode.ci = Lci;
const links = vnode.links;
for (let j = 0, llen = links.length; j < llen ; j++) {
const link = links[j];
link.r = 0;
link.q = Lci;
}
}
for (let iter = 0; iter < this.maxIter; iter++) {
/**
* Step 2. update r(ji)
*/
for (let m = 0; m < M; m++) {
const checkNode = checkNodes[m];
const links = checkNode.links;
for (let i = 0, llen = links.length; i < llen ; i++) {
const rlink = links[i];
/**
* Product for links != v
*/
let prod = 1;
for (let v = 0; v < llen; v++) {
if (v === i) {
continue;
}
const q = links[v].q;
const tanh = Math.tanh(0.5 * q);
prod *= tanh;
}
const all = prod;
const atanh = Math.log( (1 + all) / (1 - all) );
rlink.r = atanh;
}
}
/**
* Step 3. Update qij
*/
for (let i = 0; i < N; i++) {
const vnode = variableNodes[i];
const links = vnode.links;
for (let k = 0, llen = links.length; k < llen; k++) {
const link = links[k];
let sum = 0;
for (let c = 0; c < llen; c++) {
if (c !== k) {
sum += links[c].r;
}
}
link.q = vnode.ci + sum;
}
}
/**
* Step 4. Check syndrome
*/
const c = [];
for (let i = 0; i < N ; i++) {
const vnode = variableNodes[i];
const links = vnode.links;
let sum = 0;
for (let v = 0, llen = links.length ; v < llen ; v++) {
const link = links[v];
sum += link.r;
}
const LQi = vnode.ci + sum;
c[i] = LQi < 0 ? 1 : 0;
}
if (this.checkFast(c)) {
return c.slice(0, this.code.messageBits);
}
} // for iter
return null;
}
/**
* Decode codeword bits to message bits
* @param {array} message array of data from -1 -> 1
* @return decoded array of message array of data from -1 -> 1
*/
/* eslint-disable max-lines-per-function */
decodeMS(inBits) {
// localize some values
const M = this.code.M;
const N = this.code.N;
const checkNodes = this.checkNodes;
const variableNodes = this.variableNodes;
/**
* Step 1. Initialization of c(ij) and q(ij)
*/
//const variance = LdpcDecoder.calcVariance(inBits);
//const weight = 2 / variance;
const weight = 1;
for (let i = 0; i < N; i++) {
const vnode = variableNodes[i];
const Lci = inBits[i] * weight;
vnode.ci = Lci;
const links = vnode.links;
for (let j = 0, llen = links.length; j < llen ; j++) {
const link = links[j];
link.r = 0;
link.q = Lci;
}
}
for (let iter = 0; iter < this.maxIter; iter++) {
/**
* Step 2. update r(ji)
*/
for (let m = 0; m < M; m++) {
const checkNode = checkNodes[m];
const links = checkNode.links;
for (let i = 0, llen = links.length; i < llen ; i++) {
const rlink = links[i];
/**
* prod starts high, grows low
*/
let prod = 1000.0
for (let v = 0; v < llen; v++) {
if (v === i) {
continue;
}
const q = links[v].q;
const absProd = Math.abs(prod);
const absQ = Math.abs(q);
const sgnQ = q < 0 ? -1 : 1;
const sgnProd = prod < 0 ? -1 : 1;
const min = absQ < absProd ? absQ : absProd;
prod = sgnQ * sgnProd * min
}
rlink.r = prod;
}
}
/**
* Step 3. Update qij
*/
for (let i = 0; i < N; i++) {
const vnode = variableNodes[i];
const links = vnode.links;
for (let k = 0, llen = links.length; k < llen; k++) {
const link = links[k];
let sum = 0;
for (let c = 0; c < llen; c++) {
if (c !== k) {
sum += links[c].r;
}
}
link.q = vnode.ci + sum;
}
}
/**
* Step 4. Check syndrome
*/
const c = [];
for (let i = 0; i < N ; i++) {
const vnode = variableNodes[i];
const links = vnode.links;
let sum = 0;
for (let v = 0, llen = links.length ; v < llen ; v++) {
const link = links[v];
sum += link.r;
}
const LQi = vnode.ci + sum;
c[i] = LQi < 0 ? 1 : 0;
}
if (this.checkFast(c)) {
// console.log(`iter: ${iter}`)
return c.slice(0, this.code.messageBits);
}
} // for iter
return null;
}
decode(inbits) {
return this.decodeMS(inbits);
}
/* eslint-enable */
/**
* Decode codeword bits to message bytes
* @param {array} bits message array of 1's and 0's
* @return decoded array of bytes if decoding works, else null.
*/
decodeToBytes(bits) {
const outbits = this.decode(bits);
if (!outbits) {
return null;
}
const bytes = Util.bitsToBytesBE(outbits);
return bytes;
}
} |
JavaScript | class Point3 {
constructor(x = 0, y = 0, z = 0) {
/**
* The x value of the point.
* @name Point3#x
* @type number
*/
this.x = x;
/**
* The y value of the point.
* @name Point3#y
* @type number
*/
this.y = y;
/**
* The z value of the point.
* @name Point3#z
* @type number
*/
this.z = z;
}
/**
* Adds the coordinates of two points together to create a new point.
*
* @method Point3.add
* @param {Point3} a - The first Point3 object.
* @param {Point3} b - The second Point3 object.
* @param {Point3} [out] - Optional Point3 to store the value in, if not supplied a new Point3 object will be created.
* @returns {Point3} The new Point3 object.
*/
static add(a, b, out = new Point3()) {
out.x = a.x + b.x;
out.y = a.y + b.y;
out.z = a.z + b.z;
return out;
}
/**
* Subtracts the coordinates of two points to create a new point.
*
* @method Point3.subtract
* @param {Point3} a - The first Point3 object.
* @param {Point3} b - The second Point3 object.
* @param {Point3} [out] - Optional Point3 to store the value in, if not supplied a new Point3 object will be created.
* @returns {Point3} The new Point3 object.
*/
static subtract(a, b, out = new Point3()) {
out.x = a.x - b.x;
out.y = a.y - b.y;
out.z = a.z - b.z;
return out;
}
/**
* Multiplies the coordinates of two points to create a new point.
*
* @method Point3.multiply
* @param {Point3} a - The first Point3 object.
* @param {Point3} b - The second Point3 object.
* @param {Point3} [out] - Optional Point3 to store the value in, if not supplied a new Point3 object will be created.
* @returns {Point3} The new Point3 object.
*/
static multiply(a, b, out = new Point3()) {
out.x = a.x * b.x;
out.y = a.y * b.y;
out.z = a.z * b.z;
return out;
}
/**
* Divides the coordinates of two points to create a new point.
*
* @method Point3.divide
* @param {Point3} a - The first Point3 object.
* @param {Point3} b - The second Point3 object.
* @param {Point3} [out] - Optional Point3 to store the value in, if not supplied a new Point3 object3 will be created.
* @returns {Point3} The new Point3 object.
*/
static divide(a, b, out = new Point3()) {
out.x = a.x / b.x;
out.y = a.y / b.y;
out.z = a.z / b.z;
return out;
}
/**
* Determines whether the two given Point3 objects are equal. They are considered equal if they have the same x, y and z values.
*
* @method Point3.equals
* @param {Point3} a - The first Point3 object.
* @param {Point3} b - The second Point3 object.
* @returns {boolean} A value of true if the Points3 are equal, otherwise false.
*/
static equals(a, b) {
return a.x === b.x && a.y === b.y && a.z === b.z;
}
/**
* Copies the x, y and z properties from any given object to this Point3.
*
* @method Point3#copyFrom
* @param {Object} source - The object to copy from.
* @returns {Point3} This Point3 object.
*/
copyFrom(source) {
return this.setTo(source.x, source.y, source.z);
}
/**
* Determines whether the given object's x/y/z values are equal to this Point3 object.
*
* @method Point3#equals
* @param {Point3} a - The object to compare with this Point3.
* @returns {boolean} A value of true if the x and y points are equal, otherwise false.
*/
equals(a) {
return a.x === this.x && a.y === this.y && a.z === this.z;
}
/**
* Sets the x, y and z values of this Point3 object to the given values.
* If you omit the y and z value then the x value will be applied to all three, for example:
* `Point3.set(2)` is the same as `Point3.set(2, 2, 2)`
* If however you set both x and y, but no z, the z value will be set to 0.
*
* @method Point3#set
* @param {number} [x] - The x value of this point.
* @param {number} [y] - The y value of this point. If not given the x value will be used in its place.
* @param {number} [z] - The z value of this point. If not given and the y value is also not given, the x value will be used in its place.
* @returns {Point3} This Point3 object. Useful for chaining method calls.
*/
set(x, y, z) {
this.x = x || 0;
this.y = y || ((y !== 0) ? this.x : 0);
this.z = z || ((typeof y === 'undefined') ? this.x : 0);
}
/**
* Sets the x, y and z values of this Point3 object to the given values.
* If you omit the y and z value then the x value will be applied to all three, for example:
* `Point3.setTo(2)` is the same as `Point3.setTo(2, 2, 2)`
* If however you set both x and y, but no z, the z value will be set to 0.
*
* @method Point3#setTo
* @param {number} [x] - The x value of this point.
* @param {number} [y] - The y value of this point. If not given the x value will be used in its place.
* @param {number} [z] - The z value of this point. If not given and the y value is also not given, the x value will be used in its place.
* @returns {Point3} This Point3 object. Useful for chaining method calls.
*/
setTo(x, y, z) {
return this.set(x, y, z);
}
/**
* Adds the given x, y and z values to this Point3.
*
* @method Point3#add
* @param {number} x - The value to add to Point3.x.
* @param {number} y - The value to add to Point3.y.
* @param {number} z - The value to add to Point3.z.
* @returns {Point3} This Point3 object. Useful for chaining method calls.
*/
add(x, y, z) {
this.x += x || 0;
this.y += y || 0;
this.z += z || 0;
return this;
}
/**
* Subtracts the given x, y and z values from this Point3.
*
* @method Point3#subtract
* @param {number} x - The value to subtract from Point3.x.
* @param {number} y - The value to subtract from Point3.y.
* @param {number} z - The value to subtract from Point3.z.
* @returns {Point3} This Point3 object. Useful for chaining method calls.
*/
subtract(x, y, z) {
this.x -= x || 0;
this.y -= y || 0;
this.z -= z || 0;
return this;
}
/**
* Multiplies Point3.x, Point3.y and Point3.z by the given x and y values. Sometimes known as `Scale`.
*
* @method Point3#multiply
* @param {number} x - The value to multiply Point3.x by.
* @param {number} y - The value to multiply Point3.y by.
* @param {number} z - The value to multiply Point3.z by.
* @returns {Point3} This Point3 object. Useful for chaining method calls.
*/
multiply(x, y, z) {
this.x *= x || 1;
this.y *= y || 1;
this.z *= z || 1;
return this;
}
/**
* Divides Point3.x, Point3.y and Point3.z by the given x, y and z values.
*
* @method Point3#divide
* @param {number} x - The value to divide Point3.x by.
* @param {number} y - The value to divide Point3.y by.
* @param {number} z - The value to divide Point3.z by.
* @returns {Point3} This Point3 object. Useful for chaining method calls.
*/
divide(x, y, z) {
this.x /= x || 1;
this.y /= y || 1;
this.z /= z || 1;
return this;
}
} |
JavaScript | class TPiece {
/**
* @param {number} type - a piece type id
* @param {number} player - a player id who owns the piece
*/
constructor(type, player) {
this.type = type;
this.player = player;
/** @type {undefined | Array<number>} */
this.values;
}
/**
* Serializes the piece information into string data
* @param {TDesign} design - the object describing the game rules
* @returns {string} human-readable piece details
*/
toString(design) {
return design.playerNames[this.player] + " " + design.pieceNames[this.type];
}
/**
* Returns a value of the given piece type
* @param {number} ix - a piece id
* @returns {null | number} a piece value (null if the specified piece doesn't exist)
*/
getValue(ix) {
if (this.values === undefined) {
return null;
}
if (this.values[ix] === undefined) {
return null;
}
return this.values[ix];
}
/**
* Sets a value of the piece
* @param {number} ix - a piece id
* @param {null | number} new_value - a new value
* @returns {TPiece}
*/
setValue(ix, new_value) {
const current_value = this.getValue(ix);
if ((current_value === null) && (new_value === null)) {
return this;
}
if ((current_value !== null) && (new_value !== null) && (current_value == new_value)) {
return this;
}
const r = new TPiece(this.type, this.player);
if (r.values === undefined) {
r.values = [];
}
if (this.values !== undefined) {
// _.each(_.keys(this.values), i => {
// r.values[i] = this.values[i];
// });
r.values = [...this.values]; //shallow copying
}
if (new_value !== null) {
r.values[ix] = new_value;
} else {
delete r.values[ix];
}
return r;
}
/**
* Returns a piece instance promoted to another piece type.
* @param {number} type - a new piece type id
* @returns {TPiece} a new piece insatance
*/
promote(type) {
if (type == this.type) {
return this;
}
return new TPiece(type, this.player);
}
/**
* Returns a piece instance that got changed its owner.
* @param {number} player - a new player id
* @returns {TPiece} a new piece instance
*/
changeOwner(player) {
if (player == this.player) {
return this;
}
return new TPiece(this.type, player);
}
} |
JavaScript | class Pointer extends SComponent {
constructor (layout, { uuid }) {
super()
this.selection.attr('class', 'time-pointer-group')
// Save fixed y position
this.yPos = layout.height
this.selection.append('polyline')
.attr('class', 'pointer-triangle')
.attr('points', generateTrianglePoints([0, this.yPos]))
// Add overlay over axis to allow clicks
this.selection.append('rect')
.attr('class', 'pointer-overlay')
.attr('height', 80)
.attr('width', layout.width)
.attr('x', 0)
.attr('y', layout.height - 30)
this.uuid = uuid
}
plot (scales, currentIdx) {
let uuid = this.uuid
this.selection.select('.pointer-triangle')
.transition()
.duration(200)
.attr('points', generateTrianglePoints([scales.xScale(currentIdx), this.yPos]))
this.selection.select('.pointer-overlay').on('click', function () {
let clickIndex = Math.round(scales.xScale.invert(d3.mouse(this)[0]))
ev.publish(uuid, ev.JUMP_TO_INDEX, clickIndex)
})
}
} |
JavaScript | class Robot {
constructor ({app, cache, logger, router, catchErrors} = {}) {
this.events = new EventEmitter()
this.app = app
this.cache = cache
this.router = router || new express.Router()
this.log = wrapLogger(logger)
this.catchErrors = catchErrors
}
async receive (event) {
return this.events.emit('*', event).then(() => {
return this.events.emit(event.event, event)
})
}
/**
* Get an {@link http://expressjs.com|express} router that can be used to
* expose HTTP endpoints
*
* @example
* module.exports = robot => {
* // Get an express router to expose new HTTP endpoints
* const app = robot.route('/my-app');
*
* // Use any middleware
* app.use(require('express').static(__dirname + '/public'));
*
* // Add a new route
* app.get('/hello-world', (req, res) => {
* res.end('Hello World');
* });
* };
*
* @param {string} path - the prefix for the routes
* @returns {@link http://expressjs.com/en/4x/api.html#router|express.Router}
*/
route (path) {
if (path) {
const router = new express.Router()
this.router.use(path, router)
return router
} else {
return this.router
}
}
/**
* Listen for [GitHub webhooks](https://developer.github.com/webhooks/),
* which are fired for almost every significant action that users take on
* GitHub.
*
* @param {string} event - the name of the [GitHub webhook
* event](https://developer.github.com/webhooks/#events). Most events also
* include an "action". For example, the * [`issues`](
* https://developer.github.com/v3/activity/events/types/#issuesevent)
* event has actions of `assigned`, `unassigned`, `labeled`, `unlabeled`,
* `opened`, `edited`, `milestoned`, `demilestoned`, `closed`, and `reopened`.
* Often, your bot will only care about one type of action, so you can append
* it to the event name with a `.`, like `issues.closed`.
*
* @param {Robot~webhookCallback} callback - a function to call when the
* webhook is received.
*
* @example
*
* robot.on('push', context => {
* // Code was just pushed.
* });
*
* robot.on('issues.opened', context => {
* // An issue was just opened.
* });
*/
on (event, callback) {
if (event.constructor === Array) {
event.forEach(e => this.on(e, callback))
return
}
const [name, action] = event.split('.')
return this.events.on(name, async event => {
if (!action || action === event.payload.action) {
try {
const github = await this.auth(event.payload.installation.id)
const context = new Context(event, github)
await callback(context)
} catch (err) {
this.log.error({err, event})
if (!this.catchErrors) {
throw err
}
}
}
})
}
/**
* Authenticate and get a GitHub client that can be used to make API calls.
*
* You'll probably want to use `context.github` instead.
*
* **Note**: `robot.auth` is asynchronous, so it needs to be prefixed with a
* [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
* to wait for the magic to happen.
*
* @example
*
* module.exports = function(robot) {
* robot.on('issues.opened', async context => {
* const github = await robot.auth();
* });
* };
*
* @param {number} [id] - ID of the installation, which can be extracted from
* `context.payload.installation.id`. If called without this parameter, the
* client wil authenticate [as the app](https://developer.github.com/apps/building-integrations/setting-up-and-registering-github-apps/about-authentication-options-for-github-apps/#authenticating-as-a-github-app)
* instead of as a specific installation, which means it can only be used for
* [app APIs](https://developer.github.com/v3/apps/).
*
* @returns {Promise<github>} - An authenticated GitHub API client
* @private
*/
async auth (id) {
let github
if (id) {
const res = await this.cache.wrap(`app:${id}:token`, () => {
this.log.trace(`creating token for installation ${id}`)
return this.app.createToken(id)
}, {ttl: 60 * 59}) // Cache for 1 minute less than GitHub expiry
github = new GitHubApi({debug: process.env.LOG_LEVEL === 'trace'})
github.authenticate({type: 'token', token: res.data.token})
} else {
github = await this.app.asApp()
}
return probotEnhancedClient(github)
}
} |
JavaScript | class Rating {
static async addRating(
Model,
_id,
{
puntuation,
powerLevel,
pathRatedUserArray = 'ratedAlbums',
useUserID = false,
},
user,
activityInformationCallback,
) {
try {
const comparisonUser = useUserID ? user._id : user.username;
const model = await Model.findOne({
_id,
});
if (!model) {
console.log('Not found');
return null;
}
const index = model.ratings
.map(rating => rating.user)
.indexOf(comparisonUser);
// If rating does not exist.
if (index <= -1) {
// Add it.
model.ratings.push({
puntuation,
// Username.
user: comparisonUser,
powerLevel,
});
// Add to "today" the rating. (This is because in another calls to the api
// we may want to know the most hot rated albums of the day)
model.numberOfReviewsEachDay = model.numberOfReviewsEachDay
? numberReviewsDay.add(model.numberOfReviewsEachDay)
: [{ date: Date.now(), sum: 0 }];
} else {
// else replace
model.ratings.splice(index, 1, {
puntuation,
user: comparisonUser,
powerLevel,
});
// // Substract from the last day that the album received a rating.
// album.numberOfReviewsEachDay = album.numberOfReviewsEachDay
// ? numberReviewsDay.substract(album.numberOfReviewsEachDay)
// : [{ date: Date.now(), sum: 0 }];
}
const indexUser = user[pathRatedUserArray].indexOf(_id);
if (indexUser <= -1) user[pathRatedUserArray].push(_id);
user.save();
model.save();
Activity.addSomethingActivity(
Activity.createRatedInformation(
// {
// _id: album._id,
// name: `${album.name} by ${album.artist}`,
// score: req.body.puntuation,
// pathname: `/album/${album.artist}/${album.name}/${album.mbid}`,
// },
activityInformationCallback(model),
{ userId: user._id, username: user.username },
),
);
const average = Chart.averageWithPowerLevel(model.ratings);
const endModel = {
userScore: puntuation,
score: average,
__v: model.__v + 1,
_id: model._id,
};
return endModel;
} catch (err) {
console.log(err);
return null;
}
}
static async deleteRating(Model, modelID, user) {
try {
const model = await Model.findById(modelID);
if (!model) {
return null;
}
model.ratings = model.ratings.filter(
rating => String(rating.user) !== user.username,
);
const modelSaved = await model.save();
user.ratedAlbums = user.ratedAlbums.filter(
model => String(model) !== modelID,
);
user.save();
const average = Chart.averageWithPowerLevel(model.ratings);
modelSaved.score = average;
return model;
} catch (err) {
console.log(err);
return null;
}
}
} |
JavaScript | class ParamsParser {
constructor(input) {
this.input = input;
this.stream = input.split('');
this.state = `IDENT`;
this.deps = {};
this.output = [];
}
build() {
while (this.stream.length) {
this.process(this.stream.shift());
}
// Flush any lingering value
this.process(' ');
return this.output;
}
process(t) {
switch (this.state) {
case `IDENT`:
return this.processIDENT(t);
case `VALUE`:
return this.processVALUE(t);
}
}
processIDENT(t) {
// skip leading whitespace
if (TOKENS.SPACE.test(t) && !this.deps.started) { return };
this.deps.identifier = this.deps.identifier || '';
this.deps.started = true;
if (TOKENS.ASSIGN.test(t) && !this.deps.escape) {
// ↓
// title: page.title
if (!this.deps.identifier) { throw new Error("No identifier provided"); }
this.state = 'VALUE';
this.deps = { identifier: this.deps.identifier };
return;
}
if (TOKENS.ESCAPE.test(t) && !this.deps.escape) {
// ↓
// ti\:tle: page.title
return this.deps.escape = true;
}
// ↓↓↓↓↓
// title: page.title
this.deps.identifier += t;
this.deps.escape = false;
}
processVALUE(t) {
// skip leading whitespace
if (TOKENS.SPACE.test(t) && !this.deps.started) { return };
this.deps.value = this.deps.value || '';
this.deps.started = true;
// ↓
// title: "Hello \"World"
if (this.deps.escape) {
this.deps.value += t;
this.deps.escape = false;
return;
}
if (TOKENS.ESCAPE.test(t)) {
// ↓
// title: "Hello \"World"
this.deps.escape = true;
return;
}
this.deps.value += t;
if (!this.deps.delim) {
// ↓
// title: "Hello World"
if (TOKENS.DELIM.test(t)) {
return this.deps.delim = new RegExp(t);
}
// ↓
// title: (dict "a" "b")
if (TOKENS.INSCOPE.test(t)) {
return this.deps.delim = TOKENS.OUTSCOPE;
}
// ↓
// title: (0..4)[1]
if (TOKENS.INDEX.test(t)) {
return this.deps.delim = TOKENS.OUTDEX;
}
this.deps.delim = TOKENS.SPACE
// ↓
// title: variable
if (!TOKENS.SPACE.test(t)) {
return;
}
}
// ↓
// title: ( dict "a" (slice 1 2 3) )
if (this.deps.delimDepth && this.deps.delim.test(t)) {
return this.deps.delimDepth -= 1;
}
// ↓
// title: "Hello World"
if (this.deps.delim === TOKENS.SPACE && this.deps.delim.test(t)) {
this.deps.value = this.deps.value.replace(/.$/, '')
// Remove redundant parenthesis
this.deps.value = this.deps.value.replace(/^\(\(+(.+)\)+\)$/, "($1)");
this.deps.value = this.deps.value.replace(/^\((\S+)\)$/, "$1");
this.output.push([this.deps.identifier, this.deps.value]);
this.state = 'IDENT';
this.deps = {};
return;
}
// ↓ ↓ ↓
// title: "Hello World" number: (0..4)[2]
if (this.deps.delim.test(t)) {
this.deps.delim = null;
return;
}
// Handed nested parenthesis in Hugo dicts
// ↓
// title: ( dict "a" (slice 1 2 3) )
if (this.deps.delim === TOKENS.OUTSCOPE && TOKENS.INSCOPE.test(t)) {
this.deps.delimDepth = this.deps.delimDepth || 0;
this.deps.delimDepth += 1;
}
}
} |
JavaScript | class TheApi {
constructor(token) {
if(!token) throw new TypeError("valid Token must be provided!")
this.token = token;
}
getDate() {
return new Promise((resolve, reject) => {
fetch(encodeURI(`${baseUrl}/api/time?token=${this.token}`)).then(async data => {
let jsonData = await data.json();
if(jsonData.error) return reject(jsonData.error);
return resolve(jsonData);
}).catch(reject);
})
}
getLogo(){
return new Promise((resolve, reject) => {
fetch(encodeURI(`${baseUrl}/api/logo?token=${this.token}`)).then(async data => {
let jsonData = await data.json();
if(jsonData.error) return reject(jsonData.error);
return resolve(jsonData);
}).catch(reject);
})
}
} |
JavaScript | class Store {
constructor() {
this.todoList = [
{
id: 1,
title: 'Learn JavaScript',
completed: false
},
{
id: 2,
title: 'Learn Vue',
completed: false
}
];
}
/**
* Add a new todo object to the list
* @param {String} title - the title of the new todo
*/
addTodo(title) {
const newTodo = {
id: uniqueId(),
title,
completed: false
};
this.todoList.push(newTodo);
}
/**
* Complete or uncomplete a todo object
* @param {Number} id - the id of the todo object to complete / uncomplete
* @param {Boolean} completed - true to complete the todo, false to uncomplete it
*/
toggleTodo(id, completed) {
const todo = this.todoList.find(byId(id));
todo.completed = completed;
}
/**
* Complete or uncomplete all todo objects of the list
* @param {Boolean} completed - true to complete all todos, false to uncomplete them
*/
toggleAllTodos(completed) {
this.todoList.forEach(todo => {
todo.completed = completed;
});
}
/**
* Count the number of todos and the number of completed todos
* @returns {Object} the number of todos and the number of completed todos
*/
count() {
const total = this.todoList.length;
const completed = this.todoList.filter(todo => todo.completed).length;
return { total, completed };
}
/**
* Remove a todo object from the list
* @param {Number} id - the id of the todo object to remove
*/
removeTodo(id) {
const todoIndex = this.todoList.findIndex(byId(id));
this.todoList.splice(todoIndex, 1);
}
/**
* Update the title of a todo object
* @param {Number} id - the id of the todo object to update
* @param {String} title - the new title of the todo
*/
updateTodo(id, title) {
const todo = this.todoList.find(byId(id));
todo.title = title;
}
} |
JavaScript | class Controller {
constructor(config) {
const router = Router();
this.app = router;
this.config = config;
}
get(path, handler, permission) {
this.app.get(path, checkPermission(permission), handler.bind(this));
}
post(path, handler, permission, ...acceptedContentTypes) {
this.app.post(
path,
checkPermission(permission),
requireContentType(...acceptedContentTypes),
handler.bind(this),
);
}
put(path, handler, permission, ...acceptedContentTypes) {
this.app.put(
path,
checkPermission(permission),
requireContentType(...acceptedContentTypes),
handler.bind(this),
);
}
delete(path, handler, permission) {
this.app.delete(path, checkPermission(permission), handler.bind(this));
}
fileupload(path, filehandler, handler, permission) {
this.app.post(
path,
checkPermission(permission),
filehandler,
handler.bind(this),
);
}
use(path, router) {
this.app.use(path, router);
}
get router() {
return this.app;
}
} |
JavaScript | class BackgroundVideo {
/**
* Class constructor method
*
* @method constructor
* @params {object} options - object passed in to override default class options
*/
constructor(element, options) {
this.element = document.querySelectorAll(element);
this.options = Object.assign({}, defaults, options);
// Set browser prefix option
this.options.browserPrexix = this.detectBrowser();
// Ensure requestAnimationFrame is available
this.shimRequestAnimationFrame();
// Detect 3d transforms
this.options.has3d = this.detect3d();
// Set window dimensions
this.setWindowDimensions();
// Loop through each video and init
for(let i = 0; i < this.element.length; i++) {
this.init(this.element[i], i);
}
}
/**
* Init the plugin
*
* @method init
* @params element
* @params {number} iteration
*/
init(element, iteration) {
this.el = element;
this.playEvent = this.videoReadyCallback.bind(this);
this.setVideoWrap(iteration);
this.setVideoProperties()
this.insertVideos();
// Trigger beforeReady() event
if (this.options && this.options.onBeforeReady()) this.options.onBeforeReady();
// If video is cached, the video will already be ready so
// canplay/canplaythrough event will not fire.
if (this.el.readyState > 3) {
this.videoReadyCallback();
} else {
// Add event listener to detect when the video can play through
this.el.addEventListener('canplaythrough', this.playEvent, false);
this.el.addEventListener('canplay', this.playEvent, false);
}
// Prevent context menu on right click for object
if (this.options.preventContextMenu) {
this.el.addEventListener('contextmenu', () => false);
}
}
/**
* Function is triggered when the video is ready to be played
*
* @method videoReadyCallback
*/
videoReadyCallback() {
// Prevent event from being repeatedly called
this.el.removeEventListener('canplaythrough', this.playEvent, false);
this.el.removeEventListener('canplay', this.playEvent, false);
// Set original video height and width for resize and initial calculations
this.options.originalVideoW = this.el.videoWidth;
this.options.originalVideoH = this.el.videoHeight;
// Bind events for scroll, reize and parallax
this.bindEvents();
// Request first tick
this.requestTick();
// Trigger onReady() event
if (this.options && this.options.onReady()) this.options.onReady();
}
/**
* Bind class events
*
* @method bindEvents
*/
bindEvents() {
this.ticking = false;
if (this.options.parallax) {
window.addEventListener('scroll', this.requestTick.bind(this));
}
window.addEventListener('resize', this.requestTick.bind(this));
window.addEventListener('resize', this.setWindowDimensions.bind(this));
}
/**
* Set window width/height accessible within the class
*
* @method setWindowDimensions
*/
setWindowDimensions() {
this.windowWidth = window.innerWidth;
this.windowHeight = window.innerHeight;
}
/**
* When the user scrolls, check if !ticking and requestAnimationFrame
*
* @method bindEvents
*/
requestTick() {
if (!this.ticking) {
this.ticking = true;
window.requestAnimationFrame(this.positionObject.bind(this));
}
}
/**
* Position the video and apply transform styles
*
* @method positionObject
*/
positionObject() {
const scrollPos = window.pageYOffset;
let {xPos, yPos} = this.scaleObject();
// Check for parallax
if (this.options.parallax) {
// Prevent parallax when scroll position is negative to the window
if (scrollPos >= 0) {
yPos = this.calculateYPos(yPos, scrollPos);
} else {
yPos = this.calculateYPos(yPos, 0);
}
} else {
yPos = -yPos;
}
const transformStyle = (this.options.has3d) ? `translate3d(${xPos}px, ${yPos}px, 0)` : `translate(${xPos}px, ${yPos}px)`;
// Style with prefix
this.el.style[`${this.options.browserPrexix}`] = transformStyle;
// Style without prefix
this.el.style.transform = transformStyle;
this.ticking = false;
}
/**
* Scale video and wrapper, ensures video stays central and maintains aspect
* ratio
*
* @method scaleObject
*/
scaleObject() {
const heightScale = this.windowWidth / this.options.originalVideoW;
const widthScale = this.windowHeight / this.options.originalVideoH;
let scaleFactor;
this.options.bvVideoWrap.style.width = `${this.windowWidth}px`;
this.options.bvVideoWrap.style.height = `${this.windowHeight}px`;
scaleFactor = heightScale > widthScale ? heightScale : widthScale;
if (scaleFactor * this.options.originalVideoW < this.options.minimumVideoWidth) {
scaleFactor = this.options.minimumVideoWidth / this.options.originalVideoW;
}
const videoWidth = scaleFactor * this.options.originalVideoW;
const videoHeight = scaleFactor * this.options.originalVideoH;
this.el.style.width = `${videoWidth}px`;
this.el.style.height = `${videoHeight}px`;
return {
xPos: -(parseInt((videoWidth - this.windowWidth) / 2)),
yPos: parseInt(videoHeight - this.windowHeight) / 2
}
}
calculateYPos(yPos, scrollPos) {
const videoPosition = parseInt(this.options.bvVideoWrap.offsetTop);
const videoOffset = videoPosition - scrollPos;
yPos = -((videoOffset / this.options.parallax.effect) + yPos);
return yPos;
}
/**
* Create a container around the video tag
*
* @method setVideoWrap
* @params {number} - iteration of video
*/
setVideoWrap(iteration) {
const wrapper = document.createElement('div');
// Set video wrap class for later use in calculations
this.options.bvVideoWrapClass = `${this.el.className}-wrap-${iteration}`;
addClass(wrapper, 'bv-video-wrap');
addClass(wrapper, this.options.bvVideoWrapClass);
wrapper.style.position = 'relative';
wrapper.style.overflow = 'hidden';
wrapper.style.zIndex = '10';
this.el.parentNode.insertBefore(wrapper, this.el);
wrapper.appendChild(this.el);
// Set wrapper element for class wide use
this.options.bvVideoWrap = document.querySelector(`.${this.options.bvVideoWrapClass}`);
}
/**
* Set attributes and styles for video
*
* @method setVideoProperties
*/
setVideoProperties() {
this.el.setAttribute('preload', 'metadata');
this.el.setAttribute('loop', 'true');
this.el.setAttribute('autoplay', 'true');
this.el.style.position = 'absolute';
this.el.style.zIndex = '1';
var poster = this.options.autoplayFallback;
if(poster){
this.el.setAttribute('poster', poster);
}
}
/**
* Insert videos from `src` property defined
*
* @method insertVideos
*/
insertVideos() {
for(let i = 0; i < this.options.src.length; i++) {
let videoTypeArr = this.options.src[i].split('.');
let videoType = videoTypeArr[videoTypeArr.length - 1];
this.addSourceToVideo(this.options.src[i], `video/${videoType}`);
}
}
/**
* Insert videos from `src` property defined
*
* @method insertVideos
* @params {string} src - source of the video
* @params {string} type - type of video
*/
addSourceToVideo(src, type) {
const source = document.createElement('source');
source.src = src;
source.type = type;
this.el.appendChild(source);
}
/**
* Detect browser and return browser prefix for CSS
*
* @method detectBrowser
*/
detectBrowser() {
const val = navigator.userAgent.toLowerCase();
let browserPrexix;
if (val.indexOf('chrome') > -1 || val.indexOf('safari') > -1) {
browserPrexix = 'webkitTransform';
} else if (val.indexOf('firefox') > -1) {
browserPrexix = 'MozTransform';
} else if (val.indexOf('MSIE') !== -1 || val.indexOf('Trident/') > 0) {
browserPrexix = 'msTransform';
} else if (val.indexOf('Opera') > -1) {
browserPrexix = 'OTransform';
}
return browserPrexix;
}
/**
* Shim requestAnimationFrame to ensure it is available to all browsers
*
* @method shimRequestAnimationFrame
*/
shimRequestAnimationFrame() {
/* Paul Irish rAF.js: https://gist.github.com/paulirish/1579671 */
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
/**
* Detect if 3D transforms are avilable in the browser
*
* @method detect3d
*/
detect3d() {
var el = document.createElement('p'),
t, has3d,
transforms = {
'WebkitTransform': '-webkit-transform',
'OTransform': '-o-transform',
'MSTransform': '-ms-transform',
'MozTransform': '-moz-transform',
'transform': 'transform'
};
document.body.insertBefore(el, document.body.lastChild);
for (t in transforms) {
if (el.style[t] !== undefined) {
el.style[t] = 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)';
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
el.parentNode.removeChild(el);
if (has3d !== undefined) {
return has3d !== 'none';
} else {
return false;
}
}
} |
JavaScript | class ModelParser {
/**
* Checks if the class is a flexmodel and creates getters/setters if they are.
* @param {*} path
*/
processClass(path) {
if ( this.isFlexModelClass(path) ) {
console.log("Flex class ");
path.get("body.body").forEach(child => {
if ( this.isFlexProperty(child) ) {
this.privatePropHander(child, path);
}
});
}
}
/**
* Returns true if there is a @flexmodel in the comments of the class
* @param {*} path
* @returns
*/
isFlexModelClass(path) {
let leadingComments;
if ( path && path.node && path.node.leadingComments ) {
leadingComments = path.node.leadingComments;
} else if (
(t.isClassExpression(path.node) && t.isReturnStatement(path.parent)) ||
(t.isClassDeclaration(path.node) && (
t.isExportDefaultDeclaration(path.parent) || t.isExportDeclaration(path.parent)
))
) {
leadingComments = path.parent.leadingComments;
}
if ( leadingComments ) {
return leadingComments.find(c => c.value.indexOf("@cui5model") > -1) ? true : false;;
}
return false;
}
/**
* Returns true if there is @property in the class property.
*
* @param {*} path
* @returns
*/
isFlexProperty(path) {
if ( path && path.node && path.node.leadingComments ) {
return path.node.leadingComments.find(c => c.value.indexOf("@property") > -1) ? true : false;
}
return false;
}
/**
* Creates a getter/setter for the class property.
*
* @param {*} path
* @param {*} classPath
*/
privatePropHander(path, classPath) {
if ( path.node.typeAnnotation ) {
const propName = path.node.key.name;
const propType = path.node.typeAnnotation.typeAnnotation.type;
const propNameCap = Util.capitalize(propName);
const getterBody = [
t.returnStatement(
t.callExpression(
t.memberExpression(t.identifier("this"),t.identifier("getProperty")), [
t.stringLiteral(`/${propName}`)
]
)
)
];
const getterExpr = t.classMethod("method", t.identifier(`get${propNameCap}`), [], t.blockStatement(getterBody));
const setterBody = [
t.expressionStatement(
t.callExpression(
t.memberExpression(t.identifier("this"),t.identifier("setProperty")), [
t.stringLiteral(`/${propName}`),
t.identifier("value")
]
)
)
];
const setterExpr = t.classMethod("method", t.identifier(`set${propNameCap}`), [ t.identifier("value") ], t.blockStatement(setterBody));
classPath.get("body").unshiftContainer("body", getterExpr);
classPath.get("body").unshiftContainer("body", setterExpr);
}
}
} |
JavaScript | class ExpansionOverviewExample {
constructor() {
this.panelOpenState = false;
}
} |
JavaScript | class DemoTreeItem extends FuroTreeItem {
/**
* @private
* @returns {TemplateResult}
*/
render() {
// language=HTML
return html`
<furo-horizontal-flex @-dblclick="--dblclicked" @mouseenter="${(e) => this.fieldNode.triggerHover()}">
<div style="width: ${this.fieldNode.depth * 8}px; border-right: 1px solid green;"></div>
<div class="oc"><furo-data-bool-icon ?hidden="${!this.fieldNode.children.repeats.length}" ƒ-toggle="--dblclicked" ƒ-bind-data="--fieldOpen"></furo-data-bool-icon></div>
<div flex class="label" @-click="--labelClicked" >${this.fieldNode.display_name} <span class="desc">${this.fieldNode.description}</span></div>
<furo-icon icon="more-vert"></furo-icon>
</furo-horizontal-flex>
`;
}
} |
JavaScript | class IndexStorage {
/**
*
* @param {String} index
* @param {StorageEngine} storageEngine
*/
constructor (index, storageEngine) {
this._index = index;
this._storageEngine = storageEngine;
this._bootstrap = null;
// methods bound to the storage engine
this._rawMethods = [
'batchExecute',
'count',
'createCollection',
'createOrReplace',
'delete',
'deleteByQuery',
'deleteCollection',
'deleteIndex',
'exists',
'get',
'getMapping',
'mGet',
'refreshCollection',
'replace',
'search',
'truncateCollection',
'update',
'updateByQuery',
'updateCollection',
'updateMapping'
];
// we need to declare these method to keep backward compat with Repository API
this._otherMethods = [
'create',
'scroll'
];
for (const method of this._rawMethods) {
this[method] = (...args) => this._storageEngine[method](this._index, ...args);
}
}
get index () {
return this._index;
}
get bootstrap () {
return this._bootstrap;
}
set bootstrap (indexBootstrap) {
assert(
indexBootstrap instanceof require('./bootstrap/safeBootstrap'),
'IndexStorage bootstrap must be an instance of SafeBootstrap');
this._bootstrap = indexBootstrap;
}
/**
* Initialize the index, creates provided collections and call the provided boostrap
*
* @param {Object} collections - List of collections with mappings to create
*
* @return {Promise}
*/
async init (collections = {}) {
await this.createCollections(collections);
if (this._bootstrap) {
await this._bootstrap.startOrWait();
}
}
/**
* Scrolls a previously executed search
*
* @param {String} scrollId - Scroll identifier
* @param {String} scrollTTL - New scroll TTL
*/
scroll (scrollId, scrollTTL) {
return this._storageEngine.scroll(scrollId, { scrollTTL });
}
/**
* Creates a document
*
* @param {String} collection - Collection name
* @param {String} id - Document ID, may be null
* @param {Object} content - Document content
* @param {Object} options
*/
create (collection, id, content, options = {}) {
const opts = {
id,
refresh: options.refresh
};
return this._storageEngine.create(this._index, collection, content, opts);
}
/**
* Creates collections with the provided mappings
*
* @param {Object} collections - collections with mappings
*
* @returns {Promise}
*/
createCollections (collections) {
const promises = [];
for (const [collection, mappings] of Object.entries(collections)) {
promises.push(
this._storageEngine.createCollection(this._index, collection, { mappings }));
}
return Promise.all(promises);
}
} |
JavaScript | class MessageConsoleManager {
constructor(container, options) {
this.container_ = container || this.createContainer_();
this.tabContainer_ = this.createTabContainer_(this.container_);
this.msgDisplay_ = this.createMsgDisplay_(this.container_);
this.currentTab_ = null;
this.options_ = options || {};
this.tabs_ = [];
this.unassignedTabId_ = 0;
if(container) {
this.providedContainer_ = true;
}
}
createContainer_() {
const container = document.createElement("div");
container.id = "message_console_manager_container";
container.style.fontSize = "small";
container.style.fontWeight = "bold";
container.style.borderColor = "#000";
// container.style.backgroundColor = "rgba(200, 200, 200, 0.5)";
container.style.color = "#f00";
container.style.position = "absolute";
container.style.zIndex = "1050";
container.style.width = "100%";//"98%";
// container.style.minHeight = "50px";
container.style.left = "0";
container.style.bottom = "0";
container.style.textAlign = "left";
//container.style.padding = "1%";
return container;
}
createTabContainer_(container) {
const tabContainer = document.createElement("div");
container.appendChild(tabContainer);
return tabContainer;
}
createMsgDisplay_(container) {
const msgDisplay = document.createElement("div");
msgDisplay.style.backgroundColor = "rgba(200, 200, 200, 0.5)";
msgDisplay.style.padding = "1%";
container.appendChild(msgDisplay);
return msgDisplay;
}
addTab(tabTitle, message) {
const display = document.createElement("div");
const tab = {
display,
message,
currentMessage: "",
title: tabTitle,
id: this.unassignedTabId_
};
// const tab = {display, message};
display.innerText = tabTitle;
display.style.display = "inline-block";
display.style.borderRadius = "10px 10px 0 0";
display.style.backgroundColor = "rgba(200, 200, 200, 0.5)";
display.style.padding = "5px";
display.addEventListener("click", () => {
this.setSelectedTab(tab.id);
// display.innerText = tabTitle; // tab title may have (*) indicating new message;
// after it's selected * should be
// removed and only title should show
});
this.tabs_.push(tab);
if(!this.currentTab_) {
// first created tab; set current tab to this new first one
this.setSelectedTab(tab.id);
}
this.tabContainer_.appendChild(display);
return this.unassignedTabId_++;
}
getTabIdByTitle(title) {
return this.tabs_.filter(tab => tab.title === title)
.map(tab => tab.id)[0];
}
setTabHandlerByTitle(tabTitle, msgHandler, index=0) {
const tab = this.tabs_.filter(tab => tab.title === tabTitle)[index]
if(tab) {
console.log("Changing tab ", tab, "with title", tabTitle, "#", index);
// tab.title = newTabTitle;
tab.display.innerText = tabTitle;
tab.message = msgHandler;
console.log("Tab is now", tab);
}
return !!tab;
}
changeTab(id, newTabTitle, newMessage) {
const tab = this.tabs_.find(tab => tab.id === id);
if(tab) {
console.log("Changing tab", tab, "with id", id);
tab.title = newTabTitle;
tab.display.innerText = newTabTitle;
tab.message = newMessage;
console.log("Tab is now", tab);
}
return !!tab;
}
setSelectedTab(id) {
const tab = this.tabs_.find(tab => tab.id === id);
console.log("Setting tab to", tab);
if(tab) {
// maybe add CSS class for selected
// console.log("CLICKED", tab);
if(this.currentTab_) {
// unselect styles for current tab
// this.currentTab_.display.style.removeProperty("background-color");
this.currentTab_.display.style.backgroundColor = "rgba(200, 200, 200, 0.5)";
this.currentTab_.display.style.removeProperty("font-weight");
}
//display.style.backgroundColor = "#dcf4ff"; // indicate selected
tab.display.style.backgroundColor = "rgba(127, 122, 110, 0.5)"; // rgb(255, 244, 220)
tab.display.style.fontWeight = "bold";
tab.display.innerText = tab.title; // tab title may have (*) indicating new message;
// after it's selected * should be
// removed and only title should show
this.currentTab_ = tab;
}
return !!tab;
}
start() {
/* POSITIONING IGNORED FOR NOW - ORIGINALLY FOR HELP MENU DIALOG
this.startPosition_ = this.value_(this.options_.startPosition);
this.alertDisplay_.style.left = this.startPosition_.x + "px";
this.alertyDisplay_.style.top = this.startPosition_.y + "px";
*/
if(!document.getElementById("message_console_manager_container")) {
document.body.appendChild(this.container_);
} else {
this.show();
}
this.started_ = true;
}
show() {
this.container_.style.display = "block";
}
hide() {
this.container_.style.display = "none";
}
isComplete() {
// return (typeof this.message_ === "string"); // message never changes
return false;
}
finish() {
this.tabs_.map(tab => tab.display)
.forEach(tabDisplay => this.tabContainer_.removeChild(tabDisplay))
this.container_.removeChild(this.msgDisplay_);
this.container_.removeChild(this.tabContainer_);
if(!this.providedContainer_) {
// remove container only if this class created it
document.body.removeChild(this.container_);
}
//this.helpButton_.style.display = "none";
if(typeof this.options_.finish === "function") {
this.options_.finish();
}
}
animate(steps=1) {
const messages = this.tabs_.map(tab => this.value_(tab.message));
// add asterisk to indicate new messages
this.tabs_.filter((tab, index) => this.currentTab_ !== tab &&
messages[index] &&
tab.currentMessage !== messages[index] &&
!tab.display.innerText.trim().endsWith("*"))
.forEach(tab => tab.display.innerText += "*");
this.tabs_.forEach((tab, index) => tab.currentMessage = messages[index]);
this.msgDisplay_.innerText = this.currentTab_.currentMessage;
}
value_(g) {
return g instanceof Function ? g() : g;
}
} |
JavaScript | class ImagesController {
constructor(db) {
this.router = express_1.Router();
this.db = db;
this.router.post('/', upload.single('image'), this.create.bind(this));
this.router.post('/multiple', upload.array("images"), this.createMultiple.bind(this));
}
create(req, res, next) {
let image;
image = {
id: (new Date()).valueOf().toString(),
dateCreated: new Date(),
filename: req.file.filename,
fileSize: req.file.size,
path: req.file.path
};
this.db.collection(IMAGES).insertOne(image)
.then((img) => {
res.status(200).send(image);
})
.catch(err => {
res.status(400).send(err);
});
}
createMultiple(req, res, next) {
let files = req.files;
let images = new Array(files.length);
for (let index = 0; index < files.length; index++) {
let file = files[index];
images[index] = {
id: (new Date()).valueOf().toString(),
dateCreated: new Date(),
filename: file.filename,
fileSize: file.size,
path: file.path
};
}
this.db.collection(IMAGES).insertMany(images)
.then((img) => {
res.status(200).send(images);
})
.catch(err => {
res.status(400).send(err);
});
}
} |
JavaScript | class AngleTool extends BaseAnnotationTool {
constructor(props = {}) {
const defaultProps = {
name: 'Angle',
supportedInteractionTypes: ['Mouse', 'Touch'],
svgCursor: angleCursor,
configuration: {
drawHandles: true,
},
};
super(props, defaultProps);
this.preventNewMeasurement = false;
this.throttledUpdateCachedStats = throttle(this.updateCachedStats, 110);
}
createNewMeasurement(eventData) {
// Create the measurement data for this tool with the end handle activated
return {
visible: true,
active: true,
color: undefined,
invalidated: true,
handles: {
start: {
x: eventData.currentPoints.image.x,
y: eventData.currentPoints.image.y,
highlight: true,
active: false,
},
middle: {
x: eventData.currentPoints.image.x,
y: eventData.currentPoints.image.y,
highlight: true,
active: true,
},
end: {
x: eventData.currentPoints.image.x,
y: eventData.currentPoints.image.y,
highlight: true,
active: false,
},
textBox: {
active: false,
hasMoved: false,
movesIndependently: false,
drawnIndependently: true,
allowedOutsideImage: true,
hasBoundingBox: true,
},
},
};
}
pointNearTool(element, data, coords) {
if (data.visible === false) {
return false;
}
return (
lineSegDistance(
element,
data.handles.start,
data.handles.middle,
coords
) < 25 ||
lineSegDistance(element, data.handles.middle, data.handles.end, coords) <
25
);
}
updateCachedStats(image, element, data) {
const { rowPixelSpacing, colPixelSpacing } = getPixelSpacing(image);
const sideA = {
x: (data.handles.middle.x - data.handles.start.x) * colPixelSpacing,
y: (data.handles.middle.y - data.handles.start.y) * rowPixelSpacing,
};
const sideB = {
x: (data.handles.end.x - data.handles.middle.x) * colPixelSpacing,
y: (data.handles.end.y - data.handles.middle.y) * rowPixelSpacing,
};
const sideC = {
x: (data.handles.end.x - data.handles.start.x) * colPixelSpacing,
y: (data.handles.end.y - data.handles.start.y) * rowPixelSpacing,
};
const sideALength = length(sideA);
const sideBLength = length(sideB);
const sideCLength = length(sideC);
// Cosine law
let angle = Math.acos(
(Math.pow(sideALength, 2) +
Math.pow(sideBLength, 2) -
Math.pow(sideCLength, 2)) /
(2 * sideALength * sideBLength)
);
angle *= 180 / Math.PI;
data.rAngle = roundToDecimal(angle, 2);
data.invalidated = false;
}
renderToolData(evt) {
const eventData = evt.detail;
const enabledElement = eventData.enabledElement;
const { handleRadius, drawHandlesOnHover } = this.configuration;
// If we have no toolData for this element, return immediately as there is nothing to do
const toolData = getToolState(evt.currentTarget, this.name);
if (!toolData) {
return;
}
// We have tool data for this element - iterate over each one and draw it
const context = getNewContext(eventData.canvasContext.canvas);
const { image, element } = eventData;
const { rowPixelSpacing, colPixelSpacing } = getPixelSpacing(image);
const lineWidth = toolStyle.getToolWidth();
for (let i = 0; i < toolData.data.length; i++) {
const data = toolData.data[i];
if (data.visible === false) {
continue;
}
draw(context, context => {
setShadow(context, this.configuration);
// Differentiate the color of activation tool
const color = toolColors.getColorIfActive(data);
const handleStartCanvas = external.cornerstone.pixelToCanvas(
eventData.element,
data.handles.start
);
const handleMiddleCanvas = external.cornerstone.pixelToCanvas(
eventData.element,
data.handles.middle
);
drawJoinedLines(
context,
eventData.element,
data.handles.start,
[data.handles.middle, data.handles.end],
{ color }
);
// Draw the handles
const handleOptions = {
color,
handleRadius,
drawHandlesIfActive: drawHandlesOnHover,
};
if (this.configuration.drawHandles) {
drawHandles(context, eventData, data.handles, handleOptions);
}
// Update textbox stats
if (data.invalidated === true) {
if (data.rAngle) {
this.throttledUpdateCachedStats(image, element, data);
} else {
this.updateCachedStats(image, element, data);
}
}
if (data.rAngle) {
const text = textBoxText(data, rowPixelSpacing, colPixelSpacing);
const distance = 15;
let textCoords;
if (!data.handles.textBox.hasMoved) {
textCoords = {
x: handleMiddleCanvas.x,
y: handleMiddleCanvas.y,
};
const padding = 5;
const textWidth = textBoxWidth(context, text, padding);
if (handleMiddleCanvas.x < handleStartCanvas.x) {
textCoords.x -= distance + textWidth + 10;
} else {
textCoords.x += distance;
}
const transform = external.cornerstone.internal.getTransform(
enabledElement
);
transform.invert();
const coords = transform.transformPoint(textCoords.x, textCoords.y);
data.handles.textBox.x = coords.x;
data.handles.textBox.y = coords.y;
}
drawLinkedTextBox(
context,
eventData.element,
data.handles.textBox,
text,
data.handles,
textBoxAnchorPoints,
color,
lineWidth,
0,
true
);
}
});
}
function textBoxText(data, rowPixelSpacing, colPixelSpacing) {
const suffix = !rowPixelSpacing || !colPixelSpacing ? ' (isotropic)' : '';
const str = '00B0'; // Degrees symbol
return (
data.rAngle.toString() + String.fromCharCode(parseInt(str, 16)) + suffix
);
}
function textBoxAnchorPoints(handles) {
return [handles.start, handles.middle, handles.end];
}
}
addNewMeasurement(evt, interactionType) {
if (this.preventNewMeasurement) {
return;
}
this.preventNewMeasurement = true;
evt.preventDefault();
evt.stopPropagation();
const eventData = evt.detail;
const measurementData = this.createNewMeasurement(eventData);
const element = evt.detail.element;
// Associate this data with this imageId so we can render it and manipulate it
addToolState(element, this.name, measurementData);
external.cornerstone.updateImage(element);
// Step 1, create start and second middle.
moveNewHandle(
eventData,
this.name,
measurementData,
measurementData.handles.middle,
this.options,
interactionType,
success => {
measurementData.active = false;
if (!success) {
removeToolState(element, this.name, measurementData);
this.preventNewMeasurement = false;
return;
}
measurementData.handles.end.active = true;
external.cornerstone.updateImage(element);
// Step 2, create end.
moveNewHandle(
eventData,
this.name,
measurementData,
measurementData.handles.end,
this.options,
interactionType,
success => {
if (success) {
measurementData.active = false;
external.cornerstone.updateImage(element);
} else {
removeToolState(element, this.name, measurementData);
}
this.preventNewMeasurement = false;
external.cornerstone.updateImage(element);
const modifiedEventData = {
toolName: this.name,
toolType: this.name, // Deprecation notice: toolType will be replaced by toolName
element,
measurementData,
};
triggerEvent(
element,
EVENTS.MEASUREMENT_COMPLETED,
modifiedEventData
);
}
);
}
);
}
} |
JavaScript | class Intern extends Employee {
constructor(employeeInfo) {
super(employeeInfo);
const { school } = employeeInfo;
this.school = school;
}
getSchool() {
return this.school;
}
} |
JavaScript | class SpectrumDownload {
//Unique Id values for graph and download buttons
static SPECDOWNLOADPNG = "spectrum_download_png";
static SPECDOWNLOADSVG = "spectrum_download_svg";
static SPECTRUMGRAPHID = "spectrum";
static downloadbuttonX = 41;
static spanWidth = 50;
static downloadButtonWidth = 30;
static downloadButtonHeight = 30;
static buttonWidth = 50;
static buttonHeight = 28;
static buttonOne_Y = 33;
static buttonTwo_Y = 60;
//default costructor
constructor(){
}
/**
* Draw a rectangular block to keep download image
*/
static addDownloadRect = function(svgId,spectrumParameters){
d3.select("#g_spectrum_button").remove();
let svg = d3.select("body").select(svgId);
let group = svg.append("g").attr("id","g_spectrum_button");
group.append("svg:image").attr("id","spectrum_download")
.attr('x', (spectrumParameters.svgWidth-SpectrumDownload.downloadbuttonX))
.attr('y', 0)//top most point in svg
.attr('width', SpectrumDownload.downloadButtonWidth)
.attr('height', SpectrumDownload.downloadButtonHeight)
.attr("xlink:href", "../shared_scripts/spectrum_graph/images/download.png")
d3.selectAll("#g_spectrum_button").on('mouseover',function(){
d3.select(this).style("cursor", "pointer");
})
.on('mouseout',function(){
d3.select(this).style("cursor", "default");
});
$("#spectrum_download").on("click",function(){
d3.selectAll(".downloadgraph_button").remove();
SpectrumDownload.addDownloadbuttons(svgId,spectrumParameters);
});
}
/**
* Setting images as download buttons
*/
static addDownloadbuttons = function(svgId,spectrumParameters){
let group = d3.select("#g_spectrum_button");
group.append("svg:image").attr("id",SpectrumDownload.SPECDOWNLOADSVG)
.attr("class","downloadgraph_button")
.attr('x', (spectrumParameters.svgWidth-SpectrumDownload.spanWidth))
.attr('y', SpectrumDownload.buttonOne_Y)
.attr('width', SpectrumDownload.buttonWidth)
.attr('height', SpectrumDownload.buttonHeight)
.attr("xlink:href", "../shared_scripts/spectrum_graph/images/svg.png");
group.append("svg:image").attr("id",SpectrumDownload.SPECDOWNLOADPNG)
.attr("class","downloadgraph_button")
.attr('x', (spectrumParameters.svgWidth-SpectrumDownload.spanWidth))
.attr('y', SpectrumDownload.buttonTwo_Y)
.attr('width', SpectrumDownload.buttonWidth)
.attr('height', SpectrumDownload.buttonHeight)
.attr("xlink:href", "../shared_scripts/spectrum_graph/images/png.png");
SpectrumDownload.download(svgId,spectrumParameters);
}
/**
* On click action to download spectrum graph as SVG/PNG
*/
static download = function(svgId,spectrumParameters){
//On click action to download spectrum graph SVG in .svg format
$("#"+SpectrumDownload.SPECDOWNLOADSVG).click(function(){
$("#g_spectrum_button").remove();
let name = "spectrum.svg"
let svg_element = d3.selectAll("#"+SpectrumDownload.SPECTRUMGRAPHID).node();
svg2svg(svg_element,name);
SpectrumDownload.addDownloadRect(svgId,spectrumParameters);
})
//On click action to download spectrum graph PNG in .png format
$("#"+SpectrumDownload.SPECDOWNLOADPNG).click(function(){
$("#g_spectrum_button").remove();
let l_svgContainer = d3.select("#"+SpectrumDownload.SPECTRUMGRAPHID);
let svgString = getSVGString(l_svgContainer.node());
//let svg_element = document.getElementById(SpectrumDownload.SPECTRUMGRAPHID);
//let bBox = svg_element.getBBox();
let width = spectrumParameters.svgWidth;
let height = spectrumParameters.svgHeight ;
svgString2Image( svgString, 2*width, 2*height, 'png', save );
function save( dataBlob, filesize ){
saveAs( dataBlob, 'spectrum.png' );
}
SpectrumDownload.addDownloadRect(svgId,spectrumParameters);
})
}
} |
JavaScript | class VarExporter {
/**
/**
* Exports a serializable JS value to JS code.
*
* @param {*} value The value to export
*
* @returns {string} The value exported as JS code
*/
static export(value) {
return '(() => {\n let o;\n return ' + doExport(value) + ';\n})();\n';
}
} |
JavaScript | class InitCommand extends BaseCommand {
static get description() {
return "Initialize queue configuration";
}
static get signature() {
return "queue:init";
}
async handle() {
try {
// copy over sample configs and server files to respective directory
const tmplPath = path.join(__dirname, '../src/templates');
await copyFile(path.join(tmplPath, 'config.tmpl'),
this._helpers.appRoot() + "/config/queue.js");
await copyFile(path.join(tmplPath, 'queue.tmpl'),
this._helpers.appRoot() + "/start/queue.js");
await copyFile(path.join(tmplPath, 'queue_server.tmpl'),
this._helpers.appRoot() + "/queue_server.js");
this.success('Queue initialized successfully!');
} catch (e) {
console.error(e);
this.error('Failed to initialize queue with error: ' + e.message);
}
}
} |
JavaScript | class PackageJsonLookup {
constructor(parameters) {
this._loadExtraFields = false;
if (parameters) {
if (parameters.loadExtraFields) {
this._loadExtraFields = parameters.loadExtraFields;
}
}
this.clearCache();
}
/**
* A helper for loading the caller's own package.json file.
*
* @remarks
*
* This function provides a concise and efficient way for an NPM package to report metadata about itself.
* For example, a tool might want to report its version.
*
* The `loadOwnPackageJson()` probes upwards from the caller's folder, expecting to find a package.json file,
* which is assumed to be the caller's package. The result is cached, under the assumption that a tool's
* own package.json (and intermediary folders) will never change during the lifetime of the process.
*
* @example
* ```ts
* // Report the version of our NPM package
* const myPackageVersion: string = PackageJsonLookup.loadOwnPackageJson(__dirname).version;
* console.log(`Cool Tool - Version ${myPackageVersion}`);
* ```
*
* @param dirnameOfCaller - The NodeJS `__dirname` macro for the caller.
* @returns This function always returns a valid `IPackageJson` object. If any problems are encountered during
* loading, an exception will be thrown instead.
*/
static loadOwnPackageJson(dirnameOfCaller) {
const packageJson = PackageJsonLookup._loadOwnPackageJsonLookup
.tryLoadPackageJsonFor(dirnameOfCaller);
if (packageJson === undefined) {
throw new Error(`PackageJsonLookup.loadOwnPackageJson() failed to find the caller's package.json.`
+ ` The __dirname was: ${dirnameOfCaller}`);
}
if (packageJson.version !== undefined) {
return packageJson;
}
const errorPath = PackageJsonLookup._loadOwnPackageJsonLookup.tryGetPackageJsonFilePathFor(dirnameOfCaller)
|| 'package.json';
throw new Error(`PackageJsonLookup.loadOwnPackageJson() failed because the "version" field is missing in`
+ ` ${errorPath}`);
}
/**
* Clears the internal file cache.
* @remarks
* Call this method if changes have been made to the package.json files on disk.
*/
clearCache() {
this._packageFolderCache = new Map();
this._packageJsonCache = new Map();
}
/**
* Returns the absolute path of a folder containing a package.json file, by looking
* upwards from the specified fileOrFolderPath. If no package.json can be found,
* undefined is returned.
*
* @remarks
* The fileOrFolderPath is not required to actually exist on disk.
* The fileOrFolderPath itself can be the return value, if it is a folder containing
* a package.json file.
* Both positive and negative lookup results are cached.
*
* @param fileOrFolderPath - a relative or absolute path to a source file or folder
* that may be part of a package
* @returns an absolute path to a folder containing a package.json file
*/
tryGetPackageFolderFor(fileOrFolderPath) {
// Convert it to an absolute path
const resolvedFileOrFolderPath = path.resolve(fileOrFolderPath);
// Optimistically hope that the starting string is already in the cache,
// in which case we can avoid disk access entirely.
//
// (Two lookups are required, because get() cannot distinguish the undefined value
// versus a missing key.)
if (this._packageFolderCache.has(resolvedFileOrFolderPath)) {
return this._packageFolderCache.get(resolvedFileOrFolderPath);
}
// Now call the recursive part of the algorithm
return this._tryGetPackageFolderFor(resolvedFileOrFolderPath);
}
/**
* If the specified file or folder is part of a package, this returns the absolute path
* to the associated package.json file.
*
* @remarks
* The package folder is determined using the same algorithm
* as {@link PackageJsonLookup.tryGetPackageFolderFor}.
*
* @param fileOrFolderPath - a relative or absolute path to a source file or folder
* that may be part of a package
* @returns an absolute path to * package.json file
*/
tryGetPackageJsonFilePathFor(fileOrFolderPath) {
const packageJsonFolder = this.tryGetPackageFolderFor(fileOrFolderPath);
if (!packageJsonFolder) {
return undefined;
}
return path.join(packageJsonFolder, "package.json" /* PackageJson */);
}
/**
* If the specified file or folder is part of a package, this loads and returns the
* associated package.json file.
*
* @remarks
* The package folder is determined using the same algorithm
* as {@link PackageJsonLookup.tryGetPackageFolderFor}.
*
* @param fileOrFolderPath - a relative or absolute path to a source file or folder
* that may be part of a package
* @returns an IPackageJson object, or undefined if the fileOrFolderPath does not
* belong to a package
*/
tryLoadPackageJsonFor(fileOrFolderPath) {
const packageJsonFilePath = this.tryGetPackageJsonFilePathFor(fileOrFolderPath);
if (!packageJsonFilePath) {
return undefined;
}
return this.loadPackageJson(packageJsonFilePath);
}
/**
* This function is similar to {@link tryLoadPackageJsonFor}, except that it does not report an error if the
* `version` field is missing from the package.json file.
*/
tryLoadNodePackageJsonFor(fileOrFolderPath) {
const packageJsonFilePath = this.tryGetPackageJsonFilePathFor(fileOrFolderPath);
if (!packageJsonFilePath) {
return undefined;
}
return this.loadNodePackageJson(packageJsonFilePath);
}
/**
* Loads the specified package.json file, if it is not already present in the cache.
*
* @remarks
* Unless {@link IPackageJsonLookupParameters.loadExtraFields} was specified,
* the returned IPackageJson object will contain a subset of essential fields.
* The returned object should be considered to be immutable; the caller must never
* modify it.
*
* @param jsonFilename - a relative or absolute path to a package.json file
*/
loadPackageJson(jsonFilename) {
const packageJson = this.loadNodePackageJson(jsonFilename);
if (!packageJson.version) {
throw new Error(`Error reading "${jsonFilename}":\n `
+ 'The required field "version" was not found');
}
return packageJson;
}
/**
* This function is similar to {@link loadPackageJson}, except that it does not report an error if the
* `version` field is missing from the package.json file.
*/
loadNodePackageJson(jsonFilename) {
if (!FileSystem_1.FileSystem.exists(jsonFilename)) {
throw new Error(`Input file not found: ${jsonFilename}`);
}
// Since this will be a cache key, follow any symlinks and get an absolute path
// to minimize duplication. (Note that duplication can still occur due to e.g. character case.)
const normalizedFilePath = FileSystem_1.FileSystem.getRealPath(jsonFilename);
let packageJson = this._packageJsonCache.get(normalizedFilePath);
if (!packageJson) {
const loadedPackageJson = JsonFile_1.JsonFile.load(normalizedFilePath);
// Make sure this is really a package.json file. CommonJS has fairly strict requirements,
// but NPM only requires "name" and "version"
if (!loadedPackageJson.name) {
throw new Error(`Error reading "${jsonFilename}":\n `
+ 'The required field "name" was not found');
}
if (this._loadExtraFields) {
packageJson = loadedPackageJson;
}
else {
packageJson = {};
// Unless "loadExtraFields" was requested, copy over the essential fields only
packageJson.bin = loadedPackageJson.bin;
packageJson.dependencies = loadedPackageJson.dependencies;
packageJson.description = loadedPackageJson.description;
packageJson.devDependencies = loadedPackageJson.devDependencies;
packageJson.homepage = loadedPackageJson.homepage;
packageJson.license = loadedPackageJson.license;
packageJson.main = loadedPackageJson.main;
packageJson.name = loadedPackageJson.name;
packageJson.optionalDependencies = loadedPackageJson.optionalDependencies;
packageJson.peerDependencies = loadedPackageJson.peerDependencies;
packageJson.private = loadedPackageJson.private;
packageJson.scripts = loadedPackageJson.scripts;
packageJson.typings = loadedPackageJson.typings || loadedPackageJson.types;
packageJson.tsdoc = loadedPackageJson.tsdoc;
packageJson.tsdocMetadata = loadedPackageJson.tsdocMetadata;
packageJson.version = loadedPackageJson.version;
}
Object.freeze(packageJson);
this._packageJsonCache.set(normalizedFilePath, packageJson);
}
return packageJson;
}
// Recursive part of the algorithm from tryGetPackageFolderFor()
_tryGetPackageFolderFor(resolvedFileOrFolderPath) {
// Two lookups are required, because get() cannot distinguish the undefined value
// versus a missing key.
if (this._packageFolderCache.has(resolvedFileOrFolderPath)) {
return this._packageFolderCache.get(resolvedFileOrFolderPath);
}
// Is resolvedFileOrFolderPath itself a folder with a package.json file? If so, return it.
if (FileSystem_1.FileSystem.exists(path.join(resolvedFileOrFolderPath, "package.json" /* PackageJson */))) {
this._packageFolderCache.set(resolvedFileOrFolderPath, resolvedFileOrFolderPath);
return resolvedFileOrFolderPath;
}
// Otherwise go up one level
const parentFolder = path.dirname(resolvedFileOrFolderPath);
if (!parentFolder || parentFolder === resolvedFileOrFolderPath) {
// We reached the root directory without finding a package.json file,
// so cache the negative result
this._packageFolderCache.set(resolvedFileOrFolderPath, undefined);
return undefined; // no match
}
// Recurse upwards, caching every step along the way
const parentResult = this._tryGetPackageFolderFor(parentFolder);
// Cache the parent's answer as well
this._packageFolderCache.set(resolvedFileOrFolderPath, parentResult);
return parentResult;
}
} |
JavaScript | class AADObject {
/**
* Create a AADObject.
* @member {string} [objectId] The ID of the object.
* @member {string} [objectType] The type of AAD object.
* @member {string} [displayName] The display name of the object.
* @member {string} [userPrincipalName] The principal name of the object.
* @member {string} [mail] The primary email address of the object.
* @member {boolean} [mailEnabled] Whether the AAD object is mail-enabled.
* @member {string} [mailNickname] The mail alias for the user.
* @member {boolean} [securityEnabled] Whether the AAD object is
* security-enabled.
* @member {string} [signInName] The sign-in name of the object.
* @member {array} [servicePrincipalNames] A collection of service principal
* names associated with the object.
* @member {string} [userType] The user type of the object.
* @member {string} [usageLocation] A two letter country code (ISO standard
* 3166). Required for users that will be assigned licenses due to legal
* requirement to check for availability of services in countries. Examples
* include: "US", "JP", and "GB".
* @member {string} [appId] The application ID.
* @member {array} [appPermissions] The application permissions.
* @member {boolean} [availableToOtherTenants] Whether the application is be
* available to other tenants.
* @member {array} [identifierUris] A collection of URIs for the application.
* @member {array} [replyUrls] A collection of reply URLs for the
* application.
* @member {string} [homepage] The home page of the application.
*/
constructor() {
}
/**
* Defines the metadata of AADObject
*
* @returns {object} metadata of AADObject
*
*/
mapper() {
return {
required: false,
serializedName: 'AADObject',
type: {
name: 'Composite',
className: 'AADObject',
modelProperties: {
objectId: {
required: false,
serializedName: 'objectId',
type: {
name: 'String'
}
},
objectType: {
required: false,
serializedName: 'objectType',
type: {
name: 'String'
}
},
displayName: {
required: false,
serializedName: 'displayName',
type: {
name: 'String'
}
},
userPrincipalName: {
required: false,
serializedName: 'userPrincipalName',
type: {
name: 'String'
}
},
mail: {
required: false,
serializedName: 'mail',
type: {
name: 'String'
}
},
mailEnabled: {
required: false,
serializedName: 'mailEnabled',
type: {
name: 'Boolean'
}
},
mailNickname: {
required: false,
readOnly: true,
serializedName: 'mailNickname',
type: {
name: 'String'
}
},
securityEnabled: {
required: false,
serializedName: 'securityEnabled',
type: {
name: 'Boolean'
}
},
signInName: {
required: false,
serializedName: 'signInName',
type: {
name: 'String'
}
},
servicePrincipalNames: {
required: false,
serializedName: 'servicePrincipalNames',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
userType: {
required: false,
serializedName: 'userType',
type: {
name: 'String'
}
},
usageLocation: {
required: false,
readOnly: true,
serializedName: 'usageLocation',
type: {
name: 'String'
}
},
appId: {
required: false,
readOnly: true,
serializedName: 'appId',
type: {
name: 'String'
}
},
appPermissions: {
required: false,
readOnly: true,
serializedName: 'appPermissions',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
availableToOtherTenants: {
required: false,
readOnly: true,
serializedName: 'availableToOtherTenants',
type: {
name: 'Boolean'
}
},
identifierUris: {
required: false,
readOnly: true,
serializedName: 'identifierUris',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
replyUrls: {
required: false,
readOnly: true,
serializedName: 'replyUrls',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
homepage: {
required: false,
readOnly: true,
serializedName: 'homepage',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class NodeLoggingService extends LoggingService {
/**
* Constructor.
*/
constructor() {
super();
this.stub = null;
}
/**
* Initialise the logging service for the incoming request.
* This will need to stub for the request so it saves the stub for later use.
*
*
* @param {Object} stub node chaincode stub
*/
async initLogging(stub) {
this.stub = stub;
let logCFG = await this.getLoggerCfg();
Logger.setLoggerCfg(logCFG, true);
Logger.setCallBack(function(logLevel) {
const timestamp = new Date().toISOString();
const shortTxId = stub.getTxID().substring(0, 8);
return `${timestamp} [${shortTxId}] ${logLevel.toUpperCase().padEnd(8)} `;
});
}
/**
*
* @param {Object} cfg to set
*/
async setLoggerCfg(cfg) {
await this.stub.putState(LOGLEVEL_KEY, Buffer.from(JSON.stringify(cfg)));
}
/**
* Return the logger config... basically the usual default setting for debug
* Console only. maxLevel needs to be high here as all the logs goto the stdout/stderr
*
* @returns {Object} configuration
*/
async getLoggerCfg(){
let result = await this.stub.getState(LOGLEVEL_KEY);
if (result.length === 0) {
let defCfg = this.getDefaultCfg();
return defCfg;
} else {
let json = JSON.parse(result.toString());
if( json.origin && json.origin==='default-logger-module'){
json = this.getDefaultCfg();
}
return json;
}
}
/**
* @return {Object} the default cfg
*/
getDefaultCfg(){
let envVariable = process.env.CORE_CHAINCODE_LOGGING_LEVEL;
let debugString = this.mapFabricDebug(envVariable);
return {
'file': {
'maxLevel': 'none'
},
'console': {
'maxLevel': 'silly'
},
'debug' : debugString,
'logger': './consolelogger.js',
'origin':'default-runtime-hlfv1'
};
}
/**
* Produce a valid and clean debug string
* Takes away rubbish, and only permits valid values.
* If a Fabic setting is found (see regex below) that is used in preference
*
* @param {String} string input value to process
* @return {String} clean string that can be used for setting up logging.
*/
mapCfg(string){
let DEFAULT = 'composer[warn]:*';
// first split it up into elements based on ,
let details = string.split(/[\s,]+/);
// possible composer debug string
let debugString = [];
const fabricRegex=/^(NOTICE)|(WARNING)|(ERROR)|(CRITICAL)|(INFO)|(DEBUG)$/gi;
const composerRegex=/(-?)composer\[?(info|warn|debug|error|verbose)?\]?:([\w\/\*]*)/;
// loop over each
for (let i=0; i< details.length;i++){
// valid matches are either
let e = details[i].trim();
if (e === '*'){
return DEFAULT;
}
if (e.match(composerRegex)){
debugString.push(e);
}else if (e.match(fabricRegex)){
return this.mapFabricDebug(e);
}
}
// final check - if NOTHING has turned up, then again go with the default
if (debugString.length===0){
return DEFAULT;
} else {
return debugString.join(',');
}
}
/**
* Need to map the high level fabric debug settings to a more fine grained composer level
* For reference the NPM levels, and Composers
* {
error: 0,
warn: 1,
info: 2,
verbose: 3,
debug: 4,
silly: 5
}
* @param {String} fabriclevel incomiong fabric level
* @return {String} parsed fabric level string to composer.
*/
mapFabricDebug(fabriclevel){
let level;
let debugString;
if (!fabriclevel){
level ='';
} else {
level = fabriclevel.toLowerCase().trim();
}
switch (level){
case 'critical':
debugString='composer[error]:*';
break;
case 'error':
debugString='composer[error]:*';
break;
case 'warning':
debugString='composer[warn]:*';
break;
case 'notice':
debugString='composer[info]:*';
break;
case 'info':
debugString='composer[info]:*';
break;
case 'debug':
debugString='composer[debug]:*';
break;
default:
debugString='composer[warn]:*';
break;
}
return debugString;
}
} |
JavaScript | class CaptureStream {
/**
* @param {string} deviceId Device id of currently working video device
* @param {!MediaStream} stream Capture stream
* @private
*/
constructor(deviceId, stream) {
/**
* Device id of currently working video device.
* @type {string}
* @private
*/
this.deviceId_ = deviceId;
/**
* Capture stream
* @type {!MediaStream}
* @protected
*/
this.stream_ = stream;
}
/**
* @return {!MediaStream}
* @public
*/
get stream() {
return this.stream_;
}
/**
* Closes stream.
* @public
*/
async close() {
this.stream_.getVideoTracks()[0].stop();
if (await DeviceOperator.isSupported()) {
try {
await StreamManager.getInstance().setMultipleStreamsEnabled(
this.deviceId_, false);
} catch (e) {
reportError(ErrorType.MULTIPLE_STREAMS_FAILURE, ErrorLevel.ERROR, e);
}
}
}
} |
JavaScript | class StreamManager {
/**
* @private
*/
constructor() {
/**
* MediaDeviceInfo of all available video devices.
* @type {?Promise<!Array<!MediaDeviceInfo>>}
* @private
*/
this.devicesInfo_ = null;
/**
* Camera3DeviceInfo of all available video devices. Is null on HALv1 device
* without mojo api support.
* @type {?Promise<?Array<!DeviceInfo>>}
* @private
*/
this.camera3DevicesInfo_ = null;
/**
* Listeners for real device change event.
* @type {!Array<function(!Array<!DeviceInfo>): !Promise>}
* @private
*/
this.realListeners_ = [];
/**
* Latest result of Camera3DeviceInfo of all real video devices.
* @type {!Array<!DeviceInfo>}
* @private
*/
this.realDevices_ = [];
/**
* real device id and corresponding virtual devices id mapping and it is
* only available on HALv3.
* @type {?VirtualMap}
* @private
*/
this.virtualMap_ = null;
/**
* Signal it to indicate that the virtual device is ready.
* @type {?WaitableEvent<string>}
* @private
*/
this.waitVirtual_ = null;
/**
* Filter out lagging 720p on grunt. See https://crbug.com/1122852.
* @const {!Promise<function(!VideoConfig): boolean>}
* @private
*/
this.videoConfigFilter_ = (async () => {
const board = await loadTimeData.getBoard();
return board === 'grunt' ? ({height}) => height < 720 : () => true;
})();
navigator.mediaDevices.addEventListener(
'devicechange', this.deviceUpdate.bind(this));
}
/**
* Creates a new instance of StreamManager if it is not set. Returns the
* exist instance.
* @return {!StreamManager} The singleton instance.
*/
static getInstance() {
if (instance === null) {
instance = new StreamManager();
}
return instance;
}
/**
* Registers listener to be called when state of available real devices
* changes.
* @param {function(!Array<!DeviceInfo>)} listener
*/
addRealDeviceChangeListener(listener) {
this.realListeners_.push(listener);
}
/**
* Creates extra stream according to the constraints.
* @param {!MediaStreamConstraints} constraints
* @return {!Promise<!CaptureStream>}
*/
async openCaptureStream(constraints) {
const realDeviceId = assertString(constraints.video.deviceId.exact);
if (await DeviceOperator.isSupported()) {
try {
await this.setMultipleStreamsEnabled(realDeviceId, true);
constraints.video.deviceId.exact = this.virtualMap_.virtualId;
} catch (e) {
reportError(ErrorType.MULTIPLE_STREAMS_FAILURE, ErrorLevel.ERROR, e);
}
}
const stream = await navigator.mediaDevices.getUserMedia(constraints);
return new CaptureStream(realDeviceId, stream);
}
/**
* Handling function for device changing.
*/
async deviceUpdate() {
const devices = await this.doDeviceInfoUpdate_();
if (devices === null) {
return;
}
await this.doDeviceNotify_(devices);
}
/**
* Gets devices information via mojo IPC.
* @return {?Promise<?Array<!DeviceInfo>>}
* @private
*/
async doDeviceInfoUpdate_() {
this.devicesInfo_ = this.enumerateDevices_();
this.camera3DevicesInfo_ = this.queryMojoDevicesInfo_();
try {
return await this.camera3DevicesInfo_;
} catch (e) {
console.error(e);
}
return null;
}
/**
* Notifies device changes to listeners and create a mapping for real and
* virtual device.
* @param {!Array<!DeviceInfo>} devices
* @private
*/
async doDeviceNotify_(devices) {
const isVirtual = (d) => d.v3Info !== null &&
(d.v3Info.facing === Facing.VIRTUAL_USER ||
d.v3Info.facing === Facing.VIRTUAL_ENV ||
d.v3Info.facing === Facing.VIRTUAL_EXT);
const realDevices = devices.filter((d) => !isVirtual(d));
const virtualDevices = devices.filter(isVirtual);
// We currently only support one virtual device.
assert(virtualDevices.length <= 1);
if (virtualDevices.length === 1 && this.waitVirtual_ !== null) {
this.waitVirtual_.signal(virtualDevices[0].v1Info.deviceId);
this.waitVirtual_ = null;
}
let isRealDeviceChange = false;
for (const added of this.getDifference_(realDevices, this.realDevices_)) {
toast.speak(I18nString.STATUS_MSG_CAMERA_PLUGGED, added.v1Info.label);
isRealDeviceChange = true;
}
for (const removed of this.getDifference_(this.realDevices_, realDevices)) {
toast.speak(I18nString.STATUS_MSG_CAMERA_UNPLUGGED, removed.v1Info.label);
isRealDeviceChange = true;
}
if (isRealDeviceChange) {
this.realListeners_.map((l) => l(realDevices));
}
this.realDevices_ = realDevices;
}
/**
* Computes |devices| - |devices2|.
* @param {!Array<!DeviceInfo>} devices
* @param {!Array<!DeviceInfo>} devices2
* @return {!Array<!DeviceInfo>}
*/
getDifference_(devices, devices2) {
const ids = new Set(devices2.map((d) => d.v1Info.deviceId));
return devices.filter((d) => !ids.has(d.v1Info.deviceId));
}
/**
* Enumerates all available devices and gets their MediaDeviceInfo.
* @return {!Promise<!Array<!MediaDeviceInfo>>}
* @throws {!Error}
* @private
*/
async enumerateDevices_() {
const devices = (await navigator.mediaDevices.enumerateDevices())
.filter((device) => device.kind === 'videoinput');
if (devices.length === 0) {
throw new Error('Device list empty.');
}
return devices;
}
/**
* Queries Camera3DeviceInfo of available devices through private mojo API.
* @return {!Promise<?Array<!DeviceInfo>>} Camera3DeviceInfo of available
* devices. Maybe null on HALv1 devices without supporting private mojo
* api.
* @throws {!Error} Thrown when camera unplugging happens between enumerating
* devices and querying mojo APIs with current device info results.
* @private
*/
async queryMojoDevicesInfo_() {
const deviceInfos = await this.devicesInfo_;
const videoConfigFilter = await this.videoConfigFilter_;
const isV3Supported = await DeviceOperator.isSupported();
return Promise.all(deviceInfos.map(
async (d) => ({
v1Info: d,
v3Info: isV3Supported ?
(await Camera3DeviceInfo.create(d, videoConfigFilter)) :
null,
})));
}
/**
* Enables/Disables multiple streams on target camera device. The extra
* stream will be reported as virtual video device from
* navigator.mediaDevices.enumerateDevices().
* @param {string} deviceId The id of target camera device.
* @param {boolean} enabled True for eanbling multiple streams.
*/
async setMultipleStreamsEnabled(deviceId, enabled) {
assert(await DeviceOperator.isSupported());
let waitEvent;
if (enabled) {
this.waitVirtual_ = new WaitableEvent();
waitEvent = this.waitVirtual_;
} else {
this.virtualMap_ = null;
}
const deviceOperator = await DeviceOperator.getInstance();
try {
// Mojo connection may be disconnected when closing CCA.
// It causes the disabling multiple streams request failed.
// Since camera HAL will disable all virtual devices when CCA is closed,
// we can bypass the error for this case.
// TODO(b/186179072): Remove the workaround when CCA does nothing after
// closing mojo connection.
await deviceOperator.setMultipleStreamsEnabled(deviceId, enabled);
} catch (e) {
if (enabled || e.message !== 'Message pipe closed.') {
throw e;
}
}
await this.deviceUpdate();
if (enabled) {
try {
const virtualId = await waitEvent.timedWait(3000);
this.virtualMap_ = {realId: deviceId, virtualId};
} catch (e) {
throw new Error(
`${deviceId} set multiple streams to ${enabled} failed`);
}
}
}
} |
JavaScript | class TimeUnitValue extends TimeQuantity {
constructor(value, _units) {
super(typeof value == 'number'
? value
: getUnitQuantityFrom(value, _units));
this._units = _units;
TimeUnit.assertValid(_units);
}
get value() {
return this._quantity;
}
set value(v) {
this._quantity = v;
this._resetTotal();
}
getTotalMilliseconds() {
return TimeUnit.toMilliseconds(this._quantity, this._units);
}
// To avoid confusion, the unit type can only be set once at construction.
get units() {
return this._units;
}
to(units = this.units) {
return TimeUnitValue.from(this, units);
}
static from(value, units = TimeUnit.Milliseconds) {
return new TimeUnitValue(value, units);
}
} |
JavaScript | class PlaywrightDispatcher extends _dispatcher.Dispatcher {
constructor(scope, playwright, customSelectors, preLaunchedBrowser) {
const descriptors = require('../server/deviceDescriptors');
const deviceDescriptors = Object.entries(descriptors).map(([name, descriptor]) => ({
name,
descriptor
}));
super(scope, playwright, 'Playwright', {
chromium: new _browserTypeDispatcher.BrowserTypeDispatcher(scope, playwright.chromium),
firefox: new _browserTypeDispatcher.BrowserTypeDispatcher(scope, playwright.firefox),
webkit: new _browserTypeDispatcher.BrowserTypeDispatcher(scope, playwright.webkit),
android: new _androidDispatcher.AndroidDispatcher(scope, playwright.android),
electron: new _electronDispatcher.ElectronDispatcher(scope, playwright.electron),
deviceDescriptors,
selectors: customSelectors || new _selectorsDispatcher.SelectorsDispatcher(scope, playwright.selectors),
preLaunchedBrowser
}, false);
this._socksProxy = void 0;
}
async enableSocksProxy() {
this._socksProxy = new SocksProxy(this);
this._object.options.socksProxyPort = await this._socksProxy.listen(0);
_debugLogger.debugLogger.log('proxy', `Starting socks proxy server on port ${this._object.options.socksProxyPort}`);
}
async socksConnected(params) {
var _this$_socksProxy;
(_this$_socksProxy = this._socksProxy) === null || _this$_socksProxy === void 0 ? void 0 : _this$_socksProxy.socketConnected(params);
}
async socksFailed(params) {
var _this$_socksProxy2;
(_this$_socksProxy2 = this._socksProxy) === null || _this$_socksProxy2 === void 0 ? void 0 : _this$_socksProxy2.socketFailed(params);
}
async socksData(params) {
var _this$_socksProxy3;
(_this$_socksProxy3 = this._socksProxy) === null || _this$_socksProxy3 === void 0 ? void 0 : _this$_socksProxy3.sendSocketData(params);
}
async socksError(params) {
var _this$_socksProxy4;
(_this$_socksProxy4 = this._socksProxy) === null || _this$_socksProxy4 === void 0 ? void 0 : _this$_socksProxy4.sendSocketError(params);
}
async socksEnd(params) {
var _this$_socksProxy5;
(_this$_socksProxy5 = this._socksProxy) === null || _this$_socksProxy5 === void 0 ? void 0 : _this$_socksProxy5.sendSocketEnd(params);
}
async newRequest(params, metadata) {
const request = new _fetch.GlobalAPIRequestContext(this._object, params);
return {
request: _networkDispatchers.APIRequestContextDispatcher.from(this._scope, request)
};
}
} |
JavaScript | class MediaEmbedUI extends Plugin {
/**
* @inheritDoc
*/
static get requires() {
return [ MediaEmbedEditing ];
}
/**
* @inheritDoc
*/
static get pluginName() {
return 'MediaEmbedUI';
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const command = editor.commands.get( 'mediaEmbed' );
const registry = editor.plugins.get( MediaEmbedEditing ).registry;
editor.ui.componentFactory.add( 'mediaEmbed', locale => {
const dropdown = createDropdown( locale );
const mediaForm = new MediaFormView( getFormValidators( editor.t, registry ), editor.locale );
this._setUpDropdown( dropdown, mediaForm, command, editor );
this._setUpForm( dropdown, mediaForm, command );
return dropdown;
} );
}
_setUpDropdown( dropdown, form, command ) {
const editor = this.editor;
const t = editor.t;
const button = dropdown.buttonView;
dropdown.bind( 'isEnabled' ).to( command );
dropdown.panelView.children.add( form );
button.set( {
label: t( 'Insert media' ),
icon: mediaIcon,
tooltip: true
} );
// Note: Use the low priority to make sure the following listener starts working after the
// default action of the drop-down is executed (i.e. the panel showed up). Otherwise, the
// invisible form/input cannot be focused/selected.
button.on( 'open', () => {
// Make sure that each time the panel shows up, the URL field remains in sync with the value of
// the command. If the user typed in the input, then canceled (`urlInputView#fieldView#value` stays
// unaltered) and re-opened it without changing the value of the media command (e.g. because they
// didn't change the selection), they would see the old value instead of the actual value of the
// command.
form.url = command.value || '';
form.urlInputView.fieldView.select();
form.focus();
}, { priority: 'low' } );
dropdown.on( 'submit', () => {
if ( form.isValid() ) {
editor.execute( 'mediaEmbed', form.url );
closeUI();
}
} );
dropdown.on( 'change:isOpen', () => form.resetFormStatus() );
dropdown.on( 'cancel', () => closeUI() );
function closeUI() {
editor.editing.view.focus();
dropdown.isOpen = false;
}
}
_setUpForm( dropdown, form, command ) {
form.delegate( 'submit', 'cancel' ).to( dropdown );
form.urlInputView.bind( 'value' ).to( command, 'value' );
// Form elements should be read-only when corresponding commands are disabled.
form.urlInputView.bind( 'isReadOnly' ).to( command, 'isEnabled', value => !value );
}
} |
JavaScript | class VirtualCloudNetwork extends OkitArtifact {
/*
** Create
*/
constructor (data={}, okitjson={}) {
super(okitjson);
// Configure default values
this.display_name = this.generateDefaultName(okitjson.virtual_cloud_networks.length + 1);
this.compartment_id = data.parent_id;
// Generate Cidr
this.cidr_blocks = [''];
this.dns_label = this.display_name.toLowerCase().slice(-6);
this.is_ipv6enabled = false;
this.ipv6cidr_blocks = [''];
// Update with any passed data
this.merge(data);
this.convert();
Object.defineProperty(this, 'cidr_block', {get: function() {return this.cidr_blocks[0];}, set: function(cidr) {this.cidr_blocks[0] = cidr;}, enumerable: false });
}
/*
** Conversion Routine allowing loading of old json
*/
convert() {
super.convert();
if (this.cidr_block !== undefined && this.cidr_block !== '') {
if (this.cidr_blocks === undefined || this.cidr_blocks.length === 0 || (this.cidr_blocks.length === 1 && this.cidr_blocks[0] === '')) this.cidr_blocks = [this.cidr_block];
else if (this.cidr_blocks.indexOf(this.cidr_block) < 0) this.cidr_blocks.push(this.cidr_block);
delete this.cidr_block;
}
if (this.ipv6cidr_block !== undefined && this.ipv6cidr_block !== '') {
if (this.ipv6cidr_blocks === undefined || this.ipv6cidr_blocks.length === 0 || (this.ipv6cidr_blocks.length === 1 && this.ipv6cidr_blocks[0] === '')) this.ipv6cidr_blocks = [this.ipv6cidr_block];
else if (this.ipv6cidr_blocks.indexOf(this.ipv6cidr_block) < 0) this.ipv6cidr_blocks.push(this.ipv6cidr_block);
delete this.ipv6cidr_block;
}
}
/*
** Clone Functionality
*/
clone() {
return new VirtualCloudNetwork(JSON.clone(this), this.getOkitJson());
}
/*
** Delete Processing
*/
deleteChildren() {
console.log('Deleting Children of ' + this.getArtifactReference() + ' : ' + this.display_name);
// Remove Subnets
this.getOkitJson().subnets = this.getOkitJson().subnets.filter(function(child) {
if (child.vcn_id === this.id) {
console.info('Deleting ' + child.display_name);
child.delete();
return false; // So the filter removes the element
}
return true;
}, this);
// Remove Route_tables
this.getOkitJson().route_tables = this.getOkitJson().route_tables.filter(function(child) {
if (child.vcn_id === this.id) {
console.info('Deleting ' + child.display_name);
child.delete();
return false; // So the filter removes the element
}
return true;
}, this);
// Remove Security Lists
this.getOkitJson().security_lists = this.getOkitJson().security_lists.filter(function(child) {
if (child.vcn_id === this.id) {
console.info('Deleting ' + child.display_name);
child.delete();
return false; // So the filter removes the element
}
return true;
}, this);
// Remove Internet Gateways
this.getOkitJson().internet_gateways = this.getOkitJson().internet_gateways.filter(function(child) {
if (child.vcn_id === this.id) {
console.info('Deleting ' + child.display_name);
child.delete();
return false; // So the filter removes the element
}
return true;
}, this);
// Remove NAT Gateways
this.getOkitJson().nat_gateways = this.getOkitJson().nat_gateways.filter(function(child) {
if (child.vcn_id === this.id) {
console.info('Deleting ' + child.display_name);
child.delete();
return false; // So the filter removes the element
}
return true;
}, this);
// Remove Service Gateways
this.getOkitJson().service_gateways = this.getOkitJson().service_gateways.filter(function(child) {
if (child.vcn_id === this.id) {
console.info('Deleting ' + child.display_name);
child.delete();
return false; // So the filter removes the element
}
return true;
}, this);
// Local Peering Gateways
this.getOkitJson().local_peering_gateways = this.getOkitJson().local_peering_gateways.filter(function(child) {
if (child.vcn_id === this.id) {
console.info('Deleting ' + child.display_name);
child.delete();
return false; // So the filter removes the element
}
return true;
}, this);
// Network Security Groups
this.getOkitJson().network_security_groups = this.getOkitJson().network_security_groups.filter(function(child) {
if (child.vcn_id === this.id) {
console.info('Deleting ' + child.display_name);
child.delete();
return false; // So the filter removes the element
}
return true;
}, this);
console.log();
}
/*
** Artifact Specific Functions
*/
hasUnattachedSecurityList() {
for (let security_list of this.getOkitJson().security_lists) {
if (security_list.vcn_id === this.id) {
return true;
}
}
return false;
}
hasUnattachedRouteTable() {
for (let route_table of this.getOkitJson().route_tables) {
if (route_table.vcn_id === this.id) {
return true;
}
}
return false;
}
getGateways() {
let gateways = [];
// Internet Gateways
gateways.push(...this.getInternetGateways());
// NAT Gateways
gateways.push(...this.getNATGateways());
// Local Peering Gateways
gateways.push(...this.getLocalPeeringGateways());
// Service Gateways
gateways.push(...this.getServiceGateways());
// Dynamic Routing Gateways
gateways.push(...this.getDynamicRoutingGateways());
return gateways;
}
getInternetGateways() {
let gateways = [];
// Internet Gateways
for (let gateway of this.getOkitJson().internet_gateways) {
if (gateway.vcn_id === this.id) {
gateways.push(gateway);
}
}
return gateways;
}
getNATGateways() {
let gateways = [];
// NAT Gateways
for (let gateway of this.getOkitJson().nat_gateways) {
if (gateway.vcn_id === this.id) {
gateways.push(gateway);
}
}
return gateways;
}
getLocalPeeringGateways() {
let gateways = [];
// NAT Gateways
for (let gateway of this.getOkitJson().local_peering_gateways) {
if (gateway.vcn_id === this.id) {
gateways.push(gateway);
}
}
return gateways;
}
getServiceGateways() {
let gateways = [];
// Service Gateways
for (let gateway of this.getOkitJson().service_gateways) {
if (gateway.vcn_id === this.id) {
gateways.push(gateway);
}
}
return gateways;
}
getDynamicRoutingGateways() {
let gateways = [];
// Dynamic Routing Gateways
for (let gateway of this.getOkitJson().dynamic_routing_gateways) {
if (gateway.vcn_id === this.id) {
gateways.push(gateway);
}
}
return gateways;
}
getNamePrefix() {
return super.getNamePrefix() + 'vcn';
}
/*
** Utility Methods
*/
generateCIDR() {
let vcn_cidr = '10.0.0.0/16';
let vcn_octets = vcn_cidr.split('/')[0].split('.');
let vcn_cidrs = [];
for (let vcn of this.getOkitJson().getVirtualCloudNetworks()) {
if (this.id !== vcn.id) {
vcn.cidr_blocks.forEach((cidr_block) => {vcn_cidrs.push(cidr_block.split('/')[0])});
}
}
let second_octet = 0;
let ip = '';
do {
ip = `${vcn_octets[0]}.${second_octet}.${vcn_octets[2]}.${vcn_octets[3]}`
second_octet += 1;
} while (vcn_cidrs.includes(ip));
this.cidr_blocks = [`${ip}/16`];
return this.cidr_blocks;
}
/*
** Static Functionality
*/
static getArtifactReference() {
return 'Virtual Cloud Network';
}
} |
JavaScript | class UnsubscribeEmail extends React.Component {
static getInitialProps({ query }) {
return { email: query.email, slug: query.slug, type: query.type, token: query.token };
}
static propTypes = {
/** Unsubscription email, given in URL */
email: PropTypes.string.isRequired,
/** Collective slug, given in URL */
slug: PropTypes.string.isRequired,
/** Emails type to unsubscribe ex:collective.monthlyReport, given in URL */
type: PropTypes.string.isRequired,
/** Unsubscription token, given in URL */
token: PropTypes.string.isRequired,
};
constructor(props) {
super(props);
this.state = {
state: 'unsubscribing',
};
}
async componentDidMount() {
let state, errorMessage, response;
await fetch(
`${getBaseApiUrl()}/services/email/unsubscribe/${this.props.email}/${this.props.slug}/${this.props.type}/${
this.props.token
}`,
).then(res => {
response = res.json();
});
response.then(res => {
if (res.error) {
state = 'error';
errorMessage = res.error.message;
} else {
state = 'success';
}
this.setState({ state: state, errorMessage: errorMessage });
});
}
getIconColor(state) {
if (state === 'success') {
return '#00A34C';
} else if (state === 'error') {
return '#CC1836';
}
}
render() {
return (
<Page title="Unsubscribe Email">
<Container
display="flex"
py={[5, 6]}
px={2}
flexDirection="column"
alignItems="center"
background="linear-gradient(180deg, #EBF4FF, #FFFFFF)"
>
<Box my={3}>
<Email size={42} color={this.getIconColor(this.state.state)} />
</Box>
{this.state.state === 'success' && (
<MessageBox mb={3} type="success" withIcon>
<FormattedMessage id="unsubscribe.success" defaultMessage="You've unsubscribed successfully!" />
</MessageBox>
)}
{this.state.state === 'unsubscribing' && (
<MessageBox mb={3} type="white" withIcon>
<FormattedMessage id="unsubscribe.unsubscribing" defaultMessage="Unsubscribing your email..." />
</MessageBox>
)}
{this.state.state === 'error' && (
<MessageBox mb={3} type="error" withIcon>
<span>{this.state.errorMessage}</span>
</MessageBox>
)}
</Container>
</Page>
);
}
} |
JavaScript | class Shop {
constructor(shopInfoDB) {
numberOfShops +=1;
this.shopName = shopInfoDB[numberOfShops];
this.shopNumberOfItems = shopNumberOfItems;
for (let index = 0; index < shopNumberOfItems; index++) {
shopProducts[index] = new Product();
}
}
} |
JavaScript | class WT_GeoPoint {
/**
* @param {Number} lat - the latitude, in degrees.
* @param {Number} long - the longitude, in degrees.
*/
constructor(lat, long) {
this.set(lat, long);
this._readonly = new WT_GeoPointReadOnly(this);
}
/**
* @readonly
* @property {Number} lat - the latitude of this point, in degrees.
* @type {Number}
*/
get lat() {
return this._lat;
}
/**
* @readonly
* @property {Number} long - the longitude of this point, in degrees.
* @type {Number}
*/
get long() {
return this._long;
}
static _parseArgs(_1, _2) {
let returnValue = undefined;
if (_1 !== undefined && typeof _1.lat === "number" && typeof _1.long === "number") {
WT_GeoPoint._tempValue.lat = _1.lat;
WT_GeoPoint._tempValue.long = _1.long;
returnValue = WT_GeoPoint._tempValue;
} else if (typeof _1 === "number" && typeof _2 === "number") {
WT_GeoPoint._tempValue.lat = _1;
WT_GeoPoint._tempValue.long = _2;
returnValue = WT_GeoPoint._tempValue;
}
return returnValue;
}
/**
* Sets this point's coordinate values. This method takes either one or two arguments. The one-argument version takes a single object
* with .lat and .long properties. The two-argument version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the new coordinate values, or the new latitude
* value.
* @param {Number} [arg2] - the new longitude value.
* @returns {WT_GeoPoint} this point, after it has been changed.
*/
set(arg1, arg2) {
let value = WT_GeoPoint._parseArgs(arg1, arg2);
if (value) {
let lat = WT_GeoPoint._toPlusMinus180(value.lat);
let long = WT_GeoPoint._toPlusMinus180(value.long);
if (Math.abs(lat) > 90) {
lat = 180 - lat;
lat = WT_GeoPoint._toPlusMinus180(lat);
long += 180;
long = WT_GeoPoint._toPlusMinus180(long);
}
this._lat = lat;
this._long = long;
this._elevation = value.elevation;
}
return this;
}
/**
* Sets this point's coordinate values from a cartesian position vector. By convention, in the cartesian coordinate system the
* origin is at the center of the Earth, the positive x-axis passes through 0 degrees N, 0 degrees E, and the positive z-axis
* passes through the north pole.
* @param {WT_GVector3} vector - a position vector defining the new coordinates.
* @returns {WT_GeoPoint} this point, after it has been changed.
*/
setFromCartesian(vector) {
return this.set(90 - vector.theta * Avionics.Utils.RAD2DEG, vector.phi * Avionics.Utils.RAD2DEG);
}
/**
* Calculates the great-circle distance between this point and another point. This method takes either one or two arguments.
* The one-argument version takes a single object with .lat and .long properties. The two-argument version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the great-circle distance to the other point, in great-arc radians.
*/
distance(arg1, arg2) {
let other = WT_GeoPoint._parseArgs(arg1, arg2);
if (other) {
let lat1 = this.lat * Avionics.Utils.DEG2RAD;
let lat2 = other.lat * Avionics.Utils.DEG2RAD;
let long1 = this.long * Avionics.Utils.DEG2RAD;
let long2 = other.long * Avionics.Utils.DEG2RAD;
let sinHalfDeltaLat = Math.sin((lat2 - lat1) / 2);
let sinHalfDeltaLong = Math.sin((long2 - long1) / 2);
let a = sinHalfDeltaLat * sinHalfDeltaLat + Math.cos(lat1) * Math.cos(lat2) * sinHalfDeltaLong * sinHalfDeltaLong;
return 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
} else {
return undefined;
}
}
/**
* Calculates the distance along the rhumb line connecting this point with another point. This method takes either one or two
* arguments. The one-argument version takes a single object with .lat and .long properties. The two-argument version takes
* two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the rhumb-line distance to the other point, in great-arc radians.
*/
distanceRhumb(arg1, arg2) {
let other = WT_GeoPoint._parseArgs(arg1, arg2);
if (other) {
let lat1 = this.lat * Avionics.Utils.DEG2RAD;
let lat2 = other.lat * Avionics.Utils.DEG2RAD;
let long1 = this.long * Avionics.Utils.DEG2RAD;
let long2 = other.long * Avionics.Utils.DEG2RAD;
let deltaLat = lat2 - lat1;
let deltaLong = long2 - long1;
let deltaPsi = WT_GeoPoint._deltaPsi(lat1, lat2);
let correction = WT_GeoPoint._rhumbCorrection(deltaPsi, lat1, lat2);
if (Math.abs(deltaLong) > Math.PI) {
deltaLong += -Math.sign(deltaLong) * 2 * Math.PI;
}
return Math.sqrt(deltaLat * deltaLat + correction * correction * deltaLong * deltaLong);
} else {
return undefined;
}
}
/**
* Offsets this point by an initial bearing and distance along a great circle. The operation can either be performed in-place
* or a new WT_GeoPoint object can be returned.
* @param {Number} bearing - the initial bearing (forward azimuth) by which to offset.
* @param {Number} distance - the distance, in great-arc radians, by which to offset.
* @param {Boolean} [mutate] - whether to perform the operation in place.
* @returns {WT_GeoPoint} the offset point, either as a new WT_GeoPoint object or this point after it has been changed.
*/
offset(bearing, distance, mutate) {
let lat = this.lat * Avionics.Utils.DEG2RAD;
let long = this.long * Avionics.Utils.DEG2RAD;
let sinLat = Math.sin(lat);
let cosLat = Math.cos(lat);
let sinBearing = Math.sin(bearing * Avionics.Utils.DEG2RAD);
let cosBearing = Math.cos(bearing * Avionics.Utils.DEG2RAD);
let angularDistance = distance;
let sinAngularDistance = Math.sin(angularDistance);
let cosAngularDistance = Math.cos(angularDistance);
let offsetLatRad = Math.asin(sinLat * cosAngularDistance + cosLat * sinAngularDistance * cosBearing);
let offsetLongDeltaRad = Math.atan2(sinBearing * sinAngularDistance * cosLat, cosAngularDistance - sinLat * Math.sin(offsetLatRad));
let offsetLat = offsetLatRad * Avionics.Utils.RAD2DEG;
let offsetLong = (long + offsetLongDeltaRad) * Avionics.Utils.RAD2DEG;
if (mutate) {
return this.set(offsetLat, offsetLong);
} else {
return new WT_GeoPoint(offsetLat, offsetLong);
}
}
/**
* Offsets this point by a constant bearing and distance along a rhumb line. The operation can either be performed in-place
* or a new WT_GeoPoint object can be returned.
* @param {Number} bearing - the bearing by which to offset.
* @param {Number} distance - the distance, in great-arc radians, by which to offset.
* @param {Boolean} [mutate] - whether to perform the operation in place.
* @returns {WT_GeoPoint} the offset point, either as a new WT_GeoPoint object or this point after it has been changed.
*/
offsetRhumb(bearing, distance, mutate) {
let lat = this.lat * Avionics.Utils.DEG2RAD;
let long = this.long * Avionics.Utils.DEG2RAD;
let bearingRad = bearing * Avionics.Utils.DEG2RAD;
let deltaLat = distance * Math.cos(bearingRad);
let offsetLat = lat + deltaLat;
if (Math.abs(offsetLat) >= Math.PI / 2) {
// you can't technically go past the poles along a rhumb line, so we will simply terminate the path at the pole
offsetLat = Math.sign(offsetLat) * 90;
offsetLong = 0; // since longitude is meaningless at the poles, we'll arbitrarily pick a longitude of 0 degrees.
} else {
let deltaPsi = WT_GeoPoint._deltaPsi(lat, offsetLat);
let correction = WT_GeoPoint._rhumbCorrection(deltaPsi, lat, offsetLat);
let deltaLong = distance * Math.sin(bearingRad) / correction;
let offsetLong = long + deltaLong;
offsetLat *= Avionics.Utils.RAD2DEG;
offsetLong *= Avionics.Utils.RAD2DEG;
}
if (mutate) {
return this.set(offsetLat, offsetLong);
} else {
return new WT_GeoPoint(offsetLat, offsetLong);
}
}
_calculateBearing(origin, destination) {
let lat1 = origin.lat * Avionics.Utils.DEG2RAD;
let lat2 = destination.lat * Avionics.Utils.DEG2RAD;
let long1 = origin.long * Avionics.Utils.DEG2RAD;
let long2 = destination.long * Avionics.Utils.DEG2RAD;
let cosLat2 = Math.cos(lat2);
let x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * cosLat2 * Math.cos(long2 - long1);
let y = Math.sin(long2 - long1) * cosLat2;
let bearing = Math.atan2(y, x) * Avionics.Utils.RAD2DEG;
return (bearing + 360) % 360;
}
/**
* Calculates the initial bearing (forward azimuth) from this point to another point along the great circle connecting the two.
* This method takes either one or two arguments. The one-argument version takes a single object with .lat, .long properties.
* The two-argument version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the initial bearing to the other point, in degrees.
*/
bearingTo(arg1, arg2) {
let other = WT_GeoPoint._parseArgs(arg1, arg2, 0);
if (other) {
return this._calculateBearing(this, other);
} else {
return undefined;
}
}
/**
* Calculates the final bearing from another point to this point (i.e. the back azimuth from this point to the other point)
* along the great circle connecting the two. This method takes either one or two arguments. The one-argument version takes
* a single object with .lat, .long properties. The two-argument version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the final bearing from the other point, in degrees.
*/
bearingFrom(arg1, arg2) {
let other = WT_GeoPoint._parseArgs(arg1, arg2, 0);
if (other) {
return (this._calculateBearing(this, other) + 180) % 360;
} else {
return undefined;
}
}
/**
* Calculates the constant bearing to another point to this point along the rhumb line connecting the two. This method takes
* either one or two arguments. The one-argument version takes a single object with .lat, .long properties. The two-argument
* version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the constant bearing to the other point, in degrees.
*/
bearingRhumb(arg1, arg2) {
let other = WT_GeoPoint._parseArgs(arg1, arg2, 0);
if (other) {
let lat1 = this.lat * Avionics.Utils.DEG2RAD;
let long1 = this.long * Avionics.Utils.DEG2RAD;
let lat2 = other.lat * Avionics.Util.DEG2RAD;
let long2 = other.long * Avionics.Util.DEG2RAD;
let deltaLong = long2 - long1;
let deltaPsi = WT_GeoPoint._deltaPsi(lat1, lat2);
if (Math.abs(deltaLong) > Math.PI) {
deltaLong += -Math.sign(deltaLong) * 2 * Math.PI;
}
return Math.atan2(deltaLong, deltaPsi) * Avionics.Utils.RAD2DEG;
} else {
return undefined;
}
}
/**
* Calculates the cartesian (x, y, z) representation of this point, in units of great-arc radians, and returns the result.
* By convention, in the cartesian coordinate system the origin is at the center of the Earth, the positive x-axis passes through
* 0 degrees N, 0 degrees E, and the positive z-axis passes through the north pole.
* @param {WT_GVector3} [reference] - a WT_GVector3 object in which to store the results. If this argument is not supplied,
* a new WT_GVector3 object will be created.
* @returns {WT_GVector3} the cartesian representation of this point.
*/
cartesian(reference) {
if (reference) {
return reference.setFromSpherical(1, (90 - this.lat) * Avionics.Utils.DEG2RAD, this.long * Avionics.Utils.DEG2RAD);
} else {
return WT_GVector3.createFromSpherical(1, (90 - this.lat) * Avionics.Utils.DEG2RAD, this.long * Avionics.Utils.DEG2RAD);
}
}
/**
* Checks whether this point is equal to another point. Two points are considered equal if and only if they occupy the same location.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Boolean} whether this point is equal to the other point.
*/
equals(arg1, arg2, arg3) {
let other = WT_GeoPoint._parseArgs(arg1, arg2);
if (other) {
return Math.abs(this.lat - other.lat) + Math.abs(this.long - other.long) <= WT_GeoPoint.EQUALITY_TOLERANCE;
} else {
return false;
}
}
/**
* Copies this point.
* @returns {WT_GeoPoint} a copy of this point.
*/
copy() {
return new WT_GeoPoint(this.lat, this.long);
}
/**
* Gets a read-only version of this point. The read-only version is updated as this point is changed. Attempting to call
* any mutating method on the read-only version will create and return a mutated copy of this point instead.
* @returns {WT_GeoPointReadOnly} a read-only version of this point.
*/
readonly() {
return this._readonly;
}
static _toPlusMinus180(value) {
return ((value % 360) + 540) % 360 - 180;
}
static _deltaPsi(latRad1, latRad2) {
return Math.log(Math.tan(latRad2 / 2 + Math.PI / 4) / Math.tan(latRad1 / 2 + Math.PI / 4));
}
static _rhumbCorrection(deltaPsi, latRad1, latRad2) {
return Math.abs(deltaPsi) > 1e-12 ? (latRad2 - latRad1) / deltaPsi : Math.cos(lat1);
}
} |
JavaScript | class WT_GeoPointReadOnly {
/**
* @param {WT_GeoPoint} source
*/
constructor(source) {
this._source = source;
}
/**
* @readonly
* @property {Number} lat - the latitude of this point, in degrees.
* @type {Number}
*/
get lat() {
return this._source.lat;
}
/**
* @readonly
* @property {Number} long - the longitude of this point, in degrees.
* @type {Number}
*/
get long() {
return this._source.long;
}
/**
* Copies this point and sets the copy's coordinate values. This method takes either one or two arguments. The one-argument
* version takes a single object with .lat and .long properties. The two-argument version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the new coordinate values, or the new latitude
* value.
* @param {Number} [arg2] - the new longitude value.
* @returns {WT_GeoPoint} this point, after it has been changed.
*/
set(arg1, arg2) {
return this._source.copy().set(arg1, arg2);
}
/**
* Copies this point and sets the copy's coordinate values from a cartesian position vector. By convention, in the cartesian
* coordinate system the origin is at the center of the Earth, the positive x-axis passes through 0 degrees N, 0 degrees E,
* and the positive z-axis passes through the north pole.
* @param {WT_GVector3} vector - a position vector defining the new coordinates.
* @returns {WT_GeoPoint} this point, after it has been changed.
*/
setFromCartesian(vector) {
return this._source.copy().setFromCartesian(vector);
}
/**
* Calculates the great-circle distance between this point and another point. This method takes either one or two arguments.
* The one-argument version takes a single object with .lat and .long properties. The two-argument version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the great-circle distance to the other point, in great-arc radians.
*/
distance(arg1, arg2) {
return this._source.distance(arg1, arg2);
}
/**
* Calculates the distance along the rhumb line connecting this point with another point. This method takes either one or two
* arguments. The one-argument version takes a single object with .lat and .long properties. The two-argument version takes
* two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the rhumb-line distance to the other point, in great-arc radians.
*/
distanceRhumb(arg1, arg2) {
return this._source.distanceRhumb(arg1, arg2);
}
/**
* Offsets this point by an initial bearing and distance along a great-circle. The operation can either be performed in-place
* or a new WT_GeoPoint object can be returned.
* @param {Number} bearing - the initial bearing (forward azimuth) by which to offset.
* @param {Number} distance - the distance, in great-arc radians, by which to offset.
* @returns {WT_GeoPoint} the offset point.
*/
offset(bearing, distance) {
return this._source.offset(bearing, distance, false);
}
/**
* Offsets this point by a constant bearing and distance along a rhumb line. The operation can either be performed in-place
* or a new WT_GeoPoint object can be returned.
* @param {Number} bearing - the bearing by which to offset.
* @param {Number} distance - the distance, in great-arc radians, by which to offset.
* @returns {WT_GeoPoint} the offset point, either as a new WT_GeoPoint object or this point after it has been changed.
*/
offsetRhumb(bearing, distance) {
return this._source.offsetRhumb(bearing, distance, false);
}
/**
* Calculates the initial bearing (forward azimuth) from this point to another point along the great circle connecting the two.
* This method takes either one or two arguments. The one-argument version takes a single object with .lat, .long properties.
* The two-argument version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the initial bearing to the other point, in degrees.
*/
bearingTo(arg1, arg2) {
return this._source.bearingTo(arg1, arg2);
}
/**
* Calculates the final bearing from another point to this point (i.e. the back azimuth from this point to the other point)
* along the great circle connecting the two. This method takes either one or two arguments. The one-argument version takes
* a single object with .lat, .long properties. The two-argument version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the final bearing from the other point, in degrees.
*/
bearingFrom(arg1, arg2) {
return this._source.bearingFrom(arg1, arg2);
}
/**
* Calculates the constant bearing to another point to this point along the rhumb line connecting the two. This method takes
* either one or two arguments. The one-argument version takes a single object with .lat, .long properties. The two-argument
* version takes two numbers.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Number} the constant bearing to the other point, in degrees.
*/
bearingRhumb(arg1, arg2) {
return this._source.bearingRhumb(arg1, arg2);
}
/**
* Calculates the cartesian (x, y, z) representation of this point, in units of great-arc radians, and returns the result.
* By convention, in the cartesian coordinate system the origin is at the center of the Earth, the positive x-axis passes through
* 0 degrees N, 0 degrees E, and the positive z-axis passes through the north pole.
* @param {WT_GVector3} [reference] - a WT_GVector3 object in which to store the results. If this argument is not supplied,
* a new WT_GVector3 object will be created.
* @returns {WT_GVector3} the cartesian representation of this point.
*/
cartesian(reference) {
return this._source.cartesian(reference);
}
/**
* Checks whether this point is equal to another point. Two points are considered equal if and only if they occupy the same location.
* @param {{lat:Number, long:Number}|Number} arg1 - an object defining the coordinate values of the other point, or the
* latitude value of the other point.
* @param {Number} [arg2] - the longitude value of the other point.
* @returns {Boolean} whether this point is equal to the other point.
*/
equals(arg1, arg2) {
return this._source.equals(arg1, arg2);
}
/**
* Copies this point.
* @returns {WT_GeoPoint} a copy of this point.
*/
copy() {
return this._source.copy();
}
/**
* Gets a read-only version of this point. The read-only version is updated as this point is changed. Attempting to call
* any mutating method on the read-only version will create and return a mutated copy of this point instead.
* @returns {WT_GeoPointReadOnly} a read-only version of this point.
*/
readonly() {
return this;
}
} |
JavaScript | class ErrorBar extends Component {
constructor(props){
super(props);
this.state = {
}
}
render() {
return (
<div className={style.ErrorBar}>
<img src={error} className={style.ErrorIcon} alt=""/>
<div className={style.ErrorMessage}>
{this.props.message}
</div>
<div className={style.ErrorClose}
onClick={this.props.clearError}>
close
</div>
</div>
);
}
} |
JavaScript | class RpcSchema {
constructor() {
this._ajv = new Ajv({ verbose: true, schemaId: 'auto', allErrors: true });
this._ajv.addKeyword('idate', schema_utils.KEYWORDS.idate);
this._ajv.addKeyword('objectid', schema_utils.KEYWORDS.objectid);
if (global.window === global ||
(process.argv[1] && process.argv[1].includes('src/test/qa'))) {
this._ajv.addKeyword('wrapper', schema_utils.KEYWORDS.wrapper_check_only);
} else {
this._ajv.addKeyword('wrapper', schema_utils.KEYWORDS.wrapper);
}
this._client_factory = null;
this._compiled = false;
}
get compiled() {
return this._compiled;
}
/**
*
* register_api
*
*/
register_api(api) {
assert(!this[api.id], 'RPC: api already registered ' + api.id);
assert(!this._compiled, 'RPC: schema is already compiled');
_.each(api.definitions, schema => {
schema_utils.strictify(schema, {
additionalProperties: false
});
});
_.each(api.methods, method_api => {
schema_utils.strictify(method_api.params, {
additionalProperties: false
});
schema_utils.strictify(method_api.reply, {
additionalProperties: false
});
});
try {
this._ajv.addSchema(api);
} catch (err) {
dbg.error('register_api: failed compile api schema', api, err.stack || err);
throw err;
}
this[api.id] = api;
}
compile() {
if (this._compiled) {
return;
}
_.each(this, api => {
if (!api || !api.id || api.id[0] === '_') return;
_.each(api.methods, (method_api, method_name) => {
method_api.api = api;
method_api.name = method_name;
method_api.fullname = api.id + '#/methods/' + method_name;
method_api.method = method_api.method || 'POST';
assert(method_api.method in VALID_HTTP_METHODS,
'RPC: unexpected http method: ' +
method_api.method + ' for ' + method_api.fullname);
try {
method_api.params_validator = method_api.params ?
this._ajv.compile({ $ref: method_api.fullname + '/params' }) :
schema_utils.empty_schema_validator;
method_api.reply_validator = method_api.reply ?
this._ajv.compile({ $ref: method_api.fullname + '/reply' }) :
schema_utils.empty_schema_validator;
} catch (err) {
dbg.error('register_api: failed compile method params/reply refs',
method_api, err.stack || err);
throw err;
}
method_api.validate_params = (params, desc) => {
let result = method_api.params_validator(params);
if (!result) {
dbg.error('INVALID_SCHEMA_PARAMS', desc, method_api.fullname,
'ERRORS:', util.inspect(method_api.params_validator.errors, true, null, true),
'PARAMS:', util.inspect(params, true, null, true));
throw new RpcError('INVALID_SCHEMA_PARAMS', `INVALID_SCHEMA_PARAMS ${desc} ${method_api.fullname}`);
}
};
method_api.validate_reply = (reply, desc) => {
let result = method_api.reply_validator(reply);
if (!result) {
dbg.error('INVALID_SCHEMA_REPLY', desc, method_api.fullname,
'ERRORS:', util.inspect(method_api.reply_validator.errors, true, null, true),
'REPLY:', util.inspect(reply, true, null, true));
throw new RpcError('INVALID_SCHEMA_REPLY', `INVALID_SCHEMA_REPLY ${desc} ${method_api.fullname}`);
}
};
});
});
this._generate_client_factory();
this._compiled = true;
}
new_client(rpc, options) {
assert(this._compiled, 'RPC: schema is not compiled');
return this._client_factory(rpc, options);
}
_generate_client_factory() {
const client_proto = {
RPC_BUFFERS,
async create_auth_token(params) {
const res = await this.auth.create_auth(params);
this.options.auth_token = res.token;
return res;
},
async create_access_key_auth(params) {
const res = await this.auth.create_access_key_auth(params);
this.options.auth_token = res.token;
return res;
},
async create_k8s_auth(params) {
const res = await this.auth.create_k8s_auth(params);
this.options.auth_token = res.token;
return res;
},
_invoke_api(api, method_api, params, options) {
options = Object.assign(
Object.create(this.options),
options
);
return this.rpc._request(api, method_api, params, options);
}
};
for (const api of Object.values(this)) {
if (!api || !api.id || api.id[0] === '_') {
continue;
}
// Skip common api and other apis that do not define methods.
if (!api.methods) {
continue;
}
const name = api.id.replace(/_api$/, '');
if (name === 'rpc' || name === 'options') {
throw new Error('ILLEGAL API ID');
}
const api_proto = {};
for (const [method_name, method_api] of Object.entries(api.methods)) {
// The following getter is defined as a function and not as an arrow function
// to prevent the capture of "this" from the surrounding context.
// When invoked, "this" should be the client object. Using an arrow function
// will capture the "this" defined in the invocation of "_generate_client_factory"
// which is the schema object.
api_proto[method_name] = function(params, options) {
return this.client._invoke_api(api, method_api, params, options);
};
}
// The following getter is defined as a function and not as an arrow function
// on purpose. please see the last comment (above) for a detailed explanation.
Object.defineProperty(client_proto, name, {
enumerable: true,
get: function() {
const api_instance = Object.create(api_proto);
api_instance.client = this;
return Object.freeze(api_instance);
}
});
}
this._client_factory = (rpc, options) => {
const client = Object.create(client_proto);
client.rpc = rpc;
client.options = options ? Object.create(options) : {};
return client;
};
}
} |
JavaScript | class MatDatepickerInputHarnessBase extends ComponentHarness {
/** Whether the input is disabled. */
isDisabled() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).getProperty('disabled');
});
}
/** Whether the input is required. */
isRequired() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).getProperty('required');
});
}
/** Gets the value of the input. */
getValue() {
return __awaiter(this, void 0, void 0, function* () {
// The "value" property of the native input is always defined.
return (yield (yield this.host()).getProperty('value'));
});
}
/**
* Sets the value of the input. The value will be set by simulating
* keypresses that correspond to the given value.
*/
setValue(newValue) {
return __awaiter(this, void 0, void 0, function* () {
const inputEl = yield this.host();
yield inputEl.clear();
// We don't want to send keys for the value if the value is an empty
// string in order to clear the value. Sending keys with an empty string
// still results in unnecessary focus events.
if (newValue) {
yield inputEl.sendKeys(newValue);
}
// @breaking-change 12.0.0 Remove null check once `dispatchEvent` is a required method.
if (inputEl.dispatchEvent) {
yield inputEl.dispatchEvent('change');
}
});
}
/** Gets the placeholder of the input. */
getPlaceholder() {
return __awaiter(this, void 0, void 0, function* () {
return (yield (yield this.host()).getProperty('placeholder'));
});
}
/**
* Focuses the input and returns a promise that indicates when the
* action is complete.
*/
focus() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).focus();
});
}
/**
* Blurs the input and returns a promise that indicates when the
* action is complete.
*/
blur() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).blur();
});
}
/** Whether the input is focused. */
isFocused() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).isFocused();
});
}
/** Gets the formatted minimum date for the input's value. */
getMin() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).getAttribute('min');
});
}
/** Gets the formatted maximum date for the input's value. */
getMax() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).getAttribute('max');
});
}
} |
JavaScript | class MatCalendarCellHarness extends ComponentHarness {
constructor() {
super(...arguments);
/** Reference to the inner content element inside the cell. */
this._content = this.locatorFor('.mat-calendar-body-cell-content');
}
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatCalendarCellHarness`
* that meets certain criteria.
* @param options Options for filtering which cell instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return new HarnessPredicate(MatCalendarCellHarness, options)
.addOption('text', options.text, (harness, text) => {
return HarnessPredicate.stringMatches(harness.getText(), text);
})
.addOption('selected', options.selected, (harness, selected) => __awaiter(this, void 0, void 0, function* () {
return (yield harness.isSelected()) === selected;
}))
.addOption('active', options.active, (harness, active) => __awaiter(this, void 0, void 0, function* () {
return (yield harness.isActive()) === active;
}))
.addOption('disabled', options.disabled, (harness, disabled) => __awaiter(this, void 0, void 0, function* () {
return (yield harness.isDisabled()) === disabled;
}))
.addOption('today', options.today, (harness, today) => __awaiter(this, void 0, void 0, function* () {
return (yield harness.isToday()) === today;
}))
.addOption('inRange', options.inRange, (harness, inRange) => __awaiter(this, void 0, void 0, function* () {
return (yield harness.isInRange()) === inRange;
}))
.addOption('inComparisonRange', options.inComparisonRange, (harness, inComparisonRange) => __awaiter(this, void 0, void 0, function* () {
return (yield harness.isInComparisonRange()) === inComparisonRange;
}))
.addOption('inPreviewRange', options.inPreviewRange, (harness, inPreviewRange) => __awaiter(this, void 0, void 0, function* () {
return (yield harness.isInPreviewRange()) === inPreviewRange;
}));
}
/** Gets the text of the calendar cell. */
getText() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this._content()).text();
});
}
/** Gets the aria-label of the calendar cell. */
getAriaLabel() {
return __awaiter(this, void 0, void 0, function* () {
// We're guaranteed for the `aria-label` to be defined
// since this is a private element that we control.
return (yield this.host()).getAttribute('aria-label');
});
}
/** Whether the cell is selected. */
isSelected() {
return __awaiter(this, void 0, void 0, function* () {
const host = yield this.host();
return (yield host.getAttribute('aria-selected')) === 'true';
});
}
/** Whether the cell is disabled. */
isDisabled() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('disabled');
});
}
/** Whether the cell is currently activated using keyboard navigation. */
isActive() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('active');
});
}
/** Whether the cell represents today's date. */
isToday() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this._content()).hasClass('mat-calendar-body-today');
});
}
/** Selects the calendar cell. Won't do anything if the cell is disabled. */
select() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).click();
});
}
/** Hovers over the calendar cell. */
hover() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).hover();
});
}
/** Moves the mouse away from the calendar cell. */
mouseAway() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).mouseAway();
});
}
/** Focuses the calendar cell. */
focus() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).focus();
});
}
/** Removes focus from the calendar cell. */
blur() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).blur();
});
}
/** Whether the cell is the start of the main range. */
isRangeStart() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('range-start');
});
}
/** Whether the cell is the end of the main range. */
isRangeEnd() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('range-end');
});
}
/** Whether the cell is part of the main range. */
isInRange() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('in-range');
});
}
/** Whether the cell is the start of the comparison range. */
isComparisonRangeStart() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('comparison-start');
});
}
/** Whether the cell is the end of the comparison range. */
isComparisonRangeEnd() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('comparison-end');
});
}
/** Whether the cell is inside of the comparison range. */
isInComparisonRange() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('in-comparison-range');
});
}
/** Whether the cell is the start of the preview range. */
isPreviewRangeStart() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('preview-start');
});
}
/** Whether the cell is the end of the preview range. */
isPreviewRangeEnd() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('preview-end');
});
}
/** Whether the cell is inside of the preview range. */
isInPreviewRange() {
return __awaiter(this, void 0, void 0, function* () {
return this._hasState('in-preview');
});
}
/** Returns whether the cell has a particular CSS class-based state. */
_hasState(name) {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).hasClass(`mat-calendar-body-${name}`);
});
}
} |
JavaScript | class MatCalendarHarness extends ComponentHarness {
constructor() {
super(...arguments);
/** Queries for the calendar's period toggle button. */
this._periodButton = this.locatorFor('.mat-calendar-period-button');
}
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatCalendarHarness`
* that meets certain criteria.
* @param options Options for filtering which calendar instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return new HarnessPredicate(MatCalendarHarness, options);
}
/**
* Gets a list of cells inside the calendar.
* @param filter Optionally filters which cells are included.
*/
getCells(filter = {}) {
return __awaiter(this, void 0, void 0, function* () {
return this.locatorForAll(MatCalendarCellHarness.with(filter))();
});
}
/** Gets the current view that is being shown inside the calendar. */
getCurrentView() {
return __awaiter(this, void 0, void 0, function* () {
if (yield this.locatorForOptional('mat-multi-year-view')()) {
return 2 /* MULTI_YEAR */;
}
if (yield this.locatorForOptional('mat-year-view')()) {
return 1 /* YEAR */;
}
return 0 /* MONTH */;
});
}
/** Gets the label of the current calendar view. */
getCurrentViewLabel() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this._periodButton()).text();
});
}
/** Changes the calendar view by clicking on the view toggle button. */
changeView() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this._periodButton()).click();
});
}
/** Goes to the next page of the current view (e.g. next month when inside the month view). */
next() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.locatorFor('.mat-calendar-next-button')()).click();
});
}
/**
* Goes to the previous page of the current view
* (e.g. previous month when inside the month view).
*/
previous() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.locatorFor('.mat-calendar-previous-button')()).click();
});
}
/**
* Selects a cell in the current calendar view.
* @param filter An optional filter to apply to the cells. The first cell matching the filter
* will be selected.
*/
selectCell(filter = {}) {
return __awaiter(this, void 0, void 0, function* () {
const cells = yield this.getCells(filter);
if (!cells.length) {
throw Error(`Cannot find calendar cell matching filter ${JSON.stringify(filter)}`);
}
yield cells[0].select();
});
}
} |
JavaScript | class DatepickerTriggerHarnessBase extends ComponentHarness {
/** Opens the calendar if the trigger is enabled and it has a calendar. */
openCalendar() {
return __awaiter(this, void 0, void 0, function* () {
const [isDisabled, hasCalendar] = yield parallel(() => [this.isDisabled(), this.hasCalendar()]);
if (!isDisabled && hasCalendar) {
return this._openCalendar();
}
});
}
/** Closes the calendar if it is open. */
closeCalendar() {
return __awaiter(this, void 0, void 0, function* () {
if (yield this.isCalendarOpen()) {
yield closeCalendar(getCalendarId(this.host()), this.documentRootLocatorFactory());
// This is necessary so that we wait for the closing animation to finish in touch UI mode.
yield this.forceStabilize();
}
});
}
/** Gets whether there is a calendar associated with the trigger. */
hasCalendar() {
return __awaiter(this, void 0, void 0, function* () {
return (yield getCalendarId(this.host())) != null;
});
}
/**
* Gets the `MatCalendarHarness` that is associated with the trigger.
* @param filter Optionally filters which calendar is included.
*/
getCalendar(filter = {}) {
return __awaiter(this, void 0, void 0, function* () {
return getCalendar(filter, this.host(), this.documentRootLocatorFactory());
});
}
} |
JavaScript | class MatDatepickerInputHarness extends MatDatepickerInputHarnessBase {
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatDatepickerInputHarness`
* that meets certain criteria.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return getInputPredicate(MatDatepickerInputHarness, options);
}
/** Gets whether the calendar associated with the input is open. */
isCalendarOpen() {
return __awaiter(this, void 0, void 0, function* () {
// `aria-owns` is set only if there's an open datepicker so we can use it as an indicator.
const host = yield this.host();
return (yield host.getAttribute('aria-owns')) != null;
});
}
/** Opens the calendar associated with the input. */
openCalendar() {
return __awaiter(this, void 0, void 0, function* () {
const [isDisabled, hasCalendar] = yield parallel(() => [this.isDisabled(), this.hasCalendar()]);
if (!isDisabled && hasCalendar) {
// Alt + down arrow is the combination for opening the calendar with the keyboard.
const host = yield this.host();
return host.sendKeys({ alt: true }, TestKey.DOWN_ARROW);
}
});
}
/** Closes the calendar associated with the input. */
closeCalendar() {
return __awaiter(this, void 0, void 0, function* () {
if (yield this.isCalendarOpen()) {
yield closeCalendar(getCalendarId(this.host()), this.documentRootLocatorFactory());
// This is necessary so that we wait for the closing animation to finish in touch UI mode.
yield this.forceStabilize();
}
});
}
/** Whether a calendar is associated with the input. */
hasCalendar() {
return __awaiter(this, void 0, void 0, function* () {
return (yield getCalendarId(this.host())) != null;
});
}
/**
* Gets the `MatCalendarHarness` that is associated with the trigger.
* @param filter Optionally filters which calendar is included.
*/
getCalendar(filter = {}) {
return __awaiter(this, void 0, void 0, function* () {
return getCalendar(filter, this.host(), this.documentRootLocatorFactory());
});
}
} |
JavaScript | class MatDatepickerToggleHarness extends DatepickerTriggerHarnessBase {
constructor() {
super(...arguments);
/** The clickable button inside the toggle. */
this._button = this.locatorFor('button');
}
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatDatepickerToggleHarness` that
* meets certain criteria.
* @param options Options for filtering which datepicker toggle instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return new HarnessPredicate(MatDatepickerToggleHarness, options);
}
/** Gets whether the calendar associated with the toggle is open. */
isCalendarOpen() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).hasClass('mat-datepicker-toggle-active');
});
}
/** Whether the toggle is disabled. */
isDisabled() {
return __awaiter(this, void 0, void 0, function* () {
const button = yield this._button();
return coerceBooleanProperty(yield button.getAttribute('disabled'));
});
}
_openCalendar() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this._button()).click();
});
}
} |
JavaScript | class MatStartDateHarness extends MatDatepickerInputHarnessBase {
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatStartDateHarness`
* that meets certain criteria.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return getInputPredicate(MatStartDateHarness, options);
}
} |
JavaScript | class MatEndDateHarness extends MatDatepickerInputHarnessBase {
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatEndDateHarness`
* that meets certain criteria.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return getInputPredicate(MatEndDateHarness, options);
}
} |
JavaScript | class MatDateRangeInputHarness extends DatepickerTriggerHarnessBase {
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatDateRangeInputHarness`
* that meets certain criteria.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return new HarnessPredicate(MatDateRangeInputHarness, options)
.addOption('value', options.value, (harness, value) => HarnessPredicate.stringMatches(harness.getValue(), value));
}
/** Gets the combined value of the start and end inputs, including the separator. */
getValue() {
return __awaiter(this, void 0, void 0, function* () {
const [start, end, separator] = yield parallel(() => [
this.getStartInput().then(input => input.getValue()),
this.getEndInput().then(input => input.getValue()),
this.getSeparator()
]);
return start + `${end ? ` ${separator} ${end}` : ''}`;
});
}
/** Gets the inner start date input inside the range input. */
getStartInput() {
return __awaiter(this, void 0, void 0, function* () {
// Don't pass in filters here since the start input is required and there can only be one.
return this.locatorFor(MatStartDateHarness)();
});
}
/** Gets the inner start date input inside the range input. */
getEndInput() {
return __awaiter(this, void 0, void 0, function* () {
// Don't pass in filters here since the end input is required and there can only be one.
return this.locatorFor(MatEndDateHarness)();
});
}
/** Gets the separator text between the values of the two inputs. */
getSeparator() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.locatorFor('.mat-date-range-input-separator')()).text();
});
}
/** Gets whether the range input is disabled. */
isDisabled() {
return __awaiter(this, void 0, void 0, function* () {
// We consider the input as disabled if both of the sub-inputs are disabled.
const [startDisabled, endDisabled] = yield parallel(() => [
this.getStartInput().then(input => input.isDisabled()),
this.getEndInput().then(input => input.isDisabled())
]);
return startDisabled && endDisabled;
});
}
/** Gets whether the range input is required. */
isRequired() {
return __awaiter(this, void 0, void 0, function* () {
return (yield this.host()).hasClass('mat-date-range-input-required');
});
}
/** Opens the calendar associated with the input. */
isCalendarOpen() {
return __awaiter(this, void 0, void 0, function* () {
// `aria-owns` is set on both inputs only if there's an
// open range picker so we can use it as an indicator.
const startHost = yield (yield this.getStartInput()).host();
return (yield startHost.getAttribute('aria-owns')) != null;
});
}
_openCalendar() {
return __awaiter(this, void 0, void 0, function* () {
// Alt + down arrow is the combination for opening the calendar with the keyboard.
const startHost = yield (yield this.getStartInput()).host();
return startHost.sendKeys({ alt: true }, TestKey.DOWN_ARROW);
});
}
} |
JavaScript | class JWT {
/**
* @param {string} secret - JWT secret
*/
constructor(secret) {
this._secret = secret;
}
/**
* Encode Msc1 auth token as a JSON Web Token
* @param {Auth.Token} token - Token object
* @param {Object} [options={}] - Additional claims for JWT token
* @returns {string} JWT token
*/
encode(token, options = {}) {
const payload = {
jti: token.hash("hex"),
sub: token.address,
iat: parseInt(token.timeBounds.minTime, 10),
exp: parseInt(token.timeBounds.maxTime, 10),
...options
};
return jwt.sign(payload, this._secret, { algorithm: alg });
}
/**
* Decode and verify a JSON Web Token.
* @param {string} payload - JWT token
* @returns {Object} Decoded JWT claims
*/
decode(payload) {
return jwt.verify(payload, this._secret);
}
} |
JavaScript | class JobManager extends EventTarget {
/**
* Constructor.
*/
constructor() {
super();
/**
* @type {Array<Job>}
* @private
*/
this.jobs_ = [];
}
/**
* @return {Array<Job>} List of current jobs.
*/
getJobs() {
return this.jobs_;
}
/**
* Creates a new {@link Job} and optionally starts it.
*
* @param {string} src Source URI for the job's worker.
* @param {string} name The user-facing name of the job.
* @param {string} details The user-facing description of the job.
* @param {boolean=} opt_start If the job should be started; default is false.
* @param {Object=} opt_data Data to pass to the job, if started.
*
* @return {Job} The job.
*/
createJob(src, name, details, opt_start, opt_data) {
var job = new Job(src, name, details);
job.listenOnce(JobEventType.COMPLETE, this.handleJobComplete_, false, this);
job.listenOnce(JobEventType.ERROR, this.handleJobError_, false, this);
this.jobs_.push(job);
if (opt_start) {
job.startExecution(opt_data);
}
return job;
}
/**
* @param {!Job} job The job to remove.
* @private
*/
removeJob_(job) {
goog.dispose(job);
var index = this.jobs_.indexOf(job);
if (index != -1) {
this.jobs_.splice(index, 1);
}
}
/**
* Event handler for {@link JobEventType.COMPLETE} events.
*
* @param {JobEvent} event The event.
* @private
*/
handleJobComplete_(event) {
var job = /** @type {Job} */ (event.target);
if (job) {
this.removeJob_(job);
job = null;
}
}
/**
* Event handler for {@link JobEventType.ERROR} events.
*
* @param {JobEvent} event The event.
* @private
*/
handleJobError_(event) {
var job = /** @type {Job} */ (event.target);
if (job) {
this.removeJob_(job);
job = null;
}
}
} |
JavaScript | class PlayerController extends Group {
constructor(camera = false) {
super()
this.camera = camera
// if (camera) this.add(this.camera)
this.inputManager = new InputManager()
this.movementManager = new MovementManager(this.camera)
this.movementVector = new Vector3()
this.FORWARD_VECTOR = new Vector3(0, 0, 1)
this.BACK_VECTOR = new Vector3(0, 0, -1)
this.LEFT_VECTOR = new Vector3(1, 0, 0)
this.RIGHT_VECTOR = new Vector3(-1, 0, 0)
this.mouseSenitivity = 0.2
this.euler = new Euler(0, 0, 0, 'YXZ')
this.onMouseMove = () => {
if (this.inputManager.cursorLocked) {
this.euler.setFromQuaternion(this.camera.quaternion)
this.euler.x -= this.inputManager.mouseMoveY * this.mouseSenitivity * 0.01
this.euler.y -= this.inputManager.mouseMoveX * this.mouseSenitivity * 0.01
// Clamp rotation on the x axis
this.euler.x = Math.max(-(Math.PI / 2), Math.min((Math.PI / 2), this.euler.x));
this.camera.quaternion.setFromEuler(this.euler)
}
}
document.addEventListener('mousemove', this.onMouseMove, false)
}
update(delta) {
this.movementVector.set(0, 0, 0)
if (this.inputManager.moveForward) {
this.movementVector.add(this.FORWARD_VECTOR)
}
if (this.inputManager.moveBackward) {
this.movementVector.add(this.BACK_VECTOR)
}
if (this.inputManager.moveLeft) {
this.movementVector.add(this.LEFT_VECTOR)
}
if (this.inputManager.moveRight) {
this.movementVector.add(this.RIGHT_VECTOR)
}
this.movementManager.setMovementVector(this.movementVector)
if (this.inputManager.jump) {
this.movementManager.jump()
}
if (this.inputManager.isFiring) {
// this.weaponManager.attack()
}
this.movementManager.update(delta)
}
} |
JavaScript | class LogEntry {
constructor(entry){
this.entry = entry;
}
} |
JavaScript | class Payment extends Component {
constructor(props) {
super(props);
this.baseSetupValue = 500;
this.baseMonthlySubValue = 20;
this.vatValue = this.baseSetupValue / 100 * 20;
this.state = {
stripe: null,
isStripeValid: true,
accountSetupValue: this.baseSetupValue,
monthlySubscriptionValue: this.baseMonthlySubValue,
vatValue: this.vatValue,
totalValue: this.baseSetupValue + this.vatValue,
stripeToken: '',
};
this.config = [];
}
componentDidMount() {
formUtils.initFormState({
numberOfCompanies: '1'
});
const { t, location: { search } } = this.props;
this.setState({ stripe: window.Stripe(stripeKey) });
if (search.indexOf('retakePayment=true')>=0) {
this.setState({
errors: {
form: t('onBoarding.payment.form.retakePaymentError')
},
showErrorMessage: true,
stripe: window.Stripe(stripeKey)
});
}
}
componentWillUnmount() {
formUtils.clearFormState();
}
validateForm = () => {
const { showLoader, hideLoader, t, form, company } = this.props;
const { stripeToken, isStripeValid, } = this.state;
const { values: { numberOfCompanies } } = form;
if (formUtils.validateForm(this.config) && isStripeValid) {
showLoader();
return PaymentService.makePayment(stripeToken, numberOfCompanies, company.id).then((response) => {
hideLoader();
if(response.status === 200) {
navigate('/company-design');
} else if(response.status === 400) {
this.setState({
...this.state,
errors: {
form: t('onBoarding.payment.form.error'),
},
showErrorMessage: true
});
}
});
}
}
/**
* @param {number} input - value to set
* @return {void}
*/
updatePaymentValues = (input) => {
let setupValue = '--';
let subValue = '--';
let vatValue = '--';
let totalValue = '--';
if(!isNaN(input) && input < 21 && input > 0) {
setupValue = this.baseSetupValue * input;
subValue = this.baseMonthlySubValue * input
vatValue = (this.baseSetupValue * input) / 100 * 20;
totalValue = setupValue + vatValue;
}
this.setState({
accountSetupValue: setupValue,
monthlySubscriptionValue: subValue,
vatValue: vatValue,
totalValue: totalValue
});
}
areCardDetailsValid = valid => this.setState({ isStripeValid: valid });
render() {
const { t, form } = this.props;
const {
isStripeValid,
accountSetupValue,
monthlySubscriptionValue,
vatValue,
totalValue,
} = this.state;
const { errors, showErrorMessage } = form;
this.config = [
{
component: Stripe,
isStripeValid: isStripeValid,
setIsStripeValid: () => this.setState({ isStripeValid: false }),
stripeError: t('onBoarding.payment.stripeError'),
setStripeToken: token => this.setState({ stripeToken: token }),
validateForm: () => this.validateForm(),
cardFieldLabel: '',
nextButtonLabel: t('onBoarding.createAccount.ctaPrimary'),
backButtonLabel: t('onBoarding.createAccount.ctaSecondary'),
handleChange: (e) => this.areCardDetailsValid(e.complete)
},
];
const headerActions = <Link to="/company-design"><ButtonHeader label={t('header.buttons.exit')} /></Link>;
return (
<Layout headerActions={headerActions} secure companyID>
<div data-test="container-payment" className="payment" role="company-design form-page">
<h1>{ t('onBoarding.payment.title') }</h1>
{showErrorMessage &&
<ErrorBox>
{ errors.form
? errors.form
: t('form.correctErrors')
}
</ErrorBox>
}
<PaymentInfo
accountSetupLabel={t('onBoarding.payment.paymentInfo.accountSetupLabel')}
monthlySubscriptionLabel={t('onBoarding.payment.paymentInfo.monthlySubscriptionLabel')}
vatLabel={t('onBoarding.payment.paymentInfo.vatLabel')}
TotalLabel={t('onBoarding.payment.paymentInfo.TotalLabel')}
accountSetupValue={accountSetupValue}
monthlySubscriptionValue={monthlySubscriptionValue}
vatValue={vatValue}
totalValue={totalValue}
/>
<p>{t('onBoarding.payment.content.first')}</p>
<p>{t('onBoarding.payment.content.second')}</p>
<br />
<h2>{ t('onBoarding.payment.subtitle') }</h2>
<StripeProvider stripe={this.state.stripe}>
<Elements>
<Form desktopFullWidth>
{formUtils.renderForm(this.config)}
</Form>
</Elements>
</StripeProvider>
</div>
</Layout>
);
}
} |
JavaScript | class SqlDWSource extends models['CopySource'] {
/**
* Create a SqlDWSource.
* @member {object} [sqlReaderQuery] SQL Data Warehouse reader query. Type:
* string (or Expression with resultType string).
* @member {object} [sqlReaderStoredProcedureName] Name of the stored
* procedure for a SQL Data Warehouse source. This cannot be used at the same
* time as SqlReaderQuery. Type: string (or Expression with resultType
* string).
* @member {object} [storedProcedureParameters] Value and type setting for
* stored procedure parameters. Example: "{Parameter1: {value: "1", type:
* "int"}}". Type: object (or Expression with resultType object), itemType:
* StoredProcedureParameter.
*/
constructor() {
super();
}
/**
* Defines the metadata of SqlDWSource
*
* @returns {object} metadata of SqlDWSource
*
*/
mapper() {
return {
required: false,
serializedName: 'SqlDWSource',
type: {
name: 'Composite',
className: 'SqlDWSource',
modelProperties: {
sourceRetryCount: {
required: false,
serializedName: 'sourceRetryCount',
type: {
name: 'Object'
}
},
sourceRetryWait: {
required: false,
serializedName: 'sourceRetryWait',
type: {
name: 'Object'
}
},
type: {
required: true,
serializedName: 'type',
type: {
name: 'String'
}
},
sqlReaderQuery: {
required: false,
serializedName: 'sqlReaderQuery',
type: {
name: 'Object'
}
},
sqlReaderStoredProcedureName: {
required: false,
serializedName: 'sqlReaderStoredProcedureName',
type: {
name: 'Object'
}
},
storedProcedureParameters: {
required: false,
serializedName: 'storedProcedureParameters',
type: {
name: 'Object'
}
}
}
}
};
}
} |
JavaScript | class UserModel {
/**
* Create a new User model.
* @param {Object} [obj] A player response object to initialise this model with.
*/
constructor(obj=null)
{
this._id = obj && obj.id || 0;
this._username = obj && obj.username || '';
this._accountType = obj && obj.account_type || '';
this._slug = obj && obj.slug || '';
this._avatar = obj && obj.avatar || '';
this._cover = obj && obj.cover || '';
this._url = obj && obj.url || '';
this._followersCount = obj && obj.followers_count || 0;
this._isFeatured = obj && obj.is_featured || false;
this._isVerified = obj && obj.is_verified || false;
this._isPartner = obj && obj.is_partner || false;
this._isPrivate = obj && obj.is_private || false;
}
toString() {
var msg = '[UserModel';
if (this._id) msg += ' #'+this._id;
if (this._slug) msg += ' "'+this._slug+'"';
return msg +']';
}
/**
* The user's ID.
* @readonly
* @member {number} UserModel#id
* @returns {number}
*/
get id() {
return this._id;
}
/**
* The user's username.
* @readonly
* @member {string} UserModel#username
* @returns {string}
*/
get username() {
return this._username;
}
/**
* The type of account.
* @readonly
* @member {string} UserModel#accountType
* @returns {string}
*/
get accountType() {
return this._accountType;
}
/**
* The URL-friendly version of the user's name.
* @readonly
* @member {string} UserModel#slug
* @returns {string}
*/
get slug() {
return this._slug;
}
/**
* The URL of the user's avatar.
* Player provides a default.
* @readonly
* @member {string} UserModel#avatar
* @returns {string}
*/
get avatar() {
return this._avatar;
}
/**
* The URL to the user's profile cover image.
* @readonly
* @member {string} UserModel#cover
* @returns {string}
*/
get cover() {
return this._cover;
}
/**
* A relative URL to the user's profile.
* @readonly
* @member {string} UserModel#url
* @returns {string}
*/
get url() {
return this._url;
}
/**
* The number of followers the user has.
* @readonly
* @member {number} UserModel#followersCount
* @returns {number}
*/
get followersCount() {
return this._followersCount;
}
/**
* Whether Player.me has listed this as a featured user.
* @readonly
* @member {boolean} UserModel#isFeatured
* @returns {boolean}
*/
get isFeatured() {
return this._isFeatured;
}
/**
* Whether Player.me has verified this user.
* @readonly
* @member {boolean} UserModel#isVerified
* @returns {boolean}
*/
get isVerified() {
return this._isVerified;
}
/**
* Whether this is a Player.me staff member or partner.
* @readonly
* @member {boolean} UserModel#isPartner
* @returns {boolean}
*/
get isPartner() {
return this._isPartner;
}
/**
* Whether this is a private user.
* @readonly
* @member {boolean} UserModel#isPrivate
* @returns {boolean}
*/
get isPrivate() {
return this._isPrivate;
}
/**
* Whether the account is for a normal user.
* @returns {boolean}
*/
isUser(){
return this._accountType == 'user';
}
/**
* Whether the account is for a group.
* @returns {boolean}
*/
isGroup(){
return this._accountType == 'group';
}
} |
JavaScript | class _Merge extends Layer {
/**
* Creates a _Merge layer
*
* @param {Object} [attrs] - layer config attributes
*/
constructor(attrs = {}) {
super(attrs)
this.layerClass = '_Merge'
this.isMergeLayer = true
}
/**
* Layer computational logic
*
* @param {Tensor[]} inputs
* @returns {Tensor}
*/
call(inputs) {
if (this.gpu) {
this._callGPU(inputs)
} else {
const valid = this._validateInputs(inputs)
if (!valid) {
this.throwError('Invalid inputs to call method.')
}
this._callCPU(inputs)
}
return this.output
}
/**
* Internal method for validating inputs
*
* @param {Tensor[]} inputs
* @returns {boolean}
*/
_validateInputs(inputs) {
const shapes = inputs.map(x => x.tensor.shape.slice())
if (['sum', 'diff', 'mul', 'ave', 'max', 'min'].indexOf(this.mode) > -1) {
if (!shapes.every(shape => _.isEqual(shape, shapes[0]))) {
this.throwError(`All input shapes must be the same for mode ${this.mode}.`)
}
}
if (this.mode === 'dot') {
if (inputs.length !== 2) {
this.throwError(`Exactly 2 inputs required for mode ${this.mode}.`)
}
if (this.dotAxes[0] < 0) {
this.dotAxes[0] = shapes[0].length + this.dotAxes[0]
}
if (this.dotAxes[1] < 0) {
this.dotAxes[1] = shapes[1].length + this.dotAxes[1]
}
if (shapes[0][this.dotAxes[0]] !== shapes[1][this.dotAxes[1]]) {
this.throwError('Dimensions incompatibility using dot mode.')
}
} else if (this.mode === 'concat') {
let nonConcatShapes = shapes.slice()
let _concatAxis = this.concatAxis < 0 ? nonConcatShapes[0].length + this.concatAxis : this.concatAxis
if (this.concatAxis === 0) _concatAxis = 0
_.range(nonConcatShapes.length).forEach(i => {
nonConcatShapes[i].splice(_concatAxis, 1)
})
if (!nonConcatShapes.every(shape => _.isEqual(shape, nonConcatShapes[0]))) {
this.throwError('In concat mode, all shapes must be the same except along the concat axis.')
}
}
return true
}
/**
* CPU call implemented in child classes
*/
_callCPU() {}
/**
* GPU call
*
* mode: sum, diff, mul, ave, max, min
*
* method for mode concat/dot implemented in child class
*
* @param {Tensor[]} inputs
*/
_callGPU(inputs) {
inputs.forEach(input => {
if (!input.glTexture && !input.glTextureFragments) {
input.createGLTexture({ type: '2d', format: 'float', supportsTextureFragments: true })
}
})
// create output textures if doesn't already exist
if (!this.output) {
this.output = new Tensor([], inputs[0].glTextureShape)
this.output.createGLTexture({ type: '2d', format: 'float', supportsTextureFragments: true })
if (inputs[0].is1D) {
this.output.is1D = inputs[0].is1D
} else if (inputs[0].is2DReshaped || inputs[0].is2DSquareReshaped) {
if (inputs[0].is2DReshaped) {
this.output.is2DReshaped = inputs[0].is2DReshaped
} else if (inputs[0].is2DSquareReshaped) {
this.output.is2DSquareReshaped = inputs[0].is2DSquareReshaped
}
this.output.originalShape = inputs[0].originalShape.slice()
this.output.indicesForReshaped = inputs[0].indicesForReshaped
}
}
webgl2.runProgram({
program: this.mergeProgram,
output: this.output,
inputs: inputs.map((input, i) => ({ input, name: `inputs[${i}]` })),
supportsTextureFragments: true
})
// GPU -> CPU data transfer
if (this.outbound.length === 0) {
this.output.transferFromGLTexture()
if (this.output.is2DReshaped) {
this.output.reshapeFrom2D()
} else if (this.output.is2DSquareReshaped) {
this.output.reshapeFrom2DSquare()
}
}
}
} |
JavaScript | class myClass {
constructor(props) {
this.props = props
}
} |
JavaScript | class A {
foo() {
return '';
}
} |
JavaScript | class BPETokenizer extends base_tokenizer_1.BaseTokenizer {
constructor(tokenizer, configuration) {
super(tokenizer, configuration);
this.defaultTrainOptions = {
initialAlphabet: [],
limitAlphabet: 1000,
minFrequency: 2,
showProgress: true,
specialTokens: ["<unk>"],
suffix: "</w>",
vocabSize: 30000,
};
}
/**
* Instantiate and returns a new BPE tokenizer
* @param [options] Optional tokenizer options
*/
static async fromOptions(options) {
const opts = Object.assign(Object.assign({}, this.defaultBPEOptions), options);
const unkToken = base_tokenizer_1.getTokenContent(opts.unkToken);
let model;
if (opts.vocabFile && opts.mergesFile) {
const modelOptions = {
dropout: opts.dropout,
endOfWordSuffix: opts.suffix,
unkToken: unkToken,
};
const fromFile = util_1.promisify(models_1.BPE.fromFile);
model = await fromFile(opts.vocabFile, opts.mergesFile, modelOptions);
}
else {
model = models_1.BPE.empty();
}
const tokenizer = new tokenizer_1.Tokenizer(model);
if (tokenizer.tokenToId(unkToken) !== undefined) {
tokenizer.addSpecialTokens([opts.unkToken]);
}
if (opts.lowercase) {
tokenizer.setNormalizer(normalizers_1.sequenceNormalizer([normalizers_1.nfkcNormalizer(), normalizers_1.lowercaseNormalizer()]));
}
else {
tokenizer.setNormalizer(normalizers_1.nfkcNormalizer());
}
tokenizer.setPreTokenizer(pre_tokenizers_1.whitespaceSplitPreTokenizer());
const decoder = decoders_1.bpeDecoder(opts.suffix);
tokenizer.setDecoder(decoder);
return new BPETokenizer(tokenizer, opts);
}
/**
* Train the model using the given files
*
* @param files Files to use for training
* @param [options] Training options
*/
async train(files, options) {
const mergedOptions = Object.assign(Object.assign({}, this.defaultTrainOptions), options);
const trainer = trainers_1.bpeTrainer(mergedOptions);
this.tokenizer.train(trainer, files);
}
} |
JavaScript | class Buffer {
#buf;
#off = 0;
constructor(ab) {
if (ab === undefined) {
this.#buf = new Uint8Array(0);
return;
}
this.#buf = new Uint8Array(ab);
}
/** Returns a slice holding the unread portion of the buffer.
*
* The slice is valid for use only until the next buffer modification (that
* is, only until the next call to a method like `read()`, `write()`,
* `reset()`, or `truncate()`). If `options.copy` is false the slice aliases the buffer content at
* least until the next buffer modification, so immediate changes to the
* slice will affect the result of future reads.
* @param options Defaults to `{ copy: true }`
*/ bytes(options = {
copy: true,
}) {
if (options.copy === false) return this.#buf.subarray(this.#off);
return this.#buf.slice(this.#off);
}
/** Returns whether the unread portion of the buffer is empty. */ empty() {
return this.#buf.byteLength <= this.#off;
}
/** A read only number of bytes of the unread portion of the buffer. */ get length() {
return this.#buf.byteLength - this.#off;
}
/** The read only capacity of the buffer's underlying byte slice, that is,
* the total space allocated for the buffer's data. */ get capacity() {
return this.#buf.buffer.byteLength;
}
/** Discards all but the first `n` unread bytes from the buffer but
* continues to use the same allocated storage. It throws if `n` is
* negative or greater than the length of the buffer. */ truncate(n) {
if (n === 0) {
this.reset();
return;
}
if (n < 0 || n > this.length) {
throw Error("bytes.Buffer: truncation out of range");
}
this.#reslice(this.#off + n);
}
reset() {
this.#reslice(0);
this.#off = 0;
}
#tryGrowByReslice = (n) => {
const l = this.#buf.byteLength;
if (n <= this.capacity - l) {
this.#reslice(l + n);
return l;
}
return -1;
};
#reslice = (len) => {
assert(len <= this.#buf.buffer.byteLength);
this.#buf = new Uint8Array(this.#buf.buffer, 0, len);
};
/** Reads the next `p.length` bytes from the buffer or until the buffer is
* drained. Returns the number of bytes read. If the buffer has no data to
* return, the return is EOF (`null`). */ readSync(p) {
if (this.empty()) {
// Buffer is empty, reset to recover space.
this.reset();
if (p.byteLength === 0) {
// this edge case is tested in 'bufferReadEmptyAtEOF' test
return 0;
}
return null;
}
const nread = copy(this.#buf.subarray(this.#off), p);
this.#off += nread;
return nread;
}
/** Reads the next `p.length` bytes from the buffer or until the buffer is
* drained. Resolves to the number of bytes read. If the buffer has no
* data to return, resolves to EOF (`null`).
*
* NOTE: This methods reads bytes synchronously; it's provided for
* compatibility with `Reader` interfaces.
*/ read(p) {
const rr = this.readSync(p);
return Promise.resolve(rr);
}
writeSync(p) {
const m = this.#grow(p.byteLength);
return copy(p, this.#buf, m);
}
/** NOTE: This methods writes bytes synchronously; it's provided for
* compatibility with `Writer` interface. */ write(p) {
const n = this.writeSync(p);
return Promise.resolve(n);
}
#grow = (n) => {
const m = this.length;
// If buffer is empty, reset to recover space.
if (m === 0 && this.#off !== 0) {
this.reset();
}
// Fast: Try to grow by means of a reslice.
const i = this.#tryGrowByReslice(n);
if (i >= 0) {
return i;
}
const c = this.capacity;
if (n <= Math.floor(c / 2) - m) {
// We can slide things down instead of allocating a new
// ArrayBuffer. We only need m+n <= c to slide, but
// we instead let capacity get twice as large so we
// don't spend all our time copying.
copy(this.#buf.subarray(this.#off), this.#buf);
} else if (c + n > MAX_SIZE) {
throw new Error("The buffer cannot be grown beyond the maximum size.");
} else {
// Not enough space anywhere, we need to allocate.
const buf = new Uint8Array(Math.min(2 * c + n, MAX_SIZE));
copy(this.#buf.subarray(this.#off), buf);
this.#buf = buf;
}
// Restore this.#off and len(this.#buf).
this.#off = 0;
this.#reslice(Math.min(m + n, MAX_SIZE));
return m;
};
/** Grows the buffer's capacity, if necessary, to guarantee space for
* another `n` bytes. After `.grow(n)`, at least `n` bytes can be written to
* the buffer without another allocation. If `n` is negative, `.grow()` will
* throw. If the buffer can't grow it will throw an error.
*
* Based on Go Lang's
* [Buffer.Grow](https://golang.org/pkg/bytes/#Buffer.Grow). */ grow(n) {
if (n < 0) {
throw Error("Buffer.grow: negative count");
}
const m = this.#grow(n);
this.#reslice(m);
}
/** Reads data from `r` until EOF (`null`) and appends it to the buffer,
* growing the buffer as needed. It resolves to the number of bytes read.
* If the buffer becomes too large, `.readFrom()` will reject with an error.
*
* Based on Go Lang's
* [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */ async readFrom(
r,
) {
let n = 0;
const tmp = new Uint8Array(MIN_READ);
while (true) {
const shouldGrow = this.capacity - this.length < MIN_READ;
// read into tmp buffer if there's not enough room
// otherwise read directly into the internal buffer
const buf = shouldGrow
? tmp
: new Uint8Array(this.#buf.buffer, this.length);
const nread = await r.read(buf);
if (nread === null) {
return n;
}
// write will grow if needed
if (shouldGrow) this.writeSync(buf.subarray(0, nread));
else this.#reslice(this.length + nread);
n += nread;
}
}
/** Reads data from `r` until EOF (`null`) and appends it to the buffer,
* growing the buffer as needed. It returns the number of bytes read. If the
* buffer becomes too large, `.readFromSync()` will throw an error.
*
* Based on Go Lang's
* [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */ readFromSync(
r,
) {
let n = 0;
const tmp = new Uint8Array(MIN_READ);
while (true) {
const shouldGrow = this.capacity - this.length < MIN_READ;
// read into tmp buffer if there's not enough room
// otherwise read directly into the internal buffer
const buf = shouldGrow
? tmp
: new Uint8Array(this.#buf.buffer, this.length);
const nread = r.readSync(buf);
if (nread === null) {
return n;
}
// write will grow if needed
if (shouldGrow) this.writeSync(buf.subarray(0, nread));
else this.#reslice(this.length + nread);
n += nread;
}
}
} |
JavaScript | class ConsoleReporter extends BaseReporter {
/**
* Creates an instance of ConsoleReporter.
* @param {Object} opts
* @memberof ConsoleReporter
*/
constructor(opts) {
super(opts);
this.opts = _.defaultsDeep(this.opts, {
interval: 5,
logger: null,
colors: true,
onlyChanges: true,
});
if (!this.opts.colors)
kleur.enabled = false;
this.lastChanges = new Set();
}
/**
* Initialize reporter
* @param {MetricRegistry} registry
* @memberof ConsoleReporter
*/
init(registry) {
super.init(registry);
if (this.opts.interval > 0) {
this.timer = setInterval(() => this.print(), this.opts.interval * 1000);
this.timer.unref();
}
}
/**
* Convert labels to label string
*
* @param {Object} labels
* @returns {String}
* @memberof ConsoleReporter
*/
labelsToStr(labels) {
const keys = Object.keys(labels);
if (keys.length == 0)
return kleur.gray("{}");
return kleur.gray("{") + keys.map(key => `${kleur.gray(this.formatLabelName(key))}: ${kleur.magenta("" + labels[key])}`).join(", ") + kleur.gray("}");
}
/**
* Print metrics to the console.
*
* @memberof ConsoleReporter
*/
print() {
let list = this.registry.list({
includes: this.opts.includes,
excludes: this.opts.excludes,
});
if (this.opts.onlyChanges)
list = list.filter(metric => this.lastChanges.has(metric.name));
if (list.length == 0)
return;
this.log(kleur.gray(`------------------- [ METRICS START (${list.length}) ] -------------------`));
list.forEach(metric => {
this.log(kleur.cyan().bold(this.formatMetricName(metric.name)) + " " + kleur.gray("(" + metric.type + ")"));
if (metric.values.size == 0) {
this.log(kleur.gray(" <no values>"));
} else {
const unit = metric.unit ? kleur.gray(this.registry.pluralizeUnit(metric.unit)) : "";
metric.values.forEach(item => {
let val;
const labelStr = this.labelsToStr(item.labels);
switch(metric.type) {
case METRIC.TYPE_COUNTER:
case METRIC.TYPE_GAUGE:
case METRIC.TYPE_INFO:
val = item.value === "" ? kleur.grey("<empty string>") : kleur.green().bold(item.value);
if (item.rate != null) {
/*const s = [];
Object.keys(item.rates).forEach(b => {
s.push(`Rate${b}: ${item.rates[b] != null ? item.rates[b].toFixed(2) : "-"}`);
});
val = kleur.green().bold(`Value: ${val} | ` + s.join(" | "));
*/
val = val + kleur.grey(" | Rate: ") + (item.rate != null ? kleur.green().bold(item.rate.toFixed(2)) : "-");
}
break;
case METRIC.TYPE_HISTOGRAM: {
const s = [];
s.push(`Count: ${item.count}`);
if (item.buckets) {
Object.keys(item.buckets).forEach(b => {
s.push(`${b}: ${item.buckets[b] != null ? item.buckets[b] : "-"}`);
});
}
if (item.quantiles) {
s.push(`Min: ${item.min != null ? item.min.toFixed(2) : "-"}`);
s.push(`Mean: ${item.mean != null ? item.mean.toFixed(2) : "-"}`);
s.push(`Var: ${item.variance != null ? item.variance.toFixed(2) : "-"}`);
s.push(`StdDev: ${item.stdDev != null ? item.stdDev.toFixed(2) : "-"}`);
s.push(`Max: ${item.max != null ? item.max.toFixed(2) : "-"}`);
Object.keys(item.quantiles).forEach(key => {
s.push(`${key}: ${item.quantiles[key] != null ? item.quantiles[key].toFixed(2) : "-"}`);
});
}
if (item.rate != null)
s.push(`Rate: ${item.rate != null ? item.rate.toFixed(2) : "-"}`);
val = kleur.green().bold(s.join(" | "));
break;
}
}
this.log(` ${labelStr}: ${val} ${unit}`);
});
}
this.log("");
});
this.log(kleur.gray(`-------------------- [ METRICS END (${list.length}) ] --------------------`));
this.lastChanges.clear();
}
/**
* Print messages
*
* @param {...any} args
*/
log(...args) {
if (_.isFunction(this.opts.logger)) {
return this.opts.logger(...args);
} else {
return this.logger.info(...args);
}
}
/**
* Some metric has been changed.
*
* @param {BaseMetric} metric
* @param {any} value
* @param {Object} labels
* @param {Number?} timestamp
*
* @memberof BaseReporter
*/
metricChanged(metric) {
if (!this.matchMetricName(metric.name)) return;
this.lastChanges.add(metric.name);
}
} |
JavaScript | class PerspectiveView extends DOMWidgetView {
_createElement() {
this.pWidget = new PerspectiveJupyterWidget(undefined, {
plugin: this.model.get("plugin"),
columns: this.model.get("columns"),
row_pivots: this.model.get("row_pivots"),
column_pivots: this.model.get("column_pivots"),
aggregates: this.model.get("aggregates"),
sort: this.model.get("sort"),
filter: this.model.get("filter"),
expressions: this.model.get("expressions"),
plugin_config: this.model.get("plugin_config"),
server: this.model.get("server"),
client: this.model.get("client"),
dark:
this.model.get("dark") === null // only set if its a bool, otherwise inherit
? document.body.getAttribute("data-jp-theme-light") ===
"false"
: this.model.get("dark"),
editable: this.model.get("editable"),
bindto: this.el,
view: this,
});
this.perspective_client = new PerspectiveJupyterClient(this);
return this.pWidget.node;
}
_setElement(el) {
if (this.el || el !== this.pWidget.node) {
// Do not allow the view to be reassigned to a different element.
throw new Error("Cannot reset the DOM element.");
}
this.el = this.pWidget.node;
}
/**
* When state changes on the viewer DOM, apply it to the widget state.
*
* @param mutations
*/
_synchronize_state(mutations) {
for (const mutation of mutations) {
const name = mutation.attributeName.replace(/-/g, "_");
let new_value = this.pWidget.viewer.getAttribute(
mutation.attributeName
);
const current_value = this.model.get(name);
if (typeof new_value === "undefined") {
continue;
}
if (
new_value &&
typeof new_value === "string" &&
name !== "plugin"
) {
new_value = JSON.parse(new_value);
}
if (!isEqual(new_value, current_value)) {
this.model.set(name, new_value);
}
}
// propagate changes back to Python
this.touch();
}
/**
* Attach event handlers, and watch the DOM for state changes in order to
* reflect them back to Python.
*/
render() {
super.render();
this.model.on("msg:custom", this._handle_message, this);
this.model.on("change:plugin", this.plugin_changed, this);
this.model.on("change:columns", this.columns_changed, this);
this.model.on("change:row_pivots", this.row_pivots_changed, this);
this.model.on("change:column_pivots", this.column_pivots_changed, this);
this.model.on("change:aggregates", this.aggregates_changed, this);
this.model.on("change:sort", this.sort_changed, this);
this.model.on("change:filters", this.filters_changed, this);
this.model.on("change:expressions", this.expressions_changed, this);
this.model.on("change:plugin_config", this.plugin_config_changed, this);
this.model.on("change:dark", this.dark_changed, this);
this.model.on("change:editable", this.editable_changed, this);
/**
* Request a table from the manager. If a table has been loaded, proxy
* it and kick off subsequent operations.
*
* If a table hasn't been loaded, the viewer won't get a response back
* and simply waits until it receives a table name.
*/
this.perspective_client.send({
id: -2,
cmd: "table",
});
}
/**
* Handle messages from the Python Perspective instance.
*
* Messages should conform to the `PerspectiveJupyterMessage` interface.
*
* @param msg {PerspectiveJupyterMessage}
*/
_handle_message(msg, buffers) {
if (this._pending_binary && buffers.length === 1) {
// Handle binary messages from the widget, which (unlike the
// tornado handler), does not send messages in chunks.
const binary = buffers[0].buffer.slice(0);
// make sure on_update callbacks are called with a `port_id`
// AND the transferred binary.
if (this._pending_port_id !== undefined) {
// call handle individually to bypass typescript complaints
// that we override `data` with different types.
this.perspective_client._handle({
id: this._pending_binary,
data: {
id: this._pending_binary,
data: {
port_id: this._pending_port_id,
delta: binary,
},
},
});
} else {
this.perspective_client._handle({
id: this._pending_binary,
data: {
id: this._pending_binary,
data: binary,
},
});
}
this._pending_port_id = undefined;
this._pending_binary = undefined;
return;
}
if (msg.type === "table") {
// If in client-only mode (no Table on the python widget),
// message.data is an object containing "data" and "options".
this._handle_load_message(msg);
} else {
if (msg.data["cmd"] === "delete") {
// Regardless of client mode, if `delete()` is called we need to
// clean up the Viewer.
this.pWidget.delete();
return;
}
if (this.pWidget.client === true) {
// In client mode, we need to directly call the methods on the
// viewer
const command = msg.data["cmd"];
if (command === "update") {
this.pWidget._update(msg.data["data"]);
} else if (command === "replace") {
this.pWidget.replace(msg.data["data"]);
} else if (command === "clear") {
this.pWidget.clear();
}
} else {
// Make a deep copy of each message - widget views share the
// same comm, so mutations on `msg` affect subsequent message
// handlers.
const message = JSON.parse(JSON.stringify(msg));
delete message.type;
if (typeof message.data === "string") {
message.data = JSON.parse(message.data);
}
if (message.data["binary_length"]) {
// If the `binary_length` flag is set, the worker expects
// the next message to be a transferable object. This sets
// the `_pending_binary` flag, which triggers a special
// handler for the ArrayBuffer containing binary data.
this._pending_binary = message.data.id;
// Check whether the message also contains a `port_id`,
// indicating that we are in an `on_update` callback and
// the pending binary needs to be joined with the port_id
// for on_update handlers to work properly.
if (
message.data.data &&
message.data.data.port_id !== undefined
) {
this._pending_port_id = message.data.data.port_id;
}
} else {
this.perspective_client._handle(message);
}
}
}
}
get client_worker() {
if (!this._client_worker) {
this._client_worker = perspective.shared_worker();
}
return this._client_worker;
}
/**
* Given a message that commands the widget to load a dataset or table,
* process it.
*
* @param {PerspectiveJupyterMessage} msg
*/
_handle_load_message(msg) {
const table_options = msg.data["options"] || {};
if (this.pWidget.client) {
/**
* In client mode, retrieve the serialized data and the options
* passed by the user, and create a new table on the client end.
*/
const data = msg.data["data"];
const client_table = this.client_worker.table(data, table_options);
this.pWidget.load(client_table);
} else {
if (this.pWidget.server && msg.data["table_name"]) {
/**
* Get a remote table handle, and load the remote table in
* the client for server mode Perspective.
*/
const table = this.perspective_client.open_table(
msg.data["table_name"]
);
this.pWidget.load(table);
} else if (msg.data["table_name"]) {
// Get a remote table handle from the Jupyter kernel, and mirror
// the table on the client, setting up editing if necessary.
this.perspective_client
.open_table(msg.data["table_name"])
.then(async (kernel_table) => {
const kernel_view = await kernel_table.view();
const arrow = await kernel_view.to_arrow();
// Create a client side table
let client_table = this.client_worker.table(
arrow,
table_options
);
// Need to await the table and get the instance
// separately as load() only takes a promise
// to a table and not the instance itself.
const client_table2 = await client_table;
if (this.pWidget.editable) {
await this.pWidget.load(client_table);
// Allow edits from the client Perspective to
// feed back to the kernel.
const client_edit_port =
await this.pWidget.getEditPort();
const kernel_edit_port =
await kernel_table.make_port();
const client_view = await client_table2.view();
// When the client updates, if the update
// comes through the edit port then forward
// it to the server.
client_view.on_update(
(updated) => {
if (updated.port_id === client_edit_port) {
kernel_table.update(updated.delta, {
port_id: kernel_edit_port,
});
}
},
{
mode: "row",
}
);
// If the server updates, and the edit is
// not coming from the server edit port,
// then synchronize state with the client.
kernel_view.on_update(
(updated) => {
if (updated.port_id !== kernel_edit_port) {
client_table2.update(updated.delta); // any port, we dont care
}
},
{
mode: "row",
}
);
} else {
// Load the table and mirror updates from the
// kernel.
await this.pWidget.load(client_table);
kernel_view.on_update(
(updated) =>
client_table2.update(updated.delta),
{
mode: "row",
}
);
}
});
} else {
throw new Error(
`PerspectiveWidget cannot load data from kernel message: ${JSON.stringify(
msg
)}`
);
}
// Only call `init` after the viewer has a table.
this.perspective_client.send({
id: -1,
cmd: "init",
});
}
}
/**
* When the View is removed after the widget terminates, clean up the
* client viewer and Web Worker.
*/
remove() {
// Delete the <perspective-viewer> but do not terminate the shared
// worker as it is shared across other widgets.
this.pWidget.delete();
}
/**
* When traitlets are updated in python, update the corresponding value on
* the front-end viewer. `client` and `server` are not included, as they
* are not properties in `<perspective-viewer>`.
*/
plugin_changed() {
this.pWidget.restore({
plugin: this.model.get("plugin"),
});
}
columns_changed() {
this.pWidget.restore({
columns: this.model.get("columns"),
});
}
row_pivots_changed() {
this.pWidget.restore({
row_pivots: this.model.get("row_pivots"),
});
}
column_pivots_changed() {
this.pWidget.restore({
column_pivots: this.model.get("column_pivots"),
});
}
aggregates_changed() {
this.pWidget.restore({
aggregates: this.model.get("aggregates"),
});
}
sort_changed() {
this.pWidget.restore({
sort: this.model.get("sort"),
});
}
filters_changed() {
this.pWidget.restore({
filter: this.model.get("filter"),
});
}
expressions_changed() {
this.pWidget.restore({
expressions: this.model.get("expressions"),
});
}
plugin_config_changed() {
this.pWidget.plugin_config = this.model.get("plugin_config");
}
dark_changed() {
this.pWidget.dark = this.model.get("dark");
}
editable_changed() {
this.pWidget.editable = this.model.get("editable");
}
} |
JavaScript | class TonePlayer {
constructor() {
this.sampler = sampler;
}
play(notes, bpm) {
const sampler = this.sampler
// Stop and reset all the events from the tranposrt
Tone.Transport.stop();
Tone.Transport.position = 0;
Tone.Transport.cancel();
// Set the bpm
Tone.Transport.bpm.value = bpm;
// Schedule the notes, time represents absolute time in seconds
Tone.Transport.schedule((time) => {
// Relative time of note with respect to the start of mesaure, in seconds
let relativeTime = 0;
// Loop over the notes
for (const note of notes) {
// Remove the dot and rest
let noteDuration = note.duration.replace('.', '');
noteDuration = noteDuration.replace('r', '');
// Time of note
let duration = noteDuration + 'n';
if (note.isDotted) {
duration = duration + '.';
}
// Only schedule the note if it is not rest
if (!note.duration.includes('r')) {
// Schedule the note in the Transport (right time)
// after previous notes have been already played
sampler.triggerAttackRelease(note.pitch, duration, time + relativeTime);
}
// Update our relativeTime
relativeTime += Tone.Time(duration).toSeconds();
}
});
// Start Tone Transport
Tone.Transport.start();
}
} |
JavaScript | class Database extends Base {
/**
* Creates quickmongo instance
* @param {string} mongodbURL Mongodb database url
* @param {string} name Model name
* @param {object} connectionOptions Mongoose connection options
* @example const { Database } = require("quickmongo");
* const db = new Database("mongodb://localhost/quickmongo");
*/
constructor(mongodbURL, name, connectionOptions={}) {
super(mongodbURL || process.env.MONGODB_URL, connectionOptions);
/**
* Current Model
* @type {MongooseDocument}
*/
this.schema = Schema(name);
}
/**
* Sets the value to the database
* @param {string} key Key
* @param {any} value Data
* @example db.set("foo", "bar").then(() => console.log("Saved data"));
* @returns {Promise<any>}
*/
async set(key, value) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
if (!Util.isValue(value)) throw new Error("Invalid value specified!", "ValueError");
const parsed = Util.parseKey(key);
let raw = await this.schema.findOne({
ID: parsed.key
});
if (!raw) {
let data = new this.schema({
ID: parsed.key,
data: parsed.target ? Util.setData(key, {}, value) : value
});
await data.save()
.catch(e => {
return this.emit("error", e);
});
return data.data;
} else {
raw.data = parsed.target ? Util.setData(key, Object.assign({}, raw.data), value) : value;
await raw.save()
.catch(e => {
return this.emit("error", e);
});
return raw.data;
}
}
/**
* Deletes a data from the database
* @param {string} key Key
* @example db.delete("foo").then(() => console.log("Deleted data"));
* @returns {Promise<boolean>}
*/
async delete(key) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
const parsed = Util.parseKey(key);
const raw = await this.schema.findOne({ ID: parsed.key });
if (!raw) return false;
if (parsed.target) {
let data = Util.unsetData(key, Object.assign({}, raw.data));
if (data === raw.data) return false;
raw.data = data;
raw.save().catch(e => this.emit("error", e));
return true;
} else {
await this.schema.findOneAndDelete({ ID: parsed.key })
.catch(e => {
return this.emit("error", e);
});
return true;
}
}
/**
* Checks if there is a data stored with the given key
* @param {string} key Key
* @example db.exists("foo").then(console.log);
* @returns {Promise<boolean>}
*/
async exists(key) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
const parsed = Util.parseKey(key);
let get = await this.schema.findOne({ ID: parsed.key })
.catch(e => {
return this.emit("error", e);
});
if (!get) return null;
let item;
if (parsed.target) item = Util.getData(key, Object.assign({}, get.data));
else item = get.data;
return item === undefined ? false : true;
}
/**
* Checks if there is a data stored with the given key
* @param {string} key Key
* @example db.has("foo").then(console.log);
* @returns {Promise<boolean>}
*/
async has(key) {
return await this.exists(key);
}
/**
* Fetches the data from database
* @param {string} key Key
* @example db.get("foo").then(console.log);
* @returns {Promise<any>}
*/
async get(key) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
const parsed = Util.parseKey(key);
let get = await this.schema.findOne({ ID: parsed.key })
.catch(e => {
return this.emit("error", e);
});
if (!get) return null;
let item;
if (parsed.target) item = Util.getData(key, Object.assign({}, get.data));
else item = get.data;
return item !== undefined ? item : null;
}
/**
* Fetches the data from database
* @param {string} key Key
* @example db.fetch("foo").then(console.log);
* @returns {Promise<any>}
*/
async fetch(key) {
return this.get(key);
}
/**
* @typedef {object} Data
* @property {string} ID Data id
* @property {any} data Data
*/
/**
* Returns everything from the database
* @param {number} limit Data limit
* @example let data = await db.all();
* @returns {Promise<Data[]>}
* @example console.log(`There are total ${data.length} entries.`);
*/
async all(limit = 0) {
if (typeof limit !== "number" || limit < 1) limit = 0;
let data = await this.schema.find().catch(e => {});
if (!!limit) data = data.slice(0, limit);
return data.map(m => ({
ID: m.ID,
data: m.data
}));
}
/**
* Returns everything from the database
* @param {number} limit Data limit
* @returns {Promise<Data[]>}
* @example let data = await db.all();
* console.log(`There are total ${data.length} entries.`);
*/
async fetchAll(limit) {
return await this.all(limit);
}
/**
* Deletes the entire model
* @example db.deleteAll().then(() => console.log("Deleted everything"));
* @returns {Promise<boolean>}
*/
async deleteAll() {
this.emit("debug", "Deleting everything from the database...");
await this.schema.deleteMany().catch(e => {});
return true;
}
/**
* Math calculation
* @param {string} key Key of the data
* @param {string} operator One of +, -, *, / or %
* @param {number} value Value
* @example db.math("items", "+", 200).then(() => console.log("Added 200 items"));
* @returns {Promise<any>}
*/
async math(key, operator, value) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
if (!operator) throw new Error("No operator provided!");
if (!Util.isValue(value)) throw new Error("Invalid value specified!", "ValueError");
switch(operator) {
case "add":
case "+":
let add = await this.get(key);
if (!add) {
return this.set(key, value);
} else {
if (typeof add !== "number") throw new Error(`Expected existing data to be a number, received ${typeof add}!`);
return this.set(key, add + value);
}
case "subtract":
case "sub":
case "-":
let less = await this.get(key);
if (!less) {
return this.set(key, 0 - value);
} else {
if (typeof less !== "number") throw new Error(`Expected existing data to be a number, received ${typeof less}!`);
return this.set(key, less - value);
}
case "multiply":
case "mul":
case "*":
let mul = await this.get(key);
if (!mul) {
return this.set(key, 0 * value);
} else {
if (typeof mul !== "number") throw new Error(`Expected existing data to be a number, received ${typeof mul}!`);
return this.set(key, mul * value);
}
case "divide":
case "div":
case "/":
let div = await this.get(key);
if (!div) {
return this.set(key, 0 / value);
} else {
if (typeof div !== "number") throw new Error(`Expected existing data to be a number, received ${typeof div}!`);
return this.set(key, div / value);
}
case "mod":
case "%":
let mod = await this.get(key);
if (!mod) {
return this.set(key, 0 % value);
} else {
if (typeof mod !== "number") throw new Error(`Expected existing data to be a number, received ${typeof mod}!`);
return this.set(key, mod % value);
}
default:
throw new Error("Unknown operator");
}
}
/**
* Add
* @param {string} key key
* @param {number} value value
* @example db.add("items", 200).then(() => console.log("Added 200 items"));
* @returns {Promise<any>}
*/
async add(key, value) {
return await this.math(key, "+", value);
}
/**
* Subtract
* @param {string} key Key
* @param {number} value Value
* @example db.subtract("items", 100).then(() => console.log("Removed 100 items"));
* @returns {Promise<any>}
*/
async subtract(key, value) {
return await this.math(key, "-", value);
}
/**
* Returns database uptime
* @type {number}
* @example console.log(`Database is up for ${db.uptime} ms.`);
*/
get uptime() {
if (!this.readyAt) return 0;
const timestamp = this.readyAt.getTime();
return Date.now() - timestamp;
}
/**
* Exports the data to json file
* @param {string} fileName File name.
* @param {string} path File path
* @returns {Promise<string>}
* @example db.export("database.json", "./").then(path => {
* console.log(`File exported to ${path}`);
* });
*/
export(fileName="database", path="./") {
return new Promise((resolve, reject) => {
this.emit("debug", `Exporting database entries to ${path || ""}${fileName}`);
this.all().then((data) => {
const strData = JSON.stringify(data);
if (fileName) {
fs.writeFileSync(`${path || ""}${fileName}`, strData);
this.emit("debug", `Exported all data!`);
return resolve(`${path || ""}${fileName}`);
}
return resolve(strData);
}).catch(reject);
});
}
/**
* <warn>You should set `useUnique` to `true` in order to avoid duplicate documents.</warn>
*
* Imports data from other source to quickmongo.
*
* Data type should be Array containing `ID` and `data` fields.
* Example:
* ```js
* [{ ID: "foo", data: "bar" }, { ID: "hi", data: "hello" }]
* ```
* @param {Array} data Array of data
* @param {object} ops Import options
* @param {boolean} [ops.validate=false] If set to true, it will insert valid documents only
* @param {boolean} [ops.unique=false] If it should import unique data only (slow)
* @example const data = QuickDB.all(); // imports data from quick.db to quickmongo
* QuickMongo.import(data);
* @returns {Promise<boolean>}
*/
import(data=[], ops = { unique: false, validate: false }) {
return new Promise(async (resolve, reject) => {
if (!Array.isArray(data)) return reject(new Error(`Data type must be Array, received ${typeof data}!`, "DataTypeError"));
if (data.length < 1) return resolve(false);
if (!ops.unique) {
this.schema.insertMany(data, { ordered: !ops.validate }, (error) => {
if (error) return reject(new Error(`${error}`, "DataImportError"));
return resolve(true);
});
} else {
data.forEach((x, i) => {
if (!ops.validate && (!x.ID || !x.data)) return;
else if (!!ops.validate && (!x.ID || !x.data)) return reject(new Error(`Data is missing ${!x.ID ? "ID" : "data"} path!`, "DataImportError"));
setTimeout(() => {
this.set(x.ID, x.data);
}, 150 * (i + 1));
});
return resolve(true);
}
});
}
/**
* Disconnects the database
* @example db.disconnect();
* @returns {void}
*/
disconnect() {
this.emit("debug", "'database.disconnect()' was called, destroying the process...");
return this._destroyDatabase();
}
/**
* Creates database connection.
*
* You don't need to call this method because it is automatically called by database manager.
*
* @param {string} url Database url
* @returns {void}
*/
connect(url) {
return this._create(url);
}
/**
* Returns current model name
* @type {string}
* @readonly
*/
get name() {
return this.schema.modelName;
}
/**
* Read latency
* @ignore
* @private
* @returns {Promise<number>}
*/
async _read() {
let start = Date.now();
await this.get("LQ==");
return Date.now() - start;
}
/**
* Write latency
* @ignore
* @private
* @returns {Promise<number>}
*/
async _write() {
let start = Date.now();
await this.set("LQ==", Buffer.from(start.toString()).toString("base64"));
return Date.now() - start;
}
/**
* @typedef {object} DatabaseLatency
* @property {number} read Read latency
* @property {number} write Write latency
* @property {number} average Average latency
*/
/**
* Fetches read and write latency of the database in ms
* @example const ping = await db.fetchLatency();
* console.log("Read: ", ping.read);
* console.log("Write: ", ping.write);
* console.log("Average: ", ping.average);
* @returns {Promise<DatabaseLatency>}
*/
async fetchLatency() {
let read = await this._read();
let write = await this._write();
let average = (read + write) / 2;
this.delete("LQ==").catch(e => {});
return { read, write, average };
}
/**
* Fetches read and write latency of the database in ms
* @example const ping = await db.ping();
* console.log("Read: ", ping.read);
* console.log("Write: ", ping.write);
* console.log("Average: ", ping.average);
* @returns {Promise<DatabaseLatency>}
*/
async ping() {
return await this.fetchLatency();
}
/**
* Fetches everything and sorts by given target
* @param {string} key Key
* @param {object} ops Options
* @example const data = await db.startsWith("money", { sort: ".data", limit: 10 });
* @returns {Promise<Data[]>}
*/
async startsWith(key, ops) {
if (!key || typeof key !== "string") throw new Error(`Expected key to be a string, received ${typeof key}`);
let all = await this.all(ops && ops.limit);
return Util.sort(key, all, ops);
}
/**
* Resolves data type
* @param {string} key key
* @example console.log(await db.type("foo"));
* @returns {Promise<"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | "array">}
*/
async type(key) {
if (!Util.isKey(key)) throw new Error("Invalid Key!", "KeyError");
let fetched = await this.get(key);
if (Array.isArray(fetched)) return "array";
return typeof fetched;
}
/**
* Returns array of the keys
* @example const keys = await db.keyarray();
* console.log(keys);
* @returns {Promise<string[]>}
*/
async keyArray() {
const data = await this.all();
return data.map(m => m.ID);
}
/**
* Returns array of the values
* @example const data = await db.valueArray();
* console.log(data);
* @returns {Promise<any[]>}
*/
async valueArray() {
const data = await this.all();
return data.map(m => m.data);
}
/**
* Pushes an item into array
* @param {string} key key
* @param {any|any[]} value Value to push
* @example db.push("users", "John"); // -> ["John"]
* db.push("users", ["Milo", "Simon", "Kyle"]); // -> ["John", "Milo", "Simon", "Kyle"]
* @returns {Promise<any>}
*/
async push(key, value) {
const data = await this.get(key);
if (data == null) {
if (!Array.isArray(value)) return await this.set(key, [value]);
return await this.set(key, value);
}
if (!Array.isArray(data)) throw new Error(`Expected target type to be Array, received ${typeof data}!`);
if (Array.isArray(value)) return await this.set(key, data.concat(value));
data.push(value);
return await this.set(key, data);
}
/**
* Removes an item from array
* @param {string} key key
* @param {any|any[]} value item to remove
* @param {boolean} [multiple=true] if it should pull multiple items. Defaults to `true`.
* <warn>Currently, you can use `multiple` with `non array` pulls only.</warn>
* @example db.pull("users", "John"); // -> ["Milo", "Simon", "Kyle"]
* db.pull("users", ["Milo", "Simon"]); // -> ["Kyle"]
* @returns {Promise<any>}
*/
async pull(key, value, multiple = true) {
let data = await this.get(key);
if (data === null) return false;
if (!Array.isArray(data)) throw new Error(`Expected target type to be Array, received ${typeof data}!`);
if (Array.isArray(value)) {
data = data.filter(i => !value.includes(i));
return await this.set(key, data);
} else {
if (!!multiple) {
data = data.filter(i => i !== value);
return await this.set(key, data);
} else {
const hasItem = data.some(x => x === value);
if (!hasItem) return false;
const index = data.findIndex(x => x === value);
data = data.splice(index, 1);
return await this.set(key, data);
}
}
}
/**
* Returns entries count of current model
* @returns {Promise<number>}
* @example const entries = await db.entries();
* console.log(`There are total ${entries} entries!`);
*/
async entries() {
return await this.schema.estimatedDocumentCount();
}
/**
* Returns raw data from current model
* @param {object} params Search params
* @returns {Promise<MongooseDocument>}
* @example const raw = await db.raw();
* console.log(raw);
*/
async raw(params) {
return await this.schema.find(params);
}
/**
* Returns random entry from the database
* @param {number} n Number entries to return
* @returns {Promise<any[]>}
* @example const random = await db.random();
* console.log(random);
*/
async random(n = 1) {
if (typeof n !== "number" || n < 1) n = 1;
const data = await this.all();
if (n > data.length) throw new Error("Random value length may not exceed total length.", "RangeError");
const shuffled = data.sort(() => 0.5 - Math.random());
return shuffled.slice(0, n);
}
/**
* This method acts like `quick.db#table`. It will return new instance of itself.
* @param {string} name Model name
* @returns {Database}
*/
createModel(name) {
if (!name || typeof name !== "string") throw new Error("Invalid model name");
const CustomModel = new Database(this.dbURL, name, this.options);
return CustomModel;
}
/**
* This method exports **QuickMongo** data to **Quick.db**
* @param {any} quickdb Quick.db instance
* @returns {Promise<any[]>}
* @example const data = await db.exportToQuickDB(quickdb);
*/
async exportToQuickDB(quickdb) {
if (!quickdb) throw new Error("Quick.db instance was not provided!");
const data = await this.all();
data.forEach(item => {
quickdb.set(item.ID, item.data);
});
return quickdb.all();
}
/**
* Returns **QuickMongo Util**
* @example const parsed = db.utils.parseKey("foo.bar");
* console.log(parsed);
* @type {Util}
*/
get utils() {
return Util;
}
/**
* Updates current model and uses new one
* @param {string} name model name to use
* @returns {MongooseDocument}
*/
updateModel(name) {
this.schema = Schema(name);
return this.schema;
}
/**
* String representation of the database
* @example console.log(db.toString());
* @returns {string}
*/
toString() {
return `QuickMongo<{${this.schema.modelName}}>`;
}
/**
* Allows you to eval code using `this` keyword.
* @param {string} code code to eval
* @example
* db._eval("this.all().then(console.log)"); // -> [{ ID: "...", data: ... }, ...]
* @returns {any}
*/
_eval(code) {
return eval(code);
}
} |
JavaScript | class Encoder {
/**
* Encode a packet as a single string if non-binary, or as a
* buffer sequence, depending on packet type.
*
* @param {Packet} packet - packet object
* @param {Function} callback - function to handle encodings (likely engine.write)
* @return Calls callback with Array of encodings
* @api public
*/
encode(packet, callback) {
debug('encoding packet %j', packet);
const encodedPacketPromise = this._encodePacket(packet);
encodedPacketPromise.then(encodedPacket => {
callback([encodedPacket]);
});
}
/**
* @private
* @param {Packet} packet
*/
async _encodePacket(packet) {
// first is type
let encodedPacket = '' + packet.type;
// if we have a namespace other than `/`
// we append it followed by a comma `,`
if (packet.nsp && '/' !== packet.nsp) {
encodedPacket += packet.nsp + ',';
}
// immediately followed by the id
if (null != packet.id) {
encodedPacket += packet.id;
}
// json data
if (null != packet.data) {
const payload = await this._tryStringify(packet.data);
if (payload !== false) {
encodedPacket += payload;
} else {
return ERROR_PACKET;
}
}
debug('encoded %j as %s', packet, encodedPacket);
return encodedPacket;
}
/**
* @private
* @param {Object} object
* @return {Promise}
*/
_tryStringify(object) {
return new Promise(resolve => {
yieldableJSON.stringifyAsync(object, (error, stringifiedJSON) => {
if (error) {
resolve(false);
} else {
resolve(stringifiedJSON);
}
});
});
}
} |
JavaScript | class Decoder extends Emitter {
/**
* Decodes an encoded packet string into packet JSON.
*
* @param {String} encodedPacket
*/
add(encodedPacket) {
if (typeof encodedPacket === 'string') {
const packetPromise = this._decodePacket(encodedPacket);
packetPromise.then(packet => {
this.emit('decoded', packet);
})
} else {
throw new Error('Unknown type: ' + encodedPacket);
}
}
/**
* Decode a packet String (JSON data)
*
* @param {String} encodedPacket
* @return {Promise}
* @private
*/
async _decodePacket(encodedPacket) {
let i = 0;
// look up type
const packet = {
type: Number(encodedPacket.charAt(0))
};
if (null == exports.types[packet.type]) {
return buildError('unknown packet type ' + packet.type);
}
// look up namespace (if any)
if ('/' === encodedPacket.charAt(1)) {
packet.nsp = '';
while (++i) {
const c = encodedPacket.charAt(i);
// There should be a "," separating the namespace from the rest of the packet.
// If we reach the "," then the namespace is complete
if (',' === c) break;
packet.nsp += c;
if (i === encodedPacket.length) break;
}
} else {
packet.nsp = '/';
}
// look up id (if any)
const next = encodedPacket.charAt(i + 1);
if ('' !== next && Number(next) == next) {
packet.id = '';
while (++i) {
const c = encodedPacket.charAt(i);
// Keep going until we run out of characters or the character is no longer a Number
if (null == c || Number(c) != c) {
--i;
break;
}
packet.id += c;
if (i === encodedPacket.length) break;
}
packet.id = Number(packet.id);
}
// look up json data
if (encodedPacket.charAt(++i)) {
const payload = await this._tryParse(encodedPacket.substr(i));
const isPayloadValid = payload !== false && (packet.type === exports.ERROR || isArray(payload));
if (isPayloadValid) {
packet.data = payload;
} else {
return buildError('invalid payload');
}
}
debug('decoded %s as %j', encodedPacket, packet);
return packet;
}
/**
* @private
* @param {string} encodedData
* @return {Object|false}
*/
_tryParse(encodedData) {
return new Promise(resolve => {
yieldableJSON.parseAsync(encodedData, (error, parsedJSON) => {
if (error) {
resolve(false);
} else {
resolve(parsedJSON);
}
});
});
}
/**
* Deallocates a parser's resources
*
* @api public
*/
destroy() {}
} |
JavaScript | class CreateVirtualCardsSuccess extends React.Component {
static propTypes = {
cards: PropTypes.arrayOf(
PropTypes.shape({
uuid: PropTypes.string.isRequired,
currency: PropTypes.string.isRequired,
initialBalance: PropTypes.number.isRequired,
expiryDate: PropTypes.string,
}),
).isRequired,
deliverType: PropTypes.oneOf(['manual', 'email']).isRequired,
collectiveSlug: PropTypes.string.isRequired,
};
constructor(props) {
super(props);
this.redeemLinkTextareaRef = React.createRef();
}
getRedeemLinkFromVC = vc => {
const code = vc.uuid.split('-')[0];
return `${process.env.WEBSITE_URL}/${this.props.collectiveSlug}/redeem/${code}`;
};
copyLinksToClipboard = () => {
try {
this.redeemLinkTextareaRef.current.select();
document.execCommand('copy');
} catch (e) {
// TODO: this should be reported to the user
console.error('Cannot copy to clipboard', e);
}
};
buildFetchParams = () => {
return {};
};
renderManualSuccess() {
const filename = `${this.props.collectiveSlug}-giftcards-${Date.now()}.pdf`;
const downloadUrl = giftCardsDownloadUrl(filename);
return (
<React.Fragment>
<Box mb={3}>
<FormattedMessage
id="virtualCards.create.successCreate"
defaultMessage="Your {count, plural, one {gift card has} other {{count} gift cards have}} been created."
values={{ count: this.props.cards.length }}
/>
</Box>
<Flex width={1} flexDirection="column" alignItems="center">
<Flex my={3} flexWrap="wrap" justifyContent="center">
<StyledButton
m={2}
minWidth={270}
buttonSize="large"
buttonStyle="primary"
onClick={this.copyLinksToClipboard}
>
<Clipboard size="1em" />
<FormattedMessage id="CreateVirtualCardsSuccess.RedeemLinks" defaultMessage="Copy the links" />
</StyledButton>
<FileDownloader
url={downloadUrl}
filename={filename}
buildFetchParams={() => ({
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({ cards: this.props.cards }),
})}
>
{({ loading, downloadFile }) => (
<StyledButton minWidth={270} m={2} buttonSize="large" loading={loading} onClick={downloadFile}>
<Printer size="1em" />
<FormattedMessage id="CreateVirtualCardsSuccess.Download" defaultMessage="Download cards" />
</StyledButton>
)}
</FileDownloader>
</Flex>
<RedeemLinksTextarea
ref={this.redeemLinkTextareaRef}
className="result-redeem-links"
readOnly
value={this.props.cards.map(this.getRedeemLinkFromVC).join('\n')}
/>
</Flex>
</React.Fragment>
);
}
renderEmailSuccess() {
return (
<FormattedMessage
id="virtualCards.create.successSent"
defaultMessage="Your {count, plural, one {gift card has} other {{count} gift cards have}} been sent!"
values={{ count: this.props.cards.length }}
/>
);
}
render() {
const { deliverType } = this.props;
return (
<Flex flexDirection="column" alignItems="center">
<P color="green.700">
<CheckCircle size="3em" />
</P>
{deliverType === 'email' ? this.renderEmailSuccess() : this.renderManualSuccess()}
</Flex>
);
}
} |
JavaScript | class HP15CCalculator extends connect(store)(GestureEventListeners(PageViewElement)) {
/* hack to get GestureEventListeners activated */
constructor() {
super();
Gestures.addListener(this, 'tap', _ignore);
Gestures.addListener(this, 'down', _ignore);
Gestures.addListener(this, 'up', _ignore);
// initialize properties, mostly overwritten by redux
this._shift = 'f'; // want to light up both, ah well
this._complex = true;
this._trigmode = 'GRAD';
this._prgm = true;
this._user = true;
this._neg = '-';
this._digits = ['8','8','8','8','8','8','8','8','8','8'];
this._decimals = [',',',',',',',',',',',',',',',',',',','];
this.rendered = false;
// arrange to get some more work done later
this.renderComplete.then(() => {
/* arrange to monitor focus, keyboard, and touch events for everyone */
this.shadowRoot.addEventListener('focus', e => this._onFocus(e), true);
this.shadowRoot.addEventListener('blur', e => this._onBlur(e), true);
this.shadowRoot.addEventListener('keydown', e => this._onDown(e));
// this.shadowRoot.addEventListener('tap', e => this._onTap(e));
/* hp15c related start up */
// console.log(`renderComplete, this.calculator = ${this.calculator}, .init = ${this.calculator.init}, .key = ${this.calculator.key}`)
this.calculator.init(this);
/* focus initialization */
this._grabFocus();
});
}
/* grab the focus on load, too, whenever. */
_grabFocus() {
if ( ! this.focused ) {
const lcd = this.shadowRoot.getElementById('lcd');
if (lcd) {
lcd.focus();
this.focused = true;
this._adjustFocus();
} else
window.requestAnimationFrame(_ => this._grabFocus());
}
}
/* if the focus went display:none, then move focus to the row/column displayed peer */
_adjustFocus() {
if (this._focusee && this._focusee.aijk && this._focusee.style.display === 'none') {
const f = this._focusee
// console.log(`_adjustFocus found an orphan: ${f.tagName}.${f.className} ${f.style.display}`);
for (let t = f.parentElement.firstElementChild; t !== null; t = t.nextElementSibling) {
if (t.style.display !== 'none') {
// console.log(`_adjustFocus found displayed peer: ${t.tagName}.${t.className} ${t.style.display}`);
t.focus();
return
}
}
}
window.requestAnimationFrame(_ => this._adjustFocus());
}
disconnectedCallback() {
super.disconnectedCallback();
Gestures.removeListener(this, 'tap', _ignore);
Gestures.removeListener(this, 'down', _ignore);
Gestures.removeListener(this, 'up', _ignore);
}
static get properties() {
return {
_user: Boolean,
_shift: String,
_trigmode: String,
_complex: Boolean,
_program: Boolean,
_neg: String,
_digits: Array,
_decimals: Array,
}
}
_updateIndicator(sel, on) {
if (this.shadowRoot) {
// console.log(`_updateIndicator(${sel}, ${on})`);
const ind = this.shadowRoot.querySelector(sel);
if (ind) {
// console.log(`found ${ind.tagName} ${ind.className}`);
ind.style.display = on ? 'inline' : 'none';
}
}
}
_updateShift(shift) {
if (this.shadowRoot) {
// console.log(`updateShift('${shift}')`);
const indf = this.shadowRoot.querySelector('.indicator .fshift');
const indg = this.shadowRoot.querySelector('.indicator .gshift');
const clab = this.shadowRoot.querySelectorAll('.clearlabel');
const fshb = this.shadowRoot.querySelectorAll('.btn.fshift');
const gshb = this.shadowRoot.querySelectorAll('.btn.gshift');
const nshb = this.shadowRoot.querySelectorAll('.btn.nshift');
const [indf_d, indg_d, clab_d, fshb_d, gshb_d, nshb_d] =
shift === 'f' ? [ 'inline', 'none', 'block', 'table-cell', 'none', 'none' ] :
shift === 'g' ? [ 'none', 'inline', 'none', 'none', 'table-cell', 'none' ] :
[ 'none', 'none', 'none', 'none', 'none', 'table-cell' ];
if (indf) indf.style.display = indf_d;
if (indg) indg.style.display = indg_d;
if (clab) clab.forEach(b => b.style.display = clab_d);
if (fshb) fshb.forEach(b => b.style.display = fshb_d);
if (gshb) gshb.forEach(b => b.style.display = gshb_d);
if (nshb) nshb.forEach(b => b.style.display = nshb_d);
/*
* shift/unshift hides the currently focused button
* need to pass the focus to the peer in the same row and column
*/
window.requestAnimationFrame(_ => this._adjustFocus());
}
}
_updateTrigmode(mode) {
if (this.shadowRoot) {
// console.log(`updateTrigmode('${mode}')`);
const rad = this.shadowRoot.querySelector('.rad');
const grad = this.shadowRoot.querySelector('.grad');
const [rad_display, grad_display] =
mode === 'RAD' ? ['inline','none'] :
mode === 'GRAD' ? ['none','inline'] :
['none','none'];
if (rad) rad.style.display = rad_display;
if (grad) grad.style.display = grad_display;
}
}
_updateNeg(neg) {
if (this.shadowRoot) {
// console.log(`updateNeg('${neg}')`);
const sign = this.shadowRoot.querySelector('.neg');
if (sign) {
// console.log(`found neg ${sign.tagName} ${sign.className}`);
sign.setAttribute('visibility', neg === '-' ? 'visible' : 'hidden');
}
}
}
_updateDigit(i, digit) {
// compute a list of lit and unlit segments for a given digit/letter/space
const digits = [
[' _ ',' ',' _ ',' _ ',' ',' _ ',' _ ',' _ ',' _ ',' _ ',' ',' _ ',' ',' _ ',' ',' _ ',' ',' ',' ',' '],
['| |',' |',' _|',' _|','|_|','|_ ','|_ ',' |','|_|','|_|',' _ ','|_|','|_ ','| ',' _|','|_ ',' _ ',' _ ','|_|',' '],
['|_|',' |','|_ ',' _|',' |',' _|','|_|',' |','|_|',' _|',' ','| |','|_|','|_ ','|_|','|_ ','|_|','| ',' ',' '],
]
const digit_segments = (d) => {
// a digit, or a letter, or a space
let i = "0123456789-ABCDEoru ".indexOf(d);
if (i < 0) {
console.log(`bad argument to digit_segments ${d}`);
return null;
}
return [ digits[0][i][1] === '_',
digits[1][i][0] === '|',
digits[1][i][2] === '|',
digits[1][i][1] === '_',
digits[2][i][0] === '|',
digits[2][i][2] === '|',
digits[2][i][1] === '_' ];
}
if (this.shadowRoot) {
// console.log(`updateDigit(${i}, '${digit}')`);
const lit = digit_segments(digit)
if (lit) {
const dig = this.shadowRoot.querySelector(`#dig${i}`)
if (dig) {
// console.log('found #dig${i}');
let i = 0;
for (let e = dig.firstElementChild; e; e = e.nextElementSibling) {
// console.log(`found ${e.tagName} ${e.className.baseVal}`)
e.setAttribute('visibility', lit[i] ? 'visible' : 'hidden');
i += 1;
}
}
}
}
}
_updateDecimal(i, decimal) {
if (this.shadowRoot) {
// console.log(`updateDecimal(${i}, '${decimal}')`);
const dec = this.shadowRoot.getElementById(`dec${i}`)
if (dec) {
// console.log(`found decimal[${i}] ${dec.tagName}`)
const c = dec.firstElementChild;
if (c) {
// console.log(`first child ${c.tagName} ${c.className}`)
const s = c.nextElementSibling
if (s) {
// console.log(`sibling ${s.tagName} ${s.className}`);
c.style.display = decimal !== ' ' ? 'inline' : 'none';
s.style.display = decimal === ',' ? 'inline' : 'none';
// console.log(`updateDecimal(${i}, '${decimal}') is done`);
}
}
}
}
}
_stateChanged(state) {
if (this._user !== state.hp15c.user)
this._updateIndicator('.user', this._user = state.hp15c.user);
if (this._shift !== state.hp15c.shift)
this._updateShift(this._shift = state.hp15c.shift);
if (this._trigmode !== state.hp15c.trigmode)
this._updateTrigmode(this._trigmode = state.hp15c.trigmode);
if (this._complex !== state.hp15c.complex)
this._updateIndicator(".complex", this._complex = state.hp15c.complex)
if (this._program !== state.hp15c.program)
this._updateIndicator(".program", this._program = state.hp15c.program);
if (this._neg !== state.hp15c.neg)
this._updateNeg(this._neg = state.hp15c.neg);
if (this._digits !== state.hp15c.digits) {
if (state.hp15c.digits && this._digits)
state.hp15c.digits.forEach((d,i) => d !== this._digits[i] ? this._updateDigit(i, d) : true);
else if (state.hp15c.digits)
state.hp15c.digits.forEach((d,i) => this._updateDigit(i, d));
this._digits = state.hp15c.digits;
}
if (this._decimals != state.hp15c.decimals) {
if (state.hp15c.decimals && this._decimals)
state.hp15c.decimals.forEach((d,i) => d != this._decimals[i] ? this._updateDecimal(i, d) : true);
else if (state.hp15c.decimals)
state.hp15c.decimals.forEach((d,i) => this._updateDecimal(i, d))
this._decimals = state.hp15c.decimals;
}
}
_render(props) {
// test button
const test_button = () => ! this.calculator.start_tests ? '' :
html`<div id="start_tests"><button on-tap=${e => this.calculator.start_tests()}>Start<br/>Tests</button></div>`;
// sign, numbers, decimal points, and commas
// all segments are generated once in svg
// visibility is modified in stateChanged
// when the values change
const numeric_display = () => {
const width = 11*27, height = 34;
const digit_top = 0, decimal_top = 24;
const digit_left = (i) => 17+i*27, decimal_left = (i) => 36+i*27;
const digit_and_decimal = (i) => {
return svg`<g id$="dig${i}" transform$="translate(${digit_left(i)} ${digit_top})">
<path class="s0" d="M 3 1 L 17 1 13 5 7 5 Z" />
<path class="s1" d="M 2 3 L 6 7 6 10 2 14 Z" />
<path class="s2" d="M 18 3 L 18 14 14 10 14 7 Z" />
<path class="s3" d="M 6.5 12.5 L 13.5 12.5 16 14.5 13.5 16.5 6.5 16.5 4 14.5 Z" />
<path class="s4" d="M 2 15 L 6 19 6 22 2 26 Z" />
<path class="s5" d="M 18 15 L 18 26 14 22 14 19 Z" />
<path class="s6" d="M 3 28 L 17 28 13 24 7 24 Z" />
</g>
<g id$="dec${i}" transform$="translate(${decimal_left(i)} ${decimal_top})">
<rect class="s0" x="2" width="4" height="4" />
<path class="s1" d="M 2 6 L 6 6 1 9 0 9" />
</g>`;
}
return html`<svg id="digits" viewBox="0 0 287 34">
<g transform="skewX(-5)">
<path class="neg" d="M 4 13 L 16 13 16 16 4 16 Z" />
${[0,1,2,3,4,5,6,7,8,9].map((d,i) => digit_and_decimal(i))}
</g>
</svg>`;
}
// generate keypad
const span = (aijk,i,j,k) => {
if (! aijk) return html``;
var {alabel, hlabel} = aijk;
const kclass = k ? `${k}shift` : '';
return alabel ?
html`<span aijk=${aijk} class$="btn ${kclass}" aria-label$="${alabel}" role="button" tabindex="0">${hlabel}</span>` :
html`<span aijk=${aijk} class$="btn ${kclass}" role="button" tabindex="0">${hlabel}</span>` ;
}
const button = (r,c,side,k) =>
k.f && k.g ?
html`
<div class$="col ${side} col-${c}" on-tap=${_ => this._onEmit(k.n)}>
<div class="in-col">${['n','f','g'].map(t => span(k[t],r,c,t))}</div>
</div>` :
html`
<div class$="col ${side} col-${c}" on-tap=${_ => this._onEmit(k.n)}>
<div class="in-col">${span(k.n,r,c,false)}</div>
</div>`;
const rowGenerate = (row, cols, side) =>
html`<div class$="row ${side} row-${row}">${cols.map(col => button(row,col,side,keypad[row][col]))}</div>`;
// console.log('render called')
return html`
<style>
:host {
--key-bezel-background:#322;
--key-border-color:#aaa;
--lcd-bezel-background:#f7f7f7;
--lcd-panel-background:#878777;
--lcd-panel-color:#456;
--fshift-color: #c58720; /* goldenrod?; */
--gshift-color: #479ea5; /* lightblue?; */
--key-cap-color: #fff;
--key-cap-background: #302b31;
font-size:2vw;
}
.calc {
position:relative;
width:100%; /* 640px; */
height:100vh; /* 400px; */
background-color:var(--key-bezel-background);
}
.bezel {
position:absolute;
top: 1.25%;
left: 3.3%;
width: 93.4%;
height: 27.5%;
background-color:var(--lcd-bezel-background);
}
.slot {
position:absolute;
top:0;
left:0;
height:100%;
}
.lcd {
position:absolute;
top:25.4%;left:15.5%;height:56%;width:50%;
background-color:var(--lcd-panel-background);
}
.lcd svg { fill:var(--lcd-panel-color); }
.digit {
position:absolute;
top:5%;left:0;width:100%;
}
.indicator {
position:absolute;
top:70%;
left:0;
width:100%;
height:25%;
font-size:75%;
font-weight:bold;
background-color:transparent;
color:var(--lcd-panel-color);
}
.indicator .user { position:absolute; top:0; left:11%; display:none; }
.indicator .fshift { position:absolute; top:0; left:24.6%; display:none; }
.indicator .gshift { position:absolute; top:0; left:31.5%; display:none; }
.indicator .rad { position:absolute; top:0; left:58%; display:none; }
.indicator .grad { position:absolute; top:0; left:55%; display:none; }
.indicator .complex { position:absolute; top:0; left:79.4%; display:none; }
.indicator .program { position:absolute; top:0; left:86.3%; display:none; }
.keypad {
position:absolute;
top:30%;
left:3.3%;
height:65%;
width:93.4%;
background-color:var(--key-border-color);
}
/* keypad */
.kpd { /* .cwbsc */
position: absolute;
top:.75%;
left:.75%;
height:96%;
width:98.5%;
background-color: var(--key-bezel-background);
}
/* left and right sides of keypad */
.side {
display: inline-block;
height:100%;
overflow:hidden;
position:absolute;
}
.lft.side { width:50%; left:0; }
.rgt.side { width:50%; left:50%; }
.btm.side { height:50%; top:50%; }
/* rows */
/* N rows changes this height% */
.row { display: block; height: 25%; position: relative; }
/* columns and cells */
.col { display: inline-block; height:100%; width:20%; position: absolute; vertical-align: bottom; }
/* inner column */
.in-col {
width: 84%;
height: 68%;
top: 16%;
-moz-border-radius: 1px;
-webkit-border-radius: 1px;
border-radius: 1px;
cursor: pointer;
display: table;
margin: 0% 6%;
padding: 0;
position: relative;
text-align: center;
}
.col:hover .in-col { /* .cwbd:hover .cwdgb-tpl */
-moz-box-shadow:0 1px 1px rgba(0,0,0,0.1);
-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.1);
box-shadow:0 1px 1px rgba(0,0,0,0.1);
background-image:-moz-linear-gradient(top,#d9d9d9,#d0d0d0);
background-image:-ms-linear-gradient(top,#d9d9d9,#d0d0d0);
filter:progid:DXImageTransform.Microsoft.gradient(startColorStr=#d9d9d9,EndColorStr=#d0d0d0);
background-image:-o-linear-gradient(top,#d9d9d9,#d0d0d0);
background-image:-webkit-gradient(linear,left top,left bottom,from(#d9d9d9),to(#d0d0d0));
background-image:-webkit-linear-gradient(top,#d9d9d9,#d0d0d0);
background-color:#d9d9d9;
background-image:linear-gradient(top,#d9d9d9,#d0d0d0);
border:1px solid #b6b6b6;
color:#222
}
/* N columns changes these left% */
.col-0 { left: 0%; }
.col-1 { left:20%; }
.col-2 { left:40%; }
.col-3 { left:60%; }
.col-4 { left:80%; }
.col-5 { left: 0%; }
.col-6 { left:20%; }
.col-7 { left:40%; }
.col-8 { left:60%; }
.col-9 { left:80%; }
/* buttons */
.btn { /* cwbts cwbg1|cwbg2 */
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
display: table-cell;
vertical-align: middle;
background-color: var(--key-cap-background);
color: var(--key-cap-color);
font-size: 100%;
font-weight: bold;
}
/* unshifted buttons */
.btn.nshfit {
}
/* f shifted buttons */
.btn.fshift {
display:none;
color: var(--fshift-color);
}
/* g shifted buttons */
.btn.gshift {
display:none;
color: var(--gshift-color);
}
/* f shift key */
.row.row-3 .col.col-1 .in-col .btn {
background-color: var(--fshift-color);
color: black;
}
/* g shift key */
.row.row-3 .col.col-2 .in-col .btn {
background-color: var(--gshift-color);
color: black;
}
/* ENTER key */
.row.row-2 .col.col-5 {
height:200%;
}
.row.row-2 .col.col-5 .in-col {
height: 84%;
top: 8%;
z-index: 2; // move above the row that gets built later
}
.row.row-3 .col.col-5 { /* button beneath ENTER */
display:none
}
.clearlabel {
position:absolute;
left:20%;
top:47.5%;
width:80%;
height:5%;
color:var(--fshift-color);
background-color:var(--key-bezel-color);
font-size:85%;
font-weight:bold;
display:none;
}
.clearlabel span {
display:inline-block;
position:absolute;
top:0;
left:37.5%;
width:25%;
text-align:center;
}
.clearlabel svg {
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
stroke:var(--fshift-color);
fill:none;
}
/* narrow */
@media screen and (max-width:459px){
:host{font-size:3vw;}
.bezel{top:1%;height:18%;}
.lcd{top:25%;left:15%;height:50%;width:80%;}
.keypad{top:20%;height:75%;}
.lft.side{display:none;}
.rgt.side{left:0;top:0;width:100%;height:50%;}
.btm.side{display:inline-block;left:0;top:50%;width:100%;height:50%;}
}
/* wide */
@media screen and (min-width:460px){
:host{font-size:2vw;}
.bezel{top:1.25%;height:27.5%}
.lcd{top:25%;left:15%;height:50%;width:50%;}
.keypad{top:30%;height:65%}
.lft.side{display:inline-block;left:0;top:0;width:50%;height:100%;}
.rgt.side{left:50%;top:0;width:50%;height:100%}
.btm.side{display:none;}
}
</style>
<section>
<div class="calc">
<div class="bezel">
<div class="slot">
<slot></slot>
${test_button()}
</div>
<div class="lcd" id="lcd" tabindex="0">
<div class="digit">
${numeric_display()}
</div>
<div class="indicator">
<span class="user">USER</span>
<span class="fshift">f</span>
<span class="gshift">g</span>
<span class="rad"> RAD</span>
<span class="grad">GRAD</span>
<span class="complex">C</span>
<span class="program">PRGM</span>
</div>
</div>
</div>
<div class="keypad">
<div class="kpd">
<div class="lft side">
${[0,1,2,3].map(row => rowGenerate(row,[0,1,2,3,4],'lft'))}
<div class="fshift clearlabel">
<svg viewBox="0 0 100 20" preserveAspectRatio="none">
<polyline stroke-width="2" points="0,20 0,10 37.5,10" />
<polyline stroke-width="2" points="62.5,10 100,10 100,20" />
</svg>
<span>CLEAR</span>
</div>
</div>
<div class="rgt side">
${[0,1,2,3].map(row => rowGenerate(row,[5,6,7,8,9],'rgt'))}
</div>
<div class="btm side">
${[0,1,2,3].map(row => rowGenerate(row,[0,1,2,3,4],'btm'))}
<div class="fshift clearlabel">
<svg viewBox="0 0 100 20" preserveAspectRatio="none">
<polyline stroke-width="2" points="0,20 0,10 37.5,10" />
<polyline stroke-width="2" points="62.5,10 100,10 100,20" />
</svg>
<span>CLEAR</span>
</div>
</div>
</div>
</div>
</div>
</section>`;
}
_shouldRender(properties, changed, previous) {
// this.renderComplete.then(() => console.log(`render complete when this.rendered = ${this.rendered}`));
return ! this.rendered;
}
_didRender(properties, changed, previous) {
// console.log(`_didRender when this.rendered = ${this.rendered}`);
this.rendered = true;
}
// hp15c Display interface
clear_digits() {
store.dispatch(hpNeg(' '));
store.dispatch(hpDigits([' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']));
store.dispatch(hpDecimals([' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']));
}
set_neg() { store.dispatch(hpNeg('-')); }
clear_digit(i) { this.set_digit(i, ' '); }
set_digit(i, d) { store.dispatch(hpDigit(this._digits, i, d)); }
set_comma(i) { store.dispatch(hpDecimal(this._decimals, i, ',')); }
set_decimal(i) { store.dispatch(hpDecimal(this._decimals, i, '.')); }
clear_shift() { this.set_shift(' '); }
set_shift(mode) { store.dispatch(hpShift(mode)); } // mode in ['f', 'g', ' ']
set_prgm(on) { store.dispatch(hpProgram(on)); } // on in [true, false]
set_trigmode(mode) { store.dispatch(hpTrigmode(mode)); } // mode in [null, 'RAD', 'GRAD']
set_user(on) { store.dispatch(hpUser(on)); } // on in [true, false]
set_complex(on) { store.dispatch(hpComplex(on)); }
// event listeners
_onFocus(event) {
this._lastFocusee = this._focusee = event.target;
}
_onBlur(event) {
this._focusee = null;
}
_onTap(event) {
if (event.target.aijk) {
this._onEmit(event.target.aijk);
event.preventDefault();
return;
}
console.log(`_onTap(${event.target.tagName}.${event.target.className}) has no aijk property`);
}
_onDown(event) {
/*
don't even get me started, String.fromCharCode(event.which) converts to upper case
on the Lenovo bluetooth keyboard which has upper case key caps, the chromebook
has lower case key caps, so it has lower case event.which codes.
*/
let key = event.key;
if (event.altKey || event.metaKey) return false;
if (event.ctrlKey) {
// special dispensation for the ^R random key code
if (key !== 'r') return false;
key = String.fromCharCode(event.which&0x1f);
} else if (key.length > 1) {
switch (key) {
case 'Backspace': key = '\b'; break;
case 'Enter': key = '\r'; break;
case 'Escape': key = '\x1b'; break;
default: return false;
}
}
// console.log(`_onDown reports ${event.key}, raw=${event.which}, ctrl=${event.ctrlKey}, key=${key} struck`);
if (key === ' ' && this._focusee.aijk) {
// if ' ' and we are focused on a button, fire that button
this._onEmit(this._focusee.aijk);
// event.preventDefault()
} else if (hotkey[key]) {
this._onEmit(hotkey[key]);
// event.preventDefault()
} else {
console.log(`_onDown('${event.key}') left to system`);
}
}
_onEmit(aijk) {
// console.log(`_onEmit('${aijk.label}')`);
if ( ! aijk) {
throw new Error("aijk is undefined in emit");
}
if ( ! aijk.emit) {
throw new Error("aijk.emit is undefined in emit");
}
this.calculator.key(aijk.emit);
}
} |
JavaScript | class LegacyDeploymentHistoryResponse {
/**
* Create a LegacyDeploymentHistoryResponse.
* @property {array} [history] Array containing the deployment's package
* history.
*/
constructor() {
}
/**
* Defines the metadata of LegacyDeploymentHistoryResponse
*
* @returns {object} metadata of LegacyDeploymentHistoryResponse
*
*/
mapper() {
return {
required: false,
serializedName: 'LegacyDeploymentHistoryResponse',
type: {
name: 'Composite',
className: 'LegacyDeploymentHistoryResponse',
modelProperties: {
history: {
required: false,
serializedName: 'history',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'LegacyDeploymentHistoryElementType',
type: {
name: 'Composite',
className: 'LegacyDeploymentHistory'
}
}
}
}
}
}
};
}
} |
JavaScript | class Program {
/** @private */
constructor(context, rootNames, host) {
this._context = context;
this._typeChecker = new TypeChecker_1.TypeChecker(this._context);
this._reset(rootNames, host);
}
/**
* Gets the underlying compiler program.
*/
get compilerObject() {
return this._getOrCreateCompilerObject();
}
/**
* Gets if the internal compiler program is created.
* @internal
*/
_isCompilerProgramCreated() {
return this._createdCompilerObject != null;
}
/**
* Resets the program.
* @internal
*/
_reset(rootNames, host) {
const compilerOptions = this._context.compilerOptions.get();
this._getOrCreateCompilerObject = () => {
// need to use ts.createProgram instead of languageService.getProgram() because the
// program created by the language service is not fully featured (ex. does not write to the file system)
if (this._createdCompilerObject == null) {
this._createdCompilerObject = typescript_1.ts.createProgram(rootNames, compilerOptions, host, this._oldProgram);
delete this._oldProgram;
}
return this._createdCompilerObject;
};
if (this._createdCompilerObject != null) {
this._oldProgram = this._createdCompilerObject;
delete this._createdCompilerObject;
}
this._typeChecker._reset(() => this.compilerObject.getTypeChecker());
}
/**
* Get the program's type checker.
*/
getTypeChecker() {
return this._typeChecker;
}
/**
* Asynchronously emits the TypeScript files as JavaScript files.
* @param options - Options for emitting.
*/
emit(options = {}) {
return __awaiter(this, void 0, void 0, function* () {
if (options.writeFile) {
const message = `Cannot specify a ${"writeFile"} option when emitting asynchrously. `
+ `Use ${"emitSync"}() instead.`;
throw new errors.InvalidOperationError(message);
}
const { fileSystemWrapper } = this._context;
const promises = [];
const emitResult = this._emit(Object.assign({ writeFile: (filePath, text, writeByteOrderMark) => {
promises.push(fileSystemWrapper.writeFile(filePath, writeByteOrderMark ? "\uFEFF" + text : text));
} }, options));
yield Promise.all(promises);
return new results_1.EmitResult(this._context, emitResult);
});
}
/**
* Synchronously emits the TypeScript files as JavaScript files.
* @param options - Options for emitting.
* @remarks Use `emit()` as the asynchronous version will be much faster.
*/
emitSync(options = {}) {
return new results_1.EmitResult(this._context, this._emit(options));
}
/**
* Emits the TypeScript files to JavaScript files to memory.
* @param options - Options for emitting.
*/
emitToMemory(options = {}) {
const sourceFiles = [];
const { fileSystemWrapper } = this._context;
const emitResult = this._emit(Object.assign({ writeFile: (filePath, text, writeByteOrderMark) => {
sourceFiles.push({
filePath: fileSystemWrapper.getStandardizedAbsolutePath(filePath),
text,
writeByteOrderMark: writeByteOrderMark || false
});
} }, options));
return new results_1.MemoryEmitResult(this._context, emitResult, sourceFiles);
}
/** @internal */
_emit(options = {}) {
const targetSourceFile = options.targetSourceFile != null ? options.targetSourceFile.compilerNode : undefined;
const { emitOnlyDtsFiles, customTransformers, writeFile } = options;
const cancellationToken = undefined; // todo: expose this
return this.compilerObject.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
}
/**
* Gets the syntactic diagnostics.
* @param sourceFile - Optional source file to filter by.
*/
getSyntacticDiagnostics(sourceFile) {
const compilerDiagnostics = this.compilerObject.getSyntacticDiagnostics(sourceFile == null ? undefined : sourceFile.compilerNode);
return compilerDiagnostics.map(d => this._context.compilerFactory.getDiagnosticWithLocation(d));
}
/**
* Gets the semantic diagnostics.
* @param sourceFile - Optional source file to filter by.
*/
getSemanticDiagnostics(sourceFile) {
const compilerDiagnostics = this.compilerObject.getSemanticDiagnostics(sourceFile == null ? undefined : sourceFile.compilerNode);
return compilerDiagnostics.map(d => this._context.compilerFactory.getDiagnostic(d));
}
/**
* Gets the declaration diagnostics.
* @param sourceFile - Optional source file to filter by.
*/
getDeclarationDiagnostics(sourceFile) {
const compilerDiagnostics = this.compilerObject.getDeclarationDiagnostics(sourceFile == null ? undefined : sourceFile.compilerNode);
return compilerDiagnostics.map(d => this._context.compilerFactory.getDiagnosticWithLocation(d));
}
/**
* Gets the global diagnostics.
*/
getGlobalDiagnostics() {
const compilerDiagnostics = this.compilerObject.getGlobalDiagnostics();
return compilerDiagnostics.map(d => this._context.compilerFactory.getDiagnostic(d));
}
/**
* Gets the emit module resolution kind.
*/
getEmitModuleResolutionKind() {
return tsInternal.getEmitModuleResolutionKind(this.compilerObject.getCompilerOptions());
}
/**
* Gets if the provided source file was discovered while loading an external library.
* @param sourceFile - Source file.
*/
isSourceFileFromExternalLibrary(sourceFile) {
// Do not use compilerObject.isSourceFileFromExternalLibrary because that method
// will become out of date after a manipulation has happened to a source file.
// Read more in sourceFile.isFromExternalLibrary()'s method body.
return sourceFile.isFromExternalLibrary();
}
} |
JavaScript | class UserList extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this);
}
componentDidMount() {
const { getData, day, moment } = this.props;
getData(day, moment);
}
componentDidUpdate(prevProps) {
const { getData, day, moment } = this.props;
if (moment !== prevProps.moment) {
getData(day, moment);
}
}
handleDelete(id) {
const { onDelete } = this.props;
onDelete(id);
}
render() {
const {
list,
} = this.props;
return (
<React.Fragment>
{(!list || !list.length) && (
<span>
Nessuna prenotazione inserita
</span>
)}
{(list && list.length > 0) && (
<List>
{ list.map(reserv => (
<TextBox
key={reserv.id}
id={reserv.id}
onDelete={this.handleDelete}
deleteLabel={reserv.user
? `Rimuovi la prenotazione dell'utente ${reserv.user.name} ${reserv.hour
? `delle ore ${reserv.hour}` : ''}` : ''}
confirmation
>
<UserReservationItem
name={reserv.user ? reserv.user.name : 'No-name'}
hour={reserv.hour || '--:--'}
/>
</TextBox>
)) }
</List>
)}
</React.Fragment>
);
}
} |
JavaScript | class NzDatePickerComponent {
// ------------------------------------------------------------------------
// Input API End
// ------------------------------------------------------------------------
constructor(nzConfigService, datePickerService, i18n, cdr, renderer, elementRef, dateHelper, nzResizeObserver, platform, doc, directionality, noAnimation) {
this.nzConfigService = nzConfigService;
this.datePickerService = datePickerService;
this.i18n = i18n;
this.cdr = cdr;
this.renderer = renderer;
this.elementRef = elementRef;
this.dateHelper = dateHelper;
this.nzResizeObserver = nzResizeObserver;
this.platform = platform;
this.directionality = directionality;
this.noAnimation = noAnimation;
this._nzModuleName = NZ_CONFIG_MODULE_NAME;
this.isRange = false; // Indicate whether the value is a range value
this.dir = 'ltr';
this.panelMode = 'date';
this.destroyed$ = new Subject();
this.isCustomPlaceHolder = false;
this.isCustomFormat = false;
this.showTime = false;
// --- Common API
this.nzAllowClear = true;
this.nzAutoFocus = false;
this.nzDisabled = false;
this.nzBorderless = false;
this.nzInputReadOnly = false;
this.nzInline = false;
this.nzPlaceHolder = '';
this.nzPopupStyle = POPUP_STYLE_PATCH;
this.nzSize = 'default';
this.nzShowToday = true;
this.nzMode = 'date';
this.nzShowNow = true;
this.nzDefaultPickerValue = null;
this.nzSeparator = undefined;
this.nzSuffixIcon = 'calendar';
this.nzBackdrop = false;
this.nzId = null;
// TODO(@wenqi73) The PanelMode need named for each pickers and export
this.nzOnPanelChange = new EventEmitter();
this.nzOnCalendarChange = new EventEmitter();
this.nzOnOk = new EventEmitter();
this.nzOnOpenChange = new EventEmitter();
this.inputSize = 12;
this.prefixCls = PREFIX_CLASS;
this.activeBarStyle = {};
this.overlayOpen = false; // Available when "nzOpen" = undefined
this.overlayPositions = [
{
offsetY: 2,
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top'
},
{
offsetY: -2,
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom'
},
{
offsetY: 2,
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top'
},
{
offsetY: -2,
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom'
}
];
this.currentPositionX = 'start';
this.currentPositionY = 'bottom';
// ------------------------------------------------------------------------
// | Control value accessor implements
// ------------------------------------------------------------------------
// NOTE: onChangeFn/onTouchedFn will not be assigned if user not use as ngModel
this.onChangeFn = () => void 0;
this.onTouchedFn = () => void 0;
this.document = doc;
this.origin = new CdkOverlayOrigin(this.elementRef);
}
get nzShowTime() {
return this.showTime;
}
set nzShowTime(value) {
this.showTime = typeof value === 'object' ? value : toBoolean(value);
}
get realOpenState() {
// The value that really decide the open state of overlay
return this.isOpenHandledByUser() ? !!this.nzOpen : this.overlayOpen;
}
ngAfterViewInit() {
if (this.nzAutoFocus) {
this.focus();
}
if (this.isRange && this.platform.isBrowser) {
this.nzResizeObserver
.observe(this.elementRef)
.pipe(takeUntil(this.destroyed$))
.subscribe(() => {
this.updateInputWidthAndArrowLeft();
});
}
this.datePickerService.inputPartChange$.pipe(takeUntil(this.destroyed$)).subscribe(partType => {
if (partType) {
this.datePickerService.activeInput = partType;
}
this.focus();
this.updateInputWidthAndArrowLeft();
});
}
updateInputWidthAndArrowLeft() {
var _a, _b, _c;
this.inputWidth = ((_b = (_a = this.rangePickerInputs) === null || _a === void 0 ? void 0 : _a.first) === null || _b === void 0 ? void 0 : _b.nativeElement.offsetWidth) || 0;
const baseStyle = { position: 'absolute', width: `${this.inputWidth}px` };
this.datePickerService.arrowLeft =
this.datePickerService.activeInput === 'left'
? 0
: this.inputWidth + ((_c = this.separatorElement) === null || _c === void 0 ? void 0 : _c.nativeElement.offsetWidth) || 0;
if (this.dir === 'rtl') {
this.activeBarStyle = Object.assign(Object.assign({}, baseStyle), { right: `${this.datePickerService.arrowLeft}px` });
}
else {
this.activeBarStyle = Object.assign(Object.assign({}, baseStyle), { left: `${this.datePickerService.arrowLeft}px` });
}
this.cdr.markForCheck();
}
getInput(partType) {
var _a, _b;
if (this.nzInline) {
return undefined;
}
return this.isRange
? partType === 'left'
? (_a = this.rangePickerInputs) === null || _a === void 0 ? void 0 : _a.first.nativeElement
: (_b = this.rangePickerInputs) === null || _b === void 0 ? void 0 : _b.last.nativeElement
: this.pickerInput.nativeElement;
}
focus() {
const activeInputElement = this.getInput(this.datePickerService.activeInput);
if (this.document.activeElement !== activeInputElement) {
activeInputElement === null || activeInputElement === void 0 ? void 0 : activeInputElement.focus();
}
}
onFocus(event, partType) {
event.preventDefault();
if (partType) {
this.datePickerService.inputPartChange$.next(partType);
}
this.renderClass(true);
}
// blur event has not the relatedTarget in IE11, use focusout instead.
onFocusout(event) {
event.preventDefault();
if (!this.elementRef.nativeElement.contains(event.relatedTarget)) {
this.checkAndClose();
}
this.renderClass(false);
}
// Show overlay content
open() {
if (this.nzInline) {
return;
}
if (!this.realOpenState && !this.nzDisabled) {
this.updateInputWidthAndArrowLeft();
this.overlayOpen = true;
this.nzOnOpenChange.emit(true);
this.cdr.markForCheck();
}
}
close() {
if (this.nzInline) {
return;
}
if (this.realOpenState) {
this.overlayOpen = false;
this.nzOnOpenChange.emit(false);
}
}
showClear() {
return !this.nzDisabled && !this.isEmptyValue(this.datePickerService.value) && this.nzAllowClear;
}
checkAndClose() {
if (!this.realOpenState) {
return;
}
if (this.panel.isAllowed(this.datePickerService.value, true)) {
if (Array.isArray(this.datePickerService.value) && wrongSortOrder(this.datePickerService.value)) {
const index = this.datePickerService.getActiveIndex();
const value = this.datePickerService.value[index];
this.panel.changeValueFromSelect(value, true);
return;
}
this.updateInputValue();
this.datePickerService.emitValue$.next();
}
else {
this.datePickerService.setValue(this.datePickerService.initialValue);
this.close();
}
}
onClickInputBox(event) {
event.stopPropagation();
this.focus();
if (!this.isOpenHandledByUser()) {
this.open();
}
}
onOverlayKeydown(event) {
if (event.keyCode === ESCAPE) {
this.datePickerService.initValue();
}
}
// NOTE: A issue here, the first time position change, the animation will not be triggered.
// Because the overlay's "positionChange" event is emitted after the content's full shown up.
// All other components like "nz-dropdown" which depends on overlay also has the same issue.
// See: https://github.com/NG-ZORRO/ng-zorro-antd/issues/1429
onPositionChange(position) {
this.currentPositionX = position.connectionPair.originX;
this.currentPositionY = position.connectionPair.originY;
this.cdr.detectChanges(); // Take side-effects to position styles
}
onClickClear(event) {
event.preventDefault();
event.stopPropagation();
this.datePickerService.initValue(true);
this.datePickerService.emitValue$.next();
}
updateInputValue() {
const newValue = this.datePickerService.value;
if (this.isRange) {
this.inputValue = newValue ? newValue.map(v => this.formatValue(v)) : ['', ''];
}
else {
this.inputValue = this.formatValue(newValue);
}
this.cdr.markForCheck();
}
formatValue(value) {
return this.dateHelper.format(value && value.nativeDate, this.nzFormat);
}
onInputChange(value, isEnter = false) {
/**
* in IE11 focus/blur will trigger ngModelChange if placeholder changes,
* so we forbidden IE11 to open panel through input change
*/
if (!this.platform.TRIDENT &&
this.document.activeElement === this.getInput(this.datePickerService.activeInput) &&
!this.realOpenState) {
this.open();
return;
}
const date = this.checkValidDate(value);
// Can only change date when it's open
if (date && this.realOpenState) {
this.panel.changeValueFromSelect(date, isEnter);
}
}
onKeyupEnter(event) {
this.onInputChange(event.target.value, true);
}
checkValidDate(value) {
const date = new CandyDate(this.dateHelper.parseDate(value, this.nzFormat));
if (!date.isValid() || value !== this.dateHelper.format(date.nativeDate, this.nzFormat)) {
return null;
}
return date;
}
getPlaceholder(partType) {
return this.isRange
? this.nzPlaceHolder[this.datePickerService.getActiveIndex(partType)]
: this.nzPlaceHolder;
}
isEmptyValue(value) {
if (value === null) {
return true;
}
else if (this.isRange) {
return !value || !Array.isArray(value) || value.every(val => !val);
}
else {
return !value;
}
}
// Whether open state is permanently controlled by user himself
isOpenHandledByUser() {
return this.nzOpen !== undefined;
}
ngOnInit() {
var _a;
// Subscribe the every locale change if the nzLocale is not handled by user
if (!this.nzLocale) {
this.i18n.localeChange.pipe(takeUntil(this.destroyed$)).subscribe(() => this.setLocale());
}
// Default value
this.datePickerService.isRange = this.isRange;
this.datePickerService.initValue(true);
this.datePickerService.emitValue$.pipe(takeUntil(this.destroyed$)).subscribe(_ => {
var _a, _b, _c, _d;
const value = this.datePickerService.value;
this.datePickerService.initialValue = cloneDate(value);
if (this.isRange) {
const vAsRange = value;
if (vAsRange.length) {
this.onChangeFn([(_b = (_a = vAsRange[0]) === null || _a === void 0 ? void 0 : _a.nativeDate) !== null && _b !== void 0 ? _b : null, (_d = (_c = vAsRange[1]) === null || _c === void 0 ? void 0 : _c.nativeDate) !== null && _d !== void 0 ? _d : null]);
}
else {
this.onChangeFn([]);
}
}
else {
if (value) {
this.onChangeFn(value.nativeDate);
}
else {
this.onChangeFn(null);
}
}
this.onTouchedFn();
// When value emitted, overlay will be closed
this.close();
});
(_a = this.directionality.change) === null || _a === void 0 ? void 0 : _a.pipe(takeUntil(this.destroyed$)).subscribe((direction) => {
this.dir = direction;
this.cdr.detectChanges();
});
this.dir = this.directionality.value;
this.inputValue = this.isRange ? ['', ''] : '';
this.setModeAndFormat();
this.datePickerService.valueChange$.pipe(takeUntil(this.destroyed$)).subscribe(() => {
this.updateInputValue();
});
}
ngOnChanges(changes) {
var _a, _b;
if (changes.nzPopupStyle) {
// Always assign the popup style patch
this.nzPopupStyle = this.nzPopupStyle ? Object.assign(Object.assign({}, this.nzPopupStyle), POPUP_STYLE_PATCH) : POPUP_STYLE_PATCH;
}
// Mark as customized placeholder by user once nzPlaceHolder assigned at the first time
if ((_a = changes.nzPlaceHolder) === null || _a === void 0 ? void 0 : _a.currentValue) {
this.isCustomPlaceHolder = true;
}
if ((_b = changes.nzFormat) === null || _b === void 0 ? void 0 : _b.currentValue) {
this.isCustomFormat = true;
}
if (changes.nzLocale) {
// The nzLocale is currently handled by user
this.setDefaultPlaceHolder();
}
if (changes.nzRenderExtraFooter) {
this.extraFooter = valueFunctionProp(this.nzRenderExtraFooter);
}
if (changes.nzMode) {
this.setDefaultPlaceHolder();
this.setModeAndFormat();
}
}
ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}
setModeAndFormat() {
const inputFormats = {
year: 'yyyy',
month: 'yyyy-MM',
week: this.i18n.getDateLocale() ? 'RRRR-II' : 'yyyy-ww',
date: this.nzShowTime ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd'
};
if (!this.nzMode) {
this.nzMode = 'date';
}
this.panelMode = this.isRange ? [this.nzMode, this.nzMode] : this.nzMode;
// Default format when it's empty
if (!this.isCustomFormat) {
this.nzFormat = inputFormats[this.nzMode];
}
this.inputSize = Math.max(10, this.nzFormat.length) + 2;
this.updateInputValue();
}
/**
* Triggered when overlayOpen changes (different with realOpenState)
*
* @param open The overlayOpen in picker component
*/
onOpenChange(open) {
this.nzOnOpenChange.emit(open);
}
writeValue(value) {
this.setValue(value);
this.cdr.markForCheck();
}
registerOnChange(fn) {
this.onChangeFn = fn;
}
registerOnTouched(fn) {
this.onTouchedFn = fn;
}
setDisabledState(isDisabled) {
this.nzDisabled = isDisabled;
this.cdr.markForCheck();
}
// ------------------------------------------------------------------------
// | Internal methods
// ------------------------------------------------------------------------
// Reload locale from i18n with side effects
setLocale() {
this.nzLocale = this.i18n.getLocaleData('DatePicker', {});
this.setDefaultPlaceHolder();
this.cdr.markForCheck();
}
setDefaultPlaceHolder() {
if (!this.isCustomPlaceHolder && this.nzLocale) {
const defaultPlaceholder = {
year: this.getPropertyOfLocale('yearPlaceholder'),
month: this.getPropertyOfLocale('monthPlaceholder'),
week: this.getPropertyOfLocale('weekPlaceholder'),
date: this.getPropertyOfLocale('placeholder')
};
const defaultRangePlaceholder = {
year: this.getPropertyOfLocale('rangeYearPlaceholder'),
month: this.getPropertyOfLocale('rangeMonthPlaceholder'),
week: this.getPropertyOfLocale('rangeWeekPlaceholder'),
date: this.getPropertyOfLocale('rangePlaceholder')
};
this.nzPlaceHolder = this.isRange
? defaultRangePlaceholder[this.nzMode]
: defaultPlaceholder[this.nzMode];
}
}
getPropertyOfLocale(type) {
return this.nzLocale.lang[type] || this.i18n.getLocaleData(`DatePicker.lang.${type}`);
}
// Safe way of setting value with default
setValue(value) {
const newValue = this.datePickerService.makeValue(value);
this.datePickerService.setValue(newValue);
this.datePickerService.initialValue = newValue;
}
renderClass(value) {
// TODO: avoid autoFocus cause change after checked error
if (value) {
this.renderer.addClass(this.elementRef.nativeElement, 'ant-picker-focused');
}
else {
this.renderer.removeClass(this.elementRef.nativeElement, 'ant-picker-focused');
}
}
onPanelModeChange(panelMode) {
this.nzOnPanelChange.emit(panelMode);
}
// Emit nzOnCalendarChange when select date by nz-range-picker
onCalendarChange(value) {
if (this.isRange && Array.isArray(value)) {
const rangeValue = value.filter(x => x instanceof CandyDate).map(x => x.nativeDate);
this.nzOnCalendarChange.emit(rangeValue);
}
}
onResultOk() {
var _a, _b;
if (this.isRange) {
const value = this.datePickerService.value;
if (value.length) {
this.nzOnOk.emit([((_a = value[0]) === null || _a === void 0 ? void 0 : _a.nativeDate) || null, ((_b = value[1]) === null || _b === void 0 ? void 0 : _b.nativeDate) || null]);
}
else {
this.nzOnOk.emit([]);
}
}
else {
if (this.datePickerService.value) {
this.nzOnOk.emit(this.datePickerService.value.nativeDate);
}
else {
this.nzOnOk.emit(null);
}
}
}
} |
JavaScript | class Ellipsoid {
// An Ellipsoid instance initialized to the WGS84 standard.
static get WGS84() {
wgs84 = wgs84 || new Ellipsoid(WGS84_RADIUS_X, WGS84_RADIUS_Y, WGS84_RADIUS_Z);
return wgs84;
}
// Creates an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
constructor(x = 0.0, y = 0.0, z = 0.0) {
assert(x >= 0.0);
assert(y >= 0.0);
assert(z >= 0.0);
this.radii = new Vector3(x, y, z);
this.radiiSquared = new Vector3(x * x, y * y, z * z);
this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
this.oneOverRadii = new Vector3(
x === 0.0 ? 0.0 : 1.0 / x,
y === 0.0 ? 0.0 : 1.0 / y,
z === 0.0 ? 0.0 : 1.0 / z
);
this.oneOverRadiiSquared = new Vector3(
x === 0.0 ? 0.0 : 1.0 / (x * x),
y === 0.0 ? 0.0 : 1.0 / (y * y),
z === 0.0 ? 0.0 : 1.0 / (z * z)
);
this.minimumRadius = Math.min(x, y, z);
this.maximumRadius = Math.max(x, y, z);
this.centerToleranceSquared = _MathUtils.EPSILON1;
if (this.radiiSquared.z !== 0) {
this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
}
Object.freeze(this);
}
// Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
equals(right) {
return this === right || Boolean(right && this.radii.equals(right.radii));
}
// Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
toString() {
return this.radii.toString();
}
// Converts the provided cartographic to Cartesian representation.
cartographicToCartesian(cartographic, result = [0, 0, 0]) {
const normal = scratchNormal;
const k = scratchK;
const [, , height] = cartographic;
this.geodeticSurfaceNormalCartographic(cartographic, normal);
k.copy(this.radiiSquared).scale(normal);
const gamma = Math.sqrt(normal.dot(k));
k.scale(1 / gamma);
normal.scale(height);
k.add(normal);
return k.to(result);
}
// Converts the provided cartesian to cartographic (lng/lat/z) representation.
// The cartesian is undefined at the center of the ellipsoid.
cartesianToCartographic(cartesian, result = [0, 0, 0]) {
scratchCartesian.from(cartesian);
const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition);
if (!point) {
return undefined;
}
const normal = this.geodeticSurfaceNormal(point, scratchNormal);
const h = scratchHeight;
h.copy(scratchCartesian).subtract(point);
const longitude = Math.atan2(normal.y, normal.x);
const latitude = Math.asin(normal.z);
const height = Math.sign(vec3.dot(h, scratchCartesian)) * vec3.length(h);
return toCartographicFromRadians([longitude, latitude, height], result);
}
// Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
// centered at the provided origin to the provided ellipsoid's fixed reference frame.
eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
}
// Computes a 4x4 transformation matrix from a reference frame centered at
// the provided origin to the ellipsoid's fixed reference frame.
localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
}
// Computes the unit vector directed from the center of this ellipsoid toward
// the provided Cartesian position.
geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
return scratchVector
.from(cartesian)
.normalize()
.to(result);
}
// Computes the normal of the plane tangent to the surface of the ellipsoid at provided position.
geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
const cartographicVectorRadians = fromCartographicToRadians(cartographic);
const longitude = cartographicVectorRadians[0];
const latitude = cartographicVectorRadians[1];
const cosLatitude = Math.cos(latitude);
scratchVector
.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude))
.normalize();
return scratchVector.to(result);
}
// Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
return scratchVector
.from(cartesian)
.scale(this.oneOverRadiiSquared)
.normalize()
.to(result);
}
// Scales the provided Cartesian position along the geodetic surface normal
// so that it is on the surface of this ellipsoid. If the position is
// at the center of the ellipsoid, this function returns undefined.
scaleToGeodeticSurface(cartesian, result) {
return scaleToGeodeticSurface(cartesian, this, result);
}
// Scales the provided Cartesian position along the geocentric surface normal
// so that it is on the surface of this ellipsoid.
scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
scratchPosition.from(cartesian);
const positionX = scratchPosition.x;
const positionY = scratchPosition.y;
const positionZ = scratchPosition.z;
const oneOverRadiiSquared = this.oneOverRadiiSquared;
const beta =
1.0 /
Math.sqrt(
positionX * positionX * oneOverRadiiSquared.x +
positionY * positionY * oneOverRadiiSquared.y +
positionZ * positionZ * oneOverRadiiSquared.z
);
return scratchPosition.multiplyScalar(beta).to(result);
}
// Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
// its components by the result of `Ellipsoid#oneOverRadii`
transformPositionToScaledSpace(position, result = [0, 0, 0]) {
return scratchPosition
.from(position)
.scale(this.oneOverRadii)
.to(result);
}
// Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
// its components by the result of `Ellipsoid#radii`.
transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
return scratchPosition
.from(position)
.scale(this.radii)
.to(result);
}
// Computes a point which is the intersection of the surface normal with the z-axis.
getSurfaceNormalIntersectionWithZAxis(position, buffer = 0.0, result = [0, 0, 0]) {
// Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)
assert(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
assert(this.radii.z > 0);
scratchPosition.from(position);
const z = scratchPosition.z * (1 - this.squaredXOverSquaredZ);
if (Math.abs(z) >= this.radii.z - buffer) {
return undefined;
}
return scratchPosition.set(0.0, 0.0, z).to(result);
}
} |
JavaScript | class ResourceRecord {
constructor(fields) {
if (this.constructor === ResourceRecord) throw new Error('Abstract only!');
if (!fields || !fields.name) throw new Error('Record must have a name');
this.name = fields.name;
this.rrtype = fields.rrtype || RType[this.constructor.name];
this.rrclass = fields.rrclass || RClass.IN;
if ('ttl' in fields) this.ttl = fields.ttl;
if ('isUnique' in fields) this.isUnique = fields.isUnique;
this.additionals = fields.additionals || [];
}
/**
* Parse a record from a buffer. Starts reading the wrapped buffer at w/e
* position its at when fromBuffer is called.
*
* @param {BufferWrapper} wrapper
* @return {ResourceRecord}
*/
static fromBuffer(wrapper) {
const name = wrapper.readFQDN();
const rrtype = wrapper.readUInt16BE();
const rrclass = wrapper.readUInt16BE();
const ttl = wrapper.readUInt32BE();
// top-bit in rrclass is reused as the cache-flush bit
const fields = {
name,
rrtype,
rrclass : rrclass & ~0x8000,
isUnique: !!(rrclass & 0x8000),
ttl,
};
if (rrtype === RType.A) return new ResourceRecord.A(fields, wrapper);
if (rrtype === RType.PTR) return new ResourceRecord.PTR(fields, wrapper);
if (rrtype === RType.TXT) return new ResourceRecord.TXT(fields, wrapper);
if (rrtype === RType.AAAA) return new ResourceRecord.AAAA(fields, wrapper);
if (rrtype === RType.SRV) return new ResourceRecord.SRV(fields, wrapper);
if (rrtype === RType.NSEC) return new ResourceRecord.NSEC(fields, wrapper);
return new ResourceRecord.Unknown(fields, wrapper);
}
/**
* Makes a couple hashes of record properties so records can get compared
* easier.
*/
_makehashes() {
// a hash for name/rrtype/rrclass (records like PTRs might share name/type
// but have different rdata)
this.namehash = hash(this.name, this.rrtype, this.rrclass);
// hash for comparing rdata
this.rdatahash = this._hashRData();
// a unique hash for a given name/type/class *AND* rdata
this.hash = hash(this.namehash, this.rdatahash);
}
/**
* Writes the record to a wrapped buffer at the wrapper's current position.
* @param {BufferWrapper} wrapper
*/
writeTo(wrapper) {
const classField = (this.isUnique)
? this.rrclass | 0x8000
: this.rrclass;
// record info
wrapper.writeFQDN(this.name);
wrapper.writeUInt16BE(this.rrtype);
wrapper.writeUInt16BE(classField);
wrapper.writeUInt32BE(this.ttl);
// leave UInt16BE gap to write rdataLen
const rdataLenPos = wrapper.tell();
wrapper.skip(2);
// record specific rdata
this._writeRData(wrapper);
// go back and add rdata length
const rdataLen = wrapper.tell() - rdataLenPos - 2;
wrapper.buffer.writeUInt16BE(rdataLen, rdataLenPos);
}
/**
* Checks if this record conflicts with another. Records conflict if they
* 1) are both unique (shared record sets can't conflict)
* 2) have the same name/type/class
* 3) but have different rdata
*
* @param {ResourceRecord} record
* @return {boolean}
*/
conflictsWith(record) {
const hasConflict = (this.isUnique && record.isUnique) &&
(this.namehash === record.namehash) &&
(this.rdatahash !== record.rdatahash);
if (hasConflict) {
debug('Found conflict: \nRecord: %s\nIncoming: %s', this, record);
}
return hasConflict;
}
/**
* Checks if this record can answer the question. Record names are compared
* case insensitively.
*
* @param {QueryRecord} question
* @return {boolean}
*/
canAnswer(question) {
return (this.rrclass === question.qclass || question.qclass === RClass.ANY) &&
(this.rrtype === question.qtype || question.qtype === RType.ANY) &&
(this.name.toUpperCase() === question.name.toUpperCase());
}
/**
* Records are equal if name/type/class and rdata are the same
*/
equals(record) {
return (this.hash === record.hash);
}
/**
* Determines which record is lexicographically later. Used to determine
* which probe wins when two competing probes are sent at the same time.
* (see https://tools.ietf.org/html/rfc6762#section-8.2)
*
* means comparing, in order,
* - rrclass
* - rrtype
* - rdata, byte by byte
*
* Rdata has to be written to a buffer first and then compared.
* The cache flush bit has to be excluded as well when comparing
* rrclass.
*
* 1 = this record comes later than the other record
* -1 = this record comes earlier than the other record
* 0 = records are equal
*
* @param {ResourceRecord} record
* @return {number}
*/
compare(record) {
if (this.equals(record)) return 0;
if (this.rrclass > record.rrclass) return 1;
if (this.rrclass < record.rrclass) return -1;
if (this.rrtype > record.rrtype) return 1;
if (this.rrtype < record.rrtype) return -1;
// make buffers out of em so we can compare byte by byte
// this also prevents data from being name compressed, since
// we are only writing a single rdata, and nothing else
const rdata_1 = new BufferWrapper();
const rdata_2 = new BufferWrapper();
this._writeRData(rdata_1);
record._writeRData(rdata_2);
return rdata_1.unwrap().compare(rdata_2.unwrap());
}
/**
* Test if a record matches some properties. String values are compared
* case insensitively.
*
* Ex:
* > const isMatch = record.matches({name: 'test.', priority: 12})
*
* @param {object} properties
* @return {boolean}
*/
matches(properties) {
return Object.keys(properties)
.map(key => [key, properties[key]])
.every(([key, value]) => {
return (typeof this[key] === 'string' && typeof value === 'string')
? this[key].toUpperCase() === value.toUpperCase()
: misc.equals(this[key], value);
});
}
/**
* Returns a clone of the record, making a new object
*/
clone() {
const type = this.constructor.name;
const fields = this;
return new ResourceRecord[type](fields);
}
/**
* If anything changes on a record it needs to be re-hashed. Otherwise
* all the comparisons won't work with the new changes.
*
* Bad: record.target = 'new.local.';
* Good: record.updateWith(() => {record.target = 'new.local.'});
*
*/
updateWith(fn) {
// give record to updater function to modify
fn(this);
// rehash in case name/rdata changed
this._makehashes();
}
/**
* Records with reserved names shouldn't be goodbye'd
*
* _services._dns-sd._udp.<domain>.
* b._dns-sd._udp.<domain>.
* db._dns-sd._udp.<domain>.
* r._dns-sd._udp.<domain>.
* dr._dns-sd._udp.<domain>.
* lb._dns-sd._udp.<domain>.
*/
canGoodbye() {
const name = this.name.toLowerCase();
return (name.indexOf('._dns-sd._udp.') === -1);
}
/**
* Breaks up the record into an array of parts. Used in misc.alignRecords
* so stuff can get printed nicely in columns. Only ever used in debugging.
*/
toParts() {
const parts = [];
const type = (this.constructor.name === 'Unknown')
? this.rrtype
: this.constructor.name;
const ttl = (this.ttl === 0) ? misc.color(this.ttl, 'red') : String(this.ttl);
parts.push(this.name);
parts.push((this.ttl === 0) ? misc.color(type, 'red') : misc.color(type, 'blue'));
parts.push(ttl);
parts.push(String(this._getRDataStr()));
if (this.isUnique) parts.push(misc.color('(flush)', 'grey'));
return parts;
}
toString() {
return this.toParts().join(' ');
}
} |
JavaScript | class A extends ResourceRecord {
/**
* @param {object} fields
* @param {BufferWrapper} [wrapper] - only used by the .fromBuffer method
*/
constructor(fields, wrapper) {
super(fields);
// defaults:
misc.defaults(this, { ttl: 120, isUnique: true });
// rdata:
this.address = fields.address || '';
if (wrapper) this._readRData(wrapper);
this._makehashes();
}
_readRData(wrapper) {
const _len = wrapper.readUInt16BE();
const n1 = wrapper.readUInt8();
const n2 = wrapper.readUInt8();
const n3 = wrapper.readUInt8();
const n4 = wrapper.readUInt8();
this.address = `${n1}.${n2}.${n3}.${n4}`;
}
_writeRData(wrapper) {
this.address.split('.').forEach((str) => {
const n = parseInt(str, 10);
wrapper.writeUInt8(n);
});
}
_hashRData() {
return hash(this.address);
}
_getRDataStr() {
return this.address;
}
} |
JavaScript | class TXT extends ResourceRecord {
constructor(fields, wrapper) {
super(fields);
// defaults:
misc.defaults(this, { ttl: 4500, isUnique: true });
// rdata:
this.txtRaw = misc.makeRawTXT(fields.txt || {});
this.txt = misc.makeReadableTXT(fields.txt || {});
if (wrapper) this._readRData(wrapper);
this._makehashes();
}
_readRData(wrapper) {
const rdataLength = wrapper.readUInt16BE();
const end = wrapper.tell() + rdataLength;
let len;
// read each key: value pair
while (wrapper.tell() < end && (len = wrapper.readUInt8())) {
let key = '';
let chr, value;
while (len-- > 0 && (chr = wrapper.readString(1)) !== '=') {
key += chr;
}
if (len > 0) value = wrapper.read(len);
else if (chr === '=') value = null;
else value = true;
this.txtRaw[key] = value;
this.txt[key] = (Buffer.isBuffer(value)) ? value.toString() : value;
}
}
_writeRData(wrapper) {
// need to at least put a 0 byte if no txt data
if (!Object.keys(this.txtRaw).length) {
return wrapper.writeUInt8(0);
}
// value is either true, null, or a buffer
Object.keys(this.txtRaw).forEach((key) => {
const value = this.txtRaw[key];
const str = (value === true) ? key : key + '=';
let len = Buffer.byteLength(str);
if (Buffer.isBuffer(value)) len += value.length;
wrapper.writeUInt8(len);
wrapper.writeString(str);
if (Buffer.isBuffer(value)) wrapper.add(value);
});
}
_hashRData() {
return hash(this.txtRaw);
}
_getRDataStr() {
return misc.truncate(JSON.stringify(this.txt), 30);
}
} |
JavaScript | class AAAA extends ResourceRecord {
constructor(fields, wrapper) {
super(fields);
// defaults:
misc.defaults(this, { ttl: 120, isUnique: true });
// rdata:
this.address = fields.address || '';
if (wrapper) this._readRData(wrapper);
this._makehashes();
}
_readRData(wrapper) {
const _len = wrapper.readUInt16BE();
const raw = wrapper.read(16);
const parts = [];
for (let i = 0; i < raw.length; i += 2) {
parts.push(raw.readUInt16BE(i).toString(16));
}
this.address = parts.join(':')
.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')
.replace(/:{3,4}/, '::');
}
_writeRData(wrapper) {
function expandIPv6(str) {
let ip = str;
// replace ipv4 address if any
const ipv4_match = ip.match(/(.*:)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$)/);
if (ipv4_match) {
ip = ipv4_match[1];
const ipv4 = ipv4_match[2].match(/[0-9]+/g);
for (let i = 0; i < 4; i++) {
ipv4[i] = parseInt(ipv4[i], 10).toString(16);
}
ip += ipv4[0] + ipv4[1] + ':' + ipv4[2] + ipv4[3];
}
// take care of leading and trailing ::
ip = ip.replace(/^:|:$/g, '');
const ipv6 = ip.split(':');
for (let i = 0; i < ipv6.length; i++) {
// normalize grouped zeros ::
if (ipv6[i] === '') {
ipv6[i] = new Array(9 - ipv6.length).fill(0).join(':');
}
}
return ipv6.join(':');
}
expandIPv6(this.address).split(':').forEach((str) => {
const u16 = parseInt(str, 16);
wrapper.writeUInt16BE(u16);
});
}
_hashRData() {
return hash(this.address);
}
_getRDataStr() {
return this.address;
}
} |
JavaScript | class NSEC extends ResourceRecord {
constructor(fields, wrapper) {
super(fields);
// defaults:
misc.defaults(this, { ttl: 120, isUnique: true });
// rdata:
this.existing = (fields.existing || []).sort((a, b) => a - b);
if (wrapper) this._readRData(wrapper);
this._makehashes();
}
_readRData(wrapper) {
const rdataLength = wrapper.readUInt16BE();
const rdataEnd = wrapper.tell() + rdataLength;
const _name = wrapper.readFQDN(); // doesn't matter, ignored
const block = wrapper.readUInt8(); // window block for rrtype bitfield
const len = wrapper.readUInt8(); // number of octets in bitfield
// Ignore rrtypes over 255 (only implementing the restricted form)
// Bitfield length must always be < 32, otherwise skip parsing
if (block !== 0 || len > 32) return wrapper.seek(rdataEnd);
// NSEC rrtype bitfields can be up to 256 bits (32 bytes), BUT
// - js bitwise operators are only do 32 bits
// - node's buffer.readIntBE() can only read up to 6 bytes
//
// So here we're doing 1 byte of the field at a time
//
for (let maskNum = 0; maskNum < len; maskNum++) {
const mask = wrapper.readUInt8(1);
if (mask === 0) continue;
for (let bit = 0; bit < 8; bit++) {
if (mask & (1 << bit)) {
// rrtypes in bitfields are in network bit order
// 01000000 => 1 === RType.A (bit 6)
// 00000000 00000000 00000000 00001000 => 28 === RType.AAAA (bit 3)
const rrtype = (8 * maskNum) + (7 - bit);
this.existing.push(rrtype);
}
}
}
}
_writeRData(wrapper) {
// restricted form, only rrtypes up to 255
const rrtypes = [...new Set(this.existing)].filter(x => x <= 255);
// Same problems as _readRData, 32 bit operators and can't write big ints,
// so bitfields are broken up into 1 byte segments and handled one at a time
const len = (!rrtypes.length) ? 0 : (Math.ceil(Math.max(...rrtypes) / 8));
const masks = Array(len).fill(0);
rrtypes.forEach((rrtype) => {
const index = ~~(rrtype / 8); // which mask this rrtype is on
const bit = 7 - (rrtype % 8); // convert to network bit order
masks[index] |= (1 << bit);
});
wrapper.writeFQDN(this.name); // "next domain name", ignored for mdns
wrapper.writeUInt8(0); // block number, always 0 for restricted form
wrapper.writeUInt8(len); // bitfield length in octets
// write masks byte by byte since node buffers can only write 42 bit numbers
masks.forEach(mask => wrapper.writeUInt8(mask));
}
_hashRData() {
return hash(this.existing);
}
_getRDataStr() {
return this.existing.map(rrtype => RNums[rrtype] || rrtype).join(', ');
}
} |
JavaScript | class Unknown extends ResourceRecord {
constructor(fields, wrapper) {
super(fields);
// defaults:
misc.defaults(this, { ttl: 120, isUnique: true });
// rdata:
this.rdata = fields.rdata || Buffer.alloc(0);
if (wrapper) this._readRData(wrapper);
this._makehashes();
}
_readRData(wrapper) {
const rdataLength = wrapper.readUInt16BE();
this.RData = wrapper.read(rdataLength);
}
_writeRData(wrapper) {
wrapper.add(this.RData);
}
_hashRData() {
return hash(this.RData);
}
_getRDataStr() {
// replace non-ascii characters w/ gray dots
function ascii(chr) {
return (/[ -~]/.test(chr)) ? chr : misc.color('.', 'grey');
}
const chars = this.RData.toString().split('');
const str = chars.slice(0, 30).map(ascii).join('');
return (chars.length <= 30) ? str : str + '…';
}
} |
JavaScript | class EventsCustomEventResult extends models['EventsResultData'] {
/**
* Create a EventsCustomEventResult.
* @member {object} [customEvent]
* @member {string} [customEvent.name] The name of the custom event
*/
constructor() {
super();
}
/**
* Defines the metadata of EventsCustomEventResult
*
* @returns {object} metadata of EventsCustomEventResult
*
*/
mapper() {
return {
required: false,
serializedName: 'customEvent',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'type',
clientName: 'type'
},
uberParent: 'EventsResultData',
className: 'EventsCustomEventResult',
modelProperties: {
id: {
required: false,
serializedName: 'id',
type: {
name: 'String'
}
},
count: {
required: false,
serializedName: 'count',
type: {
name: 'Number'
}
},
timestamp: {
required: false,
serializedName: 'timestamp',
type: {
name: 'DateTime'
}
},
customDimensions: {
required: false,
serializedName: 'customDimensions',
type: {
name: 'Composite',
className: 'EventsResultDataCustomDimensions'
}
},
customMeasurements: {
required: false,
serializedName: 'customMeasurements',
type: {
name: 'Composite',
className: 'EventsResultDataCustomMeasurements'
}
},
operation: {
required: false,
serializedName: 'operation',
type: {
name: 'Composite',
className: 'EventsOperationInfo'
}
},
session: {
required: false,
serializedName: 'session',
type: {
name: 'Composite',
className: 'EventsSessionInfo'
}
},
user: {
required: false,
serializedName: 'user',
type: {
name: 'Composite',
className: 'EventsUserInfo'
}
},
cloud: {
required: false,
serializedName: 'cloud',
type: {
name: 'Composite',
className: 'EventsCloudInfo'
}
},
ai: {
required: false,
serializedName: 'ai',
type: {
name: 'Composite',
className: 'EventsAiInfo'
}
},
application: {
required: false,
serializedName: 'application',
type: {
name: 'Composite',
className: 'EventsApplicationInfo'
}
},
client: {
required: false,
serializedName: 'client',
type: {
name: 'Composite',
className: 'EventsClientInfo'
}
},
type: {
required: true,
serializedName: 'type',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
customEvent: {
required: false,
serializedName: 'customEvent',
type: {
name: 'Composite',
className: 'EventsCustomEventInfo'
}
}
}
}
};
}
} |
JavaScript | class TableWithRipplesExample {
constructor() {
this.displayedColumns = ['name'];
this.dataSource = ELEMENT_DATA;
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
viewport: {
latitude: 37.785164,
longitude: -122.4,
zoom: 11,
bearing: 0,
pitch: 0
},
popupInfo: null
};
this._map = React.createRef();
}
_updateViewport = viewport => {
this.setState({viewport});
};
_onClick = event => {
const feature = event.features[0];
if (feature) {
// calculate the bounding box of the feature
const [minLng, minLat, maxLng, maxLat] = bbox(feature);
// construct a viewport instance from the current state
const viewport = new WebMercatorViewport(this.state.viewport);
const {longitude, latitude, zoom} = viewport.fitBounds([[minLng, minLat], [maxLng, maxLat]], {
padding: 40
});
this.setState({
viewport: {
...this.state.viewport,
longitude,
latitude,
zoom,
transitionInterpolator: new LinearInterpolator({
around: [event.offsetCenter.x, event.offsetCenter.y]
}),
transitionDuration: 1000
}
});
}
};
render() {
const {viewport} = this.state;
return (
<MapGL
ref={this._map}
mapStyle={MAP_STYLE}
interactiveLayerIds={['sf-neighborhoods-fill']}
{...viewport}
width="100%"
height="100%"
onClick={this._onClick}
onViewportChange={this._updateViewport}
mapboxApiAccessToken={TOKEN}
>
<ControlPanel containerComponent={this.props.containerComponent} />
</MapGL>
);
}
} |
Subsets and Splits