language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Sidenav extends AxentixComponent {
static getDefaultOptions() {
return {
overlay: true,
bodyScrolling: false,
animationDuration: 300,
};
}
/**
* Construct Sidenav instance
* @constructor
* @param {String} element
* @param {Object} options
*/
constructor(element, options, isLoadedWithData) {
super();
try {
this.preventDbInstance(element);
Axentix.instances.push({ type: 'Sidenav', instance: this });
this.el = document.querySelector(element);
this.options = Axentix.getComponentOptions('Sidenav', options, this.el, isLoadedWithData);
this._setup();
} catch (error) {
console.error('[Axentix] Sidenav init error', error);
}
}
/**
* Setup component
*/
_setup() {
Axentix.createEvent(this.el, 'sidenav.setup');
this.sidenavTriggers = document.querySelectorAll('.sidenav-trigger');
this.isActive = false;
this.isAnimated = false;
this.isFixed = this.el.classList.contains('fixed');
const sidenavFixed = Axentix.getInstanceByType('Sidenav').find((sidenav) => sidenav.isFixed);
this.firstSidenavInit = sidenavFixed && sidenavFixed.el === this.el;
this.extraClasses = [
'sidenav-right',
'sidenav-both',
'sidenav-large',
'sidenav-large-left',
'sidenav-large-right',
];
this.layoutEl = document.querySelector('.layout');
this.layoutEl && this.firstSidenavInit ? this._cleanLayout() : '';
this._setupListeners();
this.options.overlay ? this._createOverlay() : '';
this.layoutEl && this.isFixed ? this._handleMultipleSidenav() : '';
this.el.style.transitionDuration = this.options.animationDuration + 'ms';
}
/**
* Setup listeners
*/
_setupListeners() {
this.listenerRef = this._onClickTrigger.bind(this);
this.sidenavTriggers.forEach((trigger) => {
if (trigger.dataset.target === this.el.id) {
trigger.addEventListener('click', this.listenerRef);
}
});
this.windowResizeRef = this.close.bind(this);
window.addEventListener('resize', this.windowResizeRef);
}
/**
* Remove listeners
*/
_removeListeners() {
this.sidenavTriggers.forEach((trigger) => {
if (trigger.dataset.target === this.el.id) {
trigger.removeEventListener('click', this.listenerRef);
}
});
this.listenerRef = undefined;
window.removeEventListener('resize', this.windowResizeRef);
this.windowResizeRef = undefined;
}
destroy() {
Axentix.createEvent(this.el, 'component.destroy');
this._removeListeners();
this.layoutEl ? this._cleanLayout() : '';
const index = Axentix.instances.findIndex((ins) => ins.instance.el.id === this.el.id);
Axentix.instances.splice(index, 1);
}
_cleanLayout() {
this.extraClasses.map((classes) => this.layoutEl.classList.remove(classes));
}
_handleMultipleSidenav() {
if (!this.firstSidenavInit) {
return;
}
const sidenavs = Array.from(document.querySelectorAll('.sidenav')).filter((sidenav) =>
sidenav.classList.contains('fixed')
);
const { sidenavsRight, sidenavsLeft } = sidenavs.reduce(
(acc, sidenav) => {
sidenav.classList.contains('right-aligned')
? acc.sidenavsRight.push(sidenav)
: acc.sidenavsLeft.push(sidenav);
return acc;
},
{ sidenavsRight: [], sidenavsLeft: [] }
);
const isBoth = sidenavsLeft.length > 0 && sidenavsRight.length > 0;
const sidenavRightLarge = sidenavsRight.some((sidenav) => sidenav.classList.contains('large'));
const sidenavLeftLarge = sidenavsLeft.some((sidenav) => sidenav.classList.contains('large'));
const isLarge = sidenavRightLarge || sidenavLeftLarge;
isLarge ? this.layoutEl.classList.add('sidenav-large') : '';
if (sidenavsRight.length > 0 && !isBoth) {
this.layoutEl.classList.add('sidenav-right');
} else if (isBoth) {
this.layoutEl.classList.add('sidenav-both');
}
if (isLarge && isBoth) {
if (sidenavRightLarge && !sidenavLeftLarge) {
this.layoutEl.classList.add('sidenav-large-right');
} else if (!sidenavRightLarge && sidenavLeftLarge) {
this.layoutEl.classList.add('sidenav-large-left');
}
}
}
/**
* Create overlay element
*/
_createOverlay() {
this.overlayElement = document.createElement('div');
this.overlayElement.classList.add('sidenav-overlay');
this.overlayElement.style.transitionDuration = this.options.animationDuration + 'ms';
this.overlayElement.dataset.target = this.el.id;
}
/**
* Enable or disable body scroll when option is true
* @param {boolean} state
*/
_toggleBodyScroll(state) {
if (!this.options.bodyScrolling) {
state ? (document.body.style.overflow = '') : (document.body.style.overflow = 'hidden');
}
}
/**
* Handle click on trigger
* @param {Event} e
*/
_onClickTrigger(e) {
e.preventDefault();
if (this.isFixed && window.innerWidth >= 960) {
return;
}
this.isActive ? this.close() : this.open();
}
/**
* Open sidenav
*/
open() {
if (this.isActive || this.isAnimated) {
return;
}
Axentix.createEvent(this.el, 'sidenav.open');
this.isActive = true;
this.isAnimated = true;
this.el.classList.add('active');
this.overlay(true);
this._toggleBodyScroll(false);
setTimeout(() => {
this.isAnimated = false;
Axentix.createEvent(this.el, 'sidenav.opened');
}, this.options.animationDuration);
}
/**
* Close sidenav
*/
close() {
if (!this.isActive || this.isAnimated) {
return;
}
this.isAnimated = true;
Axentix.createEvent(this.el, 'sidenav.close');
this.el.classList.remove('active');
this.overlay(false);
setTimeout(() => {
this._toggleBodyScroll(true);
this.isActive = false;
this.isAnimated = false;
Axentix.createEvent(this.el, 'sidenav.closed');
}, this.options.animationDuration);
}
/**
* Manage overlay
* @param {boolean} state
*/
overlay(state) {
if (this.options.overlay) {
if (state) {
this.overlayElement.addEventListener('click', this.listenerRef);
document.body.appendChild(this.overlayElement);
setTimeout(() => {
this.overlayElement.classList.add('active');
}, 50);
} else {
this.overlayElement.classList.remove('active');
setTimeout(() => {
this.overlayElement.removeEventListener('click', this.listenerRef);
document.body.removeChild(this.overlayElement);
}, this.options.animationDuration);
}
}
}
} |
JavaScript | class Post1 extends Model {
collection () {
return 'posts';
}
} |
JavaScript | class AppError extends Error {
constructor(message, status){
super(message);
this.message = message;
this.status = status;
}
} |
JavaScript | class SanshokuDokouYaku {
/** @override */
check (hand) {
const storedPons = {}
for (const combination of hand.combinations) {
if (combination instanceof Triplet || combination instanceof Quad) {
const tile = combination.tiles[0]
if (tile instanceof NumberedTile) {
if (storedPons[tile.number] == null) storedPons[tile.number] = 0
storedPons[tile.number]++
if (storedPons[tile.number] === 3) return { key: 'sanshoku doukou', hanValue: 2, yakumanValue: 0 }
}
}
}
}
} |
JavaScript | class DefaultController {
/**
* Construct the class
* @param {Object} config
* @returns {Void}
*/
constructor(config) {
this.parameter = new ParameterValidator();
this.responseError = new ResponseError();
this.config = this.parameter.set(config).isObject().value();
}
/**
* Require a library for the current platform
*
* @todo:
* This is a potential bottleneck since there is no
* static load path that can be evaluated. But I have
* no better implementation of how to load a file
* dynamically for the specified platform.
*
* @param {String} path
* @returns {Class}
*/
requireLib(path) {
return RequireLibrary(path, this.config.app.platform);
}
} |
JavaScript | class AuthService {
// GET USER DATA FROM TOKEN
getProfile() {
return decode(this.getToken());
}
// CHECK IF USER IS LOGGED IN BY THE TOKEN
loggedIn() {
const token = this.getToken();
// IF THERE IS A TOKEN AND IT'S NOT EXPIRED RETURN TRUE
// ELSE, RETURN FALSE (I.E. NOT LOGGED IN)
return token && !this.isTokenExpired(token) ? true : false;
}
// CHECK IF TOKEN IS EXPIRED
isTokenExpired(token) {
// DECODE TOKEN TO GET EXPIRATION SET BY SERVER
const decoded = decode(token);
// IF THE EXPIRATION TIME IS LESS THAN THE CURRENT TIME (IN SEC),
// TOKEN IS EXPIRED AND WE REMOVE TOKEN FROM LOCAL STORAGE & REDIRECT TO HOME
if (decoded.exp < Date.now() / 1000) {
localStorage.removeItem('id_token');
window.location.assign('/');
// RETURN TRUE (I.E. TOKEN HAS EXPIRED)
return true;
}
// IF TOKEN HASN'T PASSED IT'S EXPIRATION, RETURN FALSE
return false;
}
// RETRIEVE USER TOKEN FROM LOCAL STORAGE
getToken() {
return localStorage.getItem('id_token');
}
// SAVES USER TOKEN TO LOCAL STORAGE ON LOGIN/SIGNUP
// AND REDIRECTS TO HOMEPAGE
login(idToken) {
localStorage.setItem('id_token', idToken);
window.location.assign('/');
}
// REMOVES USER TOKEN FROM LOCAL STORAGE ON LOGOUT
// AND REDIRECTS TO HOMEPAGE
logout() {
localStorage.removeItem('id_token');
window.location.reload();
}
} |
JavaScript | class MatrixStorage extends MatrixBase {
/**
* Base constructor, should be called only from a derived class.
*
* @param {number} size The matrix's storage size.
* @param {ArrayLikeType|Constructor} dataOrType Either data or type. Data is reused, not copied. Data should be in column-major order.
*/
// data is reused, not copied!
constructor(size, dataOrType = Float64Array) {
if (new.target === MatrixStorage) {
throw new TypeError('Cannot construct MatrixStorage instances directly');
}
assert(size > 0, `Matrix storage size (${size}) should be positive`);
super();
if (typeof dataOrType === 'function') {
this._type = dataOrType;
this._data = new this._type(size);
}
else if (typeof dataOrType === 'object') {
this._type = dataOrType.constructor;
this._data = dataOrType;
}
else {
throw new Error('dataOrType should be either a data or constructor');
}
}
_getOffset(offset) {
return this._data[offset];
}
_setOffset(offset, value) {
this._data[offset] = value;
}
get type() {
return this._type;
}
fill(value) {
this._data.fill(value);
return this;
}
} |
JavaScript | class Stepper extends EventEmitter {
/**
* Create a stepper motor controller instance
* @param {Object} config - An object of configuration parameters
* @param {number[]} config.pins - An array of Raspberry Pi GPIO pin numbers _(NOT WiringPi pin numbers)_
* @param {number} [config.steps=200] - The number of steps per motor revolution
* @param {Mode} [config.mode=MODES.DUAL] - GPIO pin activation sequence
* @param {number} [config.speed=1] - Motor rotation speed in RPM
* @example <caption>Initialize a stepper controller on pins 17, 16, 13, and 12, for a motor with 200 steps per revolution</caption>
* import { Stepper } from 'wpi-stepper';
* const motor = new Stepper({ pins: [ 17, 16, 13, 12 ], steps: 200 });
* @returns {Object} an instance of Stepper
*/
constructor({ pins, steps = 200, mode = MODES.DUAL, speed = 1 }) {
super();
this.mode = mode;
this.pins = pins;
this.steps = steps;
this.stepNum = 0;
this.moving = false;
this.direction = null;
this.speed = speed;
this._moveTimer = new NanoTimer();
this._powered = false;
this._validateOptions();
wpi.setup('gpio');
for (let pin of this.pins) {
wpi.pinMode(pin, OUTPUT);
}
}
/**
* The maximum speed at which the motor can rotate (as dictated by our
* timing resolution). _Note: This is not your motor's top speed; it's the computer's.
* This library has not been tested with actual motor speeds in excess of 300 RPM.
* @type {number}
*/
get maxRPM() {
return 60 * 1e6 / this.steps;
}
/**
* Returns the absolute value of the current motor step
* @type {number}
*/
get absoluteStep() {
return Math.abs(this.stepNum);
}
/**
* Set motor speed in RPM
* @type {number}
* @param {number} rpm - The number of RPMs
* @fires Stepper#speed
* @example <caption>Sets the speed to 20 RPM</caption>
* motor.speed = 20;
* // => 20
* @example <caption>Receive notifications when motor speed changes</caption>
* motor.on('speed', (rpms, stepDelay) => console.log('RPM: %d, Step Delay: %d', rpms, stepDelay));
* motor.speed = 20;
* // => 20
* // => "RPM: 20, Step Delay: 15000"
*/
set speed(rpm) {
this._rpms = rpm;
if (this._rpms > this.maxRPM) {
this._rpms = this.maxRPM;
}
this._stepDelay = this.maxRPM / this._rpms;
/**
* Speed change event
* @event Stepper#speed
* @param {number} rpms - The current RPM number
* @param {number} stepDelay - The current step delay in microseconds
*/
this.emit('speed', this._rpms, this._stepDelay);
}
get speed() {
return this._rpms;
}
/**
* Stop the motor and power down all GPIO pins
* @fires Stepper#stop
* @example <caption>Log to console whenever the motor stops</caption>
* motor.on('stop', () => console.log('Motor stopped'));
* motor.stop();
* // => undefined
* // => "Motor stopped"
* @returns {undefined}
*/
stop() {
this._stopMoving();
this._powerDown();
/**
* Fires when the motor stops moving AND powers off all magnets
* @event Stepper#stop
*/
this.emit('stop');
}
/**
* Stop moving the motor and hold position
* @fires Stepper#hold
* @example <caption>Log to console when the motor holds position</caption>
* motor.on('hold', () => console.log('Holding position'));
* motor.hold();
* // => undefined
* // => "Holding position"
* @returns {undefined}
*/
hold() {
this._stopMoving();
/**
* Fires when the motor stops moving and holds its current position
* @event Stepper#hold
*/
this.emit('hold');
}
/**
* Move the motor a specified number of steps. Each step fires a `move` event. If another call to `move()`
* is made while a motion is still executing, the previous motion will be cancelled and a `cancel` event
* will fire.
* @param {number} stepsToMove - Positive for forward, negative for backward
* @fires Stepper#start
* @fires Stepper#move
* @fires Stepper#complete
* @fires Stepper#hold
* @fires Stepper#cancel
* @example <caption>Move the motor forward one full rotation, then log to console</caption>
* motor.move(200).then(() => console.log('Motion complete'));
* // => Promise
* // => "Motion complete"
* @example <caption>Same thing, using an event handler instead of a promise</caption>
* motor.on('complete', () => console.log('Motion complete'));
* motor.move(200);
* // => Promise
* // => "Motion complete"
* @returns {Promise.<number>} A promise resolving to the number of steps moved
*/
move(stepsToMove) {
if (stepsToMove === 0) {
return this.hold();
}
if (this.moving) {
/**
* Emitted when a motion is cancelled, before a new one begins
* @event Stepper#cancel
*/
this.emit('cancel');
this.hold();
}
this.moving = true;
let remaining = Math.abs(stepsToMove);
this.direction = stepsToMove > 0 ? FORWARD : BACKWARD;
/**
* Fires right before a new motion begins
* @event Stepper#start
* @param {Direction} direction
* @param {number} stepsToMove - The requested number of steps to move
*/
this.emit('start', this.direction, stepsToMove);
return new Promise((resolve) => {
this._moveTimer.setInterval(() => {
if (remaining === 0) {
/**
* Fires when a motion is completed and there are no more steps to move, right before the motor holds position
* @event Stepper#complete
*/
this.emit('complete');
this.hold();
return resolve(this.stepNum);
}
this.step(this.direction);
remaining--;
}, '', `${this._stepDelay}u`);
});
}
/**
* Run the motor in the given direction indefinitely
* @fires Stepper#cancel
* @fires Stepper#start
* @fires Stepper#move
* @fires Stepper#complete
* @fires Stepper#hold
* @param {Direction} [direction=FORWARD] - The direction in which to move (`FORWARD` or `BACKWARD`)
* @returns {undefined} nothing
*/
run(direction = FORWARD) {
this.move(direction * Infinity);
}
/**
* Moves the motor a single step forward. Convenience method for `this.step(FORWARD)`.
* @fires Stepper#move
* @returns {number} The motor's current step number
*/
stepForward() {
return this.step(FORWARD);
}
/**
* Moves the motor a single step backward. Convenience method for `this.step(BACKWARD)`.
* @fires Stepper#move
* @returns {number} The motor's current step number
*/
stepBackward() {
return this.step(BACKWARD);
}
/**
* Move the motor one step in the given direction
* @fires Stepper#move
* @param {Direction} direction - The direction in which to move
* @returns {number} The motor's current step number
*/
step(direction) {
if (!direction) {
return;
}
const phase = this._countStep(direction);
const pinStates = this.mode[phase];
this._setPinStates(...pinStates);
/**
* Fires each time the motor moves a step
* @event Stepper#move
* @param {number} direction - 1 for forward, -1 for backward
* @param {number} phase - Current pin activation phase
* @param {number[]} pinStates - Current pin activation states
*
* @example <caption>Log each step moved, in excruciating detail</caption>
* motor.on('move', (direction, phase, pinStates) => {
* console.debug(
* 'Moved one step (direction: %d, phase: %O, pinStates: %O)',
* direction,
* phase,
* pinStates
* );
* });
* motor.move(200);
* // => Promise
*/
this.emit('move', direction, phase, pinStates);
return this.stepNum;
}
/**
* Attach a `bunyan` logger instance to report on all possible events at varying detail levels.
* @param {Logger} logger - a Bunyan logger instance
* @returns {undefined}
*/
attachLogger(logger) {
const childLog = logger.child({ module: 'Stepper' });
this.on('power', () => childLog.info({ powered: this._powered }, 'power toggled'));
this.on('speed', () => childLog.info({ rpms: this._rpms, stepDelay: this._stepDelay }, 'speed changed'));
this.on('hold', () => childLog.info('holding position'));
this.on('start', (direction, steps) => childLog.info({ direction, steps }, 'starting motion'));
this.on('stop', () => childLog.info('stopping'));
this.on('cancel', () => childLog.info('cancelling previous motion'));
this.on('move', (direction, phase, pinStates) => {
childLog.debug({ direction, phase, pinStates }, 'move one step');
});
this.on('complete', () => childLog.info({ numSteps: this._numSteps }, 'motion complete'));
}
/**
* Stop all queued motion
* @private
* @returns {undefined}
*/
_stopMoving() {
this._resetMoveTimer();
this.moving = false;
}
_powerDown() {
let pins = [ ...this.pins ];
this._powered = false;
_.fill(pins, 0);
this._setPinStates(...pins);
this.emit('power', false);
}
_setPinStates(...states) {
if (states.length !== this.pins.length) {
throw new Error(`Must pass exactly ${this.pins.length} pin states`);
}
for (let [idx, val] of states.entries()) {
wpi.digitalWrite(this.pins[idx], val);
if (!this._powered && val === 1) {
this._powered = true;
this.emit('power', true);
}
}
}
_resetMoveTimer() {
this._moveTimer.clearInterval();
}
_countStep(direction) {
this.stepNum += direction;
if (this.stepNum >= this.steps) {
this.stepNum = 0;
} else if (this.stepNum < 0) {
this.stepNum = this.steps - 1;
}
return this.absoluteStep % this.mode.length;
}
_validateOptions() {
const { mode, pins } = this;
const invalidStep = _.findIndex(mode, (step) => step.length !== pins.length);
if (invalidStep !== -1) {
throw new Error(`Mode step at index ${invalidStep} has the wrong number of pins`);
}
}
} |
JavaScript | class App extends React.Component {
render() {
return(
<div className="notificationsFrame">
<div className="panel">
<Header />
<Content />
</div>
</div>
)
}
} |
JavaScript | class RawEntity {
constructor() {
this.name;
this.path;
this[constants.TYPE_DOT] = [];
this[constants.TYPE_MARKDOWN] = [];
this[constants.TYPE_YAML] = [];
}
} |
JavaScript | class RawAction {
constructor() {
this.name;
this.path;
this.action;
}
} |
JavaScript | class RawStory {
constructor(foundStory, config, actions, entities) {
this.foundStory = foundStory;
this.config = config;
this.actions = actions;
this.entities = entities;
if (constants.KEY_VERSION in config &&
Number.isInteger(config[constants.KEY_VERSION])) {
// Version specified and an integer. Load it in.
this.version = config[constants.KEY_VERSION];
} else {
// Version not specified or not an integer. Assume latest.
this.version = constants.STORY_FILES_VERSION;
}
}
} |
JavaScript | class RawFile {
constructor(name, contents) {
this.name = name;
this.contents = contents;
}
} |
JavaScript | class Page {
get root() {
return $(".App");
}
get sitemapLinkAboutUs() {
return $(".sitemap-container").$("a.link=About Us");
}
get sitemapLinkAccessibility() {
return $(".sitemap-container").$("a.link=Accessibility");
}
get sitemapLinkDataSources() {
return $(".sitemap-container").$("a.link=Data Sources");
}
get sitemapLinkRegionalInsights() {
return $(".sitemap-container").$("a.link=Regional Insights");
}
get sitemapLinkSummaryStatistics() {
return $(".sitemap-container").$("a.link=Summary Statistics");
}
get navbarLinkRegionalInsights() {
return $(".dashboard-navbar").$(".nav-link=Regional Insights");
}
get navbarLinkSummaryStatistics() {
return $(".dashboard-navbar").$(".nav-link=Summary Statistics");
}
get navbarLinkLogo() {
return $(".dashboard-navbar").$("#logo");
}
open(path = browser.options.baseUrl) {
return browser.url(path);
}
} |
JavaScript | class TextArea extends Control {
constructor(settings = {}) {
settings.type = settings.type || controlTypes.TEXT_AREA;
settings.element = 'textarea';
super(settings);
applySettings(this, settings);
}
} |
JavaScript | class Farmer extends Component {
constructor(props){
super(props);
this.greetingFarmer = this.greetingFarmer.bind(this);
}
// Addition of values to greetingFarmer
greetingFarmer(){
alert('Hello User! my name is Frank, The Farmer! Thank you for coming to my Market.');
}
// Redenering what has been stated above
// Returning the following values
// On button click the greetingFarmer method is run
/* RELATED TO THE ASSIGNMENT
* I tried to display an image above the button for the farmer to have a face
* Intially no image was displaying at all even with additional CSS
* Even with inline styling, only a border of what is supposed to be the picture is still there
* I set FarmerImage to reference Farmer.jpg and called upon FarmerImage in an img tag bellow
* Thank you for your help in advance
*/
render(){
return(
<div>
<img src={FarmerImage} width="300" height="300" alt="farmer with a hat!"/>
<div>
<button onClick={this.greetingFarmer}>
Talk to the Farmer
</button>
</div>
</div>
);
}
} |
JavaScript | class FormTemplate {
constructor(data){
this.template = `<form action="" class="login-form">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="password">
<button class="button" type="submit">Login</button>
</form>`;
}
} |
JavaScript | class Graph
{
constructor(canvas, noLabels, valueIDs, unit, intervalSize, maxVal, vlines, timestamps, scalesteps,linecolor)
{
/* Get the drawing context */
this.canvas = canvas;
var ctx = canvas.getContext("2d");
this.ctx = ctx;
/* Set proper height and width */
this.setWidthHeight()
/* Initialize class variables */
this.scalesteps = scalesteps
this.noLabels = noLabels;
this.intervalSize = intervalSize;
this.nValuesFloat = this.width/intervalSize
this.nValues = Math.round(this.nValuesFloat)+1;
this.points = emptyArray(noLabels, this.nValues);
this.timestamps_array = emptyArray(1, this.nValues, "");
this.colors = colorArray(noLabels);
this.maxVal = maxVal;
this.valueIDs = valueIDs;
this.unit = unit;
this.vlines = vlines;
this.timestamps = timestamps;
}
setWidthHeight()
{
this.cssScale = window.devicePixelRatio;
/* Set canvas height and width */
this.canvas.width = this.canvas.clientWidth*this.cssScale;
this.canvas.height = this.canvas.clientHeight*this.cssScale;
this.width = this.ctx.canvas.width;
this.height = this.ctx.canvas.height;
}
update(values,max_val,linecolor) /*AVB add maxval*/
{
for(var i = 0; i < this.noLabels; i++) {
/* Update scale */
this.maxVal = max_val /*AVB added this line*/
if(values[i] > this.maxVal) {
this.maxVal = values[i];
}
/* Shift new point into points array */
this.points = shiftArrayRowLeft(this.points, i, this.nValues, values[i]);
/* Update value */
byID(this.valueIDs[i]).innerHTML = `<span style="color: cadetblue;"> ${values[i].toFixed(2)} </span> ${this.unit}`;
}
/* Log time and add to timestamps_array array */
var d = new Date();
var timestamp_str = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
this.timestamps_array = shiftArrayRowLeft(this.timestamps_array, 0, this.nValues, timestamp_str);
/* Clear canvas */
this.ctx.clearRect(0, 0, this.width, this.height);
/* Set proper height and width */
this.setWidthHeight()
/* update interval size */
this.intervalSize = this.width/this.nValuesFloat;
/* Set line width */
this.ctx.lineWidth = 2*this.cssScale;
/* Set font for canvas */
this.ctx.font = (10*this.cssScale)+"px monospace";
/* Draw vertical scale */
if(this.vlines)
{
for(var i = this.nValues-1; i >= 0; i--)
{
/* Calculate line coordinates */
var x = (i+1)*this.intervalSize;
/* Draw line */
this.ctx.beginPath();
this.ctx.moveTo(x, 0);
this.ctx.lineTo(x, this.height);
this.ctx.strokeStyle = "#e3e3e3";
this.ctx.stroke();
}
}
/* Draw horizontal scale */
var hstep = this.height/this.scalesteps;
var sstep = this.maxVal/this.scalesteps;
for(var i = 1; i <= this.scalesteps; i++)
{
var y = this.height-i*hstep
var xoffset = this.width-25*this.cssScale;
var yoffset = 12*this.cssScale;
if (i>1) {this.ctx.fillText(((i-1)*sstep).toFixed(2), xoffset, y+yoffset);}
this.ctx.beginPath();
this.ctx.moveTo(0, y);
this.ctx.lineTo(this.width, y);
this.ctx.strokeStyle = "#e3e3e3";
this.ctx.stroke();
}
/* Draw time stamps */
if(this.timestamps)
{
var xBoundPix = this.ctx.measureText((this.scalesteps*sstep).toFixed(2)).width;
var xBound = Math.floor((xBoundPix/this.intervalSize)+1)
for(var i = this.nValues-1; i >= xBound; i--)
{
/* Calculate line coordinates */
var x = (i+1)*this.intervalSize;
/* Put time stamps */
var xoffset = this.width-25*this.cssScale;
var yoffset = this.ctx.measureText(this.timestamps_array[0][i]).width+4*this.cssScale;
this.ctx.rotate(Math.PI/2);
this.ctx.fillText(this.timestamps_array[0][i], this.height-yoffset, -x+xoffset);
this.ctx.stroke();
this.ctx.rotate(-Math.PI/2);
}
}
/* Draw graph */
for(var i = 0; i < this.noLabels; i++)
{
for(var j = this.nValues-1; j > 0; j--)
{
/* Calculate line coordinates */
var xstart = (j+1)*this.intervalSize-50*this.cssScale;
var xend = j*this.intervalSize-50*this.cssScale;
/*var xend = this.width-25*this.cssScale;*/
var ystart = scaleInvert(this.points[i][j], this.maxVal, this.height);
var yend = scaleInvert(this.points[i][j-1], this.maxVal, this.height);
/* Draw line */
this.ctx.beginPath();
this.ctx.moveTo(xstart, ystart);
this.ctx.lineTo(xend, yend);
this.ctx.strokeStyle = linecolor; /*this.colors[i];*/
this.ctx.stroke();
}
}
}
} |
JavaScript | class AssociationCollectionEntity extends Entity {
getSingleAssocationHrefs() {
if (!this._entity) {
return [];
}
const singleAssociations = this._entity.getSubEntitiesByClass(
Classes.associations.singleAssociation
);
const singleAssociationsHrefs = singleAssociations.map(
a => a.getLinkByRel('self').href
);
return singleAssociationsHrefs;
}
getAllAssociations() {
if (!this._entity) {
return [];
}
const associations = this._entity.getSubEntitiesByRel('item');
return associations.filter(
a => a.hasClass(Classes.associations.singleAssociation)
|| a.hasClass(Classes.associations.potentialAssociation)
);
}
canCreatePotentialAssociation() {
if (!this._entity) {
return false;
}
return this._entity.hasActionByName(Actions.associations.createPotentialAssociation);
}
canCreateAssociation() {
if (!this._entity) {
return false;
}
return this._entity.hasActionByName(Actions.associations.createAssociation);
}
async createPotentialAssociation() {
if (!this._entity || !this._entity.hasActionByName(Actions.associations.createPotentialAssociation)) {
return;
}
const fields = [
{ name: 'type', value: 'rubrics' }
];
const action = this._entity.getActionByName(Actions.associations.createPotentialAssociation);
return await performSirenAction(this._token, action, fields);
}
} |
JavaScript | class ContentKeyPolicyOption {
/**
* Create a ContentKeyPolicyOption.
* @member {uuid} [policyOptionId] The legacy Policy Option ID.
* @member {string} [name] The Policy Option description.
* @member {object} configuration The key delivery configuration.
* @member {string} [configuration.odatatype] Polymorphic Discriminator
* @member {object} restriction The requirements that must be met to deliver
* keys with this configuration
* @member {string} [restriction.odatatype] Polymorphic Discriminator
*/
constructor() {
}
/**
* Defines the metadata of ContentKeyPolicyOption
*
* @returns {object} metadata of ContentKeyPolicyOption
*
*/
mapper() {
return {
required: false,
serializedName: 'ContentKeyPolicyOption',
type: {
name: 'Composite',
className: 'ContentKeyPolicyOption',
modelProperties: {
policyOptionId: {
required: false,
nullable: false,
readOnly: true,
serializedName: 'policyOptionId',
type: {
name: 'String'
}
},
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
configuration: {
required: true,
serializedName: 'configuration',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '@odata.type',
clientName: 'odatatype'
},
uberParent: 'ContentKeyPolicyConfiguration',
className: 'ContentKeyPolicyConfiguration'
}
},
restriction: {
required: true,
serializedName: 'restriction',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '@odata.type',
clientName: 'odatatype'
},
uberParent: 'ContentKeyPolicyRestriction',
className: 'ContentKeyPolicyRestriction'
}
}
}
}
};
}
} |
JavaScript | class CaptionsButton extends buttonMixin('TextTrackButton') {
buildMenu() {
return new CaptionsMenu(this.player(), {
menuButton: this,
});
}
/**
* @override
* @return {string}
*/
buildCSSClass() {
return this.removePopupClass(`vjs-captions-button ${super.buildCSSClass()}`);
}
/**
* @override
* @return {string}
*/
buildWrapperCSSClass() {
return this.removePopupClass(`vjs-captions-button ${super.buildWrapperCSSClass()}`);
}
/**
* @override
* @returns {TranscriptMenuItem[]|SubtitlesMenuItem[]}
*/
createItems() {
// Use logic from parent to determine if we should fill menu
const length = super.createItems().length;
if (length <= 1) {
this.hideThreshold_ = 0;
return [];
}
this.hideThreshold_ = -1;
const player = this.player();
return [new SubtitlesMenuItem(player, {}), new TranscriptMenuItem(player, {})];
}
} |
JavaScript | class MasterBehaviour {
constructor(persoonsvolgend, costBehaviour, reader, tableLoader, tabMgr) {
this.persoonsvolgend = persoonsvolgend;
this.costBehaviour = costBehaviour;
this.reader = reader;
this.newCats = true;
this.loader = tableLoader;
this.table = "dag";
this.processor = undefined;
this.tabMgr = tabMgr;
}
convertBudget() {
//arrow functions
const blankOnZero = num => num == 0 ? "" : num;
//HTML elements
const budgetP = document.getElementById("budgetP");
const budgetE = document.getElementById("budgetE");
const veil = document.querySelector("#veil");
//behaviours
budgetE.addEventListener("input", () => {
budgetP.value = blankOnZero(fixed_p(Math.abs(budgetE.value) / this.persoonsvolgend, 6));
update();
if (veil.getAttribute("hidden") != null) this.costBehaviour.calculateTotal();
});
budgetP.addEventListener("input", () => {
budgetE.value = blankOnZero(fixed_p(Math.abs(budgetP.value) * this.persoonsvolgend, 2));
update();
if (veil.getAttribute("hidden") != null) this.costBehaviour.calculateTotal();
});
}
setPeriodDays() {
const periodDays = document.querySelector("#totaalDagen");
const dates = document.querySelectorAll("input[type='date']");
dates.forEach(d => d.onchange = () => {
periodDays.innerHTML = `${getPeriodDays()} dagen`;
update();
});
dates[0].dispatchEvent(new Event("change"));
}
lockInputs() {
const veil = document.querySelector("#veil");
const bValue = document.querySelector("#bValue");
const pValue = document.querySelector("#pValue");
const inputs = [bValue, pValue];
const weekendMod = this.reader.global.weekend_modifier;
inputs.forEach(inp => inp.addEventListener("input", () => {
const res = bValue.value != "" && pValue.value != "";
const bps = `B${bValue.value}/P${pValue.value}`;
const findInfo = cs => cs.find(c => c.cat_ids.includes(bps));
const cat = this.newCats ? findInfo(this.reader.categories) : findInfo(this.reader.oldCategories);
if (res && cat != undefined && cat != null) {
veil.setAttribute("hidden", "hidden");
const info = cat.cat_info
const category = new Category(info.dag_basis, info.dag_inc, info.woon_basis, info.woon_inc, weekendMod);
this.costBehaviour.rowcalculator.category = category;
document.querySelector("#radioTable input:checked").dispatchEvent(new Event("change"));
update();
}
else veil.removeAttribute("hidden");
}));
}
changeUsedFile() {
const radVersions = document.querySelectorAll(".mainInfo .switch input");
const veil = document.querySelector("#veil");
radVersions.forEach(r => r.onchange = () => {
//set category
this.newCats = document.querySelector(".mainInfo .switch input:checked").value === "true";
document.querySelector("#bValue").dispatchEvent(new Event("input"));
//update de fields
update();
if (veil.getAttribute("hidden") != null) this.costBehaviour.calculateTotal();
//update de tables
document.querySelector("#radioTable input:checked").dispatchEvent(new Event("change"));
});
radVersions[0].dispatchEvent(new Event("change"));
}
loadTable() {
const radios = document.querySelectorAll("#radioTable input[type='radio']");
radios.forEach(r => r.onchange = () => {
const tabel = document.querySelector("#overviews table");
tabel.innerHTML = "";
switch (r.value) {
case "dag":
this.newCats ? this.loader.loadDag(this.reader.categories) :
this.loader.loadDag(this.reader.oldCategories);
if (this.table != "woon" && this.table != "dag") document.querySelector("#overviews").scrollTop = 0;
break;
case "woon":
this.newCats ? this.loader.loadWoon(this.reader.categories) :
this.loader.loadWoon(this.reader.oldCategories);
if (this.table != "woon" && this.table != "dag") document.querySelector("#overviews").scrollTop = 0;
break;
case "indiv":
this.loader.loadPsycho(this.reader.psycho);
document.querySelector("#overviews").scrollTop = 0
break;
case "Bwaarden":
this.newCats ? this.loader.loadDescriptions(this.reader.bValues, "B-waarden") :
this.loader.loadDescriptions(this.reader.oldBValues, "B-waarden");
document.querySelector("#overviews").scrollTop = 0;
break;
case "Pwaarden":
this.newCats ? this.loader.loadDescriptions(this.reader.pValues, "P-waarden") :
this.loader.loadDescriptions(this.reader.oldPValues, "P-waarden");
document.querySelector("#overviews").scrollTop = 0;
break;
case "Begeleid werk":
this.loader.loadPacketDescriptions();
document.querySelector("#overviews").scrollTop = 0;
default:
break;
}
this.table = r.value;
});
}
budgetCatButton(){
const btnHelp = document.querySelector("#budgetCats");
btnHelp.addEventListener("click", () => {
//resview
const resView = document.createElement("div");
resView.classList.add("resView");
document.body.appendChild(resView);
//buttons
const buttons = document.createElement("div");
buttons.classList.add("buttonsP");
buttons.innerHTML = `<input type="button" value="🗙" id="btnCancel">`;
resView.appendChild(buttons);
//table
const tableDiv = document.createElement("div");
tableDiv.classList.add("tableDiv");
const table = this.loader.loadBudgetCats();
tableDiv.appendChild(table);
resView.appendChild(tableDiv);
//behaviour
document.querySelector("#btnCancel").onclick = () => document.body.removeChild(resView);
});
}
downloadBehaviour() {
const btnDownload = document.querySelector("#tabs #others #download");
btnDownload.addEventListener("click", () => {
document.body.style.cursor = 'wait';
this.tabMgr.refreshForDownload();
this.processor.getPreview();
document.body.style.cursor = 'default';
});
}
setMasterBehaviours() {
this.convertBudget();
this.setPeriodDays();
this.lockInputs();
this.changeUsedFile();
this.costBehaviour.setCostBehaviour();
this.loadTable();
this.downloadBehaviour();
this.tabMgr.setTabHandlers();
this.budgetCatButton();
}
} |
JavaScript | class TreeVersioningPolicy {
/**
* Constructs a new <code>TreeVersioningPolicy</code>.
* @alias module:model/TreeVersioningPolicy
* @class
*/
constructor() {
}
/**
* Constructs a <code>TreeVersioningPolicy</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/TreeVersioningPolicy} obj Optional instance to populate.
* @return {module:model/TreeVersioningPolicy} The populated <code>TreeVersioningPolicy</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new TreeVersioningPolicy();
if (data.hasOwnProperty('Uuid')) {
obj['Uuid'] = ApiClient.convertToType(data['Uuid'], 'String');
}
if (data.hasOwnProperty('Name')) {
obj['Name'] = ApiClient.convertToType(data['Name'], 'String');
}
if (data.hasOwnProperty('Description')) {
obj['Description'] = ApiClient.convertToType(data['Description'], 'String');
}
if (data.hasOwnProperty('VersionsDataSourceName')) {
obj['VersionsDataSourceName'] = ApiClient.convertToType(data['VersionsDataSourceName'], 'String');
}
if (data.hasOwnProperty('VersionsDataSourceBucket')) {
obj['VersionsDataSourceBucket'] = ApiClient.convertToType(data['VersionsDataSourceBucket'], 'String');
}
if (data.hasOwnProperty('MaxTotalSize')) {
obj['MaxTotalSize'] = ApiClient.convertToType(data['MaxTotalSize'], 'String');
}
if (data.hasOwnProperty('MaxSizePerFile')) {
obj['MaxSizePerFile'] = ApiClient.convertToType(data['MaxSizePerFile'], 'String');
}
if (data.hasOwnProperty('IgnoreFilesGreaterThan')) {
obj['IgnoreFilesGreaterThan'] = ApiClient.convertToType(data['IgnoreFilesGreaterThan'], 'String');
}
if (data.hasOwnProperty('KeepPeriods')) {
obj['KeepPeriods'] = ApiClient.convertToType(data['KeepPeriods'], [TreeVersioningKeepPeriod]);
}
if (data.hasOwnProperty('NodeDeletedStrategy')) {
obj['NodeDeletedStrategy'] = TreeVersioningNodeDeletedStrategy.constructFromObject(data['NodeDeletedStrategy']);
}
}
return obj;
}
/**
* @member {String} Uuid
*/
Uuid = undefined;
/**
* @member {String} Name
*/
Name = undefined;
/**
* @member {String} Description
*/
Description = undefined;
/**
* @member {String} VersionsDataSourceName
*/
VersionsDataSourceName = undefined;
/**
* @member {String} VersionsDataSourceBucket
*/
VersionsDataSourceBucket = undefined;
/**
* @member {String} MaxTotalSize
*/
MaxTotalSize = undefined;
/**
* @member {String} MaxSizePerFile
*/
MaxSizePerFile = undefined;
/**
* @member {String} IgnoreFilesGreaterThan
*/
IgnoreFilesGreaterThan = undefined;
/**
* @member {Array.<module:model/TreeVersioningKeepPeriod>} KeepPeriods
*/
KeepPeriods = undefined;
/**
* @member {module:model/TreeVersioningNodeDeletedStrategy} NodeDeletedStrategy
*/
NodeDeletedStrategy = undefined;
} |
JavaScript | class HotKeysEnabled extends PureComponent {
static propTypes = {
/**
* A unique key to associate with KeyEventMatchers that allows associating handler
* functions at a later stage
* @typedef {String} ActionName
*/
/**
* Name of a key event
* @typedef {'keyup'|'keydown'|'keypress'} KeyEventName
*/
/**
* A string or list of strings, that represent a sequence of one or more keys
* @typedef {String | Array.<String>} MouseTrapKeySequence
* @see {@link https://craig.is/killing/mice} for support key sequences
*/
/**
* Options for the mapping of a key sequence and event
* @typedef {Object} KeyEventOptions
* @property {MouseTrapKeySequence} sequence - The key sequence required to satisfy a
* KeyEventDescription
* @property {KeyEventName} action - The keyboard state required to satisfy a
* KeyEventDescription
*/
/**
* A description of key sequence of one or more key combinations
* @typedef {MouseTrapKeySequence|KeyMapOptions|Array<MouseTrapKeySequence>} KeyEventDescription
*/
/**
* A mapping from ActionName to KeyEventDescription
* @typedef {Object.<ActionName, KeyEventDescription>} KeyMap
*/
/**
* A map from action names to Mousetrap or Browser key sequences
* @type {KeyMap}
*/
keyMap: PropTypes.object,
/**
* A map from action names to event handler functions
* @typedef {Object<ActionName, Function>} HandlersMap
*/
/**
* A map from action names to event handler functions
* @type {HandlersMap}
*/
handlers: PropTypes.object,
/**
* Function to call when this component gains focus in the browser
* @type {Function}
*/
onFocus: PropTypes.func,
/**
* Function to call when this component loses focus in the browser
* @type {Function}
*/
onBlur: PropTypes.func,
/**
* Whether the keyMap or handlers are permitted to change after the
* component mounts. If false, changes to the keyMap and handlers
* props will be ignored
*/
allowChanges: PropTypes.bool
};
constructor(props) {
super(props);
/**
* The focus and blur handlers need access to the current component as 'this'
* so they need to be bound to it when the component is instantiated
*/
this._handleFocus = this._handleFocus.bind(this);
this._handleBlur = this._handleBlur.bind(this);
this._handleKeyDown = this._handleKeyDown.bind(this);
this._handleKeyPress = this._handleKeyPress.bind(this);
this._handleKeyUp = this._handleKeyUp.bind(this);
this._componentIsFocused = this._componentIsFocused.bind(this);
this._id = KeyEventManager.getInstance().registerKeyMap(props.keyMap);
/**
* We maintain a separate instance variable to contain context that will be
* passed down to descendants of this component so we can have a consistent
* reference to the same object, rather than instantiating a new one on each
* render, causing unnecessary re-rendering of descendant components that
* consume the context.
*
* @see https://reactjs.org/docs/context.html#caveats
*/
this._childContext = { hotKeysParentId: this._id };
}
render() {
const {
/**
* Props used by HotKeys that should not be passed down to its focus trap
* component
*/
keyMap, handlers, allowChanges,
...props
} = this.props;
const hotKeys = {
onFocus: this._wrapFunction('onFocus', this._handleFocus),
onBlur: this._wrapFunction('onBlur', this._handleBlur),
tabIndex: Configuration.option('defaultTabIndex')
};
if (this._shouldBindKeyListeners()) {
hotKeys.onKeyDown = this._handleKeyDown;
hotKeys.onKeyPress = this._handleKeyPress;
hotKeys.onKeyUp = this._handleKeyUp;
}
return (
<Component
hotKeys={ hotKeys }
{ ...props }
/>
);
}
_shouldBindKeyListeners() {
const keyMap = getKeyMap(this.props);
return !isEmpty(keyMap) || (
Configuration.option('enableHardSequences') && this._handlersIncludeHardSequences(keyMap, getHandlers(this.props))
);
}
_handlersIncludeHardSequences(keyMap, handlers) {
return Object.keys(handlers).some((action) => {
return !keyMap[action] && KeyCombinationSerializer.isValidKeySerialization(action);
});
}
_wrapFunction(propName, func){
if (typeof this.props[propName] === 'function') {
return (event) => {
this.props[propName](event);
func(event);
}
} else {
return func;
}
}
_focusTreeIdsPush(componentId) {
if (!this._focusTreeIds) {
this._focusTreeIds = [];
}
this._focusTreeIds.push(componentId);
}
_focusTreeIdsShift() {
if (this._focusTreeIds) {
this._focusTreeIds.shift();
}
}
_getFocusTreeId() {
if (this._focusTreeIds) {
return this._focusTreeIds[0];
}
}
componentDidUpdate(previousProps) {
const keyEventManager = KeyEventManager.getInstance();
keyEventManager.reregisterKeyMap(this._id, this.props.keyMap);
if (this._componentIsFocused() && (this.props.allowChanges || !Configuration.option('ignoreKeymapAndHandlerChangesByDefault'))) {
const {keyMap, handlers} = this.props;
keyEventManager.updateEnabledHotKeys(
this._getFocusTreeId(),
this._id,
keyMap,
handlers,
this._getComponentOptions()
);
}
}
_componentIsFocused() {
return this._focused === true;
}
componentDidMount() {
const keyEventManager = KeyEventManager.getInstance();
const {hotKeysParentId} = this.context;
keyEventManager.registerComponentMount(this._id, hotKeysParentId);
}
/**
* Handles when the component gains focus by calling onFocus prop, if defined, and
* registering itself with the KeyEventManager
* @private
*/
_handleFocus() {
if (this.props.onFocus) {
this.props.onFocus(...arguments);
}
const focusTreeId =
KeyEventManager.getInstance().enableHotKeys(
this._id,
getKeyMap(this.props),
getHandlers(this.props),
this._getComponentOptions()
);
if (!isUndefined(focusTreeId)) {
/**
* focusTreeId should never normally be undefined, but this return state is
* used to indicate that a component with the same componentId has already
* registered as focused/enabled (again, a condition that should not normally
* occur, but apparently can for as-yet unknown reasons).
*
* @see https://github.com/greena13/react-hotkeys/issues/173
*/
this._focusTreeIdsPush(focusTreeId);
}
this._focused = true;
}
componentWillUnmount(){
const keyEventManager = KeyEventManager.getInstance();
keyEventManager.deregisterKeyMap(this._id);
keyEventManager.registerComponentUnmount();
this._handleBlur();
}
/**
* Handles when the component loses focus by calling the onBlur prop, if defined
* and removing itself from the KeyEventManager
* @private
*/
_handleBlur() {
if (this.props.onBlur) {
this.props.onBlur(...arguments);
}
const retainCurrentFocusTreeId = KeyEventManager.getInstance().disableHotKeys(this._getFocusTreeId(), this._id);
if (!retainCurrentFocusTreeId) {
this._focusTreeIdsShift();
}
this._focused = false;
}
/**
* Delegates handing the keydown event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
_handleKeyDown(event) {
const discardFocusTreeId =
KeyEventManager.getInstance().handleKeydown(
event,
this._getFocusTreeId(),
this._id,
this._getEventOptions()
);
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
/**
* Delegates handing the keypress event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
_handleKeyPress(event) {
const discardFocusTreeId =
KeyEventManager.getInstance().handleKeypress(
event,
this._getFocusTreeId(),
this._id,
this._getEventOptions()
);
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
/**
* Delegates handing the keyup event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
_handleKeyUp(event) {
const discardFocusTreeId =
KeyEventManager.getInstance().handleKeyup(
event,
this._getFocusTreeId(),
this._id,
this._getEventOptions()
);
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
_getComponentOptions() {
return {
defaultKeyEvent: Configuration.option('defaultKeyEvent')
};
}
_getEventOptions() {
return {
ignoreEventsCondition: Configuration.option('ignoreEventsCondition')
};
}
} |
JavaScript | class MessageNotification extends ngeoMessageMessage {
/**
* Provides methods to display any sort of messages, notifications, errors,
* etc. Requires Bootstrap library (both CSS and JS) to display the alerts
* properly.
* @param {angular.ITimeoutService} $timeout Angular timeout service.
* @ngInject
*/
constructor($timeout) {
super();
/**
* @type {angular.ITimeoutService}
* @private
*/
this.timeout_ = $timeout;
const container = angular.element('<div class="ngeo-notification"></div>');
angular.element(document.body).append(container);
/**
* @type {JQuery}
* @private
*/
this.container_ = container;
/**
* @type {Object<string, CacheItem>}
* @private
*/
this.cache_ = {};
}
// MAIN API METHODS
/**
* Display the given message string or object or list of message strings or
* objects.
* @param {string | string[] | import('ngeo/message/Message.js').Message | import('ngeo/message/Message.js').Message[]} object
* A message or list of messages as text or configuration objects.
* @return {void}
*/
notify(object) {
this.show(object);
}
/**
* Clears all messages that are currently being shown.
*/
clear() {
for (const uid in this.cache_) {
this.clearMessageByCacheItem_(this.cache_[parseInt(uid, 10)]);
}
}
/**
* @override
* @param {import('ngeo/message/Message.js').Message} message Message.
*/
showMessage(message) {
const type = message.type;
console.assert(typeof type == 'string', 'Type should be set.');
const classNames = ['alert', 'fade', 'show'];
switch (type) {
case MessageType.ERROR:
classNames.push('alert-danger');
break;
case MessageType.INFORMATION:
classNames.push('alert-info');
break;
case MessageType.SUCCESS:
classNames.push('alert-success');
break;
case MessageType.WARNING:
classNames.push('alert-warning');
break;
default:
break;
}
const el = angular.element(`<div class="${classNames.join(' ')}"></div>`);
let container;
if (message.target) {
container = angular.element(message.target);
} else {
container = this.container_;
}
container.append(el);
el.html(message.msg).addClass('show');
const delay = message.delay !== undefined ? message.delay : DEFAULT_DELAY;
const item = /** @type {CacheItem} */ ({
el,
});
// Keep a reference to the promise, in case we want to manually cancel it
// before the delay
const uid = olUtilGetUid(el);
item.promise = this.timeout_(() => {
el.alert('close');
delete this.cache_[uid];
}, delay);
this.cache_[uid] = item;
}
/**
* Clear a message using its cache item.
* @param {CacheItem} item Cache item.
* @private
*/
clearMessageByCacheItem_(item) {
const el = item.el;
const promise = item.promise;
const uid = olUtilGetUid(el);
// Close the message
el.alert('close');
// Cancel timeout in case we want to stop before delay. If called by the
// timeout itself, then this has no consequence.
this.timeout_.cancel(promise);
// Delete the cache item
delete this.cache_[uid];
}
} |
JavaScript | class IppatsuYaku {
/** @override */
check ({ yakus }) {
if (yakus.includes('ippatsu')) return { key: 'ippatsu', hanValue: 1, yakumanValue: 0 }
}
} |
JavaScript | @autobind
class TestDcrInput extends React.Component {
constructor(props) {
super(props);
this.state = { amount: 0 };
}
onChangeAmount({ atomValue }) {
this.setState({ amount: atomValue });
}
render() {
return <DcrInput amount={this.state.amount} onChangeAmount={this.onChangeAmount} />;
}
} |
JavaScript | class Document {
constructor(rootElement, showGrid, rb) {
this.rootElement = rootElement;
this.rb = rb;
this.elDocContent = null;
this.elHeader = null;
this.elContent = null;
this.elFooter = null;
this.elSelectionArea = null;
this.gridVisible = showGrid;
this.gridSize = 10;
this.pdfPreviewExists = false;
// moving/resizing of element
this.dragging = false;
this.dragElementType = null;
this.dragType = DocElement.dragType.none;
this.dragObjectId = null;
this.dragContainerId = null;
this.dragLinkedContainerId = null;
this.dragCurrentContainerId = null;
this.dragStartX = 0;
this.dragStartY = 0;
this.dragCurrentX = 0;
this.dragCurrentY = 0;
this.dragSnapToGrid = false;
this.dragEnterCount = 0;
// drawing rectangle to select multiple elements
this.selectionAreaStarted = false;
this.selectionAreaStartX = 0;
this.selectionAreaStartY = 0;
}
render() {
let panel = $('#rbro_document_panel')
.mousedown(event => {
if (this.rb.isDocElementSelected() && !event.shiftKey) {
this.rb.deselectAll();
}
let offset = this.elDocContent.offset();
this.startSelectionArea(
event.originalEvent.pageX - offset.left, event.originalEvent.pageY - offset.top);
});
let elDocTabs = $('<div id="rbro_document_tabs" class="rbroDocumentTabs"></div>')
.mousedown(event => {
// avoid deselection of doc elements when clicking document tab
event.stopPropagation();
});
elDocTabs.append(
$(`<div id="rbro_document_tab_pdf_layout" class="rbroDocumentTab rbroButton rbroTabButton">
${this.rb.getLabel('documentTabPdfLayout')}</div>`)
.click(event => {
this.setDocumentTab(Document.tab.pdfLayout);
}));
let btnPdfPreview = $(
`<div id="rbro_document_tab_pdf_preview" class="rbroDocumentTab rbroButton rbroTabButton rbroHidden rbroPdfPreview
${this.rb.getProperty('enableSpreadsheet') ? 'rbroXlsxDownload' : ''}">
${this.rb.getLabel('documentTabPdfPreview')}</div>`)
.click(event => {
this.setDocumentTab(Document.tab.pdfPreview);
});
if (this.rb.getProperty('enableSpreadsheet')) {
btnPdfPreview.append($(
`<span class="rbroIcon-xlsx rbroXlsxDownlaodButton" title="${this.rb.getLabel('documentTabXlsxDownload')}"></span>`)
.click(event => { this.rb.downloadSpreadsheet(); }));
}
btnPdfPreview.append($(
`<span class="rbroIcon-cancel" title="${this.rb.getLabel('documentTabClose')}"></span>`)
.click(event => { this.closePdfPreviewTab(); }));
elDocTabs.append(btnPdfPreview);
panel.append(elDocTabs);
let elDoc = $('<div id="rbro_document_pdf" class="rbroDocument rbroDragTarget rbroHidden"></div>');
let docProperties = this.rb.getDocumentProperties();
this.elDocContent = $(`<div id="rbro_document_content"
class="rbroDocumentContent ${this.gridVisible ? 'rbroDocumentGrid' : ''}"></div>`);
this.elHeader = $(`<div id="rbro_header" class="rbroDocumentBand rbroElementContainer"
style="top: 0px; left: 0px;"></div>`);
this.elHeader.append($(`<div class="rbroDocumentBandDescription">${this.rb.getLabel('bandHeader')}</div>`));
this.elDocContent.append(this.elHeader);
this.elContent = $('<div id="rbro_content" class="rbroDocumentBand rbroElementContainer"></div>');
this.elContent.append($(`<div class="rbroDocumentBandDescription">${this.rb.getLabel('bandContent')}</div>`));
this.elDocContent.append(this.elContent);
this.elFooter = $(`<div id="rbro_footer" class="rbroDocumentBand rbroElementContainer"
style="bottom: 0px; left 0px;"></div>`);
this.elFooter.append($(`<div class="rbroDocumentBandDescription">${this.rb.getLabel('bandFooter')}</div>`));
this.elDocContent.append(this.elFooter);
elDoc.append(this.elDocContent);
this.elSelectionArea = $('<div id="rbro_selection_area" class="rbroHidden rbroSelectionArea"></div>');
this.elDocContent.append(this.elSelectionArea);
this.initializeEventHandlers();
elDoc.append('<div id="rbro_divider_margin_left" class="rbroDivider rbroDividerMarginLeft"></div>');
elDoc.append('<div id="rbro_divider_margin_top" class="rbroDivider rbroDividerMarginTop"></div>');
elDoc.append('<div id="rbro_divider_margin_right" class="rbroDivider rbroDividerMarginRight"></div>');
elDoc.append('<div id="rbro_divider_margin_bottom" class="rbroDivider rbroDividerMarginBottom"></div>');
elDoc.append('<div id="rbro_divider_header" class="rbroDivider rbroDividerHeader"></div>');
elDoc.append('<div id="rbro_divider_footer" class="rbroDivider rbroDividerFooter"></div>');
panel.append(elDoc);
panel.append($('<div id="rbro_document_pdf_preview" class="rbroDocumentPreview"></div>'));
let size = docProperties.getPageSize();
this.updatePageSize(size.width, size.height);
this.updateHeader();
this.updateFooter();
this.updatePageMargins();
this.updateDocumentTabs();
this.setDocumentTab(Document.tab.pdfLayout);
}
initializeEventHandlers() {
this.elDocContent.on('dragover', event => {
this.processDragover(event);
})
.on('dragenter', event => {
if (this.rb.isBrowserDragActive('docElement')) {
this.dragEnterCount++;
event.preventDefault(); // needed for IE
}
})
.on('dragleave', event => {
if (this.rb.isBrowserDragActive('docElement')) {
this.dragEnterCount--;
if (this.dragEnterCount === 0) {
$('.rbroElementContainer').removeClass('rbroElementDragOver');
this.dragContainerId = null;
}
}
})
.on('drop', event => {
this.processDrop(event);
return false;
});
}
processMouseMove(event) {
if (this.dragging) {
this.processDrag(event);
} else if (this.selectionAreaStarted) {
let offset = this.elDocContent.offset();
let area = this.getSelectionArea(
event.originalEvent.pageX - offset.left, event.originalEvent.pageY - offset.top);
let props = {
left: this.rb.toPixel(area.left), top: this.rb.toPixel(area.top),
width: this.rb.toPixel(area.width), height: this.rb.toPixel(area.height)};
this.elSelectionArea.css(props);
if (this.elSelectionArea.hasClass('rbroHidden')) {
// show element after css properties are set
this.elSelectionArea.removeClass('rbroHidden');
}
}
}
processDragover(event) {
if (this.rb.isBrowserDragActive('docElement')) {
let absPos = getEventAbsPos(event);
let container = null;
if (absPos !== null) {
container = this.getContainer(absPos.x, absPos.y, this.dragElementType);
this.dragCurrentX = absPos.x;
this.dragCurrentY = absPos.y;
}
let containerId = (container !== null) ? container.getId() : null;
if (containerId !== this.dragContainerId) {
$('.rbroElementContainer').removeClass('rbroElementDragOver');
if (container !== null) {
container.dragOver();
}
this.dragContainerId = containerId;
}
// without preventDefault for dragover event, the drop event is not fired
event.preventDefault();
event.stopPropagation();
}
}
processDrop(event) {
if (this.rb.isBrowserDragActive('docElement')) {
let absPos = getEventAbsPos(event);
if (absPos !== null) {
this.dragCurrentX = absPos.x;
this.dragCurrentY = absPos.y;
}
$('.rbroElementContainer').removeClass('rbroElementDragOver');
let docProperties = this.rb.getDocumentProperties();
let container = this.getContainer(
this.dragCurrentX, this.dragCurrentY, this.dragElementType);
while (container !== null && !container.isElementAllowed(this.dragElementType)) {
container = container.getParent();
}
if (container !== null && container.isElementAllowed(this.dragElementType)) {
let offset = this.elDocContent.offset();
let x = this.dragCurrentX - offset.left;
let y = this.dragCurrentY - offset.top;
let containerOffset = container.getOffset();
x -= containerOffset.x;
y -= containerOffset.y;
if (!event.ctrlKey && this.rb.getDocument().isGridVisible()) {
let gridSize = this.rb.getDocument().getGridSize();
x = utils.roundValueToInterval(x, gridSize);
y = utils.roundValueToInterval(y, gridSize);
}
let initialData = { x: '' + x, y: '' + y, containerId: container.getId() };
let cmd = new AddDeleteDocElementCmd(true, this.dragElementType, initialData,
this.rb.getUniqueId(), container.getId(), -1, this.rb);
this.rb.executeCommand(cmd);
}
event.preventDefault();
$('#rbro_menu_element_drag_item').addClass('rbroHidden');
}
}
processDrag(event) {
let absPos = getEventAbsPos(event);
if (this.dragType === DocElement.dragType.element) {
let container = this.getContainer(
absPos.x, absPos.y, this.dragElementType);
let containerId = null;
if (container !== null) {
containerId = container.getId();
if (containerId === this.dragLinkedContainerId) {
// container is the same as the linked container of dragged element, this is
// the case when dragging container elements like frames
container = container.getParent();
containerId = (container !== null) ? container.getId() : null;
}
}
if (containerId !== this.dragCurrentContainerId) {
$('.rbroElementContainer').removeClass('rbroElementDragOver');
if (container !== null && containerId !== this.dragContainerId) {
container.dragOver();
}
}
this.dragCurrentContainerId = containerId;
}
this.dragCurrentX = absPos.x;
this.dragCurrentY = absPos.y;
this.dragSnapToGrid = !event.ctrlKey;
let dragObject = this.rb.getDataObject(this.dragObjectId);
if (dragObject !== null) {
let dragDiff = dragObject.getDragDiff(
absPos.x - this.dragStartX,
absPos.y - this.dragStartY, this.dragType,
(this.dragSnapToGrid && this.isGridVisible()) ? this.getGridSize() : 0);
this.rb.updateSelectionDrag(dragDiff.x, dragDiff.y, this.dragType, null, false);
}
}
updatePageSize(width, height) {
$('#rbro_document_pdf').css({ width: this.rb.toPixel(width), height: this.rb.toPixel(height) });
}
updatePageMargins() {
let docProperties = this.rb.getDocumentProperties();
let left = this.rb.toPixel(utils.convertInputToNumber(docProperties.getValue('marginLeft')) - 1);
let top = this.rb.toPixel(utils.convertInputToNumber(docProperties.getValue('marginTop')) - 1);
let marginRight = utils.convertInputToNumber(docProperties.getValue('marginRight'));
let marginBottom = utils.convertInputToNumber(docProperties.getValue('marginBottom'));
let right = this.rb.toPixel(marginRight);
let bottom = this.rb.toPixel(marginBottom);
$('#rbro_divider_margin_left').css('left', left);
$('#rbro_divider_margin_top').css('top', top);
// hide right/bottom divider in case margin is 0, otherwise divider is still visible
// because it is one pixel to the left/top of document border
if (marginRight !== 0) {
$('#rbro_divider_margin_right').css('right', right).show();
} else {
$('#rbro_divider_margin_right').hide();
}
if (marginBottom !== 0) {
$('#rbro_divider_margin_bottom').css('bottom', bottom).show();
} else {
$('#rbro_divider_margin_bottom').hide();
}
this.elDocContent.css({ left: left, top: top, right: right, bottom: bottom });
}
updateHeader() {
let docProperties = this.rb.getDocumentProperties();
if (docProperties.getValue('header')) {
let headerSize = this.rb.toPixel(docProperties.getValue('headerSize'));
this.elHeader.css('height', headerSize);
this.elHeader.show();
$('#rbro_divider_header').css('top', this.rb.toPixel(
utils.convertInputToNumber(docProperties.getValue('marginTop')) +
utils.convertInputToNumber(docProperties.getValue('headerSize')) - 1));
$('#rbro_divider_header').show();
this.elContent.css('top', headerSize);
} else {
this.elHeader.hide();
$('#rbro_divider_header').hide();
this.elContent.css('top', this.rb.toPixel(0));
}
}
updateFooter() {
let docProperties = this.rb.getDocumentProperties();
if (docProperties.getValue('footer')) {
let footerSize = this.rb.toPixel(docProperties.getValue('footerSize'));
this.elFooter.css('height', footerSize);
this.elFooter.show();
$('#rbro_divider_footer').css('bottom', this.rb.toPixel(
utils.convertInputToNumber(docProperties.getValue('marginBottom')) +
utils.convertInputToNumber(docProperties.getValue('footerSize'))));
$('#rbro_divider_footer').show();
this.elContent.css('bottom', footerSize);
} else {
this.elFooter.hide();
$('#rbro_divider_footer').hide();
this.elContent.css('bottom', this.rb.toPixel(0));
}
}
setDocumentTab(tab) {
$('#rbro_document_tabs .rbroDocumentTab').removeClass('rbroActive');
// use z-index to show pdf preview instead of show/hide of div because otherwise pdf is reloaded (and generated) again
if (tab === Document.tab.pdfLayout) {
$('#rbro_document_tab_pdf_layout').addClass('rbroActive');
$('#rbro_document_pdf').removeClass('rbroHidden');
$('#rbro_document_pdf_preview').css('z-index', '');
$('.rbroElementButtons .rbroMenuButton').removeClass('rbroDisabled').prop('draggable', true);
$('.rbroActionButtons .rbroActionButton').prop('disabled', false);
} else if (this.pdfPreviewExists && tab === Document.tab.pdfPreview) {
$('#rbro_document_tab_pdf_preview').addClass('rbroActive');
$('#rbro_document_pdf').addClass('rbroHidden');
$('#rbro_document_pdf_preview').css('z-index', '1');
$('.rbroElementButtons .rbroMenuButton').addClass('rbroDisabled').prop('draggable', false);
$('.rbroActionButtons .rbroActionButton').prop('disabled', true);
}
}
openPdfPreviewTab(reportUrl) {
let pdfObj = '<object data="' + reportUrl + '" type="application/pdf" width="100%" height="100%"></object>';
this.pdfPreviewExists = true;
$('#rbro_document_pdf_preview').empty();
$('#rbro_document_pdf_preview').append(pdfObj);
this.setDocumentTab(Document.tab.pdfPreview);
this.updateDocumentTabs();
}
closePdfPreviewTab() {
this.pdfPreviewExists = false;
$('#rbro_document_pdf_preview').empty();
this.setDocumentTab(Document.tab.pdfLayout);
this.updateDocumentTabs();
}
updateDocumentTabs() {
let tabCount = 1;
if (this.pdfPreviewExists) {
$('#rbro_document_tab_pdf_preview').removeClass('rbroHidden');
tabCount++;
} else {
$('#rbro_document_tab_pdf_preview').addClass('rbroHidden');
}
if (tabCount > 1) {
$('#rbro_document_tabs').show();
$('#rbro_document_panel').addClass('rbroHasTabs');
} else {
$('#rbro_document_tabs').hide();
$('#rbro_document_panel').removeClass('rbroHasTabs');
}
}
/**
* Returns container for given absolute position.
* @param {Number} absPosX - absolute x position.
* @param {Number} absPosY - absolute y position.
* @param {String} elementType - needed for finding container, not all elements are allowed
* in all containers (e.g. a frame cannot contain another frame).
* @returns {[Container]} Container or null in case no container was found for given position.
*/
getContainer(absPosX, absPosY, elementType) {
let offset = this.elDocContent.offset();
return this.rb.getContainer(absPosX - offset.left, absPosY - offset.top, elementType);
}
/**
* Returns scroll y position of document content.
* @returns {Number} scroll y position.
*/
getContentScrollPosY() {
let contentOffset = this.elDocContent.offset();
let panelOffset = $('#rbro_document_panel').offset();
return panelOffset.top - contentOffset.top;
}
isGridVisible() {
return this.gridVisible;
}
toggleGrid() {
this.gridVisible = !this.gridVisible;
if (this.gridVisible) {
this.elDocContent.addClass('rbroDocumentGrid');
} else {
this.elDocContent.removeClass('rbroDocumentGrid');
}
}
getGridSize() {
return this.gridSize;
}
getHeight() {
return this.elDocContent.height();
}
getElement(band) {
if (band === Band.bandType.header) {
return this.elHeader;
} else if (band === Band.bandType.content) {
return this.elContent;
} else if (band === Band.bandType.footer) {
return this.elFooter;
}
return null;
}
isDragging() {
return this.dragging;
}
isDragged() {
return this.dragging && ((this.dragStartX !== this.dragCurrentX) || (this.dragStartY !== this.dragCurrentY));
}
startDrag(x, y, objectId, containerId, linkedContainerId, elementType, dragType) {
this.dragging = true;
this.dragStartX = this.dragCurrentX = x;
this.dragStartY = this.dragCurrentY = y;
this.dragElementType = elementType;
this.dragType = dragType;
this.dragObjectId = objectId;
this.dragContainerId = containerId;
this.dragLinkedContainerId = linkedContainerId;
this.dragCurrentContainerId = null;
this.dragSnapToGrid = false;
}
stopDrag() {
let diffX = this.dragCurrentX - this.dragStartX;
let diffY = this.dragCurrentY - this.dragStartY;
let dragObject = this.rb.getDataObject(this.dragObjectId);
if (dragObject !== null && (diffX !== 0 || diffY !== 0)) {
let container = null;
if (this.dragType === DocElement.dragType.element) {
container = this.rb.getDataObject(this.dragCurrentContainerId);
}
let dragDiff = dragObject.getDragDiff(
diffX, diffY, this.dragType, (this.dragSnapToGrid && this.isGridVisible()) ? this.getGridSize() : 0);
this.rb.updateSelectionDrag(dragDiff.x, dragDiff.y, this.dragType, container, true);
} else {
this.rb.updateSelectionDrag(0, 0, this.dragType, null, false);
}
this.dragging = false;
this.dragType = DocElement.dragType.none;
this.dragObjectId = null;
this.dragContainerId = null;
this.dragCurrentContainerId = null;
$('.rbroElementContainer').removeClass('rbroElementDragOver');
}
startBrowserDrag(dragElementType) {
this.dragEnterCount = 0;
this.dragObjectId = null;
this.dragContainerId = null;
this.dragLinkedContainerId = null;
this.dragElementType = dragElementType;
this.dragStartX = 0;
this.dragStartY = 0;
this.dragCurrentX = 0;
this.dragCurrentY = 0;
}
startSelectionArea(x, y) {
this.selectionAreaStarted = true;
this.selectionAreaStartX = x;
this.selectionAreaStartY = y;
}
stopSelectionArea(x, y, clearSelection) {
let area = this.getSelectionArea(x, y);
if (area.width > 10 && area.height > 10) {
let docElements = this.rb.getDocElements(true);
for (let docElement of docElements) {
// do not select table text and table band elements
if (docElement.isDraggingAllowed()) {
let pos = docElement.getAbsolutePosition();
if (area.left < (pos.x + docElement.getValue('widthVal')) &&
(area.left + area.width) >= pos.x &&
area.top < (pos.y + docElement.getValue('heightVal')) &&
(area.top + area.height) >= pos.y) {
let allowSelect = true;
// do not allow selection of element if its container is already selected,
// e.g. text inside selected frame element
if (docElement.getContainerId()) {
let container = docElement.getContainer();
if (container !== null && container.isSelected()) {
allowSelect = false;
}
}
if (allowSelect) {
this.rb.selectObject(docElement.getId(), clearSelection);
clearSelection = false;
}
}
}
}
}
this.selectionAreaStarted = false;
this.selectionAreaStartX = 0;
this.selectionAreaStartY = 0;
this.elSelectionArea.addClass('rbroHidden');
}
getSelectionArea(x, y) {
let area = {};
if (x > this.selectionAreaStartX) {
area.left = this.selectionAreaStartX;
area.width = x - this.selectionAreaStartX;
} else {
area.left = x;
area.width = this.selectionAreaStartX - x;
}
if (y > this.selectionAreaStartY) {
area.top = this.selectionAreaStartY;
area.height = y - this.selectionAreaStartY;
} else {
area.top = y;
area.height = this.selectionAreaStartY - y;
}
return area;
}
mouseUp(event) {
if (this.isDragging()) {
this.stopDrag();
}
if (this.selectionAreaStarted) {
let offset = this.elDocContent.offset();
this.stopSelectionArea(
event.originalEvent.pageX - offset.left,
event.originalEvent.pageY - offset.top,
!event.shiftKey);
}
}
} |
JavaScript | class Notifier {
/**
* set up the channels and default channel
*/
constructor() {
this.channels = [];
this.default = config.get('notifications.default');
}
/**
* Add a channel
* @param name
* @param driver
*/
addChannel(name, driver) {
logger.results(`Added Notification Channel: ${name}`);
this.channels.push({
name,
driver,
});
// give the notifier a chance to set up
driver.init();
}
/**
* Send a message to a channel
* @param msg
* @param extra
* @param where
*/
send(msg, extra, where) {
const target = (where === undefined || where === 'default') ? this.default : [where];
const options = extra || {};
const drivers = this.channels.filter(item => target.find(t => t === item.name));
drivers.forEach(n => n.driver.send(msg, options));
}
/**
* Tell the notifiers about the exchange manager (so they can issue commands)
* @param manager
*/
setExchangeManager(manager) {
this.channels.forEach(n => n.driver.setExchangeManager(manager));
}
} |
JavaScript | class BidirectionalMap extends Map {
constructor(...iterables) {
super(...iterables);
this.otherMap = new Map();
super.forEach(function(val, key) {
otherMap.set(val, key);
});
return super.this;
}
set(a, b) {
super.set(a, b);
this.otherMap.set(b, a);
return super.this;
}
delete(a) {
this.otherMap.delete(this.get(a));
super.delete(a);
return super.this;
}
deleteByValue(b) {
super.delete(this.otherMap.get(b));
this.otherMap.delete(b);
return super.this;
}
deleteByKey(a) {
return this.delete(a);
}
clear() {
this.otherMap.clear();
super.clear();
return undefined;
}
getKey(b) {
return this.otherMap.get(b);
}
getValue(a) {
return super.get(a);
}
hasKey(a) {
return super.has(a);
}
hasValue(b) {
return this.otherMap.has(b);
}
} |
JavaScript | class Particle{
constructor(){
//TODO
this.fov = 45;
// Start position is in the middle of the canvas
this.pos = createVector(width/2, height/ 2);
//An array to hold ray objects
this.rays = [];
//TODO
this.heading = 0;
//Generate the rays
for (let a = -this.fov / 2; a < this.fov / 2; a+=1){
this.rays.push(new Ray(this.pos, radians(a)));
}
}
//TODO
updateFOV(fov){
this.fov = fov;
this.rays = [];
for (let a = -this.fov / 2; a < this.fov / 2; a+=1){
this.rays.push(new Ray(this.pos, radians(a) + this.heading));
}
}
//TODO
rotate(angle){
this.heading += angle;
let index = 0;
for (let a = -this.fov / 2; a < this.fov / 2; a+=1){
this.rays[index].setAngle(radians(a) + this.heading);
index++;
}
}
//TODO
move(amt){
const vel = p5.Vector.fromAngle(this.heading);
vel.setMag(amt);
this.pos.add(vel);
}
// update the portion of the particle
update(x, y){
this.pos.set(x,y);
}
// Look for a wall from walls array (works without walls but its better OOP with)
look(walls){
//TODO
let scene = [];
for(let i = 0; i< this.rays.length; i++){
//TODO
const ray = this.rays[i];
// Start with nothing closest
let closest = null;
// Start looking at infinity
let record = Infinity;
//Walls is a global variable in sketch.js
for(let wall of walls){
//cast to all walls
const pt = ray.cast(wall);
//find the closest wall
if(pt){
// find distance to each wall
let d = p5.Vector.dist(this.pos, pt);
//TODO
const a = ray.dir.heading() - this.heading;
if (!mouseIsPressed){
d *= cos(a);
}
// If a wall is the closest make it the record
if(d < record){
record = d;
closest = pt;
}
// return the smallest number from these 2
record = min(d, record);
}
}
//Draw the ray if closest is not null
if(closest){
stroke(255, 100);
//Draw a line from particle x,y to the closest wall's intersection.
line(this.pos.x, this.pos.y, closest.x, closest.y);
}
//TODO
scene[i] = record;
}
return scene;
}
//Show the particle with it's rays.
show(){
fill(255);
ellipse(this.pos.x, this.pos.y , 4);
this.look(walls);
for (let ray of this.rays){
ray.show();
}
}
} |
JavaScript | class NodeResizingStage extends LayoutStageBase {
/**
* Creates a new instance of NodeResizingStage.
* @param {ILayoutAlgorithm} layout
*/
constructor(layout) {
super(layout)
this.layout = layout
this.$layoutOrientation = LayoutOrientation.LEFT_TO_RIGHT
this.$portBorderGapRatio = 0
this.$minimumPortDistance = 0
}
/**
* Gets the main orientation of the layout. Should be the same value as for the associated core layout
* algorithm.
* @return {LayoutOrientation} The main orientation of the layout
*/
get layoutOrientation() {
return this.$layoutOrientation
}
/**
* Gets the main orientation of the layout. Should be the same value as for the associated core layout
* algorithm.
* @param {LayoutOrientation} orientation One of the default layout orientations
*/
set layoutOrientation(orientation) {
this.$layoutOrientation = orientation
}
/**
* Gets the port border gap ratio for the port distribution at the sides of the nodes.
* Should be the same value as for the associated core layout algorithm.
* @return {number} The port border gap ratio
*/
get portBorderGapRatio() {
return this.$portBorderGapRatio
}
/**
* Sets the port border gap ratio for the port distribution at the sides of the nodes. Should be the same value
* as for the associated core layout algorithm.
* @param {number} portBorderGapRatio The given ratio
*/
set portBorderGapRatio(portBorderGapRatio) {
this.$portBorderGapRatio = portBorderGapRatio
}
/**
* Returns the minimum distance between two ports on the same node side.
* @return {number} The minimum distance between two ports
*/
get minimumPortDistance() {
return this.$minimumPortDistance
}
/**
* Gets the minimum distance between two ports on the same node side.
* @param {number} minimumPortDistance The minimum distance
*/
set minimumPortDistance(minimumPortDistance) {
this.$minimumPortDistance = minimumPortDistance
}
/**
* Applies the layout to the given graph.
* @param {LayoutGraph} graph The given graph
*/
applyLayout(graph) {
graph.nodes.forEach(node => {
this.adjustNodeSize(node, graph)
})
// run the core layout
this.applyLayoutCore(graph)
}
/**
* Adjusts the size of the given node.
* @param {YNode} node The given node
* @param {LayoutGraph} graph The given graph
*/
adjustNodeSize(node, graph) {
let width = 60
let height = 40
const leftEdgeSpace = this.calcRequiredSpace(node.inEdges, graph)
const rightEdgeSpace = this.calcRequiredSpace(node.outEdges, graph)
if (
this.layoutOrientation === LayoutOrientation.TOP_TO_BOTTOM ||
this.layoutOrientation === LayoutOrientation.BOTTOM_TO_TOP
) {
// we have to enlarge the width such that the in-/out-edges can be placed side by side without overlaps
width = Math.max(width, leftEdgeSpace)
width = Math.max(width, rightEdgeSpace)
} else {
// we have to enlarge the height such that the in-/out-edges can be placed side by side without overlaps
height = Math.max(height, leftEdgeSpace)
height = Math.max(height, rightEdgeSpace)
}
// adjust size for edges with strong port constraints
const edgeThicknessDP = graph.getDataProvider(HierarchicLayout.EDGE_THICKNESS_DP_KEY)
if (edgeThicknessDP !== null) {
node.edges.forEach(edge => {
const thickness = edgeThicknessDP.getNumber(edge)
const spc = PortConstraint.getSPC(graph, edge)
if (edge.source === node && spc !== null && spc.strong) {
const sourcePoint = graph.getSourcePointRel(edge)
width = Math.max(width, Math.abs(sourcePoint.x) * 2 + thickness)
height = Math.max(height, Math.abs(sourcePoint.y) * 2 + thickness)
}
const tpc = PortConstraint.getTPC(graph, edge)
if (edge.target === node && tpc !== null && tpc.strong) {
const targetPoint = graph.getTargetPointRel(edge)
width = Math.max(width, Math.abs(targetPoint.x) * 2 + thickness)
height = Math.max(height, Math.abs(targetPoint.y) * 2 + thickness)
}
})
}
graph.setSize(node, width, height)
}
/**
* Calculates the space required when placing the given edge side by side without overlaps and considering
* the specified minimum port distance and edge thickness.
* @param {IEnumerable} edges The edges to calculate the space for
* @param {LayoutGraph} graph The given graph
*/
calcRequiredSpace(edges, graph) {
let requiredSpace = 0
const edgeThicknessDP = graph.getDataProvider(HierarchicLayout.EDGE_THICKNESS_DP_KEY)
let count = 0
edges.forEach(edge => {
const thickness = edgeThicknessDP === null ? 0 : edgeThicknessDP.getNumber(edge)
requiredSpace += Math.max(thickness, 1)
count++
})
requiredSpace += (count - 1) * this.minimumPortDistance
requiredSpace += 2 * this.portBorderGapRatio * this.minimumPortDistance
return requiredSpace
}
} |
JavaScript | class SankeyPopupSupport {
/**
* Constructor that takes the graphComponent, the container div element and an ILabelModelParameter
* to determine the relative position of the popup.
* @param {GraphComponent} graphComponent The given graphComponent.
* @param {Element} div The div element.
* @param {ILabelModelParameter} labelModelParameter The label model parameter that determines
* the position of the pop-up.
*/
constructor(graphComponent, div, labelModelParameter) {
this.graphComponent = graphComponent
this.labelModelParameter = labelModelParameter
this.$div = div
this.$currentItem = null
this.$dirty = false
// make the popup invisible
div.style.opacity = '0'
div.style.display = 'none'
this.registerListeners()
}
/**
* Sets the container {@link HTMLPopupSupport#div div element}.
* @param {HTMLElement} value The div element to be set.
*/
set div(value) {
this.$div = value
}
/**
* Gets the container {@link HTMLPopupSupport#div div element}.
* @return {HTMLElement}
*/
get div() {
return this.$div
}
/**
* Sets the {@link IModelItem item} to display information for.
* Setting this property to a value other than null shows the pop-up.
* Setting the property to null hides the pop-up.
* @param {IModelItem} value The current item.
*/
set currentItem(value) {
if (value === this.$currentItem) {
return
}
this.$currentItem = value
if (value !== null) {
this.show()
} else {
this.hide()
}
}
/**
* Gets the {@link IModelItem item} to display information for.
* @return {IModelItem} The item to display information for
*/
get currentItem() {
return this.$currentItem
}
/**
* Sets the flag for the current position is no longer valid.
* @param {boolean} value True if the current position is no longer valid, false otherwise.
*/
set dirty(value) {
this.$dirty = value
}
/**
* Gets the flag for the current position is no longer valid.
* @return {boolean} True if the current position is no longer valid, false otherwise
*/
get dirty() {
return this.$dirty
}
/**
* Registers viewport, node bounds changes and visual tree listeners to the given graphComponent.
*/
registerListeners() {
// Adds listener for viewport changes
this.graphComponent.addViewportChangedListener(() => {
if (this.currentItem) {
this.dirty = true
}
})
// Adds listeners for node bounds changes
this.graphComponent.graph.addNodeLayoutChangedListener(node => {
if (
((this.currentItem && this.currentItem === node) || IEdge.isInstance(this.currentItem)) &&
(node === this.currentItem.sourcePort.owner || node === this.currentItem.targetPort.owner)
) {
this.dirty = true
}
})
// Adds listener for updates of the visual tree
this.graphComponent.addUpdatedVisualListener(() => {
if (this.currentItem && this.dirty) {
this.dirty = false
this.updateLocation()
}
})
}
/**
* Makes this pop-up visible near the given item.
*/
show() {
this.div.style.display = 'block'
this.div.style.opacity = '1'
this.updateLocation()
}
/**
* Hides this pop-up.
*/
hide() {
this.div.style.opacity = '0'
this.div.style.display = 'none'
}
/**
* Changes the location of this pop-up to the location calculated by the
* {@link HTMLPopupSupport#labelModelParameter}. Currently, this implementation does not support rotated pop-ups.
*/
updateLocation() {
if (!this.currentItem && !this.labelModelParameter) {
return
}
const width = this.div.clientWidth
const height = this.div.clientHeight
const zoom = this.graphComponent.zoom
const dummyLabel = new SimpleLabel(this.currentItem, '', this.labelModelParameter)
if (this.labelModelParameter.supports(dummyLabel)) {
dummyLabel.preferredSize = new Size(width / zoom, height / zoom)
const newLayout = this.labelModelParameter.model.getGeometry(
dummyLabel,
this.labelModelParameter
)
this.setLocation(newLayout.anchorX, newLayout.anchorY - (height + 10) / zoom)
}
}
/**
* Sets the location of this pop-up to the given world coordinates.
* @param {number} x The target x-coordinate of the pop-up.
* @param {number} y The target y-coordinate of the pop-up.
*/
setLocation(x, y) {
// Calculate the view coordinates since we have to place the div in the regular HTML coordinate space
const viewPoint = this.graphComponent.toViewCoordinates(new Point(x, y))
this.div.style.left = `${viewPoint.x}px`
this.div.style.top = `${viewPoint.y}px`
}
} |
JavaScript | class TagUndoUnit extends UndoUnitBase {
/**
* The constructor
* @param {string} undoName Name of the undo operation
* @param {string} redoName Name of the redo operation
* @param {Object} oldTag The data to restore the previous state
* @param {Object} newTag The data to restore the next state
* @param {IModelItem} item The owner of the tag
*/
constructor(undoName, redoName, oldTag, newTag, item) {
super(undoName, redoName)
this.oldTag = oldTag
this.newTag = newTag
this.item = item
}
/**
* Undoes the work that is represented by this unit.
*/
undo() {
this.item.tag = this.oldTag
}
/**
* Redoes the work that is represented by this unit.
*/
redo() {
this.item.tag = this.newTag
}
} |
JavaScript | class DirectoryVisitor {
/**
* Constructor.
* @param {String} dirname - directory name.
* @param {Function} callback - callback function with filename parameter.
*/
constructor(dirname, callback) {
this.dirname = dirname;
this.callback = callback;
}
/**
* Walk the directory structure, invoking the callback for each file.
*/
visit() {
fs.readdirSync(this.dirname).forEach(filename => this.visitDirectoryEntry(filename));
}
/**
* Handle a directory entry.
* @param {String} entryName - directory entry name; either a file or sub-directory.
*/
visitDirectoryEntry(entryName) {
const entryPath = path.resolve(this.dirname, entryName);
const stat = fs.statSync(entryPath);
if (stat.isDirectory()) {
const subDirVisitor = new DirectoryVisitor(entryPath, this.callback);
subDirVisitor.visit();
} else {
this.callback(entryPath);
}
}
} |
JavaScript | class MultiKey {
constructor(scene, keys) {
if (!Array.isArray(keys)) keys = [keys];
this.keys = keys.map(key => scene.input.keyboard.addKey(key));
}
isDown() {
return this.keys.some(key => key.isDown);
}
isUp() {
return this.keys.every(key => key.isUp);
}
} |
JavaScript | class MediaSessionController { // eslint-disable-line no-unused-vars
/**
* Create a MediaSession controller.
* @param {string} audioSelector - Selector for the Audio HTML element.
*/
constructor(audioSelector='audio') {
this._enabled = ('mediaSession' in navigator);
if (!this.enabled) {
console.log('🔈', 'Media Session not available.');
return;
}
this._audioElement = document.querySelector(audioSelector);
if (!this._audioElement) {
console.error('🔈', 'No audio element.');
return;
}
this._audioElement.src = '/sounds/silence.mp3';
this._initMediaSession();
this._audioElement.dispatchEvent(new Event('media-session-ready'));
}
/**
* Is the media session available?
* @readonly
* @member {boolean}
*/
get enabled() {
return this._enabled;
}
/**
* Get the <audio> player play status
* @readonly
* @member {boolean}
*/
get playing() {
if (this._audioElement) {
return !this._audioElement.paused;
}
return false;
}
/**
* Update the Media Session Play state.
* @return {boolean} True if any sounds are currently playing.
*/
updatePlayState() {
if (!this.enabled) {
return;
}
let playing = false;
const elems = document.querySelectorAll('.sound-container button');
elems.forEach((elem) => {
if (elem.getAttribute('aria-checked') === 'true') {
playing = true;
}
});
this._toggleAudioElem(playing);
this._previousState = null;
return playing;
}
/**
* Initializes the media session API.
* @private
*/
_initMediaSession() {
const defaultMetadata = {
title: 'SoundDrown',
album: 'White Noise Generator',
artwork: [
{src: '/images/48.png', sizes: '48x48', type: 'image/png'},
{src: '/images/192.png', sizes: '192x192', type: 'image/png'},
{src: '/images/256.png', sizes: '256x256', type: 'image/png'},
{src: '/images/512.png', sizes: '512x412', type: 'image/png'},
],
};
// eslint-disable-next-line no-undef
navigator.mediaSession.metadata = new MediaMetadata(defaultMetadata);
navigator.mediaSession.setActionHandler('play', (evt) => {
this._handlePlay(evt);
});
navigator.mediaSession.setActionHandler('pause', (evt) => {
this._handlePause(evt);
});
}
/**
* Play or Pause the <audio> player.
* @private
* @param {boolean} start - True starts, false pauses the <audio> element.
* @return {boolean} The current media session play state.
*/
_toggleAudioElem(start) {
if (!this._audioElement) {
console.error('🔈', 'No audio element.');
return;
}
start = !!start;
if ((start && this.playing) || (!start && !this.playing)) {
return this.playing;
}
if (start) {
this._audioElement.play();
return true;
}
this._audioElement.pause();
return false;
}
/**
* Handle the play event.
* @private
* @param {Event} evt - the event that triggered the play.
* @return {boolean} The current media session play state.
*/
_handlePlay(evt) {
if (this.playing) {
console.log('🔈', 'Already playing, ignore.');
return true;
}
if (this._previousState) {
for (const key in this._previousState) {
if (this._previousState[key]) {
this._noises[key].play();
}
}
this._previousState = null;
} else {
const keys = Object.keys(this._noises);
const firstKey = keys[0];
const firstNoise = this._noises[firstKey];
firstNoise.toggle(true);
}
this._toggleAudioElem(true);
if (this._gaEvent) {
this._gaEvent('MediaSession', 'play');
}
return true;
}
/**
* Handle the pause event.
* @private
* @param {Event} evt - the event that triggered the pause.
* @return {boolean} The current media session play state.
*/
_handlePause(evt) {
if (!this.playing) {
console.log('🔈', 'Already paused, ignore.');
return false;
}
this._previousState = {};
// eslint-disable-next-line guard-for-in
for (const key in this._noises) {
const noise = this._noises[key];
this._previousState[key] = noise.playing;
noise.pause();
}
this._audioElement.pause();
this._toggleAudioElem(false);
if (this._gaEvent) {
this._gaEvent('MediaSession', 'pause');
}
return false;
}
} |
JavaScript | class ChaosEvent {
/**
* Create a ChaosEvent.
* @member {date} timeStampUtc
* @member {string} kind Polymorphic Discriminator
*/
constructor() {
}
/**
* Defines the metadata of ChaosEvent
*
* @returns {object} metadata of ChaosEvent
*
*/
mapper() {
return {
required: false,
serializedName: 'ChaosEvent',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'Kind',
clientName: 'kind'
},
uberParent: 'ChaosEvent',
className: 'ChaosEvent',
modelProperties: {
timeStampUtc: {
required: true,
serializedName: 'TimeStampUtc',
type: {
name: 'DateTime'
}
},
kind: {
required: true,
serializedName: 'Kind',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class Mosaic {
/**
* Constructor
* @param id
* @param amount
*/
constructor(
/**
* The mosaic id
*/
id,
/**
* The mosaic amount. The quantity is always given in smallest units for the mosaic
* i.e. if it has a divisibility of 3 the quantity is given in millis.
*/
amount) {
this.id = id;
this.amount = amount;
}
/**
* @internal
* @returns {{amount: number[], id: number[]}}
*/
toDTO() {
return {
amount: this.amount.toString(),
id: this.id.id.toHex(),
};
}
} |
JavaScript | class FullActionDescriptor {
constructor(props) {
this.action = props.action;
const actionProperties = props.action.actionProperties;
this.actionName = actionProperties.actionName;
this.category = actionProperties.category;
this.owner = actionProperties.owner || 'AWS';
this.provider = actionProperties.provider;
this.version = actionProperties.version || '1';
this.runOrder = actionProperties.runOrder === undefined ? 1 : actionProperties.runOrder;
this.artifactBounds = actionProperties.artifactBounds;
this.namespace = actionProperties.variablesNamespace;
this.inputs = deduplicateArtifacts(actionProperties.inputs);
this.outputs = deduplicateArtifacts(actionProperties.outputs);
this.region = props.actionRegion || actionProperties.region;
this.role = actionProperties.role !== undefined ? actionProperties.role : props.actionRole;
this.configuration = props.actionConfig.configuration;
}
} |
JavaScript | class DisplacePass extends BasePass {
constructor() {
let fragmentShader = require('./shaders/displace-pass.frag')
let baseUniforms = {
originalTexture: {type: 't', value: null},
prevTexture: {type: 't', value: null},
aspect: {type: 'f', value: 1}
}
super({
fragmentShader,
uniforms: baseUniforms
})
this.baseUniforms = baseUniforms
this.baseCode = fragmentShader
this.enableDisplace = false
this.prevRenderTarget = new THREE.WebGLRenderTarget()
this.currentRenderTarget = new THREE.WebGLRenderTarget()
this.texture = this.currentRenderTarget.texture
this.passthruPass = new BasePass({
fragmentShader: require('./shaders/passthru.frag'),
uniforms: {
texture: {type: 't', value: null}
}
})
}
changeProgram(code, uniforms) {
this.uniforms = _.merge(this.baseUniforms, uniforms)
console.log(this.uniforms)
let mat = new THREE.RawShaderMaterial({
uniforms: this.uniforms,
vertexShader: this._material.vertexShader,
fragmentShader: code
})
this.updateMaterial(mat)
}
render() {
[this.prevRenderTarget, this.currentRenderTarget]
= [this.currentRenderTarget, this.prevRenderTarget]
this.uniforms.prevTexture.value = this.prevRenderTarget.texture
super.render(this.currentRenderTarget)
this.texture = this.currentRenderTarget.texture
}
reset(tex) {
if (tex) {
this.originalTexture = tex
this.uniforms.originalTexture.value =tex
}
this.passthruPass.uniforms.texture.value = this.originalTexture
this.passthruPass.render(this.currentRenderTarget)
this.texture = this.currentRenderTarget.texture
}
setSize(w, h) {
this.prevRenderTarget.setSize(w, h)
this.currentRenderTarget.setSize(w, h)
this.uniforms.aspect.value = h / w
}
} |
JavaScript | class PSDImageResourcesSection {
constructor() {
this.length = 0
this.$psd = null
this.blocks = []
}
} |
JavaScript | class PSDImageResourceBlock {
constructor() {
this.signature = ''
this.uid = 0
this.name = ''
this.size = 0
this.data = null
}
get formatData() {
return this.data
}
get valid() {
return this.signature == '8BIM'
}
} |
JavaScript | class ElementManager extends EventSystem {
/**
* Constructor
* @param {HTLMElement} wrapper - Wrapper element where elements are appended
* @param {HTMLElement} template - A cloneable HTMLElement or Template
* @param {Object} [params]
* @param {String} [params.primary_key="id"] - Necessary for rendering data
* from arrays of objects. Otherwise, ElementManager will just empty itself
* and rebuild from scratch.
* @param {Number} [params.max_elements=0] - Max element count
* @param {Boolean} [params.clone_template=true] - Whether to clone the
* initial template from the DOM. Most of the time, you want to do this.
* @param {Boolean} [params.remove_template=true] - Whether to remove the
* initial template on the DOM. Most of the time, you want to do this,
* unless there are many ElementManagers using the same template.
* @param {Boolean} [params.remove_dead_templates=true] - Whether to remove
* dead templates. A template is dead when it does not exist in new data
* passed to render()
*/
constructor({
wrapper = null,
template = null,
primary_key = "id",
max_elements = 0,
clone_template = true,
remove_template = true,
remove_dead_templates = true
}){
super();
/**
* The element in which all templates will be appended to.
* If not defined in the constructor, creates a div element.
* @type {HTMLElement}
*/
this.wrapper = wrapper || document.createElement('div');
/**
* Whether to clone the initial template from the DOM. Most of the time,
* you want to do this.
* @type {Boolean}
*/
this.clone_template = clone_template;
/**
* Whether to remove the initial template on the DOM. Most of the time,
* you want to do this, unless there are many ElementManagers using the
* same template.
* @type {Boolean}
*/
this.remove_template = remove_template;
/**
* Whether to remove dead templates. A template is dead when it does
* not exist in new data passed to render() as matched by the
* primary_key value.
* @type {Boolean}
*/
this.remove_dead_templates = remove_dead_templates
/**
* Necessary for rendering data from arrays of objects. Otherwise,
* ElementManager will just empty itself and rebuild from scratch.
* @type {String}
*/
this.primary_key = primary_key;
/**
* The maximum number of elements to render.
* @todo Implement
* @type {Number}
*/
this.max_elements = max_elements;
/**
* A Template HTMLElement to create new templates from.
* @type {HTMLElement}
*/
this.template = this.clone_template ? template.cloneNode(true) : template
this.template.removeAttribute('id');
this.template.classList.remove('template');
if(this.remove_template){
template.remove();
}
/**
* A Map of Templates, such as
* { "User1" => UserRowTemplate,
* "User2" => UserRowTemplate.. }
* @type {Map}
*/
this.elements = new Map();
/**
* Unmodified data passed to the render function.
* @type {Array|Map|Object}
*/
this.cached_data = null;
/**
* Processed data passed to the render function.
* @type {Array|Map|Object}
*/
this.render_data = null;
}
/**
* Append the entire manager to another element.
* @param {HTMLElement|Template} element
*/
appendTo(element){
Template.append(this.wrapper, element);
}
/**
* Get the number of elements in the map
* @returns {Number}
*/
getElementCount(){
return this.elements.size;
}
/**
* Empty the contents of the template manager
*/
empty(){
while (this.wrapper.firstChild) {
this.wrapper.removeChild(this.wrapper.firstChild);
}
this.elements = new Map();
this.emit("empty");
}
/**
* Attach handlers to an element
* @param {HTLMElement|Template} element
*/
attachElementHandlers(element){
}
/**
* Create a new clone of the template. Attach handlers to it.
* @returns {HTLMElement|Template}
*/
cloneTemplate(){
let element = this.template.cloneNode(true);
this.attachElementHandlers(element);
this.emit("clone", element);
return element;
}
/**
* Append an element to the wrapper
* @param {HTLMElement|Template} element
*/
appendElement(element){
this.wrapper.appendChild(element);
this.emit("append", element);
}
/**
* Remove an element by id. Removes from the DOM and collection.
* @param {String} id
*/
removeElement(id){
let element = this.elements.get(id);
if(element){
this.wrapper.removeChild(element);
this.elements.delete(id);
this.emit("remove", element);
}
}
/**
* Remove dead elements.
* Cross reference the list of current elements with an object of data.
* If the template object's name is not found in the data, then the
* template is considered dead (old).
* @example
* // The following objects currently exists in this.elements
* {user1:Template, user2:Template, user3:Template}
* // The following objects exist in the passed in data object
* {user2: {...}, user3: {...}}
* // user1 is missing in the data. Therefore, the template named
* // "user1" is no longer relevant, and is removed.
* @param {Object} data
*/
removeDeadElements(data){
for(let [key, element] of this.elements){
if(!this.getData(data, key)){
element.remove();
this.elements.delete(key);
this.emit("remove", element);
}
}
}
/**
* Get the type of the data parameter.
* @param {Object[]|Object|Map} data
* @returns {String|Null}
*/
getDataType(data){
if(data instanceof Map){
return "map";
}
else if(Array.isArray(data)){
return "array";
}
else if(typeof data === "object"){
return "object";
}
return null;
}
/**
* Cache data as-is in case the original data is required.
* todo: handle array, map, and object
* @param {Array|Map|Object} data
*/
cacheData(data){
return Object.extend({}, data);
}
/**
* Process data to be used for rendering.
* @param {Array|Map|Object} data
* @returns {Array|Map|Object}
*/
processRenderData(data){
return data;
}
/**
* Get an object of data from a data parameter based on a key. If the data
* is an array of objects, match the key with an object.id property.
* Otherwise, just match the name of the key in a map of objects or object
* of objects.
* @todo rename.. to something better
* @param {Object[]|object|Map} data
* @param {String} key
* @returns {Null|Object}
*/
getData(data, key){
switch(this.getDataType(data)){
case "array":
let el = data.filter((e) =>{
return e[this.primary_key] === key;
});
return el && el.length ? el[0] : null;
case "map":
return data.get(key);
case "object":
return data[key];
default:
return null;
}
}
/**
* Run through each object of data and render the object into an element.
* If the data is new, the element will be appended to the wrapper.
* @param {Object[]|Object|Map} data
*/
render(data){
this.cached_data = this.cacheData(data);
this.render_data = this.processRenderData(data);
switch(this.getDataType(data)){
case "array":
this.renderArray(data);
break;
case "map":
this.renderMap(data);
break;
default:
case "object":
this.renderObject(data);
break;
}
if(this.remove_dead_templates){
this.removeDeadElements(data);
}
}
/**
* Render elements from an array of data. Each object must have an "id"
* property.
* @param {Object[]} data
*/
renderArray(data){
for(let i = 0; i < data.length; i++){
let id = data[i][this.primary_key];
if(typeof id === "undefined"){
console.error("Data must have a primary key property");
return;
}
this.renderElement(id, data[i], i);
}
}
/**
* Render elements from a map of objects.
* @param {Map} data
*/
renderMap(data){
let i = 0;
for(let [key, value] of data){
this.renderElement(key, value, i);
i++;
}
}
/**
* Render elements from an object of objects.
* @param {Object} data
*/
renderObject(data){
let i = 0;
for(let k in data){
this.renderElement(k, data[k], i);
i++;
}
}
/**
* Render a single object of data by faking it as an object of objects.
* Note that if removeDeadElements is set to true (by default), this will
* remove all other elements.
* @param {String} id
* @param {Object} object
*/
renderSingle(id, object){
let obj = {};
obj[id] = object;
this.render(obj);
}
/**
* Render an element found in the element collection.
* If the element does not exist, create it.
* @param {Number|String} id - Element and data identifier
* @param {Object} data - Object of data
* @param {Number} index - The numerical index of the element
*/
renderElement(id, data, index){
let is_new = false;
let element = this.elements.get(id);
if(!element){
is_new = true;
element = this.cloneTemplate();
}
if(element){
this.appendElement(element);
if(element instanceof Template){
element.render(data);
}
else {
Template.render(element, data);
}
if(is_new){
this.elements.set(id, element);
}
}
}
/**
* Convert an array of objects into an object of objects. Each object in
* the array must have a primary key.
* @param {Object[]} data_arr
* @param {String} [primary_key="id"] - The key that identifies each data object
* @returns {Object}
*/
static dataArrayToDataObject(data_arr, primary_key = 'id'){
let data_obj = {};
for(let i = 0; i < data_arr.length; i++){
let id = data_arr[i][primary_key];
if(typeof id === "undefined"){
console.error(`dataArrayToDataObject: object does not have required "${primary_key}" value`)
}
else {
data_obj[id] = data_arr[i];
}
}
return data_obj;
}
} |
JavaScript | class ApplicationError extends Error {
/**
* Constructor for ApplicationError
* @constructor
* @param {number} id A unique identifier for the error.
* @param {string} type The type of error.
* @param {string} name A name for the error.
* @param {string} message A detailed message for the error.
* @param {number} status A related HTTP status code.
*/
constructor(id, type, name, message, status) {
super(message);
/**
* A unique identifier for the error.
*/
this.id = id;
/**
* The type of error.
*/
this.type = type;
/**
* A unique identifier for the error.
*/
this.name = `ApplicationError:${name}`;
/**
* Related HTTP status for this error.
*/
this.status = status;
}
/* eslint-disable */
toJSON() {
return {
id: this.id,
type: this.type,
name: this.name,
message: this.message,
errors: this.errors,
info: this.info,
updatedItem: this.updatedItem,
createErrors: this.createErrors,
updateErrors: this.updateErrors,
deleteErrors: this.deleteErrors
};
}
/* eslint-enable */
} |
JavaScript | class Mouse {
/**
* Creates an instance of this feature.
* @param options are the options to configure this instance
*/
constructor(options = {}) {
writeCache(this, CACHE_KEY_CONFIGURATION, Object.assign(Object.assign({}, DEFAULTS), options));
this._onStart = this._onStart.bind(this);
this._onDrag = this._onDrag.bind(this);
this._onEnd = this._onEnd.bind(this);
}
/**
* Returns the name of this feature.
*/
get name() {
return FEATURE_NAME;
}
/**
* Initializes this feature. This function will be called by the carousel
* instance and should not be called manually.
* @internal
* @param proxy the proxy instance between carousel and feature
*/
init(proxy) {
writeCache(this, CACHE_KEY_PROXY, proxy);
const config = fromCache(this, CACHE_KEY_CONFIGURATION);
const { el } = proxy;
const element = el;
element.style.cursor = config.indicator ? CURSOR_GRAB : '';
// The handler is already bound in the constructor.
//
// eslint-disable-next-line @typescript-eslint/unbound-method
el.addEventListener(EVENT_START, this._onStart, { passive: true });
}
/**
* Destroys this feature. This function will be called by the carousel instance
* and should not be called manually.
* @internal
*/
destroy() {
clearFullCache(this);
}
/**
* This triggers the feature to update its inner state. This function will be
* called by the carousel instance and should not be called manually. The
* carousel passes a event object that includes the update reason. This can be
* used to selectively/partially update sections of the feature.
* @internal
*/
update() {
/* nothing to update yet */
}
/**
* Handles the drag start event.
* @internal
* @param event the event that triggered the drag start
*/
_onStart(event) {
var _a;
const timeout = fromCache(this, CACHE_KEY_TIMEOUT);
clearTimeout(timeout);
const config = fromCache(this, CACHE_KEY_CONFIGURATION);
const proxy = fromCache(this, CACHE_KEY_PROXY);
const element = proxy.el;
fromCache(this, CACHE_KEY_SCROLL_LEFT, () => element.scrollLeft);
fromCache(this, CACHE_KEY_POSITION_X, () => __getPositionX(event));
fromCache(this, CACHE_KEY_PAGE_INDEX, () => proxy.pageIndex);
// Reset scroll behavior and scroll snapping to emulate regular scrolling.
// Prevent user selection while the user drags:
element.style.userSelect = 'none';
element.style.scrollBehavior = 'auto';
element.style.scrollSnapType = 'none';
element.style.cursor = config.indicator ? CURSOR_GRABBING : '';
// The handlers are already bound in the constructor.
//
/* eslint-disable @typescript-eslint/unbound-method */
window.addEventListener(EVENT_DRAG, this._onDrag, { passive: true });
window.addEventListener(EVENT_END, this._onEnd, { passive: true });
/* eslint-enable @typescript-eslint/unbound-method */
// Call the hook:
(_a = config.onStart) === null || _a === void 0 ? void 0 : _a.call(config, { originalEvent: event });
}
/**
* Handles the drag event. Calculates and updates scroll position.
* @internal
* @param event the event that triggered the dragging
*/
_onDrag(event) {
var _a;
const config = fromCache(this, CACHE_KEY_CONFIGURATION);
const { el } = fromCache(this, CACHE_KEY_PROXY);
const left = fromCache(this, CACHE_KEY_SCROLL_LEFT);
const x = fromCache(this, CACHE_KEY_POSITION_X);
const currentX = __getPositionX(event);
const deltaX = x - currentX;
el.scrollLeft = left + deltaX;
// Call the hook:
(_a = config.onDrag) === null || _a === void 0 ? void 0 : _a.call(config, { originalEvent: event });
}
/**
* Handles the drag end event.
* @internal
* @param event the event that triggered the drag end
*/
_onEnd(event) {
var _a, _b;
const proxy = fromCache(this, CACHE_KEY_PROXY);
const config = fromCache(this, CACHE_KEY_CONFIGURATION);
const left = fromCache(this, CACHE_KEY_SCROLL_LEFT);
const pageIndex = fromCache(this, CACHE_KEY_PAGE_INDEX);
clearCache(this, CACHE_KEY_SCROLL_LEFT);
clearCache(this, CACHE_KEY_POSITION_X);
clearCache(this, CACHE_KEY_PAGE_INDEX);
const element = proxy.el;
const threshold = Math.min(Math.max(THRESHOLD_MIN, element.clientWidth * THRESHOLD_FACTOR), THRESHOLD_MAX);
const currentLeft = element.scrollLeft;
const distance = currentLeft - left;
const offset = Math.abs(distance);
element.style.removeProperty('user-select');
element.style.removeProperty('scroll-behavior');
element.style.cursor = config.indicator ? CURSOR_GRAB : '';
// Apply the index. If the scroll offset is higher that the threshold,
// navigate to the next page depending on the drag direction.
let index = proxy.index;
if (offset > threshold) {
const direction = distance / offset;
const at = Math.max(pageIndex + direction, 0);
index = (_a = proxy.pages[at]) !== null && _a !== void 0 ? _a : index;
}
// Apply the index until the styles are rendered to the element. This is
// required to have a smooth scroll-behaviour which is disabled during the
// mouse dragging.
window.requestAnimationFrame(() => {
proxy.index = index;
});
// Get around the scroll-snapping. Enable it until the position is already
// applied. This will take ~1000ms depending on distance and browser
// behaviour.
const timeout = window.setTimeout(() => {
element.style.removeProperty('scroll-snap-type');
}, 1000);
writeCache(this, CACHE_KEY_TIMEOUT, timeout);
// The handlers are already bound in the constructor.
//
/* eslint-disable @typescript-eslint/unbound-method */
window.removeEventListener(EVENT_DRAG, this._onDrag);
window.removeEventListener(EVENT_END, this._onEnd);
/* eslint-enable @typescript-eslint/unbound-method */
// Call the hook:
(_b = config.onEnd) === null || _b === void 0 ? void 0 : _b.call(config, { originalEvent: event });
}
} |
JavaScript | class AsyncMutex {
constructor() {
this.queue = [ ]
this.acquired = false
}
/**
* This method returns a promise that resolves
* as soon as all other callers of acquire()
* have invoked release(). When the promise
* resolves, you can access to critical section
* or protected resource
*
* @method acquire
* @return {Promise}
*/
acquire() {
let self = this
return new Promise(function(resolve, reject) {
if(self.acquired) {
self.queue.push(resolve)
}
else {
self.acquired = true
resolve()
}
})
}
/**
* This method indicates that you are done
* with the critical section and will give
* control to the next caller to acquire()
*
* @method release
*/
release() {
let next = this.queue.shift()
if(next) {
next()
}
else {
this.acquired = false
}
}
/**
* This method returns the length of the
* number of threads waiting to acquire
* this lock
*/
queueSize() {
return this.queue.length
}
} |
JavaScript | class Queue {
constructor() {
this.listNode = new ListNode();
this.newNode = this.listNode;
}
get size() {
throw new Error('Not implemented');
}
enqueue(element) {
this.newNode.value = element;
this.newNode.next = new ListNode();
this.newNode = this.newNode.next;
}
dequeue() {
const x = this.listNode.value;
this.listNode.value = this.listNode.next.value;
this.listNode.next = this.listNode.next.next;
return x;
}
} |
JavaScript | class PingCommand {
constructor (prefix) {
this.prefix = prefix
this.command = prefix + 'ping'
this.helpText = `\`${this.command}\` - Check if the bot is alive.`
}
canHandle (command) {
return command === this.command
}
handle (args) {
return Promise.resolve(['Pong!'])
}
} |
JavaScript | class TelegramBot extends NodeTelegramBotApi {
/**
* Creates an instance of NodeTelegramBotApi
* @param {string} token - Token given by @BotFather
* @param {object} options - Options to initialize NodeTelegramBotApi
* @see https://github.com/yagop/node-telegram-bot-api/blob/release/doc/api.md#new-telegrambottoken-options
*/
constructor(token, options = {}) {
super(token, options);
}
/**
* Check for a valid telegram message
* @param {object} msg - Message to check
* @return {boolean}
* @see https://core.telegram.org/bots/api#update
*/
checkMessage(msg) {
return msg.message ||
msg.edited_message ||
msg.channel_post ||
msg.edited_channel_post ||
msg.inline_query ||
msg.chosen_inline_result ||
msg.callback_query;
}
/**
* Give message to processUpdate parent method
* @param {object} msg - Message to process
*/
proccessMessage(msg) {
this.processUpdate(msg);
}
} |
JavaScript | class HttpException extends Error {
constructor(statusCode, message) {
super(message);
this.statusCode = statusCode;
this.message = message;
}
} |
JavaScript | class Mammal {
constructor(genus) {
this.warm_blooded = true
this.genus = genus
}
} |
JavaScript | class Home extends Component {
state = {
email: "",
password: "",
userInfo: {},
message: ""
};
// This deals with each change from a value on the form
handleInputChange = event => {
const { name, value } = event.target;
this.setState({
[name]: value
});
};
onSubmit = event => {
event.preventDefault();
// clear any extra items left from previous session
localStorage.removeItem('current-recipe');
localStorage.removeItem('admin-id-user');
localStorage.removeItem('admin--recipe');
if (this.state.email === "" || this.state.password === "") {
this.setState({ message: "Both inputs need a value!"});
return;
} else
this.setState({ message: ""});
this.userInfo = {
email: this.state.email,
password: this.state.password
}
API.logIn(this.userInfo)
.then(function (jwt) {
localStorage.setItem('dcb-jwt', jwt.data.token)
window.location.replace("/recipes/view")
})
.catch((err) => {
if (err.response.status === 404) {
this.setState({
email: '',
password: '',
message: "That email address is not registered"
})
} else {
this.setState({
password: '',
message: "That password is incorrect"
})
}
})
};
render() {
const checkExp = () => {
const token = window.localStorage.getItem('dcb-jwt');
const noBearer = token.replace(/Bearer token: /, '');
const decoded = jwt_decode(noBearer);
if (( Date.now() >= (decoded.exp * 1000) )) {
return false;
} else {
return true;
}
}
if (!localStorage.getItem('dcb-jwt') || checkExp() === false) {
return (
<div style={{textAlign:"center"}}>
<NavbarComp />
<div style={{paddingTop: "5rem", paddingBottom: "5rem"}} className="home">
<h1><span className="red-span">Welcome to Digital Cookbook</span></h1>
<h3><span className="red-span">Please Log In or </span><a className="blue-link" href="/signup">Create an Account</a></h3>
<h2 className="red-span">{this.state.message}</h2>
<LogIn
email={this.state.email}
password={this.state.password}
handleInputChange={this.handleInputChange}
onSubmit={this.onSubmit}
/>
</div>
<Footer />
</div>
)
} else {
return (
<div style={{textAlign:"center"}}>
<NavbarComp />
<div style={{paddingTop: "5rem", paddingBottom: "5rem"}} className="home">
<h1><span className="red-span">Welcome Back!</span></h1>
<h1><span className="red-span">Please use the navbar to reach your destination</span></h1>
</div>
<Footer />
</div>
)
}
}
} |
JavaScript | class WalrusCommand extends Command {
/**
* Constructor.
* @param {VoiceService} voiceService - VoiceService.
* @param {RawFileService} rawFileService - RawFileService.
*/
constructor(voiceService, rawFileService) {
super(
["walrus", "urf"],
"make the bot do a walrus sound",
"<prefix>walrus"
);
this.voiceService = voiceService;
this.rawFileService = rawFileService;
}
/**
* Function to execute this command.
* @param {String} payload - Payload from the user message with additional information.
* @param {Message} msg - User message this function is invoked by.
*/
run(payload, msg) {
this.rawFileService.getStream(sounds[getRandomInt(sounds.length)]).
then((sfx) => {
this.voiceService.getVoiceConnection(msg).
then((voiceConnection) => {
voiceConnection.play(sfx);
});
}).
catch(((err) => console.log(err)));
msg.delete({"timeout": 10000});
}
} |
JavaScript | class Dashboard extends React.Component {
constructor(props) {
super();
}
// Fetching the platform, profile & products details
static async getInitialProps(context) {
let profile = await API.makeRequest('get', '/api/profile');
let platform = await API.makeRequest('get', '/api/profile/platform');
let products = await API.makeRequest('get', '/api/products');
return {
profile: profile,
platform: platform,
products: products,
dashboardType: 'products',
};
}
// Checking for connection with stripe
componentDidMount() {
if (this.props.platform && !this.props.platform.stripe) {
redirect('/profile/payouts');
}
}
render() {
return (
<Layout
isAuthenticated={this.props.isAuthenticated}
userProfile={this.props.userProfile}
title="Dashboard"
isDashboard="true"
>
<div className="dashboard">
<DashboardHeader
profile={this.props.profile}
platform={this.props.platform}
dashboardType={this.props.dashboardType}
/>
<div className="row">
<div className="col-12">
<div className="row">
<div className="col-6">
<div className="clearfix">
<h4>Your products</h4>
</div>
</div>
<div className="col-6">
<NewButton
label="Add new"
link="https://dashboard.stripe.com/test/products"
/>
</div>
</div>
<DashboardProductsList list={this.props.products}/>
</div>
</div>
</div>
<style jsx>{`
.dashboard {
margin-bottom: 50px;
}
.dashboard h4 {
font-size: 100%;
font-weight: bold;
margin-bottom: 30px;
}
`}</style>
</Layout>
);
}
} |
JavaScript | class MockPromise {
constructor(returnSuccess, result) {
this.returnSuccess = returnSuccess;
this.result = result || (returnSuccess ? 'my data': 'my error')
}
then(success, failure) {
if (this.returnSuccess) {
success(this.result);
}
else {
failure(this.result);
}
}
} |
JavaScript | class TreeToolbarView extends Component {
constructor(isShown, ...p) {
super('$div.bg-tree-view-toolbar.bg-toolbar.tool-panel.panel-heading', ...p);
this.shouldBeShown = (isShown == undefined) ? true : isShown;
this.disposables = new CompositeDisposable();
this.mount([
new PackageConfigButton( 'btnBarCfg:', this.btnGetConfigEnabled('btnBarCfg') ? null : {display:'none'}),
new HiddenFilesToggle( 'btnHidden:.inline-block-tight', this.btnGetConfigEnabled('btnHidden') ? null : {display:'none'}),
new CollapseToRootLevelButton('btnColAll:.inline-block-tight', this.btnGetConfigEnabled('btnColAll') ? null : {display:'none'}),
new AutoRevealToggle( 'btnReveal:.inline-block-tight', this.btnGetConfigEnabled('btnReveal') ? null : {display:'none'}),
new FontSizeButtonGroup( 'fontGroup:.inline-block-tight', this.btnGetConfigEnabled('fontGroup') ? null : {display:'none'})
]);
// register cmds that just push our buttons so that they are garanteed to to exactly what the user button click does
this.disposables.add(atom.commands.add('atom-workspace', "bg-tree-view:toggle-hidden", ()=>this.btnHidden.onClick()));
this.disposables.add(atom.commands.add('atom-workspace', "bg-tree-view:collapse-to-root-level", ()=>this.btnColAll.onClick()));
this.disposables.add(atom.commands.add('atom-workspace', "bg-tree-view:toggle-auto-reveal", ()=>this.btnReveal.onClick()));
// register our onTreeViewActivate method to get call when the tree-view tab becomes active (see onTreeViewActivate comment)
this.disposables.add(atom.workspace.onDidStopChangingActivePaneItem((item)=>{
if (item && item.constructor.name == "TreeView" )
this.onTreeViewActivate();
}))
// watch for changes to our config button visibility
this.disposables.add(OnDidChangeAnyConfig('bg-tree-view-toolbar.buttons', (cfgKey,e)=>{
this.toggleButton(cfgKey.replace(/^.*buttons./,''), e.newValue)
}));
this.getTreeView();
// the keyMaps might not be read yet so make the tooltips after a delay
setTimeout(()=>{this.registerTooltips()}, 1000);
if (this.shouldBeShown)
this.show();
}
addButton(btnName, button) {
return this.mount(btnName, button);
}
getButton(btnName) {
return this[btnName];
}
removeButton(btnName) {
if (!this[btnName]) return false;
return this.unmount(btnName);
}
isButtonEnabled(btnName) {
return (this[btnName]) && (getEl(this[btnName]).style.display != 'none')
}
toggleButton(btnName, state) {
if (!this[btnName]) return;
if (state == null)
state = ! this.isButtonEnabled(btnName);
getEl(this[btnName]).style.display = (state) ? '' : 'none';
}
btnGetConfigEnabled(btnName) {
return (atom.config.get('bg-tree-view-toolbar.buttons.'+btnName));
}
getHeight() {
var cStyles = window.getComputedStyle(this.el, null);
var h1 = parseInt(cStyles.height);
var vertMargin = parseInt(cStyles.marginTop) + parseInt(cStyles.marginBottom);
return Math.min(h1 + vertMargin, 100) +'px';
}
// this inserts our view into the DOM before the .tool-panel.tree-view
// we do not insert inside .tool-panel.tree-view because we dont want to scroll with the tree data.
// becuase we are outside .tool-panel.tree-view, we are at the same level as other WorkplaceItems (aka tab items) so switching
// items automatically display:none 's us.
show() {
this.shouldBeShown = true;
if (!this.getTreeView()) return
mount(this.treeViewEl.parentNode, this.el, this.treeViewEl);
// tool-panels are positioned absolute so we need to move down the top to make room for us
this.treeViewEl.style.top = this.getHeight();
if (!this.isMounted())
atom.notifications.addError("package bg-tree-view-toolbar could not find a tree-view to work with");
}
// change state to be not shown
hide() {
this.shouldBeShown = null;
this.removeFromTreeView();
}
// remove us from the DOM
removeFromTreeView() {
if (!this.isMounted()) return
unmount(this.el.parentNode, this.el);
// move the top of the tree-view back where it was
if (this.treeViewEl)
this.treeViewEl.style.top = "0px";
}
// the defintion of whether we are 'mounted' is whether we are attached to the tree-view node in the DOM. It may not be visible
// even if its mounted because the tree-view is not active/visible
isMounted() {
return this.getTreeView() && this.el.parentNode != null;
}
getElement() { return this.el;}
// b/c we mount ourselves at the same level as WorkplaceItems (see mount comment), every time the user activates a different
// tab, the switcher code sets our display to none. When the tree view gets activated, we have to undo that.
onTreeViewActivate() {
if (this.shouldBeShown && !this.isMounted())
this.show();
if (this.treeViewEl)
this.treeViewEl.style.top = this.getHeight();
this.el.style.display = 'inherit';
}
getTreeView() {
if (!this.treeViewEl)
this.treeViewEl = document.querySelector('.tree-view.tool-panel');
return this.treeViewEl;
}
registerTooltips() {
if (!this.getTreeView()) return
this.disposables.add(atom.tooltips.add(this.btnHidden.el, {title: "show hidden files", keyBindingCommand: 'bg-tree-view:toggle-hidden', keyBindingTarget: this.treeViewEl}));
this.disposables.add(atom.tooltips.add(this.btnColAll.el, {title: "collapse to root level", keyBindingCommand: 'bg-tree-view:collapse-to-root-level', keyBindingTarget: this.treeViewEl}));
this.disposables.add(atom.tooltips.add(this.btnReveal.el, {title: "make selected tree item follow active editor", keyBindingCommand: 'bg-tree-view:toggle-auto-reveal', keyBindingTarget: this.treeViewEl}));
}
dispose() {this.destroy()}
destroy() {
this.removeFromTreeView();
this.disposables.dispose();
}
} |
JavaScript | class Compiler {
/**
* Initialize a Compiler object.
* @param {object} options - User options
* @param {Logger.state.ENUM} logSetting - Log setting, as represented by the Logger state enum.
*/
constructor(options, logSetting = Logger.state.NORMAL) {
this.options = options;
this.log = new Logger(logSetting);
}
//solc input object --> Compiled stuff
/**
*
* @param {object} solcInput - The JSON input for the solc.js Solidity Compiler. See: https://solidity.readthedocs.io/en/v0.5.7/using-the-compiler.html#input-description
* @return {object} output - The returned output generated by solc. See link above!
*
*/
compile(solcInput) {
this.log.print(Logger.state.SUPER,
util.inspect(solcInput),
"\n"
);
//this.log.print(Logger.state.NORMAL, "Compiling...\n");
const spinner = ora('Compiling...\n').start();
const output = JSON.parse(solc.compile(JSON.stringify(solcInput)));
//Logic on what to show post-compilation (regarding the output post-compilation)
if(this.log.setting >= Logger.state.SUPER) {
this.log.print(Logger.state.SUPER,
"OUTPUT",
util.inspect(output, { depth: null })
);
} else if(output.errors) {
spinner.fail();
this.log.print(Logger.state.NORMAL,
"Error: ",
util.inspect(output, { depth: null })
);
throw "Failed to compile!";
}
spinner.stop();
return output;
}
/**
* A function which recursively searches through the given directory passed, pasgenerating a solc input, compiling it, and returning the raw compiler output.
*
* If no root filepath is passed, it will assume that the "contracts" folder one level higher than the current dir is the root where all contracts are located.
*
* @param {string} [root=path.resolve(__dirname, '../contracts')] - The root directory in which the function will start from, recursively navigated through to parse all contracts found into a solc input.
* @return {object} output - The returned output generated by solc. See: https://solidity.readthedocs.io/en/v0.5.7/using-the-compiler.html#output-description
*/
compileDirectory(root = path.resolve(__dirname, '../contracts')) {
this.log.print(Logger.state.MASTER,
"Config: ",
" Root contract directory: " + root,
"\n"
);
this.log.print(Logger.state.NORMAL, "Generating solc_input...\n");
return this.compile(SolcUtil.generateSolcInputDirectory(root));
}
/**
* A function which simply compiles a single file located at the given filepath.
*
* If no root is provided in the second argument, it will assume that the "contracts" folder one level higher than the current dir is the root where all contracts are located.
*
* @param {string} filepath - The filepath at which the file is located.
* @param {string} [root=path.resolve(__dirname, '../contracts')] - The root directory in which all contracts are located; this is for contract naming specification within the solc input.
* @return {object} output - The returned output generated by solc. See: https://solidity.readthedocs.io/en/v0.5.7/using-the-compiler.html#output-description
*
*
*/
compileFile(filepath, root = path.resolve(__dirname, '../contracts')) {
this.log.print(Logger.state.MASTER,
"Config: ",
" Root contract directory: " + root,
"\n"
);
this.log.print(Logger.state.NORMAL, "Generating solc_input...\n");
return this.compile(SolcUtil.generateSolcInputFile(filepath, root));
}
/**
* A function which compiles a raw "contract solc input name" and source code.
*
* @param {string} base - The "raw contract solc input name" (i.e. 'erc20/ERC20Interface.sol')
* @param {string} src - The raw Solidity smart contract code as a string.
* @return {object} output - The returned output generated by solc. See: https://solidity.readthedocs.io/en/v0.5.7/using-the-compiler.html#output-description
*/
compileSource(base, src) {
return this.compile(SolcUtil.generateSolcInput(base, src));
}
//Not working... :/ Uncertain how to handle this sort of callback stuff synchronously
async getPackageVersion(module) {
//Assume package-lock.json exists, by default
let packageJSON = "../package-lock.json";
/* if(fs.access(packageJSON, fs.constants.F_OK)){
packageJSON = "../package.json";
if(fs.access(packageJSON, fs.constants.F_OK)){
throw "Neither package.json or package-lock.json exists";
}
}*/
fs.access(packageJSON, fs.constants.F_OK, (err) => {
if(err) {
packageJSON = "../package.json";
fs.access(packageJSON, fs.constants.F_OK, (err2) => {
if(err2) {
throw "Neither package.json or package-lock.json exists\n" + err + "\n" + err2;
} else {
const packages = require(packageJSON);
return packages.dependencies[module];
}
});
} else {
const packages = require(packageJSON);
console.log(packages.dependencies)
return packages.dependencies[module];
}
});
}
} |
JavaScript | class VideoElement extends Html5MediaElement {
/** @type {import('lit').CSSResultGroup} */
static get styles() {
return [videoElementStyles];
}
/** @type {string[]} */
static get parts() {
return ['root', 'video'];
}
// -------------------------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------------------------
/**
* 🧑🔬 **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as
* the user switches back and forth between this document and another document or application.
*
* @type {boolean | undefined}
*/
@property({ type: Boolean, attribute: 'autopictureinpicture' })
autoPiP;
/**
* 🧑🔬 **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or
* to request picture-in-picture automatically in some cases.
*
* @type {boolean | undefined}
* @link https://w3c.github.io/picture-in-picture/#disable-pip
*/
@property({ type: Boolean, attribute: 'disablepictureinpicture' })
disablePiP;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't
* specified, nothing is displayed until the first frame is available, then the first frame is
* shown as the poster frame.
*
* @type {string}
*/
@property()
get poster() {
return this.context.currentPoster;
}
set poster(newPoster) {
this.connectedQueue.queue('currentPoster', () => {
this.context.currentPoster = newPoster;
this.requestUpdate();
});
}
/** @type {HTMLVideoElement} */
get mediaElement() {
return /** @type {HTMLVideoElement} */ (this.mediaRef.value);
}
get videoElement() {
return /** @type {HTMLVideoElement} */ (this.mediaRef.value);
}
get engine() {
return this.mediaElement;
}
get videoEngine() {
return this.videoElement;
}
// -------------------------------------------------------------------------------------------
// Lifecycle
// -------------------------------------------------------------------------------------------
connectedCallback() {
super.connectedCallback();
this.context.viewType = ViewType.Video;
this.dispatchEvent(
new ViewTypeChangeEvent({
detail: ViewType.Video
})
);
}
// -------------------------------------------------------------------------------------------
// Render
// -------------------------------------------------------------------------------------------
/** @returns {import('lit').TemplateResult} */
render() {
return this.renderVideo();
}
/**
* @protected
* @returns {import('lit').TemplateResult}
*/
renderVideo() {
return html`
<video
part="${this.getVideoPartAttr()}"
src="${ifNonEmpty(this.shouldSetVideoSrcAttr() ? this.src : '')}"
width="${ifNumber(this.width)}"
height="${ifNumber(this.height)}"
poster="${ifNonEmpty(this.poster)}"
preload="${ifNonEmpty(this.preload)}"
crossorigin="${ifNonEmpty(this.crossOrigin)}"
controlslist="${ifNonEmpty(this.controlsList)}"
?autoplay="${this.autoplay}"
?loop="${this.loop}"
?playsinline="${this.playsinline}"
?controls="${this.controls}"
?autopictureinpicture="${this.autoPiP}"
?disablepictureinpicture="${this.disablePiP}"
?disableremoteplayback="${this.disableRemotePlayback}"
.defaultMuted="${this.defaultMuted ?? this.muted}"
.defaultPlaybackRate="${this.defaultPlaybackRate ?? 1}"
${ref(this.mediaRef)}
>
${this.renderMediaChildren()}
</video>
`;
}
/**
* Override this to modify video CSS Parts.
*
* @protected
* @returns {string}
*/
getVideoPartAttr() {
return 'media video';
}
/**
* Can be used by attaching engine such as `hls.js` to prevent src attr being set on
* `<video>` element.
*
* @protected
* @returns {boolean}
*/
shouldSetVideoSrcAttr() {
return true;
}
// -------------------------------------------------------------------------------------------
// Methods
// -------------------------------------------------------------------------------------------
/**
* Issues an asynchronous request to display the video in picture-in-picture mode.
*
* It's not guaranteed that the video will be put into picture-in-picture. If permission to enter
* that mode is granted, the returned `Promise` will resolve and the video will receive a
* `enterpictureinpicture` event to let it know that it's now in picture-in-picture.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement/requestPictureInPicture
* @returns {Promise<PictureInPictureWindow>}
*/
async requestPictureInPicture() {
return this.videoElement.requestPictureInPicture();
}
// -------------------------------------------------------------------------------------------
// Fullscreen
// -------------------------------------------------------------------------------------------
presentationController = new VideoPresentationController(this);
fullscreenController = new VideoFullscreenController(
this,
this.screenOrientationController,
this.presentationController
);
} |
JavaScript | class Lock {
constructor() {
// The number of requests initiated and not yet completed
this._requests = 0
}
// -- Getters & Settings
get locked() {
return this._requests > 0
}
// -- Public methods --
/**
* Decrease the number of active requests by 1.
*/
dec() {
this._requests = Math.max(0, this._requests - 1)
}
/**
* Increase the number of active requests by 1.
*/
inc() {
this._requests += 1
}
} |
JavaScript | class VicowaModal extends WebComponentBaseClass {
#activeTranslator;
constructor() {
super();
this.#activeTranslator = null;
}
static get properties() {
return {
open: {
type: Boolean,
reflectToAttribute: true,
value: false,
},
outsideCloses: {
type: Boolean,
reflectToAttribute: true,
value: false,
},
};
}
attached() {
this.addAutoEventListener(this, "click", () => {
if (this.outsideCloses) {
this.open = false;
}
});
this.addAutoEventListener(this.$.modalBox, "click", (p_Event) => {
p_Event.cancelBubble = true;
});
}
static get template() {
return `
<style>
:host {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
display: none;
align-items: center;
justify-content: center;
z-index: 10000;
}
.background {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: black;
opacity: 0.7;
}
:host([open]) {
display: flex;
}
#modal-box {
background: white;
border: 1px solid grey;
box-shadow: 5px 5px 15px black;
min-width: 1em;
min-height: 1em;
z-index: 1;
}
</style>
<div class="background"></div>
<div id="modal-box">
<slot name="content"></slot>
</div>
`;
}
} |
JavaScript | class Vocabulary {
/**
* Class constructor.
*
* @param {integer} dim - word vector length
*/
constructor( dim ) {
if ( !isPositiveInteger( dim ) ) {
throw new TypeError( 'invalid argument. First argument must be a positive integer. Value: `'+dim+'`' );
}
this.dim = dim;
this.hashTable = new Map();
}
/**
* Calculates, stores, and returns the index for a supplied word.
*
* @param {string} word
* @returns {integer} word index
*/
addWord( word ) {
const hash = murmurhash3js.x86.hash32( word );
const remainder = hash % this.dim;
this.hashTable.set( word, remainder );
return remainder;
}
/**
* Processes a document and returns a bag-of-words representation.
*
* @param {string} doc - input document
* @returns {Array} sparse word vector
*/
toVector( doc ) {
// Tokenize document after pre-processing...
doc = processDocument( doc );
const words = tokenize( doc );
for ( let i = 0; i < words.length; i++ ) {
words[ i ] = stemmer( words[ i ] );
}
const len = words.length;
// Add bigrams:
for ( let i = 0; i < len - 1; i++ ) {
words.push( words[ i ] + ' ' + words[ i+1 ] );
}
// Create and return sparse word vector...
const out = new Uint8ClampedArray( this.dim );
for ( let i = 0; i < words.length; i++ ) {
const gram = words[ i ];
let idx;
if ( this.hashTable.has( gram ) ) {
idx = this.hashTable.get( gram );
}
else {
idx = this.addWord( gram );
}
out[ idx ] += 1;
}
const vec = createVector( out );
return vec;
}
} |
JavaScript | class FormState extends React.Component {
/**
* Infer a field value is "checked" from a boolean value.
*
* @param {object} params
* @param {boolean} params.setValuesAssumeBoolIsChecked
* @param {object} params.setValues
* @returns {{}}
*/
static checkedSetValues({ setValuesAssumeBoolIsChecked, setValues }) {
const checked = {};
if (setValuesAssumeBoolIsChecked) {
Object.keys(setValues).forEach(key => {
if (typeof setValues[key] === 'boolean') {
checked[key] = setValues[key];
}
});
}
return checked;
}
/**
* Check if "is a promise".
*
* @param {*} obj
* @returns {boolean}
*/
static isPromise(obj) {
return Object.prototype.toString.call(obj) === '[object Promise]';
}
state = {
...initialState
};
constructor(props) {
super(props);
this.touched = {};
this.checked = FormState.checkedSetValues(props);
this.refValues =
props.resetUsingSetValues === true || props.setValuesOnUpdate === true ? _cloneDeep(props.setValues) : null;
this.errors = {};
this.values = _cloneDeep(props.setValues);
}
componentDidMount() {
const { validateOnMount } = this.props;
if (validateOnMount === true) {
this.validateOnMount();
}
}
componentDidUpdate() {
const { refValues } = this;
const { setValuesOnUpdate, setValues } = this.props;
if (setValuesOnUpdate === true && !_isEqual(refValues, setValues)) {
this.updateComponentValues();
}
}
/**
* Apply form values with a custom event.
*
* @event onEventCustom
* @param {Array|object} custom
*/
onEventCustom = custom => {
const eventArray = (Array.isArray(custom) && custom) || (custom && [custom]);
if (!eventArray.length) {
return;
}
eventArray
.filter(event => 'name' in event && ('value' in event || 'checked' in event))
.forEach(event => this.onEvent({ target: { ...event }, persist: helpers.noop, type: 'custom' }));
};
/**
* Generic "on event" for handling returned event objects.
*
* @event onEvent
* @param {object} event
*/
onEvent = event => {
const { touched, values } = this;
const { id, name, value, checked } = event.options ? { ...event } : event.target;
event.persist();
const targetName = name || id || 'generated form state target, add name or id attr to field';
this.touched = { ...touched, [targetName]: true };
this.values = { ...values, [targetName]: value };
if (checked !== undefined) {
this.checked = { ...this.checked, [targetName]: checked };
}
this.setState(
{
isUpdating: true,
isValidating: true
},
() =>
this.validate(event).then(updatedErrors => {
const setUpdateErrors = { ...((updatedErrors && updatedErrors[0]) || updatedErrors || {}) };
const checkIsValid = !Object.values(setUpdateErrors).filter(val => val === true).length;
this.errors = setUpdateErrors;
this.setState({
isUpdating: false,
isValid: checkIsValid,
isValidating: false
});
})
);
};
/**
* Reset FormState's form state. Apply prop onReset function.
*
* @event onReset
* @param {object} event
*/
onReset = event => {
const { refValues, values } = this;
const { setValuesAssumeBoolIsChecked, onReset, resetUsingSetValues } = this.props;
event.persist();
const isResetWithSetValues = refValues && resetUsingSetValues === true;
const updatedValues = (isResetWithSetValues && _cloneDeep(refValues)) || {};
const updatedChecked =
(isResetWithSetValues && FormState.checkedSetValues(setValuesAssumeBoolIsChecked, updatedValues)) || {};
this.values = updatedValues;
this.checked = updatedChecked;
this.errors = {};
this.touched = {};
this.setState({
...initialState
});
if (isResetWithSetValues) {
onReset({ event, ..._cloneDeep({ values: updatedValues, prevValues: values }) });
} else {
// Resetting the values, potentially, will throw the controlled vs uncontrolled messaging.
onReset({ event, values: {}, ..._cloneDeep({ prevValues: values }) });
}
};
/**
* Validate form, then submit.
*
* @event onSubmit
* @param {object} event
*/
onSubmit = event => {
const { submitCount } = this.state;
event.persist();
event.preventDefault();
this.setState(
{
submitCount: submitCount + 1,
isSubmitting: true,
isUpdating: true,
isValidating: true
},
() =>
this.validate(event).then(updatedErrors => {
const setUpdateErrors = { ...((updatedErrors && updatedErrors[0]) || updatedErrors || {}) };
const checkIsValid = !Object.values(setUpdateErrors).filter(val => val === true).length;
this.errors = setUpdateErrors;
this.touched = {};
this.setState(
{
isValid: checkIsValid,
isValidating: false
},
() =>
checkIsValid &&
this.submit(event).then(() => {
this.setState({
isSubmitting: false,
isUpdating: false
});
})
);
})
);
};
/**
* Handle submitted form, check and return Promise, or emulate for consistency.
*
* @param {object} event
* @returns {Promise}
*/
submit(event = { type: 'submit' }) {
const { checked, errors, values, touched } = this;
const { onSubmit } = this.props;
const checkPromise = onSubmit({
event,
..._cloneDeep({ ...this.state, checked, errors, values, touched })
});
if (FormState.isPromise(checkPromise)) {
return checkPromise;
}
return {
then: callback => callback()
};
}
/**
* Handle validated form data, check and return Promise, or emulate for consistency.
*
* @param {object} event
* @returns {Promise}
*/
validate(event = { type: 'validate' }) {
const { checked, errors, values, touched } = this;
const { validate } = this.props;
const checkPromise = validate({
event,
..._cloneDeep({ ...this.state, checked, errors, values, touched })
});
if (FormState.isPromise(checkPromise)) {
return checkPromise;
}
return {
then: callback => callback(checkPromise)
};
}
/**
* Shortcut, activate validation on component mount.
*
* @param {object} event
*/
validateOnMount(event = { type: 'mount' }) {
this.validateOnUpdate(event);
}
/**
* Validate on component update.
*
* @param {object} event
*/
validateOnUpdate(event = { type: 'update' }) {
this.setState(
{
isUpdating: true,
isValidating: true
},
() =>
this.validate(event).then(updatedErrors => {
const setUpdateErrors = { ...((updatedErrors && updatedErrors[0]) || updatedErrors || {}) };
const checkIsValid = !Object.values(setUpdateErrors).filter(val => val === true).length;
this.errors = setUpdateErrors;
this.setState({
isUpdating: false,
isValidating: false,
isValid: checkIsValid
});
})
);
}
/**
* On component update, update state.
*/
updateComponentValues() {
const { setValues, setValuesAssumeBoolIsChecked, validateOnUpdate } = this.props;
this.setState(
{
isUpdating: true
},
() => {
this.checked = FormState.checkedSetValues(setValuesAssumeBoolIsChecked, setValues);
this.refValues = _cloneDeep(setValues);
this.values = _cloneDeep(setValues);
if (validateOnUpdate) {
this.validateOnUpdate();
} else {
this.setState({
isUpdating: false
});
}
}
);
}
/**
* Pass child components, integrate and apply form context.
*
* @returns {Node}
*/
render() {
const { checked, errors, values, touched } = this;
const { children } = this.props;
return (
<React.Fragment>
{children({
handleOnEventCustom: this.onEventCustom,
handleOnEvent: this.onEvent,
handleOnReset: this.onReset,
handleOnSubmit: this.onSubmit,
..._cloneDeep({ ...this.state, checked, errors, values, touched })
})}
</React.Fragment>
);
}
} |
JavaScript | class GameMap extends Component {
constructor(props) {
super(props)
this.state = {updates: 0}
this.updateInfo = props.updateInfo
this.selector = new GameSelector(
this.isInBounds,
this.updateFocusedTile
)
this.gameLoader = new GameLoader(
this.props.web3,
(width,height) => {
this.gameWidth=width;
this.gameHeight=height;
this.selector.gameWidth = width;
this.selector.gameHeight = height;
},
(atlas)=>{this.atlas = atlas; this.update()}
)
// ref to tileMap to update tileMap
this.tileMap = React.createRef();
}
updateFocusedTile = (x,y) => {
this.updateInfo(this.atlas.info(x,y),
{ NORTH: this.atlas.info(x,y+1),
SOUTH: this.atlas.info(x,y-1),
EAST: this.atlas.info(x+1,y),
WEST: this.atlas.info(x-1,y)})
}
isInBounds(x, y){
if (!this.gameWidth || !this.gameHeight){
return false
}
return (x >= -(this.gameWidth / 2) && x < (this.gameWidth / 2) && y >= -(this.gameHeight / 2) && y < (this.gameHeight / 2))
}
update(){
this.setState({updates: this.state.updates+1})
}
handleClick(x, y, ctrlKey, shiftKey) {
this.selector.handleClick(x,y,ctrlKey,shiftKey)
}
handleDrag(x1, y1, x2, y2, ctrlKey, shiftKey) {
this.selector.handleDrag(x1, y1, x2, y2, ctrlKey, shiftKey)
}
// empty, farm, wall, out of bounds
baseLayer = (x, y) => {
if (this.isInBounds(x, y)) {
const posX = x + (this.gameWidth / 2)
const posY = y + (this.gameHeight / 2)
if (this.atlas) {
const info = this.atlas.info(posX, posY)
if (info) {
return {
color: info.tileColor(),
}
} else {
return {
color: unloadedColor,
}
}
} else {
// should not be here
}
} else {
return {
color: outOfBoundsColor
}
}
}
// army
armyLayer = (x, y) => {
if (this.isInBounds(x, y)) {
const posX = x + (this.gameWidth / 2)
const posY = y + (this.gameHeight / 2)
if (this.atlas) {
const info = this.atlas.info(posX, posY)
if (info) {
if (info.containsArmy) {
return {
color: info.armyColor(),
scale: .75
}
}
} else {
return {
color: unloadedColor,
}
}
} else {
// should not be here
}
}
}
//selection
selectedLayer = (x, y) => {
const isSelected = this.selector.isSelected(x, y)
return {
color: isSelected ? "#ffffff30" : "#00000000",
outlineLeft: isSelected && !this.selector.isSelected(x - 1, y),
outlineTop: isSelected && !this.selector.isSelected(x, y + 1),
outlineRight: isSelected && !this.selector.isSelected(x + 1, y),
outlineBottom: isSelected && !this.selector.isSelected(x, y - 1),
outlineTopLeft: isSelected && !this.selector.isSelected(x - 1, y + 1),
outlineBottomLeft: isSelected && !this.selector.isSelected(x - 1, y - 1),
outlineTopRight: isSelected && !this.selector.isSelected(x + 1, y + 1),
outlineBottomRight: isSelected && !this.selector.isSelected(x + 1, y - 1),
outlineColor: selectedColor,
outlineWidth: .1
}
}
componentDidMount() {
console.log("Game map mounted")
}
render() {
if (this.atlas != null) {
return (
<div>
<TileMap
ref={this.tileMap}
layers={[this.baseLayer, this.armyLayer, this.selectedLayer]}
onClick={(x, y, ctrlKey, shiftKey) => { this.handleClick(x, y, ctrlKey, shiftKey) }}
onMouseDrag={(x1, y1, x2, y2, ctrlKey, shiftKey) => { this.handleDrag(x1, y1, x2, y2, ctrlKey, shiftKey) }}
minX={-5 * this.gameWidth}
maxX={.5 * this.gameWidth}
minY={-.5 * this.gameHeight}
maxY={.5 * this.gameHeight}
width={this.props.width}
height={this.props.height}
/>
</div>
);
} else {
return (<div><p>Loading empires from blockchain...</p></div>)
}
}
} |
JavaScript | class AbstractFilterHash extends bus_query_operation_1.ActorQueryOperationTypedMediated {
constructor(args, operator) {
super(args, operator);
if (!AbstractFilterHash.doesHashAlgorithmExist(this.hashAlgorithm)) {
throw new Error("The given hash algorithm is not present in this version of Node: " + this.hashAlgorithm);
}
if (!AbstractFilterHash.doesDigestAlgorithmExist(this.digestAlgorithm)) {
throw new Error("The given digest algorithm is not present in this version of Node: " + this.digestAlgorithm);
}
}
/**
* Check if the given hash algorithm (such as sha1) exists.
* @param {string} hashAlgorithm A hash algorithm.
* @return {boolean} If it exists.
*/
static doesHashAlgorithmExist(hashAlgorithm) {
return crypto_1.getHashes().indexOf(hashAlgorithm) >= 0;
}
/**
* Check if the given digest (such as base64) algorithm exists.
* @param {string} digestAlgorithm A digest algorithm.
* @return {boolean} If it exists.
*/
static doesDigestAlgorithmExist(digestAlgorithm) {
return ["latin1", "hex", "base64"].indexOf(digestAlgorithm) >= 0;
}
/**
* Create a string-based hash of the given object.
* @param {string} hashAlgorithm A hash algorithm.
* @param {string} digestAlgorithm A digest algorithm.
* @param object The object to hash.
* @return {string} The object's hash.
*/
static hash(hashAlgorithm, digestAlgorithm, object) {
const hash = crypto_1.createHash(hashAlgorithm);
hash.update(require('json-stable-stringify')(object));
return hash.digest(digestAlgorithm);
}
async testOperation(pattern, context) {
return true;
}
} |
JavaScript | class LinkParent extends BaseModel {
getLinkObject() {
return { linkedObjectId: this._id, objectType: this._objectType };
}
} |
JavaScript | class QueryIndexManager {
/**
* @hideconstructor
*/
constructor(cluster) {
this._cluster = cluster;
}
get _http() {
return new HttpExecutor(this._cluster._getClusterConn());
}
async _createIndex(bucketName, options, callback) {
return PromiseHelper.wrap(async () => {
var qs = '';
if (options.fields.length === 0) {
qs += 'CREATE PRIMARY INDEX';
} else {
qs += 'CREATE INDEX';
}
if (options.name) {
qs += ' `' + options.name + '`';
}
qs += ' ON `' + bucketName + '`';
if (options.fields && options.fields.length > 0) {
qs += '(';
for (var i = 0; i < options.fields.length; ++i) {
if (i > 0) {
qs += ', ';
}
qs += '`' + options.fields[i] + '`';
}
qs += ')';
}
if (options.deferred) {
qs += ' WITH {"defer_build: true}';
}
try {
await this._bucket.query(qs);
return true;
} catch (err) {
if (options.ignoreIfExists) {
if (err.message.indexOf('already exist') >= 0) {
return true;
}
}
throw err;
}
}, callback);
}
async create(bucketName, indexName, fields, options, callback) {
if (options instanceof Function) {
callback = arguments[2];
options = undefined;
}
if (!options) {
options = {};
}
return PromiseHelper.wrap(async () => {
return this._createIndex(bucketName, {
name: indexName,
fields: fields,
ignoreIfExists: options.ignoreIfExists,
deferred: options.deferred,
});
}, callback);
}
async createPrimary(bucketName, options, callback) {
if (options instanceof Function) {
callback = arguments[0];
options = undefined;
}
if (!options) {
options = {};
}
return PromiseHelper.wrap(async () => {
return this._createIndex(bucketName, {
name: options.name,
ignoreIfExists: options.ignoreIfExists,
deferred: options.deferred,
});
}, callback);
}
async _dropIndex(bucketName, options, callback) {
return PromiseHelper.wrap(async () => {
var qs = '';
if (!options.name) {
qs += 'DROP PRIMARY INDEX `' + bucketName + '`';
} else {
qs += 'DROP INDEX `' + bucketName + '`.`' + options.name + '`';
}
try {
await this._bucket.query(qs);
return true;
} catch (err) {
if (options.ignoreIfNotExists) {
if (err.message.indexOf('not found') >= 0) {
return true;
}
}
throw err;
}
}, callback);
}
async drop(bucketName, indexName, options, callback) {
if (options instanceof Function) {
callback = arguments[2];
options = undefined;
}
if (!options) {
options = {};
}
return PromiseHelper.wrap(async () => {
return this._dropIndex(bucketName, {
name: indexName,
ignoreIfNotExists: options.ignoreIfNotExists,
});
}, callback);
}
async dropPrimary(bucketName, options, callback) {
if (options instanceof Function) {
callback = arguments[0];
options = undefined;
}
if (!options) {
options = {};
}
return PromiseHelper.wrap(async () => {
return this._dropIndex(bucketName, {
name: options.name,
ignoreIfNotExists: options.ignoreIfNotExists,
});
}, callback);
}
async getAll(bucketName, options, callback) {
if (options instanceof Function) {
callback = arguments[1];
options = undefined;
}
if (!options) {
options = {};
}
return PromiseHelper.wrap(async () => {
var qs = '';
qs += 'SELECT idx.* FROM system:indexes AS idx';
qs += ' WHERE keyspace_id="' + bucketName + '"';
qs += ' AND `using`="gsi" ORDER BY is_primary DESC, name ASC';
var res = this._bucket.query(qs);
/*
Name
IsPrimary
Type
State
Keyspace
IndexKey
*/
return res;
}, callback);
}
async buildDeferred(bucketName, options, callback) {
if (options instanceof Function) {
callback = arguments[1];
options = undefined;
}
if (!options) {
options = {};
}
return PromiseHelper.wrap(async () => {
var indices = await this.list();
var deferredList = [];
for (var i = 0; i < indices.length; ++i) {
var index = indices[i];
if (index.state === 'deferred' || index.state === 'pending') {
deferredList.push(index.name);
}
}
// If there are no deferred indexes, we have nothing to do.
if (!deferredList) {
return [];
}
var qs = '';
qs += 'BUILD INDEX ON `' + bucketName + '` ';
qs += '(';
for (var j = 0; j < deferredList.length; ++j) {
if (j > 0) {
qs += ', ';
}
qs += '`' + deferredList[j] + '`';
}
qs += ')';
// Run our deferred build query
await this._bucket.query(qs);
// Return the list of indices that we built
return deferredList;
}, callback);
}
async watch(bucketName, indexNames, duration, options, callback) {
throw new Error('watching of indexes is not yet supported');
}
} |
JavaScript | class Meetings {
constructor() {
/** @private {number} Unique per-meeting id. */
this.nextId = 0;
/** @const {!Map<number, !Meeting>} All the meetings we track. */
this.meetings = new Map();
}
/**
* @return {number} How many meetings exist.
*/
get size() {
return this.meetings.size;
}
/**
* Add a meeting to our set.
*
* @param {!Meeting} meeting The meeting to add.
*/
add(meeting) {
meeting.id = this.nextId++;
this.meetings.set(meeting.id, meeting);
badge.update();
}
/**
* Remove a meeting from our set.
*
* @param {!Meeting} meeting The meeting to remove.
*/
remove(meeting) {
this.meetings.delete(meeting.id);
badge.update();
}
/**
* Get a meeting by a specific id (the internal counter).
*
* @param {number} id The meeting to get.
* @return {!Meeting|undefined} The meeting if it exists.
*/
get(id) {
return this.meetings.get(id);
}
/**
* Get the meeting the user has marked as default/preferred.
*
* Up to one meeting may be marked as such at a time.
*
* @return {!Meeting|undefined}
*/
get default() {
let ret;
this.meetings.forEach((meeting) => {
if (meeting.prefer) {
ret = meeting;
}
});
return ret;
}
/**
* Upate the user's default/preferred meeting.
*
* Up to one meeting may be marked as such at a time. If a different meeting
* is marked as the default, it will be cleared automatically. This can be
* used to clear the current preference too (so no meeting is the default).
*
* @param {number} id The (internal) meeting id.
* @param {boolean=} value How to mark the meeting's preferred state.
*/
setDefault(id, value = true) {
this.meetings.forEach((meeting) => {
if (meeting.id === id) {
meeting.prefer = value;
} else if (value && meeting.prefer) {
meeting.prefer = false;
}
});
badge.update();
}
/**
* Find a meeting associated with a specific tab.
*
* @param {!Object} param The tab settings.
* @return {!Meeting|undefined} The meeting if one exists.
*/
find({tabId, windowId}) {
let ret;
this.meetings.forEach((meeting) => {
const tab = meeting.port.sender.tab;
if (tab.id === tabId && tab.windowId === windowId) {
ret = meeting;
}
});
return ret;
}
/**
* Iterate over the meetings based on our algorithm.
*
* If a meeting has been marked default, then only process that one.
* If no meetings are active (been joined), then process all meetings.
* Else, process all active meetings.
*
* For the first meeting processed, honor the user's autofocus pref.
*
* @private
* @param {function(!Meeting)} callback
*/
processMeetings_(callback) {
const prefer = this.default;
if (prefer) {
prefer.autofocus();
callback(prefer);
return;
}
const numActive = this.numActive;
let focused = false;
this.meetings.forEach((meeting) => {
if (numActive === 0 || meeting.active) {
if (focused === false) {
focused = true;
meeting.autofocus();
}
callback(meeting);
}
});
}
/**
* Toggle mic/cam settings across meetings.
*
* @param {!Object} data Which settings to change.
*/
toggle(data = {audio: true}) {
this.processMeetings_((meeting) => meeting.toggle(data));
}
/**
* Mute mic/cam settings across meetings.
*
* @param {!Object} data Which settings to change.
*/
mute(data = {audio: true}) {
this.processMeetings_((meeting) => meeting.mute(data));
}
/**
* Unmute mic/cam settings across meetings.
*
* @param {!Object} data Which settings to change.
*/
unmute(data = {audio: true}) {
this.processMeetings_((meeting) => meeting.unmute(data));
}
/**
* Focus the active meeting if the user prefs want it.
*/
autofocus() {
if (autofocus) {
this.focus();
}
}
/**
* Focus the active meeting.
*/
focus() {
// NB: Some logic is duplicated in processMeetings_ resulting in us calling
// focus on the same tab twice in a row, but that should be fine.
let focused = false;
this.processMeetings_((meeting) => {
if (focused === false) {
focused = true;
meeting.focus();
}
});
}
/**
* Helper for counting truthy fields of meeting objects.
*
* @param {string} property The field to check.
* @return {number}
* @private
*/
countMeetings_(property) {
let ret = 0;
this.meetings.forEach((meeting) => {
ret += meeting[property] ? 1 : 0;
});
return ret;
}
/**
* @return {number} How many meetings are active (joined).
*/
get numActive() {
return this.countMeetings_('active');
}
/**
* @return {number} How many meetings have audio muted.
*/
get numAudioMuted() {
return this.countMeetings_('audioMuted');
}
/**
* @return {number} How many meetings have video muted.
*/
get numVideoMuted() {
return this.countMeetings_('videoMuted');
}
/**
* @return {!Symbol} The high level state for the badge.
*/
get state() {
if (this.size === 0) {
return Meetings.INACTIVE;
}
return this.numAudioMuted === this.size ? Meetings.MUTED : Meetings.UNMUTED;
}
/**
* @return {!Symbol} The high level summary text for the badge.
*/
get summary() {
const size = this.size;
const numAudioMuted = this.numAudioMuted;
const numVideoMuted = this.numVideoMuted;
if (size === 0) {
return 'No meetings found. Please reload Google Meet pages to connect.';
} else if (size === numAudioMuted) {
return `All meetings are muted.`;
} else if (numAudioMuted === 0) {
return `No meetings are muted.`;
} else {
return `${size} active meetings; ${numAudioMuted} are muted.`;
}
}
} |
JavaScript | class Meeting {
constructor(port) {
this.id = null;
this.title = null;
this.port = port;
this.active = false;
this.prefer = false;
this.audioMuted = null;
this.videoMuted = null;
}
bind() {
meetings.add(this);
this.port.onDisconnect.addListener(this.disconnect.bind(this));
this.port.onMessage.addListener(this.recv.bind(this));
}
disconnect() {
logging.debug('disconnect', this.port);
meetings.remove(this);
}
toggle(data = {audio: true}) {
this.send('toggle', data);
}
mute(data = {audio: true}) {
this.send('mute', data);
}
unmute(data = {audio: true}) {
this.send('unmute', data);
}
/**
* Focus the active meeting if the user prefs want it.
*/
autofocus() {
if (autofocus) {
this.focus();
}
}
focus() {
// NB: We can't rely on the port->sender details as they don't stay in
// sync with the actual tab (like the index field). So query the latest
// state here to access it.
chrome.tabs.get(this.port.sender.tab.id, (tab) => {
chrome.windows.update(tab.windowId, {focused: true});
chrome.tabs.highlight({tabs: tab.index, windowId: tab.windowId});
});
}
send(command, data = {}) {
const message = Object.assign({}, data, {command});
this.port.postMessage(message);
}
/**
* Invoked when a message came across the port.
*
* @see https://developer.chrome.com/extensions/runtime/#event-onMessage
* @param {!Object} message
* @private
*/
recv(message) {
logging.debug('recv', this.port, message);
const {command} = message;
const handler = this.commands.get(command);
if (handler) {
logging.debug(`dispatching to ${command}`, message);
handler.call(this, message);
} else {
logging.warn(`${this.port.name}: unknown command '${command}'`, message);
}
}
/**
* The page wants to log stuff.
*
* @param {string} message The log message
*/
message_log(message) {
logging.recordLog(message);
}
/**
* The user has joined the meeting, so it is now active.
*/
message_joined() {
this.active = true;
badge.update();
}
/**
* Update meeting info we care about.
*
* @param {!Object} param The new mic/cam settings.
*/
message_update({title, audioMuted, videoMuted}) {
if (title) {
this.title = title.replace(/^Meet - /, '');
}
const update =
this.audioMuted !== audioMuted || this.videoMuted !== videoMuted;
this.audioMuted = audioMuted;
this.videoMuted = videoMuted;
// Debounce updates due to possible duplicate notifications.
if (update) {
badge.update();
}
}
} |
JavaScript | class Badge {
constructor() {
this.popup = null;
}
/**
* Helper to call all the relevant badge extension APIs.
*
* @param {!Object} settings The badge settings.
*/
set({icon, title, popup, text, color}) {
if (icon !== undefined) {
if (typeof icon === 'string') {
icon = {19: `../images/${icon}-96.png`};
}
chrome.browserAction.setIcon({path: icon});
}
if (title !== undefined) {
chrome.browserAction.setTitle({title});
}
if (popup !== undefined) {
chrome.browserAction.setPopup({popup});
}
if (text !== undefined) {
chrome.browserAction.setBadgeText({text});
}
if (color !== undefined) {
chrome.browserAction.setBadgeBackgroundColor({color});
}
}
/**
* The popup action based on user prefs & meeting states.
*
* @return {string} The popup URL to use.
*/
get popupAction() {
const popup = 'html/control.html';
switch (actionButtonBehavior) {
case 'popup':
return popup;
default:
logging.warn(`Unknown action behavior '${actionButtonBehavior}'`);
case 'toggle-audio+popup':
case 'focus+popup':
case 'mute-audio+popup':
if (meetings.default) {
return '';
} else if (
meetings.numActive > 1 ||
(meetings.numActive == 0 && meetings.size > 1)
) {
return popup;
}
return '';
case 'toggle-audio':
case 'focus':
case 'mute-audio':
return '';
}
}
/**
* Update the badge icon/text/etc... based on current meetings state.
*/
update() {
// If a popup is connected, fake a refresh request.
if (this.popup) {
onInternalPageMessage(this.popup, {command: 'list'});
}
const state = meetings.state;
const size = meetings.size;
const summary = meetings.summary;
switch (state) {
default:
logging.error(`unable to update to unknown badge state '${state}'`);
break;
case Meetings.INACTIVE:
this.set({
icon: 'inactive',
title: summary,
popup: 'html/inactive.html',
text: '',
});
break;
case Meetings.UNMUTED: {
const numMuted = meetings.numAudioMuted;
const text = numMuted === 0 ? `${size}` : `${numMuted}/${size}`;
this.set({
icon: 'mic-on',
title: summary,
popup: this.popupAction,
text: text,
color: '#219653',
});
break;
}
case Meetings.MUTED:
this.set({
icon: 'mic-off',
title: summary,
popup: this.popupAction,
text: `${size}`,
color: '#d92f25',
});
break;
}
}
} |
JavaScript | class ResourceSettingCreationParameters {
/**
* Create a ResourceSettingCreationParameters.
* @property {string} [location] The location where the virtual machine will
* live
* @property {string} [name] The name of the resource setting
* @property {string} galleryImageResourceId The resource id of the gallery
* image used for creating the virtual machine
* @property {string} [size] The size of the virtual machine. Possible values
* include: 'Basic', 'Standard', 'Performance'
* @property {object} referenceVmCreationParameters Creation parameters for
* Reference Vm
* @property {string} [referenceVmCreationParameters.userName] The username
* of the virtual machine
* @property {string} [referenceVmCreationParameters.password] The password
* of the virtual machine.
*/
constructor() {
}
/**
* Defines the metadata of ResourceSettingCreationParameters
*
* @returns {object} metadata of ResourceSettingCreationParameters
*
*/
mapper() {
return {
required: false,
serializedName: 'ResourceSettingCreationParameters',
type: {
name: 'Composite',
className: 'ResourceSettingCreationParameters',
modelProperties: {
location: {
required: false,
serializedName: 'location',
type: {
name: 'String'
}
},
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
galleryImageResourceId: {
required: true,
serializedName: 'galleryImageResourceId',
type: {
name: 'String'
}
},
size: {
required: false,
serializedName: 'size',
type: {
name: 'String'
}
},
referenceVmCreationParameters: {
required: true,
serializedName: 'referenceVmCreationParameters',
type: {
name: 'Composite',
className: 'ReferenceVmCreationParameters'
}
}
}
}
};
}
} |
JavaScript | class ProductSearchHit {
/**
* Constructs a new <code>ProductSearchHit</code>.
* Document representing a product search hit.
* @alias module:models/ProductSearchHit
* @class
*/
constructor() {
}
/**
* Constructs a <code>ProductSearchHit</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:models/ProductSearchHit} obj Optional instance to populate.
* @return {module:models/ProductSearchHit} The populated <code>ProductSearchHit</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ProductSearchHit()
if (data.hasOwnProperty('currency')) {
obj.currency = ApiClient.convertToType(data.currency, 'String')
}
if (data.hasOwnProperty('hit_type')) {
obj.hit_type = ApiClient.convertToType(data.hit_type, 'String')
}
if (data.hasOwnProperty('image')) {
obj.image = Image.constructFromObject(data.image)
}
if (data.hasOwnProperty('link')) {
obj.link = ApiClient.convertToType(data.link, 'String')
}
if (data.hasOwnProperty('orderable')) {
obj.orderable = ApiClient.convertToType(data.orderable, 'Boolean')
}
if (data.hasOwnProperty('price')) {
obj.price = ApiClient.convertToType(data.price, 'Number')
}
if (data.hasOwnProperty('price_max')) {
obj.price_max = ApiClient.convertToType(data.price_max, 'Number')
}
if (data.hasOwnProperty('prices')) {
obj.prices = ApiClient.convertToType(data.prices, {String: 'Number'})
}
if (data.hasOwnProperty('product_id')) {
obj.product_id = ApiClient.convertToType(data.product_id, 'String')
}
if (data.hasOwnProperty('product_name')) {
obj.product_name = ApiClient.convertToType(data.product_name, 'String')
}
if (data.hasOwnProperty('product_type')) {
obj.product_type = ProductType.constructFromObject(data.product_type)
}
if (data.hasOwnProperty('represented_product')) {
obj.represented_product = ProductRef.constructFromObject(data.represented_product)
}
if (data.hasOwnProperty('represented_products')) {
obj.represented_products = ApiClient.convertToType(data.represented_products, [ProductRef])
}
if (data.hasOwnProperty('variation_attributes')) {
obj.variation_attributes = ApiClient.convertToType(data.variation_attributes, [VariationAttribute])
}
}
return obj
}
/**
* The ISO 4217 mnemonic code of the currency.
* @member {String} currency
*/
currency = undefined;
/**
* The type information for the search hit.
* @member {String} hit_type
*/
hit_type = undefined;
/**
* The first image of the product hit for the configured viewtype.
* @member {module:models/Image} image
*/
image = undefined;
/**
* The URL addressing the product.
* @member {String} link
*/
link = undefined;
/**
* A flag indicating whether the product is orderable.
* @member {Boolean} orderable
*/
orderable = undefined;
/**
* The sales price of the product. In case of complex products like master or set this is the minimum price of related child products.
* @member {Number} price
*/
price = undefined;
/**
* The maximum sales of related child products in case of complex products like master or set.
* @member {Number} price_max
*/
price_max = undefined;
/**
* The prices map with price book ids and their values.
* @member {Object.<String, Number>} prices
*/
prices = undefined;
/**
* The id (SKU) of the product.
* @member {String} product_id
*/
product_id = undefined;
/**
* The localized name of the product.
* @member {String} product_name
*/
product_name = undefined;
/**
* The type information for the product.
* @member {module:models/ProductType} product_type
*/
product_type = undefined;
/**
* The first represented product.
* @member {module:models/ProductRef} represented_product
*/
represented_product = undefined;
/**
* All the represented products.
* @member {Array.<module:models/ProductRef>} represented_products
*/
represented_products = undefined;
/**
* The array of represented variation attributes (for the master product only). This array can be empty.
* @member {Array.<module:models/VariationAttribute>} variation_attributes
*/
variation_attributes = undefined;
} |
JavaScript | class TermsController {
/**
* @memberof TermsController
* @param {*} req - Payload
* @param {*} res - Response object
* @returns {Response.Success} if no error occurs
* @returns {Response.internalServerError} if error occurs
*/
static async createTerm(req, res) {
try {
const result = await Term.create({ ...req.body });
Response.Success(res, { term: result }, 201);
} catch (err) {
Response.InternalServerError(res, 'Error creating term');
}
}
/**
* @memberof TermsController
* @param {*} req - Payload
* @param {*} res - Response object
* @returns {Response.Success} if no error occurs
* @returns {Response.internalServerError} if error occurs
*/
static async editTerm(req, res) {
const termId = req.params.id;
try {
const term = await Term.findOne({ _id: termId });
if (!term) return Response.NotFoundError(res, 'term does not exist');
const termValues = { $set: req.body };
const termUpdate = await Term.findOneAndUpdate({ _id: termId }, termValues, { returnOriginal: false });
return Response.Success(res, { term: termUpdate }, 200);
} catch (error) {
return Response.InternalServerError(res, 'Could not update term');
}
}
/**
* @memberof TermsController
* @param {*} req - Payload
* @param {*} res - Response object
* @returns {Response.Success} if no error occurs
* @returns {Response.InternalServerError} if error occurs
*/
static async deleteTerm(req, res) {
const termId = req.params.id;
try {
const term = await Term.findOne({ _id: termId });
if (!term) return Response.NotFoundError(res, 'term does not exist');
await Term.deleteOne({ _id: req.params.id });
Response.Success(res, { message: 'Term deleted successfully' });
} catch (err) {
Response.InternalServerError(res, 'Error deleting term');
}
}
/**
* @memberof TermsController
* @param {*} req - Payload
* @param {*} res - Response object
* @returns {Response.Success} if no error occurs
* @returns {Response.InternalServerError} if error occurs
*/
static async deleteTerms(req, res) {
try {
const { termIds } = req.body
await Term.deleteMany({ _id: { $in: termIds } });
Response.Success(res, { message: 'Terms deleted successfully' });
} catch (err) {
Response.InternalServerError(res, 'Error deleting terms');
}
}
/**
* @memberof TermsController
* @param {*} req - Payload
* @param {*} res - Response object
* @returns {Response.Success} if no error occurs
* @returns {Response.InternalServerError} if error occurs
*/
static async fetchAllTerms(req, res) {
try {
const terms = await Term.find().populate("creatorId");
return Response.Success(res, { terms });
} catch (err) {
return Response.InternalServerError(res, 'Error fetching terms');
}
}
} |
JavaScript | class ContribPower {
/**
* Constructs a new <code>ContribPower</code>.
* @alias module:model/ContribPower
* @param contributors {Array.<module:model/ContribPowerDevice>}
*/
constructor(contributors) {
ContribPower.initialize(this, contributors);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, contributors) {
obj['contributors'] = contributors;
}
/**
* Constructs a <code>ContribPower</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/ContribPower} obj Optional instance to populate.
* @return {module:model/ContribPower} The populated <code>ContribPower</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ContribPower();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('when')) {
obj['when'] = ApiClient.convertToType(data['when'], 'String');
}
if (data.hasOwnProperty('contributors')) {
obj['contributors'] = ApiClient.convertToType(data['contributors'], [ContribPowerDevice]);
}
if (data.hasOwnProperty('modes')) {
obj['modes'] = ApiClient.convertToType(data['modes'], ['Number']);
}
}
return obj;
}
} |
JavaScript | class GraphQLError extends Error {
/**
* An array of `{ line, column }` locations within the source GraphQL document
* which correspond to this error.
*
* Errors during validation often contain multiple locations, for example to
* point out two things with the same name. Errors during execution include a
* single location, the field which produced the error.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array describing the JSON-path into the execution response which
* corresponds to this error. Only included for errors during execution.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array of GraphQL AST Nodes corresponding to this error.
*/
/**
* The source GraphQL document for the first location of this error.
*
* Note that if this Error represents more than one node, the source may not
* represent nodes after the first node.
*/
/**
* An array of character offsets within the source GraphQL document
* which correspond to this error.
*/
/**
* The original error thrown from a field resolver during execution.
*/
/**
* Extension fields to add to the formatted error.
*/
/**
* @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
*/
constructor(message, ...rawArgs) {
var _this$nodes, _nodeLocations$, _ref;
const { nodes, source, positions, path, originalError, extensions } =
toNormalizedOptions(rawArgs);
super(message);
this.name = 'GraphQLError';
this.path = path !== null && path !== void 0 ? path : undefined;
this.originalError =
originalError !== null && originalError !== void 0
? originalError
: undefined; // Compute list of blame nodes.
this.nodes = undefinedIfEmpty(
Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined,
);
const nodeLocations = undefinedIfEmpty(
(_this$nodes = this.nodes) === null || _this$nodes === void 0
? void 0
: _this$nodes.map((node) => node.loc).filter((loc) => loc != null),
); // Compute locations in the source for the given nodes/positions.
this.source =
source !== null && source !== void 0
? source
: nodeLocations === null || nodeLocations === void 0
? void 0
: (_nodeLocations$ = nodeLocations[0]) === null ||
_nodeLocations$ === void 0
? void 0
: _nodeLocations$.source;
this.positions =
positions !== null && positions !== void 0
? positions
: nodeLocations === null || nodeLocations === void 0
? void 0
: nodeLocations.map((loc) => loc.start);
this.locations =
positions && source
? positions.map((pos) => (0, _location.getLocation)(source, pos))
: nodeLocations === null || nodeLocations === void 0
? void 0
: nodeLocations.map((loc) =>
(0, _location.getLocation)(loc.source, loc.start),
);
const originalExtensions = (0, _isObjectLike.isObjectLike)(
originalError === null || originalError === void 0
? void 0
: originalError.extensions,
)
? originalError === null || originalError === void 0
? void 0
: originalError.extensions
: undefined;
this.extensions =
(_ref =
extensions !== null && extensions !== void 0
? extensions
: originalExtensions) !== null && _ref !== void 0
? _ref
: Object.create(null); // Only properties prescribed by the spec should be enumerable.
// Keep the rest as non-enumerable.
Object.defineProperties(this, {
message: {
writable: true,
enumerable: true,
},
name: {
enumerable: false,
},
nodes: {
enumerable: false,
},
source: {
enumerable: false,
},
positions: {
enumerable: false,
},
originalError: {
enumerable: false,
},
}); // Include (non-enumerable) stack trace.
/* c8 ignore start */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
if (
originalError !== null &&
originalError !== void 0 &&
originalError.stack
) {
Object.defineProperty(this, 'stack', {
value: originalError.stack,
writable: true,
configurable: true,
});
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, GraphQLError);
} else {
Object.defineProperty(this, 'stack', {
value: Error().stack,
writable: true,
configurable: true,
});
}
/* c8 ignore stop */
}
get [Symbol.toStringTag]() {
return 'GraphQLError';
}
toString() {
let output = this.message;
if (this.nodes) {
for (const node of this.nodes) {
if (node.loc) {
output += '\n\n' + (0, _printLocation.printLocation)(node.loc);
}
}
} else if (this.source && this.locations) {
for (const location of this.locations) {
output +=
'\n\n' +
(0, _printLocation.printSourceLocation)(this.source, location);
}
}
return output;
}
toJSON() {
const formattedError = {
message: this.message,
};
if (this.locations != null) {
formattedError.locations = this.locations;
}
if (this.path != null) {
formattedError.path = this.path;
}
if (this.extensions != null && Object.keys(this.extensions).length > 0) {
formattedError.extensions = this.extensions;
}
return formattedError;
}
} |
JavaScript | class GuildCategoryChannel extends GuildChannel_1.GuildChannel {
/**
* Returns all {@link GuildChannel}s under this category channel
* @type {Collection<Snowflake, GuildChannel>}
*/
get children() {
return this.guild.channels.cache.filter(c => { var _a; return ((_a = c.parent) === null || _a === void 0 ? void 0 : _a.id) === this.id; });
}
} |
JavaScript | class ProductAdd extends Component {
constructor(props){
super(props);
this.productName = React.createRef();
this.description = React.createRef();
this.parent = React.createRef();
this.status = React.createRef();
this.state = {
addProduct: {},
Categories: [],
Users: [],
categoryValue: '',
Users: [],
validation:{
productName:{
rules: {
notEmpty: {
message: 'Product name field can\'t be left blank',
valid: false
}
},
valid: null,
message: ''
}
}
};
this.categoryhandleContentChange = this.categoryhandleContentChange.bind(this)
}
categoryhandleContentChange(value) {
this.setState({categoryValue:value })
}
cancelHandler(){
this.props.history.push("/products");
}
submitHandler(e){
e.preventDefault();
let formSubmitFlag = true;
for (let field in this.state.validation) {
let lastValidFieldFlag = true;
let addProduct = this.state.validation;
addProduct[field].valid = null;
for(let fieldCheck in this.state.validation[field].rules){
switch(fieldCheck){
case 'notEmpty':
if(lastValidFieldFlag === true && this[field].value.length === 0){
lastValidFieldFlag = false;
formSubmitFlag = false;
addProduct[field].valid = false;
addProduct[field].message = addProduct[field].addProduct[fieldCheck].message;
}
break;
}
}
this.setState({ validation: addProduct});
}
if(formSubmitFlag){
let addProduct = this.state.addProduct;
addProduct.productName = this.productName.value;
addProduct.description = this.description.value;
//addProduct.productCategory = this.category.value;
addProduct.size = this.size.value;
addProduct.color = this.color.value;
addProduct.brand = this.brand.value;
addProduct.productAge = this.productAge.value;
addProduct.userId = '5b236b4ad73fe224efedae86';
addProduct.productCategory = '5b3ca9c23d43f138959e3224';
//console.log('<<<MMMMMMMMMMMMMMm>',addProduct);
axios.post('/product/create', addProduct).then(result => {
if(result.data.code == '200'){
this.props.history.push("/products");
}
});
}
}
//~ categoryhandleContentChange(value) {
//~ alert('asdf');
//~ console.log('<<<<<<<<<<<<<<<<<<<<<<<content value',value);
//~ this.setState({ categoryValue: value });
//~ }
componentDidMount() {
//if(localStorage.getItem('jwtToken') != null)
//axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');
axios.get('/category/categories').then(result => {
if(result.data.code == '200'){
this.setState({
categories: result.data.result,
});
}
console.log(this.state.categories);
})
axios.get('/user/users/1' ).then(result => {
console.log('<<<<<<<<<<<<<<<<<<<<usersssss>',result);
if(result.data.code ===200){
this.setState({
users: result.data.result,
});
}
console.log(this.state.users);
})
.catch((error) => {
if(error.status === 401) {
this.props.history.push("/login");
}
});
}
render() {
let categories,users;
if(this.state.categories){
let categoryList = this.state.categories;
categories = categoryList.map(category => <Category key={category._id} category={category}/>);
}
if(this.state.users){
let userList = this.state.users;
users = userList.map(user => <User key={user._id} user={user}/>);
}
return (
<div className="animated fadeIn">
<Row>
<Col xs="12" sm="12">
<Card>
<CardHeader>
<strong>Add Product</strong>
<Button onClick={()=>this.cancelHandler()} color="primary" className="btn btn-success btn-sm pull-right">Back</Button>
</CardHeader>
<CardBody>
<Form noValidate>
<Row>
<Col xs="4" sm="12">
<FormGroup>
<Label htmlFor="company">Name</Label>
<Input type="text" invalid={this.state.validation.productName.valid === false} innerRef={input => (this.productName = input)} placeholder="Product Name" />
<FormFeedback invalid={this.state.validation.productName.valid === false}>{this.state.validation.productName.message}</FormFeedback>
</FormGroup>
</Col>
</Row>
<FormGroup>
<Label htmlFor="description">Description</Label>
<Input type="text" innerRef={input => (this.description = input)} placeholder="Description" />
</FormGroup>
<FormGroup>
<Label htmlFor="category">Category</Label>
<select innerRef={input => (this.category = input)} id="select" class="form-control" onChange={this.categoryhandleContentChange}>
{categories}
</select>
</FormGroup>
<FormGroup>
<Label htmlFor="user">User</Label>
<select innerRef={input => (this.user = input)} id="select" class="form-control" >
{users}
</select>
</FormGroup>
<FormGroup>
<Label htmlFor="size">Size</Label>
<Input type="text" innerRef={input => (this.size = input)} placeholder="Size" />
</FormGroup>
<FormGroup>
<Label htmlFor="color">Color</Label>
<Input type="text" innerRef={input => (this.color = input)} placeholder="Color" />
</FormGroup>
<FormGroup>
<Label htmlFor="brand">Brand</Label>
<Input type="text" innerRef={input => (this.brand = input)} placeholder="Brand" />
</FormGroup>
<FormGroup>
<Label htmlFor="age">Age</Label>
<Input type="text" innerRef={input => (this.productAge = input)} placeholder="Age" />
</FormGroup>
<Row>
<Col xs="6" className="text-right">
<Button onClick={(e)=>this.submitHandler(e)} color="success" className="px-4">Submit</Button>
</Col>
<Col xs="6">
<Button onClick={()=>this.cancelHandler()} color="primary" className="px-4">Cancel</Button>
</Col>
</Row>
</Form>
</CardBody>
</Card>
</Col>
</Row>
</div>
);
}
} |
JavaScript | class SnapshotPlugin {
/**
* constructor of the SnapshotPlugin class.
* @param {String} options The object of build folder.
*/
constructor(options) {
this.options = options;
}
/**
* Find all javacript file paths in the directory.
* @param {Object} assets the object of javacript file path.
* @param {String} buildPath The path of build folder.
* @return {Array} Image path array.
*/
getDir(assets, buildPath) {
const pathArray = [];
Object.keys(assets).map((item) => {
if (/.js$/.test(item)) {
pathArray.push(_path.join(buildPath, item));
}
});
return pathArray;
};
/**
* Convert javacript file asynchronously. If an error occurs, print an error message.
* @param {Object} compiler API specification, all configuration information of Webpack environment.
*/
apply(compiler) {
const buildPath = this.options.build;
compiler.hooks.done.tap('snapshot coverter', (stats) => {
const pathArray = this.getDir(stats.compilation.assets, buildPath);
pathArray.forEach((element) => {
const bcPath = element.replace('.js', '.bc');
const fileName = _path.basename(element);
exec(`"${snapshot}" generate -o "${bcPath}" "${element}"`, (error) => {
if (error) {
console.error('\u001b[31m', `Failed to convert the ${fileName} file to a snapshot.`, '\u001b[39m');
}
});
});
});
}
} |
JavaScript | class EventStore extends Store {
constructor(ipfs, id, dbname, options = {}) {
if(options.Index === undefined) Object.assign(options, { Index: EventIndex })
super(ipfs, id, dbname, options)
}
add(data) {
return this._addOperation({
op: 'ADD',
key: null,
value: data
})
}
get(hash) {
return this.iterator({ gte: hash, limit: 1 }).collect()[0]
}
iterator(options) {
const messages = this._query(options)
let currentIndex = 0
let iterator = {
[Symbol.iterator]() {
return this
},
next() {
let item = { value: null, done: true }
if(currentIndex < messages.length) {
item = { value: messages[currentIndex], done: false }
currentIndex ++
}
return item
},
collect: () => messages
}
return iterator
}
_query(opts) {
if(!opts) opts = {}
const amount = opts.limit ? (opts.limit > -1 ? opts.limit : this._index.get().length) : 1 // Return 1 if no limit is provided
const events = this._index.get().slice()
let result = []
if(opts.gt || opts.gte) {
// Greater than case
result = this._read(events, opts.gt ? opts.gt : opts.gte, amount, opts.gte ? true : false)
} else {
// Lower than and lastN case, search latest first by reversing the sequence
result = this._read(events.reverse(), opts.lt ? opts.lt : opts.lte, amount, opts.lte || !opts.lt).reverse()
}
return result
}
_read(ops, hash, amount, inclusive) {
// Find the index of the gt/lt hash, or start from the beginning of the array if not found
const index = ops.map((e) => e.hash).indexOf(hash)
let startIndex = Math.max(index, 0)
// If gte/lte is set, we include the given hash, if not, start from the next element
startIndex += inclusive ? 0 : 1
// Slice the array to its requested size
const res = ops.slice(startIndex).slice(0, amount)
return res
}
} |
JavaScript | class Log {
constructor (id, entries, heads, clock) {
this._id = id || randomId()
this._clock = clock || new Clock(this.id)
this._entries = entries || new EntrySet()
this._heads = heads || this.entries.heads
}
/**
* Returns the ID of the log
* @returns {string}
*/
get id () {
return this._id
}
/**
* Returns the clock of the log
* @returns {string}
*/
get clock () {
return this._clock
}
/**
* Returns the items in the log
* @returns {Array<Entry>}
*/
get items () {
return this.entries.values
}
/**
* Returns the values in the log
* @returns {Array<Entry>}
*/
get values () {
return this.entries.values
}
/**
* Returns the items in the log as an EntrySet
* @returns {EntrySet}
*/
get entries () {
return this._entries
}
/**
* Returns an array of heads as multihashes
* @returns {Array<string>}
*/
get heads () {
return this._heads
}
/**
* Returns an array of Entry objects that reference entries which
* are not in the log currently
* @returns {Array<Entry>}
*/
get tails () {
return this.entries.tails
}
/**
* Returns an array of multihashes that are referenced by entries which
* are not in the log currently
* @returns {Array<string>} Array of multihashes
*/
get tailHashes () {
return this.entries.tailHashes
}
/**
* Returns the lenght of the log
* @return {Number} Length
*/
get length () {
return this.entries.length
}
/**
* Find an entry
* @param {string} [hash] The Multihash of the entry as Base58 encoded string
* @returns {Entry|undefined}
*/
get (hash) {
return this.entries.get(hash)
}
/**
* Append an entry to the log
* @param {Entry} entry Entry to add
* @return {Log} New Log containing the appended value
*/
append (entry) {
const entrySet = this.entries.append(entry)
return new Log(this.id, entrySet, [entry], this.clock)
}
/**
* Get the log in JSON format
* @returns {Object<{heads}>}
*/
toJSON () {
return { id: this.id, heads: this.heads.map(e => e.hash) }
}
/**
* Get the log as a Buffer
* @returns {Buffer}
*/
toBuffer () {
return new Buffer(JSON.stringify(this.toJSON()))
}
/**
* Returns the log entries as a formatted string
* @example
* two
* └─one
* └─three
* @returns {string}
*/
toString () {
return this.items
.slice()
.reverse()
.map((e, idx) => {
const parents = EntrySet.findChildren(this.entries.values, e)
const len = parents.length
let padding = new Array(Math.max(len - 1, 0))
padding = len > 1 ? padding.fill(' ') : padding
padding = len > 0 ? padding.concat(['└─']) : padding
return padding.join('') + e.payload
})
.join('\n')
}
} |
JavaScript | class DirectoryPost extends Post {
constructor(name, hash, size) {
super("directory");
this.name = name;
this.hash = hash;
this.size = size;
}
} |
JavaScript | class FilePost extends Post {
constructor(name, hash, size, meta) {
super("file");
this.name = name;
this.hash = hash;
this.size = size || - 1;
this.meta = meta || {};
}
} |
JavaScript | class Poll extends Post {
constructor(question, options) {
super("poll");
this.question = question;
this.options = options;
}
} |
JavaScript | class TextPost extends Post {
constructor(content, replyto) {
super("text");
this.content = content;
this.replyto = replyto;
}
// encrypt(privkey, pubkey) {
// this.content = Encryption.encrypt(this.content, privkey, pubkey);
// }
} |
JavaScript | class Index {
/*
@param id - unique identifier of this index, eg. a user id or a hash
*/
constructor(id) {
this.id = id
this._index = []
}
/*
Returns the state of the datastore, ie. most up-to-date data
@return - current state
*/
get() {
return this._index
}
/*
Applies operations to the Index and updates the state
@param oplog - the source operations log that called updateIndex
@param entries - operations that were added to the log
*/
updateIndex(oplog, entries) {
this._index = oplog.ops
}
} |
JavaScript | class ScopeModel {
/**
* @for ScopeModel
* @constructor
*/
constructor() {
/**
* Local reference to the event bus
*
* @for ScopeModel
* @property _eventBus
* @type {EventBus}
* @private
*/
this._eventBus = EventBus;
/**
* Length of PTL lines (aka "vector lines") for all aircraft
*
* @for ScopeModel
* @property _ptlLength
* @type {number} length in minutes
* @default 0
* @private
*/
this._ptlLength = 0;
// TODO: Use this!
/**
* Collection of all sectors being controlled by this scope
*
* Currently set to null and not used. Is a placeholder for the
* forthcoming class `SectorCollection`.
*
* @for ScopeModel
* @property _sectorCollection
* @type {null}
* @private
*/
this._sectorCollection = null;
/**
* Current theme
*
* @for ScopeModel
* @property _theme
* @type {object}
* @private
*/
this._theme = THEME.DEFAULT;
/**
* Collection of all radar targets observed by this scope
*
* @for ScopeModel
* @property radarTargetCollection
* @type {RadarTargetCollection}
*/
this.radarTargetCollection = new RadarTargetCollection(this._theme);
this.init()
.enable();
}
get ptlLength() {
return this._ptlLength;
}
// ------------------------------ LIFECYCLE ------------------------------
/**
* Complete initialization tasks
*
* @for ScopeModel
* @method init
* @chainable
*/
init() {
return this;
}
/**
* Enable handlers
*
* @for ScopeModel
* @method enable
*/
enable() {
this._eventBus.on(EVENT.SET_THEME, this._setTheme);
}
/**
* Disable handlers
*
* @for ScopeModel
* @method disable
*/
disable() {
this._eventBus.off(EVENT.SET_THEME, this._setTheme);
}
// ------------------------------ PUBLIC ------------------------------
/**
* Accept a pending handoff from another sector
*
* NOTE: This is just a placeholder for future use, hence why the params are commented out
*
* @for ScopeModel
* @method acceptHandoff
* @param radarTargetModel {RadarTargetModel}
* @return result {array} [success of operation, system's response]
*/
acceptHandoff(/* radarTargetModel */) {
return [false, 'acceptHandoff command not yet available'];
}
/**
* Amend the cruise altitude OR interim altitude for a given `RadarTargetModel`
*
* @for ScopeModel
* @method amendAltitude
* @param radarTargetModel {RadarTargetModel}
* @param altitude {string}
* @return result {array} [success of operation, system's response]
*/
amendAltitude(radarTargetModel, altitude) {
altitude = parseInt(altitude, DECIMAL_RADIX);
return radarTargetModel.amendAltitude(altitude);
}
/**
* Increase or decrease the PTL length by one step
*
* @for ScopeModel
* @method changePtlLength
* @param {number} direction - either -1 or 1 to indicate increment direction
*/
changePtlLength(direction) {
const validValues = GameController.getGameOption(GAME_OPTION_NAMES.PROJECTED_TRACK_LINE_LENGTHS)
.split('-')
.map((val) => parseFloat(val));
const currentIndex = validValues.indexOf(this._ptlLength);
const nextIndex = currentIndex + Math.sign(direction);
if (nextIndex >= validValues.length) {
return;
}
if (nextIndex < 0) {
this._ptlLength = 0;
this._eventBus.trigger(EVENT.MARK_SHALLOW_RENDER);
return;
}
this._ptlLength = validValues[nextIndex];
this._eventBus.trigger(EVENT.MARK_SHALLOW_RENDER);
}
/**
* Decrease the length of the PTL lines for all aircraft
*
* @for ScopeModel
* @method decreasePtlLength
*/
decreasePtlLength() {
const direction = -1;
this.changePtlLength(direction);
}
/**
* Increase the length of the PTL lines for all aircraft
*
* @for ScopeModel
* @method increasePtlLength
*/
increasePtlLength() {
const direction = 1;
this.changePtlLength(direction);
}
/**
* Initiate a handoff to another sector
*
* NOTE: This is just a placeholder for future use, hence why the params are commented out
*
* @for ScopeModel
* @method initiateHandoff
* @param radarTargetModel {RadarTargetModel}
* @param sectorCode {string} the handoff code for the receiving sector
* @return result {array} [success of operation, system's response]
*/
initiateHandoff(/* radarTargetModel, sectorCode */) {
return [false, 'initiateHandoff command not yet available'];
}
/**
* Change direction and/or length of data block leader line
*
* @for ScopeModel
* @method moveDataBlock
* @param radarTargetModel {RadarTargetModel}
* @param commandArguments {string}
* @return result {array} [success of operation, system's response]
*/
moveDataBlock(radarTargetModel, commandArguments) {
return radarTargetModel.moveDataBlock(commandArguments);
}
/**
* Toggle visibility of the data block of a given `RadarTargetModel`, on this
* sector's scope, or the scope of another sector
*
* NOTE: This is just a placeholder for future use, hence why the params are commented out
*
* @for ScopeModel
* @method propogateDataBlock
* @param radarTargetModel {RadarTargetModel}
* @param sectorCode {string} handoff code for the receiving sector
* @return result {array} [success of operation, system's response]
*/
propogateDataBlock(/* radarTargetModel, sectorCode */) {
return [false, 'propogateDataBlock command not yet available'];
}
/**
* Amend the route stored in the scope for a given `RadarTargetModel`
*
* NOTE: This is just a placeholder for future use, hence why the params are commented out
*
* @for ScopeModel
* @method route
* @param radarTargetModel {RadarTargetModel}
* @param routeString {string}
* @return result {array} [success of operation, system's response]
*/
route(/* radarTargetModel, routeString */) {
return [false, 'route command not yet available'];
}
/**
* Execute a scope command from a `ScopeCommandModel`
* @method runScopeCommand
* @param scopeCommandModel {ScopeCommandModel}
* @return result {array} [success of operation, system's response]
*/
runScopeCommand(scopeCommandModel) {
const functionName = scopeCommandModel.commandFunction;
const functionArguments = scopeCommandModel.commandArguments;
const radarTargetModel = this.radarTargetCollection.findRadarTargetModelForAircraftReference(
scopeCommandModel.aircraftReference
);
if (!(functionName in this)) {
return [false, 'ERR: BAD SYNTAX'];
}
if (_isNil(radarTargetModel)) {
return [false, 'ERR: UNKNOWN AIRCRAFT'];
}
// call the appropriate function, and explode the array of arguments
// this allows any number of arguments to be accepted by the receiving method
return this[functionName](radarTargetModel, ...functionArguments);
}
/**
* Amend the scratchpad for a given `RadarTargetModel`
*
* @for ScopeModel
* @method setScratchpad
* @param radarTargetModel {RadarTargetModel}
* @param scratchPadText {string}
* @return result {array} [success of operation, system's response]
*/
setScratchpad(radarTargetModel, scratchPadText) {
if (scratchPadText.length > 3) {
return [false, 'ERR: SCRATCHPAD MAX 3 CHAR'];
}
return radarTargetModel.setScratchpad(scratchPadText.toUpperCase());
}
/**
* Toggle halo for a given `RadarTargetModel`
*
* @for ScopeModel
* @method setHalo
* @param radarTargetModel {RadarTargetModel}
* @return result {array} [success of operation, system's response]
*/
setHalo(radarTargetModel, radius) {
const haloDefaultRadius = this._theme.SCOPE.HALO_DEFAULT_RADIUS_NM;
const haloMaxRadius = this._theme.SCOPE.HALO_MAX_RADIUS_NM;
if (radius <= 0) {
return [false, 'ERR: HALO SIZE INVALID'];
}
if (radius > haloMaxRadius) {
return [false, `ERR: HALO MAX ${haloMaxRadius} NM`];
}
if (!radius) {
radius = haloDefaultRadius;
}
return radarTargetModel.setHalo(radius);
}
// ------------------------------ PRIVATE ------------------------------
/**
* Change theme to the specified name
*
* This should ONLY be called through the EventBus during a `SET_THEME` event,
* thus ensuring that the same theme is always in use by all app components.
*
* This method must remain an arrow function in order to preserve the scope
* of `this`, since it is being invoked by an EventBus callback.
*
* @for ScopeModel
* @method _setTheme
* @param themeName {string}
*/
_setTheme = (themeName) => {
if (!_has(THEME, themeName)) {
console.error(`Expected valid theme to change to, but received '${themeName}'`);
return;
}
this._theme = THEME[themeName];
}
} |
JavaScript | class EnvironmentUtil {
/**
* An environment creation function which uses the API
* to increase testing speed
*
* @param feedFileName - The filename of the feed fixture we are loading
* @param calendarFileName - The filename of the calendar fixture we are loading
* @param routeFileName - The filename of the route fixture we are loading
* @param tripFileName - The filename of the trip fixture we are loading
* @param stopFileNames - The filenames of the stop fixtures we are loading
*/
static createEnvironmentWithApi(feedFileName, calendarFileName, routeFileName, tripFileName, ...stopFileNames) {
const stopsArray = [...stopFileNames];
FeedsUtil.createFeedWithApi(feedFileName);
cy.log(feedFileName + ' feed created.');
stopsArray.forEach((stopName) => {
StopsUtil.createStopsWithApi(stopName);
cy.log(stopName + ' stop created.');
})
CalendarsUtil.createCalendarWithApi(calendarFileName);
cy.log(calendarFileName + ' calendar created.')
RoutesUtil.createRouteWithApi(routeFileName);
cy.log(routeFileName + ' route created.');
PatternsUtil.createPatternWithApi();
cy.log('Pattern created.');
TripsUtil.createTripWithApi(tripFileName);
cy.log(tripFileName + ' trip created.')
}
} |
JavaScript | class Player {
constructor(playerPositionX, playerPositionY, playerCharacter) {
this.playerPositionX = playerPositionX;
this.playerPositionY = playerPositionY;
this.playerCharacter = playerCharacter;
}
update() {
}
reset () {
this.playerPositionX = 200;
this.playerPositionY = 405;
}
render () {
ctx.drawImage(Resources.get(this.playerCharacter), this.playerPositionX, this.playerPositionY);
}
changeCharacter(playerCharacter) {
this.playerCharacter = playerCharacter;
}
// Hardcoded Pixel Positions for Perfect Collisions
handleInput (key) {
if(key == 'left')
{
if(this.playerPositionX == 0)
this.playerPositionX = this.playerPositionX;
else
this.playerPositionX = this.playerPositionX - 100;
}
else if(key == 'right')
{
if(this.playerPositionX == 400)
this.playerPositionX = this.playerPositionX;
else
this.playerPositionX = this.playerPositionX + 100;
}
else if(key == 'up')
{
if(this.playerPositionY <= 73)
{
scoreUp();
}
else
this.playerPositionY = this.playerPositionY - 83;
}
else
{
if(this.playerPositionY == 405)
this.playerPositionY = this.playerPositionY;
else
this.playerPositionY = this.playerPositionY + 83;
}
}
} |
JavaScript | class ChunkNamesPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('ChunkNamesPlugin', compilation => {
compilation.chunkTemplate.hooks.renderManifest.intercept({
register(tapInfo) {
if (tapInfo.name === 'JavascriptModulesPlugin') {
const originalFn = tapInfo.fn;
tapInfo.fn = (result, options) => {
const chunkName = options.chunk.name;
// Don't mutation options passed to other plugins
let customOpts = { ...options };
if (chunkName === 'main' || chunkName === 'vendors~main') {
customOpts.outputOptions = {
...options.outputOptions,
chunkFilename: 'js/[name].chunk.js',
};
const hasCss =
result[0] &&
result[0].identifier.startsWith('mini-css-extract-plugin');
if (hasCss) {
result[0].filenameTemplate = 'css/[name].chunk.css';
}
}
originalFn(result, customOpts);
};
}
return tapInfo;
},
});
});
}
} |
JavaScript | class Visual {
/**
* Creates a new visual. If the visual is created with a dataFrame object, the visual is 'data-bound'. Otherwise the visual is 'non-data-bound' or static. Data-bound visuals automatically update whenver the underlying data changes.
* Visuals are configured using an options object.
* @param {string} type - The type of visual from the visual library.
* @param {DataFrame} dataFrame - The DataFrame instance that is bound to the visual.
* @param {Visual~OptionsBase} options - Configuration for the visual. This is visual-type specific, but there are standard configuration options that all visuals have.
* @param {DataFrame~filterFunction} filterFunction - The function to filter the data. The filter will be applied to this visual only.
*/
constructor(type, dataFrame, options, filterFunction) {
this.dataFrame = dataFrame;
this.type = type;
this.options = options;
this.filterFunction = filterFunction;
this.panelId = null; // set by assign
this.id = `Viz${++Visual.nextId}`;
this.state = {}; // State of the visual. Preserves state between re-renders.
walk(this);
Visual.visuals.push(this);
}
/**
* Attaches the visual to a panel in the output.
* @param {String} panelId - The id of the panel to attach the visual to.
*/
attach(panelId) {
this.panelId = panelId;
// Set data binding if data bound viz
if (this.dataFrame) {
const watcher1 = new Watcher(
() => this.dataFrame._data,
(val) => this.render()
);
const watcher2 = new Watcher(
() => this.dataFrame._slicers,
(val) => this.render()
);
} else {
this.render();
}
}
/**
* Returns the data after all appropriate filters / contexts have been applied. All visuals
* should get data from this function only.
* @returns {Array} Data is returned in native Javascript Array format, which is more suited to libraries like D3.
*/
slicedData() {
if (!this.dataFrame) {
return undefined;
} else {
// Get the dataFrame bound data (which includes slicers)
let data = this.dataFrame.slicedData();
// Apply visual filter if set
if (this.filterFunction) {
data = data.filter(this.filterFunction);
}
return data.data;
}
}
/**
* Sets the internal state of the visual.
* @param {} key
* @param {*} value
*/
setState(key, value) {
this.state = { ...this.state, [key]: value };
}
/**
* Returns an orphaned Html Node element which can be manually placed into the DOM.
* @returns {Node}
*/
node() {
let renderFunction = Visual.library[this.type];
// merge with default base options (let visual do visual-specific stuff)
this.options = Object.mergeDeep(
{},
VisualLibraryBase.defaultOptions,
this.options
);
// for binding option, we ensure all properties are arrays.
for (let key in this.options.binding) {
if (typeof this.options.binding[key] === "string") {
this.options.binding[key] = [this.options.binding[key]];
} else if (Array.isArray(this.options.binding[key])) {
// good to go.
} else {
throw `Binding for ${key} must be an Array of columns.`;
}
}
// Call render function, passing the current visual.
let content;
let elVisual;
try {
content = renderFunction(this);
elVisual = VisualLibraryBase.doBaseStyles(content, this.options, this.id);
} catch (error) {
elVisual = VisualLibraryBase.doErrorVisual(error, this.options, this.id);
}
return elVisual;
}
/**
* Redraws the current visual and all other visuals in the same panel. Re-rendering
* typically occurs when data is sliced via interactive visuals.
*/
render() {
// clear the panel + redraw all visuals in the panel.
let id = this.panelId;
UI.clear(id);
Visual.visuals.forEach((c) => {
if (c.panelId === id) {
let elVisual = c.node();
UI.content(elVisual, id);
}
});
}
/**
* Creates a static html-rendered visual. This visual is not bound to any data. Use html
* visuals for static content like text and abstract shapes which does not change
*/
static html(html) {
let visual = new Visual("html", null, { html });
return visual;
}
static create(type, dataFrame, options, filterFunction) {
return new Visual(type, dataFrame, options, filterFunction);
}
} |
JavaScript | class Content extends Component {
render() {
return (
<div className="content">
<div className="row">
<div className="col-sm-4 offset-4">
<a
className="link-github"
href="https://github.com/adamzerella"
target="_blank"
rel="noopener noreferrer"
title="Go to Adam Zerella's Github"
>
<img
className="img-thumbnail"
alt="github icon"
src={GitHubIcon}
/>
</a>
</div>
</div>
<div className="row">
<div className="col-sm-4 offset-4">
<a
className="link-linkedin"
href="https://www.linkedin.com/in/adam-zerella-8803ab128/"
target="_blank"
rel="noopener noreferrer"
title="Go to Adam Zerella's linkedin"
>
<img
className="img-thumbnail"
alt="linkedin icon"
src={LinkedInIcon}
/>
</a>
</div>
</div>
<div className="row">
<div className="col-sm-4 offset-4">
<a
className="link-email"
href="mailto:[email protected]"
target="_top"
title="Email Adam Zerella"
>
<img
className="img-thumbnail"
alt="email icon"
src={MailIcon}
/>
</a>
</div>
</div>
<div className="row">
<div className="col-sm-4 offset-4">
<a
className="link-twitter"
href="https://twitter.com/adamzerella"
target="_top"
title="Go to Adam Zerella's Twitter"
>
<img
className="img-thumbnail"
alt="twitter icon"
src={TwitterIcon}
/>
</a>
</div>
</div>
</div>
);
}
} |
JavaScript | class FileContext {
/**
*
* @param {*} headers
* @param {String} content
*/
constructor(headers, content) {
this.headers = headers;
this.content = content;
}
/**
* Creates a file context from a XHR object
* @param {XMLHttpRequest} xhr
* @returns {FileContext}
*/
static fromXHR(xhr) {
let headers = {};
// iterate through every header line
xhr
.getAllResponseHeaders()
.split("\r\n")
.forEach(headerLine => {
let index = headerLine.indexOf(":");
// if ':' character does not exist,
// no need to go further on this iteration
if (index === -1) {
return;
}
let key = headerLine
.slice(0, index)
.toLowerCase()
.trim();
let value = headerLine.slice(index + 1).trim();
headers[key] = value;
});
return new FileContext(headers, xhr.responseText);
}
} |
JavaScript | class TwilioCommandHelp extends CommandHelp.default {
// Override parent functionality
flags(flags) {
if (flags.length === 0) return '';
const optionalFlags = flags.filter((f) => !f.required);
const optionalBody = this.generateFlagsOutput(optionalFlags);
const requiredFlags = flags.filter((f) => f.required);
const requiredBody = this.generateFlagsOutput(requiredFlags);
const returnList = [chalk.bold('OPTIONS')];
if (requiredFlags.length > 0) {
returnList.push(chalk.bold('REQUIRED FLAGS'));
returnList.push(indent(requiredBody, 2));
}
returnList.push(chalk.bold('OPTIONAL FLAGS'));
returnList.push(indent(optionalBody, 2));
return returnList.join('\n');
}
// To add the API help document url
docs() {
const listOfDetails = [];
const helpDoc = this.command.docLink || getDocLink(this.command.id);
if (!helpDoc) {
return '';
}
const hyperLink = urlUtil.convertToHyperlink('MORE INFO', helpDoc);
// if the terminal doesn't support hyperlink, mention complete url under More Info
if (hyperLink.isSupported) {
listOfDetails.push(chalk.bold(hyperLink.url));
} else {
listOfDetails.push(chalk.bold('MORE INFO'));
listOfDetails.push(indent(helpDoc, 2));
}
return listOfDetails.join('\n');
}
// overriding to include docs()
generate() {
const cmd = this.command;
const flags = util.sortBy(
Object.entries(cmd.flags || {})
.filter(([, v]) => !v.hidden)
.map(([k, v]) => {
v.name = k;
return v;
}),
(f) => [!f.char, f.char, f.name],
);
const args = (cmd.args || []).filter((a) => !a.hidden);
let output = util
.compact([
this.usage(flags),
this.args(args),
this.flags(flags),
this.description(),
this.aliases(cmd.aliases),
this.examples(cmd.examples || cmd.example),
this.docs(),
])
.join('\n\n');
if (this.opts.stripAnsi) output = stripAnsi(output);
return output;
}
/**
* Forked and refactored from oclif default implementation.
* Link: https://github.com/oclif/plugin-help/blob/master/src/command.ts#L125-L154
*/
generateFlagsOutput(flags) {
return list.renderList(
flags.map((flag) => {
let left = flag.helpLabel;
if (!left) {
const label = [];
if (flag.char) label.push(`-${flag.char[0]}`);
if (flag.name) {
if (flag.type === 'boolean' && flag.allowNo) {
label.push(`--[no-]${flag.name.trim()}`);
} else {
label.push(`--${flag.name.trim()}`);
}
}
left = label.join(', ');
}
if (flag.type === 'option') {
let value = flag.helpValue || flag.name;
if (!flag.helpValue && flag.options) {
value = flag.options.join('|');
}
if (!value.includes('|')) value = chalk.underline(value);
left += `=${value}`;
}
let right = flag.description || '';
if (flag.type === 'option' && flag.default) {
right = `[default: ${flag.default}] ${right}`;
}
return [left, chalk.dim(right.trim())];
}),
{ stripAnsi: this.opts.stripAnsi, maxWidth: this.opts.maxWidth - 2 },
);
}
} |
JavaScript | class AzureEventSourceProperties extends models['EventSourceCommonProperties'] {
/**
* Create a AzureEventSourceProperties.
* @member {string} eventSourceResourceId The resource id of the event source
* in Azure Resource Manager.
*/
constructor() {
super();
}
/**
* Defines the metadata of AzureEventSourceProperties
*
* @returns {object} metadata of AzureEventSourceProperties
*
*/
mapper() {
return {
required: false,
serializedName: 'AzureEventSourceProperties',
type: {
name: 'Composite',
className: 'AzureEventSourceProperties',
modelProperties: {
provisioningState: {
required: false,
serializedName: 'provisioningState',
type: {
name: 'Enum',
allowedValues: [ 'Accepted', 'Creating', 'Updating', 'Succeeded', 'Failed', 'Deleting' ]
}
},
creationTime: {
required: false,
readOnly: true,
serializedName: 'creationTime',
type: {
name: 'DateTime'
}
},
timestampPropertyName: {
required: false,
serializedName: 'timestampPropertyName',
type: {
name: 'String'
}
},
eventSourceResourceId: {
required: true,
serializedName: 'eventSourceResourceId',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class ID3Stream extends stream_1.Readable {
constructor(buf) {
super();
this.buf = buf;
}
_read() {
this.push(this.buf);
this.push(null); // push the EOF-signaling `null` chunk
}
} |
JavaScript | class EmptyPlugin extends Plugin {
/**
* Create a new plugin instance.
* @param {Object} [options = {}] Configuration for the plugin
*/
constructor (options = {}) {
super()
this.name = 'EmptyPlugin'
this.actions = new Map()
this.subscriptions = new Set()
}
/**
* Start the plugin. Would be called when the plugin is registered.
* @returns {undefined}
* @throws {Error} Will throw if plugin initialization failed
*/
start () { }
/**
* Called when a new message arrives from a subscription
* @param {String} subscription Name of the subscription that published the message
* @param {String} message JSON message object sent from the subscription
* @return {undefined}
*/
handleMessage (subscription, message) {}
} |
JavaScript | class DihedralRepresentation extends MeasurementRepresentation {
constructor(structure, viewer, params) {
super(structure, viewer, params);
this.type = 'dihedral';
this.parameters = Object.assign({
atomQuad: {
type: 'hidden', rebuild: true
},
extendLine: {
type: 'boolean', rebuild: true, default: true
},
lineVisible: {
type: 'boolean', default: true
},
planeVisible: {
type: 'boolean', default: true
},
sectorVisible: {
type: 'boolean', default: true
}
}, this.parameters);
this.init(params);
}
init(params) {
const p = params || {};
p.side = defaults(p.side, 'double');
p.opacity = defaults(p.opacity, 0.5);
this.atomQuad = defaults(p.atomQuad, []);
this.extendLine = defaults(p.extendLine, true);
this.lineVisible = defaults(p.lineVisible, true);
this.planeVisible = defaults(p.planeVisible, true);
this.sectorVisible = defaults(p.sectorVisible, true);
super.init(p);
}
createData(sview) {
if (!sview.atomCount || !this.atomQuad.length)
return;
const atomPosition = parseNestedAtoms(sview, this.atomQuad);
const dihedralData = getDihedralData(atomPosition, {
extendLine: this.extendLine
});
const n = this.n = dihedralData.labelText.length;
const labelColor = new Color(this.labelColor);
this.textBuffer = new TextBuffer({
position: dihedralData.labelPosition,
size: uniformArray(n, this.labelSize),
color: uniformArray3(n, labelColor.r, labelColor.g, labelColor.b),
text: dihedralData.labelText
}, this.getLabelBufferParams());
const c = new Color(this.colorValue);
this.lineLength = dihedralData.linePosition1.length / 3;
const lineColor = uniformArray3(this.lineLength, c.r, c.g, c.b);
this.lineBuffer = new WideLineBuffer(getFixedLengthWrappedDashData({
position1: dihedralData.linePosition1,
position2: dihedralData.linePosition2,
color: lineColor,
color2: lineColor
}), this.getBufferParams({
linewidth: this.linewidth,
visible: this.lineVisible,
opacity: this.lineOpacity
}));
this.planeLength = dihedralData.planePosition.length / 3;
this.planeBuffer = new MeshBuffer({
position: dihedralData.planePosition,
color: uniformArray3(this.planeLength, c.r, c.g, c.b)
}, this.getBufferParams({
visible: this.planeVisible
}));
this.sectorLength = dihedralData.sectorPosition.length / 3;
this.sectorBuffer = new MeshBuffer({
position: dihedralData.sectorPosition,
color: uniformArray3(this.sectorLength, c.r, c.g, c.b)
}, this.getBufferParams({
visible: this.sectorVisible
}));
return {
bufferList: [
this.textBuffer,
this.lineBuffer,
this.planeBuffer,
this.sectorBuffer
]
};
}
updateData(what, data) {
super.updateData(what, data);
const lineData = {};
const planeData = {};
const sectorData = {};
if (what.color) {
const c = new Color(this.colorValue);
Object.assign(lineData, {
color: uniformArray3(this.lineLength, c.r, c.g, c.b),
color2: uniformArray3(this.lineLength, c.r, c.g, c.b)
});
Object.assign(planeData, {
color: uniformArray3(this.planeLength, c.r, c.g, c.b)
});
Object.assign(sectorData, {
color: uniformArray3(this.sectorLength, c.r, c.g, c.b)
});
}
this.lineBuffer.setAttributes(lineData);
this.planeBuffer.setAttributes(planeData);
this.sectorBuffer.setAttributes(sectorData);
}
setParameters(params) {
var rebuild = false;
var what = {};
super.setParameters(params, what, rebuild);
if (params && (params.lineVisible !== undefined ||
params.sectorVisible !== undefined ||
params.planeVisible !== undefined)) {
this.setVisibility(this.visible);
}
if (params && params.lineOpacity) {
this.lineBuffer.setParameters({ opacity: params.lineOpacity });
}
if (params && params.opacity !== undefined) {
this.lineBuffer.setParameters({ opacity: this.lineOpacity });
}
if (params && params.linewidth) {
this.lineBuffer.setParameters({ linewidth: params.linewidth });
}
return this;
}
setVisibility(value, noRenderRequest) {
super.setVisibility(value, true);
if (this.lineBuffer) {
this.lineBuffer.setVisibility(this.lineVisible && this.visible);
}
if (this.planeBuffer) {
this.planeBuffer.setVisibility(this.planeVisible && this.visible);
}
if (this.sectorBuffer) {
this.sectorBuffer.setVisibility(this.sectorVisible && this.visible);
}
if (!noRenderRequest)
this.viewer.requestRender();
return this;
}
} |
JavaScript | class AuditPageProvider extends Nuxeo.Element {
static get template() {
return html`
<style>
:host {
display: none;
}
</style>
<nuxeo-resource
id="res"
path="/id/[[docId]]/@audit"
enrichers="{{enrichers}}"
schemas="[[schemas]]"
loading="{{loading}}"
headers="{{headers}}"
>
</nuxeo-resource>
<nuxeo-operation
id="auditOp"
op="Audit.QueryWithPageProvider"
enrichers="{{enrichers}}"
schemas="[[schemas]]"
loading="{{loading}}"
headers="{{headers}}"
>
</nuxeo-operation>
`;
}
static get is() {
return 'nuxeo-audit-page-provider';
}
static get properties() {
return {
/**
* The id of a nuxeo-connection to use.
*/
connectionId: {
type: String,
value: '',
},
/**
* If true, automatically execute the operation when either `docId` or `params` change.
*/
auto: {
type: Boolean,
value: false,
},
/**
* The delay in milliseconds to debounce the auto fetch call when `docId`, `params`, etc. changes.
*/
autoDelay: {
type: Number,
value: 300,
},
/**
* The query parameters object.
*/
params: {
type: Object,
value: {},
},
/**
* The document id to retrieve the history from.
* When set, the provider DOCUMENT_HISTORY_PROVIDER is used.
*/
docId: {
type: String,
},
/**
* The number of results per page.
*/
pageSize: {
type: Number,
value: -1,
},
/**
* The current page.
*/
page: {
type: Number,
value: 1,
},
/**
* The current page entries.
*/
currentPage: {
type: Array,
value: [],
notify: true,
},
/**
* Map of properties and direction 'asc' / 'desc'
*/
sort: {
type: Object,
value: {},
notify: true,
},
/**
* Total number of pages.
*/
numberOfPages: {
type: Number,
notify: true,
},
/**
* Total number of results.
*/
resultsCount: {
type: Number,
notify: true,
},
/**
* Returns true if a next page is available.
*/
isNextPageAvailable: {
type: Boolean,
value: false,
notify: true,
},
/**
* Current page's size
*/
currentPageSize: {
type: Number,
notify: true,
},
/**
* The `content enricher` of the resource.
* Can be an object with entity type as keys or list or string (which defaults to `document` entity type).
*/
enrichers: {
type: Object,
value: {},
},
/**
* List of comma separated values of the document schemas to be returned.
* All document schemas are returned by default.
*/
schemas: {
type: String,
},
/**
* The headers of the request.
* 'Accept': 'text/plain,application/json' is already set by default.
*/
headers: {
type: Object,
value: null,
},
/**
* True while requests are in flight.
*/
loading: {
type: Boolean,
notify: true,
readOnly: true,
},
};
}
static get observers() {
return ['_resetAndAutoFetch(params.*, docId, pageSize, sort)', '_autoFetch(page)'];
}
/**
* Fired when the current page is fetched.
*
* @event update
*/
/**
* Stringifies the elements of a given object
*/
_stringifyJSONObject(input) {
const result = input;
if (input !== null) {
Object.keys(input).forEach((key) => {
if (typeof input[key] === 'string') {
result[key] = input[key];
} else {
result[key] = JSON.stringify(input[key]);
}
});
}
return result;
}
/**
* Fetch the currentPage.
* @method fetch
*/
fetch() {
return this._isForDoc ? this._fetchRes() : this._fetchOp();
}
_fetchOp() {
const params = {
providerName: 'EVENTS_VIEW',
namedQueryParams: this._stringifyJSONObject(this.params),
currentPageIndex: this.page - 1,
pageSize: this.pageSize,
};
return this._fetch(this.$.auditOp, params);
}
_fetchRes() {
const params = {};
if (this.params.startDate) {
params.startEventDate = this.params.startDate;
}
if (this.params.endDate) {
params.endEventDate = this.params.endDate;
}
params.currentPageIndex = this.page - 1;
params.pageSize = this.pageSize;
return this._fetch(this.$.res, params);
}
_fetch(exec, params) {
if (this._sortKeys.length > 0) {
params.sortBy = this._sortKeys.join(',');
params.sortOrder = this._sortValues.join(',');
}
exec.params = params;
return exec.execute().then((response) => {
this.currentPage = response.entries.slice(0);
this.numberOfPages = response.numberOfPages;
this.resultsCount = response.resultsCount;
this.isNextPageAvailable = response.isNextPageAvailable;
this.currentPageSize = response.currentPageSize;
this.dispatchEvent(
new CustomEvent('update', {
bubbles: true,
composed: true,
}),
);
return response;
});
}
get _sortKeys() {
return Object.keys(this.sort);
}
get _sortValues() {
return this._sortKeys.map((k) => this.sort[k]);
}
get _isForDoc() {
return this.docId && this.docId.length > 0;
}
_resetAndAutoFetch() {
this.page = 1;
this._autoFetch();
}
_autoFetch() {
if (this.auto) {
// debounce in case of multiple param changes
this._debouncer = Debouncer.debounce(this._debouncer, timeOut.after(this.autoDelay), () => this.fetch());
}
}
} |
JavaScript | class ResolveTaggedIteratorArgumentPass extends mix(AbstractRecursivePass, PriorityTaggedServiceTrait) {
/**
* @inheritdoc
*/
_processValue(value, isRoot = false) {
if (value instanceof TaggedIteratorArgument) {
value.values = this.findAndSortTaggedServices(value.tag, this._container);
return value;
}
return super._processValue(value, isRoot);
}
} |
JavaScript | class Helpers {
/**
* Get randomly generated device ID
* @returns {String} Device ID
*/
getDeviceId() {
let id = crypto.randomBytes(20).toString("binary");
let hmac = crypto.createHmac(
"sha1",
Buffer.from(
"76b4a156aaccade137b8b1e77b435a81971fbd3e",
"hex"
)
);
hmac.update(Buffer.from(Buffer.from("32", "hex") + id, "binary"));
return "32" + Buffer.from(id, "binary").toString("hex") + hmac.digest("hex");
}
/**
* Convert ``Buffer`` to ``Object``
* @param {Buffer} data Binary data to convert to ``Object``
* @returns {Object} Binary data converted to ``Object``
*/
toJson(data) {
return JSON.parse(data.toString());
}
/**
* Get Amino SIG for string data
* @param {String} data Data that needs signature
* @returns {String} SID for data
*/
getSignature(data) {
let hmac = crypto.createHmac(
"sha1",
Buffer.from(
"fbf98eb3a07a9042ee5593b10ce9f3286a69d4e2",
"hex"
)
);
hmac.update(data);
return Buffer.from(
Buffer.from("32", "hex") + hmac.digest("binary"),
"binary"
).toString("base64");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.