language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Canvas { constructor(args){ this.canvasElem = args.canvasElem; //The Canvas Element this.canvasB = document.createElement("canvas"); //Create a buffer canvas this.ctx = this.canvasB.getContext('2d'); //The Buffered 2D context this.ctxF = args.canvasElem.getContext('2d'); //The Final 2D context this.rect = this.canvasElem.getBoundingClientRect(); //The Rect this.width = this.rect.width; //Real pixel width this.height = this.rect.height; //Real pixel height this.canvasElem.width = this.width; //Set width this.canvasElem.height = this.height; //Set height this.canvasElem.style.width = this.width +"px"; //Force Real width; this.canvasElem.style.height = this.height + "px"; //Force Real height; this.canvasB.width = this.width; //Set width this.canvasB.height = this.height; //Set height this.canvasB.style.width = this.width +"px"; //Force Real width; this.canvasB.style.height = this.height + "px"; //Force Real height; this.backgroundColor = args.backgroundColor; //Set background Color this.forgroundColor = args.forgroundColor; //Set forground Color } /** * Draw a new game canvas */ newGame(){ let aspect = this.width/this.height; let iaspect = imageW/imageH; let width = 0; let height = 0; let factor = 0; let xpos = 0; let ypos = 0; if(aspect > iaspect){ factor = imageH/this.height; height = this.height; width = imageW/factor; xpos = (this.width - width)/2; } else{ factor = imageW/this.width; width = this.width; height = imageH/factor; ypos = (this.height - height)/2; } //Clear this.ctx.beginPath(); this.ctx.fillStyle = this.backgroundColor; this.ctx.fillRect(0,0,this.width,this.height); this.ctx.drawImage(startImage, xpos, ypos, width, height); this.drawBuffer(); } /** * Redraw blank canvas with background objects in it */ clear(){ //Clear this.ctx.beginPath(); this.ctx.fillStyle = this.backgroundColor; this.ctx.fillRect(0,0,this.width,this.height); //Draw Box this.ctx.strokeStyle = this.forgroundColor; this.ctx.strokeWidth = 2; this.ctx.rect(0,0,this.width-1,this.height-1); this.ctx.stroke(); //Draw Center Line this.ctx.beginPath(); this.ctx.moveTo(this.width/2,0); this.ctx.lineTo(this.width/2,this.height); this.ctx.stroke(); this.drawBuffer(); } drawBuffer(){ //Draw Buffer to Screen this.ctxF.beginPath(); this.ctxF.fillStyle = this.backgroundColor; this.ctxF.fillRect(0,0,this.width,this.height); this.ctxF.drawImage(this.canvasB, 0, 0); } }
JavaScript
class Controller{ constructor(args){ this.sampleFreq = args.sampleFreq; //Frequency to Sample Data (erase direction) this.timestamp = Date.now(); //The current time this.direction = 0; //The direction this controller is going right now (see paddle directions) /** * The interval function is called every frame with the current time. */ this.intervalFunc = (now)=>{ if((now - this.timestamp) > this.sampleFreq){ this.direction = 0; } }; } }
JavaScript
class KeyboardController extends Controller{ constructor(args){ super(args); this.oldSkoolMode = false; //Ancient method of listening for keystrokes document.onkeydown = (e)=>{ e = e || window.event; var charCode = (typeof e.which == "number") ? e.which : e.keyCode; if (charCode) { //Check for Up key if(charCode == 87){ //'w' this.direction = -1; this.timestamp = Date.now(); } //Check for Down key if(charCode == 83){ //'s' this.direction = 1; this.timestamp = Date.now(); } //Check for oldSkool mode if(charCode == 32){ this.oldSkoolMode = !this.oldSkoolMode; } } }; document.onkeyup = (e)=>{ e = e || window.event; var charCode = (typeof e.which == "number") ? e.which : e.keyCode; if (charCode) { //Check for Up key if(charCode == 87){ //'w' this.direction = 0; this.timestamp = Date.now(); } //Check for Down key if(charCode == 83){ //'s' this.direction = 0; this.timestamp = Date.now(); } } }; } }
JavaScript
class LeapController extends Controller{ constructor(args){ super(args); this.handDetected = false; const controllerOptions = {enableGestures: true}; let setDirection = (dir) => { this.direction = dir this.timestamp = Date.now(); }; let setHandDetected = (detected) => {this.handDetected = detected;}; //The Leap Motion controller loop function Leap.loop(controllerOptions, function(frame) { //If We see hands we use them if (frame.hands.length > 0) { //We use all hands to update input //Fun fact this makes things interesting when friends //are being fun at parties and interfering with your //attempts to play the game. //Ofc its trivial to use only one hand but that would //be less fun and "social" for (let i = 0; i < frame.hands.length; i++) { let hand = frame.hands[i]; //We use one finger (your index) to compute direction if(hand.indexFinger.extended){ setHandDetected(true); let nameMap = ["thumb", "index", "middle", "ring", "pinky"]; let pointer = null; hand.pointables.forEach(function(pointable){ if(nameMap[pointable.type] == "index") pointer = pointable; }); if(pointer){ //If we have found your index finger we now use its direction to set our direction let direction = pointer.direction; if(direction[1] > 0.3){ setDirection(-1); } if(direction[1] < -0.3){ setDirection(1); } } }else{ setHandDetected(false); } } } }); } }
JavaScript
class AIController extends Controller{ constructor(args){ super(args); this.ball = args.ball; this.paddle = args.paddle; //Use our own interval synced with the sample rate this.interval = setInterval(()=>{ //Figure out where our paddle is relative to ball in y axis with a threshold let top = this.paddle.y + this.paddle.length/2; let bottom = this.paddle.y + this.paddle.length/2; //If top is too high move down if(top < this.ball.y ){ this.direction = 1; this.timestamp = Date.now(); } //If bottom is too low move up if(bottom > this.ball.y){ this.direction = -1; this.timestamp = Date.now(); } //If within range dont move if(top > this.ball.y && bottom < this.ball.y){ this.direction = 0; this.timestamp = Date.now(); } if(top > this.ball.y - 25 && bottom < this.ball.y + 25 && this.ball.vec.y < 0.5){ this.direction = 0; this.timestamp = Date.now(); } },this.sampleFreq); } }
JavaScript
class Pong { constructor(canvas){ this.framerate = 20; //The frame rate we want to run at this.inPlay = false; //Fun Fact this is never false you can never ever stop >:3 //TODO Add pause button this.newGameShowing = false; //Weather New game is showing this.oldSkoolMode = false; //Enable OldSkool controls //All the fun Score objects (hint the left will win if its a cheating computer unless you are a god) this.leftScore = document.getElementById("leftScore"); this.rightScore = document.getElementById("rightScore"); this.leftScr = 0; this.rightScr = 0; //The Canvas Object this.canvas = new Canvas({canvasElem:canvas, backgroundColor: "rgba(255,255,255,1)", forgroundColor: "rgba(0,0,0,1)" }); //Our round object that we want to play with this.ball = new Ball({x:this.canvas.width/2, y:this.canvas.height/2, rad:10, vec:{x:5,y:0}, color:"rgba(0,0,0,1)" }); //The Cheating Computer's Paddle this.leftPaddle = new Paddle({x:10, y:(canvas.height/2)-50, speed: 4, totalH: this.canvas.height, color:"rgba(0,0,0,1)" }); //The Human's Paddle this.rightPaddle = new Paddle({x:canvas.width-20, y:(canvas.height/2)-50, speed: 6, totalH: this.canvas.height, color:"rgba(0,0,0,1)" }); //The Cheating Computer (I have handicaped him with a speed factor half that of yours) this.leftController = new AIController({sampleFreq: this.framerate, ball: this.ball, paddle: this.leftPaddle }); //The Human using a Leap Motion //TODO Add option for old school players aka Keyboard this.rightController = new LeapController({sampleFreq: this.framerate}); //For those who want to be old school this.oldSkool = new KeyboardController({sampleFreq: 1000}); //Low Sample so as to allow for keyup //For those who want to be slightly less old school //Not enough time to finish // this.lessOldSkool = new TouchController({sampleFreq: this.framerate, //Sample rate is ignored by Touch // paddle:this.rightPaddle, // canvas:this.canvas}); this.canvas.canvasElem.onclick = ()=>{ this.inPlay = !this.inPlay; //this.oldSkool.oldSkoolMode = true; //this seems confusing since it says to hit space for oldSkool if(!this.inPlay){ this.leftScr = 0; this.rightScr = 0; this.leftScore.innerHTML = "0"; this.rightScore.innerHTML = "0"; } } //The Master Game Loop (simple right) this.interval = setInterval(()=>{ if(this.rightController.handDetected){ this.inPlay = true; } if(this.oldSkool.oldSkoolMode){ this.inPlay = true; } if(this.inPlay){ this.gameStep(); this.newGameShowing = false; }else{ if(!this.newGameShowing){ this.canvas.newGame(); this.newGameShowing = true; } } },this.framerate); } /** * Compute a state change through a single step of the game. * (oh wait... not so simple...) */ gameStep(){ let now = Date.now(); //The current timestamp (please note that time travel will make this work oddly) //Update Controller input this.leftController.intervalFunc(now); this.oldSkool.intervalFunc(now); // this.lessOldSkool.intervalFunc(now); this.rightController.intervalFunc(now); //Get oldSkool mode from Keyboard Controller this.oldSkoolMode = this.oldSkool.oldSkoolMode; //Apply controller input to the Paddles this.leftPaddle.direction = this.leftController.direction; if(this.oldSkoolMode) this.rightPaddle.direction = this.oldSkool.direction; else{ //console.log(this.lessOldSkool.timestamp > this.rightController.timestamp); // if(this.lessOldSkool.timestamp > this.rightController.timestamp){ // this.rightPaddle.direction = this.lessOldSkool.direction; // } // else{ this.rightPaddle.direction = this.rightController.direction; // } } //console.log(this.rightPaddle.direction); //Update the positions of the Round thing and the Paddles this.ball.timeStep(); this.leftPaddle.timeStep(); this.rightPaddle.timeStep(); //Handle Wall Collisions if(this.ball.x < 0 + this.ball.rad){ //left player loss this.rightScr += 1; this.ball.x = this.canvas.width/2; this.ball.y = this.canvas.height/2; this.ball.vec = {x:5,y:0} } if(this.ball.x > this.canvas.width - this.ball.rad){ //right player loss this.leftScr += 1; this.ball.x = this.canvas.width/2; this.ball.y = this.canvas.height/2; this.ball.vec = {x:-5,y:0} } var newVec = this.ball.vec; if(this.ball.y < 0 + this.ball.rad && this.ball.vec.y < 0){ //bounce mirror this.ball.vec.y = -this.ball.vec.y; } if(this.ball.y > this.canvas.height - this.ball.rad && this.ball.vec.y > 0){ //bounce mirror this.ball.vec.y = -this.ball.vec.y; } //Handle Paddle Collisions if((this.ball.x < this.leftPaddle.x + this.leftPaddle.width + this.ball.rad) && (this.ball.y > this.leftPaddle.y && this.ball.y < this.leftPaddle.y + this.leftPaddle.length) && this.ball.vec.x < 1){ //bounce this.ball.vec.x = -this.ball.vec.x let yreflectmod = this.ball.y - (this.leftPaddle.y + this.leftPaddle.length/2); if(yreflectmod > 2){ //Dumb angle calulation yreflectmod = 2; } if(yreflectmod < -2){ yreflectmod = -2; } this.ball.vec.y = this.ball.vec.y + yreflectmod; } if((this.ball.x > this.rightPaddle.x - this.ball.rad) && (this.ball.y > this.rightPaddle.y && this.ball.y < this.rightPaddle.y + this.rightPaddle.length) && this.ball.vec.x > 1){ //bounce this.ball.vec.x = -this.ball.vec.x let yreflectmod = this.ball.y - (this.rightPaddle.y + this.rightPaddle.length/2); if(yreflectmod > 4){ //Dumb angle calculation yreflectmod = 4; } if(yreflectmod < -4){ yreflectmod = -4; } this.ball.vec.y = this.ball.vec.y - yreflectmod; } //Redraw the Beautiful Canvas (ITS ART I SWEAR) this.canvas.clear(); this.ball.drawable(this.canvas.ctx); this.leftPaddle.drawable(this.canvas.ctx); this.rightPaddle.drawable(this.canvas.ctx); this.canvas.drawBuffer(); this.leftScore.innerHTML = this.leftScr; this.rightScore.innerHTML = this.rightScr; if(this.oldSkoolMode){ document.getElementById("title").innerHTML = "OldSkoolPong"; }else{ document.getElementById("title").innerHTML = "LeapPong"; } } }
JavaScript
class GoalCollection extends BaseCollection { /** * Creates the Goal collection. */ constructor() { super('Goal', new SimpleSchema({ name: { type: String }, })); } /** * Defines a new Goal. * @example * Goals.define({ name: 'Software Engineering', * description: 'Methods for group development of large, high quality software systems' }); * @param { Object } description Object with keys name and description. * Name must be previously undefined. Description is optional. * Creates a "slug" for this name and stores it in the slug field. * @throws {Meteor.Error} If the Goal definition includes a defined name. * @returns The newly created docID. */ define({ name }) { check(name, String); if (this.find({ name }).count() > 0) { throw new Meteor.Error(`${name} is previously defined in another Goal`); } return this._collection.insert({ name }); } /** * Returns the Goal name corresponding to the passed Goal docID. * @param GoalID An Goal docID. * @returns { String } An Goal name. * @throws { Meteor.Error} If the Goal docID cannot be found. */ findName(GoalID) { this.assertDefined(GoalID); return this.findDoc(GoalID).name; } /** * Returns a list of Goal names corresponding to the passed list of Goal docIDs. * @param GoalIDs A list of Goal docIDs. * @returns { Array } * @throws { Meteor.Error} If any of the instanceIDs cannot be found. */ findNames(GoalIDs) { return GoalIDs.map(GoalID => this.findName(GoalID)); } /** * Throws an error if the passed name is not a defined Goal name. * @param name The name of an Goal. */ assertName(name) { this.findDoc(name); } /** * Throws an error if the passed list of names are not all Goal names. * @param names An array of (hopefully) Goal names. */ assertNames(names) { _.each(names, name => this.assertName(name)); } /** * Returns the docID associated with the passed Goal name, or throws an error if it cannot be found. * @param { String } name An Goal name. * @returns { String } The docID associated with the name. * @throws { Meteor.Error } If name is not associated with an Goal. */ findID(name) { return (this.findDoc(name)._id); } /** * Returns the docIDs associated with the array of Goal names, or throws an error if any name cannot be found. * If nothing is passed, then an empty array is returned. * @param { String[] } names An array of Goal names. * @returns { String[] } The docIDs associated with the names. * @throws { Meteor.Error } If any instance is not an Goal name. */ findIDs(names) { return (names) ? names.map((instance) => this.findID(instance)) : []; } /** * Returns an object representing the Goal docID in a format acceptable to define(). * @param docID The docID of an Goal. * @returns { Object } An object representing the definition of docID. */ dumpOne(docID) { const doc = this.findDoc(docID); const name = doc.name; return { name }; } }
JavaScript
class SelectResultProcessor extends ResultProcessor { constructor(configuration) { super(configuration); } _process(results) { const configuration = this._getConfiguration(); if (configuration.properties) { let resultsToProcess; if (is.array(results)) { resultsToProcess = results; } else if (is.object(results)) { resultsToProcess = [ results ]; } else { resultsToProcess = null; } if (resultsToProcess) { resultsToProcess = resultsToProcess.map((result) => { const transform = {}; Object.keys(configuration.properties) .forEach((inputPropertyName) => { const outputPropertyName = configuration.properties[inputPropertyName]; attributes.write(transform, outputPropertyName, attributes.read(result, inputPropertyName)); }); return transform; }); if (is.array(results)) { results = resultsToProcess; } else { results = resultsToProcess[0]; } } } return results; } toString() { return '[SelectResultProcessor]'; } }
JavaScript
class IskeSecurityLevelWidget extends React.Component{ calcSecurityLevel() { var iskeClass = []; iskeClass[0] = this.props.datarow['iske_security_class_k']; iskeClass[1] = this.props.datarow['iske_security_class_t']; iskeClass[2] = this.props.datarow['iske_security_class_s']; var maxClass = -1; for (var i = 0; i < iskeClass.length; i++) { if (iskeClass[i] !== undefined && iskeClass[i] !== null && iskeClass[i] !== "") { var classValue = parseInt(iskeClass[i].substring(1)); if (classValue > maxClass) maxClass = classValue; } } var securityLevel = ''; switch (maxClass) { case -1: // ISKE classes not specified: securityLevel = ''; break; case 0: case 1: securityLevel = 'L'; break; case 2: securityLevel = 'M'; break; case 3: securityLevel = 'H'; break; } return securityLevel; } render() { var securityLevel = this.calcSecurityLevel(); var properties = { type: "hidden", name: this.props.field.name, value: securityLevel, "data-save": 'value', "data-type": this.props.field.type }; if (this.props.filtertype) properties["data-filter"]=this.props.filtertype; if (this.props.parentName) properties["data-parentname"]=this.props.parentName; if (this.props.arrayIndex || this.props.arrayIndex===0) properties["data-arrayindex"]=this.props.arrayIndex; return ( ce("div", {}, autoform.fieldValue(securityLevel,this.props.field), ce("input", properties)) ); } }
JavaScript
class DeviceStore extends EventEmitter { /** Create a store */ constructor () { super() //util this.fetch = fetchJson( `${rest_url}/api/devices`, () => sessionStore.getHeader() ) this.fetchDeviceProfile = fetchJson( `${rest_url}/api/deviceProfiles`, () => sessionStore.getHeader() ) this.fetchDeviceNtwkTypeLink = fetchJson( `${rest_url}/api/deviceNetworkTypeLinks`, () => sessionStore.getHeader() ) } /** * Create a device * @param {Object} body a device * @return {Object} a device */ createDevice (body) { return this.fetch('', { method: 'post', body }) } /** * Get a device * @param {string} id * @return {Object} a device */ getDevice (id) { return this.fetch(id) } /** * Update a device * @param {Object} body a device * @return {Object} a device */ updateDevice (body) { return this.fetch(body.id, { method: 'put', body }) } /** * Delete device * @param {string} id */ async deleteDevice (id) { await this.fetch(id, { method: 'delete' }) } /** * Get paginated list of devices * @param {number} pageSize * @param {number} offset * @param {string} applicationId * @return {Object[]} list of devices */ getAll (pageSize, offset, applicationId) { let query = paginationQuery(pageSize, offset) if (applicationId) query += `${query ? '&' : '?'}applicationId=${applicationId}` return this.fetch(`${query ? '?' : ''}${query}`) } /** * Create a device profile * @param {string} name * @param {string} description * @param {string} companyId * @param {string} networkTypeId * @param {string} networkSettings * @return {string} device profile ID */ async createDeviceProfile (body) { const response = await this.fetchDeviceProfile('', { method: 'post', body }) remoteErrorDisplay(response) return response.id } /** * Get a device profile * @param {string} id * @return {Object} device profile */ async getDeviceProfile (id) { const response = await this.fetchDeviceProfile(id) remoteErrorDisplay(response) return response } /** * Update a device profile * @param {Object} body * @return {Object} device profile */ async updateDeviceProfile (body) { const response = await this.fetchDeviceProfile(body.id, { method: 'put', body }) remoteErrorDisplay(response) return response } /** * Delete a device profile * @param {string} id */ async deleteDeviceProfile (id) { const response = await this.fetchDeviceProfile(id, { method: 'delete' }) remoteErrorDisplay(response) } /** * Get a paginated list of device profiles * @param {number} pageSize * @param {number} offset * @return {Object[]} list of device profiles */ async getAllDeviceProfiles (pageSize, offset) { let query = paginationQuery(pageSize, offset) const response = await this.fetchDeviceProfile(`${query ? '?' : ''}${query}`) remoteErrorDisplay(response) return response } /** * Query device profiles by company ID and network type ID * @param {string} appId * @param {string} netId * @return {Object[]} list of device profiles */ async getAllDeviceProfilesForAppAndNetType (appId, netId) { let app = await applicationStore.getApplication(appId) const query = `?companyId=${app.companyId}&networkTypeId=${netId}` const response = await this.fetchDeviceProfile(query) remoteErrorDisplay(response) return response } /** * Create a device network type * @param {string} deviceId * @param {string} networkTypeId * @param {string} deviceProfileId * @param {Object} networkSettings * @return {Object} a device network type */ async createDeviceNetworkType (deviceId, networkTypeId, deviceProfileId, networkSettings) { const body = { deviceId, networkTypeId, deviceProfileId, networkSettings } const response = await this.fetchDeviceNtwkTypeLink('', { method: 'post', body }) remoteErrorDisplay(response) return response } /** * Query device network types by device ID and networkType ID * @param {string} devId * @param {string} netId */ async getDeviceNetworkTypeLink (devId, netId) { const query = `?deviceId=${devId}&networkTypeId=${netId}` const response = await this.fetchDeviceNtwkTypeLink(query) remoteErrorDisplay(response) if (!(response && response.records && response.records.length)) { throw new Error('Not Found') } return response.records[0] } /** * Update a device network type * @param {Object} body * @return {Object} a device network type */ async updateDeviceNetworkType (body) { const response = await this.fetchDeviceNtwkTypeLink(body.id, { method: 'put', body }) remoteErrorDisplay(response) return response } /** * Delete a device network type * @param {string} id */ async deleteDeviceNetworkType (id) { const response = await this.fetchDeviceNtwkTypeLink(id, { method: 'delete' }) remoteErrorDisplay(response) } /** * Handle actions from dispatcher * @param {Object} param0 action */ handleActions ({ type }) { switch (type) { default: return } } }
JavaScript
class ParameterRef extends Ref { /** * @param {string} name */ constructor(name) { super(name, a => a.getParameter(name)) } }
JavaScript
class SurgeArresterInfo extends Assets.AssetInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.SurgeArresterInfo; if (null == bucket) cim_data.SurgeArresterInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.SurgeArresterInfo[obj.id]; } parse (context, sub) { let obj = Assets.AssetInfo.prototype.parse.call (this, context, sub); obj.cls = "SurgeArresterInfo"; base.parse_element (/<cim:SurgeArresterInfo.continuousOperatingVoltage>([\s\S]*?)<\/cim:SurgeArresterInfo.continuousOperatingVoltage>/g, obj, "continuousOperatingVoltage", base.to_string, sub, context); base.parse_element (/<cim:SurgeArresterInfo.isPolymer>([\s\S]*?)<\/cim:SurgeArresterInfo.isPolymer>/g, obj, "isPolymer", base.to_boolean, sub, context); base.parse_element (/<cim:SurgeArresterInfo.lightningImpulseDischargeVoltage>([\s\S]*?)<\/cim:SurgeArresterInfo.lightningImpulseDischargeVoltage>/g, obj, "lightningImpulseDischargeVoltage", base.to_string, sub, context); base.parse_element (/<cim:SurgeArresterInfo.lineDischargeClass>([\s\S]*?)<\/cim:SurgeArresterInfo.lineDischargeClass>/g, obj, "lineDischargeClass", base.to_string, sub, context); base.parse_element (/<cim:SurgeArresterInfo.nominalDischargeCurrent>([\s\S]*?)<\/cim:SurgeArresterInfo.nominalDischargeCurrent>/g, obj, "nominalDischargeCurrent", base.to_string, sub, context); base.parse_element (/<cim:SurgeArresterInfo.pressureReliefClass>([\s\S]*?)<\/cim:SurgeArresterInfo.pressureReliefClass>/g, obj, "pressureReliefClass", base.to_string, sub, context); base.parse_element (/<cim:SurgeArresterInfo.ratedVoltage>([\s\S]*?)<\/cim:SurgeArresterInfo.ratedVoltage>/g, obj, "ratedVoltage", base.to_string, sub, context); base.parse_element (/<cim:SurgeArresterInfo.steepFrontDischargeVoltage>([\s\S]*?)<\/cim:SurgeArresterInfo.steepFrontDischargeVoltage>/g, obj, "steepFrontDischargeVoltage", base.to_string, sub, context); base.parse_element (/<cim:SurgeArresterInfo.switchingImpulseDischargeVoltage>([\s\S]*?)<\/cim:SurgeArresterInfo.switchingImpulseDischargeVoltage>/g, obj, "switchingImpulseDischargeVoltage", base.to_string, sub, context); let bucket = context.parsed.SurgeArresterInfo; if (null == bucket) context.parsed.SurgeArresterInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Assets.AssetInfo.prototype.export.call (this, obj, false); base.export_element (obj, "SurgeArresterInfo", "continuousOperatingVoltage", "continuousOperatingVoltage", base.from_string, fields); base.export_element (obj, "SurgeArresterInfo", "isPolymer", "isPolymer", base.from_boolean, fields); base.export_element (obj, "SurgeArresterInfo", "lightningImpulseDischargeVoltage", "lightningImpulseDischargeVoltage", base.from_string, fields); base.export_element (obj, "SurgeArresterInfo", "lineDischargeClass", "lineDischargeClass", base.from_string, fields); base.export_element (obj, "SurgeArresterInfo", "nominalDischargeCurrent", "nominalDischargeCurrent", base.from_string, fields); base.export_element (obj, "SurgeArresterInfo", "pressureReliefClass", "pressureReliefClass", base.from_string, fields); base.export_element (obj, "SurgeArresterInfo", "ratedVoltage", "ratedVoltage", base.from_string, fields); base.export_element (obj, "SurgeArresterInfo", "steepFrontDischargeVoltage", "steepFrontDischargeVoltage", base.from_string, fields); base.export_element (obj, "SurgeArresterInfo", "switchingImpulseDischargeVoltage", "switchingImpulseDischargeVoltage", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#SurgeArresterInfo_collapse" aria-expanded="true" aria-controls="SurgeArresterInfo_collapse" style="margin-left: 10px;">SurgeArresterInfo</a></legend> <div id="SurgeArresterInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.template.call (this) + ` {{#continuousOperatingVoltage}}<div><b>continuousOperatingVoltage</b>: {{continuousOperatingVoltage}}</div>{{/continuousOperatingVoltage}} {{#isPolymer}}<div><b>isPolymer</b>: {{isPolymer}}</div>{{/isPolymer}} {{#lightningImpulseDischargeVoltage}}<div><b>lightningImpulseDischargeVoltage</b>: {{lightningImpulseDischargeVoltage}}</div>{{/lightningImpulseDischargeVoltage}} {{#lineDischargeClass}}<div><b>lineDischargeClass</b>: {{lineDischargeClass}}</div>{{/lineDischargeClass}} {{#nominalDischargeCurrent}}<div><b>nominalDischargeCurrent</b>: {{nominalDischargeCurrent}}</div>{{/nominalDischargeCurrent}} {{#pressureReliefClass}}<div><b>pressureReliefClass</b>: {{pressureReliefClass}}</div>{{/pressureReliefClass}} {{#ratedVoltage}}<div><b>ratedVoltage</b>: {{ratedVoltage}}</div>{{/ratedVoltage}} {{#steepFrontDischargeVoltage}}<div><b>steepFrontDischargeVoltage</b>: {{steepFrontDischargeVoltage}}</div>{{/steepFrontDischargeVoltage}} {{#switchingImpulseDischargeVoltage}}<div><b>switchingImpulseDischargeVoltage</b>: {{switchingImpulseDischargeVoltage}}</div>{{/switchingImpulseDischargeVoltage}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_SurgeArresterInfo_collapse" aria-expanded="true" aria-controls="{{id}}_SurgeArresterInfo_collapse" style="margin-left: 10px;">SurgeArresterInfo</a></legend> <div id="{{id}}_SurgeArresterInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_continuousOperatingVoltage'>continuousOperatingVoltage: </label><div class='col-sm-8'><input id='{{id}}_continuousOperatingVoltage' class='form-control' type='text'{{#continuousOperatingVoltage}} value='{{continuousOperatingVoltage}}'{{/continuousOperatingVoltage}}></div></div> <div class='form-group row'><div class='col-sm-4' for='{{id}}_isPolymer'>isPolymer: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_isPolymer' class='form-check-input' type='checkbox'{{#isPolymer}} checked{{/isPolymer}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lightningImpulseDischargeVoltage'>lightningImpulseDischargeVoltage: </label><div class='col-sm-8'><input id='{{id}}_lightningImpulseDischargeVoltage' class='form-control' type='text'{{#lightningImpulseDischargeVoltage}} value='{{lightningImpulseDischargeVoltage}}'{{/lightningImpulseDischargeVoltage}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lineDischargeClass'>lineDischargeClass: </label><div class='col-sm-8'><input id='{{id}}_lineDischargeClass' class='form-control' type='text'{{#lineDischargeClass}} value='{{lineDischargeClass}}'{{/lineDischargeClass}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_nominalDischargeCurrent'>nominalDischargeCurrent: </label><div class='col-sm-8'><input id='{{id}}_nominalDischargeCurrent' class='form-control' type='text'{{#nominalDischargeCurrent}} value='{{nominalDischargeCurrent}}'{{/nominalDischargeCurrent}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_pressureReliefClass'>pressureReliefClass: </label><div class='col-sm-8'><input id='{{id}}_pressureReliefClass' class='form-control' type='text'{{#pressureReliefClass}} value='{{pressureReliefClass}}'{{/pressureReliefClass}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ratedVoltage'>ratedVoltage: </label><div class='col-sm-8'><input id='{{id}}_ratedVoltage' class='form-control' type='text'{{#ratedVoltage}} value='{{ratedVoltage}}'{{/ratedVoltage}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_steepFrontDischargeVoltage'>steepFrontDischargeVoltage: </label><div class='col-sm-8'><input id='{{id}}_steepFrontDischargeVoltage' class='form-control' type='text'{{#steepFrontDischargeVoltage}} value='{{steepFrontDischargeVoltage}}'{{/steepFrontDischargeVoltage}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_switchingImpulseDischargeVoltage'>switchingImpulseDischargeVoltage: </label><div class='col-sm-8'><input id='{{id}}_switchingImpulseDischargeVoltage' class='form-control' type='text'{{#switchingImpulseDischargeVoltage}} value='{{switchingImpulseDischargeVoltage}}'{{/switchingImpulseDischargeVoltage}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "SurgeArresterInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_continuousOperatingVoltage").value; if ("" !== temp) obj["continuousOperatingVoltage"] = temp; temp = document.getElementById (id + "_isPolymer").checked; if (temp) obj["isPolymer"] = true; temp = document.getElementById (id + "_lightningImpulseDischargeVoltage").value; if ("" !== temp) obj["lightningImpulseDischargeVoltage"] = temp; temp = document.getElementById (id + "_lineDischargeClass").value; if ("" !== temp) obj["lineDischargeClass"] = temp; temp = document.getElementById (id + "_nominalDischargeCurrent").value; if ("" !== temp) obj["nominalDischargeCurrent"] = temp; temp = document.getElementById (id + "_pressureReliefClass").value; if ("" !== temp) obj["pressureReliefClass"] = temp; temp = document.getElementById (id + "_ratedVoltage").value; if ("" !== temp) obj["ratedVoltage"] = temp; temp = document.getElementById (id + "_steepFrontDischargeVoltage").value; if ("" !== temp) obj["steepFrontDischargeVoltage"] = temp; temp = document.getElementById (id + "_switchingImpulseDischargeVoltage").value; if ("" !== temp) obj["switchingImpulseDischargeVoltage"] = temp; return (obj); } }
JavaScript
class ProtectionEquipmentInfo extends Assets.AssetInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ProtectionEquipmentInfo; if (null == bucket) cim_data.ProtectionEquipmentInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ProtectionEquipmentInfo[obj.id]; } parse (context, sub) { let obj = Assets.AssetInfo.prototype.parse.call (this, context, sub); obj.cls = "ProtectionEquipmentInfo"; base.parse_element (/<cim:ProtectionEquipmentInfo.groundTrip>([\s\S]*?)<\/cim:ProtectionEquipmentInfo.groundTrip>/g, obj, "groundTrip", base.to_string, sub, context); base.parse_element (/<cim:ProtectionEquipmentInfo.phaseTrip>([\s\S]*?)<\/cim:ProtectionEquipmentInfo.phaseTrip>/g, obj, "phaseTrip", base.to_string, sub, context); let bucket = context.parsed.ProtectionEquipmentInfo; if (null == bucket) context.parsed.ProtectionEquipmentInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Assets.AssetInfo.prototype.export.call (this, obj, false); base.export_element (obj, "ProtectionEquipmentInfo", "groundTrip", "groundTrip", base.from_string, fields); base.export_element (obj, "ProtectionEquipmentInfo", "phaseTrip", "phaseTrip", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ProtectionEquipmentInfo_collapse" aria-expanded="true" aria-controls="ProtectionEquipmentInfo_collapse" style="margin-left: 10px;">ProtectionEquipmentInfo</a></legend> <div id="ProtectionEquipmentInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.template.call (this) + ` {{#groundTrip}}<div><b>groundTrip</b>: {{groundTrip}}</div>{{/groundTrip}} {{#phaseTrip}}<div><b>phaseTrip</b>: {{phaseTrip}}</div>{{/phaseTrip}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ProtectionEquipmentInfo_collapse" aria-expanded="true" aria-controls="{{id}}_ProtectionEquipmentInfo_collapse" style="margin-left: 10px;">ProtectionEquipmentInfo</a></legend> <div id="{{id}}_ProtectionEquipmentInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_groundTrip'>groundTrip: </label><div class='col-sm-8'><input id='{{id}}_groundTrip' class='form-control' type='text'{{#groundTrip}} value='{{groundTrip}}'{{/groundTrip}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_phaseTrip'>phaseTrip: </label><div class='col-sm-8'><input id='{{id}}_phaseTrip' class='form-control' type='text'{{#phaseTrip}} value='{{phaseTrip}}'{{/phaseTrip}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ProtectionEquipmentInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_groundTrip").value; if ("" !== temp) obj["groundTrip"] = temp; temp = document.getElementById (id + "_phaseTrip").value; if ("" !== temp) obj["phaseTrip"] = temp; return (obj); } }
JavaScript
class CompositeSwitchInfo extends Assets.AssetInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.CompositeSwitchInfo; if (null == bucket) cim_data.CompositeSwitchInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.CompositeSwitchInfo[obj.id]; } parse (context, sub) { let obj = Assets.AssetInfo.prototype.parse.call (this, context, sub); obj.cls = "CompositeSwitchInfo"; base.parse_element (/<cim:CompositeSwitchInfo.ganged>([\s\S]*?)<\/cim:CompositeSwitchInfo.ganged>/g, obj, "ganged", base.to_boolean, sub, context); base.parse_element (/<cim:CompositeSwitchInfo.initOpMode>([\s\S]*?)<\/cim:CompositeSwitchInfo.initOpMode>/g, obj, "initOpMode", base.to_string, sub, context); base.parse_element (/<cim:CompositeSwitchInfo.interruptingRating>([\s\S]*?)<\/cim:CompositeSwitchInfo.interruptingRating>/g, obj, "interruptingRating", base.to_string, sub, context); base.parse_attribute (/<cim:CompositeSwitchInfo.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context); base.parse_attribute (/<cim:CompositeSwitchInfo.phaseCode\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "phaseCode", sub, context); base.parse_element (/<cim:CompositeSwitchInfo.phaseCount>([\s\S]*?)<\/cim:CompositeSwitchInfo.phaseCount>/g, obj, "phaseCount", base.to_string, sub, context); base.parse_element (/<cim:CompositeSwitchInfo.ratedVoltage>([\s\S]*?)<\/cim:CompositeSwitchInfo.ratedVoltage>/g, obj, "ratedVoltage", base.to_string, sub, context); base.parse_element (/<cim:CompositeSwitchInfo.remote>([\s\S]*?)<\/cim:CompositeSwitchInfo.remote>/g, obj, "remote", base.to_boolean, sub, context); base.parse_element (/<cim:CompositeSwitchInfo.switchStateCount>([\s\S]*?)<\/cim:CompositeSwitchInfo.switchStateCount>/g, obj, "switchStateCount", base.to_string, sub, context); let bucket = context.parsed.CompositeSwitchInfo; if (null == bucket) context.parsed.CompositeSwitchInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Assets.AssetInfo.prototype.export.call (this, obj, false); base.export_element (obj, "CompositeSwitchInfo", "ganged", "ganged", base.from_boolean, fields); base.export_element (obj, "CompositeSwitchInfo", "initOpMode", "initOpMode", base.from_string, fields); base.export_element (obj, "CompositeSwitchInfo", "interruptingRating", "interruptingRating", base.from_string, fields); base.export_attribute (obj, "CompositeSwitchInfo", "kind", "kind", fields); base.export_attribute (obj, "CompositeSwitchInfo", "phaseCode", "phaseCode", fields); base.export_element (obj, "CompositeSwitchInfo", "phaseCount", "phaseCount", base.from_string, fields); base.export_element (obj, "CompositeSwitchInfo", "ratedVoltage", "ratedVoltage", base.from_string, fields); base.export_element (obj, "CompositeSwitchInfo", "remote", "remote", base.from_boolean, fields); base.export_element (obj, "CompositeSwitchInfo", "switchStateCount", "switchStateCount", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#CompositeSwitchInfo_collapse" aria-expanded="true" aria-controls="CompositeSwitchInfo_collapse" style="margin-left: 10px;">CompositeSwitchInfo</a></legend> <div id="CompositeSwitchInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.template.call (this) + ` {{#ganged}}<div><b>ganged</b>: {{ganged}}</div>{{/ganged}} {{#initOpMode}}<div><b>initOpMode</b>: {{initOpMode}}</div>{{/initOpMode}} {{#interruptingRating}}<div><b>interruptingRating</b>: {{interruptingRating}}</div>{{/interruptingRating}} {{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}} {{#phaseCode}}<div><b>phaseCode</b>: {{phaseCode}}</div>{{/phaseCode}} {{#phaseCount}}<div><b>phaseCount</b>: {{phaseCount}}</div>{{/phaseCount}} {{#ratedVoltage}}<div><b>ratedVoltage</b>: {{ratedVoltage}}</div>{{/ratedVoltage}} {{#remote}}<div><b>remote</b>: {{remote}}</div>{{/remote}} {{#switchStateCount}}<div><b>switchStateCount</b>: {{switchStateCount}}</div>{{/switchStateCount}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["kindCompositeSwitchKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in CompositeSwitchKind) obj["kindCompositeSwitchKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)}); obj["phaseCodePhaseCode"] = [{ id: '', selected: (!obj["phaseCode"])}]; for (let property in Core.PhaseCode) obj["phaseCodePhaseCode"].push ({ id: property, selected: obj["phaseCode"] && obj["phaseCode"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["kindCompositeSwitchKind"]; delete obj["phaseCodePhaseCode"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_CompositeSwitchInfo_collapse" aria-expanded="true" aria-controls="{{id}}_CompositeSwitchInfo_collapse" style="margin-left: 10px;">CompositeSwitchInfo</a></legend> <div id="{{id}}_CompositeSwitchInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><div class='col-sm-4' for='{{id}}_ganged'>ganged: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_ganged' class='form-check-input' type='checkbox'{{#ganged}} checked{{/ganged}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_initOpMode'>initOpMode: </label><div class='col-sm-8'><input id='{{id}}_initOpMode' class='form-control' type='text'{{#initOpMode}} value='{{initOpMode}}'{{/initOpMode}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_interruptingRating'>interruptingRating: </label><div class='col-sm-8'><input id='{{id}}_interruptingRating' class='form-control' type='text'{{#interruptingRating}} value='{{interruptingRating}}'{{/interruptingRating}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindCompositeSwitchKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindCompositeSwitchKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_phaseCode'>phaseCode: </label><div class='col-sm-8'><select id='{{id}}_phaseCode' class='form-control custom-select'>{{#phaseCodePhaseCode}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/phaseCodePhaseCode}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_phaseCount'>phaseCount: </label><div class='col-sm-8'><input id='{{id}}_phaseCount' class='form-control' type='text'{{#phaseCount}} value='{{phaseCount}}'{{/phaseCount}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ratedVoltage'>ratedVoltage: </label><div class='col-sm-8'><input id='{{id}}_ratedVoltage' class='form-control' type='text'{{#ratedVoltage}} value='{{ratedVoltage}}'{{/ratedVoltage}}></div></div> <div class='form-group row'><div class='col-sm-4' for='{{id}}_remote'>remote: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_remote' class='form-check-input' type='checkbox'{{#remote}} checked{{/remote}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_switchStateCount'>switchStateCount: </label><div class='col-sm-8'><input id='{{id}}_switchStateCount' class='form-control' type='text'{{#switchStateCount}} value='{{switchStateCount}}'{{/switchStateCount}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "CompositeSwitchInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_ganged").checked; if (temp) obj["ganged"] = true; temp = document.getElementById (id + "_initOpMode").value; if ("" !== temp) obj["initOpMode"] = temp; temp = document.getElementById (id + "_interruptingRating").value; if ("" !== temp) obj["interruptingRating"] = temp; temp = CompositeSwitchKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#CompositeSwitchKind." + temp; else delete obj["kind"]; temp = Core.PhaseCode[document.getElementById (id + "_phaseCode").value]; if (temp) obj["phaseCode"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#PhaseCode." + temp; else delete obj["phaseCode"]; temp = document.getElementById (id + "_phaseCount").value; if ("" !== temp) obj["phaseCount"] = temp; temp = document.getElementById (id + "_ratedVoltage").value; if ("" !== temp) obj["ratedVoltage"] = temp; temp = document.getElementById (id + "_remote").checked; if (temp) obj["remote"] = true; temp = document.getElementById (id + "_switchStateCount").value; if ("" !== temp) obj["switchStateCount"] = temp; return (obj); } }
JavaScript
class PotentialTransformerInfo extends Assets.AssetInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.PotentialTransformerInfo; if (null == bucket) cim_data.PotentialTransformerInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.PotentialTransformerInfo[obj.id]; } parse (context, sub) { let obj = Assets.AssetInfo.prototype.parse.call (this, context, sub); obj.cls = "PotentialTransformerInfo"; base.parse_element (/<cim:PotentialTransformerInfo.accuracyClass>([\s\S]*?)<\/cim:PotentialTransformerInfo.accuracyClass>/g, obj, "accuracyClass", base.to_string, sub, context); base.parse_attribute (/<cim:PotentialTransformerInfo.nominalRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "nominalRatio", sub, context); base.parse_attribute (/<cim:PotentialTransformerInfo.primaryRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "primaryRatio", sub, context); base.parse_element (/<cim:PotentialTransformerInfo.ptClass>([\s\S]*?)<\/cim:PotentialTransformerInfo.ptClass>/g, obj, "ptClass", base.to_string, sub, context); base.parse_element (/<cim:PotentialTransformerInfo.ratedVoltage>([\s\S]*?)<\/cim:PotentialTransformerInfo.ratedVoltage>/g, obj, "ratedVoltage", base.to_string, sub, context); base.parse_attribute (/<cim:PotentialTransformerInfo.secondaryRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "secondaryRatio", sub, context); base.parse_attribute (/<cim:PotentialTransformerInfo.tertiaryRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "tertiaryRatio", sub, context); let bucket = context.parsed.PotentialTransformerInfo; if (null == bucket) context.parsed.PotentialTransformerInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Assets.AssetInfo.prototype.export.call (this, obj, false); base.export_element (obj, "PotentialTransformerInfo", "accuracyClass", "accuracyClass", base.from_string, fields); base.export_attribute (obj, "PotentialTransformerInfo", "nominalRatio", "nominalRatio", fields); base.export_attribute (obj, "PotentialTransformerInfo", "primaryRatio", "primaryRatio", fields); base.export_element (obj, "PotentialTransformerInfo", "ptClass", "ptClass", base.from_string, fields); base.export_element (obj, "PotentialTransformerInfo", "ratedVoltage", "ratedVoltage", base.from_string, fields); base.export_attribute (obj, "PotentialTransformerInfo", "secondaryRatio", "secondaryRatio", fields); base.export_attribute (obj, "PotentialTransformerInfo", "tertiaryRatio", "tertiaryRatio", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#PotentialTransformerInfo_collapse" aria-expanded="true" aria-controls="PotentialTransformerInfo_collapse" style="margin-left: 10px;">PotentialTransformerInfo</a></legend> <div id="PotentialTransformerInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.template.call (this) + ` {{#accuracyClass}}<div><b>accuracyClass</b>: {{accuracyClass}}</div>{{/accuracyClass}} {{#nominalRatio}}<div><b>nominalRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{nominalRatio}}");}); return false;'>{{nominalRatio}}</a></div>{{/nominalRatio}} {{#primaryRatio}}<div><b>primaryRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{primaryRatio}}");}); return false;'>{{primaryRatio}}</a></div>{{/primaryRatio}} {{#ptClass}}<div><b>ptClass</b>: {{ptClass}}</div>{{/ptClass}} {{#ratedVoltage}}<div><b>ratedVoltage</b>: {{ratedVoltage}}</div>{{/ratedVoltage}} {{#secondaryRatio}}<div><b>secondaryRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{secondaryRatio}}");}); return false;'>{{secondaryRatio}}</a></div>{{/secondaryRatio}} {{#tertiaryRatio}}<div><b>tertiaryRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{tertiaryRatio}}");}); return false;'>{{tertiaryRatio}}</a></div>{{/tertiaryRatio}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_PotentialTransformerInfo_collapse" aria-expanded="true" aria-controls="{{id}}_PotentialTransformerInfo_collapse" style="margin-left: 10px;">PotentialTransformerInfo</a></legend> <div id="{{id}}_PotentialTransformerInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_accuracyClass'>accuracyClass: </label><div class='col-sm-8'><input id='{{id}}_accuracyClass' class='form-control' type='text'{{#accuracyClass}} value='{{accuracyClass}}'{{/accuracyClass}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_nominalRatio'>nominalRatio: </label><div class='col-sm-8'><input id='{{id}}_nominalRatio' class='form-control' type='text'{{#nominalRatio}} value='{{nominalRatio}}'{{/nominalRatio}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_primaryRatio'>primaryRatio: </label><div class='col-sm-8'><input id='{{id}}_primaryRatio' class='form-control' type='text'{{#primaryRatio}} value='{{primaryRatio}}'{{/primaryRatio}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ptClass'>ptClass: </label><div class='col-sm-8'><input id='{{id}}_ptClass' class='form-control' type='text'{{#ptClass}} value='{{ptClass}}'{{/ptClass}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ratedVoltage'>ratedVoltage: </label><div class='col-sm-8'><input id='{{id}}_ratedVoltage' class='form-control' type='text'{{#ratedVoltage}} value='{{ratedVoltage}}'{{/ratedVoltage}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_secondaryRatio'>secondaryRatio: </label><div class='col-sm-8'><input id='{{id}}_secondaryRatio' class='form-control' type='text'{{#secondaryRatio}} value='{{secondaryRatio}}'{{/secondaryRatio}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tertiaryRatio'>tertiaryRatio: </label><div class='col-sm-8'><input id='{{id}}_tertiaryRatio' class='form-control' type='text'{{#tertiaryRatio}} value='{{tertiaryRatio}}'{{/tertiaryRatio}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "PotentialTransformerInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_accuracyClass").value; if ("" !== temp) obj["accuracyClass"] = temp; temp = document.getElementById (id + "_nominalRatio").value; if ("" !== temp) obj["nominalRatio"] = temp; temp = document.getElementById (id + "_primaryRatio").value; if ("" !== temp) obj["primaryRatio"] = temp; temp = document.getElementById (id + "_ptClass").value; if ("" !== temp) obj["ptClass"] = temp; temp = document.getElementById (id + "_ratedVoltage").value; if ("" !== temp) obj["ratedVoltage"] = temp; temp = document.getElementById (id + "_secondaryRatio").value; if ("" !== temp) obj["secondaryRatio"] = temp; temp = document.getElementById (id + "_tertiaryRatio").value; if ("" !== temp) obj["tertiaryRatio"] = temp; return (obj); } }
JavaScript
class AssetModelCatalogue extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.AssetModelCatalogue; if (null == bucket) cim_data.AssetModelCatalogue = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.AssetModelCatalogue[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "AssetModelCatalogue"; base.parse_attribute (/<cim:AssetModelCatalogue.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attributes (/<cim:AssetModelCatalogue.AssetModelCatalogueItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetModelCatalogueItems", sub, context); let bucket = context.parsed.AssetModelCatalogue; if (null == bucket) context.parsed.AssetModelCatalogue = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "AssetModelCatalogue", "status", "status", fields); base.export_attributes (obj, "AssetModelCatalogue", "AssetModelCatalogueItems", "AssetModelCatalogueItems", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetModelCatalogue_collapse" aria-expanded="true" aria-controls="AssetModelCatalogue_collapse" style="margin-left: 10px;">AssetModelCatalogue</a></legend> <div id="AssetModelCatalogue_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#AssetModelCatalogueItems}}<div><b>AssetModelCatalogueItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetModelCatalogueItems}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["AssetModelCatalogueItems"]) obj["AssetModelCatalogueItems_string"] = obj["AssetModelCatalogueItems"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["AssetModelCatalogueItems_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetModelCatalogue_collapse" aria-expanded="true" aria-controls="{{id}}_AssetModelCatalogue_collapse" style="margin-left: 10px;">AssetModelCatalogue</a></legend> <div id="{{id}}_AssetModelCatalogue_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "AssetModelCatalogue" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["AssetModelCatalogueItems", "0..*", "1", "AssetModelCatalogueItem", "AssetModelCatalogue"] ] ) ); } }
JavaScript
class CurrentTransformerInfo extends Assets.AssetInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.CurrentTransformerInfo; if (null == bucket) cim_data.CurrentTransformerInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.CurrentTransformerInfo[obj.id]; } parse (context, sub) { let obj = Assets.AssetInfo.prototype.parse.call (this, context, sub); obj.cls = "CurrentTransformerInfo"; base.parse_element (/<cim:CurrentTransformerInfo.accuracyClass>([\s\S]*?)<\/cim:CurrentTransformerInfo.accuracyClass>/g, obj, "accuracyClass", base.to_string, sub, context); base.parse_element (/<cim:CurrentTransformerInfo.accuracyLimit>([\s\S]*?)<\/cim:CurrentTransformerInfo.accuracyLimit>/g, obj, "accuracyLimit", base.to_string, sub, context); base.parse_element (/<cim:CurrentTransformerInfo.coreCount>([\s\S]*?)<\/cim:CurrentTransformerInfo.coreCount>/g, obj, "coreCount", base.to_string, sub, context); base.parse_element (/<cim:CurrentTransformerInfo.ctClass>([\s\S]*?)<\/cim:CurrentTransformerInfo.ctClass>/g, obj, "ctClass", base.to_string, sub, context); base.parse_element (/<cim:CurrentTransformerInfo.kneePointCurrent>([\s\S]*?)<\/cim:CurrentTransformerInfo.kneePointCurrent>/g, obj, "kneePointCurrent", base.to_string, sub, context); base.parse_element (/<cim:CurrentTransformerInfo.kneePointVoltage>([\s\S]*?)<\/cim:CurrentTransformerInfo.kneePointVoltage>/g, obj, "kneePointVoltage", base.to_string, sub, context); base.parse_attribute (/<cim:CurrentTransformerInfo.maxRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "maxRatio", sub, context); base.parse_attribute (/<cim:CurrentTransformerInfo.nominalRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "nominalRatio", sub, context); base.parse_element (/<cim:CurrentTransformerInfo.primaryFlsRating>([\s\S]*?)<\/cim:CurrentTransformerInfo.primaryFlsRating>/g, obj, "primaryFlsRating", base.to_string, sub, context); base.parse_attribute (/<cim:CurrentTransformerInfo.primaryRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "primaryRatio", sub, context); base.parse_element (/<cim:CurrentTransformerInfo.ratedCurrent>([\s\S]*?)<\/cim:CurrentTransformerInfo.ratedCurrent>/g, obj, "ratedCurrent", base.to_string, sub, context); base.parse_element (/<cim:CurrentTransformerInfo.secondaryFlsRating>([\s\S]*?)<\/cim:CurrentTransformerInfo.secondaryFlsRating>/g, obj, "secondaryFlsRating", base.to_string, sub, context); base.parse_attribute (/<cim:CurrentTransformerInfo.secondaryRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "secondaryRatio", sub, context); base.parse_element (/<cim:CurrentTransformerInfo.tertiaryFlsRating>([\s\S]*?)<\/cim:CurrentTransformerInfo.tertiaryFlsRating>/g, obj, "tertiaryFlsRating", base.to_string, sub, context); base.parse_attribute (/<cim:CurrentTransformerInfo.tertiaryRatio\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "tertiaryRatio", sub, context); base.parse_element (/<cim:CurrentTransformerInfo.usage>([\s\S]*?)<\/cim:CurrentTransformerInfo.usage>/g, obj, "usage", base.to_string, sub, context); let bucket = context.parsed.CurrentTransformerInfo; if (null == bucket) context.parsed.CurrentTransformerInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Assets.AssetInfo.prototype.export.call (this, obj, false); base.export_element (obj, "CurrentTransformerInfo", "accuracyClass", "accuracyClass", base.from_string, fields); base.export_element (obj, "CurrentTransformerInfo", "accuracyLimit", "accuracyLimit", base.from_string, fields); base.export_element (obj, "CurrentTransformerInfo", "coreCount", "coreCount", base.from_string, fields); base.export_element (obj, "CurrentTransformerInfo", "ctClass", "ctClass", base.from_string, fields); base.export_element (obj, "CurrentTransformerInfo", "kneePointCurrent", "kneePointCurrent", base.from_string, fields); base.export_element (obj, "CurrentTransformerInfo", "kneePointVoltage", "kneePointVoltage", base.from_string, fields); base.export_attribute (obj, "CurrentTransformerInfo", "maxRatio", "maxRatio", fields); base.export_attribute (obj, "CurrentTransformerInfo", "nominalRatio", "nominalRatio", fields); base.export_element (obj, "CurrentTransformerInfo", "primaryFlsRating", "primaryFlsRating", base.from_string, fields); base.export_attribute (obj, "CurrentTransformerInfo", "primaryRatio", "primaryRatio", fields); base.export_element (obj, "CurrentTransformerInfo", "ratedCurrent", "ratedCurrent", base.from_string, fields); base.export_element (obj, "CurrentTransformerInfo", "secondaryFlsRating", "secondaryFlsRating", base.from_string, fields); base.export_attribute (obj, "CurrentTransformerInfo", "secondaryRatio", "secondaryRatio", fields); base.export_element (obj, "CurrentTransformerInfo", "tertiaryFlsRating", "tertiaryFlsRating", base.from_string, fields); base.export_attribute (obj, "CurrentTransformerInfo", "tertiaryRatio", "tertiaryRatio", fields); base.export_element (obj, "CurrentTransformerInfo", "usage", "usage", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#CurrentTransformerInfo_collapse" aria-expanded="true" aria-controls="CurrentTransformerInfo_collapse" style="margin-left: 10px;">CurrentTransformerInfo</a></legend> <div id="CurrentTransformerInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.template.call (this) + ` {{#accuracyClass}}<div><b>accuracyClass</b>: {{accuracyClass}}</div>{{/accuracyClass}} {{#accuracyLimit}}<div><b>accuracyLimit</b>: {{accuracyLimit}}</div>{{/accuracyLimit}} {{#coreCount}}<div><b>coreCount</b>: {{coreCount}}</div>{{/coreCount}} {{#ctClass}}<div><b>ctClass</b>: {{ctClass}}</div>{{/ctClass}} {{#kneePointCurrent}}<div><b>kneePointCurrent</b>: {{kneePointCurrent}}</div>{{/kneePointCurrent}} {{#kneePointVoltage}}<div><b>kneePointVoltage</b>: {{kneePointVoltage}}</div>{{/kneePointVoltage}} {{#maxRatio}}<div><b>maxRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{maxRatio}}");}); return false;'>{{maxRatio}}</a></div>{{/maxRatio}} {{#nominalRatio}}<div><b>nominalRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{nominalRatio}}");}); return false;'>{{nominalRatio}}</a></div>{{/nominalRatio}} {{#primaryFlsRating}}<div><b>primaryFlsRating</b>: {{primaryFlsRating}}</div>{{/primaryFlsRating}} {{#primaryRatio}}<div><b>primaryRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{primaryRatio}}");}); return false;'>{{primaryRatio}}</a></div>{{/primaryRatio}} {{#ratedCurrent}}<div><b>ratedCurrent</b>: {{ratedCurrent}}</div>{{/ratedCurrent}} {{#secondaryFlsRating}}<div><b>secondaryFlsRating</b>: {{secondaryFlsRating}}</div>{{/secondaryFlsRating}} {{#secondaryRatio}}<div><b>secondaryRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{secondaryRatio}}");}); return false;'>{{secondaryRatio}}</a></div>{{/secondaryRatio}} {{#tertiaryFlsRating}}<div><b>tertiaryFlsRating</b>: {{tertiaryFlsRating}}</div>{{/tertiaryFlsRating}} {{#tertiaryRatio}}<div><b>tertiaryRatio</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{tertiaryRatio}}");}); return false;'>{{tertiaryRatio}}</a></div>{{/tertiaryRatio}} {{#usage}}<div><b>usage</b>: {{usage}}</div>{{/usage}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_CurrentTransformerInfo_collapse" aria-expanded="true" aria-controls="{{id}}_CurrentTransformerInfo_collapse" style="margin-left: 10px;">CurrentTransformerInfo</a></legend> <div id="{{id}}_CurrentTransformerInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_accuracyClass'>accuracyClass: </label><div class='col-sm-8'><input id='{{id}}_accuracyClass' class='form-control' type='text'{{#accuracyClass}} value='{{accuracyClass}}'{{/accuracyClass}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_accuracyLimit'>accuracyLimit: </label><div class='col-sm-8'><input id='{{id}}_accuracyLimit' class='form-control' type='text'{{#accuracyLimit}} value='{{accuracyLimit}}'{{/accuracyLimit}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_coreCount'>coreCount: </label><div class='col-sm-8'><input id='{{id}}_coreCount' class='form-control' type='text'{{#coreCount}} value='{{coreCount}}'{{/coreCount}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ctClass'>ctClass: </label><div class='col-sm-8'><input id='{{id}}_ctClass' class='form-control' type='text'{{#ctClass}} value='{{ctClass}}'{{/ctClass}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kneePointCurrent'>kneePointCurrent: </label><div class='col-sm-8'><input id='{{id}}_kneePointCurrent' class='form-control' type='text'{{#kneePointCurrent}} value='{{kneePointCurrent}}'{{/kneePointCurrent}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kneePointVoltage'>kneePointVoltage: </label><div class='col-sm-8'><input id='{{id}}_kneePointVoltage' class='form-control' type='text'{{#kneePointVoltage}} value='{{kneePointVoltage}}'{{/kneePointVoltage}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_maxRatio'>maxRatio: </label><div class='col-sm-8'><input id='{{id}}_maxRatio' class='form-control' type='text'{{#maxRatio}} value='{{maxRatio}}'{{/maxRatio}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_nominalRatio'>nominalRatio: </label><div class='col-sm-8'><input id='{{id}}_nominalRatio' class='form-control' type='text'{{#nominalRatio}} value='{{nominalRatio}}'{{/nominalRatio}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_primaryFlsRating'>primaryFlsRating: </label><div class='col-sm-8'><input id='{{id}}_primaryFlsRating' class='form-control' type='text'{{#primaryFlsRating}} value='{{primaryFlsRating}}'{{/primaryFlsRating}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_primaryRatio'>primaryRatio: </label><div class='col-sm-8'><input id='{{id}}_primaryRatio' class='form-control' type='text'{{#primaryRatio}} value='{{primaryRatio}}'{{/primaryRatio}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ratedCurrent'>ratedCurrent: </label><div class='col-sm-8'><input id='{{id}}_ratedCurrent' class='form-control' type='text'{{#ratedCurrent}} value='{{ratedCurrent}}'{{/ratedCurrent}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_secondaryFlsRating'>secondaryFlsRating: </label><div class='col-sm-8'><input id='{{id}}_secondaryFlsRating' class='form-control' type='text'{{#secondaryFlsRating}} value='{{secondaryFlsRating}}'{{/secondaryFlsRating}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_secondaryRatio'>secondaryRatio: </label><div class='col-sm-8'><input id='{{id}}_secondaryRatio' class='form-control' type='text'{{#secondaryRatio}} value='{{secondaryRatio}}'{{/secondaryRatio}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tertiaryFlsRating'>tertiaryFlsRating: </label><div class='col-sm-8'><input id='{{id}}_tertiaryFlsRating' class='form-control' type='text'{{#tertiaryFlsRating}} value='{{tertiaryFlsRating}}'{{/tertiaryFlsRating}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tertiaryRatio'>tertiaryRatio: </label><div class='col-sm-8'><input id='{{id}}_tertiaryRatio' class='form-control' type='text'{{#tertiaryRatio}} value='{{tertiaryRatio}}'{{/tertiaryRatio}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_usage'>usage: </label><div class='col-sm-8'><input id='{{id}}_usage' class='form-control' type='text'{{#usage}} value='{{usage}}'{{/usage}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "CurrentTransformerInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_accuracyClass").value; if ("" !== temp) obj["accuracyClass"] = temp; temp = document.getElementById (id + "_accuracyLimit").value; if ("" !== temp) obj["accuracyLimit"] = temp; temp = document.getElementById (id + "_coreCount").value; if ("" !== temp) obj["coreCount"] = temp; temp = document.getElementById (id + "_ctClass").value; if ("" !== temp) obj["ctClass"] = temp; temp = document.getElementById (id + "_kneePointCurrent").value; if ("" !== temp) obj["kneePointCurrent"] = temp; temp = document.getElementById (id + "_kneePointVoltage").value; if ("" !== temp) obj["kneePointVoltage"] = temp; temp = document.getElementById (id + "_maxRatio").value; if ("" !== temp) obj["maxRatio"] = temp; temp = document.getElementById (id + "_nominalRatio").value; if ("" !== temp) obj["nominalRatio"] = temp; temp = document.getElementById (id + "_primaryFlsRating").value; if ("" !== temp) obj["primaryFlsRating"] = temp; temp = document.getElementById (id + "_primaryRatio").value; if ("" !== temp) obj["primaryRatio"] = temp; temp = document.getElementById (id + "_ratedCurrent").value; if ("" !== temp) obj["ratedCurrent"] = temp; temp = document.getElementById (id + "_secondaryFlsRating").value; if ("" !== temp) obj["secondaryFlsRating"] = temp; temp = document.getElementById (id + "_secondaryRatio").value; if ("" !== temp) obj["secondaryRatio"] = temp; temp = document.getElementById (id + "_tertiaryFlsRating").value; if ("" !== temp) obj["tertiaryFlsRating"] = temp; temp = document.getElementById (id + "_tertiaryRatio").value; if ("" !== temp) obj["tertiaryRatio"] = temp; temp = document.getElementById (id + "_usage").value; if ("" !== temp) obj["usage"] = temp; return (obj); } }
JavaScript
class OldSwitchInfo extends AssetInfo.SwitchInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.OldSwitchInfo; if (null == bucket) cim_data.OldSwitchInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.OldSwitchInfo[obj.id]; } parse (context, sub) { let obj = AssetInfo.SwitchInfo.prototype.parse.call (this, context, sub); obj.cls = "OldSwitchInfo"; base.parse_element (/<cim:OldSwitchInfo.dielectricStrength>([\s\S]*?)<\/cim:OldSwitchInfo.dielectricStrength>/g, obj, "dielectricStrength", base.to_string, sub, context); base.parse_element (/<cim:OldSwitchInfo.loadBreak>([\s\S]*?)<\/cim:OldSwitchInfo.loadBreak>/g, obj, "loadBreak", base.to_boolean, sub, context); base.parse_element (/<cim:OldSwitchInfo.makingCapacity>([\s\S]*?)<\/cim:OldSwitchInfo.makingCapacity>/g, obj, "makingCapacity", base.to_string, sub, context); base.parse_element (/<cim:OldSwitchInfo.minimumCurrent>([\s\S]*?)<\/cim:OldSwitchInfo.minimumCurrent>/g, obj, "minimumCurrent", base.to_string, sub, context); base.parse_element (/<cim:OldSwitchInfo.poleCount>([\s\S]*?)<\/cim:OldSwitchInfo.poleCount>/g, obj, "poleCount", base.to_string, sub, context); base.parse_element (/<cim:OldSwitchInfo.remote>([\s\S]*?)<\/cim:OldSwitchInfo.remote>/g, obj, "remote", base.to_boolean, sub, context); base.parse_element (/<cim:OldSwitchInfo.withstandCurrent>([\s\S]*?)<\/cim:OldSwitchInfo.withstandCurrent>/g, obj, "withstandCurrent", base.to_string, sub, context); let bucket = context.parsed.OldSwitchInfo; if (null == bucket) context.parsed.OldSwitchInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = AssetInfo.SwitchInfo.prototype.export.call (this, obj, false); base.export_element (obj, "OldSwitchInfo", "dielectricStrength", "dielectricStrength", base.from_string, fields); base.export_element (obj, "OldSwitchInfo", "loadBreak", "loadBreak", base.from_boolean, fields); base.export_element (obj, "OldSwitchInfo", "makingCapacity", "makingCapacity", base.from_string, fields); base.export_element (obj, "OldSwitchInfo", "minimumCurrent", "minimumCurrent", base.from_string, fields); base.export_element (obj, "OldSwitchInfo", "poleCount", "poleCount", base.from_string, fields); base.export_element (obj, "OldSwitchInfo", "remote", "remote", base.from_boolean, fields); base.export_element (obj, "OldSwitchInfo", "withstandCurrent", "withstandCurrent", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#OldSwitchInfo_collapse" aria-expanded="true" aria-controls="OldSwitchInfo_collapse" style="margin-left: 10px;">OldSwitchInfo</a></legend> <div id="OldSwitchInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + AssetInfo.SwitchInfo.prototype.template.call (this) + ` {{#dielectricStrength}}<div><b>dielectricStrength</b>: {{dielectricStrength}}</div>{{/dielectricStrength}} {{#loadBreak}}<div><b>loadBreak</b>: {{loadBreak}}</div>{{/loadBreak}} {{#makingCapacity}}<div><b>makingCapacity</b>: {{makingCapacity}}</div>{{/makingCapacity}} {{#minimumCurrent}}<div><b>minimumCurrent</b>: {{minimumCurrent}}</div>{{/minimumCurrent}} {{#poleCount}}<div><b>poleCount</b>: {{poleCount}}</div>{{/poleCount}} {{#remote}}<div><b>remote</b>: {{remote}}</div>{{/remote}} {{#withstandCurrent}}<div><b>withstandCurrent</b>: {{withstandCurrent}}</div>{{/withstandCurrent}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_OldSwitchInfo_collapse" aria-expanded="true" aria-controls="{{id}}_OldSwitchInfo_collapse" style="margin-left: 10px;">OldSwitchInfo</a></legend> <div id="{{id}}_OldSwitchInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + AssetInfo.SwitchInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dielectricStrength'>dielectricStrength: </label><div class='col-sm-8'><input id='{{id}}_dielectricStrength' class='form-control' type='text'{{#dielectricStrength}} value='{{dielectricStrength}}'{{/dielectricStrength}}></div></div> <div class='form-group row'><div class='col-sm-4' for='{{id}}_loadBreak'>loadBreak: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_loadBreak' class='form-check-input' type='checkbox'{{#loadBreak}} checked{{/loadBreak}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_makingCapacity'>makingCapacity: </label><div class='col-sm-8'><input id='{{id}}_makingCapacity' class='form-control' type='text'{{#makingCapacity}} value='{{makingCapacity}}'{{/makingCapacity}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_minimumCurrent'>minimumCurrent: </label><div class='col-sm-8'><input id='{{id}}_minimumCurrent' class='form-control' type='text'{{#minimumCurrent}} value='{{minimumCurrent}}'{{/minimumCurrent}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_poleCount'>poleCount: </label><div class='col-sm-8'><input id='{{id}}_poleCount' class='form-control' type='text'{{#poleCount}} value='{{poleCount}}'{{/poleCount}}></div></div> <div class='form-group row'><div class='col-sm-4' for='{{id}}_remote'>remote: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_remote' class='form-check-input' type='checkbox'{{#remote}} checked{{/remote}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_withstandCurrent'>withstandCurrent: </label><div class='col-sm-8'><input id='{{id}}_withstandCurrent' class='form-control' type='text'{{#withstandCurrent}} value='{{withstandCurrent}}'{{/withstandCurrent}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "OldSwitchInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_dielectricStrength").value; if ("" !== temp) obj["dielectricStrength"] = temp; temp = document.getElementById (id + "_loadBreak").checked; if (temp) obj["loadBreak"] = true; temp = document.getElementById (id + "_makingCapacity").value; if ("" !== temp) obj["makingCapacity"] = temp; temp = document.getElementById (id + "_minimumCurrent").value; if ("" !== temp) obj["minimumCurrent"] = temp; temp = document.getElementById (id + "_poleCount").value; if ("" !== temp) obj["poleCount"] = temp; temp = document.getElementById (id + "_remote").checked; if (temp) obj["remote"] = true; temp = document.getElementById (id + "_withstandCurrent").value; if ("" !== temp) obj["withstandCurrent"] = temp; return (obj); } }
JavaScript
class FaultIndicatorInfo extends Assets.AssetInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.FaultIndicatorInfo; if (null == bucket) cim_data.FaultIndicatorInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.FaultIndicatorInfo[obj.id]; } parse (context, sub) { let obj = Assets.AssetInfo.prototype.parse.call (this, context, sub); obj.cls = "FaultIndicatorInfo"; base.parse_attribute (/<cim:FaultIndicatorInfo.resetKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "resetKind", sub, context); let bucket = context.parsed.FaultIndicatorInfo; if (null == bucket) context.parsed.FaultIndicatorInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Assets.AssetInfo.prototype.export.call (this, obj, false); base.export_attribute (obj, "FaultIndicatorInfo", "resetKind", "resetKind", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#FaultIndicatorInfo_collapse" aria-expanded="true" aria-controls="FaultIndicatorInfo_collapse" style="margin-left: 10px;">FaultIndicatorInfo</a></legend> <div id="FaultIndicatorInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.template.call (this) + ` {{#resetKind}}<div><b>resetKind</b>: {{resetKind}}</div>{{/resetKind}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["resetKindFaultIndicatorResetKind"] = [{ id: '', selected: (!obj["resetKind"])}]; for (let property in FaultIndicatorResetKind) obj["resetKindFaultIndicatorResetKind"].push ({ id: property, selected: obj["resetKind"] && obj["resetKind"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["resetKindFaultIndicatorResetKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_FaultIndicatorInfo_collapse" aria-expanded="true" aria-controls="{{id}}_FaultIndicatorInfo_collapse" style="margin-left: 10px;">FaultIndicatorInfo</a></legend> <div id="{{id}}_FaultIndicatorInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Assets.AssetInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_resetKind'>resetKind: </label><div class='col-sm-8'><select id='{{id}}_resetKind' class='form-control custom-select'>{{#resetKindFaultIndicatorResetKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/resetKindFaultIndicatorResetKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "FaultIndicatorInfo" }; super.submit (id, obj); temp = FaultIndicatorResetKind[document.getElementById (id + "_resetKind").value]; if (temp) obj["resetKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#FaultIndicatorResetKind." + temp; else delete obj["resetKind"]; return (obj); } }
JavaScript
class AssetModelCatalogueItem extends Common.Document { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.AssetModelCatalogueItem; if (null == bucket) cim_data.AssetModelCatalogueItem = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.AssetModelCatalogueItem[obj.id]; } parse (context, sub) { let obj = Common.Document.prototype.parse.call (this, context, sub); obj.cls = "AssetModelCatalogueItem"; base.parse_element (/<cim:AssetModelCatalogueItem.unitCost>([\s\S]*?)<\/cim:AssetModelCatalogueItem.unitCost>/g, obj, "unitCost", base.to_string, sub, context); base.parse_attribute (/<cim:AssetModelCatalogueItem.AssetModelCatalogue\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetModelCatalogue", sub, context); base.parse_attributes (/<cim:AssetModelCatalogueItem.ErpQuoteLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpQuoteLineItems", sub, context); base.parse_attributes (/<cim:AssetModelCatalogueItem.ErpPOLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPOLineItems", sub, context); base.parse_attribute (/<cim:AssetModelCatalogueItem.AssetModel\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetModel", sub, context); let bucket = context.parsed.AssetModelCatalogueItem; if (null == bucket) context.parsed.AssetModelCatalogueItem = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Common.Document.prototype.export.call (this, obj, false); base.export_element (obj, "AssetModelCatalogueItem", "unitCost", "unitCost", base.from_string, fields); base.export_attribute (obj, "AssetModelCatalogueItem", "AssetModelCatalogue", "AssetModelCatalogue", fields); base.export_attributes (obj, "AssetModelCatalogueItem", "ErpQuoteLineItems", "ErpQuoteLineItems", fields); base.export_attributes (obj, "AssetModelCatalogueItem", "ErpPOLineItems", "ErpPOLineItems", fields); base.export_attribute (obj, "AssetModelCatalogueItem", "AssetModel", "AssetModel", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetModelCatalogueItem_collapse" aria-expanded="true" aria-controls="AssetModelCatalogueItem_collapse" style="margin-left: 10px;">AssetModelCatalogueItem</a></legend> <div id="AssetModelCatalogueItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.Document.prototype.template.call (this) + ` {{#unitCost}}<div><b>unitCost</b>: {{unitCost}}</div>{{/unitCost}} {{#AssetModelCatalogue}}<div><b>AssetModelCatalogue</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetModelCatalogue}}");}); return false;'>{{AssetModelCatalogue}}</a></div>{{/AssetModelCatalogue}} {{#ErpQuoteLineItems}}<div><b>ErpQuoteLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpQuoteLineItems}} {{#ErpPOLineItems}}<div><b>ErpPOLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPOLineItems}} {{#AssetModel}}<div><b>AssetModel</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetModel}}");}); return false;'>{{AssetModel}}</a></div>{{/AssetModel}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ErpQuoteLineItems"]) obj["ErpQuoteLineItems_string"] = obj["ErpQuoteLineItems"].join (); if (obj["ErpPOLineItems"]) obj["ErpPOLineItems_string"] = obj["ErpPOLineItems"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ErpQuoteLineItems_string"]; delete obj["ErpPOLineItems_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetModelCatalogueItem_collapse" aria-expanded="true" aria-controls="{{id}}_AssetModelCatalogueItem_collapse" style="margin-left: 10px;">AssetModelCatalogueItem</a></legend> <div id="{{id}}_AssetModelCatalogueItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.Document.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_unitCost'>unitCost: </label><div class='col-sm-8'><input id='{{id}}_unitCost' class='form-control' type='text'{{#unitCost}} value='{{unitCost}}'{{/unitCost}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetModelCatalogue'>AssetModelCatalogue: </label><div class='col-sm-8'><input id='{{id}}_AssetModelCatalogue' class='form-control' type='text'{{#AssetModelCatalogue}} value='{{AssetModelCatalogue}}'{{/AssetModelCatalogue}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetModel'>AssetModel: </label><div class='col-sm-8'><input id='{{id}}_AssetModel' class='form-control' type='text'{{#AssetModel}} value='{{AssetModel}}'{{/AssetModel}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "AssetModelCatalogueItem" }; super.submit (id, obj); temp = document.getElementById (id + "_unitCost").value; if ("" !== temp) obj["unitCost"] = temp; temp = document.getElementById (id + "_AssetModelCatalogue").value; if ("" !== temp) obj["AssetModelCatalogue"] = temp; temp = document.getElementById (id + "_AssetModel").value; if ("" !== temp) obj["AssetModel"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["AssetModelCatalogue", "1", "0..*", "AssetModelCatalogue", "AssetModelCatalogueItems"], ["ErpQuoteLineItems", "0..*", "0..1", "ErpQuoteLineItem", "AssetModelCatalogueItem"], ["ErpPOLineItems", "0..*", "0..1", "ErpPOLineItem", "AssetModelCatalogueItem"], ["AssetModel", "0..1", "0..*", "ProductAssetModel", "AssetModelCatalogueItems"] ] ) ); } }
JavaScript
class BreakerInfo extends OldSwitchInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.BreakerInfo; if (null == bucket) cim_data.BreakerInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.BreakerInfo[obj.id]; } parse (context, sub) { let obj = OldSwitchInfo.prototype.parse.call (this, context, sub); obj.cls = "BreakerInfo"; base.parse_element (/<cim:BreakerInfo.phaseTrip>([\s\S]*?)<\/cim:BreakerInfo.phaseTrip>/g, obj, "phaseTrip", base.to_string, sub, context); let bucket = context.parsed.BreakerInfo; if (null == bucket) context.parsed.BreakerInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = OldSwitchInfo.prototype.export.call (this, obj, false); base.export_element (obj, "BreakerInfo", "phaseTrip", "phaseTrip", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#BreakerInfo_collapse" aria-expanded="true" aria-controls="BreakerInfo_collapse" style="margin-left: 10px;">BreakerInfo</a></legend> <div id="BreakerInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + OldSwitchInfo.prototype.template.call (this) + ` {{#phaseTrip}}<div><b>phaseTrip</b>: {{phaseTrip}}</div>{{/phaseTrip}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_BreakerInfo_collapse" aria-expanded="true" aria-controls="{{id}}_BreakerInfo_collapse" style="margin-left: 10px;">BreakerInfo</a></legend> <div id="{{id}}_BreakerInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + OldSwitchInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_phaseTrip'>phaseTrip: </label><div class='col-sm-8'><input id='{{id}}_phaseTrip' class='form-control' type='text'{{#phaseTrip}} value='{{phaseTrip}}'{{/phaseTrip}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "BreakerInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_phaseTrip").value; if ("" !== temp) obj["phaseTrip"] = temp; return (obj); } }
JavaScript
class RecloserInfo extends OldSwitchInfo { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.RecloserInfo; if (null == bucket) cim_data.RecloserInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.RecloserInfo[obj.id]; } parse (context, sub) { let obj = OldSwitchInfo.prototype.parse.call (this, context, sub); obj.cls = "RecloserInfo"; base.parse_element (/<cim:RecloserInfo.groundTripCapable>([\s\S]*?)<\/cim:RecloserInfo.groundTripCapable>/g, obj, "groundTripCapable", base.to_boolean, sub, context); base.parse_element (/<cim:RecloserInfo.groundTripNormalEnabled>([\s\S]*?)<\/cim:RecloserInfo.groundTripNormalEnabled>/g, obj, "groundTripNormalEnabled", base.to_boolean, sub, context); base.parse_element (/<cim:RecloserInfo.groundTripRating>([\s\S]*?)<\/cim:RecloserInfo.groundTripRating>/g, obj, "groundTripRating", base.to_string, sub, context); base.parse_element (/<cim:RecloserInfo.phaseTripRating>([\s\S]*?)<\/cim:RecloserInfo.phaseTripRating>/g, obj, "phaseTripRating", base.to_string, sub, context); base.parse_element (/<cim:RecloserInfo.recloseLockoutCount>([\s\S]*?)<\/cim:RecloserInfo.recloseLockoutCount>/g, obj, "recloseLockoutCount", base.to_string, sub, context); let bucket = context.parsed.RecloserInfo; if (null == bucket) context.parsed.RecloserInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = OldSwitchInfo.prototype.export.call (this, obj, false); base.export_element (obj, "RecloserInfo", "groundTripCapable", "groundTripCapable", base.from_boolean, fields); base.export_element (obj, "RecloserInfo", "groundTripNormalEnabled", "groundTripNormalEnabled", base.from_boolean, fields); base.export_element (obj, "RecloserInfo", "groundTripRating", "groundTripRating", base.from_string, fields); base.export_element (obj, "RecloserInfo", "phaseTripRating", "phaseTripRating", base.from_string, fields); base.export_element (obj, "RecloserInfo", "recloseLockoutCount", "recloseLockoutCount", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#RecloserInfo_collapse" aria-expanded="true" aria-controls="RecloserInfo_collapse" style="margin-left: 10px;">RecloserInfo</a></legend> <div id="RecloserInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + OldSwitchInfo.prototype.template.call (this) + ` {{#groundTripCapable}}<div><b>groundTripCapable</b>: {{groundTripCapable}}</div>{{/groundTripCapable}} {{#groundTripNormalEnabled}}<div><b>groundTripNormalEnabled</b>: {{groundTripNormalEnabled}}</div>{{/groundTripNormalEnabled}} {{#groundTripRating}}<div><b>groundTripRating</b>: {{groundTripRating}}</div>{{/groundTripRating}} {{#phaseTripRating}}<div><b>phaseTripRating</b>: {{phaseTripRating}}</div>{{/phaseTripRating}} {{#recloseLockoutCount}}<div><b>recloseLockoutCount</b>: {{recloseLockoutCount}}</div>{{/recloseLockoutCount}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_RecloserInfo_collapse" aria-expanded="true" aria-controls="{{id}}_RecloserInfo_collapse" style="margin-left: 10px;">RecloserInfo</a></legend> <div id="{{id}}_RecloserInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + OldSwitchInfo.prototype.edit_template.call (this) + ` <div class='form-group row'><div class='col-sm-4' for='{{id}}_groundTripCapable'>groundTripCapable: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_groundTripCapable' class='form-check-input' type='checkbox'{{#groundTripCapable}} checked{{/groundTripCapable}}></div></div></div> <div class='form-group row'><div class='col-sm-4' for='{{id}}_groundTripNormalEnabled'>groundTripNormalEnabled: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_groundTripNormalEnabled' class='form-check-input' type='checkbox'{{#groundTripNormalEnabled}} checked{{/groundTripNormalEnabled}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_groundTripRating'>groundTripRating: </label><div class='col-sm-8'><input id='{{id}}_groundTripRating' class='form-control' type='text'{{#groundTripRating}} value='{{groundTripRating}}'{{/groundTripRating}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_phaseTripRating'>phaseTripRating: </label><div class='col-sm-8'><input id='{{id}}_phaseTripRating' class='form-control' type='text'{{#phaseTripRating}} value='{{phaseTripRating}}'{{/phaseTripRating}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_recloseLockoutCount'>recloseLockoutCount: </label><div class='col-sm-8'><input id='{{id}}_recloseLockoutCount' class='form-control' type='text'{{#recloseLockoutCount}} value='{{recloseLockoutCount}}'{{/recloseLockoutCount}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "RecloserInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_groundTripCapable").checked; if (temp) obj["groundTripCapable"] = true; temp = document.getElementById (id + "_groundTripNormalEnabled").checked; if (temp) obj["groundTripNormalEnabled"] = true; temp = document.getElementById (id + "_groundTripRating").value; if ("" !== temp) obj["groundTripRating"] = temp; temp = document.getElementById (id + "_phaseTripRating").value; if ("" !== temp) obj["phaseTripRating"] = temp; temp = document.getElementById (id + "_recloseLockoutCount").value; if ("" !== temp) obj["recloseLockoutCount"] = temp; return (obj); } }
JavaScript
class CategoryProblems { // Elementos observables. @observable page @observable filterChange /** * Crea una instancia de CategoryProblems. * @param {service} alertService - Servicio de notificaciones * @param {service} authService - Servicio de autenticación y validación * @param {service} problemService - Servicio manejador de problemas * @param {service} routerService - Servicio de enrutamiento */ constructor (alertService, authService, problemService, routerService) { this.alertService = alertService this.authService = authService this.problemsService = problemService this.routerService = routerService this.totalPages = 1 this.page = 1 this.numberOfItems = [10, 20, 30, 50] this.sortOptions = ['Id', 'Nombre', 'Dificultad'] this.filterChange = false this.limit = 10 this.sort = 'Id' this.by = 'Ascendente' this.pagination = [] this.language = 'Cualquier idioma' this.problemToRemove = null } /** * Método que toma los parametros enviados en el link y configura la página para adaptarse * al contenido solicitado. Este método hace parte del ciclo de vida de la aplicación y se * ejecuta automáticamente luego de lanzar el constructor. * @param {any} params * @param {any} routeConfig */ activate (params, routeConfig) { this.routeConfig = routeConfig this.id = params.id this.getProblems() } /** * Cuando cambia un filtro, obtiene el material con los nuevos parametros. * @param {bool} act - Nuevo estado * @param {bool} prev - Antiguo estado */ filterChangeChanged (act, prev) { if(prev !== undefined) this.getProblems() } /** * Detecta cuando el número de página es modificado para solicitar el nuevo número. * @param {Number} act - Número de página nuevo. * @param {Number} prev - Número de página antes del cambio */ pageChanged (act, prev) { if(prev !== undefined) this.getProblems() } /** * Obtiene la lista de problemas según los parametros indicados. */ getProblems () { let stringSort, stringLang if (this.sort === 'Id') stringSort = null else if (this.sort === 'Nombre') stringSort = 'name' else if (this.sort === 'Dificultad') stringSort = 'level' if (this.language === 'Español') stringLang = 'es' else if (this.language === 'Inglés') stringLang = 'en' else stringLang = null this.problemsService.getCategoryProblems(this.id, this.page, this.limit, stringSort, (this.by === 'Ascendente' ? 'asc' : 'desc'), stringLang) .then(data => { this.category = new Category(data.meta.categoryName) this.category.setTotalProblems(data.meta.totalItems) this.totalPages = data.meta.totalPages if (this.totalPages !== 0) { this.category.setProblemsLoaded(data.data) } else { this.alertService.showMessage(MESSAGES.problemsEmpty) } }).catch(error => { if (error.status === 404) { this.alertService.showMessage(MESSAGES.categoryDoesNotExist) this.routerService.navigate('') } }) } /** * Muestra un popup para confirmar la eliminación del problema indicado por id. * @param {number} id - Identificador del problema a eliminar. */ showRemoveProblem (id) { this.problemToRemove = id window.$('#remove-problem').modal('show') } /** * Elimina un problema de la plataforma. */ removeProblem () { this.problemsService.removeProblem(this.problemToRemove) .then(() => { this.alertService.showMessage(MESSAGES.problemDeleted) this.category.removeProblem(this.problemToRemove) window.$('#remove-problem').modal('hide') }) .catch(error => { if (error.status === 401 || error.status === 403) { this.alertService.showMessage(MESSAGES.permissionsError) } else if (error.status === 500) { this.alertService.showMessage(MESSAGES.serverError) } else { this.alertService.showMessage(MESSAGES.unknownError) } window.$('#remove-problem').modal('hide') }) } }
JavaScript
class Stack { /** * Represents a specialized stack for numbers that instantly returns max value * * @constructor * * @param {Number=} capacity * * @property {Array} maxes - tracks largest value in stack for constant lookup * @property {Array} storage - the stack itself * @property {Number} capacity - stack stops push when at capacity */ constructor(capacity = Infinity) { this.maxes = [-Infinity]; this.storage = []; this.capacity = capacity; } /** * @description Check maximum in stack * * Strategy: Return last value added to maxes array * * Time complexity: O(1) * Space complexity: O(1) * * @returns {Number} - maximum value in stack */ getMax() { return this.maxes[this.maxes.length - 1]; } /** * @description Check if stack is empty * * Strategy: Use storage array length * * Time complexity: O(1) * Space complexity: O(1) * * @returns {Boolean} - true if empty, or false otherwise */ isEmpty() { return this.storage.length === 0; } /** * @description Check if stack has reached capacity * * Strategy: Check if storage array length matches capacity value * * Time complexity: O(1) * Space complexity: O(1) * * @returns {Boolean} - true if full, or false otherwise */ isFull() { return this.storage.length === this.capacity; } /** * @description View value at top of stack * * Strategy: Look at storage array's final element using index * * Time complexity: O(1) * Space complexity: O(1) * * @returns {*} - value at top of stack */ peek() { return this.storage[this.storage.length - 1]; } /** * @description Add input value to top of stack * * Strategy: Use native Array push method if under capacity. If value is * greater than previous max, make it the maximum. * * Time complexity: O(1) * Space complexity: O(1) * * @param {*} val - value added to stack */ push(val) { if (this.storage.length >= this.capacity) { return; } this.storage.push(val); if (val >= this.maxes[this.maxes.length - 1]) { this.maxes.push(val); } } /** * @description Remove value from top of stack * * Strategy: Use native Array pop method. Check if maximum for removal. * * Time complexity: O(1) * Space complexity: O(1) * * @returns {Number} - value removed from stack, or undefined if empty */ pop() { const popped = this.storage[this.storage.length - 1]; const max = this.maxes[this.maxes.length - 1]; if (popped === max) { this.maxes.pop(); } return this.storage.pop(); } /** * @description Check size of stack * * Strategy: Use storage length * * Time complexity: O(1) * Space complexity: O(1) * * @returns {Number} - total amount of items in stack */ size() { return this.storage.length; } }
JavaScript
class Rules { /** * Validate that a field's date value is after another's. * * @param {string} fieldName * @param {string} afterFieldName * @param {object} formFields * @return {boolean} */ validateAfter(fieldName, afterFieldName, formFields) { let fieldValue = formFields[fieldName]; let afterFieldValue = formFields[afterFieldName]; if(this.validateDate(fieldValue) && this.validateDate(afterFieldValue)) { return this._compareDates(fieldValue, afterFieldValue) === 1; }; return false; } /** * Validate that a value contains only alphabetic characters. * * @param {string} value * @return {boolean} */ validateAlpha(value) { return typeof(value) === 'string' && value.match(/^[a-z]+$/i); } /** * Validate that a value contains only alphabetic characters, hyphens and underscores. * * @param {string} value * @return {boolean} */ validateAlphaDash(value) { return typeof(value) === 'string' && typeof(value) !== 'number' && value.match(/^[a-z\-\_]+$/i); } /** * Validate that a value contains only alphanumeric characters. * * @param {string} value * @return {boolean} */ validateAlphaNum(value) { return typeof(value) === 'string' && typeof(value) !== 'number' && value.match(/^[a-z0-9]+$/i); } /** * Validate if value is an array. * * @param {mixed} value * @return {boolean} */ validateArray(value) { return Array.isArray(value); } /** * Validate that a field's date value is before another's. * * @param {string} fieldName * @param {string} beforeFieldName * @param {object} formFields * @return {boolean} */ validateBefore(fieldName, beforeFieldName, formFields) { let fieldValue = formFields[fieldName]; let beforeFieldValue = formFields[beforeFieldName]; if(this.validateDate(fieldValue) && this.validateDate(beforeFieldValue)) { return this._compareDates(fieldValue, beforeFieldValue) === -1; }; return false; } /** * Compare two dates. * * @param {mixed} first The first date value to be compared. * @param {mixed} second The second date value to be compared. * @return {integer} */ _compareDates(first, second) { let firstDate = (new Date(first)).valueOf(); let secondDate = (new Date(second)).valueOf(); return Math.sign(firstDate - secondDate); } /** * Validate if value is boolean. * * @param {mixed} value * @return {boolean} */ validateBoolean(value) { let acceptable = [true, false, 1, 0, '1', '0']; return acceptable.includes(value); } /** * Validate if value is a date. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date * * @param {mixed} value */ validateDate(value) { return new Date(value) != 'Invalid Date'; } validateDateEquals(fieldName, otherFieldName, formFields) { let firstDate = new Date(formFields[fieldName]); let secondDate = new Date(formFields[otherFieldName]); return firstDate != 'Invalid Date' && firstDate.valueOf() === secondDate.valueOf(); } /** * Validate if value is an email address. * * @param {string} value * @return {boolean} */ validateEmail(value) { let matches = value.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i); return matches ? matches.length > 0 : false; } /** * Validate that a form field is a file. * * @param {string} fieldName * @param {File} file */ validateFile(fieldName, formData) { let field = formData[fieldName]; // let extension = this._getFileExtension(field); return field instanceof File; } /** * Get extension from filename string. * * @param {string} file * @return {string} */ _getFileExtension(file) { return file.name.split('.').pop(); } /** * Validate if value is string. * * @param {mixed} value * @return {boolean} */ validateString(value) { return typeof value === 'string'; } /** * Validate if value is integer. * * @param {mixed} value * @return {boolean} */ validateInteger(value) { return !isNaN(+value) && Number.isInteger(+value); } /** * Validate if value is object. * * @param {mixed} value * @return {boolean} */ validateObject(value) { return value instanceof Object && !(value instanceof Array); } /** * Validate if value is less than or equal to max. * * @param {mixed} value * @param {number} max * @return {boolean} */ validateMax(value, max) { // Number if (typeof (value) === 'number') { return value <= max; } // String, Array return value.length <= max; } /** * Validate if value is greater than or equal to min. * * @param {mixed} value * @param {number} min * @return {boolean} */ validateMin(value, min) { // Number if (typeof (value) === 'number') { return value >= min; } // String, Array return value.length >= min; } /** * Validate if value is null. * * @param {mixed} value * @return {boolean} */ validateNull(value) { return value == null; } /** * Validate if value is numeric. * * @param {mixed} value * @return {boolean} */ validateNumeric(value) { return !isNaN(value); } /** * Validate if value is required. * * @param {mixed} value * @return {boolean} */ validateRequired(value) { return value != null && value != '' && value.length != 0; } /** * Validate that value is required if another field equals a certain value. * * @param {string} fieldName The field name to be validated * @param {array} otherFieldName The name of field to be validated against * @param {array} otherFielValue The value of field to be validated against * @param {object} formFields The forms fields. * @return {boolean} */ validateRequiredIf(fieldName, otherFieldName, otherFieldValue, formFields) { let formFieldValue = formFields[otherFieldName]; // Check for boolean if (otherFieldValue == 'true' || otherFieldValue == 'false') { otherFieldValue = this._convertStringToBoolean(otherFieldValue); }; return formFieldValue != otherFieldValue ? false : this.validateRequired(formFields[fieldName]); } /** * Validate that a field is required unless another field has a specific value. * * @param {string} fieldName The field name to be validated * @param {array} otherFieldName The name of field to be validated against * @param {array} otherFielValue The value of field to be validated against * @param {object} formFields The forms fields. * @return {boolean} */ validateRequiredUnless(fieldName, otherFieldName, otherFieldValue, formFields) { let formFieldValue = formFields[otherFieldName]; // Check for boolean if (otherFieldValue == 'true' || otherFieldValue == 'false') { otherFieldValue = this._convertStringToBoolean(otherFieldValue); }; return formFieldValue == otherFieldValue ? true : this.validateRequired(formFields[fieldName]); } /** * * @param {string} fieldName The field name to be validated * @param {array} otherFieldNames The field names of fields to be validated against * @param {object} formFields * @return {boolean} */ validateRequiredWith(fieldName, otherFieldNames, formFields) { let valid_num = 0; otherFieldNames.forEach(name => { if(this.validateRequired(formFields[name])) { valid_num++; }; }) return valid_num > 0 ? this.validateRequired(formFields[fieldName]) : false; } /** * Validate that a field is require will all names fields. * * @param {string} fieldName The field name to be validated * @param {array} otherFieldNames The field names of fields to be validated against * @param {object} formFields * @return {boolean} */ validateRequiredWithAll(fieldName, otherFieldNames, formFields) { let valid_num = 0; otherFieldNames.forEach(name => { if(this.validateRequired(formFields[name])) { valid_num++; }; }) return otherFieldNames.length === valid_num ? this.validateRequired(formFields[fieldName]) : false; } /** * Validate a URL string. * @see https://gist.github.com/dperini/729294 * * @param {string} value The URL string to be validated. * @return {boolean} */ validateUrl(value) { let regex = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i; let matches = value.match(regex); return matches && matches.length; } /** * Validate if value is of length. * * @param {mixed} value * @param {number} length * @return {boolean} */ validateLength(value, length) { return value.length == length; } /** * Validate if value equals another value. * * @param {mixed} value * @param {mixed} comparedValue * @return {boolean} */ validateEquals(value, comparedValue) { if (Array.isArray(value) && Array.isArray(comparedValue)) { return JSON.stringify(value) === JSON.stringify(comparedValue); }; return value == comparedValue; } /** * Validate if value is greater than another value. * * @param {number} value * @param {number} comparedValue * @return {boolean} */ validateGt(value, comparedValue) { return value > comparedValue; } /** * Validate if value is less than another value. * * @param {number} value * @param {number} comparedValue * @return {boolean} */ validateLt(value, comparedValue) { return value < comparedValue; } /** * Validate if value is greater than or equal to another value. * * @param {number} value * @param {number} comparedValue * @return {boolean} */ validateGte(value, comparedValue) { return this.validateGt(value, comparedValue) || this.validateEquals(value, comparedValue); } /** * Validate if value is less than or equals another value. * * @param {number} value * @param {number} comparedValue * @return {boolean} */ validateLte(value, comparedValue) { return this.validateLt(value, comparedValue) || this.validateEquals(value, comparedValue); } /** * Validate if value is between two values. * * @param {mixed} value * @param {number} lowerValue * @param {number} higherValue * @return {boolean} */ validateBetween(value, lowerValue, higherValue) { return this.validateLt(value, higherValue) && this.validateGt(value, lowerValue); } /** * Validate if value is in an array. * * @param {mixed} value * @param {array} array * @return {boolean} */ validateInArray(value, array) { return array.includes(value); } /** * Validate if field value is different than another field value. * * @param {mixed} fieldValue * @param {array} otherFieldName * @param {object} formFields * @return {boolean} */ validateDifferent(fieldName, otherFieldName, formFields) { let fieldValue = formFields[fieldName]; let otherFieldValue = formFields[otherFieldName]; // String, Number or Boolean if(['string', 'number', 'boolean'].includes(typeof(fieldValue))) { return fieldValue !== otherFieldValue; }; // Array if(Array.isArray(fieldValue)) { return fieldValue !== otherFieldValue; } // Object if(typeof(fieldValue) === 'object') { return JSON.stringify(fieldValue) !== JSON.stringify(otherFieldValue); } } /** * Validate if field is confirmed by another field. * * @param {string} fieldName * @param {object} formFields * @return {boolean} */ validateConfirmed(fieldName, formFields) { let keys = Object.keys(formFields); let confirmFieldName = `${fieldName}_confirmation`; return keys.includes(confirmFieldName) && formFields[fieldName] == formFields[confirmFieldName]; } /** * Validate if field is present and not empty. * * @param {string} fieldName * @param {object} formFields * @return {boolean} */ validateFilled(fieldName, formFields) { let keys = Object.keys(formFields); return keys.includes(fieldName) && // Boolean and numbers should still be permitted so we exclude `0` and `false` formFields[fieldName] !== null && formFields[fieldName] !== '' } /** * Validate that a value is a valid JSON string. * * @param {string} value * @return {boolean} */ validateJson(value) { // let fieldValue = formFields[fieldName]; if(typeof(value) !== 'string') { return false; }; try { JSON.parse(value); return true; } catch(e) { return false; }; } /** * Validate that a value is a valid IP address ahering to IPv4 or IPv6 standard. * * @param {string} value * @return {boolean} */ validateIp(value) { if(typeof value !== 'string') { return false }; return this.validateIpv4(value) || this.validateIpv6(value); } /** * Validate that a value is a valid IPv4 string. * * @see https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp * @param {string} value * @return {boolean} */ validateIpv4(value) { if(typeof value !== 'string') { return false }; let matches = value.match(/^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$/); return matches && matches.length; } /** * Validate that a value is a valid IPv6 string. * * @see https://www.ibm.com/support/knowledgecenter/en/STCMML8/com.ibm.storage.ts3500.doc/opg_3584_IPv4_IPv6_addresses.html * @see https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses * @param {string} value * @return {boolean} */ validateIpv6(value) { if(typeof value !== 'string') { return false }; let matches = value.match(/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/); return matches && matches.length ? true : false; } /** * Convert a string to a boolean. * Ie. 'true' -> true * * @param {string} value */ _convertStringToBoolean(value) { if (value === 'true') { return true; } else if (value == 'false') { return false } else { return Boolean(value); }; } }
JavaScript
class DetallesPersonaleController { /** * Show a list of all detallespersonales. * GET detallespersonales * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async index({ request, response, view }) { const detallespersonales = await DetallesPersonale.all(); return response.json(detallespersonales); } /** * Render a form to be used for creating a new detallespersonale. * GET detallespersonales/create * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async create({ request, response, view }) {} /** * Create/save a new detallespersonale. * POST detallespersonales * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async store({ request, response }) { console.log(request.all()); const detallespersonale = await DetallesPersonale.create(request.all()); return response.json({ detallespersonale }); } /** * Display a single detallespersonale. * GET detallespersonales/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async show({ params, request, response, view }) { let detallespersonale = await DetallesPersonale.find(params.id); return response.json({ detallespersonale: detallespersonale }); } /** * Render a form to update an existing detallespersonale. * GET detallespersonales/:id/edit * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async edit({ params, request, response, view }) { let detallespersonale = await DetallesPersonale.find(params.id); return response.json({ detallespersonale: detallespersonale }); } /** * Update detallespersonale details. * PUT or PATCH detallespersonales/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update({ params, request, response }) { let detallespersonale = await DetallesPersonale.find(params.id); detallespersonale.merge(request.all()); await detallespersonale.save(); return response.json(detallespersonale); } /** * Delete a detallespersonale with id. * DELETE detallespersonales/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy({ params, request, response }) { let detallespersonale = await DetallesPersonale.find(params.id); detallespersonale.delete(); return response.json(detallespersonale); } }
JavaScript
class ScoreBoard extends Component { componentWillMount() { this.props.gettingRace(this.props.match.params.slug) } handleAnswer = (data) => { this.props.sendingAnswer(data); } render() { return ( <div style={{width: "100%"}}> <NavBar /> <div className="main" style={{paddingLeft: 150, paddingRight: 150, marginTop: 0}}> <Board race={this.props.race} gotRace={this.props.gotRace}/> <QuestionBaord index={this.props.race.index} race={this.props.race} quiz={this.props.quiz} gotQuiz={this.props.gotQuiz} gotRace={this.props.gotRace} slug={this.props.match.params.slug} handleAnswerFunc={this.handleAnswer}/> </div> </div> ); } }
JavaScript
class History extends EventEmitter { constructor(editor) { super(); /** * Reference to the parent editor. * * @type {Piotr.Editor} */ this.editor = editor; /** * The stack of commands. Lower the index, earlier the command. * * @private * @type {Piotr.Command[]} */ this.stack = []; /** * Points to the last stacked commands. * * @private * @type {Number} */ this.cursor = -1; } /** * Stacks an already-executed command in the history. * * @param {Piotr.Command} cmd - The command to store * @param {Object} sel - The state of selection before command execution */ push(cmd, sel) { cmd.selection = sel; this.cursor++; // Move to the next index this.stack[this.cursor] = cmd; // Add the new command this.stack.splice(this.cursor + 1); // Erase all subsequent commands this.emit("update"); } /** * Cancels the last command if possible and restores the previous state of * selection. */ undo() { if(this.canUndo()) { this.stack[this.cursor].cancel(); this.editor.selection.set(this.stack[this.cursor].selBefore); this.cursor--; this.emit("update"); } } /** * Re-executes the last command if it was canceled. */ redo() { if(this.canRedo()) { this.cursor++; this.stack[this.cursor].execute(); this.editor.selection.set(this.stack[this.cursor].selAfter); this.emit("update"); } } /** * Returns true if it is possible to undo. * * @returns {Boolean} */ canUndo() { return this.cursor >= 0; } /** * Returns true if it is possible to redo. * * @returns {Boolean} */ canRedo() { return this.cursor < (this.stack.length - 1); } }
JavaScript
class Optimized extends Component { shouldComponentUpdate() { return false; } render() { return ( <Row testing> <Column width="1/2" testing> <TypeSize/> </Column> <Column width="1/2" testing> <TypeSize/> </Column> </Row> ) } }
JavaScript
class Window extends EventEmitter { constructor ( name, options ) { super(); options = options || {}; // set default value for options _.defaultsDeep(options, { disableDevTools: false, windowType: 'dockable', width: 400, height: 300, acceptFirstMouse: true, // NOTE: this will allow mouse click works when window is not focused disableAutoHideCursor: true, // NOTE: this will prevent hide cursor when press "space" // titleBarStyle: 'hidden', // TODO backgroundColor: '#333', webPreferences: { preload: Protocol.url('editor-framework://renderer.js'), // defaultFontFamily: { // standard: 'Helvetica Neue', // serif: 'Helvetica Neue', // sansSerif: 'Helvetica Neue', // monospace: 'Helvetica Neue', // }, }, defaultFontSize: 13, defaultMonospaceFontSize: 13, }); this._loaded = false; this._currentSessions = {}; // init options this.name = name; this.disableDevTools = options.disableDevTools; this.hideWhenBlur = false; // control by options.hideWhenBlur or winType === 'quick'; this.windowType = options.windowType; this.save = options.save; if ( typeof this.save !== 'boolean' ) { this.save = true; } switch ( this.windowType ) { case 'dockable': options.resizable = true; options.alwaysOnTop = false; break; case 'float': options.resizable = true; options.alwaysOnTop = true; break; case 'fixed-size': options.resizable = false; options.alwaysOnTop = true; break; case 'quick': options.resizable = true; options.alwaysOnTop = true; this.hideWhenBlur = true; break; } this.nativeWin = new BrowserWindow(options); if ( this.hideWhenBlur ) { this.nativeWin.setAlwaysOnTop(true); } // ====================== // BrowserWindow events // ====================== this.nativeWin.on('focus', () => { if ( !App.focused ) { App.focused = true; App.emit('focus'); } }); this.nativeWin.on('blur', () => { // BUG: this is an atom-shell bug, // it cannot get focused window at the same frame // https://github.com/atom/atom-shell/issues/984 setImmediate(() => { if ( !BrowserWindow.getFocusedWindow() ) { App.focused = false; App.emit('blur'); } }); if ( this.hideWhenBlur ) { // this.nativeWin.close(); this.nativeWin.hide(); } }); this.nativeWin.on('close', event => { // quick window never close, it just hide if ( this.windowType === 'quick' ) { event.preventDefault(); this.nativeWin.hide(); } // NOTE: I cannot put these in 'closed' event. In Windows, the getBounds will return // zero width and height in 'closed' event Panel._onWindowClose(this); Window.commitWindowStates(); Window.saveWindowStates(); }); this.nativeWin.on('closed', () => { Panel._onWindowClosed(this); // if we still have sendRequestToPage callbacks, // just call them directly to prevent request endless waiting for ( let sessionId in this._currentSessions ) { Ipc._closeSessionThroughWin(sessionId); let cb = this._currentSessions[sessionId]; if (cb) { cb(); } } this._currentSessions = {}; if ( this.isMainWindow ) { Window.removeWindow(this); Window.main = null; EditorM._quit(); // TODO: change to App._quit() } else { Window.removeWindow(this); } this.dispose(); }); this.nativeWin.on('unresponsive', event => { Console.error( `Window "${this.name}" unresponsive: ${event}` ); }); // ====================== // WebContents events // ====================== // order: dom-ready -> did-frame-finish-load -> did-finish-load // this.nativeWin.webContents.on('dom-ready', event => { // Console.log('dom-ready'); // }); // this.nativeWin.webContents.on('did-frame-finish-load', () => { // Console.log('did-frame-finish-load'); // }); this.nativeWin.webContents.on('did-finish-load', () => { this._loaded = true; // TODO: do we really need this? // Ipc.sendToMain('editor:window-reloaded', this); }); this.nativeWin.webContents.on('crashed', event => { Console.error( `Window "${this.name}" crashed: ${event}` ); }); this.nativeWin.webContents.on('will-navigate', (event, url) => { event.preventDefault(); Electron.shell.openExternal(url); // TODO: can have more protocol for navigate }); // NOTE: window must be add after nativeWin assigned Window.addWindow(this); } /** * @method dispose * * Dereference the native window. */ dispose () { // NOTE: Important to dereference the window object to allow for GC this.nativeWin = null; } /** * @method load * @param {string} url * @param {object} argv * * Load page by url, and send `argv` in query property of the url. * The renderer process will parse the `argv` when the page is ready and save it in `Editor.argv` in renderer process. */ load ( editorUrl, argv ) { let resultUrl = Protocol.url(editorUrl); if ( !resultUrl ) { Console.error( `Failed to load page ${editorUrl} for window "${this.name}"` ); return; } this._loaded = false; let argvHash = argv ? encodeURIComponent(JSON.stringify(argv)) : undefined; let url = resultUrl; // if this is an exists local file if ( Fs.existsSync(resultUrl) ) { url = Url.format({ protocol: 'file', pathname: resultUrl, slashes: true, hash: argvHash }); this._url = url; this.nativeWin.loadURL(url); return; } // otherwise we treat it as a normal url if ( argvHash ) { url = `${resultUrl}#${argvHash}`; } this._url = url; this.nativeWin.loadURL(url); } /** * @method show * * Show the window */ show () { this.nativeWin.show(); } /** * @method hide * * Hide the window */ hide () { this.nativeWin.hide(); } /** * @method close * * Close the window */ close () { this._loaded = false; this.nativeWin.close(); } /** * @method forceClose * * Force close the window */ forceClose () { this._loaded = false; // NOTE: I cannot put these in 'closed' event. In Windows, the getBounds will return // zero width and height in 'closed' event Panel._onWindowClose(this); Window.commitWindowStates(); Window.saveWindowStates(); if (this.nativeWin) { this.nativeWin.destroy(); } } /** * @method focus * * Focus on the window */ focus () { this.nativeWin.focus(); } /** * @method minimize * * Minimize the window */ minimize () { this.nativeWin.minimize(); } /** * @method restore * * Restore the window */ restore () { this.nativeWin.restore(); } /** * @method openDevTools * @param {object} options * @param {string} options.mode - Opens the devtools with specified dock state, can be `right`, `bottom`, `undocked`, `detach`. * Defaults to last used dock state. * In `undocked` mode it’s possible to dock back. * In detach mode it’s not. * * Open the devtools */ openDevTools (options) { if (this.disableDevTools) { return; } options = options || { mode: 'detach' }; this.nativeWin.openDevTools(options); } /** * @method closeDevTools * * Closes the devtools */ closeDevTools () { this.nativeWin.closeDevTools(); } /** * @method adjust * @param {number} x * @param {number} y * @param {number} w * @param {number} h * * Try to adjust the window to fit the position and size we give */ adjust ( x, y, w, h ) { let adjustToCenter = false; if ( typeof x !== 'number' ) { adjustToCenter = true; x = 0; } if ( typeof y !== 'number' ) { adjustToCenter = true; y = 0; } if ( typeof w !== 'number' || w <= 0 ) { adjustToCenter = true; w = 800; } if ( typeof h !== 'number' || h <= 0 ) { adjustToCenter = true; h = 600; } let display = Electron.screen.getDisplayMatching( { x: x, y: y, width: w, height: h } ); this.nativeWin.setSize(w,h); this.nativeWin.setPosition( display.workArea.x, display.workArea.y ); if ( adjustToCenter ) { this.nativeWin.center(); } else { this.nativeWin.setPosition( x, y ); } } /** * @method commitWindowState * @param {object} layoutInfo * * Commit the current window state */ commitWindowState ( layoutInfo ) { // don't do anything if we do not want to save the window if ( !this.save ) { return; } let winBounds = this.nativeWin.getBounds(); if ( !winBounds.width ) { Console.warn(`Failed to commit window state. Invalid window width: ${winBounds.width}`); winBounds.width = 800; } if ( !winBounds.height ) { Console.warn(`Failed to commit window state. Invalid window height ${winBounds.height}`); winBounds.height = 600; } // store windows layout let winInfo = _windowLayouts[this.name]; winInfo = Object.assign( winInfo || {}, winBounds); if ( layoutInfo ) { winInfo.layout = layoutInfo; } _windowLayouts[this.name] = winInfo; } /** * @method restorePositionAndSize * * Restore window's position and size from the `local` profile `layout.windows.json` */ restorePositionAndSize () { // restore window size and position let size = this.nativeWin.getSize(); let winPosX, winPosY, winSizeX = size[0], winSizeY = size[1]; let profile = Profile.load('layout.windows', 'local'); if ( profile.windows && profile.windows[this.name] ) { let winInfo = profile.windows[this.name]; winPosX = winInfo.x; winPosY = winInfo.y; winSizeX = winInfo.width; winSizeY = winInfo.height; } this.adjust( winPosX, winPosY, winSizeX, winSizeY ); } // ======================================== // Ipc // ======================================== _send (...args) { let webContents = this.nativeWin.webContents; if (!webContents) { Console.error(`Failed to send "${args[0]}" to ${this.name} because web contents are not yet loaded`); return false; } webContents.send.apply( webContents, args ); return true; } _sendToPanel ( panelID, message, ...args ) { if ( typeof message !== 'string' ) { Console.error(`The message ${message} sent to panel ${panelID} must be a string`); return; } let opts = Ipc._popReplyAndTimeout(args); if ( !opts ) { args = ['editor:ipc-main2panel', panelID, message, ...args]; if ( this._send.apply ( this, args ) === false ) { Console.failed( `send message "${message}" to panel "${panelID}" failed, no response received.` ); } return; } let sessionId = Ipc._newSession(message, `${panelID}@main`, opts.reply, opts.timeout, this); this._currentSessions[sessionId] = opts.reply; // args = ['editor:ipc-main2panel', panelID, message, ...args, Ipc.option({ sessionId: sessionId, waitForReply: true, timeout: opts.timeout, // this is only used as debug info })]; this._send.apply(this, args); return sessionId; } _closeSession ( sessionId ) { if ( !this.nativeWin ) { return; } delete this._currentSessions[sessionId]; } /** * @method send * @param {string} - The message name. * @param {...*} [arg] - Whatever arguments the message needs. * @param {function} [callback] - You can specify a callback function to receive IPC reply at the last or the 2nd last argument. * @param {number} [timeout] - You can specify a timeout for the callback at the last argument. If no timeout specified, it will be 5000ms. * * Send `message` with `...args` to renderer process asynchronously. It is possible to add a callback as the last or the 2nd last argument to receive replies from the IPC receiver. */ send ( message, ...args ) { if ( typeof message !== 'string' ) { Console.error(`Send message failed for '${message}'. The message must be a string`); return; } let opts = Ipc._popReplyAndTimeout(args); if ( !opts ) { args = [message, ...args]; if ( this._send.apply ( this, args ) === false ) { Console.failed( `send message "${message}" to window failed. No response was received.` ); } return; } let sessionId = Ipc._newSession(message, `${this.nativeWin.id}@main`, opts.reply, opts.timeout, this); this._currentSessions[sessionId] = opts.reply; // args = ['editor:ipc-main2renderer', message, ...args, Ipc.option({ sessionId: sessionId, waitForReply: true, timeout: opts.timeout, // this is only used as debug info })]; this._send.apply(this, args); return sessionId; } /** * @method popupMenu * @param {object} template - the Menu template * @param {number} [x] - the x position * @param {number} [y] - the y position * * Popup a context menu */ popupMenu ( template, x, y ) { if ( x !== undefined ) { x = Math.floor(x); } if ( y !== undefined ) { y = Math.floor(y); } let webContents = this.nativeWin.webContents; let editorMenu = new Menu(template,webContents); editorMenu.nativeMenu.popup(this.nativeWin, x, y); editorMenu.dispose(); } // ======================================== // properties // ======================================== /** * @property {Boolean} isMainWindow * * If this is a main window. */ get isMainWindow () { return Window.main === this; } /** * @property {Boolean} isFocused * * If the window is focused. */ get isFocused () { return this.nativeWin.isFocused(); } /** * @property {Boolean} isMinimized * * If the window is minimized. */ get isMinimized () { return this.nativeWin.isMinimized(); } /** * @property {Boolean} isLoaded * * If the window is loaded. */ get isLoaded () { return this._loaded; } // ======================================== // static window operation // ======================================== /** * @property {Object} defaultLayout * @static * * The default layout. */ static get defaultLayout () { return _defaultLayout; } static set defaultLayout (value) { _defaultLayout = value; } /** * @property {Array} windows * @static * * The current opened windows. */ static get windows () { return _windows.slice(); } /** * @property {Editor.Window} main * @static * * The main window. */ static set main (value) { return _mainwin = value; } static get main () { return _mainwin; } // NOTE: this will in case save-layout not invoke, // and it will missing info for current window static loadLayouts () { _windowLayouts = {}; let profile = Profile.load( 'layout.windows', 'local', { version: '', windows: {}, }); for ( let name in profile.windows ) { let info = profile.windows[name]; _windowLayouts[name] = info; } } /** * @method find * @static * @param {string|BrowserWindow|BrowserWindow.webContents} param * @return {Editor.Window} * * Find window by name or by BrowserWindow instance */ static find ( param ) { // param === string if ( typeof param === 'string' ) { for ( let i = 0; i < _windows.length; ++i ) { let win = _windows[i]; if ( win.name === param ) return win; } return null; } // param === BrowserWindow if ( param instanceof BrowserWindow ) { for ( let i = 0; i < _windows.length; ++i ) { let win = _windows[i]; if ( win.nativeWin === param ) { return win; } } return null; } // param === WebContents (NOTE: webContents don't have explicit constructor in electron) for ( let i = 0; i < _windows.length; ++i ) { let win = _windows[i]; if ( win.nativeWin && win.nativeWin.webContents === param ) { return win; } } return null; } /** * @method addWindow * @static * @param {Editor.Window} win * * Add an editor window */ static addWindow ( win ) { _windows.push(win); } /** * @method removeWindow * @static * @param {Editor.Window} win * * Remove an editor window */ static removeWindow ( win ) { let idx = _windows.indexOf(win); if ( idx === -1 ) { Console.warn( `Cannot find window ${win.name}` ); return; } _windows.splice(idx,1); } /** * @method commitWindowStates * @static * * Commit all opened window's state */ static commitWindowStates () { for ( let i = 0; i < _windows.length; ++i ) { let editorWin = _windows[i]; editorWin.commitWindowState(); } } /** * @method saveWindowStates * @static * * Save current window's state to profile `layout.windows.json` at `local` */ static saveWindowStates () { // do not save layout in test environment // TODO: change to App.argv._command if ( EditorM.argv._command === 'test' ) { return; } // we've quit the app, do not save layout after that. if ( !Window.main ) { return; } let profile = Profile.load( 'layout.windows', 'local' ); profile.windows = {}; for ( let i = 0; i < _windows.length; ++i ) { let editorWin = _windows[i]; profile.windows[editorWin.name] = _windowLayouts[editorWin.name]; } profile.version = EditorM.App.version; profile.save(); } } // end class Window
JavaScript
class Table { /** * @param string id * @param string alias * @param Object colums */ constructor (id, alias, columns) { this.id = id this.alias = alias this.columns = columns.getColumns() } /** * Return a table object. * * @return Object * @todo this probably doesn't make sense. */ getTable () { return { id: this.id, alias: this.alias, columns: this.columns } } }
JavaScript
class Nolynch { constructor() { /** * Parameter: enabled * If nolynch is enabled or not. If it isn't, the game will ignore it. * * *Type:* <Boolean: https://www.w3schools.com/js/js_booleans.asp> */ this.enabled = false; /** * Property: voters * Which players have voted for nolynch, mapped by their names. * * *Type:* <Unit> < <String: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String>, <Player> > */ this.voters = new Unit(); /** * Property: votes * How many votes nolynch has. * * *Type:* <Number: https://www.w3schools.com/js/js_numbers.asp> */ this.votes = 0; } /** * Function: clear * Clears this instance by setting the votes to 0 and clearing the voters Unit. */ clear() { this.votes = 0; this.voters.clear(); } }
JavaScript
class Loan { /** * @description creates new loan applications * @param {object} req request object * @param {object} res response object * @returns {object} new loan application object */ static Model() { return new Model('loans'); } static async loanApply(req, res) { const { amount, tenor } = req.body; const { firstName, lastName, email } = req.user; const interest = 0.05 * amount.toFixed(2); const paymentInstallment = Number(((amount + interest) / tenor).toFixed(2)); const balance = Number((amount + interest).toFixed(2)); const columns = '"userMail", amount, tenor, interest, "paymentInstallment", balance'; const values = `'${email}', ${amount}, ${tenor}, ${interest}, ${paymentInstallment}, ${balance}`; try { const data = await Loan.Model().select('*', `WHERE "userMail"='${email}'`); if (data[0] && !data[0].repaid) { return conflictResponse(req, res, 'You have a current unrepaid loan'); } const loan = await Loan.Model().insert(columns, `${values}`, 'RETURNING *'); return res.status(201).json({ status: 201, data: { firstName, lastName, ...loan[0], }, }); } catch (error) { return res.status(400).send(error.message); } } /** * @description Retrieves all loans from the data structure * and also if query is specified, it return loans that match the specified query * @param {object} req request object * @param {object} res response object * @returns [array] array of loans */ static async getAllLoans(req, res) { const { status } = req.query; let { repaid } = req.query; try { if (status && repaid) { repaid = JSON.parse(repaid); // parses repaid back to boolean const clause = `WHERE status='${status}' AND repaid=${repaid}`; const data = await Loan.Model().select('*', clause); if (!data[0]) { return nullResponse(req, res, 'No loan found'); } return res.status(200).json({ status: 200, data, }); } const data = await Loan.Model().select('*'); return res.status(200).json({ status: 200, data, }); } catch (error) { return res.status(400).send(error.message); } } /** * @description Retrieves a single specified loan * @param {object} req request parameter * @param {object} res response object {status, data} * @returns {object} A specified loan */ static async getALoan(req, res) { const { id } = req.params; try { const data = await Loan.Model().select('*', `WHERE id=${id}`); if (data[0]) { return res.status(200).json({ status: 200, data: { ...data[0], }, }); } return nullResponse(req, res, 'Loan does not exist'); } catch (error) { return res.status(400).send(error.message); } } /** * @description Approves or rejects a loan for a particular user * @param {object} req request object * @param {object} res response object * @returns {object} loan application with new status */ static async approveRejectLoan(req, res) { const { status } = req.body; const { id } = req.params; try { const data = await Loan.Model().select('*', `WHERE id=${id}`); if (!data[0]) { return nullResponse(req, res, 'Loan does not exist'); } if (data[0].status === 'approved') { return conflictResponse(req, res, 'Loan is approved already'); } const approve = await Loan.Model().update(`status='${status}'`, `WHERE id=${id} RETURNING *`); const msg = Messages.loanApprovalMessage(approve[0]); sendMail(msg); return res.status(200).json({ status: 200, data: approve[0], }); } catch (error) { return res.status(400).json(error.message); } } }
JavaScript
class TestReporter extends Transform { /** * @constructor * @param {object} options - Custom options for this reporter */ constructor (options={}) { super({ objectMode: true }); if (typeof options === 'function') { let formatter = options; options = { formatter, }; } /** Extends the default options */ this.options = Object.assign({}, options); } /** * Formats the contents for output * * @param {string} contents - Input text coming in from gulp vinyl * @returns {string} Formatted contents */ formatter (contents) { return contents; } /** * Required transform implementation for transform streams * * @param {vinyl} file - Vinyl file with test result contents * @param {string} enc - Encoding type not used for object streams. * @param {function} done - Callback when finished formatting the output */ _transform (file, enc, done) { let formatter = this.options.formatter || this.formatter; file.contents = new Buffer(formatter(file.contents.toString('utf8'))); process.stdout.write(file.contents); done(null, file); } }
JavaScript
class Movie { constructor(id, title, year, category, rating) { this.title = title; this.year = year; this.category = category; this.rating = rating; this.id = id; } }
JavaScript
class ValidationException extends BadRequestException_1.BadRequestException { /** * Creates a new instance of validation exception and assigns its values. * * @param category (optional) a standard error category. Default: Unknown * @param correlation_id (optional) a unique transaction id to trace execution through call chain. * @param results (optional) a list of validation results * @param message (optional) a human-readable description of the error. * * @see [[ValidationResult]] */ constructor(correlationId, message, results) { super(correlationId, "INVALID_DATA", message || ValidationException.composeMessage(results)); if (results) { this.withDetails("results", results); } } /** * Composes human readable error message based on validation results. * * @param results a list of validation results. * @returns a composed error message. * * @see [[ValidationResult]] */ static composeMessage(results) { let builder = "Validation failed"; if (results && results.length > 0) { let first = true; for (let i = 0; i < results.length; i++) { let result = results[i]; if (result.getType() == ValidationResultType_1.ValidationResultType.Information) { continue; } builder += first ? ": " : ", "; builder += result.getMessage(); first = false; } } return builder; } /** * Creates a new ValidationException based on errors in validation results. * If validation results have no errors, than null is returned. * * @param correlationId (optional) transaction id to trace execution through call chain. * @param results list of validation results that may contain errors * @param strict true to treat warnings as errors. * @returns a newly created ValidationException or null if no errors in found. * * @see [[ValidationResult]] */ static fromResults(correlationId, results, strict) { let hasErrors = false; for (let i = 0; i < results.length; i++) { let result = results[i]; if (result.getType() == ValidationResultType_1.ValidationResultType.Error) { hasErrors = true; } if (strict && result.getType() == ValidationResultType_1.ValidationResultType.Warning) { hasErrors = true; } } return hasErrors ? new ValidationException(correlationId, null, results) : null; } /** * Throws ValidationException based on errors in validation results. * If validation results have no errors, than no exception is thrown. * * @param correlationId (optional) transaction id to trace execution through call chain. * @param results list of validation results that may contain errors * @param strict true to treat warnings as errors. * * @see [[ValidationResult]] * @see [[ValidationException]] */ static throwExceptionIfNeeded(correlationId, results, strict) { let ex = ValidationException.fromResults(correlationId, results, strict); if (ex) throw ex; } }
JavaScript
class DemoScene { constructor(config, path) { // Root path of the DemoSystem this.setupRootPath(path); this.loader = new DemoLoader(); this.started = false; this.settings = config; this.applySettings(); // TODO Refactor // Give all the internal engine scripts to the loader this.loader.addScript(this.ROOT_PATH + "lib/Detector.js", true); this.loader.addScript(this.ROOT_PATH + "models/Scene.js", true); this.loader.addScript(this.ROOT_PATH + "models/Model.js", true); this.loader.addScript(this.ROOT_PATH + "models/Action.js", true); this.loader.addScript(this.ROOT_PATH + "models/AreaTrigger.js", true); this.loader.addScript(this.ROOT_PATH + "services/DemoService.js", true); this.loader.addScript(this.ROOT_PATH + "services/ActionService.js", true); this.loader.addScript(this.ROOT_PATH + "services/ModelService.js", true); this.loader.addScript(this.ROOT_PATH + "services/PhysicsService.js", true); this.loader.addScript(this.ROOT_PATH + "services/TriggerService.js", true); this.loader.addScript(this.ROOT_PATH + "managers/ActionManager.js", true); this.loader.addScript(this.ROOT_PATH + "controllers/DemoController.js", true); this.loader.addScript(this.ROOT_PATH + "controllers/InteractionController.js", true); this.loader.addScript(this.ROOT_PATH + "controllers/TriggerController.js", true); this.loader.addScript(this.ROOT_PATH + "controllers/DialogController.js", true); this.loader.addScript(this.ROOT_PATH + "controllers/EventController.js", true); this.loader.addScript(this.ROOT_PATH + "utils/DemoUtils.js", true); this.loader.addScript(this.ROOT_PATH + "utils/Statics.js", true); this.loader.addScript(this.ROOT_PATH + "utils/Support.js", true); } /** Private methods */ setupRootPath(path) { this.ROOT_PATH = path; if (!path && document.currentScript) { var currentPath = document.currentScript.src; if (currentPath) { this.ROOT_PATH = currentPath.substring(0, currentPath.lastIndexOf("/")+1); } else { this.ROOT_PATH = '/'; } } }; shaderCallback(name, file, content, callback) { Shaders[name] = content; callback(); }; modelCallback(name, file, content, callback) { var modelClass = eval(name); if (modelClass instanceof Model) { ModelService.load(modelClass, callback); } }; /** Public methods */ setProperties(config) { if (this.started) { console.warn("You cannot set properties anymore after the DemoScene engine has been started."); return; } // Merge existing settings and given config this.settings = Object.assign(config, this.settings); this.applySettings(); } applySettings() { if (this.settings.controls) { this.loader.addScript(this.ROOT_PATH + "modules/CharacterControls.js", true); } if (this.settings.pointerlock) { this.loader.addScript(this.ROOT_PATH + "modules/Pointerlock.js",true); } if (this.settings.audio) { this.loader.addScript(this.ROOT_PATH + "soundsystem/AudioPlayer.js", true); this.loader.addScript(this.ROOT_PATH + "soundsystem/MusicPlayer.js", true); this.loader.addScript(this.ROOT_PATH + "soundsystem/SoundPlayer.js", true); } } addGenericScript(name, scriptFile, initial, callback) { this.loader.addScript({name: name, file: scriptFile}, initial, callback); } addScene(sceneConfig) { var initial = sceneConfig.initial; this.loader.addScripts(sceneConfig.shaders, initial, this.shaderCallback); this.loader.addScripts(sceneConfig.models, initial, this.modelCallback); this.loader.addScript(sceneConfig.scene, initial); } start() { this.started = true; this.loader.start(); return true; } }
JavaScript
class CartItem { constructor({sku, description, price, quantity}) { this.sku = sku; this.description = description; this.price = price; this.quantity = quantity; } }
JavaScript
class Help extends CommandBase { _commands = require('../commands'); constructor(...args) { // Call the base class ctor with the values // we need to make this particular command. super('Help', ['h', 'help'], (args) => { const target = 90; // spaces width for help header const header = 'CLI Test Application Help'; let avgDiff = (target - header.length) / 2; const commands = require('../commands'); console.log( chalk.bgBlue( header.padStart(avgDiff + header.length) .padEnd((avgDiff * 2) + header.length))); commands.forEach(cmd => cmd.help()); }); this._description = "Outputs help information for all commands."; this._example = "cli help, cli -h"; } list() { return this._commands.map(cmd => cmd.name); } usage() { console.log(chalk.blue(`Usage: cli <command\n`)); console.log(chalk.blue(`where <command is one of: \n \t ${list.join(', ')}\n`)); } }
JavaScript
class MyDate { constructor(time) { this.time = new Date(time * 1000); } WEEKS = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; MONTHS = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; get getDay() { return this.WEEKS[this.time.getDay()]; } get getMonth() { return this.MONTHS[this.time.getMonth()]; } get getDate() { return this.time.getDate(); } get getFullYear() { return this.time.getFullYear(); } get toLocaleTimeString() { return this.time.toLocaleTimeString(); } }
JavaScript
class Stack { /* constructor () { this.head = null; this.length = 0; } */ push(/* element */) { throw new Error('Not implemented'); /* // Если стек полон -- ошибка O(1) if (this.length === this.lastElementIndex + 1) { throw new Error('Stack is full'); } // Добавление элемента в конец массива O(1) this.array[this.lastElementIndex + 1] = element; // Увеличение индекса последнего элемента O(1) this.length++; } /* push(element) { // throw new Error('Not implemented'); const node = new Node(value); if (this.head) { node.next = this.head; this.head = node; } else { this.head = ; } this.length++; // return this; */ } pop() { throw new Error('Not implemented'); /* if (this.length === 0) { return 'underfined'; } this.lastElementIndex--; return 1; /* if (this.head === null) { return 'underfined'; */ } /* const current = this.head; this.head = this.head.next; this.length--; return current.value; } */ peek() { throw new Error('Not implemented'); // return this.head.value; // return this.array[this.lastElementIndex]; // return 1; } }
JavaScript
class QualityControl { /** * Creates an quality control instance * @param {Object} context - Audio context used to extract data from utterance. * @param {Object} blob - the blob containig utterance data. * @param {Object} audioBuffer - Allows access to data of the utterance. */ constructor(context, blob, audioBuffer) { this.context = context; this.blob = blob; this.audioBuffer = audioBuffer; } /** * Checks if sound is of good quality: not too short or silent */ async isQualitySound() { const blobArrayBuffer = await this.blob.arrayBuffer(); this.audioBuffer = await this.context.decodeAudioData(blobArrayBuffer); const qualityResult = { success: true, errorMessage: '', }; const audioResult = this.silenceCheck(); if (this.audioBuffer.duration < 2.0) { qualityResult.success = false; qualityResult.errorMessage = 'Recording is too short. Try again!'; } else if (audioResult) { qualityResult.success = false; qualityResult.errorMessage = audioResult; } return qualityResult; } /** * Checks if the sound is too silent by finding the average of the 100 biggest values * of the buffer's data */ silenceCheck() { const soundCutOff = 0.2; const bufferArray = this.audioBuffer.getChannelData(0); const noDuplicateValues = Array.from(new Set(bufferArray)); // makes sure all values are unique const biggestValues = this.nLargest(noDuplicateValues, 100); const average = this.findAverage(biggestValues); if (average > soundCutOff) { return null; } else { return 'Recording is too silent. Try again!'; } } /** * Helper function for silenceCheck that returns the 100 biggest values of an array */ nLargest(arr, n) { const sorted = [...arr].sort((a, b) => b - a); return sorted.slice(0, n); } /** * Helper function for silenceCheck that returns the average of the numbers in an array */ findAverage(arr) { let total = 0; for (let i = 0; i < arr.length; i++) { total += arr[i]; } return total / arr.length; } }
JavaScript
class Wizard extends Component { constructor(props) { super(props); this.state = { mysql_ip: '', mysql_port: '', mysql_user: '', mysql_pass: '', mysql_database: '', node_port: '', mysql_engine: '', node_cerftificates: '', }; } updateForm = (key, event) => { console.info(key , event); console.info(event.target.value) this.setState({ [key]: event.target.value }); } render() { return ( <div className='container'> <MuiThemeProvider theme={theme}> <div className='jumbotron'> <div className='row'> <div className='col-xs-12 col-sm-6 offset-3'> <StepWizard isLazyMount> <First /> <Second update={this.updateForm} form={this.state} /> <Third /> <Fourth /> </StepWizard> </div> </div> </div> </MuiThemeProvider> </div> ); } }
JavaScript
class ConfirmOrderProducts extends Component { tableHead = { products: ['Modell', 'Antall', 'Pris'] }; render() { return ( <Table striped bordered hover> <thead> <tr> {this.tableHead[this.props.tableHead].map(data => ( <td key={data}>{data}</td> ))} </tr> </thead> <tbody> {Object.keys(this.props.tableBody).map((data, index) => ( <tr key={data}> <td>{data}</td> <td>{this.props.tableBody[data][0]}</td> <td>{this.props.tableBody[data][1] * this.props.tableBody[data][0]}</td> </tr> ))} </tbody> </Table> ); } }
JavaScript
class OptionsBuilder { constructor(controlProperties) { this.controlProperties = controlProperties; } /** * converts properties of view-model (with k- convention) to an object * that can be passed to a Kendo control. It also wraps templates into a function * so the Kendo templating system is not used */ getOptions(viewModel, className) { let options = {}; for (let prop of this.controlProperties.getProperties(className)) { let value = viewModel[getBindablePropertyName(prop)]; if (hasValue(value)) { if (this.isTemplate(prop)) { options[prop] = () => value; } else { options[prop] = value; } } } return pruneOptions(options); } isTemplate(propertyName) { return propertyName.toLowerCase().indexOf('template') > -1; } }
JavaScript
class Gambler { constructor(url, token) { // Initialize instance attributes this.url = url; this.token = token; this.money = null; this.status = null; // To be used in fetch requests var that = this; // PART OF BONUS MARK: To animate the result var styleElement = document.createElement("style"); document.head.appendChild(styleElement); // Source: https://css-tricks.com/snippets/css/typewriter-effect/ this.animate = "\ output[name='result'] {\ overflow: hidden; /* Ensures the content is not revealed until the animation */\ border-right: .15em solid orange; /* The typwriter cursor */\ white-space: nowrap; /* Keeps the content on a single line */\ margin: 0 auto; /* Gives that scrolling effect as the typing happens */\ letter-spacing: .15em; /* Adjust as needed */\ animation: \ typing 3.5s steps(30, end),\ blink-caret .5s step-end infinite;\ }\ \ /* The typing effect */\ @keyframes typing {\ from { width: 0 }\ to { width: 100% }\ }\ \ /* The typewriter cursor effect */\ @keyframes blink-caret {\ from, to { border-color: transparent }\ 50% { border-color: orange; }\ }" // Retrieve previous session if it exists if (localStorage.getItem("session") != null) { this.session = localStorage.getItem("session"); // POST Request 1 var formData = new FormData(); var that = this; formData.append("token", this.token); // REQUIREMENT 7 fetch(this.url + this.session + "/", { method: 'POST', body: formData, }) .then(function(response) { // Return json of response return response.json() }) // Retrieve previous's sessions money, game state, // and change HTML .then(function(response) { that.money = response.money; // Update the page's HTML document.getElementsByName('money')[0].innerHTML = that.money; document.getElementsByName('session')[0].innerHTML = that.session; if (response.game) { that.gameState = response.game; that.allButtonsOn(); } else { that.lastGame = response.last_game; that.allButtonsOff(response); } }) }; // REQUIREMENT 2 fetch("https://pizza.cs.ualberta.ca/296/") .then(function(response) { // Update the Status on the website using the up tag from the HTML status = response.statusText; var statusInHTML = document.getElementsByName('up'); statusInHTML[0].innerHTML = status; return response.text().then(function(myJson) { // Print hello message from the server console.log(myJson); }) }) .catch(function(error) { console.log("Error!") }); // REQUIREMENT 3 // If there is no previous session if (localStorage.getItem("session") == null) { var formData = new FormData(); var that = this; formData.append("token", this.token) fetch("https://pizza.cs.ualberta.ca/296/sit", { method: 'POST', body: formData, }) .then(function(response) { return response.json() }) .then(function(response) { that.session = response.session; that.money = response.money; localStorage.setItem("session", that.session); // Change the html to the session document.getElementsByName('money')[0].innerHTML = that.money; document.getElementsByName('session')[0].innerHTML = that.session; }) .catch(function(error) { console.log("Error!") }) } // Set the initial state of the game. // Make all the buttons unclickable except the 'bet' button. this.initialGameState(); } lastRound2(gameState, typeOfGame) { // Set, update, and maintain the money // on display and in the game's current session this.money = this.money + gameState.won; gameState.money = this.money; // For the dealer: Replace the facecards and ace with its appropriate letter. // Use a for loop to reassign each value. var dealersHand = gameState.dealer_hand; if (dealersHand.length > 1) { document.getElementsByName('surrender')[0].disabled = true; } for (var i = 0; i < dealersHand.length; i++) { if (dealersHand[i] == 1) { dealersHand[i] = "A"; } if (dealersHand[i] == 11) { dealersHand[i] = "J"; } if (dealersHand[i] == 12) { dealersHand[i] = "Q"; } if (dealersHand[i] == 13) { dealersHand[i] = "K"; } } // For the player: Replace the facecards and ace with its appropriate letter var playersHand = gameState.player_hand; for (var i = 0; i < playersHand.length; i++) { if (playersHand[i] == 1) { playersHand[i] = "A"; } if (playersHand[i] == 11) { playersHand[i] = "J"; } if (playersHand[i] == 12) { playersHand[i] = "Q"; } if (playersHand[i] == 13) { playersHand[i] = "K"; } } // Otherwise, it would print out the current game state twice // and doesn't print when typeOfGame is lastGame. if (typeOfGame == "last_game") { console.log("Money: "+ this.money); console.log("Bet: "+ gameState.bet); console.log("Dealer's Hand: " + dealersHand); console.log("Your Cards: " + playersHand); } // Replace the HTML on the page with the current money, and // appropriate facecard and ace letters. document.getElementsByName('money')[0].innerHTML = this.money; document.getElementsByName('dealer_hand')[0].innerHTML = dealersHand; document.getElementsByName('player_hand')[0].innerHTML = playersHand; // Replace the HTML on the bottom part of the page for result and // 'you made'. this.allButtonsOff(); // Animate document.getElementsByName('result')[0].innerHTML = gameState.result; this.bonusAnimation(this.animate); document.getElementsByName('last_bet')[0].innerHTML = gameState.bet; document.getElementsByName('won')[0].innerHTML = gameState.won; } bonusAnimation(elementStyle) { // Locate the style tag on the HTML file. // Alter the text within the style tag. var style = document.getElementsByTagName('style')[0]; var animation = document.createElement('style'); animation.innerHTML = elementStyle; // Replace style.parentNode.insertBefore(animation, style); style.parentNode.removeChild(style); } sameRound2(gameState, typeOfGame) { // When the round is ending, print the current game state to the // console and upadte the HTML on the web page. document.getElementsByName('result')[0].innerHTML = " "; document.getElementsByName('won')[0].innerHTML = " "; // For the dealer: Replace the facecards and ace with its appropriate letter. // Use a for loop to reassign each value. var dealersHand = gameState.dealer_hand; if (dealersHand.length > 1) { document.getElementsByName('surrender')[0].disabled = true; } for (var i = 0; i < dealersHand.length; i++) { if (dealersHand[i] == 1) { dealersHand[i] = "A"; } if (dealersHand[i] == 11) { dealersHand[i] = "J"; } if (dealersHand[i] == 12) { dealersHand[i] = "Q"; } if (dealersHand[i] == 13) { dealersHand[i] = "K"; } } // For the player: Replace the facecards and ace with its appropriate letter var playersHand = gameState.player_hand; for (var i = 0; i < playersHand.length; i++) { if (playersHand[i] == 1) { playersHand[i] = "A"; } if (playersHand[i] == 11) { playersHand[i] = "J"; } if (playersHand[i] == 12) { playersHand[i] = "Q"; } if (playersHand[i] == 13) { playersHand[i] = "K"; } } // console.log("Your Cards: " + playersHand); // Replace the HTML on the page with the current money, and // appropriate facecard and ace letters. document.getElementsByName('money')[0].innerHTML = this.money; document.getElementsByName('dealer_hand')[0].innerHTML = dealersHand; document.getElementsByName('player_hand')[0].innerHTML = playersHand; // Otherwise, it would print out the current game state twice // and doesn't print when typeOfGame is gameState. if (typeOfGame == "game") { console.log("Money: "+ this.money); console.log("Bet: "+ gameState.bet); console.log("Dealer's Hand: " + dealersHand); console.log("Your Cards: " + playersHand); } this.allButtonsOn(); } // REQUIREMENT 4 bet(amount) { // Make the amount a positive number so we don't // get the 400 Bad Request Error amount = Math.abs(amount); // Update the 'you bet' on the bottom of the page document.getElementsByName('last_bet')[0].innerText = amount; document.getElementsByName('result')[0].innerHTML = " "; document.getElementsByName('won')[0].innerHTML = " "; // Make 'bet' unclickable and all the other actions clickable. this.allButtonsOn(); var that = this; // If we are dealing with a previous session if (this.lastGame) { this.lastRound2(this.lastGame, "lastGame") } else if (this.gameState) { this.sameRound2(this.gameState, "gameState") } var formData = new FormData(); formData.append("token", this.token) formData.append('amount', amount) fetch(this.url + this.session + "/bet", { method: 'POST', body: formData, }) // Retrieve the response .then(function(response) { // Update the Status on the website using the up tag from the HTML that.status = response.statusText; document.getElementsByName('up')[0].innerHTML = that.status; return response.json() }) // If we are not dealing with a current session .then(function(response) { if (response.last_game) { // When the round is over that.lastRound2(response.last_game, "last_game") } else if (response.game) { // When the round is still playing that.sameRound2(response.game, "game") } }) .catch(function(error) { console.log("Error with 'Bet'!") }); } stand() { var formData = new FormData(); formData.append("token", this.token) var that = this; // If we are dealing with a previous session if (this.lastGame) { this.lastRound2(this.lastGame, "lastGame") } else if (this.gameState) { this.sameRound2(this.gameState, "gameState") } fetch(this.url + this.session + "/stand", { method: 'POST', body: formData, }) // Retrieve the response .then(function(response) { // Update the Status on the website using the up tag from the HTML status = response.statusText; var statusInHTML = document.getElementsByName('up'); statusInHTML[0].innerHTML = status; return response.json() }) // If we are not dealing with a previous session .then(function(response) { // console.log(response); if (response.last_game) { // When the round is over that.lastRound2(response.last_game, "last_game"); } else if (response.game) { // When the round is still playing that.sameRound2(response.game, "game") } }) .catch(function(error) { console.log("Error with 'Stand'!") }); } hit() { // If we are dealing with a previous session if (this.lastGame) { this.lastRound2(this.lastGame, "lastGame") } else if (this.gameState) { this.sameRound2(this.gameState, "gameState") } var formData = new FormData(); var that = this; formData.append("token", this.token) fetch(this.url + this.session + "/hit", { method: 'POST', body: formData, }) // Retrieve the response .then(function(response) { // Update the Status on the website using the up tag from the HTML status = response.statusText; var statusInHTML = document.getElementsByName('up'); statusInHTML[0].innerHTML = status; return response.json() }) // If we are not dealing with a previous session .then(function(response) { if (response.last_game) { that.lastRound2(response.last_game, "last_game") } else if (response.game) { that.sameRound2(response.game, "game") } // PART OF REQUIREMENT 6: // You can't surrender after hitting document.getElementsByName('surrender')[0].disabled = true; }) .catch(function(error) { console.log("Error with 'Hit'!") }); } double_down() { // If we are dealing with a previous session if (this.lastGame) { this.lastRound2(this.lastGame, "lastGame") } else if (this.gameState) { this.sameRound2(this.gameState, "gameState") } var formData = new FormData(); var that = this; formData.append("token", this.token); fetch(this.url + this.session + "/double_down", { method: 'POST', body: formData, }) // Retrieve the response .then(function(response) { // Update the Status on the website using the up tag from the HTML status = response.statusText; var statusInHTML = document.getElementsByName('up'); statusInHTML[0].innerHTML = status; return response.json() }) // If we are not dealing with a previous session .then(function(response) { // that.money = that.money - (that.money - response.money) if (response.last_game) { that.lastRound2(response.last_game, "last_game") } else if (response.game) { that.sameRound2(response.game, "game") } }) .catch(function(error) { console.log("Error with 'Double Down'!") }); } surrender() { // Get the information for the POST request var formData = new FormData(); var that = this; formData.append("token", this.token) fetch(this.url + this.session + "/surrender", { method: 'POST', body: formData, }) // Retrieve the response .then(function(response) { // Update the Status on the website using the up tag from the HTML status = response.statusText; var statusInHTML = document.getElementsByName('up'); statusInHTML[0].innerHTML = status; return response.json() }) .then(function(response) { if (response.last_game) { that.lastRound2(response.last_game, "last_game") } else if (response.game) { that.sameRound2(response.game, "game") } }) .catch(function(error) { console.log("Error with 'Surrender'!") }); } initialGameState() { // Set the initial state of the game. // PART OF REQUIREMENT 6: // You can't stand/hit/double down/surrender when there is NO game in progress. document.getElementsByName('stand')[0].disabled = true; document.getElementsByName('hit')[0].disabled = true; document.getElementsByName('double_down')[0].disabled = true; document.getElementsByName('surrender')[0].disabled = true; } allButtonsOff(response) { // After one of the four actions has been selected (not including bet), // make all the buttons unclickable. Only bet can be used. // console.log(response); // if (response.last_game) { document.getElementsByName('stand')[0].disabled = true; document.getElementsByName('hit')[0].disabled = true; document.getElementsByName('double_down')[0].disabled = true; document.getElementsByName('surrender')[0].disabled = true; // Make bet clickable/usable. document.getElementsByName('betButton')[0].disabled = false; document.getElementsByName('bet')[0].disabled = false; } allButtonsOn() { // After bet has been selected, make all the othe buttons clickable. // Make bet unclickable. document.getElementsByName('stand')[0].disabled = false; document.getElementsByName('hit')[0].disabled = false; document.getElementsByName('double_down')[0].disabled = false; document.getElementsByName('surrender')[0].disabled = false; // You can't bet when there's a game in progress. document.getElementsByName('betButton')[0].disabled = true; // You can't change your bet when there's a game in progress. document.getElementsByName('bet')[0].disabled = true; } }
JavaScript
@connect(({ demo }) => ({ demo, })) class Demo extends Component { handleSubmit = () => { const { dispatch } = this.props; dispatch({ type: 'demo/process', payload: { data: document.getElementById('input').value, }, }); }; render() { let data = this.props.demo.data; return ( <div> <Input placeholder={data} disabled={true} /> <Input id="input" /> <Button onClick={this.handleSubmit} /> </div> ); } }
JavaScript
class TcpdumpLineQueue { /** * TcpdumpLineQueue constructor * @constructor */ constructor(data) { this.data = data || ''; } /** * Add data to the queue. * @param {String} data The string to add. */ addData(data) { this.data += data; } /** * Slice the data at the given index. * @param {Number} index The index from which to slice the data. */ sliceAtIndex(index) { this.data = this.data.slice(index); } /** * Determine the index of the given string, if present. * @param {String} string The string to look for. * @return {Number} The index of the given string if present, else -1. */ indexOf(string) { return this.data.indexOf(string); } /** * Determine if the given regular expression matches. * @param {RegExp} regex The regular expression to match against. * @return {Array} The matches, else null. */ match(regex) { return this.data.match(regex); } }
JavaScript
class WithDrawer extends Component { static propTypes = { /** * Function responsible for rendering children. * This function should implement the following signature: * ( { rowHeight: number, rowRenderer: func - has to be passed as the React-Virtualized rowRenderer prop, toggleDrawer: func - can be used by decorated component to trigger drawer expansion toggleDrawerWithAnimation: func - can be used by decorated component to trigger drawer expansion toggleDrawerCellRenderer: func - can be passed as a cellRenderer prop for a RV Table Column }) => PropTypes.element */ children: PropTypes.func.isRequired, /** * a function that will return the React element to be used in the drawer * it will be passed the props that are passed to a RV rowRenderer * so that the drawer content element can use them to display data */ drawerContent: PropTypes.func.isRequired, /** * array of data for each row's drawer * { collapsedHeight; number, expandedHeight: number } */ rowsDimensions: PropTypes.array.isRequired, } constructor( props ) { super( props ); this.state = { rowsExpandedState: {} }; // used by the expand row mechanism this.rowsHeight = []; this.rowsTween = {}; } /** * a custom function as the row renderer * returning what we want to see in the drawer of each row * * @param {object} props passed by the React Virtualized rowRenderer function * @returns {React.element} a React element that will render a Table row */ rowRenderer = ( rowProps ) => { const drawerContent = this.props.drawerContent( rowProps ); const { collapsedHeight, expandedHeight } = this.props.rowsDimensions[ rowProps.index ]; return ( <RowRendererWithDrawer drawerContent={ drawerContent } collapsedHeight={ collapsedHeight } expandedHeight={ expandedHeight } key={ rowProps.key } expanded={ this.state.rowsExpandedState[ rowProps.index ] } { ...rowProps } /> ); } /** * toggles the drawer */ toggleDrawer = ( index ) => { this.setState( ( state ) => { return { rowsExpandedState: { ...state.rowsExpandedState, [ index ]: ! state.rowsExpandedState[ index ], } }; }, () => this.table.recomputeRowHeights() ); } /** * sets up & starts the drawer animated expansion mechanism * @param {integer} index - the index of the row we want to expand */ toggleDrawerWithAnimation = ( index ) => { const _this = this; this._animating = true; const expanded = this.state.rowsExpandedState[ index ]; if ( ! expanded ) { _this.toggleDrawer( index ); } const height = expanded ? this.props.rowsDimensions[ index ].expandedHeight : this.props.rowsDimensions[ index ].collapsedHeight; const targetHeight = expanded ? this.props.rowsDimensions[ index ].collapsedHeight : this.props.rowsDimensions[ index ].expandedHeight; this.rowsHeight[ index ] = { height }; this.rowsTween[ index ] ? this.rowsTween[ index ].stop() : null; this.rowsTween[ index ] = new TWEEN.Tween( { height } ) .to( { height: targetHeight }, 250 ) .easing( TWEEN.Easing.Quadratic.Out ) .onUpdate( function() { // store tweened height for this row _this.rowsHeight[ index ] = this.height; // React Virtualized needs this to update row heights & positions // on each frame _this.table.recomputeRowHeights( index ); } ) .onComplete( function() { delete _this.rowsHeight[ index ]; if ( expanded ) { _this.toggleDrawer( index ); } _this._animating = false; } ) .start(); // start the loop this._animate(); } /** * starts the animation loop * @param {DOMHighResTimeStamp} time the current time */ _animate = ( time ) => { if ( this._animating ) { requestAnimationFrame( this._animate ); } TWEEN.update( time ); } rowHeight = ( { index } ) => { const { expandedHeight, collapsedHeight } = this.props.rowsDimensions[ index ]; const expanded = this.state.rowsExpandedState[ index ]; const initialHeight = expanded ? expandedHeight : collapsedHeight; return this.rowsHeight[ index ] || initialHeight; } setTableRef = ( element ) => { this.table = element; } render() { return this.props.children( { rowRenderer: this.rowRenderer, rowHeight: this.rowHeight, setTableRef: this.setTableRef, rowsExpandedState: this.state.rowsExpandedState, toggleDrawer: this.toggleDrawer, toggleDrawerWithAnimation: this.toggleDrawerWithAnimation, } ); } }
JavaScript
class PriorityQueue { constructor() { this.values = []; } enqueue (value, priority) { let newNode = new Node (value, priority); this.values.push(newNode); this.bubbleUp(); } bubbleUp() { let index = this.values.length -1; const element = this.values[index]; while (index > 0) { let parentIndex = Math.floor((index - 1) / 2); let parent = this.values[parentIndex]; if (element.priority >= parent.priority) break; this.values[parentIndex] = element; this.values[index] = parent; index = parentIndex; } } dequeue() { const min = this.values[0]; const end = this.values.pop(); if (this.values.length > 0) { this.values[0] = end; this.sinkDown(); } return max; } sinkDown() { let index = 0; const length = this.values.length; const element = this.values[0]; while(true) { let leftChildIndex = 2 * index + 1; let rightChildIndex = 2 * index + 2; let rightChild, leftChild; let swap = null; if (leftChildIndex < length) { leftChild = this.values[leftChildIndex]; if (leftChild.priority > element.priority) { swap = leftChildIndex; } } if (rightChildIndex < length) { rightChild = this.values[rightChildIndex]; if ( (swap === null && rightChild.priority < element.priority) || (swap !==null && rightChild.priority < leftChild.priority) ){ swap = rightChildIndex; } if (swap === null) break; this.values[index] = this.values[swap]; this.values[swap] = element; index = swap; } } } }
JavaScript
class FactorService extends Service { /** * Get an email OTP factor enrollment. * @param {string} userId The identifier of the user for which to retrieve * enrollments. * @return {Promise<Array>} The array of enrollments for the given user. */ async getEnrollments(userId=undefined) { let response; if (userId) { response = await this.get('/v2.0/factors', {search: `userId="${userId}"&enabled=true`}); } else { response = await this.get('/v2.0/factors', {search: `enabled=true`}); } return response.data; } }
JavaScript
class HistoryPanelProxy { constructor() { const Galaxy = getGalaxyInstance(); Galaxy.currHistoryPanel = this; const model = (this.model = new Backbone.Model({})); this.collection = { constructor(models) { this.models = models; this.unwatch = null; }, each(callback) { const historyItems = store.getters.getHistoryItems({ historyId: model.id, filterText: "" }); historyItems.forEach((model) => { callback(new Backbone.Model(model)); }); }, on(name, callback) { this.off(); this.unwatch = store.watch( (state, getters) => getters.getLatestCreateTime(), () => { callback(); console.debug("History change watcher detected a change.", name); } ); console.debug("History change watcher enabled.", name); }, off(name) { if (this.unwatch) { this.unwatch(); console.debug("History change watcher disabled.", name); } }, }; // watch the store, update history id store.watch( (state, getters) => getters["history/currentHistory"], (history) => { this.model.id = history.id; this.model.set("name", history.name); } ); // start watching the history with continuous queries watchHistory(); } refreshContents() { // to be removed after disabling legacy history } loadCurrentHistory() { store.dispatch("history/loadCurrentHistory"); } switchToHistory(historyId) { this.model.id = historyId; store.dispatch("history/setCurrentHistoryId", historyId); } async buildCollection(collectionType, selection, hideSourceItems, fromRulesInput = false) { let selectionContent = null; if (fromRulesInput) { selectionContent = selection; } else { selectionContent = new Map(); selection.models.forEach((obj) => { selectionContent.set(obj.id, obj); }); } const modalResult = await buildCollectionModal( collectionType, this.model.id, selectionContent, hideSourceItems, fromRulesInput ); if (modalResult) { console.debug("Submitting collection build request.", modalResult); await createDatasetCollection({ id: this.model.id }, modalResult); } } render() { const container = document.createElement("div"); $("#right > .unified-panel-header").remove(); $("#right > .unified-panel-controls").remove(); $("#right > .unified-panel-body").remove(); $("#right").addClass("beta").prepend(container); const mountFn = mountVueComponent(HistoryIndex); mountFn({}, container); } }
JavaScript
class NumberInput { constructor(el, integer, max) { this.$el = el; this.integer = integer; this.max = max; const group = numberFormat[','] === ' ' ? 's' : numberFormat[',']; const decimals = numberFormat['.']; this.trimLeadingZerosRegExp = new RegExp(`^[0\\${group}]+(?!\\${decimals}|$)`); this.queue = { timeout: null, fromCaret: 0 }; this.handleKeydown = this.handleKeydown.bind(this); this.handleKeypress = this.handleKeypress.bind(this); this.$el.addEventListener('keydown', this.handleKeydown); this.$el.addEventListener('keypress', this.handleKeypress); } mask(value) { if (!value) { return ''; } value = value + ''; const maxIntegerPositions = this.max ? this.max.toString().length : Infinity; const maxFractionPositions = this.integer ? 0 : numberFormat.decimals; const fraction = []; let integer = []; let inputIdx; let outputIdx; let input; let hasFractional = false; let integerPart; let fractionalPart; value = [value]; NUMBER_DELIMETRS.forEach((jumpChar) => { let valueArray = []; value.forEach((chunk) => { chunk = String(chunk); valueArray = valueArray.concat(chunk.split(jumpChar)); }); value = valueArray; }); integerPart = value.shift() || ''; fractionalPart = value; value = [integerPart]; if (fractionalPart.length > 0) { value.push(fractionalPart.join('')); } if (maxFractionPositions && value.length > 1) { hasFractional = true; } if (value.length > 2) { value[1] = value[1] + value.slice(2).join(''); } inputIdx = 0; outputIdx = 0; input = value[0]; while (outputIdx < maxIntegerPositions && inputIdx < input.length) { let inputChar = input.charAt(inputIdx); if (/^\d$/.test(inputChar)) { integer.push(inputChar); outputIdx += 1; } inputIdx += 1; } inputIdx = 0; outputIdx = 0; input = (value[1] || ''); while (outputIdx < maxFractionPositions && inputIdx < input.length) { let inputChar = input.charAt(inputIdx); if (/^\d$/.test(inputChar)) { fraction.push(inputChar); outputIdx += 1; } inputIdx += 1; } value = ''; integer = integer.reverse(); // support different digit groups sizes. if (numberFormat.groupSize.length === 1) { while (integer.length > 0) { value = integer.splice(0, numberFormat.groupSize[0]).reverse().join('') + value; if (integer.length > 0) { value = numberFormat[','] + value; } } } else { value = integer.splice(0, numberFormat.groupSize[0]).reverse().join(''); while (integer.length > 0) { value = numberFormat[','] + value; value = integer.splice(0, numberFormat.groupSize[1]).reverse().join('') + value; } } if (hasFractional) { value = value + numberFormat['.'] + fraction.join(''); } return value; } unmask(value) { if (!value) { return ''; } return (value + '').trim() .split(numberFormat[',']) .join('') .split(numberFormat['.']) .join('.'); } value() { const value = this.unmask(this.$el.value); return (value === '' || isNaN(value)) ? null : Number(value); } // Splits input value by selection position. splitValue() { const element = this.$el; const value = element.value; const selection = getSelection(element); const start = selection.start; const end = selection.end; const prependix = this.unmask(value.substring(0, start)); const appendixStart = end > 0 ? value.substring(0, end).length : 0; const appendix = this.unmask(value.substring(end), appendixStart); return { start, end, prependix, appendixStart, appendix }; } off() { this.$el.removeEventListener('keydown', this.handleKeydown); this.$el.removeEventListener('keypress', this.handleKeypress); } // Updates input. updateInput(value, selection) { const element = this.$el; element.value = this.mask(value); if (selection) { setSelection(element, { start: selection }); } } // Handles keydown event. handleKeydown(e) { const key = e.keyCode; const element = e.target; let value = element.value; let step = 1; if (key === keys.BACKSPACE || key === keys.DELETE) { let { start, end, prependix, appendix } = this.splitValue(); if (key === keys.BACKSPACE && start === end) { prependix = prependix.slice(0, -1); step = -1; start -= 1; } if (key === keys.DELETE && start === end) { appendix = appendix.substring(1); } this.updateInput(prependix + appendix); value = element.value; setSelection(element, { start: value.length }); e.preventDefault(); } } // Handles keypress event. handleKeypress(e) { if (e.which === 0 || e.metaKey || e.ctrlKey || e.keyCode === keys.ENTER) { return; } const element = e.target; const queue = this.queue; let value = element.value; const { start, end, prependix, appendix } = this.splitValue(); clearTimeout(queue.timeout); if (!queue.prependix) { queue.prependix = prependix; queue.maskedPrependix = value.substring(0, start); queue.appendix = appendix; queue.maskedAppendix = value.substring(end); } queue.timeout = setTimeout(() => { value = element.value; const len = queue.maskedAppendix.length ? -queue.maskedAppendix.length : value.length; const input = value.slice(queue.maskedPrependix.length, len); const selectionStart = this.mask(`${queue.prependix}${input}`).length; this.updateInput(`${queue.prependix}${input}${queue.appendix}`, selectionStart); queue.prependix = false; queue.appendix = false; }, SLOW_MODE_DELAY); } }
JavaScript
class TemplateParser extends BaseParser { /** * Files not processed. * @member {string[]} */ notProcessed = []; /** * Constructor. * * @param {object} config Configs. * * @return {TemplateParser} */ constructor(config) { super(config); } /** * Parser run. * * @param {string[]} files Files to parse. * @param {string} parseName Parse name. * @param {boolean} paginate Paginate? * @param {object} data Additional data to parse. * @param {string[]|null} incremental Incremental build? * * @return {number} */ async parse(files, parseName = null, paginate = true, data = null, incremental = null) { let pn = parseName || 'NULL'; this.notProcessed = []; this.paginators = []; let totalFiles = files.length; let count = 0; if (!this.config.processArgs.argv.silent) syslog.printProgress(0); await Promise.all(files.map(async element => { let trimmed = element.replace(this.config.sitePath, ''); let ext = path.extname(element).substring(1); if (this.config.templateHandlers.hasHandlerForExt(ext)) { try { debug(`Seeing if template for ${trimmed} is parseable (${pn}).`) let tf = await this._parseTemplateFile(element, parseName, paginate, true, data, incremental); if (null !== tf) { this._addToCollections(tf); debug(`${trimmed} was indeed parseable (${pn}).`) } else { debug(`Template file is null: ${trimmed}. This just means it won't be added to collections here.`); } } catch (e) { if (e instanceof StaticoTemplateHandlerError) { syslog.error(`Failed to process ${trimmed}: ${e.message}`); } else { throw e; } } } else { this._copyFile(element); } count++; if (!this.config.processArgs.argv.silent) syslog.printProgress((count/totalFiles) * 100); })); if (!this.config.processArgs.argv.silent) syslog.endProgress(); return count; } /** * Parse file and return string output. * * @param {string[]} file File to parse. * @param {string} parseName Parse name. * @param {boolean} paginate Paginate? * @param {object} data Additional data to parse. * * @return {TemplateFile} */ async parseAndReturnString(file, parseName = null, paginate = true, data = null) { let trimmed = file.replace(this.config.sitePath, ''); let ext = path.extname(file).substring(1); if (this.config.templateHandlers.hasHandlerForExt(ext)) { try { debug(`Seeing if template for ${trimmed} is parseable (${pn}).`); let tf; try { tf = new TemplateFile(file, this.config, true, data); } catch (e) { syslog.error(`Failed to construct template file for: ${trimmed}, ${e.message}`); } if (!tf) { syslog.error(`Failed to create TemplateFile for ${file}`); } else { await tf.load(parseName, paginate); await this.config.events.emit('statico.abouttoparsetemplatefile', this.config, tf); if (null === parseName || parseName === tf.data.parse) { debug(`Passing control to template handler for ${ext}, for file ${trimmed}.`); let handler = this.config.templateHandlers.getHandlerForExt(ext) await handler.process(tf); //await this.config.events.emit('statico.parsedtemplatefile', this.config, tf); return tf; } } } catch (e) { if (e instanceof StaticoTemplateHandlerError) { syslog.error(`Failed to process ${trimmed}: ${e.message}`); } else { throw e; } } } return null; } /** * Parse a template file. * * @param {string} filePath Where the file is. * @param {string} parseName The parse. Either a parse name or null to force the parse. * @param {boolean} paginate Paginate? * @param {object} data Additional data to parse. * @param {string[]|null} incremental Incremental build? * * @return {TemplateFile|null} Template file or null. */ async _parseTemplateFile(filePath, parseName, paginate = true, mightHaveLayout = true, data = null, incremental = null) { let trimmed = filePath.replace(this.config.sitePath, ''); debug(`In _parseTemplateFile for ${trimmed}.`); let ext = path.extname(filePath).substring(1); if (this.config.templateHandlers.hasHandlerForExt(ext)) { debug(`Reconfirmed we have template handler for ${ext}, processing ${trimmed}.`); let tf; try { tf = new TemplateFile(filePath, this.config, mightHaveLayout, data); } catch (e) { syslog.error(`Failed to construct template file for: ${trimmed}, ${e.message}`); } if (!tf) { syslog.error(`Failed to create TemplateFile for ${filePath}`); } await tf.load(parseName, paginate); await this.config.events.emit('statico.abouttoparsetemplatefile', this.config, tf); if (null === parseName || parseName === tf.data.parse) { debug(`Passing control to template handler for ${ext}, for file ${trimmed}.`) let handler = this.config.templateHandlers.getHandlerForExt(ext) await handler.process(tf, incremental); // Add schema. if (!this.config.schema[tf.data.permalink]) { this.config.schema[tf.data.permalink] = new Schema(this.config); } this.config.schema[tf.data.permalink].setCtx(tf.data); //await this.config.events.emit('statico.parsedtemplatefile', this.config, tf); return tf; } else { this.notProcessed.push(filePath); } } else { throw new StaticoTemplateParserError(`No template handler found for extension '${ext}', processing file: ${filePath}`); } return null; } /** * Add a template to collections. * * @param {TemplateFile} tf Template file to add. * * @return {void} */ async _addToCollections(tf) { if (!this.config.collections.all) { this.config.collections.all = new CollectionDateSorted('all'); } if (!tf.data.permalink) { return; } if (this.config.collections.all.has(tf.data.permalink) && !this.config.watching) { throw new StaticoTemplateParserError(`We already have a template file for permalink '${tf.data.permalink}'.`); } this.config.collections.all.set(tf.data.permalink, tf); for (let idx in this.config.collectionSpec) { if (tf.data[idx]) { if (true === this.config.collectionSpec[idx]) { // Create the collection if necessary. if (!this.config.collections[idx]) { this.config.collections[idx] = {}; } // get a proper array of items. let items = tf.data[idx]; if (!Array.isArray(items)) { if ("string" == typeof items) { if (items.includes(',')) { items = items.split(','); } else { items = [items]; } } else { items = [items]; } } // Add each item. for (let entry of items) { if (!this.config.collections[idx][entry]) { this.config.collections[idx][entry] = new CollectionDateSorted(`${idx}:${entry}`); } this.config.collections[idx][entry].set(tf.data.permalink, tf); } } } } if (tf.data.dynamic) { this.config.dynamicData[tf.data.permalink] = tf.data.dynamic; } } }
JavaScript
class Color { // values are 0-100 for normal RGBA constructor(r = -1, g = 0, b = 0, a = 100) { if (r < 0) { a = 0; r = 0; } this.r = r; this.g = g; this.b = b; this.a = a; } rgb() { return [this.r, this.g, this.b]; } rgba() { return [this.r, this.g, this.b, this.a]; } isNull() { return this.a === 0; } alpha(v) { return new Color(this.r, this.g, this.b, clamp$1(v, 0, 100)); } // luminosity (0-100) get l() { return Math.round(0.5 * (Math.min(this.r, this.g, this.b) + Math.max(this.r, this.g, this.b))); } // saturation (0-100) get s() { if (this.l >= 100) return 0; return Math.round(((Math.max(this.r, this.g, this.b) - Math.min(this.r, this.g, this.b)) * (100 - Math.abs(this.l * 2 - 100))) / 100); } // hue (0-360) get h() { let H = 0; let R = this.r; let G = this.g; let B = this.b; if (R >= G && G >= B) { H = 60 * ((G - B) / (R - B)); } else if (G > R && R >= B) { H = 60 * (2 - (R - B) / (G - B)); } else if (G >= B && B > R) { H = 60 * (2 + (B - R) / (G - R)); } else if (B > G && G > R) { H = 60 * (4 - (G - R) / (B - R)); } else if (B > R && R >= G) { H = 60 * (4 + (R - G) / (B - G)); } else { H = 60 * (6 - (B - G) / (R - G)); } return Math.round(H); } equals(other) { if (typeof other === "string") { if (other.startsWith("#")) { if (other.length == 4) { return this.css() === other; } } if (this.name && this.name === other) return true; } else if (typeof other === "number") { const O = from(other); return this.css() === O.css(); } const O = from(other); if (this.isNull()) return O.isNull(); if (O.isNull()) return false; return this.r === O.r && this.g === O.g && this.b === O.b && this.a === O.a; } toInt() { // if (this.isNull()) return -1; const r = Math.max(0, Math.min(15, Math.round((this.r / 100) * 15))); const g = Math.max(0, Math.min(15, Math.round((this.g / 100) * 15))); const b = Math.max(0, Math.min(15, Math.round((this.b / 100) * 15))); const a = Math.max(0, Math.min(15, Math.round((this.a / 100) * 15))); // TODO - alpha return (r << 12) + (g << 8) + (b << 4) + a; } toLight() { return this.rgb(); } clamp() { if (this.isNull()) return this; return make([ clamp$1(this.r, 0, 100), clamp$1(this.g, 0, 100), clamp$1(this.b, 0, 100), clamp$1(this.a, 0, 100), ]); } blend(other) { const O = from(other); if (O.isNull()) return this; if (O.a === 100) return O; const pct = O.a / 100; const keepPct = 1 - pct; const newColor = make(Math.round(this.r * keepPct + O.r * pct), Math.round(this.g * keepPct + O.g * pct), Math.round(this.b * keepPct + O.b * pct), Math.round(O.a + this.a * keepPct)); return newColor; } mix(other, percent) { const O = from(other); if (O.isNull()) return this; if (percent >= 100) return O; const pct = clamp$1(percent, 0, 100) / 100; const keepPct = 1 - pct; const newColor = make(Math.round(this.r * keepPct + O.r * pct), Math.round(this.g * keepPct + O.g * pct), Math.round(this.b * keepPct + O.b * pct), (this.isNull() ? 100 : this.a) * keepPct + O.a * pct); return newColor; } // Only adjusts r,g,b lighten(percent) { if (this.isNull()) return this; if (percent <= 0) return this; const pct = clamp$1(percent, 0, 100) / 100; const keepPct = 1 - pct; return make(Math.round(this.r * keepPct + 100 * pct), Math.round(this.g * keepPct + 100 * pct), Math.round(this.b * keepPct + 100 * pct), this.a); } // Only adjusts r,g,b darken(percent) { if (this.isNull()) return this; const pct = clamp$1(percent, 0, 100) / 100; const keepPct = 1 - pct; return make(Math.round(this.r * keepPct + 0 * pct), Math.round(this.g * keepPct + 0 * pct), Math.round(this.b * keepPct + 0 * pct), this.a); } bake(_clearDancing = false) { return this; } // Adds a color to this one add(other, percent = 100) { const O = from(other); if (O.isNull()) return this; const alpha = (O.a / 100) * (percent / 100); return new Color(Math.round(this.r + O.r * alpha), Math.round(this.g + O.g * alpha), Math.round(this.b + O.b * alpha), clamp$1(Math.round(this.a + alpha * 100), 0, 100)); } scale(percent) { if (this.isNull() || percent == 100) return this; const pct = Math.max(0, percent) / 100; return make(Math.round(this.r * pct), Math.round(this.g * pct), Math.round(this.b * pct), this.a); } multiply(other) { if (this.isNull()) return this; let data; if (Array.isArray(other)) { if (other.length < 3) throw new Error("requires at least r,g,b values."); data = other; } else { if (other.isNull()) return this; data = other.rgb(); } const pct = (data[3] || 100) / 100; return make(Math.round(this.r * (data[0] / 100) * pct), Math.round(this.g * (data[1] / 100) * pct), Math.round(this.b * (data[2] / 100) * pct), 100); } // scales rgb down to a max of 100 normalize() { if (this.isNull()) return this; const max = Math.max(this.r, this.g, this.b); if (max <= 100) return this; return make(Math.round((100 * this.r) / max), Math.round((100 * this.g) / max), Math.round((100 * this.b) / max), 100); } /** * Returns the css code for the current RGB values of the color. * @param base256 - Show in base 256 (#abcdef) instead of base 16 (#abc) */ css() { if (this.a !== 100) { const v = this.toInt(); // if (v < 0) return "transparent"; return "#" + v.toString(16).padStart(4, "0"); } const v = this.toInt(); // if (v < 0) return "transparent"; return "#" + v.toString(16).padStart(4, "0").substring(0, 3); } toString() { if (this.name) return this.name; // if (this.isNull()) return "null color"; return this.css(); } }
JavaScript
class Utils { /** * Loop between .9 and .3 to check peak at each thresolds * @param {function} onLoop Function for each iteration * @param {mixed} minValidThresold Function for each iteration * @param {mixed} callback Function executed at the end */ loopOnThresolds(onLoop, minValidThresold, callback) { /** * Top starting value to check peaks * @type {number} */ let thresold = 0.95; /** * Minimum value to check peaks */ if (typeof minValidThresold === 'function' || typeof minValidThresold === 'boolean') { callback = minValidThresold || callback; minValidThresold = 0.3; } if (typeof minValidThresold === 'undefined') { minValidThresold = 0.3; } if (typeof callback !== 'function') { callback = this.noop; } const minThresold = minValidThresold; /** * Optionnal object to store data */ const object = {}; /** * Loop between 0.90 and 0.30 (theoretically it is 0.90 but it is 0.899999, due because of float manipulation) */ do { let stop = false; thresold -= 0.05; onLoop(object, thresold, bool => { stop = bool; }); if (stop) { break; } } while (thresold > minThresold); /** * Ended callback */ return callback(object); } /** * Generate an object with each keys (thresolds) with a defaultValue * @param {mixed} defaultValue Contain the înitial value for each thresolds * @param {function} callback Callback function * @return {object} Object with thresolds key initialized with a defaultValue */ generateObjectModel(defaultValue, callback) { return this.loopOnThresolds((object, thresold) => { object[thresold.toString()] = JSON.parse(JSON.stringify(defaultValue)); }, object => { if (callback) { return callback(JSON.parse(JSON.stringify(object))); } return object; }); } /** * Empty method */ noop() {} }
JavaScript
class Active extends Component { render() { return ( <div> </div> ) } }
JavaScript
class CDLL { constructor(value) { this.head = { value: value, next: null }; this.tail = this.head; this.length = 1; } append(value) { const node = { value: value, prev: null, next: null }; node.next = this.head; node.prev = this.tail; this.tail.next = node; this.tail = node; this.head.prev = node; this.length++; } // Due to being a circular list, currentNode is never equal to null, so while loop never ends. This ends up //timing out. // printList() { // const array = []; // let currentNode = this.head; // while (currentNode !== null) { // array.push(currentNode.value); // currentNode = currentNode.next; // } // console.log(array); // } printList() { const array = []; let currentNode = this.head; let index = 0; while (index < this.length) { array.push(currentNode.value); currentNode = currentNode.next; index++; } console.log(array); } }
JavaScript
class IotHubDefinitionDescription { /** * Create a IotHubDefinitionDescription. * @member {boolean} [applyAllocationPolicy] flag for applying * allocationPolicy or not for a given iot hub. * @member {number} [allocationWeight] weight to apply for a given iot h. * @member {string} [name] Host name of the IoT hub. * @member {string} connectionString Connection string og the IoT hub. * @member {string} location ARM region of the IoT hub. */ constructor() { } /** * Defines the metadata of IotHubDefinitionDescription * * @returns {object} metadata of IotHubDefinitionDescription * */ mapper() { return { required: false, serializedName: 'IotHubDefinitionDescription', type: { name: 'Composite', className: 'IotHubDefinitionDescription', modelProperties: { applyAllocationPolicy: { required: false, serializedName: 'applyAllocationPolicy', type: { name: 'Boolean' } }, allocationWeight: { required: false, serializedName: 'allocationWeight', type: { name: 'Number' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, connectionString: { required: true, serializedName: 'connectionString', type: { name: 'String' } }, location: { required: true, serializedName: 'location', type: { name: 'String' } } } } }; } }
JavaScript
class TypingOverview { /** * @constructor * @param {Element} elm_prev - Block containing characters already typed * @param {Element} elm_curr - Block containing the entire text that's still need to be typed * @param {Element} elm_error - Block containing : either empty if last character typed is correct, * or current letter to type if last character typed is incorrect */ constructor(elm_prev, elm_curr, elm_error) { this.elm_prev = elm_prev; this.elm_curr = elm_curr; this.elm_error = elm_error; } /** * Returns innerText of current-block * @returns {string} */ getCurrentText() { return this.elm_curr.innerText; } /** * Set Text of current-block * @returns {void} * @param {string} text */ setCurrentText(text) { this.elm_curr.innerText = text; } /** * Set HTML of current-block. Delete last character if it's a space * @returns {void} * @param {string} text */ setCurrentHTML(text) { this.elm_curr.innerHTML = text; // Last character space prevention. if ( this.getCurrentText().substring(text.length-1, text.length) === " " ) { this.setCurrentText(text.substring(0, text.length - 1)); } } /** * Specifies move of current letter supposed to be typed, in every cases (is the key pressed correct ? And is this the first try or did we already failed > in this last case elm-error isn't empty) * @returns {void} * @param {boolean} success - true: key pressed correct - false: key pressed incorrect */ manageChar(success) { // Is keyPressed correct ? if (success) { // Is there something in the transitionnal-error text block ? this.elm_error.innerText === '' ? this.moveChar(this.elm_curr, this.elm_prev) : this.moveChar(this.elm_error, this.elm_prev); } else { this.elm_error.innerText === '' ? this.moveChar(this.elm_curr, this.elm_error) : ''; } } /** * Controls move of current letter supposed to be typed : from a specified block to another. * @private * @returns {void} * @param {Element} elm_from * @param {Element} elm_to */ moveChar(elm_from, elm_to) { const text = elm_from.innerText; let char = text.substring(0, 1); // Making errors on 'space character' visibles if (char === " " && elm_to === this.elm_error) { char = "␣"; } if (elm_to === this.elm_prev) { char = this.colorizeChar(char, elm_from); } elm_to.innerHTML = elm_to.innerHTML + char; elm_from.innerHTML = text.substring(1, text.length); } /** * In the case of letter insertion in prev-block (test needed), letter is colorized with correct or incorrect color (<span> with class tag added) * @private * @param {string} char * @param {Element} elm_from * @returns {string} */ colorizeChar(char, elm_from) { const class_name = elm_from === this.elm_curr ? "color-success" : "color-error"; return `<span class='${class_name}'>${char}</span>`; } }
JavaScript
class WatchedTitle { constructor(title, date, isSeries) { this.title = title; this.date = date; this.isSeries = isSeries; this.count = 1; } }
JavaScript
class Meetup extends Event { constructor (cfg = {}) { super(cfg) this.description = 'A meetup.com event.' this.url = null /** * @cfg {String|Array} [organizer] * The organizer of a meetup. */ this.organizer = cfg.organizer || [] } set url (value) { if (value.startsWith('http')) { this.url = value } else { throw new Error('Invalid URL') } } /** * Open the * @param {string} URI * The URL of the meetup. */ display (uri = null) { document.location = uri || this.url } }
JavaScript
class AllGenies extends React.Component { constructor(props) { super(props); } componentDidMount() { this.props.getGenies(); } render() { // Assigned a new variable, genies, to this.props.genies. const genies = this.props.genies; return ( <div className="container"> <div className="d-sm-flex justify-content-between align-items-center"> <h2>All Available Genies</h2> </div> <div /> <div className="container"> <div className="row row-cols-1 row-cols-md-5 g-4"> {genies.length === 0 ? ( <div className="card"> <div className="card-body"> <h6>**There are no genies available**</h6> </div> </div> ) : ( genies.map((genie) => ( <div key={genie.id} className="col"> <img src={genie.imageURL} className="img-fluid rounded-start card-img-top" /> <div className="card bg-warning border-dark text-light"> <div className="card-body text-center"> <div className="h1"> <Link to={`/genies/${genie.id}`}> <h4 className="card-title">{genie.name}</h4> </Link> <h6 className="card-text"> <span className="text-primary">Description: </span> {genie.description} </h6> <h6 className="card-text"> <span className="text-primary">Price: </span> {genie.price / 100} </h6> <h6 className="card-text"> <span className="text-primary">Wish Quantity: </span> {genie.wishQty} <div /> </h6> </div> </div> </div> </div> )) )} </div> </div> <div className="text-center">End of List</div> </div> ); } }
JavaScript
class Engine { /** * * @param file {String} File path in local file system * @param language {String} For which language to generate (es, ts) * @param client {String} Which http client backend will be used (axios, fetch, superagent) * @param destination {String} Destination folder, where will be put generated source code * @param parameters {Boolean} Render parameters definition for each path ({operationId}_PARAMETERS.js) * @param urls {Boolean} Render url definition for each path ({operationId}_RAW_URL.js) * @param linter {Object|Boolean} Linter configuration, leave them false to not perform linting */ constructor ({ file, language = 'es', client = 'axios', destination = '', parameters = false, urls = false, linter = false, uselessPayload = false }) { this._file = file this._language = language this._client = client this._destination = destination this._servers = null this._paths = null this._withParameters = parameters this._withUrls = urls this._uselessPayload = uselessPayload this._supported = '^3.*.*' this._linter = linter ? new Linter(linter) : linter } get file () { return this._file } set file (value) { this._file = value } get language () { return this._language } get uselessPayload () { return this._uselessPayload } set language (value) { this._language = value } get client () { return this._client } set client (value) { this._client = value } get destination () { return this._destination } set destination (value) { this._destination = value } get withParameters () { return this._withParameters } set withParameters (value) { this._withParameters = Boolean(value) } get withUrls () { return this._withUrls } set withUrls (value) { this._withUrls = Boolean(value) } get defaultServerAddress () { return _.get(this._servers, [0, 'url'], '') } async generate () { log.info('Start generate') return new Promise((resolve, reject) => { return this .loadAndConvert() .then((json) => { this._json = json this.renderIndexFile() this.renderRequestFile() if (!Array.isArray(this._paths)) { return Promise.reject(new Error('Missing paths in documentation')) } const paths = this._paths.map(path => path.renderToFile(this)) return Promise.all(paths) .then((results) => { resolve(true) }) .catch(e => { console.error(e) reject(e) }) }) }) } get imports () { if (!Array.isArray(this._paths)) { console.error('Missing paths in documentation') return [] } return this._paths.reduce((map, path) => map.concat(path.fullImportStatement), []) } get methods () { if (!Array.isArray(this._paths)) { console.error('Missing paths in documentation') return [] } return this._paths.map(path => path.operationId) } renderIndexFile () { const template = path.join(__dirname, this.language, this.client, 'index.twig') const file = path.join(this.destination, 'index.js') return renderTemplateToFile(template, file, this) } renderRequestFile () { const template = path.join(__dirname, this.language, this.client, 'request.twig') const file = path.join(this.destination, 'request.js') return renderTemplateToFile(template, file, this) } loadAndConvert () { return new Promise((resolve, reject) => { try { const json = yaml.load(fs.readFileSync(this._file, 'utf8')) const { openapi = '0.0.0'} = json if (semver.satisfies(openapi, this._supported)) { log.info('JSON', json) this.extractInfo(json) this.extractPaths(json) this.extractServers(json) resolve(json) } else { reject(new Error(`Unsatisfied open api version, supported ${this._supported}`)) } } catch (e) { reject(e) } }) } extractInfo (json) { const { info = {} } = json if (Object.keys(info).length > 0) { this._info = info } } extractServers (json) { const { servers = [] } = json if (servers.length > 0) { this._servers = servers } } extractPaths (json) { const { paths = {} } = json if (Object.keys(paths).length > 0) { this._paths = [] Object.keys(paths).forEach(path => { const methods = paths[path] Object.keys(methods).forEach(method1 => { const object = ApiPath.extract(methods[method1], method1, path, json) this._paths.push(object) }) }) } } }
JavaScript
class CMultiColumn extends CColumn { /** * Create column object. Should not be called directly. * * @method constructor * @param {Object} table Parent CTable object. * @param {Object} record Parent CRecord object. * @param {Object} options Column options: * @param {int} [options.width] Column width in percents. * @param {List} [options.columns] List of record field. * @param {List} [options.labels] List of labels. * @param {Boolean} [options.no_search] Disable search field by this column. * @param {List} [options.search_columns] List of columns used for search (all columns if empty). * @param {int} [options.labels_width] Label width. * @param {Object} [options.columns_options] For select-like columns - options list * @param {Object} [options.columns_endpoints] For select-like columns - remote options list url * @param {Object} [options.columns_params] For select-like columns - remote options list params */ constructor(table, record, options = {}) { super(table, record, options); if (! ('columns_options' in this.options)){ this.options.columns_options = {}; } if (! ('columns_endpoints' in this.options)){ this.options.columns_endpoints = {}; } if (! ('columns_params' in this.options)){ this.options.columns_params = {}; } for (var i in this.options.columns_endpoints){ this.table.load_from_options_cache(this.options.columns_endpoints[i], this.options.columns_params[i], $.proxy(this.fill_options, this, i)); } } fill_options(colname, options){ this.options.columns_options[colname] = options; if (this.cell_elem != null){ this.build_cell(this.cell_elem); } } /** * Build cell part of column. * @method build_cell * @param {JQueryNode} elem Container element. * */ build_cell(elem){ super.build_cell(elem); this.cell_elem = elem; var dt_style = ''; if(typeof(this.options.labels_width) != "undefined"){ dt_style = ' style="width:'+this.options.labels_width+';" '; } var text = ''; for (var i in this.options.columns){ var cell_value = this.record.record_field(this.options.columns[i]); if(this.options.columns[i] in this.options.columns_options){ for (var k in this.options.columns_options[this.options.columns[i]]){ if (this.options.columns_options[this.options.columns[i]][k][0] == cell_value) cell_value = this.options.columns_options[this.options.columns[i]][k][1]; } } else { if(this.options.columns[i] in this.options.columns_endpoints){ cell_value = ''; } } text += '<dt'+dt_style+'> ' + this.options.labels[i] + ': </dt><dd>' + cell_value + '</dd>'; } elem.html('<dl>' + text + '</dl>'); } /** * Build options part of column with search input. * @method build_options * @param {JQueryNode} elem Container element. * */ build_options(elem){ this.options_elem = elem; if(typeof(this.options.no_search) == "undefined" || !this.options.no_search){ this.search_field = $('<input class="input" type="search"></input>').appendTo(this.options_elem); this.search_field.change($.proxy(this.set_search_filter, this)); } } /** * Search input change handler. * @method set_search_filter * @private * */ set_search_filter(){ if(typeof(this.options.search_columns) == "undefined"){ this.table.set_search(this.options.columns.join('+'), this.search_field.val()); } else { this.table.set_search(this.options.search_columns.join('+'), this.search_field.val()); } this.table.select(); } /** * Column is visible?. * @method visible_column * @return {Boolean} Always true * */ visible_column(){ return true; } /** * Editor is visible?. * @method visible_editor * @return {Boolean} Always false * */ visible_editor(){ return false; } }
JavaScript
class Options extends NodeMixin(Array) { static get Properties() { return { selectedPath: { type: Array, strict: true, }, selectedRoot: null, selectedLeaf: null, }; } constructor(options = [], props = {}) { super(props); for (let i = 0; i < options.length; i++) { let option; if (options[i] instanceof OptionItem) { option = options[i]; } else if (typeof options[i] === 'object') { option = new OptionItem(options[i]); } else { option = new OptionItem({value: options[i]}); } this.push(option); option.addEventListener('selected-changed', this.onOptionItemSelectedChanged); option.addEventListener('selectedPath-changed', this.onOptionItemSelectedPathChanged); option.connect(this); } } option(value) { for (let i = 0; i < this.length; i++) { if (this[i].value === value) return this[i]; } return null; } selectedPathChanged() { if (!this.selectedPath.length) { for (let i = 0; i < this.length; i++) { if (this[i].select === 'pick') { this[i].setSelectedPath(false, []); } } } else { this.setSelectedPath(this.selectedPath); const selected = this.selectedPath[0]; for (let i = 0; i < this.length; i++) { if (this[i].select === 'pick' && this[i].value === selected) { const nextpath = [...this.selectedPath]; nextpath.shift(); this[i].setSelectedPath(true, nextpath); return; } } } } onOptionItemSelectedPathChanged(event) { const target = event.target; if (target.select === 'pick') { if (target.selectedPath.length) { this.setSelectedPath([target.value, ...target.selectedPath]); } } } onOptionItemSelectedChanged(event) { const target = event.target; if (target.select === 'pick') { if (target.selected) { for (let i = 0; i < this.length; i++) { if (this[i].select === 'pick' && this[i] !== target) { this[i].setSelectedPath(false, []); } } this.setSelectedPath([target.value, ...target.selectedPath]); } else { let hasSelected = false; for (let i = 0; i < this.length; i++) { if (this[i].selected) { hasSelected = true; continue; } } if (!hasSelected) this.setSelectedPath([]); } } } setSelectedPath(path = []) { this.setProperties({ selectedPath: path, selectedRoot: path[0],// || '', selectedLeaf: path[path.length - 1],// || '', }); } // TODO: test selectDefault() { for (let i = 0; i < this.length; i++) { if (this[i].select === 'pick') { if (this[i].hasmore) { const selected = this[i].options.selectDefault(); if (selected) return true; } else { this[i].setSelectedPath(true, []); return true; } } } return false; } changed() { this.dispatchEvent('changed'); } }
JavaScript
class OptionItem extends Node { static get Properties() { return { value: undefined, label: '', icon: '', hint: '', action: undefined, select: 'pick', // 'toggle' | 'pick' | 'none' selected: Boolean, selectedPath: { type: Array, strict: true, }, selectedRoot: null, selectedLeaf: null, options: { type: Options, strict: true } }; } get compose() { return { options: {'on-selectedPath-changed': this.onOptionsSelectedPathChanged}, }; } constructor(option) { if (typeof option !== 'object' || option === null) { option = { value: option, label: option, }; } if (option.options) { if (!(option.options instanceof Options)) { option.options = new Options(option.options); } } if (!option.label) { if (typeof option.value === 'object') { option.label = option.value.constructor.name; } else { option.label = String(option.value); } } if (option.select === 'toggle' && option.options && option.options.length) { console.warn('IoGUI OptionItem: options with {select: "toggle"} cannot have suboptions!'); option.options = new Options(); } if (option.select === 'pick' && option.options.length) { option.selected = !!option.options.selectedPath.length; option.selectedPath = [...option.options.selectedPath]; } super(option); if (this.select === 'pick' && this.options.length) { this.setSelectedPath(!!this.options.selectedPath.length, [...this.options.selectedPath]); } } get hasmore() { return !!(this.options.length); } option(value) { return this.options.option(value); } onOptionsSelectedPathChanged() { if (this.select === 'pick') { this.setSelectedPath(!!this.options.selectedPath.length, [...this.options.selectedPath]); } } selectedChanged() { if (this.select === 'pick') { if (!this.selected) { this.options.setSelectedPath([]); this.setSelectedPath(false, []); } } } setSelectedPath(selected, path = []) { this.setProperties({ selected: selected, selectedPath: path , selectedRoot: path[0] || '', selectedLeaf: path[path.length - 1] || '', }); } changed() { this.dispatchEvent('changed'); } }
JavaScript
class Mole extends Component { render() { // this determines which sprite to grab on the sprite sheet var spritePosition = -800 + (constants.SPRITE_SIZE * this.props.molePosition); // adding sprite to button as background var spriteStyling = { background: 'url('+moleSprite+')', backgroundPosition: spritePosition + 'px 0px' } return ( <button className="Mole" style={spriteStyling} onClick={() => this.props.onClick()}> </button> ); } }
JavaScript
class ScratchPad { /** * create a new temporary scratch file, where objects can be temporarily written out * @returns {ScratchPad} * @async */ static async create () { const id = `scratch-pad-${pid}-${seq++}.v8-serializer` const tempPath = join(tmpdir(), id) const fileRef = await fs.open(tempPath, 'wx+') await fs.unlink(tempPath) return new ScratchPad(fileRef, id) } /** * Internal, use ScratchPad.create instead * @param {fs.FileHandle} file - file handle to unlinked temp file we can append and read * @param {string} id - name used to lock resouces */ constructor (fileRef, id) { this.ref = fileRef this.id = id this.length = 0 } /** * Write an object to the ScratchPad, returning an function which returns a promise of the object when run * @param {StructuredCloneable} object * @returns {ReaderCallback} * @async */ async write (object) { const encoded = serialize(object) return await lockWhile(['scratch-file', this.id], async () => { const length = encoded.length const position = this.length this.length += length await this.ref.write(encoded, 0, length, position) const read = async () => { const buffer = Buffer.alloc(length) await lockWhile(['scratch-file', this.id], async () => { await this.ref.read(buffer, 0, length, position) }) return deserialize(buffer) } return read }) } /** * Read function, when called returns a promise which resolves with a structured clone of the original object written to the scratchpad * @callback ReaderFunction * @returns {StructuredCloneable} - deserialised deep copy of object given to write() command that created this reader * @async */ /** * Close the scratch file, freeing it's space from the local disk */ close () { this.ref.close() this.ref = undefined } }
JavaScript
class UniversalViewer extends Polymer.Element { constructor() { super(); this.__viewerCounter = UniversalViewer._counter; return this; } static get NOT_SUPPLIED_BY_USER() { return "Not Supplied By User"; } static get DEFAULT_WIDTH() { return "100%"; } static get DEFAULT_HEIGHT() { return "600px"; } static get is() { return "universal-viewer"; } static get _counter() { UniversalViewer.__counter = (UniversalViewer.__counter || 0) + 1; return UniversalViewer.__counter; } get _viewerCounter() { return this.__viewerCounter.toString(); } static get properties() { return { _viewerCount: String, __srcdoc: String, width: { type: String, value: UniversalViewer.NOT_SUPPLIED_BY_USER // default will be 100% }, height: { type: String, value: UniversalViewer.NOT_SUPPLIED_BY_USER // default will be 600px }, uri: String } } connectedCallback() { super.connectedCallback(); this._viewerCount = this._viewerCounter; // let iframe = this.$['iframe-viewer']; // let iframeDoc = iframe.contentDocument; // iframeDoc.open(); // // iframeDoc.write(html); // iframeDoc.close(); // function constructIFrame() { // // iframe = this.$['iframe-viewer']; // let iframeDoc = iframe.contentDocument ? iframe.contentDocument : (iframe.contentWindow ? iframe.contentWindow.document : iframe.document); // if (!iframeDoc) { // setTimeout(constructIFrame, 500); // } else { // iframeDoc.open(); // iframeDoc.close(); // // let bodyTag = iframeDoc.createElement("body"); // // let bodyDivTag = iframeDoc.createElement("div"); // bodyDivTag.className = "uv"; // bodyDivTag.style.width = "100%"; // bodyDivTag.style.height = "100%"; // bodyDivTag.setAttribute("data-uri", `${this.uri}`); // // let dataUriAttribute = iframeDoc.createAttribute("data-uri"); // // dataUriAttribute.value = `${this.uri}`; // // bodyDivTag.attributes.setNamedItem(dataUriAttribute); // bodyDivTag.setAttribute("overflow", "hidden"); // // let overflowAttribute = iframeDoc.createAttribute("overflow"); // // overflowAttribute.value = "hidden"; // // bodyDivTag.attributes.setNamedItem(overflowAttribute); // bodyDivTag.setAttribute("allowfullscreen", "allowfullscreen"); // // let allowfullscreenAttribute = iframeDoc.createAttribute("allowfullscreen"); // // allowfullscreenAttribute.value = "allowfullscreen"; // // bodyDivTag.attributes.setNamedItem(allowfullscreenAttribute); // // bodyTag.appendChild(bodyDivTag); // // let bodyScriptTag = iframeDoc.createElement("script"); // bodyScriptTag.id = "embedUV"; // bodyScriptTag.type = "application/javascript"; // bodyScriptTag.src = "../lib/uv-2.0.2/lib/embed.js"; // // bodyScriptTag.textContent = "alert('why firefox! WHYHWHWHWYWNYWHWHWY!')"; // // bodyTag.appendChild(bodyScriptTag); // // let htmlTag = iframeDoc.getElementsByTagName("html")[0]; // htmlTag.replaceChild(bodyTag, iframeDoc.getElementsByTagName("body")[0]); // // } // // } // // // // let divId = "container-" + this._viewerCount; // let divContainer = this.shadowRoot.getElementById(divId); // // let iframe = divContainer.ownerDocument.createElement("iframe"); // iframe.id = "iframe-viewer"; // iframe.style.width = "100%"; // iframe.style.height = "100%"; // iframe.style.border = "0"; // iframe.setAttribute("allowfullscreen", "allowfullscreen"); // // let allowfullscreenAttribute = divContainer.ownerDocument.createAttribute("allowfullscreen"); // // allowfullscreenAttribute.value = "allowfullscreen"; // // iframe.attributes.setNamedItem(allowfullscreenAttribute); // iframe.setAttribute("seamless", "seamless"); // // let seamlessAttribute = divContainer.ownerDocument.createAttribute("seamless"); // // seamlessAttribute.value = "seamless"; // // iframe.attributes.setNamedItem(seamlessAttribute); // iframe.setAttribute("src", "../blank.html"); // // if (window.attachEvent) { // iframe.attachEvent('onload', constructIFrame.bind(this, iframe)); // } else if (window.addEventListener) { // iframe.addEventListener('load', constructIFrame.bind(this, iframe), false); // } else { // document.addEventListener('DOMContentReady', constructIFrame.bind(this, iframe), false); // } // // divContainer.appendChild(iframe); // // // // // // iframeDoc.getElementsByTagName("div")[0].parentNode.insertBefore(bodyScriptTag, iframeDoc.getElementsByTagName("div")[0].nextSibling); // // // super.connectedCallback(); // // this._viewerCount = this._viewerCounter; // // let constructIFrame = function(iframe) { // // let iframeDoc = iframe.contentDocument ? iframe.contentDocument : (iframe.contentWindow ? iframe.contentWindow.document : iframe.document); // // if (!iframeDoc) { // // setTimeout(constructIFrame, 500); // // } else { // // let bodyTag = iframeDoc.createElement("body"); // // // // let bodyDivTag = iframeDoc.createElement("div"); // // bodyDivTag.className = "uv"; // // bodyDivTag.style.width = "100%"; // // bodyDivTag.style.height = "100%"; // // let dataUriAttribute = iframeDoc.createAttribute("data-uri"); // // dataUriAttribute.value = `${this.uri}`; // // bodyDivTag.attributes.setNamedItem(dataUriAttribute); // // let overflowAttribute = iframeDoc.createAttribute("overflow"); // // overflowAttribute.value = "hidden"; // // bodyDivTag.attributes.setNamedItem(overflowAttribute); // // let allowfullscreenAttribute = iframeDoc.createAttribute("allowfullscreen"); // // allowfullscreenAttribute.value = "allowfullscreen"; // // bodyDivTag.attributes.setNamedItem(allowfullscreenAttribute); // // // // bodyTag.appendChild(bodyDivTag); // // let htmlTag = iframeDoc.getElementsByTagName("html")[0]; // // htmlTag.replaceChild(bodyTag, iframeDoc.getElementsByTagName("body")[0]); // // // // let bodyScriptTag = iframeDoc.createElement("script"); // // bodyScriptTag.id = "embedUV"; // // bodyScriptTag.type = "application/javascript"; // // iframeDoc.getElementsByTagName("body")[0].appendChild(bodyScriptTag); // // iframeDoc.getElementsByTagName("script")[0].src = "../lib/embed.js"; // // } // // } // // // // let divId = "container-" + this._viewerCount; // // let divContainer = this.shadowRoot.getElementById(divId); // // // // let iframe = divContainer.ownerDocument.createElement("iframe"); // // iframe.id = "iframe-viewer"; // // iframe.style.width = "100%"; // // iframe.style.height = "100%"; // // iframe.style.border = "0"; // // // // if (window.attachEvent) { // // iframe.attachEvent('onload', constructIFrame.bind(this, iframe)); // // } else if (window.addEventListener) { // // iframe.addEventListener('load', constructIFrame.bind(this, iframe), false); // // } else { // // document.addEventListener('DOMContentReady', constructIFrame.bind(this, iframe), false); // // } // // // // divContainer.appendChild(iframe); // // if (this.style.width === "") { if (this.width == UniversalViewer.NOT_SUPPLIED_BY_USER) { this.style.width = UniversalViewer.DEFAULT_WIDTH; } else { this.style.width = this.width; } } /* else { was set via css } */ if (this.style.height === "") { if (this.height == UniversalViewer.NOT_SUPPLIED_BY_USER) { this.style.height = UniversalViewer.DEFAULT_HEIGHT; } else { this.style.height = this.height; } } /* else { was set via css } */ } }
JavaScript
class Connectible extends BasePin { constructor() { super(); this._resolving = false; this._deference_connected = false; this._inbound = []; } /** * * @note it will throw an error if this pin is already locked. * You can read more about this [here](https://connective.dev/docs/pin#subscribing-and-binding). * */ connect(pin) { if (this.locked) throw new PinLockedError(); if (!this._inbound.includes(pin)) this._inbound.push(pin); return this; } /** * * @note Accessing this property locks the pin. * You can read more about this [here](https://connective.dev/docs/pin#subscribing-and-binding). * */ get observable() { if (this.shouldResolve(this._inbound, this._observable)) { if (this._resolving) { if (!this._deferred) { this._deferred = new Subject(); } return this._deferred; } else { this._resolving = true; this._observable = this.resolve(this._inbound); if (this._deferred) { let _pristine = this._observable; this._observable = defer(() => { if (!this._deference_connected) { this.track(_pristine.subscribe(this._deferred)); this._deference_connected = true; } return _pristine; }); } this._resolving = false; } } if (!this._observable) throw new UnresolvedPinObservableError(); return this._observable; } /** * * @note Calling `.clear()` will unlock the pin and disconnect it from * all the pins its connected to (removing their references). There is no guarantee * that the pin will be usable afterwards. * */ clear() { this._inbound.length = 0; this._observable = undefined; this._deference_connected = false; if (this._deferred) { this._deferred.complete(); this._deferred = undefined; } return super.clear(); } /** * * @returns `true` if the pin is locked, `false` if not. * You can read more about this [here](https://connective.dev/docs/pin#subscribing-and-binding). * */ get locked() { return this.isLocked(this._observable); } /** * * @returns `true` if any other pin is connected to this pin, `false` if not. * */ get connected() { return this.isConnected(); } /** * * Override this to determine the value of `.connected` through other means. * */ isConnected() { return this._inbound.length > 0; } }
JavaScript
class eventsWrapper extends events { /** * @constructor * @param {net.Socket} socket Node.JS Socket client */ constructor(socket) { super(); this.socket = socket; this.socket.on("data", (buf) => { const messages = parseSocketMessages(buf.toString()); for (const message of messages) { this.emit(message.title, message.body); } }); this.socket.on("error", console.error); this.on("ping", (dt) => this.send("ping", dt, 0)); } /** * @method send * @desc Send message to socket client * @param {!String} title message title * @param {Object=} body message body * @param {Number=} [timeOut=5000] Send timeout! * @returns {Promise<any>} */ send(title, body = {}, timeOut = 5000) { return new Promise((resolve, reject) => { const data = JSON.stringify({ title, body }); this.socket.write(Buffer.from(`${data}\n`)); // Return if we dont expect a return from MordorClient if (timeOut === 0) { return resolve(); } /** @type {NodeJS.Timer} */ let timeOutRef = null; function handler(data) { clearTimeout(timeOutRef); resolve(data); } timeOutRef = setTimeout(() => { this.removeListener(title, handler); reject(new Error(`Timeout message ${title}`)); }, timeOut); this.addListener(title, handler); return void 0; }); } }
JavaScript
class Container extends React.Component { /** * Construct new RCR component * * @constructor * @param {Object} props */ constructor(props) { super(props); this.state = {}; } // TODO: Add cheking for hot reloading. componentWillUpdate() { // TODO: Make reload only if necessary. if (module.hot) { const ReactComponent = this.constructor; const actions = (new ReactComponent).actions; this.unRegisterReducers({...this.actions, ...this.rootActions}); this.actions = actions; this.registerReducers({...this.actions, ...this.rootActions}); this.mapActions(this.actions, this.rootActions); } } }
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 Provider extends React.Component { /** * For convenience when setting up a component that tracks this * <Provider>'s value in state. * * const { Provider, Consumer } = createContext("default value") * * class MyComponent { * state = { * value: Provider.defaultValue * } * * // ... * * render() { * return <Provider value={this.state.value}/> * } * } */ static defaultValue = defaultValue; static propTypes = { children: PropTypes.node, value: PropTypes.any }; static defaultProps = { value: defaultValue }; static contextTypes = { broadcasts: PropTypes.object }; static childContextTypes = { broadcasts: PropTypes.object.isRequired }; subscribers = []; publish = value => { this.subscribers.forEach(s => s(value)); }; subscribe = subscriber => { this.subscribers.push(subscriber); return () => { this.subscribers = this.subscribers.filter(s => s !== subscriber); }; }; getValue = () => { return this.props.value; }; getChildContext() { return { broadcasts: { ...this.context.broadcasts, [channel]: { subscribe: this.subscribe, getValue: this.getValue } } }; } componentWillReceiveProps(nextProps) { if (this.props.value !== nextProps.value) { this.publish(nextProps.value); } } render() { return this.props.children; } }
JavaScript
class Consumer extends React.Component { static contextTypes = { broadcasts: PropTypes.object }; static propTypes = { children: PropTypes.func, quiet: PropTypes.bool }; static defaultProps = { quiet: false }; broadcast = this.context.broadcasts && this.context.broadcasts[channel]; state = { value: this.broadcast ? this.broadcast.getValue() : defaultValue }; componentDidMount() { if (this.broadcast) { this.unsubscribe = this.broadcast.subscribe(value => { this.setState({ value }); }); } else { warning( this.props.quiet, "<Consumer> was rendered outside the context of its <Provider>" ); } } componentWillUnmount() { if (this.unsubscribe) this.unsubscribe(); } render() { const { children } = this.props; return children ? children(this.state.value) : null; } }
JavaScript
class LeakyReLU extends Layer { /** * Creates a LeakyReLU activation layer * @param {number} attrs.alpha - negative slope coefficient */ constructor(attrs = {}) { super(attrs) this.layerClass = 'LeakyReLU' const { alpha = 0.3 } = attrs this.alpha = alpha // GPU setup if (this.gpu) { this.program = webgl2.compileProgram(require('./LeakyReLU.webgl2.glsl')) } } /** * Layer computational logic * * @param {Tensor} x * @returns {Tensor} */ call(x) { if (this.gpu) { this._call_gpu(x) } else { this._call_cpu(x) } return this.output } /** * CPU call */ _call_cpu(x) { this.output = x relu(this.output, { alpha: this.alpha }) } /** * GPU call */ _call_gpu(x) { if (!x.glTexture) { x.createGLTexture() } if (!this.output) { this.output = new Tensor([], x.glTextureShape) this.output.createGLTexture() if (x.glTextureIsTiled) { this.output.glTextureIsTiled = x.glTextureIsTiled this.output.untiledShape = x.untiledShape } } webgl2.selectProgram(this.program) webgl2.bindOutputTexture(this.output.glTexture, this.output.glTextureShape) const textures = [x.glTexture] const textureTypes = ['2d'] const textureNames = ['x'] webgl2.bindInputTextures(this.program, textures, textureTypes, textureNames) const uniforms = [this.alpha] const uniformTypes = ['float'] const uniformNames = ['alpha'] webgl2.bindUniforms(this.program, uniforms, uniformTypes, uniformNames) webgl2.runProgram() if (this.outbound.length === 0) { this.output.transferFromGLTexture() } } }
JavaScript
class SchemaAggregator { constructor(rootDir) { this.srcSchemaPath = path.resolve(rootDir, "src/schemas"); this.targetSchemaPath = path.resolve(rootDir, "dist/schemas"); } apply(compiler) { compiler.hooks.afterCompile.tap("SchemaAggregator", (compilation) => { $RefParser.bundle(path.resolve(this.srcSchemaPath, "manifest.schema.json")).then((jsonSchema) => { if (!fs.existsSync(this.targetSchemaPath)) { fs.mkdirSync(this.targetSchemaPath, {recursive: true}); } //Remove $schema element. This is a trick to make the json-language-server of vscode invalidate its schema cache. delete jsonSchema["$schema"]; fs.writeFileSync(path.resolve(this.targetSchemaPath, "manifest.schema.json"), JSON.stringify(jsonSchema)); // recursively remove all 'markdownDescription' elements this.processDescriptions(jsonSchema, (obj) => { delete obj["markdownDescription"]; }); const bundledSchema = JSON.stringify(jsonSchema); fs.writeFileSync(path.resolve(this.targetSchemaPath, "manifest.schema.short.json"), bundledSchema); }, (rejected) => { console.error("Cannot load manifest.json schema: " + rejected); } ); }); } processDescriptions(obj, cb) { if (obj instanceof Array) { for (var i in obj) { this.processDescriptions(obj[i], cb); } return; } if (obj instanceof Object) { let description = obj["markdownDescription"]; if (typeof description === "string" || description instanceof String) { cb(obj); } let children = Object.keys(obj); if (children.length > 0) { for (let i = 0; i < children.length; i++) { this.processDescriptions(obj[children[i]], cb); } } } return; } }
JavaScript
class TestChildProcess extends EventEmitter { constructor() { super(); } send(message) { super.emit('message', message); } }
JavaScript
class CalculationUtil { /** * Asynchronously calculates PCA. * @param datasets {Array} All datasets with entries * @returns {Promise} that will resolve with a calculated PCA or null. */ static calculatePcaAsync(datasets) { return WorkerUtil.execByWorker(WorkerTaskNames.CALCULATE_PCA, datasets); } /** * Synchronously calculates PCA. This should be called only by a worker process! * @param datasets {Array} All datasets with entries * @returns {Object} a calculated PCA or null. */ static calculatePcaSync(datasets) { const pcaCalc = new Calculator(); return pcaCalc.calculatePca(datasets); } /** * Asynchronously calculates areas. * @param pca {Object} Calculated PCA * @param eigens {[number]} Selected eigenpairs indexes * @param k {number} Coefficient * @returns {Promise} that will resolve with a calculated PCA or null. */ static calculateAreasAsync(pca, eigens, k) { return WorkerUtil.execByWorker(WorkerTaskNames.CALCULATE_AREAS, {pca, eigens, k}); } /** * Synchronously calculates areas. This should be called only by a worker process! * @param pca {Object} Calculated PCA * @param eigens {[number]} Selected eigenpairs indexes * @param k {number} Coefficient * @returns {Object} a calculated PCA or null. */ static calculateAreasSync({pca, eigens, k}) { const pcaCalc = new Calculator(); return pcaCalc.calculateAreas(pca, eigens, k); } /** * Projects given values to space defined by given base. * @param values {[[number]]} Values that will be projected * @param base {[number]} Space base. * @returns {[[number]]} projected values */ static projectValues(values, base) { const M = new Matrix(values); const U = new Matrix(base); const C = M.mmul(U); return C.to2DArray(); } }
JavaScript
class MatrixUtil { /** * Creates centered matrix from the given matrix. * @param matrix non-centered matrix * @returns {Matrix} */ static center(matrix) { let centerMatrix = new Matrix(matrix); const means = mean(matrix); centerMatrix.subRowVector(means); return centerMatrix; } }
JavaScript
class Ennemy extends AbstractEnnemy { constructor(options) { super({ texture: Loader.getTexture('ennemy_right'), stats: { minAttack: 1, maxAttack: 3, precision: 0.7, life: 8, }, id: options.id, currentTile: options.currentTile, target: options.target, }); this.anchor = { x: 0, y: 0.3 }; this.velocity = Math.random() * (50 - 30) + 30; this.side = options.side; this.direction = 'right'; this.position.x = this.currentTile.x * tileSize; this.position.y = this.currentTile.y * tileSize; this.animCount = 0; } update(elapsed) { switch (this.direction) { case 'top': this.position.y -= this.velocity * elapsed; break; case 'bottom': this.position.y += this.velocity * elapsed; break; case 'right': this.position.x += this.velocity * elapsed; break; default: this.fight(); } this.animate(); if (this.direction === '') return; if (this.position.x > (this.currentTile.x * tileSize + tileSize)) { this.currentTile.x++; this.findDirection(); } if (this.position.y < (this.currentTile.y * tileSize - tileSize)) { this.currentTile.y--; this.findDirection(); } if (this.position.y > (this.currentTile.y * tileSize + tileSize)) { this.currentTile.y++; this.findDirection(); } } animate() { this.scale.x = 1 + Math.sin(this.animCount) * 0.025; this.scale.y = 1 + Math.cos(this.animCount) * 0.05; this.animCount += 0.1; } findDirection() { if (this.direction !== 'bottom' && tileIsWalkable(this.currentTile.x, this.currentTile.y - 1)) { this.direction = 'top'; this.texture = Loader.getTexture('ennemy_back'); return; } if (this.direction !== 'top' && tileIsWalkable(this.currentTile.x, this.currentTile.y + 1)) { this.direction = 'bottom'; this.texture = Loader.getTexture('ennemy_front'); return; } if (tileIsWalkable(this.currentTile.x + 1, this.currentTile.y)) { this.direction = 'right'; this.texture = Loader.getTexture('ennemy_right'); return; } this.direction = ''; this.texture = Loader.getTexture('ennemy_right'); } }
JavaScript
class TableActions extends PureComponent { render () { const { children, disabled, errorMessage, clearError, selected, actions, statuses, clearFilter, applyFilter, onFilterChange, onInputFilterChange, currentFilter, filterValue, filters, page, size, totalPages, changePage, changeSize, create, createPermission, createText, } = this.props; return (<Grid fluid> <Panel className="bg-muted no-radius"> <Panel.Body> <Row> { create && (<Col xs={2}> <AllowedBtn block onClick={create} disabled={disabled} action={createPermission} > <i className="fa fa-plus" aria-hidden="true"> </i> &nbsp;{createText} <Preloader type="ICON" active={disabled}/> </AllowedBtn> </Col>) } <Col xs={ create ? 6 : 8 }> <SearchFilter filters={filters} clear={clearFilter} value={filterValue} disabled={disabled} statuses={statuses} current={currentFilter} applyFilter={applyFilter} onFilterChange={onFilterChange} onInputChange={onInputFilterChange} /> </Col> <Col xs={2}> {!is.array(actions) ? '' : ( <AllowedActionList name="Actions" icon="fa fa-list" disabled={disabled || !selected.length} actions={actions.map(item => ({ ...item, action: () => item.action(selected) }))} /> )} </Col> <Col xs={2} className="text-right"> <strong> Show: </strong>&nbsp; <PageSize value={size} disabled={disabled} onChange={changeSize}/> </Col> </Row> </Panel.Body> </Panel> <Row> <Col xs={10} xsOffset={1}> <Alert active title={'Error: '} message={errorMessage} onChange={clearError} /> </Col> </Row> <Row> <Col xs={12}> { children } </Col> </Row> <Row> <Col xs={12} className="text-center"> <Pagination page={page} total={totalPages} disabled={disabled} onChange={changePage} /> </Col> </Row> </Grid>); } componentDidMount () { this.props.init(); } componentWillUnmount () { this.props.clear(); } }
JavaScript
class App { constructor() { this.startApp(); } startApp() { Navigation.startSingleScreenApp({ screen: { screen: 'example.DiscoverScreen', title: 'Discover', }, }); } }
JavaScript
class MultiLogger { constructor(...loggers) { this._loggers = loggers; } info(msg) { for (const logger of this._loggers) { logger.info(msg); } } warn(msg) { for (const logger of this._loggers) { logger.warn(msg); } } error(msg) { for (const logger of this._loggers) { logger.error(msg); } } debug(debugFunction) { let message; const memoized = typeof debugFunction === 'string' ? debugFunction : () => { if (!message) { message = debugFunction(); } return message; }; for (const logger of this._loggers) { logger.debug(memoized); } } setLogLevel(level) { for (const logger of this._loggers) { logger.setLogLevel(level); } } getLogLevel() { for (const logger of this._loggers) { return logger.getLogLevel(); } return LogLevel_1.default.OFF; } }
JavaScript
class Ingredient { /** @type {String} */ description; /** @type {Number} */ weight; /** @type {String} */ type; /** * @param {String} [description=''] A description of this ingredient. * @param {Number} [weight=0] The weight of this ingredient, unitless. * @throws {Error} * * @returns {Ingredient} */ constructor(description = '', weight = 0){ if(this.constructor === Ingredient){ throw new Error('Ingredient is an abstract class and must be extended'); } this.description = description; this.weight = weight; } /** * Responsible for deriving/returning a tangible value for this object. * * @implements ValueInterface#valueOf * @see #getDescription * @see #getWeight * @see #getType * * @return {{type: String, data: {description: String, weight: Number}}} */ valueOf(){ const type = this.getType(); const description = this.getDescription(); const weight = this.getWeight(); return ({ type, data: { description, weight } }); } /** * Responsible for getting the overall weight of this ingredient. * * @return {Number} The weight, unitless. */ getWeight(){ return this.weight; } /** * Responsible for setting the weight of this ingredient. * * @param {Number} w The new weight value. * @throws {TypeError} * @see #getWeight * * @returns {Number} */ setWeight(w){ if(!Number.isFinite(w)) throw new TypeError('weight should be a finite value'); this.weight = w; return this.getWeight(); } /** * Responsible for getting the type of this ingredient. * * @see Lexicon * @throws {TypeError} * * @return {String} A word from the the lexicon used in child class definition. */ getType(){ if(typeof this.type != 'string'){ // This type-check is made here because a child instance must define this property throw new TypeError('Ingredient->type should be a string'); } return this.type; } /** * Responsible for getting the description of this ingredient. * * @return {String} */ getDescription(){ return this.description; } /** * Responsible for setting the description of this ingredient. * * @param {String} desc Any descriptive text. * @see #getDescription * @throws {TypeError} * * @return {String} */ setDescription(desc){ if(typeof desc != 'string') throw new TypeError('desc should be a string'); this.description = desc; return this.getDescription(); } /** * Responsible for determining whether a value is an instance of Ingredient. * @static * * @param {*} value Any value to test. * * @return {Boolean} */ static isIngredient(value){ return ( value instanceof Ingredient || (value && value.prototype && value.prototype instanceof Ingredient) ); } }
JavaScript
class jfAjaxRequestOptions extends jfAjaxRequestBase { /** * @override */ method = 'OPTIONS'; }
JavaScript
class FileToolbar extends React.Component { state = { isDeleteFileDialogShown: false, isCreateFileDialogShown: false, isCreateDirectoryDialogShown : false, isMoveDialogShown : false } fetchFiles = () => this.props.fetchFiles() showDeleteFileDialog = () => this.setState({ isDeleteFileDialogShown: true }) hideDeleteFileDialog = () => this.setState({ isDeleteFileDialogShown: false }) showCreateFileDialog = () => this.setState({ isCreateFileDialogShown: true }) hideCreateFileDialog = () => this.setState({ isCreateFileDialogShown: false }) showCreateDirectoryDialog = () => this.setState({ isCreateDirectoryDialogShown: true }) hideCreateDirectoryDialog = () => this.setState({ isCreateDirectoryDialogShown: false }) showMoveDialog = () => this.setState({ isMoveDialogShown: true }) hideMoveDialog = () => this.setState({ isMoveDialogShown: false }) render() { const { loading, selection } = this.props; const tooltipOptions = { showDelay: 500, position: "top" } return ( <div className="this"> <style jsx>{` .this :global(.p-toolbar) { border: 0; border-radius: 0; background-color: #eee; border-bottom: 1px solid #ddd; } .this :global(.p-toolbar-group-left) :global(.p-button) { margin-right: 0.25rem; } `}</style> <Toolbar> <div className="p-toolbar-group-left"> <Button disabled={loading} tooltip="New file" icon="pi pi-file" tooltipOptions={tooltipOptions} onClick={this.showCreateFileDialog}/> <Button disabled={loading} tooltip="New directory" icon="pi pi-folder-open" tooltipOptions={tooltipOptions} onClick={this.showCreateDirectoryDialog}/> <Button disabled={loading || !selection} tooltip="Move/Rename file or directory" icon="pi pi-pencil" tooltipOptions={tooltipOptions} onClick={this.showMoveDialog}/> <Button disabled={loading || !selection} tooltip="Delete file or directory" icon="pi pi-trash" tooltipOptions={tooltipOptions} onClick={this.showDeleteFileDialog}/> </div> <div className="p-toolbar-group-right"> <Button disabled={loading} onClick={this.fetchFiles} tooltip="Reload" icon={"pi pi-refresh" + (loading ? " pi-spin" : "")} tooltipOptions={tooltipOptions} /> </div> </Toolbar> <DeleteDialog visible={this.state.isDeleteFileDialogShown} onHide={this.hideDeleteFileDialog} /> <CreateDialog directoryMode={false} visible={this.state.isCreateFileDialogShown} onHide={this.hideCreateFileDialog} /> <CreateDialog directoryMode={true} visible={this.state.isCreateDirectoryDialogShown} onHide={this.hideCreateDirectoryDialog} /> <MoveDialog visible={this.state.isMoveDialogShown} onHide={this.hideMoveDialog} /> </div> ) } }
JavaScript
class DataStatistics { /** * Create a DataStatistics. * @member {number} [totalData] The total bytes of data to be processed, as * part of the job. * @member {number} [processedData] The number of bytes of data processed * till now, as part of the job. * @member {number} [cloudData] The number of bytes of data written to cloud, * as part of the job. * @member {number} [throughput] The average throughput of data * processed(bytes/sec), as part of the job. */ constructor() { } /** * Defines the metadata of DataStatistics * * @returns {object} metadata of DataStatistics * */ mapper() { return { required: false, serializedName: 'DataStatistics', type: { name: 'Composite', className: 'DataStatistics', modelProperties: { totalData: { required: false, serializedName: 'totalData', type: { name: 'Number' } }, processedData: { required: false, serializedName: 'processedData', type: { name: 'Number' } }, cloudData: { required: false, serializedName: 'cloudData', type: { name: 'Number' } }, throughput: { required: false, serializedName: 'throughput', type: { name: 'Number' } } } } }; } }
JavaScript
class DepthCalculator { calculateDepth(array, cnt=1) { var result = cnt; for(var i = 0; i < array.length; ++i) { if (Array.isArray(array[i])) { var subArray = this.calculateDepth(array[i], cnt + 1); if (subArray > result) { result = subArray; } } } return result; } }
JavaScript
class Query { /** Construct a query from an array of cube objects. * * Should be considered a private constructor - use from instead to create a query. * * @param {Cube[]} cubes - An array of cubes. */ constructor(cubes = []) { this.union = cubes; } /** A set of constraints. * * An object with properties names that represent field names on which a constraint is applied, and * property values represent a constraint. The constraint may be a simple comparable value, a Range * object, or an array with a maximum of two elements representing the lower and upper bounds of a * constraint. * * @typedef {Object<string,Range|Comparable[]|Comparable>} Query~ConstraintObject */ /** Create a query from an constraint object * * The constraint object can have any number of properties. In the following example, the resulting * query applies all the following constraints: w >= 3, x == 3, y >= 3, y < 7, z < 7 * @example 1 * Query.from({ w: [3,], x : 3, y : [3,7], z: [,7]}) * * @param {Query~ConstraintObject} obj - A constraint object. * @returns a Query */ static from(obj) { return new Query( [ new Cube(obj) ] ); } static isQuery(obj) { return obj instanceof Query; } /** Get the default query formatter * @returns {QueryFormatter} the default query formatter */ static get DEFAULT_FORMAT() { function printDimension(context,name) { if (name === null) return '$self'; if (!context || !context.dimension) return name; return printDimension(context.context, context.dimension) + "." + name; } const printValue = value => typeof value === 'string' ? '"' + value + '"' : value; return { andExpr(...ands) { return ands.join(' and ') }, orExpr(...ors) { return "(" + ors.join(' or ') + ")"}, operExpr(dimension, operator, value, context) { // null dimension implies that we are in a 'has' clause where the dimension is attached to the // outer 'has' operator if (operator === 'match') return value; if (operator === 'has') return printDimension(context, dimension) + " has(" + value + ")" //if (dimension === null) return '$self' + operator + printValue(value) return printDimension(context,dimension) + operator + printValue(value) } } } /** Delete any redundant critera from the query */ optimize() { for (let i = 0; i < this.union.length; i++) for (let j = 0; j < this.union.length; j++) if (this.union[i].contains(this.union[j])) { delete this.union[j]; } } /** * @typedef {Object} Query~FactorResult * @property {Query} factored - the part of the query from which a factor has been removed * @property {Query} remainder - the part of the query from which a factor could not be removed */ /** Attempt to simplify a query by removing a common factor from the canonical form. * * Given something like: * ``` * let query = Query * .from({x: 2, y : [3,4], z : 8}) * .or({x:2, y: [,4], z: 7}) * .or({x:3, y: [3,], z: 7}); * * let { factored, remainder } = query.factor({ x: 2}); * ``` * factored should equal `Query.from({y : [3,4], z : 8}).or({y: [,4], z: 7})` and * remainder should equal `Query.from({x:3, y: [3,], z: 7})` * * @param {ConstraintObject} constraint - object to factor out of query * @return {Query~FactorResult} */ factor(common) { let result = []; let remainder = []; for (let cube of this.union) { try { let factored_cube = cube.removeConstraints(common); result.push(factored_cube); } catch (err) { remainder.push(cube); } } if (result.length === 0) { return { remainder: this }; } else { let factored = new Query(result); if (remainder.length === 0) return { factored } else { return { factored, remainder: new Query(remainder) } } } } /** Find the factor that is common to the largest number of sub-expressions in canonical form. * * @returns {Object} A constraint object containing the common factor, or undefined. */ findFactor() { let constraints = []; for (let cube of this.union) { for (let dimension in cube) { let match = false; for ( let bucket of constraints) { if (bucket.dimension === dimension && bucket.range.equals(cube[dimension])) { bucket.count++; match = true; } } if (!match) constraints.push({ dimension, count: 1, range: cube[dimension] }); } } let bucket = constraints .filter(a=>a.count > 1) .sort((a,b) => (a.count > b.count) ? -1 : ((b.count > a.count) ? 1 : 0)) .shift(); return bucket === undefined ? undefined : { [bucket.dimension] : bucket.range }; } /** Convert a query to a an expression. * * @param {QueryFormatter} [formatter=Query~DEFAULT_FORMATTER] - Generates expressions from element of a query * @param {Context} [context] - context information * @returns {Expression} expression - result expression. Typically a string but can be any type. */ toExpression(formatter=Query.DEFAULT_FORMAT, context) { if (this.union.length === 1) { return this.union[0].toExpression(formatter,context); } if (this.union.length > 1) { let factor = this.findFactor(); if (factor) { let dimension = Object.keys(factor).shift(); let range = factor[dimension]; let { factored, remainder } = this.factor(factor); if (factored && remainder) return formatter.orExpr( formatter.andExpr( range.toExpression(dimension, formatter, context), factored.toExpression(formatter, context) ), remainder.toExpression(formatter, context) ); if (factored) return formatter.andExpr( range.toExpression(dimension, formatter, context), factored.toExpression(formatter, context) ); } else { return formatter.orExpr( ...this.union.map( cube => cube.toExpression(formatter, context) ) ); } } } /** Create a new query that will return results in this query or some cube. * @private * @param {Cube} other_cube - cube of additional results * @returns {Query} a new compound query. */ _orCube(other_cube) { let result = []; let match = false; for (let cube of this.union) { if (cube.contains(other_cube)) { match = true; result.push(cube); } else if (other_cube.contains(cube)) { match = true; result.push(other_cube); } else { result.push(cube); } } if (!match) result.push(other_cube); return new Query(result); } /** Create a new query that will return the union of results in this query with some other constraint. * * @param {Query~ConstraintObject} other_constraint * @returns {Query} a new compound query. */ orConstraint(other_constraint) { return this._orCube(new Cube(other_constraint)); } /** Create a new query that will return the union of results in this query and with some other query. * * @param {Query} other_query - the other query * @returns {Query} a new compound query that is the union of result sets from both queries */ orQuery(other_query) { let result = this; for (let cube of other_query.union) { result = result._orCube(cube); } return result; } /** Create a new query that will return the union of results in this query and with some other query or constraint. * * @param {Query|Query~ConstraintObject} obj - the other query or constraint * @returns {Query} a new compound query that is the union of result sets */ or(obj) { if (obj instanceof Query) return this.orQuery(obj); if (obj instanceof Cube) return this._orCube(obj); return this.orConstraint(obj); } /** Create a new query that will return results that are in this query and in some cube. * @private * @param {Cube} other_cube - cube of additional results * @returns {Query} a new compound query. */ _andCube(other_cube) { let result = []; for (let cube of this.union) { let intersection = cube.intersect(other_cube); if (intersection) result.push(intersection); } return new Query(result); } /** Create a new query that will return results in this query that also comply with some other constraint. * * @param {Query~ConstraintObject} other_constraint * @returns {Query} a new compound query. */ andConstraint(constraint) { return this._andCube(new Cube(constraint)); } /** Create a new query that will return the intersection of results in this query and some other query. * * @param {Query} other_query - the other query * @returns {Query} a new compound query that is the intersection of result sets from both queries */ andQuery(other_query) { let result = other_query; for (let cube of this.union) { result = result._andCube(cube); } return result; } /** Create a new query that will return the union of results in this query and with some other query or constraint. * * @param {Query|Query~ConstraintObject} obj - the other query or constraint * @returns {Query} a new compound query that is the union of result sets */ and(obj) { if (obj instanceof Query) return this.andQuery(obj); if (obj instanceof Cube) return this._andCube(obj); return this.andConstraint(obj); } /** Establish if this results of this query would be a superset of the given query. * * @param {Query} other_query - the other query * @returns true if other query is a subset of this one, false if it isn't, null if containment is indeterminate */ containsQuery(other_query) { for (let cube of other_query.union) { let cube_contained = this._containsCube(cube); if (!cube_contained) return cube_contained; } return true; } /** Establish if this results of this query would be a superset of the given cube. * * @private * @param {Cube} cube - the cube * @returns true if cube is a subset of this one, false if it isn't, null if containment is indeterminate */ _containsCube(cube) { for (let c of this.union) { let contains_cube = c.contains(cube); if (contains_cube || contains_cube === null) return contains_cube; } return false; } /** Establish if a specific data item should be in the results of this query * * Very similar to `contains`. For an 'item' with simple properties, the result should be identical. * However an object provided to `contains` is assumed to be a constraint, so properties with array/object * values are processed as ranges. An item provided to 'containsItem' is an individual data item to test, * so array and object properties are not processed as ranges. * * @param item to test * @returns true, false or null */ containsItem(item) { for (let c of this.union) { let contains_item = c.containsItem(item); if (contains_item || contains_item === null) return contains_item; } return false; } /** Establish if this results of this query would be a superset of the given constraint. * * @param {Query~ConstraintObject} constraint - the constraint * @returns true if constraint is a subset of this query, false if it isn't, null if containment is indeterminate */ containsConstraint(constraint) { return this._containsCube(new Cube(constraint)); } /** Establish if this results of this query would be a superset of the given constraint or query. * * Containment may be indeterminate one or more of the queries/constraints involved is parametrized and containment * cannot be determined until the parameter values are known. However, the library works quite hard to identify * cases where containment can be determined even if the query is parametrized. For example: * ``` * Query.from({ height: [$.param1, 12]}).contains(Query.from{ height[13, $.param2]}) * ``` * will return false since the two ranges can never overlap even though they are parametrized. * * @param {Query~ConstraintObject|Query} obj - the constraint or query * @returns true if obj is a subset of this query, false if it isn't, null if containment is indeterminate */ contains(obj) { if (obj instanceof Query) return this.containsQuery(obj); if (obj instanceof Cube) return this._containsCube(obj); return this.containsConstraint(obj); } /** Establish if this result of this query is the same as the given query. * * @param {Query} other_query - the other query * @returns true if other query is a subset of this one. */ equalsQuery(other_query) { let unmatched = Array.from(other_query.union); // Complicated by the fact that this.union and other_query.union may not be in same order for (let constraint of this.union) { let index = unmatched.findIndex(item => constraint.equals(item)); if (index < 0) return false; delete unmatched[index]; } return unmatched.reduce(a=>a+1,0) === 0; // Array.length not change by delete } /** Establish if this result of this query is the same as the given cube. * * @private * @param {Cube} cube - cube to compare * @returns true if results of this query would be the same as the notional results for the cube. */ _equalsCube(cube) { if (this.union.length != 1) return false; return this.union[0].equals(cube); } /** Establish if this results of this query would be the same as for a query created from the given constraint. * * @param {Query~ConstraintObject} constraint - the constraint * @returns true if constraint is the same as this query. */ equalsConstraint(other_constraint) { return _equalsCube(new Cube(other_constraint)); } /** Establish if this results of this query would be a superset of the given constraint or query. * * @param {Query~ConstraintObject|Query} obj - the constraint or query * @returns true if obj is a subset of this query. */ equals(obj) { if (obj instanceof Query) return this.equalsQuery(obj); if (obj instanceof Cube) return this._equalsCube(obj); return this.equalsConstraint(obj); } /** Bind a set of paramters to a query. * * Property values from the parameters object are used to fill in values for any parameters that * this query was created. So: * ``` * Query * .from({ height : [$.floor, $.ceiling]}) * .bind({ floor:12, ceiling: 16}) * .toExpression(); * ``` * will return something like `height >= 12 and height < 16`. * * @param {Object} parameter values * @returns {Query} new query, with parameter values set. */ bind(parameters) { let cubes = Stream .from(this.union) .map(cube => cube.bind(parameters)) .filter(cube => cube !== null) .toArray(); return cubes.length > 0 ? new Query(cubes) : null; } /** Convenience property for filtering * * Given a query, query.predicate is equal to item=>this.contains(item); * @ returns {Function} a function that returns true if its parameter is matched by this query. */ get predicate() { return item => this.containsItem(item); } }
JavaScript
class RdbCMSAPostsCommonActions { /** * Class constructor. */ constructor(options) { if (typeof(options) === 'undefined') { options = {}; } if ( !RdbaCommon.isset(() => options.formIDSelector) || (RdbaCommon.isset(() => options.formIDSelector) && _.isEmpty(options.formIDSelector)) ) { options.formIDSelector = '#posts-add-form' } this.formIDSelector = options.formIDSelector; if ( !RdbaCommon.isset(() => options.tTypeForCategory) || (RdbaCommon.isset(() => options.tTypeForCategory) && _.isEmpty(options.tTypeForCategory)) ) { options.tTypeForCategory = 'category'; } this.tTypeForCategory = options.tTypeForCategory; if ( !RdbaCommon.isset(() => options.tTypeForTag) || (RdbaCommon.isset(() => options.tTypeForTag) && _.isEmpty(options.tTypeForTag)) ) { options.tTypeForTag = 'tag'; } this.tTypeForTag = options.tTypeForTag; if ( !RdbaCommon.isset(() => options.editingObject) ) { if (typeof(RdbCMSAPostsAddObject) !== 'undefined') { options.editingObject = RdbCMSAPostsAddObject; } else if (typeof(RdbCMSAPostsEditObject) !== 'undefined') { options.editingObject = RdbCMSAPostsEditObject; } } this.editingObject = options.editingObject; this.editControllerClass; this.postCommonEditRevision; this.aceEditor; this.tagify; this.tinyMce; }// constructor /** * Activate content editor. * * @link https://www.tiny.cloud/docs/configure/editor-appearance/#font_formats TinyMCE default fonts. * @link https://www.tiny.cloud/docs/plugins/help/#help_tabs TinyMCE default help tabs. * @link https://www.tiny.cloud/docs/configure/editor-appearance/#examplethetinymcedefaultmenuitems TinyMCE default menu items. * @link https://www.tiny.cloud/docs/general-configuration-guide/basic-setup/#defaulttoolbarcontrols TinyMCE default toolbar. * @link https://www.tiny.cloud/docs/mobile/ Mobile settings. * @link https://www.tiny.cloud/docs/plugins/codesample/#codesample_languages Code sample languages. * @link https://prismjs.com/#supported-languages Prism supported languages. * @param {string} editorSelector The content editor selector. * @returns {undefined} */ activateContentEditor(editorSelector = '#revision_body_value') { let editingObject = this.editingObject; let tinyMceDefaultConfig = { 'selector': editorSelector, //'content_css': RdbCMSAPostsIndexObject.publicCssBaseUrl + '/Controllers/Admin/FinancialTemplates/variable-plugin.css', 'convert_urls': false, 'height': 400, 'menu': { file: {title: 'Files', items: 'newdocument restoredraft | preview | print '}, edit: {title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'}, view: {title: 'View', items: 'code | visualaid visualchars visualblocks | preview fullscreen'}, insert: {title: 'Insert', items: 'image link media rdbcmsafilebrowser template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'}, format: {title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | removeformat'}, tools: {title: 'Tools', items: 'code wordcount'}, table: {title: 'Table', items: 'inserttable | cell row column | tableprops deletetable'}, help: {title: 'Help', items: 'help'} }, 'mobile': { 'menubar': true }, 'plugins': 'advlist anchor autosave charmap code codesample emoticons fullscreen help hr image insertdatetime link lists media nonbreaking pagebreak paste preview searchreplace table toc visualblocks visualchars wordcount', 'rdbcmsaEditingObject': editingObject, 'toolbar': 'undo redo | styleselect | bold italic underline | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | image rdbcmsafilebrowser', 'toolbar_drawer': 'sliding', // autosave plugins options. 'autosave_ask_before_unload': true, 'autosave_interval': '30s', // image plugins options. 'image_advtab': true, 'image_caption': true, 'image_title': true, 'codesample_languages': [ { text: 'Apache Configuration', value: 'apacheconf' }, { text: 'ASP.NET (C#)', value: 'aspnet' }, { text: 'Bash', value: 'bash' }, { text: 'BASIC', value: 'basic' }, { text: 'Batch', value: 'batch' }, { text: 'BBcode', value: 'bbcode' }, { text: 'C', value: 'c' }, { text: 'C#', value: 'csharp' }, { text: 'C++', value: 'cpp' }, { text: 'CoffeeScript', value: 'coffeescript' }, { text: 'CSS', value: 'css' }, { text: 'Diff', value: 'diff' }, { text: 'F#', value: 'fsharp' }, { text: 'Git', value: 'git' }, { text: 'Go', value: 'go' }, { text: 'Haml', value: 'haml' }, { text: 'Handlebars', value: 'handlebars' }, { text: 'HTML/XML', value: 'markup' }, { text: 'Icon', value: 'icon' }, { text: '.ignore', value: 'ignore' }, { text: 'Ini', value: 'ini' }, { text: 'Java', value: 'java' }, { text: 'JavaScript', value: 'javascript' }, { text: 'JSDoc', value: 'jsdoc' }, { text: 'JSON', value: 'json' }, { text: 'JSONP', value: 'jsonp' }, { text: 'Less', value: 'less' }, { text: 'Makefile', value: 'makefile' }, { text: 'Markdown', value: 'markdown' }, { text: 'MongoDB', value: 'mongodb' }, { text: 'nginx', value: 'nginx' }, { text: 'Pascal', value: 'pascal' }, { text: 'Perl', value: 'perl' }, { text: 'PHP', value: 'php' }, { text: 'PowerShell', value: 'powershell' }, { text: '.properties', value: 'properties' }, { text: 'Python', value: 'python' }, { text: 'R', value: 'r' }, { text: 'Regex', value: 'regex' }, { text: 'Ruby', value: 'ruby' }, { text: 'Sass (Sass)', value: 'sass' }, { text: 'Sass (Scss)', value: 'scss' }, { text: 'Smarty', value: 'smarty' }, { text: 'SQL', value: 'sql' }, { text: 'Twig', value: 'twig' }, { text: 'TypeScript', value: 'typescript' }, { text: 'VB.Net', value: 'vbnet' }, { text: 'Visual Basic', value: 'vb' }, { text: 'WebAssembly', value: 'wasm' }, { text: 'Wiki markup', value: 'wiki' }, { text: 'YAML', value: 'yaml' }, { text: 'Other', value: 'none' }, ] };// tinyMceDefaultConfig let rdbcmsaFileBrowserPlugin = ''; if (RdbaCommon.isset(() => editingObject.publicModuleUrl)) { rdbcmsaFileBrowserPlugin = editingObject.publicModuleUrl + '/assets/js/Controllers/Admin/Posts/tinymce/plugins/rdbcmsa-file-browser.js'; let newTinyMceConfig = { 'external_plugins': { 'rdbcmsafilebrowser': rdbcmsaFileBrowserPlugin } }; tinyMceDefaultConfig = _.defaultsDeep(newTinyMceConfig, tinyMceDefaultConfig); } this.tinyMce = tinymce.init(tinyMceDefaultConfig); return this.tinyMce; }// activateContentEditor /** * Activate featured image browser. * * @returns {undefined} */ activateFeaturedImageBrowser() { let thisClass = this; window.addEventListener('message', this.featuredImageOnMessage, false); // @link https://stackoverflow.com/a/11986895/128761 Access class property use target attribute. window.postCommonClass = this; RDTADialog.init(); document.addEventListener('click', function(event) { if ( RdbaCommon.isset(() => event.currentTarget.activeElement.id) && event.currentTarget.activeElement.id === 'post_feature_image-openbrowser' ) { let dialogImageBrowser = document.getElementById('dialog-image-browser'); if (dialogImageBrowser) { dialogImageBrowser.querySelector('.rd-dialog-body').innerHTML = '<iframe src="' + thisClass.editingObject.getFileBrowserUrl + '?featured-image=1" tabindex="-1">'; } }// endif element id matched; }); }// activateFeaturedImageBrowser /** * Activate `HTML` editor. * * @param {string} editorSelector The ID of HTML editor (textarea). * @returns {undefined} */ activateHtmlEditor(editorSelector = 'revision_head_value') { if (!document.getElementById(editorSelector + '-editor')) { let event = new Event('rdbcmsa.postsCommonActions.activateHtmlEditor.notfound'); document.dispatchEvent(event, {'bubbles': true}); console.info('the editor was not found. (' + editorSelector + '-editor)'); return ; } let aceEditor = ace.edit(editorSelector + '-editor', { 'maxLines': 90, 'minLines': 10, 'mode': 'ace/mode/html' }); aceEditor.setTheme('ace/theme/monokai'); // listen on change and set value back to textarea. aceEditor.session.on('change', function(delta) { document.getElementById(editorSelector).value = aceEditor.getValue(); }); // do not validate doctype. // @link https://stackoverflow.com/a/39176259/128761 Original source code. aceEditor.session.on('changeAnnotation', function () { let annotations = aceEditor.session.getAnnotations(); if (!_.isArray(annotations)) { annotations = []; } let len = annotations.length; let i = len; while (i--) { if (/doctype first\. Expected/.test(annotations[i].text)) { annotations.splice(i, 1); } else if (/Unexpected End of file\. Expected/.test(annotations[i].text)) { annotations.splice(i, 1); } } if (len > annotations.length) { aceEditor.session.setAnnotations(annotations); } }); let event = new Event('rdbcmsa.postsCommonActions.activateHtmlEditor.found'); document.dispatchEvent(event, {'bubbles': true}); this.aceEditor = aceEditor; }// activateHtmlEditor /** * Activate tags editor. * * @link https://github.com/yairEO/tagify Tagify document. * @returns {undefined} */ activateTagsEditor() { let thisClass = this; let tagsElement = document.querySelector('#prog_tags'); let RdbCMSAPostsEditingObject = this.editingObject; let allowAddNewTag = RdbCMSAPostsEditingObject.permissionAddTag; let tagify = new Tagify(tagsElement, { 'editTags': false, 'enforceWhitelist': !allowAddNewTag// use opposite of permission result. see tagify document. }); tagify.on('add', function(e) { if (!RdbaCommon.isset(() => e.detail.data.tid)) { // if not found tid, it is add new tag. //console.log('this is new tag.', e.detail.data); e.detail.tag.style = '--tag-bg: #d7fdd7;';// light green. } }); tagify.on('input', function(e) { tagify.settings.whitelist.length = 0; // reset current whitelist tagify.loading(true) // show the loader animation RdbaCommon.XHR({ 'url': RdbCMSAPostsEditingObject.getTagsRESTUrl + '?search[value]=' + e.detail.value + '&search[regex]=false', 'method': RdbCMSAPostsEditingObject.getTagsRESTMethod, 'contentType': 'application/x-www-form-urlencoded;charset=UTF-8', 'dataType': 'json' }) .catch(function(responseObject) { // XHR failed. let response = responseObject.response; if (response && response.formResultMessage) { RDTAAlertDialog.alert({ 'text': response.formResultMessage, 'type': 'error' }); } tagify.dropdown.hide.call(tagify); if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { RdbCMSAPostsEditingObject.csrfKeyPair = response.csrfKeyPair; } return Promise.reject(responseObject); }) .then(function(responseObject) { // XHR success. let response = responseObject.response; if (response && response.listItems) { // format result to make it work for tagify. let whitelist = []; let i = 0; response.listItems.forEach(function(item, index) { whitelist[i] = { 'value': RdbaCommon.unEscapeHtml(item.t_name), 'tid': item.tid }; i++; }); // replace tagify "whitelist" array values with new values // and add back the ones already choses as Tags tagify.settings.whitelist.push(...whitelist, ...tagify.value); tagify .loading(false) // render the suggestions dropdown. .dropdown.show.call(tagify, e.detail.value); } if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { RdbCMSAPostsEditingObject.csrfKeyPair = response.csrfKeyPair; } return Promise.resolve(responseObject); }); }); this.tagify = tagify; }// activateTagsEditor /** * AJAX get post related data such as categories, statuses. * * This method return promise so, it can be use with `.then(function(responseObject) {})`.<br> * Example:<pre> * let PromiseAjaxGetRelatedData = postCommonClass.ajaxGetRelatedData(); * PromiseAjaxGetRelatedData.then(function(responseObject) { * let response = responseObject.response; * // your code. * }); * </pre> * * @param {string} ajaxURL The AJAX URL. No query string. * @param {string} ajaxMethod The AJAX method. * @returns {Promise} */ ajaxGetRelatedData(ajaxURL, ajaxMethod) { let thisClass = this; let promiseObj = RdbaCommon.XHR({ 'url': ajaxURL + '?t_type=' + thisClass.tTypeForCategory, 'method': ajaxMethod, 'contentType': 'application/x-www-form-urlencoded;charset=UTF-8', 'dataType': 'json' }) .catch(function(responseObject) { // XHR failed. let response = responseObject.response; if (response && response.formResultMessage) { RDTAAlertDialog.alert({ 'type': 'danger', 'text': response.formResultMessage }); } if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { thisClass.editingObject.csrfKeyPair = response.csrfKeyPair; } return Promise.reject(responseObject); }) .then(function(responseObject) { // XHR success. let response = responseObject.response; if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { thisClass.editingObject.csrfKeyPair = response.csrfKeyPair; } // write categories checkboxes. if (RdbaCommon.isset(() => response.categories.items)) { let sourceTemplate = document.getElementById('rdbcmsa-contents-categories-formfields'); let source = ''; if (sourceTemplate) { source = sourceTemplate.innerHTML; } else { console.warn('source template (#rdbcmsa-contents-categories-formfields) was not found.'); } let template = Handlebars.compile(source); Handlebars.registerHelper('getMarginLeft', function (levelNumber) { if (isNaN(levelNumber)) { return 0; } levelNumber = (parseInt(levelNumber) - 1); let baseLeftSpace = .813; return (baseLeftSpace * levelNumber); }); let rendered = template(response.categories.items); let categoriesPlaceholder = document.querySelector('#categories-form-fields .control-wrapper'); if (categoriesPlaceholder) { categoriesPlaceholder.innerHTML = rendered; } else { console.warn('categories placeholder (#categoriesPlaceholder) was not found.'); } } // write statuses options. if (RdbaCommon.isset(() => response.postStatuses)) { let optionString = ''; response.postStatuses.forEach(function(item, index) { optionString += '<option value="' + item.value + '">' + item.text + '</option>'; }); let post_status = document.querySelector('#post_status'); if (post_status) { post_status.innerHTML = optionString; } } return Promise.resolve(responseObject); }); return promiseObj; }// ajaxGetRelatedData /** * Detect browser features and set (or hide) description. * * @returns {undefined} */ detectBrowserFeaturesAndSetDescription() { // detect datetime-local input type supported. let isDateTimeLocalSupported = function () { let input = document.createElement('input'); let value = 'a'; input.setAttribute('type', 'datetime-local'); input.setAttribute('value', value); return (input.value !== value); }; if (isDateTimeLocalSupported()) { // if datetime-local supported. // hide description. let post_publish_date = document.querySelector('#post_publish_date'); if (post_publish_date) { post_publish_date.nextElementSibling.classList.add('rd-hidden'); } } }// detectBrowserFeaturesAndSetDescription /** * Listen message from featured image. * * This method is callback function from `activateFeaturedImageBrowser() method. * * @param {object} event * @returns {undefined} */ featuredImageOnMessage(event) { // @link https://stackoverflow.com/a/11986895/128761 Access class property use target attribute. let thisClass = event.currentTarget.postCommonClass; if (event && event.data && event.data.sender === 'rdbcmsasetfeaturedimage') { let posts = (RdbaCommon.isset(() => event.data.content) ? event.data.content : {}); thisClass.renderFeaturedImage(posts); let dialogElement = document.getElementById('dialog-image-browser'); if (dialogElement) { let closeButton = dialogElement.querySelector('.rd-dialog-close'); if (closeButton) { closeButton.focus(); closeButton.click(); } } } }// featuredImageOnMessage /** * Listen click to remove featured image. * * @returns {undefined} */ listenClickRemoveFeaturedImage() { document.addEventListener('click', function(event) { if ( ( RdbaCommon.isset(() => event.currentTarget.activeElement.id) && event.currentTarget.activeElement.id === 'post_feature_image-removebutton' ) || ( RdbaCommon.isset(() => event.target.id) && event.target.id === 'post_feature_image-removebutton' ) ) { let post_feature_image = document.getElementById('post_feature_image'); if (post_feature_image) { post_feature_image.value = ''; } let previewContainer = document.getElementById('post_feature_image-preview'); previewContainer.innerHTML = ''; } }); }// listenClickRemoveFeaturedImage /** * Listen enable revision and allow revision log to write. * * @returns {undefined} */ listenEnableRevision() { let thisClass = this; document.addEventListener('change', function(event) { if ( RdbaCommon.isset(() => event.target.id) && event.target.id === 'prog_enable_revision' ) { event.preventDefault(); let thisCheckbox = event.target; let revision_log =document.querySelector('#revision_log'); if (thisCheckbox.checked && thisCheckbox.checked === true) { revision_log.disabled = false; revision_log.dataset.markDisabled = false; } else { revision_log.disabled = true; revision_log.dataset.markDisabled = true; } } }); }// listenEnableRevision /** * Listen form submit and make it XHR. * * @param {string} ajaxURL The AJAX URL. No query string. * @param {string} ajaxMethod The AJAX method. * @returns {undefined} */ listenFormSubmit(ajaxURL, ajaxMethod) { let thisClass = this; document.addEventListener('submit', function(event) { if ( RdbaCommon.isset(() => event.target.id) && '#' + event.target.id === thisClass.formIDSelector ) { event.preventDefault(); // form validations. --------------------------------- let post_name = document.querySelector('#post_name'); if (!post_name || _.isEmpty(post_name.value)) { RDTAAlertDialog.alert({ 'text': thisClass.editingObject.txtPleaseEnterTitle, 'type': 'error' }); return ; } // end form validations. ---------------------------- // ajax save post. let thisForm = event.target; let saveButtons = thisForm.querySelectorAll('.rdbcmsa-contents-posts-save-container button,' + ' .rdbcmsa-contents-posts-save-container input[type="submit"],' + ' .rdbcmsa-contents-posts-save-container input[type="button"]' ); // reset form result placeholder thisForm.querySelector('.form-result-placeholder').innerHTML = ''; // add spinner icon thisForm.querySelector('.submit-button-row .control-wrapper').insertAdjacentHTML('beforeend', '<i class="fas fa-spinner fa-pulse fa-fw loading-icon" aria-hidden="true"></i>'); // lock save buttons saveButtons.forEach(function(item, index) { item.disabled = true; }); let formData = new FormData(thisForm); formData.append(thisClass.editingObject.csrfName, thisClass.editingObject.csrfKeyPair[thisClass.editingObject.csrfName]); formData.append(thisClass.editingObject.csrfValue, thisClass.editingObject.csrfKeyPair[thisClass.editingObject.csrfValue]); if (event.submitter && event.submitter.name && event.submitter.value) { formData.append(event.submitter.name, event.submitter.value); } RdbaCommon.XHR({ 'url': ajaxURL, 'method': ajaxMethod, 'contentType': 'application/x-www-form-urlencoded;charset=UTF-8', 'data': new URLSearchParams(_.toArray(formData)).toString(), 'dataType': 'json' }) .catch(function(responseObject) { // XHR failed. let response = responseObject.response; if (response && response.formResultMessage) { RDTAAlertDialog.alert({ 'type': RdbaCommon.getAlertClassFromStatus(response.formResultStatus), 'html': RdbaCommon.renderAlertContent(response.formResultMessage) }); } if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { thisClass.editingObject.csrfKeyPair = response.csrfKeyPair; } return Promise.reject(responseObject); }) .then(function(responseObject) { // XHR success. let response = responseObject.response; if (response.redirectBack) { window.location.href = response.redirectBack; } else { // if anything else (no redirectBack). if ( response.revision_id && response.revision_id > 0 && RdbaCommon.isset(() => thisClass.postCommonEditRevision.currentRevisionId) ) { thisClass.postCommonEditRevision.currentRevisionId = response.revision_id; } // save and stay. thisClass.reloadFormData(); } if (response && response.formResultMessage) { // if there is form result message, display it. RdbaCommon.displayAlertboxFixed(response.formResultMessage, response.formResultStatus); } if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { thisClass.editingObject.csrfKeyPair = response.csrfKeyPair; } return Promise.resolve(responseObject); }) .finally(function() { // remove loading icon thisForm.querySelector('.loading-icon').remove(); // unlock save buttons saveButtons.forEach(function(item, index) { item.disabled = false; }); }); } }); }// listenFormSubmit /** * Listen post status change and do following. * * Make published date input box read only/editable.<br> * Set preview text of current status to the submit button. * * @param {string} postStatusId The post status input ID. * @param {string} postPublishDateId The post publish date input ID. * @returns {undefined} */ listenPostStatusChange(postStatusId = 'post_status', postPublishDateId = 'post_publish_date') { let thisClass = this; document.addEventListener('change', function(event) { if ( RdbaCommon.isset(() => event.target.id) && event.target.id === postStatusId ) { event.preventDefault(); let post_status = event.target; let post_publish_date = document.getElementById(postPublishDateId); if (post_status && post_status.value == 2) { // if selected status is scheduled0 post_publish_date.readOnly = false; post_publish_date.dataset.markDisabled = false; post_publish_date.disabled = false; } else { post_publish_date.readOnly = true; post_publish_date.dataset.markDisabled = true; post_publish_date.disabled = true; } if (RdbaCommon.isset(() => post_status.options[post_status.selectedIndex])) { // set current status text to submit button. let submitBtnStatus = document.getElementById('prog-current-post_status'); let selectedText = post_status.options[post_status.selectedIndex].text; submitBtnStatus.innerHTML = ' <i>(' + selectedText + ')</i>'; } } }); }// listenPostStatusChange /** * Listen on type URL and correct to safe URL string. * * @returns {undefined} */ listenUrlToCorrectUrl() { let thisClass = this; document.addEventListener('keyup', function(event) { if ( event.target && event.target.id === 'alias_url' && event.target.form && '#' + event.target.form.id === thisClass.formIDSelector ) { let thisForm = event.target.form; let submitButton = thisForm.querySelector('.rdba-submit-button'); submitButton.disabled = true; } }); document.addEventListener('keyup', RdsUtils.delay(function(event) { if ( event.target && event.target.id === 'alias_url' && event.target.form && '#' + event.target.form.id === thisClass.formIDSelector ) { let thisForm = event.target.form; let urlField = event.target; let submitButton = thisForm.querySelector('.rdba-submit-button'); let safeUrl = RdsUtils.convertUrlSafeString(urlField.value); if (urlField) { urlField.value = safeUrl; } submitButton.disabled = false; } }, 700)); }// listenUrlToCorrectUrl /** * Reload form data from latest post and its revision. * * @returns {undefined} */ reloadFormData() { let thisClass = this; let thisForm = document.querySelector(this.formIDSelector); if (thisForm) { // reset form. thisForm.reset(); } if (RdbaCommon.isset(() => this.aceEditor)) { // if html code editor is in used. // destroy ace editor. this.aceEditor.destroy(); } if (RdbaCommon.isset(() => this.tagify)) { // if tag editor is in used. // destroy tagify. this.tagify.destroy(); } // ajax get latest form data and set form values. thisClass.editControllerClass.ajaxGetFormData() .then(function() { return thisClass.triggerEvents(); }) .then(function() { // reload editing tinyMCE. let tinyMCEBodyValue = tinymce.get('revision_body_value'); if (tinyMCEBodyValue) { tinyMCEBodyValue.setContent(thisForm.querySelector('#revision_body_value').value); tinyMCEBodyValue.setDirty(false); tinyMCEBodyValue.fire('change');// trigger event. } }) .then(function() { if (RdbaCommon.isset(() => thisClass.aceEditor)) { // if html code editor is in used. // reload ace editor by destroy and re-activate it. cannot find the way to update content properly. thisClass.activateHtmlEditor(); } if (RdbaCommon.isset(() => thisClass.tagify)) { // if tag editor is in used. // re-activate tagify. thisClass.activateTagsEditor(); thisClass.editControllerClass.setupFormTags(thisClass); } }) .then(function() { // reload revision history. if ( RdbaCommon.isset(() => thisClass.postCommonEditRevision.activatedDatatable) && thisClass.postCommonEditRevision.activatedDatatable === true ) { thisClass.postCommonEditRevision.reloadDatatable(); } }); }// reloadFormData /** * Render featured image. * * This method was called from `featuredImageOnMessage()` and other methods. * @param {Object} posts * @returns {undefined} */ renderFeaturedImage(posts) { if (RdbaCommon.isset(() => posts.files.file_id)) { // render preview featured image template. let source = document.getElementById('rdbcmsa-featured-image-preview-elements').innerHTML; let template = Handlebars.compile(source); document.getElementById('post_feature_image-preview').innerHTML = template(posts); // set featured image value (file_id). document.getElementById('post_feature_image').value = posts.files.file_id; }// endif; posts.files.file_id }// renderFeaturedImage /** * Trigger form fields events. * * @returns {Promise} Return promise object. */ triggerEvents() { let promiseObj = new Promise((resolve, reject) => { // trigger event on elements. let post_status = document.getElementById('post_status'); if (post_status) { post_status.dispatchEvent(new Event('change', {'bubbles': true})); } let prog_enable_revision = document.getElementById('prog_enable_revision'); if (prog_enable_revision) { prog_enable_revision.dispatchEvent(new Event('change', {'bubbles': true})); } resolve(); }); return promiseObj; }// triggerEvents }// RdbCMSAPostsCommonActions
JavaScript
class RegisterScreen extends Component { /** * Constructor */ static contextType = LocalizationContext; constructor() { super() this.state = { name: "", email: "", username: "", password: "", confirmedPassword: "" } this.register = this.register.bind(this) this.host = Config.HOST } openTOSPage = async () => { WebBrowser.openBrowserAsync('https://radioapp.storytellers-conteurs.ca/tos/posts/tos.html'); } openPrivacyPolicyPage = async () => { WebBrowser.openBrowserAsync('https://radioapp.storytellers-conteurs.ca/tos/posts/privacypolicy.html'); } /** * Redirect to the login page */ goToLogin() { // Actions.LoginScreen(); Actions.LoginScreen(); } /** * Go to the email verification page */ goToEmailVerification() { console.log('Go to email verification'); Actions.EmailVerification({ email: this.state.email, code: "", username: "" }); } validateEmail(email) { const regexp = /^(([^<>()[\]\\.,;:\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,}))$/; return regexp.test(email); } /** * Register a Storytellers account */ register() { if (this.state.name === "" || this.state.email === "" || this.state.username === "" || this.state.password === "") { Alert.alert( this.context.t('missingRegistrationInfo'), this.context.t('missingRegistrationInfo'), ); } else { // Check if the passwords match if (this.state.password != this.state.confirmedPassword) { Alert.alert(this.context.t('passwordMismatch')); return; } // Validating email if (!this.validateEmail(this.state.email)) { Alert.alert( this.context.t('invalidEmail'), this.context.t('makeSureValidEmailEntered'), ); } else { console.log(this.host + `register?name=${this.state.name}&email=${this.state.email}`) fetch(this.host + `register?name=${this.state.name}&email=${this.state.email}`, { method: 'POST', headers: new Headers({ 'Authorization': base64.encode(`${this.state.username}:${this.state.password}`) }) }) .then(response => { return response.json() }) .then(result => { if (result["success"]) { console.log("Successful response") // Going to the email screen this.goToEmailVerification(); } else { Alert.alert( this.context.t('invalidRegistration') ) } }) .catch((error) => { Alert.alert( "Connection Error" ) console.error(error); }); } } } /** * Render the registration screen */ render() { return ( <View style={styles.container}> {/* Registration form */} <View> <Text style={styles.title}>{this.context.t('createYourAccountMessage')}</Text> </View> <View> <Input style={styles.input} placeholder={this.context.t('fullName')} onChangeText={(text) => this.setState({ name: text })} /> <Input style={styles.input} placeholder={this.context.t('email')} onChangeText={(text) => this.setState({ email: text })} /> <Input style={styles.input} placeholder={this.context.t('username')} onChangeText={(text) => this.setState({ username: text })} /> <Input secureTextEntry={true} style={styles.input} placeholder={this.context.t('password')} autoCapitalize='none' onChangeText={(text) => this.setState({ password: text })} /> <Input secureTextEntry={true} style={styles.input} placeholder={this.context.t('confirmPassword')} autoCapitalize='none' onChangeText={(text) => this.setState({ confirmedPassword: text })} /> </View> <View> <Button buttonStyle={styles.signUpButton} title={this.context.t('register')} onPress={this.register} /> <Text style={{ marginTop: 15, textAlign: 'center' }}>{this.context.t('termsOfServiceMessage')}</Text> <View style={{ flexDirection: 'row', alignSelf: 'center' }}> <TouchableOpacity onPress={this.openTOSPage}><Text style={{ textDecorationLine: 'underline', textAlign: 'center' }}>{this.context.t('termsOfService')}</Text></TouchableOpacity> <Text style={{ textAlign: 'center' }}> {this.context.t('and')} </Text> <TouchableOpacity onPress={this.openPrivacyPolicyPage}><Text style={{ textDecorationLine: 'underline', textAlign: 'center' }}>{this.context.t('privacyPolicy')}</Text></TouchableOpacity> </View> </View> {/* Option to return to the login screen */} <View style={styles.loginButtonText}> <Text style={styles.text}>{this.context.t('alreadyHaveAccount')}</Text> <TouchableOpacity onPress={this.goToLogin}> <Text style={styles.buttonText}> {this.context.t('login')}</Text> </TouchableOpacity> </View> </View> ); } }
JavaScript
class Card { constructor(value, color, type){ this.value = value; this.color = color; this.type = type; this.playable = false; } // check if a card is the card given in parameters equals(card) { return card.value == this.value && card.color === this.color && card.type === this.type; } }
JavaScript
class Bug extends Error { // constructor initializes state of the class constructor(args) { super(args); // initializes "this" context of the class this.problem = args.problem; this.cause = args.cause; this.level = args.level; this.timeStamp = args.timeStamp; } }
JavaScript
class CreateInView { /** * Constructor for inserting information into economies table in DynamoDb * * @param {Object} params * @param {Number} params.tokenId * @param {Number} params.clientId * @param {Number} params.chainId * @param {String} params.gatewayContractAddress * @param {String} params.brandedTokenContract * @param {String} params.utilityBrandedTokenContract * @param {String} params.chainEndpoint * @param {String} params.stakeCurrencyContractAddress * * @constructor */ constructor(params) { const oThis = this; oThis.tokenId = params.tokenId; oThis.clientId = params.clientId; oThis.chainId = params.chainId; oThis.gatewayContractAddress = params.gatewayContractAddress; oThis.brandedTokenContract = params.brandedTokenContract; oThis.utilityBrandedTokenContract = params.utilityBrandedTokenContract; oThis.chainEndpoint = params.chainEndpoint; oThis.stakeCurrencyContractAddress = params.stakeCurrencyContractAddress; } /** * Perform * * @return {Promise<result>} */ perform() { const oThis = this; return oThis._asyncPerform().catch(function(error) { if (responseHelper.isCustomResult(error)) { return error; } else { logger.error(`${__filename}::perform::catch`); logger.error(error); return responseHelper.error({ internal_error_identifier: 'l_s_e_civ_1', api_error_identifier: 'unhandled_catch_response', debug_options: {} }); } }); } /*** * Async performer for the class. * * @private * * @return {Promise<result>} */ async _asyncPerform() { const oThis = this; await oThis._fetchTokenDetails(); await oThis._initializeVars(); return oThis._createEntryInEconomyTable(); } /** * Fetch token details from tokens table. * * @return {Promise<void>} * * @private */ async _fetchTokenDetails() { const oThis = this; let cacheResponse = await new TokenCache({ clientId: oThis.clientId }).fetch(); if (cacheResponse.isFailure()) { logger.error('Could not fetched token details.'); return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_s_e_civ_2', api_error_identifier: 'something_went_wrong', debug_options: { clientId: oThis.clientId } }) ); } let tokenDetails = cacheResponse.data; const economyTimestamp = tokenDetails.createdAt; oThis.displayName = tokenDetails.name; oThis.symbol = tokenDetails.symbol; oThis.conversionFactor = tokenDetails.conversionFactor; oThis.decimals = tokenDetails.decimal; oThis.blockTimestamp = parseInt((new Date(economyTimestamp).getTime() / 1000).toFixed(0)); } /** * Initialize variables. * * @return {Promise<void>} * * @private */ async _initializeVars() { const oThis = this, blockScannerObj = await blockScannerProvider.getInstance([oThis.chainId]), CreateEconomyKlass = blockScannerObj.economy.Create; let economyParams = { chainId: oThis.chainId, decimals: oThis.decimals, contractAddress: oThis.utilityBrandedTokenContract, displayName: oThis.displayName, conversionFactor: oThis.conversionFactor, symbol: oThis.symbol }; // Always sanitize extra storage params outside the call let extraStorageParams = { gatewayContractAddress: oThis.gatewayContractAddress.toLowerCase(), originContractAddress: oThis.brandedTokenContract.toLowerCase(), baseCurrencyContractAddress: oThis.stakeCurrencyContractAddress.toLowerCase() }; oThis.createEconomyObject = new CreateEconomyKlass( economyParams, extraStorageParams, oThis.blockTimestamp, oThis.chainEndpoint ); } /** * Create entry in economy table in DynamoDB. * * @return {Promise<void>} * * @private */ async _createEntryInEconomyTable() { const oThis = this; return oThis.createEconomyObject.perform(); } }
JavaScript
class ElementNotFound { constructor(locator, prefixMessage = "Element", postfixMessage = "was not found by text|CSS|XPath") { if (typeof locator === "object") { locator = JSON.stringify(locator); } throw new Error(`${prefixMessage} ${locator} ${postfixMessage}`); } }
JavaScript
class DropdownDirective{ /** * @constructor */ constructor() { /** @type {string} */ this.templateUrl = "./dropdown.html"; /** @type {string} */ this.restrict = "E"; /** * Binds 'label' string. Binds 'values' array with all possible values. Binds 'model' with the current selected value. Binds a 'change' function. * @type {Scope} **/ this.scope = { label: "@", values: "=", model: "=", change: "&" }; /** * * @type {DropdownController} */ this.controller = DropdownController; /** * * @type {string} */ this.controllerAs = "ctrl"; /** * * @type {boolean} */ this.bindToController = true; } /** * Links the change function to model changes. * @param {Scope} scope */ link(scope){ scope.$watch( ()=>{return scope.ctrl.model;}, ()=>{scope.ctrl.change();} ); } }
JavaScript
class Template { static parse(text) { // format: {{name:description:type}} // type defaults to "text" if not present let expr = new RegExp("\{\{([^:{}]+)(?::([^:{}]*))?(?::([^:{}]+))?\}\}", "g"); let matches = {}; let match; while (match = expr.exec(text)) { if (!(match[1] in matches)) { matches[match[1]] = { name: match[1], description: match[2] || "", type: match[3] || "text", positions: [] }; } matches[match[1]].positions.push({ start: match.index, end: match.index + match[0].length }); } return matches; } static apply(text, data) { let placeholders = this.parse(text); let missing = []; let ops = []; for (var name in placeholders) { if (name in data) { placeholders[name].positions.forEach((position) => { ops.push({ start: position.start, end: position.end, replacement: data[name] }); }); } else { missing.push(name); } } if (missing.length > 0) { throw new TemplateException("The following parameters have been missing in parameter data: " + missing.join(", ")); } if (Object.keys(placeholders).length === 0 && Object.keys(data).length !== 0) { throw new TemplateException("No placeholders found, but data has been passed and wasn't empty!"); } if (JSON.stringify(Object.keys(placeholders)) !== JSON.stringify(Object.keys(data))) { throw new TemplateException("Placeholders do not match the ones defined in the template!"); } ops.sort((a, b) => { if (a.start < b.start) { return -1; } if (a.start > b.start) { return 1; } if (a.end < b.end) { return -1; } if (a.end > b.end) { return 1; } return 0; }); let offset = 0; ops.forEach((op) => { text = text.substring(0, op.start + offset) + op.replacement + text.substring(op.end + offset); offset += op.replacement.length - (op.end - op.start); }); return text; } }
JavaScript
class Signal extends ToneAudioNode { constructor() { super(optionsFromArguments(Signal.getDefaults(), arguments, ["value", "units"])); this.name = "Signal"; /** * Indicates if the value should be overridden on connection. */ this.override = true; const options = optionsFromArguments(Signal.getDefaults(), arguments, ["value", "units"]); this.output = this._constantSource = new ToneConstantSource({ context: this.context, convert: options.convert, offset: options.value, units: options.units, minValue: options.minValue, maxValue: options.maxValue, }); this._constantSource.start(0); this.input = this._param = this._constantSource.offset; } static getDefaults() { return Object.assign(ToneAudioNode.getDefaults(), { convert: true, units: "number", value: 0, }); } connect(destination, outputNum = 0, inputNum = 0) { // start it only when connected to something connectSignal(this, destination, outputNum, inputNum); return this; } dispose() { super.dispose(); this._param.dispose(); this._constantSource.dispose(); return this; } //------------------------------------- // ABSTRACT PARAM INTERFACE // just a proxy for the ConstantSourceNode's offset AudioParam // all docs are generated from AbstractParam.ts //------------------------------------- setValueAtTime(value, time) { this._param.setValueAtTime(value, time); return this; } getValueAtTime(time) { return this._param.getValueAtTime(time); } setRampPoint(time) { this._param.setRampPoint(time); return this; } linearRampToValueAtTime(value, time) { this._param.linearRampToValueAtTime(value, time); return this; } exponentialRampToValueAtTime(value, time) { this._param.exponentialRampToValueAtTime(value, time); return this; } exponentialRampTo(value, rampTime, startTime) { this._param.exponentialRampTo(value, rampTime, startTime); return this; } linearRampTo(value, rampTime, startTime) { this._param.linearRampTo(value, rampTime, startTime); return this; } targetRampTo(value, rampTime, startTime) { this._param.targetRampTo(value, rampTime, startTime); return this; } exponentialApproachValueAtTime(value, time, rampTime) { this._param.exponentialApproachValueAtTime(value, time, rampTime); return this; } setTargetAtTime(value, startTime, timeConstant) { this._param.setTargetAtTime(value, startTime, timeConstant); return this; } setValueCurveAtTime(values, startTime, duration, scaling) { this._param.setValueCurveAtTime(values, startTime, duration, scaling); return this; } cancelScheduledValues(time) { this._param.cancelScheduledValues(time); return this; } cancelAndHoldAtTime(time) { this._param.cancelAndHoldAtTime(time); return this; } rampTo(value, rampTime, startTime) { this._param.rampTo(value, rampTime, startTime); return this; } get value() { return this._param.value; } set value(value) { this._param.value = value; } get convert() { return this._param.convert; } set convert(convert) { this._param.convert = convert; } get units() { return this._param.units; } get overridden() { return this._param.overridden; } set overridden(overridden) { this._param.overridden = overridden; } get maxValue() { return this._param.maxValue; } get minValue() { return this._param.minValue; } /** * See [[Param.apply]]. */ apply(param) { this._param.apply(param); return this; } }