language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class BrickTargeter { /** * Creates an instance of BrickTargeter * * @constructor * @param {Phaser.Group} bricks * @param {Ball} ball */ constructor(bricks, ball) { // Target Brick this.target = null; this.ball = ball; this.bricks = bricks || []; } /** * Among the remaining bricks, finds the brick that is farthest away * from the player ball. * * This is not intended to be an efficient way to win the game, but * rather a way to make the AI's play style resemble that of a human * * This method is called again when the target brick 'dies'. */ next() { let incumbent = { brick: null, d2: 0 }; // Iterate through remaining bricks this.bricks.forEachAlive( brick => { const d2 = distanceSquared(brick, this.ball) || 0; const incumbentIsFartherAway = incumbent.d2 > d2; incumbent = incumbentIsFartherAway ? incumbent : {brick, d2}; }); // Target is the final incumbent this.target = incumbent.brick; // If a target is found, have it invoke this function again on death if (this.target) { this.target.events.onKilled.add( () => { this.next(); }); } } getBrick() { if (!this.target) { this.next(); } return this.target; } }
JavaScript
class Map extends BaseContainer { constructor(scene, x, y) { super(scene, x ?? 760, y ?? 480); /** @type {IglooMap} */ this.iglooMap; // block const block = scene.add.rectangle(0, 0, 1520, 960); block.isFilled = true; block.fillColor = 0; block.fillAlpha = 0.2; this.add(block); // bg const bg = scene.add.image(0, -35, "map", "bg"); bg.setOrigin(0.5, 0.5007429420505201); this.add(bg); // dojo const dojo = scene.add.image(69, -310, "map", "dojo"); dojo.setOrigin(0.5038759689922481, 0.5056179775280899); this.add(dojo); // mountains const mountains = scene.add.image(29, -276, "map", "mountains"); this.add(mountains); // island const island = scene.add.image(-12, -30, "map", "island"); island.setOrigin(0.5005417118093174, 0.5); this.add(island); // mtn const mtn = scene.add.image(-232, -256, "map", "mtn"); this.add(mtn); // village const village = scene.add.image(-181, -179, "map", "village"); village.setOrigin(0.503030303030303, 0.5041322314049587); this.add(village); // beach const beach = scene.add.image(-390, -94, "map", "beach"); this.add(beach); // dock const dock = scene.add.image(-370, 114, "map", "dock"); dock.setOrigin(0.5, 0.5037037037037037); this.add(dock); // town const town = scene.add.image(-128, 22, "map", "town"); this.add(town); // forts const forts = scene.add.image(78, 30, "map", "forts"); forts.setOrigin(0.5045045045045045, 0.5045871559633027); this.add(forts); // igloo const igloo = scene.add.image(201, 141, "map", "igloo"); this.add(igloo); // plaza const plaza = scene.add.image(264, 22, "map", "plaza"); plaza.setOrigin(0.5, 0.5038167938931297); this.add(plaza); // rink const rink = scene.add.image(52, -98, "map", "rink"); rink.setOrigin(0.5023041474654378, 0.5); this.add(rink); // forest const forest = scene.add.image(291, -84, "map", "forest"); forest.setOrigin(0.5027027027027027, 0.5057471264367817); this.add(forest); // cove const cove = scene.add.image(334, -169, "map", "cove"); cove.setOrigin(0.5, 0.5058823529411764); this.add(cove); // mine const mine = scene.add.image(168, -214, "map", "mine"); mine.setOrigin(0.5042016806722689, 0.5); this.add(mine); // berg const berg = scene.add.image(402, -210, "map", "berg"); this.add(berg); // note const note = scene.add.image(419, 242, "map", "note"); note.setOrigin(0.5017667844522968, 0.5); this.add(note); // grey_button const grey_button = scene.add.image(483, -333, "main", "grey-button"); this.add(grey_button); // grey_x const grey_x = scene.add.image(483, -335, "main", "grey-x"); this.add(grey_x); // iglooMap const iglooMap = new IglooMap(scene, 0, 0); iglooMap.visible = false; this.add(iglooMap); // block (components) new Interactive(block); // bg (components) new Interactive(bg); // dojo (components) const dojoButton = new Button(dojo); dojoButton.spriteName = "dojo"; dojoButton.callback = () => this.onRoomClick(321); dojoButton.activeFrame = false; const dojoShowHint = new ShowHint(dojo); dojoShowHint.text = "dojoext_hint"; // mtn (components) const mtnButton = new Button(mtn); mtnButton.spriteName = "mtn"; mtnButton.callback = () => this.onRoomClick(230); mtnButton.activeFrame = false; const mtnShowHint = new ShowHint(mtn); mtnShowHint.text = "mtn_hint"; // village (components) const villageButton = new Button(village); villageButton.spriteName = "village"; villageButton.callback = () => this.onRoomClick(200); villageButton.activeFrame = false; const villageShowHint = new ShowHint(village); villageShowHint.text = "village_hint"; // beach (components) const beachButton = new Button(beach); beachButton.spriteName = "beach"; beachButton.callback = () => this.onRoomClick(400); beachButton.activeFrame = false; const beachShowHint = new ShowHint(beach); beachShowHint.text = "beach_hint"; // dock (components) const dockButton = new Button(dock); dockButton.spriteName = "dock"; dockButton.callback = () => this.onRoomClick(800); dockButton.activeFrame = false; const dockShowHint = new ShowHint(dock); dockShowHint.text = "dock_hint"; // town (components) const townButton = new Button(town); townButton.spriteName = "town"; townButton.callback = () => this.onRoomClick(100); townButton.activeFrame = false; const townShowHint = new ShowHint(town); townShowHint.text = "town_hint"; // forts (components) const fortsButton = new Button(forts); fortsButton.spriteName = "forts"; fortsButton.callback = () => this.onRoomClick(801); fortsButton.activeFrame = false; const fortsShowHint = new ShowHint(forts); fortsShowHint.text = "forts_hint"; // igloo (components) const iglooButton = new Button(igloo); iglooButton.spriteName = "igloo"; iglooButton.callback = () => this.iglooMap.show(); iglooButton.activeFrame = false; const iglooShowHint = new ShowHint(igloo); iglooShowHint.text = "igloos_hint"; // plaza (components) const plazaButton = new Button(plaza); plazaButton.spriteName = "plaza"; plazaButton.callback = () => this.onRoomClick(300); plazaButton.activeFrame = false; const plazaShowHint = new ShowHint(plaza); plazaShowHint.text = "plaza_hint"; // rink (components) const rinkButton = new Button(rink); rinkButton.spriteName = "rink"; rinkButton.callback = () => this.onRoomClick(802); rinkButton.activeFrame = false; const rinkShowHint = new ShowHint(rink); rinkShowHint.text = "rink_hint"; // forest (components) const forestButton = new Button(forest); forestButton.spriteName = "forest"; forestButton.callback = () => this.onRoomClick(809); forestButton.activeFrame = false; const forestShowHint = new ShowHint(forest); forestShowHint.text = "forest_hint"; // cove (components) const coveButton = new Button(cove); coveButton.spriteName = "cove"; coveButton.callback = () => this.onRoomClick(810); coveButton.activeFrame = false; const coveShowHint = new ShowHint(cove); coveShowHint.text = "cove_hint"; // mine (components) const mineButton = new Button(mine); mineButton.spriteName = "mine"; mineButton.callback = () => this.onRoomClick(807); mineButton.activeFrame = false; const mineShowHint = new ShowHint(mine); mineShowHint.text = "shack_hint"; // berg (components) const bergButton = new Button(berg); bergButton.spriteName = "berg"; bergButton.callback = () => this.onRoomClick(805); bergButton.activeFrame = false; // note (components) new Interactive(note); // grey_button (components) const grey_buttonButton = new Button(grey_button); grey_buttonButton.spriteName = "grey-button"; grey_buttonButton.callback = () => { this.visible = false }; this.iglooMap = iglooMap; /* START-USER-CTR-CODE */ /* END-USER-CTR-CODE */ } /* START-USER-CODE */ onRoomClick(id) { let room = this.crumbs.scenes.rooms[id] if (this.world.room.key == room.key) return this.visible = false this.world.client.sendJoinRoom(id, room.key, room.x, room.y, 80) } /* END-USER-CODE */ }
JavaScript
class ChartCard extends React.Component { static propTypes = { /** Unique string usable as an element ID for the ChartCard */ chartCardId: PropTypes.string.isRequired, /** Title of the card */ title: PropTypes.string.isRequired, /** Description of the presented chart */ chartInfo: PropTypes.string.isRequired, /** React renderable element that is the focus of this chart card, ie the * actual chart, and perhaps also an a11y table representation of * that chart if desired. */ children: PropTypes.node.isRequired, /** flag for an especially long description that requires smaller text. */ longDescription: PropTypes.bool, }; /* ************************************************************************** * constructor */ /** */ constructor(props) { super(props); this.state = { isInfoOpen: false, }; this._infoBtn = React.createRef(); // We need to know when the info was closed after being open // so we can set the focus to the info button to open it again // but this property isn't state because we don't want to re-render // when it changes. this._infoJustClosed = false; } /* ************************************************************************** * componentDidUpdate */ /** * * componentDidUpdate() is invoked immediately after updating occurs. This * method is not called for the initial render. * * Use this as an opportunity to operate on the DOM when the component has * been updated. */ componentDidUpdate() { // We want to have the focus on the info button when the chart card is // rendered immediately after the displayed info was closed by the user if (this._infoJustClosed) { this._infoBtn.current.focus(); this._infoJustClosed = false; } } /* ************************************************************************** * render */ /** * * Required method of a React component. * @see {@link https://reactjs.org/docs/react-component.html#render|React.Component.render} */ render() { logger.debug('ChartCard.render: children', this.props.children); const infoId = `chart-info-${this.props.chartCardId}`; return ( <div className='chart-card-component card has-text-centered is-centered' id='riff-chart-card'> {/* Use a column flexbox to allow the chart to adjust to the space not occupied by the card title, remember only the direct children of the flex container will be adjusted. */} <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}> <div> <div className='chart-card-title'> <span>{this.props.title}</span> <button className='chart-card-toggle' onClick={() => this.setState({ isInfoOpen: true })} aria-describedby={infoId} tabIndex='-1' ref={this._infoBtn} > <InfoIcon/> </button> </div> </div> <div style={{ minHeight: 0, flexGrow: 1, flexShrink: 1 }}> <div className='chart-card-chart card-image has-text-centered is-centered'> {this.props.children} </div> </div> </div> {this.state.isInfoOpen && <ChartCardInfo id={infoId} close={() => { this.setState({ isInfoOpen: false }); this._infoJustClosed = true; }} chartInfo={this.props.chartInfo} longDescription={this.props.longDescription} /> } </div> ); } }
JavaScript
class MediaServerResponse { /** * result * Creates a success message returning mediasoup and application related data. * @param {object} data */ static result(data) { return MediaServerResponse.response( 'success', data ); } /** * succeded * Creates a response message with succeded status and no result. */ static succeded() { return MediaServerResponse.response('success', ''); } /** * failed * Creates a response message with failed status and some message. * @param {string} msg */ static failed(msg = '') { return MediaServerResponse.response('failed', msg); } /** * response * Creates the MediaServer response, which shall always * follow this format as established in the documentation * of the MediaServer API. * @param {string} status * @param {object} result */ static response(status, result) { return { status: status, result: result } } }
JavaScript
class FusedChannelData { constructor(atlasX, atlasY) { // allow for resizing this.width = atlasX; this.height = atlasY; // cpu memory buffer with the combined rgba texture atlas for display this.fused = new Uint8Array(this.width * this.height * 4); // webgl texture with the rgba texture atlas for display this.fusedTexture = new THREE.DataTexture(this.fused, this.width, this.height); this.fusedTexture.generateMipmaps = false; this.fusedTexture.magFilter = THREE.LinearFilter; this.fusedTexture.minFilter = THREE.LinearFilter; this.fusedTexture.wrapS = THREE.ClampToEdgeWrapping; this.fusedTexture.wrapT = THREE.ClampToEdgeWrapping; this.maskTexture = new THREE.DataTexture(new Uint8Array(this.width * this.height), this.width, this.height, THREE.LuminanceFormat, THREE.UnsignedByteType); this.maskTexture.generateMipmaps = false; this.maskTexture.magFilter = THREE.LinearFilter; this.maskTexture.minFilter = THREE.LinearFilter; this.maskTexture.wrapS = THREE.ClampToEdgeWrapping; this.maskTexture.wrapT = THREE.ClampToEdgeWrapping; // for single-channel tightly packed array data: this.maskTexture.unpackAlignment = 1; // force single threaded use even if webworkers are available this.useSingleThread = false; // thread control this.fuseWorkersWorking = 0; this.setupWorkers(); } static onFuseComplete() {} static setOnFuseComplete(onFuseComplete) { FusedChannelData.onFuseComplete = onFuseComplete; } cleanup() { if (this.workers && this.workers.length > 0) { for (var i = 0; i < this.workers.length; ++i) { this.workers[i].onmessage = null; this.workers[i].terminate(); } } this.workers = []; this.workersCount = 0; this.fusedTexture.dispose(); this.maskTexture.dispose(); } setupWorkers() { if (this.useSingleThread || !window.Worker) { this.workersCount = 0; return; } // We will break up the image into one piece for each web-worker // can we assert that npx is a perfect multiple of workersCount?? var npx = this.height*this.width; this.workersCount = 4; this.fuseWorkersWorking = 0; // var segmentLength = npx / workersCount; // This is the length of array sent to the worker // var blockSize = this.height / workersCount; // Height of the picture chunk for every worker // Function called when a job is finished var me = this; var onWorkEnded = function (e) { me.fuseWorkersWorking++; // copy e.data.data into fused me.fused.set(e.data.data, Math.floor(e.data.workerindex*(npx/me.workersCount))*4); if (me.fuseWorkersWorking === me.workersCount) { me.fusedData = {data:me.fused, width:me.width, height:me.height}; me.fusedTexture.image = me.fusedData; me.fusedTexture.needsUpdate = true; me.fuseWorkersWorking = 0; if (FusedChannelData.onFuseComplete) { FusedChannelData.onFuseComplete(); } // if there are any fusion requests in queue, execute the next one now. me.isFusing = false; if (me.fuseRequested) { me.fuse(me.fuseRequested, me.fuseMethodRequested, me.channelsDataToFuse); } me.fuseRequested = false; me.channelsDataToFuse = null; } }; this.workers = []; for (var index = 0; index < this.workersCount; index++) { var worker = new FuseWorker(); worker.onmessage = onWorkEnded; worker.onerror = function(e) { alert('Error: Line ' + e.lineno + ' in ' + e.filename + ': ' + e.message); }; this.workers.push(worker); } } // batch is array containing which channels were just loaded // channels is the array containing the channel data. onChannelLoaded(batch, channels) { if (this.useSingleThread || !window.Worker) { return; } var npx = this.height*this.width; // pass channel data to workers for (var i = 0; i < this.workersCount; ++i) { // hand some global data to the worker for (var j = 0; j < batch.length; ++j) { var channelIndex = batch[j]; // chop up the arrays. this is a copy operation! var arr = channels[channelIndex].imgData.data.buffer.slice(Math.floor(i*(npx/this.workersCount)), Math.floor((i+1)*(npx/this.workersCount) - 1)); //console.log(arr.byteLength); var workerData = { msgtype:"channeldata", channelindex: channelIndex, workerindex: i, w: this.width, h: this.height, data: arr }; //console.log("POST channeldata worker " + i + ", channel "+ channelIndex); // hand the data arrays to each worker. they will assume ownership. this.workers[i].postMessage(workerData, [workerData.data]); } } } appendEmptyChannel(name) { // nothing to do yet } fuse(combination, fuseMethod, channels) { fuseMethod = fuseMethod || "m"; // we can fuse if we have any loaded channels that are showing. // actually, we can fuse if no channels are showing (but they are loaded), too. var canFuse = false; for (var i = 0; i < combination.length; ++i) { var c = combination[i]; var idx = c.chIndex; if (channels[idx].loaded) { // set the lut in this fuse combination. c.lut = channels[idx].lut; canFuse = true; //break; } } if (!canFuse) { return; } // If workers are not supported // Perform all calculations in current thread as usual if (this.useSingleThread || !window.Worker) { // console.log("SINGLE THREADED"); this.singleThreadedFuse(combination, channels); if (FusedChannelData.onFuseComplete) { FusedChannelData.onFuseComplete(); } return; } // Keep a queue of a maximum of 1 fuse request at a time. // if 1 fuse is already happening, queue the next one // if 1 is queued, replace it with the latest. if (this.isFusing) { this.fuseRequested = combination; this.channelsDataToFuse = channels; this.fuseMethodRequested = fuseMethod; return; } // We will break up the image into one piece for each web-worker // can we assert that npx is a perfect multiple of workersCount?? this.fuseWorkersWorking = 0; this.isFusing = true; // var segmentLength = npx / workersCount; // This is the length of array sent to the worker // var blockSize = this.height / workersCount; // Height of the picture chunk for every worker // Launching every worker //console.log("BEGIN FUSE"); for (var index = 0; index < this.workersCount; index++) { this.workers[index].postMessage({msgtype: "fuse", combination:combination, fuseMethod:fuseMethod}); } } // sum over [{chIndex, rgbColor}] singleThreadedFuse(combination, channels) { //console.log("BEGIN"); // explore some faster ways to fuse here... var ar,ag,ab,c,r,g,b,channeldata; var x, i, cx, fx, idx; var cl = combination.length; var npx4 = this.height*this.width*4; var npx = this.height*this.width; var fused = this.fused; // init the rgba image for (x = 0; x < npx4; x+=4) { fused[x+0]=0; fused[x+1]=0; fused[x+2]=0; fused[x+3]=255; } var value = 0; for (i = 0; i < cl; ++i) { c = combination[i]; idx = c.chIndex; if (!channels[idx].loaded) { continue; } if (c.rgbColor) { r = c.rgbColor[0]/255.0; g = c.rgbColor[1]/255.0; b = c.rgbColor[2]/255.0; channeldata = channels[idx].imgData.data; for (cx = 0, fx = 0; cx < npx; cx+=1, fx+=4) { value = channeldata[cx]; value = c.lut[value];//this.channels[idx].lut[value]; ar = fused[fx+0]; fused[fx + 0] = Math.max(ar, r * value); ag = fused[fx+1]; fused[fx + 1] = Math.max(ag, g * value); ab = fused[fx+2]; fused[fx + 2] = Math.max(ab, b * value); } } } // clamp the rgba image: ensure not over 255. for (var x = 0; x < npx4; x+=4) { fused[x+0]=Math.min(fused[x+0], 255); fused[x+1]=Math.min(fused[x+1], 255); fused[x+2]=Math.min(fused[x+2], 255); } this.fusedData = {data:this.fused, width:this.width, height:this.height}; this.fusedTexture.image = this.fusedData; this.fusedTexture.needsUpdate = true; //console.log("END"); } // currently only one channel can be selected to participate as a mask setChannelAsMask(idx, channel) { if (!channel || !channel.loaded) { return false; } var datacopy = channel.imgData.data.buffer.slice(0); var maskData = {data:new Uint8Array(datacopy), width:this.width, height:this.height}; this.maskTexture.image = maskData; this.maskTexture.needsUpdate = true; this.maskChannelLoaded = true; this.maskChannelIndex = idx; return true; } }
JavaScript
class ComponentManager { constructor() { this.registry = {}; this.components = []; } /** * Returns a component by name or alias. If no component is found, `undefined` is returned * * @param {String} nameOrAlias The full name or alias of the component * @return {Object} */ getComponent(nameOrAlias) { return _.get(this.registry, nameOrAlias); } /** * Tests whether or not a component exists from a certain name or alias * * @param {String} nameOrAlias * @return {Boolean} */ hasComponent(nameOrAlias) { return !_.isNil(this.getComponent(nameOrAlias)); } /** * Normalizes a component name or alias. If name is provided, name is returned. If * an alias is provdied, it's primary name is returned. If no component is registered * with the provided name/alias, `null` is returned. * * @param {String} nameOrAlias * @return {String} */ normalize(nameOrAlias) { if (this.hasComponent(nameOrAlias)) { return this.getComponent(nameOrAlias).name; } return null; } /** * Applies a function to each component in this manager * * @param {Function} callback */ each(callback) { _.each(this.components, callback); } /** * Registers a component with this component manager. This method returns nothing. * * Names and aliases can use dot notation to represent nested namespaces. * * @param {Component} cmp */ registerComponent(cmp) { if (!(cmp instanceof Component)) { throw new Exception('Only Component instances can be registered with a ComponentManager'); } var { name, alias } = cmp; this.components.push(cmp); _.set(this.registry, name, cmp); // register this component by each aliased name too if (!_.isEmpty(alias)) { _.each(_.castArray(alias), a => { _.set(this.registry, a, cmp); }); } return cmp; } }
JavaScript
class ProductList extends Component{ render(props){ return( <Fragment> {/* Use fragment to render multiple tags of jsx Notes: To use Fragment we have to import Fragment at top*/} {/* Single Product Card Section*/} <div className="card mt-4"> <img className="card-img-top img-fluid" src={process.env.PUBLIC_URL +"/images/"+this.props.prodImage} alt=""/> <div className="card-body"> <h3 className="card-title">{this.props.prodName}</h3> <h4>{this.props.price}</h4> <p className="card-text">{this.props.description}</p> <span className="text-warning">&#9733; &#9733; &#9733; &#9733; &#9734;</span> 4.0 stars </div> </div> </Fragment>); } }
JavaScript
class Shader extends GLShader { /** * Constructs a new Shader. * * @param {Renderer} renderer - The Renderer to use for this shader. * @param {string} vertexSrc - The vertex shader source as an array of strings. * @param {string} fragmentSrc - The fragment shader source as an array of strings. */ constructor(renderer, vertexSrc, fragmentSrc) { super(renderer.gl, checkPrecision(vertexSrc), checkPrecision(fragmentSrc)); /** * Parent Renderer instance. * * @member {Renderer} */ this.renderer = renderer; /** * Binding for when context is restored. * * @member {SignalBinding} */ this._onContextChangeBinding = renderer.onContextChange.add(this.recompile, this); } /** * */ destroy() { this._onContextChangeBinding.detachAll(); this._onContextChangeBinding = null; this.renderer = null; } }
JavaScript
class PGAgent { /** * @param {RLEnvironmentBase} env * @param {number} resolution */ constructor(env, resolution = 20) { this._table = new SoftmaxPolicyGradient(env, resolution) } /** * Returns a score. * @param {RLEnvironmentBase} env * @returns {Array<Array<Array<number>>>} */ get_score(env) { return this._table.toArray() } /** * Returns a action. * @param {RLEnvironmentBase} env * @param {*[]} state * @returns {*[]} */ get_action(env, state) { return this._table.get_action(state) } /** * Update model. * @param {*[]} actions * @param {number} learning_rate */ update(actions, learning_rate) { this._table.update(actions, learning_rate) } }
JavaScript
class ValidateUploadVideoParams extends ServiceBase { /** * Constructor to validate video by user. * * @param {object} params * @param {object} params.current_user * @param {string} [params.video_description]: Video description * @param {string} [params.link]: Link * @param {string/number} [params.per_reply_amount_in_wei]: amount in wei to write reply on video. * * @augments ServiceBase * * @constructor */ constructor(params) { super(); const oThis = this; oThis.currentUser = params.current_user; oThis.videoDescription = params.video_description; oThis.perReplyAmountInWei = params.per_reply_amount_in_wei || 0; oThis.link = params.link; } /** * Async perform. * * @returns {Promise<result>} * @private */ async _asyncPerform() { return responseHelper.successWithData({}); } }
JavaScript
class ClassWithStaticField3{ static baseStaticField = 'base static field'; static anotherBaseStaticField = this.baseStaticField; static baseStaticFieldMethod(){ return 'base static method output'} }
JavaScript
class ClassWithPublicInstanceMethod { publicMethod(){ return 'hello world' } }
JavaScript
class ClassWithGetSet { #msg = 'hello world' get msg() { return this.#msg } set msg(x) { this.#msg = `hello ${x}` } }
JavaScript
class SetStateInComponentDidMount extends React.Component { constructor(props){ super(props), this.state={ stateField: this.props.valueToUseInitially } } componentDidMount() { this.setState({stateField: this.props.valueToUseInOnDOMReady}); } render() { return <div />; } }
JavaScript
class creationSentence { constructor(descriptor = '', focus = '', type = '', additionalSentence = '') { this.descriptor = descriptor; this.focus = focus; this.type = type; this.additionalSentence = additionalSentence; }; }
JavaScript
class creationStat { constructor(value = 10, edge = 0, poolModificator = 0, edgeModificator = 0) { this.value = (Number.isInteger(value)) ? value : 10; this.edge = (Number.isInteger(edge)) ? edge : 0; this.poolModificator = poolModificator; this.edgeModificator = edgeModificator; }; }
JavaScript
class creationStats { constructor(might = new creationStat(), speed = new creationStat(), intellect = new creationStat(), additional = new creationStat()) { this.might = might; this.speed = speed; this.intellect = intellect; this.additional = additional; }; }
JavaScript
class creationSkill { constructor(id = '', name = '', level = 2, skill = {}) { this.id = id; this.name = name; this.level = level; this.skill = skill; }; }
JavaScript
class creationAbility { constructor(id = '', name = '', tier = 0, ability = {}) { this.id = id; this.name = name; this.tier = tier; this.ability = ability; }; }
JavaScript
class creationItem { constructor(id = '', name = '', quantity = 1, item = {}) { this.id = id; this.name = name; this.quantity = quantity; this.item = item; }; }
JavaScript
class creationData { constructor() { this.sentence = new creationSentence(); this.tier = 1; this.effort = 0; this.effortModificator = 0; this.stats = new creationStats(); this.skills = []; this.abilities = []; this.items = []; }; /** * @description Change the specified type of the sentence * @param { String } type * @param { String } sentence * @return {*} * @memberof creationData */ changeSentence(type, sentence) { if (!type in this.sentence) return; this.sentence[type] = sentence; }; /** * @description Set the tier of the creation data * @param { Number } tier * @return {*} * @memberof creationData */ setTier(tier) { if (!Number.isInteger(tier)) return; this.tier = tier; }; /** * @description Change a stat value * @param { String } stat * @param { Number / creationStat } value * @return {*} * @memberof creationData */ changeStat(stat, value) { if (stat === 'effort') { if (!Number.isInteger(value)) return; this.effort = value; } else { value = Object.assign(new creationStat(), value); if (!stat in this.stats) return; this.stats[stat] = value; }; }; /** * @description Add a modificator (either for pool or edge) to a stat * @param { String } stat * @param { String } type - pool or edge * @param { String } modificator * @return {*} * @memberof creationData */ addStatModificator(stat, type, modificator) { if (stat === 'effort') { const current = this.effortModificator, mathExpression = current + modificator; this.effortModificator = mathExpression; } else if (!stat in this.stats) return; if (type === 'pool') { const current = this.stats[stat].poolModificator, mathExpression = current + modificator; this.stats[stat].poolModificator = mathExpression; } else if (type === 'edge') { const current = this.stats[stat].edgeModificator, mathExpression = current + modificator; this.stats[stat].edgeModificator = mathExpression; }; }; /** * @description Check if a skill exists and return it * @param { String } idOrName * @return { Boolean / creationSkill } * @memberof creationData */ skillExists(idOrName) { for (const skill of this.skills) if (skill) if (skill.id == idOrName || skill.name === idOrName) return skill; return false; }; /** * @description Set the level (inability, practiced, trained, specialized) of a skill * @param { String } idOrName * @param { Number } level * @return {*} * @memberof creationData */ setSkillLevel(idOrName, level) { if (!Number.isInteger(level)) return; for (const skill of this.skills) { if (!skill) continue; if (skill.id == idOrName || skill.name === idOrName) { level = parseInt(level); skill.skill.data.skillLevel = skillLevels[level]; skill.skill.data.rollButton.skill = skillLevels[level]; skill.level = level; }; }; }; /** * @description Get the level of a skill * @param { String } idOrName * @return { Boolean / Number } * @memberof creationData */ getSkillLevel(idOrName) { for (const skill of this.skills) if (skill) if (skill.id == idOrName || skill.name === idOrName) return skill.level; return false; }; /** * @description Check if an ability exists and return it * @param { String } idOrName * @return { Boolean / creationAbility } * @memberof creationData */ abilityExists(idOrName) { for (const ability of this.abilities) if (ability) if (ability.id == idOrName || ability.name === idOrName) return ability; return false; }; /** * @description Set the tier of an ability * @param { String } idOrName * @param { Number } tier * @return {*} * @memberof creationData */ setAbilityTier(idOrName, tier) { if (!Number.isInteger(tier)) return; if (parseInt(tier) > 6) return; for (const ability of this.abilities) { if (!ability) continue; if (ability.id == idOrName || ability.name === idOrName) { ability.tier = parseInt(tier); }; }; }; /** * @description Get the tier of an ability * @param { String } idOrName * @return { Boolean / Number } * @memberof creationData */ getAbilityTier(idOrName) { for (const ability of this.abilities) if (ability) if (ability.id == idOrName || ability.name === idOrName) return ability.tier; return false; }; /** * @description Check if an item exists and return it * @param { String } idOrName * @return { Boolean / creationItem } * @memberof creationData */ itemExists(idOrName) { for (const item of this.items) if (item) if (item.id == idOrName || item.name === idOrName) return item; return false; }; /** * @description Set the quantity of an item * @param { String } idOrName * @param { Number } quantity * @return {*} * @memberof creationData */ setItemQuantity(idOrName, quantity) { if (!Number.isInteger(quantity)) return; for (const item of this.items) { if (!item) continue; if (item.id == idOrName || item.name === idOrName) { quantity = parseInt(quantity); if ('quantity' in item.item.data) item.item.data.quantity = quantity; item.quantity = quantity; }; }; }; /** * @description Get the quantity of an item * @param { String } idOrName * @return { Boolean / Number } * @memberof creationData */ getItemQuantity(idOrName) { for (const item of this.items) if (item) if (item.id == idOrName || item.name === idOrName) return item.quantity; return false; }; }
JavaScript
class PASnapshot { constructor() {} /** * Compare records in snapshots for a specified indicator at multiple dates, such as to * identify records included in one snapshot but not the other. * @param {String} sys_id The indicator sys_id. * @param {Number} date1 The date of the first snapshot, in the format yyyymmdd. * @param {Number} date2 The date of the second snapshot, in the format yyyymmdd. * @param {String} type Specifies what data to retrieve. Valid values are: * all1: all records in the first snapshot * all2: all records in the second snapshot * shared: records that are in both snapshots * movedin: records that are in the second snapshot, but not the first * movedout: records that are in the first snapshot, but not the second * * @returns A comma-separated list of sys_id values. * @example var snapshot2 = PASnapshot.getCompareIDs('fb007202d7130100b96d45a3ce6103b4', 20160430, 20160531, 'shared'); * gs.info(snapshot2); */ getCompareIDs(sys_id, date1, date2, type) {} /** * Get the query used to compare records in snapshots for a specified indicator at * multiple dates. * @param {String} sys_id The indicator sys_id. * @param {Number} date1 The date of the first snapshot, in the format yyyymmdd. * @param {Number} date2 The date of the second snapshot, in the format yyyymmdd. * @param {String} type Specifies what data to retrieve. Valid values are: * all1: all records in the first snapshot * all2: all records in the second snapshot * shared: records that are in both snapshots * movedin: records that are in the second snapshot, but not the first * movedout: records that are in the first snapshot, but not the second * * @returns The table, view, and encoded query as a JSON string. * @example var snapshot4 = PASnapshot.getCompareQuery('fb007202d7130100b96d45a3ce6103b4', 20160530, 20160531, 'all1'); * gs.info(snapshot4); * */ getCompareQuery(sys_id, date1, date2, type) {} /** * Get the sys_id values for all records contained in the snapshot for a specified * indicator at the specified date. * @param {String} sys_id The indicator sys_id. * @param {Number} date The date when the snapshot was taken, in the format yyyymmdd. * @returns A comma-separated list of sys_id values. * @example var snapshot1 = PASnapshot.getIDs('fb007202d7130100b96d45a3ce6103b4', 20160530); * gs.info(snapshot1); */ getIDs(sys_id, date) {} /** * Get the query used to generate the snapshot for a specified indicator at the specified * date. * @param {String} sys_id The indicator sys_id. * @param {Number} date The date when the snapshot was taken, in the format yyyymmdd. * @returns The table, view, and encoded query as a JSON string. * @example var snapshot3 = PASnapshot.getQuery('fb007202d7130100b96d45a3ce6103b4', 20160530); * gs.info(snapshot3); */ getQuery(sys_id, date) {} }
JavaScript
class Message { // Formats a message. See //base/format.js for documentation, parameters and examples. static format = format; // Filters all colours from |message| and returns the remainder of the message. static filter(message) { return message.replace(/\{[0-9A-F]{6,8}\}/gi, ''); } // Loads messages from |kMessageDataFile|. Unsafe messages will be considered as fatal errors. static loadMessages() { let messages = JSON.parse(readFile(kMessageDataFile)); if (!messages || typeof messages !== 'object') throw new Error('Unable to read messages from data file: ' + kMessageDataFile); Message.installMessages(messages); } // Reloads the messages when the server is already running. All uppercase-only properties on the // Message function will be removed, after which the format will be reloaded again. static reloadMessages() { // Load the |messages| first, so that any JSON errors won't result in the server being // completely busted, and nothing being sent to anyone at all. const messages = JSON.parse(readFile(kMessageDataFile)); let originalMessageCount = 0; for (const property of Object.getOwnPropertyNames(Message)) { if (property.toUpperCase() !== property) continue; delete Message[property]; originalMessageCount++; } return { originalMessageCount, messageCount: Message.installMessages(messages) }; } // Installs the given |messages| on the Message object. Returns the number of messages that // have been installed on the object. static installMessages(messages) { let messageCount = 0; for (let [ identifier, messageText ] of Object.entries(messages)) { if (!Message.validate(messageText)) throw new Error(`The message named "${identifier}" is not safe for usage.`); messageText = Message.substitutePrefix(messageText, identifier); Object.defineProperty(Message, identifier, { value: messageText, configurable: true, writable: false, }); messageCount++; } return messageCount; } // Substitutes any @-prefixes in |message| with the intended text. This will also affect the color // of the remainder of the message when the prefix uses a color. static substitutePrefix(message, identifier) { if (!message.startsWith('@')) return message; return message.replace(/^@([^\s]+)\s*/, (_, prefixName) => { if (!kMessagePrefixes.hasOwnProperty(prefixName)) throw new Error('The message named "' + identifier + '" uses an invalid prefix: @' + prefixName); return kMessagePrefixes[prefixName]; }); } // Validates that |message| can safely be send to users. static validate(message) { // TODO: Figure out and implement the appropriate safety rules. return typeof message === 'string'; } }
JavaScript
class FormComponentVewModel { constructor() { this.personalDetails = [ { show: true, inputName: 'firstName', label: 'First name', value: 'adam', updatedCss: 'updated', }, { show: true, inputName: 'lastName', label: 'Last name', value: 'chow', updatedCss: 'updated', }, ]; } onInputChange(e, $el, newValue, oldValue) { console.log('onInputChange: ', this); this.personalDetails[0].show = false; this.updateView(); } afterTemplateRender() { console.log('template rendered'); } updateView(opt) { this.APP.render(opt); } getInputAttr(index) { const personalDetail = this.personalDetails[index]; return { id: personalDetail.inputName, name: personalDetail.inputName, }; } }
JavaScript
class MapWithTime { constructor() { this.map = new Map(); } /** * Set the key to value for t = time * @param {any} key * @param {any} value * @param {number} time */ set(key, value, time) { if (!this.map.has(key)) { const arr = [{ value, time }]; this.map.set(key, arr); } else { const arr = this.map.get(key); // check all elements in arr. // If one contains the same value. Rewrite the time // else push new element of value, time let found = false; const updatedArr = arr.map(element => { const { value: eValue } = element; if (eValue !== value) return element; found = true; return { value, time }; }); if (!found) { updatedArr.push({ value, time }); } this.map.set(key, updatedArr); } } /** * Gets the key at time t * @param {any} key * @param {number} time * @return {any} */ get(key, time) { // get biggest time smaller or equal to time if (!this.map.has(key)) return null; const arr = this.map.get(key); let value = null; let biggestTimeSmallerThanTime = null; for (let i = 0; i < arr.length; i++) { const { value: eValue, time: eTime } = arr[i]; if (eTime > time) continue; if (value === null && biggestTimeSmallerThanTime === null) { value = eValue; biggestTimeSmallerThanTime = eTime; } if (eTime >= biggestTimeSmallerThanTime) { value = eValue; biggestTimeSmallerThanTime = eTime; } } return value; } }
JavaScript
class Grid { constructor(canvas, comp) { this.MIN_ZOOM = comp.config.MIN_ZOOM this.MAX_ZOOM = comp.config.MAX_ZOOM this.canvas = canvas this.ctx = canvas.getContext('2d') this.comp = comp this.$p = comp.$props this.data = this.$p.sub this.range = this.$p.range this.id = this.$p.grid_id this.layout = this.$p.layout.grids[this.id] this.interval = this.$p.interval this.cursor = comp.$props.cursor this.offset_x = 0 this.offset_y = 0 this.deltas = 0 // Wheel delta events this.drag = null; this.pinch = null; this.listeners() this.overlays = [] } listeners() { const hamster = Hamster(this.canvas) hamster.wheel((event, delta) => this.mousezoom(-delta * 50, event)) const mc = new Hammer.Manager(this.canvas) mc.add(new Hammer.Pan()) mc.add(new Hammer.Tap()) mc.add(new Hammer.Pinch()) mc.get('pinch').set({ enable: true }) mc.on('panstart', event => { if (this.cursor.scroll_lock) return const tfrm = this.$p.y_transform this.drag = { x: event.center.x + this.offset_x, y: event.center.y + this.offset_y, r: Object.assign({}, this.range), o: tfrm ? (tfrm.offset || 0) : 0, y_r: tfrm && Array.isArray(tfrm.range) ? tfrm.range.slice(0) : undefined, B: this.layout.B, compound: 0, // compounding tally of our x-axis movement from the position where panstart stared from } this.comp.$emit('cursor-changed', { grid_id: this.id, x: event.center.x + this.offset_x, y: event.center.y + this.offset_y }) this.comp.$emit('cursor-locked', true) }) mc.on('panmove', event => { if (this.drag !== null) { this.mousedrag( this.drag.x + event.deltaX, this.drag.y + event.deltaY, ) this.comp.$emit('cursor-changed', { grid_id: this.id, x: event.center.x + this.offset_x, y: event.center.y + this.offset_y }) } }) mc.on('panend', () => { this.drag = null this.comp.$emit('cursor-locked', false) }) mc.on('tap', event => { this.comp.$emit('cursor-changed', { grid_id: this.id, x: event.center.x + this.offset_x, y: event.center.y + this.offset_y }) this.update() }) mc.on('pinchstart', () => { this.pinch = { t: this.range.delta, } }) mc.on('pinchend', () => { this.pinch = null }) mc.on('pinch', event => { if (this.pinch !== null) this.pinchzoom(event.scale) }) window.addEventListener('gesturestart', event => { event.preventDefault() }) window.addEventListener('gesturechange', event => { event.preventDefault() }) window.addEventListener('gestureend', event => { event.preventDefault() }) } mousemove(event) { this.comp.$emit('cursor-changed', { grid_id: this.id, x: event.layerX, y: event.layerY + this.layout.offset }) // TODO: Temp solution, need to implement // a proper way to get the chart el offset this.offset_x = event.layerX - event.pageX + window.scrollX this.offset_y = event.layerY - event.pageY + this.layout.offset + window.scrollY this.propagate('mousemove', event) } mouseout(event) { this.comp.$emit('cursor-changed', {}) this.propagate('mouseout', event) } mouseup(event) { this.drag = null //this.pinch = null this.comp.$emit('cursor-locked', false) this.propagate('mouseup', event) } mousedown(event) { this.propagate('mousedown', event) this.comp.$emit('cursor-locked', true) if (event.defaultPrevented) return this.comp.$emit('custom-event', { event: 'grid-mousedown', args: [this.id] }) } click(event) { this.propagate('click', event) } new_layer(layer) { if (layer.name === 'crosshair') { this.crosshair = layer } else { this.overlays.push(layer) } this.update() } del_layer(id) { this.overlays = this.overlays.filter(x => x.id !== id) this.update() } show_hide_layer(event) { const l = this.overlays.filter(x => x.id === event.id) if (l.length) l[0].display = event.display } update() { // Update reference to the grid // TODO: check what happens if data changes interval this.layout = this.$p.layout.grids[this.id] this.interval = this.$p.interval if (!this.layout) return this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height) this.grid() this.overlays.slice(0) // copy .sort((l1, l2) => l1.z - l2.z) // z-index sorting .forEach(l => { if (!l.display) return this.ctx.save() const r = l.renderer if (r.hasOwnProperty('pre_draw') && typeof r.pre_draw === 'function') r.pre_draw(this.ctx) r.draw(this.ctx) if (r.hasOwnProperty('post_draw') && typeof r.post_draw === 'function') r.post_draw(this.ctx) this.ctx.restore() }) if (this.crosshair) { this.crosshair.renderer.draw(this.ctx) } } // Actually draws the grid (for real) grid() { this.ctx.strokeStyle = this.$p.colors.colorGrid this.ctx.beginPath() const ymax = this.layout.height for (const [x, p] of this.layout.xs) { this.ctx.moveTo(x - 0.5, 0) this.ctx.lineTo(x - 0.5, ymax) } for (const [y, y$] of this.layout.ys) { this.ctx.moveTo(0, y - 0.5) this.ctx.lineTo(this.layout.width, y - 0.5) } this.ctx.stroke() if (this.$p.grid_id) this.upper_border() } upper_border() { this.ctx.strokeStyle = this.$p.colors.colorScale this.ctx.beginPath() this.ctx.moveTo(0, 0.5) this.ctx.lineTo(this.layout.width, 0.5) this.ctx.stroke() } mousezoom(delta, event) { event.originalEvent.preventDefault() event.preventDefault() event.deltaX = event.deltaX || Utils.get_deltaX(event) event.deltaY = event.deltaY || Utils.get_deltaY(event) if (event.deltaX !== 0) { this.trackpad = true if (Math.abs(event.deltaX) >= Math.abs(event.deltaY)) { delta *= 0.1 } this.trackpad_scroll(event) } if (this.trackpad) delta *= 0.032 delta = Utils.smart_wheel(delta) // TODO: mouse zooming is a little jerky, // needs to follow f(mouse_wheel_speed) and // if speed is low, scroll should be slower if (delta < 0 && this.data.length <= this.MIN_ZOOM) return if (delta > 0 && this.data.length > this.MAX_ZOOM) return const k = this.interval / 1000 let diff = delta * k * this.data.length if (event.originalEvent.ctrlKey) { let offset = event.originalEvent.offsetX let diff_x = offset / (this.canvas.width-1) * diff let diff_y = diff - diff_x this.change_range(-diff_x, diff_y) } else { this.change_range(-diff) } } /** * Call w/ updated coords * @param x new! * @param y new! */ mousedrag(x, y) { const ls = !!this.layout.grid.logScale let range = null if (ls && this.drag.y_r) { const dy = this.drag.y - y range = this.drag.y_r.slice(0) range[0] = math.exp((0 - this.drag.B + dy) / this.layout.A) range[1] = math.exp( (this.layout.height - this.drag.B + dy) / this.layout.A) } if (this.$p.y_transform && !this.$p.y_transform.auto && this.drag.y_r) { let d$ = this.layout.$_hi - this.layout.$_lo d$ *= (this.drag.y - y) / this.layout.height const offset = this.drag.o + d$ this.comp.$emit('sidebar-transform', { grid_id: this.id, range: ls ? (range || this.drag.y_r) : [ this.drag.y_r[0] - offset, this.drag.y_r[1] - offset, ] }) } const dt_from_starting_position = this.drag.r.delta * (this.drag.x - x) / this.layout.width const dx = dt_from_starting_position - this.drag.compound this.change_range(dx, dx) this.drag.compound = dt_from_starting_position } pinchzoom(scale) { if (scale > 1 && this.data.length <= this.MIN_ZOOM) return if (scale < 1 && this.data.length > this.MAX_ZOOM) return const t = this.pinch.t const nt = t * 1 / scale const dt = (nt - t) * 0.5 this.change_range(-dt, dt) } trackpad_scroll(event) { const dt = event.deltaX * this.range.delta * 0.011 this.change_range(dt, dt) } change_range(start_diff, end_diff = 0) { // TODO: better way to limit the view. Problem: // when you are at the dead end of the data, // and keep scrolling, // the chart continues to scale down a little. // Solution: I don't know yet if (!this.range || this.data.length < 2) return // TODO: where to do the clamping? in utils? //start_diff = Utils.clamp( // start_diff, //-Infinity, // this.data[l][0] - this.interval * 5.5, // ) //end_diff = Utils.clamp( // end_diff, // this.data[0][0] + this.interval * 5.5, // Infinity //) // TODO: IMPORTANT scrolling is jerky The Problem caused // by the long round trip of 'range-changed' event. // First it propagates up to update layout in Chart.vue, // then it moves back as watch() update. It takes 1-5 ms. // And because the delay is different each time we see // the lag. No smooth movement and it's annoying. // Solution: we could try to calc the layout immediatly // somewhere here. Still will hurt the sidebar & bottombar this.comp.$emit('movement', [start_diff, end_diff]) } // Propagate mouse event to overlays propagate(name, event) { for (const layer of this.overlays) { if (layer.renderer.hasOwnProperty(name) && typeof layer.renderer[name] === 'function') { layer.renderer[name](event) } const mouse = layer.renderer.mouse if (mouse.listeners) { mouse.emit(name, event) } const keys = layer.renderer.keys if (keys && keys.listeners) { keys.emit(name, event) } } } }
JavaScript
class MapMenu extends PolymerElement{constructor(){super();import("./node_modules/@lrnwebcomponents/map-menu/lib/map-menu-container.js")}static get template(){return html` <style> :host { --map-menu-active-color: rgba(0, 0, 0, 0.1); display: block; overflow-y: scroll; position: relative; height: 100%; } #activeIndicator { background: var(--map-menu-active-color); transition: all 0.3s ease-in-out; position: absolute; @apply --map-menu-active-indicator; } map-menu-container { padding: 32px; @apply --map-menu-container; } /* turn default active color if indicator is on */ :host([active-indicator]) map-menu-builder { --map-menu-active-color: transparent; } </style> <div id="itemslist"> <map-menu-container> <div id="activeIndicator"></div> <map-menu-builder id="builder" items="[[items]]" selected="[[selected]]" ></map-menu-builder> </map-menu-container> </div> <smooth-scroll id="smoothScroll"></smooth-scroll> `}static get tag(){return"map-menu"}static get properties(){return{title:{type:String,value:"Content Outline"},data:{type:Array,value:null},/** * Support for JSON Outline Schema manifest format */manifest:{type:Object,notify:!0,observer:"_manifestChanged"},items:{type:Array,value:null,notify:!0},/** * Current selected item. */selected:{type:String,notify:!0},/** * Auto scroll an active element if not in view */autoScroll:{type:Boolean,value:!1},/** * Show active indicator animation */activeIndicator:{type:Boolean,value:!1}}}connectedCallback(){super.connectedCallback();afterNextRender(this,function(){this.addEventListener("link-clicked",this.__linkClickedHandler.bind(this));this.addEventListener("toggle-updated",this.__toggleUpdated.bind(this));this.addEventListener("active-item",this.__activeItemHandler.bind(this));this.addEventListener("map-meu-item-hidden-check",this._mapMeuItemHiddenCheckHandler.bind(this))})}disconnectedCallback(){this.removeEventListener("link-clicked",this.__linkClickedHandler.bind(this));this.removeEventListener("toggle-updated",this.__toggleUpdated.bind(this));this.removeEventListener("active-item",this.__activeItemHandler.bind(this));this.removeEventListener("map-meu-item-hidden-check",this._mapMeuItemHiddenCheckHandler.bind(this));super.disconnectedCallback()}static get observers(){return["_dataChanged(data)"]}__activeItemHandler(e){const target=e.detail;this.refreshActiveChildren(target)}_mapMeuItemHiddenCheckHandler(e){const action=e.detail.action,target=e.detail.target,hiddenChild=e.detail.hiddenChild;if("closed"===action&&!0===hiddenChild){this.__updateActiveIndicator(this._activeItem,200,!0)}else{this.__updateActiveIndicator(this._activeItem,200,!1)}}/** * Set and unset active properties on children * @param {string} activeItem * @param {number} timeoutTime */refreshActiveChildren(activeItem,timeoutTime=200){const oldActiveItem=this._activeItem,newActiveItem=activeItem;if(newActiveItem&&""!==newActiveItem){// set the new active attribute to the item newActiveItem.setAttribute("active",!0);// move the highlight thingy if(this.activeIndicator){this.__updateActiveIndicator(newActiveItem,timeoutTime)}// if auto scroll enabled then scroll element into view if(this.autoScroll){// kick off smooth scroll this.$.smoothScroll.scroll(newActiveItem,{duration:300,scrollElement:this})}}if(oldActiveItem){oldActiveItem.removeAttribute("active");this.__updateActiveIndicator(newActiveItem,timeoutTime)}this._activeItem=newActiveItem}_manifestChanged(newValue,oldValue){if(newValue){this.set("data",newValue.items)}}/** * Set data property */setData(data){this.set("data",[]);this.set("data",data)}/** * Convert data from a linear array * to a nested array for template rendering */_dataChanged(data){const items=[];if(!data)return;// find parents data.forEach(element=>{// find top level parents if(!element.parent){items.push(element)}});// Recursively find and set children items.forEach((item,i)=>{this._setChildren(item,data)});// Update items array this.set("items",[]);this.set("items",items)}/** * Recursively search through a data to find children * of a specified item. * @param {object} item item of an array to search on. Passed by reference. * @param {array} data linear array of the data set. * @return {void} */_setChildren(item,data){// find all children const children=data.filter(d=>item.id===d.parent);item.children=children;if(0<item.children.length){item.children.forEach(child=>{// recursively call itself this._setChildren(child,data)})}}/** * Determine if a menu item has children */__hasChildren(item){return 0<item.children.length}/** * asdf */__linkClickedHandler(e){this.selected=e.detail.id;this.dispatchEvent(new CustomEvent("selected",{bubbles:!0,cancelable:!0,composed:!0,detail:e.detail.id}))}/** * When a user clicks the toggle button to collapse or * expand a submenu, this event gets triggered after * the animation has been triggered */__toggleUpdated(e){const action=e.detail.opened?"opened":"closed",target=e.path[0];if("undefined"!==typeof this._activeItem){this._activeItem.dispatchEvent(new CustomEvent("map-menu-item-hidden-check",{bubbles:!0,cancelable:!0,composed:!0,detail:Object.assign({},{action:action,target:target})}))}}/** * Find out if */__isInViewport(element){const scrollParent=this.__getScrollParent(element);if(!scrollParent)return!1;var elementTop=element.offsetTop,elementBottom=elementTop+element.offsetHeight,viewportTop=scrollParent.offsetTop,viewportBottom=viewportTop+scrollParent.offsetHeight;return elementBottom>viewportTop&&elementTop<viewportBottom}/** * Get scroll parent */__getScrollParent(node){if(null==node){return null}if(node.scrollHeight>node.clientHeight){return node}else{return this.__getScrollParent(node.parentNode)}}/** * Move the highlight widget over active element */__updateActiveIndicator(element,timeoutTime=200,hidden=!1){// run it through to set time just to let stuff set up setTimeout(()=>{const activeIndicator=this.$.activeIndicator,left=element.offsetLeft,bottom=element.offsetBottom,top=element.offsetTop,width=element.offsetWidth,height=!hidden?element.offsetHeight:0;// if the height is zero then make the timeoutTime faster timeoutTime=0<height?timeoutTime:10;activeIndicator.setAttribute("style",`width:${width}px;height:${height}px;top:${top}px;left:${left}px`)},timeoutTime)}/** * Find out if any parents of the item are collapsed */__parentsHidden(node){// get the parent node const parent=node.parentNode;// bail if we have no node to work with if(null==parent)return null;// if we found a submenu check if it is hidden if("MAP-MENU-SUBMENU"===parent.tagName){// if open is set to false then we have // found a hidden parent if(!parent.opened)return!0}// wrap up and exit if we came all the way back to map-menu if("MAP-MENU"===parent.tagName)return!1;// if we got all the way here then we need recursively run this // against the parent node return this.__parentsHidden(parent)}}
JavaScript
class PIXICanvas extends React.Component { /* setHideVertexOptions={this.setHideVertexOptions.bind(this)} setSelectedElementData={this.setSelectedElementData.bind(this)} setRightContentName={this.setRightContentName.bind(this)} setMiddleBottomContentName={this.setMiddleBottomContentName.bind(this)} middleBottomContentName={this.state.middleBottomContentName} selectedElementData={this.state.selectedElementData} setStatusMessage={this.selectedElementData} connector={this.connector} resetShallReRenderD3Canvas={this.resetShallReRenderD3Canvas.bind(this)} shallReRenderD3Canvas={this.state.shallReRenderD3Canvas} makeQuery={this.makeQuery.bind(this)} */ static defaultProps = { setHideVertexOptions: () => console.error("setHideVertexOptions not set",), setSelectedElementData: (selectedData) => console.error("setSelectedElementData not set", selectedData), setRightContentName: (contentName) => console.error("setRightContentName not set", contentName), setMiddleBottomContentName: (contentName) => console.error("setMiddleBottomContentName not set", contentName), middleBottomContentName: null, selectedElementData: null, setStatusMessage: (message) => console.debug("setStatusMessage not set", message), showVertexOptions: (selectedLabel) => console.debug("this.showVertexOptions not set", selectedLabel), connector: null, dataStore: null, resetShallReRenderD3Canvas: () => console.log("resetShallReRenderD3Canvas"), shallReRenderD3Canvas: false, makeQuery: () => console.error("makeQuery not set"), setGraphicsEngine: (graphicsEngine) => console.log("setGraphicsEngine not set", graphicsEngine), getFocusedNodes: () => console.log("getFocusedNodes"), setFocusedNodes: (nodes) => console.error("setFocusedNodes not set", nodes), setDefaultQuery: (query) => console.log("setDefaultQuery not set", query), } static propTypes = { setSelectedElementData: PropTypes.func, setMiddleBottomContentName: PropTypes.func, makeQuery: PropTypes.func, setHideVertexOptions: PropTypes.func, setRightContentName: PropTypes.func, requestBuilder: PropTypes.object, dataStore: PropTypes.object, connector: PropTypes.object, middleBottomContentName: PropTypes.string, showVertexOptions: PropTypes.func, shallReRenderD3Canvas: PropTypes.bool, resetShallReRenderD3Canvas: PropTypes.func, selectedElementData: PropTypes.object, setStatusMessage: PropTypes.func, setGraphicsEngine: PropTypes.func, getFocusedNodes: PropTypes.func, setFocusedNodes: PropTypes.func, setDefaultQuery: PropTypes.func } constructor(props) { super(props); this.state = { // focusedNodes: [], shallReRender: true, // zoomToPoint: [], } } checkAndAddNewData2Simulation() { /* This will add the new data needed for the new simulation.. */ console.log("PIXICanvas checkAndAddNewData2Simulation()", this.props.dataStore.getAllData()); this.graphicsEngine.clearCanvas(); this.graphicsEngine.isRendering = true; this.props.setStatusMessage("Updating the graph..."); const {verticesToRender, edgesToRender} = this.props.dataStore.determineAllDataToRender(); console.log("]=====verticesToRender, edgesToRender", verticesToRender, edgesToRender); // adding this data to force simulation this.forceSimulator.addDataToGraphSimulation(verticesToRender, edgesToRender,); // save the 2d position data to storage. this.props.dataStore.setDataToRender(verticesToRender, edgesToRender); // saves to already rendered data, to find the diff later. this.props.dataStore.setAlreadyRenderedData(verticesToRender, edgesToRender); // this.graphicsEngine.clearCanvas(); // add to simulation. console.log("vertices2RenderPrepared", verticesToRender); // this.onForceSimulationEnd(this.graphicsEngine, this.setStatusMessage.bind(this)); if (this.props.shallReRenderD3Canvas === true) { this.props.resetShallReRenderD3Canvas() } } // shouldComponentUpdate(nextProps, nextState) { // // if (this.graphicsEngine.isRendering) { // return false; // } // const {newVerticesToRender, newEdgesToRender} = this.props.dataStore.getNewDataToRender(); // console.log("===newVerticesToRender", newVerticesToRender, newEdgesToRender) // return newVerticesToRender.length > 0 || newEdgesToRender.length > 0; // // } // shouldComponentUpdate(nextProps) { // console.log("shouldComponentUpdate || nextProps.shallReRenderD3Canvas", nextProps.shallReRenderD3Canvas) // // console.log("=this.state.focusedNodes !== newState.focusedNodes", this.state.focusedNodes !== newState.focusedNodes, this.state.focusedNodes, newState.focusedNodes) // // // if (this.state.focusedNodes !== newState.focusedNodes) { // // this.graphicsEngine.graphicsStore.focusOnElements(this.state.focusedNodes); // // } // // return nextProps.shallReRenderD3Canvas // || this.props.selectedElementData !== nextProps.selectedElementData // // || this.state.focusedNodes !== newState.focusedNodes; // || this.state.shallReRender === true; // } componentDidUpdate() { console.log("componentDidUpdate", this.props.shallReRenderD3Canvas); if (this.props.shallReRenderD3Canvas) { // this.checkAndAddNewData2Simulation(); this.renderPIXICanvas(); } } renderPIXICanvas() { let _this = this; const canvasElem = document.querySelector(".canvas"); const nodeMenuEl = document.querySelector(".nodeMenuContainer"); // const graphCanvasStatus = document.querySelector("#graph-canvas-status"); // remove previous canvas element; while (canvasElem.firstChild) { canvasElem.removeChild(canvasElem.firstChild); } let lastSelectedNodeData = null; if (this.graphicsEngine) { lastSelectedNodeData = this.graphicsEngine.eventStore.lastSelectedNodeData } console.log("canvasElem.offsetWidth,", canvasElem.offsetWidth, canvasElem.offsetHeight) this.settings = new GESettings(canvasElem.offsetWidth, canvasElem.offsetHeight); this.graphicsEngine = new GraphicsEngine(canvasElem, nodeMenuEl, this.settings, this.props.dataStore, this.onElementSelected.bind(this) ) this.props.setGraphicsEngine(this.graphicsEngine); if (lastSelectedNodeData) { // assigning the last selected Node data back this.graphicsEngine.eventStore.lastSelectedNodeData = lastSelectedNodeData; } this.forceSimulator = new GraphSimulator(this.settings, () => { console.log("========on onForceSimulationEnd ") // const {vertices2Render, edges2Render} = _this.getDataToRender(); _this.onForceSimulationEnd(_this.graphicsEngine, _this.setStatusMessage.bind(_this) ); }, 0.05); this.checkAndAddNewData2Simulation(); } componentDidMount() { console.log("componentDidMount", this.props.shallReRenderD3Canvas); this.renderPIXICanvas(); } setStatusMessage(message) { this.props.setStatusMessage(message); } onForceSimulationEnd(graphicsEngine, setStatusMessage) { console.log("onForceSimulationEnd", graphicsEngine, setStatusMessage); graphicsEngine.renderGraphics(); graphicsEngine.isRendering = false; if (graphicsEngine.isFirstLoaded === true) { // center the view only for the first time. graphicsEngine.resetViewport(); graphicsEngine.isFirstLoaded = false; } const lastSelectedNodeData = graphicsEngine.eventStore.lastSelectedNodeData; // const nodeContainer = graphicsEngine.graphicsStore.nodeDataToNodeGfx.get(nodeData.id); console.log("===lastSelectedNodeData", lastSelectedNodeData) const focusedNodes = graphicsEngine.dataStore.getUniqueFocusedNodes(); if (lastSelectedNodeData) { // if last selected node, zoom to that // graphicsEngine.graphicsStore.focusOnElements([lastSelectedNodeData]) graphicsEngine.graphicsStore.focusOnElements(focusedNodes) graphicsEngine.zoom2Node(lastSelectedNodeData.id) graphicsEngine.highlightNodeById(lastSelectedNodeData.id) } else if (focusedNodes.length > 0) { // if if focused nodes exist, zoom to them. // graphicsEngine.zoom2Node(lastSelectedNodeData.id) graphicsEngine.graphicsStore.focusOnElements(focusedNodes) graphicsEngine.zoom2Node(focusedNodes[-0].id) } setStatusMessage("Updated the graph"); // this.graphCanvasStatus.innerHTML = "Updated the data"; // this.graphicsEngine.updatePositions(); // GraphicsEngine.upd } onElementSelected(nodeData) { // if (this.props.middleBottomContentName !== "vertex-options") { if (nodeData) { // this.props.setMiddleBottomContentName('selected-data-overview'); this.props.setSelectedElementData(nodeData); } else { // if data is none, remove the bottom content // this.props.setMiddleBottomContentName(null); this.props.setSelectedElementData(null); } // } } render() { // console.log("PIXICanvas render()", this.props.dataStore.getAllRawVerticesList()) console.log("this.state.focusedNodes", this.props.getFocusedNodes()); return ( <div style={{"width": "100%", "height": "100%"}}> <NodeMenu getFocusedNodes={this.props.getFocusedNodes} setFocusedNodes={this.props.setFocusedNodes} connector={this.props.connector} selectedElementData={this.props.selectedElementData} makeQuery={this.props.makeQuery} graphicsEngine={this.graphicsEngine} setDefaultQuery={this.props.setDefaultQuery} setRightContentName={this.props.setRightContentName} /> <div className="graphContainer canvas"> </div> </div> ) } }
JavaScript
class GCSToBigQueryLoader { /** * Appends data to an existing table. */ async jsonLines(sourceBucketName, sourceFileName, targetDatasetId, targetTableId) { console.log(`>> Starting to load file gs://${sourceBucketName}/${sourceFileName}`); const sourceFile = new Storage() .bucket(sourceBucketName) .file(sourceFileName); // Configure the load job. For full list of options, see: // https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad. const metadata = { sourceFormat: 'NEWLINE_DELIMITED_JSON' }; // Load data from a Google Cloud Storage file into the table const table = new BigQuery() .dataset(targetDatasetId) .table(targetTableId); console.log(` . writing content into ${targetDatasetId}.${targetTableId}`); const [job] = await table.load(sourceFile, metadata); console.log(`>> JOB ${job.id} COMPLETED!`); // Check the job's status for errors const errors = job.status.errors; if (errors && errors.length > 0) { throw errors; } return table; } }
JavaScript
class StripeCheckout extends React.Component { totalPartsPrice() { // eslint-disable-line react/sort-comp let sum = 0; services.map((service) => { const regexedService = service.replace(/\s/g, ''); return regexedService; }) .reduce((acc, curr) => { if (this.props.cart[curr].selected && this.props.part[curr]) { // serviceparts shouls be an array of parts belonging to a service const servicePartKeys = Object.keys(this.props.part[curr]); return servicePartKeys.reduce((accu, currKey) => { if (this.props.part[curr][currKey].valid) { /* if engine oil part, cut price in half*/ /* eslint no-underscore-dangle: ["error", { "allow": ["price_", "__value__"] }] */ const price = this.props.part[curr][currKey] === this.props.part[curr].EngineOil ? parseFloat(this.props.part[curr][currKey].price.__value__ / 2) : parseFloat(this.props.part[curr][currKey].price.__value__); const quantity = parseFloat(this.props.part[curr][currKey].quantity); sum += price * quantity; return sum; } return sum; }, 0); } return acc + 0; }, 0); // if using own parts, return 0 for parts cost if (!this.props.useOwnParts) { return sum; } return 0; } // TODO: 9/10 when you get autodata api, you must extract the right key-value here totalServicesPrice() { // return N/A if any selected service has an unavailable labortime /* const selectedUnavailableServices = Object.keys(this.props.cart).filter((key) => this.props.cart[key].selected && this.props.cart[key].unavailable); if (selectedUnavailableServices && selectedUnavailableServices.length > 0) { return -9; } */ const sumOfLaborTimes = services.map((service) => { const regexedService = service.replace(/\s/g, ''); return regexedService; }) .reduce((acc, curr) => { if (this.props.cart[curr].selected && typeof this.props.cart[curr].laborTime === 'number') { let laborTime = this.props.cart[curr].laborTime; if (laborTime < 0.25) { laborTime = 0.25; } return acc + laborTime; } return acc + 0; }, 0); return sumOfLaborTimes * 67 * 2; } totalPrice() { const subTotal = this.totalServicesPrice() + this.totalPartsPrice(); const taxRate = 0.0875; const tax = subTotal * taxRate; let total = subTotal + tax; if (this.props.voucherCodeStatus) { total -= 15; } return parseFloat(Math.round(total * 1) / 1); } // TODO:redirect to appointments dashboard after successful payment // TODO:add error handling for appointments and quotes mutations // TODO: send a text message and email after successful payment // get token from stripe client => inject amount in to token => send to server to create charge // if stripe charged successfully, create a quote and then create an appointment referencing the quote id of the created quote and then redeem voucher onToken = (token) => { // eslint-disable-line consistent-return console.log(token); const extractedToken = token; extractedToken.amount = this.totalPrice() * 100; // dynamic const stringifiedToken = JSON.stringify(extractedToken); if (this.props.authenticated) { return this.props.client.mutate({ mutation: gql` mutation createStripeCharge($token: JSON!){ createStripeCharge(token: $token){ response } } `, variables: { token: stringifiedToken, }, }).then((stripeChargeResponse) => { // eslint-disable-line consistent-return console.log(stripeChargeResponse.data.createStripeCharge); let voucherCodeStatusBool; if (!this.props.voucherCodeStatus) { voucherCodeStatusBool = false; console.log(`false or null, ${voucherCodeStatusBool}`); } else { voucherCodeStatusBool = this.props.voucherCodeStatus; console.log(`true, ${voucherCodeStatusBool}`); } if (stripeChargeResponse.data.createStripeCharge.response.paid) { this.props.onSuccessfulPayment(); return this.props.client.mutate({ mutation: gql` mutation createUserQuote($token: String!, $motorcycleJSON: JSON!, $cartJSON: JSON!, $partJSON: JSON!, $useOwnParts: Boolean!, $voucherCodeStatus: Boolean!){ createUserQuote(token: $token, motorcycleJSON: $motorcycleJSON, cartJSON: $cartJSON, partJSON: $partJSON, useOwnParts: $useOwnParts, voucherCodeStatus: $voucherCodeStatus){ id fk_user_id motorcycle_json cart_json part_json use_own_parts voucher_code_status created_at updated_at } } `, variables: { token: localStorage.getItem('authToken'), motorcycleJSON: JSON.stringify(this.props.vehicle), cartJSON: JSON.stringify(this.props.cart), partJSON: JSON.stringify(this.props.part), useOwnParts: this.props.useOwnParts, voucherCodeStatus: voucherCodeStatusBool, }, }).then((response) => { console.log(response.data.createUserQuote); this.props.onSaveQuoteClick(); return response.data.createUserQuote.id; }).then((quoteID) => { // eslint-disable-line arrow-body-style return this.props.client.mutate({ mutation: gql` mutation createUserAppointment($token: String!, $motorcycle_address: String!, $contact_number: String!, $note: String!, $estimated_start_time: String!, $estimated_end_time: String!, $status: String!, $fk_quote_id: Int!, $fk_mechanic_id: Int! ){ createUserAppointment(token: $token, motorcycle_address: $motorcycle_address, contact_number: $contact_number, note: $note, estimated_start_time: $estimated_start_time, estimated_end_time: $estimated_end_time, status: $status, fk_quote_id: $fk_quote_id, fk_mechanic_id: $fk_mechanic_id){ id motorcycle_address contact_number note estimated_start_time estimated_end_time status fk_quote_id fk_mechanic_id fk_user_id } } `, variables: { token: localStorage.getItem('authToken'), motorcycle_address: this.props.calendarAppointmentState.motorcycle_address, contact_number: this.props.calendarAppointmentState.contact_number, note: this.props.calendarAppointmentState.note, estimated_start_time: this.props.calendarAppointmentState.selectedTimeSlot.start, estimated_end_time: this.props.calendarAppointmentState.selectedTimeSlot.end, status: 'pending', fk_quote_id: quoteID, fk_mechanic_id: this.props.calendarAppointmentState.selectedTimeSlot.mechanic, }, }) .then((appointmentResult) => { // eslint-disable-line arrow-body-style console.log(appointmentResult.data.createUserAppointment); if (voucherCodeStatusBool) { return this.props.client.mutate({ mutation: gql` mutation redeemVoucher($voucherCode: String!, $user_id: Int!) { redeemVoucher(voucherCode: $voucherCode, user_id: $user_id) { response } } `, variables: { user_id: this.props.userId, voucherCode: localStorage.getItem('voucherCode'), }, }) .then((voucherResult) => { console.log(voucherResult); return this.props.onSuccessfulOrder(); }); } return this.props.onSuccessfulOrder(); }); }); } console.log('else statement reached'); return this.props.onFailedPayment(); }) .catch((err) => { console.log(err); return this.props.onPaymentAppointmentError(); }); } } render() { return ( <StripeCheckoutComp name="motofix" description="Your personal mechanic anywhere" image={'https://res.cloudinary.com/motocloud/image/upload/v1489386170/f6s-logo_p0r60z.png'} token={this.onToken} stripeKey="pk_test_Uq1Klar8ByVNEJGycRrPLA3X" panelLabel="Pay" currency="USD" email={localStorage.getItem('email')} allowRememberMe zipcode > <button className="ui teal button">Pay ${this.totalPrice()} with card</button> </StripeCheckoutComp> ); } }
JavaScript
class FlipSprite extends Sprite { draw(context, sprite, flip, x, y) { var spriteX, spriteY = 0; if (typeof sprite[0] !== "undefined") { [spriteX, spriteY] = sprite; } else { spriteX = sprite; } // Draw to our canvas this.canvas.clear() .flip(flip, this.width / 2, this.height / 2) .sprite(this.image, this.width, this.height, spriteX, spriteY) .reset(); // Draw our canvas to the context context.drawImage(this.canvas.element, x, y); } }
JavaScript
class Warning extends PluginBase { /** * Notify core that read-only mode is supported */ static get isReadOnlySupported() { return true; } /** * Get Toolbox settings * * @public * @returns {string} */ static get toolbox() { return { icon: ToolboxIcon, title: 'Warning', }; } /** * Allow to press Enter inside the Warning * * @public * @returns {boolean} */ static get enableLineBreaks() { return true; } /** * Warning Tool`s styles * * @returns {object} */ get CSS() { return { baseClass: this.api.styles.block, wrapper: 'cdx-warning', title: 'cdx-warning__title', input: this.api.styles.input, message: 'cdx-warning__message', }; } /** * Render plugin`s main Element and fill it with saved data * * @param {WarningData} data — previously saved data * @param {WarningConfig} config — user config for Tool * @param {object} api - Editor.js API * @param {boolean} readOnly - read-only mode flag */ constructor({ data, api, readOnly }) { super({ title: api.i18n.t('title'), }); this.api = api; this.readOnly = readOnly; this.titlePlaceholder = this.api.i18n.t('placeholder'); this.messagePlaceholder = this.api.i18n.t('message'); this.data = { title: data.title || '', message: data.message || '', }; } /** * Create Warning Tool container with inputs * * @returns {Element} */ render() { const container = this._make('div', [this.CSS.baseClass, this.CSS.wrapper]); const title = this._make('div', [this.CSS.input, this.CSS.title], { contentEditable: !this.readOnly, innerHTML: this.data.title, }); const message = this._make('div', [this.CSS.input, this.CSS.message], { contentEditable: !this.readOnly, innerHTML: this.data.message, }); title.dataset.placeholder = this.titlePlaceholder; message.dataset.placeholder = this.messagePlaceholder; title.addEventListener('keydown', this.handleTitleKeydown.bind(this)); message.addEventListener('keydown', this.handleMessageKeydown.bind(this)); container.appendChild(this.titleWrapper); container.appendChild(title); container.appendChild(message); this.titleElement = title; return container; } handleTitleKeydown(event) { if (isBackspaceValid(event, this.titleElement.innerText)) { this.api.blocks.delete(); } } handleMessageKeydown(event) { // BACKSPACE KEYCODE if (event.keyCode === 8) { const sel = window.getSelection(); const range = sel.getRangeAt(0); if (range.startOffset === range.endOffset && range.endOffset === 0) { event.preventDefault(); event.stopPropagation(); this.titleElement.focus(); moveCaretToEnd(this.titleElement); } } } /** * Extract Warning data from Warning Tool element * * @param {HTMLDivElement} warningElement - element to save * @returns {WarningData} */ save(warningElement) { const title = warningElement.querySelector(`.${this.CSS.title}`); const message = warningElement.querySelector(`.${this.CSS.message}`); return Object.assign(this.data, { title: title.innerHTML, message: message.innerHTML, }); } /** * Helper for making Elements with attributes * * @param {string} tagName - new Element tag name * @param {Array|string} classNames - list or name of CSS classname(s) * @param {object} attributes - any attributes * @returns {Element} */ _make(tagName, classNames = null, attributes = {}) { const el = document.createElement(tagName); if (Array.isArray(classNames)) { el.classList.add(...classNames); } else if (classNames) { el.classList.add(classNames); } // eslint-disable-next-line guard-for-in, no-restricted-syntax for (const attrName in attributes) { el[attrName] = attributes[attrName]; } return el; } /** * Sanitizer config for Warning Tool saved data * * @returns {object} */ static get sanitize() { return { title: {}, message: {}, }; } }
JavaScript
class PanelSubAccordion extends Component { state = { panelFirstClassName: panelClassNameDefault, panelSecondClassName: panelClassNameDefault, isFirstOpen: false, isSecondOpen: false, }; toggleFirstSubAccordion = () => { const { isFirstOpen } = this.state; if (isFirstOpen) { this.setState({ panelFirstClassName: panelClassNameDefault, isFirstOpen: !isFirstOpen }) } else { this.setState({ panelFirstClassName: panelClassNameDefault + ' open', isFirstOpen: !isFirstOpen }) } }; toggleSecondSubAccordion = () => { const { isSecondOpen } = this.state; if (isSecondOpen) { this.setState({ panelSecondClassName: panelClassNameDefault, isSecondOpen: !isSecondOpen }) } else { this.setState({ panelSecondClassName: panelClassNameDefault + ' open', isSecondOpen: !isSecondOpen }) } }; render() { const { panelFirstClassName, panelSecondClassName } = this.state; return ( <div className="col-xs-12 col-sm-6"> <div className="ui-sub-section"> <div className="ui-sub-title">Panel sub-accordion</div> <div className={panelFirstClassName}> <div className="panel-heading" onClick={() => this.toggleFirstSubAccordion()}> <h3 className="panel-title">Panel title 1</h3> </div> <div className="panel-body"> <div className="ui-panel-content">Panel Content 1</div> <div className="panel-control"> <div className="wrap-control-group hide-indent-bottom"> <div className="control-group with-indent right"> <button className="btn btn-success btn-inverse btn-create"> <i className="btn-icon fa fa-plus"></i> <span className="btn-text">Create</span> </button> </div> </div> </div> </div> </div> <div className={panelSecondClassName}> <div className="panel-heading" onClick={() => this.toggleSecondSubAccordion()}> <h3 className="panel-title">Panel title 2</h3> </div> <div className="panel-body"> <div className="ui-panel-content">Panel Content 2</div> <div className="panel-control"> <div className="wrap-control-group hide-indent-bottom"> <div className="control-group with-indent right"> <button className="btn btn-success btn-inverse btn-create"> <i className="btn-icon fa fa-plus"></i> <span className="btn-text">Create</span> </button> </div> </div> </div> </div> </div> </div> </div> ); } }
JavaScript
class Product extends ProductBase { /** * (experimental) Creates a Product construct that represents an external product. * * @param scope The parent creating construct (usually `this`). * @param id The construct's name. * @param productArn Product Arn. * @experimental */ static fromProductArn(scope, id, productArn) { const arn = core_1.Stack.of(scope).splitArn(productArn, core_1.ArnFormat.SLASH_RESOURCE_NAME); const productId = arn.resourceName; if (!productId) { throw new Error('Missing required Portfolio ID from Portfolio ARN: ' + productArn); } return new class extends ProductBase { constructor() { super(...arguments); this.productId = productId; this.productArn = productArn; } }(scope, id); } }
JavaScript
class CloudFormationProduct extends Product { /** * @experimental */ constructor(scope, id, props) { super(scope, id); this.validateProductProps(props); const product = new servicecatalog_generated_1.CfnCloudFormationProduct(this, 'Resource', { acceptLanguage: props.messageLanguage, description: props.description, distributor: props.distributor, name: props.productName, owner: props.owner, provisioningArtifactParameters: this.renderProvisioningArtifacts(props), replaceProvisioningArtifacts: props.replaceProductVersionIds, supportDescription: props.supportDescription, supportEmail: props.supportEmail, supportUrl: props.supportUrl, }); this.productArn = core_1.Stack.of(this).formatArn({ service: 'catalog', resource: 'product', resourceName: product.ref, }); this.productId = product.ref; } renderProvisioningArtifacts(props) { return props.productVersions.map(productVersion => { const template = productVersion.cloudFormationTemplate.bind(this); validation_1.InputValidator.validateUrl(this.node.path, 'provisioning template url', template.httpUrl); return { name: productVersion.productVersionName, description: productVersion.description, disableTemplateValidation: productVersion.validateTemplate === false ? true : false, info: { LoadTemplateFromURL: template.httpUrl, }, }; }); } ; validateProductProps(props) { validation_1.InputValidator.validateLength(this.node.path, 'product product name', 1, 100, props.productName); validation_1.InputValidator.validateLength(this.node.path, 'product owner', 1, 8191, props.owner); validation_1.InputValidator.validateLength(this.node.path, 'product description', 0, 8191, props.description); validation_1.InputValidator.validateLength(this.node.path, 'product distributor', 0, 8191, props.distributor); validation_1.InputValidator.validateEmail(this.node.path, 'support email', props.supportEmail); validation_1.InputValidator.validateUrl(this.node.path, 'support url', props.supportUrl); validation_1.InputValidator.validateLength(this.node.path, 'support description', 0, 8191, props.supportDescription); if (props.productVersions.length == 0) { throw new Error(`Invalid product versions for resource ${this.node.path}, must contain at least 1 product version`); } props.productVersions.forEach(productVersion => { validation_1.InputValidator.validateLength(this.node.path, 'provisioning artifact name', 0, 100, productVersion.productVersionName); validation_1.InputValidator.validateLength(this.node.path, 'provisioning artifact description', 0, 8191, productVersion.description); }); } }
JavaScript
class MediatedPagedAsyncRdfIterator extends PagedAsyncRdfIterator_1.PagedAsyncRdfIterator { constructor(firstPageUrl, firstPageData, firstPageMetadata, mediatorRdfDereference, mediatorMetadata, mediatorMetadataExtract, context) { super(firstPageUrl, { autoStart: false }); this.firstPageData = firstPageData; this.firstPageMetadata = firstPageMetadata; this.mediatorRdfDereference = mediatorRdfDereference; this.mediatorMetadata = mediatorMetadata; this.mediatorMetadataExtract = mediatorMetadataExtract; this.context = context; } async getIterator(url, page, onNextPage) { let pageData; // Don't call mediators again if we are on the first page if (!page) { pageData = this.firstPageData; let next; try { next = (await this.firstPageMetadata()).next; } catch (e) { this.emit('error', e); } onNextPage(next); } else { const pageQuads = await this.mediatorRdfDereference .mediate({ context: this.context, url }); const pageMetaSplit = await this.mediatorMetadata.mediate({ context: this.context, pageUrl: pageQuads.pageUrl, quads: pageQuads.quads, triples: pageQuads.triples }); pageData = pageMetaSplit.data; // Don't await, we want to process metadata in the background. this.mediatorMetadataExtract .mediate({ context: this.context, pageUrl: pageQuads.pageUrl, metadata: pageMetaSplit.metadata }) .then((result) => onNextPage(result.metadata.next)).catch((e) => this.emit('error', e)); } return pageData; } }
JavaScript
class Resource { constructor() { this.id = null; this.status = ""; this.key = ""; this.data = null; this.resourceType = ""; this.filesToLoad = []; //list of files to load for this resource } }
JavaScript
class Address extends NGN.EventEmitter { #uri #originalURI #parts = null #protocol = globalThis.location ? globalThis.location.protocol.replace(':', '') : 'http' #username #password #hostname = HOSTNAME #port = null #path = '/' #querystring = null #queryObject = {} #querymode = 'boolean' #hash = null #parsed = false #insecure = false #defaultPort = DEFAULT_PORT #parse = (force = false) => { if (this.#parsed && !force) { return } // If a relative path is defined, apply the current path to the URL if (this.#uri && URL_RELATIVE_PATTERN.test(this.#uri) && globalThis.location && globalThis.location.pathname) { this.#uri = `${globalThis.location.pathname}/${this.#uri}` } const parts = new URL(this.#uri || '/', `${this.#protocol}://${this.#hostname}`) this.#parts = parts this.#protocol = coalesceb(parts.protocol, this.#protocol).replace(':', '') this.#hostname = coalesceb(parts.hostname, this.#hostname) this.#port = coalesceb(parts.port, this.#defaultPort[this.#protocol]) this.#username = coalesceb(parts.username) this.#password = coalesceb(parts.password) this.#path = coalesceb(parts.pathname, '/') this.#querystring = coalesce(parts.search, '').replace(/^\?/, '').trim() this.#hash = coalesceb(parts.hash.replace(/^#+/, '')) this.#queryObject = this.#deserializeQueryParameters(this.#querystring) if (this.#port !== null) { this.#port = forceNumber(this.#port) } this.#parsed = true } // TODO: Modify when private variables no longer need transpilation, // this method can replace alot of boilerplate code when updating attributes. // #update = (key, value) => { // const attr = this[`#${key}`] // if (value !== attr) { // const old = attr // this[`#${key}`] = value // this.emit(`update.${key}`, { old, new: value }) // } // } #deserializeQueryParameters = (paramString = '') => { if (!coalesceb(paramString)) { return new Map() } const PATTERN = /(((?<key>[^&]+)(?:=)(?<value>[^&]+))|(?<bool>[^&]+))[&|\n]?/g return new Map(paramString.trim().match(PATTERN).map(p => { const mode = this.#querymode === 'boolean' ? true : (this.#querymode === 'string' ? '' : null) const values = p.replace('&', '').split('=').concat([mode]) const value = values[1] if (typeof value === 'string') { if (value.trim().toLowerCase() === 'true' || value.trim().toLowerCase() === 'false') { values[1] = forceBoolean(value) } else if (!isNaN(value)) { values[1] = forceNumber(value) } } return values })) } /** * @param {string} [uri=./] * The URI. This can be fully qualified or a relative path. * Examples: `https://domain.com`, `./path/to/my.html` * Produces [RFC 3986](https://tools.ietf.org/html/rfc3986) compliant URL's. * @param {boolean} [insecure=false] * Setting this to `true` will display the #password in plain text instead of a masked format (in toString operations). * Not recommended. */ constructor (uri = null, insecure = false) { super() this.#insecure = forceBoolean(coalesceb(insecure, false)) this.href = uri /** * @property {object} query * Represents the query string as an object. */ this.query = new Proxy({}, { // Proxy query parameters and handle change events. get: (obj, prop) => { !this.#parsed && this.#parse() const result = this.#queryObject.get(prop) switch (this.#querymode) { case 'string': return '' case 'null': return null } return result }, set: (obj, prop, value) => { const oldParamVal = this.#queryObject.get(prop) if (oldParamVal === value) { return false } const old = Object.freeze(Object.fromEntries(this.#queryObject)) switch (this.#querymode) { case 'null': case 'string': if (coalesceb(value) === null) { value = true } break } this.#queryObject.set(prop, value) const newValue = Object.freeze(Object.fromEntries(this.#queryObject)) this.#querystring = Array.from(this.#queryObject).map(items => `${items[0]}=${items[1]}`).join('&') this.emit('query.update', { old, new: newValue, parameter: { name: prop, old: oldParamVal, new: value } }) return true }, has: (obj, prop) => this.#queryObject.has(prop), deleteProperty: (obj, prop) => this.#queryObject.delete(prop), ownKeys: obj => Array.from(this.#queryObject.keys()), defineProperty: (obj, prop, descriptor) => { if (coalesce(descriptor.enumerable, true)) { this.#queryObject.add(prop, coalesce(descriptor.value, descriptor.get)) } }, getOwnPropertyDescriptor: (obj, prop) => { const val = this.#queryObject.get(prop) return { enumerable: val !== undefined, configurable: true, writable: val !== undefined, value: val } } }) /** * @property {string} scheme * Alias for #property. */ this.alias('scheme', this.protocol) } get protocol () { !this.#parsed && this.#parse() return this.#protocol } set protocol (value) { value = /^(.*):?(\/+?.*)?/i.exec(value) if (value !== null && value.length > 0 && value[1] !== this.#protocol) { const old = this.#protocol this.#protocol = value[1] this.emit('update.protocol', { old, new: this.#protocol }) } } get username () { !this.#parsed && this.#parse() return this.#username } set username (value) { if (value.length > 0 && value !== this.#username) { const old = this.#username this.#username = value this.emit('update.username', { old, new: value }) } } get password () { !this.#parsed && this.#parse() if (coalesceb(this.#password) === null) { return null } return this.#insecure ? this.#password : this.#password.replace(/./g, '*') } set password (value) { value = coalesceb(value) if ((value === null || value.length > 0) && value !== this.#password) { let old = coalesce(this.#password, '') if (!this.#insecure) { old = old.replace(/./g, '*') } this.#password = value this.emit('update.password', { old, new: !value ? null : value.replace(/./g, '*') }) } } get hostname () { !this.#parsed && this.#parse() return this.#hostname } set hostname (value) { value = coalesce(value, '').trim().toLowerCase() if (value.length > 0 && value !== this.#hostname) { const old = this.#hostname this.#hostname = value this.emit('update.hostname', { old, new: value }) } } get host () { return `${this.hostname}:${this.port}` } get port () { !this.#parsed && this.#parse() return coalesce(this.#port, this.defaultPort) } set port (value) { value = coalesceb(value, 'default') if (typeof value === 'string') { value = coalesce(this.#defaultPort[value.trim().toLowerCase()], this.defaultPort) } if (value === null || value < 1 || value > 65535) { throw new Error(`"${value}" is an invalid port. Must be a number between 1-65535, "default" to use the protocol's default port, or one of these recognized protocols: ${Object.keys(this.#defaultPort).join(', ')}.`) } if (this.#port !== value) { const old = this.#port this.#port = value this.emit('update.port', { old, new: this.port }) } } /** * A method for resetting the port to the default. * The default value is determined by the protocol. * If the protocol is not recognized, port `80` is used. * This is the equivalent of setting port = `null`. */ resetPort () { this.port = null } get defaultPort () { return coalesce(this.#defaultPort[this.#protocol], this.#protocol !== 'file' ? 80 : null) } get path () { !this.#parsed && this.#parse() return this.#path } set path (value) { value = coalesceb(value, '/') if (value !== this.#path) { const old = this.#path this.#path = value this.emit('update.path', { old, new: value }) } } get querystring () { !this.#parsed && this.#parse() return this.#querystring } set querystring (value) { value = coalesceb(value) || '' if (value !== this.#querystring) { const old = this.#querystring this.#querystring = value this.#queryObject = this.#deserializeQueryParameters(value) this.emit('update.querystring', { old, new: value }) } } get hash () { !this.#parsed && this.#parse() return this.#hash } set hash (value) { value = coalesce(value, '').trim().replace(/^#+/, '') if (value !== this.#hash) { const old = this.#hash this.#hash = value this.emit('update.hash', { old, new: value }) } } /** * @property {string} * The full URL represented by this object. */ get href () { return this.toString() } set href (uri) { this.#originalURI = uri this.#uri = uri this.#parsed = false this.#parse() } get searchParams () { !this.#parsed && this.#parse() return this.#parts.searchParams } get origin () { !this.#parsed && this.#parse() return this.#parts.origin } get search () { !this.#parsed && this.#parse() return this.#parts.search } get local () { !this.#parsed && this.#parse() return localschemes.has(this.hostname.toLowerCase()) } /** * The canonical URL as a string. * @param {object} [cfg] * There are a number of flags that can be used to change * the result of this method. Refer to the following: * * http://username@password:domain.com/path/to/file.html?optionA=a&optionB=b#demo * |__| |______| |______| |________||________________| |_________________| |__| * 1 2 3 4 5 6 7 * * 1. Protocol/Scheme * 1. Username * 1. Password * 1. Domain/Authority * 1. Path * 1. Querystring * 1. Hash * @param {boolean} [cfg.protocol=true] * Generate the protocol/scheme (i.e. `http://`) * @param {boolean} [cfg.hostname = true] * Generate the hostname. * @param {boolean} [cfg.username = false] * Generate the username. Example: `https://[email protected]`. * Setting this to `true` will force the hostname to also be generated, * (even if hostname is set to `false`). * @param {boolean} [cfg.password = false] * Generate the password. Example: `https://username:[email protected]`. * This requires the `username` option to be `true`, and it will only be generated * if a username exists. * @param {boolean} [cfg.forcePort=false] * By default, no port is output in the string for known * protocols/schemes. Set this to `true` to force the * output to contain the port. This is ignored for URL's * with a `file` protocol. * @param {boolean} [cfg.path=true] * Generate the path. * @param {boolean} [cfg.querystring=true] * Generate the query string * @param {boolean} [cfg.shrinkQuerystring=false] * This unique flag can shrink boolean flags by stripping off `true` values and eliminating `false` parameters entirely. For * example, a query string of `?a=true&b=false&c=demo` would become `?a&c=demo`. * This is designed for interacting with API's that use "parameter presence" to toggle/filter responses, * especially when there are many boolean query parameters in the URL. * @param {boolean} [cfg.hash=true] * Generate the hash value. * @param {string} [cfg.queryMode] * Override the default #queryMode ('boolean' by default). * @warning Displaying the password in plain text is a security vulnerability. */ toString (cfg = {}) { !this.#parsed && this.#parse() const uri = new URL(`${this.protocol}://nourl/`) if (coalesce(cfg.path, true)) { uri[uri.pathname ? 'pathname' : 'path'] = this.#path.replace(/\/{2,}|\\{2,}/g, '/') } if (uri.protocol !== 'file') { (cfg.username || cfg.password) && (uri.username = this.#username) cfg.password && this.#password && (uri.password = this.#password) coalesce(cfg.hostname, true) && (uri.hostname = this.#hostname) if (cfg.forcePort || this.port !== this.defaultPort) { uri.port = this.port } if (coalesce(cfg.hash, true) && coalesceb(this.#hash)) { uri.hash = this.#hash } if (coalesce(cfg.querystring, true) && this.queryParameterCount > 0) { const qs = [] for (const [key, value] of this.#queryObject) { // Shrink if (typeof value === 'boolean' && cfg.shrinkQuerystring) { if (value) { qs.push(key) } } else { qs.push(`${key}${value.toString().trim().length === 0 ? '' : '=' + value}`) } } if (qs.length > 0) { uri.search = qs.join('&') } } } let result = uri.toString().replace(/\/\/nourl\//, '') if (!coalesce(cfg.protocol, true)) { result = result.replace(`${this.protocol}://`, '') } if (cfg.forcePort && result.indexOf(`:${this.port}`) < 0) { result = result.replace(uri.hostname, `${uri.hostname}:${this.port}`) } return result } /** * Uses a find/replace strategy to generate a custom URL string. * All variables surrounded in double brackets will be replaced * by the URL equivalent. * * - `{{protocol}}` is the URL protocol, such as `http`, `https`, or `file`. * - `{{separator}}` is what separates the protocol from everything else. Default is `://`. * - `{{username}}` is the username. * - `{{password}}` is the ** plain text ** password. * - `{{hostname}}` is the domain/authority. * - `{{port}}` is the port number, prefixed by `:` (i.e. `:port`). * - `{{path}}` is the path. * - `{{querystring}}` is the querystring prefixed by `?` (i.e. `?a=1&b=2`). * - `{{hash}}` is the hash, prefixed by `#` (i.e. `#myhash`) * @param {string} [template={{protocol}}{{separator}}{{hostname}}{{port}}{{path}}{{querystring}}{{hash}}] * The template to use for constructing the output. * @param {boolean} [encode=true] * URI encode the result string. * @param {string} [separator=://] * The optional separator is defined dynamically, but defaults to `://`. * @returns {string} */ formatString (template = '{{protocol}}{{separator}}{{hostname}}{{port}}{{path}}{{querystring}}{{hash}}', encode = true, separator = '://') { const hasQueryString = this.queryParameterCount > 0 const hasHash = coalesceb(this.#hash) !== null const result = template .replace(/{+protocol}+/gi, coalesce(this.protocol)) .replace(/{+scheme}+/gi, coalesce(this.protocol)) .replace(/{+username}+/gi, coalesce(this.username)) .replace(/{+password}+/gi, coalesce(this.password)) .replace(/{+hostname}+/gi, coalesce(this.hostname)) .replace(/{+host}+/gi, coalesce(this.hostname)) .replace(/{+port}+/gi, this.port === this.defaultPort ? '' : `:${this.port}`) .replace(/{+path}+/gi, this.path) .replace(/{+querystring}+/gi, hasQueryString ? '?' + this.querystring : '') .replace(/{+query}+/gi, hasQueryString ? '?' + this.querystring : '') .replace(/{+hash}+/gi, hasHash ? '#' + this.hash : '') .replace(/{+separator}+/gi, separator) return encode ? encodeURI(result) : result } /** * Map a protocol to a default port. This will override any existing setting. * Common TCP/UDP ports can be found [here](https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers). * @param {string|object} protocol * The protocol, such as `http`. Case insensitive. * This can also be an object, specifying multiple protocol/port combinations. * For example: * ``` * { * snmp: 162, * nntp: 563 * } * ``` * @param {number} port * The port number to assign as the protocol default. */ setDefaultProtocolPort (protocol, port) { if (typeof protocol === 'object') { Object.keys(protocol).forEach(key => this.setDefaultProtocolPort(key, protocol[key])) return } protocol = protocol.trim().toLowerCase() port = forceNumber(port, 10) const old = this.#defaultPort[protocol] this.#defaultPort[protocol] = port if (old !== port) { this.emit('update.defaultport', { protocol, old, new: port }) } } /** * Remove default port mapping for a protocol. * @param {string} protocol * The protocol, such as `http`. Case insensitive. * Multiple protocols can be specified, using multiple arguments `unsetDefaultProtocolPort('http', 'https', 'ssh')` * @warning **DESTRUCTIVE METHOD:** If a default protocol was overridden, unsetting it with this method will not rollback to the prior value. */ removeDefaultProtocolPort () { for (let protocol of arguments) { protocol = protocol.trim().toLowerCase() const old = this.#defaultPort[protocol] if (old) { delete this.#defaultPort[protocol] this.emit('delete.defaultport', { protocol, old }) } } } /** * Determine if accessing a URL is considered a cross origin request or part of the same domain. * @param {string|URI} [alternativeUrl] * Optionally provide an alternative URL to compare the #url with. * @param {boolean} [strictProtocol=false] * Requires the protocol to be the same (not just the hostname). * @returns {boolean} * `true` = same origin * `false` = different origin (cross origin) */ isSameOrigin (url, strictProtocol = false) { !this.#parsed && this.#parse() const parts = typeof url === 'string' ? new URL(url, `${this.#protocol}://${this.#hostname}`) : url const host = coalesceb(parts.hostname, this.#hostname) return host === this.#hostname && (strictProtocol ? (parts.protocol === this.protocol) : true) } get hasQueryParameters () { return this.queryParameterCount > 0 } get queryParameterCount () { return Object.keys(this.query).length } /** * @property {string} [mode=boolean] (boolean, string, null) * Specify how to treat "empty" query parameters. * For example, a query string of `?a=1&b=demo&c` has a * non-descript query parameter (`c`). The presence of * this attribute suggests it could be a boolean (`true`). * It could also be an empty string or a null value. * * The following modes are available: * * 1. `boolean`: Non-descript query parameters are assigned a value of `true` when present. * 1. `string`: Non-descript query parameters are assigned a zero-length (empty) string. * 1. `null`: Non-descript query parameters are assigned a value of `null`. */ set queryMode (mode = 'boolean') { if (mode === null) { NGN.WARN('Query mode was set to a null object. Expected a string (\'null\'). The value was auto-converted to a string, but this method is only supposed to receive string values.') } mode = coalesce(mode, 'null').trim().toLowerCase() if (mode !== this.#querymode) { if (new Set(['boolean', 'string', 'null']).has(mode)) { const old = this.#querymode this.#querymode = mode this.emit('update.querymode', { old, new: mode }) } } } }
JavaScript
class SimpleEraseGesture extends Gesture { constructor(layer) { super(); this.layer_ = layer; this.affectedCells_ = []; } startHover(cell) { if (!cell) return; this.affectedCells_ = this.calcAffectedCells_(cell); this.affectedCells_.forEach(affectedCell => { affectedCell.showHighlight(this.layer_, null); }); } stopHover() { this.affectedCells_.forEach(affectedCell => { affectedCell.hideHighlight(this.layer_); }); this.affectedCells_ = []; } startGesture() { super.startGesture(); this.affectedCells_.forEach(affectedCell => { affectedCell.setLayerContent(this.layer_, null, true); }); } continueGesture(cell) { if (!cell) return; this.affectedCells_ = this.calcAffectedCells_(cell); this.affectedCells_.forEach(affectedCell => { affectedCell.setLayerContent(this.layer_, null, true); }); } stopGesture() { super.stopGesture(); this.affectedCells_ = []; state.opCenter.recordOperationComplete(); } calcAffectedCells_(cell) { const targetCell = this.calculateTargetCell_(cell); if (!targetCell.hasLayerContent(this.layer_)) { return []; } if (targetCell.role != 'primary') { return [cell]; } const targetCellContent = targetCell.getLayerContent(this.layer_); let startCell = targetCell; if (targetCellContent[ck.startCell]) { startCell = state.theMap.cells.get(targetCellContent[ck.startCell]); } const startCellContent = startCell.getLayerContent(this.layer_); let endCell = startCell; if (startCellContent[ck.endCell]) { endCell = state.theMap.cells.get(startCellContent[ck.endCell]); } return startCell.getPrimaryCellsInSquareTo(endCell); } calculateTargetCell_(cell) { if (cell.role == 'horizontal') { const topCell = cell.getNeighbor('top', false); const bottomCell = cell.getNeighbor('bottom', false); if (this.cellsBelongToSameBox_(topCell, bottomCell)) { return topCell; } const leftCell = cell.getNeighbor('left', true); const rightCell = cell.getNeighbor('right', true); if (this.cellsBelongToSameBox_(leftCell, rightCell)) { return leftCell; } } else if (cell.role == 'vertical') { const leftCell = cell.getNeighbor('left', false); const rightCell = cell.getNeighbor('right', false); if (this.cellsBelongToSameBox_(leftCell, rightCell)) { return leftCell; } const topCell = cell.getNeighbor('top', true); const bottomCell = cell.getNeighbor('bottom', true); if (this.cellsBelongToSameBox_(topCell, bottomCell)) { return topCell; } } else if (cell.role == 'corner') { const topLeftCell = cell.getNeighbor('top-left', false); const bottomRightCell = cell.getNeighbor('bottom-right', false); if (this.cellsBelongToSameBox_(topLeftCell, bottomRightCell)) { return topLeftCell; } const leftCell = cell.getNeighbor('left', true); const rightCell = cell.getNeighbor('right', true); if (this.cellsBelongToSameBox_(leftCell, rightCell)) { return leftCell; } const topCell = cell.getNeighbor('top', true); const bottomCell = cell.getNeighbor('bottom', true); if (this.cellsBelongToSameBox_(topCell, bottomCell)) { return topCell; } } // It's either a primary cell or a non-primary cell which does not belong to // another primary cell. return cell; } cellsBelongToSameBox_(topLeftCell, bottomRightCell) { if (!topLeftCell || !bottomRightCell) return false; const content1 = topLeftCell.getLayerContent(this.layer_); const content2 = bottomRightCell.getLayerContent(this.layer_); if (!content1 || !content2) return false; if (!content2[ck.startCell]) return false; return content2[ck.startCell] == topLeftCell.key || content2[ck.startCell] == content1[ck.startCell]; } }
JavaScript
class LoadBalancerConfiguration { /** * Create a LoadBalancerConfiguration. * @property {object} [privateIpAddress] Private IP address. * @property {string} [privateIpAddress.ipAddress] Private IP address bound * to the availability group listener. * @property {string} [privateIpAddress.subnetResourceId] Subnet used to * include private IP. * @property {string} [publicIpAddressResourceId] Resource id of the public * IP. * @property {string} [loadBalancerResourceId] Resource id of the load * balancer. * @property {number} [probePort] Probe port. * @property {array} [sqlVirtualMachineInstances] List of the SQL virtual * machine instance resource id's that are enrolled into the availability * group listener. */ constructor() { } /** * Defines the metadata of LoadBalancerConfiguration * * @returns {object} metadata of LoadBalancerConfiguration * */ mapper() { return { required: false, serializedName: 'LoadBalancerConfiguration', type: { name: 'Composite', className: 'LoadBalancerConfiguration', modelProperties: { privateIpAddress: { required: false, serializedName: 'privateIpAddress', type: { name: 'Composite', className: 'PrivateIPAddress' } }, publicIpAddressResourceId: { required: false, serializedName: 'publicIpAddressResourceId', type: { name: 'String' } }, loadBalancerResourceId: { required: false, serializedName: 'loadBalancerResourceId', type: { name: 'String' } }, probePort: { required: false, serializedName: 'probePort', type: { name: 'Number' } }, sqlVirtualMachineInstances: { required: false, serializedName: 'sqlVirtualMachineInstances', type: { name: 'Sequence', element: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } } } } }; } }
JavaScript
class LRUMap { /** * Instantiate a LRU map of maximum size maxSize. * @param {number} maxSize The maximum size of the map. */ constructor(maxSize) { this._maxSize = maxSize; /** @type {Map.<K,V>} */ this._map = new Map(); /** @type {UniqueLinkedList.<K>} */ this._accessQueue = new UniqueLinkedList(); } /** * The current size of the map. * @type {number} */ get size() { return this._map.size; } /** * Clears the map. */ clear() { this._accessQueue.clear(); return this._map.clear(); } /** * Deletes a key from the map. * @param {K} key The key to delete. * @returns {boolean} Whether an entry was deleted. */ delete(key) { this._accessQueue.remove(key); return this._map.delete(key); } /** * Returns an iterator over key value pairs [k, v]. * @returns {Iterator.<Array>} */ entries() { return this._map.entries(); } /** * Execute a given function for each key value pair in the map. * @param {function(key:K, value:V):*} callback The function to be called. * @param {*} [thisArg] This value will be used as this when executing the function. */ forEach(callback, thisArg) { return this._map.forEach(callback, thisArg); } /** * Return the corresponding value to a specified key. * @param {K} key The key to look for. * @returns {V} The value the key maps to (or undefined if not present). */ get(key) { this._access(key); return this._map.get(key); } /** * Returns true if the specified key is to be found in the map. * @param {K} key The key to look for. * @returns {boolean} True, if the key is in the map, false otherwise. */ has(key) { return this._map.has(key); } /** * Returns an iterator over the keys of the map. * @returns {Iterator.<K>} */ keys() { return this._map.keys(); } /** * Evicts the k least recently used entries from the map. * @param {number} [k] The number of entries to evict (default is 1). */ evict(k=1) { while (k > 0 && this._accessQueue.length > 0) { const oldest = this._accessQueue.shift(); this._map.delete(oldest); --k; } } /** * Marks a key as accessed. * This implicitly makes the key the most recently used key. * @param {K} key The key to mark as accessed. * @private */ _access(key) { /* * Just removing and inserting the key again may take seconds (yes, seconds!). * This is due to the JavaScript Map implementation as illustrated in this benchmark: * https://gist.github.com/paberr/1d916343631c0e42f8311a6f2782f30d * * 100,000 accesses using Map remove/insert: ~4s * 100,000 accesses using optimised version: ~9ms */ this._accessQueue.moveBack(key); } /** * Inserts or replaces a key's value into the map. * If the maxSize of the map is exceeded, the least recently used key is evicted first. * Inserting a key implicitly accesses it. * @param {K} key The key to set. * @param {V} value The associated value. */ set(key, value) { if (this.size >= this._maxSize) { this.evict(); } if (this.size < this._maxSize) { this._map.set(key, value); this._access(key); } } /** * Returns an iterator over the values of the map. * @returns {Iterator.<V>} */ values() { return this._map.values(); } /** * Returns an iterator over key value pairs [k, v]. * @returns {Iterator.<Array>} */ [Symbol.iterator]() { return this._map.entries(); } }
JavaScript
class OpenhabService extends myui.AaimService { constructor() { super(); this._functions.set("queryThings", this.queryThings); this._functions.set("currentState", this.currentState); this._functions.set("setState", this.setState); } queryThings(thing_UID) { /** If the thing_UID is not specified! -> getAllThings() - Method from my_openHAB_Lib - Namespace */ let allThings = openHAB_Object.getAllThings(); /** If the thing_UID is specified! -> getOneSpecificThing() - Method from my_openHAB_Lib - Namespace */ if (thing_UID) { let thing = openHAB_Object.getOneSpecificThing(thing_UID); return thing } else { return allThings; } } currentState(thingLabel, channelLabel) { let values = {}; values = openHAB_Object.getState_value(thingLabel, channelLabel); return values; } setState(thingLabel, channelLabel, values) { openHAB_Object.setState_values (thingLabel, channelLabel, values); } }
JavaScript
class MockReadableStream extends ReadableStreamBuffer { /** * Initializes a new stream that will read the specified data. * @param {string|Buffer} [data] Data to be read. */ constructor(data=null) { super(); this.readCallback = () => true; if (data) { this.put(data); } this.stop(); } /** * Specifies a callback that will be invoked each time the stream reads data. * @param {function} callback Called before the stream reads data. Should return a value indicating whether or not the read should continue. */ registerReadCallback(callback) { this.readCallback = callback; } /** * Overridden to call the mock's read callback. * @private */ _read() { const proceed = this.readCallback.apply(null, arguments); if (proceed) { super._read.apply(this, arguments); } } }
JavaScript
class Darts501Game extends DartsBaseGame { static defaultOptions = { startingPoints: 501, doubleIn: false, doubleOut: true }; /** * Initializes a new instance of the `Darts501Game` class. * * @constructs Darts501Game * @param {Player[]} players An array of players. * @param {Object} [options={}] The options object * * @example * // Creating the new instance * var game = new Darts501Game([new Player({name: 'Player 1'}), new Player({name: 'Player 2'})]); * */ constructor(players, options = {}) { let opts = Object.assign({}, Darts501Game.defaultOptions, options); super(players, opts); } /** * Determines whether option `doubleIn` is set to `true` or `false`. * * @returns {boolean} If `true` it will affect game specific logic. */ get doubleIn() { return this._options.doubleIn; } /** * Determines whether option `doubleOut` is set to `true` or `false`. * * @returns {boolean} If `true` it will affect game specific logic. */ get doubleOut() { return this._options.doubleOut; } /** * Represents single `throw`. * * @param {number} num Number between 0 and 20 plus 25 (bull) * @param {number} [multiplier=1] Multiplier is between 1 and 3 for all of the numbers but 25 (which has only x2 multiplier). * @returns {Throw} `Throw` instance. */ throw(num, multiplier = 1) { let currentThrow = super.throw(num, multiplier); if(this.currentPlayerTotalPoints === 0) { if(this.doubleOut) { if(multiplier === 2) { this.currentPlayer.winner = true; } else { this.invalidateRound(this.currentRound); } } else { this.currentPlayer.winner = true; } } if(this.currentPlayerTotalPoints < 0) { this.invalidateRound(this.currentRound); } if(num && this.doubleIn && (this.currentPlayerTotalPoints + num * multiplier) === this.startingPoints && multiplier !== 2) { this.invalidateThrow(currentThrow); } if(this.doubleOut && this.currentPlayerTotalPoints === 1) { this.invalidateRound(this.currentRound); } return currentThrow; } /** * Calculates points for specific round. * * @param {Round} round Round instance. * @returns {number} Points for round. */ getPointsByRound(round) { return Array.from(round.throws).reduce((prev, curr) => prev + curr.number * curr.multiplier, 0); } /** * @returns {number} Calculates points for `currentRound` */ get currentRoundPoints() { return this.getPointsByRound(this.currentRound); } /** * @returns {number} Calculates total points for `currentPlayer` */ get currentPlayerTotalPoints() { return this.getPointsByPlayer(this.currentPlayer); } /** * Calculates total points for specific player. * * @param {Player} player Instance of the `Player` class. * @returns {number} Total points. */ getPointsByPlayer(player) { return this.startingPoints - this.throwsByPlayer(player).reduce((prev, curr) => prev + curr.number * curr.multiplier, 0); } /** * @returns {Number} Points that game starts with. */ get startingPoints() { return parseInt(this._options.startingPoints, 10); } /** * Calculates step-by-step throws to check-out in the same round. * * @param {number} points Total number of points left. * @param {number} leftThrows Number of throws. * @returns {Array} Array of possible throws as string. */ getCheckoutHint(points, leftThrows = 3) { let results = []; let possibleThrows = []; let singles = []; let doubles = []; let triples = []; let num = 20; let getPoints = (throwInstance) => { return throwInstance.number * throwInstance.multiplier; } while(num > 0) { singles.push(new Throw(num)); doubles.push(new Throw(num, 2)); triples.push(new Throw(num, 3)); num --; } singles.push(new Throw(25)); doubles.push(new Throw(25, 2)); possibleThrows = possibleThrows.concat(singles, doubles, triples); for(let double of doubles) { if(points === getPoints(double)) { results.push([double]); } if(leftThrows > 1) { for(let possibleThrow of possibleThrows) { if(getPoints(possibleThrow) + getPoints(double) === points) { results.push([possibleThrow, double]); } if(leftThrows > 2) { for(let possibleThrow2 of possibleThrows) { if (getPoints(possibleThrow) + getPoints(possibleThrow2) + getPoints(double) === points) { results.push([possibleThrow2, possibleThrow, double]); } } } } } } return results; } }
JavaScript
class Player { // # // # // ### ## ### // # # # ## # // ## ## # // # ## ## // ### /** * Processes the request. * @param {Express.Request} req The request. * @param {Express.Response} res The response. * @returns {Promise} A promise that resolves when the request is complete. */ static async get(req, res) { const queryGameType = req.query.gameType && req.query.gameType.toString() || void 0, querySeason = req.query.season && req.query.season.toString() || void 0, playerId = isNaN(Number.parseInt(req.params.id, 10)) ? 0 : Number.parseInt(req.params.id, 10), postseason = !!req.query.postseason, gameType = !queryGameType || ["TA", "CTF"].indexOf(queryGameType.toUpperCase()) === -1 ? "TA" : queryGameType.toUpperCase(), validSeasonNumbers = await Season.getSeasonNumbers(); let season = isNaN(+querySeason) ? void 0 : Number.parseInt(querySeason, 10); validSeasonNumbers.push(0); if (validSeasonNumbers.indexOf(season) === -1) { season = void 0; } const career = await PlayerModel.getCareer(playerId, season, postseason, gameType); if (career) { const seasonList = career.career.map((c) => c.season).filter((s, index, seasons) => seasons.indexOf(s) === index).sort(), teams = new Teams(); teams.getTeam(career.player.teamId, career.player.teamName, career.player.tag); career.career.forEach((careerSeason) => { teams.getTeam(careerSeason.teamId, careerSeason.teamName, careerSeason.tag); }); career.careerTeams.forEach((team) => { teams.getTeam(team.teamId, team.teamName, team.tag); }); career.opponents.forEach((team) => { teams.getTeam(team.teamId, team.teamName, team.tag); }); career.maps.forEach((map) => { teams.getTeam(map.bestOpponentTeamId, map.bestOpponentTeamName, map.bestOpponentTag); }); const totals = { games: career.career.reduce((sum, stat) => sum + stat.games, 0), captures: career.career.reduce((sum, stat) => sum + stat.captures, 0), pickups: career.career.reduce((sum, stat) => sum + stat.pickups, 0), carrierKills: career.career.reduce((sum, stat) => sum + stat.carrierKills, 0), returns: career.career.reduce((sum, stat) => sum + stat.returns, 0), kills: career.career.reduce((sum, stat) => sum + stat.kills, 0), assists: career.career.reduce((sum, stat) => sum + stat.assists, 0), deaths: career.career.reduce((sum, stat) => sum + stat.deaths, 0), damage: career.career.reduce((sum, stat) => sum + stat.damage, 0), gamesWithDamage: career.career.reduce((sum, stat) => sum + stat.gamesWithDamage, 0), deathsInGamesWithDamage: career.career.reduce((sum, stat) => sum + stat.deathsInGamesWithDamage, 0), overtimePeriods: career.career.reduce((sum, stat) => sum + stat.overtimePeriods, 0), primaries: (career.damage.Impulse || 0) + (career.damage.Cyclone || 0) + (career.damage.Reflex || 0) + (career.damage.Crusher || 0) + (career.damage.Driller || 0) + (career.damage.Flak || 0) + (career.damage.Thunderbolt || 0) + (career.damage.Lancer || 0), secondaries: (career.damage.Falcon || 0) + (career.damage["Missile Pod"] || 0) + (career.damage.Hunter || 0) + (career.damage.Creeper || 0) + (career.damage.Nova || 0) + (career.damage.Devastator || 0) + (career.damage["Time Bomb"] || 0) + (career.damage.Vortex || 0), totalDamage: Object.keys(career.damage).reduce((sum, weapon) => sum + career.damage[weapon], 0) }; res.status(200).send(await Common.page( "", {css: ["/css/player.css"]}, PlayerView.get({ playerId, player: career.player, career: career.career, totals, careerTeams: career.careerTeams, seasonList, season, postseason, gameType, opponents: career.opponents, maps: career.maps, damage: career.damage, teams }), req )); } else { res.status(404).send(await Common.page( "", {css: ["/css/error.css"]}, NotFoundView.get({message: "This player does not exist."}), req )); } } }
JavaScript
class Alignment { constructor(vehicles, desiredNeighborhood) { this._vehicles = vehicles; this._desiredNeighborhood = desiredNeighborhood; } run(vehicle) { let desiredNeighborhood = (this._desiredNeighborhood ? this._desiredNeighborhood : vehicle.size * 2.5); let neighborVehicles = vehicles.filter(v => v != vehicle && distanceSquared(v.position, vehicle.position) < (desiredNeighborhood * desiredNeighborhood) ); if (neighborVehicles.length == 0) return createVector(0, 0); let force = (neighborVehicles .map(v => v.velocity) .reduce((total, next) => total.add(next), createVector(0, 0))) .div(neighborVehicles.length); if (force.mag() > 0) { force.setMag(vehicle.maxSpeed).sub(vehicle.velocity).limit(vehicle.maxForce); } return force; } }
JavaScript
class ListView extends Component { render() { const {markers, selectedLocation, onLocationClick} = this.props return ( <ul className="ListView"> {markers.map( marker => { const selectedClassName = (marker === selectedLocation) ? ' ListView-item-selected' : '' return ( <li key={marker.place} className={`ListView-item${selectedClassName}`}> <button className="ListView-button" type="button" onClick={() => onLocationClick(marker)}> {marker.place} </button> </li> ); })} </ul> ); } }
JavaScript
class Register extends Component { static propTypes = { windowPath: PropTypes.string.isRequired, splitWindowPath: PropTypes.array.isRequired, pushWindowPath: PropTypes.func.isRequired, replaceWindowPath: PropTypes.func.isRequired, fetchDialect2: PropTypes.func.isRequired, computeDialect2: PropTypes.object.isRequired, inviteUser: PropTypes.func.isRequired, computeUserInvite: PropTypes.object.isRequired, computeUser: PropTypes.object.isRequired, computeLogin: PropTypes.object.isRequired, routeParams: PropTypes.object.isRequired }; constructor(props, context) { super(props, context); this.state = { formValue: null, userRequest: null }; // Bind methods to 'this' ['_onRequestSaveForm'].forEach((method => this[method] = this[method].bind(this))); } fetchData(newProps) { if (newProps.routeParams.hasOwnProperty('dialect_path')) { newProps.fetchDialect2(newProps.routeParams.dialect_path); } } // Fetch data on initial render componentDidMount() { this.fetchData(this.props); } // Refetch data on URL change componentWillReceiveProps(nextProps) { let currentWord, nextWord; if (this.state.userRequest != null) { currentWord = ProviderHelpers.getEntry(this.props.computeUserInvite, this.state.userRequest); nextWord = ProviderHelpers.getEntry(nextProps.computeUserInvite, this.state.userRequest); } if (nextProps.windowPath !== this.props.windowPath) { this.fetchData(nextProps); } // 'Redirect' on success if (selectn('success', currentWord) != selectn('success', nextWord) && selectn('success', nextWord) === true) { //nextProps.replaceWindowPath('/' + nextProps.routeParams.theme + selectn('response.path', nextWord).replace('Dictionary', 'learn/words')); } } shouldComponentUpdate(newProps, newState) { switch (true) { case (newProps.windowPath != this.props.windowPath): return true; break; case (newProps.computeDialect2 != this.props.computeDialect2): return true; break; case (newProps.computeUserInvite != this.props.computeUserInvite): return true; break; } return false; } _onRequestSaveForm(currentUser, e) { // Prevent default behaviour e.preventDefault(); let formValue = this.refs["form_user_create"].getValue(); let properties = {}; for (let key in formValue) { if (formValue.hasOwnProperty(key) && key) { if (formValue[key] && formValue[key] != '') { properties[key] = formValue[key]; } } } this.setState({ formValue: properties }) let payload = Object.assign({}, properties, { 'userinfo:groups': [properties['userinfo:groups']] }); // Passed validation if (formValue) { let userRequest = { "entity-type": "document", "type": "FVUserRegistration", "id": selectn('userinfo:email', properties), "properties": payload }; this.props.inviteUser(userRequest, null, null, intl.trans('views.pages.users.register.user_request_success', 'User request submitted successfully!')); this.setState({userRequest}); } else { window.scrollTo(0, 0); } } render() { let FVUserFields = selectn("FVUser", fields); let FVUserOptions = Object.assign({}, selectn("FVUser", options)); console.debug(FVUserFields); console.debug(FVUserOptions); const computeEntities = ProviderHelpers.toJSKeepId([{ 'id': this.state.userRequest, 'entity': this.props.computeUserInvite, }, { 'id': this.props.routeParams.dialect_path, 'entity': this.props.computeDialect2 }]) const computeUserInvite = ProviderHelpers.getEntry(this.props.computeUserInvite, this.state.userRequest); const computeDialect2 = ProviderHelpers.getEntry(this.props.computeDialect2, this.props.routeParams.dialect_path); // Hide requested space field is pre-set. if (selectn("fields.fvuserinfo:requestedSpace", FVUserOptions) && selectn('response.uid', computeDialect2)) { FVUserOptions['fields']['fvuserinfo:requestedSpace']['type'] = 'hidden'; } let dialectGroups = ProviderHelpers.getDialectGroups(selectn('response.contextParameters.acls[0].aces', computeDialect2)); if (dialectGroups.all != null) { FVUserFields['userinfo:groups'] = t.enums(dialectGroups.all); FVUserOptions['fields']['userinfo:groups'] = { label: intl.trans('group', 'Group', 'first') }; } return <PromiseWrapper renderOnError={true} computeEntities={computeEntities}> <h1>{selectn('response.title', computeDialect2)} {intl.trans('register', 'Register', 'first')}</h1> <div className="row" style={{marginTop: '15px'}}> <p style={{padding: '15px'}}>We are working on fixing some problems with registration of new users.<br/>To register in the meantime, please email [email protected].</p> </div> <div className="row" style={{marginTop: '15px', display: 'none'}}> <div className={classNames('col-xs-8', 'col-md-10')}> <form onSubmit={this._onRequestSaveForm.bind(this, this.props.computeLogin)}> <t.form.Form ref="form_user_create" type={t.struct(FVUserFields)} context={selectn('response', computeDialect2)} value={this.state.formValue || {'fvuserinfo:requestedSpace': selectn('response.uid', computeDialect2)}} options={FVUserOptions}/> <div className="form-group"> <button type="submit" className="btn btn-primary">{intl.trans('save', 'Save', 'first')}</button> </div> </form> </div> </div> </PromiseWrapper>; } }
JavaScript
class FileField { constructor(input, options={}, prefix='data-mh-file-field--') { // Configure the options this._options = {} $.config( this._options, { /** * A comma separated list of file types that are accepted. */ 'accept': '', /** * If true then the field will support users dropping files on * to the acceptor to upload them. */ 'allowDrop': false, /** * The initial aspect ratio to apply to the crop region for * an image. */ 'cropAspectRatio': '1.0', /** * The label displayed when the field is not populated and the * user is dragging a file over the page. */ 'dropLabel': 'Drop file here', /** * The image variation to display as the preview in the * image editor (if applicable). */ 'editing': 'editing', /** * The type of file that the field will accept, can be either * 'file' or 'image'. The type does not validate or enforce * the types of files that can be accepted, instead it * provides a hint to the class about how to configure itself * best for the expected type of file. */ 'fileType': 'file', /** * Flag indicating if the aspect ratio of the crop region for * the image should be fixed. */ 'fixCropAspectRatio': false, /** * The label displayed when the field is not populated. */ 'label': 'Select a file...', /** * The image variation to display as the preview in the * viewer (if applicable). */ 'preview': 'preview', /** * The image variation to display as the preview in the * viewer (if applicable). */ 'maxPreviewSize': [480, 480], /** * The URL that any file will be uploaded to. */ 'uploadUrl': '/upload' }, options, input, prefix ) // Convert the crop ratio to a float this._options.cropAspectRatio = parseFloat(this._options.cropAspectRatio) // Convert `maxPreviewSize` option given as an attribute to a list if (typeof this._options.maxPreviewSize === 'string') { const maxPreviewSize = this._options.maxPreviewSize.split(',') this._options.maxPreviewSize = [ parseInt(maxPreviewSize[0], 10), parseInt(maxPreviewSize[1], 10) ] } // Configure the behaviours this._behaviours = {} $.config( this._behaviours, { 'acceptor': 'default', 'asset': 'manhattan', 'assetProp': 'manhattan', 'formData': 'default', 'imageEditor': 'default', 'metadata': 'manhattan', 'uploader': 'default', 'viewer': 'default' }, options, input, prefix ) // The current asset this._asset = null // The state of the field (initializing, accepting, uploading, // viewing). this._state = 'initializing' // Handles to the state components this._acceptor = null this._uploader = null this._viewer = null // Handle to the error message component this._error = null // Domain for related DOM elements this._dom = { 'input': null, 'field': null } // Store a reference to the input element this._dom.input = input } // -- Getters & Setters -- get asset() { return Object.assign(this._asset, {}) } get field() { return this._dom.field } get input() { return this._dom.input } get state() { return this._state } // -- Public methods -- /** * Clear any error from the field. */ clearError() { if (this._error) { this._error.destroy() // Clear the error CSS modifier from the field this.field.classList.remove(this.constructor.css['hasError']) } } /** * Clear the field (transition to the accepting state). */ clear() { const cls = this.constructor // Clear the current state component this._destroyStateComponent() // Clear the asset input value this._asset = null this.input.value = '' // Set up the acceptor const behaviour = this._behaviours.acceptor this._acceptor = cls.behaviours.acceptor[behaviour](this) this._acceptor.init() // Set up event handlers for the acceptor $.listen( this._acceptor.acceptor, { 'accepted': (event) => { this.upload(event.files[0]) } } ) // Set the new state this._state = 'accepting' // Trigger a change event against the input $.dispatch(this.input, 'change') } /** * Remove the file field. */ destroy() { if (this._dom.field) { this._dom.field.parentNode.removeChild(this._dom.field) this._dom.field = null } // Remove the file field reference from the input delete this._dom.input._mhFileField } /** * Return the value of the named property from the asset. */ getAssetProp(name) { const behaviours = this.constructor.behaviours.assetProp const behaviour = this._behaviours.assetProp return behaviours[behaviour](this, 'get', name) } /** * Initialize the file field. */ init() { const cls = this.constructor // Store a reference to the file field instance against the input this._dom.input._mhFileField = this // Store a reference to the file field instance against the input this.input._mhFileField = this // Create the field element this._dom.field = $.create( 'div', { 'class': [ cls.css['field'], cls.css.types[this._options.fileType] ].join(' ') } ) this.input.parentNode.insertBefore( this._dom.field, this.input.nextSibling ) if (this.input.value) { this.populate(JSON.parse(this.input.value)) } else { this.clear() } } /** * Populate the file field (transition to the viewing state). */ populate(asset) { const cls = this.constructor // Clear the current state component this._destroyStateComponent() // Update the asset and input value this._asset = asset this.input.value = JSON.stringify(asset) // Set up the viewer const behaviour = this._behaviours.viewer this._viewer = cls.behaviours.viewer[behaviour](this) this._viewer.init() // Set up event handlers for the viewer $.listen( this._viewer.viewer, { 'download': () => { // Build a link to trigger a file download const a = $.create( 'a', { 'download': '', 'href': this.getAssetProp('downloadURL'), 'target': '_blank' } ) a.click() }, 'edit': () => { const imageEditorBehaviour = this._behaviours.imageEditor const imageEditor = cls.behaviours .imageEditor[imageEditorBehaviour](this) imageEditor.init() imageEditor.show() $.listen( imageEditor.overlay, { 'okay': () => { const {transforms} = imageEditor const {previewDataURI} = imageEditor previewDataURI.then(([dataURI, sizeInfo]) => { // Set the preview image this._viewer.imageURL = dataURI // Set base transforms against the image this.setAssetProp( 'transforms', imageEditor.transforms ) // Set the preview URL this.setAssetProp('previewURL', dataURI) imageEditor.hide() }) }, 'cancel': () => { imageEditor.hide() }, 'hidden': () => { imageEditor.destroy() } } ) }, 'metadata': () => { const metaBehaviour = this._behaviours.metadata const metadata = cls.behaviours .metadata[metaBehaviour](this) metadata.init() metadata.show() $.listen( metadata.overlay, { 'okay': () => { // Apply any metadata changes const {props} = metadata for (let key in props) { this.setAssetProp(key, props[key]) } // Hide the medata overlay metadata.hide() }, 'cancel': () => { metadata.hide() }, 'hidden': () => { metadata.destroy() } } ) }, 'remove': () => { // Clear the asset from the file field this.clear() } } ) // Set the new state this._state = 'viewing' // Trigger a change event against the input $.dispatch(this.input, 'change') } /** * Post an error against the field. */ postError(message) { // Clear any existing error this.clearError() // Post an error against the field this._error = new ErrorMessage(this.field) this._error.init(message) // Add clear handler $.listen( this._error.error, { 'clear': () => { // Clear the error this.clearError() } } ) // Add the error CSS modifier to the field this.field.classList.add(this.constructor.css['hasError']) } /** * Set the value of the named property from the asset. */ setAssetProp(name, value) { const behaviours = this.constructor.behaviours.assetProp const behaviour = this._behaviours.assetProp // Set the asset property behaviours[behaviour](this, 'set', name, value) // Update the input value to reflect the change this.input.value = JSON.stringify(this._asset) // Trigger a change event against the input $.dispatch(this.input, 'change') } /** * Upload a file (transition to the uploading state). */ upload(file) { const cls = this.constructor // Clear the current state component this._destroyStateComponent() // Build the form data const formData = cls.behaviours.formData[this._behaviours.formData]( this, file ) // Set up the uploader this._uploader = cls.behaviours.uploader[this._behaviours.uploader]( this, this._options.uploadUrl, formData ) this._uploader.init() // Set up event handlers for the uploader $.dispatch(this.input, 'uploading') $.listen( this._uploader.uploader, { 'aborted cancelled error': () => { $.dispatch(this.input, 'uploadfailed') this.clear() }, 'uploaded': (event) => { $.dispatch(this.input, 'uploaded') try { // Extract the asset from the response const behaviour = this._behaviours.asset const asset = cls.behaviours.asset[behaviour]( this, event.response ) // Populate the field this.populate(asset) } catch (error) { if (error instanceof ResponseError) { // Clear the field this.clear() // Display the upload error this.postError(error.message) } else { // Re-through any JS error throw error } } } } ) // Set the new state this._state = 'uploading' } // -- Private methods -- /** * Destroy the component for the current state (acceptor, uploader or * viewer). */ _destroyStateComponent() { // Clear any error this.clearError() // Clear the state component switch (this.state) { case 'accepting': this._acceptor.destroy() break case 'uploading': this._uploader.destroy() break case 'viewing': this._viewer.destroy() break // no default } } }
JavaScript
class AccordionHeaderComponent extends Component { className = CLASS_NAMES.header; get ariaDisabled() { return this.args.isDisabled ? 'true' : 'false'; } get ariaExpanded() { return this.args.isExpanded ? 'true' : 'false'; } get ariaLevel() { return this.args.ariaLevel ?? DEFAULT_ARIA_LEVEL; } }
JavaScript
class Segment { constructor() { this.didInit = false; /** * If `true`, the user cannot interact with the segment. */ this.disabled = false; /** * If `true`, the segment buttons will overflow and the user can swipe to see them. */ this.scrollable = false; } valueChanged(value) { if (this.didInit) { this.updateButtons(); this.ionChange.emit({ value }); } } segmentClick(ev) { const selectedButton = ev.target; this.value = selectedButton.value; } connectedCallback() { if (this.value === undefined) { const checked = this.getButtons().find(b => b.checked); if (checked) { this.value = checked.value; } } this.emitStyle(); } componentDidLoad() { this.updateButtons(); this.didInit = true; } emitStyle() { this.ionStyle.emit({ 'segment': true }); } updateButtons() { const value = this.value; for (const button of this.getButtons()) { button.checked = (button.value === value); } } getButtons() { return Array.from(this.el.querySelectorAll('ion-segment-button')); } render() { const mode = getIonMode(this); return (h(Host, { class: Object.assign({}, createColorClasses(this.color), { [mode]: true, 'segment-disabled': this.disabled, 'segment-scrollable': this.scrollable }) })); } static get is() { return "ion-segment"; } static get encapsulation() { return "scoped"; } static get originalStyleUrls() { return { "ios": ["segment.ios.scss"], "md": ["segment.md.scss"] }; } static get styleUrls() { return { "ios": ["segment.ios.css"], "md": ["segment.md.css"] }; } static get properties() { return { "color": { "type": "string", "mutable": false, "complexType": { "original": "Color", "resolved": "string | undefined", "references": { "Color": { "location": "import", "path": "../../interface" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "The color to use from your application's color palette.\nDefault options are: `\"primary\"`, `\"secondary\"`, `\"tertiary\"`, `\"success\"`, `\"warning\"`, `\"danger\"`, `\"light\"`, `\"medium\"`, and `\"dark\"`.\nFor more information on colors, see [theming](/docs/theming/basics)." }, "attribute": "color", "reflect": false }, "disabled": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "If `true`, the user cannot interact with the segment." }, "attribute": "disabled", "reflect": false, "defaultValue": "false" }, "scrollable": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "If `true`, the segment buttons will overflow and the user can swipe to see them." }, "attribute": "scrollable", "reflect": false, "defaultValue": "false" }, "value": { "type": "string", "mutable": true, "complexType": { "original": "string | null", "resolved": "null | string | undefined", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "the value of the segment." }, "attribute": "value", "reflect": false } }; } static get events() { return [{ "method": "ionChange", "name": "ionChange", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "Emitted when the value property has changed." }, "complexType": { "original": "SegmentChangeEventDetail", "resolved": "SegmentChangeEventDetail", "references": { "SegmentChangeEventDetail": { "location": "import", "path": "../../interface" } } } }, { "method": "ionStyle", "name": "ionStyle", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "Emitted when the styles change." }, "complexType": { "original": "StyleEventDetail", "resolved": "StyleEventDetail", "references": { "StyleEventDetail": { "location": "import", "path": "../../interface" } } } }]; } static get elementRef() { return "el"; } static get watchers() { return [{ "propName": "value", "methodName": "valueChanged" }]; } static get listeners() { return [{ "name": "ionSelect", "method": "segmentClick", "target": undefined, "capture": false, "passive": false }]; } }
JavaScript
class DelegateDataService extends DataService { /** *Creates an instance of DelegateDataService. * @param {*} strategyName * @memberof DelegateDataService */ constructor(strategyName) { super(); let self = this; self.delegateStrategyName = strategyName; } /** * Query Currency Exchange Rate Latest Data * * @param {*} currency * @returns * @memberof DelegateDataService */ async queryCurrencyLatestData(currency) { return serviceProvider.getServiceInstance(DataService, this.delegateStrategyName).queryCurrencyLatestData(currency); } /** * Query Currency Exchange Rate Historical Data * * @param {*} currency * @param {*} date * @returns * @memberof DelegateDataService */ async queryCurrencyHistoricalData(currency, date) { return serviceProvider.getServiceInstance(DataService, this.delegateStrategyName).queryCurrencyHistoricalData(currency, date); } }
JavaScript
class DataServiceProvider { constructor() { serviceProvider.registerServiceInstance(DataService, new DefaultDataService()); this.delegateServiceInstanceMap = {}; } /** * Get service instance * * @param {*} strategyName * @returns * @memberof DataServiceProvider */ getService(strategyName) { if (this.delegateServiceInstanceMap[strategyName]) { return this.delegateServiceInstanceMap[strategyName]; } else { this.delegateServiceInstanceMap[strategyName] = new DelegateDataService(strategyName); return this.delegateServiceInstanceMap[strategyName]; } } }
JavaScript
class Service { /** * Constructor. * @param {EdmProvider} edmProvider the entity data model */ constructor(edmProvider) { validateThat('edmProvider', edmProvider).truthy().typeOf('object'); this._edmProvider = edmProvider; this._componentManager = new ComponentManager(); this._formatManager = new FormatManager(); this._bodyParserManager = new FormatManager(); this._basePath = ''; this._loggerFacade = null; this._metadataCache = null; this._metadataETag = null; this._isTrusted = false; } /** * Get the EDM. * @returns {Edm} the EDM */ getEdm() { return this._edmProvider; } /** * Get the FormatManager. * @returns {FormatManager} the format manager */ getFormatManager() { return this._formatManager; } /** * (Creates and) returns an instance of MetadataCache to cache MIME-type and locale specific metadata documents. * @returns {MetadataCache} the metadata cache * @private */ _getMetadataCache() { if (!this._metadataCache) this._metadataCache = new MetadataCache(); return this._metadataCache; } /** * Returns the base path of the current odata service. * The base path is the part of the URL not belonging to OData * which means that this part of the URL will not be interpreted as an OData resource. * * @returns {string} The base path of the url. */ getBasePath() { return this._basePath; } /** * Sets the base path of the URL. * The OData resource URL starts after this base path and will be interpreted as an OData resource. * @param {string} basePath The base path of the url. * @returns {Service} This instance of odata service. * @throws {InternalServerError} if the provided basePath is not null and does not end with '/' */ setBasePath(basePath) { if (basePath !== null && basePath !== undefined && !basePath.endsWith('/')) { throw new InternalServerError("Provided base path must end with '/'"); } this._basePath = basePath; return this; } /** * Registers an event listener by its name. * The names are not arbitrary. Currently only the following events are supported: * General listeners: request, error, debug * CRUD listeners: create, read, update, delete * Batch listeners: batch-start, batch-end, atomicity-group-start, atomicity-group-end * @param {string} eventName The name of the listener. * @param {Object} eventListener the listener to register. * @returns {Service} Instance of this service. */ on(eventName, eventListener) { const supportedEvents = [ 'request', 'error', 'debug', 'create', 'read', 'update', 'delete', 'atomicity-group-start', 'atomicity-group-end', 'batch-start', 'batch-end' ]; if (!supportedEvents.includes(eventName.toLowerCase())) { throw IllegalArgumentError.createForIllegalValue('eventName', ...supportedEvents); } validateThat('eventListener', eventListener).typeOf('function'); this.getComponentManager().use(eventName, eventListener); this.getLogger().debug('Register listener for ' + eventName); return this; } /** * Registers a service component by its name. The names are not arbitrary. They must be used * from /lib/core/ComponentManager.Components. * * @param {string} name The name of the component. * @param {*} component the component to register. * @returns {Service} Instance of this service. */ use(name, component) { this.getLogger().debug('Register component ' + name); this.getComponentManager().use(name, component); return this; } /** * Registers a logger. Occurring log events will be sent to this logger instance. * @param {Logger} logger The root logger * @param {Function} formatter Formatter to be used to convert * @returns {Service} Instance of this service. */ log(logger, formatter) { this._loggerFacade = new LoggerFacade(logger).setFormatter(formatter); this._componentManager.use(ComponentManager.Components.LOGGER, this._loggerFacade); return this; } /** * Returns the component manager. The component manager manages all registered components within the library. * @returns {ComponentManager} The component manager */ getComponentManager() { return this._componentManager; } /** * Sets the supported OData version. * @param {string} version - The supported OData version * @returns {Service} this instance of Service */ setOdataVersion(version) { this._odataVersion = version; this.getLogger().debug('Set OdataVersion to ' + version); return this; } /** * Returns the supported OData version. * @returns {string} the supported OData version */ getOdataVersion() { return this._odataVersion; } /** * Sets the distinct ETag for the metadata document. * @param {string} etag the ETag for the metadata document * @returns {Service} this instance of Service */ setMetadataEtag(etag) { this._metadataETag = etag; return this; } /** * Returns the distinct ETag for the metadata document. * @returns {?string} the ETag for the metadata document */ getMetadataEtag() { return this._metadataETag; } /** * Returns the current logger. * @returns {Logger} The current logger instance */ getLogger() { return this._loggerFacade; } /** * Processes a request. This is the main starting point to use this library. * @param {http.IncomingMessage|PlainHttpRequest} request The request to process. * @param {http.ServerResponse|PlainHttpResponse} response The response to process. * @returns {Promise} a Promise that resolves when the request has been processed successfully */ process(request, response) { const logger = this.getLogger(); logger.path('Entering Service.process()...'); // Check if odata-dabug=json|html is part of the request url const isDebugRequested = IS_DEBUG_REGEXP.test(request.url); const isProfiling = isDebugRequested || IS_PROFILING_REGEXP.test(request.url); logger.debug('Debug mode requested:', isDebugRequested); logger.debug('Profiling requested:', isProfiling); const rootPerformanceMonitor = PerformanceMonitorFactory.getInstance(isProfiling).start(); logger.debug('Start processing request', request.method, request.url); logger.debug('Using OData base path', this.getBasePath()); let context; let errorFromDebugHandler = null; let isDebug = false; return Promise.resolve() .then(() => // This Promise handles the setup of the context object. new Promise(resolve => { const serviceResolutionFn = ServiceResolutions.viaBasePath(this._basePath, Boolean(request._batchContext)); context = new Context(request, response, this, serviceResolutionFn); context.setPerformanceMonitor(rootPerformanceMonitor); context.setLogger(isDebugRequested ? new DebugLogger(logger) : logger); context.getRequest().setService(this); logger.debug('Request headers:', context.getRequest().getHeaders()); resolve(); })) .then(() => // In this Promise, the debug handler gets called and the debug information gets evaluated. new Promise(resolve => { const debugHandler = this.getComponentManager().getComponent('debug'); if (debugHandler) { const next = error => { if (error) { logger.error(error.message); logger.error('Error stacktrace:', ...error.stack.split('\n')); errorFromDebugHandler = error; } else { // Check whether debug mode is allowed by the application (default is false) and // if debug was requested. Only if both are true the request will be executed in debug mode isDebug = context.getRequest().getContract().isDebug() && isDebugRequested; context.getRequest().getContract().enableDebugMode(isDebug); if (isDebug) { context.getResponse().setBuffered(true); } logger.path("Component 'debug' was called; debugging is " + (isDebug ? 'enabled' : 'disabled') + ' for the request'); } resolve(); }; // Debug handler gets called here, with the next callback declared above debugHandler(context.getRequest(), context.getResponse(), next); } else { resolve(); } })) .then(() => { // This Promise handles the creation and execution of the command chain. const options = { context, componentManager: this._componentManager, formatManager: this._formatManager, bodyParserManager: this._bodyParserManager, isDebug: isDebug, isProfiling }; const successCommands = CommandFactory.createForSingleRequest(options); const errorCommands = CommandFactory.createForSingleRequestError(options); const executor = new CommandExecutor(context.getLogger(), rootPerformanceMonitor); return new Promise((resolve, reject) => { const endCallback = err => { rootPerformanceMonitor.stop(); if (err) { logger.error(err.message); logger.error('Error stacktrace:', ...err.stack.split('\n')); reject(err); } else { logger.debug('Request processing finished'); resolve(); } }; executor.execute(successCommands, errorCommands, errorFromDebugHandler, endCallback); }); }); } /** * Sets whether we trust in the data provided by the service implementation. * @param {boolean} isTrusted whether we trust in the data provided by the service implementation * @returns {Service} this instance */ trust(isTrusted) { this._isTrusted = isTrusted; return this; } /** * Returns whether we trust in the data provided by the service implementation. * @returns {boolean} whether we trust in the data provided by the service implementation */ isTrusted() { return this._isTrusted; } /** * Registers a serializer needed to serialize the result data into the response. * @param {RepresentationKind.Kinds} representationKind Kind of request like 'metadata' or 'resource'. * @param {string} contentType Requested content type like 'application/json'. * @param {Function} serializerFunction The function which will be called on serialization. * @param {Function} [parameterCheckFunction] the function to check the format parameters * @returns {Service} This instance of service. */ format(representationKind, contentType, serializerFunction, parameterCheckFunction) { return this._registerDeserializer(this._formatManager, representationKind, contentType, serializerFunction, parameterCheckFunction); } /** * Registers a body parsing facade. This facade is responsible for parsing/deserializing the request payload. * @param {RepresentationKind.Kinds} representationKind The corresponding representation kind * @param {ContentTypeInfo.ContentTypes} contentType The corresponding content type * @param {Function} deserializerFunction The deserialization facade to register * @returns {Service} This instance */ parse(representationKind, contentType, deserializerFunction) { return this._registerDeserializer(this._bodyParserManager, representationKind, contentType, deserializerFunction); } /** * Registers a provided deserializer function at its format manager in dependency of the corresponding * representation kind and content type * * @param {FormatManager} manager The corresponding manager * @param {RepresentationKind.Kinds} representationKind The corresponding representation kind * @param {ContentTypeInfo.ContentTypes} contentType The corresponding content type * @param {Function} parserFunction The parser facade to register * @param {?Function} parameterCheckFunction the function to check the format parameters * @returns {Service} This instance * @private */ _registerDeserializer(manager, representationKind, contentType, parserFunction, parameterCheckFunction) { if (representationKind !== RepresentationKinds.NO_CONTENT) { validateThat('contentType', contentType).notNullNorUndefined().typeOf('string'); } validateThat('serializerFunction', parserFunction).truthy().typeOf('function'); manager.use(representationKind, contentType, parserFunction, parameterCheckFunction); return this; } }
JavaScript
class Reader { /** * @param {object} opts * @param {string} opts.bookDir opts.bookDir, */ constructor(opts = {}) { opts.bookDir = opts.bookDir.replace(/[\.]{2,}/ig, ''); const { bookDir } = opts; this.__opts = opts; this.__readmePath = path.join(bookDir, 'README.md'); this.__summaryPath = path.join(bookDir, 'SUMMARY.md'); this.__cache = { timestamp: 0, list: [], files: { // 'SUMMARY.md' : '', // 'README.md' : '', // 'xxx/xxx.md': '', } } } getSummary() { const reuslt = this.__getFile(this.__summaryPath); return reuslt; } getReadme() { const reuslt = this.__getFile(this.__readmePath); return reuslt; } getPage(pagePath, opts = {}) { pagePath = pagePath.replace(/[\.]{2,}/ig, ''); const filePath = path.join(this.__opts.bookDir, `${pagePath}.md`); let summaryRes = { success: false, data: null }; if (opts && opts.summary === true) { summaryRes = this.getSummary(); } const pageRes = this.__getFile(filePath); const result = { success: pageRes.success, data: { content: pageRes.data, summary: summaryRes.data, } } return result; } __getFile(filePath) { const result = { success: false, content: null, }; if (fs.existsSync(filePath) === true) { if (fs.statSync(filePath).isFile() === true) { result.data = fs.readFileSync(filePath, { encoding: 'utf8' }); result.success = true; } } return result; } }
JavaScript
class CartStoreService extends ApiService { constructor(httpClient, loginService, apiEndpoint = 'cart') { super(httpClient, loginService, apiEndpoint); this.name = 'cartStoreService'; } getLineItemTypes() { return lineItemConstants.types; } getLineItemPriceTypes() { return lineItemConstants.priceTypes; } mapLineItemTypeToPriceType(itemType) { const lineItemTypes = this.getLineItemTypes(); const priceTypes = this.getLineItemPriceTypes(); const mapTypes = { [lineItemTypes.PRODUCT]: priceTypes.QUANTITY, [lineItemTypes.CUSTOM]: priceTypes.QUANTITY, [lineItemTypes.CREDIT]: priceTypes.ABSOLUTE }; return mapTypes[itemType]; } createCart(salesChannelId, additionalParams = {}, additionalHeaders = {}) { const route = `_proxy/store-api/${salesChannelId}/v1/checkout/cart`; const headers = this.getBasicHeaders(additionalHeaders); return this.httpClient.get(route, { additionalParams, headers }); } getCart(salesChannelId, contextToken, additionalParams = {}, additionalHeaders = {}) { const route = `_proxy/store-api/${salesChannelId}/v1/checkout/cart`; const headers = { ...this.getBasicHeaders(additionalHeaders), 'sw-context-token': contextToken }; return this.httpClient.get(route, { additionalParams, headers }); } cancelCart(salesChannelId, contextToken, additionalParams = {}, additionalHeaders = {}) { const route = `_proxy/store-api/${salesChannelId}/v1/checkout/cart`; const headers = { ...this.getBasicHeaders(additionalHeaders), 'sw-context-token': contextToken }; return this.httpClient.delete(route, { additionalParams, headers }); } removeLineItems( salesChannelId, contextToken, lineItemKeys, additionalParams = {}, additionalHeaders = {} ) { const route = `_proxy/store-api/${salesChannelId}/v1/checkout/cart/line-item`; const headers = { ...this.getBasicHeaders(additionalHeaders), 'sw-context-token': contextToken }; return this.httpClient.delete(route, { additionalParams, headers, data: { ids: lineItemKeys } }); } getRouteForItem(id, salesChannelId) { return `_proxy/store-api/${salesChannelId}/v1/checkout/cart/line-item`; } getPayloadForItem(item, salesChannelId, isNewProductItem, id) { const dummyPrice = deepCopyObject(item.priceDefinition); dummyPrice.taxRules = item.priceDefinition.taxRules; dummyPrice.quantity = item.quantity; dummyPrice.type = this.mapLineItemTypeToPriceType(item.type); return { items: [ { id: id, referencedId: id, label: item.label, quantity: item.quantity, type: item.type, description: item.description, priceDefinition: dummyPrice, stackable: true, removable: true, salesChannelId } ] }; } saveLineItem( salesChannelId, contextToken, item, additionalParams = {}, additionalHeaders = {} ) { const isNewProductItem = item._isNew && item.type === this.getLineItemTypes().PRODUCT; const id = item.identifier || item.id || utils.createId(); const route = this.getRouteForItem(id, salesChannelId, isNewProductItem); const headers = { ...this.getBasicHeaders(additionalHeaders), 'sw-context-token': contextToken }; const payload = this.getPayloadForItem(item, salesChannelId, isNewProductItem, id); if (item._isNew) { return this.httpClient.post(route, payload, { additionalParams, headers }); } return this.httpClient.patch(route, payload, { additionalParams, headers }); } addPromotionCode( salesChannelId, contextToken, code, additionalParams = {}, additionalHeaders = {} ) { const route = `_proxy/store-api/${salesChannelId}/v1/checkout/cart/line-item`; const headers = { ...this.getBasicHeaders(additionalHeaders), 'sw-context-token': contextToken }; const payload = { items: [ { type: 'promotion', referencedId: code } ] }; return this.httpClient.post(route, payload, { additionalParams, headers }); } modifyShippingCosts(salesChannelId, contextToken, shippingCosts, additionalHeaders, additionalParams = {},) { const route = '_proxy/modify-shipping-costs'; const headers = { ...this.getBasicHeaders(additionalHeaders), 'sw-context-token': contextToken }; return this.httpClient.patch(route, { salesChannelId, shippingCosts }, { additionalParams, headers }); } disableAutomaticPromotions(contextToken, additionalParams = {}, additionalHeaders = {}) { const route = '_proxy/disable-automatic-promotions'; const headers = { ...this.getBasicHeaders(additionalHeaders), 'sw-context-token': contextToken }; return this.httpClient.patch(route, {}, { additionalParams, headers }); } enableAutomaticPromotions(contextToken, additionalParams = {}, additionalHeaders = {}) { const route = '_proxy/enable-automatic-promotions'; const headers = { ...this.getBasicHeaders(additionalHeaders), 'sw-context-token': contextToken }; return this.httpClient.patch(route, {}, { additionalParams, headers }); } }
JavaScript
class DetBlog extends Component { componentDidMount() { // window.location.reload(); if (this.props.match.params.handle) { this.props.getShopingByHandle(this.props.match.params.handle); } } actualiza(){ window.location.reload() } componentWillReceiveProps(nextProps) { if (nextProps.shopingfile.shopingfile === null && this.props.shopingfile.loading) { this.props.history.push('/not-found'); } } render() { // window.location.reload(); const { shopingfile, loading } = this.props.shopingfile; let shofileContent; // let texto = JSON.stringify(shopingfile.description); // console.log(texto.length) // // let texto2 = ( // currentTodos.map(l1 => ( // console.log(texto) // )) //) if (shopingfile === null || loading) { shofileContent = <Spinner />; //window.location.reload(); } else { shofileContent = ( <div> <div > <div className="col-md-6"> <Link to="/blog" className="btn btn-info btn-light mb-3 float-left light-blue darken-2"> Ir a Blog </Link> </div> <section className="view intro-video"> <div className="hm-gradient"> <div className="full-bg-img"> <div className="container flex-center"> <div className="row pt-5 mt-3"> <div className="col-lg-12 wow fadeIn"> <h3 className="align center">{shopingfile.name}</h3> {shopingfile.popular && <div className="embed-responsive embed-responsive-16by9 wow fadeInRight"> <iframe class="embed-responsive-item" src={shopingfile.imageUrls} allowfullscreen></iframe> </div> || <img className="img-fluid" src={shopingfile.imageUrls}/> } </div> <div className="col-lg-12 wow fadeIn mb-5 text-center text-lg-left"> <div className="black-text"> <br> </br> <p className="text-justify" style={{fontSize:"20px"}}>{shopingfile.description} . . .</p> </div> </div> </div> </div> </div> </div> </section> </div> </div> ) } return ( <div > <div > <div className="col-mb-8"> {shofileContent} </div> <div className="col-mb-8"> <div className="container flex-center"> <button class="btn btn-info btn-block mt-4 01579b light-blue darken-2" onClick={this.actualiza} >Comentar en Facebook</button> <div className="row pt-5 mt-3"> <div className="fb-comments" data-href="https://sfsystemfactura.000webhostapp.com" data-numposts="5" data-width="100%" data-order-by="reverse-time" ></div> </div> </div> </div> </div> </div> ); } }
JavaScript
class ValidCheck extends BaseCheck { static get task () { return { ruleSetId: fakeValidRuleSetId } } get prefix () { return `${super.prefix}-test` } async buildLines () { return [ this.buildLine(fakeLineData), fakePermitHeadingLine, fakeContactHeadingLine ] } }
JavaScript
class InvalidCheck extends BaseCheck { static get task () { return { ruleSetId: fakeInvalidRuleSetId } } }
JavaScript
class ProofsModule { constructor(proofService, messageSender, credentialService, ledgerService) { this.proofService = proofService; this.messageSender = messageSender; this.credentialService = credentialService; this.ledgerService = ledgerService; } /** * This method is used to send proof request * @param connection : Connection to which issuer wants to issue a credential * @param ProofRequestTemplate : Template used to send proof request */ sendProofRequest(connection, proofRequestTemplate) { return __awaiter(this, void 0, void 0, function* () { const proofOfferMessage = yield this.proofService.createRequest(connection, proofRequestTemplate); const outboundMessage = helpers_1.createOutboundMessage(connection, proofOfferMessage); yield this.messageSender.sendMessage(outboundMessage); }); } /** * This method is used to send Presentation of proof * @param proofRequestMessage */ sendPresentation(connection, proofRequestMessage) { return __awaiter(this, void 0, void 0, function* () { const credentials = yield this.credentialService.getCredentialsForProofReq(proofRequestMessage); console.log("Credentials for proof:" + JSON.stringify(credentials)); const presentation = yield this.proofService.createPresentation(proofRequestMessage, credentials, this.ledgerService); console.log("Prrof req:" + JSON.stringify(presentation)); const outboundMessage = helpers_1.createOutboundMessage(connection, presentation); yield this.messageSender.sendMessage(outboundMessage); }); } verifyPresentation(connection, proofRequestMessage, presentProofMessage) { return __awaiter(this, void 0, void 0, function* () { const credentials = yield this.credentialService.getCredentialsForProofReq(proofRequestMessage); console.log("Credentials for proof:" + JSON.stringify(credentials)); const result = yield this.proofService.verifyPresentation(proofRequestMessage, presentProofMessage, credentials, this.ledgerService); console.log("PROOF MODULE:Result:" + result); // console.log("Prrof req:" + JSON.stringify(presentation)); // const outboundMessage = createOutboundMessage(connection, presentation); // await this.messageSender.sendMessage(outboundMessage); }); } proverCreateMasterSecret(masterSecret) { return __awaiter(this, void 0, void 0, function* () { return yield this.proofService.proverCreateMasterSecret(masterSecret); }); } getProofs() { return __awaiter(this, void 0, void 0, function* () { return this.proofService.getAll(); }); } find(id) { return __awaiter(this, void 0, void 0, function* () { return this.proofService.find(id); }); } }
JavaScript
class ValuesSourceBase { // eslint-disable-next-line require-jsdoc constructor(valueSrcType, refUrl, name, field) { if (isEmpty(valueSrcType)) throw new Error('ValuesSourceBase `valueSrcType` cannot be empty'); this._name = name; this._valueSrcType = valueSrcType; this._refUrl = refUrl; this._body = {}; this._opts = this._body[valueSrcType] = {}; if (!isNil(field)) this._opts.field = field; } /** * Field to use for this source. * * @param {string} field a valid field name * @returns {ValuesSourceBase} returns `this` so that calls can be chained */ field(field) { this._opts.field = field; return this; } /** * Script to use for this source. * * @param {Script|Object|string} script * @returns {ValuesSourceBase} returns `this` so that calls can be chained * @throws {TypeError} If `script` is not an instance of `Script` */ script(script) { this._opts.script = script; return this; } /** * Specifies the type of values produced by this source, e.g. `string` or * `date`. * * @param {string} valueType * @returns {ValuesSourceBase} returns `this` so that calls can be chained */ valueType(valueType) { this._opts.value_type = valueType; return this; } /** * Order specifies the order in the values produced by this source. It can * be either `asc` or `desc`. * * @param {string} order The `order` option can have the following values. * `asc`, `desc` to sort in ascending, descending order respectively. * @returns {ValuesSourceBase} returns `this` so that calls can be chained. */ order(order) { if (isNil(order)) invalidOrderParam(order, this._refUrl); const orderLower = order.toLowerCase(); if (orderLower !== 'asc' && orderLower !== 'desc') { invalidOrderParam(order, this._refUrl); } this._opts.order = orderLower; return this; } /** * Missing specifies the value to use when the source finds a missing value * in a document. * * Note: This option was deprecated in * [Elasticsearch v6](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/breaking-changes-6.0.html#_literal_missing_literal_is_deprecated_in_the_literal_composite_literal_aggregation). * From 6.4 and later, use `missing_bucket` instead. * * @param {string|number} value * @returns {ValuesSourceBase} returns `this` so that calls can be chained */ missing(value) { this._opts.missing = value; return this; } /** * Specifies whether to include documents without a value for a given source * in the response. Defaults to `false` (not included). * * Note: This method is incompatible with elasticsearch 6.3 and older. * Use it only with elasticsearch 6.4 and later. * * @param {boolean} value * @returns {ValuesSourceBase} returns `this` so that calls can be chained */ missingBucket(value) { this._opts.missing_bucket = value; return this; } /** * Override default `toJSON` to return DSL representation for the Composite * Aggregation values source. * * @override * @returns {Object} returns an Object which maps to the elasticsearch query DSL */ toJSON() { return { [this._name]: recursiveToJSON(this._body) }; } }
JavaScript
class NotifierTransport extends Transport { constructor(opts) { super(opts); this.name = 'NT'; // NotifierTransport } log(info, callback) { const msg = { severity: info[LEVEL], ts: new Date(info.timestamp).getTime(), message: info.message }; setImmediate(() => this.emit('logged', msg)); callback(); } }
JavaScript
class MixedPropertiesAndAdditionalPropertiesClass { /** * Constructs a new <code>MixedPropertiesAndAdditionalPropertiesClass</code>. * @alias module:model/MixedPropertiesAndAdditionalPropertiesClass */ constructor() { MixedPropertiesAndAdditionalPropertiesClass.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>MixedPropertiesAndAdditionalPropertiesClass</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/MixedPropertiesAndAdditionalPropertiesClass} obj Optional instance to populate. * @return {module:model/MixedPropertiesAndAdditionalPropertiesClass} The populated <code>MixedPropertiesAndAdditionalPropertiesClass</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new MixedPropertiesAndAdditionalPropertiesClass(); if (data.hasOwnProperty('uuid')) { obj['uuid'] = ApiClient.convertToType(data['uuid'], 'String'); } if (data.hasOwnProperty('dateTime')) { obj['dateTime'] = ApiClient.convertToType(data['dateTime'], 'Date'); } if (data.hasOwnProperty('map')) { obj['map'] = ApiClient.convertToType(data['map'], {'String': Animal}); } } return obj; } }
JavaScript
class RefCountedObject { /** * @type {number} * @private */ _refCount = 0; /** * Inrements the counter. */ incRefCount() { this._refCount++; } /** * Decrements the counter. When the value reaches zero, destroy is called. */ decRefCount() { this._refCount--; } /** * The current reference count. * * @type {number} */ get refCount() { return this._refCount; } }
JavaScript
class Signup extends Component { static navigationOptions = ({ navigation }) => { const { params = {} } = navigation.state const { navigate } = navigation return { title: 'Signup', headerTintColor: "#616161", headerStyle: styles.header } } constructor(props) { super(props) // Default state this.state = { fullNameInput: '', fullNameInputError: '', emailInput: '', emailInputError: '', passwordInput: '', passwordInputError: '', confirmPasswordInput: '', confirmPasswordInputError: '', loading: false } } /** * On full name input change * * @param {any} text * @memberof Signup */ onfullNameChange(text) { this.setState({ fullNameInput: text, fullNameInputError: '' }) } /** * On email input change * * @param {any} text * @memberof Signup */ onEmailChange(text) { this.setState({ emailInput: text, emailInputError: '' }) } /** * On password input change event * * @param {any} text * @memberof Signup */ onPasswordChange(text) { this.setState({ passwordInput: text, passwordInputError: '' }) } /** * On confirm password input change event * * @param {any} text * @memberof Signup */ onConfirmPasswordChange(text) { this.setState({ confirmPasswordInput: text, confirmPasswordInputError: '' }) } /** * On loggin button pressed * * @memberof Signup */ onSignupButton() { const { register } = this.props const { fullNameInput, emailInput, passwordInput, confirmPasswordInput } = this.state; if (_.trim(fullNameInput) === '') { this.setState({ fullNameInputError: 'Field is required.' }) return } if (_.trim(emailInput) === '') { this.setState({ emailInputError: 'Field is required.' }) return } if (_.trim(passwordInput) === '') { this.setState({ passwordInputError: 'Field is required.' }) return } if (_.trim(confirmPasswordInput) === '') { this.setState({ confirmPasswordInputError: 'Field is required.' }) return } if (confirmPasswordInput !== passwordInput) { this.setState({ confirmPasswordInputError: 'Should be equal to password.', passwordInputError: 'Should be equal to confirm password.' }) return } register({ fullName: fullNameInput, email:emailInput, password: passwordInput }) } renderButton() { if (this.props.loading) { return ( <Button textStyle={styles.buttonText} buttonStyle={styles.button}> Loading ... </Button> ) } const { navigation } = this.props return ( <CardSection style={styles.buttons}> <Button onPress={this.onSignupButton.bind(this)}> Signup </Button> </CardSection> ) } render() { const { fullNameInput, fullNameInputError, emailInput, emailInputError, passwordInput, passwordInputError, confirmPasswordInput, confirmPasswordInputError } = this.state return ( <KeyboardAvoidingView behavior="padding" style={{ flex: 1 }} > <ScrollView> <Card> <CardSection style={styles.logo}> <Image style={styles.logoImage} source={{ uri: 'https://raw.githubusercontent.com/Qolzam/react-social-network/master/docs/app/logo.png' }} /> </CardSection> <Text style={{ alignSelf: 'center', fontSize: 30, color: '#eeeeee' }}>Green</Text> <View style={{ height: 20 }} /> <View style={{ padding: 20 }}> <TextField label="Full Name" onChangeText={this.onfullNameChange.bind(this)} value={fullNameInput} error={fullNameInputError !== ''} helperText={fullNameInputError} /> <View style={{ height: 20 }} /> <TextField label="Email" keyboardType='email-address' onChangeText={this.onEmailChange.bind(this)} value={emailInput} error={emailInputError !== ''} helperText={emailInputError} /> <View style={{ height: 20 }} /> <TextField secureTextEntry label="Password" onChangeText={this.onPasswordChange.bind(this)} value={passwordInput} error={passwordInputError !== ''} helperText={passwordInputError} /> <View style={{ height: 20 }} /> <TextField secureTextEntry label="Confirm Password" onChangeText={this.onConfirmPasswordChange.bind(this)} value={confirmPasswordInput} error={confirmPasswordInputError !== ''} helperText={confirmPasswordInputError} /> </View> <View style={{ height: 20 }} /> <Text style={styles.errorTextStyle}> {this.props.error} </Text> {this.renderButton()} </Card> </ScrollView> </KeyboardAvoidingView> ) } }
JavaScript
class ChartistRender extends PolymerElement{// render function static get template(){return html` <style include="chartist-render-shared-styles"> :host { display: block; } </style> <div id="chart" chart$="[[__chartId]]" class$="ct-chart [[scale]]"></div> `}// properties available to the custom element for data binding static get properties(){return{/** * The unique identifier of the chart. */id:{type:String,value:"chart"},/** * The type of chart:bar, line, or pie */type:{type:String,value:"bar"},/** * The scale of the chart. (See https://gionkunz.github.io/chartist-js/api-documentation.html)``` Container class Ratio .ct-square 1 .ct-minor-second 15:16 .ct-major-second 8:9 .ct-minor-third 5:6 .ct-major-third 4:5 .ct-perfect-fourth 3:4 .ct-perfect-fifth 2:3 .ct-minor-sixth 5:8 .ct-golden-section 1:1.618 .ct-major-sixth 3:5 .ct-minor-seventh 9:16 .ct-major-seventh 8:15 .ct-octave 1:2 .ct-major-tenth 2:5 .ct-major-eleventh 3:8 .ct-major-twelfth 1:3 .ct-double-octave 1:4``` */scale:{type:String,observer:"makeChart"},/** * The chart title used for accessibility. */chartTitle:{type:String,value:null,observer:"makeChart"},/** * The chart description used for accessibility. */chartDesc:{type:String,value:"",observer:"makeChart"},/** * The chart data. */data:{type:Object,value:null,observer:"makeChart"},/** * The options available at https://gionkunz.github.io/chartist-js/api-documentation.html. */options:{type:Object,value:null,observer:"makeChart"},/** * The responsive options. (See https://gionkunz.github.io/chartist-js/api-documentation.html.) */responsiveOptions:{type:Array,value:[],observer:"makeChart"},/** * The show data in table form as well? Default is false. */showTable:{type:Boolean,value:!1,observer:"makeChart"}}}/** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */static get tag(){return"chartist-render"}/** * life cycle, element is afixed to the DOM */connectedCallback(){super.connectedCallback();const basePath=pathFromUrl(decodeURIComponent(import.meta.url));let location=`${basePath}lib/chartist/dist/chartist.min.js`;window.addEventListener("es-bridge-chartistLib-loaded",this._chartistLoaded.bind(this));window.ESGlobalBridge.requestAvailability();window.ESGlobalBridge.instance.load("chartistLib",location)}disconnectedCallback(){window.removeEventListener("es-bridge-chartistLib-loaded",this._chartistLoaded.bind(this));super.disconnectedCallback()}/** * life cycle, element is ready */ready(){super.ready();let root=this;window.dispatchEvent(new CustomEvent("chartist-render-ready",{detail:root}));if("object"===typeof Chartist)root._chartistLoaded.bind(root)}/** * determines if char is ready */_chartistLoaded(){this.__chartistLoaded=!0;this.makeChart()}/** * Makes chart and returns the chart object. */makeChart(){setTimeout(()=>{this.chart=this._renderChart()},100)}/** * Renders chart and returns the chart object. */_renderChart(){let root=this,chart=null;root.__chartId=root._getUniqueId("chartist-render-");if(root!==void 0&&"object"===typeof Chartist&&null!==root.$.chart&&null!==root.data){if("bar"==root.type){if(root.responsiveOptions!==void 0&&0<root.responsiveOptions.length){root.responsiveOptions.forEach(option=>{if(option[1]!==void 0){if(option[1].axisX&&"noop"==option[1].axisX.labelInterpolationFnc)option[1].axisX.labelInterpolationFnc=Chartist.noop;if(option[1].axisY&&"noop"==option[1].axisY.labelInterpolationFnc)option[1].axisY.labelInterpolationFnc=Chartist.noop}})}chart=Chartist.Bar(this.$.chart,root.data,root.options,root.responsiveOptions)}else if("line"==root.type){chart=Chartist.Line(this.$.chart,root.data,root.options,root.responsiveOptions)}else if("pie"==root.type){chart=Chartist.Pie(this.$.chart,root.data,root.options,root.responsiveOptions)}window.dispatchEvent(new CustomEvent("chartist-render-draw",{detail:chart}));chart.on("created",()=>{root.addA11yFeatures(chart.container.childNodes[0])})}return chart}/** * Add accessibility features. */addA11yFeatures(svg){let desc=this.data.labels!==void 0&&null!==this.data.labels?this.chartDesc+this.makeA11yTable(svg):this.chartDesc;this._addA11yFeature(svg,"desc",desc);this._addA11yFeature(svg,"title",this.chartTitle);svg.setAttribute("aria-labelledby",this.__chartId+"-chart-title "+this.__chartId+"-chart-desc")}/** * Add accessibility features. */makeA11yTable(svg){let title=null!==this.chartTitle?this.chartTitle:"A "+this.type+" chart.",table=["<table summary=\"Each column is a series of data, and the first column is the data label.\">","<caption>"+title+"</caption>","<tbody>"];for(var i=0;i<this.data.labels.length;i++){table.push("<tr><th scope=\"row\">"+this.data.labels[i]+"</th>");if("pie"==this.type){table.push("<td>"+this.data.series[i]+"</td>")}else{for(var j=0;j<this.data.series.length;j++){table.push("<td>"+this.data.series[j][i]+"</td>")}}table.push("</tr>")}table.push("</tbody></table>");return table.join("")}/** * For inserting chart title and description. */_addA11yFeature(svg,tag,html){let el=document.createElement(tag),first=svg.childNodes[0];el.innerHTML=html;el.setAttribute("id",this.__chartId+"-chart-"+tag);svg.insertBefore(el,first)}/** * Get unique ID from the chart */_getUniqueId(prefix){let id=prefix+Date.now();return id}}
JavaScript
class UserPoolIdentityProvider { constructor() { } /** * Import an existing UserPoolIdentityProvider. * * @stability stable */ static fromProviderName(scope, id, providerName) { class Import extends core_1.Resource { constructor() { super(...arguments); this.providerName = providerName; } } return new Import(scope, id); } }
JavaScript
class Endpoint { constructor(desc) { this.addresses = desc.addresses; this.conditions = desc.conditions; this.hostname = desc.hostname; this.targetRef = desc.targetRef; this.topology = desc.topology; } }
JavaScript
class EndpointSlice { constructor(desc) { this.addressType = desc.addressType; this.apiVersion = EndpointSlice.apiVersion; this.endpoints = desc.endpoints; this.kind = EndpointSlice.kind; this.metadata = desc.metadata; this.ports = desc.ports; } }
JavaScript
class EndpointSliceList { constructor(desc) { this.apiVersion = EndpointSliceList.apiVersion; this.items = desc.items.map((i) => new EndpointSlice(i)); this.kind = EndpointSliceList.kind; this.metadata = desc.metadata; } }
JavaScript
class CueModule { constructor(name, config) { this.name = name; this.ready = false; // --------------- PREPARE ELEMENT TEMPLATE -------------- // this has to be done early so that ref-ready template.innerHTML // can be composed via string factory returned from Component.define this.template = document.createElement('template'); this.template.innerHTML = config.element || ''; this.refNames = collectElementReferences(this.template.content, {}); } setupOnce(config) { if (this.ready === false) { this.ready = true; // ------------------ COMPLETE TEMPLATE ----------------- this.template.__slots = {}; this.template.__hasSlots = false; const slots = this.template.content.querySelectorAll('slot'); for (let i = 0; i < slots.length; i++) { const slot = slots[i]; this.template.__slots[slot.getAttribute('name')] = slot.outerHTML; this.template.__hasSlots = true; } // ------------------ CREATE SCOPED CSS ------------------ config.style = config.style || config.styles; // allow both names if (config.style) { this.style = this.createScopedStyles(config.style); CUE_CSS.components.innerHTML += this.style; } // ----------------- SETUP DATA, COMPUTED & REACTIONS -------------- this.data = { static: {}, computed: new Map(), bindings: {}, reactions: {} }; // Assign Data from Config const allProperties = {}; if (config.data) { for (const k in config.data) { const v = config.data[k]; allProperties[k] = v.value; if (v.value && v.value.id === STORE_BINDING_ID) { this.data.bindings[k] = v.value; } else if (typeof v.value === 'function') { this.data.computed.set(k, new ComputedProperty(k, v.value)); } else { this.data.static[k] = v.value; } if (typeof v.reaction === 'function') { this.data.reactions[k] = v.reaction; } } } // Setup Computed Properties if assigned if (this.data.computed.size) { this.data.computed = setupComputedProperties(allProperties, this.data.computed); } // ---------------------- LIFECYCLE METHODS ---------------------- this.initialize = typeof config.initialize === 'function' ? config.initialize : NOOP; } } createScopedStyles(styles) { // Re-write $self to component-name styles = styles.replace(SELF_REGEXP, this.name); // Re-write $refName(s) in style text to class selector for (const refName in this.refNames) { // replace $refName with internal .class when $refName is: // - immediately followed by css child selector (space . : # [ > + ~) OR // - immediately followed by opening bracket { OR // - immediately followed by chaining comma , // - not followed by anything (end of line) styles = styles.replace(new RegExp("(\\" + refName + "(?=[\\40{,.:#[>+~]))|\\" + refName + "\b", 'g'), this.refNames[refName]); } CUE_CSS.compiler.innerHTML = styles; const tmpSheet = CUE_CSS.compiler.sheet; let styleNodeInnerHTML = '', styleQueries = ''; for (let i = 0, rule; i < tmpSheet.rules.length; i++) { rule = tmpSheet.rules[i]; if (rule.type === 7 || rule.type === 8) { // do not scope @keyframes styleNodeInnerHTML += rule.cssText; } else if (rule.type === 1) { // style rule styleNodeInnerHTML += this.constructScopedStyleRule(rule); } else if (rule.type === 4 || rule.type === 12) { // @media/@supports query styleQueries += this.constructScopedStyleQuery(rule); } else { console.warn(`CSS Rule of type "${rule.type}" is not currently supported by Cue Components.`); } } // write queries to the end of the rules AFTER the other rules for specificity (issue #13) styleNodeInnerHTML += styleQueries; // Empty Compiler styleSheet CUE_CSS.compiler.innerHTML = ''; return styleNodeInnerHTML; } constructScopedStyleQuery(query, cssText = '') { if (query.type === 4) { cssText += '@media ' + query.media.mediaText + ' {'; } else { cssText += '@supports ' + query.conditionText + ' {'; } let styleQueries = ''; for (let i = 0, rule; i < query.cssRules.length; i++) { rule = query.cssRules[i]; if (rule.type === 7 || rule.type === 8) { // @keyframes cssText += rule.cssText; } else if (rule.type === 1) { cssText += this.constructScopedStyleRule(rule, cssText); } else if (rule.type === 4 || rule.type === 12) { // nested query styleQueries += this.constructScopedStyleQuery(rule); } else { console.warn(`CSS Rule of type "${rule.type}" is not currently supported by Components.`); } } // write nested queries to the end of the surrounding query (see issue #13) cssText += styleQueries + ' }'; return cssText; } constructScopedStyleRule(rule) { let cssText = ''; if (rule.selectorText.indexOf(',') > -1) { const selectors = rule.selectorText.split(','); const scopedSelectors = []; for (let i = 0, selector; i < selectors.length; i++) { selector = selectors[i].trim(); if (selector.lastIndexOf(':root', 0) === 0) { // escape context (dont scope) :root notation scopedSelectors.push(selector.replace(':root', '')); } else if (this.isTopLevelSelector(selector, this.name)) { // dont scope component-name scopedSelectors.push(selector); } else { // prefix with component-name to create soft scoping scopedSelectors.push(this.name + ' ' + selector); } } cssText += scopedSelectors.join(', ') + rule.cssText.substr(rule.selectorText.length); } else { if (rule.selectorText.lastIndexOf(':root', 0) === 0) { // escape context (dont scope) :root notation cssText += rule.cssText.replace(':root', ''); // remove first occurrence of :root } else if (this.isTopLevelSelector(rule.selectorText)) { // dont scope component-name cssText += rule.cssText; } else { // prefix with component-name to create soft scoping cssText += this.name + ' ' + rule.cssText; } } return cssText; } isTopLevelSelector(selectorText) { if (selectorText === this.name) { return true; } else if (selectorText.lastIndexOf(this.name, 0) === 0) { // starts with componentName return CHILD_SELECTORS.indexOf(selectorText.charAt(this.name.length)) > -1; // character following componentName is valid child selector } else { // nada return false; } } }
JavaScript
class GetSessionTokenCommand extends smithy_client_1.Command { // Start section: command_properties // End section: command_properties constructor(input) { // Start section: command_constructor super(); this.input = input; // End section: command_constructor } /** * @internal */ resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize)); this.middlewareStack.use(middleware_signing_1.getAwsAuthPlugin(configuration)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "GetSessionTokenCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.GetSessionTokenRequest.filterSensitiveLog, outputFilterSensitiveLog: models_0_1.GetSessionTokenResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return Aws_query_1.serializeAws_queryGetSessionTokenCommand(input, context); } deserialize(output, context) { return Aws_query_1.deserializeAws_queryGetSessionTokenCommand(output, context); } }
JavaScript
class Edit extends SublimeObject { constructor (self /*: MappedVariable | null*/, stepObject /*: StepObject | null*/ = null, stepRequired /*: boolean*/ = false, codeChainString /*: string*/ = '') { super(self, stepObject, stepRequired, codeChainString) } }
JavaScript
class BaseNote extends BaseModel { /** * @constructor * @param {Object} obj The object passed to constructor */ constructor(obj) { super(obj); if (obj === undefined || obj === null) return; this.id = this.constructor.getValue(obj.id); this.active_flag = this.constructor.getValue(obj.active_flag); this.add_time = this.constructor.getValue(obj.add_time); this.content = this.constructor.getValue(obj.content); this.deal = this.constructor.getValue(obj.deal); this.deal_id = this.constructor.getValue(obj.deal_id); this.last_update_user_id = this.constructor.getValue(obj.last_update_user_id); this.org_id = this.constructor.getValue(obj.org_id); this.organization = this.constructor.getValue(obj.organization); this.person = this.constructor.getValue(obj.person); this.person_id = this.constructor.getValue(obj.person_id); this.pinned_to_deal_flag = this.constructor.getValue(obj.pinned_to_deal_flag); this.pinned_to_organization_flag = this.constructor.getValue(obj.pinned_to_organization_flag); this.pinned_to_person_flag = this.constructor.getValue(obj.pinned_to_person_flag); this.update_time = this.constructor.getValue(obj.update_time); this.user = this.constructor.getValue(obj.user); this.user_id = this.constructor.getValue(obj.user_id); } /** * Function containing information about the fields of this model * @return {array} Array of objects containing information about the fields */ static mappingInfo() { return super.mappingInfo().concat([ { name: 'id', realName: 'id' }, { name: 'active_flag', realName: 'active_flag' }, { name: 'add_time', realName: 'add_time' }, { name: 'content', realName: 'content' }, { name: 'deal', realName: 'deal', type: 'BaseNoteDealTitle' }, { name: 'deal_id', realName: 'deal_id' }, { name: 'last_update_user_id', realName: 'last_update_user_id' }, { name: 'org_id', realName: 'org_id' }, { name: 'organization', realName: 'organization', type: 'Organization1' }, { name: 'person', realName: 'person', type: 'Person1' }, { name: 'person_id', realName: 'person_id' }, { name: 'pinned_to_deal_flag', realName: 'pinned_to_deal_flag' }, { name: 'pinned_to_organization_flag', realName: 'pinned_to_organization_flag' }, { name: 'pinned_to_person_flag', realName: 'pinned_to_person_flag' }, { name: 'update_time', realName: 'update_time' }, { name: 'user', realName: 'user', type: 'NoteCreatorUser' }, { name: 'user_id', realName: 'user_id' }, ]); } /** * Function containing information about discriminator values * mapped with their corresponding model class names * * @return {object} Object containing Key-Value pairs mapping discriminator * values with their corresponding model classes */ static discriminatorMap() { return {}; } }
JavaScript
class ConvertMangaCommand { /** * Constructor * * @param {Kindlegen} kindlegen Kindlegen service */ constructor(kindlegen) { this.kindlegen = kindlegen; } /** * Get command name * * @return {string} Command name */ getName() { return "kindlegen:convert-manga"; } /** * Get command description * * @return {string} Command description */ getDescription() { return "Convert manga directory"; } /** * Execute the command * * @param {Array} parameters Command parameters */ *execute(parameters) { let targetPath = parameters[0]; let newFilePath = parameters[1]; let title = parameters[2]; yield this.kindlegen.convertManga(targetPath, newFilePath, title); } }
JavaScript
class FormattingElementList { constructor(treeAdapter) { this.length = 0; this.entries = []; this.treeAdapter = treeAdapter; this.bookmark = null; } //Noah Ark's condition //OPTIMIZATION: at first we try to find possible candidates for exclusion using //lightweight heuristics without thorough attributes check. _getNoahArkConditionCandidates(newElement) { const candidates = []; if (this.length >= NOAH_ARK_CAPACITY) { const neAttrsLength = this.treeAdapter.getAttrList(newElement).length; const neTagName = this.treeAdapter.getTagName(newElement); const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement); for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.MARKER_ENTRY) { break; } const element = entry.element; const elementAttrs = this.treeAdapter.getAttrList(element); const isCandidate = this.treeAdapter.getTagName(element) === neTagName && this.treeAdapter.getNamespaceURI(element) === neNamespaceURI && elementAttrs.length === neAttrsLength; if (isCandidate) { candidates.push({ idx: i, attrs: elementAttrs }); } } } return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates; } _ensureNoahArkCondition(newElement) { const candidates = this._getNoahArkConditionCandidates(newElement); let cLength = candidates.length; if (cLength) { const neAttrs = this.treeAdapter.getAttrList(newElement); const neAttrsLength = neAttrs.length; const neAttrsMap = Object.create(null); //NOTE: build attrs map for the new element so we can perform fast lookups for (let i = 0; i < neAttrsLength; i++) { const neAttr = neAttrs[i]; neAttrsMap[neAttr.name] = neAttr.value; } for (let i = 0; i < neAttrsLength; i++) { for (let j = 0; j < cLength; j++) { const cAttr = candidates[j].attrs[i]; if (neAttrsMap[cAttr.name] !== cAttr.value) { candidates.splice(j, 1); cLength--; } if (candidates.length < NOAH_ARK_CAPACITY) { return; } } } //NOTE: remove bottommost candidates until Noah's Ark condition will not be met for (let i = cLength - 1; i >= NOAH_ARK_CAPACITY - 1; i--) { this.entries.splice(candidates[i].idx, 1); this.length--; } } } //Mutations insertMarker() { this.entries.push({ type: FormattingElementList.MARKER_ENTRY }); this.length++; } pushElement(element, token) { this._ensureNoahArkCondition(element); this.entries.push({ type: FormattingElementList.ELEMENT_ENTRY, element: element, token: token }); this.length++; } insertElementAfterBookmark(element, token) { let bookmarkIdx = this.length - 1; for (; bookmarkIdx >= 0; bookmarkIdx--) { if (this.entries[bookmarkIdx] === this.bookmark) { break; } } this.entries.splice(bookmarkIdx + 1, 0, { type: FormattingElementList.ELEMENT_ENTRY, element: element, token: token }); this.length++; } removeEntry(entry) { for (let i = this.length - 1; i >= 0; i--) { if (this.entries[i] === entry) { this.entries.splice(i, 1); this.length--; break; } } } clearToLastMarker() { while (this.length) { const entry = this.entries.pop(); this.length--; if (entry.type === FormattingElementList.MARKER_ENTRY) { break; } } } //Search getElementEntryInScopeWithTagName(tagName) { for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.MARKER_ENTRY) { return null; } if (this.treeAdapter.getTagName(entry.element) === tagName) { return entry; } } return null; } getElementEntry(element) { for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.ELEMENT_ENTRY && entry.element === element) { return entry; } } return null; } }
JavaScript
class Plugin { /** * Called when the plugin is parsed by the engine * @param {Object} settings - The plugin settings if was defined in the config files */ constructor(settings) { this.settings = settings; } /** * Plugin hook called before the engine runs all the rules * * @param {Object} context - plugin name, rules id, rules severity, rules options */ preRun(context) { this.context = context; } /** * Plugin hook called after the engine runs all the rule * * @param {Object} summary - plugin name, rules id, rules severity, rules execution status, rules execution duration */ postRun(summary) { this.summary = summary; } }
JavaScript
class BybitDataStream extends WebSocketClient { // cfg.addr - like wss://stream.bybit.com/realtime // cfg.symbols - [BTCUSD] constructor(cfg) { super(cfg); this.mgrTrade = new TradeMgr({ path: './output/bybit/', symbols: this.cfg.symbols, }); } _procConfig() { super._procConfig(); if (!this.cfg.addr) { // this.cfg.addr = 'wss://testnet.bitmex.com/realtime'; this.cfg.addr = 'wss://stream.bybit.com/realtime'; } if (!this.cfg.symbols) { this.cfg.symbols = ['BTCUSD']; } } _addChannel() { let args = []; for (let i = 0; i < this.cfg.symbols.length; ++i) { args.push('trade.' + this.cfg.symbols[i]); } this.sendMsg({ op: 'subscribe', args: args, }); } _onChannel_Deals(data) { for (let i = 0; i < data.length; ++i) { this.mgrTrade.addTrade(data[i].symbol, data[i].trade_id, new Date(data[i].timestamp), data[i].price, data[i].size, data[i].side == 'Buy' ? TRADETYPE.BUY : TRADETYPE.SELL); } } //------------------------------------------------------------------------------ // WebSocketClient sendMsg(msg) { this._send(JSON.stringify(msg)); } _onOpen() { super._onOpen(); console.log('bybit open '); this._addChannel(); } _onMsg(data) { super._onMsg(data); try{ let msg = JSON.parse(data); if (msg) { if (msg.hasOwnProperty('success')) { } else if (msg.hasOwnProperty('topic')) { let arr = msg.topic.split('.'); if (arr[0] == 'trade') { this._onChannel_Deals(msg.data); } else { console.log(data); } } } } catch (err) { console.log('bybit onmsg err! ' + err + ' ' + data); this.close(); } } _onClose() { console.log('bybit close '); super._onClose(); } _onError(err) { console.log('bybit error ' + JSON.stringify(err)); super._onError(err); } _onKeepalive() { let msg = { op: 'ping', }; this.sendMsg(msg); super._onKeepalive(); } }
JavaScript
class DetectLabelsCommand extends smithy_client_1.Command { // Start section: command_properties // End section: command_properties constructor(input) { // Start section: command_constructor super(); this.input = input; // End section: command_constructor } /** * @internal */ resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "RekognitionClient"; const commandName = "DetectLabelsCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.DetectLabelsRequest.filterSensitiveLog, outputFilterSensitiveLog: models_0_1.DetectLabelsResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return Aws_json1_1_1.serializeAws_json1_1DetectLabelsCommand(input, context); } deserialize(output, context) { return Aws_json1_1_1.deserializeAws_json1_1DetectLabelsCommand(output, context); } }
JavaScript
class BaseCommand { /** * Current command execution context. * @type {CommandContext} */ #context; /** * @param {CommandContext} context */ constructor(context) { this.#context = context; } /** * Main command method. Must be implemented by child classes. * @async * @abstract * @return {*} */ async run() { throw new Error("Command is not implemented!"); } /** * Get current command context. * @return {CommandContext} */ get context() { return this.#context; } /** * Validate command context before calling command. * @return {Promise<boolean>} Validation result. * @throws BaseError */ async validate() { if ( this.constructor?.validators && typeof this.constructor?.validators === "object" ) { const validator = new CommandContextValidator(this.context, this.constructor.validators); await validator.validate(); } return true; } /** * Resolve text for current lang instance. * @param {string} code Field code. * @param {Object<string,string>} [options] (Optional) Fields for replacements. * @return {string} Resolved from Lang text or field code itself if nothing found. */ resolveLang(code, options) { return this.context.getLang().get(code, options); } /** * Current context message. * @return {module:"discord.js".Message} */ get message() { return this.context.getMessage(); } /** * Current context arguments. * @return {string[]} */ get args() { return this.context.getArgs(); } /** * Command name. Used for calling command in chat. * @type {string} * @abstract */ static code; /** * Title of command. * @type {string} */ static title; /** * Description of command. * @type {string} */ static description; /** * Usage string. * @type {string} */ static usage; /** * Examples list. Contains codes for resolving from lang. `command.%code%` will be pushed on calling `getCode` * static method. * @type {string[]} */ static examples; /** * Command aliases. * @type {string[]} */ static aliases; /** * Category code. * @type {string} */ static category; /** * Automatic validation options. * @type {Cognitum.ContextValidatorOptions} */ static validators; /** * Get command code. * @return {string} Command code. */ static getCode() { return this.code; } /** * Get command title. If command title is not provided then returns string in next format: `command.%code%.title`. * @return {string} Command title or generated from command code string. */ static getTitle() { if (typeof this.title !== "string") return `command.${this.code}.title`; return this.title; } /** * Get command description. If command title is not provided then returns string in next format: * `command.%code%.description`. * @return {string} Command description or generated from command code string. */ static getDescription() { if (typeof this.description !== "string") return `command.${this.code}.description`; return this.description; } /** * Get command usage string. * @return {string} Command usage string. */ static getUsage() { return this.usage; } /** * Get usage examples. Will generate an array with codes in this format: `command.%commandCode%.%exampleCode%` * @return {string[]} Array of examples codes for resolving using `Lang` class. */ static getExamples() { return this.examples?.map?.(code => `command.${this.getCode()}.${code}`); } /** * Get command aliases. * @return {string[]} Array of command aliases. */ static getAliases() { return this.aliases; } /** * Checks is aliases set correctly. * @return {boolean} Checking result. */ static aliasesAvailable() { return this.aliases instanceof Array && this.aliases.length > 0; } /** * Get category code. * @return {string} Category code. */ static getCategory() { return this.category; } /** * Validate command class required metadata for availability. * @return {boolean} Result of validation. */ static validateMetaInformation() { return typeof this.code === "string" && this.code.length > 0 && typeof this.category === "string" && this.category.length > 0; } }
JavaScript
class I3STileManager { constructor() { this._statusMap = {}; } add(request, key, callback, frameState) { if (!this._statusMap[key]) { this._statusMap[key] = {request, callback, key, frameState, status: STATUS.REQUESTED}; request() .then(data => { this._statusMap[key].status = STATUS.COMPLETED; this._statusMap[key].callback(data, frameState); }) .catch(error => { this._statusMap[key].status = STATUS.ERROR; callback(error); }); } } update(key, frameState) { if (this._statusMap[key]) { this._statusMap[key].frameState = frameState; } } find(key) { return this._statusMap[key]; } }
JavaScript
class value_item { constructor(owner, field, label) { this.curr_val = owner[field]; this.jobj = owner; this.field = field; this.type = typeof owner[field]; this.labeltext = label; } create_DOM() { let parent = document.createElement('div'); parent.classList.add('item'); let label = document.createElement('p'); label.classList.add('label'); label.textContent = this.labeltext; let input = document.createElement('input'); input.setAttribute('type', 'text'); input.classList.add('value'); input.value = this.curr_val; // Save the element for later this.input_elem = input; parent.appendChild(label); parent.appendChild(input); return parent; } update_value() { var newval = ''; if (this.type == 'number') { newval = Number(this.input_elem.value); } else if (this.type == 'boolean') { newval = Boolean(this.input_elem.value); } else { // YOLO string newval = this.input_elem.value } this.jobj[this.field] = newval; } reset_value() { this.input_elem.value = this.curr_val; } }
JavaScript
class character_item { constructor(actor, context) { this.actor = actor; this.ctx = context; } create_DOM() { let parent = document.createElement('div'); parent.classList.add('section-content'); parent.classList.add('character-content'); let header = document.createElement('h3'); header.classList.add('character-name'); header.textContent = this.actor._name; parent.appendChild(header); // These three values are the current levels Object.entries(this.ctx.current).forEach((entry) => { let [idx, value] = entry; let subvalue = document.createElement('div'); subvalue.classList.add('item'); subvalue.classList.add('character-item'); let sublabel = document.createElement('p'); sublabel.classList.add('label'); sublabel.textContent = value.name; subvalue.appendChild(sublabel); let subinput = document.createElement('input'); subinput.setAttribute('type', 'text'); subinput.classList.add('value'); subinput.value = this.actor[idx]; subvalue.appendChild(subinput); parent.appendChild(subvalue); value['elem'] = subinput; }); // And of course these have to be just subtly different from the above this.ctx.static.forEach((value, idx) => { let subvalue = document.createElement('div'); subvalue.classList.add('item'); subvalue.classList.add('character-item'); let sublabel = document.createElement('p'); sublabel.classList.add('label'); sublabel.textContent = value.name; subvalue.appendChild(sublabel); let subinput = document.createElement('input'); subinput.setAttribute('type', 'text'); subinput.classList.add('value'); subinput.value = this.actor._paramPlus[idx]; subvalue.appendChild(subinput); parent.appendChild(subvalue); value['elem'] = subinput; }); return parent; } update_value() { Object.entries(this.ctx.current).forEach((entry) => { let [idx, value] = entry; this.actor[idx] = Number(value['elem'].value); }); this.ctx.static.forEach((value, idx) => { this.actor._paramPlus[idx] = Number(value['elem'].value); }); } reset_value() { Object.entries(this.ctx.current).forEach((entry) => { let [idx, value] = entry; value['elem'].value = this.actor[idx]; }); this.ctx.static.forEach((value, idx) => { value['elem'].value = this.actor._paramPlus[idx]; }); } }
JavaScript
class section { constructor(name) { this.name = name; this.items = []; } add_item(item) { this.items.push(item); } add_extras(extras_arr) { this.extras = extras_arr; } create_DOM() { let section_div = document.createElement('div'); section_div.classList.add('section'); let header = document.createElement('h2'); header.classList.add('section-header'); header.classList.add('expanded'); header.textContent = this.name; let section_content = document.createElement('div'); section_content.classList.add('section-content'); let extras_div = document.createElement('div'); // Enable expand / collapse behavior header.onclick = function(event) { if (event.target.classList.contains('expanded')) { event.target.classList.remove('expanded'); event.target.classList.add('collapsed'); section_content.classList.add('section-hidden'); extras_div.classList.add('section-hidden'); } else { event.target.classList.add('expanded'); event.target.classList.remove('collapsed'); section_content.classList.remove('section-hidden'); extras_div.classList.remove('section-hidden'); } }; section_div.appendChild(header); section_div.appendChild(section_content); this.items.forEach((item) => { section_content.appendChild(item.create_DOM()); }); // Add dropdown for extra items, if desired if (this.extras) { extras_div.classList.add('extras'); // Add a label let extras_label = document.createElement('p'); extras_label.classList.add('extras'); extras_label.textContent = 'Add to inventory: '; extras_div.appendChild(extras_label); // Create the dropdown list let select_list = document.createElement('select'); select_list.classList.add('extras'); // Create and append the options this.extras.forEach((extra) => { let option = document.createElement('option'); option.context = extra; option.text = extra.name; select_list.appendChild(option); }); extras_div.appendChild(select_list); // Create the button let btnadd = document.createElement('button'); btnadd.onclick = (event) => { let val = select_list.options[select_list.selectedIndex].context; // Add the item to the JSON object val.obj[val.id] = 1; // Create the new item let item = new value_item(val.obj, val.id, val.name) this.add_item(item); // Add to the DOM section_content.appendChild(item.create_DOM()); }; btnadd.textContent = 'Add item'; extras_div.appendChild(btnadd); section_div.appendChild(extras_div); } return section_div; } update_values() { this.items.forEach((item) => { item.update_value(); }); } reset_values() { this.items.forEach((item) => { item.reset_value(); }); } }
JavaScript
class NodoExp { constructor(tipo,valor) { this.tipo=tipo this.valor=valor } getValor() { } getC3D() {} }
JavaScript
class SimpleGraphClient { constructor(token) { if (!token || !token.trim()) { throw new Error('SimpleGraphClient: Invalid token received.'); } this._token = token; // Get an Authenticated Microsoft Graph client using the token issued to the user. this.graphClient = Client.init({ authProvider: (done) => { done(null, this._token); // First parameter takes an error if you can't get an access token. } }); } /** * Sends an email on the user's behalf. * @param {string} toAddress Email address of the email's recipient. * @param {string} subject Subject of the email to be sent to the recipient. * @param {string} content Email message to be sent to the recipient. */ async sendMail(toAddress, subject, content) { if (!toAddress || !toAddress.trim()) { throw new Error('SimpleGraphClient.sendMail(): Invalid `toAddress` parameter received.'); } if (!subject || !subject.trim()) { throw new Error('SimpleGraphClient.sendMail(): Invalid `subject` parameter received.'); } if (!content || !content.trim()) { throw new Error('SimpleGraphClient.sendMail(): Invalid `content` parameter received.'); } // Create the email. const mail = { body: { content: content, // `Hi there! I had this message sent from a bot. - Your friend, ${ graphData.displayName }!`, contentType: 'Text' }, subject: subject, // `Message from a bot!`, toRecipients: [{ emailAddress: { address: toAddress } }] }; // Send the message. return await this.graphClient .api('/me/sendMail') .post({ message: mail }, (error, res) => { if (error) { throw error; } else { return res; } }); } /** * Gets recent mail the user has received within the last hour and displays up to 5 of the emails in the bot. */ async getRecentMail() { return await this.graphClient .api('/me/messages') .version('beta') .top(5) .get().then((res) => { return res; }); } /** * Collects information about the user in the bot. */ async getMe() { return await this.graphClient .api('/me') .get().then((res) => { return res; }); } /** * Collects the user's manager in the bot. */ async getManager() { return await this.graphClient .api('/me/manager') .version('beta') .select('displayName') .get().then((res) => { return res; }); } }
JavaScript
class V1ObjectMeta { static getAttributeTypeMap() { return V1ObjectMeta.attributeTypeMap; } }
JavaScript
class Rule { constructor(col, op, values) { this.c = col; this.o = op; this.v = values; } }
JavaScript
class Profile extends Component { constructor(){ super(...arguments); this.state = { ranattr:'ok', }; } componentWillReceiveProps(nextProps) { console.log('profile',{nextProps}) } componentDidMount() { // setLayoutHandler.call(this); Promise.all([ AsyncStorage.getItem(constants.jwt_token.TOKEN_NAME), AsyncStorage.getItem(constants.jwt_token.TOKEN_DATA), AsyncStorage.getItem(constants.jwt_token.PROFILE_JSON), ]) .then(results_asyncstorage => { console.log('fetched data for profile') this.setState({ results_asyncstorage, user_props: this.props.user, }); }) .catch(err => { console.log('profile err', err); }); } render() { console.log('PROFILE RENDER this.state', this.state); return ( <View // onLayout={onLayoutUpdate.bind(this)} style={[styles.stretchBox, styles.scrollViewWrapperContainer, styles.statusBarPadding, ]}> <ScrollView style={styles.stretchBox } contentContainerStyle={ { paddingVertical: 20,position:'relative' }}> <Button title="Log out" onPress={() => { console.log('pressed button') this.props.logoutUser() }} /> <Text>results_asyncstorage2: {JSON.stringify(this.state.results_asyncstorage,null,2)}</Text> <Text>user_props: {JSON.stringify(this.state.user_props,null,2)}</Text> </ScrollView> </View> ); } }
JavaScript
class PackageManager extends Feature { static shortcut = 'packageManager' async featureWasEnabled() { this.status = CREATED if (this.runtime.argv.packageManager) { await this.startAsync() } } initialState = { authenticated: false, ...(process.env.NPM_TOKEN && { npmToken: process.env.NPM_TOKEN }), } get runtime() { return super.runtime } get options() { return super.options } observables() { const p = this return { status: CREATED, manifests: ['shallowMap', {}], entities: ['shallowMap', {}], nodeModules: ['shallowMap', {}], remotes: ['shallowMap', []], updateNodeModule: [ 'action', function updateNodeModule(pkg) { p.nodeModules.set(pkg.name, { ...(p.nodeModules.get(pkg.name) || {}), [pkg.version]: pkg, }) return this }, ], updateRemote: [ 'action', function updateRemote(name, data, replace = false) { if (replace) { p.remotes.set(name, this.normalizePackage(data)) } else { p.remotes.set(name, { ...(this.remotes.get(name) || {}), ...data, }) } }, ], checkRemoteStatus: [ 'action', function checkRemoteStatus(options = {}) { const p = this return p.runtime .select('package/repository-status', options) .then(data => { Object.keys(data).forEach(pkg => p.updateRemote(pkg, data[pkg], true)) return data }) .catch(error => { this.error = error }) }, ], } } /** * Starts the PackageManager service, which scans the local project for any package.json manifests * and populates our manifests observable with the information * * @param {Object} [options={}] * @param {Boolean} [options.remote=false] whether to fetch the remote information about this package from npm * @returns {Promise<PackageManager>} * @memberof PackageManager */ async startAsync(options = {}) { if (this.status === STARTING) { await this.activationEventWasFired(options) return this } else if (this.status === READY) { return this } else if (this.status === CREATED) { this.fireHook(WILL_START, options) this.status = STARTING try { if (this.fileManager.status === 'CREATED') { await this.fileManager.startAsync() } else { await this.fileManager.whenActivated() } await this.loadManifests() if (options.remote) { await this.checkRemoteStatus() } this.status = READY return this } catch (error) { this.fireHook(DID_FAIL, error) this.lastError = error this.status = FAILED return this } } } /** * Starts the package manager with the callback style * * @param {Object} [options={}] * @param {Boolean} [options.remote=false] whether to load remote repository information from npm * @param {Function} cb * @returns {Promise<PackageManager>} * @memberof PackageManager */ start(options = {}, cb) { if (typeof cb !== 'function') { return this.startAsync(options) } this.startAsync(options) .then(() => cb(null, this)) .catch(cb) return this } /** * Returns a promise which resolves when the package manager is finally activated. * * @param {Object} [options={}] * @param {Number} [options.timeout=30000] * @returns {Promise<PackageManager>} * @memberof PackageManager */ async activationEventWasFired(options = {}) { const f = this const { timeout = 30 * 1000 } = options const ok = resolve => () => resolve(f) const notOk = (reject, err) => f => reject(err) if (this.status === FAILED || this.status === READY) { return Promise.resolve(this) } return new Promise((resolve, reject) => { f.once(WAS_ACTIVATED, () => ok(resolve)()) f.once(DID_FAIL, err => notOk(reject, err)()) }) .catch(error => error) .then(() => f) } /** * Returns a promise which will resolve when the package manager is finally activated. If it hasn't yet * been started, this will start it. * * @param {Object} [options={}] * @returns {Promise<PackageManager>} * @memberof PackageManager */ async whenActivated(options = {}) { if (this.status === READY) { return this } if (this.status === CREATED) { this.status = STARTING await this.startAsync(options) this.status = READY } else if (this.status === STARTING) { await this.activationEventWasFired(options).catch(e => e) } return this } /** * Info about all the possible statuses the package manager can be in * * @readonly * @memberof PackageManager */ get statuses() { return STATUSES } /** * Information about the life cycle hooks emitted by the package manager * * @readonly * @memberof PackageManager */ get lifecycleHooks() { return LIFECYCLE_HOOKS } /** * A reference to the FileManager feature * @type {FileManager} * @memberof PackageManager * @readonly */ get fileManager() { return this.runtime.fileManager } /** * A reference to the PackageFinder feature * * @type {PackageFinder} * @readonly * @memberof PackageManager */ get finder() { return this.runtime.packageFinder } /** * Returns the ids of all the packages found. The id is the relative path to the package.json * * @property {Array<PackageId>} * @readonly * @memberof PackageManager */ get packageIds() { return Array.from(this.manifests.keys()) } /** * Returns all of the package manifests found. * * @type {Array<PackageManifest>} * @readonly * @memberof PackageManager */ get packageData() { return Array.from(this.manifests.values()).map(v => this.runtime.convertToJS(v)) } /** * Returns the names found in each manifest * * @type {Array<String>} * @readonly * @memberof PackageManager */ get packageNames() { return this.packageData.map(p => p.name) } /** * Returns each manifest as entries * * @type {Array<Array>} * @readonly * @memberof PackageManager */ get entries() { return this.manifests.entries().map(v => [v[0], this.runtime.convertToJS(v[1])]) } /** * Returns an object of every package manifest keyed by name * * @type {Object<String,PackageManifest>} * @readonly * @memberof PackageManager */ get byName() { return this.chain .invoke('manifests.values', []) .keyBy(v => v.name) .mapValues(v => this.runtime.convertToJS(v)) .value() } /** * Returns an object of every remote package manifest keyed by name * * @type {Object<String,PackageManifest>} * @readonly * @memberof PackageManager */ get remotesByName() { return this.chain .invoke('remotes.values', []) .keyBy(v => v.name) .mapValues(v => this.runtime.convertToJS(v)) .value() } /** * Returns the packages where the version in the local tree isn't published to npm * * @readonly * @memberof PackageManager */ get packagesAhead() { const { lodash: { pickBy }, finder: { semver }, versionMap, latestMap, } = this return pickBy(versionMap, (v, k) => v && latestMap[k] && semver.gt(v, latestMap[k])) } /** * Returns the packages who have a version number that doesn't exist in the npm registry * * @readonly * @memberof PackageManager */ get unpublished() { const { lodash: { pickBy }, versionMap, } = this return pickBy(versionMap, (v, k) => { const remote = this.remotes.get(k) return remote && remote.versions.indexOf(v) === -1 }) } /** * Returns the packages in the local tree whose versions are behind what is on npm. * * @readonly * @memberof PackageManager */ get packagesBehind() { const { lodash: { pickBy }, finder: { semver }, versionMap, latestMap, } = this return pickBy(versionMap, (v, k) => v && latestMap[k] && semver.lt(v, latestMap[k])) } get outdated() { return this.packagesBehind } get latestMap() { const p = this const get = p.runtime.lodash.get return p.chain .result('remotes.values', []) .keyBy(v => v.name) .mapValues((v, k) => { return get(v, ['dist-tags', 'latest'], v.version) }) .pickBy(v => v && v.length) .value() } get tarballUrls() { const { remotes } = this return Array.from(remotes.values()).reduce((memo, remote) => { if (remote && remote.dist) { memo[remote.name] = remote.dist && remote.dist.tarball } return memo }, {}) } get hasYarnPackageLock() { return this.runtime.fsx.existsSync(this.runtime.resolve('yarn.lock')) } get hasNpmPackageLock() { return this.runtime.fsx.existsSync(this.runtime.resolve('package-lock.json')) } get usesLerna() { return this.runtime.fsx.existsSync(this.runtime.resolve('lerna.json')) } get usesYarnWorkspaces() { return this.hasYarnPackageLock && this.yarnWorkspacePatterns.length } get lernaPackagePatterns() { return !this.usesLerna ? [] : this.runtime.fsx.readJsonSync(this.runtime.resolve('lerna.json')).packages } get yarnWorkspacePatterns() { return this.runtime.get('currentPackage.workspaces', []) } get allVersionsByPackage() { return this.chain .get('remoteEntries') .fromPairs() .mapValues('versions') .value() } get versionMap() { const p = this return p.chain .result('manifests.values', []) .keyBy(v => v.name) .mapValues(v => v.version) .value() } /** * Returns all of the package manifests found. * * @type {Array<PackageManifest>} * @readonly * @memberof PackageManager */ get remoteData() { return Array.from(this.remotes.values()).map(v => this.runtime.convertToJS(v)) } /** * Returns each remote manifest as entries * * @type {Array<Array>} * @readonly * @memberof PackageManager */ get remoteEntries() { return this.remotes.entries().map(v => [v[0], this.runtime.convertToJS(v[1])]) } /** * Returns a table of all of the packages, their current version, and remote version */ get remoteVersionMap() { return this.chain .get('versionMap') .mapValues((local, name) => ({ local, remote: this.get(['remotesByName', name, 'version'], local), })) .value() } get cache() { return this.fileManager.createCache({ skypagerCachePath: this.findPackageCachePath(), }) } isPackageCacheEnabled() { const { options } = this const isDisabled = !!( String(this.tryGet('disablePackageCache')) === 'true' || String(this.tryGet('enablePackageCache')) === 'false' || process.env.DISABLE_PACKAGE_CACHE || options.noPackageCache || options.disablePackageCache || String(options.packageCache) === 'false' ) return !isDisabled } findPackageCachePath() { const { options } = this const { runtime } = this const { isEmpty } = this.lodash const packageCachePath = this.tryGet('packageCachePath', options.packageCachePath) if (packageCachePath && packageCachePath.length) { return runtime.resolve(packageCachePath) } if (process.env.SKYPAGER_PACKAGE_CACHE_ROOT) { return runtime.resolve(process.env.SKYPAGER_PACKAGE_CACHE_ROOT) } else if (process.env.PORTFOLIO_CACHE_ROOT) { return runtime.resolve(process.env.PORTFOLIO_CACHE_ROOT, 'skypager-package-manager') } else if (!isEmpty(runtime.gitInfo.root)) { return runtime.resolve( runtime.gitInfo.root, 'node_modules', '.cache', 'skypager-package-manager' ) } return runtime.resolve('node_modules', '.cache', 'skypager-package-manager') } get allEntities() { return this.packageNames.map(e => this.entity(e)) } entity(packageName) { if (this.entities.has(packageName)) { return this.entities.get(packageName) } const pkg = this.findByName(packageName) if (!pkg) { throw new Error(`Package ${packageName} not found`) } const p = new Package(pkg, { ...this.context, packageManager: this, }) this.entities.set(packageName, p) return p } /** * Finds a package by its id, or name * * @param {String} id the package id, or name * @returns {PackageManifest} */ find(id) { const ids = this.manifests.keys() const match = ids.find( i => i === id || i === `${id}/package.json` || i === `src/${id}` || i === `src/${id}/package.json` ) || id const result = this.manifests.get(match) || this.manifests.values().find(v => v && v.name && v.name === id) if (!result) { return } const toJS = v => this.runtime.convertToJS(v) return toJS(this.lodash.mapValues(result, v => toJS(v))) } /** * Finds a package by a function * * @param {Function} iterator * @returns {PackageManifest} */ findBy(fn) { return this.manifests.values().filter(fn || this.lodash.identity) } /** * Finds a package by its name * * @param {String} name */ findByName(name) { return this.manifests.get(name) || this.manifests.values().find(m => m.name === name) } /** * Find all dependents of a given package * * @param {String} packageName * @param {Object} options * @param {Boolean} [options.names=false] return the package names * @param {String|Boolean} [options.type='all'] which type of dependencies matter (one of: all,production,development) * @returns {Object<String, PackageManifest>|Array<String>} */ findDependentsOf(packageName, options = {}) { const { pickBy } = this.lodash const { names = false, type = 'any' } = options let results if (type === 'all' || type === 'any' || type === true) { results = pickBy(this.dependenciesMap, v => v[packageName]) } else if (type === 'production') { results = pickBy(this.buildDependenciesMap({ type: 'production' }), v => v[packageName]) } else if (type === 'development') { results = pickBy(this.buildDependenciesMap({ type: 'development' }), v => v[packageName]) } else if (type === 'both') { results = pickBy(this.buildDependenciesMap({ type: 'both' }), v => v[packageName]) } else { results = {} } return names ? Object.keys(results) : results } /** * For every package in the project, run the lodash pickBy function to get arbitrary attributes * * @param {Function} pickBy function which will get passed (value, key) * @returns {Array<Object>} */ pickAllBy(fn) { fn = typeof fn === 'function' ? fn : v => v return this.packageData.map(pkg => this.lodash.pickBy(pkg, fn)) } /** * For every package in the project, run the lodash pick function to get arbitrary attributes * * @param {...String} attributes list of attribute keys to pull from the package * @returns {Array<Object>} */ pickAll(...attributes) { return this.packageData.map(p => this.lodash.pick(p, ...attributes)) } /** * For every package in the project, run the lodash pickBy function to get arbitrary attributes * * @param {Function} pickBy function which will get passed (value, key) * @returns {Array<Object>} */ pickAllRemotesBy(fn) { fn = typeof fn === 'function' ? fn : v => v return this.remoteData.map(pkg => this.lodash.pickBy(pkg, fn)) } /** * For every package in the project, run the lodash pick function to get arbitrary attributes * * @param {...String} attributes list of attribute keys to pull from the package * @returns {Array<Object>} */ pickAllRemotes(...attributes) { return this.remoteData.map(p => this.lodash.pick(p, ...attributes)) } get pacote() { const { extract, packument, manifest, tarball } = pacote const { npmToken = this.options.npmToken } = this.currentState const enablePackageCache = this.isPackageCacheEnabled() const packageCachePath = this.findPackageCachePath() const twoArgs = fn => (spec, options = {}) => fn(spec, { ...(npmToken && { token: npmToken }), ...(enablePackageCache && { cache: packageCachePath }), ...options, }) const threeArgs = fn => (spec, dest, options = {}) => fn(spec, dest, { ...(npmToken && { token: npmToken }), ...(enablePackageCache && { cache: packageCachePath }), ...options, }) return { ...pacote, extract: threeArgs(extract), manifest: twoArgs(manifest), packument: twoArgs(packument), tarball: { ...twoArgs(tarball), toFile: threeArgs(tarball.toFile), stream: twoArgs(tarball.stream), }, } } async npmClient(options = {}) { if (this._npmClient && !options.fresh) { return this._npmClient } let npmToken = this.state.get('') await this.findAuthToken(options) const client = this.runtime.client('npm', { npmToken, ...options, }) return (this._npmClient = client) } async findAuthToken(options = {}) { if (!options.fresh || !options.refresh) { if (this.options.npmToken) { return this.options.npmToken } else if (process.env.NPM_TOKEN) { return process.env.NPM_TOKEN } else if (this.state.has('npmToken')) { return this.state.get('npmToken') } } const { cwd = this.runtime.cwd } = options const npmrcPath = await this.runtime.fsx.findUpAsync('.npmrc', { cwd, }) if (npmrcPath) { const contents = await this.runtime.fsx.readFileAsync(npmrcPath).then(buf => String(buf)) const lines = contents.split('\n') const authTokenLine = lines.find(line => { if (line.match(options.registry || 'registry.npmjs.org') && line.match(':_authToken=')) { return true } }) if (!authTokenLine) { return this.findAuthToken({ cwd: this.runtime.resolve(cwd, '..') }) } else { const value = authTokenLine.split(':_authToken=')[1] if (value) { this.state.set('authenticated', true) this.state.set('npmToken', value) } return value } } else { this.state.set('authenticated', true) this.state.delete('npmToken') return undefined } } /** * Find node module packages using the PackageFnder * * @param {Object} [options={}] options for the packageFinder.find method * @returns {Promise<Array<PackageManifest>>} * @memberof PackageManager */ async findNodeModules(options = {}) { const testPaths = await this.walkUp({ filename: 'node_modules' }) const packages = await this.finder.find( { testPaths: testPaths.concat(testPaths.map(p => p.replace('node_modules', ''))), moduleFolderName: options.folderName || 'node_modules', ...options, parse: true, }, this.context ) packages.forEach(pkg => { this.updateNodeModule(this.normalizePackage(pkg)) }) return packages } /** * Returns an index of all of the package names and their last modified timestamps * * @param {Object} options * @param {Boolean} [options.listFiles=false] include the files and their times */ async showLastModified(options = {}) { const { listFiles = false } = options const { fileManager } = this const { sortBy } = this.lodash const getMtime = file => (file.stats ? Math.ceil(file.stats.mtime / 1000) : 0) return this.chain .get('packageData', []) .map(({ name, _file }) => { const files = fileManager.fileObjects.filter( ({ path }) => _file && _file.dir && path.startsWith(_file.dir) ) return [name, files] }) .fromPairs() .mapValues(files => listFiles ? sortBy(files, getMtime) .reverse() .map(file => ({ id: file.relative, lastModified: getMtime(file), })) : files.reduce((memo, file) => { const mtime = getMtime(file) return mtime > memo ? mtime : memo }, 0) ) .value() } /** * Selects all of the files in the FileManager that live underneath a given package folder * * @param {*} [options={}] * @returns {Array<{ name: string, tree: array, manifest: PackageManifest }>} * @memberof PackageManager */ async selectPackageTree(options = {}) { if (typeof options === 'string') { options = { name: options } } const { name } = options const pkg = this.find(name) || this.findByName(name) if (pkg && pkg._packageId) { return this.runtime .select('files/tree', { rootNode: pkg._packageId.replace('/package.json', ''), readContents: true, hashFiles: true, ...options, }) .then(tree => ({ name: pkg.name, manifest: pkg, tree })) } else { return this.runtime .select('files/tree', { readContents: true, hashFiles: true, ...options, }) .then(tree => ({ name: this.runtime.get('currentPackage.name', this.runtime.cwd.split('/').pop()), manifest: this.runtime.currentPackage, tree, })) } } /** * Exports nodes and edges for use in a graph visualization * * @param {Object} [options={}] * @returns {PackageGraph} * @memberof PackageManager */ async exportGraph(options = {}) { const packageManager = this const { currentPackage } = this.runtime const { result, keys, pickBy, entries, flatten } = this.lodash const { byName } = this const { defaultProjectType = 'library', scope, exclude = [], direction = 'both' } = options const packageScope = scope || options.packageScope || currentPackage.name.startsWith('@') ? currentPackage.name.split('/')[0] : currentPackage.name.split('-') function stripPackageScope(fromName) { return fromName.replace(`${packageScope}/`, '') } function isDevDependency(sourceName, targetName) { const pkg = byName[sourceName] return pkg.devDependencies && pkg.devDependencies[targetName] } // a package can declare its projectType as a package.json property // at the top level, or under the key whose name matches the package scope (e.g. @skypager looks in skypager) const findProjectType = typeof options.findProjectType === 'function' ? options.findProjectType : p => result(p, 'projectType', () => result(p, [packageScope.replace('@', ''), 'projectType'], defaultProjectType) ) const packageDependents = this.chain .get('dependenciesMap') .mapValues(d => keys(pickBy(d, (v, k) => k.startsWith(packageScope) && exclude.indexOf(k) === -1)) ) .pickBy(v => v.length) .value() const packagesDependedOn = this.chain .get('packageNames') .filter(name => exclude.indexOf(name) === -1 && name.startsWith(packageScope)) .map(name => [name, keys(packageManager.findDependentsOf(name))]) .sortBy(v => v[1].length) .reject(v => !v[1].length) .fromPairs() .value() const nodes = this.packageData .filter( ({ name }) => exclude.indexOf(name) === -1 && (packagesDependedOn[name] || packageDependents[name]) ) .map((p, index) => { const { name } = p const projectType = findProjectType(p) return { data: { id: stripPackageScope(name), label: stripPackageScope(name) }, classes: [projectType], } }) .filter(Boolean) const dependsLinks = flatten( entries(packagesDependedOn) .filter(([targetName]) => exclude.indexOf(targetName) === -1) .map(([targetName, list]) => list .filter(sourceName => exclude.indexOf(sourceName) === -1) .map((sourceName, i) => ({ data: { source: stripPackageScope(sourceName), target: stripPackageScope(targetName), }, classes: [ 'depends', isDevDependency(sourceName, targetName) ? 'devDependency' : 'prodDependency', ], })) ) ) const needsLinks = flatten( entries(packageDependents) .filter(([sourceName]) => exclude.indexOf(sourceName) === -1) .map(([sourceName, list]) => list .filter(targetName => exclude.indexOf(targetName) === -1) .map((targetName, i) => { return { data: { source: stripPackageScope(sourceName), target: stripPackageScope(targetName), }, classes: [ 'needs', isDevDependency(sourceName, targetName) ? 'devDependency' : 'prodDependency', ], } }) ) ) let edges // graph the packages by what they depend on if (direction === 'depends') { edges = dependsLinks // graph the packages by what is depended on } else if (direction === 'needs') { edges = needsLinks } else if (direction === 'both') { // show both types of relationships edges = needsLinks.concat(dependsLinks) } // this is the shape required by the cytograph-dagre library return { graph: { nodes, edges, }, packagesDependedOn, packageDependents, packages: this.packageData, exclude, packageScope, direction, } } /** * Returns all of the packages who have modifications in their tree * * @param {Object} [options={}] * @param {Boolean} [dependents='true|false|production|development] include the dependents of the changed packages as well * @returns {Promise<Array>} * @memberof PackageManager */ async selectModifiedPackages(options = {}) { const { uniq, flatten } = this.lodash const { dependents = true } = options const packageIds = await this.runtime.select('package/changed', options) const withChanges = packageIds.map(id => this.manifests.get(id)).filter(Boolean) if (!dependents) { return withChanges } const modifiedNames = withChanges.map(({ name }) => name) const getAll = checkNames => uniq( flatten( checkNames.map(name => this.findDependentsOf(name, { names: true, type: dependents })) ).concat(checkNames) ) const finalList = uniq([1, 2, 3, 4].reduce(list => getAll(list).concat(list), modifiedNames)) return finalList.map(name => (options.names ? name : this.findByName(name))) } /** * Creates a JSON snapshot of all of the package manifests, * along with additional metadata * * @param {*} [options={}] * @returns {PackageManagerSnapshot} * @memberof PackageManager */ async createSnapshot(options = {}) { const { mapValues } = this.lodash const m = this.manifests.toJSON() const r = this.remotes.toJSON() const manifests = mapValues(m, v => this.runtime.convertToJS(v)) const remotes = mapValues(r, v => this.runtime.convertToJS(v)) return { manifests, remotes, gitInfo: this.runtime.gitInfo, cwd: this.runtime.cwd, versionMap: this.versionMap, latestMap: this.latestMap, } } /** * Gets a map of packages and their dependents * * @readonly * @memberof PackageManager */ get dependenciesMap() { return this.buildDependenciesMap({ type: 'all' }) } buildDependenciesMap(options = {}) { const { type = 'all' } = options const { at, defaults } = this.lodash return this.chain .invoke('manifests.values') .keyBy('name') .mapValues(v => { if (type === 'production') { return defaults({}, ...at(v, 'dependencies')) } else if (type === 'development') { return defaults({}, ...at(v, 'devDependencies')) } else if (type === 'both') { return defaults({}, ...at(v, 'dependencies', 'devDependencies')) } else { return defaults( {}, ...at(v, 'dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies') ) } }) .value() } async sortPackages(options = {}) { if (!this.usesLerna) { throw new Error(`We rely on lerna currently for their topological sorting.`) } const sorted = await this.runtime .select('process/output', { cmd: `lerna ls --toposort --json`, }) .then(lines => JSON.parse(lines.join('\n'))) return sorted.map(s => s.name) } async loadManifests(options = {}) { const { defaults, compact, castArray, flatten } = this.lodash const { runtime, fileManager } = this const packageIds = await fileManager.matchPaths(/package.json$/) const absolute = packageIds.map(p => runtime.resolve(p)) const include = compact(flatten([...absolute, ...castArray(options.include)])) await this.fileManager.readAllContent({ hash: true, ...options, include: p => include.indexOf(p) >= 0, }) this.failed = this.failed || [] packageIds.forEach(id => { try { const _file = fileManager.files.get(id) const _packageId = id const data = JSON.parse(_file.content) this.manifests.set( id, this.normalizePackage( defaults( {}, data, { _packageId, _file, }, this.manifests.get(id) ) ) ) } catch (error) { this.failed.push({ id, error }) } }) } async _loadManifests(options = {}) { const { defaults, compact, castArray, flatten } = this.lodash const { runtime, fileManager } = this const { manifestPath } = runtime const packageIds = await fileManager.matchPaths(/package.json$/) const absolute = packageIds.map(p => runtime.resolve(p)) const include = compact(flatten([...absolute, ...castArray(options.include)])) const results = await this.fileManager.readAllContent({ hash: true, ...options, include: p => include.indexOf(p) >= 0, }) this.failed = this.failed || [] try { this.manifests.set(this.runtime.relative(this.runtime.manifestPath), { ...this.runtime.currentPackage, _packageId: 'package.json', _file: this.fileManager.files.get('package.json'), }) } catch (error) {} results.forEach(entry => { const [id, content] = entry try { const data = JSON.parse(content || '{}') } catch (error) { this.failed.push([id, error]) } }) return this } walkUp(options = {}) { const testPaths = this.findModulePaths({ cwd: this.runtime.cwd, filename: 'package.json', ...options, }) return options.sync ? this.runtime.fsx.existingSync(...testPaths) : Promise.resolve(this.runtime.fsx.existingAsync(...testPaths)) } walkUpSync(options = {}) { const testPaths = this.findModulePaths({ cwd: this.runtime.cwd, filename: 'package.json', ...options, }) return this.runtime.fsx.existingSync(...testPaths) } findModulePaths(options = {}) { if (typeof options === 'string') { options = { cwd: options } } const cwd = options.cwd const filename = options.filename || options.file || 'skypager.js' const parts = cwd.split('/').slice(1) parts[0] = `/${parts[0]}` const testPaths = [] while (parts.length) { testPaths.push([...parts, filename].join('/')) parts.pop() } return testPaths } normalizePackage(manifest = {}) { const { defaults } = this.lodash return defaults(manifest, { keywords: [], description: '', author: '', contributors: [], scripts: {}, }) } async downloadPackage(packageName, options = {}) { const pkg = this.findByName(packageName) if (!pkg) { throw new Error(`Package ${packageName} not found`) } const { name } = pkg const { runtime } = this const { resolve, dirname, relative, sep } = runtime.pathUtils const { mkdirpAsync: mkdir, copyAsync: copy } = runtime.fsx const { uniqBy, identity } = this.lodash let { destination } = options const { version = pkg.version, folders = [], filter = identity, stripPrefix = 'package', dryRun, extract = false, replace = false, verbose = false, } = options const defaultDestination = resolve(runtime.cwd, 'build', 'packages', name, version) const downloadDestination = extract ? resolve(tmpdir(), name, version) : destination || defaultDestination await mkdir(downloadDestination) const tarballPath = await this.downloadTarball(`${name}@${version}`, downloadDestination) if (!extract) { return { name, version, tarballPath, dirname: dirname(tarballPath), } } const filterPaths = path => { let pass = !!filter(path) const item = stripPrefix ? path .split(sep) .slice(1) .join(sep) : path if (pass && folders.length) { pass = !!folders.find(i => item.startsWith(i)) } if (pass) { extracted.push(resolve(extractFolder, path)) } return pass } if (replace && !destination) { destination = pkg._file.dir await extractTar({ file: tarballPath, cwd: destination, filter: filterPaths, }) return { name, version, tarballPath, dirname: dirname(tarballPath), destination, } } const extracted = [] let extractFolder = dirname(tarballPath) await extractTar({ file: tarballPath, cwd: extractFolder, filter: filterPaths, }) const response = {} destination = destination ? resolve(runtime.cwd, destination) : defaultDestination const ops = extracted.map(sourceFile => { const destId = stripPrefix ? relative(extractFolder, sourceFile) .split(sep) .slice(1) .join(sep) : relative(extractFolder, sourceFile) const dest = resolve(destination, destId) const destDir = dirname(dest) return { destDir, destId, dest, sourceFile } }) const destDirectories = uniqBy(ops, 'destDir').map(op => op.destDir) response.ops = ops response.destinationDirectories = destDirectories if (dryRun) { console.log(`# Source:`, extractFolder) console.log(`# Destination:`, destination) if (verbose) { response.destinationDirectories.map(dir => { console.log(`mkdir -p ${dir}`) }) ops.map(({ sourceFile, dest }) => { console.log( `cp ${sourceFile.replace(extractFolder, '~')} ${dest.replace(destination, '$dest')}` ) }) } } else { // might just be able to tar extract directly on to the destination without making directories await Promise.all(response.destinationDirectories.map(dir => mkdir(dir))) await Promise.all(ops.map(({ sourceFile, dest }) => copy(sourceFile, dest))) } return { ...response, tarballPath, extracted, dirname: extractFolder, destination, } } async downloadTarball(spec, destination, options = {}) { const { mkdirpAsync: mkdir } = this.runtime.fsx if (!spec) { throw new Error('Please provide a valid package spec, e.g. @skypager/node@latest') } if (typeof destination === 'object') { options = destination destination = options.destination || options.dest } let [name, version] = spec.replace(/^@/, '').split('@') if (!destination) { if (!version || !version.length) { const manifest = await this.pacote.manifest(spec) version = manifest.version } destination = `build/packages/${name}/${version}/package.tgz` } const isDirectory = await this.runtime.fsx .statAsync(destination) .then(stat => stat.isDirectory()) .catch(error => false) if (isDirectory) { const fileName = `package-${name.replace('/', '-')}-${version}.tgz` destination = this.runtime.resolve(destination, fileName) } destination = this.runtime.resolve(destination) await mkdir(this.runtime.pathUtils.dirname(destination)) await this.pacote.tarball.toFile(spec, destination, options) return destination } packageProject(packageName, options = {}) { return this.createTarball(packageName, options) } async createTarball(packageName, options = {}) { const pkg = this.findByName(packageName) if (!pkg) { throw new Error(`Package ${packageName} not found`) } const dir = pkg._file.dir const files = await this.listPackageContents(packageName, { relative: false, hash: false, stats: false, }).then(results => results.map(r => r.path)) const { output = `${packageName.replace(/\//g, '-')}.tgz` } = options const file = this.runtime.resolve(output) const outputDir = this.runtime.pathUtils.dirname(file) await this.runtime.fsx.mkdirpAsync(outputDir) await createTar( { gzip: true, portable: true, mtime: new Date('1985-10-26T08:15:00.000Z'), prefix: 'package/', file, cwd: dir, ...options, }, files ) return file } /** * Uses npm-packlist to tell us everything in a project that will be published to npm * * @param {String} packageName the name of the package * @param {Object} options * @param {Boolean} [options.relative=false] whether to return the relative path, returns absolute by default. */ async listPackageContents(packageName, { relative = false, hash = false, stats = false } = {}) { const pkg = this.findByName(packageName) if (!pkg) { throw new Error(`Package ${packageName} not found`) } const dir = pkg._file.dir const { resolve: resolvePath } = this.runtime.pathUtils const files = await require('npm-packlist')({ path: dir }) const response = files.map(rel => ({ path: relative ? rel : resolvePath(dir, rel) })) const hashFile = file => new Promise((resolve, reject) => { require('md5-file')(resolvePath(resolvePath(dir, file.path)), (err, hash) => err ? reject(err) : resolve((file.hash = hash)) ) }) const fileSize = file => this.runtime.fsx .statAsync(resolvePath(dir, file.path)) .then(stats => (file.size = stats.size)) if (hash && stats) { await Promise.all(response.map(file => Promise.all([hashFile(file), fileSize(file)]))) } else if (hash) { await Promise.all(response.map(file => hashFile(file))) } else if (stats) { await Promise.all(response.map(file => fileSize(file))) } return response } /** * Uses npm-packlist to build the list of files that will be published to npm, * calculates an md5 hash of the contents of each of the files listed, and then * sorts them by the filename. Creates a hash of that unique set of objects, to * come up with a unique hash for the package source that is being released. * * @param {String} packageName * @param {Object} options * @param {Boolean} [options.compress=true] compress all the hashes into a single hash string value, setting to false will show the individual hashes of every file * @returns {String|Object} * @memberof PackageManager */ async calculatePackageHash(packageName, { compress = true } = {}) { const pkg = this.findByName(packageName) if (!pkg) { throw new Error(`Package ${packageName} not found`) } const { resolve: resolvePath } = this.runtime.pathUtils const { dir } = pkg._file const hash = file => new Promise((resolve, reject) => { file = resolvePath(dir, file) require('md5-file')(file, (err, hash) => (err ? reject(err) : resolve(hash))) }) const files = await require('npm-packlist')({ path: dir }) const { hashObject } = this.runtime const { sortBy } = this.lodash const hashes = await Promise.all(files.map(file => hash(file).then(hash => [file, hash]))) return compress ? hashObject(sortBy(hashes, entry => entry[0])) : hashes } }
JavaScript
class Root extends Component { render () { return ( <Provider store={store}> <Router history={history} routes={rootRoute} /> </Provider> ); } }
JavaScript
class Model { constructor(name, options) { this._name = name.toLowerCase(); this._db = null; this._model = null; this._options = options || {}; } preSave(data) { const cData = { ...data }; if (this._options.timestamp) { cData.createdAt = new Date(Date.now()); cData.updatedAt = new Date(Date.now()); } return cData; } preUpdate(update) { const cUpdate = { ...update }; if (this._options.timestamp) { if (_.isNil(update.$set)) { cUpdate.$set = {}; } cUpdate.$set.updatedAt = new Date(Date.now()); } return cUpdate; } get name() { return this._name; } get options() { return this._options; } set database(db) { this._db = db; this._model = this._db.collection(this._name); } get database() { return this._db; } get model() { return this._model; } async create(data) { let document = data; if (this.preSave) { document = this.preSave(data); } return this._model.insertOne(document) .then((res) => (res.insertedCount > 0 ? res.ops[0] : null)); } async updateById(id, update, options = {}) { let cUpdate = { ...update }; if (this.preUpdate) { cUpdate = this.preUpdate(update); } return this._model.findOneAndUpdate({ _id: new ObjectId(id) }, cUpdate, options) .then((res) => res.value); } async updateOne(filter, update, options = {}) { let cUpdate = { ...update }; if (this.preUpdate) { cUpdate = this.preUpdate(update); } return this._model.findOneAndUpdate(filter, cUpdate, options) .then((res) => res.value); } async find(filter = {}, options = {}) { return this._model.find(filter, options); } async findOne(filter, options = {}) { return this._model.findOne(filter, options); } async findById(id, options = {}) { return this._model.findOne({ _id: new ObjectId(id) }, options); } async deleteOne(filter, options = {}) { return this._model.findOneAndDelete(filter, options) .then((res) => res.value); } async deleteById(id, options = {}) { return this._model.findOneAndDelete({ _id: new ObjectId(id) }, options) .then((res) => res.value); } async exists(filter) { return this._model.findOne(filter).then((res) => !_.isNil(res)); } async count(filter) { if (filter) { return this._model.countDocuments(filter); } return this._model.estimatedDocumentCount(); } }
JavaScript
class OpenAPIValidator { /** * Creates an instance of OpenAPIValidation * * @param opts - constructor options * @param {Document | string} opts.definition - the OpenAPI definition, file path or Document object * @param {object} opts.ajvOpts - default ajv constructor opts (default: { unknownFormats: 'ignore' }) * @param {OpenAPIRouter} opts.router - passed instance of OpenAPIRouter. Will create own child if no passed * @param {boolean} opts.lazyCompileValidators - skips precompiling Ajv validators and compiles only when needed * @memberof OpenAPIRequestValidator */ constructor(opts) { this.definition = opts.definition; this.ajvOpts = Object.assign({ unknownFormats: 'ignore', nullable: true }, (opts.ajvOpts || {})); this.customizeAjv = opts.customizeAjv; // initalize router this.router = opts.router || new router_1.OpenAPIRouter({ definition: this.definition }); // initialize validator stores this.requestValidators = {}; this.responseValidators = {}; this.statusBasedResponseValidators = {}; this.responseHeadersValidators = {}; // precompile validators if not in lazy mode if (!opts.lazyCompileValidators) { this.preCompileRequestValidators(); this.preCompileResponseValidators(); this.preCompileResponseHeaderValidators(); } } /** * Pre-compiles Ajv validators for requests of all api operations * * @memberof OpenAPIValidator */ preCompileRequestValidators() { const operations = this.router.getOperations(); for (const operation of operations) { const operationId = utils_1.default.getOperationId(operation); this.requestValidators[operationId] = this.buildRequestValidatorsForOperation(operation); } } /** * Pre-compiles Ajv validators for responses of all api operations * * @memberof OpenAPIValidator */ preCompileResponseValidators() { const operations = this.router.getOperations(); for (const operation of operations) { const operationId = utils_1.default.getOperationId(operation); this.responseValidators[operationId] = this.buildResponseValidatorForOperation(operation); this.statusBasedResponseValidators[operationId] = this.buildStatusBasedResponseValidatorForOperation(operation); } } /** * Pre-compiles Ajv validators for response headers of all api operations * * @memberof OpenAPIValidator */ preCompileResponseHeaderValidators() { const operations = this.router.getOperations(); for (const operation of operations) { const operationId = utils_1.default.getOperationId(operation); this.responseHeadersValidators[operationId] = this.buildResponseHeadersValidatorForOperation(operation); } } /** * Validates a request against prebuilt Ajv validators and returns the validation result. * * The method will first match the request to an API operation and use the pre-compiled Ajv validation schema to * validate it. * * @param {Request} req - request to validate * @param {(Operation | string)} operation - operation to validate against * @returns {ValidationResult} * @memberof OpenAPIRequestValidator */ validateRequest(req, operation) { const result = { valid: true }; result.errors = []; if (!operation) { operation = this.router.matchOperation(req); } else if (typeof operation === 'string') { operation = this.router.getOperation(operation); } if (!operation || !operation.operationId) { throw new Error(`Unknown operation`); } // get pre-compiled ajv schemas for operation const { operationId } = operation; const validators = this.getRequestValidatorsForOperation(operationId) || []; // build a parameter object to validate const { params, query, headers, cookies, requestBody } = this.router.parseRequest(req, operation); // convert singular query parameters to arrays if specified as array in operation parametes if (query) { for (const [name, value] of _.entries(query)) { if (typeof value === 'string') { const operationParameter = _.find(operation.parameters, { name, in: 'query' }); if (operationParameter) { const { schema } = operationParameter; if (schema && schema.type === 'array') { query[name] = [value]; } } } } } const parameters = _.omitBy({ path: params, query, header: headers, cookie: cookies, }, _.isNil); if (typeof req.body !== 'object' && req.body !== undefined) { const payloadFormats = _.keys(_.get(operation, 'requestBody.content', {})); if (payloadFormats.length === 1 && payloadFormats[0] === 'application/json') { // check that JSON isn't malformed when the only payload format is JSON try { JSON.parse(`${req.body}`); } catch (err) { result.errors.push({ keyword: 'parse', dataPath: '', schemaPath: '#/requestBody', params: [], message: err.message, }); } } } if (typeof requestBody === 'object' || headers['content-type'] === 'application/json') { // include request body in validation if an object is provided parameters.requestBody = requestBody; } // validate parameters against each pre-compiled schema for (const validate of validators) { validate(parameters); if (validate.errors) { result.errors.push(...validate.errors); } } if (_.isEmpty(result.errors)) { // set empty errors array to null so we can check for result.errors truthiness result.errors = null; } else { // there were errors, set valid to false result.valid = false; } return result; } /** * Validates a response against a prebuilt Ajv validator and returns the result * * @param {*} res * @param {(Operation | string)} [operation] * @package {number} [statusCode] * @returns {ValidationResult} * @memberof OpenAPIRequestValidator */ validateResponse(res, operation, statusCode) { const result = { valid: true }; result.errors = []; const op = typeof operation === 'string' ? this.router.getOperation(operation) : operation; if (!op || !op.operationId) { throw new Error(`Unknown operation`); } const { operationId } = op; let validate = null; if (statusCode) { // use specific status code const validateMap = this.getStatusBasedResponseValidatorForOperation(operationId); if (validateMap) { validate = utils_1.default.findStatusCodeMatch(statusCode, validateMap); } } else { // match against all status codes validate = this.getResponseValidatorForOperation(operationId); } if (validate) { // perform validation against response validate(res); if (validate.errors) { result.errors.push(...validate.errors); } } else { // maybe we should warn about this? TODO: add option to enable / disable warnings // console.warn(`No validation matched for ${JSON.stringify({ operationId, statusCode })}`); } if (_.isEmpty(result.errors)) { // set empty errors array to null so we can check for result.errors truthiness result.errors = null; } else { // there were errors, set valid to false result.valid = false; } return result; } /** * Validates response headers against a prebuilt Ajv validator and returns the result * * @param {*} headers * @param {(Operation | string)} [operation] * @param {number} [opts.statusCode] * @param {SetMatchType} [opts.setMatchType] - one of 'any', 'superset', 'subset', 'exact' * @returns {ValidationResult} * @memberof OpenAPIRequestValidator */ validateResponseHeaders(headers, operation, opts) { const result = { valid: true }; result.errors = []; const op = typeof operation === 'string' ? this.router.getOperation(operation) : operation; if (!op || !op.operationId) { throw new Error(`Unknown operation`); } let setMatchType = opts && opts.setMatchType; const statusCode = opts && opts.statusCode; if (!setMatchType) { setMatchType = backend_1.SetMatchType.Any; } else if (!_.includes(Object.values(backend_1.SetMatchType), setMatchType)) { throw new Error(`Unknown setMatchType ${setMatchType}`); } const { operationId } = op; const validateMap = this.getResponseHeadersValidatorForOperation(operationId); if (validateMap) { let validateForStatus; if (statusCode) { validateForStatus = utils_1.default.findStatusCodeMatch(statusCode, validateMap); } else { validateForStatus = utils_1.default.findDefaultStatusCodeMatch(validateMap).res; } if (validateForStatus) { const validate = validateForStatus[setMatchType]; if (validate) { headers = _.mapKeys(headers, (value, headerName) => headerName.toLowerCase()); validate({ headers }); if (validate.errors) { result.errors.push(...validate.errors); } } } } if (_.isEmpty(result.errors)) { // set empty errors array to null so we can check for result.errors truthiness result.errors = null; } else { // there were errors, set valid to false result.valid = false; } return result; } /** * Get an array of request validator functions for an operation by operationId * * @param {string} operationId * @returns {*} {(Ajv.ValidateFunction[] | null)} * @memberof OpenAPIValidator */ getRequestValidatorsForOperation(operationId) { if (this.requestValidators[operationId] === undefined) { const operation = this.router.getOperation(operationId); this.requestValidators[operationId] = this.buildRequestValidatorsForOperation(operation); } return this.requestValidators[operationId]; } /** * Compiles a schema with Ajv instance and handles circular references. * * @param ajv The Ajv instance * @param schema The schema to compile */ static compileSchema(ajv, schema) { const decycledSchema = this.decycle(schema); return ajv.compile(decycledSchema); } /** * Produces a deep clone which replaces object reference cycles with JSONSchema refs. * This function is based on [cycle.js]{@link https://github.com/douglascrockford/JSON-js/blob/master/cycle.js}, which was referred by * the [MDN]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value}. * @param object An object for which to remove cycles */ static decycle(object) { const objects = new WeakMap(); // object to path mappings return (function derez(value, path) { // The derez function recurses through the object, producing the deep copy. let oldPath; // The path of an earlier occurance of value let nu; // The new object or array // typeof null === "object", so go on if this value is really an object but not // one of the weird builtin objects. if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { // If the value is an object or array, look to see if we have already // encountered it. If so, return a {"$ref":PATH} object. This uses an // ES6 WeakMap. oldPath = objects.get(value); if (oldPath !== undefined) { return { $ref: oldPath }; } // Otherwise, accumulate the unique value and its path. objects.set(value, path); // If it is an array, replicate the array. if (Array.isArray(value)) { nu = []; value.forEach((element, i) => { nu[i] = derez(element, path + '/' + i); }); } else { // If it is an object, replicate the object. nu = {}; Object.keys(value).forEach((name) => { nu[name] = derez(value[name], path + '/' + name); }); } return nu; } return value; })(object, '#'); } /** * Builds Ajv request validation functions for an operation and registers them to requestValidators * * @param {Operation} operation * @returns {*} {(Ajv.ValidateFunction[] | null)} * @memberof OpenAPIValidator */ buildRequestValidatorsForOperation(operation) { if (!(operation === null || operation === void 0 ? void 0 : operation.operationId)) { // no operationId, don't register a validator return null; } // validator functions for this operation const validators = []; // schema for operation requestBody if (operation.requestBody) { const requestBody = operation.requestBody; const jsonbody = requestBody.content['application/json']; if (jsonbody && jsonbody.schema) { const requestBodySchema = { title: 'Request', type: 'object', additionalProperties: true, properties: { requestBody: jsonbody.schema, }, }; requestBodySchema.required = []; if (_.keys(requestBody.content).length === 1) { // if application/json is the only specified format, it's required requestBodySchema.required.push('requestBody'); } // add compiled params schema to schemas for this operation id const requestBodyValidator = this.getAjv(ValidationContext.RequestBody); validators.push(OpenAPIValidator.compileSchema(requestBodyValidator, requestBodySchema)); } } // schema for operation parameters in: path,query,header,cookie const paramsSchema = { title: 'Request', type: 'object', additionalProperties: true, properties: { path: { type: 'object', additionalProperties: false, properties: {}, required: [], }, query: { type: 'object', properties: {}, additionalProperties: false, required: [], }, header: { type: 'object', additionalProperties: true, properties: {}, required: [], }, cookie: { type: 'object', additionalProperties: true, properties: {}, required: [], }, }, required: [], }; // params are dereferenced here, no reference objects. const { parameters } = operation; if (parameters) { parameters.map((parameter) => { const param = parameter; const target = paramsSchema.properties[param.in]; // Header params are case-insensitive according to https://tools.ietf.org/html/rfc7230#page-22, so they are // normalized to lower case and validated as such. const normalizedParamName = param.in === 'header' ? param.name.toLowerCase() : param.name; if (param.required) { target.required = target.required || []; target.required = _.uniq([...target.required, normalizedParamName]); paramsSchema.required = _.uniq([...paramsSchema.required, param.in]); } target.properties = target.properties || {}; if (param.content && param.content['application/json']) { target.properties[normalizedParamName] = param.content['application/json'].schema; } else { target.properties[normalizedParamName] = param.schema; } }); } // add compiled params schema to requestValidators for this operation id const paramsValidator = this.getAjv(ValidationContext.Params, { coerceTypes: true }); validators.push(OpenAPIValidator.compileSchema(paramsValidator, paramsSchema)); return validators; } /** * Get response validator function for an operation by operationId * * @param {string} operationId * @returns {*} {(Ajv.ValidateFunction | null)} * @memberof OpenAPIValidator */ getResponseValidatorForOperation(operationId) { if (this.responseValidators[operationId] === undefined) { const operation = this.router.getOperation(operationId); this.responseValidators[operationId] = this.buildResponseValidatorForOperation(operation); } return this.responseValidators[operationId]; } /** * Builds an ajv response validator function for an operation and registers it to responseValidators * * @param {Operation} operation * @returns {*} {(Ajv.ValidateFunction | null)} * @memberof OpenAPIValidator */ buildResponseValidatorForOperation(operation) { if (!operation || !operation.operationId) { // no operationId, don't register a validator return null; } if (!operation.responses) { // operation has no responses, don't register a validator return null; } const responseSchemas = []; _.mapKeys(operation.responses, (res, status) => { const response = res; if (response.content && response.content['application/json'] && response.content['application/json'].schema) { responseSchemas.push(response.content['application/json'].schema); } return null; }); if (_.isEmpty(responseSchemas)) { // operation has no response schemas, don't register a validator return null; } // compile the validator function and register to responseValidators const schema = { oneOf: responseSchemas }; const responseValidator = this.getAjv(ValidationContext.Response); return OpenAPIValidator.compileSchema(responseValidator, schema); } /** * Get response validator function for an operation by operationId * * @param {string} operationId * @returns {*} {(StatusBasedResponseValidatorsFunctionMap | null)} * @memberof OpenAPIRequestValidator */ getStatusBasedResponseValidatorForOperation(operationId) { if (this.statusBasedResponseValidators[operationId] === undefined) { const operation = this.router.getOperation(operationId); this.statusBasedResponseValidators[operationId] = this.buildStatusBasedResponseValidatorForOperation(operation); } return this.statusBasedResponseValidators[operationId]; } /** * Builds an ajv response validator function for an operation and registers it to responseHeadersValidators * * @param {Operation} operation * @returns {*} {(StatusBasedResponseValidatorsFunctionMap | null)} * @memberof OpenAPIValidator */ buildStatusBasedResponseValidatorForOperation(operation) { if (!operation || !operation.operationId) { // no operationId, don't register a validator return null; } if (!operation.responses) { // operation has no responses, don't register a validator return null; } const responseValidators = {}; const validator = this.getAjv(ValidationContext.Response); _.mapKeys(operation.responses, (res, status) => { const response = res; if (response.content && response.content['application/json'] && response.content['application/json'].schema) { const validateFn = response.content['application/json'].schema; responseValidators[status] = OpenAPIValidator.compileSchema(validator, validateFn); } return null; }); return responseValidators; } /** * Get response validator function for an operation by operationId * * @param {string} operationId * @returns {*} {(ResponseHeadersValidateFunctionMap | null)} * @memberof OpenAPIRequestValidator */ getResponseHeadersValidatorForOperation(operationId) { if (this.responseHeadersValidators[operationId] === undefined) { const operation = this.router.getOperation(operationId); this.responseHeadersValidators[operationId] = this.buildResponseHeadersValidatorForOperation(operation); } return this.responseHeadersValidators[operationId]; } /** * Builds an ajv response validator function for an operation and returns it * * @param {Operation} operation * @returns {*} {(ResponseHeadersValidateFunctionMap | null)} * @memberof OpenAPIValidator */ buildResponseHeadersValidatorForOperation(operation) { if (!operation || !operation.operationId) { // no operationId, don't register a validator return null; } if (!operation.responses) { // operation has no responses, don't register a validator return null; } const headerValidators = {}; const validator = this.getAjv(ValidationContext.ResponseHeaders, { coerceTypes: true }); _.mapKeys(operation.responses, (res, status) => { const response = res; const validateFns = {}; const properties = {}; const required = []; _.mapKeys(response.headers, (h, headerName) => { const header = h; headerName = headerName.toLowerCase(); if (header.schema) { properties[headerName] = header.schema; required.push(headerName); } return null; }); validateFns[backend_1.SetMatchType.Any] = OpenAPIValidator.compileSchema(validator, { type: 'object', properties: { headers: { type: 'object', additionalProperties: true, properties, required: [], }, }, }); validateFns[backend_1.SetMatchType.Superset] = OpenAPIValidator.compileSchema(validator, { type: 'object', properties: { headers: { type: 'object', additionalProperties: true, properties, required, }, }, }); validateFns[backend_1.SetMatchType.Subset] = OpenAPIValidator.compileSchema(validator, { type: 'object', properties: { headers: { type: 'object', additionalProperties: false, properties, required: [], }, }, }); validateFns[backend_1.SetMatchType.Exact] = OpenAPIValidator.compileSchema(validator, { type: 'object', properties: { headers: { type: 'object', additionalProperties: false, properties, required, }, }, }); headerValidators[status] = validateFns; return null; }); return headerValidators; } /** * Get Ajv options * * @param {ValidationContext} validationContext * @param {Ajv.Options} [opts={}] * @returns Ajv * @memberof OpenAPIValidator */ getAjv(validationContext, opts = {}) { const ajvOpts = Object.assign(Object.assign({}, this.ajvOpts), opts); const ajv = new Ajv(ajvOpts); for (const [name, format] of Object.entries(defaultFormats)) { ajv.addFormat(name, format); } if (this.customizeAjv) { return this.customizeAjv(ajv, ajvOpts, validationContext); } return ajv; } }
JavaScript
class ResultComponent { constructor() { this._type = ''; this._icon = ''; } /** * @param {?} value * @return {?} */ set type(value) { this._type = value; switch (value) { case 'success': this._icon = 'check-circle'; break; case 'error': this._icon = 'close-circle'; break; default: this._icon = value; break; } } }
JavaScript
class Database { constructor(driver = MySQL) { let configuration = JSON.parse(readFile('database.json')); // Establish a connection with the MySQL server using the configuration. this.connection_ = new driver(configuration.hostname, configuration.username, configuration.password, configuration.database, configuration.port); // Announce the result of the connection attempt once its known. this.connection_.ready.then( () => console.log('[Database] The connection with the database has been established.'), error => console.log('[Database] Unable to connect to the database:', error)); } // Returns the total number of queries that have been executed on the connection. get totalQueryCount() { return this.connection_.totalQueryCount; } // Returns the number of queries which are still unresolved. get unresolvedQueryCount() { return this.connection_.unresolvedQueryCount; } // Returns the connection that's powering the Database instance. Should only be used for tests. get connectionForTests() { return this.connection_; } // Closes the MySQL connection. Further use of the Database class will yield errors. dispose() { this.connection_.close(); this.connection_ = null; } // Executes |query| on the MySQL connection. Returns a promise that will be resolved when the // query either has finished executing, or reject when the query cannot be executed. // // Rather than including parameters directly in the |query|, consider using question marks and // passing the substitutions as additional parameters. They will be substituted within the |query| // safely, in order, reducing the possibility of running unwanted queries by accident. query(query, ...parameters) { let substitutionIndex = 0; return this.connection_.query(query.replace(/(^|[^\?])\?(?!\?)/g, (_, prefix) => { if (substitutionIndex >= parameters.length) throw new Error('Not enough substitution parameters were provided for this query.'); return substituteValue(prefix, parameters[substitutionIndex], substitutionIndex++); })); } }
JavaScript
class Wall { constructor(name = 'wall', width = 25, height = 10, depth = 0.5) { const mesh = BABYLON.MeshBuilder.CreateBox(name, {width, height, depth}, Scene); mesh.material = new BABYLON.StandardMaterial('wallMat', Scene); mesh.position.y = height / 2; mesh.checkCollisions = true; // Handle events when mouse moves over the mesh mesh.actionManager = new BABYLON.ActionManager(Scene); mesh.actionManager.registerAction(new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnPointerOverTrigger, this.onMouseOver)); mesh.actionManager.registerAction(new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnPointerOutTrigger, this.onMouseOut)); this.mesh = mesh; } /** * Handles the mouse over event * @param mesh The mesh that was hovered over */ onMouseOver(mesh) { if (mesh.meshUnderPointer !== null) { mesh.meshUnderPointer.renderOutline = true; mesh.meshUnderPointer.outlineWidth = MESH_OUTLINE_WIDTH; } } /** * Handles the mouse out event * @param mesh The mesh that was previously hovered over */ onMouseOut(mesh) { if (mesh.meshUnderPointer !== null) { mesh.meshUnderPointer.renderOutline = false; } } }
JavaScript
class Input { /** * @param {Model} model * @param {Element} * @return {Input} */ constructor(model, inputElement) { /** * @type {Object} */ this.model = model; /** * @type {boolean} * @private */ this._firstUpdate = true; /** * @type {Element} */ this.elem = inputElement; if (this.model.options.observer) { this.observe(); } this.addInitialClass(); /** * @type {Number} */ this.initialUnix = null; if (this.model.options.inline == false) { this._attachInputElementEvents(); } return this; } addInitialClass() { $(this.elem).addClass('pwt-datepicker-input-element'); } parseInput(inputString) { let parse = new PersianDateParser(), that = this; if (parse.parse(inputString) !== undefined) { let pd = this.model.PersianDate.date(parse.parse(inputString)).valueOf(); that.model.state.setSelectedDateTime('unix', pd); that.model.state.setViewDateTime('unix', pd); that.model.view.render(); } } observe() { let that = this; ///////////////// Manipulate by Copy And paste $(that.elem).bind('paste', function (e) { Helper.delay(function () { that.parseInput(e.target.value); }, 60); }); let typingTimer, doneTypingInterval = that.model.options.inputDelay, ctrlDown = false, ctrlKey = [17, 91], vKey = 86; $(document).keydown(function (e) { if ($.inArray(e.keyCode, ctrlKey) > 0) ctrlDown = true; }).keyup(function (e) { if ($.inArray(e.keyCode, ctrlKey) > 0) ctrlDown = false; }); $(that.elem).bind('keyup', function (e) { let $self = $(this); let trueKey = false; if (e.keyCode === 8 || e.keyCode < 105 && e.keyCode > 96 || e.keyCode < 58 && e.keyCode > 47 || (ctrlDown && (e.keyCode == vKey || $.inArray(e.keyCode, ctrlKey) > 0 ))) { trueKey = true; } if (trueKey) { clearTimeout(typingTimer); typingTimer = setTimeout(function () { doneTyping($self); }, doneTypingInterval); } }); $(that.elem).on('keydown', function () { clearTimeout(typingTimer); }); function doneTyping($self) { that.parseInput($self.val()); } ///////////////// Manipulate by alt changes // TODO // self.model.options.altField.bind("change", function () { // //if (!self._flagSelfManipulate) { // let newDate = new Date($(this).val()); // if (newDate !== "Invalid Date") { // let newPersainDate = this.model.PersianDate.date(newDate); // self.selectDate(newPersainDate.valueOf()); // } // // } // }); } /** * @private * @desc attach events to input field */ _attachInputElementEvents() { let that = this; let closePickerHandler = function (e) { if (!$(e.target).is(that.elem) && !$(e.target).is(that.model.view.$container) && $(e.target).closest('#' + that.model.view.$container.attr('id')).length == 0 && !$(e.target).is($(that.elem).children())) { that.model.api.hide(); $('body').unbind('click', that._closePickerHandler); } }; that._closePickerHandler = closePickerHandler; $(this.elem).on('focus click', Helper.debounce(function (evt) { that.model.api.show(); if (that.model.state.ui.isInline === false) { $('body').unbind('click', that._closePickerHandler).bind('click', that._closePickerHandler); } if (Helper.isMobile) { $(this).blur(); } evt.stopPropagation(); return false; }, 200)); $(this.elem).on('keydown', Helper.debounce(function (evt) { if (evt.which === 9){ that.model.api.hide(); return false; } }, 200)); } /** * @desc get <input/> element position * @return {{top: Number, left: Number}} * @todo remove jquery */ getInputPosition() { return $(this.elem).offset(); } /** * @desc get <input/> element size * @return {{width: Number, height: Number}} * @todo remove jquery */ getInputSize() { return { width: $(this.elem).outerWidth(), height: $(this.elem).outerHeight() }; } /** * @desc update <input/> element value * @param {Number} unix * @todo remove jquery * @private */ _updateAltField(unix) { let value = this.model.options.altFieldFormatter(unix); $(this.model.options.altField).val(value); } /** * @desc update <input/> element value * @param {Number} unix * @todo remove jquery * @private */ _updateInputField(unix) { let value = this.model.options.formatter(unix); if ($(this.elem).val() != value) { $(this.elem).val(value); } } /** * @param unix */ update(unix) { if (this.model.options.initialValue == false && this._firstUpdate) { this._firstUpdate = false; } else { this._updateInputField(unix); this._updateAltField(unix); } } /** * @desc return initial value * @return {Number} - unix */ getOnInitState() { const persianDatePickerTimeRegex = '^([0-1][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9]))?$'; let garegurianDate = null, $inputElem = $(this.elem), inputValue; // Define input value by check inline mode and input mode if ($inputElem[0].nodeName === 'INPUT') { inputValue = $inputElem[0].getAttribute('value'); } else { inputValue = $inputElem.data('date'); } // Check time string by regex if (inputValue && inputValue.match(persianDatePickerTimeRegex)) { let timeArray = inputValue.split(':'), tempDate = new Date(); tempDate.setHours(timeArray[0]); tempDate.setMinutes(timeArray[1]); if (timeArray[2]) { tempDate.setSeconds(timeArray[2]); } else { tempDate.setSeconds(0); } this.initialUnix = tempDate.valueOf(); } else { if (this.model.options.initialValueType === 'persian' && inputValue) { let parse = new PersianDateParser(); let pd = new persianDate(parse.parse(inputValue)).valueOf(); garegurianDate = new Date(pd).valueOf(); } else if (this.model.options.initialValueType === 'unix' && inputValue) { garegurianDate = parseInt(inputValue); } else if (inputValue) { garegurianDate = new Date(inputValue).valueOf(); } if (garegurianDate && garegurianDate != 'undefined') { this.initialUnix = garegurianDate; } else { this.initialUnix = new Date().valueOf(); } } return this.initialUnix; } }
JavaScript
class DocxImager { /** * Represents a DocxImager instance * @constructor */ constructor(){ this.zip = null; } /** * Load the DocxImager instance with the docx. * @param {String} docx_path full path of the template docx * @returns {Promise} */ async load(docx_path){ return this.__loadDocx(docx_path).catch((e)=>{ console.log(e); }); } async __loadDocx(docx_path){ let zip = new JSZip(); this.zip = await zip.loadAsync(fs.readFileSync(docx_path)); } /** * Replaces the template image with the image obtained from the web url * @param {String} image_uri web uri of the image * @param {String} image_id id of the image in the docx * @param {String} type type of the template image * @returns {Promise} */ replaceWithImageURL(image_uri, image_id, type, cbk){ this.__validateDocx(); let req3 = https.request(image_uri, (res) => { let buffer = []; res.on('data', (d) => { buffer.push(d); }); res.on('end', ()=>{ fs.writeFileSync('t1.'+type, Buffer.concat(buffer)); //res.headers['content-type'] this.__replaceImage(Buffer.concat(buffer), image_id, type, cbk); }); }); req3.on('error', (e) => { console.error(e); }); req3.end(); } /** * Replaces the template image with the image obtained from the local path * @param {String} image_path full path of the image in the local system * @param {String} image_id id of the image in the docx * @param {String} type type of the template image * @returns {Promise} */ replaceWithLocalImage(image_path, image_id, type, cbk){ this.__validateDocx(); let image_buffer = fs.readFileSync(image_path); this.__replaceImage(image_buffer, image_id, type, cbk); } /** * Replaces the template image with the image obtained from the Base64 string * @param {String} base64_string Base64 form of the image * @param {String} image_id id of the image in the docx * @param {String} type type of the template image * @returns {Promise} */ replaceWithB64Image(base64_string, image_id, type, cbk){ this.__validateDocx(); this.__replaceImage(Buffer.from(base64_string, 'base64'), image_id, type, cbk); } async __replaceImage(buffer, image_id, type, cbk){ //1. replace the image return new Promise((res, rej)=>{ try{ let path = 'word/media/image'+image_id+'.'+type; this.zip.file(path, buffer); res(true); }catch(e){ rej(); } }); } // {{insert_image variable_name type width height }} + {variable_name : "image_url"} //context - dict of variable_name vs url async insertImage(context){ // a. get the list of all variables. let variables = await this.__getVariableNames(); //b. download/retrieve images. let final_context = await this.__getImages(variables, context); //deep merge image buffer/name and meta. for(let var_name in final_context){ if(final_context.hasOwnProperty(var_name)){ final_context[var_name][TYPE] = variables[var_name][TYPE]; final_context[var_name][HEIGHT] = variables[var_name][HEIGHT]; final_context[var_name][WIDTH] = variables[var_name][WIDTH]; } } //1. insert entry in [Content-Type].xml await this._addContentType(final_context); //2. write image in media folder in word/ /*let image_path = */await this._addImage(final_context); //3. insert entry in /word/_rels/document.xml.rels //<Relationship Id="rId3" Type=IMAGE_URI Target="media/image2.png"/> /*let rel_id = */await this._addRelationship(final_context); //4. insert in document.xml after calculating EMU. await this._addInDocumentXML(final_context); // this.zip.generateNodeStream({streamFiles : true}) // .pipe(fs.createWriteStream('./merged.docx')) // .on('finish', function(x){ // callback(); // }); // http://polymathprogrammer.com/2009/10/22/english-metric-units-and-open-xml/ // https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/ } /** * Saves the transformed docx. * @param {String} op_file_name Output file name with full path. * @returns {Promise} */ async save(op_file_name){ if(!op_file_name){ op_file_name = './merged.docx'; } return new Promise(async(res, rej)=>{ this.zip.generateNodeStream({streamFiles : true}) .pipe(fs.createWriteStream(op_file_name)) .on('finish', function(x){ res(); }); }); } async __getVariableNames(){ return new Promise(async (res, rej)=>{ try{ let content = await this.zip.file('word/document.xml').async('nodebuffer'); content = content.toString(); content = DocxImager.__cleanXML(content); let matches = content.match(/(<w:r>.*?insert_image.*?<\/w:r>)/g); //match all r tags if(matches && matches.length){ let variables = {}; for(let i = 0; i < matches.length; i++){ let tag = matches[i].match(/{{(.*?)}}/g)[0]; let splits = tag.split(' '); let node = {}; // node['variable_name'] = splits[1]; node[TYPE] = splits[2]; node[WIDTH] = splits[3]; node[HEIGHT] = splits[4]; variables[splits[1]] = node; } res(variables); }else{ rej(new Error('Invalid Docx')); } }catch(e){ console.log(e); rej(e); } }); } async __getImages(variables, context){ return new Promise(async (res, rej)=>{ try{ let image_map = {}; for(let variable_name in variables){ if(variables.hasOwnProperty(variable_name)){ let path = context[variable_name]; //TODO assuming the path is the url, also check for local/b64. let buffer = await this.__getImageBuffer(path, IMAGE_RETRIEVAL_TYPE.URL); let name = 'image1'+'.'+variables[variable_name][TYPE]; image_map[variable_name] = {}; image_map[variable_name][NAME] = name; image_map[variable_name][BUFFER] = buffer; } } res(image_map); }catch(e){ console.log(e); rej(e); } }) } async __getImageBuffer(path, retrieval_type){ return new Promise((res, rej)=>{ try{ if(retrieval_type === IMAGE_RETRIEVAL_TYPE.URL){ let req = https.request(path, (result) => { let buffer = []; result.on('data', (d) => { buffer.push(d); }); result.on('end', ()=>{ res(Buffer.concat(buffer)); }); }); req.on('error', (e) => { throw e; }); req.end(); } }catch(e){ console.log(e); rej(e); } }) } async _addContentType(final_context) { return new Promise(async (res, rej)=>{ try{ let content = await this.zip.file('[Content_Types].xml').async('nodebuffer'); content = content.toString(); let matches = content.match(/<Types.*?>.*/gm); if (matches && matches[0]) { // let new_str = matches[0] + '<Default Extension="' + type + '" ContentType="image/' + type + '"/>' let new_str = ''; for(let var_name in final_context){ if(final_context.hasOwnProperty(var_name)){ new_str += '<Override PartName="/word/media/'+final_context[var_name][NAME]+'" ContentType="'+final_context[var_name][TYPE]+'"/>'; } } let c = matches[0]+new_str; this.zip.file('[Content_Types].xml', content.replace(matches[0], c)); res(true); } }catch(e){ console.log(e); rej(e); } }) } async _addImage(final_context){ return new Promise(async (res, rej)=>{ try{ // let image_name = uuid(); // let image_path = 'media/'+image_name; // this.docx.file('word/'+image_path, image_buffer); // res(image_path); for(let var_name in final_context){ if(final_context.hasOwnProperty(var_name)){ let o = final_context[var_name]; let img_path = 'media/'+o[NAME]; o[PATH] = img_path; this.zip.file('word/'+img_path, o[BUFFER]); } } res(true); }catch(e){ console.log(e); rej(e); } }) } async _addRelationship(final_context){ return new Promise( async (res, rej)=>{ try{ let content = await this.zip.file('word/_rels/document.xml.rels').async('nodebuffer'); parseString(content.toString(), (err, relation)=>{ if(err){ console.log(err); //TODO check if an error thrown will be catched by enclosed try catch rej(err); } let cnt = relation.Relationships.Relationship.length; // let rID = 'rId'+(cnt+1); // relation.Relationships.Relationship.push({ // $ : { // Id : rID, // Type : IMAGE_URI, // Target : image_path // } // }); for(let var_name in final_context){ if(final_context.hasOwnProperty(var_name)){ let o = final_context[var_name]; let rel_id = 'rId'+(++cnt); o[REL_ID] = rel_id; relation.Relationships.Relationship.push({ $ : { Id : rel_id, Type : IMAGE_URI, Target : o[PATH] } }); } } let builder = new Builder(); let modifiedXML = builder.buildObject(relation); this.zip.file('word/_rels/document.xml.rels', modifiedXML); res(true); }); }catch(e){ console.log(e); rej(e); } }); } async _addInDocumentXML(final_context){ return new Promise(async (res, rej)=>{ try{ let content = await this.zip.file('word/document.xml').async('nodebuffer'); content = content.toString(); content = DocxImager.__cleanXML(content); let matches = content.match(/(<w:r>.*?insert_image.*?<\/w:r>)/g); //match all runs in p tags containing //TODO iterate through all matches to match more than one tag if(matches && matches[0]){ let tag = matches[0].match(/{{(.*?)}}/g)[0]; let splits = tag.split(' '); let var_name = splits[1]; let width = splits[2]; let height = splits[3]; let obj = final_context[var_name]; let xml = DocxImager.__getImgXMLElement(obj[REL_ID], height, width); content = content.replace(matches[0], xml); this.zip.file('word/document.xml', content); res(true); }else{ rej(new Error('Invalid Docx')); } }catch(e){ console.log(e); rej(e); } }); } static __cleanXML(xml){ //Simple variable match //({{|{(.*?){)(.*?)(}{1,2})(.*?)(?:[^}])(}{1}) //1. ({{|{(.*?){) - Match {{ or {<xmltgas...>{{ //2. (.*?) - Match any character //3. (}}|} - Match } or }} //4. (.*?) - Match any character //5. (?:[^}]) - KILLER: Stop matching //6. } - Include the Killer match let variable_regex = /({{|{(.*?){)(.*?)(}}|}(.*?)(?:[^}])})/g; let replacements = xml.match(variable_regex); // let replacements = xml.match(/({{#|{{#\/s)(?:(?!}}).)*|({{|{(.*?){)(?:(?!}}).)*|({{(.*?)#|{{#\/s)(?:(?!}}).)*/g); // let replacements = xml.match(/({{#|{{#\/s)(?:([^}}]).)*|({{|{(.*?){)(?:([^}}]).)*|({{(.*?)#|{{#\/s)(?:([^}}]).)*/g); // let replacements = xml.match(/({{#|{{#\/s)(?:(?!}}).)*|{{(?:(?!}}).)*|({{(.*?)#|{{(.*?)#\/s)(?:(?!}}).)*|{(.*?){(?:(?!}}).)*/g);//|({(.*?){(.*?)#|{{#\/s)(?:(?!}}).)* // let replacements = xml.match(/({(.*?){#|{(.*?){#\/s)(?:(?!}(.*?)}).)*|{(.*?){(?:(?!}(.*?)}).)*/g); let replaced_text; if(replacements){ for(let i = 0; i < replacements.length; i++){ replaced_text = replacements[i].replace(/<\/w:t>.*?(<w:t>|<w:t [^>]*>)/g, ''); xml = xml.replace(replacements[i], replaced_text); } } xml = xml.replace(/&quot;/g, '"'); xml = xml.replace(/&gt;/g, '>'); xml = xml.replace(/&lt;/g, '<'); // xml = xml.replace(/&amp;/g, '&'); xml = xml.replace(/&apos;/g, '\''); return xml; } static __getImgXMLElement(rId, height, width){ let calc_height = 951710;//9525 * height; let calc_width = 2855130;//9525 * width; // from web merge return '<w:r>'+ '<w:rPr>' + '<w:noProof/>' + '</w:rPr>' + '<w:drawing>' + '<wp:inline distT="0" distB="0" distL="0" distR="0">' + '<wp:extent cx="'+calc_width+'" cy="'+calc_height+'"/>' + '<wp:effectExtent l="0" t="0" r="0" b="0"/>' + '<wp:docPr id="1402" name="Picture" descr=""/>' + // '<wp:cNvGraphicFramePr>' + // '<a:graphicFrameLocks noChangeAspect="1"/>' + // '</wp:cNvGraphicFramePr>' + '<wp:cNvGraphicFramePr>' + '<a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/>'+ '</wp:cNvGraphicFramePr>'+ '<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">' + '<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' + '<pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">' + '<pic:nvPicPr>' + '<pic:cNvPr id="1" name="Picture" descr=""/>' + '<pic:cNvPicPr>' + '<a:picLocks noChangeAspect="0" noChangeArrowheads="1"/>' + '</pic:cNvPicPr>' + '</pic:nvPicPr>' + '<pic:blipFill>' + '<a:blip r:embed="'+rId+'">' + // '<a:extLst>' + // '<a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C2}">' + // '<a14:useLocalDpi val="0"/>' + // '</a:ext>' + // '</a:extLst>' + '</a:blip>' + '<a:srcRect/>' + '<a:stretch>' + '<a:fillRect/>' + '</a:stretch>' + '</pic:blipFill>' + '<pic:spPr bwMode="auto">' + '<a:xfrm>' + '<a:off x="0" y="0"/>' + '<a:ext cx="'+calc_width+'" cy="'+calc_height+'"/>' + '</a:xfrm>' + '<a:prstGeom prst="rect">' + '<a:avLst/>' + '</a:prstGeom>' + '<a:noFill/>' + '<a:ln>' + '<a:noFill/>' + '</a:ln>' + '</pic:spPr>' + '</pic:pic>' + '</a:graphicData>' + '</a:graphic>' + '</wp:inline>' + '</w:drawing>'+ '</w:r>'; // from docx // return '<w:r>' + // '<w:rPr/>' + // '<w:drawing>' + // '<wp:anchor behindDoc="0" distT="0" distB="0" distL="0" distR="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="0" relativeHeight="2">' + // '<wp:simplePos x="0" y="0"/>' + // '<wp:positionH relativeFrom="column">' + // '<wp:align>center</wp:align>' + // '</wp:positionH>' + // '<wp:positionV relativeFrom="paragraph">' + // '<wp:posOffset>635</wp:posOffset>' + // '</wp:positionV>' + // '<wp:extent cx="5779770" cy="5396865"/>' + // '<wp:effectExtent l="0" t="0" r="0" b="0"/>' + // '<wp:wrapSquare wrapText="largest"/>' + // '<wp:docPr id="1" name="Image1" descr=""/>' + // '<wp:cNvGraphicFramePr>' + // '<a:graphicFrameLocks noChangeAspect="1"/>' + // '</wp:cNvGraphicFramePr>' + // '<a:graphic>' + // '<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' + // '<pic:pic>' + // '<pic:nvPicPr>' + // '<pic:cNvPr id="1" name="Image1" descr=""/>' + // '<pic:cNvPicPr>' + // '<a:picLocks noChangeAspect="1" noChangeArrowheads="1"/>' + // '</pic:cNvPicPr>' + // '</pic:nvPicPr>' + // '<pic:blipFill>' + // '<a:blip r:embed="rId2"/>' + // '<a:stretch>' + // '<a:fillRect/>' + // '</a:stretch>' + // '</pic:blipFill>' + // '<pic:spPr bwMode="auto">' + // '<a:xfrm>' + // '<a:off x="0" y="0"/>' + // '<a:ext cx="5779770" cy="5396865"/>' + // '</a:xfrm>' + // '<a:prstGeom prst="rect">' + // '<a:avLst/>' + // '</a:prstGeom>' + // '</pic:spPr>' + // '</pic:pic>' + // '</a:graphicData>' + // '</a:graphic>' + // '</wp:anchor>' + // '</w:drawing>' + // '</w:r>'; } __validateDocx(){ if(!this.zip){ throw new Error('Invalid docx path or format. Please load docx.') } } //idml functi8on async merge(idml_path, context, merged_file_path){ return new Promise(async (res, rej)=>{ let zip = await zip.loadAsync(fs.readFileSync(idml_path)); //get all the file names that are to be merged. let des_map = await zip.file('designmap.xml').async('nodebuffer').toString(); let regex = new RegExp(/<idPkg:Story src="(.*?)".?\/>/gm); let m = regex.exec(des_map); let rels = []; while(m != null){ rels.push(m[1]); m = regex.exec(des_map); } if(rels && rels.length > 0){ for(let i = 0; i < rels.length; i++){ let content = await zip.file(rels[i]).async('nodebuffer').toString(); content = Handlebars.compile(content)(context); zip.file(rels[i], content); } zip.generateNodeStream({streamFiles : true}) .pipe(fs.createWriteStream(merged_file_path)) .on('finish', function(x){ res(true); }); }else{ rej(new Error('IDML file does not contain any story file')); } }); } }
JavaScript
class Logcat { /** * Creates a logcat stream. * * The authentication service should implement the following methods: * - `authHeader()` which must return a set of headers that should be send along with a request. * - `unauthorized()` a function that gets called when a 401 was received. * * @constructor * @param {object} uriOrEmulator * @param {object} auth */ constructor(uriOrEmulator, auth) { if (uriOrEmulator instanceof EmulatorControllerService) { this.emulator = uriOrEmulator; } else { this.emulator = new EmulatorControllerService(uriOrEmulator, auth); } this.offset = 0; this.lastline = ""; this.events = new EventEmitter(); this.stream = null; } /** * Register a listener. * * @param {string} name Name of the event. * @param {Callback} fn Function to notify on the given event. * @memberof Logcat */ on = (name, fn) => { this.events.on(name, fn); }; /** * Cancel the currently active logcat stream. * * @memberof Logcat */ stop = () => { if (this.stream) { this.stream.cancel(); } }; /** * Requests the logcat stream, invoking the callback when a log line arrives. * * @param {Callback} fnNotify when a new log line arrives. * @memberof Logcat */ start = fnNotify => { if (fnNotify) this.on("data", fnNotify); const self = this; /* eslint-disable */ const request = new proto.android.emulation.control.LogMessage(); request.setStart(this.offset); this.stream = this.emulator.streamLogcat(request); this.stream.on("data", response => { self.offset = response.getNext(); const contents = response.getContents(); const lines = contents.split("\n"); const last = contents[contents.length - 1]; var cnt = lines.length; if (last != "\n") { cnt--; self.lastline += lines[Math.max(0, cnt - 1)]; } for (var i = 0; i < cnt; i++) { var line = lines[i]; if (i === 0) { line = self.lastline + line; self.lastline = ""; } if (line.length > 0) self.events.emit("data", line); } }); this.stream.on("error", error => { if ((error.code = 1)) { // Ignore we got cancelled. } }); }; }
JavaScript
class Geometry extends Node { constructor(name, gl, shader) { super(); this.type = 'Lore.Geometry'; this.name = name; this.gl = gl; this.shader = shader; this.attributes = {}; this.drawMode = this.gl.POINTS; this.isVisible = true; this.stale = false; } addAttribute(name, data, length) { this.attributes[name] = new Attribute(data, length, name); this.attributes[name].createBuffer(this.gl, this.shader.program); return this; } updateAttribute(name, data) { if (data) { this.attributes[name].data = data; } this.attributes[name].update(this.gl); return this; } getAttribute(name) { return this.attributes[name]; } removeAttribute(name) { delete this.attributes[name]; return this; } setMode(drawMode) { switch (drawMode) { case DrawModes.points: this.drawMode = this.gl.POINTS; break; case DrawModes.lines: this.drawMode = this.gl.LINES; break; case DrawModes.lineStrip: this.drawMode = this.gl.LINE_STRIP; break; case DrawModes.lineLoop: this.drawMode = this.gl.LINE_LOOP; break; case DrawModes.triangles: this.drawMode = this.gl.TRIANGLES; break; case DrawModes.triangleStrip: this.drawMode = this.gl.TRIANGLE_STRIP; break; case DrawModes.triangleFan: this.drawMode = this.gl.TRIANGLE_FAN; break; } return this; } size() { // Is this ok? All attributes should have the same length ... if (Object.keys(this.attributes).length > 0) { return this.attributes[Object.keys(this.attributes)[0]].size; } return 0; } hide() { this.isVisible = false; } show() { this.isVisible = true; this.stale = true; } draw(renderer) { if (!this.isVisible) return; for (let prop in this.attributes) if (this.attributes[prop].stale) this.attributes[prop].update(this.gl); this.shader.use(); // Update the modelView and projection matrices if (renderer.camera.isProjectionMatrixStale || this.stale) { this.shader.uniforms.projectionMatrix.setValue(renderer.camera.getProjectionMatrix()); } if (renderer.camera.isViewMatrixStale || this.stale) { let modelViewMatrix = Matrix4f.multiply(renderer.camera.viewMatrix, this.modelMatrix); this.shader.uniforms.modelViewMatrix.setValue(modelViewMatrix.entries); } this.shader.updateUniforms(); for (let prop in this.attributes) { this.attributes[prop].bind(this.gl); } this.gl.drawArrays(this.drawMode, 0, this.size()); this.stale = false; } }