language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class FatePhase extends Phase {
constructor(game) {
super(game, Phases.Fate);
this.initialise([
new SimpleStep(game, () => this.discardCharactersWithNoFate()),
new SimpleStep(game, () => this.removeFateFromCharacters()),
new SimpleStep(game, () => this.placeFateOnUnclaimedRings()),
new ActionWindow(this.game, 'Action Window', 'fate')
]);
}
discardCharactersWithNoFate() {
for(let player of this.game.getPlayersInFirstPlayerOrder()) {
this.game.queueSimpleStep(() => this.promptPlayerToDiscard(player, player.cardsInPlay.filter(card => (
card.fate === 0 && card.allowGameAction('discardFromPlay')
))));
}
}
promptPlayerToDiscard(player, cardsToDiscard) {
if(cardsToDiscard.length === 0) {
return;
}
this.game.promptForSelect(player, {
source: 'Fate Phase',
activePromptTitle: 'Choose character to discard\n(or click Done to discard all characters with no fate)',
waitingPromptTitle: 'Waiting for opponent to discard characters with no fate',
cardCondition: card => cardsToDiscard.includes(card),
cardType: CardTypes.Character,
controller: Players.Self,
buttons: [{ text: 'Done', arg: 'cancel' }],
onSelect: (player, card) => {
this.game.applyGameAction(null, { discardFromPlay: card });
this.promptPlayerToDiscard(player, cardsToDiscard.filter(c => c !== card));
return true;
},
onCancel: () => {
for(let character of cardsToDiscard) {
this.game.applyGameAction(null, { discardFromPlay: character });
}
}
});
}
removeFateFromCharacters() {
this.game.applyGameAction(null, { removeFate: this.game.findAnyCardsInPlay(card => card.allowGameAction('removeFate')) });
}
placeFateOnUnclaimedRings() {
this.game.raiseEvent(EventNames.OnPlaceFateOnUnclaimedRings, {}, () => {
_.each(this.game.rings, ring => {
if(!ring.claimed) {
ring.modifyFate(1);
}
});
});
}
} |
JavaScript | class Player extends React.Component {
// create the random function for the reach file to access
random() {
return reach.hasRandom.random();
}
// get the move the user wants to play
async getHand(x, xs, os) { // bool(x) whether its X's turn
// Present the buttons to the user so that they can actually select their move
// hand is a box ID number relative to numeric keypad
let valid = 1; // occupied
let hand = null;
while (valid > 0) { // while occupied
hand = await new Promise((resolveHandP) => {
this.setState({
view: "GetHand",
resolveHandP,
xs, // 1d array of 1's 0's; 1 = occupied by X
os // 1d array of 1's 0's; 1 = occupied by O
});
for (let i = 1; i < 10; i++) {
if (dev) {
console.log(`${i} ${intToHand[i]} xs[i-1]=${parseInt(xs[i-1])} os[i-1]=${parseInt(os[i-1])}`);
}
if (parseInt(xs[i-1]) === 1) {
document.getElementById(intToHand[i]).src = X_image;
}
if (parseInt(os[i-1]) === 1) {
document.getElementById(intToHand[i]).src = O_image;
}
}
});
var blinger = document.getElementById("bling");
blinger.play();
valid = (
parseInt(os[handToInt[hand]])
+ parseInt(xs[handToInt[hand]])
); // should return 1=occupied / 0=vacant
if (dev) {
console.log(`${valid}`);
}
};
sleep(4000);
if (dev) {
console.log(`${os}`);
console.log(`${xs}`);
}
// Display that a move as been accepted
this.setState({
view: "GetHandb",
playable: true
});
document.getElementById(hand).src = {
x: X_image,
o: O_image,
}[x ? "x" : "o"];
if (dev) {
console.log(`${hand}`);
}
for (let i = 1; i < 10; i++) {
if (dev) {
console.log(`${i} ${intToHand[i]} xs[i-1]=${parseInt(xs[i-1])} os[i-1]=${parseInt(os[i-1])}`);
}
if (parseInt(xs[i-1]) === 1) {
document.getElementById(intToHand[i]).src = X_image;
}
if (parseInt(os[i-1]) === 1) {
document.getElementById(intToHand[i]).src = O_image;
}
}
// return the move
return handToInt[hand];
}
// function to display who won
endsWith(won, double, oppo, tie) {
this.setState({
view: "Finale",
won: won,
double: double,
tie: tie
});
}
// Inform the players that a timeout has occurred
informTimeout() {
this.setState({
view: "Timeout"
});
}
// returns hand to Reach
setImg(box_id) {
this.state.resolveHandP(box_id);
}
} |
JavaScript | class Deployer extends Player {
// Set the wager
constructor(props) {
super(props);
this.state = {
view: "SetWager"
};
}
setWager(wager) {
this.setState({
view: "Deploy",
wager
});
}
// Deploy the contract
async deploy() {
const ctc = this.props.acc.deploy(backend);
this.setState({
view: "Deploying",
ctc
});
this.wager = reach.parseCurrency(this.state.wager); // UInt
backend.A(ctc, this);
if (dev) {
console.log(await reach.getDefaultAccount());
}
const ctcInfo = await ctc.getInfo();
const ctcInfoStr = JSON.stringify(ctcInfo, null, 2);
this.setState({
view: "WaitingForAttacher",
ctcInfoStr
});
}
// render the data returned by the class
render() {
return renderView(this, DeployerViews);
}
} |
JavaScript | class Attacher extends Player {
// Display the view for attaching to the deployer
constructor(props) {
super(props);
this.state = {
view: "Attach"
};
}
// Actually attach
attach(ctcInfoStr) {
const ctc = this.props.acc.attach(backend, JSON.parse(ctcInfoStr));
this.setState({
view: "Attaching"
});
backend.B(ctc, this);
}
// accept the wager proposed by the deployer
async acceptWager(wagerAtomic) {
// Fun([UInt], Null)
const wager = reach.formatCurrency(wagerAtomic, 4);
return await new Promise((resolveAcceptedP) => {
this.setState({
view: "AcceptTerms",
wager,
resolveAcceptedP
});
});
}
// if the terms have been accepted, display that the player is waiting for his/her turn.
termsAccepted() {
this.state.resolveAcceptedP();
this.setState({
view: "WaitingForTurn"
});
}
// render that data returned by this class
render() {
return renderView(this, AttacherViews);
}
} |
JavaScript | class Board extends H5P.EventDispatcher {
/**
* @constructor
* @param {object} params Parameters from semantics.
* @param {string} params.words List of words/phrases/numbers.
* @param {number} params.size Size of the board.
* @param {boolean} params.shuffleOnRetry If true, board will be shuffled on retry.
* @param {function} params.buttonClicked Callback to check if game is won.
* @param {object} params.visuals Visuals parameters.
* @param {number} contentId ContentId.
* @param {object[]} [previousState] State of previous session.
* @param {string} [previousState[].label] Button's label.
* @param {boolean} [previousState[].flipped] True, if button was flipped, else false.
*/
constructor(params, contentId, previousState) {
super();
this.params = params;
this.previousState = previousState;
// Set words
this.words = this
.generateWords(this.previousState)
.map(words => this.addHTMLLineBreaks(words));
// Button image path
const imagePath = (params.visuals.buttonImage && params.visuals.buttonImage.path) ?
H5P.getPath(params.visuals.buttonImage.path, contentId) :
undefined;
// Initialize buttons
this.buttons = this.initButtons(this.params.size, imagePath);
this.setButtonLabels(this.words);
// Set activated state from previous session
if (previousState.length > 0) {
this.buttons.forEach((button, index) => {
button.toggleActivated(previousState[index].flipped);
});
}
this.setJoker(this.params.joker);
// Setup board
this.board = document.createElement('div');
for (let i = 0; i < this.params.size; i++) {
const row = document.createElement('div');
row.classList.add('h5p-bingo-column');
for (let j = 0; j < this.params.size; j++) {
row.appendChild(this.buttons[i * this.params.size + j].getDOM());
}
this.board.appendChild(row);
}
this.board.classList.add('h5p-bingo-board');
// Global CSS customization should still be possible
if (this.params.visuals.backgroundColor !== '') {
this.board.style.background = this.params.visuals.backgroundColor;
}
// Base font size to be used if possible
this.fontSizeBase = parseFloat(window.getComputedStyle(document.body, null)
.getPropertyValue('font-size'));
// Resize font sizes and thus board
this.on('resize', () => {
setTimeout(() => {
this.resizeButtons();
}, 0);
});
}
/**
* Generate words.
* @param {object[]} [previousState] State of previous session.
* @return {object[]} Words.
*/
generateWords(previousState = []) {
let words = [];
// Use previous if available
if (previousState.length > 0) {
words = previousState.map(button => button.label);
}
else {
// Use numbers
if (this.params.mode === 'numbers') {
for (let i = 1; i <= 3 * this.params.size * this.params.size; i++) {
words.push(i.toString());
}
}
else {
// Use words
if (!this.params.words || this.params.words.trim() === '') {
words = ['someone', 'forgot', 'to', 'set', 'some', 'words'];
}
else {
words = this.params.words.split('\n');
}
}
}
return words;
}
/**
* Add line breaks to words.
*
* Uses the words' character lengths and the longest word's character length
* as a heuristic to set a maximum width and line breaks accordingly
* @param {string} [words=''] Words.
* @params {number} [lengthMax] Maximum character length per line.
* @return {string} Sentence with <br />s.
*/
addHTMLLineBreaks(words = '', lengthMax) {
// Try to have a width/height ratio of 2:1
lengthMax = lengthMax || Math.ceil(Math.sqrt(words.length) * 2);
words = words.split(' ');
let out = [];
let current = '';
words.forEach( (word, index) => {
if (current.length + 1 + word.length > lengthMax && index > 0) {
current = `${current}<br />`;
out.push(current);
current = '';
}
current = `${current} ${word}`.trim();
});
out.push(current);
return out.join('');
}
/**
* Resize buttons.
*
* @param {object} [arguments] Optional arguments.
* @param {number} [arguments.startFontSize] Shrink factor.
* @param {number} [arguments.fontSizeMin=-Infinity] Minimum font size in px.
* @param {number} [arguments.fontSizeMax=Infinity] Maximum font size in px.
*/
resizeButtons({startFontSize = this.fontSizeBase, fontSizeMin = -Infinity, fontSizeMax = Infinity} = {}) {
if (this.preventResize === true) {
return;
}
const fontSize = Math.min(Math.max(startFontSize, fontSizeMin), fontSizeMax);
// Determine button with widest label as future reference
if (!this.widestLabelId) {
this.widestLabelId = this.buttons
.map(button => button.getLabelWidth())
// Retrieve index of maximum value
.reduce((max, cur, index, arr) => cur > arr[max] ? index : max, 0);
}
// Determine button with highest label as future reference
if (!this.highestLabelId) {
this.highestLabelId = this.buttons
.map(button => button.getLabelHeight())
// Retrieve index of maximum value
.reduce((max, cur, index, arr) => cur > arr[max] ? index : max, 0);
}
// Set values
this.board.style.fontSize = fontSize + 'px';
const buttonWidth = this.buttons[this.widestLabelId].getWidth();
// Workaround for IE11 ...
const buttonOffsetWidth = this.buttons[this.widestLabelId].getOffsetWidth();
this.buttons.forEach(button => {
button.setMinHeight(`${buttonOffsetWidth}px`);
});
// Fit labels into buttons
if (fontSize > fontSizeMin) {
const longestLabelWidth = this.buttons[this.widestLabelId].getLabelWidth();
const highestLabelHeight = this.buttons[this.highestLabelId].getLabelHeight();
if (longestLabelWidth > buttonWidth || highestLabelHeight > buttonWidth) {
this.resizeButtons({startFontSize: startFontSize * 0.9});
}
}
}
/**
* Get the DOM element for the board.
* @return {object} DOM element.
*/
getDOM() {
return this.board;
}
/**
* Create a set of buttons.
* @param {number} [size=5] Size of the bingo board.
* @param {string} [imagePath] Path to button image.
* @return {object[]} Array as board.
*/
initButtons(size = 5, imagePath) {
const buttons = [];
for (let i = 0; i < size * size; i++) {
const button = new Button(i, imagePath, {mode: this.params.mode});
button.on('click', () => this.params.buttonClicked());
buttons.push(button);
}
return buttons;
}
/**
* Randomly set button labels from a set of words.
* If there number of words is smaller than the number of buttons,
* the words will be used repeatedly.
* @param {object[]} words Words to set button labels to.
*/
setButtonLabels(words) {
let filler = [];
this.buttons.forEach((button, index) => {
let label;
// Keep previous state with order or random new one
if (this.previousState.length > 0) {
label = this.previousState[index].label;
}
else {
if (filler.length === 0) {
filler = words.slice();
}
label = filler.splice(Math.floor(Math.random() * filler.length), 1)[0];
}
button.setLabel(label);
});
}
/**
* Make center button a joker.
* @param {boolean} enabled If true, joker should be set.
*/
setJoker(enabled) {
if (enabled !== true || this.params.size % 2 === 0) {
return;
}
// Make center button a joker
const button = this.buttons[Math.floor(this.params.size / 2) * this.params.size +
Math.floor(this.params.size / 2)];
button.toggleFlipped(true);
button.toggleBingo(true);
button.toggleActivated(true);
button.toggleBlocked(true);
button.setLabel('');
}
/**
* Get matches to a button pattern.
* @param {object[]} patterns Arrays containing the fields.
* @return {object[]} All patterns matching the win condition.
*/
getMatches(patterns) {
const matches = [];
patterns.forEach(pattern => {
if (pattern.every(field => this.buttons[field].isActivated())) {
matches.push(pattern);
}
});
return matches;
}
/**
* Get labels from all buttons that are activated.
* @return {object[]} Label strings.
*/
getActivatedButtonsLabels() {
return this.buttons
.filter(button => button.isActivated() && button.getLabel() !== '')
.map(button => button.getLabel());
}
/**
* Get IDs from all buttons that are activated.
* @return {object[]} IDs.
*/
getActivatedButtonsIDs() {
return this.buttons
.filter(button => button.isActivated())
.map(button => button.id);
}
/**
* Get possible choices for this board.
* @return {object} XApi choices object.
*/
getXAPIChoices() {
return this.buttons.map((button, index) => ({
'id': index,
'description': {
'en-US': button.getLabel()
}
}));
}
/**
* Block all buttons.
*/
blockButtons() {
this.buttons.forEach(button => {
button.toggleBlocked(true);
});
}
/**
* Unblock all buttons.
*/
unblockButtons() {
this.buttons.forEach(button => {
button.toggleBlocked(false);
});
}
/**
* Reset the board.
*/
reset() {
this.buttons.forEach(button => {
button.reset();
});
if (this.params.shuffleOnRetry) {
this.previousState = [];
this.words = this.generateWords().map(words => this.addHTMLLineBreaks(words));
this.setButtonLabels(this.words);
}
this.setJoker(this.params.joker);
delete this.widestLabelId;
delete this.highestLabelId;
this.trigger('resize');
}
/**
* Animate patterns.
* @param {object[]} patterns Sets of buttons' IDs to be animated.
* @param {number} [delay=100] Optional delay between each animation.
*/
animatePatterns(patterns, delay = 100) {
/**
* Animate a pattern.
* @param {object[]} pattern IDs of buttons to be animated.
* @param {number} [delay=100] Optional delay between each animation.
*/
const animatePattern = (pattern, delay = 100) => {
// Stop resizing when animation plays
this.preventResize = true;
if (pattern.length > 0) {
this.buttons[pattern[0]].animate();
setTimeout(() => {
animatePattern(pattern.slice(1));
}, delay);
}
else {
setTimeout(() => {
this.preventResize = false;
});
}
};
patterns.forEach(pattern => {
animatePattern(pattern, delay);
});
}
/**
* Answer call to return the current state.
*
* @return {object[]} Current state.
*/
getCurrentState() {
return this.buttons.map(button => ({
label: button.getLabel(),
flipped: button.isActivated()
}));
}
} |
JavaScript | class PullRequestLinks {
/**
* Constructs a new <code>PullRequestLinks</code>.
* @alias module:model/PullRequestLinks
*/
constructor() {
PullRequestLinks.initialize(this);
}
/**
* 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) {
}
/**
* Constructs a <code>PullRequestLinks</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/PullRequestLinks} obj Optional instance to populate.
* @return {module:model/PullRequestLinks} The populated <code>PullRequestLinks</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PullRequestLinks();
if (data.hasOwnProperty('comments')) {
obj['comments'] = PullRequestLinksComments.constructFromObject(data['comments']);
}
if (data.hasOwnProperty('html')) {
obj['html'] = PullRequestLinksComments.constructFromObject(data['html']);
}
if (data.hasOwnProperty('review_comments')) {
obj['review_comments'] = PullRequestLinksComments.constructFromObject(data['review_comments']);
}
if (data.hasOwnProperty('self')) {
obj['self'] = PullRequestLinksComments.constructFromObject(data['self']);
}
}
return obj;
}
} |
JavaScript | class byrobot_controller_4 extends byrobot_base
{
/*
생성자
*/
constructor()
{
super();
this.log('BYROBOT_E-DRONE_CCONTROLLER - constructor()');
this.targetDevice = 0x20;
this.targetDeviceID = '0F0901';
this.arrayRequestData = null;
}
} |
JavaScript | class UploadController {
/**
* @constructs
*/
constructor() {}
/**
* Responses back uploaded file url if no error.
*
* @param {Object} req - HTTP request.
* @param {Object} res - HTTP response.
* @param {nextCallback} next - A callback to run.
* @returns An HTTP response.
* @static
*/
static profileUpload(req, res, next) {
let url = '/uploads/users/' + req.payload._id + '/' + req.file.fieldname + '/' + req.file.filename;
return res.status(200).send({ url: url });
}
} |
JavaScript | class Panel
{
/**
* @constructor
* @param {THREE.Vector3} pos
* @param {number} size
* @param {THREE.Color} color
* @param {THREE.Scene} scene
*/
constructor(pos, size, color, scene) {
this.material = new THREE.SpriteMaterial({color: color});
this.mesh = new THREE.Sprite(
this.material
);
this.size = size;
this.mesh.position.copy(pos);
this.mesh.scale.set(this.size, this.size, 1);
scene.add(this.mesh);
}
/**
*
* @param {Particle} particle
*/
applyParticle(particle) {
let panelPos = new THREE.Vector2(this.mesh.position.x, this.mesh.position.y);
if(particle.isInRange(panelPos)) {
let d = Math.round(panelPos.distanceTo(particle.pos) * SIGNIFICANT_DIGITS) / SIGNIFICANT_DIGITS;
let intensity = Math.round(particle.intensity * SIGNIFICANT_DIGITS) / SIGNIFICANT_DIGITS;
let i = Math.max(Math.min(intensity / (d * (d / 2)), 1.0), 0.001);
i = i <= 0.01 ? i * 0.4 : i;
let scale = (1.0 - i) * this.mesh.scale.x;
scale = Math.round(scale * SIGNIFICANT_DIGITS) / SIGNIFICANT_DIGITS;
this.mesh.scale.set(scale, scale, 1);
}
}
/**
*
* @param {Lights} lights
*/
applyLights(lights) {
this.applyParticle(lights.core);
for(let particle of lights.particles) {
this.applyParticle(particle);
}
}
/**
* Function clearing previous frame scale.
*/
clearScaling() {
this.mesh.scale.set(this.size, this.size, 1);
}
} |
JavaScript | class Darkness
{
static get Z_POSITION() {
return -100;
}
static get DEAD_SPACE() {
return 20;
}
static get LIGHTS_FALL_SPEED() {
return 1.3;
}
/**
* @constructor
* @param {number} widthDivNum
* @param {number} clearance
* @param {THREE.Scene} scene
* @param {ThreeJS} three
*/
constructor(widthDivNum, clearance, scene, three) {
console.assert(0 < widthDivNum);
let densePanelSize = ThreeJS.VIEWPORT_HALFSIZE * 2 / widthDivNum;
this.panelSize = densePanelSize - clearance / 2;
let panelPosRel = densePanelSize / 2;
//Panels.
const MAGNIFICATION = Math.max(1, window.innerHeight / 1920);
let panelPosX = -ThreeJS.VIEWPORT_HALFSIZE;
let panelPosY = -ThreeJS.VIEWPORT_HALFSIZE * MAGNIFICATION;
this.panels = [];
let viewRange = Math.max(three.camera.right, three.camera.bottom) + this.panelSize;
let ua = navigator.userAgent;
let isMobile = (ua.indexOf('Mobile') > 0 ||
ua.indexOf('iPhone') > 0 ||
ua.indexOf('iPod') > 0 ||
ua.indexOf('iPad') > 0 ||
ua.indexOf('Android') > 0 ||
ua.indexOf('Windows Phone') > 0);
for(let y = 0; y < widthDivNum * MAGNIFICATION; y++) {
let panelsRow = [];
panelPosY += panelPosRel;
for(let x = 0; x < widthDivNum; x++) {
panelPosX += panelPosRel;
if(isMobile &&
(panelPosX < -viewRange ||
viewRange < panelPosX ||
panelPosY < -viewRange ||
viewRange < panelPosY)) {
continue;
}
panelsRow.push(
new Panel(
new THREE.Vector3(panelPosX, panelPosY, Darkness.Z_POSITION),
this.panelSize, 0x0f0f0f, scene)
);
panelPosX += panelPosRel;
}
this.panels.push(panelsRow);
panelPosY += panelPosRel;
panelPosX = -ThreeJS.VIEWPORT_HALFSIZE;
}
//Lights.
this.lights = [];
this.timer = 0;
this.prevLightXPos = NaN;
}
/**
* @param {number} aspect
* @param {three} three
*/
createLight(aspect, three) {
let lightXPos = 0;
let viewRangeX = three.camera.right + this.panelSize;
let viewRangeY = three.camera.bottom + this.panelSize;
let corrected = Math.min(viewRangeX * 1.3, ThreeJS.VIEWPORT_HALFSIZE);
do {
lightXPos = Math.random() * (corrected * 2) - corrected;
} while(this.prevLightXPos - Darkness.DEAD_SPACE <= lightXPos &&
lightXPos <= this.prevLightXPos + Darkness.DEAD_SPACE)
this.prevLightXPos = lightXPos;
let light = new Lights(lightXPos, -viewRangeY - Lights.CORE_INTENSITY - 300);
this.lights.push(light);
}
/**
* @param {number} aspect
*/
updateLights(aspect) {
for(let light of this.lights) {
light.core.vel.y = Darkness.LIGHTS_FALL_SPEED;
light.update();
}
this.lights = this.lights.filter(function(light) {
return light.core.pos.y <= ThreeJS.VIEWPORT_HALFSIZE * aspect + Lights.CORE_INTENSITY + 300;
});
}
/**
*
* @param {Mouse} mouse
* @param {number} aspect
* @param {ThreeJS} three
*/
update(mouse, aspect, three) {
//Apply Lights.
for(let yPanel of this.panels) {
for(let xPanel of yPanel) {
let viewRangeX = three.camera.right + this.panelSize;
let viewRangeY = three.camera.bottom + this.panelSize;
if(xPanel.mesh.position.x < -viewRangeX ||
viewRangeX < xPanel.mesh.position.x ||
xPanel.mesh.position.y < -viewRangeY ||
viewRangeY < xPanel.mesh.position.y) {
continue;
}
xPanel.clearScaling();
for(let light of this.lights) {
xPanel.applyLights(light);
}
}
}
//Update Lights.
this.updateLights(aspect);
//Create Lights.
let span = 600;
if(this.timer % span === 0) {
this.createLight(aspect, three);
}
this.timer++;
}
} |
JavaScript | class Mouse
{
/**
* @constructor
* @param {ThreeJS} three
*/
constructor(three) {
this.pos = new THREE.Vector2(0, 0);
let onMouseMove = (e) => {
this.pos.x = (e.clientX / three.targetElem.clientWidth * 2 - 1) * ThreeJS.VIEWPORT_HALFSIZE;
this.pos.y = (e.clientY / three.targetElem.clientHeight * 2 - 1) * (ThreeJS.VIEWPORT_HALFSIZE * three.aspect);
}
three.targetElem.addEventListener('mousemove', onMouseMove);
}
} |
JavaScript | class Particle
{
/**
* Constant representing the range by intensity * RANGE_RATE.
*/
static get RANGE_RATE() {
return 30;
}
/**
*
* @param {number} x
* @param {number} y
* @param {number} intensity
*/
constructor(x, y, intensity) {
this.pos = new THREE.Vector2(x, y);
this.intensity = intensity;
this.vel = new THREE.Vector2(0, 0);
this.acc = new THREE.Vector2(0, 0);
this.initialPos = new THREE.Vector2(0, 0);
this.initialVel = new THREE.Vector2(0, 0);
this.initialIntentisy = 0;
this.lifespan = 100;
this.livingTime = 0;
}
/**
* Function setting initial values.
*/
setInitial() {
this.initialPos = this.pos.clone();
this.initialVel = this.vel.clone();
this.initialIntentisy = this.intensity;
}
/**
* Function moving self-position in velocity.
*/
moveInVelocity() {
this.pos.add(this.vel);
}
/**
* Function moving self-position in acceleration.
*/
moveInAcceleration() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.set(0, 0);
}
decay() {
this.intensity -= this.initialIntentisy / this.lifespan;
this.livingTime++;
}
isBright() {
return this.livingTime <= this.lifespan;
}
isInRange(pos) {
let undefined;
if(pos === undefined) {
return false;
}
let ratio = 1;
if(this.intensity < Lights.CORE_INTENSITY) {
ratio = 5;
}
let range = this.intensity * ratio;
return pos.distanceToSquared(this.pos) < range * range;
}
} |
JavaScript | class Lights
{
static get CORE_INTENSITY() {
return 400;
}
static get PARTICLE_INTENSITY() {
return 50;
}
static get PARTICLE_MOMENTUM() {
return 2;
}
static get MAX_SPEED() {
return 20;
}
static get INJECITON_ANGLE_RANGE() {
return Math.PI / 6;
}
/**
* @constructor
* @param {number} x
* @param {number} y
*/
constructor(x, y) {
this.core = new Particle(x, y, Lights.CORE_INTENSITY);
this.particles = [];
this.timer = 0;
this.particleDir = new THREE.Vector2(0, -1);
}
/**
*
*/
createParticle() {
let particle = new Particle(this.core.pos.x, this.core.pos.y, Lights.PARTICLE_INTENSITY);
let injectionAngle = Math.random() * (Lights.INJECITON_ANGLE_RANGE * 2) - Lights.INJECITON_ANGLE_RANGE;
let injectionDir = this.particleDir.rotateAround(new THREE.Vector2(0, 0), injectionAngle);
particle.vel = injectionDir.setLength(Lights.PARTICLE_MOMENTUM);
particle.setInitial();
this.particles.push(particle);
}
/**
*
* @param {THREE.Vector2} [target = null]
*/
update(target = null) {
this.timer++;
let prevPos = this.core.pos.clone();
if(target !== null) {
this.core.vel.subVectors(target, this.core.pos);
}
this.particles = this.particles.filter(function(particle) {
return particle.isBright();
});
this.core.moveInAcceleration();
for(let i = 0, length = this.particles.length; i < length; i++) {
this.particles[i].moveInAcceleration();
this.particles[i].decay();
}
//Set particle direction vector.
if(!prevPos.equals(this.core.pos)) {
prevPos.sub(this.core.pos);
prevPos.normalize();
this.particleDir = prevPos;
}
//Create particle.
const GRANULARITY = 1000;
let alpha = Math.min(this.core.vel.length() / Lights.MAX_SPEED, 1.0);
let span = Math.floor(GRANULARITY / (GRANULARITY * alpha));
if(this.timer % span === 0) {
this.createParticle();
}
}
} |
JavaScript | class Checkbox extends PureComponent {
static propTypes = {
name: PropTypes.string,
label: PropTypes.string,
className: PropTypes.string,
containerClassName: PropTypes.string,
containerStyle: PropTypes.object,
cellClassName: PropTypes.string,
labelClassName: PropTypes.string,
defaultChecked: PropTypes.bool,
checked: PropTypes.bool,
indeterminate: PropTypes.bool,
disabled: PropTypes.bool,
onChange: PropTypes.func,
children: PropTypes.node
};
componentDidMount() {
if (this.input != null) {
this.input.indeterminate = this.props.indeterminate;
}
}
componentDidUpdate(prevProps) {
const {indeterminate} = this.props;
if (this.input != null && indeterminate !== prevProps.indeterminate) {
this.input.indeterminate = this.props.indeterminate;
}
}
inputRef = el => {
if (el != null) {
el.indeterminate = this.props.indeterminate;
}
this.input = el;
};
render() {
const {
children,
label,
className,
containerClassName,
containerStyle,
cellClassName,
labelClassName,
indeterminate,
...restProps
} = this.props;
const classes = classNames(styles.input, className);
const containerClasses = classNames(styles.checkbox, containerClassName);
const cellClasses = classNames(styles.cell, cellClassName);
const labelClasses = classNames(styles.label, labelClassName);
return (
<label
className={containerClasses}
style={containerStyle}
data-test="ring-checkbox"
>
<input
{...restProps}
data-checked={restProps.checked}
ref={this.inputRef}
type="checkbox"
className={classes}
/>
<span className={cellClasses}>
<Icon
glyph={checkmarkIcon}
className={styles.check}
/>
<Icon
glyph={minusIcon}
className={styles.minus}
/>
</span>
<span className={labelClasses}>{label || children}</span>
</label>
);
}
} |
JavaScript | class BlpImage {
constructor() {
this.content = 0;
this.alphaBits = 0;
this.width = 0;
this.height = 0;
this.type = 0;
this.hasMipmaps = false;
this.mipmapOffsets = new Uint32Array(16);
this.mipmapSizes = new Uint32Array(16);
this.uint8array = null;
/**
* Used for JPG images.
*/
this.jpgHeader = null;
/**
* Used for indexed images.
*/
this.pallete = null;
}
load(buffer) {
let bytes = typecast_1.bytesOf(buffer);
// This includes the JPG header size, in case its a JPG image.
// Otherwise, the last element is ignored.
let header = new Int32Array(bytes.buffer, 0, 40);
if (header[0] !== exports.BLP1_MAGIC) {
throw new Error('WrongMagicNumber');
}
this.content = header[1];
this.alphaBits = header[2];
this.width = header[3];
this.height = header[4];
this.type = header[5];
this.hasMipmaps = header[6] !== 0;
for (let i = 0; i < 16; i++) {
this.mipmapOffsets[i] = header[7 + i];
this.mipmapSizes[i] = header[23 + i];
}
this.uint8array = bytes;
if (this.content === CONTENT_JPG) {
this.jpgHeader = bytes.subarray(160, 160 + header[39]);
}
else {
this.pallete = bytes.subarray(156, 156 + 1024);
}
}
getMipmap(level) {
let uint8array = this.uint8array;
let offset = this.mipmapOffsets[level];
let size = this.mipmapSizes[level];
let imageData;
if (this.content === CONTENT_JPG) {
let jpgHeader = this.jpgHeader;
let data = new Uint8Array(jpgHeader.length + size);
let jpegImage = new jpg_1.JpegImage();
data.set(jpgHeader);
data.set(uint8array.subarray(offset, offset + size), jpgHeader.length);
jpegImage.parse(data);
// The JPG data might not actually match the correct mipmap size.
imageData = new ImageData(jpegImage.width, jpegImage.height);
jpegImage.getData(imageData);
}
else {
let pallete = this.pallete;
let width = Math.max(this.width / (1 << level), 1); // max of 1 because for non-square textures one dimension will eventually be <1.
let height = Math.max(this.height / (1 << level), 1);
let size = width * height;
let alphaBits = this.alphaBits;
let bitStream;
let bitsToByte = 0;
imageData = new ImageData(width, height);
if (alphaBits > 0) {
bitStream = new bitstream_1.default(uint8array.buffer, offset + size, Math.ceil((size * alphaBits) / 8));
bitsToByte = convertbitrange_1.default(alphaBits, 8);
}
let data = imageData.data;
for (let i = 0; i < size; i++) {
let dataIndex = i * 4;
let paletteIndex = uint8array[offset + i] * 4;
// BGRA->RGBA
data[dataIndex] = pallete[paletteIndex + 2];
data[dataIndex + 1] = pallete[paletteIndex + 1];
data[dataIndex + 2] = pallete[paletteIndex];
if (alphaBits > 0) {
data[dataIndex + 3] = bitStream.readBits(alphaBits) * bitsToByte;
}
else {
data[dataIndex + 3] = 255;
}
}
}
return imageData;
}
mipmaps() {
if (this.hasMipmaps) {
return Math.ceil(Math.log2(Math.max(this.width, this.height))) + 1;
}
return 1;
}
} |
JavaScript | class BaseEntity {
/**
*
* @param body {Body} Body representing physical position and properties. If Body's position is Vector(0, 0), it
* is assumed that Entity wants to be spawned at random point and slowly enter the screen.
* @param atlasName {String} name of atlas loaded into AssetsManager
*/
constructor(body, atlasName) {
this.body = body
if (this.body.pos.x === 0 && this.body.pos.y === 0) {
this.body.pos.y = -this.body.height
this.body.pos.x = Chance.randomRange(0, Shared.gameWidth - this.body.width)
}
this.components = new ComponentManager(this)
this.onDestroyed = new Signal()
this.atlas = AssetsManager.textures[atlasName]
this.cellIndex = this.atlas.cellIndex
this._opacity = 1
this.animationManager = null
if (this.atlas.type === TextureAtlas.SPRITE_SHEET)
this.animationManager = this.components.add(new AnimationManager(this))
this.state = ENTITY_STATE.ACTIVE
}
/**
* Effect to be played when this Entity is destroyed.
* <br>If you want your Entity to die without destruction effect, return null here.
*
* @example Play "explosion_orange" effect for 500ms
* get destructionEffect() {
* return new ExplosionEffect(this, "explosion_orange", 500, 2)
* }
*
* @returns {null|BaseEffect}
*/
get destructionEffect() {
return null
}
/**
* The name of the sound that should be played when this Entity is destroyed.
*
* @return {null|string}
*/
get destructionSoundName() {
return null
}
/**
* The opacity of this object.
*
* @return {number} opacity of this object ranging from 0 to 1 (inclusive).
*/
get opacity() {
return this._opacity
}
/**
* Set the opacity of this object.
*
* @param v {Number} desired opacity value. Should range from 0 to 1 (inclusive).
*/
set opacity(v) {
let opacityValue = v
if (opacityValue > 1 - Number.EPSILON)
opacityValue = 1
else if (opacityValue < Number.EPSILON)
opacityValue = 0
this._opacity = opacityValue
}
/**Updates entity's inner state.
* You should not override this method. */
update() {
this.components.preUpdate()
this.components.update()
this.components.postUpdate()
}
/**
* Draws Entity's atlas by default.
* <p>If you want custom drawing, override this method.
*
* @param ctx canvas context passed by render()
*/
draw(ctx) {
let cell = this.atlas.cells[this.cellIndex]
ctx.drawImage(this.atlas.image, cell.x, cell.y, cell.w, cell.h, this.body.pos.x, this.body.pos.y,
this.body.width, this.body.height)
}
/**
* <p>Renders entity on canvas. This method handles opacity, rotationSpeed and other properties.
* <p>You **should not** override this method.
* Override draw() instead.
*
* @param ctx {CanvasRenderingContext2D} canvas context passed by Game.render()
*/
render(ctx) {
ctx.save()
ctx.globalAlpha = this.opacity
if (this.body.rotation !== 0) {
ctx.translate(this.body.centerX, this.body.centerY)
ctx.rotate(this.body.rotation)
ctx.translate(-this.body.centerX, -this.body.centerY)
}
this.components.preRender(ctx)
this.draw(ctx)
this.components.postRender(ctx)
ctx.restore()
}
/**
* Changes entity's state to "destroyed". Game will render destruction animation if present
* and then remove object from game.
*
* <p>You should not override this method.
*/
destroy() {
this.state = ENTITY_STATE.DESTROYED
this.onDestroyed.dispatch()
}
} |
JavaScript | class GlamorousComponent extends Component {
// state = {theme: null}
// setTheme = theme => this.setState({theme})
componentWillMount() {
// const {theme} = this.props
// if (this.context[CHANNEL]) {
// // if a theme is provided via props, it takes precedence over context
// this.setTheme(theme ? theme : this.context[CHANNEL].getState())
// } else {
// this.setTheme(theme || {})
// }
this.cachedStyles = {}
}
componentWillReceiveProps(nextProps) {
// if (this.props.theme !== nextProps.theme) {
// this.setTheme(nextProps.theme)
// }
}
componentDidMount() {
// if (this.context[CHANNEL] && !this.props.theme) {
// // subscribe to future theme changes
// this.unsubscribe = this.context[CHANNEL].subscribe(this.setTheme)
// }
}
componentWillUnmount() {
// // cleanup subscription
// this.unsubscribe && this.unsubscribe()
}
/**
* This is a function which will cache the styles
* differently depending on if in DEV mode or not.
* Caching styles on instance won't work for hot-reloading.
* Memoizing the static styles solves this.
* @param {Object} staticStyles
*/
_cacheStaticStyles(staticStyles) {
if (module.hot) {
const index = JSON.stringify(staticStyles)
if (index in this.cachedStyles) {
this.cachedStylesNumber = this.cachedStyles[index]
} else {
this.cachedStylesNumber = StyleSheet.create({
key: staticStyles,
}).key
this.cachedStyles[index] = this.cachedStylesNumber
}
} else {
this.cachedStylesNumber = this.cachedStylesNumber ||
StyleSheet.create({key: staticStyles}).key
}
}
/**
* This is a function which will split the
* style rules (functions) from the styles passed to
* the glamorous component factory as args
* @param {...Object|Function} styles
* @return {Object}
*/
_splitArgs(args){
return args.reduce((split, arg) => {
if (typeof arg === 'function') {
if(arg.length === 1) {
split['staticGlamorRules'] = arg(this.props)
} else {
split['dynamicGlamorRules'] = arg(this.props)
}
} else if (typeof arg === 'object') {
split['glamorStyles'] = arg
}
return split
}, {})
}
/**
* This is a function which will split the props
* that were passed to the component in JSX
* @param {...Object} props
* @return {Object}
*/
_splitProps({style, ...rest}) {
const hasItem = (list, name) => list.indexOf(name) !== -1
const isRNStyle = name => hasItem(RNStyles, name)
const returnValue = {toForward: {}, styleProps: {}, style}
return Object.keys(rest).reduce(
(split, propName) => {
if (isRNStyle(propName)) {
split.styleProps[propName] = rest[propName]
} else {
split.toForward[propName] = rest[propName]
}
return split
},
returnValue,
)
}
render() {
const {...rest} = this.props
const {
staticGlamorRules,
dynamicGlamorRules,
glamorStyles,
} = this._splitArgs(styles)
const {
toForward,
styleProps,
style,
} = this._splitProps(rest)
const staticStyles = {
...glamorStyles,
...styleProps,
...staticGlamorRules,
}
this._cacheStaticStyles(staticStyles)
const mergedStyles = Array.isArray(style) ?
[this.cachedStylesNumber, ...style] :
[this.cachedStylesNumber, style]
return <Comp style={[mergedStyles, dynamicGlamorRules]} {...toForward} />
}
} |
JavaScript | class AutocompleteInput extends Component {
constructor(props) {
super(props);
this.state = {
menuDisabled: true
};
this.handleOnBlur = this.handleOnBlur.bind(this);
this.handleNewRequest = this.handleNewRequest.bind(this);
this.handleUpdateInput = this.handleUpdateInput.bind(this);
this.getSuggestion = this.getSuggestion.bind(this);
this.setSearchText = this.setSearchText.bind(this);
}
componentWillMount() {
this.setSearchText(this.props);
}
handleOnBlur() {
this.setSearchText(this.props);
}
handleNewRequest(chosenRequest, index) {
if (index !== -1) {
const { choices, input, optionValue } = this.props;
const selectedSource = choices[index];
input.onChange(selectedSource[optionValue]);
this.setState({ text: this.getSuggestion(selectedSource) });
}
};
handleUpdateInput(searchText) {
this.setState({ text: searchText, menuDisabled: true });
if (searchText.length >= 3) {
this.setState({ menuDisabled: false });
const { setFilter } = this.props;
setFilter && setFilter(searchText);
}
};
getSuggestion(choice) {
const { optionText } = this.props;
const choiceName =
typeof optionText === 'function'
? optionText(choice)
: get(choice, optionText);
return choiceName;
}
setSearchText(props) {
const { choices, input, optionValue } = props;
const selectedSource = choices.find(
choice => get(choice, optionValue) === input.value
);
const searchText = selectedSource ? this.getSuggestion(selectedSource) : '';
this.setState({ text: searchText });
}
render() {
const {
choices,
elStyle,
filter,
isRequired,
label,
meta,
options,
optionValue,
resource,
source,
} = this.props;
if (typeof meta === 'undefined') {
throw new Error(
"The AutocompleteInput component wasn't called within a redux-form <Field>. Did you decorate it and forget to add the addField prop to your component? See https://marmelab.com/admin-on-rest/Inputs.html#writing-your-own-input-component for details."
);
}
const { touched, error } = meta;
let dataSource = choices.map((choice, index) => {
return index < 10 ? {
value: (<AutoComplete.Item primaryText={this.getSuggestion(choice)} value={get(choice, optionValue)} />),
text: this.getSuggestion(choice)
} : null;
});
dataSource = dataSource.filter( Boolean );
const omittedResults = choices.length - dataSource.length;
if (omittedResults > 0) {
dataSource.push({
value: (<AutoComplete.Item primaryText={`${omittedResults} more`} value="dummy value" disabled />),
text: `${omittedResults} more`
})
}
const menuProps = {
disableAutoFocus: true,
maxHeight: this.state.menuDisabled ? 0 : null
};
return (
<AutoComplete
searchText={this.state.text}
dataSource={dataSource}
floatingLabelText={
<FieldTitle
label={label}
source={source}
resource={resource}
isRequired={isRequired}
/>
}
filter={filter}
menuProps={menuProps}
onBlur={this.handleOnBlur}
onNewRequest={this.handleNewRequest}
onUpdateInput={this.handleUpdateInput}
style={elStyle}
errorText={touched && error}
{...options}
/>
);
}
} |
JavaScript | class Manager extends Employee {
// collecting constructor values from employee class
constructor(name, id, email, officeNumber) {
super(name, id, email);
this.officeNumber = officeNumber;
}
// function to get office number of manager
getOfficeNumber() {
return this.officeNumber
}
// function to get role
getRole() {
return "Manager"
}
} |
JavaScript | class ExchangeUtil {
/** Key and value of exchange type. */
static get KeyValuePairs() {
return ExchangeKV;
}
/** Get stringed value. */
static toStr = (exchange = Exchange.BUY) => {
switch (exchange) {
case Exchange.BUY:
return 'Buy';
case Exchange.SELL:
return 'Sell';
default:
return '';
}
}
} |
JavaScript | class BarClass extends React.Component {
render() {
return this.props.children;
}
} |
JavaScript | class ContentReferenceEditor extends HashBrown.Entity.View.Field.FieldBase {
/**
* Constructor
*/
constructor(params) {
super(params);
this.editorTemplate = require('template/field/editor/contentReferenceEditor');
this.configTemplate = require('template/field/config/contentReferenceEditor');
}
/**
* Fetches view data
*/
async fetch() {
if(this.state.name === 'config') {
// Build schema options
this.state.schemaOptions = {};
for(let schema of await HashBrown.Service.SchemaService.getAllSchemas('content') || []) {
this.state.schemaOptions[schema.name] = schema.id;
}
} else {
let allContent = await HashBrown.Service.ContentService.getAllContent();
this.state.contentOptions = {};
for(let content of allContent) {
if(this.model.config.allowedSchemas && this.model.config.allowedSchemas.indexOf(content.schemaId) < 0) { continue; }
this.state.contentOptions[content.prop('title', HashBrown.Context.language) || content.id] = content.id;
}
}
}
} |
JavaScript | class PluginsConfig {
/**
* @param {?=} options
*/
constructor(options) {
this.origin = '';
// console.log('PluginsConfig', options);
if (options) {
Object.assign(this, options);
}
}
} |
JavaScript | class PluginsService {
/**
* @param {?} options
*/
constructor(options) {
// console.log('PluginsService', options);
options = options || {};
// options.defaultPage = (options.defaultPage || PageNotFoundComponent) as Type<PageComponent>;
// options.notFoundPage = (options.notFoundPage || PageNotFoundComponent) as Type<PageComponent>;
this.options = new PluginsConfig(options);
}
} |
JavaScript | class PluginsModuleComponent {
constructor() {
this.version = '0.0.12';
}
/**
* @return {?}
*/
ngOnInit() {
}
} |
JavaScript | class FacebookConfig {
constructor() {
this.fields = 'id,name,first_name,last_name,email,gender,picture,cover,link';
this.scope = 'public_profile, email'; // publish_stream
this.version = 'v2.10';
}
} |
JavaScript | class GoogleTagManagerComponent extends DisposableComponent {
/**
* @param {?} platformId
* @param {?} pluginsService
* @param {?} router
* @param {?} googleTagManager
*/
constructor(platformId, pluginsService, router, googleTagManager) {
super();
this.platformId = platformId;
this.pluginsService = pluginsService;
this.router = router;
this.googleTagManager = googleTagManager;
this.useIframe = true;
this.pageView = new EventEmitter();
}
/**
* @return {?}
*/
ngAfterViewInit() {
if (isPlatformBrowser(this.platformId)) {
this.router.events.pipe(takeUntil(this.unsubscribe), filter((/**
* @param {?} e
* @return {?}
*/
e => e instanceof NavigationEnd))).subscribe((/**
* @param {?} e
* @return {?}
*/
(e) => {
/** @type {?} */
const url = `${this.pluginsService.options.origin}${e.urlAfterRedirects}`;
// console.log('GoogleTagManagerComponent.NavigationEnd', e.id, e.url, e.urlAfterRedirects, url);
if (this.dataLayer) {
this.pageView.emit({ dataLayer: this.dataLayer, url });
}
else {
this.googleTagManager.once().pipe(takeUntil(this.unsubscribe)).subscribe((/**
* @param {?} dataLayer
* @return {?}
*/
dataLayer => {
// console.log('dataLayer', dataLayer);
this.id = this.googleTagManager.options.id;
this.iframeUrl = `https://www.googletagmanager.com/ns.html?id=${this.id}`;
this.dataLayer = dataLayer;
this.pageView.emit({ dataLayer: this.dataLayer, url });
}));
}
}));
}
}
} |
JavaScript | class GoogleConfig {
constructor() {
this.cookiepolicy = 'single_host_origin';
this.scope = 'profile email';
this.fetch_basic_profile = true;
this.ux_mode = 'popup';
}
} |
JavaScript | class PayPalWidgetComponent extends DisposableComponent {
/**
* @param {?} platformId
* @param {?} paypalService
*/
constructor(platformId, paypalService) {
super();
this.platformId = platformId;
this.paypalService = paypalService;
}
/**
* @return {?}
*/
ngAfterViewInit() {
if (isPlatformBrowser(this.platformId)) {
this.paypalService.render(this.paypalOptions, '#paypal-widget-button').pipe(takeUntil(this.unsubscribe)).subscribe((/**
* @param {?} paypal
* @return {?}
*/
paypal => {
// console.log('PayPalWidgetComponent.rendered', paypal)
}));
}
}
} |
JavaScript | class SwiperDirective {
/**
* @param {?} platformId
* @param {?} zone
* @param {?} elementRef
* @param {?} differs
* @param {?} defaults
*/
constructor(platformId, zone, elementRef, differs, defaults) {
this.platformId = platformId;
this.zone = zone;
this.elementRef = elementRef;
this.differs = differs;
this.defaults = defaults;
this.index_ = null;
this.config_ = null;
this.disabled = false;
this.performance = false;
this.autoplay = new EventEmitter();
this.autoplayStart = new EventEmitter();
this.autoplayStop = new EventEmitter();
this.beforeDestroy = new EventEmitter();
this.beforeResize = new EventEmitter();
this.breakpoint = new EventEmitter();
this.click = new EventEmitter();
this.doubleTap = new EventEmitter();
this.fromEdge = new EventEmitter();
this.imagesReady = new EventEmitter();
this.indexChange = new EventEmitter();
this.init = new EventEmitter();
this.keyPress = new EventEmitter();
this.lazyImageLoad = new EventEmitter();
this.lazyImageReady = new EventEmitter();
this.progress = new EventEmitter();
this.reachBeginning = new EventEmitter();
this.reachEnd = new EventEmitter();
this.resize = new EventEmitter();
this.scroll = new EventEmitter();
this.scrollDragEnd = new EventEmitter();
this.scrollDragMove = new EventEmitter();
this.scrollDragStart = new EventEmitter();
this.setTransition = new EventEmitter();
this.setTranslate = new EventEmitter();
this.slideChange = new EventEmitter();
this.slideChangeTransitionEnd = new EventEmitter();
this.slideChangeTransitionStart = new EventEmitter();
this.slideNextTransitionEnd = new EventEmitter();
this.slideNextTransitionStart = new EventEmitter();
this.slidePrevTransitionEnd = new EventEmitter();
this.slidePrevTransitionStart = new EventEmitter();
this.sliderMove = new EventEmitter();
this.tap = new EventEmitter();
this.touchEnd = new EventEmitter();
this.touchMove = new EventEmitter();
this.touchMoveOpposite = new EventEmitter();
this.touchStart = new EventEmitter();
this.transitionEnd = new EventEmitter();
this.transitionStart = new EventEmitter();
}
/**
* @param {?} index
* @return {?}
*/
set index(index) {
if (index != null) {
this.setIndex(index);
}
}
/**
* @return {?}
*/
ngAfterViewInit() {
if (!isPlatformBrowser(this.platformId)) {
return;
}
/** @type {?} */
const params = new SwiperConfig(this.defaults);
params.assign(this.config); // Custom configuration
if (params.scrollbar === true) {
params.scrollbar = {
el: '.swiper-scrollbar'
};
}
if (params.pagination === true) {
params.pagination = {
el: '.swiper-pagination'
};
}
if (params.navigation === true) {
params.navigation = {
prevEl: '.swiper-button-prev',
nextEl: '.swiper-button-next'
};
}
if (this.disabled) {
params.allowSlidePrev = false;
params.allowSlideNext = false;
}
if (this.index_ != null) {
params.initialSlide = this.index_;
this.index_ = null;
}
params.on = {
slideChange: (/**
* @return {?}
*/
() => {
if (this.swiper_ && this.indexChange.observers.length) {
this.emit(this.indexChange, this.swiper_.realIndex);
}
})
};
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_ = new Swiper(this.elementRef.nativeElement, params);
}));
if (params.init !== false && this.init.observers.length) {
this.emit(this.init, this.swiper_);
}
// Add native Swiper event handling
SwiperEvents.forEach((/**
* @param {?} eventName
* @return {?}
*/
(eventName) => {
/** @type {?} */
let swiperEvent = eventName.replace('swiper', '');
swiperEvent = swiperEvent.charAt(0).toLowerCase() + swiperEvent.slice(1);
this.swiper_.on(swiperEvent, (/**
* @param {...?} args
* @return {?}
*/
(...args) => {
if (args.length === 1) {
args = args[0];
}
/** @type {?} */
const emitter = (/** @type {?} */ (this[(/** @type {?} */ (swiperEvent))]));
if (emitter.observers.length) {
this.emit(emitter, args);
}
}));
}));
if (!this.config_) {
this.config_ = this.differs.find(this.config || {}).create();
this.config_.diff(this.config || {});
}
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this.swiper_) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_.destroy(true, this.swiper_.initialized || false);
}));
this.swiper_ = null;
}
}
/**
* @return {?}
*/
ngDoCheck() {
if (this.config_) {
/** @type {?} */
const changes = this.config_.diff(this.config || {});
if (changes) {
this.index_ = this.getIndex(true);
this.ngOnDestroy();
this.ngAfterViewInit();
this.update();
}
}
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (this.swiper_ && changes['disabled']) {
if (changes['disabled'].currentValue !== changes['disabled'].previousValue) {
if (changes['disabled'].currentValue === true) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.ngOnDestroy();
this.ngAfterViewInit();
}));
}
else if (changes['disabled'].currentValue === false) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.ngOnDestroy();
this.ngAfterViewInit();
}));
}
}
}
}
/**
* @private
* @param {?} emitter
* @param {?} value
* @return {?}
*/
emit(emitter, value) {
if (this.performance) {
emitter.emit(value);
}
else {
this.zone.run((/**
* @return {?}
*/
() => emitter.emit(value)));
}
}
/**
* @return {?}
*/
swiper() {
return this.swiper_;
}
/**
* @return {?}
*/
initialize() {
if (this.swiper_) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_.init();
}));
}
}
/**
* @return {?}
*/
update() {
setTimeout((/**
* @return {?}
*/
() => {
if (this.swiper_) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_.update();
}));
}
}), 0);
}
/**
* @param {?=} real
* @return {?}
*/
getIndex(real) {
if (!this.swiper_) {
return this.index_ || 0;
}
else {
return real ? this.swiper_.realIndex : this.swiper_.activeIndex;
}
}
/**
* @param {?} index
* @param {?=} speed
* @param {?=} silent
* @return {?}
*/
setIndex(index, speed, silent) {
if (!this.swiper_) {
this.index_ = index;
}
else {
/** @type {?} */
let realIndex = index * this.swiper_.params.slidesPerGroup;
if (this.swiper_.params.loop) {
realIndex += this.swiper_.loopedSlides;
}
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_.slideTo(realIndex, speed, !silent);
}));
}
}
/**
* @param {?=} speed
* @param {?=} silent
* @return {?}
*/
prevSlide(speed, silent) {
if (this.swiper_) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_.slidePrev(speed, !silent);
}));
}
}
/**
* @param {?=} speed
* @param {?=} silent
* @return {?}
*/
nextSlide(speed, silent) {
if (this.swiper_) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_.slideNext(speed, !silent);
}));
}
}
/**
* @param {?=} reset
* @return {?}
*/
stopAutoplay(reset) {
if (reset) {
this.setIndex(0);
}
if (this.swiper_ && this.swiper_.autoplay) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_.autoplay.stop();
}));
}
}
/**
* @param {?=} reset
* @return {?}
*/
startAutoplay(reset) {
if (reset) {
this.setIndex(0);
}
if (this.swiper_ && this.swiper_.autoplay) {
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.swiper_.autoplay.start();
}));
}
}
} |
JavaScript | class SwiperComponent {
/**
* @param {?} zone
* @param {?} cdRef
* @param {?} platformId
* @param {?} defaults
*/
constructor(zone, cdRef, platformId, defaults) {
this.zone = zone;
this.cdRef = cdRef;
this.platformId = platformId;
this.defaults = defaults;
this.index = null;
this.disabled = false;
this.performance = false;
this.useSwiperClass = true;
this.autoplay = new EventEmitter();
this.autoplayStart = new EventEmitter();
this.autoplayStop = new EventEmitter();
this.beforeDestroy = new EventEmitter();
this.beforeResize = new EventEmitter();
this.breakpoint = new EventEmitter();
this.click = new EventEmitter();
this.doubleTap = new EventEmitter();
this.fromEdge = new EventEmitter();
this.imagesReady = new EventEmitter();
this.indexChange = new EventEmitter();
this.init = new EventEmitter();
this.keyPress = new EventEmitter();
this.lazyImageLoad = new EventEmitter();
this.lazyImageReady = new EventEmitter();
this.progress = new EventEmitter();
this.reachBeginning = new EventEmitter();
this.reachEnd = new EventEmitter();
this.resize = new EventEmitter();
this.scroll = new EventEmitter();
this.scrollDragEnd = new EventEmitter();
this.scrollDragMove = new EventEmitter();
this.scrollDragStart = new EventEmitter();
this.setTransition = new EventEmitter();
this.setTranslate = new EventEmitter();
this.slideChange = new EventEmitter();
this.slideChangeTransitionEnd = new EventEmitter();
this.slideChangeTransitionStart = new EventEmitter();
this.slideNextTransitionEnd = new EventEmitter();
this.slideNextTransitionStart = new EventEmitter();
this.slidePrevTransitionEnd = new EventEmitter();
this.slidePrevTransitionStart = new EventEmitter();
this.sliderMove = new EventEmitter();
this.tap = new EventEmitter();
this.touchEnd = new EventEmitter();
this.touchMove = new EventEmitter();
this.touchMoveOpposite = new EventEmitter();
this.touchStart = new EventEmitter();
this.transitionEnd = new EventEmitter();
this.transitionStart = new EventEmitter();
this.mo = null;
this.swiperConfig = null;
this.paginationBackup = null;
this.paginationConfig = null;
}
/**
* @return {?}
*/
get isAtLast() {
return (!this.directiveRef || !this.directiveRef.swiper()) ?
false : this.directiveRef.swiper()['isEnd'];
}
/**
* @return {?}
*/
get isAtFirst() {
return (!this.directiveRef || !this.directiveRef.swiper()) ?
false : this.directiveRef.swiper()['isBeginning'];
}
/**
* @return {?}
*/
ngAfterViewInit() {
if (!isPlatformBrowser(this.platformId)) {
return;
}
this.zone.runOutsideAngular((/**
* @return {?}
*/
() => {
this.updateClasses();
if (this.swiperSlides && typeof MutationObserver !== 'undefined') {
this.mo = new MutationObserver((/**
* @return {?}
*/
() => {
this.updateClasses();
}));
this.mo.observe(this.swiperSlides.nativeElement, { childList: true });
}
}));
window.setTimeout((/**
* @return {?}
*/
() => {
if (this.directiveRef) {
this.init.emit();
this.directiveRef.indexChange = this.indexChange;
SwiperEvents.forEach((/**
* @param {?} eventName
* @return {?}
*/
(eventName) => {
if (this.directiveRef) {
/** @type {?} */
const directiveOutput = (/** @type {?} */ (eventName));
/** @type {?} */
const componentOutput = (/** @type {?} */ (eventName));
this.directiveRef[directiveOutput] = (/** @type {?} */ (this[componentOutput]));
}
}));
}
}), 0);
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this.mo) {
this.mo.disconnect();
}
if (this.config && this.paginationBackup) {
this.config.pagination = this.paginationBackup;
}
}
/**
* @return {?}
*/
getConfig() {
this.swiperConfig = new SwiperConfig(this.defaults);
this.swiperConfig.assign(this.config); // Custom configuration
if (this.swiperConfig.pagination === true ||
(this.swiperConfig.pagination && typeof this.swiperConfig.pagination === 'object' &&
(!this.swiperConfig.pagination.type || this.swiperConfig.pagination.type === 'bullets') &&
!this.swiperConfig.pagination.renderBullet && this.swiperConfig.pagination.el === '.swiper-pagination')) {
this.config = this.config || {};
if (!this.paginationConfig) {
this.paginationBackup = this.config.pagination;
this.paginationConfig = {
el: '.swiper-pagination',
renderBullet: (/**
* @param {?} index
* @param {?} className
* @return {?}
*/
(index, className) => {
/** @type {?} */
const children = this.swiperSlides ? this.swiperSlides.nativeElement.children : [];
/** @type {?} */
let bullet = `<span class="${className} ${className}-middle" index="${index}"></span>`;
if (index === 0) {
bullet = `<span class="${className} ${className}-first" index="${index}"></span>`;
}
else if (index === (children.length - 1)) {
bullet = `<span class="${className} ${className}-last" index="${index}"></span>`;
}
return `<span class="swiper-pagination-handle" index="${index}">${bullet}</span>`;
})
};
}
if (this.swiperConfig.pagination === true) {
this.config.pagination = this.paginationConfig;
}
else {
this.config.pagination = Object.assign({}, this.config.pagination, this.paginationConfig);
}
}
return (/** @type {?} */ (this.config));
}
/**
* @private
* @return {?}
*/
updateClasses() {
if (this.swiperSlides) {
/** @type {?} */
let updateNeeded = false;
/** @type {?} */
const children = this.swiperSlides.nativeElement.children;
for (let i = 0; i < children.length; i++) {
if (!children[i].classList.contains('swiper-slide')) {
updateNeeded = true;
children[i].classList.add('swiper-slide');
}
}
if (updateNeeded && this.directiveRef) {
this.directiveRef.update();
}
}
this.cdRef.detectChanges();
}
/**
* @param {?} index
* @return {?}
*/
onPaginationClick(index) {
if (this.config && this.directiveRef && (this.config.pagination === true ||
(this.config.pagination && typeof this.config.pagination === 'object' &&
(!this.config.pagination.type || this.config.pagination.type === 'bullets') &&
(this.config.pagination.clickable && this.config.pagination.el === '.swiper-pagination')))) {
this.directiveRef.setIndex(index);
}
}
} |
JavaScript | class TrustPilotConfig {
constructor() {
this.businessunitId = '58e253ab0000ff00059fc0fe';
this.businessunitName = 'www.eurospin-viaggi.it';
}
} |
JavaScript | class TrustPilotWidgetOptions {
/**
* @param {?=} options
*/
constructor(options) {
this.locale = 'it-IT';
this.styleHeight = '350px';
this.styleWidth = '100%';
this.theme = 'light';
this.group = 'on';
this.stars = '1,2,3,4,5';
if (options) {
Object.assign(this, options);
}
}
/**
* @param {?=} options
* @return {?}
*/
static newFromConfig(options) {
return new TrustPilotWidgetOptions(options);
}
/**
* @param {?=} options
* @return {?}
*/
set(options) {
if (options) {
Object.assign(this, options);
}
return this;
}
} |
JavaScript | class HUD {
/** @param {THREE.Scene} scene
*/
constructor(scene) {
this.scene = scene;
this.HUDObjects = [];
}
/** Creates a new UI element and adds it to the HUDObjects list.
*
* @param {number} relativeLeft - The x-position of the UI
* element's center relative to the left side of the camera's
* viewport.
* @param {number} relativeTop - The y-position of the UI element's
* center relative to the top side of the camera's viewport.
* @param {string} action - The action to associate with the UI
* element.
* @param {hex or string} color - The base color to use for the UI
* element.
* @param {number} [width=0.15] - The width of the UI element. The
* value should represent the fraction of the screen width, so in
* the range (0, 1]. If not provided, and no height is provided
* either, then the default width will be 0.15. If a height is
* provided, then the width will be calculated based on the height,
* such that the resulting UI element is square.
* @param {number} [height] - The height of the UI element. The
* value should represent the fraction of the screen height, so in
* the range (0, 1]. If not provided, then the height will be
* calculated as: <code>width * aspect</code> (resulting in a
* square element).
* @param {string} textureName - (optional) The name of the texture
* to apply to the UI element's mesh. The TextureMgr is used to
* retrieve the texture associated with this name. So the texture
* should have been loaded in the TextureMgr upfront.
* @param {boolean} isTransparent - (optional) If set to `true`,
* then the `transparent` property of the element's material will
* also be set to true. Default is `true`.
*/
addUIElement(relativeLeft, relativeTop, action, color, width, height, textureName, isTransparent) {
// Clamp to the [0, 1] range.
relativeLeft = Math.min(Math.max(relativeLeft, 0.0), 1.0);
relativeTop = Math.min(Math.max(relativeTop, 0.0), 1.0);
action = action || "noop";
if ( isTransparent == null ) {
isTransparent = true;
}
const g = new THREE.PlaneBufferGeometry(1, 1, 1, 1);
const m = new THREE.MeshBasicMaterial({ color: color });
m.color.convertSRGBToLinear();
if ( textureName ) {
if ( g_texMgr ) {
const tex = g_texMgr.getTexture(textureName);
if ( tex ) {
m.map = tex;
// Note: If the textures contain
// transparent parts, then we should set
// the `transparent `property to `true`.
m.transparent = isTransparent;
} else {
console.error(`Couldn't retrieve texture with name ${textureName} from TextureMgr.`);
}
} else {
console.error("Can't load texture without TextureMgr.");
}
}
const mesh = new THREE.Mesh(g, m);
// Assign a (camera) relative location for the button.
// Location format is [<left>, <top>]. Values are percentages
// of the size, defined as a value in the range 0.0 and 1.0.
mesh.userData.relLoc = [relativeLeft, relativeTop];
// Also assign an action. This will be the action used in the
// emitted "click" event.
mesh.userData.uiAction = action;
mesh.userData.disabled = false;
mesh.userData.width = width;
mesh.userData.height = height;
mesh.userData.calculatedWH = false;
this.HUDObjects.push(mesh);
this.scene.add(mesh);
}
/** Should be called each frame to update the location of the HUD
* elements.
*
* Positioning inspired by https://stackoverflow.com/a/34866778
*
* @param {THREE.Camera} camera - The camera used to unproject()
* the UI elements relative to the camera's view.
*/
update(camera) {
// Note: A depth of -1.0 should place the object at the near
// plane of the camera.
// Note: unproject() relies on the camera's
// `projectionMatrixInverse` and `matrixWorld`.
for ( const obj of this.HUDObjects ) {
if ( !obj.userData.calculatedWH ) {
// Calculate (default) width and/or height if
// they weren't provided. We try to achieve a
// square size (which means we need to take the
// camera/screen aspect ratio into account.
if ( !obj.userData.width && ! obj.userData.height ) {
obj.userData.width = 0.15;
obj.userData.height = 0.15 * camera.aspect;
} else if ( !obj.userData.width ) {
obj.userData.width = obj.userData.height / camera.aspect;
} else if ( !obj.userData.height) {
obj.userData.height = obj.userData.width * camera.aspect;
}
// Calculate the factor with which we should
// scale the mesh of the UI element in the
// camera/world space to based on the requested
// screen space relative size.
// Note: Since the projection space goes from
// -1 to +1 and the width/height goes from
// 0 to +1, we need to double their value.
const s = new THREE.Vector3(obj.userData.width * 2, obj.userData.height * 2, -0.99);
// Note: The same as `.unproject()` but without
// `matrixWorld` step (as it's not needed).
s.applyMatrix4(camera.projectionMatrixInverse);
obj.scale.x = s.x;
obj.scale.y = s.y;
obj.userData.calculatedWH = true;
}
obj.position.set(-1 + 2 * obj.userData.relLoc[0], 1 - 2 * obj.userData.relLoc[1], -0.99).unproject(camera);
obj.quaternion.setFromRotationMatrix(camera.matrixWorld);
}
}
dispose() {
for ( const obj of this.HUDObjects ) {
obj.geometry.dispose();
obj.material.dispose();
}
// "Clear" the array.
this.HUDObjects.length = 0;
}
getObjectsForRaycasting() {
// Note: We still include UI element that were disabled. Because
// if a disabled element is clicked, we still want it to
// register as a virtual hit. To be able to prevent the AR
// hittest ray to be fired "through" the disabled UI element.
return this.HUDObjects.filter(obj => obj.visible);
}
/** Hides the UI element associated with the specified action.
* @param {string} name - The action name of the UI element to
* hide.
* @param {number} delay - (optional) Delay (in seconds) after
* which the element will be hidden. Default: 0.
*/
hideAction(name, delay) {
if ( delay == null ) {
delay = 0;
}
// TODO Should we store the UI elements in a dictionary instead
// of an array?
for ( const uiElem of this.HUDObjects ) {
if ( uiElem.userData.uiAction == name ) {
if ( uiElem.userData.hideShowDelayTimeoutId != null ) {
window.clearTimeout(uiElem.userData.hideShowDelayTimeoutId);
uiElem.userData.hideShowDelayTimeoutId = null;
}
if ( delay > 0 ) {
uiElem.userData.hideShowDelayTimeoutId = window.setTimeout((elem, hud) => {
hud.hideAction(elem.userData.uiAction, 0);
}, delay * 1000, uiElem, this);
} else {
uiElem.visible = false;
}
break;
}
}
}
/** Makes a previously hidden UI element visible again.
* @param {string} name - The action name of the UI element to
* show again.
* @param {number} delay - (optional) Delay (in seconds) after
* which the element will be shown. Default: 0.
*/
showAction(name, delay) {
if ( delay == null ) {
delay = 0;
}
for ( const uiElem of this.HUDObjects ) {
if ( uiElem.userData.uiAction == name ) {
if ( uiElem.userData.hideShowDelayTimeoutId != null ) {
window.clearTimeout(uiElem.userData.hideShowDelayTimeoutId);
uiElem.userData.hideShowDelayTimeoutId = null;
}
if ( delay > 0 ) {
uiElem.userData.hideShowDelayTimeoutId = window.setTimeout((elem, hud) => {
hud.showAction(elem.userData.uiAction, 0);
}, delay * 1000, uiElem, this);
} else {
uiElem.visible = true;
}
break;
}
}
}
/** Disables the specified action.
*
* This will reduce the element's opacity, and will also no longer
* include it in the list of objects used for ray casting against.
* @param {string} name - Then name of the action to disable.
* @param {number} delay - (optional) Delay (in seconds) after
* which the element will be disabled. Default: 0.
*/
disableAction(name, delay) {
if ( delay == null ) {
delay = 0;
}
for ( const uiElem of this.HUDObjects ) {
if ( uiElem.userData.uiAction == name ) {
if ( uiElem.userData.disEnableDelayTimeoutId != null ) {
window.clearTimeout(uiElem.userData.disEnableDelayTimeoutId);
uiElem.userData.disEnableDelayTimeoutId = null;
}
if ( delay > 0 ) {
uiElem.userData.disEnableDelayTimeoutId = window.setTimeout((elem, hud) => {
hud.disableAction(elem.userData.uiAction, 0)
}, delay * 1000, uiElem, this);
} else {
uiElem.material.opacity = 0.25;
uiElem.userData.disabled = true;
}
break;
}
}
}
/** Enables the specified action.
*
* This will restore the element's opacity to 1, and will take it
* into account again when ray casting.
* @param {string} name - Then name of the action to enable.
* @param {number} delay - (optional) Delay (in seconds) after
* which the element will be enabled. Default: 0.
*/
enableAction(name, delay) {
if ( delay == null ) {
delay = 0;
}
for ( const uiElem of this.HUDObjects ) {
if ( uiElem.userData.uiAction == name ) {
if ( uiElem.userData.disEnableDelayTimeoutId != null ) {
window.clearTimeout(uiElem.userData.disEnableDelayTimeoutId);
uiElem.userData.disEnableDelayTimeoutId = null;
}
if ( delay > 0 ) {
uiElem.userData.disEnableDelayTimeoutId = window.setTimeout((elem, hud) => {
hud.enableAction(elem.userData.uiAction, 0)
}, delay * 1000, uiElem, this);
} else {
uiElem.material.opacity = 1.0;
uiElem.userData.disabled = false;
}
break;
}
}
}
/** Associates a callback with an action.
*
* This will assign the provided function as the uiCallback
* property of this actions userData.
* @param {string} name - Then name of the action to assign the
* callback to.
* @param {function} callback - The function to assign as the
* callback. When called the function will receive on parameter:
* its action's name.
*/
setActionCallback(name, callback) {
for ( const uiElem of this.HUDObjects ) {
if ( uiElem.userData.uiAction == name ) {
uiElem.userData.uiCallback = callback;
break;
}
}
}
} |
JavaScript | class AppError extends Error {
/**
* @param {string} key
* @param {number} status
* @param {Record<string, any>} [info={}]
* @param {Error} [cause]
*/
constructor(key, status, info, cause) {
super();
this.key = key;
this.status = status;
this.info = info || {};
this.cause = cause;
Object.setPrototypeOf(this, AppError.prototype);
if (typeof status !== "number" || typeof key !== "string") {
return AppError.serverError(
{
appErrorConstructParams: {
key,
status,
},
},
this,
);
}
}
/**
* @param {*} value
* @returns {value is AppError}
*/
static instanceOf(value) {
return (
value &&
typeof value.key === "string" &&
typeof value.status === "number" &&
!!value.info
);
}
/**
* @param {Record<string, any>} [info={}]
* @param {Error} [error]
* @returns {AppError}
*/
static notFound(info = {}, error = undefined) {
return new AppError("error.server.notFound", 404, info, error);
}
/**
* @param {Record<string, any>} [info={}]
* @param {Error} [error]
* @returns {AppError}
*/
static notImplemented(info = {}, error = undefined) {
return new AppError("error.server.notImplemented", 405, info, error);
}
/**
* @param {Record<string, any>} [info={}]
* @param {Error} [error]
* @returns {AppError}
*/
static serverError(info = {}, error = undefined) {
return new AppError("error.server.internal", 500, info, error);
}
/**
* @param {string} key
* @param {Record<string, any>} [info={}]
* @param {Error} [error]
* @returns {AppError}
*/
static validationError(key, info = {}, error = undefined) {
return new AppError(key, 400, info, error);
}
/**
* Format any error skipping the stack automatically for nested errors
*
* @param {AppError | Error | undefined | null | {} | string | number | boolean | Function | unknown} [e]
* @returns {Record<string, any>}
*/
static format(e) {
if (isNil(e)) {
return {
warning: "Missing error",
};
}
const typeOf = typeof e;
if (typeOf === "symbol") {
return {
warning: "Can't serialize Symbol",
};
}
if (typeOf === "bigint") {
return {
warning: "Can't serialize BigInt",
};
}
if (typeOf === "string" || typeOf === "boolean" || typeOf === "number") {
return {
value: e,
};
}
if (typeOf === "function") {
return {
type: "function",
name: e.name,
parameterLength: e.length,
};
}
const stack = (e?.stack ?? "").split("\n").map((it) => it.trim());
// Remove first element as this is the Error name
stack.shift();
if (isNil(e)) {
return e;
} else if (AppError.instanceOf(e)) {
return {
key: e.key,
status: e.status,
info: e.info,
stack,
cause: e.cause ? AppError.format(e.cause) : undefined,
};
} else if (e.name === "AggregateError") {
return {
name: e.name,
message: e.message,
stack: stack,
cause: e.errors?.map((it) => AppError.format(it)),
};
} else if (e.name === "PostgresError") {
return {
name: e.name,
message: e.message,
postgres: {
severity: e?.severity,
code: e?.code,
position: e?.position,
routine: e?.routine,
},
stack,
};
} else if (e.isAxiosError) {
return {
name: e.name,
message: e.message,
axios: {
requestPath: e.request?.path,
requestMethod: e.request?.method,
responseStatus: e.response?.status,
responseHeaders: e.response?.headers,
responseBody: e.response?.data,
},
stack,
};
} else if (typeof e.toJSON === "function") {
const result = e.toJSON();
result.stack = stack;
return result;
}
// Any unhandled case
return {
name: e.name,
message: e.message,
stack,
cause: e.cause ? AppError.format(e.cause) : undefined,
};
}
/**
* Use AppError#format when AppError is passed to console.log / console.error.
* This works because it uses `util.inspect` under the hood.
* Util#inspect checks if the Symbol `util.inspect.custom` is available.
*/
[inspect.custom]() {
return AppError.format(this);
}
/**
* Use AppError#format when AppError is passed to JSON.stringify().
* This is used in the compas insight logger in production mode.
*/
toJSON() {
return AppError.format(this);
}
} |
JavaScript | class TextShape extends BaseStyle_1.BaseStyle {
constructor(canvas, ctx, name = "Text_" + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)) {
super(canvas, ctx, name);
this._text = "";
}
get type() { return interfaces_1.ShapeType.TEXT; }
withText(text, maxWidth) {
this._maxWidth = maxWidth;
this.text = text;
return this;
}
set text(text) {
this._text = text;
this.styleManager.begin();
this.width = this._maxWidth || this.ctx.measureText(this._text).width;
this.styleManager.end();
}
get text() {
return this._text;
}
textStyle(font, align, baseline) {
this.styleManager.textStyle(font, align, baseline);
return this;
}
traceShape(ctx) {
ctx.fillRect(0 - this.originX, 0 - this.originY, this.width, this.height);
}
customDraw() {
if (this.styleManager.hasFill) {
this.ctx.fillText(this.text, 0 - this.originX, 0 - this.originY, this._maxWidth);
}
if (this.styleManager.hasStroke) {
this.ctx.strokeText(this.text, 0 - this.originX, 0 - this.originY, this._maxWidth);
}
}
} |
JavaScript | class DataSetSelector {
constructor(parent, options) {
this.options = options;
this.trackedSelections = null;
this.onSelectionChanged = () => this.updateSelectionHash();
this.$node = d3.select('.navbar-header')
.append('div')
.classed('dataSelector', true)
.append('form')
.classed('form-inline', true)
.append('div')
.classed('form-group', true)
.classed('hidden', true); // show after loading has finished
}
/**
* Initialize the view and return a promise
* that is resolved as soon the view is completely initialized.
* @returns {Promise<DataSetSelector>}
*/
init() {
this.build();
return this.update(); // return the promise
}
/**
* Build the basic DOM elements and binds the change function
*/
build() {
this.$node.append('label')
.attr('for', 'ds')
.text(Language.DATA_SET);
// create select and update hash on property change
this.$select = this.$node.append('select')
.attr('id', 'ds')
.classed('form-control', true)
.on('change', () => {
const selectedData = this.$select.selectAll('option')
.filter((d, i) => i === this.$select.property('selectedIndex'))
.data();
AppContext.getInstance().hash.setProp(AppConstants.HASH_PROPS.DATASET, selectedData[0].key);
AppContext.getInstance().hash.removeProp(AppConstants.HASH_PROPS.TIME_POINTS);
AppContext.getInstance().hash.removeProp(AppConstants.HASH_PROPS.DETAIL_VIEW);
AppContext.getInstance().hash.removeProp(AppConstants.HASH_PROPS.SELECTION);
if (selectedData.length > 0) {
GlobalEventHandler.getInstance().fire(AppConstants.EVENT_DATA_COLLECTION_SELECTED, selectedData[0].values);
this.trackSelections(selectedData[0].values[0].item);
}
});
}
/**
* Toggle tracking of selection of rows/columns/cells for the given dataset
* @param matrix selected dataset
*/
trackSelections(matrix) {
if (this.trackedSelections) {
this.trackedSelections.off(ProductIDType.EVENT_SELECT_PRODUCT, this.onSelectionChanged);
}
this.trackedSelections = matrix.producttype;
this.trackedSelections.on(ProductIDType.EVENT_SELECT_PRODUCT, this.onSelectionChanged);
}
/**
* Update the URL hash based on the selections
*/
updateSelectionHash() {
if (!this.trackedSelections) {
return;
}
const ranges = this.trackedSelections.productSelections();
const value = ranges.map((r) => r.toString()).join(';');
AppContext.getInstance().hash.setProp(AppConstants.HASH_PROPS.SELECTION, value);
}
/**
* Restore the selections based on the URL hash
*/
restoreSelections() {
if (!this.trackedSelections) {
return;
}
const value = AppContext.getInstance().hash.getProp(AppConstants.HASH_PROPS.SELECTION, '');
if (value === '') {
return;
}
const ranges = value.split(';').map((s) => ParseRangeUtils.parseRangeLike(s));
this.trackedSelections.select(ranges);
}
/**
* Update the list of datasets and returns a promise
* @returns {Promise<DataSetSelector>}
*/
update() {
const dataprovider = new DataProvider();
return dataprovider.load()
.then((data) => {
const $options = this.$select.selectAll('option').data(data);
$options.enter().append('option');
$options
.attr('value', (d) => d.key)
.text((d) => `${d.key}`);
$options.exit().remove();
if (AppContext.getInstance().hash.has(AppConstants.HASH_PROPS.DATASET)) {
const selectedData = data.filter((d, i) => d.key === AppContext.getInstance().hash.getProp(AppConstants.HASH_PROPS.DATASET));
if (selectedData.length > 0) {
this.$select.property('selectedIndex', data.indexOf(selectedData[0]));
GlobalEventHandler.getInstance().fire(AppConstants.EVENT_DATA_COLLECTION_SELECTED, selectedData[0].values);
this.trackSelections(selectedData[0].values[0].item);
this.restoreSelections();
TimePointUtils.selectTimePointFromHash(selectedData[0].values);
}
}
else {
// invoke change function once to broadcast event
this.$select.on('change')();
}
// show form element
this.$node.classed('hidden', false);
return this;
});
}
/**
* Factory method to create a new DataSetSelector instance
* @param parent
* @param options
* @returns {DataSetSelector}
*/
static create(parent, options) {
return new DataSetSelector(parent, options);
}
} |
JavaScript | class FrontPage extends DTHelper {
/**
* Primary constructor.
*
* @since 1.0.0
*/
constructor() {
super();
if ( ! rdb.is_front_page ) {
return;
}
FrontPage._filters();
this.$win = $( window );
this.$table = $( '#all-matches' );
this.nonce = $( '#nonce' ).val();
this.table = this._dataTable();
this._yadcf();
}
/**
* Initialize YetAnotherDataTablesCustomFilter.js
*
* @since 1.0.0
* @access private
*
* @param {string} data Option group response.
*/
_yadcf() {
/**
* Season filter config.
*
* @since 1.0.0
*
* @type {Object}
*/
const season = {
column_number: 1,
column_data_type: 'text',
filter_type: 'select',
filter_container_id: 'season',
filter_default_label: 'Select Season',
filter_match_mode: 'exact',
filter_reset_button_text: false,
reset_button_style_class: false,
select_type: rdb.is_mobile ? '' : 'chosen',
select_type_options: {
width: '100%'
}
};
/**
* Opponent filter config.
*
* @since 1.0.0
*
* @type {Object}
*/
const opponent = {
column_number: 2,
column_data_type: 'text',
filter_type: 'select',
filter_match_mode: 'exact',
filter_container_id: 'opponent',
filter_default_label: 'Select Opponent',
filter_reset_button_text: false,
reset_button_style_class: false,
select_type: rdb.is_mobile ? '' : 'chosen',
select_type_options: {
width: '100%'
}
};
/**
* Competition filter config.
*
* @since 1.0.0
*
* @type {Object}
*/
const competition = {
column_number: 3,
column_data_type: 'text',
filter_type: 'select',
filter_container_id: 'competition',
filter_default_label: 'Select Competition',
filter_reset_button_text: false,
reset_button_style_class: false,
select_type: rdb.is_mobile ? '' : 'chosen',
select_type_options: {
case_sensitive_search: true,
enable_split_word_search: true,
width: '100%'
},
text_data_delimeter: ' '
};
/**
* Venue filter config.
*
* @since 1.0.0
*
* @type {Object}
*/
const venue = {
column_number: 4,
column_data_type: _.isEmpty( sessionStorage.venueOptions ) ? 'text' : 'html',
filter_type: 'select',
filter_container_id: 'venue',
filter_default_label: 'Select Venue',
filter_reset_button_text: false,
reset_button_style_class: false,
select_type: rdb.is_mobile ? '' : 'chosen',
select_type_options: {
include_group_label_in_selected: true,
width: '100%'
},
text_data_delimeter: ' '
};
if ( 'html' === venue.column_data_type ) {
venue.data = [ sessionStorage.venueOptions ];
venue.data_as_is = true;
}
/**
* Initialize YADCF.
*/
yadcf.init( this.table, [ season, opponent, competition, venue ] );
}
/**
* Initialize DataTables.js.
*
* @since 1.0.0
* @access private
*
* @link https://datatables.net/reference/event/
* @see init.dt search.dt page.dt order.dt length.dt
*
* @return {DataTable} Current DT instance.
*/
_dataTable() {
const self = this;
// Filter by team checkbox.
$.fn.dataTable.ext.search.push(
function( settings, searchData, index, rowData, counter ) {
const teams = $( 'input[name="wpcm_team"]:checked' ).map( function() {
return this.value;
}).get();
const friendlies = $( 'input[name="wpcm_friendly"]:checked' ).map( function() {
return this.value;
}).get();
if ( teams.length === 0 && friendlies.length === 1 ) {
return true;
}
if ( ! _.includes( ['mens-eagles', 'womens-eagles'], searchData[7] ) ) {
friendlies[0] = '*';
}
if ( teams.indexOf( searchData[7] ) !== -1 && ( '*' === friendlies[0] || friendlies.indexOf( searchData[8] ) !== -1 ) ) {
return true;
}
return false;
}
);
// No more error alerts.
$.fn.dataTable.ext.errMode = 'throw';
// DataTable initializer.
const table = this.$table.DataTable({ // eslint-disable-line
destroy: true,
autoWidth: false,
deferRender: true,
ajax: {
url: adminUrl( 'admin-ajax.php' ),
data: {
action: 'get_matches',
nonce: this.nonce
},
dataSrc: ( response ) => {
if ( ! response.success ) {
$( '#all-matches' ).on( 'error.dt', function( e, settings, techNote, message ) {
console.log( 'An error has been reported by DataTables: ', message );
}).DataTable(); // eslint-disable-line
window.location.reload();
}
let oldData = sessionStorage.allMatches;
const newData = JSON.stringify( response.data );
if ( newData !== oldData ) {
sessionStorage.removeItem( 'allMatches' );
sessionStorage.setItem( 'allMatches', newData );
oldData = newData;
}
const responseData = JSON.parse( oldData ),
final = [];
// Venue options.
this._venueOptions( responseData );
// Parse response.
_.each( responseData, ( match ) => {
const api = {
ID: match.ID,
idStr: `match-${ match.ID }`,
competition: {
display: DTHelper.competition( match ),
filter: DTHelper.competition( match )
},
date: {
display: DTHelper.formatDate( match.ID, match.date.GMT, match.links ),
filter: match.season
},
fixture: {
display: DTHelper.logoResult( match ),
filter: DTHelper.opponent( match.fixture )
},
venue: {
display: DTHelper.venueLink( match.venue ),
filter: match.venue.name
},
friendly: match.friendly ? 'friendly' : 'test',
label: match.competition.label,
neutral: match.venue.neutral,
sort: match.date.timestamp,
team: match.team.slug,
links: match.links
};
final.push( api );
});
return final;
}
},
columnDefs: [
{
className: 'control match-id sorting_disabled',
orderable: false,
targets: 0
},
{
className: 'date',
targets: 1
},
{
className: 'fixture',
targets: 2
},
{
className: 'competition min-medium',
targets: 3
},
{
className: 'venue min-wordpress',
targets: 4
},
{
className: 'comp-label hide',
visible: false,
targets: 5
},
{
className: 'timestamp hide',
visible: false,
targets: 6
},
{
className: 'team hide',
visible: false,
targets: 7
},
{
className: 'friendly hide',
visible: false,
targets: 8
}
],
columns: [
{
data: 'ID',
render: ( data ) => {
return `<span class="hide">${ data }</span>`;
}
},
{
data: 'date',
title: 'Date',
render: {
_: 'display',
display: 'display',
filter: 'filter'
},
orderData: 6,
responsivePriority: 2
},
{
data: 'fixture',
title: 'Fixture',
render: {
_: 'display',
display: 'display',
filter: 'filter'
},
responsivePriority: 1
},
{
data: 'competition',
title: 'Event',
render: {
_: 'display',
display: 'display',
filter: 'filter'
}
},
{
data: 'venue',
title: 'Venue',
render: {
_: 'display',
display: 'display',
filter: 'filter'
}
},
{
data: 'label'
},
{
data: 'sort'
},
{
data: 'team'
},
{
data: 'friendly'
}
],
buttons: false,
dom: '<"wpcm-row"<"wpcm-column flex"fp>> + t + <"wpcm-row"<"wpcm-column pagination"p>>',
language: {
infoEmpty: 'Try reloading the page',
loadingRecords: DT_LOADING,
search: '',
searchPlaceholder: 'Search Matches (Hint: Try "friendly", "ireland", or even "rwc")',
zeroRecords: 'Try reloading the page',
},
order: [
[ 6, 'desc' ]
],
pageLength: 25,
pagingType: 'full_numbers',
scrollCollapse: true,
searching: true,
rowId: 'idStr',
responsive: {
breakpoints: BREAKPOINTS,
details: {
type: 'column',
target: 0
}
},
initComplete: function() {
const api = this.api();
const $teamFilters = $( '.team-filters' );
$teamFilters.on( 'change', 'input[name="wpcm_team"]', function( e ) {
$( `#${ e.currentTarget.value }` ).toggleClass( 'active' );
const $matchType = $teamFilters.find( '.match-type' );
if ( 'mens-eagles' === e.currentTarget.value || 'womens-eagles' === e.currentTarget.value ) {
$matchType.removeClass( 'hide' ).addClass( 'active' );
} else {
$matchType.removeClass( 'active' ).addClass( 'hide' );
}
const checkedBoxes = _.compact( $teamFilters.find( '.active' ).map( function() {
return this.id;
}).get() );
FrontPage._radioFilters( checkedBoxes );
api.draw();
});
$teamFilters.on( 'change', 'input[name="wpcm_friendly"]', function() {
api.draw();
});
$( '.match-filters' ).on( 'change', 'select', function() {
api.draw();
});
self.$win.on( 'resize orientationchange', _.throttle( function() {
api.draw();
}, 300 ) );
api.columns.adjust();
}
});
return table;
}
/**
* Generate grouped venue dropdown options.
*
* @since 1.0.0
* @access private
*
* @param {Object[]} responseData REST API response data.
*
* @return {string} HTML sting of grouped options.
*/
_venueOptions( responseData ) {
if ( sessionStorage.venueOptions ) {
return sessionStorage.venueOptions;
}
let venueGroup = {},
venueOptions = '';
_.each( responseData, ( match ) => {
venueGroup[ COUNTRIES[ match.venue.country.toUpperCase() ] ] = [];
});
_.each( responseData, ( match ) => {
if ( ! _.includes( venueGroup[ COUNTRIES[ match.venue.country.toUpperCase() ] ], match.venue.name ) ) {
venueGroup[ COUNTRIES[ match.venue.country.toUpperCase() ] ].push( match.venue.name );
}
});
_.each( responseData, ( match ) => {
venueGroup[ COUNTRIES[ match.venue.country.toUpperCase() ] ] = _.sortBy( venueGroup[ COUNTRIES[ match.venue.country.toUpperCase() ] ], venue => venue.toLowerCase() );
});
venueGroup = ksort( venueGroup );
venueOptions += '<option value="">Select Venue</option>';
_.each( venueGroup, ( venues, country ) => {
venueOptions += `<optgroup label="${ country }">`;
_.each( venues, ( venue ) => {
venueOptions += `<option value="${ venue }">${ venue }</option>`;
});
venueOptions += `</optgroup>`;
});
sessionStorage.setItem( 'venueOptions', venueOptions );
}
/**
* Initialize Chosen.js on non-mobile screens.
*
* @since 1.0.0
* @access private
* @static
*/
static _filters() {
if ( ! rdb.is_mobile ) {
$( '.chosen_select' ).chosen({ width: '49%' });
}
}
/**
* Show/Hide radio button filters based on selected teams.
*
* @since 1.0.0
* @access private
* @static
*
* @param {array} checkedBoxes Checked box ID values.
*/
static _radioFilters( checkedBoxes ) {
const me = 'mens-eagles',
we = 'womens-eagles',
teams = [ me, we ],
$chk = $( '.team-filters .match-type' );
if ( _.xor( checkedBoxes, teams ).length === 0 ||
( checkedBoxes.length === 1 && ( me === checkedBoxes[0] || we === checkedBoxes[0] ) )
) {
$chk.removeClass( 'hide' ).addClass( 'active' );
} else {
$chk.removeClass( 'active' ).addClass( 'hide' );
}
}
} |
JavaScript | class Main extends Logger {
constructor() {
super('root');
this.Level = Level;
this.MDC = MDC;
this.Plugins = Plugins;
Core.initialize();
}
/**
* Removes all existing loggers and events, and reloads the configuration from scratch.
*/
reset() {
Core.reset();
Plugins.reset();
Core.initialize();
}
getLogger(name, config) {
// TODO check of logger already exists
return new Logger(name, config);
}
} |
JavaScript | class UserInput extends React.Component {
constructor(props) {
super(props);
this.state = {
showPassword: false,
showPasswordField: true,
showEmailField: true,
showUserTypeSelection: true,
textUser: 'Username required',
textEmail: 'Email required',
textPassword: 'Password required',
};
this.handleChange = this.handleChange.bind(this);
this.handleOptionChange = this.handleOptionChange.bind(this);
this.handleClickShowPassword = this.handleClickShowPassword.bind(this);
}
componentWillMount() {
if (this.props.profile) {
this.setState({
showPasswordField: false,
showUserTypeSelection: false,
textUser: '',
textEmail: '',
textPassword: '',
})
} else if(this.props.login) {
this.setState({
showUserTypeSelection: false,
showEmailField: false,
textUser: 'Username required',
textPassword: 'Password required',})
}
}
componentDidUpdate(prevProps) {
if (prevProps.error !== this.props.error) {
if (this.props.error) {
if (this.props.login) {
this.props.validations.usernameValid = false;
this.props.validations.passwordValid = false;
this.setState({
textUser: "Username or password invalid",
textPassword: "Username or password invalid"
})
} else {
this.props.validations.usernameValid = false;
this.setState({
textUser: "User already exists"
});
}
}
}
}
validateInput(value, field) {
let message = '';
let fieldValid = false;
switch (field) {
case "Username":
case "Password":
if (value.length !== 0) {
fieldValid = true;
} else {
message = field + " required"
}
break;
case "Email":
const email = value;
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const result = re.test(email.toLowerCase());
if (result) {
fieldValid = true;
} else {
fieldValid = false;
message = "Invalid " + field;
}
break;
default:
break;
}
return [fieldValid, message]
}
handleClickShowPassword() {
this.setState({showPassword: !this.state.showPassword})
}
handleChange(e) {
const value = e.target.value;
const field = e.target.id;
const valid = this.validateInput(value, field);
switch (field) {
case "Username":
this.props.validations.usernameValid = valid[0];
this.props.user.username = value;
this.setState({
textUser: valid[1]
});
break;
case "Email":
this.props.validations.emailValid = valid[0];
this.props.user.email = value;
this.setState({
textEmail: valid[1]
});
break;
case "Password":
this.props.validations.passwordValid = valid[0];
this.props.user.password = value;
this.setState({
textPassword: valid[1]
});
break;
default:
console.log("error")
}
this.props.onUpdate();
if (this.props.profile) {
this.props.resetSaveButton()
}
}
handleOptionChange() {
this.props.user.isUniversityUser = !this.props.user.isUniversityUser;
this.props.onUpdate()
}
render() {
let userTypeSelection = <RadioGroup onChange={this.handleOptionChange} row>
<FormControlLabel value="student" control={<Radio color="primary"/>} label="Student User"
checked={!this.props.user.isUniversityUser}/>
<FormControlLabel value="uni" control={<Radio color="primary"/>} label="University User"
checked={this.props.user.isUniversityUser}/>
</RadioGroup>;
let passwordField = <TextField
label="Password"
id="Password"
type={this.state.showPassword ? 'text' : 'password'}
required={true}
value={this.props.user.password}
onChange={this.handleChange}
error={!this.props.validations.passwordValid}
helperText={this.state.textPassword}
variant="standard"
margin="dense"
InputProps={{
endAdornment:
<InputAdornment position="end">
<IconButton onClick={this.handleClickShowPassword}>
{this.state.showPassword ? <Visibility/> : <VisibilityOff/>}
</IconButton>
</InputAdornment>
}}/>;
let emailField = <TextField
label="E-mail"
id="Email"
type="email"
required={true}
value={this.props.user.email}
onChange={this.handleChange}
error={!this.props.validations.emailValid}
helperText={this.state.textEmail}
variant="standard"
margin="dense"/>;
return (
<Grid container direction="column">
{this.state.showUserTypeSelection ? userTypeSelection : null}
<TextField
label="Username"
id="Username"
type="text"
required={true}
value={this.props.user.username}
onChange={this.handleChange}
helperText={this.state.textUser}
variant="standard"
error={!this.props.validations.usernameValid}
margin="dense"/>
{this.state.showEmailField ? emailField : null}
{this.state.showPasswordField ? passwordField : null}
</Grid>
);
}
} |
JavaScript | class StartTextDetectionCommand extends smithy_client_1.Command {
// Start section: command_properties
// End section: command_properties
constructor(input) {
// Start section: command_constructor
super();
this.input = input;
// End section: command_constructor
}
/**
* @internal
*/
resolveMiddleware(clientStack, configuration, options) {
this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const clientName = "RekognitionClient";
const commandName = "StartTextDetectionCommand";
const handlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog: models_0_1.StartTextDetectionRequest.filterSensitiveLog,
outputFilterSensitiveLog: models_0_1.StartTextDetectionResponse.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
}
serialize(input, context) {
return Aws_json1_1_1.serializeAws_json1_1StartTextDetectionCommand(input, context);
}
deserialize(output, context) {
return Aws_json1_1_1.deserializeAws_json1_1StartTextDetectionCommand(output, context);
}
} |
JavaScript | @observer
class AppRoot extends React.Component {
constructor (props) {
super(props)
this.state = {}
}
render () {
return (
<React.Fragment>
{/* <DevTools /> */}
<Switch>
<Route component={MainDecorator} />
</Switch>
</React.Fragment>
)
}
} |
JavaScript | class DataTable extends Component {
constructor( props ) {
super( props );
debug( 'Constructor is invoked...' );
this.id = props.id || uid( props );
const dataInfo = props.dataInfo || {};
this.dragged = null;
this.reorder = [];
this.state = {
showInfo: !!dataInfo.showOnStartup,
dataInfo: {
info: dataInfo.info || [],
name: dataInfo.name || '',
variables: dataInfo.variables || null,
showOnStartup: dataInfo.showOnStartup || null
},
showSaveModal: false
};
}
static getDerivedStateFromProps( nextProps, prevState ) {
debug( 'Generating derived state...' );
const newState = {};
if ( nextProps.data !== prevState.data ) {
debug( 'Data is new...' );
let rows;
let keys;
let isArr = isArray( nextProps.data );
if ( isArr || isObject( nextProps.data ) ) {
if ( isArr ) {
// Case: `data` is already an array of observations
rows = nextProps.data.slice();
keys = objectKeys( rows[ 0 ] );
} else {
// Case: `data` is an object with keys for the various variables
rows = createRows( nextProps.data );
keys = objectKeys( nextProps.data );
}
debug( 'Created a `rows` array of length: '+rows.length );
if ( contains( keys, 'id' ) ) {
// Do not attach `id` column:
for ( let i = 0; i < rows.length; i++ ) {
if ( nextProps.showRemove && !rows[ i ][ 'remove' ]) {
rows[ i ][ 'remove' ] = false;
}
}
} else {
// Attach `id` column:
for ( let i = 0; i < rows.length; i++ ) {
if ( nextProps.showRemove && !rows[ i ][ 'remove' ]) {
rows[ i ][ 'remove' ] = false;
}
rows[ i ][ 'id' ] = i + 1;
}
keys.push( 'id' );
}
newState.rows = rows;
newState.keys = keys;
newState.filtered = nextProps.filters;
newState.showTooltip = false;
newState.data = nextProps.data;
newState.columns = createColumns( nextProps, newState );
}
}
if ( nextProps.dataInfo !== prevState.dataInfo ) {
debug( 'Data information has changed...' );
if ( nextProps.dataInfo ) {
newState.dataInfo = {
info: nextProps.dataInfo.info || [],
name: nextProps.dataInfo.name || '',
variables: nextProps.dataInfo.variables || null,
showOnStartup: nextProps.dataInfo.showOnStartup || null
};
}
}
if ( isEmptyObject( newState ) ) {
return null;
}
return newState;
}
componentDidMount() {
debug( 'Component has mounted...' );
if ( this.table ) {
const thead = findDOMNode( this.table ).getElementsByClassName( 'rt-thead' )[ 0 ];
const theadControls = findDOMNode( this.table ).getElementsByClassName( 'rt-thead' )[ 1 ];
const tbody = findDOMNode( this.table ).getElementsByClassName( 'rt-tbody' )[0];
tbody.addEventListener( 'scroll', () => {
thead.scrollLeft = tbody.scrollLeft;
theadControls.scrollLeft = tbody.scrollLeft;
});
}
}
componentDidUpdate( prevProps, prevState ) {
debug( 'Component has updated...' );
let newState = {};
if (
this.props.filters &&
(
this.props.filters !== prevProps.filters ||
this.props.filters.length !== prevProps.filters.length
)
) {
debug( `Data table now has ${this.props.filters.length} filters...` );
newState.filtered = this.props.filters;
}
if (
this.props.data !== prevProps.data &&
this.state.keys.length !== prevState.keys.length
) {
const thead = findDOMNode( this.table ).getElementsByClassName( 'rt-thead' )[ 0 ];
const theadControls = findDOMNode( this.table ).getElementsByClassName( 'rt-thead' )[ 1 ];
const tbody = findDOMNode( this.table ).getElementsByClassName( 'rt-tbody' )[0];
thead.scrollLeft = thead.scrollWidth;
theadControls.scrollLeft = theadControls.scrollWidth;
tbody.scrollLeft = tbody.scrollWidth;
}
if ( !isEmptyObject( newState ) ) {
debug( 'Trigger a state change after update...' );
this.setState( newState );
}
}
renderEditable = ( cellInfo ) => {
return (
<div
style={{ backgroundColor: '#fafafa' }}
contentEditable
suppressContentEditableWarning
onBlur={e => {
const rows = [...this.state.rows ];
const val = e.target.innerHTML;
rows[ cellInfo.index ][ cellInfo.column.id ] = RE_NUMBER.test( val ) ? Number( val ) : val;
this.setState({ rows }, () => {
this.props.onEdit( rows );
});
}}
/* eslint-disable-next-line react/no-danger */
dangerouslySetInnerHTML={{
__html: this.state.rows[ cellInfo.index ][ cellInfo.column.id ]
}}
/>
);
}
renderCheckboxRemovable = ( cellInfo ) => {
return (
<input
id="checkBox"
type="checkbox"
key={`${cellInfo.index}-${cellInfo.column.id}-${this.state.rows.length}`}
onClick={e => {
const rows = [ ...this.state.rows ];
rows[ cellInfo.index ][ cellInfo.column.id ] = e.target.checked;
this.setState({ rows });
this.props.onClickRemove( rows );
}}
/>
);
}
handleFilterChange = ( filtered, column ) => {
const tbody = findDOMNode( this.table ).getElementsByClassName( 'rt-tbody' )[0];
tbody.scrollTop = 0;
const session = this.context;
session.log({
id: this.id,
type: TABLE_FILTER,
value: column.id
});
this.setState({
filtered
}, () => {
this.props.onFilteredChange( this.state.filtered.filter( x => !isNull( x.value ) ) );
});
}
handleSortedChange = ( sorted, column ) => {
const session = this.context;
session.log({
id: this.id,
type: TABLE_SORT,
value: column.id
});
this.setState({
sorted
});
}
showDescriptions = () => {
this.setState({
showVarModal: true
});
}
reset = () => {
const session = this.context;
session.log({
id: this.id,
type: TABLE_RESET,
value: ''
});
this.setState({
filtered: [],
sorted: []
}, () => {
this.props.onFilteredChange( this.state.filtered );
});
}
showInfo = () => {
debug( 'Show dataset information...' );
this.setState({
showInfo: true
});
}
toggleSaveModal = () => {
this.setState({
showSaveModal: !this.state.showSaveModal
});
}
saveJSON = () => {
const blob = new Blob([ JSON.stringify( this.state.data ) ], {
type: 'application/json'
});
const dataInfo = this.props.dataInfo;
let name;
if ( !dataInfo || !dataInfo.name ) {
name = 'dataset.json';
} else {
name = dataInfo.name;
}
saveAs( blob, name );
}
saveCSV = () => {
const session = this.context;
import( 'csv-stringify' ).then( main => {
const stringify = main.default;
stringify( this.state.rows, {
header: true
}, ( err, output ) => {
if ( err ) {
return session.addNotification({
title: this.props.t('error-encountered'),
message: this.props.t('error-csv')+err.message,
level: 'error',
position: 'tl'
});
}
const blob = new Blob([ output ], {
type: 'text/plain'
});
const dataInfo = this.props.dataInfo;
let name;
if ( !dataInfo || !dataInfo.name ) {
name = 'dataset.csv';
} else {
name = `${dataInfo.name}.csv`;
}
saveAs( blob, name );
});
});
}
render() {
debug( 'Rendering component' );
let { rows, dataInfo } = this.state;
if ( !rows ) {
return <Alert variant="danger">{this.props.t('no-data')}</Alert>;
}
let modal = null;
if ( this.state.showVarModal ) {
modal = <Modal
dialogClassName="modal-50w"
show={this.state.showVarModal}
onHide={()=>{
this.setState({ showVarModal: false });
}}>
<Modal.Header closeButton>
<Modal.Title>
{this.props.t('variables')}
</Modal.Title>
</Modal.Header>
<Modal.Body>
{createDescriptions( dataInfo.variables, this.props.t )}
</Modal.Body>
</Modal>;
} else if ( this.state.showInfo ) {
debug( 'Rendering dataset information modal...' );
modal = <Modal
show={this.state.showInfo}
dialogClassName="modal-50w"
onHide={()=>{
this.setState({
showInfo: false
});
}}>
<Modal.Header closeButton>
<Modal.Title>
{dataInfo.name} {this.props.t('description')}
</Modal.Title>
</Modal.Header>
<Modal.Body dangerouslySetInnerHTML={{ // eslint-disable-line react/no-danger
__html: md.render( isArray( dataInfo.info ) ? dataInfo.info.join( '\n' ) : dataInfo.info )
}}>
</Modal.Body>
</Modal>;
}
let cols = this.state.columns.slice();
// Run re-order events:
this.reorder.forEach( o => {
cols[ o.a ] = cols.splice( o.b, 1, cols[o.a] )[ 0 ];
});
cols = cols.map( ( col, i ) => {
if ( col.Header === 'id' ) {
return col;
}
return ({
...col,
Header: <span
className="draggable-header" id={`header-${col.id}`}
draggable="true"
onDragStart={e => {
e.stopPropagation();
e.dataTransfer.setData( 'Text', i );
this.dragged = i;
}}
onDrag={e => e.stopPropagation}
onDragEnd={e => {
e.stopPropagation();
setTimeout(() => {
this.dragged = null;
}, 100 );
}}
onDragOver={e => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
}}
onDrop={e => {
e.preventDefault();
let a = i;
let b = this.dragged;
const keys = this.state.columns.map( x => x.id );
keys.shift();
const tmp = keys[ a ];
keys[ a ] = keys[ b ];
keys[ b ] = tmp;
this.props.onColumnDrag( keys );
this.reorder.push({ a, b });
this.forceUpdate();
}}
>{col.Header}</span>
});
});
if ( this.props.showIdColumn ) {
cols.unshift({
Header: 'id',
accessor: 'id',
className: 'frozen',
headerClassName: 'frozen',
filterable: false,
resizable: false,
width: 50
});
}
if ( this.props.showRemove ) {
cols.push({
Header: this.props.t('remove'),
accessor: 'remove',
Cell: this.renderCheckboxRemovable,
filterable: false
});
}
cols.push({
Header: '',
className: 'table_last_col',
filterable: false,
sortable: false,
resizable: false,
width: 30
});
const saveButton = <Tooltip placement="bottom" tooltip={this.props.disableDownload ? this.props.t('download-disabled') : this.props.t('download-data')} >
<Button className="save-button" variant="light" onClick={this.toggleSaveModal} disabled={this.props.disableDownload} >
<i className="fas fa-download"></i>
</Button>
</Tooltip>;
return (
<Fragment>
<div className="data-table-wrapper" id={this.id} style={this.props.style} >
<div className='data-table-header-wrapper'>
<Tooltip placement="bottom" tooltip={this.props.t('open-description')} show={dataInfo.info.length > 0} >
<Button
variant="light"
disabled={dataInfo.info.length === 0}
onClick={this.showInfo}
className='data-table-title-button'
style={{
cursor: dataInfo.info.length > 0 ? 'pointer' : 'inherit'
}}
>
<h4 className='data-table-title-button-h4'>
{dataInfo.name ? dataInfo.name : this.props.t('data')}
</h4>
</Button>
</Tooltip>
{saveButton}
<TutorialButton
id={this.id}
session={this.context}
onTutorialCompletion={this.props.onTutorialCompletion}
t={this.props.t}
/>
</div>
<ReactTable
id={this.id}
data={rows}
columns={cols}
showPagination={true}
sortable={true}
resizable={true}
filterable={this.props.filterable}
filtered={this.state.filtered}
sorted={this.state.sorted}
showPageSizeOptions={false}
defaultPageSize={50}
onFilteredChange={this.handleFilterChange}
onSortedChange={this.handleSortedChange}
style={this.props.style}
getTableProps={() => {
return {
onScroll: e => {
let left = e.target.scrollLeft > 0 ? e.target.scrollLeft : 0;
for ( let i = 0; i < this.frozenElems.length; i++ ) {
this.frozenElems[ i ].style.left = `${left}px`;
}
}
};
}}
getTrProps={( state, rowInfo, column, table ) => {
let out;
if ( this.props.getTrProps ) {
out = this.props.getTrProps( state, rowInfo, column, table );
} else {
out = {};
}
if ( !out.style ) {
out.style = {};
}
out.style.width = 'max-content !important';
return out;
}}
previousText={this.props.t('previous')}
nextText={this.props.t('next')}
loadingText={this.props.t('loading')}
noDataText={this.props.t('no-rows-found')}
pageText={this.props.t('page')}
ofText={this.props.t('of')}
rowsText={this.props.t('rows')}
>
{( state, makeTable, instance ) => {
const selectedRows = state.sortedData.length;
return (
<div ref={( table ) => {
if ( table ) {
this.table = table;
this.frozenElems = findDOMNode( this.table ).getElementsByClassName( 'frozen' );
}
}} >
<ButtonToolbar className="data-table-header-toolbar">
{ dataInfo.variables ? <Tooltip placement="right" tooltip={this.props.t('variable-descriptions-tooltip')} ><Button
onClick={this.showDescriptions}
variant="light"
size="xsmall"
className="variable-descriptions-button"
>
{this.props.t('variable-descriptions')}
</Button></Tooltip> : null }
{ ( selectedRows !== rows.length ) || ( this.state.sorted && this.state.sorted.length > 0 ) ?
<Tooltip placement="left" tooltip={this.props.t('reset-display-tooltip')} >
<Button
onClick={this.reset}
variant="light"
size="xsmall"
className="reset-button"
>
{this.props.t('reset-display')}
</Button>
</Tooltip> : null }
</ButtonToolbar>
{makeTable()}
<label className="label-number-rows">
<i>{this.props.t('number-rows')}: {selectedRows} ({this.props.t('total')}: {rows.length})</i>
</label>
</div>
);
}}
</ReactTable>
</div>
{modal}
{this.state.showSaveModal ?
<Modal
show={this.state.showSaveModal}
onHide={this.toggleSaveModal}
>
<Modal.Header closeButton>
<Modal.Title>
{this.props.t('download-data')}
</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.props.t('download-data-body')}
</Modal.Body>
<Modal.Footer>
<Button onClick={() => {
this.saveCSV();
this.toggleSaveModal();
}} >{this.props.t('save-csv')}</Button>
<Button onClick={() => {
this.saveJSON();
this.toggleSaveModal();
}} >{this.props.t('save-json')}</Button>
</Modal.Footer>
</Modal> : null }
</Fragment>
);
}
} |
JavaScript | class CustomSerializer extends Serializer {
constructor(node, options, originalSource) {
if (typeof originalSource !== 'string') {
throw new TypeError('originalSource must be a string.');
}
super(node, options);
this.originalSource = originalSource;
}
_originalSourceFor(locationInfo) {
return this.originalSource.slice(locationInfo.startOffset, locationInfo.endOffset);
}
_serializeAttributes(node) {
const nodeInfo = node.sourceCodeLocation;
const attrsInfo = nodeInfo && nodeInfo.attrs;
const attrs = this.treeAdapter.getAttrList(node);
let prevAttrInfo = null;
for (const {name, value, prefix} of attrs) {
const attrInfo = attrsInfo && attrsInfo[name];
// Use formatting from original source code when serializing existing attributes:
if (attrInfo) {
if (prevAttrInfo) {
this.html += this.originalSource.slice(prevAttrInfo.endOffset, attrInfo.startOffset);
} else {
const nodeName = this.treeAdapter.getTagName(node);
this.html += this.originalSource.slice(nodeInfo.startOffset + nodeName.length + 1, attrInfo.startOffset);
}
} else {
// Use space when no source code information is available:
this.html += ' ';
}
this.html += (prefix || '') + name;
if (!attrInfo || /[\"\']$/.test(this._originalSourceFor(attrInfo))) {
this.html += '="' + value + '"';
}
if (attrInfo) {
prevAttrInfo = attrInfo;
}
}
}
_serializeTextNode(node) {
const content = this.treeAdapter.getTextNodeContent(node);
this.html += content;
}
} |
JavaScript | class OrdersCaptureRequest {
constructor(orderId) {
this.path = '/v2/checkout/orders/{order_id}/capture?';
this.path = this.path.replace('{order_id}', querystring.escape(orderId));
this.verb = 'POST';
this.body = null;
this.headers = {
'Content-Type': 'application/json'
};
}
payPalClientMetadataId(payPalClientMetadataId) {
this.headers['PayPal-Client-Metadata-Id'] = payPalClientMetadataId;
return this;
}
payPalRequestId(payPalRequestId) {
this.headers['PayPal-Request-Id'] = payPalRequestId;
return this;
}
prefer(prefer) {
this.headers['Prefer'] = prefer;
return this;
}
requestBody(orderActionRequest) {
this.body = orderActionRequest;
return this;
}
} |
JavaScript | class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set($$props) {
if (this.$$set && !is_empty($$props)) {
this.$$.skip_bound = true;
this.$$set($$props);
this.$$.skip_bound = false;
}
}
} |
JavaScript | class SvelteComponentDev extends SvelteComponent {
constructor(options) {
if (!options || (!options.target && !options.$$inline)) {
throw new Error("'target' is a required option");
}
super();
}
$destroy() {
super.$destroy();
this.$destroy = () => {
console.warn('Component was already destroyed'); // eslint-disable-line no-console
};
}
$capture_state() { }
$inject_state() { }
} |
JavaScript | class AzureOpcTwinClient extends ServiceClient {
/**
* Create a AzureOpcTwinClient.
* @param {credentials} credentials - Subscription credentials which uniquely identify client subscription.
* @param {string} [baseUri] - The base URI of the service.
* @param {object} [options] - The parameter options
* @param {Array} [options.filters] - Filters to be added to the request pipeline
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@link https://github.com/request/request#requestoptions-callback Options doc}
* @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
*/
constructor(credentials, baseUri, options) {
if (credentials === null || credentials === undefined) {
throw new Error('\'credentials\' cannot be null.');
}
if (!options) options = {};
super(credentials, options);
this.baseUri = baseUri;
if (!this.baseUri) {
this.baseUri = 'http://localhost:9080';
}
this.credentials = credentials;
let packageInfo = this.getPackageJsonInfo(__dirname);
this.addUserAgentInfo(`${packageInfo.name}/${packageInfo.version}`);
this.models = models;
this._browse = _browse;
this._getSetOfUniqueNodes = _getSetOfUniqueNodes;
this._browseNext = _browseNext;
this._getNextSetOfUniqueNodes = _getNextSetOfUniqueNodes;
this._browseUsingPath = _browseUsingPath;
this._getCallMetadata = _getCallMetadata;
this._callMethod = _callMethod;
this._readValue = _readValue;
this._getValue = _getValue;
this._readAttributes = _readAttributes;
this._writeValue = _writeValue;
this._writeAttributes = _writeAttributes;
msRest.addSerializationMixin(this);
}
/**
* @summary Browse node references
*
* Browse a node on the specified endpoint. The endpoint must be activated and
* connected and the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The browse request
*
* @param {string} [body.nodeId] Node to browse.
* (default: RootFolder).
*
* @param {string} [body.direction] Possible values include: 'Forward',
* 'Backward', 'Both'
*
* @param {object} [body.view]
*
* @param {string} body.view.viewId Node of the view to browse
*
* @param {number} [body.view.version] Browses specific version of the view.
*
* @param {date} [body.view.timestamp] Browses at or before this timestamp.
*
* @param {string} [body.referenceTypeId] Reference types to browse.
* (default: hierarchical).
*
* @param {boolean} [body.noSubtypes] Whether to include subtypes of the
* reference type.
* (default is false)
*
* @param {number} [body.maxReferencesToReturn] Max number of references to
* return. There might
* be less returned as this is up to the client
* restrictions. Set to 0 to return no references
* or target nodes.
* (default is decided by client e.g. 60)
*
* @param {boolean} [body.targetNodesOnly] Whether to collapse all references
* into a set of
* unique target nodes and not show reference
* information.
* (default is false)
*
* @param {boolean} [body.readVariableValues] Whether to read variable values
* on target nodes.
* (default is false)
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<BrowseResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
browseWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._browse(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Browse node references
*
* Browse a node on the specified endpoint. The endpoint must be activated and
* connected and the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The browse request
*
* @param {string} [body.nodeId] Node to browse.
* (default: RootFolder).
*
* @param {string} [body.direction] Possible values include: 'Forward',
* 'Backward', 'Both'
*
* @param {object} [body.view]
*
* @param {string} body.view.viewId Node of the view to browse
*
* @param {number} [body.view.version] Browses specific version of the view.
*
* @param {date} [body.view.timestamp] Browses at or before this timestamp.
*
* @param {string} [body.referenceTypeId] Reference types to browse.
* (default: hierarchical).
*
* @param {boolean} [body.noSubtypes] Whether to include subtypes of the
* reference type.
* (default is false)
*
* @param {number} [body.maxReferencesToReturn] Max number of references to
* return. There might
* be less returned as this is up to the client
* restrictions. Set to 0 to return no references
* or target nodes.
* (default is decided by client e.g. 60)
*
* @param {boolean} [body.targetNodesOnly] Whether to collapse all references
* into a set of
* unique target nodes and not show reference
* information.
* (default is false)
*
* @param {boolean} [body.readVariableValues] Whether to read variable values
* on target nodes.
* (default is false)
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {BrowseResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link BrowseResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
browse(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._browse(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._browse(endpointId, body, options, optionalCallback);
}
}
/**
* @summary Browse set of unique target nodes
*
* Browse the set of unique hierarchically referenced target nodes on the
* endpoint. The endpoint must be activated and connected and the module client
* and server must trust each other. The root node id to browse from can be
* provided as part of the query parameters. If it is not provided, the
* RootFolder node is browsed. Note that this is the same as the POST method
* with the model containing the node id and the targetNodesOnly flag set to
* true.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.nodeId] The node to browse or omit to browse the
* root node (i=84)
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<BrowseResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getSetOfUniqueNodesWithHttpOperationResponse(endpointId, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._getSetOfUniqueNodes(endpointId, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Browse set of unique target nodes
*
* Browse the set of unique hierarchically referenced target nodes on the
* endpoint. The endpoint must be activated and connected and the module client
* and server must trust each other. The root node id to browse from can be
* provided as part of the query parameters. If it is not provided, the
* RootFolder node is browsed. Note that this is the same as the POST method
* with the model containing the node id and the targetNodesOnly flag set to
* true.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.nodeId] The node to browse or omit to browse the
* root node (i=84)
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {BrowseResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link BrowseResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getSetOfUniqueNodes(endpointId, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getSetOfUniqueNodes(endpointId, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getSetOfUniqueNodes(endpointId, options, optionalCallback);
}
}
/**
* @summary Browse next set of references
*
* Browse next set of references on the endpoint. The endpoint must be
* activated and connected and the module client and server must trust each
* other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The request body with continuation token.
*
* @param {string} body.continuationToken Continuation token from previews
* browse request.
* (mandatory)
*
* @param {boolean} [body.abort] Whether to abort browse and release.
* (default: false)
*
* @param {boolean} [body.targetNodesOnly] Whether to collapse all references
* into a set of
* unique target nodes and not show reference
* information.
* (default is false)
*
* @param {boolean} [body.readVariableValues] Whether to read variable values
* on target nodes.
* (default is false)
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<BrowseNextResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
browseNextWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._browseNext(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Browse next set of references
*
* Browse next set of references on the endpoint. The endpoint must be
* activated and connected and the module client and server must trust each
* other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The request body with continuation token.
*
* @param {string} body.continuationToken Continuation token from previews
* browse request.
* (mandatory)
*
* @param {boolean} [body.abort] Whether to abort browse and release.
* (default: false)
*
* @param {boolean} [body.targetNodesOnly] Whether to collapse all references
* into a set of
* unique target nodes and not show reference
* information.
* (default is false)
*
* @param {boolean} [body.readVariableValues] Whether to read variable values
* on target nodes.
* (default is false)
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {BrowseNextResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link BrowseNextResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
browseNext(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._browseNext(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._browseNext(endpointId, body, options, optionalCallback);
}
}
/**
* @summary Browse next set of unique target nodes
*
* Browse the next set of unique hierarchically referenced target nodes on the
* endpoint. The endpoint must be activated and connected and the module client
* and server must trust each other. Note that this is the same as the POST
* method with the model containing the continuation token and the
* targetNodesOnly flag set to true.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {string} continuationToken Continuation token from
* GetSetOfUniqueNodes operation
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<BrowseNextResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getNextSetOfUniqueNodesWithHttpOperationResponse(endpointId, continuationToken, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._getNextSetOfUniqueNodes(endpointId, continuationToken, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Browse next set of unique target nodes
*
* Browse the next set of unique hierarchically referenced target nodes on the
* endpoint. The endpoint must be activated and connected and the module client
* and server must trust each other. Note that this is the same as the POST
* method with the model containing the continuation token and the
* targetNodesOnly flag set to true.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {string} continuationToken Continuation token from
* GetSetOfUniqueNodes operation
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {BrowseNextResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link BrowseNextResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getNextSetOfUniqueNodes(endpointId, continuationToken, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getNextSetOfUniqueNodes(endpointId, continuationToken, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getNextSetOfUniqueNodes(endpointId, continuationToken, options, optionalCallback);
}
}
/**
* @summary Browse using a browse path
*
* Browse using a path from the specified node id. This call uses
* TranslateBrowsePathsToNodeIds service under the hood. The endpoint must be
* activated and connected and the module client and server must trust each
* other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The browse path request
*
* @param {string} [body.nodeId] Node to browse from.
* (default: RootFolder).
*
* @param {array} body.browsePaths The paths to browse from node.
* (mandatory)
*
* @param {boolean} [body.readVariableValues] Whether to read variable values
* on target nodes.
* (default is false)
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<BrowsePathResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
browseUsingPathWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._browseUsingPath(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Browse using a browse path
*
* Browse using a path from the specified node id. This call uses
* TranslateBrowsePathsToNodeIds service under the hood. The endpoint must be
* activated and connected and the module client and server must trust each
* other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The browse path request
*
* @param {string} [body.nodeId] Node to browse from.
* (default: RootFolder).
*
* @param {array} body.browsePaths The paths to browse from node.
* (mandatory)
*
* @param {boolean} [body.readVariableValues] Whether to read variable values
* on target nodes.
* (default is false)
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {BrowsePathResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link BrowsePathResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
browseUsingPath(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._browseUsingPath(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._browseUsingPath(endpointId, body, options, optionalCallback);
}
}
/**
* @summary Get method meta data
*
* Return method meta data to support a user interface displaying forms to
* input and output arguments. The endpoint must be activated and connected and
* the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The method metadata request
*
* @param {string} [body.methodId] Method id of method to call.
* (Required)
*
* @param {array} [body.methodBrowsePath] An optional component path from the
* node identified by
* MethodId to the actual method node.
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MethodMetadataResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getCallMetadataWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._getCallMetadata(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Get method meta data
*
* Return method meta data to support a user interface displaying forms to
* input and output arguments. The endpoint must be activated and connected and
* the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The method metadata request
*
* @param {string} [body.methodId] Method id of method to call.
* (Required)
*
* @param {array} [body.methodBrowsePath] An optional component path from the
* node identified by
* MethodId to the actual method node.
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {MethodMetadataResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link MethodMetadataResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getCallMetadata(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getCallMetadata(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getCallMetadata(endpointId, body, options, optionalCallback);
}
}
/**
* @summary Call a method
*
* Invoke method node with specified input arguments. The endpoint must be
* activated and connected and the module client and server must trust each
* other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The method call request
*
* @param {string} [body.methodId] Method id of method to call.
*
* @param {string} [body.objectId] Context of the method, i.e. an object or
* object type
* node.
*
* @param {array} [body.argumentsProperty] Arguments for the method - null
* means no args
*
* @param {array} [body.methodBrowsePath] An optional component path from the
* node identified by
* MethodId or from a resolved objectId to the actual
* method node.
*
* @param {array} [body.objectBrowsePath] An optional component path from the
* node identified by
* ObjectId to the actual object or objectType node.
* If ObjectId is null, the root node (i=84) is used.
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<MethodCallResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
callMethodWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._callMethod(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Call a method
*
* Invoke method node with specified input arguments. The endpoint must be
* activated and connected and the module client and server must trust each
* other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The method call request
*
* @param {string} [body.methodId] Method id of method to call.
*
* @param {string} [body.objectId] Context of the method, i.e. an object or
* object type
* node.
*
* @param {array} [body.argumentsProperty] Arguments for the method - null
* means no args
*
* @param {array} [body.methodBrowsePath] An optional component path from the
* node identified by
* MethodId or from a resolved objectId to the actual
* method node.
*
* @param {array} [body.objectBrowsePath] An optional component path from the
* node identified by
* ObjectId to the actual object or objectType node.
* If ObjectId is null, the root node (i=84) is used.
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {MethodCallResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link MethodCallResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
callMethod(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._callMethod(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._callMethod(endpointId, body, options, optionalCallback);
}
}
/**
* @summary Read variable value
*
* Read a variable node's value. The endpoint must be activated and connected
* and the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The read value request
*
* @param {string} [body.nodeId] Node to read from (mandatory)
*
* @param {array} [body.browsePath] An optional path from NodeId instance to
* the actual node.
*
* @param {string} [body.indexRange] Index range to read, e.g. 1:2,0:1 for 2
* slices
* out of a matrix or 0:1 for the first item in
* an array, string or bytestring.
* See 7.22 of part 4: NumericRange.
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ValueReadResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
readValueWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._readValue(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Read variable value
*
* Read a variable node's value. The endpoint must be activated and connected
* and the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The read value request
*
* @param {string} [body.nodeId] Node to read from (mandatory)
*
* @param {array} [body.browsePath] An optional path from NodeId instance to
* the actual node.
*
* @param {string} [body.indexRange] Index range to read, e.g. 1:2,0:1 for 2
* slices
* out of a matrix or 0:1 for the first item in
* an array, string or bytestring.
* See 7.22 of part 4: NumericRange.
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {ValueReadResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link ValueReadResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
readValue(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._readValue(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._readValue(endpointId, body, options, optionalCallback);
}
}
/**
* @summary Get variable value
*
* Get a variable node's value using its node id. The endpoint must be
* activated and connected and the module client and server must trust each
* other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {string} nodeId The node to read
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ValueReadResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getValueWithHttpOperationResponse(endpointId, nodeId, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._getValue(endpointId, nodeId, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Get variable value
*
* Get a variable node's value using its node id. The endpoint must be
* activated and connected and the module client and server must trust each
* other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {string} nodeId The node to read
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {ValueReadResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link ValueReadResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getValue(endpointId, nodeId, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getValue(endpointId, nodeId, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getValue(endpointId, nodeId, options, optionalCallback);
}
}
/**
* @summary Read node attributes
*
* Read attributes of a node. The endpoint must be activated and connected and
* the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The read request
*
* @param {array} body.attributes Attributes to read
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ReadResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
readAttributesWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._readAttributes(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Read node attributes
*
* Read attributes of a node. The endpoint must be activated and connected and
* the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The read request
*
* @param {array} body.attributes Attributes to read
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {ReadResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link ReadResponseApiModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
readAttributes(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._readAttributes(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._readAttributes(endpointId, body, options, optionalCallback);
}
}
/**
* @summary Write variable value
*
* Write variable node's value. The endpoint must be activated and connected
* and the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The write value request
*
* @param {string} [body.nodeId] Node id to to write value to.
*
* @param {array} [body.browsePath] An optional path from NodeId instance to
* the actual node.
*
* @param {object} body.value Value to write. The system tries to convert
* the value according to the data type value,
* e.g. convert comma seperated value strings
* into arrays. (Mandatory)
*
* @param {string} [body.dataType] A built in datatype for the value. This can
* be a data type from browse, or a built in
* type.
* (default: best effort)
*
* @param {string} [body.indexRange] Index range to write
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ValueWriteResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
writeValueWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._writeValue(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Write variable value
*
* Write variable node's value. The endpoint must be activated and connected
* and the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The write value request
*
* @param {string} [body.nodeId] Node id to to write value to.
*
* @param {array} [body.browsePath] An optional path from NodeId instance to
* the actual node.
*
* @param {object} body.value Value to write. The system tries to convert
* the value according to the data type value,
* e.g. convert comma seperated value strings
* into arrays. (Mandatory)
*
* @param {string} [body.dataType] A built in datatype for the value. This can
* be a data type from browse, or a built in
* type.
* (default: best effort)
*
* @param {string} [body.indexRange] Index range to write
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {ValueWriteResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link ValueWriteResponseApiModel} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
writeValue(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._writeValue(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._writeValue(endpointId, body, options, optionalCallback);
}
}
/**
* @summary Write node attributes
*
* Write any attribute of a node. The endpoint must be activated and connected
* and the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The batch write request
*
* @param {array} body.attributes Attributes to update
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WriteResponseApiModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
writeAttributesWithHttpOperationResponse(endpointId, body, options) {
let client = this;
let self = this;
return new Promise((resolve, reject) => {
self._writeAttributes(endpointId, body, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Write node attributes
*
* Write any attribute of a node. The endpoint must be activated and connected
* and the module client and server must trust each other.
*
* @param {string} endpointId The identifier of the activated endpoint.
*
* @param {object} body The batch write request
*
* @param {array} body.attributes Attributes to update
*
* @param {object} [body.header]
*
* @param {object} [body.header.elevation]
*
* @param {string} [body.header.elevation.type] Possible values include:
* 'None', 'UserName', 'X509Certificate', 'JwtToken'
*
* @param {object} [body.header.elevation.value] Value to pass to server
*
* @param {array} [body.header.locales] Optional list of locales in preference
* order.
*
* @param {object} [body.header.diagnostics]
*
* @param {string} [body.header.diagnostics.level] Possible values include:
* 'None', 'Status', 'Operations', 'Diagnostics', 'Verbose'
*
* @param {string} [body.header.diagnostics.auditId] Client audit log entry.
* (default: client generated)
*
* @param {date} [body.header.diagnostics.timeStamp] Timestamp of request.
* (default: client generated)
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {WriteResponseApiModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link WriteResponseApiModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
writeAttributes(endpointId, body, options, optionalCallback) {
let client = this;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._writeAttributes(endpointId, body, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._writeAttributes(endpointId, body, options, optionalCallback);
}
}
} |
JavaScript | class ContactEventUpdateDto {
/**
* Constructs a new <code>ContactEventUpdateDto</code>.
* @alias module:model/ContactEventUpdateDto
*/
constructor() {
ContactEventUpdateDto.initialize(this);
}
/**
* 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) {
}
/**
* Constructs a <code>ContactEventUpdateDto</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/ContactEventUpdateDto} obj Optional instance to populate.
* @return {module:model/ContactEventUpdateDto} The populated <code>ContactEventUpdateDto</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ContactEventUpdateDto();
if (data.hasOwnProperty('FieldName')) {
obj['FieldName'] = ApiClient.convertToType(data['FieldName'], 'String');
}
if (data.hasOwnProperty('OldValue')) {
obj['OldValue'] = ApiClient.convertToType(data['OldValue'], 'String');
}
if (data.hasOwnProperty('NewValue')) {
obj['NewValue'] = ApiClient.convertToType(data['NewValue'], 'String');
}
}
return obj;
}
} |
JavaScript | class ContactsList extends Component {
constructor(props) {
super(props);
this.deleteContact = this.deleteContact.bind(this)
this.state = {
paginationValue: '50',
contact: []};
}
componentDidMount() {
axios.get('http://localhost:5000/contacts/')
.then((response) => {
// const contact = response.data.map((contacts) =>({
// id: contacts.id,
// fullname: contacts.fullname
// }));
this.setState({ contact: response.data});
})
.catch((error) => {
console.log(error);
});
}
deleteContact(e,id) {
e.preventDefault();
axios.get('http://localhost:5000/contacts/delete/'+id)
.then(response => { console.log(response.data)});
this.setState({
contact: this.state.contact.filter(el => el._id !== id)
})
// window.location = '/';
}
// ContactList() {
// return this.state.contact.map(eachcontact => {
// return <li key={eachcontact._id}><Avatar name={eachcontact.fullname} size="25" round={true} /> {eachcontact.fullname}</li>
// })
// }
render() {
return (
<div className ="container">
<h3 style={{color: "rgb(49, 90, 86)"}}>{this.state.contact.lenght} CONTACTS</h3>
<Accordion>
{this.state.contact.map(item => {
return (
<AccordionItem title={`${item.fullname}`} expanded={item === 1}>
<div className = "prof">
<div className="align">
<li> <FontAwesomeIcon icon="user" size="lg"/> </li>
<li> <FontAwesomeIcon icon="envelope" size="lg"/> </li>
<li><FontAwesomeIcon icon="mobile" size="lg"/> </li>
<li> <FontAwesomeIcon icon="map-marker-alt" size="lg"/> </li>
</div>
<ol>
<button className = "coinn"> <Link to={"contacts/edit/"+item._id}></Link><FontAwesomeIcon icon="edit"/> </button>
<button className = "coin" onClick={(e)=>this.deleteContact(e,item._id)}> <FontAwesomeIcon icon="trash"/></button>
<div className ="av"> <Avatar name={item.fullname} size="35" round={true} /></div>
<li> {`${item.fullname}`}</li>
<li> {`${item.email}`} </li>
<li> {`${item.phone}`} </li>
<li> {`${item.address}`} </li>
</ol>
<ul className="social-icon-list">
<li>
<a
href="https://www.facebook.com/carlytesnor"
className="social-link"
>
<FontAwesomeIcon icon={["fab", "instagram"]} size="xs" />
</a>
</li>
<li>
<a
href="https://www.facebook.com/carlytesnor"
className="social-link"
>
<FontAwesomeIcon icon={["fab", "facebook"]} size="xs" />
</a>
</li>
<li>
<a href="https://twitter.com/TesnorC" className="social-link">
<FontAwesomeIcon icon={["fab", "twitter"]} size="xs" />
</a>
</li>
<li>
<a href="https://github.com/tazz509" className="social-link">
<FontAwesomeIcon icon={["fab", "github"]} size="xs" />
</a>
</li>
<li>
<a
href="https://www.linkedin.com/in/carly-r-tesnor-633736160/"
className="social-link"
>
<FontAwesomeIcon icon={["fab", "linkedin"]} size="xs" />
</a>
</li>
</ul>
</div>
</AccordionItem>
);
})}
</Accordion>
</div>
)
}
} |
JavaScript | class VillageState {
constructor(place, packets) {
this.place = place, this.packets = packets
}
/*
*update state after movet to destination and return new state
*/
move(destination) {
if (!_graphRoad[this.place].includes(destination)) return this;
let newPackets = this.packets.map(p => {
if (p.place !== this.place) return p;
else return { place: destination, address: p.address }
}).filter(packet => {
return packet.address !== packet.place;
})
return new VillageState(destination, newPackets)
}
} |
JavaScript | class ParameterBag {
static validateSchema(schema) {
for (let name in schema) {
const def = schema[name];
if (!def.hasOwnProperty('type')) {
throw new TypeError(`[stateManager] Invalid schema definition - param "${name}": "type" key is required`);
}
if (!types.hasOwnProperty(def.type)) {
throw new TypeError(`[stateManager] Invalid schema definition - param "${name}": "{ type: '${def.type}' }" does not exists`);
}
const required = types[def.type].required;
required.forEach(function(key) {
if (def.event === true && key === 'default') {
// do nothing, default is always null for `event` params
} else if (!def.hasOwnProperty(key)) {
throw new TypeError(`[stateManager] Invalid schema definition - param "${name}" (type "${def.type}"): "${key}" key is required`);
}
});
}
}
constructor(schema, initValues = {}) {
if (!schema) {
throw new Error(`[stateManager] schema is mandatory`);
}
schema = cloneDeep(schema);
initValues = cloneDeep(initValues);
/**
* List of parameters.
*
* @type {Object<String, Param>}
* @name _params
* @memberof ParameterBag
* @instance
* @private
*/
this._values = {};
/**
* List of schema with init values.
*
* @type {Object<String, paramDefinition>}
* @name _schema
* @memberof ParameterBag
* @instance
* @private
*/
this._schema = {};
ParameterBag.validateSchema(schema);
// make shure initValues make sens according to the given schema
for (let name in initValues) {
if (!schema.hasOwnProperty(name)) {
throw new ReferenceError(`[stateManager] init value defined for undefined param "${name}"`);
}
}
for (let [name, def] of Object.entries(schema)) {
const {
defaultOptions,
coerceFunction
} = types[def.type];
def = Object.assign({}, defaultOptions, def);
// if event property is set to true, the param must
// be nullable and its default value is `undefined`
if (def.event === true) {
def.nullable = true;
def.default = null;
}
let initValue;
if (initValues.hasOwnProperty(name)) {
initValue = initValues[name];
} else {
initValue = def.default;
}
this._schema[name] = def;
// coerce init value and store in definition
initValue = this.set(name, initValue)[0];
this._schema[name].initValue = initValue;
this._values[name] = initValue;
}
}
/**
* Define if the parameter exists.
*
* @param {String} name - Name of the parameter.
* @return {Boolean}
*/
has(name) {
return this._schema.hasOwnProperty(name);
}
/**
* Return values of all parameters as a flat object.
*
* @return {Object}
*/
getValues() {
let values = {};
for (let name in this._values) {
values[name] = this.get(name);
}
return values;
}
/**
* Return the value of the given parameter. If the parameter is of `any` type,
* a deep copy is returned.
*
* @param {String} name - Name of the parameter.
* @return {Mixed} - Value of the parameter.
*/
get(name) {
if (!this.has(name)) {
throw new ReferenceError(`[stateManager] Cannot get value of undefined parameter "${name}"`);
}
if (this._schema[name].type === 'any') {
return cloneDeep(this._values[name]);
} else {
return this._values[name];
}
}
/**
* Set the value of a parameter. If the value of the parameter is updated
* (aka if previous value is different from new value) all registered
* callbacks are registered.
*
* @param {String} name - Name of the parameter.
* @param {Mixed} value - Value of the parameter.
* @param {Boolean} [forcePropagation=false] - if true, propagate value even
* if the value has not changed.
* @return {Array} - [new value, updated flag].
*/
set(name, value) {
if (!this.has(name)) {
throw new ReferenceError(`[stateManager] Cannot set value of undefined parameter "${name}"`);
}
const def = this._schema[name];
const { coerceFunction } = types[def.type];
if (value === null && def.nullable === false) {
throw new TypeError(`[stateManager] Invalid value for ${def.type} param "${name}": value is null and param is not nullable`);
} else if (value === null && def.nullable === true) {
value = value;
} else {
value = coerceFunction(name, def, value);
}
const currentValue = this._values[name];
const updated = !equal(currentValue, value);
this._values[name] = value;
// return tuple so that the state manager can handle the `filterChange` option
return [value, updated];
}
/**
* Reset a parameter to its initialization values. Reset all parameters if no argument.
* @note - prefer `state.set(state.getInitValues())`
* or `state.set(state.getDefaultValues())`
*
* @param {String} [name=null] - Name of the parameter to reset.
*/
// reset(name = null) {
// if (name !== null) {
// this._params[name] = this._initValues[name];
// } else {
// for (let name in this.params) {
// this._params[name].reset();
// }
// }
// }
/**
* Return the given schema along with the initialization values.
*
* @return {Object}
*/
getSchema(name = null) {
if (name === null) {
return this._schema;
} else {
if (!this.has(name)) {
throw new ReferenceError(`[stateManager] Cannot get schema description of undefined parameter "${name}"`);
}
return this._schema[name];
}
}
// return the default value, if initValue has been given, return init values
getInitValues() {
const initValues = {};
for (let [name, def] of Object.entries(this._schema)) {
initValues[name] = def.initValue;
}
return initValues;
}
// return the default value, if initValue has been given, return init values
getDefaults() {
const defaults = {};
for (let [name, def] of Object.entries(this._schema)) {
defaults[name] = def.defaults;
}
return defaults;
}
} |
JavaScript | class Env {
/**
* Sets the data configuration property.
* This is a getter-setter function.
*
* @public
*
* @param {DataModel} data Instance of datamodel to be visualized
* @return {Env} Instance of the environment
*/
data () { /* pseudo funciton */ }
/**
* Sets the width configuration property. Width in px is total horizontal space each canvas should take.
* This is a getter-setter function.
*
* @public
*
* @param {Number} width Width of the visualization area
* @return {Env} Instance of the environment
*/
width () { /* pseudo funciton */ }
/**
* Sets the height configuration property. Height in px is total horizontal space each canvas should take.
* This is a getter-setter function.
*
* @public
*
* @param {Number} width Height of the visualization area
* @return {Env} Instance of the environment
*/
height () { /* pseudo funciton */ }
/**
* Sets the configuration property for setting minimium unit width. *Unit* here is {@link VisualUnit} component of
* Muze.
*
* This is a getter-setter function.
*
* @public
*
* @param {Number} [minWidth = 150] Min width of a {@link VisualUnit}
* @return {Env} Instance of the environment
*/
minUnitWidth () { /* pseudo funciton */ }
/**
* Sets the configuration property for setting minimium unit height. *Unit* here is {@link VisualUnit} component of
* Muze.
*
* This is a getter-setter function.
*
* @public
*
* @param {Number} [minWidth = 150] Min height of a {@link VisualUnit}
* @return {Env} Instance of the environment
*/
minUnitHeight () { /* pseudo funciton */ }
/**
* Sets the configuration for canvases. User passed configuration is merged with default configuration and then
* set to canvas
*
* This is a getter-setter function.
*
* @public
*
* @param {Object} config Partial or full configuration of canvas.
* @param {AxisConfig} config.axes.x X Axis configuration {@link AxisConfig}.
* @param {AxisConfig} config.axes.y Y Axis configuration {@link AxisConfig}.
* @param {GridLineConfig} config.gridLines Grid line configuration {@link GridLineConfig}.
* @param {GridBandConfig} config.gridBands Grid band configuration {@link GridBandConfig}.
* @param {GlobalLegendConfig} config.legend Legend configuration {@link GlobalLegendConfig}.
* @param {InteractionConfig} config.interaction Interaction configuration {@link InteractionConfig}
* @param {Object} config.autoGroupBy Group by configuration.
* @param {boolean} config.autoGroupBy.disabled If true, then disables automatic group by of datamodel in the
* chart. By default, set to false.
* @return {Env} Instance of the environment
*/
config () { /* pseudo function */ }
/**
* Creates an instance of {@link Canvas}
*
* @public
*
* @return {Canvas} Instance of canvas
*/
canvas () { /* pseudo function */ }
/**
* Components of Muze are loaded from registry. User can override the default component by overriding the registry
* with new component definition.
*
* Muze creates multiple cells to house the visualization components. Those are called {@link Cells}.
* `cellRegistry` is the registry for those cells.
* - {@link SimpleCell}
* - {@link TextCell}
* - {@link AxisCell}
* - {@link GeomCell}
* - {@link BlankCell}
*
* This funciton acts as getter and setter.
* When acts as a getter this returns the list of registries you can extend.
* When acts as a setter this allows user to register a component for a existing key. During the process of setting
* a new component in registry, it is not allowed to create a new key.
*
* ```
* const GeomCell = env.cellRegistry().GeomCell;
* env.cellRegistry({
* GeomCell: class NewGeomCell extends GeomCell {
* render () {
* // override the render
* }
* }
* });
* ```
*
* When called as a setter
* @param {Object} override Key value pair where keys are the name of the cells user with to override. Allowed keys
* are
* - `SimpleCell`
* - `TextCell`
* - `AxisCell`
* - `GeomCell`
* - `BlankCell`
* And value being the overridden class definition.
*
* @return {Env} Instance of current environment
*
* When called as a getter
* @return {object} Object containing the registration key and class definition
* ```
* {
* SimpleCell: SimpleCell,
* TextCell: TextCell,
* AxisCell: AxisCell,
* GeomCell: GeomCell,
* BlankCell: BlankCell
* }
* ```
*
* @public
*/
cellRegistry () { /* pseudo function */ }
/**
* Components of Muze are loaded from registry. User can override the default component by overriding the registry
* with new component definition.
*
* Muze composes layers to create a visualization. Each layer contain one mark (plot) type. Superposition of
* one or multiple such layers create one visulization. Muze provides definition of atomic layers. A new layer can
* be created and used as a mark type. `layerRegistry` handles the registrtion process. Atomic layers are
* - {@link AreaLayer}
* - {@link ArcLayer}
* - {@link LineLayer}
* - {@link TextLayer}
* - {@link PointLayer}
* - {@link TickLayer}
* - {@link BarLayer}
* - {@link BaseLayer}
*
* For `layerRegistry` a new layer can be registered by using a new key.
*
* ```
* const PointLayer = env.layerRegistry().point;
* env.layerRegistry({
* grass: class GrassLayer extends PointLayer {
* render () {
* // renders layer here
* }
* }
* });
* ```
* Access the new layer type by mentioning it as a mark type
* ```
* .layers([{
* mark: 'bar',
* encoding: {
* y: 'Acceleration'
* }
* }, {
* mark: 'grass', // new mark type
* encoding: {
* y: 'Displacement'
* }
* }])
* ```
*
* When called as a setter
* @param {Object} override Key value pair where keys are the name of the cells user with to override. Allowed keys
* are
* - `Area`
* - `Arc`
* - `Line`
* - `Text`
* - `Point`
* - `Tick`
* - `Bar`
* And value being the overridden class definition.
*
* @return {Env} Instance of current environment
*
* When called as a getter
* @return {object} Object containing the registration key and class definition
* ```
* {
* Area: AreaLayer,
* Text: TextLayer,
* Arc: ArcLayer,
* Line: LineLayer,
* Bar: BarLayer,
* Line: LineLayer,
* Point: PointLayer,
* Tick: TickLayer
* }
* ```
*
* @public
*/
layerRegistry () { /* pseudo function */ }
} |
JavaScript | class TimerClearedError extends Error {
/**
* @override
*/
constructor(timerId, ...args) {
super(...args);
this.name = 'TimerClearedError';
this.timerId = timerId;
}
} |
JavaScript | class Timer {
/**
* @param {Object} env the OWL env
* @param {function} onTimeout
* @param {integer} duration
* @param {Object} [param3={}]
* @param {boolean} [param3.silentCancelationErrors=true] if unset, caller
* of timer will observe some errors that come from current timer calls
* that has been cleared with `.clear()` or `.reset()`.
* @see TimerClearedError for when timer has been aborted from `.clear()`
* or `.reset()`.
*/
constructor(env, onTimeout, duration, { silentCancelationErrors = true } = {}) {
this.env = env;
/**
* Determine whether the timer has a pending timeout.
*/
this.isRunning = false;
/**
* Duration, in milliseconds, until timer times out and calls the
* timeout function.
*/
this._duration = duration;
/**
* Determine whether the caller of timer `.start()` and `.reset()`
* should observe cancelation errors from `.clear()` or `.reset()`.
*/
this._hasSilentCancelationErrors = silentCancelationErrors;
/**
* The function that is called when the timer times out.
*/
this._onTimeout = onTimeout;
/**
* Deferred of a currently pending invocation to inner function on
* timeout.
*/
this._timeoutDeferred = undefined;
/**
* Internal reference of `setTimeout()` that is used to invoke function
* when timer times out. Useful to clear it when timer is cleared/reset.
*/
this._timeoutId = undefined;
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Clear the timer, which basically sets the state of timer as if it was
* just instantiated, without being started. This function makes sense only
* when this timer is running.
*/
clear() {
this.env.browser.clearTimeout(this._timeoutId);
this.isRunning = false;
if (!this._timeoutDeferred) {
return;
}
this._timeoutDeferred.reject(new TimerClearedError(this.id));
}
/**
* Reset the timer, i.e. the pending timeout is refreshed with initial
* duration. This function makes sense only when this timer is running.
*/
async reset() {
this.clear();
await this.start();
}
/**
* Starts the timer, i.e. after a certain duration, it times out and calls
* a function back. This function makes sense only when this timer is not
* yet running.
*
* @throws {Error} in case the timer is already running.
*/
async start() {
if (this.isRunning) {
throw new Error("Cannot start a timer that is currently running.");
}
this.isRunning = true;
const timeoutDeferred = makeDeferred();
this._timeoutDeferred = timeoutDeferred;
const timeoutId = this.env.browser.setTimeout(
() => {
this.isRunning = false;
timeoutDeferred.resolve(this._onTimeout());
},
this._duration
);
this._timeoutId = timeoutId;
let result;
try {
result = await timeoutDeferred;
} catch (error) {
if (
!this._hasSilentCancelationErrors ||
!(error instanceof TimerClearedError) ||
error.timerId !== this.id
) {
// This branching should never happens.
// Still defined in case of programming error.
throw error;
}
} finally {
this.env.browser.clearTimeout(timeoutId);
this._timeoutDeferred = undefined;
this.isRunning = false;
}
return result;
}
} |
JavaScript | class HTMLExporter extends DOMExporter {
constructor (params, options = {}) {
super(_defaultParams(params, options), options)
}
exportDocument (doc) {
const htmlEl = DefaultDOMElement.parseHTML('<html><head></head><body></body></html>')
return this.convertDocument(doc, htmlEl)
}
getDefaultBlockConverter () {
return defaultBlockConverter // eslint-disable-line no-use-before-define
}
getDefaultPropertyAnnotationConverter () {
return defaultAnnotationConverter // eslint-disable-line no-use-before-define
}
} |
JavaScript | class WordPicker {
constructor() {
this.dictionaryPath = path.join(__dirname, '../dictionary.json');
}
/**
* @description Reads the json dictionary file
* @memberof WordPicker
*
* @returns JSON object
*/
readJSONDictionary() {
return fs.readFileSync(this.dictionaryPath, 'utf-8');
}
/**
*
* @description Returns the keyname in the json object
* @param {*} obj
* @memberof WordPicker
*
* @returns {string} key name
*/
getKeyName(obj) {
return Object.keys(obj);
}
/**
* @description Picks a random word from the json dictionary
* @memberof WordPicker
*
* @returns {string} word
*/
pickRandomWord() {
const dictionary = this.readJSONDictionary();
const parsedJSON = JSON.parse(dictionary);
// Choose a random json object from the array
const randomJSON =
parsedJSON[Math.floor(Math.random() * parsedJSON.length)];
console.log(randomJSON);
const keyName = this.getKeyName(randomJSON);
return randomJSON[`${keyName}`];
}
/**
* @description Gets a single meaning of the word if available
*
* @param {object} object
* @memberof WordPicker
*
* @returns {object} noun object
*/
getSingleMeaning(object) {
if (object.meaning.noun[0].definition)
return `(n). ${object.meaning.noun[0].definition}`;
if (object.meaning.verb[0].definition)
return `(v). ${object.meaning.verb[0].definition}`;
if (object.meaning.adjective[0].definition)
return `(adj). ${object.meaning.adjective[0].definition}`;
}
} |
JavaScript | class MovieDetail extends Component {
constructor(props) {
super(props);
this.movie = this.props.navigation.state.params.movie;
this.state = {
movie: {},
loading: true,
}
}
async fetchDetails(id) {
const details_api = `https://api.themoviedb.org/3/${id}?api_key=${api_key}&language=${lang}`;
let data = await fetch(details_api);
let result = await data.json();
return result;
}
async componentWillMount() {
await this.fetchDetails(this.movie.id).then((details) => {
this.setState({
movie: details,
loading: false
})
})
}
render() {
let movieObj = {
title: this.movie.title,
rate: this.movie.vote_average,
overview: this.movie.overview,
date: this.movie.release_date,
backdrop_path: this.movie.backdrop_path,
}
let Content = (props) => {
if (!this.state.loading) {
return (
<View>
<View style={styles.border}>
<View style={[styles.info]}>
<Text>
<FontAwesome >
{Icons.calendar + ' '}
</FontAwesome>
{movieObj.date}
</Text>
<Text>
<FontAwesome >
{Icons.thumbsOUp + ' '}
</FontAwesome>
{movieObj.rate}
</Text>
</View>
</View>
<View style={[styles.headerView]}>
<H3 style={[styles.headerText]}>Overview</H3>
</View>
<View style={styles.border}>
<View style={styles.info}>
<Text style={styles.tagline}>
{this.state.movie.tagline}
</Text>
<Text>{movieObj.overview}</Text>
</View>
</View>
<Reviews />
</View>
)
} else {
return <ActivityIndicator size="large" />;
}
}
let Reviews = () => {
return (
<View>
<View style={[styles.headerView]}>
<H3 style={[styles.headerText]}>Reviews</H3>
</View>
<View style={styles.border}>
<View style={styles.info}>
<MovieReviewsList movieId={this.movie.id} />
</View>
</View>
</View>
)
}
return (
<ScrollView>
<View style={[styles.header, styles.border]}>
<Image source={{ uri: image_path.concat(movieObj.backdrop_path) }}
resizeMode="contain" resizeMethod='scale'
style={styles.image} />
<View style={styles.title_background}>
<Text style={styles.title}>{movieObj.title}</Text>
</View>
</View>
<Content />
</ScrollView>
);
}
} |
JavaScript | class Token {
/**
*
* @param {array} source
* @param {string} type
* @param {string} channel
* @param {number} start
* @param {number} stop
* @param {number} tokenIndex
* @param {number} line
* @param {number} column
* @param {string} text
* @returns {Token}
*/
constructor(
source=null,
type=null,
channel=null,
start=null,
stop=null,
tokenIndex=null,
line=null,
column=null,
text=null
) {
this.source = source;
this.type = type;
this.channel = channel;
this.start = start;
this.stop = stop;
this.tokenIndex = tokenIndex;
this.line = line;
this.column = column;
this._text = text;
if (Symbol && Symtol.toStringTag) {
this[Symbol.toStringTag] = 'Token';
}
}
/**
*
* @returns 0
*/
static get INVALID_TYPE() {
return INVALID_TYPE;
}
/**
*
* @description
* During lookahead operations, this "token" signifies we hit rule end ATN
* state and did not follow it despite needing to.
*
* @returns -2
*/
static get EPSILON() {
return EPSILON;
}
/**
*
* @returns 1
*/
static get MIN_USER_TOKEN_TYPE() {
return MIN_USER_TOKEN_TYPE;
}
/**
*
* @returns -1
*/
static get EOF() {
return EOF;
}
/**
*
* @description
* All tokens go to the parser (unless skip() is called in that rule) on a
* particular "channel". The parser tunes to a particular channel so that
* whitespace etc. can go to the parser on a "hidden" channel.
*
* @returns 0
*/
static get DEFAULT_CHANNEL() {
return DEFAULT_CHANNEL;
}
/**
*
* @description
* Anything on a different channel that DEFAULT_CHANNEL is not parsed by
* parser.
*
* @returns 1
*/
static get HIDDEN_CHANNEL() {
return HIDDEN_CHANNEL;
}
get text() {
return this._text;
}
set text(text) {
this._text = text;
}
getTokenSource() {
return this.source[0];
}
getInputStream() {
return this.source[1];
}
/**
*
* @description
* When this object is serialized e.g., @{code JSON.stringify} this method
* is called implicitly, and it's return value is used for serialization.
*
* @returns {{
* stop: Token.stop,
* line: Token.line,
* channel: Token.channel,
* start: Token.start,
* column: Token.column,
* tokenIndex: Token.tokenIndex,
* text: Token.text,
* type: Token.type
* }}
* @private
*/
toJSON() {
const { type, channel, start, stop, tokenIndex, line, column, text } = this;
return {
type,
channel,
start,
stop,
tokenIndex,
line,
column,
text
};
}
} |
JavaScript | class HistoryValidation extends Validation {
/**
* @param {String} data.id - objectId
* @returns
* @memberof ImageValidation
*/
history(data) {
return this.Joi
.object({
dateStart: this.Joi
.string()
.regex(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/)
.required(),
dateFinish: this.Joi
.string()
.regex(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/)
.required(),
_csrf: this.Joi
.string()
.required(),
})
.validate(data);
}
/**
* @param {String} data.id - objectId
* @returns
* @memberof HistoryValidation
*/
email(data) {
return this.Joi
.object({
email: this.Joi
.string()
.email()
.required(),
_csrf: this.Joi
.string()
.required(),
})
.validate(data);
}
} |
JavaScript | class ImageComponent extends LitElement {
static get properties() {
return {
name: {type: String},
file: {type: Object}
};
}
constructor() {
super();
this.name = "unknown"
this.file = {};
}
firstUpdated(changedProperties) {
var app = this;
this.agent = new HelloAgent(this.name);
this.agent.receive = function(from, message) {
if (message.hasOwnProperty("action")){
switch(message.action) {
case "fileChanged":
// code block
console.log(message)
app.fileChanged(message.file)
break;
default:
// code block
console.log("Unknown action ",message)
}
}
};
}
render() {
return html`
<!-- <h1>${this.name}</h1>
uri ${this.file.uri}, type: ${this.file.type}-->
${this.file.uri != undefined ?
html`
<a href="${this.file.uri}" target="_blank">
<img src=${this.file.uri} style='border:5px solid lightgray;max-width:400;max-height=400'>
</a>
`
: html`<p> Here must show the image ${this.file.uri}</p>`
}
`;
}
fileChanged(file){
console.log(file)
this.file = file
}
} |
JavaScript | class Parameter extends Resolveable {
/**
* @type {string}
*/
name;
/**
* @type {*}
*/
value;
/**
* @param {string} name
* @param {*} value
*/
constructor(name, value) {
super();
this.name = name;
this.value = value;
}
/**
* @return {*}
*/
doResolve() {
return this.value;
}
} |
JavaScript | class Schedule {
static SCHEDULE_DAYS = ["Mo", "Tu", "We", "Th", "Fr"];
// hours indicate start (inclusive) of one hour block with exclusive end e.g. [8, 9) in ascending order
static SCHEDULE_HOURS = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
static SCHEDULE_DAY_DURATION =
Schedule.SCHEDULE_HOURS[Schedule.SCHEDULE_HOURS.length - 1] -
Schedule.SCHEDULE_HOURS[0];
/**
* Each sub array contains the `CourseSession`s for the corresponding entry in `SCHEDULE_DAYS`
* e.g. `dailySessions[1]` would return the `CourseSession`s on Tuesday
* Within each sub array, the `CourseSession`s are ordered by start time
* @type {Array<CourseSession[]>}
*/
dailySessions;
/**
* Array containing the selected CourseSessions matching data stored in dailySessions
* Allowing identification and tracing values to access department and level
* by matching the crn from a CourseSession to its CourseSection
* @type {Array<CourseSection>}
*/
selectedSections;
/**
* Array containing the selected Courses matching data stored in selectedSections
* Allowing identification and tracing values to access course title and professors
* by matching the department and level from a CourseSection to its Course
* @type {Array<Course>}
*/
selectedCourses;
/**
* Create a new `Schedule`
* Initializes `dailySessions,' 'selectedSections,' and 'selectedCourses'
*/
constructor() {
this.dailySessions = [];
this.selectedSections = [];
this.selectedCourses = [];
for (let d = 0; d < Schedule.SCHEDULE_DAYS.length; d++) {
this.dailySessions.push([]);
}
}
/**
* Returns the index that newCourseSession should be inserted at or `null` if there
* is a schedule conflict
* Assumes that `newCourseSession.time_start != newCourseSession.time_end`
* @param {CourseSession} newCourseSession
* @returns {number|null} the index to insert the new course session
* @throws Will throw error if `newCourseSession` conflicts with existing sessions
*/
getAddCourseSessionIndex(newCourseSession) {
if (!newCourseSession) {
console.warn(`Ignoring add null/undefined courseSession`);
} else if (
newCourseSession.day_of_week === undefined ||
newCourseSession.time_end === undefined ||
newCourseSession.time_start === undefined
) {
console.error(`
Cannot add courseSession with undefined values
${JSON.stringify(newCourseSession)}
`);
} else {
const daySessions = this.dailySessions[newCourseSession.day_of_week];
const numSessions = daySessions.length;
// If daySessions is empty, no conflicts
if (numSessions === 0) return 0;
// If session is after latest session, return last index
if (
newCourseSession.time_start >= daySessions[numSessions - 1].time_end &&
newCourseSession.time_end > daySessions[numSessions - 1].time_end
) {
return numSessions;
}
// Check courseSessions in the same day as newCourseSession for conflicts
for (let i = 0; i < daySessions.length; i++) {
let sess = daySessions[i];
// If newCourseSession time block is before sess time block return current index
if (
newCourseSession.time_end <= sess.time_start &&
newCourseSession.time_start < sess.time_start
) {
return i;
// If newCourseSession time block is after sess time block
} else if (
newCourseSession.time_start >= sess.time_end &&
newCourseSession.time_end > sess.time_end
) {
// Check next courseSession
continue;
// Otherwise there is a schedule conflict
} else {
console.error(`
Schedule conflict between
${JSON.stringify(newCourseSession)}
and ${JSON.stringify(sess)}
`);
throw {
type: "Schedule Conflict",
existingSession: sess,
addingSession: newCourseSession,
};
}
}
// Should be unreachable
return null;
}
}
/**
* Removes a `courseSession` from this schedule by iterating
* through `dailySessions`
* Definitely a better way to do this but this works for now
* @param {CourseSession} courseSession
* @returns {boolean} if course session was removed from schedule
*/
_removeCourseSession(courseSession) {
if (!courseSession) {
console.warn(`Ignoring remove null/undefined courseSession`);
} else {
let i = 0;
for (const sess of this.dailySessions[courseSession.day_of_week]) {
if (
sess.crn === courseSession.crn &&
sess.section === courseSession.section &&
sess.time_start === courseSession.time_start &&
sess.time_end === courseSession.time_end &&
sess.day_of_week === courseSession.day_of_week
) {
this.dailySessions[courseSession.day_of_week].splice(i, 1);
console.log(`Removed courseSession at index ${i}`);
return true;
}
i += 1;
}
// console.error(`Failed to remove could not find ${JSON.stringify(courseSession)}`);
return false;
}
}
/**
* Adds all the `CourseSession`s in `courseSection` to this schedule
* @param {CourseSection} courseSection
* @param {Course} course
* @param {number[]} [sessionIndices=null] If schedule conflict has already been checked, pass
* the resultant indices in to avoid rechecking
* @returns {boolean} if course section was added to schedule
* @throws Will throw error if `newCourseSession` conflicts with existing sessions
*/
addCourseSection(course, courseSection, sessionIndices = null) {
if (!courseSection) {
console.warn(`Ignoring add null/undefined courseSection`);
} else if (courseSection.sessions.length === 0) {
console.error(
`Cannot add courseSection with no sessions ${JSON.stringify(
courseSection
)}`
);
} else if (
!!sessionIndices &&
sessionIndices.length != courseSection.sessions.length
) {
console.warning(`Provided number of checked conflicts ${sessionIndices.length}
does not match number of sessions ${courseSection.sessions.length},
ignoring..`);
sessionIndices = null;
} else {
/**
* @private
* @typedef Addition
* @property {number} index
* @property {number} day
* @property {CourseSession} courseSession
*/
/**
* Keeps track of the courseSessions that will be added
* We need this in case we are inserting adjacent sessions
* @type {Addition[]}
*/
const additions = [];
// Check that there are no session conflicts in course section sessions
courseSection.sessions.forEach((courseSession, index) => {
let sessionIndex =
sessionIndices !== null
? sessionIndices[index] // If already checked for conflicts
: // use provided indices
this.getAddCourseSessionIndex(courseSession);
if (sessionIndex === null) {
// Should never happen
console.error(`Failed to add course section`);
return false;
} else {
additions.push({
index: sessionIndex,
day: courseSession.day_of_week,
courseSession,
});
}
});
console.log(`Additions before sort: ${JSON.stringify(additions)}`);
additions.sort((a1, a2) =>
a1.day === a2.day
? a1.day - a2.day
: a2.courseSession.time_start - a1.courseSession.time_start
);
console.log(`Additions after sort: ${JSON.stringify(additions)}`);
for (const { index, day, courseSession } of additions) {
this.dailySessions[day].splice(index, 0, courseSession);
// Allow for sessions to have a reference to their parent course
// but don't copy the sections so we avoid circular JSON (which will cause JSON.stringify to fail).
// Am giving a 'backpointer' so the ICS schedule can be easily built based on what sessions are
// currently selected / inserted.
// eslint-disable-next-line
// let courseInfo = (({sections, ...o}) => o)(course);
// courseSession.course = courseInfo;
courseSession._courseKey = course.id;
// courseSession._courseKey = this._getCourseIdentifier(course);
console.log(
`Inserted on day ${day} at index ${index} new courseSession ${JSON.stringify(
courseSession
)}`
);
}
this.selectedSections.push(courseSection);
console.log(`Added new courseSection ${JSON.stringify(courseSection)}`);
return true;
}
}
/**
* Remove all sessions in courseSection from schedule
* Does not check if individual course session removal succeeds
* @param {CourseSection} courseSection
*/
removeCourseSection(courseSection) {
if (!courseSection) {
console.warn(`Ignoring remove null/undefined courseSection`);
// } else if (courseSection.sessions.length === 0) {
// console.error(
// `Cannot remove courseSection with no sessions ${JSON.stringify(courseSection)}`
// );
} else {
for (const courseSession of courseSection.sessions) {
this._removeCourseSession(courseSession);
}
courseSection.selected = false;
var i;
for (i = 0; i < this.selectedSections.length; i++) {
if (this.selectedSections[i].selected == false) {
this.selectedSections.splice(i, 1);
}
}
}
}
/**
* Removes all sections of course and the course from tracking
* @param {Course} course
*/
removeCourse(course) {
if (!course) {
console.warn(`Ignoring remove null/undefined course`);
} else if (course.sections.length === 0) {
console.error(
`Cannot remove course with no sections ${JSON.stringify(course)}`
);
} else {
for (const section of course.sections) {
this.removeCourseSection(section);
}
var i;
for (i = 0; i < this.selectedCourses.length; i++) {
if (this.selectedCourses[i].selected == false) {
this.selectedCourses.splice(i, 1);
}
}
// console.log(this.selectedCourses.length);
}
}
/**
* Adds a course selected to internal storage for data retrieval in 'ScheduleEvent'
* @param {Course} course
*/
addCourse(course) {
if (!course) {
console.warn("Ignoring add null/undefined course");
} else {
this.selectedCourses.push(course);
}
}
} |
JavaScript | class FeatureImporter extends Importer {
/**
* Constructor.
* @param {IParser<T>} parser The parser
*/
constructor(parser) {
super(parser);
/**
* If HTML content should be trusted on imported data.
* @type {boolean}
* @protected
*/
this.trustHTML = false;
dispatcher.getInstance().listen(DataEventType.MAX_FEATURES, this.onMaxFeaturesReached_, false, this);
}
/**
* @inheritDoc
*/
disposeInternal() {
dispatcher.getInstance().unlisten(DataEventType.MAX_FEATURES, this.onMaxFeaturesReached_, false, this);
super.disposeInternal();
}
/**
* Get if imported HTML content should be trusted.
*
* @return {boolean} If imported HTML content should be trusted.
*/
getTrustHTML() {
return this.trustHTML;
}
/**
* Set if imported HTML content should be trusted.
*
* @param {boolean} value If imported HTML content should be trusted.
*/
setTrustHTML(value) {
this.trustHTML = value;
}
/**
* @inheritDoc
* @suppress {accessControls} For speed.
*/
addItemInternal(item) {
var feature;
if (item instanceof Feature) {
feature = /** @type {!Feature} */ (item);
}
if (feature) {
// make sure an id is set on the feature
if (!feature.id_) {
feature.setId(getUid(feature) + '');
} else {
// this works around inadvertant duplicate IDs, but maintains the original ID
var realId = feature.id_;
feature.setId(getUid(feature) + '');
// set the ID field only if it wasn't already set
if (feature.values_[Fields.ID] == null) {
feature.values_[Fields.ID] = realId;
}
}
// simplify the geometry if possible
simplifyGeometry(feature);
}
if (item) {
this.sanitize(item);
super.addItemInternal(item);
}
if (feature) {
// if our internal time field is set, but not a time instance, move it to an uppercased field to avoid conflicts
var time = feature.values_[RecordField.TIME];
if (time != null && !osImplements(time, ITime.ID)) {
feature.set(RecordField.TIME.toUpperCase(), time);
feature.set(RecordField.TIME, undefined);
}
feature.enableEvents();
}
}
/**
* @param {T} item The item
* @protected
* @suppress {accessControls}
*/
sanitize(item) {
var props = item.values_;
for (var key in props) {
var value = props[key];
if (typeof value === 'string' && needsSanitize.test(value)) {
// save the HTML description to its own property to control where it gets displayed
if (this.trustHTML && !props[RecordField.HTML_DESCRIPTION] && DESC_REGEXP.test(key)) {
props[RecordField.HTML_DESCRIPTION] = value;
}
try {
props[key] = sanitize(value).trim();
} catch (e) {
var msg = 'Could not sanitize value';
log.error(logger, msg);
props[key] = 'Error: ' + msg;
}
}
}
}
/**
* Listens for the max features reached event and stops all further processing
*
* @param {GoogEvent} event
* @private
*/
onMaxFeaturesReached_(event) {
this.reset();
}
} |
JavaScript | class App extends Component {
render() {
return (
<box top="center"
left="center"
width="80%"
height="80%"
border={{type: 'line'}}
style={{border: {fg: 'blue'}}}>
<Bar
label="Server Utilization (%)"
barWidth={4}
barSpacing={6}
xOffset={0}
maxHeight={9}
data={{
titles: ['bar1', 'bar2'],
data: [5, 10]
}}
/>
</box>
);
}
} |
JavaScript | class HelpRegistrar {
constructor() {
this.cache = {};
this.deferrals = [];
}
register(helpEntry) {
this.cache[helpEntry.name] = helpEntry;
}
registerAll(helpEntries) {
for (let entry of helpEntries) {
this.register(entry);
}
}
getHelpEntry(name) {
return this.cache[name];
}
getAllHelpEntries() {
return this.cache;
}
listEntries() {
const allEntries = this.cache;
Object.keys(allEntries)
.sort()
.filter((key) => {
return allEntries[key].isForClass();
})
.forEach((key) => {
const clazz = allEntries[key];
console.log(makeHeader(key));
clazz.children.forEach((child) => {
console.log(`• ${child.name}`);
});
});
}
displayEntry(key) {
const entry = this.getHelpEntry(key) || noHelpEntryFound(key);
entry.displayEntry();
}
/**
* defer - Defers parsing of help, etc. Useful for instances
* when we don't need to generate help. For example, when only using
* axus a unit test dependency.
*
* @param {type} builder description
* @return {type} description
*/
defer(builder) {
this.deferrals.push(builder);
}
processDeferrals() {
this.deferrals.forEach((deferral) => deferral.build());
}
} |
JavaScript | class ListNode {
constructor(value, next) {
this.value = value;
this.next = next;
}
/***
* @param {ListNode} startNode
* @param {function} callback
***/
forEach(callback) {
LinkedListUtils.forEach(this, callback);
}
toString() {
return `{
value: ${this.value},
next: ${this.next ? this.next.toString() : "null"}
} `;
}
} |
JavaScript | class LinkedListUtils {
constructor() {
throw new Error("LinkedList cannot be instantiated.");
}
/***
* Create linked list of ListNodes from an Array of values.
*
* @param {Array} values
* @return {ListNode}
***/
static fromValues(values) {
let head = new ListNode(values.shift());
let tail = head;
values.forEach((value) => {
tail.next = new ListNode(value);
tail = tail.next;
});
return head;
}
/***
* Create a linked list of ListNodes from a linked list of Objects.
*
* @return {ListNode}
***/
static fromObjects(headObject) {
let head = new ListNode(headObject.value);
let tail = head;
let tailObject = headObject.next;
while (tailObject) {
tail.next = new ListNode(tailObject.value);
tail = tail.next;
tailObject = tailObject.next;
}
return head;
}
/***
* Loops through each element of a linked list.
*
* @param {ListNode} head
* @param {function} callback
*
***/
static forEach(head, callback) {
LinkedListUtils.toArray(head).forEach(callback);
}
// static toString(head) {
// return JSON.stringify(head);
// }
/***
* @param {ListNode} head
* @return {Array<ListNode>}
***/
static toArray(head) {
const output = [];
let tail = head;
while (tail) {
output.push(tail);
tail = tail.next;
}
return output;
}
} |
JavaScript | class Store {
constructor(dbName = 'keyval-store', storeName = 'keyval') {
this.storeName = storeName;
this._dbp = new Promise((resolve, reject) => {
const idx = indexedDB || window.indexedDB;
const openreq = indexedDB.open(dbName, 1);
openreq.onerror = () => reject(openreq.error);
openreq.onsuccess = () => resolve(openreq.result);
// First time setup: create an empty object store
openreq.onupgradeneeded = () => {
openreq.result.createObjectStore(storeName);
};
});
}
_withIDBStore(type, callback) {
return this._dbp.then(db => new Promise((resolve, reject) => {
const transaction = db.transaction(this.storeName, type);
transaction.oncomplete = () => resolve();
transaction.onabort = transaction.onerror = () => reject(transaction.error);
callback(transaction.objectStore(this.storeName));
}));
}
} |
JavaScript | class CycloneQuaternion extends THREE.Quaternion {
get x() { return this._x; }
set x(v) { this.changed = (this.changed || v !== this._x); this._x = v; }
get y() { return this._y; }
set y(v) { this.changed = (this.changed || v !== this._y); this._y = v; }
get z() { return this._z; }
set z(v) { this.changed = (this.changed || v !== this._z); this._z = v; }
get w() { return this._w; }
set w(v) { this.changed = (this.changed || v !== this._w); this._w = v; }
copy(quat) {
this.changed = true;
return super.copy(quat);
}
set(x, y, z, w) {
this.changed = true;
return super.set(x, y, z, w);
}
setFromEuler(euler, update) {
this.changed = true;
return super.setFromEuler(euler, update);
}
setFromAxisAngle(axis, angle) {
this.changed = true;
return super.setFromAxisAngle(axis, angle);
}
setFromRotationMatrix(m) {
this.changed = true;
return super.setFromRotationMatrix(m);
}
setFromUnitVectors(v1, v2) {
this.changed = true;
return super.setFromUnitVectors(v1, v2);
}
reset() {
this.changed = false;
}
toJSON() {
return {x: this._x, y: this._y, z: this._z, w: this.w};
}
} |
JavaScript | class CloudinaryComponent extends Component {
constructor(props, context) {
super(props, context);
}
getChildContext() {
return {};
}
render() {
return null;
}
getChildTransformations(children) {
if(children === undefined || children === null) return null;
let mapped = React.Children.map(children, child =>{
if (!React.isValidElement(child)) {
// child is not an element (e.g. simple text)
return;
}
let options = {};
if (child.type && child.type.exposesProps){
options = CloudinaryComponent.normalizeOptions(child.props, child.context);
}
let childOptions = this.getChildTransformations(child.props.children);
if(childOptions !== undefined && childOptions !== null){
options.transformation = childOptions;
}
return options;
});
if(mapped != null){
return mapped.filter(o=>!Util.isEmpty(o));
} else return null;
}
/**
* Returns an object with all the transformation parameters based on the context and properties of this element
* and any children.
* @param options
* @returns {object} a hash of transformation and configuration parameters
* @protected
*/
getTransformation(options) {
var transformation;
if (this.props.children !== undefined) {
let childrenOptions = this.getChildTransformations(this.props.children);
if (!Util.isEmpty(childrenOptions)) {
transformation = childrenOptions;
return {...options, transformation};
}
}
return {...options};
}
/**
* Combine properties of all options to create an option Object that can be passed to Cloudinary methods.<br>
* `undefined` and `null` values are filtered out.
* @protected
* @returns {Object}
* @param options one or more options objects
*/
static normalizeOptions(...options) {
return options.reduce((left, right)=> {
for (let key in right) {
let value = right[key];
if (value !== null && value !== undefined) {
left[key] = value;
}
}
return left;
}
, {});
}
/**
* Generate a Cloudinary resource URL based on the options provided and child Transformation elements
* @param options
* @returns {string} a cloudinary URL
* @protected
*/
getUrl(options) {
let transformation = this.getTransformation(options);
let cl = Cloudinary.new(Util.withSnakeCaseKeys(options));
return cl.url(options.publicId, transformation);
}
} |
JavaScript | class Signature extends BaseModel {
constructor (args) {
super(args, schemas.SignatureSchema)
}
} |
JavaScript | class SchemaHelper {
/**
* Creates a new `SchemaHelper` instance.
* @param schema JSON schema to parse.
*/
constructor(schema) {
this.schema = schema;
this.property = this.createProperty(schema);
}
/**
* List of required property names.
*/
get required() {
return this.schema['required'] || [];
}
/**
* Returns the schema object for a given property path.
* @param path Path of the properties schema to return.
*/
pathToSchema(path) {
let property = undefined;
const segments = path.replace('[]', '').split('.');
if (segments.length > 0) {
property = this.property;
for (let i = 0; i < segments.length; i++) {
property = property.children.find((c) => c.name == segments[i]);
if (!property) {
break;
}
}
}
return property;
}
/**
* @private
*/
createProperty(schema, path = '') {
// Simplify array handling by collapsing to arrays sub-type
let type = schema['type'];
if (type == 'array') {
const items = schema['items'] || schema['contains'];
if (Array.isArray(items)) {
throw new Error(`${path} has an items array which is not supported`);
}
else if (typeof items == 'object') {
// Copy parent $ properties like $entities
for (const name in schema) {
if (schema.hasOwnProperty(name) && name.startsWith('$')) {
items[name] = schema[name];
}
}
schema = items;
type = schema['type'];
path += '[]';
}
else {
throw new Error(`${path} has an items array which is not supported`);
}
}
// Create child properties
const children = [];
if (type == 'object') {
const properties = schema['properties'] || {};
for (const name in properties) {
if (properties.hasOwnProperty(name) && !name.startsWith('$')) {
const newPath = path == '' ? name : `${path}.${name}`;
children.push(this.createProperty(properties[name], newPath));
}
}
}
return new propertySchema_1.PropertySchema(path, schema, children);
}
} |
JavaScript | class Eventing {
constructor() {
this.events = {};
}
/**
*
*/
on(name, handler) {
if (Object.prototype.hasOwnProperty.call(this.events, name)) {
this.events[name].push(handler);
} else {
this.events[name] = [handler];
}
}
/**
*
*/
off(name, handler) {
let index = -1;
/* This is a bit tricky, because how would you identify functions?
This simple solution should work if you pass THE SAME handler. */
if (!Object.prototype.hasOwnProperty.call(this.events, name)) {
return;
}
index = this.events[name].indexOf(handler);
if (index !== -1) {
this.events[name].splice(index, 1);
}
}
/**
*
*/
fireEvent(name, args) {
let i;
if (!Object.prototype.hasOwnProperty.call(this.events, name)) {
return;
}
/* if (!args || !args.length) {
logger.debug(' Firing Eventing on event :', name, args);
args = [];
} */
const evs = this.events[name];
const l = evs.length;
for (i = 0; i < l; i += 1) {
evs[i](name, args);
}
}
} |
JavaScript | class ModuleDispatcher {
/**
* @param {Object|null} settings — settings object, optional
* @param {Object} settings.Library — global object containing Modules
*/
constructor(settings = {}) {
this.Library = settings.Library || window;
/**
* Found modules list
* @type {Module[]}
*/
this.modules = this.findModules(document);
/**
* Now we are ready to init Modules
*/
this.initModules();
}
/**
* Return all modules inside the passed Element
*
* @param {Element} element — where to find modules
* @return {Module[]} found modules list
*/
findModules(element) {
/**
* Store found modules
* @type {Module[]}
*/
let modules = [];
/**
* Elements with data-module
* @type {NodeList}
*/
let elements = element.querySelectorAll('[data-module]');
/**
* Iterate found Elements and push them to the Modules list
*/
for (let i = elements.length - 1; i >= 0; i--) {
/**
* One Element can contain several Modules
* @type {Array}
*/
modules.push(...this.extractModulesData(elements[i]));
}
return modules;
}
/**
* Get all modules from an Element
*
* @example <div data-module="comments likes">
* @return {Module[]} - Array of Module objects with settings
*/
extractModulesData(element) {
let modules = [];
/**
* Get value of data-module attribute
*/
let modulesList = element.dataset.module;
/**
* In case of multiple spaces in modulesList replace with single ones
*/
modulesList = modulesList.replace(/\s+/, ' ');
/**
* One Element can contain several modules
* @example <div data-module="comments likes">
* @type {Array}
*/
let moduleNames = modulesList.split(' ');
moduleNames.forEach( (name, index) => {
let module = new Module({
name: name,
element: element,
settings: this.getModuleSettings(element, index, name),
moduleClass: this.Library[name]
});
modules.push(module);
});
return modules;
}
/**
* Returns Settings for the Module
*
* @param {object} element — HTML element with data-module attribute
* @param {Number} index - index of module (in case if an Element countains several modules)
* @param {String} name - Module's name
*
* @example
*
* <textarea name="module-settings" hidden>
* {
* // your module's settings
* }
* </textarea>
*
*/
getModuleSettings(element, index, name) {
let settingsNodes = element.querySelector('textarea[name="module-settings"]'),
settingsObject;
if (!settingsNodes) {
return null;
}
try {
settingsObject = settingsNodes.value.trim();
settingsObject = JSON.parse(settingsObject);
} catch(e) {
console.warn(`Can not parse Module «${name}» settings because of: ` + e);
console.groupCollapsed(name + ' settings');
console.log(settingsObject);
console.groupEnd();
return null;
}
/**
* Case 1:
*
* Single module, settings via object
*
* <textarea name="module-settings" hidden>
* {
* // Comments Module settings
* }
* </textarea>
*/
if (!Array.isArray(settingsObject)) {
if (index === 0) {
return settingsObject;
} else {
console.warn('Wrong settings format. For several Modules use an array instead of object.');
return null;
}
}
/**
* Case 2:
*
* Several modules, settings via array
*
* <textarea name="module-settings" hidden>
* [
* {
* // Module 1 settings
* },
* {
* // Module 2 settings
* },
* ...
* ]
* </textarea>
*/
if (settingsObject[index]) {
return settingsObject[index];
} else {
return null;
}
}
/**
* Initializes a list of Modules via calling {@link Module#init} for each
*/
initModules() {
console.groupCollapsed('ModuleDispatcher');
this.modules.forEach( module => {
module.init();
});
console.groupEnd();
}
} |
JavaScript | class HistoricoController {
async create(req, res) {
const { loggedUser } = req
const historico = await Historico.create({
...req.body,
user: loggedUser._id
})
return res.json(historico)
}
async list(req, res) {
const { loggedUser: user } = req
const historico = await Historico.find({ user })
return res.json(historico)
}
async find(req, res) {
const { loggedUser } = req
const { user } = req.params
const historico = await Historico.findOne(user)
console.log(user)
if (!historico) {
return res.status(404).json({ message: 'Credit Card not found' })
} else if (!historico.user.equals(loggedUser._id)) {
return res
.status(403)
.json({ error: 'Your are not authorized to access this record' })
}
return res.json(historico)
}
async update(req, res) {
const { id } = req.params
let historico = await Historico.findById(id)
historico = await Historico.findByIdAndUpdate(id, req.body, {
new: true,
})
}
} |
JavaScript | class Person{
constructor(name = "Anonymous", age = 0) {
this.name = name;
this.age = age;
}
getGreeting() {
if (this.name == "Slim Shady"){
return `Hi my name is what? My name is who? My name is chicka chicka ${this.name}`;
}
//return 'Hi my name is ' + this.name;
//Template string, better than concatenation
return `Hi my name is ${this.name}`; //Use backtick, next to 1 on keyboard
}
getDescription(){
return `${this.name} is ${this.age} year(s) old`;
}
} |
JavaScript | class GameObject {
constructor(pos = [10, 10], radians = 0, hitbox = { left: -5, top: -5, right: 5, bottom: 5 }) {
this.type = "gameobject";
this.category = "gameobject";
try {
this.pos = pos;
this.radians = radians;
this.hitbox = hitbox;
} catch (e) {
throw new Error("GameObject failed to construct due to: " + e.message);
}
}
set pos(pos) {
let temp;
if ((temp = typeof pos) !== "object") { //Make sure that pos is an array.
throw new Error("GameObject expected array for pos, but got " + temp + "!");
}
if (typeof(pos[0] + pos[1]) !== "number") { //Make sure that the two array values are numbers.
throw new Error("GameObject expected numbers for pos values, but got something different!");
}
this._pos = [pos[0], pos[1]]; //Set only the two array values we need. Ignore any that come after.
}
get pos() {
return this._pos;
}
set radians(radians) {
let temp;
if ((temp = typeof radians) !== "number") { //Make sure that radians is a number.
throw new Error("GameObject expected number for radians, but got " + temp + "!");
}
this._radians = radians; //Set the value; it is safe.
}
get radians() {
return this._radians;
}
set degrees(degrees) {
let temp;
if ((temp = typeof degrees) !== "number") {
throw new Error("GameObject expected number for degrees, but got " + temp + "!");
} else {
this._radians = (degrees / 180) * Math.PI;
}
}
get degrees() {
return (this._radians / Math.PI) * 180;
}
set hitbox(newHitbox) {
let temp;
//I'm starting to get really tired of writing formal comments like this.
//so im not going to bother anymore
if ((temp = typeof newHitbox) !== "object") { //fail if we aren't given an object. we shouldn't be given anything other than a object.
throw new Error("GameObject expected object for newHitbox, but got " + temp + "!");
}
if (typeof(newHitbox.left + newHitbox.top + newHitbox.right + newHitbox.bottom) !== "number") { //all the hitbox properties should be numbers. say 'fuck you' if they aren't numbers.
throw new Error("GameObject expected numbers for newBounds values, but got something else!");
}
this._hitBox = { //only set the four values we expect to use. don't do, for example, this.hitBox = hitBox. Then, anyone could add some 'foo' property that doesn't need to be there.
left: newHitbox.left,
top: newHitbox.top,
right: newHitbox.right,
bottom: newHitbox.bottom,
width: newHitbox.right - newHitbox.left, //Set width and height values that we might need later indirectly
height: newHitbox.bottom - newHitbox.top
};
}
get hitbox() {
return this._hitBox;
}
set world(world) {
let temp;
if ((temp = typeof world) !== "object") { //throw an error if world isn't an object
throw new Error("GameObject expected object for world, but got " + temp + "!");
}
if ((temp = world.category) !== "world") { //throw an error if world isn't a world. we're using category because the world might have a more specific type, like 'system' or 'pocket-dimension'
throw new Error("GameObject expected object of category 'world' for world, but got '" + temp + "'!");
}
if (this.world) { //remove this object from its previous world, if it had one.
this.world.removeObject(this.world.objects.indexOf(this));
}
this._world = world; //set the new world value
}
get world() {
return this._world;
}
update(dt) { //A basic GameObject doesn't bother updating, but this is meant to be redefined for any children of this class.
}
draw(ctx, rel) { //A default draw function. this will be called by the camera.
ctx.fillStyle = "green";
ctx.strokeStyle = "black";
ctx.save(); //Save the context since we are going to translate and rotate it.
ctx.translate(rel[0], rel[1]);
ctx.rotate(this.radians);
ctx.beginPath();
ctx.rect(this.hitBox.left, this.hitBox.top, this.hitBox.width, this.hitBox.height); //We should be at [0, 0] so just define the rectangle by the hitbox values.
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.restore(); //Restore the context.
}
} |
JavaScript | class World {
constructor() {
this.type = "world"; //This is a world.
this.category = "world"; //In broader terms, this is a world.
this.objects = []; //The array that will hold our objects.
}
set type(type) {
let temp;
if ((temp = typeof type) !== "string") { //Make sure type is a string.
throw new Error("World expected string for type, but got " + temp + "!");
}
this._type = type;
}
get type() {
return this._type;
}
set category(category) {
let temp;
if ((temp = typeof category) !== "string") { //Make sure category is a string.
throw new Error("World expected string for category, but got " + temp + "!");
}
this._category = category;
}
get category() {
return this._category;
}
set objects(objects) {
this._objects = objects;
}
get objects() {
return this._objects;
}
addObject(object) {
let temp;
if ((temp = typeof object) !== "object") {
throw new Error("World.addObject expected object but got " + temp + "!");
}
temp = this.objects.length;
object.world = this;
this.objects.push(object);
return temp;
}
moveObject(oldIndex, newIndex) {
if (typeof(oldIndex + newIndex) === "number") { //Make sure that oldIndex and newIndex are both numbers.
if (newIndex >= this.objects.length) { //I copied this chunk off StackOverflow, so I don't really knw how it works.
temp = newIndex - this.objects.length + 1; //But it is meant to move the item at oldIndex to newIndex, and create undefined values if newIndex is beyond the length of the array.
while (temp--) {
this.objects.push(undefined);
}
}
this.objects.splice(newIndex, 0, this.objects.splice(oldIndex, 1)[0]);
} else {
throw new Error("World.moveObject did not get numbers for both of its parameters!"); //Throw an error if we weren't given numbers.
}
}
deleteObject(index, quiet = false) {
let temp;
if ((temp = typeof index) === "number") { //Make sure we were given a number.
if (index > -1) {
this.objects[index].delete((typeof quiet === "boolean" ? quiet : false)); //Call a delete function for the object in case it has any cleaning up it needs to do.
//Quiet tells the object whether it should make its deletion known (e.g. explosion particles)
this.objects.splice(index, 1); //Do the actual removal.
} else {
throw new Error("World.deleteObject got a negative number for index!"); //Throw an error if index is negative (can't have a negative index, or access one for that matter.)
}
} else {
throw new Error("World.deleteObject expected number but got " + temp + "!"); //Throw an error if not given a number.
}
}
update(dt) {
this.objects.forEach(function(e) {
e.update(dt);
});
}
} |
JavaScript | class Canvas {
constructor(id, width = 400, height = 200) {
this.type = "canvas"; //This is a canvas.
this.category = "canvas"; //In broader terms, this is a canvas.
try { //Try to set our properties.
this.id = id;
this.width = width;
this.height = height;
} catch (e) { //Give up and throw an error if something failed.
throw new Error("Canvas failed to construct due to: " + e.message);
}
}
set id(id) {
let temp;
if ((temp = typeof id) !== "string") { //Make sure id is a string.
throw new Error("Canvas expected string for id, but got " + temp + "!");
}
if ((temp = document.getElementById(id)) === undefined) { //Make sure that id indeed points us to an element that exists.
throw new Error("Canvas got undefined for element with id '" + id + "'! Did you mistype the id?");
}
if (temp.tagName !== "CANVAS") { //Make sure that the element we are being pointed to is a canvas.
throw new Error("Canvas got '" + temp.tagName + "' for element with id '" + id + "'! Did you give the wrong id?");
}
this._el = temp; //id is safe, so set the el property based on the id.
this._ctx = this._el.getContext("2d"); //Get the context from the element.
this._id = id; //Set the id as well.
}
get id() {
return this._id;
}
set el(el) {
return false;
}
get el() {
return this._el;
}
set ctx(ctx) {
return false;
}
get ctx() {
return this._ctx;
}
set width(width) {
let temp;
if ((temp = typeof width) !== "number") { //Make sure width is a number.
throw new Error("Canvas expected number for width, but got " + temp + "!");
}
if (width < 0) { //Don't let the width be negative.
throw new Error("Canvas cannot have negative width!");
}
this._el.width = width;
this._width = width;
}
get width() {
return this._width;
}
set height(height) {
let temp;
if ((temp = typeof height) !== "number") { //Make sure height is a number.
throw new Error("Canvas expected number for height, but got " + temp + "!");
}
if (height < 0) { //Don't let the height be negative.
throw new Error("Canvas cannot have negative height!");
}
this._el.height = height;
this._height = height;
}
get height() {
return this._height;
}
set type(type) {
let temp;
if ((temp = typeof type) !== "string") { //Make sure type is a string.
throw new Error("Canvas expected string for type, but got " + temp + "!");
}
this._type = type;
}
get type() {
return this._type;
}
set category(category) {
let temp;
if ((temp = typeof category) !== "string") { //Make sure category is a string.
throw new Error("Canvas expected string for category, but got " + temp + "!");
}
this._category = category;
}
get category() {
return this._category;
}
} |
JavaScript | class Camera {
constructor(target, bounds, source, pos, scale = [1, 1]) {
this.type = "camera"; //This is a camera.
this.category = "camera"; //In broader terms, this is a camera.
try { //Try to set our properties.
this.target = target;
this.bounds = bounds;
this.source = source;
this.pos = pos;
this.scale = scale;
} catch (e) { //Give up and throw an error if something failed.
throw new Error("Camera failed to construct due to: " + e.message);
}
}
set target(target) {
let temp;
if ((temp = typeof target) !== "object") { //Make sure target is an object.
throw new Error("Camera expected object for target, but got " + temp + "!");
}
if ((temp = target.type) !== "canvas") { //Make sure target is of type 'canvas'.
throw new Error("Camera expected object of type 'canvas' for target, but got '" + temp + "'!");
}
this._target = target; //Tests passed, so the value should be safe. Set it.
}
get target() {
return this._target;
}
set bounds(newBounds) {
let temp;
if ((temp = typeof newBounds) !== "object") { //Make sure newBounds is an object.
throw new Error("Camera expected object for newBounds, but got " + temp + "!");
}
if (typeof(newBounds.left + newBounds.top + newBounds.right + newBounds.bottom) !== "number") { //Make sure that the four important values are all numbers.
throw new Error("Camera expected numbers for newBounds values, but was given something different!");
}
if (newBounds.right - newBounds.left < 0) { //Make sure we don't end up with a camera with negative width.
throw new Error("Camera will have negative width!");
}
if (newBounds.bottom - newBounds.top < 0) { //Make sure we don't end up with a camera with negative height.
throw new Error("Camera will have negative height!");
}
//Tests passed, so the value should be safe. Set it.
this._bounds = { //Only set the six values that bounds is supposed to have. If we're given some newBounds.bar for example, don't set that because it shouldn't be there. Also indirectly set a width and height value.
left: newBounds.left,
top: newBounds.top,
right: newBounds.right,
bottom: newBounds.bottom,
width: newBounds.right - newBounds.left,
height: newBounds.bottom - newBounds.top
};
}
get bounds() {
return this._bounds;
}
set source(source) {
let temp;
if ((temp = typeof source) !== "object") { //Make sure that source is an object.
throw new Error("Camera expected object for source, but got " + temp + "!");
}
if ((temp = source.category) !== "world") { //Make sure that source is of category 'world'. we're using category because the world might have a more specific type, like 'system' or 'pocket-dimension'
throw new Error("Camera expected object of category 'world' for source, but got '" + temp + "'!");
}
this._source = source; //Tests passed, so the value should be safe. Set it.
}
get source() {
return this._source;
}
set pos(pos) {
let temp;
if ((temp = typeof pos) !== "object") { //Make sure pos is an array.
throw new Error("Camera expected array for pos, but got " + temp + "!");
}
if (typeof(pos[0] + pos[1]) !== "number") { //Make sure that the two coordinates are numbers.
throw new Error("Camera expected numbers for pos values, but was given something different!");
}
//Tests passed, so the value must be safe. Set it.
this._pos = [pos[0], pos[1]]; //Only set pos with two indices. If the pos we were given had more than two, ignore them.
}
get pos() {
return this._pos;
}
set scale(scale) {
let temp;
if ((temp = typeof scale) !== "object") { //Make sure scale is an array.
throw new Error("Camera expected array for scale, but got " + temp + "!");
}
if (typeof(scale[0] + scale[1]) !== "number") { //Make sure that the two values are numbers.
throw new Error("Camera expected numbers for scale values, but was given something different!");
}
//Tests passed, so the value must be safe. Set it.
this._scale = [scale[0], scale[1]]; //Only set scale with two indices. If the scale we were given had more than two, ignore them.
}
get scale() {
return this._scale;
}
set background(background) {
let temp;
if ((temp = typeof background) !== "string") { //Make sure background is a string.
throw new Error("Camera expected string for background, but got " + temp + "!");
}
this._background = background; //We aren't very sure that background is safe, since we are too lazy to check that it is a hex, rgb, or other color value that Context will recognize. But let's use it anyway.
}
get background() {
return this._background;
}
set stroke(stroke) {
let temp;
if ((temp = typeof stroke) !== "string") { //Make sure stroke is a string.
throw new Error("Camera expected string for stroke, but got " + temp + "!");
}
this._stroke = stroke; //We aren't very sure that stroke is safe, since we are too lazy to check that it is a hex, rgb, or other color value that Context will recognize. But let's use it anyway.
}
get stroke() {
return this._stroke;
}
set lineWidth(lineWidth) {
let temp;
if ((temp = typeof lineWidth) !== "number") { //Make sure lineWidth is a number.
throw new Error("Camera expected number for lineWidth, but got " + temp + "!");
}
if (lineWidth < 0) {
throw new Error("Camera was given a negative number for new lineWidth!");
}
this._lineWidth = lineWidth;
}
get lineWidth() {
return this._lineWidth;
}
set type(type) {
let temp;
if ((temp = typeof type) !== "string") { //Make sure type is a string.
throw new Error("Camera expected string for type, but got " + temp + "!");
}
this._type = type;
}
get type() {
return this._type;
}
set category(category) {
let temp;
if ((temp = typeof category) !== "string") { //Make sure category is a string.
throw new Error("Camera expected string for category, but got " + temp + "!");
}
this._category = category;
}
get category() {
return this._category;
}
beforeDraw(ctx) { //Called by draw() before the main target.forEach loop. By default it is used to draw a background and outline for the camera. Anything drawn here will be drawn over by draw() and drawAfter().
if (this.background) {
ctx.fillStyle = this.background; //Fill a background if this camera is given a background color.
ctx.fillRect(this.bounds.left, this.bounds.top, this.bounds.width, this.bounds.height);
}
if (this.stroke) {
ctx.strokeStyle = this.stroke; //Draw an outline if this camera is given an outline color.
if (this.lineWidth) { //Change the stroke width if this camera has a specific one set.
ctx.lineWidth = this.lineWidth;
} else {
ctx.lineWidth = 1;
}
ctx.strokeRect(this.bounds.left, this.bounds.top, this.bounds.width, this.bounds.height);
}
}
afterDraw(ctx) { //Called by draw() after the main target.forEach loop. Empty by default. Anything drawn here will draw over draw() and beforeDraw(). Use this for overlays, crosshairs, etc.
}
draw() { //Called by a draw loop.
let ctx = this.target.ctx,
pos = this.pos,
bounds = this.bounds,
scale = this.scale;
this.beforeDraw(ctx);
ctx.beginPath();
ctx.save(); //Save the context since we're going to clip and possibly scale it.
ctx.rect(bounds.left, bounds.top, bounds.width, bounds.height);
ctx.clip(); //Clip the context so that nothing is drawn past the bounds of this camera.
if (scale !== [1, 1]) { //If we are drawing at any scale other than [1, 1], then set it.
ctx.scale(scale[0], scale[1]);
}
this.source.objects.forEach(function(e) { //Call draw() for every object in the world this camera is drawing.
e.draw(ctx, [e.pos[0] - pos[0] + bounds.left / scale[0], e.pos[1] - pos[1] + bounds.top / scale[1]]);
//Every object expects what context it is drawing on, and its position on that context.
});
ctx.restore(); //Restore the context.
ctx.closePath();
this.afterDraw(ctx);
}
} |
JavaScript | class afPaginate {
constructor (config) {
// when two tables are displayed inside the same page
this.idprefix = config.idprefix || (Math.random () + '').split('.').pop().substring(0, 4);
this.debug = config.debug || false;
this.table = config.table; // table div selector
// headers
this.column_aliases = {};
this.headers = [];
this.should_hide = {};
this.pretty_headers = false;
this.event_headers_datas = {}; // will contain useful information such as the current switch state
this.last_sorted_header = [];
if (config.headers) {
this.column_aliases = config.headers.rename || this.column_aliases;
this.pretty_headers = config.headers.pretty || this.pretty_headers;
if (config.headers.hidden) {
for (let name of config.headers.hidden)
this.should_hide[name] = true;
}
}
this.datas = config.datas || [];
// search
this.enable_search = false;
this.search_inputs_datas = [];
this.disable_for = [];
if (config.search) {
this.button_search_id = config.search.button;
this.enable_search = config.search.enable || this.enable_search;
this.disable_for = config.search.disable_for || this.disable_for;
}
// pagination
this.pagination = config.pagination; // pagination div selector
this.page = { current : 1, total : 1 };
if (config.page) {
this.page.current = config.page.current || page.current;
this.page.total = config.page.total || page.total;
}
// templates
this.header_template = '<th id="@id">@content</th>';
this.body_template = '<td id="@id">@content</td>';
this.pagination_template = `<button id="@prevId">Prev</button>
@currentPage/@totalPage
<button id="@nextId">Next</button>`;
this.search_template = `<td><input type="text" placeholder="@placeholder" id="@id"></td>`;
this.disabled_search_template = `<td style='color:gray'>@key</td>`;
if (config.template) {
this.header_template = config.template.header || this.header_template;
this.body_template = config.template.body || this.body_template;
this.pagination_template = config.template.pagination || this.pagination_template;
this.search_template = config.template.search || this.search_template;
this.disabled_search_template = config.template.disabled_search || this.disabled_search_template;
}
this.rendered_once = false;
}
/**
* @params {string} str
*/
infos (str) {
if (this.debug) console.log (str);
}
/**
* Called when we want to run the engine
* @params {Function} fun
*/
async run (fun) {
this.infos ('--- engine start ---');
fun (this);
}
whenSearch (fun) {
this.whenSearchCallback = fun;
}
whenRow (fun) {
this.whenRowCallback = fun;
}
whenHeader (fun) {
this.whenHeaderCallback = fun;
}
whenHeaderClicked (fun) {
this.whenHeaderClickedCallback = fun;
}
// pagination
whenPagePrev (fun) {
this.whenPagePrevCallback = fun;
}
whenPageNext (fun) {
this.whenPageNextCallback = fun;
}
/**
* Initializes the header content
*/
initHeaders () {
if (this.headers.length == 0) {
if (this.datas.length != 0)
this.headers = Object.keys(this.datas[0]);
}
}
/**
* @params {string} key
*/
buildRowId (key, r, c) {
return `${this.idprefix}_${key}_${r}_${c}`;
}
/**
* @params {string} key
*/
buildHeaderId (key) {
return `${this.idprefix}_${key}`;
}
/**
* @params {string} key
*/
buildInputId (key) {
return `${this.idprefix}_input_${key}`;
}
/**
* Renders the table
* @params {boolean?} force_render
*/
async render (force_render) {
this.infos ('--- rendering ---')
this.initHeaders ();
if (force_render)
this.rendered_once = false; // reinitializes the event datas
// headers AND search inputs
let th_headers = [], search_inputs = [], useful_header_infos = [];
for (let header of this.headers) {
if (this.should_hide[header]) continue;
const header_name = this.column_aliases[header] || this.makePretty(header);
const header_id = this.buildHeaderId(header);
useful_header_infos.push({ name : header, id : header_id }); // useful for later
if ( !this.rendered_once ) {
this.event_headers_datas[header] = false;
this.last_sorted_header = [this.headers[0], false];
}
// headers
const str = this.feedTemplate (this.header_template, {
id : header_id,
content : header_name
});
th_headers.push(str);
// search inputs
if (this.enable_search) {
const input_id = this.buildInputId(header);
if (this.disable_for.includes(header)) {
search_inputs.push(this.feedTemplate(this.disabled_search_template, {
key : header
}));
} else {
search_inputs.push(this.feedTemplate(this.search_template, {
placeholder : header_name,
id : input_id,
key : header // probably useful
}));
this.search_inputs_datas.push({ id : input_id, name : header});
}
}
}
// additionnal header
if (this.whenHeaderCallback)
await this.whenHeaderCallback (this, th_headers);
// body
let td_rows = [], i = 0, j = 0;
for (let row of this.datas) {
let curr_row = [];
for (let key in row) {
if (this.should_hide[key]) continue;
const str = this.feedTemplate (this.body_template, {
id : this.buildRowId(key, i, j),
content : row[key]
});
curr_row.push(str);
j++;
}
// additionnal row
if (this.whenRowCallback)
await this.whenRowCallback(this, curr_row, row, i);
td_rows.push (curr_row);
i++;
}
// renders it
$(this.table).html (
this.makeStringUsing(th_headers, search_inputs, td_rows)
);
// events
for (let header of useful_header_infos) {
$('#' + header.id).click(async () => {
for (let key in this.event_headers_datas) {
if (key == header.name) {
this.event_headers_datas[key] = ! this.event_headers_datas[key] ;
this.last_sorted_header = [key, this.event_headers_datas[key]];
} else {
this.event_headers_datas[key] = false;
}
}
const curr_state = this.event_headers_datas[header.name];
if (this.whenHeaderClickedCallback)
await this.whenHeaderClickedCallback (this, header.name, curr_state, header.id);
this.infos (`-- header name = ${header.name}, id=${header.id}, state = ${curr_state} clicked --`);
});
}
if (!this.rendered_once) {
// since the btn is not going to be rendered again, we should avoid attaching it to another event
$(this.button_search_id).click(async () => {
const inputs_values = {};
for (let {id, name} of this.search_inputs_datas)
inputs_values[name] = $('#' + id).val();
this.infos ('-- fetch:inputs ' + JSON.stringify(inputs_values) + ' --' )
if (this.whenSearchCallback)
await this.whenSearchCallback (this, inputs_values, this.last_sorted_header);
});
}
// prev, next
this.buildPaginateControls ();
this.rendered_once = true;
}
buildPaginateControls () {
const template = this.pagination_template;
const variables = {
prevId : this.idprefix + '_prev',
nextId : this.idprefix + '_next',
currentPage : this.page.current,
totalPage : this.page.total
};
// render
$(this.pagination).html(
this.feedTemplate (template, variables)
);
// events
$('#' + variables.prevId).click(async () => {
if (this.whenPagePrevCallback)
await this.whenPagePrevCallback (this, this.page, this.last_sorted_header);
});
$('#' + variables.nextId).click(async () => {
if (this.whenPageNextCallback)
await this.whenPageNextCallback (this, this.page, this.last_sorted_header);
});
}
/**
* Builds a string given an array of header and rows
* @protected
* @params {string[]} headers
* @params {string[][]} rows
*/
makeStringUsing (headers, search_inputs, rows) {
let html = `<tr>${headers.join('')}</tr>`;
if (this.enable_search)
html += `<tr>${search_inputs.join('')}/tr>`;
html += rows.map(row => {
return `<tr>${row.join('')}</tr>`
}).join('');
return html;
}
/**
* Feeds a template
* A variable looks like this "@foo_bar"
* @params {string} template_str
* @params {JSON[]} var_map
*/
feedTemplate (template_str, var_map) {
return template_str.replace(/@([0-9A-Za-z_]+)?/g, token => {
// const res = var_map[RegExp.$1]; // doesnt work on chrome
const res = var_map[token.substr(1)];
return res || token; // render if the token has a key
});
}
/**
* Trim and prettify
* Ex : "something__ Good" => Something Good
* @params {string} str
*/
makePretty (str) {
return str.split(/[ _]+/g).map(item => {
if (item.length == 0) return item;
let str = item[0].toUpperCase();
if (item.length > 1)
str += item.substr(1).toLowerCase ();
return str;
}).join(' ');
}
/**
* @returns {JSON} search inputs values
*/
getInputsValue () {
return {'wawa' : 'lala', 'mama' : 'foo'};
}
} |
JavaScript | class Cache {
constructor(basePath) {
this.basePath = path.resolve(basePath);
mkdirp.sync(this.basePath);
}
get(cachePath) {
const resolved = path.resolve(this.basePath, cachePath);
return common_1.readJSON(resolved).catch(_err => {
// gracefully handle corruptions
});
}
async set(cachePath, value) {
const resolved = path.resolve(this.basePath, cachePath);
if (path.relative(this.basePath, resolved).indexOf(path.sep) !== -1)
await new Promise((resolve, reject) => mkdirp(path.dirname(resolved), err => err ? reject(err) : resolve()));
await new Promise((resolve, reject) => fs.writeFile(resolved, JSON.stringify(value), err => err ? reject(err) : resolve()));
}
async setUnlock(cachePath, value) {
const resolved = path.resolve(this.basePath, cachePath);
if (path.relative(this.basePath, resolved).indexOf(path.sep) !== -1)
await new Promise((resolve, reject) => mkdirp(path.dirname(resolved), err => err ? reject(err) : resolve()));
await new Promise((resolve, reject) => fs.writeFile(resolved, JSON.stringify(value), err => err ? reject(err) : resolve()));
await new Promise((resolve, reject) => lockfile.unlock(resolved, {
realpath: false
}, err => err ? reject(err) : resolve()));
}
async del(cachePath) {
const resolved = path.resolve(this.basePath, cachePath);
await new Promise((resolve, reject) => fs.unlink(resolved, err => err ? reject(err) : resolve()));
}
async lock(cachePath, timeout = 3000) {
const resolved = path.resolve(this.basePath, cachePath);
await new Promise((resolve, reject) => mkdirp(path.dirname(resolved), err => err ? reject(err) : resolve()));
const unlock = await new Promise((resolve, reject) => lockfile.lock(resolved, {
// exponential backoff of 5 checks from 200ms up to 3s
// followed by a constant timeout check of 3 seconds
// to an absolute maximum of the given timeout
realpath: false,
retries: {
retries: 2 + Math.floor(timeout / 3000),
factor: 1.5707,
minTimeout: 200,
maxTimeout: 3000
}
}, (err, unlock) => err ? reject(err) : resolve(unlock)));
return () => {
return new Promise((resolve, reject) => unlock(err => err ? reject(err) : resolve()));
};
}
// get, but only if unlocked, waiting on unlock
// in fs terms between instances for specific unused scenarios this can be racy on a small margin,
// if a get applies after a promise, ensure any corresponding locked sets itself to be idempotently accessible
async getUnlocked(cachePath, timeout = 3000) {
const resolved = path.resolve(this.basePath, cachePath);
await promiseRetry(async (retry) => {
const locked = await new Promise((resolve, reject) => lockfile.check(resolved, { realpath: false }, (err, locked) => err ? reject(err) : resolve(locked)));
if (locked)
retry(new Error(`Operation timeout.`));
}, {
retries: 2 + Math.floor(timeout / 3000),
factor: 1.5707,
minTimeout: 200,
maxTimeout: 3000
});
return this.get(resolved);
}
// get, waiting on any lock, locking,
// creating and then unlocking if not existing
async getOrCreate(path, timeout = 3, createTask) {
let result = await this.getUnlocked(path, timeout);
if (result)
return result;
let unlock = await this.lock(path, timeout);
// could have been beaten to the lock
result = await this.getUnlocked(path, timeout);
if (result)
return result;
let timer;
let timeoutPromise = new Promise((_resolve, reject) => {
timer = setTimeout(() => reject(new common_1.JspmError('Operation timeout.')));
});
try {
let value = await Promise.race([timeoutPromise, createTask()]);
clearTimeout(timer);
this.set(path, value);
return value;
}
finally {
unlock();
}
}
} |
JavaScript | class SdmxOutput extends BaseOutput {
write(metadata, outputFile) {
outputFile = this.getFilename(metadata, outputFile)
const descriptors = metadata.getDescriptors()
const concepts = metadata.getConcepts()
const conceptIds = Object.keys(concepts)
const language = this.getLanguage(descriptors)
const reportingType = descriptors['REPORTING_TYPE']
const refArea = descriptors['REF_AREA']
const dataflowId = this.getDataflowId(descriptors)
let serieses = descriptors['SERIES']
if (!Array.isArray(serieses)) {
serieses = [serieses]
}
const namespaces = {
mes: 'http://www.sdmx.org/resources/sdmxml/schemas/v2_1/message',
com: 'http://www.sdmx.org/resources/sdmxml/schemas/v2_1/common',
gen: 'http://www.sdmx.org/resources/sdmxml/schemas/v2_1/metadata/generic',
str: 'http://www.sdmx.org/resources/sdmxml/schemas/v2_1/structure',
}
const sdmxDsd = metadata.getValue('sdmx_dsd')
let dsdVersion = '1.0'
if (sdmxDsd) {
const doc = new dom().parseFromString(sdmxDsd)
const select = xpath.useNamespaces(namespaces)
try {
dsdVersion = select('//str:DataStructures/str:DataStructure', doc)[0].getAttribute('version')
}
catch (e) {
metadata.addMessage('WARNING: Unable to get version of SDMX DSD. Assume 1.0.')
}
}
const obj = {
'mes:GenericMetadata': {
'@xmlns:mes': namespaces.mes,
'@xmlns:gen': namespaces.gen,
'@xmlns:com': namespaces.com,
'mes:Header': {
'mes:ID': this.generateMessageId(),
'mes:Test': 'false',
'mes:Prepared': new Date().toISOString(),
'mes:Sender': { '@id': 'sender' },
'mes:Structure': {
'@structureID': 'MDS1',
'com:Structure@@com': {
'URN': 'urn:sdmx:org.sdmx.infomodel.metadatastructure.MetadataStructure=IAEG-SDGs:SDG_MSD(0.3)',
}
}
},
'mes:MetadataSet': serieses.map(series => {
return {
'@structureRef': 'MDS1',
'@setID': this.generateSetId(),
'com:Name@@com': {
'@xml:lang': language,
'#': 'SDG METADATA SET',
},
'gen:Report@@gen': {
'@id': 'SDG_META_RPT',
'gen:Target': {
'@id': 'KEY_TARGET',
'gen:ReferenceValue': [
{
'@id': 'DIMENSION_DESCRIPTOR_VALUES_TARGET',
'gen:DataKey': {
'com:KeyValue@@com': [
{
'@id': 'SERIES',
'com:Value': series
},
{
'@id': 'REPORTING_TYPE',
'com:Value': reportingType,
},
{
'@id': 'REF_AREA',
'com:Value': refArea,
}
]
}
},
{
'@id': 'Dataflow',
'gen:ObjectReference': {
'URN': 'urn:sdmx:org.sdmx.infomodel.datastructure.Dataflow=IAEG-SDGs:' + dataflowId + '(' + dsdVersion + ')'
}
}
]
},
'gen:AttributeSet': {
'gen:ReportedAttribute': conceptIds.map(id => {
return {
'@id': id,
'com:Text@@com': {
'@xml:lang': language,
'$': concepts[id],
}
}
})
}
},
}
})
}
}
const doc = create({ namespaceAlias: namespaces }).ele(obj).dec({ 'encoding': 'utf-8'})
const xml = doc.end({ prettyPrint: true })
return this.writeFile(outputFile, xml, metadata)
}
generateMessageId() {
// @TODO: Decide on requirements for this id.
return 'MESSAGE_ID_PLACEHOLDER'
}
generateSetId() {
return uuidv4()
}
getDataflowId(descriptors) {
return descriptors['REPORTING_TYPE'] === 'G' ? 'DF_SDG_GLH' : 'DF_SDG_GLC'
}
getFilenameExtension() {
return 'xml'
}
} |
JavaScript | class linksTransformer {
constructor(links) {
this.links = links
}
async element(element) {
links.forEach(link => {
element.append(`<a href="${link.url}">${link.name}</a>`, { html: true });
})
}
} |
JavaScript | class GoogleAnalytics extends Component {
componentDidMount () {
this.logPageChange(
this.props.location.pathname,
this.props.location.search
);
}
componentDidUpdate ({ location: prevLocation }) {
const { location: { pathname, search } } = this.props;
const isDifferentPathname = pathname !== prevLocation.pathname;
const isDifferentSearch = search !== prevLocation.search;
if (isDifferentPathname || isDifferentSearch) {
this.logPageChange(pathname, search);
}
}
logPageChange (pathname, search = '') {
const page = pathname + search;
const { location } = window;
ReactGA.set({
page,
location: `${location.origin}${page}`,
...this.props.options
});
ReactGA.pageview(page);
}
render () {
return null;
}
} |
JavaScript | class OnceJob extends Job {
/**
* @param {OnceJobConfig} jobConfig
* @param {JobExecutor} executor
*/
constructor(jobConfig, executor) {
super(jobConfig, executor);
}
run() {
super.run().then(() => this._hasRun = true);
}
/**
* Returns the time (ms) until the next job of this id should run.
* @returns {number}
* @private
*/
get nextRun() {
// TODO POSITIVE_INFINITY will cause setTimeout to be triggered immediately (not a problem right now since this method is called only once, but also not very clean)
return this._hasRun ? Number.POSITIVE_INFINITY : super.nextRun;
}
} |
JavaScript | class Students extends React.PureComponent {
// Construstor for states and components.
constructor(props) {
super(props);
this.getStudentsData(); // When component first render it calld the function getStudentsData().
// initialize states needed
this.state = {
studentsList: [],
gradeLevel: this.props.match.params.gradeLevel,
sectionName: this.props.match.params.sectionName,
sectionID: this.props.match.params.sectionID,
studentIDToDelete: '',
studentIDToEdit: '',
open: false,
modalIsOpen: false,
modalEditIsOpen: false,
firstName: '',
lastName: '',
};
}
// When comoponent mounts render component Modal for dialogs
componentWillMount() {
Modal.setAppElement('body');
}
// Function handles when an input is change in an HTML component <TextField>.
handleInputChange = e => {
// If user types into <TextField>, then get input according to the name of the HTML tag and the value.
this.setState({
[e.target.name]: e.target.value,
});
};
// Function onClick open the Dialog to ADD a NEW Student to the current section.
handleClickOpen = () => {
// reset states to default.
this.setState({
open: true,
firstName: '',
lastName: '',
});
};
// Function onClose close the Dialog to ADD a NEW Student to the current section.
handleClose = () => {
this.setState({ open: false });
};
// Function onClick open the Dialog to DELETE a current studen based on user's input.
openModal = record => {
// Change state variables of sectionID and name in order to know what section needs to be deleted from database.
this.setState({
modalIsOpen: true,
studentIDToDelete: record.id,
firstName: record.first,
lastName: record.last,
});
};
// Function onClose close the Dialog to DELETE a current student based users input.
closeModal = () => {
this.setState({ modalIsOpen: false });
};
// Function onClick open the Dialog to EDIT a current student based on user input.
openModalEdit = record => {
// Change state variables of studentID, first name, last name accroding to user's input
// in order for the application to know what student is being eddited the student's ID is used.
this.setState({
modalEditIsOpen: true,
studentIDToEdit: record.id,
firstName: record.first,
lastName: record.last,
});
};
// Function onClose close the Dialog to EDIT a current student.
closeModalEdit = () => {
this.setState({ modalEditIsOpen: false });
};
// Make API call to server in order to GET the student's list according to the current section.
getStudentsData = () => {
const gradeLevel = encodeURI(this.props.match.params.gradeLevel); // Determine what is the current grade level.
const currentSection = encodeURI(this.props.match.params.sectionID); // Determine what is the current sectionID.
fetch(
`http://localhost:3000/api/students/${gradeLevel}/${currentSection}`, // API path to server sending the grade leve, and section id as parameters.
{
method: 'GET', // GET request to server
},
)
.then(promise => promise.json()) // Promise recieved from server
.then(res => {
// get response from the server.
// if server response is empty, meaning the current section has no students then return 'No Data Available'
if (res.length === 0) {
this.setState({ studentsList: [{ first: 'No Data Available' }] });
} else {
// else change the state of studentsList a populated with the students list.
this.setState({ studentsList: res });
}
});
};
// Make API call to server in order to DELETE a student from the database.
deleteStudent = () => {
const studentIDToDelete = this.state.studentIDToDelete; // determine which student need to be deleted according to the student's id.
this.closeModal(); // close the delete dialog.
// If there is a student to delete then make API call
if (studentIDToDelete != '') {
fetch(`http://localhost:3000/api/student/delete/${studentIDToDelete}`, {
// API path sends parameter with the studen id to be deleted.
method: 'DELETE', // Determine is DELETE request to server.
})
.then(res => res.json()) // get response.
.then(data => {
this.getStudentsData(); // re-render the component with the edited student list.
});
}
};
// Make API call to server in order to POST a new student into the database.
postNewStudentToDatabase = e => {
e.preventDefault();
// Object to be seent to server with the new data to add a new student.
const databody = {
studentID: null,
firstName: this.state.firstName,
lastName: this.state.lastName,
sectionID: this.state.sectionID,
};
fetch('http://localhost:3000/api/student/add', {
// API path to communicate with server.
method: 'POST', // Determine is POST request to server.
body: JSON.stringify(databody), // Send the Object with the new data.
headers: {
'Content-Type': 'application/json', // Let the server know the object is of type JSON
},
})
.then(res => res.json()) // Get server respone
.then(data => {
this.getStudentsData(); // re-render the component with the edited student list.
});
};
// Make API call to server in order to EDIT a student's data in the database.
putStudentInfToServer = e => {
e.preventDefault();
this.closeModalEdit();
// Object to be sent to server with the new data for an edited student.
const databody = {
studentID: this.state.studentIDToEdit,
firstName: this.state.firstName,
lastName: this.state.lastName,
};
fetch('http://localhost:3000/api/student/edit', {
// API path to communicate with server.
method: 'PUT', // Determine is a PUT request for server.
body: JSON.stringify(databody), // Send the Object with the new data.
headers: {
'Content-Type': 'application/json', // Let the server know the object is of type JSON
},
})
.then(res => res.json()) // get response from server
.then(data => {
this.getStudentsData(); // re-render the component with the edited student list.
});
};
// Render Student List View
render() {
const { classes } = this.props;
return (
<div className="section-dashboard">
<GradeMenu />
<div className="table-section">
<StudentsToolbar
handleClickOpen={this.handleClickOpen}
handleTabChange={this.handleTabChange}
/>
<StudentsTable
studentsList={this.state.studentsList}
openModal={this.openModal}
openModalEdit={this.openModalEdit}
/>
<AddStudentsDialog
open={this.state.open}
handleClose={this.handleClose}
handleInputChange={this.handleInputChange}
postNewStudentToDatabase={this.postNewStudentToDatabase}
firstName={this.state.firstName}
lastName={this.state.lastName}
/>
<Modal
className="Modal"
overlayClassName="Overlay"
isOpen={this.state.modalIsOpen}
onRequestClose={this.closeModal}
>
<DeleteStudentInfDialog
firstName={this.state.firstName}
lastName={this.state.lastName}
deleteStudent={this.deleteStudent}
closeModal={this.closeModal}
/>
</Modal>
<Modal
className="Modal"
overlayClassName="Overlay"
isOpen={this.state.modalEditIsOpen}
onRequestClose={this.closeModalEdit}
>
<EditStudentInfDialog
firstName={this.state.firstName}
lastName={this.state.lastName}
closeModalEdit={this.closeModalEdit}
putStudentInfToServer={this.putStudentInfToServer}
handleInputChange={this.handleInputChange}
/>
</Modal>
</div>
</div>
);
}
} |
JavaScript | class Iteration {
/**
* @param {Iterable.<T>} iterable Iterable object.
*/
constructor(iterable) {
this[$iterable] = iterable;
}
/**
* Initialize this with a iterable object.
* @template S element type.
* @param {Iterable.<S>} iterable Iterable object.
* @returns {Iteration.<S>} the new Iteration object. Cannot reuse.
*/
static on(iterable) {
return new Iteration(iterable);
}
/**
* Check if all the elements match.
*
* @param {(value: T, index: number) => boolean} predicate Predicate function used to inspect elements.(index origin is Zero)
* @return {boolean} Returns true if all elements meet the condition. Returns true whenever Iterable is empty.
*/
allMatch(predicate) {
return allMatch(this[$iterable], predicate);
}
/**
* Check if any of the elements match.
*
* @param {(value: T, index: number) => boolean} predicate Predicate function used to inspect elements.(index origin is Zero)
* @return {boolean} Returns true if either element meets the conditions. Returns false whenever Iterable is empty.
*/
anyMatch(predicate) {
return anyMatch(this[$iterable], predicate);
}
/**
* Concatenate iterable objects.
* @param {Iterable.<Iterable.<T>>} subsequents Iterable objects.
* @returns {Iteration.<T>} The new Iteration. Cannot reuse.
*/
concat(...subsequents) {
return Iteration.on(concat(this[$iterable], ...subsequents));
}
/**
* Discards the element while the condition is met. And it returns the rest.
* @param {(value: T, index: number) => boolean} predicate Predicate to determine whether to discard the value.(index origin is Zero)
* @returns {Iteration.<T>} The new Iteration. Cannot reuse.
*/
dropWhile(predicate) {
return Iteration.on(dropWhile(this[$iterable], predicate));
}
/**
* Returns only the elements that satisfy the condition.
* @param {(value: T, index: number) => boolean} predicate A predicate that determines if a value is legal.(index origin is Zero)
* @returns {Iteration.<T>} The new Iteration. Cannot reuse.
*/
filter(predicate) {
return Iteration.on(filter(this[$iterable], predicate));
}
/**
* Returns the first element that matches the condition.
* @param {undefined | ((value: T, index: number) => boolean)} predicate If omit the condition, always true.(index origin is Zero)
* @return {?T} The first element that satisfies the condition. Null if not found.
*/
findFirst(predicate) {
return findFirst(this[$iterable], predicate);
}
/**
* Maps the element to another type and flat.
*
* @template U another type
* @param {Iterable.<T>} iterable Iterable object.
* @param {(value: T, index: number) => Iterable.<U>} mapper Transformer function.(index origin is Zero)
* @returns {Iteration.<U>} The new Iteration. Cannot reuse.
*/
flatMap(mapper) {
return Iteration.on(flatMap(this[$iterable], mapper));
}
/**
* Perform the iteration.
* @param {(value: T, index: number) => void} consumer Consumer function. (index origin is Zero)
* @returns {void} Nothing.
*/
forEach(consumer) {
forEach(this[$iterable], consumer);
}
/**
* Limit the number of elements.
* @param {number} maxSize Maximum number of elements.
* @returns {Iteration.<T>} The new Iteration. Cannot reuse.
*/
limit(maxSize) {
return Iteration.on(limit(this[$iterable], maxSize));
}
/**
* Maps the element to another type.
* @template U another type.
* @param {(value: T, index: number) => S} mapper Transformer function.(index origin is Zero)
* @returns {Iteration.<U>} The new Iteration. Cannot reuse.
*/
map(mapper) {
return Iteration.on(map(this[$iterable], mapper));
}
/**
* Apply the consumption function to the element.
*
* This is intended for logging during debugging, for example.
* @param {(value: T, index: number) => void} consumer Consumer function. (index origin is Zero)
* @returns {Iteration.<T>} The new Iteration. Cannot reuse.
*/
peek(consumer) {
return Iteration.on(peek(this[$iterable], consumer));
}
/**
* Performs a reduction on the elements of a iterable object using the initial value,
* cumulative, and associative functions.
* @template U result type.
* @param {(result: U | null, element: T, index: number) => U} accumulator A function that transforms and calculates the result.(index origin is Zero)
* @param {?U} initial Initial value.
* @returns {U | null} Result value.
*/
reduce(accumulator, initial = null) {
return reduce(this[$iterable], accumulator, initial);
}
/**
* Remove n elements from the beginning.
* @param {number} n The number of elements to skip from the beginning.
* @returns {Iteration.<T>} The new Iteration. Cannot reuse.
*/
skip(n) {
return Iteration.on(skip(this[$iterable], n));
}
/**
* Returns the elements until the condition is no longer met. Discard the rest.
* @param {(value: T, index: number) => boolean} predicate A predicate that determines whether the value is still returned.(index origin is Zero)
* @returns {Iteration.<T>} The new Iteration. Cannot reuse.
*/
takeWhile(predicate) {
return Iteration.on(takeWhile(this[$iterable], predicate));
}
/**
* Convert to an Iterable object.
* @returns {Iterable<T>} The new Iterable. Cannot reuse.
*/
toIterable() {
return toIterable(this[$iterable]);
}
/**
* Convert to an Iterator object.
* @returns {Iterator<T, undefined, unknown>} The new Iterator. Cannot reuse.
*/
toIterator() {
return toIterator(this[$iterable]);
}
/**
* Combines each element of a iterable object.
*
* The first element of the array is the value of the first Iterable object.
* The second element is the value of the second Iterable object.
*
* If one is shorter than the other, the return length is equal to that length.
* @param {Iterable.<T>} another Iterable object.
* @returns {Iteration.<Array.<T>>} The new Iteration. Cannot reuse.
*/
zip(another) {
return Iteration.on(zip(this[$iterable], another));
}
[Symbol.iterator]() {
return this.toIterable();
}
} |
JavaScript | class ClientProfilerService {
/**
*
* @param {Container} container The service container
*/
constructor(container) {
this.container = container;
}
/**
* Get the profiler's bass storage manager
* @param {boolean} [newSession] true to get a new session, false to use cache
* @returns {Manager|null}
*/
getStorageManager(newSession = false) {
return this.container.get('profiler').getStorageManager(newSession);
}
/**
* Create a new recording account
* @param {Object} data The data to create the user account with
* @returns {Promise}
*/
createAccount(data) {
const manager = this.getStorageManager();
const account = manager.createDocument('RecordingAccount', data || {});
return this.container.get('validator').validate(account).then(() => {
return manager.findCountBy('RecordingAccount', {email: account.email}).then(num => {
if (num > 0) {
const err = new Error('Validation Error');
err.validationErrors = [{
message: 'The provided email address is already taken.',
property: 'email'
}];
return Promise.reject(err);
}
manager.persist(account);
return manager.flush(account);
});
}).catch(err => {
if (Array.isArray(err)) {
// the error will be an array if the validator found errors
const e = new Error('Validation Error');
e.validationErrors = err;
return Promise.reject(e);
}
// it's possible that some other error was caught
return Promise.reject(err);
});
}
} |
JavaScript | class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set($$props) {
if (this.$$set && !is_empty($$props)) {
this.$$.skip_bound = true;
this.$$set($$props);
this.$$.skip_bound = false;
}
}
} |
JavaScript | class SvelteComponentDev extends SvelteComponent {
constructor(options) {
if (!options || (!options.target && !options.$$inline)) {
throw new Error("'target' is a required option");
}
super();
}
$destroy() {
super.$destroy();
this.$destroy = () => {
console.warn('Component was already destroyed'); // eslint-disable-line no-console
};
}
$capture_state() { }
$inject_state() { }
} |
JavaScript | class Util {
/**
* Get the current directory!
* @static
* @type {string}
* @returns {string}
*/
static get directory() {
return `${path.dirname(require.main.filename)}${path.sep}`;
}
} |
JavaScript | class FrameElement extends DocElement {
constructor(id, initialData, rb) {
super(rb.getLabel('docElementFrame'), id, 100, 100, rb);
this.frame = null;
this.setupComplete = false;
this.label = '';
this.backgroundColor = '';
this.borderAll = false;
this.borderLeft = false;
this.borderTop = false;
this.borderRight = false;
this.borderBottom = false;
this.borderColor = '#000000';
this.borderWidth = '1';
this.shrinkToContentHeight = false;
this.spreadsheet_hide = false;
this.spreadsheet_column = '';
this.spreadsheet_addEmptyRow = false;
this.setInitialData(initialData);
this.borderWidthVal = utils.convertInputToNumber(this.borderWidth);
}
setup(openPanelItem) {
this.borderWidthVal = utils.convertInputToNumber(this.borderWidth);
super.setup();
this.createElement();
this.updateDisplay();
if (this.linkedContainerId === null) {
this.linkedContainerId = this.rb.getUniqueId();
}
this.frame = new Frame(this.linkedContainerId, 'frame_' + this.linkedContainerId, this.rb);
this.frame.init(this);
this.rb.addContainer(this.frame);
this.setupComplete = true;
this.updateStyle();
this.updateName();
if (openPanelItem){
this.panelItem.open();
}
}
/**
* Register event handler for a container element so it can be dragged and
* allow selection on double click.
*/
registerEventHandlers() {
super.registerContainerEventHandlers();
}
/**
* Returns highest id of this component, this is the id of the linked container because it is
* created after the frame element.
* @returns {Number}
*/
getMaxId() {
return this.linkedContainerId;
}
setValue(field, value, elSelector, isShown) {
if (field.indexOf('border') !== -1) {
// Style.setBorderValue needs to be called before super.setValue because it calls updateStyle() which expects
// the correct border settings
this[field] = value;
if (field === 'borderWidth') {
this.borderWidthVal = utils.convertInputToNumber(value);
}
Style.setBorderValue(this, field, '', value, elSelector, isShown);
}
super.setValue(field, value, elSelector, isShown);
if (field === 'label') {
this.updateName();
}
}
updateDisplayInternal(x, y, width, height) {
if (this.el !== null) {
let props = { left: this.rb.toPixel(x), top: this.rb.toPixel(y),
width: this.rb.toPixel(width), height: this.rb.toPixel(height) };
this.el.css(props);
}
// update inner frame element size
if (this.borderLeft) {
width -= this.borderWidthVal;
}
if (this.borderRight) {
width -= this.borderWidthVal;
}
if (this.borderTop) {
height -= this.borderWidthVal;
}
if (this.borderBottom) {
height -= this.borderWidthVal;
}
let styleProperties = {};
styleProperties['width'] = this.rb.toPixel(width);
styleProperties['height'] = this.rb.toPixel(height);
$(`#rbro_el_content_frame${this.id}`).css(styleProperties);
}
updateStyle() {
let styleProperties = {};
let borderStyleProperties = {};
styleProperties['background-color'] = this.getValue('backgroundColor');
if (this.getValue('borderLeft') || this.getValue('borderTop') ||
this.getValue('borderRight') || this.getValue('borderBottom')) {
borderStyleProperties['border-style'] = this.getValue('borderTop') ? 'solid' : 'none';
borderStyleProperties['border-style'] += this.getValue('borderRight') ? ' solid' : ' none';
borderStyleProperties['border-style'] += this.getValue('borderBottom') ? ' solid' : ' none';
borderStyleProperties['border-style'] += this.getValue('borderLeft') ? ' solid' : ' none';
borderStyleProperties['border-width'] = this.getValue('borderWidthVal') + 'px';
borderStyleProperties['border-color'] = this.getValue('borderColor');
} else {
borderStyleProperties['border-style'] = 'none';
}
$(`#rbro_el_content${this.id}`).css(borderStyleProperties);
this.el.css(styleProperties);
}
/**
* Returns all data fields of this object. The fields are used when serializing the object.
* @returns {String[]}
*/
getFields() {
return ['id', 'containerId', 'linkedContainerId', 'label',
'x', 'y', 'width', 'height', 'backgroundColor',
'borderAll', 'borderLeft', 'borderTop', 'borderRight', 'borderBottom', 'borderColor', 'borderWidth',
'printIf', 'removeEmptyElement', 'shrinkToContentHeight',
'spreadsheet_hide', 'spreadsheet_column', 'spreadsheet_addEmptyRow'];
}
getElementType() {
return DocElement.type.frame;
}
getXTagId() {
return 'rbro_frame_element_position_x';
}
getYTagId() {
return 'rbro_frame_element_position_y';
}
getWidthTagId() {
return 'rbro_frame_element_width';
}
getHeightTagId() {
return 'rbro_frame_element_height';
}
createElement() {
this.el = $(`<div id="rbro_el${this.id}" class="rbroDocElement rbroFrameElement rbroElementContainer"></div>`);
// rbroContentContainerHelper contains border styles
// rbroDocElementContentFrame contains width and height
this.el
.append($(`<div id="rbro_el_content${this.id}" class="rbroContentContainerHelper"></div>`)
.append($(`<div id="rbro_el_content_frame${this.id}" class="rbroDocElementContentFrame"></div>`))
);
this.appendToContainer();
this.registerEventHandlers();
}
getContentElement() {
return $(`#rbro_el_content_frame${this.id}`);
}
remove() {
super.remove();
this.rb.deleteContainer(this.frame);
}
updateName() {
if (this.label.trim() !== '') {
this.name = this.label;
} else {
this.name = this.rb.getLabel('docElementFrame');
}
$(`#rbro_menu_item_name${this.id}`).text(this.name);
}
/**
* Adds SetValue commands to command group parameter in case the specified parameter is used in any of
* the object fields.
* @param {Parameter} parameter - parameter which will be renamed.
* @param {String} newParameterName - new name of the parameter.
* @param {CommandGroupCmd} cmdGroup - possible SetValue commands will be added to this command group.
*/
addCommandsForChangedParameterName(parameter, newParameterName, cmdGroup) {
this.addCommandForChangedParameterName(parameter, newParameterName, 'rbro_frame_element_print_if', 'printIf', cmdGroup);
}
} |
JavaScript | class MatTabBody extends _MatTabBodyBase {
/**
* @param {?} elementRef
* @param {?} dir
* @param {?} changeDetectorRef
*/
constructor(elementRef, dir, changeDetectorRef) {
super(elementRef, dir, changeDetectorRef);
}
} |
JavaScript | class MatInkBar {
/**
* @param {?} _items
*/
constructor(_items) {
this._items = _items;
}
/**
* Hides the ink bar.
* @return {?}
*/
hide() {
this._items.forEach((/**
* @param {?} item
* @return {?}
*/
item => item._foundation.deactivate()));
}
/**
* Aligns the ink bar to a DOM node.
* @param {?} element
* @return {?}
*/
alignToElement(element) {
/** @type {?} */
const correspondingItem = this._items.find((/**
* @param {?} item
* @return {?}
*/
item => item.elementRef.nativeElement === element));
/** @type {?} */
const currentItem = this._currentItem;
if (currentItem) {
currentItem._foundation.deactivate();
}
if (correspondingItem) {
/** @type {?} */
const clientRect = currentItem ?
currentItem._foundation.computeContentClientRect() : undefined;
// The MDC indicator won't animate unless we give it the `ClientRect` of the previous item.
correspondingItem._foundation.activate(clientRect);
this._currentItem = correspondingItem;
}
}
} |
JavaScript | class MatInkBarFoundation {
/**
* @param {?} elementRef
* @param {?} document
*/
constructor(elementRef, document) {
this._adapter = {
addClass: (/**
* @param {?} className
* @return {?}
*/
className => {
if (!this._destroyed) {
this._element.classList.add(className);
}
}),
removeClass: (/**
* @param {?} className
* @return {?}
*/
className => {
if (!this._destroyed) {
this._element.classList.remove(className);
}
}),
setContentStyleProperty: (/**
* @param {?} propName
* @param {?} value
* @return {?}
*/
(propName, value) => {
this._indicatorContent.style.setProperty(propName, value);
}),
computeContentClientRect: (/**
* @return {?}
*/
() => {
// `getBoundingClientRect` isn't available on the server.
return this._destroyed || !this._indicatorContent.getBoundingClientRect ? {
width: 0, height: 0, top: 0, left: 0, right: 0, bottom: 0
} : this._indicatorContent.getBoundingClientRect();
})
};
this._element = elementRef.nativeElement;
this._foundation = new MDCSlidingTabIndicatorFoundation(this._adapter);
this._createIndicator(document);
}
/**
* Aligns the ink bar to the current item.
* @param {?=} clientRect
* @return {?}
*/
activate(clientRect) {
this._foundation.activate(clientRect);
}
/**
* Removes the ink bar from the current item.
* @return {?}
*/
deactivate() {
this._foundation.deactivate();
}
/**
* Gets the ClientRect of the indicator.
* @return {?}
*/
computeContentClientRect() {
return this._foundation.computeContentClientRect();
}
/**
* Initializes the foundation.
* @return {?}
*/
init() {
this._foundation.init();
}
/**
* Destroys the foundation.
* @return {?}
*/
destroy() {
/** @type {?} */
const indicator = this._indicator;
if (indicator.parentNode) {
indicator.parentNode.removeChild(indicator);
}
this._element = this._indicator = this._indicatorContent = (/** @type {?} */ (null));
this._foundation.destroy();
this._destroyed = true;
}
/**
* @private
* @param {?} document
* @return {?}
*/
_createIndicator(document) {
if (!this._indicator) {
/** @type {?} */
const indicator = this._indicator = document.createElement('span');
/** @type {?} */
const content = this._indicatorContent = document.createElement('span');
indicator.className = 'mdc-tab-indicator';
content.className = 'mdc-tab-indicator__content mdc-tab-indicator__content--underline';
indicator.appendChild(content);
this._element.appendChild(indicator);
}
}
} |
JavaScript | class MatTabHeader extends _MatTabHeaderBase {
/**
* @param {?} elementRef
* @param {?} changeDetectorRef
* @param {?} viewportRuler
* @param {?} dir
* @param {?} ngZone
* @param {?} platform
* @param {?=} animationMode
*/
constructor(elementRef, changeDetectorRef, viewportRuler, dir, ngZone, platform,
// @breaking-change 9.0.0 `_animationMode` parameter to be made required.
animationMode) {
super(elementRef, changeDetectorRef, viewportRuler, dir, ngZone, platform, animationMode);
}
/**
* @return {?}
*/
ngAfterContentInit() {
this._inkBar = new MatInkBar(this._items);
super.ngAfterContentInit();
}
} |
JavaScript | class MatTabGroup extends _MatTabGroupBase {
/**
* @param {?} elementRef
* @param {?} changeDetectorRef
* @param {?=} defaultConfig
* @param {?=} animationMode
*/
constructor(elementRef, changeDetectorRef, defaultConfig, animationMode) {
super(elementRef, changeDetectorRef, defaultConfig, animationMode);
}
} |
JavaScript | class MatTabNav extends _MatTabNavBase {
/**
* @param {?} elementRef
* @param {?} dir
* @param {?} ngZone
* @param {?} changeDetectorRef
* @param {?} viewportRuler
* @param {?=} platform
* @param {?=} animationMode
*/
constructor(elementRef, dir, ngZone, changeDetectorRef, viewportRuler,
/**
* @deprecated @breaking-change 9.0.0 `platform` parameter to become required.
*/
platform, animationMode) {
super(elementRef, dir, ngZone, changeDetectorRef, viewportRuler, platform, animationMode);
}
/**
* @return {?}
*/
ngAfterContentInit() {
this._inkBar = new MatInkBar(this._items);
super.ngAfterContentInit();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.