language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class CurrencyRatio extends Currency { constructor(amount, numerator, denominator, shift) { super(amount, shift); this.numerator = numerator; this.denominator = denominator; this.symbol = `${numerator.symbol}/${denominator.symbol}`; } }
JavaScript
class Server { constructor() { this._logger = logger_1.default.getInstance(); const cred = this.loadCredentials(); this.app = new Express(); this.server = https.createServer(cred, this.app); this.socket = new websockets_1.WebSocket(this.server); this.server.listen(process.env.SERVER_PORT, () => { this._logger.info('Server runs on Port ' + process.env.SERVER_PORT); }); this.app.get('/', function (req, res) { res.sendFile(process.env.NODE_PATH + '/assets/localIndex.html'); }); } loadCredentials() { const cert = fs.readFileSync(process.env.CERT_PATH + '/fullchain.pem'); const key = fs.readFileSync(process.env.CERT_PATH + '/privkey.pem'); return { key: key, cert: cert }; } }
JavaScript
class TetrahedronBuffer extends GeometryBuffer { constructor (data, params) { const p = params || {} const geo = new TetrahedronBufferGeometry(1, 0) super(data, p, geo) this.setAttributes(data, true) } applyPositionTransform (matrix, i, i3) { target.fromArray(this._heightAxis, i3) up.fromArray(this._depthAxis, i3) matrix.lookAt(eye, target, up) scale.set(this._size[ i ], up.length(), target.length()) matrix.scale(scale) } setAttributes (data, initNormals) { if (data.size) this._size = data.size if (data.heightAxis) this._heightAxis = data.heightAxis if (data.depthAxis) this._depthAxis = data.depthAxis super.setAttributes(data, initNormals) } get updateNormals () { return true } }
JavaScript
class Manager { static getInstance(app) { if (!this.instance) { this.instance = new Manager(app) } this.instance.init() return this.instance } constructor(app) { this.app = app } async init() { this.clientMap = {} let d = await this.app.getDrives() for (let i of d) { let data = this.app.decode(i.path) let { key, refresh_token } = data if (data.expires_at) data.expires_at = parseInt(data.expires_at) let needUpdate = false if (!key && data.client_id) { data.key = key = data.client_id needUpdate = true } //if client_id existed if (key) { let isUsedKey = this.clientMap[key] if (isUsedKey) { data.key = key = `${key}::${Date.now()}` needUpdate = true } } // 处理起始目录 if (!data.path) { data.path = data.root_id || DEFAULT_ROOT_ID needUpdate = true } if (needUpdate) { await this.app.saveDrive(data, { refresh_token }) } this.clientMap[key] = { ...data } } } /** * 刷新令牌 / refresh token * * @param {object} credentials * @param {object} { credentials: object } | { error:true, message:string } * @api private */ async refreshAccessToken(credentials) { console.log('refreshAccessToken') let { client_id, client_secret, redirect_uri, refresh_token, ...rest } = credentials if (!(client_id && client_secret && refresh_token)) { return this.app.error({ message: 'Invalid parameters: An error occurred during refresh access token' }) } let formdata = { client_id: client_id.split('::')[0], client_secret, // redirect_uri, refresh_token, grant_type: 'refresh_token', } let { data } = await this.app.request.get(`https://openapi.baidu.com/oauth/2.0/token`, { data: formdata }) if (data.error) return this.app.error({ message: data.error_description || data.error }) // expires_in 30 days let expires_at = data.expires_in * 1000 + Date.now() return { client_id, client_secret, redirect_uri, refresh_token: data.refresh_token, // refresh_token 永久有效 access_token: data.access_token, expires_at, ...rest } } /** * get credentials by client_id * * @param {string} [id] * @return {object} * @api public */ async getCredentials(key) { let credentials = this.clientMap[key] if (!credentials) { return this.app.error({ message: 'unmounted' }) } // 未初始化(access_token不存在)、即将过期 刷新token if (!(credentials.access_token && credentials.expires_at && credentials.expires_at - Date.now() > 5 * 60 * 1000)) { credentials = await this.refreshAccessToken(credentials) this.clientMap[key] = { ...credentials } await this.app.saveDrive({ key, expires_at: credentials.expires_at, access_token: credentials.access_token, refresh_token: credentials.refresh_token, }) } return credentials } }
JavaScript
class TileNode { /** * Create a TileNode * @param {context} state - The scene in which the sprite resides. * @param {number} x - The x position of the TileNode in the Layout. * @param {number} y - The y position of the TileNode in the Layout. * @param {number} height - The height of the TileNode in the Layout. * @param {number} numChildren - The number of children this TileNode will have. * @see Layout */ constructor(state, x, y, height, numChildren){ this.state = state, this.x = x, this.y = y, this.z = height-1, this.height = height, this.parents = [], this.children = [], this.tile = null, this.selectable = false } /** * Sets the sprite tint to a hexadecimal color. This color by default is off-yellow (0xFFFD9A) * but, can be set to any hexadecimal value. * * @param {number} tint - The hexadecimal value used to tint the sprite * @see Board.selectTile() */ highlightTile (tint = 0xFFFD9A) { this.tile.setTint(tint) } /** * Removes the sprite tint. This will return the tint color to white. * */ unhighlightTile () { this.tile.clearTint() } /** * Sets the sprite tint to a hexadecimal color. This color by default is a grey (0x808080). * This method functions the same as highlightTile but defaults to a different color for clarity. * * @param {number} dim - The hexadecimal value used to tint the sprite * @see Layout.InitializeBeginnerMode() * @see TileNode.highlightTile(tint) */ dimTile (dim = 0x808080) { this.tile.setTint(dim) } /** * Sets the sprite position of the TileNode to be centered on the screen in the correct layout position. * The sprite is also scaled to the session scale parameter * <p> * Tile position is determined by the size of the tile and its position in the layout * after determining its base position the position is further offset to be centered on its children * * @param {number} numChildren - The number of children a given TileNode has * @see TileNode * @see Layout */ setSpritePosition(numChildren) { var s = gameSession var xPos = s.tileset.tileFaceX * s.scale * this.x + s.offsetX var yPos = s.tileset.tileFaceY * s.scale * this.y + s.offsetY // For two and four children if (numChildren === 2) { xPos += (((s.tileset.tileFaceX * s.scale) / 2) * (this.z)) //yPos += ((tileFaceY * scale) / 2) * (this.z) } else if (numChildren === 4) { xPos += ((s.tileset.tileFaceX * s.scale) / 2) * (this.z) yPos += ((s.tileset.tileFaceY * s.scale) / 2) * (this.z) } else if (numChildren === 1) { xPos += ((s.tileset.tileX - s.tileset.tileFaceX) * s.scale) * (s.layout.header.height / 2) yPos += ((s.tileset.tileY - s.tileset.tileFaceY) * s.scale) * (s.layout.header.height / 2) } // Adjusts tile to the center of its children yPos -= ((s.tileset.tileY - s.tileset.tileFaceY) * s.scale) * this.z xPos -= ((s.tileset.tileX - s.tileset.tileFaceX) * s.scale) * this.z this.tile.setPosition(xPos,yPos) this.tile.setScale(scale) } /** * Initializes a sprite with a given image for this tile at the origin. * The img argument must specify a preloaded Phaser Sprite * <p> * We set the depth of the tile based on its position in the layout array. * This ensures that each tile overlaps each other correctly * This method works for 999x999x999 tiles * * @param {string} img - A string denoting a preloaded Phaser Sprite * @see TileNode */ setTile(img) { this.tile = this.state.add.sprite(0, 0, img).setInteractive() // Assures each tile has a unique depth per layout this.tile.setDepth(this.height*1000000 + this.y*1000 + this.x) var self = this this.tile.on('pointerdown', function () { self.state.board.selectTile(self) }) } /** * Checks if the sprite contained in TileNode has been initialized * @return {boolean} A boolean value */ isSet () { if (this.tile === null) { return false } return true } /** * removes a given TileNode from the parent array * @param {TileNode} tilenode - The TileNode to remove */ removeParent (tileNode) { for (var i = 0; i < this.parents.length; i++) { if (tileNode === this.parents[i]) { this.parents.splice(i,1) } } } /** * Checks if all children have initialized sprites * @return {boolean} A boolean value * @depreciated */ allChildrenGenerated () { for (var i = 0; i < this.children.length; i++) { if (!this.children[i].isSet()){ console.log(this.children[i]) return false } } return true } /** * Checks if all Parents have initialized sprites * @return {boolean} A boolean value */ allParentsGenerated () { for (var i = 0; i < this.parents.length; i++) { if (!this.parents[i].isSet()){ //console.log(this.parents[i]) return false } } return true } /** * Finds the children of a TileNode and inserts them into the children array. As it finds the * TileNode's children it also populates the parent array. * <p> * This function also propagates down the children finding all the children recursively * When called on the layout roots this function will fill all children and the parents of the layout * @return {TileNode} The current TileNode */ findChildren (layout, numChildren) { if (this.height === 1) { return this } //get the children for the current position var children = [] if (numChildren === 1) { children.push(layout.layers[this.z-1][this.y][this.x]) } if (numChildren === 2) { children.push(layout.layers[this.z-1][this.y][this.x]) children.push(layout.layers[this.z-1][this.y][this.x+1]) } if (numChildren === 4) { children.push(layout.layers[this.z-1][this.y][this.x]) children.push(layout.layers[this.z-1][this.y][this.x+1]) children.push(layout.layers[this.z-1][this.y+1][this.x]) children.push(layout.layers[this.z-1][this.y+1][this.x+1]) } for (var i = 0; i < children.length; i++) { //If the child hasn't already already been looked at and isn't a leaf recursively call findChildren if (children[i].children.length < 1 && children[i].height > 1) { this.children.push(children[i].findChildren(layout, numChildren)) } else { this.children.push(children[i]) } children[i].parents.push(this) } return this } }
JavaScript
class LoginPage extends React.Component { constructor(props) { super(props); this.state = { tryingToLogin: false, }; } render() { //avoids trying to render before the promise from the server is fulfilled //pull form from the url // const params = new URLSearchParams(this.props.location.search) // const returnpath = params.get('returnpath'); const last_visited = localStorage.getItem("last_visited"); if (!this.state.tryingToLogin) { if (this.props.user.info && last_visited !== this.props.links.signin) { return ( <Redirect to={last_visited ? last_visited : this.props.links.profile} /> ); } if (this.props.auth.isLoaded && !this.props.auth.isEmpty) return <Redirect to={this.props.links.signup} />; } return ( <> <div className="boxed_wrapper"> <BreadCrumbBar links={[{ name: "Sign In" }]} /> <section className="register-section sec-padd-top" style={{ paddingTop: 5 }} > <div className="container"> <div className="row"> {/* <!--Form Column--> */} <div className="form-column column col-md-8 col-12 offset-md-2"> <LoginForm tryingToLogin={(status) => this.setState({ tryingToLogin: status }) } /> </div> </div> </div> </section> </div> </> ); } }
JavaScript
class CPMEvol extends CPM { /** The constructor of class CA. * @param {GridSize} field_size - the size of the grid of the model. * @param {object} conf - configuration options; see CPM base class. * * @param {object[]} [conf.CELLS=[empty, CPM.Cell, CPM.StochasticCorrector]] - Array of objects of (@link Cell) * subclasses attached to the CPM. These define the internal state of the cell objects that are tracked * */ constructor( field_size, conf ){ super( field_size, conf ) /** Store the {@Cell} of each cell on the grid. @example this.cells[1] // cell object of cell with cellId 1 @type {Cell} */ this.cells =[new Cell(conf, 0, -1, this)] /** Store the constructor of each cellKind on the grid, in order * 0th index currently unused - but this is explicitly left open for * further extension (granting background variable parameters through Cell) @type {CellObject} */ this.cellclasses = conf["CELLS"] /* adds cellDeath listener to record this if pixels change. */ this.post_setpix_listeners.push(this.cellDeath.bind(this)) } /** Completely reset; remove all cells and set time back to zero. Only the * constraints and empty cell remain. */ reset(){ super.reset() this.cells = [this.cells[0]] // keep empty declared } /** The postSetpixListener of CPMEvol registers cell death. * @listens {CPM#setpixi} as this records when cels no longer contain any pixels. * Note: CPM class already logs most of death, so it registers deleted entries. * @param {IndexCoordinate} i - the coordinate of the pixel that is changed. * @param {CellId} t_old - the cellid of this pixel before the copy * @param {CellId} t_new - the cellid of this pixel after the copy. */ /* eslint-disable no-unused-vars*/ cellDeath( i, t_old, t_new){ if (this.cellvolume[t_old] === undefined && t_old !== 0 ){ this.cells[t_old].death() delete this.cells[t_old] } } /** Get the {@link Cell} of the cell with {@link CellId} t. @param {CellId} t - id of the cell to get kind of. @return {Cell} the cell object. */ getCell ( t ){ return this.cells[t] } /* ------------- MANIPULATING CELLS ON THE GRID --------------- */ /** Initiate a new {@link CellId} for a cell of {@link CellKind} "kind", and create elements for this cell in the relevant arrays. Overrides super to also add a new Cell object to track. @param {CellKind} kind - cellkind of the cell that has to be made. @return {CellId} newid of the new cell.*/ makeNewCellID ( kind ){ let newid = super.makeNewCellID(kind) this.cells[newid] =new this.cellclasses[kind](this.conf, kind, newid, this) return newid } /** Calls a birth event in a new daughter Cell object, and hands * the other daughter (as parent) on to the Cell. @param {CellId} childId - id of the newly created Cell object @param {CellId} parentId - id of the other daughter (that kept the parent id)*/ birth (childId, parentId, partition){ this.cells[childId].birth(this.cells[parentId], partition ) } }
JavaScript
class Delegation { constructor(pubkey, expiration, targets) { this.pubkey = pubkey; this.expiration = expiration; this.targets = targets; } toCBOR() { // Expiration field needs to be encoded as a u64 specifically. return cbor.value.map(Object.assign({ pubkey: cbor.value.bytes(this.pubkey), expiration: cbor.value.u64(this.expiration.toString(16), 16) }, (this.targets && { targets: cbor.value.array(this.targets.map(t => cbor.value.bytes(t.toBlob()))), }))); } toJSON() { // every string should be hex and once-de-hexed, // discoverable what it is (e.g. de-hex to get JSON with a 'type' property, or de-hex to DER with an OID) // After de-hex, if it's not obvious what it is, it's an ArrayBuffer. return Object.assign({ expiration: this.expiration.toString(16), pubkey: this.pubkey.toString('hex') }, (this.targets && { targets: this.targets.map(p => p.toBlob().toString('hex')) })); } }
JavaScript
class DelegationChain { constructor(delegations, publicKey) { this.delegations = delegations; this.publicKey = publicKey; } /** * Create a delegation chain between two (or more) keys. By default, the expiration time * will be very short (15 minutes). * * To build a chain of more than 2 identities, this function needs to be called multiple times, * passing the previous delegation chain into the options argument. For example: * * @example * const rootKey = createKey(); * const middleKey = createKey(); * const bottomeKey = createKey(); * * const rootToMiddle = await DelegationChain.create( * root, middle.getPublicKey(), Date.parse('2100-01-01'), * ); * const middleToBottom = await DelegationChain.create( * middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle }, * ); * * // We can now use a delegation identity that uses the delegation above: * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom); * * @param from The identity that will delegate. * @param to The identity that gets delegated. It can now sign messages as if it was the * identity above. * @param expiration The length the delegation is valid. By default, 15 minutes from calling * this function. * @param options A set of options for this delegation. expiration and previous * @param options.previous - Another DelegationChain that this chain should start with. * @param options.targets - targets that scope the delegation (e.g. Canister Principals) */ static async create(from, to, expiration = new Date(Date.now() + 15 * 60 * 1000), options = {}) { var _a, _b; const delegation = await _createSingleDelegation(from, to, expiration, options.targets); return new DelegationChain([...(((_a = options.previous) === null || _a === void 0 ? void 0 : _a.delegations) || []), delegation], ((_b = options.previous) === null || _b === void 0 ? void 0 : _b.publicKey) || from.getPublicKey().toDer()); } /** * Creates a DelegationChain object from a JSON string. * * @param json The JSON string to parse. */ static fromJSON(json) { const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json; if (!Array.isArray(delegations)) { throw new Error('Invalid delegations.'); } const parsedDelegations = delegations.map(signedDelegation => { const { delegation, signature } = signedDelegation; const { pubkey, expiration, targets } = delegation; if (targets !== undefined && !Array.isArray(targets)) { throw new Error('Invalid targets.'); } return { delegation: new Delegation(_parseBlob(pubkey), BigInt(`0x${expiration}`), // expiration in JSON is an hexa string (See toJSON() below). targets && targets.map((t) => { if (typeof t !== 'string') { throw new Error('Invalid target.'); } return Principal.fromHex(t); })), signature: _parseBlob(signature), }; }); return new this(parsedDelegations, derBlobFromBlob(_parseBlob(publicKey))); } /** * Creates a DelegationChain object from a list of delegations and a DER-encoded public key. * * @param delegations The list of delegations. * @param publicKey The DER-encoded public key of the key-pair signing the first delegation. */ static fromDelegations(delegations, publicKey) { return new this(delegations, publicKey); } toJSON() { return { delegations: this.delegations.map(signedDelegation => { const { delegation, signature } = signedDelegation; const { targets } = delegation; return { delegation: Object.assign({ expiration: delegation.expiration.toString(16), pubkey: delegation.pubkey.toString('hex') }, (targets && { targets: targets.map(t => t.toBlob().toString('hex')), })), signature: signature.toString('hex'), }; }), publicKey: this.publicKey.toString('hex'), }; } }
JavaScript
class DelegationIdentity extends SignIdentity { constructor(_inner, _delegation) { super(); this._inner = _inner; this._delegation = _delegation; } /** * Create a delegation without having access to delegateKey. * * @param key The key used to sign the reqyests. * @param delegation A delegation object created using `createDelegation`. */ static fromDelegation(key, delegation) { return new this(key, delegation); } getDelegation() { return this._delegation; } getPublicKey() { return { toDer: () => this._delegation.publicKey, }; } sign(blob) { return this._inner.sign(blob); } async transformRequest(request) { const { body } = request, fields = __rest(request, ["body"]); const requestId = await requestIdOf(body); return Object.assign(Object.assign({}, fields), { body: { content: body, sender_sig: await this.sign(blobFromUint8Array(Buffer.concat([requestDomainSeparator, requestId]))), sender_delegation: this._delegation.delegations, sender_pubkey: this._delegation.publicKey, } }); } }
JavaScript
class RootScene extends Component { constructor() { super() StatusBar.setBarStyle('light-content') } getCurrentRouteName(navigationState) { if (!navigationState) { return null; } const route = navigationState.routes[navigationState.index]; // dive into nested navigators if (route.routes) { return this.getCurrentRouteName(route); } return route.routeName; } render() { return ( <Navigator onNavigationStateChange={(prevState, currentState) => { const currentScene = this.getCurrentRouteName(currentState); const previousScene = this.getCurrentRouteName(prevState); if (previousScene !== currentScene) { if (lightContentScenes.indexOf(currentScene) >= 0) { StatusBar.setBarStyle('light-content') } else { StatusBar.setBarStyle('dark-content') } } } } /> ); } }
JavaScript
class ExpandableArea extends window.HTMLElement { attachedCallback() { if ('isUpgraded' in this) { // We've already been attached. return; } // Note that this will always be undefined on IE6-8 because // `firstElementChild` wasn't added until IE9. But that's ok, it // just means we won't progressively enhance on those browsers. this.expander = this.firstElementChild; this.isUpgraded = Boolean(this.expander && !supports.isForciblyDegraded(this)); if (this.isUpgraded) { this.expander.setAttribute('aria-expanded', 'false'); this.expander.setAttribute('role', 'button'); this.expander.setAttribute('tabindex', '0'); this.expander.onclick = this.toggle.bind(this); this.expander.onkeyup = (e) => { if (e.keyCode === KEY_SPACE || e.keyCode === KEY_ENTER) { this.toggle(); } }; dispatchBubbly(this, 'expandableareaready'); } } toggle() { if (!this.isUpgraded) { return; } const newVal = this.expander.getAttribute('aria-expanded') === 'true' ? 'false' : 'true'; this.expander.setAttribute('aria-expanded', newVal); ga('send', 'event', 'expandable area', newVal === 'true' ? 'expand' : 'collapse', this.expander.textContent); } }
JavaScript
class DocBlock { #name = ''; #type = ''; #extends = ''; #annotations = null; #comment = ''; readOnly = false; constructor(type='', comment = ''){ this.#type = type; this.#annotations = new Map(); if(comment !== ''){ this.comment = comment; } } [Symbol.iterator]() { let annotationKeys = Array.from(this.#annotations.keys()); let keyStep = 0; let annotationStep = 0; /** * Iteration Process to allow devs to simply iterate through the annotations in a doc block * @return {*} */ let next = ()=>{ let retValue = {value: undefined, done: false}; // If we haven't reached the end of the annotation keys if(keyStep < this.#annotations.size){ let key = annotationKeys[keyStep]; // If the step through the annotations hasn't already reached the end of the collection if(annotationStep < this.#annotations.get(key).length){ retValue.value = this.#annotations.get(key)[annotationStep]; // If the next annotation step would reach the end of the collection, // reset the annotation step and advance the keystep } if(++annotationStep >= this.#annotations.get(key).length){ annotationStep = 0; keyStep++; } } else { retValue.done = true; } return retValue; }; return { next:next.bind(this) }; } /** * Get the full text of the comment node * @return {string} */ get comment(){ return this.#comment; } /** * Set the comment string and extract any annotations within. * Can only be set once * @param {string} text */ set comment(text){ if(this.#comment === ''){ this.#comment = text; let annotationMatches = text.match(annotationPhraseRegex); if(annotationMatches){ for (let expression of annotationMatches){ this.annotationFromPhrase(expression); } } } } get name(){ return this.#name; } get type(){ return this.#type; } get extends(){ return this.#extends; } forBlock(...args){ this.#name = args[0]; if(this.#type === "class"){ this.#extends = args[1]; } else if(this.#type === "property"){ this.readOnly = args[1] === 'get'; } } /** * If there are any annotations in this docblock. * * @return {boolean} */ hasAnnotations(){ return this.#annotations.size > 0; } /** * Does the docblock have a specific annotation. * * @param {string} annotation * @return {boolean} */ hasAnnotation(annotation){ return typeof this.#annotations.get(annotation) !== "undefined"; } /** * Create an annotation from data instead of a phrase. * Useful for memoizing system important data which the dev doesn't need to mark. * * @param {string} name * @param {*} value * @param {string} type */ addAnnotation(name, value=null, type=null){ let annotation = new Annotation(); annotation.fromValues(name, value, type); // if name has /, then split on / and do the following: // if key path does not exist // annotations.set(firstPhrase, {secondPhrase: {each nested phrase}) // annotations.get(firstPhrase)[secondPhrase][etc].lastPhrase = []; // // annotations.get(firstPhrase)[secondPhrase][thirdPhrase].lastPhrase.push(annotation); // if(typeof this.#annotations.get(annotation.name) === "undefined"){ this.#annotations.set(annotation.name,[]); } this.#annotations.get(annotation.name).push(annotation); } /** * Memoize an annotation from a slice of the comment. * If there is already an annotation with a matching name (like param), * then the internal reference is changed to an array and the current and * new annotations are added to it. * @param {string} expression */ annotationFromPhrase(expression){ let annotation = new Annotation(expression.trim()); if(typeof this.#annotations.get(annotation.name) === "undefined"){ this.#annotations.set(annotation.name, []); } this.#annotations.get(annotation.name).push(annotation); } /** * Get the annotation object(s) for a given name * * @param {string} annotation * @return {Annotation} */ getAnnotation(annotation){ return typeof this.#annotations.get(annotation) !== "undefined" ? this.#annotations.get(annotation) : []; } /** * Get the value of the first matching annotation * @param {string} annotation * @return {null | string} */ getFirstAnnotationValue(annotation){ return typeof this.#annotations.get(annotation) !== "undefined" ? this.#annotations.get(annotation)[0].value : null; } }
JavaScript
class Form{ /** * Form constructor * @param {string} id - ID of the main Wrapper, which contains all Elements * @param {string} prefix - The Field prefix * @param {Condition[]} conditions - List of Condition-objects */ constructor(id, prefix, conditions){ /** * The ID of the Form-Wrapper * @type {string} */ this.id = id; /** * The field prefix * @type {string} */ this.prefix = prefix; /** * The Wrapper around the Form * @type {*|jQuery|HTMLElement} */ this.wrapper = $('#' + this.id); /** * List of Condition-objects * @type {Condition[]} */ this.logic = conditions; /** * List of all Form-Elements within the Form-Element * @type {*|jQuery|HTMLElement} */ this.fields = this.wrapper.find('[name]'); } /** * Hooks the conditional rendering to all Elements * and triggers one initial check */ init(){ this.fields.on('change keyup formInit', () => { this.handleChange(); }).first().trigger('formInit'); } /** * Checks all conditions and show or hide * the Form-Elements according to the check-result */ handleChange(){ this.resetObjects(); this.logic.forEach((logic) => { let target = $('[name="' + this.prefix + logic.name + '"]'), check = $('[name="' + this.prefix + logic.field + '"]'); // Search for data-name if we are most likely looking for a wrapping item if (target.length === 0) { target = $('[data-name="' + logic.name + '"'); } if (check.length > 0) { // disjunctive normal form for the condition if (!logic.not && this.constructor.getValue(check) === logic.value || logic.not && this.constructor.getValue(check) !== logic.value) { this.stageObject(target, this.prefix + logic.name, true); } else { this.stageObject(target, this.prefix + logic.name, false); } } }); this.resolveObjects(); } /** * Resets the forms Target-States */ resetObjects(){ this.targets = {}; } /** * Sets the target state in the forms Target-State * @param target the given target to stage * @param name the identifier key of the given target * @param show if the target should be hidden or shown */ stageObject(target, name, show){ if (!this.targets[name]) { this.targets[name] = { target: target, show: show } } else { if (this.targets[name].show) { this.targets[name].show = show; } } } /** * Resolves the target states and shows/hides the Element depending on the logic-results */ resolveObjects(){ const className = 'js-core-target'; for (let item in this.targets) { let target = this.targets[item]; let wrapper = target.target; if (!wrapper.hasClass(className)) { wrapper = target.target.parents('.' + className).first(); } wrapper.toggle(target.show); } } /** * Helps to get the value from a checkbox or radio input * @param check * @returns {*|jQuery|HTMLElement} the Element to get the Value from */ static getValue(check){ if (['checkbox', 'radio'].indexOf(check.attr('type')) >= 0) { if (check.prop('checked')) { return check.val(); } else { return ''; } } return check.val(); } }
JavaScript
class Condition{ /** * Condition constructor * @param {string} field the field to check * @param {string} value the value the field needs to have, for the condition to be be met * @param {bool} not if the condition should be inverted * @param {string} name the origin field name */ constructor(field, value, not, name){ this.field = field; this.value = value; this.not = not; this.name = name; } }
JavaScript
class mat2 { /** * Creates a matrix, with elements specified separately. * * @param {Number} m00 - Value assigned to element at column 0 row 0. * @param {Number} m01 - Value assigned to element at column 0 row 1. * @param {Number} m02 - Value assigned to element at column 1 row 0. * @param {Number} m03 - Value assigned to element at column 1 row 1. */ constructor(m00 = 1, m01 = 0, m02 = 0, m03 = 1) { if (m00 instanceof Float32Array) { // deep copy if (m01) { this.m = new Float32Array(4); this.m.set(m00); } else { this.m = m00; } } else { this.m = new Float32Array(4); let m = this.m; /** * The element at column 0 row 0. * @type {number} * */ m[0] = m00; /** * The element at column 0 row 1. * @type {number} * */ m[1] = m01; /** * The element at column 1 row 0. * @type {number} * */ m[2] = m02; /** * The element at column 1 row 1. * @type {number} * */ m[3] = m03; } } /** * Creates a matrix, with elements specified separately. * * @param {Number} m00 - Value assigned to element at column 0 row 0. * @param {Number} m01 - Value assigned to element at column 0 row 1. * @param {Number} m02 - Value assigned to element at column 1 row 0. * @param {Number} m03 - Value assigned to element at column 1 row 1. * @returns {mat2} The newly created matrix. */ static create(m00 = 1, m01 = 0, m02 = 0, m03 = 1) { return new mat2(m00, m01, m02, m03); } /** * Clone a matrix. * * @param {mat2} a - Matrix to clone. * @returns {mat2} The newly created matrix. */ static clone(a) { let am = a.m; return new mat2(am[0], am[1], am[2], am[3]); } /** * Copy content of a matrix into another. * * @param {mat2} out - Matrix to modified. * @param {mat2} a - The specified matrix. * @returns {mat2} out. */ static copy(out, a) { out.m.set(a.m); return out; } /** * Sets a matrix as identity matrix. * * @param {mat2} out - Matrix to modified. * @returns {mat2} out. */ static identity(out) { let outm = out.m; outm[0] = 1; outm[1] = 0; outm[2] = 0; outm[3] = 1; return out; } /** * Sets the elements of a matrix to the given values. * * @param {mat2} out - The matrix to modified. * @param {Number} m00 - Value assigned to element at column 0 row 0. * @param {Number} m01 - Value assigned to element at column 0 row 1. * @param {Number} m10 - Value assigned to element at column 1 row 0. * @param {Number} m11 - Value assigned to element at column 1 row 1. * @returns {mat2} out. */ static set(out, m00, m01, m10, m11) { let outm = out.m; outm[0] = m00; outm[1] = m01; outm[2] = m10; outm[3] = m11; return out; } /** * Transposes a matrix. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - Matrix to transpose. * @returns {mat2} out. */ static transpose(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values let outm = out.m, am = a.m; if (out === a) { let a1 = am[1]; outm[1] = am[2]; outm[2] = a1; } else { outm[0] = am[0]; outm[1] = am[2]; outm[2] = am[1]; outm[3] = am[3]; } return out; } /** * Inverts a matrix. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - Matrix to invert. * @returns {mat2} out. */ static invert(out, a) { let am = a.m, outm = out.m; let a0 = am[0], a1 = am[1], a2 = am[2], a3 = am[3]; // Calculate the determinant let det = a0 * a3 - a2 * a1; if (!det) { return null; } det = 1.0 / det; outm[0] = a3 * det; outm[1] = -a1 * det; outm[2] = -a2 * det; outm[3] = a0 * det; return out; } /** * Calculates the adjugate of a matrix. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - Matrix to calculate. * @returns {mat2} out. */ static adjoint(out, a) { let outm = out.m, am = a.m; // Caching this value is nessecary if out == a let a0 = am[0]; outm[0] = am[3]; outm[1] = -am[1]; outm[2] = -am[2]; outm[3] = a0; return out; } /** * Calculates the determinant of a matrix. * * @param {mat2} a - Matrix to calculate. * @returns {Number} Determinant of a. */ static determinant(a) { let am = a.m; return am[0] * am[3] - am[2] * am[1]; } /** * Multiply two matrices explicitly. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - The first operand. * @param {mat2} b - The second operand. * @returns {mat2} out. */ static multiply(out, a, b) { let am = a.m, outm = out.m; let a0 = am[0], a1 = am[1], a2 = am[2], a3 = am[3]; let b0 = bm[0], b1 = bm[1], b2 = bm[2], b3 = bm[3]; outm[0] = a0 * b0 + a2 * b1; outm[1] = a1 * b0 + a3 * b1; outm[2] = a0 * b2 + a2 * b3; outm[3] = a1 * b2 + a3 * b3; return out; } /** * Alias of {@link mat2.multiply}. */ static mul(out, a, b) { return mat2.multiply(out, a, b); } /** * Rotates a matrix by the given angle. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - Matrix to rotate. * @param {Number} rad - The rotation angle. * @returns {mat2} out */ static rotate(out, a, rad) { let am = a.m, outm = out.m; let a0 = am[0], a1 = am[1], a2 = am[2], a3 = am[3], s = Math.sin(rad), c = Math.cos(rad); outm[0] = a0 * c + a2 * s; outm[1] = a1 * c + a3 * s; outm[2] = a0 * -s + a2 * c; outm[3] = a1 * -s + a3 * c; return out; } /** * Scales the matrix given by a scale vector. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - Matrix to scale. * @param {vec2} v - The scale vector. * @returns {mat2} out **/ static scale(out, a, v) { let am = a.m, outm = out.m; let a0 = am[0], a1 = am[1], a2 = am[2], a3 = am[3], v0 = v.x, v1 = v.y; outm[0] = a0 * v0; outm[1] = a1 * v0; outm[2] = a2 * v1; outm[3] = a3 * v1; return out; } /** * Creates a matrix from a given angle. * This is equivalent to (but much faster than): * * mat2.set(dest, 1, 0, 0, 1); * mat2.rotate(dest, dest, rad); * * @param {mat2} out - Matrix to store result. * @param {Number} rad - The rotation angle. * @returns {mat2} out. */ static fromRotation(out, rad) { let outm = out.m; let s = Math.sin(rad), c = Math.cos(rad); outm[0] = c; outm[1] = s; outm[2] = -s; outm[3] = c; return out; } /** * Creates a matrix from a scale vector. * This is equivalent to (but much faster than): * * mat2.set(dest, 1, 0, 0, 1); * mat2.scale(dest, dest, vec); * * @param {mat2} out - Matrix to store result. * @param {vec2} v - Scale vector. * @returns {mat2} out. */ static fromScaling(out, v) { let outm = out.m; outm[0] = v.x; outm[1] = 0; outm[2] = 0; outm[3] = v.y; return out; } /** * Returns a string representation of a matrix. * * @param {mat2} a - The matrix. * @returns {String} String representation of this matrix. */ static str(a) { let am = a.m; return `mat2(${am[0]}, ${am[1]}, ${am[2]}, ${am[3]})`; } /** * Store elements of a matrix into array. * * @param {array} out - Array to store result. * @param {mat2} m - The matrix. * @returns {Array} out. */ static array(out, m) { let mm = m.m; out[0] = mm[0]; out[1] = mm[1]; out[2] = mm[2]; out[3] = mm[3]; return out; } /** * Returns Frobenius norm of a matrix. * * @param {mat2} a - Matrix to calculate Frobenius norm of. * @returns {Number} - The frobenius norm. */ static frob(a) { let am = a.m; return (Math.sqrt(Math.pow(am[0], 2) + Math.pow(am[1], 2) + Math.pow(am[2], 2) + Math.pow(am[3], 2))); } /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix. * @param {mat2} L - The lower triangular matrix. * @param {mat2} D - The diagonal matrix. * @param {mat2} U - The upper triangular matrix. * @param {mat2} a - The input matrix to factorize. */ static LDU(L, D, U, a) { let Lm = L.m, Um = U.m, am = a.m; Lm[2] = am[2] / am[0]; Um[0] = am[0]; Um[1] = am[1]; Um[3] = am[3] - Lm[2] * Um[1]; } /** * Adds two matrices. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - The first operand. * @param {mat2} b - The second operand. * @returns {mat2} out. */ static add(out, a, b) { let am = a.m, bm = b.m, outm = out.m; outm[0] = am[0] + bm[0]; outm[1] = am[1] + bm[1]; outm[2] = am[2] + bm[2]; outm[3] = am[3] + bm[3]; return out; } /** * Subtracts matrix b from matrix a. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - The first operand. * @param {mat2} b - The second operand. * @returns {mat2} out. */ static subtract(out, a, b) { let am = a.m, bm = b.m, outm = out.m; outm[0] = am[0] - bm[0]; outm[1] = am[1] - bm[1]; outm[2] = am[2] - bm[2]; outm[3] = am[3] - bm[3]; return out; } /** * Alias of {@link mat2.subtract}. */ static sub(out, a, b) { return mat2.subtract(out, a, b); } /** * Returns whether the specified matrices are equal. (Compared using ===) * * @param {mat2} a - The first matrix. * @param {mat2} b - The second matrix. * @returns {Boolean} True if the matrices are equal, false otherwise. */ static exactEquals(a, b) { let am = a.m, bm = b.m; return am[0] === bm[0] && am[1] === bm[1] && am[2] === bm[2] && am[3] === bm[3]; } /** * Returns whether the specified matrices are approximately equal. * * @param {mat2} a - The first matrix. * @param {mat2} b - The second matrix. * @returns {Boolean} True if the matrices are equal, false otherwise. */ static equals(a, b) { let am = a.m, bm = b.m; let a0 = am[0], a1 = am[1], a2 = am[2], a3 = am[3]; let b0 = bm[0], b1 = bm[1], b2 = bm[2], b3 = bm[3]; return ( Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) ); } /** * Multiply each element of a matrix by a scalar number. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - Matrix to scale * @param {Number} b - The scale number. * @returns {mat2} out. */ static multiplyScalar(out, a, b) { let am = a.m, outm = out.m; outm[0] = am[0] * b; outm[1] = am[1] * b; outm[2] = am[2] * b; outm[3] = am[3] * b; return out; } /** * Adds two matrices after multiplying each element of the second operand by a scalar number. * * @param {mat2} out - Matrix to store result. * @param {mat2} a - The first operand. * @param {mat2} b - The second operand. * @param {Number} scale - The scale number. * @returns {mat2} out. */ static multiplyScalarAndAdd(out, a, b, scale) { let am = a.m, bm = b.m, outm = out.m; outm[0] = am[0] + (bm[0] * scale); outm[1] = am[1] + (bm[1] * scale); outm[2] = am[2] + (bm[2] * scale); outm[3] = am[3] + (bm[3] * scale); return out; } }
JavaScript
class Role { constructor(data) { this.id = data.id; this.createdAt = (this.id / 4194304) + 1420070400000; this.update(data); } update(data) { this.name = data.name !== undefined ? data.name : this.name; this.mentionable = data.mentionable !== undefined ? data.mentionable : this.mentionable; this.managed = data.managed !== undefined ? data.managed : this.managed; this.hoist = data.hoist !== undefined ? data.hoist : this.hoist; this.color = data.color !== undefined ? data.color : this.color; this.position = data.position !== undefined ? data.position : this.position; this.permissions = new Permission(data.permissions); } /** * Generates a JSON representation of the role permissions * @returns {Object} */ asJSON() { return this.permissions.asJSON(); } get mention() { return `<@&${this.id}>`; } }
JavaScript
class FBUserFileStoreClient extends FBJWTClient { /** * Initialise user filestore client * * @param {string} serviceSecret * Service secret * * @param {string} serviceToken * Service token * * @param {string} serviceSlug * Service slug * * @param {string} userFileStoreUrl * User filestore URL * * @param {object} [options] * Options for instantiating client * * @param {number} [options.maxSize] * Default max size for uploads (bytes) * * @param {number} [options.expires] * Default expiry duration in days for uploads * eg. 14 * * @return {object} * **/ constructor (serviceSecret, serviceToken, serviceSlug, userFileStoreUrl, options = {}) { super(serviceSecret, serviceToken, serviceSlug, userFileStoreUrl, FBUserFileStoreClientError) this.maxSize = options.maxSize || defaultMaxSize this.expires = options.expires || defaultExpires } /** * Get url to download uploaded file from * * @param {string} userId * User ID * * @param {string} fingerprint * File fingerprint * * @return {string} url */ getFetchUrl (userId, fingerprint) { return this.createEndpointUrl(endpoints.fetch, {serviceSlug: this.serviceSlug, userId, fingerprint}) } /** * Fetch user file * * @param {object} args * Fetch args * * @param {string} args.userId * User ID * * @param {string} args.userToken * User token * * @param {string} args.fingerprint * File fingerprint * * @param {object} logger * Bunyan logger instance * * @return {promise<string>} * Promise resolving to file * **/ async fetch (args, logger) { const {userId, userToken, fingerprint} = args const url = endpoints.fetch const serviceSlug = this.serviceSlug const encrypted_user_id_and_token = this.encryptUserIdAndToken(userId, userToken) // eslint-disable-line camelcase const context = {serviceSlug, userId, fingerprint} const payload = {encrypted_user_id_and_token} const json = await this.sendGet({url, context, payload}, logger) const {file} = json return Buffer.from(file, 'base64').toString() } /** * Store user file * * @param {object} args * Store args * * @param {string} args.userId * User ID * * @param {string} args.userToken * User token * * @param {string|buffer} args.file * User file * * @param {object} args.policy * Policy to apply to file * * @param {number} [args.policy.max_size] * Maximum file size in bytes * * @param {string} [args.policy.expires] * Maximum file size in bytes * * @param {array<string>} [args.policy.allowed_types] * Allowed mime-types * * @param {object} logger * Bunyan logger instance * * @return {promise<undefined>} * **/ async store (args, logger) { const {userId, userToken} = args let {file, policy} = args const url = endpoints.store const serviceSlug = this.serviceSlug if (!file.buffer) { file = Buffer.from(file) } file = file.toString('base64') policy = Object.assign({}, policy) if (!policy.max_size) { policy.max_size = this.maxSize } if (!policy.expires) { policy.expires = this.expires } if (policy.allowed_types && policy.allowed_types.length === 0) { delete policy.allowed_types } const encrypted_user_id_and_token = this.encryptUserIdAndToken(userId, userToken) // eslint-disable-line camelcase const context = {serviceSlug, userId} const payload = {encrypted_user_id_and_token, file, policy} const result = await this.sendPost({url, context, payload}, logger) // useless if no fingerprint returned if (!result.fingerprint) { this.throwRequestError(500, 'ENOFINGERPRINT') } return result } /** * Store user file from a file path * * @param {string} filePath * Path to user file * * @param {object} args * Store args * * @param {string} args.userId * User ID * * @param {string} args.userToken * User token * * @param {object} args.policy * Policy to apply to file - see store method for details * * @param {object} logger * Bunyan logger instance * * @return {promise<undefined>} * **/ async storeFromPath (filePath, args, logger) { const file = await readFile(filePath) args.file = file return this.store(args, logger) } }
JavaScript
class CalbackMapper { /** * CallbackMapper constructor */ constructor() { this.reset(); } /** * Reset the registrations */ reset() { this._callbackMap = {}; this._argsMap = {}; } /** * Registers a callback to an action that you can trigger with the trigger method. * You can also pass in arguments to pass into the callback when it is being triggered. * * @param {string} action * @param {function} callback * @param {array} args */ on(action, callback, args = []) { if(typeof action !== "string") { console.error('CallbackMapper: not registering callback since the action is not a string'); return; } if(typeof callback !== "function") { console.error('CallbackMapper: not registering callback since the callback is not a function'); return; } if(!Array.isArray(args)) { console.error('CallbackMapper: not registering callback since the args parameter is not an array'); return; } if(!this._callbackMap.hasOwnProperty(action)) this._callbackMap[action] = []; if(!this._argsMap.hasOwnProperty(action)) this._argsMap[action] = []; this._callbackMap[action].push(callback); this._argsMap[action].push(args); } /** * @param {string} action */ trigger(action) { if(typeof action !== "string") { console.error('CallbackMapper: not triggering callback since the action is not a string'); return; } if(!this._callbackMap.hasOwnProperty(action) && !this._argsMap.hasOwnProperty(action)) { return; } let callbacksCount = this._callbackMap[action].length; for(let index = 0; index < callbacksCount; index++) { this._callbackMap[action][index].apply(this, this._argsMap[action][index].slice()); } } /** * @param {string} action */ clearCallbacksForAction(action) { if(!this._callbackMap.hasOwnProperty(action)) return; delete this._callbackMap[action]; } }
JavaScript
class Doughnut { constructor(options) { /** * @private * Options property exposing widget's options */ this._options = {}; /** * @public * Width of the widget */ this._options.outerRadius = getOptionValue(options.outerRadius, Defaults.OUTER_RADIUS); /** * @public * Width of the widget */ this._options.innerRadius = getOptionValue(options.innerRadius, Defaults.INNER_RADIUS); /** * @public * Active color */ this._options.activeColor = getOptionValue(options.activeColor, Defaults.ACTIVE_COLOR); /** * @public * Inactive color */ this._options.inactiveColor = getOptionValue(options.inactiveColor, Defaults.INACTIVE_COLOR); /** * @public * Inactive color */ this._options.backgroundColor = getOptionValue(options.backgroundColor, Defaults.BACKGROUND_COLOR); /** * @public * Value */ this._options.value = getOptionValue(options.value, Defaults.VALUE); /** * @public * Animation duration */ this._options.animationDuration = getOptionValue(options.animationDuration, Defaults.ANIMATION_DURATION); /** * @public * Render to container */ this._options.renderTo = getOptionValue(options.renderTo, null); /** * @private * observable handler */ this._observable = new Observable([ /** * @event * Fires when mouse is over */ "mouseOver", /** * @event * Fires when mouse is out */ "mouseOut" ]); /** * @private * DoughnutRenderer */ this._doughnutRenderer = new DoughnutRenderer(this._options); this._doughnutRenderer.on("mouseOver", ()=>{ this._observable.fire("mouseOver") }); this._doughnutRenderer.on("mouseOut", ()=>{ this._observable.fire("mouseOut") }); if (options.renderTo){ this.render(options.renderTo); } } /** * Bind widget event * @param {String} event event name * @param {Function} handler event handler * @returns {Doughnut} returns this widget instance */ on(eventName, handler) { this._observable.on(eventName, handler); return this; } /** * Unbind widget event * @param {String} event event name * @param {Function} [handler] event handler * @returns {Doughnut} returns this widget instance */ off(eventName, handler) { this._observable.off(eventName, handler); return this; } /** * Destroys widget * @returns {Doughnut} returns this widget instance */ destroy() { this._observable.destroy(); this._doughnutRenderer.destroy(); this._options = null; return this; } /** * Render logic of this widget * @param {String|DOMElement} selector selector or DOM element * @returns {Doughnut} returns this widget instance */ render(selector) { this._doughnutRenderer.render(selector); return this; } /** * Sets widget data * @param {Object} options * @returns {Doughnut} returns this widget instance */ update(options) { if (!this._doughnutRenderer.isRendered()) { throw "Can't call update() when widget is not rendered, please call .render() first." } this._doughnutRenderer.update(options); return this; } }
JavaScript
class Progression extends React.Component { componentDidMount() { $('.progression-step').progress(); } componentDidUpdate() { this.props.chapters.map((chapter, i) => { console.log(`#progress-${i}`); let percentage = this.getPercentage(chapter,i); console.log(this.getPercentage(chapter,i)); $(`#progress-${i}`).progress({percent: percentage}); }); } getPercentage(chapter, index) { let {chapters, currentChapter, currentExercise } = this.props; let percentage = 0; if(chapter.type == "instruction") { percentage = (index < currentChapter) ? 100 : 0; } else if(index < currentChapter){ percentage = 100 } else if(index == currentChapter){ percentage = (currentExercise / chapter.exercises.length) * 100; } return percentage; } render () { let chapters = this.props.chapters; return ( <div id="progression" data-chapter={this.props.currentChapter} data-exercise={this.props.currentExercise}> {chapters.map((chapter, i) => { return <div key={i} id={'progress-'+i} className="ui indicating progress progression-step"> <div className="bar"></div> <div className="label">{chapter.title}</div> </div> })} </div> ); } }
JavaScript
class Helper { /** * @method generateToken * @description Generates token for securing endpoints * @static * @param {object} data - data object * @returns {object} JSON response * @memberof Helper */ static generateToken(data) { const token = jwt.sign(data, 'secret', { expiresIn: '365d', }); return token; } /** * @method hashPassword * @description Hash password before saving in database * @static * @param {string} password * @returns {string} string response * @memberof Helper */ static hashPassword(password) { return bcrypt.hashSync(password, 10); } /** * @method verifyPassword * @description verify if given and database password match * @static * @param {string} password * @param {string} hashed * @returns {boolean} boolean response * @memberof Helper */ static verifyPassword(password, hashed) { return bcrypt.compareSync(password, hashed); } /** * @method regEx * @description contain regular expressions for validating user input * @static * @returns {object} json response * @memberof Helper */ static regEx() { return { id: /^[1-9](\d+)?$/, name: /^[a-zA-Z]+$/, price: /^[\d]+[.]?[\d]+$/, email: /^[\w]+[@][\w]+[.][a-z]{2,3}$/, }; } }
JavaScript
class GCDS { constructor({ GCLOUD_PROJECT_ID, KEY_FILENAME, NODE_ENV = "develop" }, { Datastore = require("@google-cloud/datastore") } = {}) { this.Datastore = Datastore; this.datastore = Datastore({ projectId: GCLOUD_PROJECT_ID, keyFilename: KEY_FILENAME }); this.namespace = NODE_ENV; } getIncompleteKey(kind) { const path = Array.isArray(kind) ? kind : [kind]; return this.getKey(path); } getKey(path) { return this.datastore.key({ namespace: this.namespace, path }); } getCompleteKey(entityName, id) { return this.getKey([entityName, parseInt(id)]); } allocateIds(incompleteKey, n) { if (n < MAX_PER_REQ + 1) return this.datastore.allocateIds(incompleteKey, n).then(([keys]) => keys); else { const nRequests = Math.ceil(n / MAX_PER_REQ); const lastRequestSize = n - (nRequests - 1) * MAX_PER_REQ; const promiseArray = new Array(nRequests).fill(null).map((_, index) => { const reqSize = index === nRequests - 1 ? lastRequestSize : MAX_PER_REQ; return this.datastore.allocateIds(incompleteKey, reqSize).then(([keys]) => keys); }); return Promise.all(promiseArray) .then(result => result.reduce((acc, arr) => acc.concat(arr), [])); } } save(entity) { if (!Array.isArray(entity) || entity.length < MAX_PER_REQ + 1) return this.datastore.save(entity); else { let chunks = []; for (let i = 0; i < entity.length; i += MAX_PER_REQ) { chunks.push(entity.slice(i, i + MAX_PER_REQ)); } return Promise.all(chunks.map(chunk => this.datastore.save(chunk))) .then(result => result.reduce((acc, arr) => acc.concat(arr), [])); } } upsert(entity) { return this.datastore.upsert(entity); } get(key) { return this.datastore.get(key).then(result => Array.isArray(key) ? result : result[0]); } delete(key) { return this.datastore.delete(key); } query(kind) { return this.datastore.createQuery(this.namespace, kind); } }
JavaScript
class LocaleManager extends Events(Base) { static get defaultConfig() { return { locales : {}, // Enable strict locale checking by default for tests throwOnMissingLocale : VersionHelper.isTestEnv }; } construct(...args) { const me = this; super.construct(...args); const scriptTag = document.querySelector('script[data-default-locale]'); if (scriptTag) { me.defaultLocaleName = scriptTag.dataset.defaultLocale; } if (BrowserHelper.isBrowserEnv && window.bryntum && window.bryntum.locales) { Object.keys(window.bryntum.locales).forEach(localeName => { // keeping this check in case some client tries to use an old locale if (!localeName.startsWith('moment')) { const locale = window.bryntum.locales[localeName]; if (locale.extends) { me.extendLocale(locale.extends, locale); } else if (locale.localeName) { me.registerLocale(locale.localeName, { desc : locale.localeDesc, locale : locale }); } } }); if (!me.locale) { // English locale is built in, no need to apply it here since it will be applied anyway if (me.defaultLocaleName !== 'En') { // No locale applied, use default or first found me.applyLocale(me.defaultLocaleName || Object.keys(me.locales)[0]); } } } } set locales(localeConfigs) { this._locales = localeConfigs; } /** * Get currently registered locales. * Returns an object with locale names (`localeName`) as properties. * * Example: * ``` * const englishLocale = LocaleManager.locales.En; * ``` * * this returns registered English locale object. * ``` * { * "desc": "English", * "locale": { * "localeName": "En", * "localeDesc": "English", * * ... (localization goes here) * * } * } * ``` * @readonly * @property {Object} */ get locales() { return this._locales; } /** * Get/set currently used locale. Set a name of a locale to have it applied, or give a locale configuration to * have it registered and then applied * @property {String|Object} */ set locale(locale) { if (typeof locale === 'string') { this.applyLocale(locale); } else { if (!locale.locale) { locale = { locale, localeName : locale.localeName || 'custom' }; } this.registerLocale(locale.localeName, locale); this.applyLocale(locale.localeName); } } get locale() { return this._locale; } /** * Register a locale to make it available for applying. * Registered locales are available in {@link Core.localization.LocaleManager#property-locales-static}. * @param {String} name Name of locale (for example `En` or `SvSE`) * @param {Object} config Object with localized properties */ registerLocale(name, config) { const me = this, isDefault = me.defaultLocaleName === name, isCurrent = me.locale && me.locale.localeName === name, isFirst = Object.keys(me.locales).length === 0; // Avoid registering the same locale twice and merge configs if (!me.locales[name]) { me.locales[name] = config; } else { me.locales[name].locale = LocaleHelper.mergeLocales(me.locales[name].locale, config.locale); } // if no default locale specified, use the first one. otherwise apply the default when it is registered // also reapply if current locale is registered again (first grid, then scheduler etc). if (isDefault || (!me.defaultLocaleName && (isFirst || isCurrent))) { me.internalApplyLocale(me.locales[name]); } } /** * Extend an already loaded locale to add additional translations. * @param {String} name Name of locale (for example `En` or `SvSE`) * @param {Object} config Object with localized properties */ extendLocale(name, config) { const locale = this.locales[name]; if (!locale) { return false; } locale.locale = LocaleHelper.mergeLocales(locale.locale, config); delete locale.locale.extends; // If current loaded locale is the same then apply to reflect changes if (this.locale?.localeName === name) { this.applyLocale(name); } return true; } internalApplyLocale(localeConfig) { this._locale = localeConfig.locale; this.trigger('locale', localeConfig); } /** * Apply a locale. Locale must be defined in {@link Core.localization.LocaleManager#property-locales-static}. * If it is not loaded it will be loaded using AjaxHelper {@link Core.helper.AjaxHelper#function-get-static} request and then applied. * @param {String} name Name of locale to apply (for example `En` or `SvSE`) * @returns {boolean|Promise} */ applyLocale(name, forceApply = false, ignoreError = false) { const me = this, localeConfig = me.locales[name]; if (localeConfig && localeConfig.locale && me._locale === localeConfig.locale && !forceApply) { // no need to apply same locale again return true; } // ignoreError is used in examples where one example might have defined a locale not available in another if (!localeConfig) { if (ignoreError) return true; throw new Error(`Locale ${name} not registered`); } function internalApply() { me.internalApplyLocale(localeConfig); } if (!localeConfig.locale) { return new Promise((resolve, reject) => { me.loadLocale(localeConfig.path).then(response => { response.text().then(text => { const // eslint-disable-next-line no-new-func parseLocale = new Function(text); parseLocale(); if (BrowserHelper.isBrowserEnv) { localeConfig.locale = window.bryntum.locales[name]; } internalApply(); resolve(localeConfig); }); }).catch(response => reject(response)); }); } internalApply(); return true; } /** * Loads a locale using AjaxHelper {@link Core.helper.AjaxHelper#function-get-static} request. * @private * @param {String} path Path to locale file * @returns {Promise} */ loadLocale(path) { return AjaxHelper.get(path); } /** * Specifies if {@link Core.localization.Localizable#function-L-static Localizable.L()} function would throw error if no localization found in runtime * @property {Boolean} * @default false */ set throwOnMissingLocale(value) { this._throwOnMissingLocale = value; } get throwOnMissingLocale() { return this._throwOnMissingLocale; } }
JavaScript
class ProgressBar extends MotorCortex.HTMLClip { get html() { const list = this.attrs.data.map((elem, index) => { return ( <div class={"row row-" + index}> <div class="bar-header">{elem.name}</div> <div class={"container-bar container-bar-" + index}> <div class={ "inner-bar inner-bar-" + index + " " + (elem.value < this.criticalValue ? "extra-trunced-" + index : null) } ></div> </div> <div class={`text indicator-${index}`}>{elem.value}</div> <div class={"text text-unit"}> {!this.attrs.options?.hidePercentage ? "%" : null} </div> </div> ); }); return <div class="container-progressBar">{list}</div>; } get css() { const cssArgs = { barSum: this.barSum, barCount: this.barCount, data: this.attrs.data, palette: this.attrs.palette ? this.attrs.palette : {}, font: this.attrs.font ? this.attrs.font : {}, options: this.attrs.options ? this.attrs.options : {}, }; return buildCSS(cssArgs); } get fonts() { return [ { type: "google-font", src: this.attrs.font?.url ? this.attrs.font.url : "https://fonts.googleapis.com/css2?family=Staatliches&display=swap", }, ]; } buildTree() { if (this.attrs.timings.static === 0) { this.static = 0; } else { this.static = this.attrs.timings.static ? this.attrs.timings.static : 1000; } this.intro = this.attrs.timings.intro ? this.attrs.timings.intro : 0; this.outro = this.attrs.timings.outro ? this.attrs.timings.outro : 0; const avg = this.barSum / this.barCount; fadeOutOpacityControl(this, `.container-progressBar`); if (this.attrs.timings?.intro) { const slideInDuration = Math.floor(this.intro * 0.33); const expandBaseDuration = Math.floor(this.intro * 0.25); const expandBarDuration = Math.floor(this.intro * 0.33); for (let i = 0; i < this.barCount; i++) { const slideIn = new MCAnime.Anime( { animatedAttrs: { bottom: `${ 50 + ((avg - i) * 100) / this.barCount - (60 / this.barCount) * 2.15 }%`, opacity: 1, }, initialValues: { bottom: `-${65 / this.barCount}%`, opacity: 0, }, }, { duration: slideInDuration, selector: `.row-${i}`, easing: "easeInOutQuad", } ); const expand_base = new MCAnime.Anime( { animatedAttrs: { width: "60%", }, initialValues: { width: "0.2%", }, }, { duration: expandBaseDuration, selector: `.container-bar-${i}`, easing: "easeInOutQuad", } ); const expand_bar = new MCAnime.Anime( { animatedAttrs: { width: `${this.attrs.data[i].value.toFixed(2)}%`, }, initialValues: { width: "0%", }, }, { duration: expandBarDuration, selector: `.inner-bar-${i}`, easing: "easeInOutQuad", } ); const indicatorCounter = new Counter.Counter( { animatedAttrs: { count: this.attrs.data[i].value, }, initialValues: { count: 0, }, }, { easing: "easeInOutQuad", selector: `.indicator-${i}`, duration: expandBarDuration, } ); this.addIncident(slideIn, 0); this.addIncident(expand_base, slideInDuration); this.addIncident(expand_bar, slideInDuration + expandBaseDuration); this.addIncident( indicatorCounter, slideInDuration + expandBaseDuration ); } const expand_text = new MCAnime.Anime( { animatedAttrs: { left: "62%", opacity: 1, }, initialValues: { left: "0%", opacity: 0, }, }, { duration: expandBarDuration, selector: `.text`, easing: "easeInOutQuad", } ); this.addIncident(expand_text, slideInDuration); } const staticGraph = new MCAnime.Anime( { animatedAttrs: {} }, { duration: this.static, selector: ".container-progressBar" } ); this.addIncident(staticGraph, this.intro); if (this.outro) { const bufferTime = this.intro + this.static + this.outro; const slideInDuration = Math.floor(this.outro * 0.33); const expandBaseDuration = Math.floor(this.outro * 0.25); const expandBarDuration = Math.floor(this.outro * 0.33); for (let i = 0; i < this.barCount; i++) { const slideIn = new MCAnime.Anime( { animatedAttrs: { bottom: `-${65 / this.barCount}%`, opacity: 0, }, initialValues: { bottom: `${ 50 + ((avg - i) * 100) / this.barCount - (60 / this.barCount) * 2.15 }%`, opacity: 1, }, }, { duration: slideInDuration, selector: `.row-${i}`, easing: "easeInOutQuad", } ); const expand_base = new MCAnime.Anime( { animatedAttrs: { width: "0.2%", }, initialValues: { width: "60%", }, }, { duration: expandBaseDuration, selector: `.container-bar-${i}`, easing: "easeInOutQuad", } ); const expand_bar = new MCAnime.Anime( { animatedAttrs: { width: "0%", }, initialValues: { width: `${this.attrs.data[i].value.toFixed(2)}%`, }, }, { duration: expandBarDuration, selector: `.inner-bar-${i}`, easing: "easeInOutQuad", } ); const indicatorCounter = new Counter.Counter( { animatedAttrs: { count: 0, }, initialValues: { count: this.attrs.data[i].value, }, }, { easing: "easeInOutQuad", selector: `.indicator-${i}`, duration: expandBarDuration, } ); this.addIncident(slideIn, bufferTime - slideInDuration); this.addIncident( expand_base, bufferTime - slideInDuration - expandBaseDuration ); this.addIncident( expand_bar, bufferTime - slideInDuration - expandBaseDuration - expandBarDuration ); this.addIncident( indicatorCounter, bufferTime - slideInDuration - expandBaseDuration - expandBarDuration ); } const expand_text = new MCAnime.Anime( { animatedAttrs: { left: "0%", opacity: 0, }, initialValues: { left: "62%", opacity: 1, }, }, { duration: expandBarDuration, selector: `.text`, easing: "easeInOutQuad", } ); this.addIncident( expand_text, bufferTime - slideInDuration - expandBaseDuration * 1.1 ); } } get barSum() { let sum = 0; for (let i = 1; i <= this.barCount; i++) { sum += i; } return sum; } get barCount() { return this.attrs.data.length; } get criticalValue() { if (this.barCount / 10 === 1) { return (this.barCount / 10) * 10; } else if (this.barCount / 10 > 1) { return (this.barCount / 10 - 1) * 10; } else { return (this.barCount / 10 + 1) * 10; } } }
JavaScript
class Tile { constructor(tileType, position = {x: 0, y: 0}, facing = 0) { this.tileType = tileType; this.position = position; this.size = {width: 1, height: 1}; this.facing = facing; } }
JavaScript
class NumberWidget extends Widget { constructor(title, url, value, color) { super(title, url); this.value = value; this.color = color; } async evaluate(context) { let value; if (typeof (this.value) == 'number') { value = this.value; } else { let result = await evaluate_1.Evaluate.parseExpression(this.value, context); if (typeof (result) == 'number') { value = result; } else { value = +result; } } const title = await evaluateMetadata(this.title, context, value); const url = await evaluateMetadata(this.url, context, value); const color = await evaluateMetadata(this.color, context, value); return new NumberWidget(title, url, value, color); } }
JavaScript
class QueryNumberWidget extends Widget { constructor(title, url, type, query, color) { super(title, url); this.type = type; this.query = query; this.color = color; } async evaluate(context) { let results = await evaluateQuery(this.type, this.query, 0, context); const value = results.totalCount; const url = this.url != null ? await evaluateMetadata(this.url, context, value) : results.url; const title = await evaluateMetadata(this.title, context, value); const color = await evaluateMetadata(this.color, context, value); return new NumberWidget(title, url, value, color); } }
JavaScript
class ScriptNumberWidget extends Widget { constructor(title, url, script, color) { super(title, url); this.script = script; this.color = color; } async evaluate(context) { let result = await evaluate_1.Evaluate.runScript(this.script, context); let value; let title = null; let url = null; let color = null; if (typeof result == 'object' && result.value) { title = result.title; url = result.url; color = result.color; result = result.value; } if (typeof result != 'number') { result = result.toString(); if (result.match(/^\d+$/)) { result = +result; } else { result = Number.NaN; } } value = result; if (title == null) { title = await evaluateMetadata(this.title, context, value); } if (url == null) { url = await evaluateMetadata(this.url, context, value); } if (color == null) { color = await evaluateMetadata(this.color, context, value); } return new NumberWidget(title, url, result, color); } }
JavaScript
class StringWidget extends Widget { constructor(title, url, value, align, color) { super(title, url); this.value = value; this.align = align; this.color = color; } async evaluate(context) { let value = await evaluate_1.Evaluate.parseExpression(this.value, context); const title = await evaluateMetadata(this.title, context, value); const url = await evaluateMetadata(this.url, context, value); const align = await evaluateMetadata(this.align, context, value); const color = await evaluateMetadata(this.color, context, value); return new StringWidget(title, url, value, align, color); } }
JavaScript
class ScriptStringWidget extends Widget { constructor(title, url, script, align, color) { super(title, url); this.script = script; this.align = align; this.color = color; } async evaluate(context) { let result = await evaluate_1.Evaluate.runScript(this.script, context); let value; let title = null; let url = null; let align = null; let color = null; if (typeof result == 'object' && result.value) { title = result.title; url = result.url; color = result.color; result = result.value; } if (typeof result != 'string') { result = result.toString(); } value = result; if (title == null) { title = await evaluateMetadata(this.title, context, value); } if (url == null) { url = await evaluateMetadata(this.url, context, value); } if (align == null) { align = await evaluateMetadata(this.align, context, value); } if (color == null) { color = await evaluateMetadata(this.color, context, value); } return new StringWidget(title, url, result, align, color); } }
JavaScript
class GraphWidget extends Widget { constructor(title, url, elements) { super(title, url); this.elements = elements ? elements : new Array(); } async evaluate(context) { let elements = new Array(); for (let element of this.elements) { let result = await element.evaluate(context); if (!(result instanceof NumberWidget)) { throw new Error('graph widget elements must be number widgets'); } elements.push(result); } const title = await evaluateExpression(this.title, context); const url = await evaluateExpression(this.url, context); return new GraphWidget(title, url, elements); } }
JavaScript
class Section { constructor(title, description, widgets) { this.title = title; this.description = description; this.widgets = widgets; } async evaluate(context) { const evaluated = new Array(); for (let widget of this.widgets) { evaluated.push(await widget.evaluate(context)); } const title = this.title ? await evaluate_1.Evaluate.parseExpression(this.title, context) : null; const description = this.description ? await evaluate_1.Evaluate.parseExpression(this.description, context) : null; return new Section(title, description, evaluated); } }
JavaScript
class Button extends Component { constructor () { super() this.state = { ripples: [] } this.handleClick = this.handleClick.bind(this) } handleClick (e, b) { // console.log(e, b) // console.log('this.button', this.button) // console.log('event', e) console.dir(e.currentTarget) // Get Cursor Position let cursorPos = { top: e.clientY - e.currentTarget.offsetTop - 25, left: e.clientX - e.currentTarget.offsetLeft - 25 } // console.log('cursorPos', cursorPos, { // offsetLeft: this.button.offsetLeft, // offsetTop: this.button.offsetTop // }) this.setState({ ripples: this.state.ripples.concat(<Ripple key={Date.now()} cursorPos={cursorPos} isVisible />) }) setTimeout(() => { this.setState({ ripples: this.state.ripples.filter((r, i) => !!i) }) }, 1000) } render () { const { children, href, content, classes, primary, positive, negative, rounded, size, onClick } = this.props const classNames = cx( classes.button, primary && classes.primary, positive && classes.positive, negative && classes.negative, rounded && classes.rounded, size && classes[`${size}-size`] ) const otherProps = { onClick } if (href) { return ( <Link to={href} ref={button => { this.button = button }} className={classNames} {...otherProps} onMouseUp={this.handleClick} onTouchEnd={this.handleClick} > {content || children} {this.state.ripples} </Link> ) } return ( <button ref={button => { this.button = button }} className={classNames} {...otherProps} onMouseUp={this.handleClick} onTouchEnd={this.handleClick} > {content || children} {this.state.ripples} </button> ) } }
JavaScript
class ProductManager extends Manager { constructor(participantManager, callback) { super(participantManager, DB.products, ['gtin'], callback); this.productService = new (require('../services/ProductService'))(ANCHORING_DOMAIN); } /** * Binds the {@link Product#manufName} to the Product * @param {Product} product * @param {function(err, Product)} callback * @private */ _bindParticipant(product, callback){ let self = this; self.getIdentity((err, mah) => { if (err) return self._err(`Could not retrieve identity`, err, callback); product.manufName = mah.id; callback(undefined, product); }); } /** * Must wrap the entry in an object like: * <pre> * { * index1: ... * index2: ... * value: item * } * </pre> * so the DB can be queried by each of the indexes and still allow for lazy loading * @param {string} key * @param {Product} item * @param {string|object} record * @return {object} the indexed object to be stored in the db * @protected * @override */ _indexItem(key, item, record){ return { gtin: key, name: item.name, value: record } }; /** * Util function that loads a ProductDSU and reads its information * @param {string|KeySSI} keySSI * @param {function(err, Product, Archive)} callback * @protected * @override */ _getDSUInfo(keySSI, callback){ return this.productService.get(keySSI, callback); } /** * Creates a {@link Product} dsu * @param {string|number} [gtin] the table key * @param {Product} product * @param {function(err, keySSI, string)} callback where the string is the mount path relative to the main DSU * @override */ create(gtin, product, callback) { if (!callback){ callback = product; product = gtin; gtin = product.gtin; } let self = this; self._bindParticipant(product, (err, product) => { if (err) return self._err(`Could not bind mah to product`, err, callback); self.productService.create(product, (err, keySSI) => { if (err) return self._err(`Could not create product DSU for ${JSON.stringify(product, undefined, 2)}`, err, callback); const record = keySSI.getIdentifier(); self.insertRecord(gtin, self._indexItem(gtin, product, record), (err) => { if (err) return self._err(`Could not inset record with gtin ${gtin} on table ${self.tableName}`, err, callback); const path =`${self.tableName}/${gtin}`; console.log(`Product ${gtin} created stored at '${path}'`); callback(undefined, keySSI, path); }); }); }); } /** * reads ssi for that gtin in the db. loads is and reads the info at '/info' * @param {string} gtin * @param {boolean} [readDSU] defaults to true. decides if the manager loads and reads from the dsu or not * @param {function(err, Product|KeySSI, Archive)} callback returns the Product if readDSU and the dsu, the keySSI otherwise * @override */ getOne(gtin, readDSU, callback) { super.getOne(gtin, readDSU, callback); } /** * Removes a product from the list (does not delete/invalidate DSU, simply 'forgets' the reference) * @param {string|number} gtin * @param {function(err)} callback * @override */ remove(gtin, callback) { super.remove(gtin, callback); } /** * updates a product from the list * @param {string|number} [gtin] the table key * @param {Product} newProduct * @param {function(err, Product, Archive)} callback * @override */ update(gtin, newProduct, callback){ if (!callback){ callback = newProduct; newProduct = gtin; gtin = newProduct.gtin; } let self = this; return callback(`Product DSUs cannot be updated`); } /** * Lists all registered items according to query options provided * @param {boolean} [readDSU] defaults to true. decides if the manager loads and reads from the dsu's {@link INFO_PATH} or not * @param {object} [options] query options. defaults to {@link DEFAULT_QUERY_OPTIONS} * @param {function(err, object[])} callback * @override */ getAll(readDSU, options, callback){ const defaultOptions = () => Object.assign({}, DEFAULT_QUERY_OPTIONS, { query: ['__timestamp > 0'], sort: "dsc" }); if (!callback){ if (!options){ callback = readDSU; options = defaultOptions(); readDSU = true; } if (typeof readDSU === 'boolean'){ callback = options; options = defaultOptions(); } if (typeof readDSU === 'object'){ callback = options; options = readDSU; readDSU = true; } } options = options || defaultOptions(); super.getAll(readDSU, options, callback); } /** * Converts the text typed in a general text box into the query for the db * Subclasses should override this * @param {string} keyword * @return {string[]} query * @protected */ _keywordToQuery(keyword){ keyword = keyword || '.*'; return [`gtin like /${keyword}/g`]; } /** * * @param model * @returns {Product} * @override */ fromModel(model){ return new Product(super.fromModel(model)); } }
JavaScript
class Session { static changes = [] static lastState = {} /** * Return an Object representing the current state * @returns {Object} data The current state held in the store */ static getState() { // Merge changes since last retrieval into state const lastState = this.changes.reduce( (a, x) => Object.assign(a,x), this.lastState ) // Reset array of changes this.changes = [] this.lastState = lastState return lastState } /** * Update the current state * @param {Object} data Data to modify or put into the store * @returns {undefined} * @throws {string} Update only accepts objects */ static update(data) { if(typeof data === 'object') this.changes.push(data) else throw 'Update only accepts objects' } }
JavaScript
class Menu extends Component { static propTypes = { isAuthenticated: PropTypes.bool, isLoggedIn: PropTypes.func.isRequired, pathname: PropTypes.string.isRequired }; static defaultProps = { isAuthenticated: false }; constructor(props) { super(props); if (!props.isAuthenticated) { setTimeout(() => { props.isLoggedIn(); }, 5); } } render() { if (!this.props.isAuthenticated) { return null; } return ( <div className={`navbar-collapse collapse ${styles.sidebar}`} id="sidebar"> <nav> <ul className={styles.navigation}> <li> <NavLink to="/dashboard" activeClassName="selected" exact strict activeStyle={{ fontWeight: 'bold', backgroundColor: '#fff' }}> <i className="fa fa-tachometer fa-fw"></i> <span>&nbsp;Dashboard</span> </NavLink> </li> <li> <NavLink to="/users" activeClassName="selected" strict activeStyle={{ fontWeight: 'bold', backgroundColor: '#fff' }}> <i className="fa fa-users fa-fw"></i> <span>&nbsp;Users</span> </NavLink> </li> <li> <input type="checkbox" name="group-1" id="group-1"/> <label htmlFor="group-1"> <i className="fa fa-cog fa-fw"></i> <span>&nbsp;System</span> </label> <ul> <li> <NavLink to="/roles" activeClassName="selected" strict activeStyle={{ fontWeight: 'bold', backgroundColor: '#fff' }}> <i className="fa fa-user-circle fa-fw"></i> <span>&nbsp;Roles</span> </NavLink> </li> </ul> </li> </ul> </nav> </div> ); } }
JavaScript
class SmartInterval { /** * @param { function } opts.callback Function that returns a promise, called on each iteration * unless still in progress (required) * @param { milliseconds } opts.startingInterval `currentInterval` is set to this initially * @param { milliseconds } opts.maxInterval `currentInterval` will be incremented to this * @param { milliseconds } opts.hiddenInterval `currentInterval` is set to this * when the page is hidden * @param { integer } opts.incrementByFactorOf `currentInterval` is incremented by this factor * @param { boolean } opts.lazyStart Configure if timer is initialized on * instantiation or lazily * @param { boolean } opts.immediateExecution Configure if callback should * be executed before the first interval. */ constructor(opts = {}) { this.cfg = { callback: opts.callback, startingInterval: opts.startingInterval, maxInterval: opts.maxInterval, hiddenInterval: opts.hiddenInterval, incrementByFactorOf: opts.incrementByFactorOf, lazyStart: opts.lazyStart, immediateExecution: opts.immediateExecution, }; this.state = { intervalId: null, currentInterval: this.cfg.startingInterval, pagevisibile: true, }; this.initInterval(); } /* public */ start() { const { cfg, state } = this; if (cfg.immediateExecution && !this.isLoading) { cfg.immediateExecution = false; this.triggerCallback(); } state.intervalId = window.setInterval(() => { if (this.isLoading) { return; } this.triggerCallback(); if (this.getCurrentInterval() === cfg.maxInterval) { return; } this.incrementInterval(); this.resume(); }, this.getCurrentInterval()); } // cancel the existing timer, setting the currentInterval back to startingInterval cancel() { this.setCurrentInterval(this.cfg.startingInterval); this.stopTimer(); } onVisibilityHidden() { if (this.cfg.hiddenInterval) { this.setCurrentInterval(this.cfg.hiddenInterval); this.resume(); } else { this.cancel(); } } // start a timer, using the existing interval resume() { this.stopTimer(); // stop existing timer, in case timer was not previously stopped this.start(); } onVisibilityVisible() { this.cancel(); this.start(); } destroy() { document.removeEventListener('visibilitychange', this.onVisibilityChange); window.removeEventListener('blur', this.onWindowVisibilityChange); window.removeEventListener('focus', this.onWindowVisibilityChange); this.cancel(); // eslint-disable-next-line @gitlab/no-global-event-off $(document).off('visibilitychange').off('beforeunload'); } /* private */ initInterval() { const { cfg } = this; if (!cfg.lazyStart) { this.start(); } this.initVisibilityChangeHandling(); this.initPageUnloadHandling(); } triggerCallback() { this.isLoading = true; this.cfg .callback() .then(() => { this.isLoading = false; }) .catch((err) => { this.isLoading = false; throw err; }); } onWindowVisibilityChange(e) { this.state.pagevisibile = e.type === 'focus'; this.handleVisibilityChange(); } onVisibilityChange(e) { this.state.pagevisibile = e.target.visibilityState === 'visible'; this.handleVisibilityChange(); } initVisibilityChangeHandling() { // cancel interval when tab or window is no longer shown (prevents cached pages from polling) document.addEventListener('visibilitychange', this.onVisibilityChange.bind(this)); window.addEventListener('blur', this.onWindowVisibilityChange.bind(this)); window.addEventListener('focus', this.onWindowVisibilityChange.bind(this)); } initPageUnloadHandling() { // TODO: Consider refactoring in light of turbolinks removal. // prevent interval continuing after page change, when kept in cache by Turbolinks $(document).on('beforeunload', () => this.cancel()); } handleVisibilityChange() { const intervalAction = this.isPageVisible() ? this.onVisibilityVisible : this.onVisibilityHidden; intervalAction.apply(this); } getCurrentInterval() { return this.state.currentInterval; } setCurrentInterval(newInterval) { this.state.currentInterval = newInterval; } incrementInterval() { const { cfg } = this; const currentInterval = this.getCurrentInterval(); if (cfg.hiddenInterval && !this.isPageVisible()) return; let nextInterval = currentInterval * cfg.incrementByFactorOf; if (nextInterval > cfg.maxInterval) { nextInterval = cfg.maxInterval; } this.setCurrentInterval(nextInterval); } isPageVisible() { return this.state.pagevisibile; } stopTimer() { const { state } = this; state.intervalId = window.clearInterval(state.intervalId); } }
JavaScript
class Apple { constructor() { this.pos = createVector(5, 5); this.setPos(); // Singleton if (!Apple.instance) Apple.instance = this; return Apple.instance; } // Drawing apple on the map draw() { fill('red'); rect(this.pos.x * res, this.pos.y * res, res, res); } // Set new apple position on the map setPos() { let x = floor(random(cols)); let y = floor(random(rows)); this.pos.set(x, y); } }
JavaScript
class Employee { constructor(connection) { this.connection = connection } getAllEmployees() { //Chris helped me get CONCAT and AS keywords for SQL this.connection.query(` SELECT e1.id AS 'ID', e1.first_name AS 'First Name', e1.last_name AS 'Last Name', role.title AS 'Role', department.name AS 'Department', role.salary AS 'Salary', CONCAT(e2.first_name, ' ', e2.last_name) AS Manager FROM employee e1 INNER JOIN role ON role.id = e1.role_id INNER JOIN department ON role.department_id = department.id JOIN employee e2 WHERE e2.id = e1.manager_id `, callback) } getEmployeesByDepartment() { this.connection.query(` SELECT e1.id AS 'ID', e1.first_name AS 'First Name', e1.last_name AS 'Last Name', role.title AS 'Role', department.name AS 'Department', role.salary AS 'Salary', CONCAT(e2.first_name, ' ', e2.last_name) AS Manager FROM employee e1 INNER JOIN role ON role.id = e1.role_id INNER JOIN department ON role.department_id = department.id JOIN employee e2 WHERE e2.id = e1.manager_id ORDER BY department.id ASC`, callback) } getEmployeesByManager() { this.connection.query(` SELECT e1.id AS 'ID', e1.first_name AS 'First Name', e1.last_name AS 'Last Name', role.title AS 'Role', department.name AS 'Department', role.salary AS 'Salary', CONCAT(e2.first_name, ' ', e2.last_name) AS Manager FROM employee e1 INNER JOIN role ON role.id = e1.role_id INNER JOIN department ON role.department_id = department.id JOIN employee e2 WHERE e2.id = e1.manager_id ORDER BY e1.manager_id ASC`, callback) } getAllDepartments() { this.connection.query(`SELECT name FROM department`, callback) } getAllRoles() { this.connection.query(`SELECT title, salary FROM role`, callback) } updateRole(id, options) { this.connection.query(`UPDATE employee SET ? WHERE ?`, [options, { id }], callback) } updateManager(id, options) { this.connection.query(`UPDATE employee SET ? WHERE ?`, [options, { id }], callback) } deleteEmployee(val) { this.connection.query(`DELETE FROM employee WHERE id = ?`, val, callback) } deleteRole(val) { this.connection.query(`DELETE FROM role WHERE id = ?`, val, callback) } deleteDepartment(val) { this.connection.query(`DELETE FROM department WHERE id = ?`, val, callback) } addDepartment(options) { return this.connection.query(`INSERT INTO department SET ?`, options, callback) } addRole(options) { return this.connection.query(`INSERT INTO role SET ?`, options, callback) } addEmployee(options) { return this.connection.query(`INSERT INTO employee SET ?`, options, callback) } //next three functions set questions with employeee/role/department info getEmployeeInfo(){ this.connection.query('SELECT first_name, last_name, id FROM employee', function(err, res){ if (err) throw err else { let emp = [] res.forEach(element => { emp.push(`${element['first_name']} ${element['last_name']} ID: ${ element.id}`) }) questions.addEmployee[3].choices = emp questions.removeEmployee[0].choices = emp questions.updateManager[0].choices = emp questions.updateManager[1].choices = emp questions.updateRole[0].choices = emp } }) } getRoleInfo(){ this.connection.query('SELECT title, id FROM role', function(err, res){ if (err) throw err let roles = [] res.forEach(role => { roles.push(`${ role.title } RoleID: ${ role.id }`) }) questions.addEmployee[2].choices = roles questions.removeRole[0].choices = roles questions.updateRole[1].choices = roles }) } getDepartmentInfo(){ this.connection.query('SELECT * FROM department', function(err, res){ if(err) throw err let depart = [] res.forEach(element => { depart.push(`${ element.name } DepartmentID: ${ element.id }`) }); questions.removeDepartment[0].choices = depart questions.addRole[2].choices = depart }) } }
JavaScript
class MozuProvisioningContractsCatalogProvisionRequest { /** * Constructs a new <code>MozuProvisioningContractsCatalogProvisionRequest</code>. * @alias module:model/MozuProvisioningContractsCatalogProvisionRequest */ constructor() { MozuProvisioningContractsCatalogProvisionRequest.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>MozuProvisioningContractsCatalogProvisionRequest</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/MozuProvisioningContractsCatalogProvisionRequest} obj Optional instance to populate. * @return {module:model/MozuProvisioningContractsCatalogProvisionRequest} The populated <code>MozuProvisioningContractsCatalogProvisionRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new MozuProvisioningContractsCatalogProvisionRequest(); if (data.hasOwnProperty('isOverride')) { obj['isOverride'] = ApiClient.convertToType(data['isOverride'], 'Boolean'); } if (data.hasOwnProperty('isRetry')) { obj['isRetry'] = ApiClient.convertToType(data['isRetry'], 'Boolean'); } if (data.hasOwnProperty('tenantId')) { obj['tenantId'] = ApiClient.convertToType(data['tenantId'], 'Number'); } if (data.hasOwnProperty('masterCatalogId')) { obj['masterCatalogId'] = ApiClient.convertToType(data['masterCatalogId'], 'Number'); } if (data.hasOwnProperty('catalogId')) { obj['catalogId'] = ApiClient.convertToType(data['catalogId'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('defaultLocaleCode')) { obj['defaultLocaleCode'] = ApiClient.convertToType(data['defaultLocaleCode'], 'String'); } if (data.hasOwnProperty('defaultCurrencyCode')) { obj['defaultCurrencyCode'] = ApiClient.convertToType(data['defaultCurrencyCode'], 'String'); } } return obj; } }
JavaScript
class PlayerControls extends Lightning.Component { /** * @static * @returns * @memberof PlayerControls * Renders the template */ static _template() { return { w: 1755, clipping: true, Title: { w: 409, h: 67 }, Subtitle: { y: 72, w: 202, h: 34 }, TimeBar: { y: 142, zIndex: 1, color: 0xff3a3a3a, w: 1755, h: 8, rect: true }, ProgressBar: { y: 142, h: 8, zIndex: 1, rect: true, color: 0xff0ad887 }, ControlsBackground: { w: 1755, h: 116, y: 147, rect: true, color: 0xff000000, CurrentTime: { color: 0xffc4c4c4, w: 92, h: 29, x: 27, y: 11 }, TotalTime: { color: 0xffc4c4c4, x: 1638, y: 11, w: 92, h: 29 }, ControlsList: { x: 506, y: 5, w: 740, h: 106, roll: true, itemSize: 146, horizontal: true, invertDirection: false, type: Lightning.components.ListComponent } }, SettingsBackground: { y: 263, w: 1755, h: 100, rect: true, color: 0x30000052, PlaybackSettings: { x: 533, y: 0, w: 690, h: 100, itemSize: 144, roll: true, horizontal: true, invertDirection: false, type: Lightning.components.ListComponent } } } } _init() { this.toggle = null /** * Setting icons for Controls and Settings */ this.tag('ControlsList').items = [ { iconNormal: ImageConstants.FIRST, iconSelected: ImageConstants.FIRST_SELECTED, HighLight: ImageConstants.PRIMARY_SELECTION }, { iconNormal: ImageConstants.REWIND, iconSelected: ImageConstants.REWIND_SELECTED, HighLight: ImageConstants.PRIMARY_SELECTION }, { iconNormal: ImageConstants.PAUSEBUTTON, iconSelected: ImageConstants.PAUSE_SELECTED, HighLight: ImageConstants.PRIMARY_SELECTION }, { iconNormal: ImageConstants.FORWARD, iconSelected: ImageConstants.FORWARD_SELECTED, HighLight: ImageConstants.PRIMARY_SELECTION }, { iconNormal: ImageConstants.LAST, iconSelected: ImageConstants.LAST_SELECTED, HighLight: ImageConstants.PRIMARY_SELECTION } ].map((data, index) => { return { ref: 'Icon_' + index, type: IconComponent, items: data, h: 106 } }) this.tag('PlaybackSettings').items = [ { iconNormal: ImageConstants.RECORD, iconSelected: ImageConstants.RECORD_INACTIVE, HighLight: ImageConstants.SECONDARY_SELECTION }, { iconNormal: ImageConstants.SETTINGS_ICON_NORMAL, iconSelected: ImageConstants.SETTINGS_ICON_SELECTED, HighLight: ImageConstants.SECONDARY_SELECTION }, { iconNormal: ImageConstants.CAPTIONS, iconSelected: ImageConstants.CAPTIONS, HighLight: ImageConstants.SECONDARY_SELECTION }, { iconNormal: ImageConstants.INFO, iconSelected: ImageConstants.INFO, HighLight: ImageConstants.SECONDARY_SELECTION } ].map((data, index) => { return { ref: 'Icon_' + index, type: IconComponent, items: data, h: 106, w: 140 } }) //Variable to store the duration of the video content. this.videoDuration = 0 this._setState('PlaybackControls') } /** * Function to set the title in the video controls. * @param {String} title title to be displayed in video controls. */ set title(v) { Log.info('setting title', v) this.tag('Title').patch({ text: { fontSize: 56, fontFace: 'Regular', text: v } }) } /** * Function to set the subtitle in the video control menu. * @param {String} subtitle sub title to be displayed. */ set subtitle(v) { this.tag('Subtitle').patch({ text: { fontSize: 28, fontFace: 'Medium', text: v } }) } /** * Function to set the duration of the video. * @param {String} duration video duration to be set. */ set duration(v) { this.videoDuration = v this.tag('TotalTime').patch({ text: { fontSize: 24, textAlign: 'center', fontFace: 'Regular', text: this.SecondsTohhmmss(v) } }) } /** * Function to set the current video time. * @param {String} currentTime current time to be set. */ set currentTime(v) { this.tag('CurrentTime').patch({ text: { fontSize: 24, textAlign: 'center', fontFace: 'Regular', text: this.SecondsTohhmmss(v) } }) this.tag('ProgressBar').patch({ w: (1755 * v) / this.videoDuration }) } /** * Function to convert time in seconds to hh:mm:ss format. * @param {String} totalSeconds time in seconds. */ SecondsTohhmmss(totalSeconds) { this.hours = Math.floor(totalSeconds / 3600) this.minutes = Math.floor((totalSeconds - this.hours * 3600) / 60) this.seconds = totalSeconds - this.hours * 3600 - this.minutes * 60 this.seconds = Math.round(totalSeconds) - this.hours * 3600 - this.minutes * 60 this.result = this.hours < 10 ? '0' + this.hours : this.hours this.result += ':' + (this.minutes < 10 ? '0' + this.minutes : this.minutes) this.result += ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds) return this.result } _active() { //To bring back the focus to the pause/play button whenever the control is on screen this.tag('ControlsList').setIndex(2) } /** * To reset the PlayerControls */ _reset() { this.toggle = null let currentIndex = 2 if (this.tag('ControlsList').index == 0 || this.tag('ControlsList').index == 4) { currentIndex = this.tag('ControlsList').index Log.info(this.currentIndex, 'currentIndex') } this.tag('ControlsList').setIndex(2) this.tag('ControlsList') .element.tag('Icon') .patch({ src: Utils.asset(ImageConstants.PAUSEBUTTON) }) this.tag('ControlsList').element.patch({ items: { iconNormal: ImageConstants.PAUSEBUTTON, iconSelected: ImageConstants.PAUSE_SELECTED, HighLight: ImageConstants.PRIMARY_SELECTION } }) this.tag('ControlsList').setIndex(currentIndex) this._setState('PlaybackControls') } /** * @static * @returns * @memberof PlayerControls * set Player Controls States */ static _states() { return [ class PlaybackControls extends this { $enter() { this.index = 0 this.tag('ControlsList').setIndex(2) } _handleRight() { if (this.tag('ControlsList').length - 1 != this.tag('ControlsList').index) { this.tag('ControlsList').setNext() } } _handleLeft() { if (0 != this.tag('ControlsList').index) { this.tag('ControlsList').setPrevious() } } _getFocused() { return this.tag('ControlsList').element } _handleDown() { this._setState('PlaybackSettings') } _handleUp() { Log.info('Hide Control !!!!!!!!') this.fireAncestors('$exitPlayerControl', '') } _handleEnter() { switch (this.tag('ControlsList').index) { case 0: this.fireAncestors('$lastVideo', '') break case 1: this.fireAncestors('$rewind', '') break case 2: this.fireAncestors('$doPlayPause', '') if (this.toggle == 0) { this.tag('ControlsList').element.patch({ items: { iconNormal: ImageConstants.PAUSEBUTTON, iconSelected: ImageConstants.PAUSE_SELECTED, HighLight: ImageConstants.PRIMARY_SELECTION } }) this.tag('ControlsList') .element.tag('Icon') .patch({ src: Utils.asset(ImageConstants.PAUSE_SELECTED) }) this.toggle = 1 } else { this.tag('ControlsList').element.patch({ items: { iconNormal: ImageConstants.PLAY, iconSelected: ImageConstants.PLAY_SELECTED, HighLight: ImageConstants.PRIMARY_SELECTION } }) this.tag('ControlsList') .element.tag('Icon') .patch({ src: Utils.asset(ImageConstants.PLAY_SELECTED) }) this.toggle = 0 } break case 3: this.fireAncestors('$fastfwd', '') break case 4: this.fireAncestors('$nextVideo', '') break } } $exit() { this.tag('ControlsList').setIndex(2) } }, class PlaybackSettings extends this { $enter() { this.tag('ControlsList').setIndex(2) Log.info('\n Playback setting state') } _handleRight() { if (this.tag('PlaybackSettings').length - 1 != this.tag('PlaybackSettings').index) { this.tag('PlaybackSettings').setNext() } } _handleLeft() { if (0 != this.tag('PlaybackSettings').index) { this.tag('PlaybackSettings').setPrevious() } } _handleEnter() { this.fireAncestors('$mediaplayerControl', '') } _getFocused() { return this.tag('PlaybackSettings').element } _handleUp() { this.visible = true this.alpha = 1 this._setState('PlaybackControls') } $exit() { this.tag('PlaybackSettings').setIndex(0) } } ] } }
JavaScript
class UITestSuite { get app() { return this.mochaContext && this.mochaContext.app; } get logger() { return this.app && this.app.logger; } get currentTestName() { const currentTest = this.mochaContext && this.mochaContext.test; if (!currentTest) return undefined; return `${currentTest.parent.title}.${currentTest.title}`; } get currentLogsDir() { const logsDir = this.mochaContext && this.mochaContext.logsDir; if (!logsDir) return undefined; const currentTestName = this.currentTestName; return currentTestName ? path.join(logsDir, currentTestName) : logsDir; } get testAccount() { return this.mochaContext && this.mochaContext.testAccount; } get serviceUri() { return this.mochaContext && this.mochaContext.serviceUri; } get extensionDir() { return this.mochaContext && this.mochaContext.extensionDir; } get extensionInfo() { return this.extensionDir && require(path.join(this.extensionDir, 'package.json')); } get hostWindow() { return UITestSuite._hostWindow; } set hostWindow(value) { UITestSuite._hostWindow = value; } get guestWindow() { return UITestSuite._guestWindow; } set guestWindow(value) { UITestSuite._guestWindow = value; } get hostWorkbench() { return UITestSuite._hostWorkbench; } set hostWorkbench(value) { UITestSuite._hostWorkbench = value; } get guestWorkbench() { return UITestSuite._guestWorkbench; } set guestWorkbench(value) { UITestSuite._guestWorkbench = value; } get inviteUri() { return UITestSuite._inviteUri; } set inviteUri(value) { UITestSuite._inviteUri = value; } /** Signs in the test user (in the host window), if not already signed in. */ static async ensureSignedIn(context) { const suite = new UITestSuite(); suite.mochaContext = context; const signedIn = await suite.checkForStatusBarTitle(suite.hostWindow, suite.testAccount.email); if (!signedIn) { const userCode = await web.signIn(suite.serviceUri, 'microsoft', suite.testAccount.email, suite.testAccount.password, false); assert(userCode, 'Should have gotten a user code from browser sign-in.'); await suite.runLiveShareCommand(suite.hostWorkbench, 'liveshare.signin.token'); await suite.hostWorkbench.quickinput.waitForQuickInputOpened(); await suite.hostWindow.waitForSetValue(quickinput_1.QuickInput.QUICK_INPUT_INPUT, userCode); await suite.hostWindow.dispatchKeybinding('enter'); await suite.waitForStatusBarTitle(suite.hostWindow, suite.testAccount.email); } } /** Call from a static before() method in a subclass to start sharing before a test suite. */ static async startSharing(context, join = true) { await UITestSuite.ensureSignedIn(context); const suite = new UITestSuite(); suite.mochaContext = context; await suite.share(); if (join) { await suite.join(); } // Wait a bit for things to settle after sharing/joining. For some reason // this makes it less likely for focus to be stolen from a quickopen (command) // input box immediately afterward. await new Promise((c) => setTimeout(c, 2000)); } /** Call from a static after() method in a subclass to end sharing after a test suite. */ static async endSharing(context, unjoin = true) { const suite = new UITestSuite(); suite.mochaContext = context; if (unjoin) { await suite.unjoin(); } await suite.unshare(); } async captureScreenshot(window, name) { if (!name.toLowerCase().endsWith('.png')) { name += '.png'; } const screenshotPath = path.join(this.currentLogsDir, name); const raw = await window.capturePage(); const buffer = new Buffer(raw, 'base64'); await fs_extra_1.mkdirp(this.currentLogsDir); await util.promisify(fs.writeFile)(screenshotPath, buffer); } async openGuestWindow(workspaceFilePath) { if (!workspaceFilePath) { await this.hostWorkbench.quickopen.runCommand('New Window'); } else { await this.openFolderOrWorkspace(this.hostWindow, workspaceFilePath, true); } let newWindowId; await this.hostWindow.waitForWindowIds((ids) => { // TODO: Handle >2 windows. if (ids.length === 2) { newWindowId = ids[1]; return true; } }); return await this.getNewWindow(this.hostWindow, newWindowId); } async openFolderOrWorkspace(window, path, openInNewWindow) { const workspaceUri = 'file://' + path; await this.executeCommand(window, 'delay+vscode.openFolder', workspaceUri, openInNewWindow); } async reloadWindow(window) { await this.executeCommand(window, 'delay+workbench.action.reloadWindow'); } async closeWorkspace(window) { await this.executeCommand(window, 'delay+workbench.action.closeFolder'); } async closeWindow(window) { await this.executeCommand(window, 'delay+workbench.action.closeWindow'); if (window === this.guestWindow) { this.guestWindow = null; } } /** * Uses a test hook in the VSLS extension to execute an arbitrary VS Code command. */ async executeCommand(window, command, ...args) { await window.dispatchKeybinding('ctrl+shift+alt+f1'); const commandAndArgs = `${command} ${JSON.stringify(args)}`; await window.waitForSetValue(quickinput_1.QuickInput.QUICK_INPUT_INPUT, commandAndArgs); await window.dispatchKeybinding('enter'); } async getNewWindow(existingWindow, windowId) { // This code accesses some private members of the `Code` class, // because it was not designed to support multi-window automation. const newWindow = new code_1.Code(existingWindow.process, existingWindow.client, existingWindow.driver, this.logger); newWindow._activeWindowId = windowId; newWindow.driver = existingWindow.driver; // Wait for the new window to be ready. (This code is copied from // Application.checkWindowReady(), which only works for the first window.) await newWindow.waitForElement('.monaco-workbench'); await new Promise(c => setTimeout(c, 500)); return newWindow; } getLiveShareCommandInfo(id) { const command = this.extensionInfo.contributes.commands.find((c) => c.command === id); assert(command && command.title && command.category, 'Expected Live Share command: ' + id); return command; } async runLiveShareCommand(workbench, id) { const command = this.getLiveShareCommandInfo(id); const title = command && command.title; const category = command && command.category; await workbench.quickopen.runCommand(`${category}: ${title}`); } async runLiveShareCommandIfAvailable(workbench, id) { const command = this.getLiveShareCommandInfo(id); const title = command && command.title; const category = command && command.category; await workbench.quickopen.openQuickOpen(`>${category}: ${title}`); const window = workbench.quickopen.code; await window.dispatchKeybinding('enter'); await window.dispatchKeybinding('escape'); } /** * Waits for a notification with text that matches a given substring or regex. * @returns a CSS selector for the found notification element */ async waitForNotification(window, message) { let notificationIndex = -1; await window.waitForElements('.notification-list-item-message', false, (elements) => { notificationIndex = 0; for (let element of elements) { if (element.textContent.match(message)) { return true; } notificationIndex++; } return false; }); return `.notifications-toasts > div:nth-child(${notificationIndex + 1}) ` + '.notification-list-item'; } async waitForAndClickNotificationButton(window, message, buttonText) { const selector = await this.waitForNotification(window, message); // Notifications animate in, so they can't be clicked immediately. await new Promise((c) => setTimeout(c, 500)); await window.waitAndClick(`${selector} a.monaco-button[title="${buttonText}"]`); } async waitForAndDismissNotification(window, message) { const selector = await this.waitForNotification(window, message); // Notifications animate in, so they can't be clicked immediately. await new Promise((c) => setTimeout(c, 500)); // Click on the notification first to ensure the focus is in the right place. await window.waitAndClick(selector); // Send the hotkey to dismiss the notification. await window.dispatchKeybinding(os.platform() === 'darwin' ? 'cmd+backspace' : 'delete'); } /** * Checks if the statusbar currently contains an entry with the given title (not label). */ async checkForStatusBarTitle(window, titleMatch) { const statusbarElements = await window.waitForElements('.statusbar-entry a', false); const entry = statusbarElements.find(element => { const title = element.attributes['title']; return !!(title && title.match(titleMatch)); }); return !!entry; } /** * Waits for a statusbar with the given title (not label). * Or specify invert=true to wait until it goes away. * @returns a CSS selector for the found statusbar item */ async waitForStatusBarTitle(window, titleMatch, invert = false) { let itemIndex = -1; await window.waitForElements('.statusbar > div', true, (elements) => { itemIndex = 0; for (let element of elements) { const title = element.children && element.children[0] && element.children[0].attributes['title']; if (title && title.match(titleMatch)) { return !invert; } itemIndex++; } return invert; }); return `.statusbar > div:nth-of-type(${itemIndex + 1})`; } async waitForAndClickStatusBarTitle(window, titleMatch) { const selector = await this.waitForStatusBarTitle(window, titleMatch); await window.waitAndClick(`${selector} > a`); } async waitForDocumentTitle(window, titleMatch, invert = false) { await window.waitForElements('.monaco-icon-label a.label-name', false, (elements) => { for (let element of elements) { const title = element.textContent; if (title && title.match(titleMatch)) { return !invert; } } return invert; }); } async share(connectionMode) { this.hostWorkbench.quickopen.runCommand('Notifications: Clear All Notifications'); await this.changeSettings({ 'liveshare.connectionMode': connectionMode || UITestSuite._defaultConnectionMode }); await this.runLiveShareCommand(this.hostWorkbench, 'liveshare.start'); const welcomeRegex = /vsliveshare-welcome-page/; const invitationRegex = /Invitation link copied/; const firewallRegex = /firewall.*vsls-agent/; // Depending on the state of the welcome page memento and firewall configuration, // sharing could lead to one of 3 different things. Wait for all of them simultaneously. let blockedByFirewall = false; let welcomePageShown = false; await this.hostWindow.waitForElements('.monaco-icon-label a.label-name, .notification-list-item-message', false, (elements) => { for (let element of elements) { if (UITestSuite._firstShare && welcomeRegex.test(element.textContent)) { welcomePageShown = true; return true; } else if (invitationRegex.test(element.textContent)) { return true; } else if (firewallRegex.test(element.textContent)) { blockedByFirewall = true; return true; } } }); if (blockedByFirewall) { // A non-automatable firewall dialog is about to be shown. // Abort sharing by reloading the window. Then wait for ready state. await this.reloadWindow(this.hostWindow); await new Promise((c) => setTimeout(c, 4000)); await this.waitForStatusBarTitle(this.hostWindow, /(Start Collaboration)|(Share the workspace)/); if (!connectionMode) { // A specific connection mode was not specified. // So switch the default mode to relay and try again. UITestSuite._defaultConnectionMode = 'relay'; return this.share(UITestSuite._defaultConnectionMode); } else { throw new Error(`Cannot share in ${connectionMode} mode. Blocked by firewall.`); } } UITestSuite._firstShare = false; if (!welcomePageShown) { await this.waitForAndDismissNotification(this.hostWindow, invitationRegex); } this.inviteUri = clipboardy_1.readSync(); assert(this.inviteUri && this.inviteUri.startsWith(this.serviceUri), 'Invite link should have been copied to clipboard.'); } async unshare() { await this.runLiveShareCommandIfAvailable(this.hostWorkbench, 'liveshare.end'); await this.waitForStatusBarTitle(this.hostWindow, /(Start Collaboration)|(Share the workspace)/); this.inviteUri = null; } async join(connectionMode = 'auto') { if (!this.inviteUri) { throw new Error('Not in shared state.'); } await this.changeSettings({ 'liveshare.connectionMode': connectionMode }); if (!this.guestWindow) { this.guestWindow = await this.openGuestWindow(); this.guestWorkbench = new workbench_1.Workbench(this.guestWindow, this.app.userDataPath); } await this.runLiveShareCommand(this.guestWorkbench, 'liveshare.join'); await this.guestWorkbench.quickinput.waitForQuickInputOpened(); await this.guestWindow.waitForSetValue(quickinput_1.QuickInput.QUICK_INPUT_INPUT, this.inviteUri); await this.guestWindow.dispatchKeybinding('enter'); // The window should reload with collaborating status. // Consume some of the time here to reduce the liklihood of the next wait timing out. await new Promise((c) => setTimeout(c, 5000)); await this.waitForStatusBarTitle(this.guestWindow, 'Collaborating'); } async unjoin() { await this.runLiveShareCommandIfAvailable(this.guestWorkbench, 'liveshare.leave'); // Wait until the window reload has surely started, to avoid // detecting the status before the reload. await new Promise((c) => setTimeout(c, 4000)); // The guest window should reload in an unjoined state. await this.waitForStatusBarTitle(this.guestWindow, /(Start Collaboration)|(Share the workspace)/); } async changeSettings(settings) { const settingsFilePath = this.mochaContext.settingsFilePath; let settingsObject = JSON.parse((await util.promisify(fs.readFile)(settingsFilePath)).toString()); for (let name in settings) { let value = settings[name]; if (typeof value === 'undefined') { delete settingsObject[name]; } else { settingsObject[name] = value; } } await util.promisify(fs.writeFile)(settingsFilePath, JSON.stringify(settingsObject, null, '\t')); // Allow some time for VS Code to load the changed settings. await new Promise((c) => setTimeout(c, 1000)); } }
JavaScript
class Node { constructor(value) { this.value = value this.next = null; } }
JavaScript
class ModalMultiSelect extends _react.Component { constructor(props) { super(props); this._selectAll = () => { const allValues = this.props.options.map(option => option.value); this.setState({ activeValues: allValues }); }; this._selectNone = () => { this.setState({ activeValues: [] }); }; this._resetSelection = () => { this.setState({ activeValues: this.props.value }); }; this._showModal = () => { this.setState({ showModal: true, // When you show the modal, the initial selection should match the actually selected values. activeValues: this.props.value }); }; this._dismissModal = () => { this.setState({ showModal: false }); }; this._confirmValues = () => { // TODO (matthewwithanm): Use ctrl-enter to confirm this._dismissModal(); this.props.onChange(this.state.activeValues); }; this.state = { activeValues: props.value, showModal: false }; } render() { const LabelComponent = this.props.labelComponent || DefaultLabelComponent; const selectedOptions = this.props.options.filter(option => this.props.value.indexOf(option.value) !== -1); const className = (0, (_classnames || _load_classnames()).default)(this.props.className, { 'btn-warning': this.props.value.length === 0 }); return _react.createElement( (_Button || _load_Button()).Button, { className: className, disabled: this.props.disabled, size: this.props.size, onClick: event => { // Because of how Portals work in React, this handler will actually be triggered for all // clicks within the modal! We need to filter those out to separate button clicks. // (see https://reactjs.org/docs/portals.html#event-bubbling-through-portals) const modalElement = this._modal && _reactDom.default.findDOMNode(this._modal); if (modalElement == null || !modalElement.contains(event.target)) { this._showModal(); } } }, _react.createElement(LabelComponent, { selectedOptions: selectedOptions }), this._renderModal() ); } _renderModal() { if (!this.state.showModal) { return; } return _react.createElement( (_Modal || _load_Modal()).Modal, { ref: c => { this._modal = c; }, onDismiss: this._dismissModal }, _react.createElement((_MultiSelectList || _load_MultiSelectList()).MultiSelectList, { commandScope: atom.views.getView(atom.workspace), value: this.state.activeValues, options: this.props.options, optionComponent: this.props.optionComponent, onChange: activeValues => this.setState({ activeValues }) }), _react.createElement( 'div', { className: 'nuclide-modal-multi-select-actions' }, _react.createElement( (_ButtonGroup || _load_ButtonGroup()).ButtonGroup, null, _react.createElement( (_Button || _load_Button()).Button, { onClick: this._selectNone }, 'None' ), _react.createElement( (_Button || _load_Button()).Button, { onClick: this._selectAll }, 'All' ), _react.createElement( (_Button || _load_Button()).Button, { onClick: this._resetSelection }, 'Reset' ) ), _react.createElement( (_ButtonGroup || _load_ButtonGroup()).ButtonGroup, null, _react.createElement( (_Button || _load_Button()).Button, { onClick: this._dismissModal }, 'Cancel' ), _react.createElement( (_Button || _load_Button()).Button, { buttonType: (_Button || _load_Button()).ButtonTypes.PRIMARY, onClick: this._confirmValues }, 'Confirm' ) ) ) ); } }
JavaScript
class Mailer { /** * Creates an instance of Mailer. * * @memberof Mailer */ constructor() { const { GMAIL_USERNAME, GMAIL_PASSWORD } = process.env; this.transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: GMAIL_USERNAME, pass: GMAIL_PASSWORD } }); } /** * Set where the email is from * * @param {string} from - sets where the email is from * * @memberof Mailer * * @returns {undefined} */ from(from) { this.from = from; } /** * Set the recipient of the mail * * @param {string} to - sets the email recipient * * @memberof Mailer * * @returns {undefined} */ to(to) { this.to = to; } /** * Set the subject of the mail * * @param {string} subject - sets the subject of the mail * * @memberof Mailer * * @returns {undefined} */ subject(subject) { this.subject = subject; } /** * Set the mail text without HTML syntax * * @param {string} text - sets the text version of the mail * * @memberof Mailer * * @returns {undefined} */ text(text) { this.text = text; } /** * Set the html format of the mail * * @param {string} html - sets the html version of the mail * * @memberof Mailer * * @returns {undefined} */ html(html) { this.html = html; } /** * Set the mail option to be sent to Nodemailer * * @returns {object} mailOptions * * @memberof Mailer */ mailOptions() { return { from: this.from, subject: this.subject, html: this.html, to: this.to }; } /** * Sends the mail using nodemailer * * @memberof Mailer * * @returns {undefined} */ send() { return this.transporter .sendMail( this.mailOptions(), () => { } ); } }
JavaScript
class IceBox { /** * Construct an {@link IceBox}. */ constructor() { Object.defineProperties(this, { _filter: { value: new Filter({ getKey: function getKey(iceState) { return iceState.ufrag; }, isLessThanOrEqualTo: function isLessThanOrEqualTo(a, b) { return a.revision <= b.revision; } }) }, _ufrag: { writable: true, value: null }, ufrag: { enumerable: true, get() { return this._ufrag; } } }); } /** * Set the ICE username fragment on the {@link IceBox}. This method returns any * ICE candidates associated with the username fragment. * @param {string} ufrag * @returns {Array<RTCIceCandidateInit>} */ setUfrag(ufrag) { this._ufrag = ufrag; const ice = this._filter.toMap().get(ufrag); return ice ? ice.candidates : []; } /** * Update the {@link IceBox}. This method returns any new ICE candidates * associated with the current username fragment. * @param {object} iceState * @returns {Array<RTCIceCandidateInit>} */ update(iceState) { // NOTE(mroberts): The Server sometimes does not set the candidates property. iceState.candidates = iceState.candidates || []; const oldIceState = this._filter.toMap().get(iceState.ufrag); const oldCandidates = oldIceState ? oldIceState.candidates : []; return this._filter.update(iceState) && this._ufrag === iceState.ufrag ? iceState.candidates.slice(oldCandidates.length) : []; } }
JavaScript
class Tw2GeometryLineBatch extends Tw2GeometryBatch { /** * Commits the Geometry Line Batch for rendering * @param {String} technique - technique name */ Commit(technique) { if (this.geometryRes && this.effect) { this.geometryRes.RenderLines(this.meshIx, this.start, this.count, this.effect, technique); } } }
JavaScript
class TransactionItem { constructor(_amount, _title, _spontaneous, _id){ this.state = ({ amount: _amount, title: _title, spontaneous: _spontaneous, id: _id, }); } //getter functions to get the values throughout the rest of the program getAmount() { return this.state.amount; } getTitle() { return this.state.title; } getSpontaneous() { return this.state.spontaneous; } }
JavaScript
class ERR_INVALID_ARG_TYPE extends Error { constructor(name, st, obj, cb = def) { // Declare reset function const reset = (o, n, s, c) => { obj = o; name = n; st = s; cb = c; }; // Change value of arguments if any argument is of invalid type if (typeof name !== "string") { reset(name, "name", "of type string", def); } else if (typeof st !== "string") { reset(st, "statement", "of type string", def); } else if (typeof cb !== "function") { reset(cb, "callback", "of type function", def); } // Generate error message super(`The "${name}" argument must be ${st}. Received ${cb(obj)}`); } // Change constructor's name name = `TypeError [${this.constructor.name}]`; }
JavaScript
class MyComponent extends React.Component { constructor(props) { super(props); } render() { // Change code below this line return ( <div> <h1>Hello React!</h1> </div> ) // Change code above this line } }
JavaScript
class NodeLayoutPortLocationHandle extends ConstrainedHandle { /** * Creates a new instance of <code>NodeLayoutPortLocationHandle</code>. * @param {INode} node * @param {IHandle} wrappedHandle */ constructor(node, wrappedHandle) { super(wrappedHandle) this.node = node } /** * Returns the constraints for the new location. * @param {IInputModeContext} context The context in which the drag will be performed * @param {Point} originalLocation The value of the * {@link ConstrainedDragHandler<TWrapped>#location} property at the time of * {@link ConstrainedDragHandler<TWrapped>#initializeDrag} * @param {Point} newLocation The coordinates in the world coordinate system that the client wants * the handle to be at. Depending on the implementation the * {@link ConstrainedDragHandler<TWrapped>#location} may or may not be modified to reflect the new * value * @returns {Point} */ constrainNewLocation(context, originalLocation, newLocation) { return newLocation.getConstrained(this.node.layout.toRect()) } }
JavaScript
class VideoFeedManager extends Component { /** * Fetch videos with the selected sources when video source selection changes / on startup * @param sources */ fetchVideos = sources => { store.dispatch(fetchFeedItemsAction(sources)); }; /** * Video feed component entry point - * Fetching feeds from all sources (URL, facebook & youtube) */ componentDidMount() { this.fetchVideos(); } render() { let Feed; switch (this.props.feedDisplayState) { case VideoDisplayState.INIT: case VideoDisplayState.FETCHING: Feed = <div className="loader" />; break; case VideoDisplayState.FETCHED: Feed = ( <div className="video-feed-container"> <VideoSourceSelectionManager fetchVideos={this.fetchVideos} /> <div className="video-feed"> {this.props.items.map((item, i) => { return <VideoItemManager videoItem={item} key={i} />; })} </div> </div> ); break; case VideoDisplayState.ERROR: Feed = ( <div className="video-load-error-text">{this.props.errorString}</div> ); break; default: Feed = <div />; } return Feed; } }
JavaScript
class ScreenshotView extends ElementBaseWithUrls { static get is() { return 'cuic-screenshot-view'; } static get properties() { return { key: { type: String, observer: 'keyChanged_' }, filterValues_: Array, userTags_: Array, metadata_: Array, }; } keyChanged_() { if (this.key) { this.$['get-screenshot-data'].generateRequest(); } } handleError_(e) { alert('Error fetching screenshot data.') console.log('Error fetching screenshot data:'); console.log(e.detail); } convertToArray_(o) { return Object.entries(o).map( e=>{ return {'name': e[0], 'value': e[1]}}); } handleResponse_(r) { const response = r.detail.response; this.set('filterValues_', this.convertToArray_(response.filters)); this.set('metadata_', this.convertToArray_(response.metadata)); this.set('userTags_', response.userTags) } }
JavaScript
class StoreComponent extends _react.default.PureComponent { constructor() { super(); this.handleStoreUpdate = this.handleStoreUpdate.bind(this); } componentWillMount() { this.reduxWatcher = store.subscribe(this.handleStoreUpdate); const storeState = store.getState(); const state = {}; this.props.watchInStore.forEach(key => { state[key] = storeState[key]; }); this.setState(state); } componentWillUnmount() { this.reduxWatcher(); } handleStoreUpdate() { const storeState = store.getState(); const update = {}; this.props.watchInStore.forEach(key => { if (storeState[key] !== this.state[key]) { update[key] = storeState[key]; } }); if (Object.keys(update).length) { this.setState({ ...this.state, ...update }); } } render() { const props = { ...this.props }; delete props.children; return _react.default.cloneElement(this.props.children, { ...props, ...this.state }); } }
JavaScript
class Slide extends React.Component { /** * Initialize the component. */ constructor (props) { super(props); this.state = { animationPlayState: 'paused' }; this.onLoad = this.onLoad.bind(this); this.onEnd = this.onEnd.bind(this); } /** * Load the slide's image and wait for it to finish loading. */ componentDidMount () { const image = new Image(); image.addEventListener('load', this.onLoad); image.src = this.props.image.filename; } /** * Start the slide animation and set up a removal timer. */ onLoad () { this.setState({ animationPlayState: 'running' }); setTimeout(this.onEnd, 10000); } /** * Remove the slide. */ onEnd () { this.props.removeSlide(this.props.index); } /** * Render the slide. */ render () { const style = { backgroundImage: 'url('+ this.props.image.filename +')', backgroundPosition: this.props.image.position, animationPlayState: this.state.animationPlayState, animationName: 'animation-'+ Math.ceil(Math.random() * 4) }; return( <div className="slide" style={style}/> ); } }
JavaScript
class List extends Component { constructor(props) { super(props); this.state = { page: 1, size : 0, total_items: 0, items: [], loading: false, hasErrors: false, }; } componentDidMount() { const params = queryString.parse(this.props.location.search); const currentPage = params.page || 1; PostsService.getAll(currentPage).then((data) => { this.setState({ total_items: data.total_items, size: data.size, items: data.items, loading: false, hasErrors: false, }) }).catch((error) => { console.error(error); this.setState({ total_items: 0, items: [], loading: false, hasErrors: true, }) }); this.setState({ total_items: 0, items: [], loading: true, hasErrors: false, }) } render() { const { page, size, hasErrors, loading, total_items, items, } = this.state; const hasNextPage = ((size * (page - 1)) + items.length) < total_items; return ( <div className="page"> <Jumbotron className="page posts list"> <h1 className="display-4">Welcome</h1> <p>Learn more <a href="/about">about this project</a>.</p> </Jumbotron> {hasErrors && (<span>oops an error occurred...</span>)} {loading && (<span>loading...</span>)} {!loading && !hasErrors && items.length === 0 && (<span>No posts exists</span>)} {!loading && !hasErrors && items.length > 0 && items.map((item, index) => ( <article key={index}> <h3>{item.title}</h3> <p>{item.text}</p> <p><Link to={POST_URLS.READ.replace('{id}',item.id)}>read more...</Link></p> </article> ))} {!loading && !hasErrors && hasNextPage && ( <p><Link to={`${POST_URLS.LIST}/?page=${page + 1}`}>next page</Link></p> )} </div> ); } }
JavaScript
class CrashDeleteCounter { /** * Create a CrashDeleteCounter. * @property {string} [appId] * @property {string} [crashGroupId] * @property {string} [crashId] * @property {number} [crashesDeleted] * @property {number} [attachmentsDeleted] * @property {number} [blobsSucceeded] * @property {number} [blobsFailed] */ constructor() { } /** * Defines the metadata of CrashDeleteCounter * * @returns {object} metadata of CrashDeleteCounter * */ mapper() { return { required: false, serializedName: 'CrashDeleteCounter', type: { name: 'Composite', className: 'CrashDeleteCounter', modelProperties: { appId: { required: false, serializedName: 'app_id', type: { name: 'String' } }, crashGroupId: { required: false, serializedName: 'crash_group_id', type: { name: 'String' } }, crashId: { required: false, serializedName: 'crash_id', type: { name: 'String' } }, crashesDeleted: { required: false, serializedName: 'crashes_deleted', type: { name: 'Number' } }, attachmentsDeleted: { required: false, serializedName: 'attachments_deleted', type: { name: 'Number' } }, blobsSucceeded: { required: false, serializedName: 'blobs_succeeded', type: { name: 'Number' } }, blobsFailed: { required: false, serializedName: 'blobs_failed', type: { name: 'Number' } } } } }; } }
JavaScript
class HongKongDisneyland extends DisneyBase { /** * Create a new HongKongDisneyland object */ constructor(options = {}) { options.name = options.name || "Hong Kong Disneyland"; options.timezone = options.timezone || "Asia/Hong_Kong"; // set park's location as it's entrance options.latitude = options.latitude || 22.3132; options.longitude = options.longitude || 114.0445; // Disney API configuration for Shanghai Magic Kingdom options.resort_id = options.resort_id || "hkdl"; options.park_id = options.park_id || "desHongKongDisneyland"; options.park_region = options.park_region || "INTL"; // inherit from base class super(options); } // I've never witnessed the facilities URL actually work in the live app, so disable it GetFacilitiesData() { return Promise.resolve({}); } }
JavaScript
class Background { // static constants static CONSTANTS = { EVENTS: { GALLERY: { SET: 'gallery-set', RESET: 'gallery-reset', }, OPTIONS: { SET: 'options-set', RESET: 'options-reset', }, }, // identifies listener target for message TARGET: { B: 'background', C: 'content', P: 'popup', }, ACTION: { GET: 'getGalleries', NEW: 'createGallery', DEL: 'deleteGallery', DIR: 'getContent', ADD: 'addContent', REM: 'removeContent', IMP: 'importContent', }, RESPONSE: { GET: 'getGalleriesResponse', NEW: 'createGalleryResponse', DEL: 'deleteGalleryResponse', DIR: 'getContentResponse', ADD: 'addContentResponse', REM: 'removeContentResponse', IMP: 'importContentResponse', ERROR: 'Error', }, // determines which environment extension is running by reading URL from config options ENV: { PROD: ['stock.adobe', 'contributor.stock.adobe'], STAGE: ['primary.stock.stage.adobe', 'staging1.contributors.adobestock', 'sandbox.stock.stage.adobe'], DEV: ['adobestock.dev', 'contributors.dev'], }, // key values for local storage DATA: { /** * The response models map generic HTTP requests to specific JSON objects from Stock * BASE: JSON root element to be parsed * COUNT: Name of JSON element containing number of elements * MAP: Specific elements to retrieve from each JSON array item * LIMIT: Max number of results to fetch with each request */ getGalleriesResponse: { BASE: 'galleries', COUNT: 'nb_results', MAP: [ 'name', 'nb_media', 'id', ], LIMIT: 100, // api request limit }, getContentResponse: { BASE: 'files', COUNT: 'nb_results', MAP: [ 'id', 'title', 'width', 'height', 'nb_downloads', 'thumbnail_url', 'href', ], LIMIT: 100, // api request limit }, importContentResponse: { BASE: 'files', COUNT: 'nb_results', MAP: ['id'], LIMIT: 100, // api request limit }, TOKEN: 'access_token', GALLERY: 'selectedGallery', URL: 'endpoint', API_KEY: 'apiKey', ENV: 'environment', POPUP: 'helper', STOCK_TAB: 'activeTab', }, ERROR_CODES: { TOKEN_PROBLEM: 999, }, } // stores data in local storage static store(obj, cb = null) { if (chrome.storage) { chrome.storage.sync.set(obj, cb || (() => { const key = Object.keys(obj)[0]; chrome.storage.sync.get(key, (item) => { console.log(`Stored ${key}:`, item[key]); }); })); } } // gets data and returns promise for chaining static retrieve(key) { return new Promise((resolve, reject) => { chrome.storage.sync.get(key, (item) => { if (chrome.runtime.lastError) { const msg = chrome.runtime.lastError.message; console.error(msg); reject(msg); } else { resolve(item[key]); } }); }); } // clears all storage -- should only be run when extension is initialized or logout occurs static emptyStorage() { chrome.storage.sync.clear(); } // broadcasts messages to chrome runtime static notify(msg) { const { STOCK_TAB, POPUP } = Background.CONSTANTS.DATA; const { TARGET } = Background.CONSTANTS; // is message for content page or popup? const destination = (msg && msg.target && msg.target === TARGET.P) ? POPUP : STOCK_TAB; Background.retrieve(destination).then((t) => { const activeTab = t; if (activeTab) { chrome.tabs.query({ active: true, currentWindow: true }, () => { chrome.tabs.sendMessage(activeTab.id, msg); }); } else console.error(`Target tab not defined yet for: ${JSON.stringify(msg)}`); }); } // get runtime environment static getEnvironment(url) { const re = /(https?:\/\/)(.*)\.(com|loc)/; let env; const match = (re.exec(url) && re.exec(url)[2]) ? re.exec(url)[2] : null; if (match) { Object.entries(Background.CONSTANTS.ENV).forEach(([key, value]) => { if (value.includes(match)) { env = key; } }); } return env || 'PROD'; } // sets url and api key locally static setConfigVars(data, env) { // eslint-disable-next-line no-undef const svc = stock; const K = Background.CONSTANTS; svc.CFG.URL[env] = data[K.DATA.URL]; svc.CFG.API_KEY[env] = data[K.DATA.API_KEY]; } // makes service call (services located in services.mjs) static async callStockService(method, input, pageModel) { // eslint-disable-next-line no-undef const svc = stock; const { retrieve, CONSTANTS: K } = Background; const env = retrieve(K.DATA.ENV); const token = retrieve(K.DATA.TOKEN); const args = await Promise.all([ env, token, ]).then(([e, t]) => { // if environment is undefined, use PROD const environment = (!e) ? 'PROD' : e; if (!t) { // TODO: Fix response and fix issue where opening Stock site in new tab breaks plugin throw svc.http.parseErrors({ code: K.ERROR_CODES.TOKEN_PROBLEM }); } return [environment, t]; }).catch((e) => { console.error(e); }); // append any incoming parameters args.push(input); args.push(pageModel); // calls {method} from services try { const response = await svc[method].apply(null, args); console.log(response); return response; } catch (e) { // throw original error message throw (e.message || e); } } }
JavaScript
class Log { constructor(logType, continuous, details) { this.type = logType; this.continuous = continuous; this.details = details; } /** * Method closes a continue log * @method close * @memberof module:API.cvat.classes.Log * @readonly * @instance * @async * @throws {module:API.cvat.exceptions.PluginError} */ async close() { const result = await PluginRegistry .apiWrapper.call(this, Log.prototype.close); return result; } }
JavaScript
class PieceAnimation extends Animation { /** * Piece animation constructors * * @param {Object} scene The active scene * @param {vec3} stackPos Start/Endpoint for the animated piece. Corresponds to its position in the stack * @param {vec3} cellPos Start/Endpoint for the animated piece. Corresponds to its position on the board. * @param {String} type Determins whether the piece is being added to be board 'add' or removed from it by reset 'remove' or capture 'capture' */ constructor(scene, stackPos, cellPos, type) { super(scene); this.type = type; var deltaVec = vec3.create(); vec3.subtract(deltaVec, stackPos, cellPos); var h = deltaVec[1]; deltaVec[1] = 0; var d = vec3.length(deltaVec); var smallR = (d + h - Math.sqrt(2) * h) / 2; var bigR = smallR + Math.sqrt(2) * h; var spanRatio = 3 * smallR / bigR; vec3.normalize(deltaVec, deltaVec); var rotAxis = vec3.fromValues(deltaVec[2], 0, -deltaVec[0]); var smallCenter = vec3.create(); vec3.scale(smallCenter, deltaVec, -smallR); vec3.add(smallCenter, stackPos, smallCenter); var bigCenter = vec3.create(); vec3.scale(bigCenter, deltaVec, bigR); vec3.add(bigCenter, cellPos, bigCenter); this.currAnimation = 'first'; switch(type) { case 'add': this.firstAnimation = new CircularAnimation(scene, 300 * spanRatio, smallCenter, smallR, 180, -135, rotAxis); this.secondAnimation = new CircularAnimation(scene, 300, bigCenter, bigR, 45, -45, rotAxis); break; case 'remove': case 'capture': this.firstAnimation = new CircularAnimation(scene, 300, bigCenter, bigR, 0, 45, rotAxis); this.secondAnimation = new CircularAnimation(scene, 300 * spanRatio, smallCenter, smallR, 45, 135, rotAxis); break; } } /** * Updates the animation's transformation matrix. * * @param {number} deltaTime Time elapsed since last update in miliseconds * * @returns {number} Returns 0 unless the end of the animation is reach. In that case, it returns the reminder of the available deltaTime. * * @override Animation.update() */ update(deltaTime) { var remainingDelta = this.firstAnimation.update(deltaTime); if (remainingDelta > 0) { this.currAnimation = 'second'; remainingDelta = this.secondAnimation.update(remainingDelta); } return remainingDelta; } /** * Applies the current transformation matrix to the scene. * * @override Animation.apply() */ apply() { if (this.currAnimation == 'first') this.firstAnimation.apply(); else this.secondAnimation.apply(); } }
JavaScript
class clrlyFast{ static get _clearlyFast(){ return this.__clearlyFast; } static set _clearlyFast(clearlyFast){ this.__clearlyFast = clearlyFast; } /** * Initialize the tool */ static init(){ this._clearlyFast = clrly.new("clearlyFastElement") clrly.style(` clearlyFastElement{ display: none; } `); } /** * The clearlyFastElement where all the images are loaded */ static get element(){ return this._clearlyFast; } /** * Loads a new image * @param {*} src src of the image * @returns src of the image */ static image(src){ var img = clrly.new("img", {parent: this.element, src: src}); return img.src; } }
JavaScript
class TransactionStateManager extends EventEmitter { constructor({ initState, txHistoryLimit, getNetwork, getCurrentChainId }) { super(); this.store = new ObservableStore({ transactions: {}, ...initState, }); this.txHistoryLimit = txHistoryLimit; this.getNetwork = getNetwork; this.getCurrentChainId = getCurrentChainId; } /** * Generates a TransactionMeta object consisting of the fields required for * use throughout the extension. The argument here will override everything * in the resulting transaction meta. * * TODO: Don't overwrite everything? * * @param {Partial<TransactionMeta>} opts - the object to use when * overwriting default keys of the TransactionMeta * @returns {TransactionMeta} the default txMeta object */ generateTxMeta(opts = {}) { const netId = this.getNetwork(); const chainId = this.getCurrentChainId(); if (netId === 'loading') { throw new Error('MetaMask is having trouble connecting to the network'); } let dappSuggestedGasFees = null; // If we are dealing with a transaction suggested by a dapp and not // an internally created metamask transaction, we need to keep record of // the originally submitted gasParams. if ( opts.txParams && typeof opts.origin === 'string' && opts.origin !== 'metamask' ) { if (typeof opts.txParams.gasPrice !== 'undefined') { dappSuggestedGasFees = { gasPrice: opts.txParams.gasPrice, }; } else if ( typeof opts.txParams.maxFeePerGas !== 'undefined' || typeof opts.txParams.maxPriorityFeePerGas !== 'undefined' ) { dappSuggestedGasFees = { maxPriorityFeePerGas: opts.txParams.maxPriorityFeePerGas, maxFeePerGas: opts.txParams.maxFeePerGas, }; } if (typeof opts.txParams.gas !== 'undefined') { dappSuggestedGasFees = { ...dappSuggestedGasFees, gas: opts.txParams.gas, }; } } return { id: createId(), time: new Date().getTime(), status: TRANSACTION_STATUSES.UNAPPROVED, metamaskNetworkId: netId, chainId, loadingDefaults: true, dappSuggestedGasFees, ...opts, }; } /** * Get an object containing all unapproved transactions for the current * network. This is the only transaction fetching method that returns an * object, so it doesn't use getTransactions like everything else. * * @returns {Record<string, TransactionMeta>} Unapproved transactions keyed * by id */ getUnapprovedTxList() { const chainId = this.getCurrentChainId(); const network = this.getNetwork(); return pickBy( this.store.getState().transactions, (transaction) => transaction.status === TRANSACTION_STATUSES.UNAPPROVED && transactionMatchesNetwork(transaction, chainId, network), ); } /** * Get all approved transactions for the current network. If an address is * provided, the list will be further refined to only those transactions * originating from the supplied address. * * @param {string} [address] - hex prefixed address to find transactions for. * @returns {TransactionMeta[]} the filtered list of transactions */ getApprovedTransactions(address) { const searchCriteria = { status: TRANSACTION_STATUSES.APPROVED }; if (address) { searchCriteria.from = address; } return this.getTransactions({ searchCriteria }); } /** * Get all pending transactions for the current network. If an address is * provided, the list will be further refined to only those transactions * originating from the supplied address. * * @param {string} [address] - hex prefixed address to find transactions for. * @returns {TransactionMeta[]} the filtered list of transactions */ getPendingTransactions(address) { const searchCriteria = { status: TRANSACTION_STATUSES.SUBMITTED }; if (address) { searchCriteria.from = address; } return this.getTransactions({ searchCriteria }); } /** * Get all confirmed transactions for the current network. If an address is * provided, the list will be further refined to only those transactions * originating from the supplied address. * * @param {string} [address] - hex prefixed address to find transactions for. * @returns {TransactionMeta[]} the filtered list of transactions */ getConfirmedTransactions(address) { const searchCriteria = { status: TRANSACTION_STATUSES.CONFIRMED }; if (address) { searchCriteria.from = address; } return this.getTransactions({ searchCriteria }); } /** * Adds the txMeta to the list of transactions in the store. * if the list is over txHistoryLimit it will remove a transaction that * is in its final state. * it will also add the key `history` to the txMeta with the snap shot of * the original object * @param {TransactionMeta} txMeta - The TransactionMeta object to add. * @returns {TransactionMeta} The same TransactionMeta, but with validated * txParams and transaction history. */ addTransaction(txMeta) { // normalize and validate txParams if present if (txMeta.txParams) { txMeta.txParams = normalizeAndValidateTxParams(txMeta.txParams, false); } this.once(`${txMeta.id}:signed`, () => { this.removeAllListeners(`${txMeta.id}:rejected`); }); this.once(`${txMeta.id}:rejected`, () => { this.removeAllListeners(`${txMeta.id}:signed`); }); // initialize history txMeta.history = []; // capture initial snapshot of txMeta for history const snapshot = snapshotFromTxMeta(txMeta); txMeta.history.push(snapshot); const transactions = this.getTransactions({ filterToCurrentNetwork: false, }); const { txHistoryLimit } = this; // checks if the length of the tx history is longer then desired persistence // limit and then if it is removes the oldest confirmed or rejected tx. // Pending or unapproved transactions will not be removed by this // operation. For safety of presenting a fully functional transaction UI // representation, this function will not break apart transactions with the // same nonce, per network. Not accounting for transactions of the same // nonce and network combo can result in confusing or broken experiences // in the UI. // // TODO: we are already limiting what we send to the UI, and in the future // we will send UI only collected groups of transactions *per page* so at // some point in the future, this persistence limit can be adjusted. When // we do that I think we should figure out a better storage solution for // transaction history entries. const nonceNetworkSet = new Set(); const txsToDelete = transactions .reverse() .filter((tx) => { const { nonce } = tx.txParams; const { chainId, metamaskNetworkId, status } = tx; const key = `${nonce}-${chainId ?? metamaskNetworkId}`; if (nonceNetworkSet.has(key)) { return false; } else if ( nonceNetworkSet.size < txHistoryLimit - 1 || getFinalStates().includes(status) === false ) { nonceNetworkSet.add(key); return false; } return true; }) .map((tx) => tx.id); this._deleteTransactions(txsToDelete); this._addTransactionsToState([txMeta]); return txMeta; } /** * @param {number} txId * @returns {TransactionMeta} the txMeta who matches the given id if none found * for the network returns undefined */ getTransaction(txId) { const { transactions } = this.store.getState(); return transactions[txId]; } /** * updates the txMeta in the list and adds a history entry * @param {Object} txMeta - the txMeta to update * @param {string} [note] - a note about the update for history */ updateTransaction(txMeta, note) { // normalize and validate txParams if present if (txMeta.txParams) { txMeta.txParams = normalizeAndValidateTxParams(txMeta.txParams, false); } // create txMeta snapshot for history const currentState = snapshotFromTxMeta(txMeta); // recover previous tx state obj const previousState = replayHistory(txMeta.history); // generate history entry and add to history const entry = generateHistoryEntry(previousState, currentState, note); if (entry.length) { txMeta.history.push(entry); } // commit txMeta to state const txId = txMeta.id; this.store.updateState({ transactions: { ...this.store.getState().transactions, [txId]: txMeta, }, }); } /** * SearchCriteria can search in any key in TxParams or the base * TransactionMeta. This type represents any key on either of those two * types. * @typedef {TxParams[keyof TxParams] | TransactionMeta[keyof TransactionMeta]} SearchableKeys */ /** * Predicates can either be strict values, which is shorthand for using * strict equality, or a method that receives he value of the specified key * and returns a boolean. * @typedef {(v: unknown) => boolean | unknown} FilterPredicate */ /** * Retrieve a list of transactions from state. By default this will return * the full list of Transactions for the currently selected chain/network. * Additional options can be provided to change what is included in the final * list. * * @param opts - options to change filter behavior * @param {Record<SearchableKeys, FilterPredicate>} [opts.searchCriteria] - * an object with keys that match keys in TransactionMeta or TxParams, and * values that are predicates. Predicates can either be strict values, * which is shorthand for using strict equality, or a method that receives * the value of the specified key and returns a boolean. The transaction * list will be filtered to only those items that the predicate returns * truthy for. **HINT**: `err: undefined` is like looking for a tx with no * err. so you can also search txs that don't have something as well by * setting the value as undefined. * @param {TransactionMeta[]} [opts.initialList] - If provided the filtering * will occur on the provided list. By default this will be the full list * from state sorted by time ASC. * @param {boolean} [opts.filterToCurrentNetwork=true] - Filter transaction * list to only those that occurred on the current chain or network. * Defaults to true. * @param {number} [opts.limit] - limit the number of transactions returned * to N unique nonces. * @returns {TransactionMeta[]} The TransactionMeta objects that all provided * predicates return truthy for. */ getTransactions({ searchCriteria = {}, initialList, filterToCurrentNetwork = true, limit, } = {}) { const chainId = this.getCurrentChainId(); const network = this.getNetwork(); // searchCriteria is an object that might have values that aren't predicate // methods. When providing any other value type (string, number, etc), we // consider this shorthand for "check the value at key for strict equality // with the provided value". To conform this object to be only methods, we // mapValues (lodash) such that every value on the object is a method that // returns a boolean. const predicateMethods = mapValues(searchCriteria, (predicate) => { return typeof predicate === 'function' ? predicate : (v) => v === predicate; }); // If an initial list is provided we need to change it back into an object // first, so that it matches the shape of our state. This is done by the // lodash keyBy method. This is the edge case for this method, typically // initialList will be undefined. const transactionsToFilter = initialList ? keyBy(initialList, 'id') : this.store.getState().transactions; // Combine sortBy and pickBy to transform our state object into an array of // matching transactions that are sorted by time. const filteredTransactions = sortBy( pickBy(transactionsToFilter, (transaction) => { // default matchesCriteria to the value of transactionMatchesNetwork // when filterToCurrentNetwork is true. if ( filterToCurrentNetwork && transactionMatchesNetwork(transaction, chainId, network) === false ) { return false; } // iterate over the predicateMethods keys to check if the transaction // matches the searchCriteria for (const [key, predicate] of Object.entries(predicateMethods)) { // We return false early as soon as we know that one of the specified // search criteria do not match the transaction. This prevents // needlessly checking all criteria when we already know the criteria // are not fully satisfied. We check both txParams and the base // object as predicate keys can be either. if (key in transaction.txParams) { if (predicate(transaction.txParams[key]) === false) { return false; } } else if (predicate(transaction[key]) === false) { return false; } } return true; }), 'time', ); if (limit !== undefined) { // We need to have all transactions of a given nonce in order to display // necessary details in the UI. We use the size of this set to determine // whether we have reached the limit provided, thus ensuring that all // transactions of nonces we include will be sent to the UI. const nonces = new Set(); const txs = []; // By default, the transaction list we filter from is sorted by time ASC. // To ensure that filtered results prefers the newest transactions we // iterate from right to left, inserting transactions into front of a new // array. The original order is preserved, but we ensure that newest txs // are preferred. for (let i = filteredTransactions.length - 1; i > -1; i--) { const txMeta = filteredTransactions[i]; const { nonce } = txMeta.txParams; if (!nonces.has(nonce)) { if (nonces.size < limit) { nonces.add(nonce); } else { continue; } } // Push transaction into the beginning of our array to ensure the // original order is preserved. txs.unshift(txMeta); } return txs; } return filteredTransactions; } /** * Update status of the TransactionMeta with provided id to 'rejected'. * After setting the status, the TransactionMeta is deleted from state. * * TODO: Should we show historically rejected transactions somewhere in the * UI? Seems like it could be valuable for information purposes. Of course * only after limit issues are reduced. * * @param {number} txId - the target TransactionMeta's Id */ setTxStatusRejected(txId) { this._setTransactionStatus(txId, TRANSACTION_STATUSES.REJECTED); this._deleteTransaction(txId); } /** * Update status of the TransactionMeta with provided id to 'unapproved' * * @param {number} txId - the target TransactionMeta's Id */ setTxStatusUnapproved(txId) { this._setTransactionStatus(txId, TRANSACTION_STATUSES.UNAPPROVED); } /** * Update status of the TransactionMeta with provided id to 'approved' * * @param {number} txId - the target TransactionMeta's Id */ setTxStatusApproved(txId) { this._setTransactionStatus(txId, TRANSACTION_STATUSES.APPROVED); } /** * Update status of the TransactionMeta with provided id to 'signed' * * @param {number} txId - the target TransactionMeta's Id */ setTxStatusSigned(txId) { this._setTransactionStatus(txId, TRANSACTION_STATUSES.SIGNED); } /** * Update status of the TransactionMeta with provided id to 'submitted' * and sets the 'submittedTime' property with the current Unix epoch time. * * @param {number} txId - the target TransactionMeta's Id */ setTxStatusSubmitted(txId) { const txMeta = this.getTransaction(txId); txMeta.submittedTime = new Date().getTime(); this.updateTransaction(txMeta, 'txStateManager - add submitted time stamp'); this._setTransactionStatus(txId, TRANSACTION_STATUSES.SUBMITTED); } /** * Update status of the TransactionMeta with provided id to 'confirmed' * * @param {number} txId - the target TransactionMeta's Id */ setTxStatusConfirmed(txId) { this._setTransactionStatus(txId, TRANSACTION_STATUSES.CONFIRMED); } /** * Update status of the TransactionMeta with provided id to 'dropped' * * @param {number} txId - the target TransactionMeta's Id */ setTxStatusDropped(txId) { this._setTransactionStatus(txId, TRANSACTION_STATUSES.DROPPED); } /** * Update status of the TransactionMeta with provided id to 'failed' and put * the error on the TransactionMeta object. * * @param {number} txId - the target TransactionMeta's Id * @param {Error} err - error object */ setTxStatusFailed(txId, err) { const error = err || new Error('Internal metamask failure'); const txMeta = this.getTransaction(txId); txMeta.err = { message: error.message?.toString() || error.toString(), rpc: error.value, stack: error.stack, }; this.updateTransaction( txMeta, 'transactions:tx-state-manager#fail - add error', ); this._setTransactionStatus(txId, TRANSACTION_STATUSES.FAILED); } /** * Removes all transactions for the given address on the current network, * preferring chainId for comparison over networkId. * * @param {string} address - hex string of the from address on the txParams * to remove */ wipeTransactions(address) { // network only tx const { transactions } = this.store.getState(); const network = this.getNetwork(); const chainId = this.getCurrentChainId(); // Update state this.store.updateState({ transactions: omitBy( transactions, (transaction) => transaction.txParams.from === address && transactionMatchesNetwork(transaction, chainId, network), ), }); } /** * Filters out the unapproved transactions from state */ clearUnapprovedTxs() { this.store.updateState({ transactions: omitBy( this.store.getState().transactions, (transaction) => transaction.status === TRANSACTION_STATUSES.UNAPPROVED, ), }); } // // PRIVATE METHODS // /** * Updates a transaction's status in state, and then emits events that are * subscribed to elsewhere. See below for best guesses on where and how these * events are received. * @param {number} txId - the TransactionMeta Id * @param {TransactionStatusString} status - the status to set on the * TransactionMeta * @emits txMeta.id:txMeta.status - every time a transaction's status changes * we emit the change passing along the id. This does not appear to be used * outside of this file, which only listens to this to unsubscribe listeners * of :rejected and :signed statuses when the inverse status changes. Likely * safe to drop. * @emits tx:status-update - every time a transaction's status changes we * emit this event and pass txId and status. This event is subscribed to in * the TransactionController and re-broadcast by the TransactionController. * It is used internally within the TransactionController to try and update * pending transactions on each new block (from blockTracker). It's also * subscribed to in metamask-controller to display a browser notification on * confirmed or failed transactions. * @emits txMeta.id:finished - When a transaction moves to a finished state * this event is emitted, which is used in the TransactionController to pass * along details of the transaction to the dapp that suggested them. This * pattern is replicated across all of the message managers and can likely * be supplemented or replaced by the ApprovalController. * @emits updateBadge - When the number of transactions changes in state, * the badge in the browser extension bar should be updated to reflect the * number of pending transactions. This particular emit doesn't appear to * bubble up anywhere that is actually used. TransactionController emits * this *anytime the state changes*, so this is probably superfluous. */ _setTransactionStatus(txId, status) { const txMeta = this.getTransaction(txId); if (!txMeta) { return; } txMeta.status = status; try { this.updateTransaction( txMeta, `txStateManager: setting status to ${status}`, ); this.emit(`${txMeta.id}:${status}`, txId); this.emit(`tx:status-update`, txId, status); if ( [ TRANSACTION_STATUSES.SUBMITTED, TRANSACTION_STATUSES.REJECTED, TRANSACTION_STATUSES.FAILED, ].includes(status) ) { this.emit(`${txMeta.id}:finished`, txMeta); } this.emit(METAMASK_CONTROLLER_EVENTS.UPDATE_BADGE); } catch (error) { log.error(error); } } /** * Adds one or more transactions into state. This is not intended for * external use. * * @private * @param {TransactionMeta[]} transactions - the list of transactions to save */ _addTransactionsToState(transactions) { this.store.updateState({ transactions: transactions.reduce((result, newTx) => { result[newTx.id] = newTx; return result; }, this.store.getState().transactions), }); } /** * removes one transaction from state. This is not intended for external use. * * @private * @param {number} targetTransactionId - the transaction to delete */ _deleteTransaction(targetTransactionId) { const { transactions } = this.store.getState(); delete transactions[targetTransactionId]; this.store.updateState({ transactions, }); } /** * removes multiple transaction from state. This is not intended for external use. * * @private * @param {number[]} targetTransactionIds - the transactions to delete */ _deleteTransactions(targetTransactionIds) { const { transactions } = this.store.getState(); targetTransactionIds.forEach((transactionId) => { delete transactions[transactionId]; }); this.store.updateState({ transactions, }); } }
JavaScript
class LogCatMonitor { constructor(deviceId, userProvidedLogCatArguments, adbHelper) { this._deviceId = deviceId; this._userProvidedLogCatArguments = userProvidedLogCatArguments; this._logger = OutputChannelLogger_1.OutputChannelLogger.getChannel(`LogCat - ${deviceId}`); this.adbHelper = adbHelper; } start() { const logCatArguments = this.getLogCatArguments(); const adbParameters = ["-s", this._deviceId, "logcat"].concat(logCatArguments); this._logger.debug(`Monitoring LogCat for device ${this._deviceId} with arguments: ${logCatArguments}`); this._logCatSpawn = this.adbHelper.startLogCat(adbParameters); /* LogCat has a buffer and prints old messages when first called. To ignore them, we won't print messages for the first 0.5 seconds */ const filter = new executionsLimiter_1.ExecutionsFilterBeforeTimestamp(/*delayInSeconds*/ 0.5); this._logCatSpawn.stderr.on("data", (data) => { filter.execute(() => this._logger.info(data.toString())); }); this._logCatSpawn.stdout.on("data", (data) => { filter.execute(() => this._logger.info(data.toString())); }); return this._logCatSpawn.outcome.then(() => this._logger.info(localize(0, null)), (reason) => { if (!this._logCatSpawn) { // We stopped log cat ourselves this._logger.info(localize(1, null)); return Q.resolve(void 0); } else { return Q.reject(reason); // Unkown error. Pass it up the promise chain } }).finally(() => { this._logCatSpawn = null; }); } dispose() { if (this._logCatSpawn) { const logCatSpawn = this._logCatSpawn; this._logCatSpawn = null; logCatSpawn.spawnedProcess.kill(); } OutputChannelLogger_1.OutputChannelLogger.disposeChannel(this._logger.channelName); } getLogCatArguments() { // We use the setting if it's defined, or the defaults if it's not return this.isNullOrUndefined(this._userProvidedLogCatArguments) // "" is a valid value, so we can't just if () this ? LogCatMonitor.DEFAULT_PARAMETERS : ("" + this._userProvidedLogCatArguments).split(" "); // Parse string and split into string[] } isNullOrUndefined(value) { return typeof value === "undefined" || value === null; } }
JavaScript
class MudResizeListener { constructor(id) { this.logger = function (message) { }; this.options = {}; this.throttleResizeHandlerId = -1; this.dotnet = undefined; this.breakpoint = -1; this.id = id; } listenForResize(dotnetRef, options) { if (this.dotnet) { this.options = options; return; } //this.logger("[MudBlazor] listenForResize:", { options, dotnetRef }); this.options = options; this.dotnet = dotnetRef; this.logger = options.enableLogging ? console.log : (message) => { }; this.logger(`[MudBlazor] Reporting resize events at rate of: ${(this.options || {}).reportRate || 100}ms`); window.addEventListener("resize", this.throttleResizeHandler.bind(this), false); if (!this.options.suppressInitEvent) { this.resizeHandler(); } this.breakpoint = this.getBreakpoint(window.innerWidth); } throttleResizeHandler() { clearTimeout(this.throttleResizeHandlerId); //console.log("[MudBlazor] throttleResizeHandler ", {options:this.options}); this.throttleResizeHandlerId = window.setTimeout(this.resizeHandler.bind(this), ((this.options || {}).reportRate || 100)); } resizeHandler() { if (this.options.notifyOnBreakpointOnly) { let bp = this.getBreakpoint(window.innerWidth); if (bp == this.breakpoint) { return; } this.breakpoint = bp; } try { //console.log("[MudBlazor] RaiseOnResized invoked"); if (this.id) { this.dotnet.invokeMethodAsync('RaiseOnResized', { height: window.innerHeight, width: window.innerWidth }, this.getBreakpoint(window.innerWidth), this.id); } else { this.dotnet.invokeMethodAsync('RaiseOnResized', { height: window.innerHeight, width: window.innerWidth }, this.getBreakpoint(window.innerWidth)); } //this.logger("[MudBlazor] RaiseOnResized invoked"); } catch (error) { this.logger("[MudBlazor] Error in resizeHandler:", { error }); } } cancelListener() { this.dotnet = undefined; //console.log("[MudBlazor] cancelListener"); window.removeEventListener("resize", this.throttleResizeHandler); } matchMedia(query) { let m = window.matchMedia(query).matches; //this.logger(`[MudBlazor] matchMedia "${query}": ${m}`); return m; } getBrowserWindowSize() { //this.logger("[MudBlazor] getBrowserWindowSize"); return { height: window.innerHeight, width: window.innerWidth }; } getBreakpoint(width) { if (width >= this.options.breakpointDefinitions["Xl"]) return 4; else if (width >= this.options.breakpointDefinitions["Lg"]) return 3; else if (width >= this.options.breakpointDefinitions["Md"]) return 2; else if (width >= this.options.breakpointDefinitions["Sm"]) return 1; else //Xs return 0; } }
JavaScript
class UnitModifier { /** * Sort in apply order. * * @param {Array.<unitModifier>} unitModifierArray * @returns {Array.<unitModifier>} ordered (original list also mutated in place) */ static sortPriorityOrder(unitModifierArray) { unitModifierArray.sort((a, b) => { return ( PRIORITY[a._modifier.priority] - PRIORITY[b._modifier.priority] ); }); return unitModifierArray; } /** * Find player's unit modifiers. * * @param {number} playerSlot * @param {string} withOwner - self, opponent, any * @returns {Array.<unitModifier>} modifiers */ static getPlayerUnitModifiers(playerSlot, withOwner) { assert(typeof playerSlot === "number"); assert(typeof withOwner === "string"); assert(OWNER[withOwner]); _maybeInit(); const unitModifiers = []; for (const obj of world.getAllObjects()) { const objNsid = ObjectNamespace.getNsid(obj); const unitModifier = _triggerNsidToUnitModifier[objNsid]; if (!unitModifier) { continue; } if (obj.getContainer()) { continue; // inside a container } if (obj instanceof Card && !obj.isFaceUp()) { continue; // face down card } // Enfoce modifier type (self, opponent, any). if ( unitModifier.raw !== "any" && unitModifier.raw.owner !== withOwner ) { continue; // wrong owner } // If an object has an owner, use it before trying to guess owner. const ownerSlot = obj.getOwningPlayerSlot(); if (ownerSlot >= 0 && ownerSlot !== playerSlot) { continue; // explit different owner } // TODO XXX CHECK IF IN PLAYER AREA // TODO XXX MAYBE USE obj.getOwningPlayerSlot IF SET? const insidePlayerArea = true; // TODO XXX if (!insidePlayerArea) { continue; } // Found a unit modifier! Add it to the list. if (!unitModifiers.includes(unitModifier)) { unitModifiers.push(unitModifier); } } return unitModifiers; } /** * Get faction abilility. * * @param {string} factionAbility * @returns {unitModifier} */ static getFactionAbilityUnitModifier(factionAbility) { assert(typeof factionAbility === "string"); _maybeInit(); return _factionAbilityToUnitModifier[factionAbility]; } /** * Get faction abililities. * * @param {string} unitAbility * @returns {unitModifier} */ static getUnitAbilityUnitModifier(unitAbility) { assert(typeof factionAbility === "string"); _maybeInit(); return _unitAbilityToUnitModifier[unitAbility]; } // ------------------------------------------------------------------------ /** * Constructor. * * @param {object} modifier - UnitModifiersSchema compliant object */ constructor(modifier) { assert(typeof modifier === "object"); assert(UnitModifierSchema.validate(modifier)); this._modifier = modifier; } /** * Localized modifier name. * * @returns {string} */ get name() { return locale(this._modifier.localeName); } /** * Localized modifier description. * * @returns {string} */ get desc() { return locale(this._modifier.localeDescription); } /** * Get the underlying object. * * @returns {object} */ get raw() { return this._modifier; } /** * Apply unit modifier. * * @param {object} unitToUnitAttrs - mutated in place * @param {object} auxData - table of misc things modifiers might use */ apply(unitAttrsSet, auxData) { if (this._modifier.applyEach) { for (const unitAttrs of unitAttrsSet.values()) { this._modifier.applyEach(unitAttrs, auxData); } } if (this._modifier.applyAll) { this._modifier.applyAll(unitAttrsSet, auxData); } // Paranoid verify modifier did not break it. for (const unitAttrs of unitAttrsSet.values()) { assert(unitAttrs.validate()); } } }
JavaScript
class CausalNetMemory extends Tensor{ constructor(){ super(); this.Memory = memDownCache; this.R = causalNetCore.CoreFunction; } set Memory(memory){ //TODO: type checking this.memory = memory; } get Memory(){ if(!this.memory){ throw Error(`memory is not set`); } return this.memory; } get MemorySize(){ return this.memorySize; } set MemorySize(size){ this.memorySize = size; } get NumSlots(){ return this.memorySize[0]; } get SlotSize(){ return this.memorySize[1]; } async initMemory(size, initTensor=null){ this.MemorySize = size; const R = this.R; if(!initTensor){ initTensor = await this.T.randomNormal(size); } let slotIdxs = R.range(0, this.NumSlots); return this.writeSlots(slotIdxs, initTensor); } async normalize(){ const Memory = this.Memory, NumSlots = this.NumSlots, R = this.R; let memValues = await Memory.recall(R.range(0, NumSlots)); let allTs = this.T.tensor(memValues); let meanTs = allTs.mean(1, true); let stdTs = allTs.sub(meanTs).pow(2).mean(1, true).pow(0.5); return allTs.sub(meanTs).div(stdTs); } async getMatchScore(slotIdxs){ let normTs = await this.normalize(); let cTs = normTs.gather(slotIdxs); let similarityScore = normTs.dot(cTs.transpose()); return similarityScore; } async getTopKSimilar(slotIdxs, k){ let matchScoreTensor = await this.getMatchScore(slotIdxs); const {values, indices} = matchScoreTensor.transpose().topk(k); return indices; } async writeSlots(slotIdxs, memoryTensor){ const R = this.R, SlotSize = this.SlotSize, Memory = this.Memory; let tensorData = await memoryTensor.data(); let values = R.splitEvery(SlotSize, tensorData); for(let idx of R.range(0, slotIdxs.length)){ await Memory.write(slotIdxs[idx], values[idx]); } return memoryTensor; } async readSlots(slotIndexs){ const Memory = this.Memory, T = this.T; let values = []; for(let slotIdx of slotIndexs){ let value = await Memory.read(slotIdx); values.push(value); } return T.variable(T.tensor(values)); } }
JavaScript
class Html extends Component { static propTypes = { assets: PropTypes.object, component: PropTypes.node, isDev: PropTypes.bool, reqPathName: PropTypes.string, }; prepareStore(allStore) { const keyArr = Object.keys(allStore); const output = {}; keyArr.map((key) => { output[key] = toJS(allStore[key]); }); return output; } // isFirstLoad() { // return this.props.reqPathName === '/'; // } render() { const {assets, component, ...allStore} = this.props; const stores = this.prepareStore(allStore); const content = component ? ReactDOM.renderToString(component) : ''; const head = Helmet.rewind(); return ( <html lang="en-us"> <head> {head.base.toComponent()} {head.meta.toComponent()} {head.link.toComponent()} {head.script.toComponent()} <title>数据API平台</title> <link rel="shortcut icon" href="/favicon3.ico"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta httpEquiv="content-type" content="text/html;charset=utf-8"/> {/* styles (will be present only in production with webpack extract text plugin) */} <link href="../vendors/css/font-awesome.css" rel="stylesheet" type="text/css" charSet="UTF-8"/> <link href="../vendors/css/antd.css" rel="stylesheet" type="text/css" charSet="UTF-8"/> <link href="../vendors/css/preload.css" rel="stylesheet" type="text/css" charSet="UTF-8"/> <link href="../vendors/css/highlight.css" rel="stylesheet" type="text/css" charSet="UTF-8"/> { Object.keys(assets.styles).map((style, key) => <link href={assets.styles[style]} key={key} rel="stylesheet" type="text/css" charSet="UTF-8"/> ) } {/* <link href="/vendors/css/antd.css" media="screen, projection" rel="stylesheet" type="text/css" charSet="UTF-8"/> */} {/* (will be present only in development mode) */} {/* outputs a <style/> tag with all bootstrap styles + App.scss + it could be CurrentPage.scss. */} {/* can smoothen the initial style flash (flicker) on page load in development mode. */} {/* ideally one could also include here the style for the current page (Home.scss, About.scss, etc) */} </head> <body> <div id="content" style={{height: '100%'}} dangerouslySetInnerHTML={{__html: content}}/> <script dangerouslySetInnerHTML={{__html: `window.__data=${JSON.stringify(stores)};`}} charSet="UTF-8"/> <script src={assets.javascript['common.js']} charSet="UTF-8"/> <script id="mainJs" src={assets.javascript.main} charSet="UTF-8"/> {/* {this.isFirstLoad() ? '' : <script src="../vendors/js/echarts_v3_3_2.min.js"></script> } {this.isFirstLoad() ? '' : <script src="../vendors/js/map/china.min.js"></script> } */} <script src="../vendors/js/error.js"></script> </body> </html> ); } }
JavaScript
class ChannelData { /** * Constructor to populate channel data sheet in Google Sheets. * * @param {object} params * * @constructor */ constructor(params) { const oThis = this; oThis.channelIds = []; oThis.channelData = {}; oThis.videoData = {}; oThis.finalData = {}; } /** * Main performer for class. * * @returns {Promise<void>} */ async perform() { const oThis = this; await oThis.fetchChannelVideoData(); await oThis.fetchVideoDetails(); await oThis.fetchPixelData(); await oThis.uploadData(); } /** * Fetch channel data and video ids of channel. * * @sets oThis.channelData * * @returns {Promise<void>} */ async fetchChannelVideoData() { const oThis = this; const dbRows = await new ChannelModel() .select(['id', 'name', 'created_at']) .where({ status: channelConstants.invertedStatuses[channelConstants.activeStatus] }) .order_by('id asc') .fire(); if (dbRows.length === 0) { return; } for (let i = 0; i < dbRows.length; i++) { const dbRow = dbRows[i]; const formattedData = new ChannelModel().formatDbData(dbRow); oThis.channelData[formattedData.id] = { id: formattedData.id, name: formattedData.name, createdAt: formattedData.createdAt, totalUsers: 0, totalVideos: 0, totalReplies: 0, totalTransactions: 0, lastVideoTime: null, lastReplyTime: null, lastTransactionTime: null, totalHalfWatchedVideo: 0, totalHalfWatchedReply: 0, lastHalfWatchedDateVideo: null, lastHalfWatchedDateReply: null }; await oThis.fetchChannelVideos(formattedData.id); oThis.channelIds.push(formattedData.id); } const channelStatDbRows = await new ChannelStatModel() .select('*') .where({ channel_id: oThis.channelIds }) .fire(); for (let i = 0; i < channelStatDbRows.length; i++) { const dbRow = channelStatDbRows[i]; const formattedData = new ChannelStatModel().formatDbData(dbRow); oThis.channelData[formattedData.channelId]['totalVideos'] = formattedData.totalVideos; oThis.channelData[formattedData.channelId]['totalUsers'] = formattedData.totalUsers; } } /** * Fetch video details. * * @sets oThis.videoData * * @returns {Promise<void>} */ async fetchVideoDetails() { const oThis = this; const videoIds = Object.keys(oThis.videoData); while (true) { const videoIdBatch = videoIds.splice(0, batchSize); if (videoIdBatch.length === 0) { return; } const dbRows = await new VideoDetailModel() .select(['video_id', 'total_replies', 'total_transactions']) .where({ video_id: videoIdBatch, status: videoDetailConstant.invertedStatuses[videoDetailConstant.activeStatus] }) .fire(); for (let i = 0; i < dbRows.length; i++) { const dbRow = dbRows[i]; const formattedData = new VideoDetailModel().formatDbData(dbRow); oThis.videoData[formattedData.videoId]['totalReplies'] = formattedData.totalReplies; oThis.videoData[formattedData.videoId]['totalTransactions'] = formattedData.totalTransactions; } const contributionDbRows = await new VideoContributorModel() .select('video_id, max(created_at) as lastTransactionTime') .where({ video_id: videoIdBatch }) .group_by('video_id') .fire(); for (let i = 0; i < contributionDbRows.length; i++) { const dbRow = contributionDbRows[i]; oThis.videoData[dbRow.video_id]['lastTransactionTime'] = dbRow.lastTransactionTime; } await oThis.fetchReplyDetails(videoIdBatch); } } /** * Fetch reply details. * * @sets oThis.videoData * * @returns {Promise<void>} */ async fetchReplyDetails(videoIdBatch) { const oThis = this; let offset = 0; while (true) { const replyDbRows = await new ReplyDetailModel() .select('parent_id, entity_id, total_transactions, created_at') .where(['status != ?', replyDetailConstant.invertedStatuses[replyDetailConstant.deletedStatus]]) .where({ parent_id: videoIdBatch }) .order_by('id asc') .limit(batchSize) .offset(offset) .fire(); if (replyDbRows.length === 0) { return; } const replyIdMap = {}, replyVideoIds = []; for (let i = 0; i < replyDbRows.length; i++) { const dbRow = replyDbRows[i]; if ( !oThis.videoData[dbRow.parent_id]['lastReplyTime'] || oThis.videoData[dbRow.parent_id]['lastReplyTime'] < dbRow.created_at ) { oThis.videoData[dbRow.parent_id]['lastReplyTime'] = dbRow.created_at; } oThis.videoData[dbRow.parent_id]['totalTransactions'] += dbRow.total_transactions; replyIdMap[dbRow.entity_id] = dbRow.parent_id; replyVideoIds.push(dbRow.entity_id); } if (replyVideoIds.length > 0) { const contributionReplyDbRows = await new VideoContributorModel() .select('video_id, max(created_at) as lastTransactionTime') .where({ video_id: replyVideoIds }) .group_by('video_id') .fire(); for (let i = 0; i < contributionReplyDbRows.length; i++) { const dbRow = contributionReplyDbRows[i]; const vid = replyIdMap[dbRow.video_id]; if ( !oThis.videoData[vid]['lastTransactionTime'] || oThis.videoData[vid]['lastTransactionTime'] < dbRow.lastTransactionTime ) { oThis.videoData[vid]['lastTransactionTime'] = dbRow.lastTransactionTime; } } } offset += batchSize; } } /** * Fetch channel video ids. * * @sets oThis.videoData * * @returns {Promise<void>} */ async fetchChannelVideos(channelId) { const oThis = this; let offset = 0; while (true) { const dbRows = await new ChannelVideoModel() .select(['channel_id', 'video_id', 'created_at']) .where({ status: channelVideosConstants.invertedStatuses[channelVideosConstants.activeStatus], channel_id: channelId }) .order_by('id asc') .limit(batchSize) .offset(offset) .fire(); if (dbRows.length == 0) { return; } for (let i = 0; i < dbRows.length; i++) { const dbRow = dbRows[i]; const formattedData = new ChannelVideoModel().formatDbData(dbRow); oThis.videoData[formattedData.videoId] = oThis.videoData[formattedData.videoId] || { channelIds: [] }; oThis.videoData[formattedData.videoId]['channelIds'].push(formattedData.channelId); oThis.videoData[formattedData.videoId]['createdAt'] = formattedData.createdAt; } offset = offset + batchSize; } } /** * Fetch all users data. * * @sets oThis.finalData * * @returns {Promise<void>} */ async fetchPixelData() { const oThis = this; const bucket = coreConstants.S3_USER_ASSETS_BUCKET, channelFileKey = coreConstants.CHANNEL_DATA_S3_FILE_PATH, channelCsvPath = coreConstants.CHANNEL_DATA_LOCAL_FILE_PATH; await s3Wrapper.downloadObjectToDisk(bucket, channelFileKey, channelCsvPath); let videoWatchData = await oThis.parseCsvFile(channelCsvPath); oThis.processCsvDataForVideos(videoWatchData); } /** * Process csv data for videos * @return {*} */ processCsvDataForVideos(parsedDataArray) { const oThis = this; if (parsedDataArray.length === 0) { logger.info('===== Pixel data is empty ====='); return; } // Loop over parsed data to update video Data. for (let index = 0; index < parsedDataArray.length; index++) { const parsedDataRow = parsedDataArray[index], entityType = parsedDataRow.e_entity, rowTimestamp = new Date(parsedDataRow.timestamp); if (entityType == 'video') { const videoId = parsedDataRow.video_id; if (Number(videoId) > 0 && CommonValidators.validateNonEmptyObject(oThis.videoData[videoId])) { oThis.videoData[videoId]['totalHalfWatchedVideo'] = +parsedDataRow.total_videos_watched; oThis.videoData[videoId]['lastHalfWatchedDateVideo'] = rowTimestamp; } } else if (entityType == 'reply') { const videoId = parsedDataRow.parent_video_id; if (Number(videoId) > 0 && CommonValidators.validateNonEmptyObject(oThis.videoData[videoId])) { oThis.videoData[videoId]['totalHalfWatchedReply'] = +parsedDataRow.total_videos_watched; oThis.videoData[videoId]['lastHalfWatchedDateReply'] = rowTimestamp; } } else { throw new Error(`Invalid entityType-${entityType}`); } } } /** * Parse CSV file. * * @param csvFilePath * @return {Promise<any>} */ async parseCsvFile(csvFilePath) { const oThis = this; const csvDataArray = []; return new Promise(function(onResolve) { try { // eslint-disable-next-line no-sync if (fs.existsSync(csvFilePath)) { fs.createReadStream(csvFilePath) .pipe(csvParser()) .on('data', function(row) { csvDataArray.push(row); }) .on('end', function() { onResolve(csvDataArray); }); } else { return onResolve(csvDataArray); } } catch (err) { return onResolve(csvDataArray); } }); } /** * Upload data to Google Sheets. * * @returns {Promise<void>} */ async uploadData() { const oThis = this; for (const videoId in oThis.videoData) { const videoDetail = oThis.videoData[videoId]; const channelIds = videoDetail.channelIds; for (let i = 0; i < channelIds.length; i++) { const channelId = channelIds[i]; const channelDetail = oThis.channelData[channelId]; channelDetail.totalReplies = channelDetail.totalReplies + videoDetail.totalReplies; channelDetail.totalTransactions = channelDetail.totalTransactions + videoDetail.totalTransactions; if (!channelDetail.lastVideoTime || channelDetail.lastVideoTime < videoDetail.createdAt) { channelDetail.lastVideoTime = videoDetail.createdAt; } if ( videoDetail.lastReplyTime && (!channelDetail.lastReplyTime || channelDetail.lastReplyTime < videoDetail.lastReplyTime) ) { channelDetail.lastReplyTime = videoDetail.lastReplyTime; } if ( videoDetail.lastTransactionTime && (!channelDetail.lastTransactionTime || channelDetail.lastTransactionTime < videoDetail.lastTransactionTime) ) { channelDetail.lastTransactionTime = videoDetail.lastTransactionTime; } if (videoDetail.totalHalfWatchedVideo) { channelDetail.totalHalfWatchedVideo = channelDetail.totalHalfWatchedVideo + videoDetail.totalHalfWatchedVideo; } if (videoDetail.totalHalfWatchedReply) { channelDetail.totalHalfWatchedReply = channelDetail.totalHalfWatchedReply + videoDetail.totalHalfWatchedReply; } if ( videoDetail.lastHalfWatchedDateVideo && (!channelDetail.lastHalfWatchedDateVideo || channelDetail.lastHalfWatchedDateVideo < videoDetail.lastHalfWatchedDateVideo) ) { channelDetail.lastHalfWatchedDateVideo = videoDetail.lastHalfWatchedDateVideo; } if ( videoDetail.lastHalfWatchedDateReply && (!channelDetail.lastHalfWatchedDateReply || channelDetail.lastHalfWatchedDateReply < videoDetail.lastHalfWatchedDateReply) ) { channelDetail.lastHalfWatchedDateReply = videoDetail.lastHalfWatchedDateReply; } } } const dataToUpload = []; dataToUpload.push(oThis.rowKeys); for (let i = 0; i < oThis.channelIds.length; i++) { const channelId = oThis.channelIds[i]; const channelDetail = oThis.channelData[channelId]; channelDetail.lastHalfWatchedDateVideo = channelDetail.lastHalfWatchedDateVideo ? channelDetail.lastHalfWatchedDateVideo.getTime() / 1000 : null; channelDetail.lastHalfWatchedDateReply = channelDetail.lastHalfWatchedDateReply ? channelDetail.lastHalfWatchedDateReply.getTime() / 1000 : null; const row = [ channelDetail.id, channelDetail.name, oThis.datetimeInStr(channelDetail.createdAt), channelDetail.totalUsers, channelDetail.totalVideos, channelDetail.totalReplies, channelDetail.totalTransactions, channelDetail.totalHalfWatchedVideo, channelDetail.totalHalfWatchedReply, oThis.datetimeInStr(channelDetail.lastHalfWatchedDateVideo), oThis.datetimeInStr(channelDetail.lastHalfWatchedDateReply), oThis.datetimeInStr(channelDetail.lastVideoTime), oThis.datetimeInStr(channelDetail.lastReplyTime), oThis.datetimeInStr(channelDetail.lastTransactionTime) ]; dataToUpload.push(row); } return new GoogleSheetsUploadData().upload( pepoUsageSheetNamesConstants.channelDataLifetimeSheetName, dataToUpload, pepoUsageSheetNamesConstants.usageReportNamesToGroupIdsMap[ pepoUsageSheetNamesConstants.channelDataLifetimeSheetName ] ); } datetimeInStr(timestamp) { const oThis = this; if (timestamp) { return basicHelper.timeStampInMinutesToDateTillSeconds(timestamp); } else { return ''; } } /** * Returns row keys. * * @returns {*[]} */ get rowKeys() { return [ 'community_id', 'community_name', 'creation_date', 'total_members', 'total_videos', 'total_replies', 'no_of_transactions', 'videos_half_watched', 'replies_half_watched', 'last_half_video_watched_date', 'last_half_reply_watched_date', 'last_video_created_on', 'last_reply_created_on', 'last_transaction_date' ]; } }
JavaScript
class Navigation extends React.Component { render() { return ( <nav className="navbar navbar-default navbar-static-top"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar" > <span className="sr-only">Toggle navigation</span> <span className="icon-bar" /> <span className="icon-bar" /> <span className="icon-bar" /> </button> <IndexLink to="/" className="navbar-brand"> Home </IndexLink> </div> <div id="navbar" className="navbar-collapse collapse"> <ul className="nav navbar-nav"> <li> <Link to="/addItem">Add Item</Link> </li> <li> <Link to="/rating">Rating</Link> </li> <li> <Link to="/chart">Chart</Link> </li> </ul> </div> </div> </nav> ); } }
JavaScript
class ECKey extends Key { constructor (...args) { super(...args) this[JWK_MEMBERS]() Object.defineProperty(this, 'kty', { value: 'EC', enumerable: true }) if (!EC_CURVES.has(this.crv)) { throw new errors.JOSENotSupported('unsupported EC key curve') } } static get [PUBLIC_MEMBERS] () { return EC_PUBLIC } static get [PRIVATE_MEMBERS] () { return EC_PRIVATE } // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special // JSON.stringify handling in V8 [THUMBPRINT_MATERIAL] () { return { crv: this.crv, kty: 'EC', x: this.x, y: this.y } } [KEY_MANAGEMENT_ENCRYPT] () { return this.algorithms('deriveKey') } [KEY_MANAGEMENT_DECRYPT] () { if (this.public) { return new Set() } return this.algorithms('deriveKey') } static async generate (crv = 'P-256', privat = true) { if (!EC_CURVES.has(crv)) { throw new errors.JOSENotSupported(`unsupported EC key curve: ${crv}`) } let privateKey, publicKey if (keyObjectSupported) { ({ privateKey, publicKey } = await generateKeyPair('ec', { namedCurve: crv })) return privat ? privateKey : publicKey } ({ privateKey, publicKey } = await generateKeyPair('ec', { namedCurve: crv, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } })) if (privat) { return createPrivateKey(privateKey) } else { return createPublicKey(publicKey) } } static generateSync (crv = 'P-256', privat = true) { if (!EC_CURVES.has(crv)) { throw new errors.JOSENotSupported(`unsupported EC key curve: ${crv}`) } let privateKey, publicKey if (keyObjectSupported) { ({ privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: crv })) return privat ? privateKey : publicKey } ({ privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: crv, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } })) if (privat) { return createPrivateKey(privateKey) } else { return createPublicKey(publicKey) } } }
JavaScript
class HTMLRendererPlugin extends FLT.Plugin { /** * Register plugin * * @since 1.0.0 * * @return string[] */ static _register() { return ["toHTML", "toHTMLDOM"]; } /** * Render to HTML * * @since 1.0.0 * * @param object userOptions User options * @return string */ static toHTML(userOptions = {}) { let document = HTMLRendererPlugin.toHTMLDOM.call(this, userOptions); let bodyOnly = userOptions.hasOwnProperty("bodyOnly") ? userOptions.bodyOnly : false; if (bodyOnly) return pretty(serializer.serializeToString(document.body)); else return `<!DOCTYPE html>\n${pretty(serializer.serializeToString(document))}`; } /** * Render to HTML DOM * * @since 1.2.0 * * @param object userOptions User options * @return HTMLDocument */ static toHTMLDOM(userOptions = {}) { // options let options = { bodyOnly: false, // whether to return just the body insertHeading: true, // whether to insert an h1 for the document title bodyClass: [], // classes to apply to the body element stylesheet: [], // external stylesheet URLs to include }; for (let i in options) { if (userOptions.hasOwnProperty(i)) options[i] = userOptions[i]; } // document setup let document = Domino.createDOMImplementation().createHTMLDocument(); document.documentElement.setAttribute("xmlns", "http://www.w3.org/1999/xhtml"); let metaEl = document.head.appendChild(document.createElement("meta")); metaEl.setAttribute("http-equiv", "Content-Type"); metaEl.setAttribute("content", "text/html; charset=utf-8"); // source metadata if (this.features.DCMETA) { this.getDC("date").forEach((s) => document.head.appendChild(document.createComment(`Date: ${s}`)) ); this.getDC("source").forEach((s) => document.head.appendChild(document.createComment(`Source: ${s}`)) ); } // styles let styleEl = document.head.appendChild(document.createElement("style")); styleEl.textContent = style; if (options.stylesheet.length) for (let url of options.stylesheet) { let el = document.head.appendChild(document.createElement("link")); el.setAttribute("rel", "stylesheet"); el.setAttribute("type", "text/css"); el.setAttribute("href", url); } // other metadata HTMLRendererPlugin.applyMetadata.call(this, document); // body if (options.bodyClass.length) document.body.classList.add(...options.bodyClass); if (options.insertHeading && this.features.DCMETA) { let title = this.getDC("title").join(", "); if (title) { let h1 = document.body.appendChild(document.createElement("h1")); h1.setAttribute("id", "title"); h1.textContent = title; } } // render context let noteIndex = 1, link = null, hint = null, blob = null, sect = document.body.appendChild(document.createElement("section")), dest = FLT.Constants.D_BODY, reset = () => { link = null; hint = null; }, destEl = () => { // get the current destination element switch (dest) { case FLT.Constants.D_BODY: { let p = sect.lastElementChild; if (!p || !(p instanceof Domino.impl.HTMLParagraphElement)) p = sect.appendChild(document.createElement("p")); return p; } case FLT.Constants.D_NOTE: // notAnElement is used here because domino doesn't return an iterable // unless there are multiple queries provided - this is a workaround. let note = [...sect.querySelectorAll("aside, notAnElement")].slice(-1)[0]; return [...note.querySelectorAll("p, notAnElement")].slice(-1)[0]; case FLT.Constants.D_CELL: { let cell = [...sect.querySelectorAll("th, td")].slice(-1)[0]; let cont = [...cell.querySelectorAll("aside, p")].slice(-1)[0]; return cont || cell; } case FLT.Constants.D_HEAD: { let h = sect.lastElementChild; if ( !h || !(h instanceof Domino.impl.HTMLHeadingElement) || h.tagName !== "H2" ) h = sect.appendChild(document.createElement("h2")); return h; } default: throw new FLT.Error.FLTError(`Unknown render destination ${dest}`); } }; // iterate all typed & text lines, but *not* metadata lines for (let line of this.lines) { if (line.reset) reset(); // reset flag must be handled first, for all types if (line instanceof FLT.TypeLine) { // typed lines switch (line.lineType) { // start a new section case FLT.Constants.T_SECTION: link = null; dest = FLT.Constants.D_BODY; // reset target to body when a new section is created if (!sect.hasChildNodes()) sect.parentNode.removeChild(sect); sect = document.body.appendChild(document.createElement("section")); if (line.align in alignClasses) sect.classList.add(alignClasses[line.align]); if (line.break && sect.parentElement.querySelector("section") !== sect) { let hr = document.createElement("hr"); sect.insertAdjacentElement("beforeBegin", hr); } break; // start a new paragraph case FLT.Constants.T_PARAGRAPH: { link = null; let cont = destEl().closest("aside, td, th, section"); let p = cont.appendChild(document.createElement("p")); if (line.align in alignClasses) p.classList.add(alignClasses[line.align]); break; } // set the tooltip content case FLT.Constants.T_HINT: hint = line.content; break; // create a link case FLT.Constants.T_LINK: { link = destEl().appendChild(document.createElement("a")); link.setAttribute("href", line.content); if (hint) link.setAttribute("title", hint), (hint = null); break; } // create an anchor case FLT.Constants.T_ANCHOR: { let a = destEl().appendChild(document.createElement("a")); a.setAttribute("name", line.content); break; } // set the blob content case FLT.Constants.T_BLOB: blob = { type: line.mediaType, data: line.data }; break; // create an image case FLT.Constants.T_IMAGE: { let img = destEl().appendChild(document.createElement("img")); if (line.content) img.setAttribute("src", line.content); else if (!blob) throw new FLT.Error.FLTError("No image content available"); else img.setAttribute("src", `data:${blob.type};base64,${blob.data}`); if (hint) img.setAttribute("title", hint), (hint = null); break; } // create a table case FLT.Constants.T_TABLE: { let table = sect.appendChild(document.createElement("table")); table.fltColumns = line.content; break; } // set the render destination case FLT.Constants.T_DESTINATION: { link = null; if (line.destination === FLT.Constants.D_NOTE) { let a = destEl().appendChild(document.createElement("a")); a.setAttribute("name", `flt-note-return-${noteIndex}`); a.setAttribute("href", `#flt-note-${noteIndex}`); a.classList.add("to-note"); a.textContent = noteIndex; let note = sect.appendChild(document.createElement("aside")); a = note.appendChild(document.createElement("a")); a.setAttribute("name", `flt-note-${noteIndex}`); a.setAttribute("href", `#flt-note-return-${noteIndex}`); a.classList.add("from-note"); noteIndex++; note.appendChild(document.createElement("p")); } else if (line.destination === FLT.Constants.D_CELL) { let table = sect.querySelector("table:last-of-type"); if (!table) throw new FLT.Error.FLTError( "Cannot set destination to D_CELL when no table is defined" ); let cellCount = table.querySelectorAll("th, td").length; let row = table.querySelector("tr:last-of-type"); if (!row || !(BigInt(cellCount) % BigInt(table.fltColumns))) row = table.appendChild(document.createElement("tr")); row.appendChild(document.createElement(line.header ? "th" : "td")); } else if (line.destination === FLT.Constants.D_HEAD) { sect = document.body.appendChild(document.createElement("section")); } dest = line.destination; break; } } } else if (line instanceof FLT.TextLine) { // formatted text // TODO optimise nesting let out = destEl(); if (link && out.contains(link)) out = link; if (line.italic) out = out.appendChild(document.createElement("em")); if (line.bold) out = out.appendChild(document.createElement("strong")); if (line.underline || line.strikeout || line.mono) { out = out.appendChild(document.createElement("span")); if (line.underline) out.classList.add("underline"); if (line.strikeout) out.classList.add("strikeout"); if (line.mono) out.classList.add("monospace"); } if (line.supertext) out = out.appendChild(document.createElement("sup")); if (line.subtext) out = out.appendChild(document.createElement("sub")); out.appendChild(document.createTextNode(line.text)); } } // cleanup document.querySelectorAll("section, p").forEach((el) => { if (!el.hasChildNodes()) el.parentNode.removeChild(el); }); return document; } /** * Render document metadata into the DOM * * @since 1.0.0 * * @return void */ static applyMetadata(document) { if (!this.features.DCMETA) return; // not applicable if DC is disabled // title tag let title = this.getDC("title").join(", "); if (title) { let titleEl = document.head.appendChild(document.createElement("title")); titleEl.textContent = title; } // dublin core -> opengraph let og = (term, value) => { let el = document.head.appendChild(document.createElement("meta")); el.setAttribute("property", `og:${term}`); el.setAttribute("content", value); }; og("type", "article"); let terms = { title: { name: "title", merge: true }, description: { name: "description", merge: true }, creator: { name: "article:author", merge: false }, subject: { name: "article:tag", merge: false }, date: { name: "article:published_time", merge: false }, }; for (let term in terms) { let value = this.getDC(term); if (!value) continue; if (terms[term].merge) value = [value.join(", ")]; value.forEach((v) => og(terms[term].name, v)); } } }
JavaScript
class Redirects { /** * The constructor. */ constructor() { this.redirects = new Map(); this.matcher = pathMatch({ sensitive: false, strict: false, end: true, }); } /** * @param {string} pathname The pathname to lookup. * @returns {string|Promise|undefined} */ get(pathname) { return this.redirects.get(pathname) || null; } /** * Returns the redirect for a passed pathname. * @param {string} pathname The pathname to check. * @return {string|null} */ getRedirect(pathname) { /** * Try to make a direct match with the pathname. * If we get lucky then we don't have to iterate over the protected patterns. */ let redirect = this.get(pathname); /** * If we didn't find a direct match then we need to match * the given pathname against the protected patters. */ if (!redirect) { // Get the protected patterns as an array. const patterns = Array.from(this.redirects.keys()); const [withoutParams] = pathname.split('?'); // Loop over the patterns until a match is found. patterns.some((pattern) => { // Check for a match. const match = this.matcher(pattern)(withoutParams); // Match found, set the redirect. if (match) { redirect = this.redirects.get(pattern); } return match; }); } return redirect; } /** * @param {string} from The link to redirect from. Route patterns are also supported. * @param {string|Function|Promise} to redirect / handle to create a dynamic link. * @param {boolean} force Whether or not to forcefully set the redirect. */ set(from = null, to = null, force = false) { if (!from || !to) { return; } if (!force && this.redirects.has(from)) { return; } this.redirects.set(from, to); } /** * @param {string} pathname The pathname to remove. */ unset(pathname) { this.redirects.delete(pathname); } }
JavaScript
class Scene { constructor(renderer) { this.type = "Scene"; if(!renderer || renderer.type !== "Renderer") { throwError(this.type + ": Renderer not passed as first argument", renderer); } else if(!renderer.gl) { throwError(this.type + ": Renderer WebGL context is undefined", renderer); } this.renderer = renderer; this.gl = renderer.gl; this.initStacks(); } /*** Init our Scene stacks object ***/ initStacks() { this.stacks = { "opaque": { length: 0, programs: [], order: [], }, "transparent": { length: 0, programs: [], order: [], }, "renderPasses": [], "scenePasses": [], }; } /*** RESET STACKS ***/ /*** Reset the plane stacks (used when disposing a plane) ***/ resetPlaneStacks() { // clear the plane stacks this.stacks.opaque = { length: 0, programs: [], order: [], }; this.stacks.transparent = { length: 0, programs: [], order: [], }; // rebuild them with the new plane indexes for(let i = 0; i < this.renderer.planes.length; i++) { this.addPlane(this.renderer.planes[i]); } } /*** Reset the shader pass stacks (used when disposing a shader pass) ***/ resetShaderPassStacks() { // now rebuild the drawStacks // start by clearing all drawstacks this.stacks.scenePasses = []; this.stacks.renderPasses = []; // restack our planes with new indexes for(let i = 0; i < this.renderer.shaderPasses.length; i++) { this.renderer.shaderPasses[i].index = i; if(this.renderer.shaderPasses[i]._isScenePass) { this.stacks.scenePasses.push(this.renderer.shaderPasses[i].index); } else { this.stacks.renderPasses.push(this.renderer.shaderPasses[i].index); } } // reset the scenePassIndex if needed if(this.stacks.scenePasses.length === 0) { this.renderer.state.scenePassIndex = null; } } /*** ADDING PLANES ***/ /*** Add a new entry to our opaque and transparent programs arrays ***/ initProgramStack(programID) { this.stacks["opaque"]["programs"]["program-" + programID] = []; this.stacks["transparent"]["programs"]["program-" + programID] = []; } /*** This function will stack planes by opaqueness/transparency, program ID and then indexes Stack order drawing process: - draw opaque then transparent planes - for each of those two stacks, iterate through the existing programs (following the "order" array) and draw their respective planes This is done to improve speed, notably when using shared programs, and reduce GL calls params: @plane (Plane object): plane to add to our scene ***/ addPlane(plane) { if(!this.stacks["opaque"]["programs"]["program-" + plane._program.id]) { this.initProgramStack(plane._program.id); } const stackType = plane._transparent ? "transparent" : "opaque"; let stack = this.stacks[stackType]; if(stackType === "transparent") { stack["programs"]["program-" + plane._program.id].unshift(plane.index); // push to the order array only if it's not already in there if(!stack["order"].includes(plane._program.id)) { stack["order"].unshift(plane._program.id); } } else { stack["programs"]["program-" + plane._program.id].push(plane.index); // push to the order array only if it's not already in there if(!stack["order"].includes(plane._program.id)) { stack["order"].push(plane._program.id); } } stack.length++; } /*** This function will remove a plane from our scene. This just reset the plane stacks for now. Useful if we'd want to change the way our draw stacks work and keep the logic separated from our renderer params: @plane (Plane object): plane to remove from our scene ***/ removePlane(plane) { this.resetPlaneStacks(); } /*** Changing the position of a plane inside the correct plane stack to render it on top of the others ***/ movePlaneToFront(plane) { const drawType = plane._transparent ? "transparent" : "opaque"; let stack = this.stacks[drawType]["programs"]["program-" + plane._program.id]; stack = stack.filter(index => index !== plane.index); if(drawType === "transparent") { stack.unshift(plane.index); } else { stack.push(plane.index); } this.stacks[drawType]["programs"]["program-" + plane._program.id] = stack; // update order array this.stacks[drawType]["order"] = this.stacks[drawType]["order"].filter(programID => programID !== plane._program.id); this.stacks[drawType]["order"].push(plane._program.id); } /*** ADDING POST PROCESSING ***/ /*** Add a shader pass to the stack params: @shaderPass (ShaderPass object): shaderPass to add to our scene ***/ addShaderPass(shaderPass) { if(!shaderPass._isScenePass) { this.stacks.renderPasses.push(shaderPass.index); } else { this.stacks.scenePasses.push(shaderPass.index); } } /*** This function will remove a shader pass from our scene. This just reset the shaderPass stacks for now. Useful if we'd want to change the way our draw stacks work and keep the logic separated from our renderer params: @shaderPass (ShaderPass object): shader pass to remove from our scene ***/ removeShaderPass(shaderPass) { this.resetShaderPassStacks(); } /*** DRAWING SCENE ***/ /*** Loop through one of our stack (opaque or transparent objects) and draw its planes ***/ drawStack(stackType) { for(let i = 0; i < this.stacks[stackType]["order"].length; i++) { const programID = this.stacks[stackType]["order"][i]; const program = this.stacks[stackType]["programs"]["program-" + programID]; for(let j = 0; j < program.length; j++) { const plane = this.renderer.planes[program[j]]; // be sure the plane exists if(plane) { // draw the plane plane._startDrawing(); } } } } /*** Enable the first Shader pass scene pass ***/ enableShaderPass() { if(this.stacks.scenePasses.length && this.stacks.renderPasses.length === 0 && this.renderer.planes.length) { this.renderer.state.scenePassIndex = 0; this.renderer.bindFrameBuffer(this.renderer.shaderPasses[this.stacks.scenePasses[0]].target); } } /*** Draw the shader passes ***/ drawShaderPasses() { // if we got one or multiple scene passes after the render passes, bind the first scene pass here if(this.stacks.scenePasses.length && this.stacks.renderPasses.length && this.renderer.planes.length) { this.renderer.state.scenePassIndex = 0; this.renderer.bindFrameBuffer(this.renderer.shaderPasses[this.stacks.scenePasses[0]].target); } // first the render passes for(let i = 0; i < this.stacks.renderPasses.length; i++) { this.renderer.shaderPasses[this.stacks.renderPasses[i]]._startDrawing(); } // then the scene passes if(this.stacks.scenePasses.length > 0) { for(let i = 0; i < this.stacks.scenePasses.length; i++) { this.renderer.shaderPasses[this.stacks.scenePasses[i]]._startDrawing(); } } } /*** Draw our scene content ***/ draw() { // enable first frame buffer for shader passes if needed this.enableShaderPass(); // loop on our stacked planes this.drawStack("opaque"); // draw transparent planes if needed if(this.stacks["transparent"].length) { // clear our depth buffer to display transparent objects this.gl.clearDepth(1.0); this.gl.clear(this.gl.DEPTH_BUFFER_BIT); this.drawStack("transparent"); } // now render the shader passes this.drawShaderPasses(); } }
JavaScript
class Loader { /** * Creates an instance of Loader using [[LoaderOptions]]. No defaults are set * using this library, instead the defaults are set by the Google Maps * JavaScript API server. * * ``` * const loader = Loader({apiKey, version: 'weekly', libraries: ['places']}); * ``` */ constructor({ apiKey, channel, client, id = DEFAULT_ID, libraries = [], language, region, version, mapIds, nonce, retries = 3, url = "https://maps.googleapis.com/maps/api/js", }) { this.CALLBACK = "__googleMapsCallback"; this.callbacks = []; this.done = false; this.loading = false; this.errors = []; this.version = version; this.apiKey = apiKey; this.channel = channel; this.client = client; this.id = id || DEFAULT_ID; // Do not allow empty string this.libraries = libraries; this.language = language; this.region = region; this.mapIds = mapIds; this.nonce = nonce; this.retries = retries; this.url = url; if (Loader.instance) { if (!fastDeepEqual(this.options, Loader.instance.options)) { throw new Error(`Loader must not be called again with different options. ${JSON.stringify(this.options)} !== ${JSON.stringify(Loader.instance.options)}`); } return Loader.instance; } Loader.instance = this; } get options() { return { version: this.version, apiKey: this.apiKey, channel: this.channel, client: this.client, id: this.id, libraries: this.libraries, language: this.language, region: this.region, mapIds: this.mapIds, nonce: this.nonce, url: this.url, }; } get failed() { return this.done && !this.loading && this.errors.length >= this.retries + 1; } /** * CreateUrl returns the Google Maps JavaScript API script url given the [[LoaderOptions]]. * * @ignore */ createUrl() { let url = this.url; url += `?callback=${this.CALLBACK}`; if (this.apiKey) { url += `&key=${this.apiKey}`; } if (this.channel) { url += `&channel=${this.channel}`; } if (this.client) { url += `&client=${this.client}`; } if (this.libraries.length > 0) { url += `&libraries=${this.libraries.join(",")}`; } if (this.language) { url += `&language=${this.language}`; } if (this.region) { url += `&region=${this.region}`; } if (this.version) { url += `&v=${this.version}`; } if (this.mapIds) { url += `&map_ids=${this.mapIds.join(",")}`; } return url; } /** * Load the Google Maps JavaScript API script and return a Promise. */ load() { return this.loadPromise(); } /** * Load the Google Maps JavaScript API script and return a Promise. * * @ignore */ loadPromise() { return new Promise((resolve, reject) => { this.loadCallback((err) => { if (!err) { resolve(window.google); } else { reject(err.error); } }); }); } /** * Load the Google Maps JavaScript API script with a callback. */ loadCallback(fn) { this.callbacks.push(fn); this.execute(); } /** * Set the script on document. */ setScript() { if (document.getElementById(this.id)) { // TODO wrap onerror callback for cases where the script was loaded elsewhere this.callback(); return; } const url = this.createUrl(); const script = document.createElement("script"); script.id = this.id; script.type = "text/javascript"; script.src = url; script.onerror = this.loadErrorCallback.bind(this); script.defer = true; script.async = true; if (this.nonce) { script.nonce = this.nonce; } document.head.appendChild(script); } deleteScript() { const script = document.getElementById(this.id); if (script) { script.remove(); } } /** * Reset the loader state. */ reset() { this.deleteScript(); this.done = false; this.loading = false; this.errors = []; this.onerrorEvent = null; } resetIfRetryingFailed() { if (this.failed) { this.reset(); } } loadErrorCallback(e) { this.errors.push(e); if (this.errors.length <= this.retries) { const delay = this.errors.length * Math.pow(2, this.errors.length); console.log(`Failed to load Google Maps script, retrying in ${delay} ms.`); setTimeout(() => { this.deleteScript(); this.setScript(); }, delay); } else { this.onerrorEvent = e; this.callback(); } } setCallback() { window.__googleMapsCallback = this.callback.bind(this); } callback() { this.done = true; this.loading = false; this.callbacks.forEach((cb) => { cb(this.onerrorEvent); }); this.callbacks = []; } execute() { this.resetIfRetryingFailed(); if (this.done) { this.callback(); } else { // short circuit and warn if google.maps is already loaded if (window.google && window.google.maps && window.google.maps.version) { console.warn("Google Maps already loaded outside @googlemaps/js-api-loader." + "This may result in undesirable behavior as options and script parameters may not match."); this.callback(); return; } if (this.loading) ; else { this.loading = true; this.setCallback(); this.setScript(); } } } }
JavaScript
class PatchableComponent extends React.PureComponent { constructor (props) { super(props); this.forceUpdate = this.forceUpdate.bind(this); } componentDidMount () { this.unsubscribe = subscribe(this.forceUpdate); } componentWillUnmount () { this.unsubscribe(); } }
JavaScript
class ReceiptForm extends Component{ constructor(props){ super(props); this.state = { inputText: '' } } onChange = (value) => { this.setState({ inputText: value, isError: false }); } onSubmitForm = (event) =>{ event.preventDefault(); const {matricola_docente,date,matricola_studente,id} = this.props; if(this.state.inputText){ this.props.onReceiptSubmit(matricola_docente,date,matricola_studente,this.state.inputText,id) this.setState({ inputText: '' }) }else{ this.setState({ isError: true }) } } render(){ return( <form onSubmit={this.onSubmitForm}> <TextArea id={this.props.id} maxRows={10} minRows={3} textCallback={this.onChange} className={`form-control form-control-lg mt-3${this.state.isError ? ' is-invalid' : ''}`} placeholder='Motivazione, Es."Spiegazione generatore di grafi"' inputValue={this.state.inputText} /> <div className="invalid-feedback"> Inserisci una motivazione valida... </div> <Submit classColor='btn-primary' className='btn-right w-100 mt-3' buttontext='Effettua Prenotazione'/> </form> ); } }
JavaScript
class CommandFailedError extends Error { constructor() { super( 'The Buck worker-tool command failed. Diagnostics should have ' + 'been printed on the standard error output.', ); } }
JavaScript
class TextOperationResult { /** * Create a TextOperationResult. * @property {string} [status] Status of the text operation. Possible values * include: 'Not Started', 'Running', 'Failed', 'Succeeded' * @property {object} [recognitionResult] Text recognition result of the text * operation. * @property {number} [recognitionResult.page] The 1-based page number of the * recognition result. * @property {number} [recognitionResult.clockwiseOrientation] The * orientation of the image in degrees in the clockwise direction. Range * between [0, 360). * @property {number} [recognitionResult.width] The width of the image in * pixels or the PDF in inches. * @property {number} [recognitionResult.height] The height of the image in * pixels or the PDF in inches. * @property {string} [recognitionResult.unit] The unit used in the Width, * Height and BoundingBox. For images, the unit is "pixel". For PDF, the unit * is "inch". Possible values include: 'pixel', 'inch' * @property {array} [recognitionResult.lines] A list of recognized text * lines. */ constructor() { } /** * Defines the metadata of TextOperationResult * * @returns {object} metadata of TextOperationResult * */ mapper() { return { required: false, serializedName: 'TextOperationResult', type: { name: 'Composite', className: 'TextOperationResult', modelProperties: { status: { required: false, nullable: false, serializedName: 'status', type: { name: 'Enum', allowedValues: [ 'Not Started', 'Running', 'Failed', 'Succeeded' ] } }, recognitionResult: { required: false, serializedName: 'recognitionResult', type: { name: 'Composite', className: 'TextRecognitionResult' } } } } }; } }
JavaScript
class RSAPrivateKey { //********************************************************************************** /** * Constructor for RSAPrivateKey class * @param {Object} [parameters={}] * @param {Object} [parameters.schema] asn1js parsed value to initialize the class from */ constructor(parameters = {}) { //region Internal properties of the object /** * @type {number} * @desc version */ this.version = getParametersValue(parameters, "version", RSAPrivateKey.defaultValues("version")); /** * @type {Integer} * @desc modulus */ this.modulus = getParametersValue(parameters, "modulus", RSAPrivateKey.defaultValues("modulus")); /** * @type {Integer} * @desc publicExponent */ this.publicExponent = getParametersValue(parameters, "publicExponent", RSAPrivateKey.defaultValues("publicExponent")); /** * @type {Integer} * @desc privateExponent */ this.privateExponent = getParametersValue(parameters, "privateExponent", RSAPrivateKey.defaultValues("privateExponent")); /** * @type {Integer} * @desc prime1 */ this.prime1 = getParametersValue(parameters, "prime1", RSAPrivateKey.defaultValues("prime1")); /** * @type {Integer} * @desc prime2 */ this.prime2 = getParametersValue(parameters, "prime2", RSAPrivateKey.defaultValues("prime2")); /** * @type {Integer} * @desc exponent1 */ this.exponent1 = getParametersValue(parameters, "exponent1", RSAPrivateKey.defaultValues("exponent1")); /** * @type {Integer} * @desc exponent2 */ this.exponent2 = getParametersValue(parameters, "exponent2", RSAPrivateKey.defaultValues("exponent2")); /** * @type {Integer} * @desc coefficient */ this.coefficient = getParametersValue(parameters, "coefficient", RSAPrivateKey.defaultValues("coefficient")); if("otherPrimeInfos" in parameters) /** * @type {Array.<OtherPrimeInfo>} * @desc otherPrimeInfos */ this.otherPrimeInfos = getParametersValue(parameters, "otherPrimeInfos", RSAPrivateKey.defaultValues("otherPrimeInfos")); //endregion //region If input argument array contains "schema" for this object if("schema" in parameters) this.fromSchema(parameters.schema); //endregion //region If input argument array contains "json" for this object if("json" in parameters) this.fromJSON(parameters.json); //endregion } //********************************************************************************** /** * Return default values for all class members * @param {string} memberName String name for a class member */ static defaultValues(memberName) { switch(memberName) { case "version": return 0; case "modulus": return new asn1js.Integer(); case "publicExponent": return new asn1js.Integer(); case "privateExponent": return new asn1js.Integer(); case "prime1": return new asn1js.Integer(); case "prime2": return new asn1js.Integer(); case "exponent1": return new asn1js.Integer(); case "exponent2": return new asn1js.Integer(); case "coefficient": return new asn1js.Integer(); case "otherPrimeInfos": return []; default: throw new Error(`Invalid member name for RSAPrivateKey class: ${memberName}`); } } //********************************************************************************** /** * Return value of pre-defined ASN.1 schema for current class * * ASN.1 schema: * ```asn1 * RSAPrivateKey ::= Sequence { * version Version, * modulus Integer, -- n * publicExponent Integer, -- e * privateExponent Integer, -- d * prime1 Integer, -- p * prime2 Integer, -- q * exponent1 Integer, -- d mod (p-1) * exponent2 Integer, -- d mod (q-1) * coefficient Integer, -- (inverse of q) mod p * otherPrimeInfos OtherPrimeInfos OPTIONAL * } * * OtherPrimeInfos ::= Sequence SIZE(1..MAX) OF OtherPrimeInfo * ``` * * @param {Object} parameters Input parameters for the schema * @returns {Object} asn1js schema object */ static schema(parameters = {}) { /** * @type {Object} * @property {string} [blockName] * @property {string} [version] * @property {string} [modulus] * @property {string} [publicExponent] * @property {string} [privateExponent] * @property {string} [prime1] * @property {string} [prime2] * @property {string} [exponent1] * @property {string} [exponent2] * @property {string} [coefficient] * @property {string} [otherPrimeInfosName] * @property {Object} [otherPrimeInfo] */ const names = getParametersValue(parameters, "names", {}); return (new asn1js.Sequence({ name: (names.blockName || ""), value: [ new asn1js.Integer({ name: (names.version || "") }), new asn1js.Integer({ name: (names.modulus || "") }), new asn1js.Integer({ name: (names.publicExponent || "") }), new asn1js.Integer({ name: (names.privateExponent || "") }), new asn1js.Integer({ name: (names.prime1 || "") }), new asn1js.Integer({ name: (names.prime2 || "") }), new asn1js.Integer({ name: (names.exponent1 || "") }), new asn1js.Integer({ name: (names.exponent2 || "") }), new asn1js.Integer({ name: (names.coefficient || "") }), new asn1js.Sequence({ optional: true, value: [ new asn1js.Repeated({ name: (names.otherPrimeInfosName || ""), value: OtherPrimeInfo.schema(names.otherPrimeInfo || {}) }) ] }) ] })); } //********************************************************************************** /** * Convert parsed asn1js object into current class * @param {!Object} schema */ fromSchema(schema) { //region Clear input data first clearProps(schema, [ "version", "modulus", "publicExponent", "privateExponent", "prime1", "prime2", "exponent1", "exponent2", "coefficient", "otherPrimeInfos" ]); //endregion //region Check the schema is valid const asn1 = asn1js.compareSchema(schema, schema, RSAPrivateKey.schema({ names: { version: "version", modulus: "modulus", publicExponent: "publicExponent", privateExponent: "privateExponent", prime1: "prime1", prime2: "prime2", exponent1: "exponent1", exponent2: "exponent2", coefficient: "coefficient", otherPrimeInfo: { names: { blockName: "otherPrimeInfos" } } } }) ); if(asn1.verified === false) throw new Error("Object's schema was not verified against input data for RSAPrivateKey"); //endregion //region Get internal properties from parsed schema this.version = asn1.result.version.valueBlock.valueDec; this.modulus = asn1.result.modulus.convertFromDER(256); this.publicExponent = asn1.result.publicExponent; this.privateExponent = asn1.result.privateExponent.convertFromDER(256); this.prime1 = asn1.result.prime1.convertFromDER(128); this.prime2 = asn1.result.prime2.convertFromDER(128); this.exponent1 = asn1.result.exponent1.convertFromDER(128); this.exponent2 = asn1.result.exponent2.convertFromDER(128); this.coefficient = asn1.result.coefficient.convertFromDER(128); if("otherPrimeInfos" in asn1.result) this.otherPrimeInfos = Array.from(asn1.result.otherPrimeInfos, element => new OtherPrimeInfo({ schema: element })); //endregion } //********************************************************************************** /** * Convert current object to asn1js object and set correct values * @returns {Object} asn1js object */ toSchema() { //region Create array for output sequence const outputArray = []; outputArray.push(new asn1js.Integer({ value: this.version })); outputArray.push(this.modulus.convertToDER()); outputArray.push(this.publicExponent); outputArray.push(this.privateExponent.convertToDER()); outputArray.push(this.prime1.convertToDER()); outputArray.push(this.prime2.convertToDER()); outputArray.push(this.exponent1.convertToDER()); outputArray.push(this.exponent2.convertToDER()); outputArray.push(this.coefficient.convertToDER()); if("otherPrimeInfos" in this) { outputArray.push(new asn1js.Sequence({ value: Array.from(this.otherPrimeInfos, element => element.toSchema()) })); } //endregion //region Construct and return new ASN.1 schema for this object return (new asn1js.Sequence({ value: outputArray })); //endregion } //********************************************************************************** /** * Convertion for the class to JSON object * @returns {Object} */ toJSON() { const jwk = { n: toBase64(arrayBufferToString(this.modulus.valueBlock.valueHex), true, true, true), e: toBase64(arrayBufferToString(this.publicExponent.valueBlock.valueHex), true, true, true), d: toBase64(arrayBufferToString(this.privateExponent.valueBlock.valueHex), true, true, true), p: toBase64(arrayBufferToString(this.prime1.valueBlock.valueHex), true, true, true), q: toBase64(arrayBufferToString(this.prime2.valueBlock.valueHex), true, true, true), dp: toBase64(arrayBufferToString(this.exponent1.valueBlock.valueHex), true, true, true), dq: toBase64(arrayBufferToString(this.exponent2.valueBlock.valueHex), true, true, true), qi: toBase64(arrayBufferToString(this.coefficient.valueBlock.valueHex), true, true, true) }; if("otherPrimeInfos" in this) jwk.oth = Array.from(this.otherPrimeInfos, element => element.toJSON()); return jwk; } //********************************************************************************** /** * Convert JSON value into current object * @param {Object} json */ fromJSON(json) { if("n" in json) this.modulus = new asn1js.Integer({ valueHex: stringToArrayBuffer(fromBase64(json.n, true, true)) }); else throw new Error("Absent mandatory parameter \"n\""); if("e" in json) this.publicExponent = new asn1js.Integer({ valueHex: stringToArrayBuffer(fromBase64(json.e, true, true)) }); else throw new Error("Absent mandatory parameter \"e\""); if("d" in json) this.privateExponent = new asn1js.Integer({ valueHex: stringToArrayBuffer(fromBase64(json.d, true, true)) }); else throw new Error("Absent mandatory parameter \"d\""); if("p" in json) this.prime1 = new asn1js.Integer({ valueHex: stringToArrayBuffer(fromBase64(json.p, true, true)) }); else throw new Error("Absent mandatory parameter \"p\""); if("q" in json) this.prime2 = new asn1js.Integer({ valueHex: stringToArrayBuffer(fromBase64(json.q, true, true)) }); else throw new Error("Absent mandatory parameter \"q\""); if("dp" in json) this.exponent1 = new asn1js.Integer({ valueHex: stringToArrayBuffer(fromBase64(json.dp, true, true)) }); else throw new Error("Absent mandatory parameter \"dp\""); if("dq" in json) this.exponent2 = new asn1js.Integer({ valueHex: stringToArrayBuffer(fromBase64(json.dq, true, true)) }); else throw new Error("Absent mandatory parameter \"dq\""); if("qi" in json) this.coefficient = new asn1js.Integer({ valueHex: stringToArrayBuffer(fromBase64(json.qi, true, true)) }); else throw new Error("Absent mandatory parameter \"qi\""); if("oth" in json) this.otherPrimeInfos = Array.from(json.oth, element => new OtherPrimeInfo({ json: element })); } //********************************************************************************** }
JavaScript
class CampaignIndex extends Component{ // we need to define the following for next.js to get correct data from contract static async getInitialProps() { const campaigns = await factory.methods.getDeployedCampaigns().call(); return { campaigns }; } // we want to create new function to create a card group renderCampaigns() { const items = this.props.campaigns.map(address => { return{ header: address, description: ( <Link route= {`/campaigns/${address}`}> <a>View Campaign</a> </Link> ), fluid: true }; }); return <Card.Group items = {items} />; } // we need to output some jsx for react so we do not get an error //this will render the address of the campaign on the page render() { // we want first element from this arrray return ( <Layout> <div> <h3>Open Campaigns</h3> <Link route = "/campaigns/new"> <a> <Button floated = 'right' content = 'Create Campaign' icon = 'add circle' primary /> </a> </Link> {this.renderCampaigns()} </div> </Layout> ); } }
JavaScript
class ApplicationGatewayFirewallRuleSet extends models['Resource'] { /** * Create a ApplicationGatewayFirewallRuleSet. * @property {string} [provisioningState] The provisioning state of the web * application firewall rule set. * @property {string} ruleSetType The type of the web application firewall * rule set. * @property {string} ruleSetVersion The version of the web application * firewall rule set type. * @property {array} ruleGroups The rule groups of the web application * firewall rule set. */ constructor() { super(); } /** * Defines the metadata of ApplicationGatewayFirewallRuleSet * * @returns {object} metadata of ApplicationGatewayFirewallRuleSet * */ mapper() { return { required: false, serializedName: 'ApplicationGatewayFirewallRuleSet', type: { name: 'Composite', className: 'ApplicationGatewayFirewallRuleSet', modelProperties: { id: { required: false, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, location: { required: false, serializedName: 'location', type: { name: 'String' } }, tags: { required: false, serializedName: 'tags', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, provisioningState: { required: false, serializedName: 'properties.provisioningState', type: { name: 'String' } }, ruleSetType: { required: true, serializedName: 'properties.ruleSetType', type: { name: 'String' } }, ruleSetVersion: { required: true, serializedName: 'properties.ruleSetVersion', type: { name: 'String' } }, ruleGroups: { required: true, serializedName: 'properties.ruleGroups', type: { name: 'Sequence', element: { required: false, serializedName: 'ApplicationGatewayFirewallRuleGroupElementType', type: { name: 'Composite', className: 'ApplicationGatewayFirewallRuleGroup' } } } } } } }; } }
JavaScript
class PercentageActive extends CPM.Stat { computePercentageOfCell( cellid, cellpixels ){ // get pixels of this cell const pixels = cellpixels[ cellid ] // loop over the pixels and count activities > 0 let activecount = 0 for( let i = 0; i < pixels.length; i++ ){ const pos = this.M.grid.p2i( pixels[i] ) if( this.M.getConstraint( "ActivityConstraint" ).pxact( pos ) > 0 ){ activecount++ } } // divide by total number of pixels and multiply with 100 to get percentage return ( 100 * activecount / pixels.length ) } compute(){ // Get object with arrays of pixels for each cell on the grid, and get // the array for the current cell. let cellpixels = this.M.getStat( CPM.PixelsByCell ) // Create an object for the centroids. Add the centroid array for each cell. let percentages = {} for( let cid of this.M.cellIDs() ){ percentages[cid] = this.computePercentageOfCell( cid, cellpixels ) } return percentages } }
JavaScript
class MainPanel { addChild(child){ Main.panel._rightBox.insert_child_at_index(child, 0); } removeChild(child) { Main.panel._rightBox.remove_child(child); } addToStatusArea(view) { Main.panel.addToStatusArea('NetworkStatsStatusView', view, 0, 'right'); } removeFromStatusArea(view) { view.destroy(); } }
JavaScript
class EmailDesigner extends React.Component { static propTypes = { defaultValue: PropTypes.object, editable: PropTypes.bool, endpoint: PropTypes.string, fields: PropTypes.array, program: PropTypes.object, settings: PropTypes.bool, tokens: PropTypes.array } static defaultProps = { settings: true } render() { return <Designer { ...this._getDesigner() } /> } _getDesigner() { const { defaultValue, editable, endpoint, program, settings, tokens } = this.props return { title: 't(Email)', canvas: '/automation/admin/emails/designer', editable, endpoint, preview: true, components: { page: Page, section: Section }, program_id: program ? program.id : null, settings, tokens, blocks: [ { label: 't(Text)', type: 'text', icon: 'align-justify', component: Text }, { label: 't(Divider)', type: 'divider', icon: 'minus', component: Divider }, // { label: 't(Image Group)', type: 'images', icon: 'th', component: Images }, { label: 't(Image)', type: 'image', icon: 'picture-o', component: Image }, { label: 't(Button)', type: 'button', icon: 'mouse-pointer', component: Button }, { label: 't(Preferences)', type: 'preferences', icon: 'check', component: Preferences }, { label: 't(Social Share)', type: 'share', icon: 'share', component: Share }, { label: 't(Social Follow)', type: 'follow', icon: 'plus', component: Follow }, { label: 't(Video)', type: 'video', icon: 'play', component: Video }, { label: 't(Web Version)', type: 'web', icon: 'globe', component: Web } ], defaultValue } } }
JavaScript
class Index extends React.Component { render() { return ( <div> <ScrollUpButton /> {/* //This is all you need to get the default view working */} </div> ); } }
JavaScript
class CRender { constructor (canvas) { if (!canvas) { console.error('CRender Missing parameters!') return } const ctx = canvas.getContext('2d') const { clientWidth, clientHeight } = canvas const area = [clientWidth, clientHeight] canvas.setAttribute('width', clientWidth) canvas.setAttribute('height', clientHeight) /** * @description Context of the canvas * @type {Object} * @example ctx = canvas.getContext('2d') */ this.ctx = ctx /** * @description Width and height of the canvas * @type {Array} * @example area = [300,100] */ this.area = area /** * @description Whether render is in animation rendering * @type {Boolean} * @example animationStatus = true|false */ this.animationStatus = false /** * @description Added graph * @type {[Graph]} * @example graphs = [Graph, Graph, ...] */ this.graphs = [] /** * @description Color plugin * @type {Object} * @link https://github.com/jiaming743/color */ this.color = color /** * @description Bezier Curve plugin * @type {Object} * @link https://github.com/jiaming743/BezierCurve */ this.bezierCurve = bezierCurve // bind event handler canvas.addEventListener('mousedown', mouseDown.bind(this)) canvas.addEventListener('mousemove', mouseMove.bind(this)) canvas.addEventListener('mouseup', mouseUp.bind(this)) } }
JavaScript
class AccessController { /** * Constructor. * @param {AclManager} aclManager The ACL manager to use. */ constructor(aclManager) { const method = 'constructor'; LOG.entry(method, aclManager); this.aclManager = aclManager; this.participant = null; LOG.exit(method); } /** * Get the current participant. * @return {Resource} The current participant. */ getParticipant() { return this.participant; } /** * Set the current participant. * @param {Resource} participant The current participant. */ setParticipant(participant) { this.participant = participant; } /** * Check that the specified participant has the specified * level of access to the specified resource. * @param {Resource} resource The resource. * @param {string} access The level of access. * @param {Resource} participant The participant. * @throws {AccessException} If the specified participant * does not have the specified level of access to the specified * resource. */ check(resource, access) { const method = 'check'; LOG.entry(method, resource.getFullyQualifiedIdentifier(), access); try { // Check to see if a participant has been set. If not, then ACL // enforcement is not enabled. let participant = this.participant; if (!participant) { LOG.debug(method, 'No participant'); LOG.exit(method); return; } // Check to see if an ACL file was supplied. If not, then ACL // enforcement is not enabled. if (!this.aclManager.getAclFile()) { LOG.debug(method, 'No ACL file'); LOG.exit(method); return; } // Iterate over the ACL rules in order, but stop at the first rule // that permits the action. let aclRules = this.aclManager.getAclRules(); let result = aclRules.some((aclRule) => { LOG.debug(method, 'Processing rule', aclRule); let value = this.checkRule(resource, access, participant, aclRule); LOG.debug(method, 'Processed rule', value); return value; }); // If a ACL rule permitted the action, return. if (result) { LOG.exit(method); return; } // Otherwise no ACL rule permitted the action. throw new AccessException(resource, access, participant); } catch (e) { LOG.error(method, e); throw e; } } /** * Check the specified ACL rule permits the specified level * of access to the specified resource. * @param {Resource} resource The resource. * @param {string} access The level of access. * @param {Resource} participant The participant. * @param {AclRule} aclRule The ACL rule. * @returns {boolean} True if the specified ACL rule permits * the specified level of access to the specified resource. */ checkRule(resource, access, participant, aclRule) { const method = 'checkRule'; LOG.entry(method, participant.getFullyQualifiedIdentifier(), resource, access, participant, aclRule); // Is the ACL rule relevant to the specified noun? if (!this.matchNoun(resource, aclRule)) { LOG.debug(method, 'Noun does not match'); LOG.exit(method, false); return false; } // Is the ACL rule relevant to the specified verb? if (!this.matchVerb(access, aclRule)) { LOG.debug(method, 'Verb does not match'); LOG.exit(method, false); return false; } // Is the ACL rule relevant to the specified participant? if (!this.matchParticipant(participant, aclRule)) { LOG.debug(method, 'Participant does not match'); LOG.exit(method, false); return false; } // Is the predicate met? if (!this.matchPredicate(resource, access, participant, aclRule)) { LOG.debug(method, 'Predicate does not match'); LOG.exit(method, false); return false; } // Yes, is this an allow or deny rule? if (aclRule.getAction() === 'ALLOW') { LOG.exit(method, true); return true; } // This must be an explicit deny rule, so throw. let e = new AccessException(resource, access, participant); LOG.error(method, e); throw e; } /** * Check that the specified participant has the specified * level of access to the specified resource. * @param {Resource} resource The resource. * @param {AclRule} aclRule The ACL rule. * @returns {boolean} True if the specified ACL rule permits * the specified level of access to the specified resource. */ matchNoun(resource, aclRule) { const method = 'matchNoun'; LOG.entry(method, resource.getFullyQualifiedIdentifier(), aclRule); // Determine the input fully qualified name and ID. let fqn = resource.getFullyQualifiedType(); let ns = resource.getNamespace(); let id = resource.getIdentifier(); // Check the namespace and type of the ACL rule. let noun = aclRule.getNoun(); // Check to see if the fully qualified name matches. let reqFQN = noun.getFullyQualifiedName(); if (fqn === reqFQN) { // Noun is matching fully qualified type. } else if (ns === reqFQN) { // Noun is matching namespace. } else { // Noun does not match. LOG.exit(method, false); return false; } // Check to see if the identifier matches (if specified). let reqID = noun.getInstanceIdentifier(); if (reqID) { if (id === reqID) { // Noun is matching identifier. } else { // Noun does not match. LOG.exit(method, false); return false; } } else { // Noun does not specify identifier. } LOG.exit(method, true); return true; } /** * Check that the specified participant has the specified * level of access to the specified resource. * @param {string} access The level of access. * @param {AclRule} aclRule The ACL rule. * @returns {boolean} True if the specified ACL rule permits * the specified level of access to the specified resource. */ matchVerb(access, aclRule) { const method = 'matchVerb'; LOG.entry(method, access, aclRule); // Check to see if the access matches the verb of the ACL rule. // Verb can be one of: // 'CREATE' / 'READ' / 'UPDATE' / 'ALL' / 'DELETE' let result = false; let verb = aclRule.getVerb(); if (verb === 'ALL' || access === verb) { result = true; } LOG.exit(method, result); return result; } /** * Check that the specified participant has the specified * level of access to the specified resource. * @param {Resource} participant The participant. * @param {AclRule} aclRule The ACL rule. * @returns {boolean} True if the specified ACL rule permits * the specified level of access to the specified resource. */ matchParticipant(participant, aclRule) { const method = 'matchParticipant'; LOG.entry(method, participant.getFullyQualifiedIdentifier(), aclRule); // Is a participant specified in the ACL rule? let reqParticipant = aclRule.getParticipant(); if (!reqParticipant) { LOG.exit(method, true); return true; } // Check to see if the participant is an instance of the // required participant type, or is in the required // namespace. let ns = participant.getNamespace(); let reqFQN = reqParticipant.getFullyQualifiedName(); if (participant.instanceOf(reqFQN)) { // Participant is matching type or subtype. } else if (ns === reqFQN) { // Participant is matching namespace. } else { // Participant does not match. LOG.exit(method, false); return false; } // Check to see if the identifier matches (if specified). let id = participant.getIdentifier(); let reqID = reqParticipant.getInstanceIdentifier(); if (reqID) { if (id === reqID) { // Participant is matching identifier. } else { // Participant does not match. LOG.exit(method, false); return false; } } else { // Participant does not specify identifier. } LOG.exit(method, true); return true; } /** * Check that the specified participant has the specified * level of access to the specified resource. * @param {Resource} resource The resource. * @param {string} access The level of access. * @param {Resource} participant The participant. * @param {AclRule} aclRule The ACL rule. * @returns {boolean} True if the specified ACL rule permits * the specified level of access to the specified resource. */ matchPredicate(resource, access, participant, aclRule) { const method = 'matchPredicate'; LOG.entry(method, resource.getFullyQualifiedIdentifier(), access, participant.getFullyQualifiedIdentifier(), aclRule); // Get the predicate from the rule. let predicate = aclRule.getPredicate().getExpression(); // We can fast track the simple boolean predicates. if (predicate === 'true') { LOG.exit(method, true); return true; } else if (predicate === 'false') { LOG.exit(method, false); return false; } // Otherwise we need to build a function. let source = `return (${predicate});`; let argNames = []; let argValues = []; // Check to see if the resource needs to be bound. let resourceVar = aclRule.getNoun().getVariableName(); if (resourceVar) { argNames.push(resourceVar); argValues.push(resource); } // Check to see if the participant needs to be bound. let reqParticipant = aclRule.getParticipant(); if (reqParticipant) { let participantVar = aclRule.getParticipant().getVariableName(); if (participantVar) { argNames.push(participantVar); argValues.push(participant); } } // Compile and execute the function. let result; try { LOG.debug(method, 'Compiling and executing function', source, argNames, argValues); let func = new Function(argNames.join(','), source); result = func.apply(null, argValues); } catch (e) { LOG.error(method, e); throw new AccessException(resource, access, participant); } // Convert the result into a boolean before returning it. result = !!result; LOG.exit(method, result); return result; } }
JavaScript
class SlideView extends LitElement { static get properties() { return { url: { type: String, reflect: true, attribute: true }, delta: { type: String, reflect: true, attribute: true }, focus: { type: Boolean, reflect: true, attribute: true }, fullscreen: { type: Boolean, reflect: true, attribute: true } }; } static get styles() { return [ bulmaStyle, css` iframe, section { width: 100%; height: 100%; } ` ]; } constructor() { super(); this.url = ''; this.delta = '0'; this.fullscreen = false; } attributeChangedCallback(name, oldval, newval) { super.attributeChangedCallback(name, oldval, newval); if (newval && (name === 'url' || (this.url && name === 'delta'))) { const iframe = this.shadowRoot.querySelector('iframe'); let src = `${this.url}#delta=${this.delta}`; if (this.focus) { src += '&focus'; } iframe.src = src; iframe.classList.remove('is-hidden'); } } render() { return html` <section style="width: ${this.fullscreen ? '100vw' : '100%'}; height: ${this.fullscreen ? '100vh' : '100%'}"> <iframe>Current slide</iframe> </section> `; } }
JavaScript
class TreeRequest extends Base { /** * Create service * @param {App} app The application * @param {object} config Configuration * @param {Logger} logger Logger service */ constructor(app, config, logger) { super(app); this._config = config; this._logger = logger; } /** * Service name is 'daemon.events.treeRequest' * @type {string} */ static get provides() { return 'daemon.events.treeRequest'; } /** * Dependencies as constructor arguments * @type {string[]} */ static get requires() { return [ 'app', 'config', 'logger' ]; } /** * Event name * @type {string} */ get name() { return 'tree_request'; } /** * Event handler * @param {string} id ID of the client * @param {object} message The message * @return {Promise} */ async handle(id, message) { let client = this.daemon.clients.get(id); if (!client) return; this._logger.debug('tree-request', `Got TREE REQUEST`); try { let relayId = uuid.v1(); let timer, onResponse; let reply = (value, tree) => { if (timer) { clearTimeout(timer); timer = null; } if (onResponse) this.tracker.removeListener('tree_response', onResponse); let reply = this.daemon.TreeResponse.create({ response: value, tree: tree, }); let relay = this.daemon.ServerMessage.create({ type: this.daemon.ServerMessage.Type.TREE_RESPONSE, treeResponse: reply, }); let data = this.daemon.ServerMessage.encode(relay).finish(); this._logger.debug('tree-request', `Sending TREE RESPONSE`); this.daemon.send(id, data); }; let server = this.tracker.getServer(message.treeRequest.trackerName); if (!server || !server.connected) return reply(this.daemon.TreeResponse.Result.NO_TRACKER); if (!server.registered) return reply(this.daemon.TreeResponse.Result.NOT_REGISTERED); onResponse = (name, response) => { if (response.messageId !== relayId) return; this._logger.debug('tree-request', `Got TREE RESPONSE from tracker`); reply(response.treeResponse.response, response.treeResponse.tree); }; this.tracker.on('tree_response', onResponse); timer = setTimeout( () => reply(this.daemon.TreeResponse.Result.TIMEOUT), this.daemon.constructor.requestTimeout ); let request = this.tracker.TreeRequest.create({ daemonName: message.treeRequest.daemonName, path: message.treeRequest.path, }); let relay = this.tracker.ClientMessage.create({ type: this.tracker.ClientMessage.Type.TREE_REQUEST, messageId: relayId, treeRequest: request, }); let data = this.tracker.ClientMessage.encode(relay).finish(); this.tracker.send(message.treeRequest.trackerName, data); } catch (error) { this._logger.error(new NError(error, 'TreeRequest.handle()')); } } }
JavaScript
class TestAppender { debug(args) { } info(args){} warn(args){} error(args){} }
JavaScript
class RingAlertForm extends api.exported.FormObject.class { /** * Constructor * * @param {number} id The identifier * @param {objects} radioEvents The radio events * @param {objects} cameras The cameras * @returns {RingAlertForm} The instance */ constructor(id, radioEvents, cameras) { super(id); /** * @Property("radioEvents"); * @Type("objects"); * @Cl("RadioScenarioForm"); * @Title("ring.alert.radio.events"); */ this.radioEvents = radioEvents; /** * @Property("cameras"); * @Type("objects"); * @Cl("CamerasListForm"); * @Title("ring.alert.cameras"); */ this.cameras = cameras; } /** * Convert a json object to TrashReminderSubform object * * @param {object} data Some data * @returns {RingAlertForm} An instance */ json(data) { return new RingAlertForm(data.id, data.radioEvents, data.cameras); } }
JavaScript
class RingAlert { /** * Constructor * * @param {PluginAPI} api The core APIs * * @returns {RingAlert} The instance */ constructor(api) { this.api = api; this.start(); const self = this; this.api.configurationAPI.setUpdateCb(() => { self.start(); }); } /** * Start the listener */ start() { const self = this; const radioCb = (radioObject) => { const config = self.api.configurationAPI.getConfiguration(); let detected = false; if (config && config.radioEvents && config.radioEvents.length > 0) { config.radioEvents.forEach((radioFormObject) => { if (self.api.radioAPI.compareFormObject(radioFormObject, radioObject)) { detected = true; } }); } if (detected) { self.api.messageAPI.sendMessage("*", self.api.translateAPI.t("ring.alert.message")); if (config && config.cameras && config.cameras.length > 0) { config.cameras.forEach((cameraId) => { self.api.cameraAPI.getImage(cameraId.identifier, (err, data) => { if (!err && data) { self.api.messageAPI.sendMessage("*", null, "cameras", null, data.toString("base64")); } }); }); } } }; this.api.radioAPI.unregister(radioCb, "ring-alert"); this.api.radioAPI.register(radioCb, "ring-alert"); } }
JavaScript
class KostalPikoBA extends utils.Adapter { /**************************************************************************************** * @param {Partial<utils.AdapterOptions>} [options={}] */ constructor(options) { super({ ...options, name: 'kostal-piko-ba' }); this.on('ready', this.onReady.bind(this)); // this.on('objectChange', this.onObjectChange.bind(this)); // this.on('stateChange', this.onStateChange.bind(this)); // this.on('message', this.onMessage.bind(this)); this.on('unload', this.onUnload.bind(this)); } /**************************************************************************************** * Is called when databases are connected and adapter received configuration. */ async onReady() { if (!this.config.ipaddress) { this.log.error('Kostal Piko IP address not set'); } else { this.log.info(`IP address found in config: ${this.config.ipaddress}`); } if (!this.config.polltimelive) { this.config.polltimelive = 10000; this.log.warn(`Polltime not set or zero - will be set to ${(this.config.polltimelive / 1000)} seconds`); } this.log.info(`Polltime set to: ${(this.config.polltimelive / 1000)} seconds`); if (!this.config.polltimedaily) { this.config.polltimedaily = 60000; this.log.warn(`Polltime statistics data not set or zero - will be set to ${(this.config.polltimedaily / 1000)} seconds`); } this.log.info(`Polltime daily statistics set to: ${(this.config.polltimedaily / 1000)} seconds`); if (!this.config.polltimetotal) { this.config.polltimetotal = 200000; this.log.warn(`Polltime alltime statistics not set or zero - will be set to ${(this.config.polltimetotal / 1000)} seconds`); } this.log.info(`Polltime alltime statistics set to: ${(this.config.polltimetotal / 1000)} seconds`); //sentry.io ping /* if (this.supportsFeature && this.supportsFeature('PLUGINS')) { const sentryInstance = this.getPluginInstance('sentry'); if (sentryInstance) { const Sentry = sentryInstance.getSentryObject(); Sentry && Sentry.withScope(scope => { scope.setLevel('info'); scope.setExtra('key', 'value'); Sentry.captureMessage('Adapter started', 'info'); // Level "info" }); } } */ // this.subscribeStates('*'); // all states changes inside the adapters namespace are subscribed if (this.config.ipaddress) { KostalRequest = `http://${this.config.ipaddress}/api/dxs.json` + `?dxsEntries=${ID_Power_SolarDC }&dxsEntries=${ID_Power_GridAC }` + `&dxsEntries=${ID_Power_DC1Power }&dxsEntries=${ID_Power_DC1Current }` + `&dxsEntries=${ID_Power_DC1Voltage }&dxsEntries=${ID_Power_DC2Power }` + `&dxsEntries=${ID_Power_DC2Current }&dxsEntries=${ID_Power_DC2Voltage }` + `&dxsEntries=${ID_Power_DC3Power }&dxsEntries=${ID_Power_DC3Current }` + `&dxsEntries=${ID_Power_DC3Voltage }` + `&dxsEntries=${ID_Power_SelfConsumption}&dxsEntries=${ID_Power_HouseConsumption}` + `&dxsEntries=${ID_OperatingState }` + `&dxsEntries=${ID_BatTemperature }&dxsEntries=${ID_BatStateOfCharge }` + `&dxsEntries=${ID_BatCurrent }&dxsEntries=${ID_BatCurrentDir }` + `&dxsEntries=${ID_GridLimitation }`; KostalRequestDay = `http://${this.config.ipaddress}/api/dxs.json` + `?dxsEntries=${ID_StatDay_SelfConsumption}&dxsEntries=${ID_StatDay_SelfConsumptionRate}` + `&dxsEntries=${ID_StatDay_Yield }&dxsEntries=${ID_StatDay_HouseConsumption }` + `&dxsEntries=${ID_StatDay_Autarky }`; KostalRequestTotal = `http://${this.config.ipaddress}/api/dxs.json` + `?dxsEntries=${ID_StatTot_SelfConsumption}&dxsEntries=${ID_StatTot_SelfConsumptionRate}` + `&dxsEntries=${ID_StatTot_Yield }&dxsEntries=${ID_StatTot_HouseConsumption }` + `&dxsEntries=${ID_StatTot_Autarky }&dxsEntries=${ID_StatTot_OperatingTime }` + `&dxsEntries=${ID_BatChargeCycles}`; this.log.debug('OnReady done'); await this.ReadPikoTotal(); await this.ReadPikoDaily(); await this.Scheduler(); this.log.debug('Initial ReadPiko done'); } else { this.stop; } } /**************************************************************************************** * Is called when adapter shuts down - callback has to be called under any circumstances! * @param {() => void} callback */ onUnload(callback) { try { clearTimeout(adapterIntervals.live); clearTimeout(adapterIntervals.daily); clearTimeout(adapterIntervals.total); Object.keys(adapterIntervals).forEach(interval => clearInterval(adapterIntervals[interval])); this.log.info('Adapter Kostal-Piko-BA cleaned up everything...'); callback(); } catch (e) { callback(); } } /**************************************************************************************** * Scheduler */ Scheduler() { this.ReadPiko(); try { clearTimeout(adapterIntervals.live); adapterIntervals.live = setTimeout(this.Scheduler.bind(this), this.config.polltimelive); } catch (e) { this.log.error(`Error in setting adapter schedule: ${e}`); this.restart; } } /**************************************************************************************** * ReadPiko */ ReadPiko() { var got = require('got'); (async () => { try { // @ts-ignore got is valid var response = await got(KostalRequest); if (!response.error && response.statusCode == 200) { var result = await JSON.parse(response.body).dxsEntries; this.setStateAsync('Power.SolarDC', { val: Math.round(result[0].value), ack: true }); this.setStateAsync('Power.GridAC', { val: Math.round(result[1].value), ack: true }); this.setStateAsync('Power.DC1Power', { val: Math.round(result[2].value), ack: true }); this.setStateAsync('Power.DC1Current', { val: (Math.round(1000 * result[3].value)) / 1000, ack: true }); this.setStateAsync('Power.DC1Voltage', { val: Math.round(result[4].value), ack: true }); this.setStateAsync('Power.DC2Power', { val: Math.round(result[5].value), ack: true }); this.setStateAsync('Power.DC2Current', { val: (Math.round(1000 * result[6].value)) / 1000, ack: true }); this.setStateAsync('Power.DC2Voltage', { val: Math.round(result[7].value), ack: true }); this.setStateAsync('Power.DC3Power', { val: Math.round(result[8].value), ack: true }); this.setStateAsync('Power.DC3Current', { val: (Math.round(1000 * result[9].value)) / 1000, ack: true }); this.setStateAsync('Power.DC3Voltage', { val: Math.round(result[10].value), ack: true }); this.setStateAsync('Power.SelfConsumption', { val: Math.round(result[11].value), ack: true }); this.setStateAsync('Power.HouseConsumption', { val: Math.floor(result[12].value), ack: true }); this.setStateAsync('State', { val: result[13].value, ack: true }); this.setStateAsync('Battery.Temperature', { val: result[14].value, ack: true }); this.setStateAsync('Battery.SoC', { val: result[15].value, ack: true }); if (result[17].value) { // result[8] = 'Battery current direction; 1=Load; 0=Unload' this.setStateAsync('Battery.Current', { val: result[16].value, ack: true}); } else { // discharge this.setStateAsync('Battery.Current', { val: result[16].value * -1, ack: true}); } this.setStateAsync('Power.Surplus', { val: Math.round(result[1].value - result[11].value), ack: true }); this.setStateAsync('GridLimitation', { val: result[18].value, ack: true }); this.log.debug('Piko-BA live data updated'); } else { this.log.error(`Error: ${response.error} by polling Piko-BA: ${KostalRequest}`); } } catch (e) { this.log.error(`Error in calling Piko API: ${e}`); this.log.error(`Please verify IP address: ${this.config.ipaddress} !!!`); } // END try catch }) (); } // END ReadPiko /**************************************************************************************** * ReadPikoDaily */ ReadPikoDaily() { var got = require('got'); (async () => { try { // @ts-ignore got is valid var response = await got(KostalRequestDay); if (!response.error && response.statusCode == 200) { var result = await JSON.parse(response.body).dxsEntries; this.setStateAsync('Statistics_Daily.SelfConsumption', { val: Math.round(result[0].value) / 1000, ack: true }); this.setStateAsync('Statistics_Daily.SelfConsumptionRate', { val: Math.round(result[1].value), ack: true }); this.setStateAsync('Statistics_Daily.Yield', { val: Math.round(result[2].value) / 1000, ack: true }); this.setStateAsync('Statistics_Daily.HouseConsumption', { val: Math.round(result[3].value) / 1000, ack: true }); this.setStateAsync('Statistics_Daily.Autarky', { val: Math.round(result[4].value), ack: true }); this.log.debug('Piko-BA daily data updated'); } else { this.log.error(`Error: ${response.error} by polling Piko-BA: ${KostalRequest}`); } } catch (e) { this.log.error(`Error in calling Piko API: ${e}`); this.log.error(`Please verify IP address: ${this.config.ipaddress} !!!`); } // END try catch clearTimeout(adapterIntervals.daily); adapterIntervals.daily = setTimeout(this.ReadPikoDaily.bind(this), this.config.polltimedaily); })(); } // END ReadPikoDaily /**************************************************************************************** * ReadPikoTotal * */ ReadPikoTotal() { var got = require('got'); (async () => { try { // @ts-ignore got is valid var response = await got(KostalRequestTotal); if (!response.error && response.statusCode == 200) { var result = await JSON.parse(response.body).dxsEntries; this.setStateAsync('Statistics_Total.SelfConsumption', { val: Math.round(result[0].value), ack: true }); this.setStateAsync('Statistics_Total.SelfConsumptionRate', { val: Math.round(result[1].value), ack: true }); this.setStateAsync('Statistics_Total.Yield', { val: Math.round(result[2].value), ack: true }); this.setStateAsync('Statistics_Total.HouseConsumption', { val: Math.round(result[3].value), ack: true }); this.setStateAsync('Statistics_Total.Autarky', { val: Math.round(result[4].value), ack: true }); this.setStateAsync('Statistics_Total.OperatingTime', { val: result[5].value, ack: true }); this.setStateAsync('Battery.ChargeCycles', { val: result[6].value, ack: true }); this.log.debug('Piko-BA lifetime data updated'); } else { this.log.error(`Error: ${response.error} by polling Piko-BA: ${KostalRequest}`); } } catch (e) { this.log.error(`Error in calling Piko API: ${e}`); this.log.error(`Please verify IP address: ${this.config.ipaddress} !!!`); } // END try catch })(); clearTimeout(adapterIntervals.total); adapterIntervals.total = setTimeout(this.ReadPikoTotal.bind(this), this.config.polltimetotal); } // END ReadPikoTotal } // END Class
JavaScript
class AccessTokens { /** * Refresh - Gets new access token * @param {object} req * @param {object} res * @returns {object} */ static refresh(req, res) { const refreshToken = req.body.refresh_token; client.get(refreshToken, (error, response) => { if (response != null) { if (!JSON.parse(response).refresh_token) return res.status(404).json({ error: 'No refresh token found' }); jwt.verify(JSON.parse(response).refresh_token, process.env.JWT_REFRESH_TOKEN, (err, authToken) => { if (err) { return res.status(401).json({ message: 'Refresh Token is Invalid' }); } else { const userData = jwt.decode(JSON.parse(response).refresh_token); const newAccessToken = jwt.sign({ id: userData.id, name: userData.name, email: userData.email }, process.env.JWT_ACCESS_TOKEN, { expiresIn: 600 }); client.set(refreshToken, JSON.stringify({ jwt: newAccessToken, refresh_token: refreshToken })); return res.status(200).json({ jwt: newAccessToken }); } }); } else { return res.status(404).json({ error: 'No token found!' }); } }); } /** * login - Authenticates already existing user * @param {object} req * @param {object} res * @returns {object} */ static login(req, res) { const { email, password } = req.body; User.findOne({ email }, (error, user) => { if (error) return res.status(500).json({ error: 'There seems to be some issue. Try agin!' }); if (user === null) return res.status(401).json({ error: 'User does not exist' }); const validPassword = bcrypt.compareSync(password, user.password); if (!validPassword) return res.status(401).json({ error: 'User does not exits' }); const token = jwt.sign({ id: user._id, name: user.name, email: user.email }, process.env.JWT_ACCESS_TOKEN, { expiresIn: 600 }); const refresh_token = jwt.sign({ id: user._id, name: user.name, email: user.email }, process.env.JWT_REFRESH_TOKEN, { expiresIn: 86400 }); const response = { jwt: token, refresh_token }; client.set(refresh_token, JSON.stringify(response)); return res.status(201).json(response); }); } /** * logout - Removes authentication token for a user * @param {object} req * @param {object} res * @returns {object} */ static logout(req, res) { client.get(req.body.refresh_token, (error, response) => { if (response != null) { if (!JSON.parse(response).refresh_token) return res.status(404).json({ error: 'No refresh token found' }); jwt.verify(JSON.parse(response).refresh_token, process.env.JWT_REFRESH_TOKEN, (err, authToken) => { if (err) { return res.status(401).json({ message: 'Refresh Token is Invalid' }); } else { client.del(req.body.refresh_token, (error, response) => { if (response === 1) { delete req.headers['x-access-token']; return res.status(204).json({}) } else { return res.status(200).json({ message: 'User not logged out '}); } }); } }); } else { return res.status(404).json({ error: 'No token found! '}); } }); } }
JavaScript
class SCJukebox{ constructor(id){ this.id = id ; this.playlist = []; // var currentTrack = 0; } initSC(){ SC.initialize({ client_id: 'ebe2d1362a92fc057ac484fcfb265049' // client_id: this.id }); } // 336768726 getTrackById(id){ console.log(id); // var id = this.value; var promise = new Promise(function(resolve, reject){ SC.get('/tracks/'+ id ).then(function(response) { console.log(response); resolve(response); }); }); return promise; } getTracksByTerm(term){ // if(this.playedOnce > 0){ // document.getElementById('songs-div').remove(); // } else { // this.playedOnce++ // } var promise = new Promise(function(resolve, reject){ SC.get('/tracks', { q: term }).then(function(response){ var tracks = []; console.log(tracks); response.forEach(function(cur){ tracks.push(cur); }); resolve(tracks); }); }); return promise; } getPlaylist(){ return this.playlist; } setPlaylist(arr){ for (var i=0; i<arr.length; i++){ this.playlist.push(arr[i]); } } streamById(trackId){ SC.stream('/tracks/' + trackId).then(function(player) { console.log(player); player.play(); document.getElementById('play').addEventListener('click', function(){ console.log(trackId); player.play(); }); document.getElementById('pause').addEventListener('click', function(){ player.pause(); }); document.getElementById('stop').addEventListener('click', function(){ player.pause(); player.seek(0); }); // player.on('finish', function(){ // currentTrack += 1 // getTrackById(id); // }); }); } displaySongsResult(song){ document.getElementById('playlist').innerHTML = song.title; // document.getElementById('artwork').src = tracks[current].artwork_url || 'http://' + q + '.jpg.to' } } //end class
JavaScript
class Phrase { constructor(phrase) { this.phrase = phrase.toLowerCase(); this.splitPhrase = this.phrase.split(''); this.phraseNoSpaces = this.phrase.replace(/ /g, '') this.phraseDiv = document.getElementById('phrase'); this.ul = this.phraseDiv.firstElementChild this.liList = this.ul.children; } // adds the created phrase to the game board addPhraseToDisplay() { this.splitPhrase.forEach(letter => { const li = document.createElement('li') if (letter === ' ') { li.classList = 'space'; } else { li.classList = `hide letter ${letter}` } li.innerHTML = `${letter}`; this.ul.appendChild(li) }); } // checks if guessed letter is present in activePhrase checkLetter(letter) { if (letter === '' || letter === ' ') { console.log('please guess a letter') return false } else if (this.phrase.includes(letter)) { return true } else { return false } } // reveals letter in gameboard. showMatchedLetter(guess) { [...this.liList].forEach(li => { if (li.textContent === guess) { li.className = `show letter ${guess}` } }) } }
JavaScript
class QuizQuestion { /** * Constructor for a question object * @param {string} url */ constructor (url) { this.questionUrl = url this.question = this.getQuestion() this.answerUrl this.response this.alternatives } /** * @returns {string} question itself */ async getQuestion () { const response = await fetch(this.questionUrl) const responseBody = await response.json() if (responseBody.alternatives) { this.alternatives = responseBody.alternatives } this.answerUrl = responseBody.nextURL return responseBody.question } /** * Send answer to question, return result in JSON * @param {string} answerString * @returns {JSON} */ async sendAnswer (answerString) { const response = await fetch(this.answerUrl, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ answer: answerString }) }) const responseBody = await response.json() return responseBody } }
JavaScript
class PrimitiveFieldCtrl { constructor($scope, FieldService, SharedSpaceToolbarService) { 'ngInject'; this.$scope = $scope; this.FieldService = FieldService; this.SharedSpaceToolbarService = SharedSpaceToolbarService; } $onChanges(changes) { if (changes.fieldValues) { this._onFieldValuesChanged(changes.fieldValues.currentValue); } } _onFieldValuesChanged(fieldValues) { delete this.firstServerError; fieldValues.forEach((value, index) => { const field = this.form[this.getFieldName(index)]; if (!field) { return; } const isValid = !value.errorInfo || !value.errorInfo.message; field.$setValidity('server', isValid); if (!isValid) { field.$setTouched(); } if (!isValid && !this.firstServerError) { this.firstServerError = value.errorInfo.message; } }); } getFieldName(index) { const fieldName = this.name ? `${this.name}/${this.fieldType.id}` : this.fieldType.id; return index > 0 ? `${fieldName}[${index + 1}]` : fieldName; } getFieldError() { let combinedError = null; this.fieldValues.forEach((value, index) => { const fieldName = this.getFieldName(index); const field = this.form[fieldName]; if (field) { combinedError = Object.assign(combinedError || {}, field.$error); } }); return combinedError; } isValid() { return !this.fieldValues.some((fieldValue, index) => { const fieldName = this.getFieldName(index); const field = this.form[fieldName]; return field && field.$invalid && field.$touched; }); } onLabelClick($event) { this.$scope.$broadcast('primitive-field:focus', $event); } focusPrimitive($event = null) { this.hasFocus = true; this.onFieldFocus(); this.oldValues = angular.copy(this.fieldValues); this.FieldService.unsetFocusedInput(); if ($event) { $event.target = angular.element($event.target); this.FieldService.setFocusedInput($event.target, $event.customFocus); } } blurPrimitive($event = null) { if ($event) { $event.target = angular.element($event.relatedTarget); if (this.FieldService.shouldPreserveFocus($event.target)) { this.FieldService.triggerInputFocus(); return; } } delete this.hasFocus; this.onFieldBlur(); this._saveField(); } valueChanged() { this._saveField({ throttle: true }); } _saveField(options) { if (!angular.equals( this.FieldService.cleanValues(this.oldValues), this.FieldService.cleanValues(this.fieldValues), )) { this.FieldService.save({ ...options, name: this.getFieldName(), values: this.fieldValues, }).then(this._afterSaveField.bind(this)); } } _afterSaveField(validatedValues) { let errorsChanged = false; validatedValues.forEach((validatedValue, index) => { const currentValue = this.fieldValues[index]; const field = this.form[this.getFieldName(index)]; if (field) { field.$setTouched(); } if (validatedValue.errorInfo && !currentValue.errorInfo) { currentValue.errorInfo = validatedValue.errorInfo; errorsChanged = true; } if (!validatedValue.errorInfo && currentValue.errorInfo) { delete currentValue.errorInfo; errorsChanged = true; } }); if (errorsChanged) { this._onFieldValuesChanged(this.fieldValues); } } }