language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Signup extends Component { constructor(props){ super(props); this.state={ // isModalOpen:false, redirectToReferrer:false } this.handleSignup = this.handleSignup.bind(this); } handleSignup() { // this.toggleModal(); this.props.signupUser({username: this.username.value, password: this.password.value,firstname: this.firstname.value,lastname: this.lastname.value}); // event.preventDefault(); this.setState({redirectToReferrer:true}) alert("You have succesfully registered") } render() { const redirectToReferrer = this.state.redirectToReferrer; if (redirectToReferrer === true) { return <Redirect to="/home" /> } else return ( <div className="col-12 col-md-3 mx-auto" style={{margin:'50px',border:'solid black 1px',padding:'15px',borderRadius:'20px'}}> <h3>Signup</h3> <hr /> <Form onSubmit={this.handleSignup}> <FormGroup> <Label htmlFor="username">Username</Label> <Input type="text" id="username" name="username" innerRef={(input) => this.username = input} required /> </FormGroup> <FormGroup> <Label htmlFor="password">Password</Label> <Input type="password" id="password" name="password" innerRef={(input) => this.password = input} required /> </FormGroup> <FormGroup> <Label htmlFor="firstname">First Name</Label> <Input type="text" id="firstname" name="firstname" innerRef={(input) => this.firstname = input} required /> </FormGroup> <FormGroup> <Label htmlFor="lastname">Last Name</Label> <Input type="text" id="lastname" name="lastname" innerRef={(input) => this.lastname = input} required /> </FormGroup> <Button type="submit" to="/home" value="submit" color="primary">Signup</Button> </Form> </div> ); } }
JavaScript
class RequestedWatchlistScreeningConfig { /** * @param {string[]} categories * The list of categories corresponding to each watchlist screening conducted */ constructor(categories) { if (categories) { Validation.isArrayOfStrings(categories, 'categories'); this.categories = categories.filter((elem, pos) => categories.indexOf(elem) === pos); } } /** * @returns {Object} data for JSON.stringify() */ toJSON() { return { categories: this.categories, }; } }
JavaScript
class UIMain extends PRuntime { /** * Link the View engine to the application engine. * * @param {PEngine} engine The engine reference. */ use(engine) { if (puzzle.config.views.enabled) { this.init(engine); puzzle.modules.register("views", this); } } /** * Initializes the ui system. * * @param {PEngine} engine The engine reference. */ init(engine) { const config = engine.config.views; /** * Various path lists that are used by the view engine. * * @protected * @member {Object} */ this._paths = { views: [ this._pathResolve(config.views) ], partials: [ this._pathResolve(config.partials) ] }; /** * Reference to handlebars instance. * * @alias puzzle.handlebars; * @type {handlebars} */ engine.set("handlebars", handlebars); /** * View configuration object. * * Using this object you can add paths to view/partials array. * * @alias puzzle.viewConfig; * @type {Object} */ engine.set("viewConfig", { view: (viewPath) => { this._paths.views.push(this._pathResolve(viewPath)); }, partials: (partialPath) => { this._paths.partials.push(this._pathResolve(partialPath)); } }); } /** * Performs some actions. */ online() { if (!puzzle.config.views.enabled) { return; } const { http, config } = puzzle; http.engine("hbs", hbs.express4({ partialsDir: this._paths.partials, defaultLayout: this._pathResolve(config.views.defaultLayout), extname: ".hbs", handlebars, i18n: puzzle.i18n, layoutsDir: this._pathResolve(config.views.layouts), beautify: true, })); http.set("view engine", "hbs"); http.set("views", this._paths.views); http.use(URLBuilder("/"), express.static(this._pathResolve(config.views.publicContent))); } /** * Resolves the path to the given folder path. * * @protected * @param {string} folderPath The path to be resolved. * * @return {string} */ _pathResolve(folderPath) { return path.resolve(folderPath); } }
JavaScript
class EventEmitter { /** * @constructor */ constructor() { let eventListeners_ = {}; /** * Emits an event, calling specified previously event listener * @param {Object} event Event */ this.dispatch = (event) => { if (eventListeners_[event.type]) { for(let callback of eventListeners_[event.type]) { callback({ data: event.data || null, type: event.type }); } } }; /** * Adds listener for event with specified callback * @param {String} eventType Event name * @param {Function} callback Function that will be executed when event is fired */ this.addEventListener = (eventType, callback) => { if (!eventListeners_[eventType]) { eventListeners_[eventType] = []; } eventListeners_[eventType].push(callback); }; /** * Removes callback for target event * @param {String} eventType Event name * @param {Function} callback Function that will be removed */ this.removeEventListener = (eventType, callback) => { if (!eventListeners_[eventType]) { return; } eventListeners_[eventType] = eventListeners_[eventType].filter((listener) => { return listener !== callback; }); }; /** * Removes all callbacks for target event * @param {String} eventType Event name */ this.removeEventListeners = (eventType) => { eventListeners_[eventType] = []; }; } }
JavaScript
class MockedHtml { /** * constructor. Takes no options. Establishes a dictionary with key * selector text and value the callback function */ constructor() { this._activeListeners = {}; this.mockedValues = {}; } /** * find. Takes a selector and primes it for the click event. Returns * a mocked selector, which is tied to this._activeListeners using * the same selector text. * @param {string} selectorText Selector text for the new listener * @return {Object} The mocked page element */ find(selectorText) { const mockedValue = (selectorText in this.mockedValues) ? this.mockedValues[selectorText] : null; if (selectorText in this._activeListeners) { return this._activeListeners[selectorText]; } const pageElement = new MockPageElement(selectorText, mockedValue); this._activeListeners[selectorText] = pageElement; return pageElement; } }
JavaScript
class FollowField { constructor(flowField) { this._flowField = flowField; this._lookAhead = 50; } run(vehicle) { let prediction = p5.Vector.normalize(vehicle.velocity) .mult(this._lookAhead).add(vehicle.position); let flow = this._flowField.calcFlow(prediction).copy(); if (flow.mag() == 0) return flow; return flow.setMag(vehicle.maxSpeed).sub(vehicle.velocity).limit(vehicle.maxForce); } lookAhead(value) { this._lookAhead = value; return this; } }
JavaScript
class CELVisitor extends antlr4.tree.ParseTreeVisitor { // Visit a parse tree produced by CELParser#start. visitStart(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#expr. visitExpr(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#conditionalOr. visitConditionalOr(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#conditionalAnd. visitConditionalAnd(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#relation. visitRelation(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#calc. visitCalc(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#MemberExpr. visitMemberExpr(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#LogicalNot. visitLogicalNot(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#Negate. visitNegate(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#SelectOrCall. visitSelectOrCall(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#PrimaryExpr. visitPrimaryExpr(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#Index. visitIndex(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#CreateMessage. visitCreateMessage(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#IdentOrGlobalCall. visitIdentOrGlobalCall(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#Nested. visitNested(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#CreateList. visitCreateList(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#CreateStruct. visitCreateStruct(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#ConstantLiteral. visitConstantLiteral(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#exprList. visitExprList(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#fieldInitializerList. visitFieldInitializerList(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#mapInitializerList. visitMapInitializerList(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#Int. visitInt(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#Uint. visitUint(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#Double. visitDouble(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#String. visitString(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#Bytes. visitBytes(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#BoolTrue. visitBoolTrue(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#BoolFalse. visitBoolFalse(ctx) { return this.visitChildren(ctx); } // Visit a parse tree produced by CELParser#Null. visitNull(ctx) { return this.visitChildren(ctx); } }
JavaScript
class ContainerCreator { constructor(auth, stream) { // poll redis here. this._redis = Redis(); this._auth = auth; this._cache = {}; if(stream) { debug('constructor', 'set to to stream changes instead of poll'); this._stream = true; this._pub = Redis(); } } /** * Streams changes **/ stream() { this._redis.subscribe('NewWorkspace', 'WorkspaceConflict', (err, count) => { debug('stream', 'sub to', count, 'channels'); }) this._redis.on('message', (channel, msg) => { let data; try { data = JSON.parse(msg); } catch(e) { debug('stream:message', 'failed to parse msg as JSON'); return; } let username = data.username; if(!username) return debug('stream:message', 'invalid username:', username); debug('stream:process', channel, username, data); // write it to our cache. this._writeToCache(username, data); debug('stream:message', 'processed event type:', channel) }) } /** * Return a containers object. * * @param {String} username - username of owner of wanted container. * @param {Function} done - callback. **/ fetch(username, done) { if(!done) return false; if(!this._stream) return this._pullFromRedis(username, done); return this._pullFromCache(username, done); } /** * Pull from our internal cache. **/ _pullFromCache(username, done) { if(!this._cache[username]) return this._pullFromRedis(username, done); return done(this._cache[username]); } /** * Write user info to cache * @todo data checks. **/ _writeToCache(username, data) { debug('cache:write', username, 'success'); this._cache[username] = data; } /** * Internal function to just pull from redis. **/ _pullFromRedis(username, done) { this._pub.get(username, (err, res) => { if(err) { debug('redis:pull', err); } if(!res) { // fetch from database instead. debug('redis:pull', 'invalid res, pulling from DB', res) return this._pullFromDatabase(username, done); } debug('redis:pull', 'success') // regardless of op mode, store in cache. let data = JSON.parse(res); this._writeToCache(username, data); return done(data); }) } /** * Internal method of pulling from database. * * @param {String} username - username of owner of wanted container * @param {Function} done - callback. **/ _pullFromDatabase(username, done) { this._auth.getUserObject(username) .then(user => { debug('_pullFromDatabase', 'got user object'); debug('_pullFromDatabase', user) if(!user) return done('invalid container response'); if(!user.docker) { user.docker = { ip: null } } let cont = user.docker; cont.auth = user.api.public+':'+user.api.secret; debug('db:pull', cont); // fix API results. if(!cont.username) { cont.username = username; } let cont_str; try { cont_str = JSON.stringify(cont) } catch(e) { return debug('pull:db:parse', 'failed to stringify as JSON'); } // if streaming, publish the NewWorkspace event. if(this._stream) { this._pub.publish('NewWorkspace', cont_str); this._pub.set(username, cont_str); } else { this._redis.set(username, cont_str); } return done(cont); }) .catch(err => { return done(err); }) } }
JavaScript
class Initialization { constructor() { this.BASEURL = $('#baseurl').html(); window.onload = this.onLoad(); window.onresize = () => { // on resize events } } onLoad() { /** * INITIALIZATION */ //remove preloader $('.page-preloader').remove(); $('body').removeClass('loading'); //Initialize Foundation $(document).foundation(); /** * EXTERNAL CLASSES * * if(element.length){ * new ClassName(element); * } * **/ } }
JavaScript
class SumObserverMetric extends BaseObserverMetric_1.BaseObserverMetric { constructor(name, options, processor, resource, instrumentationLibrary, callback) { super(name, options, processor, resource, types_1.MetricKind.SUM_OBSERVER, instrumentationLibrary, callback); } _processResults(observerResult) { observerResult.values.forEach((value, labels) => { const instrument = this.bind(labels); // SumObserver is monotonic which means it should only accept values // greater or equal then previous value const previous = instrument.getAggregator().toPoint(); let previousValue = -Infinity; if (previous.timestamp[0] !== 0 || previous.timestamp[1] !== 0) { previousValue = previous.value; } if (value >= previousValue) { instrument.update(value); } }); } }
JavaScript
class Counter extends Component { constructor () { super() this.state = { persons: [], value: 1 } this.handleClick = this.handleClick.bind(this) } handleClick () { console.log('Success!') axios.get(`https://jsonplaceholder.typicode.com/users`) .then(res => { const persons = res.data; this.setState({ persons }); }) } render() { return ( <div> <h1>Hello - Welcome to Snehal's React training examples page</h1> <div className='button_container'> <button className='increment_button' onClick={() => { this.setState({ value: this.state.value + 1 }) }}>Increment</button> <span className='counter_span'>{ this.state.value }</span> <div> <button className='button' onClick={this.handleClick}>Get Users from https://jsonplaceholder.typicode.com/ mock REST API</button> </div> <div> <ul> { this.state.persons.map(person => <li>{person.name}</li>)} </ul> </div> </div> </div> ); } }
JavaScript
class EventProcessor { constructor() { this.reset(); } /** * Resets the current Combo */ reset() { this.currentCombo = new key_combo_1.KeyCombo(); } /** * Process a keyboardEvent */ processEvent(ev, actions, options) { const wasAppended = this.currentCombo.addEvent(ev); // Avoid repeated events if (!wasAppended) { return false; } const shouldProcess = !options.onlyStateCombos || options.onlyStateCombos && this.currentCombo.hasStateKeys(); if (shouldProcess) { if (options.debug) { this.printDebugKeyPressed(ev); } this.processActionCombos(ev, actions, options); } } /** * Resets the combo and prints debug output */ cleanCombo(options) { this.reset(); if (options.debug) { utils_1.logger.log('ShortcutJS: Cleaned keyMap'); } } /** * Search for matching actions, given a keyCombo, and execute its callbacks */ processActionCombos(ev, actions, options) { for (let action of actions.values()) { if (this.matchesComboAction(action)) { if (options.debug) { this.printDebugActionFound(action); } if (options.preventDefault) { ev.preventDefault(); } for (let cb of action.callbacks) { cb(ev); } // Don't continue after finding it return false; } } } /** * Checks whether the currentCombo matches a particular action */ matchesComboAction(action) { return key_combo_1.KeyCombo.isEqual(this.currentCombo, action.keyCombo); } /** * Prints keydown events */ printDebugKeyPressed(ev) { utils_1.logger.group('ShortcutJS: KeyPressed'); utils_1.logger.log('Key: ', ev.keyCode); utils_1.logger.group('Current combo:'); utils_1.logger.log('Keys: ', [...this.currentCombo.keys]); utils_1.logger.log('State keys: ', this.currentCombo.stateKeys); utils_1.logger.groupEnd(); utils_1.logger.groupEnd(); } /** * Prints when action matches */ printDebugActionFound(action) { utils_1.logger.group('%cShortcutJS: Action Matched', 'color: green'); utils_1.logger.log('Action: ', action.name); utils_1.logger.group('Current combo:'); utils_1.logger.log('Keys: ', [...this.currentCombo.keys]); utils_1.logger.log('State keys: ', this.currentCombo.stateKeys); utils_1.logger.groupEnd(); utils_1.logger.log(`${action.callbacks.size} callbacks found`); utils_1.logger.groupEnd(); } }
JavaScript
class ImportAndScopeChainBuilder extends ScopeChainBuilder { constructor(reporter) { super(reporter); this.imports = Object.create(null); } visitImportedBinding(tree) { var name = tree.binding.getStringValue(); this.imports[name] = tree; } }
JavaScript
class WrittenBuffer extends AsyncObject { constructor (buf, string, offset, length, encoding) { super(buf, string, offset || 0, length || buf.length - offset, encoding || 'utf8') } syncCall () { return (buf, string, offset, length, encoding) => { buf.write(string, offset, length, encoding) return buf } } }
JavaScript
class EntitySchemaReader { /** * * @param namingConvention */ constructor(namingConvention) { this.namingConvention = namingConvention; } /** * * @param Entity * @return {{table: String, fields: {}, primaryKey: string|null, eagerAggregations: {}, lazyAggregations: {}}} */ read(Entity) { let table = this.getTable(Entity); let fields = this.getFields(Entity, table); let foundPkFieldName = lodash.findKey(fields, metadata => metadata.type === PrimaryKey); let primaryKeyFieldWithoutTableName = null; if (foundPkFieldName) { primaryKeyFieldWithoutTableName = Reflect.getMetadata('gluon.entity.fields', Entity)[foundPkFieldName].name || this.namingConvention.columnNameFromFieldName(foundPkFieldName); } let aggregations = this.getAggregations(Entity, table, primaryKeyFieldWithoutTableName); let eagerKeys = Reflect.getMetadata('gluon.entity.eager', Entity) || []; return { table : table, fields : fields, primaryKey : foundPkFieldName ? fields[foundPkFieldName].name : null, eagerAggregations : lodash.pick(aggregations, eagerKeys), lazyAggregations : lodash.omit(aggregations, eagerKeys) }; } /** * * @param Entity * @return {*[]} */ getTable(Entity) { let entityTable = Reflect.getMetadata('gluon.entity', Entity); if (!entityTable) { entityTable = this.namingConvention.tableNameFromEntityName(Entity.name); } return entityTable; } /** * * @param Entity * @param tableName * @return {{}} */ getFields(Entity, tableName) { return lodash.mapValues( Reflect.getMetadata('gluon.entity.fields', Entity), (metaDescription, fieldName) => { let name = null; if (!(metaDescription.type.prototype instanceof PrimitiveType)) { name = this.getFields(metaDescription.type, tableName) } else if (!metaDescription.name) { name = tableName + '.' + this.namingConvention.columnNameFromFieldName(fieldName) } else { name = tableName + '.' + lodash.snakeCase(metaDescription.name); } return {...metaDescription, name: name}; } ); } /** * * * @param Entity * @param tableName * @param primaryKey * @return {{}} */ getAggregations(Entity, tableName, primaryKey) { let aggregations = Reflect.getMetadata('gluon.entity.aggregation', Entity) || {}; return lodash.mapValues(aggregations, metadata => { return { ...metadata, foreignKey: metadata.name || this.namingConvention.fkNameFromTableAndIdColumn(tableName, primaryKey), schema: this.read(metadata.entity) } }) } }
JavaScript
class JSCGuild extends Guild { /** * Creates a role. * @param {JSRoleOptions} options Options for the role. */ createRole(options = {}) { return this.roles.create({ data: { name: options.name, color: options.color, mentionable: options.mention, permissions: options.permissions, hoist: options.hoisted, position: options.position } }); }; /** * Returns a link for an embed with online members. */ get embedOnlineMembers() { return `https://img.shields.io/discord/${this.id}?color=7289da&logo=discord&logoColor=white` }; /** * Returns a better-looking region. */ get betterRegion() { let reg; if (this.region === "russia") { reg = 'Russia' } else if (this.region === 'hongkong') { reg = "Hong Kong" } else if (this.region === "brazil") { reg = 'Brazil' } else if (this.region === "europe") { reg = 'Europe' } else if (this.region === "sydney") { reg = 'Sydney' } else if (this.region === "southafrica") { reg = 'South Africa' } else if (this.region === "singapore") { reg = "Singapore" } else if (this.region === "us-south") { reg = "US South" } else if (this.region === "us-central") { reg = 'US Central' } else if (this.region === "us-west") { reg = 'US West' } else if (this.region === "us-east") { reg = 'US East' } else if (this.region === "india") { reg = "India" } else if (this.region === "japan") { reg = 'Japan' }; return reg; }; }
JavaScript
class Heap { /** * @constructor * * @param {Function} compareFn A Function used to order each item within the * Heap. * * @example * * const Heap = require('estructura/heap') * * const aHeap = new Heap() * * @example * * <caption> * Or supply your own comparison Function. * </caption> * * const Heap = require('estructura/heap') * * const aHeap = new Heap( * (itemA, itemB) => { * // return -1, 0 or +1 * } * ) */ constructor(compareFn = Comparator.compareFnAscending) { this.compareFn_ = compareFn this.heapData_ = [] this.size = 0 this.peekFront = this.peek } /** * Add an item to the Heap. * * `O(log n)` * * @param {*} aValue * * @return {Number} The new size of the Heap. * * @example * * const aHeap = new Heap() * * aHeap.push('John Doe') * >>> 1 */ push(aValue) { const heapData = this.heapData_, compareFn = this.compareFn_ heapData.push(aValue) // #.bubbleUp let idxNr = this.size, parentIdxNr while ((parentIdxNr = ((idxNr - 1) >> 1)) >= 0 && compareFn(heapData[parentIdxNr], aValue) > 0) { heapData[idxNr] = heapData[parentIdxNr] heapData[parentIdxNr] = aValue idxNr = parentIdxNr } return ++this.size } /** * `O(1)` * * @return {*} * * @example * * <caption> * Dependent on the used comparison `Function`. The default comparison `Function` * will sort in an ascending manner. * </caption> * * const aHeap = new Heap() * aHeap.push(4) * aHeap.push(2) * * aHeap.peek() * >>> 2 * * @alias peekFront */ peek() { return this.heapData_[0] } /** * `O(log n)` * * @return {*} * * @example * * <caption> * Based on the comparison `Function`. Return the `Min` or `Max` value within * the `Heap`. * </caption> * * const aHeap = new Heap() * aHeap.push(4) * aHeap.push(2) * * aHeap.pop() * >>> 2 */ pop() { if (this.size < 1) return undefined const heapData = this.heapData_ const heapSize = --this.size const retValue = heapData[0] const dwnValue = heapData.pop() if (heapSize < 1) return retValue heapData[0] = dwnValue const compareFn = this.compareFn_ // #.sinkDown let idxNr = 0, fChildIdxNr = (idxNr << 1) + 1, sChildIdxNr = fChildIdxNr + 1 while (fChildIdxNr < heapSize) { if (sChildIdxNr < heapSize && compareFn(heapData[fChildIdxNr], heapData[sChildIdxNr]) > 0) { fChildIdxNr = sChildIdxNr } if (compareFn(heapData[fChildIdxNr], dwnValue) <= 0) { heapData[idxNr] = heapData[fChildIdxNr] heapData[fChildIdxNr] = dwnValue } idxNr = fChildIdxNr, fChildIdxNr = (idxNr << 1) + 1, sChildIdxNr = fChildIdxNr + 1 } return retValue } /** * Turn the current Data Structure into an Array. * * @return {*} * * @example * * <caption> * Based on whether the current `Heap` is a `MinHeap` or `MaxHeap`. Take a look at * the comparison `Function`. * </caption> * * const aHeap = new Heap() * aHeap.push('A') * aHeap.push('B') * * aHeap.toArray() * >>> [ "A", "B" ] */ toArray() { const aHeap = this.constructor.fromHeap(this), heapData = [] while (aHeap.size) heapData.push( aHeap.pop() ) return heapData } /** * Create a Heap by giving an Array, Set or another Iterable. * * @param {Iterable} iterateOver * @param {Function} compareFn * * @return {Heap} * * @example * * const aHeap = Heap.from(['A', 'C', 'B', 'D']) * * @example * * <caption> * Or by supplying your own comparison `Function`. * </caption> * * const aHeap = Heap.from(['A', 'C', 'B', 'D'], * (itemA, itemB) => { * // return -1, 0 or +1 * } * ) */ static from(iterateOver, compareFn = Comparator.compareFnAscending) { const aHeap = new Heap(compareFn) for (const aValue of iterateOver) aHeap.push(aValue) return aHeap } /** * Create a copy of a Heap. * * @param {Heap} useHeap * * @return {Heap} * * @example * * const heapA = new Heap() * heapA.push('A') * heapA.push('C') * heapA.push('B') * heapA.push('D') * * const heapB = Heap.fromHeap(heapA) * heapB.push('F') * heapB.push('E') * * heapA.size * >>> 4 * * heapB.size * >>> 6 */ static fromHeap(useHeap) { const aHeap = new useHeap.constructor(null) // Copy the current `compareFn_`: aHeap.compareFn_ = useHeap.compareFn_ // Create a shallow copy and insert the `heapData_`: aHeap.heapData_ = useHeap.heapData_.slice() aHeap.size = useHeap.size return aHeap } }
JavaScript
class ChatSidebar extends Component { constructor(props) { super(props); this.handleRoomClick = this.handleRoomClick.bind(this); } /** * Open the clicked chat room * * @param {*} e * @param {*} param1 */ handleRoomClick(e, { roomid }) { const { socket, currentUser, users } = this.props; soa.openRoom( { socket, currentUserId: currentUser.id, roomId: roomid }, response => { if (response.success) { const { activeRoom, messages } = response.data; this.props.setMenuVisibility(false); const options = { room: activeRoom, messages }; //dynamically update the room name if it's a direct message if (activeRoom.group === "direct") { options.room = setDirectMessageName({ room: activeRoom, currentUser, users }); } this.props.openChatRoom(options); } } ); } renderUnreadMessagesLabel(unreadMessageCount) { if (unreadMessageCount === 0 || unreadMessageCount === undefined) { return null; } return ( <Label className="unread-messages-label" color="red"> {unreadMessageCount} </Label> ); } renderChannels() { const { rooms } = this.props; if (rooms.channels === undefined) { return; } return rooms.channels.map((roomId, index) => { const room = rooms[roomId]; return ( <Menu.Item className="sidebar-menu-item" key={room.id} roomid={room.id} icon="hashtag" name={room.name} onClick={this.handleRoomClick} /> ); }); } /** * TODO: update to render all users, but grey out the users who do not have a socketID meaning they aren't connected */ renderDirectMessages() { const { currentUser, rooms, users } = this.props; if (rooms.direct !== undefined) { /** * Only render the room if the current user is in the room */ return rooms.direct.map((roomId, index) => { const room = rooms[roomId]; const userId = room.users.find( (userId, index) => userId !== currentUser.id ); const user = users[userId]; const roomMetaKey = getRoomMetaKey(room.id); const roomMeta = currentUser.metaData[roomMetaKey] ? currentUser.metaData[roomMetaKey] : {}; return ( <React.Fragment key={room.id}> <Menu.Item id={room.id} className="sidebar-menu-item" roomid={room.id} name={user.name} roomname={user.name} onClick={this.handleRoomClick} > <Icon color={user.socketId ? "green" : null} name={user.socketId ? "circle" : "circle outline"} /> {user.name} {this.renderUnreadMessagesLabel(roomMeta.unreadMessageCount)} </Menu.Item> </React.Fragment> ); }); } } render() { const { currentUser } = this.props; const trigger = ( <span> <Icon color={currentUser.socketId ? "green" : null} name={currentUser.socketId ? "circle" : "circle outline"} /> {currentUser.name} {/* <Menu.Header as="h4">{currentUser.name}</Menu.Header> */} </span> ); return ( <div id="chat-sidebar"> <Menu.Item> <Menu.Header as="h2"> Channels <Popup position="bottom left" trigger={ <Button floated="right" size="large" className="sidebar-add-chat-btn" icon={ <Icon color="grey" name="add circle" className="sidebar-add-chat-icon" onClick={this.props.handleCreateChannelClick} /> } /> } content="Create a new channel" style={{ opacity: 0.9, padding: "2em", maxHeight: "60px" }} size="mini" inverted /> </Menu.Header> <Menu.Menu>{this.renderChannels()}</Menu.Menu> </Menu.Item> <Menu.Item> <Menu.Header as="h2"> Direct Messages <Popup trigger={ <Button floated="right" size="large" className="sidebar-add-chat-btn" icon={ <Icon name="add circle" className="sidebar-add-chat-icon" /> } onClick={this.props.handleAddDirectMessageClick} /> } content="Open a direct message" style={{ opacity: 0.9, padding: "2em", maxHeight: "60px" }} size="mini" inverted /> </Menu.Header> <Menu.Menu>{this.renderDirectMessages()}</Menu.Menu> </Menu.Item> </div> ); } }
JavaScript
class NotTask extends Task { /** * Creates a new Not task. * @param {Task} subtask - A subtasks to attempt to fail. */ constructor (subtask) { super('not') /** * The child subtask that should be attempted. * @type Task * @public * @readonly */ this.subtask = subtask } }
JavaScript
class QueryBuilder { constructor() { this.queryArr = []; return new Proxy(this, { get: (target, prop, receiver) => { if (target[prop]) { return Reflect.get(target, prop, receiver); } return target.builder[prop]; }, }); } /** * list all * @returns {Array} */ all() { return ['hema']; } /** * find specific item with ID * @param id * @returns {Object} */ find(id = '') { return { id }; } /** * filter the search results * @param filter * @returns {BaseComponent} */ filter(filter = '') { this.queryArr.push(`filter=${filter}`); return this; } /** * complete generating the final URL * @returns {string} */ prepareParams() { if (this.queryArr.length) { return `?${this.queryArr.join('&')}`; } return ''; } /** * fetch the results * @returns {Promise} */ get(customUrl = '', method = '') { // prepare url const params = this.prepareParams(); return new Promise((resolve, reject) => { const options = RequestOptions.prepare({ method: method || 'GET', url: `${this.options.baseUrl}/${customUrl || this.url}${params}`, token: this.options.token, }); this.http(options, (err, res, body) => { if (err) { return reject(err); } return resolve(JSON.parse(body)); }); }); } }
JavaScript
class DOMParseState { // : (Schema, Object, NodeBuilder) constructor(schema, options, top) { // : Object The options passed to this parse. this.options = options || {} // : Schema The schema that we are parsing into. this.schema = schema this.top = top // : [Mark] The current set of marks this.marks = noMarks // : bool Whether to preserve whitespace this.preserveWhitespace = this.options.preserveWhitespace this.info = schemaInfo(schema) this.onEnter = null this.find = options.findPositions } // : (Mark) → [Mark] // Add a mark to the current set of marks, return the old set. addMark(mark) { let old = this.marks this.marks = mark.addToSet(this.marks) return old } // : (DOMNode) // Add a DOM node to the content. Text is inserted as text node, // otherwise, the node is passed to `addElement` or, if it has a // `style` attribute, `addElementWithStyles`. addDOM(dom) { if (dom.nodeType == 3) { let value = dom.nodeValue let top = this.top if (/\S/.test(value) || top.type.isTextblock) { if (!this.preserveWhitespace) { value = value.replace(/\s+/g, " ") // If this starts with whitespace, and there is either no node // before it or a node that ends with whitespace, strip the // leading space. if (/^\s/.test(value)) top.stripTrailingSpace() } if (value) this.insertNode(this.schema.text(value, this.marks)) this.findInText(dom) } else { this.findInside(dom) } } else if (dom.nodeType == 1 && !dom.hasAttribute("pm-ignore")) { let style = dom.getAttribute("style") if (style) this.addElementWithStyles(parseStyles(style), dom) else this.addElement(dom) } } // : (DOMNode) // Try to find a handler for the given tag and use that to parse. If // none is found, the element's content nodes are added directly. addElement(dom) { let name = dom.nodeName.toLowerCase() if (listTags.hasOwnProperty(name)) this.normalizeList(dom) // Ignore trailing BR nodes, which browsers create during editing if (this.options.editableContent && name == "br" && !dom.nextSibling) return if (!this.parseNodeType(dom, name)) { if (ignoreTags.hasOwnProperty(name)) { this.findInside(dom) } else { let sync = blockTags.hasOwnProperty(name) && this.top this.addAll(dom) if (sync) this.sync(sync) } } } // Run any style parser associated with the node's styles. After // that, if no style parser suppressed the node's content, pass it // through to `addElement`. addElementWithStyles(styles, dom) { let oldMarks = this.marks, marks = this.marks for (let i = 0; i < styles.length; i += 2) { let result = matchStyle(this.info.styles, styles[i], styles[i + 1]) if (!result) continue if (result.attrs === false) return marks = result.type.create(result.attrs).addToSet(marks) } this.marks = marks this.addElement(dom) this.marks = oldMarks } // (DOMNode, string) → bool // Look up a handler for the given node. If none are found, return // false. Otherwise, apply it, use its return value to drive the way // the node's content is wrapped, and return true. parseNodeType(dom) { let result = matchTag(this.info.selectors, dom) if (!result) return false let isNode = result.type instanceof NodeType, sync, before if (isNode) sync = this.enter(result.type, result.attrs) else before = this.addMark(result.type.create(result.attrs)) let contentNode = dom, preserve = null, prevPreserve = this.preserveWhitespace if (result.content) { if (result.content.content === false) contentNode = null else if (result.content.content) contentNode = result.content.content preserve = result.content.preserveWhitespace } if (contentNode) { this.findAround(dom, contentNode, true) if (preserve != null) this.preserveWhitespace = preserve this.addAll(contentNode, sync) if (sync) this.sync(sync.prev) else if (before) this.marks = before if (preserve != null) this.preserveWhitespace = prevPreserve this.findAround(dom, contentNode, true) } else { this.findInside(parent) } return true } // : (DOMNode, ?NodeBuilder, ?number, ?number) // Add all child nodes between `startIndex` and `endIndex` (or the // whole node, if not given). If `sync` is passed, use it to // synchronize after every block element. addAll(parent, sync, startIndex, endIndex) { let index = startIndex || 0 for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) { this.findAtPoint(parent, index) this.addDOM(dom) if (sync && blockTags.hasOwnProperty(dom.nodeName.toLowerCase())) this.sync(sync) } this.findAtPoint(parent, index) } // : (Node) → ?Node // Try to insert the given node, adjusting the context when needed. insertNode(node) { let ok = this.top.findPlace(node.type, node.attrs, node) if (ok) { this.sync(ok) return true } } // : (NodeType, ?Object, [Node]) → ?Node // Insert a node of the given type, with the given content, based on // `dom`, at the current position in the document. insert(type, attrs, content) { let node = type.createAndFill(attrs, content, type.isInline ? this.marks : null) if (node) this.insertNode(node) } // : (NodeType, ?Object) → ?NodeBuilder // Try to start a node of the given type, adjusting the context when // necessary. enter(type, attrs) { if (this.onEnter) { let result = this.onEnter() if (result !== false) return result } let ok = this.top.findPlace(type, attrs) if (ok) { this.sync(ok) return ok } } // : () // Leave the node currently at the top. leave() { if (!this.preserveWhitespace) this.top.stripTrailingSpace() this.top = this.top.prev } sync(to) { for (;;) { for (let cur = to; cur; cur = cur.prev) if (cur == this.top) { this.top = to return } this.leave() } } // Kludge to work around directly nested list nodes produced by some // tools and allowed by browsers to mean that the nested list is // actually part of the list item above it. normalizeList(dom) { for (let child = dom.firstChild, prev; child; child = child.nextSibling) { if (child.nodeType == 1 && listTags.hasOwnProperty(child.nodeName.toLowerCase()) && (prev = child.previousSibling)) { prev.appendChild(child) child = prev } } } findAtPoint(parent, offset) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].node == parent && this.find[i].offset == offset) this.find[i].pos = this.top.currentPos } } findInside(parent) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].pos == null && parent.contains(this.find[i].node)) this.find[i].pos = this.top.currentPos } } findAround(parent, content, before) { if (parent != content && this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].pos == null && parent.contains(this.find[i].node)) { let pos = content.compareDocumentPosition(this.find[i].node) if (pos & (before ? 2 : 4)) this.find[i].pos = this.top.currentPos } } } findInText(textNode) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].node == textNode) this.find[i].pos = this.top.currentPos - (textNode.nodeValue.length - this.find[i].offset) } } }
JavaScript
class UniversalStudiosFlorida extends UniversalPark { static parkName = 'Universal Studios Florida'; static timezone = 'America/New_York'; static location = new GeoLocation({ latitude: 28.4749822, longitude: -81.4664970, }); /** * The identifier for the park * @name UniversalStudiosFlorida.parkId * @type {Number} */ static parkId = 10010; }
JavaScript
class JSEN { /** * Parse a string JSEN data structure and return an instance of it * @param jsenStr a string encoded according to JSEN syntax * * @return a JSEN data structure (JavaScript array) * * @see JSEN.stringify */ static parse( jsenStr ) { return JSON.parse( jsenStr ); } /** * Encode a JSEN data structure into a string * * @param jsenCode a JSEN data structure (JavaScript array) * @param replacer parameter not used * @param space an indentation string or a number representing the number of speced for indentation (see JSON.stringify) * * @returns a string representing a JSEN data structure * @see JSEN.parse, JSON.strngify */ static stringify( jsenCode, replacer, space ) { let codeLines = [ '[' ]; space = ( space? (typeof(space) == 'number'? ' '.repeat(space) :space): '' ); // Default value: no indentation let isControlNextStatement = false; // Loop on all code statement for( const codeStatement of jsenCode ) { // Get code statement type let codeStatementType = typeof( codeStatement ); if( ( codeStatementType == 'object' ) && ( Array.isArray( codeStatement ) ) ) { codeStatementType = 'block'; } // Init sting line with indentation let stringLine = space; // Introduce indentation after statements that controls the next statement (indent) if( isControlNextStatement ) { if( codeStatementType != 'block' ) { stringLine = space+stringLine; } isControlNextStatement = false; } // Generate statement switch( codeStatementType ) { case 'function': stringLine += codeStatement.toString(); break; case 'string': stringLine += '\''+codeStatement+'\''; case 'undefined': break; case 'block': codeLines.push( space+'[' ); const blockLines = JSEN.stringify( codeStatement, replacer, space+space ); codeLines = codeLines.concat( blockLines ); stringLine += ']'; break; case 'object': stringLine += codeStatement.toString( codeStatement ); isControlNextStatement = ( codeStatement.isControlNextStatement? true: false ); break; } codeLines.push( stringLine+',' ); } if( codeLines.length > 1 ) { codeLines.push( ']' ); } else { codeLines[0] = '[]'; } return codeLines.join( '\n' ); } /* ----------------------------------------------------------------- * Basic JSEN Statements *-----------------------------------------------------------------*/ /** * Sleeps, suspending the execution for an interval of time * During sleep, a JSEN thread is moved in the suspended thread queue * @param {*} params number of seconds to sleep (1 = 1s, 0.5 = 500ms) * * The parameter params can be: * - a float number: 1.2 // 1s and 200ms * - an object: { value: 1 } // 1s * - a function: ()=> 1 // 1s * * @example * JSEN.sleep( ()=> timeout ), * * @see JSEN.on */ static sleep = ( params )=> { return { //TODO: find a better way to have the indirect parameter by class.field name: 'sleep', params: params, toString: JSEN._toStringOneParams, }; } /** * Log a message in jsen calls (log startd with thread name) * @param {*} msg a message to be printed to the console * * The parameter msg can be: * - a function: ()=> 'ciao' // the message printed is 'ciao' * - an object: { value: 'ciao' } // the message printed is 'ciao' * - any other JavaScript data structure: it will be printed as it is * * @example * JSEN.print( 'Ciao' ), * JSEN.print( ()=> variableValue ), */ static print = ( msg )=> { return { name: 'print', params: msg, toString: JSEN._toStringOneParams, }; } /** * Control statement if * @param {*} condition a boolean condition evaluated in the if statement * * The parameter condition can be: * - a function: ()=> 1 > 10 // the function returns the validity of the condition * - an object: { value: true } // the value atrribute returns the validity of the condition * - any other JavaScript data structure: it will be evalutated as a condition * * @example * JSEN.if( ()=> i > 5 ), * JSEN.print( 'Condition true' ), * JSEN.else(), * JSEN.print( 'Condition false' ), * * @see JSEN.else */ static if = ( condition )=> { return { name: 'if', params: condition, toString: JSEN._toStringOneParams, isControlNextStatement: true, }; } /** * Define a lablel in a JSEN data structure. Label are local in JSEN blocks. * There are 2 labels available by default in every JSEN block: 'blockBegin', 'blockEnd' * @param {*} labelName name of the label as a string * * The parameter labelName can be: * - a function: ()=> 'start' // the label is 'start' * - an object: { value: 'start' } // the label is 'start' * - a constant string: 'start' // the label is 'start' * * @example * JSEN.label( 'start' ), * * @see JSEN.goto */ static label = ( labelName )=> { // TODO: fill now the label list of the context (so, all label will be available at run time) return { name: 'label', params: labelName, toString: JSEN._toStringOneParams, }; } /** * Jump to a lablel in a JSEN data structure. The goto have a limitations. A godo can * only jump into a local JSEN blocks. A jump between JSEN blocks is not supported. * A goto can only jump backwards, to a previously defined label. * @param {*} labelName name of the label as a string * * The parameter labelName can be: * - a function: ()=> 'start' // the label is 'start' * - an object: { value: 'start' } // the label is 'start' * - a constant string: 'start' // the label is 'start' * * @example * JSEN.goto( 'start' ), * * @see JSEN.goto */ static goto = ( labelName )=> { return { name: 'goto', params: labelName, toString: JSEN._toStringOneParams, }; } /* ----------------------------------------------------------------- * Advanced JSEN Statements *-----------------------------------------------------------------*/ /** * Suspends the exectuion of the JSEN thread until the condition becames true or the * timeout is over (if specified). The JSEN thread is moved in the suspended thread queue * until the condition is true or until timeout is over * @param {*} condition condition to let the JSEN execution continue * @param {*} timeout max timeout to sleep while the condition is false * * The exit status of a JSEN.on can be captured by JSEN.getOnStatus * * @example * JSEN.on( ()=> userName == 'guest', 1.2 ), * JSEN.on( ()=> userName == 'guest' ), * * @see JSEN.sleep, JSEN.getOnStatus */ static on = ( condition, timeout )=> { return { name: 'on', params: { condition: condition, timeout: timeout, }, toString: (self)=> { const timeoutStr = ( self.params.timeout? ', '+JSEN._paramsToString( self.params.timeout ): '' ); return 'JSEN.'+self.name+'( '+JSEN._paramsToString( self.params.condition )+timeoutStr+' )'; }, }; } /** * Returns the exist status of a JSEN.on. It informs if the JSEN.on continued because * the condition became true (value: 'çondition') or the timeout is over (value: 'timeout') * @param {*} callback a function that contains as only parameter the value of the on status * * @example * JSEN.on( ()=> userName == 'guest', 10 ), * JSEN.getOnStatus( (value)=> exitStatus = value ), * JSEN.print( ()=> 'ON condition continued because of '+exitStatus ), * * In this example the variable exitStatus can get the value 'condition' or 'timetout' * * @see JSEN.on */ static getOnStatus = ( callback )=> { return { name: 'getOnStatus', params: { variableName: '', // Set by virtual machine callback: callback, }, toString: JSEN._toStringOneParams, }; } /** * Control statement else, used in combination with a JSEN.if statement. * It executes the associated block in case the if condition is not true * * @example * JSEN.if( ()=> i > 5 ), * JSEN.print( 'Condition true' ), * JSEN.else(), * JSEN.print( 'Condition false' ), * * @see JSEN.if */ static else = ( ifResult )=> { return { name: 'else', params: ifResult, toString: JSEN._toStringNoParams, isControlNextStatement: true, } } /** * Infinite loop on the associated JSEN block. * Such a loop can be terminated using JSEN.break * * @example * JSEN.loop(), * [ * JSEN.print( 'We are in the loop' ), * JSEN.if( ()=> i > 5 ), * JSEN.break(), * ()=> ++i, * ], * * @see JSEN.break */ static loop = ()=> { return { name: 'loop', toString: JSEN._toStringNoParams, isControlNextStatement: true, }; } /** * Interrupt the execution of a JSEN block, continuing execution after it. * In case there is no other continuation, the JSEN tread will be terminated. * JSEN.break can be used in conbination of a control statement or just into a * simple JSEN block not controlled by any control statement * * @see JSEN.continue, JSEN.loop, JSEN.for, JSEN.foreach, JSEN.while, JSEN.until */ static break = ()=> { return { name: 'break', toString: JSEN._toStringNoParams, } } // Function to go to beginning of the currently running block or loop /** * Continue the execution of a JSEN block from the beginning of it. * JSEN.continue can be used in conbination of a control statement or just into a * simple JSEN block not controlled by any control statement * * @see JSEN.break, JSEN.loop, JSEN.for, JSEN.foreach, JSEN.while, JSEN.until */ static continue = ()=> { return { name: 'continue', toString: JSEN._toStringNoParams, } } /** * Loop on the associated JSEN block while the condition is true. * Such a loop can be terminated using JSEN.break * * @example * JSEN.while( ()=> i > 5 ), * [ * JSEN.print( 'We are in the loop' ), * ], * * @see JSEN.continue, JSEN.break, JSEN.loop, JSEN.for, JSEN.foreach, JSEN.until */ static while = ( condition )=> { return { name: 'while', params: condition, toString: JSEN._toStringOneParams, isControlNextStatement: true, }; } /** * Iterate on the associated JSEN block moving the iterator from lower to upper values. * Such a loop can be terminated using JSEN.break * * * @example * JSEN.for( 'i', 10 ), // i => [0, 10[, increment 1 * [ * JSEN.print( 'We print this line 10 times' ), * ], * JSEN.for( 'i', 5, 10 ), // i => [5, 10[, increment 1 * [ * JSEN.print( 'We print this line 5 times' ), * ], * JSEN.for( 'i', 5, 10, 2 ), // i => [5, 7, 9], increment 2 * [ * JSEN.print( 'We print this line 3 times' ), * ], * JSEN.for( 'i', 10, 5 ), // i => [10, 5[, increment -1 * [ * JSEN.print( 'We print this line 5 times' ), * ], * JSEN.for( 'i', 10, 5, -2 ), // i => [-10, -8, -6], increment -2 * [ * JSEN.print( 'We print this line 3 times' ), * ], * JSEN.for( 'i', ()=> beginIndex, ()=> endIndex ), // i => [beginIndex, endIndex[, increment -1 * [ * JSEN.print( 'We print this line several times' ), * ], * * @see JSEN.continue, JSEN.break, JSEN.loop, JSEN.foreach, JSEN.while, JSEN.until */ static for = ( iterator, lower, upper, increment )=> { // If upper is not defined, then the lower represents the upper bound // Note: lower and upper may represent opposite values if increment is negative if( upper === undefined ) { upper = lower; lower = 0; } return { name: 'for', params: { iterator: iterator, lower: lower, upper: upper, increment: increment, }, toString: (self)=> { return 'JSEN.'+self.name+'( '+JSEN._paramsToString( self.params.iterator )+', '+ JSEN._paramsToString( self.params.lower )+', '+ JSEN._paramsToString( self.params.upper )+', '+ JSEN._paramsToString( self.params.increment )+' )'; }, isControlNextStatement: true, }; } /** * Iterate on the associated JSEN block moving the iterator along the elements of an iteralbe object. * Such a loop can be terminated using JSEN.break * * * @example * JSEN.foreach( 'i', [1, 2, 3] ), // i => [1, 2, 3] * [ * JSEN.print( 'We print this line 3 times' ), * ], * JSEN.foreach( 'i', ['a', 'b'] ), // i => ['a', 'b'] * [ * JSEN.print( 'We print this line 2 times' ), * ], * JSEN.foreach( 'i', arrayValue ), // Statically assigned * [ * JSEN.print( 'We print this line several times' ), * ], * JSEN.foreach( 'i', ()=> arrayValue ), // Dynamically evaluated * [ * JSEN.print( 'We print this line several times' ), * ], * * @see JSEN.continue, JSEN.break, JSEN.loop, JSEN.for, JSEN.while, JSEN.until */ static foreach = ( iterator, array )=> { return { name: 'foreach', params: { iterator: iterator, array: array, }, toString: (self)=> { return 'JSEN.'+self.name+'( '+JSEN._paramsToString( self.params.iterator )+', '+ JSEN._paramsToString( self.params.array )+' )'; }, isControlNextStatement: true, }; } /** * Get the value of a user variable * @param {*} variableName name of the variable * @param {*} callback function with a single parameter with the value of the variable * * @example * JSEN.get( 'i', (value)=> console.log( 'i =', value ) ); * * @see JSEN.set */ static get = ( variableName, callback )=> { return { name: 'get', params: { variableName: variableName, callback: callback, }, toString: (self)=> { return 'JSEN.'+self.name+'( '+JSEN._paramsToString( self.params.variableName )+', '+ JSEN._paramsToString( self.params.callback )+' )'; }, }; } /** * Set the value of a user variable * @param {*} variableName name of the variable * @param {*} value value to be associated to the variable * * @example * JSEN.set( 'i', 5 ); * JSEN.set( 'i', ()=> a+b ); * * @see JSEN.get */ static set = ( variableName, value )=> { return { name: 'set', params: { variableName: variableName, value: value, }, toString: (self)=> { return 'JSEN.'+self.name+'( '+JSEN._paramsToString( self.params.variableName )+', '+ JSEN._paramsToString( self.params.value )+' )'; }, }; } /** * Loop on the associated JSEN block until the condition becomes false. * Such a loop can be terminated using JSEN.break * * @example * [ * JSEN.print( 'We are in the loop' ), * ], * JSEN.until( ()=> i < 5 ), * * @see JSEN.continue, JSEN.break, JSEN.loop, JSEN.for, JSEN.foreach, JSEN.while */ static until = ( condition )=> { return { name: 'until', params: condition, toString: JSEN._toStringOneParams, //NOTE: Do not set 'isIterative: true' here } } /** * Multi value control statement, switching on different cases * @param {*} value value on which to switch * * @example * JSEN.switch( ()=> testVar ), * JSEN.case( 0 ), * [ * ()=> console.log( 'testVar 0' ), * ], * JSEN.case( 1 ), * [ * ()=> console.log( 'testVar 1' ), * ], * JSEN.case( 2 ), * [ * ()=> console.log( 'testVar 2' ), * ], * * @see JSEN.case, JSEN.break, JSEN.if, JSEN.else */ static switch = ( value )=> { return { name: 'switch', params: value, toString: JSEN._toStringOneParams, } } /** * Case for multi value control statement, switching on different cases * @param {*} value value of the specific case * * @example * JSEN.switch( ()=> testVar ), * JSEN.case( 0 ), * [ * ()=> console.log( 'testVar 0' ), * ], * JSEN.case( 1 ), * [ * ()=> console.log( 'testVar 1' ), * ], * JSEN.case( 2 ), * [ * ()=> console.log( 'testVar 2' ), * ], * * @see JSEN.switch, JSEN.break, JSEN.if, JSEN.else */ static case = ( value )=> { return { name: 'case', params: value, toString: JSEN._toStringOneParams, isControlNextStatement: true, } } // Function to force the execution of checkOn conditions /** * Force the execution of the threat that test all condition for suspended thread on JSEN.on() * * @example * JSEN.forceCheckOn(), * * @see JSEN.on+++ */ static forceCheckOn = ()=> { return { name: 'forceCheckOn', params: 0, toString: JSEN._toStringNoParams, }; } /* ----------------------------------------------------------------- * Private JSEN functions *-----------------------------------------------------------------*/ static _toStringNoParams = (self)=> { return 'JSEN.'+self.name+'()'; } static _toStringOneParams = (self)=> { return 'JSEN.'+self.name+'( '+JSEN._paramsToString( self.params )+' )'; } static _paramsToString( params ) { let result = ''; if( params !== undefined ) { switch( typeof( params ) ) { case 'object': result = JSON.stringify( params ); break; case 'string': result = '\''+params+'\''; break; default: result = params.toString(); break; } } return result; } }
JavaScript
class TokenBucketFilter { /** * New TokenBucketFilter. * @constructor */ constructor(times, period=1000) { assert(times, 'You must specify `times` per `period` (defaults to 1000)'); this.tokenCount = 0; this.bucketSize = times; this.refreshInterval = period/times; const timer = setInterval(this._tick.bind(this), this.refreshInterval); timer.unref(); } /** * Ticks. * @access protected */ _tick() { this.tokenCount = Math.max(this.bucketSize, this.tokenCount + 1); } /** * Uses token. * @access public * @returns Promise */ async take() { while (this.tokenCount === 0) { await delay(this.refreshInterval); } this.tokenCount = Math.max(this.tokenCount - 1, 0); } }
JavaScript
class Write extends Component { constructor(props, context) { super(props, context); this.state = { redirect: this.context.state.isLogin } this.handlewrite = this.handlewrite.bind(this) } handlewrite = async (e) => { e.preventDefault(); let isLogin = this.context.state.isLogin if (isLogin) { let heading = document.getElementById("heading"); let content = document.getElementById("content"); let token = this.context.state.token let res = await titleAPI.createTitile(token, heading.value, content.value) let status = res.status; if (status === 201) { alert('提交成功!') heading.value = ''; content.value = ''; } } } render() { if(!this.state.redirect) { return ( <Redirect to="/login" /> ) } else { return( <section className="write hero"> <div className="hero-body"> <div className="columns is-centered"> <div className="column is-7"> <form className="box" onSubmit={this.handlewrite}> <nav className="level"> <div className="level-left"> <p className="level-item"><strong>记一行代码 解惑他人</strong></p> </div> <div className="level-right"> <p className="level-item"> <button type="submit" className="button is-small is-rounded is-info">发布</button> </p> </div> </nav> <div className="control"> <input id="heading" className="input is-info" type="text" maxLength="100" required placeholder="列出Docker容器" /> <hr/> <textarea id="content" className="textarea has-fixed-size is-info" rows="8" maxLength="800" required placeholder="docker ps -a" > </textarea> </div> </form> </div> </div> </div> </section> ) } } }
JavaScript
class Bus { constructor () { /** * @type {int} */ this.currentStation = 1 /** * 40 seats for Guests. Bus Driver's seat is * not listed here, because he has a hardcoded * position. * @type {Seat[]} */ this.seats = [ new Seat(1, 655, 255), new Seat(2, 175, 95), new Seat(3, 495, 255), new Seat(4, 375, 95), new Seat(5, 175, 255), new Seat(6, 655, 95), new Seat(7, 335, 255), new Seat(8, 495, 95), new Seat(9, 255, 255), new Seat(10, 575, 255), new Seat(11, 255, 95), new Seat(12, 575, 95), new Seat(13, 375, 255), new Seat(14, 215, 255), new Seat(15, 215, 95), new Seat(16, 335, 95), new Seat(17, 535, 95), new Seat(18, 615, 95), new Seat(19, 535, 255), new Seat(20, 615, 255), new Seat(21, 375, 215), new Seat(22, 335, 215), new Seat(23, 375, 135), new Seat(24, 335, 135), new Seat(25, 495, 215), new Seat(26, 495, 135), new Seat(27, 535, 135), new Seat(28, 535, 215), new Seat(29, 255, 215), new Seat(30, 255, 135), new Seat(31, 575, 135), new Seat(32, 575, 215), new Seat(33, 215, 215), new Seat(34, 215, 135), new Seat(35, 615, 135), new Seat(36, 615, 215), new Seat(37, 175, 135), new Seat(38, 175, 215), new Seat(39, 655, 135), new Seat(40, 655, 215) ] } /** * check every seat for a person sitting on it * @return {int} number of guests */ howManyGuestsInTheBus () { let guestCounter = 0 this.seats.forEach(seat => { if (seat.guest != null) { guestCounter++ } }) return guestCounter } /** * searches for the available seat with the * lowest seat number. * @return {Seat} seat. if all seats are taken, it * returns null. */ nextFreeSeat () { // array is sorted by seat number let nextFreeSeat = null this.seats.forEach(seat => { if (seat.isFree) { // only assign the first free seat if (nextFreeSeat == null) { nextFreeSeat = seat } } }) return nextFreeSeat } /** * check if all seats are taken * @return {boolean} true: all seats are taken. * false: there are free seats available */ isFull () { if (this.howManyGuestsInTheBus() >= this.seats.length) { return true } return false } /** * count healthy guests in the bus * @return {int} how many guests in the bus are healthy */ getNumberOfHealthyGuests () { let numHealthyGuests = 0 this.seats.forEach(seat => { if (!seat.isFree) { if (seat.guest.healthCondition === HealthCondition.HEALTHY) { numHealthyGuests++ } } }) return numHealthyGuests } /** * count infected guests in the bus * @return {int} how many guests in the bus are infected */ getNumberOfInfectedGuests () { let numInfectedGuests = 0 this.seats.forEach(seat => { if (!seat.isFree) { if (seat.guest.healthCondition === HealthCondition.INFECTED) { numInfectedGuests++ } } }) return numInfectedGuests } /** * return the seats of all infected guests * @param {Seat[]} infectedSeats the return value is stored in that argument */ getInfectedSeats (infectedSeats) { this.seats.forEach(seat => { if (!seat.isFree) { if (seat.guest.healthCondition === HealthCondition.INFECTED) { infectedSeats.push(seat) } } }) } }
JavaScript
class AddMimeTypeGuesserPass extends implementationOf(CompilerPassInterface) { /** * @inheritdoc */ process(container) { if (! container.has('mime_types')) { return; } const definition = container.findDefinition('mime_types'); for (const id of Object.keys(container.findTaggedServiceIds('mime.mime_type_guesser'))) { definition.addMethodCall('registerGuesser', [ new Reference(id) ]); } } }
JavaScript
class b2MouseJointDef extends b2JointDef { constructor() { super(5 /* e_mouseJoint */); this.target = new b2Vec2(); this.maxForce = 0; this.frequencyHz = 5; this.dampingRatio = 0.7; } }
JavaScript
class BaseModel { /** * Create model * @param {Postgres|MySQL|Mongo} db Database service * @param {Util} util Util service */ constructor(db, util) { this._dirty = false; this._fields = new Map(); this._fieldToProp = new Map(); this._propToField = new Map(); this._db = db; this._util = util; } /** * Service name is 'models.base' * @type {string} */ static get provides() { return 'models.base'; } /** * Add a field * @param {string} field DB field name * @param {string} property Model property name */ _addField(field, property) { this._fields.set(field, undefined); this._fieldToProp.set(field, property); this._propToField.set(property, field); } /** * Remove a field * @param {string} field DB field name * @param {string} property Model property name */ _removeField(field, property) { this._fields.delete(field); this._fieldToProp.delete(field); this._propToField.delete(property); } /** * Set a field to a value * @param {string} field DB field name * @param {*} value New value */ _setField(field, value) { this._fields.set(field, value); this._dirty = true; return value; } /** * Get field * @param {string} field DB field name * @return {*} Returns current value */ _getField(field) { return this._fields.get(field); } /** * Convert to object. Dates are converted to strings in UTC timezone * @param {string[]} [fields] Fields to save * @param {object} [options] Options * @param {string|null} [options.timeZone='UTC'] DB time zone * @return {object} Returns serialized object */ _serialize(fields, options = {}) { if (fields && !Array.isArray(fields)) { options = fields; fields = undefined; } if (!fields) fields = Array.from(this._fields.keys()); let { timeZone = 'UTC' } = options; let data = {}; for (let field of fields) { let prop = this._fieldToProp.get(field); if (!prop) prop = this._util.snakeToCamel(field); let desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), prop); let value = (desc && desc.get) ? desc.get.call(this) : this._getField(field); if (value && moment.isMoment(value)) { if (timeZone) value = value.tz(timeZone); if (this._db.constructor.datetimeFormat) value = value.format(this._db.constructor.datetimeFormat); else value = value.toDate(); } data[field] = value; } return data; } /** * Load data. Dates are expected to be in UTC and are converted into local timezone * @param {object} data Raw DB data object * @param {object} [options] Options * @param {string|null} [options.timeZone='UTC'] DB time zone */ _unserialize(data, options = {}) { let { timeZone = 'UTC' } = options; for (let field of this._fields.keys()) { this._fields.set(field, undefined); if (typeof data[field] === 'undefined') continue; let prop = this._fieldToProp.get(field); if (!prop) prop = this._util.snakeToCamel(field); let desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), prop); let value = (desc && desc.set) ? desc.set.call(this, data[field]) : this._setField(field, data[field]); if (value && moment.isMoment(value) && timeZone) { value = moment.tz(value.format('YYYY-MM-DD HH:mm:ss.SSS'), timeZone).local(); value = moment(value.format('YYYY-MM-DD HH:mm:ss.SSS')); if (desc && desc.set) desc.set.call(this, value); else this._setField(field, value); } } this._dirty = false; } }
JavaScript
class MenuTabs { QueueTabs = [ { name: 'PENDING_REVIEW', label: 'Waiting', }, { name: 'PRINTING', label: 'In Progress', }, { name: 'DONE', label: 'Recently Completed', }, { name: 'FAILED', label: 'Print Failed', }, ]; ManageAccountTabs = [ { name: 'settings', label: 'Settings', }, { name: 'users', label: 'User Profiles', }, ]; }
JavaScript
class AggregatingFetcher { /** * * @param {object} params * @param {number} [params.frequency] number of milliseconds to wait for requests to aggregate */ constructor({ frequency = 100, fetch, maxExtraSize = 32000, maxFetchSize = 1000000, }) { this.requestQueues = {} // url => array of requests this.fetchCallback = fetch this.frequency = frequency this.maxExtraSize = maxExtraSize this.maxFetchSize = maxFetchSize } _canAggregate(requestGroup, request) { return ( // the fetches overlap, or come close request.start <= requestGroup.end + this.maxExtraSize && // aggregating would not result in a fetch that is too big request.end - request.start + requestGroup.end - requestGroup.start < this.maxFetchSize ) } // returns a promise that only resolves // when all of the signals in the given array // have fired their abort signal _allSignalsFired(signals) { return new Promise(resolve => { let signalsLeft = signals.filter(s => !s.aborted).length signals.forEach(signal => { signal.addEventListener('abort', () => { signalsLeft -= 1 // console.log('aggregatingfetcher received an abort') if (!signalsLeft) { // console.log('aggregatingfetcher aborting aggegated request') resolve() } }) }) }).catch(e => { // eslint-disable-next-line no-console console.error(e) }) } // dispatch a request group as a single request // and then slice the result back up to satisfy // the individual requests _dispatch({ url, start, end, requests }) { // if any of the requests have an AbortSignal `signal` in their requestOptions, // make our aggregating abortcontroller track it, aborting the request if // all of the abort signals that are aggregated here have fired const abortWholeRequest = new AbortController() const signals = [] requests.forEach(({ requestOptions }) => { if (requestOptions && requestOptions.signal) signals.push(requestOptions.signal) }) if (signals.length === requests.length) { this._allSignalsFired(signals).then(() => abortWholeRequest.abort()) } this.fetchCallback(url, start, end - 1, { signal: abortWholeRequest.signal, }).then( response => { const data = response.buffer requests.forEach(({ start: reqStart, end: reqEnd, resolve }) => { // remember Buffer.slice does not copy, it creates // an offset child buffer pointing to the same data resolve({ headers: response.headers, buffer: data.slice(reqStart - start, reqEnd - start), }) }) }, err => { requests.forEach(({ reject }) => reject(err)) }, ) } _aggregateAndDispatch() { entries(this.requestQueues).forEach(([url, requests]) => { if (!requests || !requests.length) return // console.log(url, requests) // we are now going to aggregate the requests in this url's queue // into groups of requests that can be dispatched as one const requestsToDispatch = [] // look to see if any of the requests are aborted, and if they are, just // reject them now and forget about them requests.forEach(request => { const { requestOptions, reject } = request if ( requestOptions && requestOptions.signal && requestOptions.signal.aborted ) { reject(Object.assign(new Error('aborted'), { code: 'ERR_ABORTED' })) } else { requestsToDispatch.push(request) } }) requestsToDispatch.sort((a, b) => a.start - b.start) // eslint-disable-next-line no-param-reassign requests.length = 0 if (!requestsToDispatch.length) return let currentRequestGroup for (let i = 0; i < requestsToDispatch.length; i += 1) { const next = requestsToDispatch[i] if ( currentRequestGroup && this._canAggregate(currentRequestGroup, next) ) { // aggregate it into the current group currentRequestGroup.requests.push(next) currentRequestGroup.end = next.end } else { // out of range, dispatch the current request group if (currentRequestGroup) this._dispatch(currentRequestGroup) // and start on a new one currentRequestGroup = { requests: [next], url, start: next.start, end: next.end, } } } if (currentRequestGroup) this._dispatch(currentRequestGroup) }) } _enQueue(url, request) { if (!this.requestQueues[url]) this.requestQueues[url] = [] this.requestQueues[url].push(request) } /** * * @param {string} url * @param {number} start 0-based half-open * @param {number} end 0-based half-open * @param {object} [requestOptions] options passed to the underlying fetch call */ fetch(url, start, end, requestOptions = {}) { return new Promise((resolve, reject) => { this._enQueue(url, { start, end, resolve, reject, requestOptions }) if (!this.timeout) { this.timeout = setTimeout(() => { this.timeout = undefined this._aggregateAndDispatch() }, this.frequency || 1) } }) } }
JavaScript
class minHeap { constructor() { this.heap = []; //map to keep track of the deleted elements and not have do heapify every time we have a type 2 query (removal): this.tracker = new Map(); } peek() { let min = this.heap[1]; //if the min value is present on the map (it was not deleted from the heap), log it and exit: if(this.tracker.has(min)){ console.log(this.heap[1]); return; } //in case the min value has been deleted, perform standard heap removal (replace it by the last element in the heap and heapify to maintain properties if min heap). After this is done, recursively call the peek() function and recheck if the new min is still on the map and so on: this.swapValues(this.heap.length-1,1); this.heap.pop(); if(this.heap.length > 2){ this.heapifyTopBottomRecursively(); } this.peek(); } insert(value) { if(this.heap.length < 1) { this.heap[0] = null; this.heap.push(value); this.tracker.set(value,true); //add new element to the map also (key : val -> value : true or false). return; } this.heap.push(value); this.tracker.set(value,true); //add new element to the map also (key : val -> value : true or false). this.heapifyBottomTopRecursively(); } heapifyBottomTopRecursively(index=this.heap.length-1) { let parentIndex = Math.floor(index/2); if(!this.heap[parentIndex]) return; if(this.heap[parentIndex] > this.heap[index]) { this.swapValues(index, parentIndex); index = parentIndex; this.heapifyBottomTopRecursively(index); } else { return; } } remove(value) { if(this.heap.length <= 1) { return; } //remove element directly from the map, instead of from the heap (O(1) vs O(logn)): this.tracker.delete(value); } heapifyTopBottomRecursively(rootIndex=1) { if(!this.heap[rootIndex]) { return; } let leftIndex, rightIndex; leftIndex = 2*rootIndex; rightIndex = (2*rootIndex)+1; if(!this.heap[leftIndex]) { return; } if(this.heap[rootIndex] > this.heap[leftIndex] || this.heap[rootIndex] > this.heap[rightIndex]) { if(!this.heap[rightIndex] || this.heap[leftIndex] < this.heap[rightIndex]) { this.swapValues(rootIndex, leftIndex); rootIndex = leftIndex; } else { this.swapValues(rootIndex, rightIndex); rootIndex = rightIndex; } this.heapifyTopBottomRecursively(rootIndex); } } swapValues(child, parent) { let temp = this.heap[child]; this.heap[child] = this.heap[parent]; this.heap[parent] = temp; } }
JavaScript
class GitHubAPI { constructor($http,$q){ this._http = $http; this._q = $q; this._authToken = undefined; } setAuthToken(token){ this._access_token = token; return token; } get(url, params = {}){ params.access_token = this._access_token; return this._http.get(url,{params}) .then((res) => this._parseResponse(res)); } getAll(url, params = {}, all = []){ params.access_token = this._access_token; params.page = params.page || 1; return this.get(url,params).then(results => { if(!results.length){ return all; } params.page++; return this.getAll(url, params, all.concat(results)); }); } _parseResponse(res){ return res.data; } }
JavaScript
class GitHubUser { constructor(gitHubAPI, tokenStore, $location){ this._api = gitHubAPI; this._tokenStore = tokenStore; this._$location = $location; this._userData = undefined; this._userOrgs = undefined; } authenticate(){ return this._getToken() .then(() => this.getUser()); } getUser(){ if(!this._loadUserData){ this._loadUserData = this._api.get(`${GITHUB_BASE_URL}/user`) .then((user) => this._userData = user); } return this._loadUserData; } getOrgs(){ if(!this._loadUserOrgs){ this._loadUserOrgs = this._api.get(`${GITHUB_BASE_URL}/user/orgs`) .then((userOrgs) => this._userOrgs = userOrgs); } return this._loadUserOrgs; } parseURLToken(){ return this._$location.search()[GITHUB_TOKEN_KEY]; } _getToken(){ //check if we have one in the URL from the server let urlToken = this.parseURLToken() if(urlToken){ //clear url this._$location.search({}) return this._tokenStore.setToken(urlToken) .then((token) => this._api.setAuthToken(token)); } //otherwise check storage (and reject if not found) return this._tokenStore.getToken() .then((token) => this._api.setAuthToken(token)); } }
JavaScript
class GitHub { constructor(gitHubAPI,gitHubUser,$q){ this._api = gitHubAPI; this._user = gitHubUser; this._orgs = []; this._q = $q; } get orgs(){ return this._orgs; } checkAuthenticated(){ return this._user.authenticate(); } getUserOrgs(params){ return this._user.getOrgs() .then(orgs => orgs.map((org) => new GitHubOrg(this._api, org))) .then((orgs) => this._orgs = orgs); } getOrg(orgLogin){ let org = this._orgs.filter((org) => org.login === orgLogin).pop(); if(org){ return this._q.when(org); } return this._api.get(`${GITHUB_BASE_URL}/orgs/${orgLogin}`) .then((org) => new GitHubOrg(this._api, org)) .then((org) => { this._orgs.push(org); return org; }); } addOrg(org){ return this.getOrg(org.login) } }
JavaScript
class PushError extends Error { constructor(message = '') { super(); /** * Error name (PushError). */ this.name = 'PushError'; /** * Error message. */ this.message = message; } }
JavaScript
class Color extends WMTS { /** * Constructor */ constructor() { super({ projection, tileGrid, urls: urlsPng, crossOrigin: 'anonymous', tilePixelRatio: 1, layer: 'geolandbasemap', style: 'normal', matrixSet: 'google3857', requestEncoding: ('REST'), }); } }
JavaScript
class Window { constructor() { this.messages = []; this.newMessage = ""; // UI Behavior properties this.isCollapsed = false; this.isLoadingHistory = false; this.hasFocus = false; this.hasMoreMessages = true; this.historyPage = 0; } }
JavaScript
class StonePileEncounter extends Encounter { constructor() { super({ type: ENCOUNTER_NAME, description: __("Something makes a crumpling noise as you tread along. You look down and see that you've stepped on a piece of paper that was discarded long ago. Glancing briefly at it, you can tell that it's covered in detailed magical instructions. It's a new spell!"), actions: Actions.oneButton(__("Read it"), "encounter", { params: { type: ENCOUNTER_NAME, action: ACTION_READ_IT } } ), }); } /** * Image of the stone pile. * * @param {Character} character - The character currently in this encounter. * * @return {string} */ getImage(character) { return 'encounters/scatterslide/scroll.png'; } /** * Gets an addendum to the location in the bot name, for clarificatino. * * @param {Character} character - The character currently in this encounter. * * @return {string} */ getBotSuffix(character) { return __(": Scroll"); } /** * Perform one of this encounter's actions. * * @param {string} action - The action to perform. * @param {Character} character - The character performing the action. * @param {object} message - The message that preceeded this, for updating. */ async doAction(action, character, message) { let title = ''; let spell = null; character.state = CHARACTER_STATE.IDLE; if (character.location.type === 'scatterslide-mine') { spell = Spells.new('open_wounds'); } else if (character.location.type === 'scatterslide-underdrift') { spell = Spells.new('poison_cloud'); } else { throw new Error("No spell scroll for location ${character.location.type}."); } if (ACTION_READ_IT === action) { character.learnSpell(spell.type); title = __("You read the scroll, learning a new spell: %s. Once you've read it, the letters on the scroll fade away to nothing, and you discard the now-worthless paper.", spell.getDisplayName(character)); } else { throw new Error(`Uncrecognized action for ${this.type}: '${action}'`); } await this.updateLast({ attachments: Attachments.one({ title }), doLook: true }); } }
JavaScript
class GitClient { constructor(options, context) { this.options = options; this.context = context; } fetch(url) { let opts = this.options; let dest = path.resolve(opts.dest); let context = this.context; return (0, future_1.doFuture)(function* () { //XXX: @types/node-git is outdated yield (0, future_1.liftP)(() => git.Clone.clone(url, dest, { certificateCheck: (process.platform === 'darwin') ? () => 0 : undefined, callbacks: { credentials: (_, username) => git.Cred.sshKeyFromAgent(username) } })); yield (0, file_1.unlink)(`${dest}/.git`); let manifest = yield (0, manifest_1.validateManifest)(dest); return (0, future_1.pure)(new project_1.Project(dest, manifest, context)); }); } }
JavaScript
class Historico { Data; TipoOperacao; Valor; criar() { } destruir() { } }
JavaScript
class NumericPriorityScheduler { constructor() { /** * A 2-D array of all the dependencies. The queues with lower priority will * be dequeued first. * @private {!Array<!Array<!PrefetchResource>>} */ this.dependencies_ = new Array(NUM_PRIORITIES); for (let i = 0; i < NUM_PRIORITIES; i++) { this.dependencies_[i] = new Array(); } /** * A set containing URLs (or request id) of requests that are in-flight. * @private {!Set<!string>} */ this.outstandingPrefetchUrls_ = new Set(); this.timeTracker = new TimeTracker.TimeTracker(); /** * Tracks the URLs that are already requested to prevent duplicated requests * in the case where prefetch request goes out after the actual request. * @private {!Set<!string>} */ this.requestedURLs_ = new Set(); /** * The landing page URL that this experiment will navigate to. This is used * to detect when the navigation to the landing page has already started. */ this.lpUrl = ''; /** * Flag indicating whether the browser has already navigated to the landing * page. The browser has navigated when the request header for lpUrl is * sent. * * @private {!boolean} */ this.navigatedToDst_ = false; /** * Array containing URLs that are waiting to be fetched for a particular * priority. * * @private {!Array<!PrefetchResource>} */ this.queuedPrefetches_ = new Array(); /** * Indicates which priority level that the scheduler is requesting right * now. * * @private {number} */ this.curFetchPriority_ = -1; this.didInit_ = false; this.initializedContentScript_ = false; } /** * Handles the event before the headers are sent for the request. * * @param {!Object} details Details about the request. * @private */ onSendHeaders_(details) { console.log('send headers:'); console.log(details); const isPrefetch = this.isPrefetchRequest_(details.requestHeaders); // TODO(vaspol): track the whether the prefetch request is received before // the resource is discovered from the browser. this.timeTracker.registerRequest( details.requestId, details.timeStamp, isPrefetch); console.log(this.timeTracker); // Browser is navigating to the landing page. if (details.url === this.lpUrl) { const /** @type {Message.NavigatedToDst} */ msg = { type: MessageType.NAVIGATED_TO_DST, url: this.lpUrl }; this.notifyContentScript_(msg); // In a re-using a browser for multiple experiments, this has to be switch // back to false. However, for this current setup with WPT, it is okay to // leave it as is. this.navigatedToDst_ = true; } // Keep track of the URLs that are already requested so that we don't // send out a prefetch request for that URL again. this.requestedURLs_.add(details.url); } /** * Determines from the requestHeaders whether this request is a prefetch * request or not. * * @param {Array<!Object>} requestHeaders the headers of the request to be * determined. * * @return {boolean} whether the request is a prefetch request or not based on the * requestHeader * @private */ isPrefetchRequest_(requestHeaders) { for (let i = 0; i < requestHeaders.length; i++) { const element = requestHeaders[i]; if (element.name.toLowerCase() === 'purpose' && element.value.toLowerCase() === 'prefetch') { return true; } } return false; } /** * onHeadersReceived_ implements the logic when the response header is * received from the server. It parses the response headers and extracts the * dependency hints along with its priority. * * @param {!Object} details Details about the request. See: * https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/webRequest/onHeadersReceived#details * * @return {!Object} a object containing the request headers * @private */ onHeadersReceived_(details) { const /** @type {Message.Info} */ completeMsg = { type: MessageType.INFO, message: performance.now() + ' HeadersReceived: ' + details.url + ' headers: ' + details.responseHeaders }; this.notifyContentScript_(completeMsg); details.responseHeaders.forEach((element) => { if (element.name.toLowerCase() === 'x-prefetch') { // Prefetch URLs are in the same format as Preload HTTP headers. this.parsePrefetchURLs(this.dependencies_, element.value); } else if (element.name.toLowerCase() === 'x-lp-url') { this.lpUrl = element.value; } }); return {requestHeaders: details.responseHeaders}; } /** * parsePrefetchURLs parses the hinted x-prefetch string and populate the * dependencies with the appropriate URLs into the correct priority bucket. */ parsePrefetchURLs(dependencies, prefetchStr) { const prefetchURLs = prefetchStr.split(DELIMETER); prefetchURLs.forEach((element) => { const prefetchInfo = element.split(';'); // Parse the URL. const trimmedUrl = prefetchInfo[0].trim(); const url = trimmedUrl.substring(1, trimmedUrl.length - 1); // Remove < and > // Parse the priority. const priority = parseInt(prefetchInfo[1].split('=')[1].trim(), 10); const targetPriority = Math.min(priority, NUM_PRIORITIES - 1); // Parse the type. const type = prefetchInfo[2].split('=')[1].trim(); const prefetchResource = new PrefetchResource(url, type); dependencies[targetPriority].push(prefetchResource); }); } /** * handleFetchCompleted implements the logic handling when all requests have * been received at a priority level. This function fetches resources from * the next priority tier. */ handleFetchCompleted(fetchedURL) { const /** @type {Message.Info} */ calledMsg = { 'type': MessageType.INFO, 'message': performance.now() + ' calling handleFetchCompleted() after fetch: ' + fetchedURL }; this.notifyContentScript_(calledMsg); // Start prefetching more when we don't have any outstanding fetches. if (this.outstandingPrefetchUrls_.size >= OUTSTANDING_REQUESTS_ALLOWED) { return; } // Find the first non-empty dependency in the priorities. Queue them up // for fetching. Do this only when the queue for prefetching is empty. let nextPriority = -1; for (let i = 0; i < this.dependencies_.length; i++) { if (this.dependencies_[i].length > 0) { nextPriority = i; break; } } if (this.outstandingPrefetchUrls_.size == 0 && nextPriority != -1 && this.queuedPrefetches_.length == 0) { // Enqueue more URLs to prefetch when there isn't any outstanding // prefetches, the prefetch queue is empty, and there are more // URLs left to prefetch. const dependencies = this.dependencies_[nextPriority]; while (dependencies.length > 0) { const dependency = dependencies.splice(0, 1)[0]; // Remove the first dependency. this.queuedPrefetches_.push(dependency); } this.curFetchPriority_ = nextPriority; } const /** @type {Message.Info} */ msg = { 'type': MessageType.INFO, 'message': performance.now() + ' len(outstanding_prefetches): ' + this.outstandingPrefetchUrls_.size + ' len(queuedPrefetches): ' + this.queuedPrefetches_.length + ' ' + String(this.queuedPrefetches_) }; this.notifyContentScript_(msg); // Fetch the dependency from the queued ones only. while (this.outstandingPrefetchUrls_.size < OUTSTANDING_REQUESTS_ALLOWED && this.queuedPrefetches_.length > 0) { // Get the next dependency to fetch. const dependency = this.queuedPrefetches_.splice(0, 1)[0]; this.fetchDependency(dependency, this.curFetchPriority_); } } /** * Implements fetching of a dependency using <link rel="prefetch">. * * @param {PrefetchResource} resource the resource to be prefetched. * @param {number} priority the number representing the priority of the * resource. */ fetchDependency(resource, priority) { // If this url has already been requested, don't prefetch it again. const url = resource.url; if (this.requestedURLs_.has(url)) { console.log( 'URL: ' + url + ' has already been requested by the browser NOT PREFETCHING'); const /** @type {Message.Log} */ msg = { type: MessageType.LOG_TIMING, url: url, requestId: '', fetchTime: -1, requestTimestampMs: -1, completeTimestampMs: -1, isPrefetch: 'late' }; this.notifyContentScript_(msg); return; } // Notify content script prefetch url. let msgType = this.navigatedToDst_ ? MessageType.PRELOAD_RESOURCE : MessageType.PREFETCH_RESOURCE; // Not part of the main frame, fetch it with <link rel="prefetch"> if (priority > MAX_MAIN_FRAME_PRIORITY) { msgType = MessageType.PREFETCH_RESOURCE; } const /** @type {Message.Prefetch} */ msg = { type: msgType, url: resource.url, resourceType: resource.type }; this.notifyContentScript_(msg); this.outstandingPrefetchUrls_.add(url); } /** * Implements the logic to handle messages from the content script. * * @private */ onContentMessage_(msg, sender, sendResponse) { switch (msg.type) { case MessageType.CONTENT_SCRIPT_INIT: if (!this.initializedContentScript_) { this.handleFetchCompleted('INIT'); this.initializedContentScript_ = true; } break; case MessageType.COMPLETED: break; default: console.warn('received an undefined message of type ' + msg.type); } } onErrorOccurred_(details) { const /** @type {Message.Info} */ completeMsg = { type: MessageType.INFO, message: performance.now() + 'Error: ' + details.url }; this.notifyContentScript_(completeMsg); this.onFetchCompleted_(details); } onFetchSucceed_(details) { const /** @type {Message.Info} */ completeMsg = { type: MessageType.INFO, message: performance.now() + ' Completed: ' + details.url + ' len(outstanding): ' + this.outstandingPrefetchUrls_.size + ' outstanding: ' + String(Array.from(this.outstandingPrefetchUrls_)) + ' details: ' + JSON.stringify(details) }; this.notifyContentScript_(completeMsg); this.onFetchCompleted_(details); } /** * Implements the logic when a fetch of a resource has been completed * regardless of whether it succeeded or not. * * @private */ onFetchCompleted_(details) { this.outstandingPrefetchUrls_.delete(details.url); this.handleFetchCompleted(details.url); const /** @type {Message.Debug} */ debugMsg = { type: MessageType.DEBUG, data: JSON.stringify(this.timeTracker) }; this.notifyContentScript_(debugMsg); console.log(details); console.log( 'fetch completed for ' + details.url + ' requestId: ' + details.requestId); console.log(this.timeTracker); const fetchTime = this.timeTracker.completeRequest(details.requestId, details.timeStamp); console.log('fetchTime: ' + fetchTime); const /** @type {Message.Log} */ logMsg = { type: MessageType.LOG_TIMING, url: details.url, requestId: details.requestId, fetchTime: fetchTime, requestTimestampMs: this.timeTracker.getRequestTime(details.requestId), completeTimestampMs: this.timeTracker.getCompleteTime(details.requestId), isPrefetch: this.timeTracker.isPrefetchRequest(details.requestId) }; console.log('sending log message: ' + JSON.stringify(logMsg)); this.notifyContentScript_(logMsg); } /** * Helper method for sending a message to the content script. * * @param {*} msg the message to be sent. * * @private */ notifyContentScript_(msg) { // Get the current active tab and send the message to it. chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { chrome.tabs.sendMessage(tabs[0].id, msg); }); } run() { if (!this.didInit_) { const /** @type {Message.Info} */ completeMsg = { type: MessageType.INFO, message: performance.now() + ' starting background script' }; this.notifyContentScript_(completeMsg); const /** @type {!Array.<!string>} */ requestExtraInfoSpec = ['requestHeaders']; const /** @type {!Array.<!string>} */ responseExtraInfoSpec = ['responseHeaders']; const /** @type {!RequestFilter} */ filters = { urls: ['<all_urls>'], }; // Add the event listeners. chrome.webRequest.onSendHeaders.addListener( this.onSendHeaders_.bind(this), filters, requestExtraInfoSpec); chrome.webRequest.onHeadersReceived.addListener( this.onHeadersReceived_.bind(this), filters, responseExtraInfoSpec); chrome.webRequest.onCompleted.addListener( this.onFetchSucceed_.bind(this), filters, responseExtraInfoSpec); chrome.webRequest.onErrorOccurred.addListener( this.onErrorOccurred_.bind(this), filters); chrome.runtime.onMessage.addListener(this.onContentMessage_.bind(this)); this.didInit_ = true; console.log('scheduler inited'); } } }
JavaScript
class StreamLambda extends Lambda { constructor(options) { if (!options) throw new Error('Options required'); super(options); const { EventSourceArn, BatchSize = 1, MaximumBatchingWindowInSeconds, Enabled = true, StartingPosition = 'LATEST' } = options; const required = [EventSourceArn]; if (required.some((variable) => !variable)) throw new Error('You must provide an EventSourceArn'); this.Resources[`${this.LogicalName}EventSource`] = { Type: 'AWS::Lambda::EventSourceMapping', Condition: this.Condition, Properties: { BatchSize, MaximumBatchingWindowInSeconds, Enabled, EventSourceArn, FunctionName: { Ref: this.LogicalName }, StartingPosition } }; const generatedRoleRef = this.Resources[`${this.LogicalName}Role`]; const streamStatement = { Effect: 'Allow', Action: [ 'dynamodb:GetRecords', 'dynamodb:GetShardIterator', 'dynamodb:DescribeStream', 'dynamodb:ListStreams', 'kinesis:GetRecords', 'kinesis:GetShardIterator', 'kinesis:DescribeStream', 'kinesis:ListStreams' ], Resource: [ EventSourceArn, { 'Fn::Sub': ['${arn}/*', { arn: EventSourceArn }] } ] }; if (generatedRoleRef && generatedRoleRef.Properties.Policies) { generatedRoleRef.Properties.Policies[0].PolicyDocument.Statement.push(streamStatement); } else if (generatedRoleRef) { generatedRoleRef.Properties.Policies = [ { PolicyName: 'StreamAccess', PolicyDocument: { Version: '2012-10-17', Statement: [streamStatement] } } ]; } } }
JavaScript
class Card { /** * Constructor. * * @param text The text of the card. * @param type The type of the card. * @param node The DOM element of the card in the editor. */ constructor(text, type, node) { this.text = text this.type = type this.node = node } /** * Removes events for this card for the associated ID * * @param id The ID. */ removeEvents(id) { $(document).off("click", `#del-id-${id}`) $(document).off("click", `#knob-id-${id}`) $("#deck-display").off("click", `#edit-id-${id}`) } }
JavaScript
class User { /** * * @param {number} id * @param {string} firstName * @param {string|null} [lastName] * @param {string|null} [username] */ constructor(id, firstName, lastName, username) { this._id = id this._firstName = firstName this._lastName = lastName this._username = username } /** * Unique identifier for this user or bot * @returns {number} */ get id() { return this._id } /** * User‘s or bot’s first name * @returns {string} */ get firstName() { return this._firstName } /** * User‘s or bot’s last name * @returns {string|null} */ get lastName() { return this._lastName } /** * User‘s or bot’s username * @returns {string|null} */ get username() { return this._username } /** * * @param {Object} raw * @returns {User} */ static deserialize(raw) { return new User(raw['id'], raw['first_name'], raw['last_name'] ? raw['last_name'] : null, raw['username'] ? raw['username'] : null) } /** * * @returns {Object} */ serialize() { return { id: this.id ? this.id : undefined, first_name: this.firstName ? this.firstName : undefined, last_name: this.lastName ? this.lastName : undefined, username: this.username ? this.username : undefined } } /** * * @returns {string} */ toJSON() { return this.serialize() } }
JavaScript
class MultiMapManager extends React.Component { constructor (props) { super(props) // state becomes an object of persistedStateKeys (or component names) with their persisted states' this.state = { intialized: false, maps: [], syncedState: [], visibleState: [], visibleMapCount: 0 } this.syncedView = null this.promisesResolvers = [] // create context when <MultiMapManager> is included in component tree MultiMapContext = React.createContext() } componentDidMount () { window.addEventListener('resize', this.refreshMaps) } refreshMaps = () => { this.forceUpdate() // this refresh needs to fire after the component updates the map views setTimeout(() => this.state.maps.map(map => map.updateSize()), 0) } syncableMapListener = (map, e) => { const { synced, type } = e if (type === 'synced' && !synced) { // reset view of newly desynced map const view = this.state[map.getTargetElement().id].view map.setView(view) } else { this.setSyncedView(map) } this.refreshMaps() } setSyncedView = map => { if (!this.syncedView) { // this is the first map, set the view in state this.syncedView = map.getView() } else { map.setView(this.syncedView) } } addToContext = (config, addToContextProp = () => {}) => { const { map } = config const mapId = map.getTargetElement().id const synced = map.getSyncedState() const visible = map.getVisibleState() const mapConfig = { ...config, synced, visible, view: map.getView() } const newState = { ...this.state, [mapId]: mapConfig } // call original prop addToContextProp(config) this.setState({ ...newState }) // attach listener const listener = e => this.syncableMapListener(map, e) map.on(['synced', 'visible'], listener) if (synced) this.setSyncedView(map) } onMapInitOverride = async (map, onMapInitProp = () => {}) => { const maps = [...this.state.maps, map] this.setState({ maps }) const promise = new Promise((resolve) => { // call original prop onMapInitProp(map) this.promisesResolvers.push(resolve) }) // check for that last time this is called & initialize if (maps.length === this.props.mapsConfig.length) this.intialize() return promise } intialize = async () => { const { maps } = this.state const { contextProps } = await this.props.onMapsInit(maps) // resolve all onMapInit promises now this.promisesResolvers.map(resolve => resolve()) this.refreshMaps() this.setState({ intialized: true, ...contextProps }) } getContextValue = () => { const { contextProps, translations } = this.props const { maps } = this.state const map = maps[0] return { ...this.state, map, onMapAdded: this.onMapAdded, onMapRemoved: this.onMapRemoved, syncedState: maps.map(m => m.getSyncedState()), translations, visibleState: maps.map(m => m.getVisibleState()), visibleMapCount: maps.map(m => m.getVisibleState()).filter(e => e).length, ...contextProps } } childModifier = rawChildren => { const { intialized } = this.state const children = !Array.isArray(rawChildren) ? [rawChildren] : rawChildren const adoptedChildren = children.map((child, i) => { // only render FlexMap & FullScreenFlex until initialized const allow = intialized || child.props.disableAsyncRender if (child?.props?.isMultiMap) { // we caught a map const addToContextOverride = config => this.addToContext(config, child.props.addMapToContext) const onMapInitOverride = map => this.onMapInitOverride(map, child.props.onMapInit) const propsOverride = { ...child.props, addMapToContext: addToContextOverride, onMapInit: onMapInitOverride, _ol_kit_context_id: child.props.id, isMultiMap: true, key: i, map: null // important so <Map> creates a SyncableMap } const adoptedChild = React.cloneElement(child, propsOverride) return adoptedChild } else if (Array.isArray(child)) { // child is an array of children return this.childModifier(child) } else if (child?.props?.children) { // loop through children of children return allow && React.cloneElement(child, { ...child.props }, [this.childModifier(child.props.children)]) } else { // this allows the Maps to render and initialize first before all other comps return allow ? child : null } }) return adoptedChildren } render () { const adoptedChildren = this.childModifier(this.props.children) return ( <ErrorBoundary floating={true}> <MultiMapContext.Provider value={this.getContextValue()}> {adoptedChildren} </MultiMapContext.Provider> </ErrorBoundary> ) } }
JavaScript
class ListerFluxService extends Tache { /** Initialise une nouvelle instance de la classe 'Tache'. * @param requete La requête cliente. * @param reponse Le port de réponse client. */ constructor(requete, reponse){ super(requete, reponse); } /** Execute la tâche. */ executer(){ var tache = this; var bdd = new PontBDD(); var corps = super.obtenirCorpsRequete(); var traceur = new Traceur('ListerFluxService', corps); // Récupération en base de données. traceur.debuterAction("Récupération de la liste des documents disponible."); bdd.listerDocumentsParType(corps.type, corps.nom_pastell, corps.date_debut, corps.date_fin, corps.comparaison_debut, corps.comparaison_fin, corps.etat_document, corps.ordre, corps.direction) .then(function(donnees) { tache.envoiReponseSimple(200, 'Ok', tache.traduire(donnees)); })// FIN : Récupération de la liste des documents disponible. // ERREUR : Récupération de la liste des documents disponible. .catch(function(erreur) { console.log(erreur); tache.envoiReponseSimple(500, "Une erreur est survenue lors de la récupération des document du flux '"+corps.type+"'.", null); }); } /** Traduit les données 'RowPacketData' en JSON. * @param donnees Les données à traduire. */ traduire(donnees) { var resultat = []; for(var i = 0; i < donnees.length; i++) resultat.push({ selection: donnees[i].selection, id: donnees[i].id, id_service: donnees[i].id_service, id_entite: donnees[i].id_entite, id_pastell: donnees[i].id_pastell, etat: donnees[i].etat, date_debut: donnees[i].date_debut, date_fin: donnees[i].date_fin, succes: donnees[i].succes }); return resultat; } }
JavaScript
class TypedError extends Error { constructor (message) { super(); if (Error.hasOwnProperty('captureStackTrace')) Error.captureStackTrace(this, this.constructor); else Object.defineProperty(this, 'stack', { value: (new Error()).stack }); Object.defineProperty(this, 'message', { value: message }); } get name () { return this.constructor.name; } }
JavaScript
class Red extends Component { render () { return ( <div className='emocard-wrapper__red'> <div className='emocard-header__red'> Feeling Red {/* <Mantra className='mantra__red' /> <Timer className='timer__red' /> */} </div> {/* <div className='emocard-emotion emocard-emotion__red'> <Emotion className='emotion emotion__red' /> </div> */} <button className='all-clear'>All Clear</button> </div> ) } }
JavaScript
class Complication extends CharacterTrait { constructor(characterTrait) { super(characterTrait.trait, characterTrait.listKey, characterTrait.getCharacter); this.characterTrait = characterTrait; } cost() { return this.characterTrait.cost(); } costMultiplier() { return this.characterTrait.costMultiplier(); } activeCost() { return this.characterTrait.activeCost(); } realCost() { return this.characterTrait.realCost(); } label() { let label = this.characterTrait.label(); if (this.characterTrait.trait.hasOwnProperty('input')) { switch (this.characterTrait.trait.xmlid.toUpperCase()) { case 'ACCIDENTALCHANGE': label = 'AC'; break; case 'DEPENDENCE': label = 'Dependence'; break; case 'DEPENDENTNPC': label = 'DNPC'; break; case 'DISTINCTIVEFEATURES': label = 'DF'; break; case 'ENRAGED': label = 'Enraged'; break; case 'HUNTED': label = 'Hunted'; break; case 'PHYSICALLIMITATION': label = 'Physical'; break; case 'PSYCHOLOGICALLIMITATION': label = 'Psychological'; break; case 'REPUTATION': label = 'Reputation'; break; case 'SOCIALLIMITATION': label = 'Social'; break; case 'SUSCEPTIBILITY': label = 'Susceptibility'; break; case 'VULNERABILITY': label = 'Vulnerability'; break; default: label = 'Custom'; } label += `: ${this.characterTrait.trait.input}`; } else if (this.characterTrait.trait.xmlid.toUpperCase() === 'RIVALRY') { let adderMap = common.toMap(this.characterTrait.trait.adder); label = `Rivalry: ${adderMap.get('DESCRIPTION').optionAlias.slice(1)}`; } return label; } attributes() { let attributes = this.characterTrait.attributes(); if (this.characterTrait.trait.xmlid.toUpperCase() === 'GENERICDISADVANTAGE') { attributes.unshift({ label: 'Custom Complication', value: '', }); } else { let label = this.characterTrait.trait.template.display; if (this.characterTrait.trait.xmlid.toUpperCase() === 'UNLUCK') { label = label.replace('[LVL]', this.characterTrait.trait.levels); } attributes.unshift({ label: label, value: '', }); } return attributes; } definition() { return this.characterTrait.definition(); } roll() { if (this.characterTrait.trait.xmlid.toUpperCase() === 'UNLUCK') { return { roll: `${this.characterTrait.trait.levels}d6`, type: EFFECT, }; } return this.characterTrait.roll(); } advantages() { return this.characterTrait.advantages(); } limitations() { return this.characterTrait.limitations(); } }
JavaScript
class StrictEventEmitter extends Emitter { /** * Adds the `listener` function as an event listener for `ev`. * * @param ev Name of the event * @param listener Callback function */ on(ev, listener) { super.on(ev, listener); return this; } /** * Adds a one-time `listener` function as an event listener for `ev`. * * @param ev Name of the event * @param listener Callback function */ once(ev, listener) { super.once(ev, listener); return this; } /** * Emits an event. * * @param ev Name of the event * @param args Values to send to listeners of this event */ emit(ev, ...args) { super.emit(ev, ...args); return this; } /** * Emits a reserved event. * * This method is `protected`, so that only a class extending * `StrictEventEmitter` can emit its own reserved events. * * @param ev Reserved event name * @param args Arguments to emit along with the event */ emitReserved(ev, ...args) { super.emit(ev, ...args); return this; } /** * Returns the listeners listening to an event. * * @param event Event name * @returns Array of listeners subscribed to `event` */ listeners(event) { return super.listeners(event); } }
JavaScript
class Structure { /** * Create a new Node and assign a value. * * @param {*} data * @returns {Node} */ createNode(data) { return new Node(data); } /** * Throw an error with a custom interpolated message. * * @param {String} message * @param {Object} params */ error(message, params = {}) { params.class = this.constructor.name; let errorMessage = message; Object.keys(params).forEach(key => { errorMessage = errorMessage.replace('{' + key + '}', params[key]); }); throw new Error(errorMessage); } }
JavaScript
class Report { constructor() { /** * Example of this object: * { * "adsystem.com": { * "positive": [ * { * "pageUrl": "https://example.org/", * "url": "https://adsystem.com/script.js" * "criteria": "......matching criteria...." * } * ], * "negative": [ * { * "pageUrl": "https://example.net/", * "reason": "Page is down" * } * ] * } * } */ this.report = {}; } /** * Records a positive check result. It will be used later to build the report. * * @param {String} name - circumvention system name * @param {String} pageUrl - test page url * @param {String} url - url that matches the circumvention system criteria * @param {Object} criteria - criteria that was used to match this url */ addPositiveResult(name, pageUrl, url, criteria) { const result = this.getOrCreateResult(name); consola.debug(`Positive: ${name} on ${pageUrl}: ${url}`); result.positive.push({ pageUrl, url, criteria, }); } /** * Records a negative check result. It will be used later to build the report. * * @param {String} name - circumvention system name * @param {String} pageUrl - test page url * @param {String} reason - specific reason why the result is negative. * Reason must match {@see reasons}. * @throws {TypeError} if reason is not valid. */ addNegativeResult(name, pageUrl, reason) { if (!reasons[reason]) { throw new TypeError(`${reason} is not a valid reason`); } consola.debug(`Negative: ${name} on ${pageUrl}: ${reason}`); const result = this.getOrCreateResult(name); result.negative.push({ pageUrl, reason, }); } /** * Gets or creates result object by name * * @param {String} name - circumvention system name * @returns {*} result object */ getOrCreateResult(name) { let result = this.report[name]; if (!result) { result = { positive: [], negative: [], }; this.report[name] = result; } return result; } /** * Returns an object with positive and negative results count: * { * "postitive": 5, * "negative": 1 * } * * @returns {*} count of positive and negative results */ count() { const cnt = { positive: 0, negative: 0, }; _.forOwn(this.report, (value) => { cnt.positive += value.positive.length; cnt.negative += value.negative.length; }); return cnt; } /** * Builds the report */ build() { let reportTxt = '# Circumvention report\n\n'; _.forOwn(this.report, (value, key) => { reportTxt += `### ${key}`; reportTxt += '\n'; if (value.positive.length > 0) { reportTxt += '\n'; reportTxt += '#### Positive matches\n\n'; reportTxt += '| Page | URL |\n'; reportTxt += '| --- | --- |\n'; value.positive.forEach((val) => { reportTxt += `| ${val.pageUrl} | ${val.url} |`; reportTxt += '\n'; }); } if (value.negative.length > 0) { reportTxt += '\n'; reportTxt += '#### Negative matches\n\n'; reportTxt += '| Page | Reason |\n'; reportTxt += '| --- | --- |\n'; value.negative.forEach((val) => { reportTxt += `| ${val.pageUrl} | ${val.reason} |`; reportTxt += '\n'; }); } reportTxt += '\n'; }); return reportTxt; } /** * Build blocking rules for the positive results * * @returns {Array<String>} array with basic URL blocking rules */ buildRules() { const rules = []; _.forOwn(this.report, (value, key) => { if (_.isEmpty(value.positive)) { return; } rules.push('! ------------------------------'); rules.push(`! System: ${key}`); rules.push('! ------------------------------'); const byPageUrl = {}; value.positive.forEach((val) => { let matches = byPageUrl[val.pageUrl]; if (!matches) { matches = []; byPageUrl[val.pageUrl] = matches; } matches.push({ url: val.url, criteria: val.criteria, }); }); _.forOwn(byPageUrl, (matches, pageUrl) => { const pageRules = []; for (let i = 0; i < matches.length; i += 1) { const { url, criteria } = matches[i]; const rule = buildRule(url, pageUrl, criteria); if (rules.indexOf(rule) === -1) { pageRules.push(rule); } } if (pageRules.length > 0) { rules.push(`! Found on: ${pageUrl}`); _.uniq(pageRules).forEach((r) => rules.push(r)); } }); }); return rules; } }
JavaScript
class OperatorSubdispatcher extends BaseSubdispatcher { get prefix () { return 'pg_' } get dependencies () { return ['operator'] } get methods () { const operator = this.app.services.operator return { submitBlock: operator.submitBlock.bind(operator), getEthInfo: operator.getEthInfo.bind(operator), getNextBlock: operator.getNextBlock.bind(operator) } } }
JavaScript
class Icon extends Component { //////////////////////// // Methods //////////////////////// render(){ return ( <TouchableOpacity onPress={this.props.onPress}> <Image style={[styles.iconImage, this.props.style]} source={this.props.source} /> </TouchableOpacity> ) } }
JavaScript
class HL_FSCAV_DATA{ constructor(frequency, units, c_units, peak_width, state){ this.frequency = frequency; this.origin_file_array = []; this.current = new HL_FSCV_ARRAY([], units, 'Current'); this.norm_current = new HL_FSCV_ARRAY([], units, 'Norm. current'); this.time = new HL_FSCV_ARRAY([], 's', 'Time'); this.concentration = new HL_FSCV_ARRAY([], c_units, 'Concentration'); //Labels or predictions. // Parameters to calculate the charge, get the linear fit and the SNN model. this.local_neighbours = peak_width; this.local_min_index = [0, 1]; this.local_max_index = 0; this.percentages_interval = [0.2, 0.5]; this.analyte = 'serotonin'; this.max_indexes = []; this.max_values = []; this.min_indexes = []; this.min_values = []; this.total_auc = []; this.line_auc = []; this.auc = []; this.normalised_dataset = []; this.normalised_labels = []; this.linear_fit_parameters = []; this.snn_fit_parameters = []; this.snn_model; // Plotting parameters. this.plot_settings = new HL_PLOT_SETTINGS(); this.cv_plot_state = 'block'; this.fit_plot_state = 'none'; this.state = state; this.graph_index = 0; this.number_of_files = 0; // Whole CV parameters. this.whole_cv_model = new TF_CV_MODEL_CLASS(); }; read_data_from_loaded_files(data, names_of_files, concentration_label){ this.current.array.push(data.map(x => arrayColumn(x, 2))); this.time.array.push(data.map(x => makeArr(0,(x.length-1)/this.frequency, x.length))); this.origin_file_array.push(names_of_files); this.number_of_files+=data.length; this.concentration.array.push(uniform_array(data.length, concentration_label)); }; linearise_data_arrays(){ this.current.array = linearise(this.current.array, 1); this.time.array = linearise(this.time.array, 1); this.origin_file_array = linearise(this.origin_file_array, 1); this.concentration.array = linearise(this.concentration.array, 1); }; data_loading_finished(peak_width, min1, min2, max, percentage_1, percentage_2){ this.linearise_data_arrays(); this.calculate_limits_and_auc(peak_width, min1, min2, max, percentage_1, percentage_2); }; calculate_limits_and_auc(peak_width, min1, min2, max, percentage_1, percentage_2){ this.local_neighbours = peak_width; this.local_min_index = [min1, min2]; this.local_max_index = max; this.percentages_interval = [percentage_1/100, percentage_2/100]; if (this.analyte == 'serotonin'){for(var i=0;i<this.current.array.length; ++i){this.get_max_and_min_values_serotonin(i); this.get_auc(i)};} else {for(var i=0;i<this.current.array.length; ++i){this.get_max_and_min_values_dopamine(i); this.get_auc(i)};} }; get_max_and_min_values_serotonin(index){ let local_max = local_maxima(this.current.array[index], this.local_neighbours); let local_min = local_minima(this.current.array[index], this.local_neighbours); [this.max_indexes[index], this.max_values[index]] = [local_max[0][this.local_max_index], local_max[1][this.local_max_index]]; [this.min_indexes[index], this.min_values[index]] = [[local_min[0][this.local_min_index[0]], local_min[0][this.local_min_index[1]]], [local_min[1][this.local_min_index[0]], local_min[1][this.local_min_index[1]]]]; }; get_max_and_min_values_dopamine(index){ //Get oxidation trace. let oxidation_trace = this.current.array[index].slice(parseInt(this.percentages_interval[0]*this.current.array[index].length), parseInt(this.percentages_interval[1]*this.current.array[index].length)); let oxidation_diff = diff_arr(this.current.array[index], 1).slice(parseInt(this.percentages_interval[0]*this.current.array[index].length), parseInt(this.percentages_interval[1]*this.current.array[index].length)); let local_max = local_maxima(oxidation_trace, this.local_neighbours); let local_min1 = local_minima(oxidation_diff, this.local_neighbours); let local_min2 = local_minima(oxidation_trace, this.local_neighbours); [this.max_indexes[index], this.max_values[index]] = [local_max[0][0]+parseInt(this.percentages_interval[0]*this.current.array[index].length), local_max[1][0]]; [this.min_indexes[index], this.min_values[index]] = [[local_min1[0][0]+parseInt(this.percentages_interval[0]*this.current.array[index].length), local_min2[0][local_min2[0].length-1]+parseInt(this.percentages_interval[0]*this.current.array[index].length)], [this.current.array[index][local_min1[0][0]+parseInt(this.percentages_interval[0]*this.current.array[index].length)], local_min2[1][local_min2[0].length-1]]]; }; get_auc(index){ this.get_normalized_current_array(index); this.total_auc[index] = simpson_auc(this.norm_current.array[index].slice(this.min_indexes[index][0], this.min_indexes[index][1]), this.frequency); var linear_parameters = linear_fit([this.time.array[index][this.min_indexes[index][0]], this.time.array[index][this.min_indexes[index][1]]], [this.norm_current.array[index][this.min_indexes[index][0]], this.norm_current.array[index][this.min_indexes[index][1]]]); var line = this.time.array[index].slice(this.min_indexes[index][0], this.min_indexes[index][1]).map(x => linear_parameters[0]+linear_parameters[1]*x); this.line_auc[index] = simpson_auc(line,this.frequency); this.auc[index] = this.total_auc[index] - this.line_auc[index]; }; get_normalized_current_array(index){ this.norm_current.array[index] = []; for(var j = 0; j<this.current.array[index].length; ++j){this.norm_current.array[index][j] = this.current.array[index][j] - this.min_values[index][0]}; }; change_points(pindex, type){ if(type == "min1"){this.min_indexes[this.graph_index][0] = pindex; this.min_values[this.graph_index][0] = this.current.array[this.graph_index][pindex]} else if(type == "min2"){this.min_indexes[this.graph_index][1] = pindex; this.min_values[this.graph_index][1] = this.current.array[this.graph_index][pindex]} else {this.max_indexes[this.graph_index] = pindex; this.max_values[this.graph_index] = this.current.array[this.graph_index][pindex]}; // Recalculate auc this.get_auc(this.graph_index); }; manual_change_points(value, type){ //Value is given in percentage. if(type =="first_interval_point_button"){ for(var i=0;i<this.current.array.length; ++i){this.min_indexes[i][0] = parseInt(value*this.current.array[i].length/100); this.min_values[i][0] = this.current.array[i][parseInt(value*this.current.array[i].length/100)]; this.get_auc(i)}; } else if(type=="max_point_button"){ for(var i=0;i<this.current.array.length; ++i){this.max_indexes[i] = parseInt(value*this.current.array[i].length/100); this.max_values[i] = this.current.array[i][parseInt(value*this.current.array[i].length/100)]; this.get_auc(i)}; } else if(type=="second_interval_point_button"){ for(var i=0;i<this.current.array.length; ++i){this.min_indexes[i][1] = parseInt(value*this.current.array[i].length/100); this.min_values[i][1] = this.current.array[i][parseInt(value*this.current.array[i].length/100)]; this.get_auc(i)}; }; }; initialise_graph(div){ Plotly.newPlot(div, [], this.plot_settings.plot_layout, this.plot_settings.plot_configuration); }; invert_current_values(div){ this.current.array[this.graph_index] = this.current.array[this.graph_index].map(x => -x); this.get_max_and_min_values(this.graph_index); this.get_auc(this.graph_index); this.plot_graph(div); }; get_linear_fit(div, status_id, type){if(this.state = 'fit'){ this.linear_fit_parameters[0] = linear_fit(this.auc, this.concentration.array); this.linear_fit_parameters[1] = linear_estimation_errors(this.auc.map(x =>this.linear_fit_parameters[0][0]+this.linear_fit_parameters[0][1]*x), this.concentration.array, this.auc); this.get_linear_fit_metrics(div, type); this.update_fitting_status(status_id); }}; get_linear_fit_metrics(div, type){ if(type =='regression_plot_type'){ let x_line_fit = makeArr(index_of_min(this.auc)[0], index_of_max(this.auc)[0], 100); this.plot_scatter_and_line(div, this.concentration.array, this.auc, 'Experimental', 'Experimental', x_line_fit.map(x => this.linear_fit_parameters[0][0]+this.linear_fit_parameters[0][1]*x), x_line_fit, 'Fit', this.concentration.name +" ("+this.concentration.units+")", "Charge ("+this.current.units+"·s)", '<b>Linear Fit</b>', '<b>S(Q) = '+this.linear_fit_parameters[0][0].toFixed(2)+ ' + '+this.linear_fit_parameters[0][1].toFixed(2)+' · Q<br>'+'R<sup>2</sup> = '+this.linear_fit_parameters[0][2].toFixed(2)+'</b>'); } else{ this.plot_scatter_and_line(div, this.concentration.array, this.auc.map(x => this.linear_fit_parameters[0][0]+this.linear_fit_parameters[0][1]*x), 'Experimental', this.origin_file_array, makeArr(0,index_of_max(this.concentration.array)[0], 100), makeArr(0,index_of_max(this.concentration.array)[0], 100), "Ideal", 'True values: '+this.concentration.name+' ('+this.concentration.units+')', 'Predicted values: '+this.concentration.name+' ('+this.concentration.units+')', 'Linear Fit', '<b>SEE: ' + this.linear_fit_parameters[1][0].toFixed(2) +' '+this.concentration.units+'</b>'); }; }; predict_from_linear_fit(div, linear_fit_parameters){if(this.state = 'predict'){ // Method only to be used by objects in predict mode. this.get_prediction_from_linear_fit(linear_fit_parameters, this); this.plot_scatter_and_line(div, makeArr(0,this.concentration.array.length-1, this.concentration.array.length-1), this.concentration.array, 'Predictions', this.origin_file_array, [], [], '', 'File number', this.concentration.name +" ("+this.concentration.units+")", '<b>Predictions</b>', 'Predictions from linear fit'); }}; get_prediction_from_linear_fit(linear_fit_parameters, fscav_data){ fscav_data.linear_fit_parameters = linear_fit_parameters; fscav_data.concentration.array = fscav_data.auc.map(x => linear_fit_parameters[0][0]+linear_fit_parameters[0][1]*x); }; show_predict_charge(div){if(this.state = 'predict'){ this.plot_scatter_and_line(div, makeArr(0,this.auc.length-1, this.auc.length-1), this.auc, 'Charge plot', this.origin_file_array, [], [], '', 'File number', "Charge ("+this.current.units+"·s)", '<b>Charge plot</b>', 'Estimated charge from voltammograms.'); }}; get_snn_fit(div, epochs, learning_rate, layer_size, patience, min_delta, dropout_rate, std_noise, status_id, snn_type){if(this.state = 'fit'){ var self = this; this.get_normalised_training_set([this.auc, this.line_auc, arrayColumn(this.min_values, 1), arrayColumn(this.max_values, 0)], this.concentration.array); if(snn_type === 'single_electrode'){this.define_new_snn_model(std_noise, layer_size, dropout_rate); this.compile_and_fit(self, div, learning_rate, epochs, patience, min_delta, status_id);} else if(snn_type == 'multiple_electrodes'){tf.loadLayersModel("TensorFlowModels/dnn_fscav.json").then(model => self.get_loaded_model(model, std_noise, dropout_rate)).then(() => self.compile_and_fit(self, div, learning_rate, epochs, patience, min_delta, status_id))}; }}; define_new_snn_model(std_noise, layer_size, dropout_rate){ this.snn_model = tf.sequential({layers: [tf.layers.gaussianNoise({stddev:std_noise, inputShape: [4]}), tf.layers.dense({units: layer_size, activation: 'relu'}),tf.layers.gaussianDropout({rate:dropout_rate}), tf.layers.dense({units: layer_size, activation: 'relu'}), tf.layers.dense({units: 1})]}); }; get_loaded_model(model, std_noise, dropout_rate){ this.snn_model = model; this.snn_model.layers[0].outboundNodes[0].outboundLayer.stddev = std_noise; // Change Gaussian STD of noise. this.snn_model.layers[2].outboundNodes[0].outboundLayer.rate = dropout_rate; //Change the dropout rate. }; compile_and_fit(self, div, learning_rate, epochs, patience, min_delta, status_id){ this.snn_model.compile({optimizer: tf.train.adam(learning_rate), loss: tf.losses.meanSquaredError, metrics: [tf.metrics.meanSquaredError]}); const data = tf.tensor(transpose(this.normalised_dataset[0])); const labels = tf.tensor(this.normalised_labels[0]); this.snn_model.fit(data, labels, {epochs: epochs, validationSplit:0.1, callbacks: tf.callbacks.earlyStopping({monitor: 'val_loss', patience: patience, minDelta: min_delta})}).then(info => { self.update_fitting_status(status_id); this.snn_fit_parameters[0] = [info.history.loss, info.history.val_loss]; self.get_snn_fitting_metrics(div); }); }; get_snn_fitting_metrics(div){if(this.state = 'fit'){ // Function to calculate and plot the predictions of the snn with the train data. Important: good predictions do not mean it will perform well with other data. const data = tf.tensor(transpose(this.normalised_dataset[0])); let predicted_concentration = denormalize(Array.from(this.snn_model.predict(data).dataSync()), this.normalised_labels[1], this.normalised_labels[2]); this.snn_fit_parameters[1] = Math.sqrt(mse(this.concentration.array, predicted_concentration)); this.plot_scatter_and_line(div, this.concentration.array, predicted_concentration, 'Experimental', this.origin_file_array, makeArr(0,index_of_max(this.concentration.array)[0], 100), makeArr(0,index_of_max(this.concentration.array)[0], 100), 'Ideal', 'True values: '+this.concentration.name+' ('+this.concentration.units+')', 'Predicted values: '+this.concentration.name+' ('+this.concentration.units+')', 'SNN Fit', '<b>RMSE: ' + this.snn_fit_parameters[1].toFixed(2) +' '+this.concentration.units+'</b>'); }}; predict_from_snn(div, snn_model, norm_data, norm_labels){if(this.state = 'predict'){ this.get_prediction_from_snn(snn_model, norm_data, norm_labels, this); this.plot_scatter_and_line(div, makeArr(0,this.concentration.array.length-1, this.concentration.array.length), this.concentration.array, 'Predictions', this.origin_file_array, [], [], '', 'File number', this.concentration.name +" ("+this.concentration.units+")", '<b>Predictions</b>', 'Predictions from SNN'); }}; get_prediction_from_snn(snn_model, norm_data, norm_labels, fscav_data){ //Assign model and normalization to predict object. this.snn_model = snn_model; const data = tf.tensor(transpose(this.get_normalised_prediction_set([fscav_data.auc, fscav_data.line_auc, arrayColumn(fscav_data.min_values, 1), arrayColumn(fscav_data.max_values, 0)], norm_data[1], norm_data[2]))); fscav_data.concentration.array = denormalize(Array.from(fscav_data.snn_model.predict(data).dataSync()), norm_labels[1], norm_labels[2]); }; update_fitting_status(status_id){ _(status_id).innerHTML = "&#10004"; }; get_normalised_training_set(data, labels){if(this.state = 'fit'){ let max = [], min = [], norm_data = [], max_labels = index_of_max(labels)[0], min_labels = index_of_min(labels)[0], norm_labels = normalize(labels, max_labels, min_labels); for(var i = 0; i<data.length;++i){max[i] = index_of_max(data[i])[0]; min[i] = index_of_min(data[i])[0]; norm_data[i] = normalize(data[i], max[i], min[i])}; this.normalised_dataset = [norm_data, max, min]; this.normalised_labels = [norm_labels, max_labels, min_labels]; }}; get_normalised_prediction_set(data, training_max, training_min){if(this.state = 'predict'){ let norm_data = []; for(var i = 0; i<data.length; ++i){norm_data[i] = normalize(data[i], training_max[i], training_min[i])}; return norm_data; }}; predict_from_snn_whole_cv_model(div, std_noise, dropout_rate){ var self = this; tf.loadLayersModel("TensorFlowModels/dnn_fscav_whole_cv.json").then(model => self.get_loaded_model(model, std_noise, dropout_rate)).then(() => self.get_prediction_from_snn_whole_cv_model(div)); }; get_prediction_from_snn_whole_cv_model(div){if(this.state = 'predict'){ this.get_normalised_whole_cv_dataset(); const data = tf.tensor(this.normalised_dataset); let a = this.snn_model.predict(data).dataSync(); this.concentration.array = Array.from(a); this.plot_scatter_and_line(div, makeArr(0,this.concentration.array.length-1, this.concentration.array.length), this.concentration.array, 'Predictions', this.origin_file_array, [], [], '', 'File number', this.concentration.name +" ("+this.concentration.units+")", '<b>Predictions</b>', 'Predictions from SNN'); }}; get_normalised_whole_cv_dataset(){ let transposed_cvs = transpose(this.current.array); let norm_transposed_cvs = []; for (let i = 0; i<transposed_cvs.length;++i){ norm_transposed_cvs[i] = standard_normalize(transposed_cvs[i], this.whole_cv_model.mean_features[i], this.whole_cv_model.std_features[i]); }; this.normalised_dataset = transpose(norm_transposed_cvs); }; plot_graph(div){ var layout = this.plot_settings.plot_layout; layout.title.text = "<b>"+this.origin_file_array[this.graph_index]+"</b>"; layout.xaxis = {title:this.time.name +" ("+this.time.units+")"}; layout.yaxis = {title:this.current.name +" ("+this.current.units+")"}; if(this.state == 'fit'){ layout.annotations = [{ xref: 'paper', yref: 'paper', x: 0.98, xanchor: 'right', y: 0.9, yanchor: 'bottom', text: '<b>Fitting signals<br>'+this.concentration.name+': '+this.concentration.array[this.graph_index]+' '+this.concentration.units+'</b>', showarrow: false }]; } else{ layout.annotations = [{ xref: 'paper', yref: 'paper', x: 0.98, xanchor: 'right', y: 0.9, yanchor: 'bottom', text: '<b>Prediction signals</b>', showarrow: false }]; }; var trace = { y: this.current.array[this.graph_index], x:this.time.array[this.graph_index], text:this.origin_file_array[this.graph_index], showlegend: false, }; let scatter_data_max = { y:[this.current.array[this.graph_index][this.max_indexes[this.graph_index]]], x:[this.time.array[this.graph_index][this.max_indexes[this.graph_index]]], name: 'Points', type: 'scatter', showlegend: false, mode: 'markers', marker: {color: 'black'}, text:'Max' }; let scatter_data_min = { y:[this.current.array[this.graph_index][this.min_indexes[this.graph_index][0]], this.current.array[this.graph_index][this.min_indexes[this.graph_index][1]]], x:[this.time.array[this.graph_index][this.min_indexes[this.graph_index][0]], this.time.array[this.graph_index][this.min_indexes[this.graph_index][1]]], name: 'Points', type: 'scatter', showlegend: false, mode: 'markers+lines', line: {color: 'black', width:0.5, dash: 'dot'}, marker: {color: 'black'}, text:'Min' }; _(div).style.display = "block"; Plotly.newPlot(div, [trace], layout, this.plot_settings.plot_configuration); Plotly.addTraces(div, [scatter_data_max, scatter_data_min]); // Assign callback when click to local function graph_click(); _(div).on('plotly_click', function(data){graph_clicked(data)}); _(div).style.display = this.cv_plot_state; }; plot_scatter_and_line(div, x, y, scatter_name, scatter_text, x_line, y_line, line_name, x_label, y_label, title, annotations){ var layout = this.plot_settings.plot_layout; layout.title.text = "<b>"+title+"</b>"; layout.xaxis = {title:x_label}; layout.yaxis = {title:y_label}; layout.annotations = [{ xref: 'paper', yref: 'paper', x: 0.98, xanchor: 'right', y: 0.1, yanchor: 'bottom', text: annotations, showarrow: false }]; let scatter = { y:y, x:x, name: scatter_name, type: 'scatter', showlegend: false, mode: 'markers', marker: {color: 'black'}, text:scatter_text }; let trace = { y: y_line, x: x_line, text:line_name, showlegend: false, }; _(div).style.display = "block"; Plotly.newPlot(div, [trace], layout, this.plot_settings.plot_configuration); Plotly.addTraces(div, [scatter]); _(div).style.display = this.fit_plot_state; }; export_to_xlsx(fscav_data_predict){if(this.state = 'fit'){ // Export parameters calculated from the CVs. var wb = XLSX.utils.book_new(), aoa; // Export fitting parameters. if(this.current.array?.length){ aoa = transpose([this.auc, this.line_auc, arrayColumn(this.min_values, 0), arrayColumn(this.min_values, 1), arrayColumn(this.max_values, 0), this.origin_file_array, this.concentration.array]); aoa.unshift(['Charge above line ('+this.current.units+'· s)', 'Charge below line ('+this.current.units+'· s)', 'Interval start (sample)', 'Interval end (sample)', 'Max point (sample)', 'File', this.concentration.name +' ('+this.concentration.units+')']); XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(aoa), "FSCAV Parameters")}; // Export prediction parameters. if(fscav_data_predict.current.array?.length){ aoa = transpose([fscav_data_predict.auc, fscav_data_predict.line_auc, arrayColumn(fscav_data_predict.min_values, 0), arrayColumn(fscav_data_predict.min_values, 1), arrayColumn(fscav_data_predict.max_values, 0), fscav_data_predict.origin_file_array]); aoa.unshift(['Charge above line ('+fscav_data_predict.current.units+'· s)', 'Charge below line ('+fscav_data_predict.current.units+'· s)', 'Interval start (value)', 'Interval end (value)', 'Max point (value)','File']); XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(aoa), 'Prediction Parameters')}; // Export linear fit parameters. if(this.linear_fit_parameters?.length){XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet([['Slope','SE slope', 'Intercept', 'SE intercept', 'R^2', 'SEE'], [this.linear_fit_parameters[0][1], this.linear_fit_parameters[1][1], this.linear_fit_parameters[0][0], this.linear_fit_parameters[1][2], this.linear_fit_parameters[0][2], this.linear_fit_parameters[1][0]]]), 'Fitting Parameters')}; //Export SNN fit parameters if(this.snn_model){XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet([['RMSE'], [this.snn_fit_parameters[1]]]), 'SNN Fit Parameters')}; //Export model SNN predictions. if(fscav_data_predict.concentration.array?.length){aoa = transpose([fscav_data_predict.concentration.array.slice()]); aoa.unshift([this.concentration.name + ' ('+this.concentration.units+')']);XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(aoa), 'Predictions')}; XLSX.writeFile(wb, 'FSCAV_calibration_AK.xlsx'); }; }; }
JavaScript
class Turtle { /** * Instanciates a turtle * @param {Integer} x - position in the horizontal axis * @param {Integer} y - position in the vertical axis * @param {Float} angle - Direction. In degrees, angle between the direction's vector of Turtle and the X axis's vector * @param {Boolean} drawing - If true, movements will be drawn to canvas * @param {Boolean} hidden - If true, the turtle won't be shown on canvas, if false, it will be * @constructor */ constructor(x, y, angle, drawing, hidden) { this.position = new Vector(x, y); this.previousPos = this.position.clone(); this.angle = new Vector(1, 0); this.angle.rotateDeg(angle).normalize(); this.drawing = drawing; this.hidden = hidden; this.draw(); } /** * Draw the turtle on screen */ draw() { turtleRenderingContext.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); if (!this.hidden) { turtleRenderingContext.strokeStyle = '#FFFF00'; turtleRenderingContext.beginPath(); turtleRenderingContext.moveTo(this.position.x, this.position.y); turtleRenderingContext.arc( this.position.x, this.position.y, 10, this.angle.angle() + (Math.PI / 4), this.angle.angle() + (7 * Math.PI / 4) ); turtleRenderingContext.closePath(); turtleRenderingContext.stroke(); } } /** * Draw the path the turtle just traveled through */ drawPath() { if (this.drawing) { renderingContext.beginPath(); renderingContext.moveTo(this.previousPos.x, this.previousPos.y); renderingContext.lineTo(this.position.x, this.position.y); renderingContext.closePath(); renderingContext.stroke(); } } /** * Draw the new step of the drawing plus the turtle on the canvas */ update() { //draw the new step and save the step this.drawPath(); //draw the turtle on top of everything this.draw(); } /** * Move the turtle along a line defined by the turtle's direction (angle) * @param {Integer} distance - Distance to travel from current position to new position */ moveAlongDirection(distance) { //TODO: move by a number of pixels, not by a distance this.previousPos = this.position.clone(); this.position.add( this.angle.clone().multiply( new Vector(distance, distance) ) ); this.update(); } /** * Add degrees to turtle's current angle (CCW) * @param {Integer} degrees - Amount of degrees to add to current angle */ rotateBy(degrees) { this.angle.rotateDeg(degrees).normalize(); this.draw(); } /** * Set hidden, and then redraw the canvas with(out) the turtle * @param {Boolean} hidden - whether the turtle is hidden or not */ setHidden(hidden) { this.hidden = hidden; this.draw(); } }
JavaScript
class UserModel { constructor() { this.login = ''; this.email = ''; } /** * Async check on current user auth. * * @param loadFromServer {Boolean} If true, requests server API. If false, checks local storage. Defaults to false * @param serviceLocator {ServiceLocator} Instance of Service Locator. Required then loadFromServer == true * @returns {Promise} In resolve we get UserModel. When is auth false - call reject */ static loadCurrent(loadFromServer = false, serviceLocator = null) { if (loadFromServer) { return serviceLocator.api.get('user') .then((dataFromServer) => dataFromServer.json(), {}) .then((json) => UserModel.fromApiJson(json.message)); } return new Promise((resolve, reject) => { const jsonStr = localStorage.getItem('user'); if (!jsonStr) { reject(); return; } const json = JSON.parse(jsonStr); if (!json) { reject(); return; } const model = UserModel.fromApiJson(json); resolve(model); }); } static loadCurrentSyncronized() { return JSON.parse(localStorage.getItem('user')); } /** * Parses server API response and creates model instance. * * @param json {Object} JSON object from server API * @return {UserModel} New model instance */ static fromApiJson(json) { const model = new UserModel(); model.login = json.login; model.email = json.email; return model; } /** * Saves current object in localStorage */ saveInLocalStorage() { try { localStorage.setItem('user', JSON.stringify(this)); } catch (exception) { console.log('Error while write to storage!!!\n' + exception); } } static clearInLocalStorage() { localStorage.removeItem('user'); } }
JavaScript
class Session { constructor(modules) { this.map = new Map([['_', modules._]]); this.flushed = new Set; this.modules = modules; } add(module) { if (!this.map.has(module)) { const info = this.modules[module]; info.dependencies.forEach(this.add, this); this.map.set(module, info); } return this; } flush() { const output = []; this.map.forEach(({module, code}, name) => { if (!this.flushed.has(name)) { this.flushed.add(name); output.push(module); } if (0 < code.length) output.push(code); }); this.map.clear(); return output.join('\n'); } }
JavaScript
class CandidatoBox extends Component { render() { return ( <ContainerTextoCandidato className="testing_align"> {this.props.eleitoSenador && <SenadorQuadroFoto> {this.props.eleitoSenador === "s" ? <span>Eleito</span> : ""} <img src={this.props.srcImagem} /> </SenadorQuadroFoto>} <NomeCandidato> {this.props.nome} </NomeCandidato> {this.props.eleitoSenador ? <PartidoCandidato> {this.props.partido} </PartidoCandidato> : <PartidoCandidatoSmall> {this.props.partido} </PartidoCandidatoSmall>} {this.props.eleitoSenador ? <PercentualCandidato> {this.props.percentual} </PercentualCandidato> : <PercentualCandidatoSmall> {this.props.percentual} </PercentualCandidatoSmall>} <VotosCandidato> {this.props.votos} </VotosCandidato> {/* {this.props.eleito && this.props.eleitoSenador && <progress value={this.props.percentual} max="100"> </progress>} */} {this.props.eleito && this.props.eleitoSenador && <BarraDeProgresso percentual={this.props.percentual} />} </ContainerTextoCandidato> ) } }
JavaScript
class SR5Item extends Item { static async create(data, options) { if (!data.img) { data.img = `systems/sr5/img/items/${data.type}.svg`; } return super.create(data, options); } prepareData() { super.prepareData(); const itemData = this.data; const data = itemData.data; let owner, ownerData; if(this.actor?.data){ owner = this.actor.data; let ownerObject = this.actor.data.toObject(false); ownerData = ownerObject.data; } SR5_UtilityItem._resetItemModifiers(itemData); switch (itemData.type) { case "itemWeapon": // Pour faire fonctionner l'ajout et la suppression d'accessoire (pas trouvé mieux :/) if (typeof data.accessory === "object") data.accessory = Object.values(data.accessory); if (data.damageElement === "toxin") SR5_UtilityItem._handleWeaponToxin(data, owner); if (data.ammunition.value > data.ammunition.max) data.ammunition.value = data.ammunition.max; if (data.category === "meleeWeapon" && owner){ if (!data.isLinkedToFocus) SR5_UtilityItem._handleWeaponFocus(itemData, owner); SR5_UtilityItem._checkIfWeaponIsFocus(this, owner); if (!owner.data.visions.astral.isActive) data.isUsedAsFocus = false; } if (Object.keys(data.itemEffects).length) SR5_UtilityItem.applyItemEffects(itemData); SR5_UtilityItem._handleBow(itemData); SR5_UtilityItem._handleWeaponAccessory(data, owner); SR5_UtilityItem._handleWeaponAmmunition(data); SR5_UtilityItem._generateWeaponRange(data, owner); SR5_UtilityItem._generateWeaponDicepool(itemData, owner); SR5_UtilityItem._generateWeaponDamage(data, owner); SR5_UtilityItem._handleMatrixMonitor(itemData); SR5_EntityHelpers.GenerateMonitorBoxes(data, 'matrix'); SR5_UtilityItem._handleItemPrice(data); SR5_UtilityItem._handleItemAvailability(data); if (data.conditionMonitors.matrix.actual.value >= data.conditionMonitors.matrix.value) { data.wirelessTurnedOn = false; } break; case "itemSpell": if (data.quickening) data.freeSustain = true; break; case "itemAmmunition": SR5_UtilityItem._handleAmmoPrice(data); SR5_UtilityItem._handleItemAvailability(data); break; case "itemPreparation": if (owner) SR5_UtilityItem._handlePreparation(itemData); break; case "itemRitual": if (owner) SR5_UtilityItem._handleRitual(itemData, owner); break; case "itemKnowledge": if (owner) SR5_CharacterUtility._generateKnowledgeSkills(data, owner); break; case "itemLanguage": if (owner) SR5_CharacterUtility._generateLanguageSkills(data, owner); break; case "itemAugmentation": SR5_UtilityItem._handleAugmentation(data); SR5_UtilityItem._handleMatrixMonitor(itemData); SR5_EntityHelpers.GenerateMonitorBoxes(data, 'matrix'); if (data.conditionMonitors.matrix.actual.value >= data.conditionMonitors.matrix.value) { data.wirelessTurnedOn = false; } if (owner){ if (data.isAccessory) { SR5_UtilityItem._checkIfAccessoryIsPlugged(itemData, owner); if (!data.isPlugged) { data.isActive = false; data.wirelessTurnedOn = false; } } } break; case "itemArmor": case "itemGear": if (itemData.type === "itemArmor"){ if (Object.keys(data.itemEffects).length) { SR5_UtilityItem.applyItemEffects(itemData); } SR5_UtilityItem._handleArmorValue(data); } SR5_UtilityItem._handleItemCapacity(data); SR5_UtilityItem._handleItemPrice(data); SR5_UtilityItem._handleItemAvailability(data); SR5_UtilityItem._handleItemConcealment(data); SR5_UtilityItem._handleMatrixMonitor(itemData); SR5_EntityHelpers.GenerateMonitorBoxes(data, 'matrix'); if (data.conditionMonitors.matrix.actual.value >= data.conditionMonitors.matrix.value) { data.wirelessTurnedOn = false; } if (owner){ if (data.isAccessory) { SR5_UtilityItem._checkIfAccessoryIsPlugged(itemData, owner); if (!data.isPlugged) { data.isActive = false; data.wirelessTurnedOn = false; } } } break; case "itemDevice": SR5_UtilityItem._handleCommlink(data); SR5_UtilityItem._handleItemPrice(data); SR5_UtilityItem._handleItemAvailability(data); if (Object.keys(data.itemEffects).length) { SR5_UtilityItem.applyItemEffects(itemData); } SR5_UtilityItem._handleMatrixMonitor(itemData); if ((data.conditionMonitors.matrix.actual.value >= data.conditionMonitors.matrix.value) && (data.type !== "baseDevice")) { data.isActive = false; } SR5_EntityHelpers.GenerateMonitorBoxes(data, 'matrix'); break; case "itemFocus": SR5_UtilityItem._handleFocus(data); break; case "itemSpirit": SR5_UtilityItem._handleSpirit(data); break; case "itemAdeptPower": SR5_UtilityItem._handleAdeptPower(data, owner); break; case "itemPower": if (owner) SR5_UtilityItem._handlePower(data, owner) break; case "itemSpritePower": if (owner) SR5_UtilityItem._handleSpritePower(data, owner) break; case "itemProgram": SR5_UtilityItem._handleItemPrice(data); SR5_UtilityItem._handleItemAvailability(data); break; case "itemLifestyle": if (typeof data.options === "object") data.options = Object.values(data.options); SR5_UtilityItem._handleLifeStyle(data); SR5_UtilityItem._handleItemPrice(data); break; case "itemSin": if (typeof data.license === "object") data.license = Object.values(data.license); SR5_UtilityItem._handleSinLicense(data); SR5_UtilityItem._handleItemPrice(data); SR5_UtilityItem._handleItemAvailability(data); break; case "itemSprite": SR5_UtilityItem._handleMatrixMonitor(itemData); SR5_EntityHelpers.GenerateMonitorBoxes(data, 'matrix'); break; case "itemVehicle": if (typeof data.mount === "object") data.mount = Object.values(data.mount); SR5_UtilityItem._handleVehicle(data); SR5_UtilityItem._handleItemPrice(data); SR5_UtilityItem._handleItemAvailability(data); SR5_UtilityItem._handleMatrixMonitor(itemData); if (data.type === "drone") data.conditionMonitors.condition.base = Math.ceil((data.attributes.body / 2) + 6); else data.conditionMonitors.condition.base = Math.ceil((data.attributes.body / 2) + 12); SR5_EntityHelpers.updateValue(data.conditionMonitors.condition, 1) SR5_EntityHelpers.updateValue(data.conditionMonitors.condition.actual, 0); SR5_EntityHelpers.GenerateMonitorBoxes(data, 'condition'); SR5_EntityHelpers.GenerateMonitorBoxes(data, 'matrix'); break; case "itemDrug": SR5_UtilityItem._handleItemPrice(data); SR5_UtilityItem._handleItemAvailability(data); data.vector.value = []; for (let key of Object.keys(SR5.propagationVectors)) { if (data.vector[key]) { data.vector.value.push(game.i18n.localize(SR5.propagationVectors[key])); } } break; default: } //Etiquette pour afficher le label des jets. const labels = {}; this.labels = labels; return itemData; } // Expand data is used in most dropdown infos getExpandData(htmlOptions) { const data = duplicate(this.data.data); let lists = SR5_EntityHelpers.sortTranslations(SR5); let tags =[]; let accessories =[]; data.description = data.description || ""; data.description = TextEditor.enrichHTML(data.description, htmlOptions); switch(this.data.type){ case "itemAugmentation": tags.push( game.i18n.localize(lists.augmentationTypes[data.type]), game.i18n.localize(lists.augmentationCategories[data.category]), game.i18n.localize(lists.augmentationGeneCategories[data.category]), ); if (data.type === "bioware" || data.type === "culturedBioware" || data.type === "cyberware" || data.type === "nanocyber" || data.type === "symbionts") { tags.push(game.i18n.localize(lists.augmentationGrades[data.grade])); } if (data.itemRating > 0) { tags.push(game.i18n.localize("SR5.ItemRating") + ` ${data.itemRating}`); } if (data.marks.length){ for (let m of data.marks){ tags.push(game.i18n.localize("SR5.Mark") + game.i18n.localize(`SR5.Colons`) + ` ${m.ownerName} [${m.value}]`); } } if (data.isSlavedToPan){ let panMaster = SR5_EntityHelpers.getRealActorFromID(data.panMaster); tags.push(game.i18n.localize("SR5.DeviceSlavedToPan") + ` (${panMaster.name})`); } break; case "itemWeapon": if (data.category === "rangedWeapon"){ tags.push( game.i18n.localize(lists.rangedWeaponTypes[data.type]), game.i18n.localize(`SR5.WeaponModesShort`) + game.i18n.localize(`SR5.Colons`) + ` ${data.firingMode.value}`, game.i18n.localize(`SR5.RecoilCompensationShort`) + game.i18n.localize(`SR5.Colons`) + ` ${data.recoilCompensation.value}`, game.i18n.localize(`SR5.WeaponRange`) + game.i18n.localize(`SR5.Colons`) + ` ${data.range.short.value}/${data.range.medium.value}/${data.range.long.value}/${data.range.extreme.value}` + game.i18n.localize(`SR5.MeterUnit`), game.i18n.localize(`SR5.Ammunition`) + game.i18n.localize(`SR5.Colons`) + ` ` + game.i18n.localize(lists.allAmmunitionTypes[data.ammunition.type]), ); if (data.accessory) { for (let a of data.accessory){ accessories.push(`${a.name}: ${a.data?.gameEffect}`); tags.push([game.i18n.localize(lists.weaponAccessories[a.name]), a.gameEffects]); } } } else if (data.category === "meleeWeapon"){ tags.push( game.i18n.localize(lists.meleeWeaponTypes[data.type]), game.i18n.localize(`SR5.WeaponReach`) + game.i18n.localize(`SR5.Colons`) + ` ${data.reach.value}`, ); } else if (data.category === "grenade"){ tags.push( game.i18n.localize(`SR5.WeaponRange`) + game.i18n.localize(`SR5.Colons`) + ` ${data.range.short.value}/${data.range.medium.value}/${data.range.long.value}/${data.range.extreme.value}` + game.i18n.localize(`SR5.MeterUnit`), ); } if (data.marks.length){ for (let m of data.marks){ tags.push(game.i18n.localize("SR5.Mark") + game.i18n.localize(`SR5.Colons`) + ` ${m.ownerName} [${m.value}]`); } } if (data.isSlavedToPan){ let panMaster = SR5_EntityHelpers.getRealActorFromID(data.panMaster); tags.push(game.i18n.localize("SR5.DeviceSlavedToPan") + ` (${panMaster.name})`); } break; case "itemPreparation": case "itemSpell": tags.push(`${game.i18n.localize('SR5.SpellType')}${game.i18n.localize('SR5.Colons')} ${game.i18n.localize(lists.spellTypes[data.type])}`); tags.push(game.i18n.localize(lists.spellCategories[data.category])); switch (data.category){ case "combat": tags.push(game.i18n.localize(lists.spellCombatTypes[data.subCategory])); break; case "detection": tags.push( game.i18n.localize(lists.spellDetectionTypes[data.subCategory]), game.i18n.localize(lists.spellDetectionSens[data.detectionSense]), ); break; case "health": if (data.healthEssence){ tags.push(game.i18n.localize(`SR5.Essence`)); } break; case "illusion": tags.push( game.i18n.localize(lists.spellIllusionTypes[data.subCategory]), game.i18n.localize(lists.spellIllusionSens[data.illusionSense]), ); break; case "manipulation": tags.push(game.i18n.localize(lists.spellManipulationTypes[data.subCategory])); if (data.manipulationDamaging){ tags.push(game.i18n.localize(`SR5.Damaging`)); } break; default: } if (this.data.type === "itemSpell") { let plus = (data.drain.value <= 0 ? "" : "+"); tags.push(`${game.i18n.localize('SR5.SpellDrain')}${game.i18n.localize('SR5.Colons')} ${game.i18n.localize('SR5.SpellForceShort')} ${plus}${data.drain.value}`); tags.push(`${game.i18n.localize('SR5.SpellDrainActual')}${game.i18n.localize('SR5.Colons')} ${data.drainValue.value}`); } break; case "itemGear": if (data.marks.length){ for (let m of data.marks){ tags.push(game.i18n.localize("SR5.Mark") + game.i18n.localize(`SR5.Colons`) + ` ${m.ownerName} [${m.value}]`); } } if (data.isSlavedToPan){ let panMaster = SR5_EntityHelpers.getRealActorFromID(data.panMaster); tags.push(game.i18n.localize("SR5.DeviceSlavedToPan") + ` (${panMaster.name})`); } break; case "itemRitual": if (data.anchored) tags.push(game.i18n.localize(`SR5.Anchored`)); if (data.materialLink) tags.push(game.i18n.localize(`SR5.MaterialLink`)); if (data.minion) tags.push(game.i18n.localize(`SR5.Minion`)); if (data.spotter) tags.push(game.i18n.localize(`SR5.Spotter`)); if (data.spell) tags.push(game.i18n.localize(`SR5.Spell`)); tags.push(`${game.i18n.localize('SR5.DurationToPerform')}${game.i18n.localize('SR5.Colons')} ${game.i18n.localize('SR5.SpellForceShort')} × ${game.i18n.localize(lists.ritualDurations[data.durationToPerform])}`); break; case "itemAdeptPower": tags.push(`${game.i18n.localize('SR5.PowerPointsCost')}${game.i18n.localize('SR5.Colons')} ${data.powerPointsCost.value}`); tags.push(`${game.i18n.localize('SR5.ActionType')}${game.i18n.localize('SR5.Colons')} ${game.i18n.localize(lists.actionTypes[data.actionType])}`); break; case "itemQuality": tags.push(`${game.i18n.localize(lists.qualityTypes[data.type])}`); if (data.itemRating !== 0) tags.push(`${game.i18n.localize('SR5.ItemRating')}${game.i18n.localize('SR5.Colons')} ${data.itemRating}`); tags.push(`${game.i18n.localize('SR5.KarmaCost')}${game.i18n.localize('SR5.Colons')} ${data.karmaCost}`); break; default: } data.properties = tags.filter(p => !!p); data.accessories = accessories.filter(p => !!p); return data; } // Recharge les armes à distance reloadAmmo() { let lists = SR5_EntityHelpers.sortTranslations(SR5); let ownerActor, itemAmmoData; if (this.actor.isToken) ownerActor = SR5_EntityHelpers.getRealActorFromID(this.actor.token.id); else ownerActor = SR5_EntityHelpers.getRealActorFromID(this.actor.id); const data = duplicate(this.data); let ammoNeeded = data.data.ammunition.max - data.data.ammunition.value; if (ammoNeeded < 1) return; let itemAmmo = ownerActor.items.find((item) => item.type === "itemAmmunition" && (item.data.data.type === data.data.ammunition.type) && (item.data.data.class === data.data.type)); if (itemAmmo) { itemAmmoData = itemAmmo.data.toObject(); if (itemAmmoData.data.quantity <=0) { Dialog.confirm({ title: game.i18n.localize('SR5.DIALOG_WarningNoMoreAmmoTitle'), content: "<h3>" + game.i18n.localize('SR5.DIALOG_Warning') + "</h3><p>" + game.i18n.format('SR5.DIALOG_WarningNoMoreAmmo', {actor: ownerActor.name, ammoType: game.i18n.localize(lists.allAmmunitionTypes[data.data.ammunition.type]), weaponType: game.i18n.localize(lists.rangedWeaponTypes[data.data.type]), itemName: data.name }) + "</p>", yes: () => { data.data.ammunition.value = data.data.ammunition.max; this.update(data); }, }); } else { if (ammoNeeded <= itemAmmoData.data.quantity) { data.data.ammunition.value = data.data.ammunition.max; this.update(data); itemAmmoData.data.quantity -= ammoNeeded; itemAmmo.update(itemAmmoData); } else { data.data.ammunition.value += itemAmmoData.data.quantity; this.update(data); itemAmmoData.data.quantity = 0; itemAmmo.update(itemAmmoData); } } } else { Dialog.confirm({ title: game.i18n.localize('SR5.DIALOG_WarningNoAmmoTypeTitle'), content: "<h3>" + game.i18n.localize('SR5.DIALOG_Warning') + "</h3><p>" + game.i18n.format('SR5.DIALOG_WarningNoAmmoType', {actor: ownerActor.name, ammoType: game.i18n.localize(lists.allAmmunitionTypes[data.data.ammunition.type]), weaponType: game.i18n.localize(lists.rangedWeaponTypes[data.data.type]), itemName: data.name }) + "</p>", yes: () => { data.data.ammunition.value = data.data.ammunition.max; this.update(data); }, }); } } async placeGabarit(event) { if (canvas.scene) { const template = AbilityTemplate.fromItem(this); if (template) await template.drawPreview(event, this); } else if (this.type === "itemWeapon") this.rollTest("weapon"); if (this.actor.sheet._element) { if (this.isOwner && this.actor.sheet) this.actor.sheet.minimize(); } } //Roll a test rollTest(rollType, rollKey, chatData){ SR5_Roll.actorRoll(this, rollType, rollKey, chatData); } /** Overide Item's create Dialog to hide certain items and sort them alphabetically*/ static async createDialog(data={}, {parent=null, pack=null, ...options}={}) { // Collect data const documentName = this.metadata.name; const hiddenTypes = ["itemKarma", "itemMark", "itemNuyen", "itemEffect", "itemCyberdeck"]; const originalTypes = game.system.documentTypes[documentName]; const types = originalTypes.filter( (itemType) => !hiddenTypes.includes(itemType) ); const folders = parent ? [] : game.folders.filter(f => (f.data.type === documentName) && f.displayed); const title = game.i18n.localize('SR5.DIALOG_CreateNewItem'); // Render the document creation form const html = await renderTemplate(`templates/sidebar/document-create.html`, { name: game.i18n.localize('SR5.DIALOG_NewItem'), folder: data.folder, folders: folders, hasFolders: folders.length >= 1, type: types[0], types: types.reduce((obj, t) => { const label = CONFIG[documentName]?.typeLabels?.[t] ?? t; obj[t] = game.i18n.has(label) ? game.i18n.localize(label) : t; return SR5_EntityHelpers.sortObjectValue(obj); }, {}), hasTypes: types.length > 1, presets: CONFIG.Cards.presets }); // Render the confirmation dialog window return Dialog.prompt({ title: title, content: html, label: title, callback: async html => { const form = html[0].querySelector("form"); const fd = new FormDataExtended(form); foundry.utils.mergeObject(data, fd.toObject(), {inplace: true}); if ( !data.folder ) delete data["folder"]; const preset = CONFIG.Cards.presets[data.preset]; if ( preset && (preset.type === data.type) ) { const presetData = await fetch(preset.src).then(r => r.json()); data = foundry.utils.mergeObject(presetData, data); } return this.create(data, {parent, pack, renderSheet: true}); }, rejectClose: false, options: options }); } }
JavaScript
class MockModelInterface { /** * @param {!Object<string,*>} model */ constructor(model) { this.dataLayer = [model]; this.helper = new DataLayerHelper(this.dataLayer); } /** * @param {string} key * @return {*} value */ get(key) { return this.helper.get(key); } /** * @param {string} key * @param {*} value */ set(key, value) { this.dataLayer.push({[key]: value}); } }
JavaScript
class MockStorage { /** * @param {!Object<string,*>=} mockStorage */ constructor(mockStorage = {}) { this.mockStorage = mockStorage; } /** * @param {string} key * @param {*} value */ save(key, value) { this.mockStorage[key] = value; } /** * @param {string} key * @return {*} value */ load(key) { return this.mockStorage[key]; } }
JavaScript
class TileBase { /** * @constructor * * @param {string} url URL location of TileBase * @param {Object} opts Options Object */ constructor(url, opts) { if (!opts) opts = {}; this.isopen = false; this.version = null; this.config_length = 0; // The length of the config object in bytes const p = new URL(url); if (!interfaces[p.protocol]) throw new TBError(400, `${p.protocol} not supported`); this.handler = new interfaces[p.protocol](url); this.config = new Config(this); this.start_index = false; this.start_tile = false; } /** * Open a TileBase file for reading */ async open() { if (this.isopen) throw new TBError(400, 'TileBase file is already open'); await this.handler.open(); await this.config.range(); await this.config.read(); await this.config.verify(); this.start_index = 7 + this.config_length; // The number of bytes to the start of the index this.start_tile = this.start_index + this.config.index_count(); // The number of bytes to the start of the tiles this.isopen = true; } /** * Close a TileBase file from reading */ async close() { if (!this.isopen) throw new TBError(400, 'TileBase file is already closed'); await this.handler.close(); this.isopen = false; } /** * Return a partial TileJSON Object for the TileBase File * Note: TileBase file will not populate the URL fields * * @returns {Object} TileJSON Object */ tilejson() { if (!this.isopen) throw new TBError(400, 'TileBase file is not open'); const ul = TB.tileToBBOX([ this.config.config.ranges[this.config.config.max][0], this.config.config.ranges[this.config.config.max][1], this.config.config.max ]); const lr = TB.tileToBBOX([ this.config.config.ranges[this.config.config.max][2], this.config.config.ranges[this.config.config.max][3], this.config.config.max ]); const bounds = [ul[0], ul[1], lr[2], lr[3]]; return { tilejson: '2.0.0', name: 'default', version: '1.0.0', scheme: 'xyz', tiles: [], minzoom: this.config.config.min, maxzoom: this.config.config.max, bounds: bounds, center: centroid(bboxPolygon(bounds)).geometry.coordinates }; } /** * Return a single tile from a TileBase file * * @param {number} z Z Coordinate * @param {number} x X Coordinate * @param {number} y Y Coordinate * @param {boolean} unzip Auto unzip tiles * * @returns Buffer Tile */ async tile(z, x, y, unzip = false) { if (!this.isopen) throw new TBError(400, 'TileBase file is not open'); z = parseInt(z); x = parseInt(x); y = parseInt(y); for (const ele of [x, y, z]) { if (isNaN(ele)) throw new TBError(400, 'ZXY coordinates must be integers'); } if (!this.config.config.ranges[z]) throw new TBError(404, 'Zoom not supported'); if (x < this.config.config.ranges[z][0]) throw new TBError(404, 'X below range'); if (x > this.config.config.ranges[z][2]) throw new TBError(404, 'X above range'); if (y < this.config.config.ranges[z][1]) throw new TBError(404, 'Y below range'); if (y > this.config.config.ranges[z][3]) throw new TBError(404, 'Y above range'); let tiles = 0; // Calculate tile counts below requested zoom for (let c = this.config.config.min; c < z; c++) { tiles += (this.config.config.ranges[c][2] - this.config.config.ranges[c][0] + 1) * (this.config.config.ranges[c][3] - this.config.config.ranges[c][1] + 1); } // Calculate tile counts at requested zoom const x_diff = this.config.config.ranges[z][2] - this.config.config.ranges[z][0] + 1; const pre = x_diff * (y - this.config.config.ranges[z][1]); tiles += pre + x - this.config.config.ranges[z][0]; const idxbuff = await this.handler.read(this.start_index + (tiles * 16), 16); const idx = Number(idxbuff.readBigUInt64LE(0)); const size = Number(idxbuff.readBigUInt64LE(8)); if (size === 0) { return Buffer.alloc(0); } else { let tile = await this.handler.read(this.start_tile + idx, size); if (!unzip) return tile; tile = await gunzip(tile); return new Uint8Array(tile).buffer; } } /** * Convert an MBtiles file to TileBase * * @param {string} input Location to input MBTiles * @param {string} output Location to output TileBase * * @returns TileBase */ static to_tb(input, output) { return new Promise((resolve, reject) => { const config = { min: false, max: false, ranges: {} }; new MBTiles(input + '?mode=ro', async (err, mbtiles) => { if (err) return reject(err); try { const info = await getInfo(mbtiles); if (isNaN(Number(info.minzoom))) return reject(new TBError(400, 'Missing metadata.minzoom')); if (isNaN(Number(info.maxzoom))) return reject(new TBError(400, 'Missing metadata.maxzoom')); if (!info.bounds) return reject(new TBError(400, 'Missing metadata.bounds')); config.min = info.minzoom; config.max = info.maxzoom; // Create Config File & Write to DB for (let z = config.min; z <= config.max; z++) { const p1 = tc.tiles(point([info.bounds[0], info.bounds[1]]).geometry, { min_zoom: z, max_zoom: z })[0]; const p2 = tc.tiles(point([info.bounds[2], info.bounds[3]]).geometry, { min_zoom: z, max_zoom: z })[0]; config.ranges[z] = [p1[0], p2[1], p2[0], p1[1]]; } Config.write(output, config); const tb = fs.createWriteStream(output, { flags:'a' }); const tbt = fs.createWriteStream(output + '.tiles'); let current_byte = BigInt(0); // Request each of the tiles within a range for a specific zoom for (let z = config.min; z <= config.max; z++) { for (let y = config.ranges[z][1]; y <= config.ranges[z][3]; y++) { for (let x = config.ranges[z][0]; x <= config.ranges[z][2]; x++) { const tile = await getTile(mbtiles, z, x, y); const tile_ln = BigInt(tile.length); const tileloc = Buffer.alloc(16); tileloc.writeBigUInt64LE(current_byte, 0); tileloc.writeBigUInt64LE(tile_ln, 8); tb.write(tileloc); tbt.write(tile); current_byte += tile_ln; } } } tbt.close(); fs.createReadStream(output + '.tiles').pipe(tb); tb.on('close', () => { fs.unlinkSync(output + '.tiles'); return resolve(new TileBase('file://' + output)); }); } catch (err) { if (err instanceof TBError) return reject(err); return reject(new TBError(500, err.message)); } }); }); function getInfo(mbtiles) { return new Promise((resolve, reject) => { mbtiles.getInfo((err, info) => { if (err) return reject(err); return resolve(info); }); }); } function getTile(mbtiles, z, x, y) { return new Promise((resolve, reject) => { mbtiles.getTile(z, x, y, (err, tile) => { if (err && err.message === 'Tile does not exist') return resolve(Buffer.alloc(0)); if (err) return reject(err); return resolve(tile); }); }); } } }
JavaScript
class Color extends Behaviour { /** * Constructs a Color behaviour instance. * * @param {number|string} colorA - the starting color * @param {number|string} colorB - the ending color * @param {number} life - the life of the particle * @param {function} easing - The behaviour's decaying trend * @param {boolean} [isEnabled=true] - Determines if the behaviour will be applied or not * @return void */ constructor(colorA, colorB, life, easing, isEnabled = true) { super(life, easing, type, isEnabled); this.reset(colorA, colorB); } /** * Gets the _same property which determines if the alpha are the same. * * @return {boolean} */ get same() { return this._same; } /** * Sets the _same property which determines if the alpha are the same. * * @param {boolean} same * @return {boolean} */ set same(same) { /** * @type {boolean} */ this._same = same; } reset(colorA, colorB, life, easing) { this.same = colorB === null || colorB === undefined ? true : false; this.colorA = createColorSpan(colorA); this.colorB = createColorSpan(colorB); life && super.reset(life, easing); } initialize(particle) { particle.transform.colorA = ColorUtil.getRGB(this.colorA.getValue()); particle.useColor = true; particle.transform.colorB = this.same ? particle.transform.colorA : ColorUtil.getRGB(this.colorB.getValue()); } mutate(particle, time, index) { this.energize(particle, time, index); if (!this._same) { particle.color.r = MathUtils.lerp( particle.transform.colorA.r, particle.transform.colorB.r, this.energy ); particle.color.g = MathUtils.lerp( particle.transform.colorA.g, particle.transform.colorB.g, this.energy ); particle.color.b = MathUtils.lerp( particle.transform.colorA.b, particle.transform.colorB.b, this.energy ); } else { particle.color.r = particle.transform.colorA.r; particle.color.g = particle.transform.colorA.g; particle.color.b = particle.transform.colorA.b; } } /** * Creates a Color initializer from JSON. * * @param {object} json - The JSON to construct the instance from. * @property {number} json.colorA - The starting color * @property {number} json.colorB - The ending color * @property {number} json.life - The life of the particle * @property {string} json.easing - The behaviour's decaying trend * @return {Color} */ static fromJSON(json) { const { colorA, colorB, life, easing, isEnabled = true } = json; return new Color(colorA, colorB, life, getEasingByName(easing), isEnabled); } }
JavaScript
class DataGrid { constructor(params) { if (params.element) this.element = params.element; else if (params.elementId) this.element = $('#'+params.elementId); else console.warn('DataGrid: please specify target element'); this.filter = params.filter; this.selectable = (typeof params.selectable !== 'undefined' ? params.selectable : true); this.selectionCallback = params.selectionCallback; this.mouseOver = params.mouseOver; this.mouseOut = params.mouseOut; this.dateSortAsc = params.dateSortAsc; this.dateSortDesc = params.dateSortDesc; this.height = params.height; this.class = (typeof params.class !== 'undefined' ? params.class : "dt-cell hover compact row-border"); this.columns = params.columns; this.options = params.options || {}; if (!this.columns) { console.error('Missing required "columns" parameter'); return; } this.initialize(); } initialize() { var self = this; this.element.html('<img id="busy" src="picts/ajax-loader.gif" /><table cellpadding="0" cellspacing="0" border="0" class="' + self.class + '" style="cursor:pointer;"></table>'); // Instantiate grid var dataTable = this.dataTable = this.element.children('table').dataTable($.extend(true, {}, { paging: false, info: false, searching: true, dom: 'lrt', // remove unused elements (like search box) scrollY: self.height, language: { zeroRecords: "", emptyTable: "" }, columns: self.columns }, self.options)); var dataTableBody = dataTable.children('tbody'); // Handle row selection event if (self.selectable) { dataTableBody.on('click', 'tr', function(event) { var tr = this; var row = dataTable.api().row(tr).data(); if (!row) return; if ( $(tr).hasClass('selected') ) { // unselect $(tr).removeClass('selected'); } else { // select if (event.ctrlKey || event.metaKey) // multi select ; // no action required else if (event.shiftKey) { // block select var oSettings = dataTable.fnSettings(), fromPos = dataTable.fnGetPosition(self.lastRowSelected), toPos = dataTable.fnGetPosition(tr), fromIndex = $.inArray(fromPos, oSettings.aiDisplay), toIndex = $.inArray(toPos, oSettings.aiDisplay), start = (fromIndex < toIndex ? fromIndex : toIndex), end = (fromIndex < toIndex ? toIndex : fromIndex); for (var i = start; i <= end; i++) { var tr2 = dataTable.api().row(oSettings.aiDisplay[i]).node(); $(tr2).addClass('selected'); // select item } } else dataTable.$('tr.selected').removeClass('selected'); // unselect all $(tr).addClass('selected'); // select item self.lastRowSelected = tr; } self.selectItem(row); }); // Handle row double-click event dataTableBody.on('dblclick', 'tr', function() { var tr = this; var row = dataTable.api().row(tr).data(); if (row) { self.dataTable.$('tr.selected').removeClass('selected'); // unselect all $(tr).addClass('selected'); // select item self.lastRowSelected = tr; self.selectItem(row); self.openItem(row); } }); // Handle row hover events dataTableBody.on('mouseover', 'tr', function () { if (self.getSelectedItems()) // Do nothing if row(s) currently selected return; var tr = $(this).closest('tr'); var row = dataTable.api().row(tr).data(); if (row && self.mouseOver) self.mouseOver.call(self, row); }); dataTableBody.on('mouseout', 'tr', function () { if (self.getSelectedItems()) // Do nothing if row(s) currently selected return; if (self.mouseOut) self.mouseOut.call(self); }); } // Add custom filter if (self.filter) { $.fn.dataTable.ext.search.push( function(settings, data, dataIndex) { var data = self.dataTable.api().row(dataIndex).data(); return self.filter(data); } ); } // Add custom date sort functions if (self.dateSortAsc) $.fn.dataTable.ext.oSort['relative-date-asc'] = self.dateSortAsc.bind(this); if (self.dateSortDesc) $.fn.dataTable.ext.oSort['relative-date-desc'] = self.dateSortDesc.bind(this); } reset() { // TODO return this; } setData(data) { var busy = document.getElementById('busy'); if (busy) busy.parentNode.removeChild(busy); if (data) { this.dataTable.api() .clear() .rows.add(data); } else { this.dataTable.api() .clear() } } update(data) { var busy = document.getElementById('busy'); if (busy) busy.parentNode.removeChild(busy); if (data) { this.setData(data); this.redraw(); } return this; } search(search_term) { this.dataTable.api() .search(search_term) .draw(); } redraw() { this.dataTable.api().draw(); } getNumRows() { return this.dataTable.api().page.info().recordsTotal; } getNumRowsDisplayed() { return this.dataTable.api().page.info().recordsDisplay; } getSelectedRows() { var rows = this.dataTable.api().rows('.selected'); return rows; } getSelectedItems() { //console.log('getSelectedItems'); var items = this.dataTable.api().rows('.selected').data(); if (!items || !items.length) return; return items; } getSelectedItemList() { var items = this.getSelectedItems(); var item_list; if (items && items.length) item_list = $.map(items, function(item) { return item.id + '_' + item.type; }).join(','); return item_list; } setSelectedItems(items) { this.dataTable.api().rows().every( function () { var row = this; var d = row.data(); items.each(function(item) { if (d.id == item.id) { var tr = row.node(); $(tr).addClass('selected'); // select item } }); }); } clearSelection() { this.dataTable.$('tr.selected').removeClass('selected'); // unselect all } selectItem(item) { console.log('DataGrid.selectItem'); var selectedItems = this.getSelectedItems(); if (this.selectionCallback) this.selectionCallback.call(this, selectedItems); } openItem(row) { console.log('DataGrid.openItem'); if (row && row.open) row.open.call(row); } }
JavaScript
class HyperballStickImpostorBuffer extends MappedBoxBuffer { constructor(data, params = {}) { super(data, params); this.parameterTypes = HyperballStickImpostorBufferParameterTypes; this.isImpostor = true; this.vertexShader = 'HyperballStickImpostor.vert'; this.fragmentShader = 'HyperballStickImpostor.frag'; this.addUniforms({ 'modelViewProjectionMatrix': { value: new Matrix4() }, 'modelViewProjectionMatrixInverse': { value: new Matrix4() }, 'modelViewMatrixInverseTranspose': { value: new Matrix4() }, 'shrink': { value: this.parameters.shrink } }); this.addAttributes({ 'position1': { type: 'v3', value: null }, 'position2': { type: 'v3', value: null }, 'color2': { type: 'c', value: null }, 'radius': { type: 'f', value: null }, 'radius2': { type: 'f', value: null } }); this.setAttributes(data); this.makeMapping(); } get defaultParameters() { return HyperballStickImpostorBufferDefaultParameters; } }
JavaScript
class ServerQuery { /** * runs a Query to the SensorThingsServer * @param {string} queryURL the URL * @param {parameterMap} parameterMap the parameterMap * @param {function} callback Callback function * @param {string} obsStart the start date for the request * @param {string} obsEnd the end date for the request. If boolean value false, no end date will be set */ createQuery(queryURL, parameterMap, callback, obsStart, obsEnd) { if (queryURL.length <= 0 || queryURL == " ") { if (logging) console.log("invalid URL"); callback(null); return; } let containsParams = false; if (queryURL != "" && queryURL != null) containsParams = (queryURL.indexOf("?") >= 0); let selectors = new STParser().createSelectors(parameterMap, containsParams, obsStart, obsEnd); let cb = function(a) { if (logging) console.log("decoding", a); new STParser().decodeQuery(a, callback); }; this.createDirectQueryPaging(queryURL + selectors, cb); } /** * creates a single Query without appending the selectors, but with pageing * @param {string} query the URL to query from * @param {function} callback the function to call once completed */ createDirectQueryPaging(query, callback) { if (logging) { console.log("Querying: ", "'" + query + "'"); } $.ajax({ type: "GET", crossDomain: true, url: query, timeout: 120000, dataType: "json", error: function(xhr, status, error) { if (window.printAJAXerrors) console.log("AJAX ERROR:", error, status, xhr); callback(null); }, success: function(jsonResponse) { let result = jsonResponse; new STParser().retrieveAdditionalPages(result, callback); }, }); } /** * runs a Query to the SensorThingsServer, without paging, without appending the selectors * @param {string} query the Query * @param {function} callback the function to call once completed */ createDirectQuery(query, callback) { if (logging) { console.log("Querying: ", "'" + query + "'"); callback(null); } $.ajax({ type: "GET", crossDomain: true, url: query, timeout: 120000, dataType: "json", error: function(xhr, status, error) { if (window.printAJAXerrors) console.log("AJAX ERROR:", error, status, xhr); }, success: function(jsonResponse) { let result = jsonResponse; callback(result); } }); } }
JavaScript
class Geometry { // two optional paramaters constructor(scene, objectpool = null) { // public // #region this._objectpool = objectpool; // TODO: abstract and rearchitect this._scene = scene; this.object = null; // assigned to later through methods, default is null TODO: restructure this scheme this.objLoader = new OBJLoader2Parallel(); // refrence to an obj loader this.watchMouse.bind(this); this.data = []; // #endregion } // load objects from custom configuration (static) loadFromConfiguration( interactionHandler, models = Object.keys( threeConfig.models ) /** config object keys, or allow the keys to be passed in manually */ ) { models.map(modelName => { // load obj via local objloader instance const geometryInstance = new Geometry(this._scene); geometryInstance.objLoader.load( threeConfig.models[modelName][0].path, geometry => { // configure materials //TODO: abstract material creation from threeconfig let material; const config = threeConfig.models[modelName][0]; // configuration options top level if (config.material) { const materialConfig = config.material[0]; const materialProps = materialConfig.props[0]; if (materialProps.envMap) { materialProps.envMap = new CubeTextureLoader().load( // load referenced URL's [ materialProps.envMap, materialProps.envMap, materialProps.envMap, materialProps.envMap, materialProps.envMap, materialProps.envMap ].map(fileName => texturePath + fileName) ); materialProps.envMap.minFilter = LinearFilter; } switch (materialConfig.type) { case "physical": material = new MeshPhysicalMaterial(materialProps); break; case "custom": material = new ShaderMaterial(materialProps); break; case "phong": material = new MeshPhongMaterial(materialProps); break; default: console.error( "misconfigured material type, please use custom,phong or physical" ); break; } } // append properties to submesh's / primary mesh if (geometry.children.length > 0) { geometry.traverse(childMesh => { // this will go through ALL children // add materials to all subobjects material ? (childMesh.material = material) : console.log("using default material"); childMesh.scale.set(...config.scale); childMesh.position.set(...config.position); childMesh.rotation.set(...config.rotation); console.log(childMesh.name); // check for fx on object and append them to material }); } geometryInstance.object = geometry; this._scene.add(geometryInstance.object); // bind the event handler to the instance while we pass it in (IMPORTANT OR WE WILL GET UNDEFINED BEHAVIOR IN OBJECT REFRENCE) if (config.interactive) interactionHandler.eventHandlers.push( geometryInstance.watchMouse.bind(geometryInstance) ); // add the geometrys events to an object handler this._objectpool.addToPool(geometryInstance.object); } ), // progress event () => {}, // on error event err => { console.error( `obj loading failed: ${err} with path:${modelPath}${ config.path } at directory ${basename(__dirname) + basename(__filename, ".js")}` ); }; }); } // custom object loading handling loadObj(url) { return func => { this.objLoader.load(url, func); }; } // event handler that moves the mesh towards the 'target' specified watchMouse(target) { this.object.lookAt(...target); } // event handler that moves the mesh to position moveObject(position) {} // event handler that moves the mesh by the rotation amount (in quaternions) roateObject(quaternion) {} // for primitives (static) make(type) { if (type === "plane") { return (width, height, widthSegments = 1, heightSegments = 1) => { this.object = new PlaneGeometry( width, height, widthSegments, heightSegments ); }; } if (type === "sphere") { return (radius, widthSegments = 32, heightSegments = 32) => { this.object = new SphereGeometry(radius, widthSegments, heightSegments); }; } if (type === "box") { return ( width, height, depth, widthSegments = 32, heightSegments = 32, depthSegments ) => { this.object = new BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ); }; } } // static method to place objects or add a material place(position, rotation, material) { material ? console.log("using basic material") : (material = new Material("#1111a1").standard); const mesh = new Mesh(this.object, material); // Use ES6 spread to set position and rotation from passed in array mesh.position.set(...position); mesh.rotation.set(...rotation); if (threeConfig.lighting.shadow.enabled) { mesh.receiveShadow = true; } this._scene.add(mesh); } }
JavaScript
class ESlintPlugin extends Plugin { /** * run */ async run(){ if(!linter){ linter = require('eslint').linter; } if(!options){ options = extend({}, defaultOptions); options = extend(options, this.options); } let content = await this.getContent('utf8'); let messages = linter.verify(content, options, { filename: this.file.path }); messages = messages.map(item => { return { fatal: item.fatal, message: item.message, line: item.line, column: item.column } }); return messages; } /** * update */ update(messages){ messages.forEach(item => { if(item.fatal){ return this.fatal(item.message, item.line, item.column); } this.error(item.message, item.line, item.column); }); } /** * use cluster */ static cluster(){ return true; } /** * enable cache */ static cache(){ return true; } }
JavaScript
class Node extends EventChannel { constructor() { super(); // Set an id @TODO move to a path base ID. this.id = uuid(); // Following will propergate tree modified event to the top. this.on('tree-modified', function (event) { if (!_.isNil(this.parent)) { this.parent.trigger('tree-modified', event); } }); /** * View State Object to keep track of the model's view properties * @type {{bBox: SimpleBBox, components: {}, dimensionsSynced: boolean}} */ this.viewState = { bBox: new SimpleBBox(), components: {}, properties: {}, alias: undefined, dimensionsSynced: false, hidden: false, }; this.isStatement = false; this.isExpression = false; this.errors = []; } /** * If there are child nodes which are compound statements, this should carry the implementation accordingly */ setChildrenCompoundStatus() { // Will implement by the particular node } /** * * @param {NodeVisitor} visitor */ accept(visitor) { visitor.beginVisit(this); // eslint-disable-next-line guard-for-in for (const childName in this) { if (childName !== 'parent' && childName !== 'position' && childName !== 'ws') { const child = this[childName]; if (child instanceof Node && child.kind) { child.accept(visitor); } else if (child instanceof Array) { for (let i = 0; i < child.length; i++) { const childItem = child[i]; if (childItem instanceof Node && childItem.kind) { childItem.accept(visitor); } } } } } visitor.endVisit(this); } sync(visitor, newTree) { visitor.beginVisit(this, newTree); // eslint-disable-next-line guard-for-in for (const childName in this) { if (childName !== 'parent' && childName !== 'position' && childName !== 'ws') { if (newTree === undefined || newTree[childName] === undefined) { console.warn(`could not find ${childName} in newTree`, newTree); } else { const child = this[childName]; const child2 = newTree[childName]; if (child instanceof Node && child.kind) { child.sync(visitor, child2); } else if (child instanceof Array) { for (let i = 0; i < child.length; i++) { const childItem = child[i]; const childItem2 = child2[i]; if (childItem instanceof Node && childItem.kind) { childItem.sync(visitor, childItem2); } } } } } } visitor.endVisit(this, newTree); } getKind() { return this.kind; } getWS() { return this.wS; } getPosition() { return this.position; } /** * Get the source of the current Node. * @param {boolean?} pretty ignore WS and put default WS. * @return {string} source. */ getSource(pretty) { return getSourceOf(this, pretty); } [Symbol.iterator]() { const children = []; for (const key of Object.keys(this)) { const prop = this[key]; if (prop instanceof Node && key !== 'parent') { children.push([key, prop]); } else if (_.isArray(prop) && prop.length > 0 && prop[0] instanceof Node) { let i = 0; for (const propI of prop) { children.push([key + '[' + i++ + ']', propI]); } } } let nextIndex = 0; return { next() { return nextIndex < children.length ? { value: children[nextIndex++], done: false } : { done: true }; }, }; } entries() { const props = []; for (const key of _.pull(Object.keys(this) , 'symbolType', 'ws', 'viewState', 'id', '_events', 'parent', 'position', 'kind')) { const prop = this[key]; if (_.isArray(prop)) { if (prop.length > 0 && !(prop[0] instanceof Node)) { props.push([key, prop]); } } else if (!(prop instanceof Node)) { props.push([key, prop]); } } return props; } getID() { return this.id; } /** * Get the current file * @returns {object} - current file */ getFile() { let parentNode = this; while (parentNode.parent) { parentNode = parentNode.parent; } return parentNode.file; } /** * Set the current file * @param {object} file - current file */ setFile(file) { this.file = file; } /** * Get root of the node which is the compilation unit * @returns {Node} root node * @memberof Node */ getRoot() { if (this.kind === 'CompilationUnit' || !this.parent) { return this; } else { return this.parent.getRoot(); } } /** * Set errors of this node * @param {Object[]} errors - errors */ setErrors(errors) { this.errors = errors; } /** * Get all the errors of this node * @returns {Object[]} errors */ getErrors() { return this.errors; } /** * Checks if an string is valid as an identifier. * @param {string} identifier - The string value. * @return {boolean} - True if valid, else false. */ static isValidIdentifier(identifier) { if (_.isUndefined(identifier)) { return false; } else if (/^[a-zA-Z_$][a-zA-Z0-9_]*$/.test(identifier)) { return true; } return false; } /** * Checks if a string is valid as a type. * @param {string} type - The string value. * @return {boolean} - True if valid, else false. */ static isValidType(type) { if (_.isUndefined(type)) { return false; } else if (/^[a-zA-Z0-9:_]*\s*[[*\s\]<*\s*>a-zA-Z0-9_]*$/.test(type)) { return true; } return false; } /** * Check if the node is a statement node. * * @returns {boolean} return true if node is a statement. * @memberof Node */ isStatement() { return this.isStatement; } /** * Check if the node is a expression node. * * @returns {boolean} return true if node is an expression. * @memberof Node */ isExpression() { return this.isExpression; } /** * Remove the node from the tree. * * @memberof Node */ remove() { const parent = this.parent; if (this.parent === undefined) { // Unable to remove, this is a root node. return; } // get the parent and iterate till you find the node. for (const key of Object.keys(this.parent)) { const prop = this.parent[key]; if (prop instanceof Node && key !== 'parent') { if (prop.getID() === this.getID() && prop instanceof Node) { // Delete if, else, and else if blocks as they have children tree. // Check whether prop is a else if block. const isElseIf = (prop.kind === 'If' && prop.parent.kind === 'If'); if (isElseIf) { const elseStatement = prop.elseStatement; // if statement is not a kind of If if (elseStatement && elseStatement.kind !== 'If') { parent.ladderParent = false; } // If next else statement exist using setElseStatement otherwise // delete the property from object. if (elseStatement) { parent.setElseStatement(elseStatement); } else { delete this.parent[key]; parent.trigger('tree-modified', { origin: this, type: 'child-removed', title: `Removed ${this.kind}`, data: { node: this, }, }); } } else { delete this.parent[key]; parent.trigger('tree-modified', { origin: this, type: 'child-removed', title: `Removed ${this.kind}`, data: { node: this, }, }); } } } else if (_.isArray(prop) && prop.length > 0 && prop[0] instanceof Node) { let propFound = false; let i = 0; for (const propI of prop) { if (propI.getID() === this.getID()) { propFound = true; break; } i += 1; } if (propFound) { prop.splice(i, 1); parent.trigger('tree-modified', { origin: this, type: 'child-removed', title: `Removed ${this.kind}`, data: { node: this, }, }); return; } } } } /** * Clear the whitespace of the node. * * @memberof Node */ clearWS() { this.accept({ beginVisit: (node) => { delete node.ws; }, endVisit: (node) => { // do nothing. }, }); } /** * Get the content start position for the statement * @returns {number} - start position */ getContentStartCursorPosition() { return this.getPosition().startOffset; } /** * Get the content replace region on content suggestion at design view * @returns {{startC: {number}, stopC: {number}}} - object containing start char and the stop char */ getContentReplaceRegion() { const segments = this.getFile().content.split(/\r?\n/); const position = this.getPosition(); const joinedSegments = segments.slice(0, position.startLine - 1).join(); const start = joinedSegments.length + 1 + position.startOffset; const stop = start + this.getSource().length + 1; return { startC: start, stopC: stop, }; } }
JavaScript
class Model extends Base { /** * Model constructor. * * @constructor * @param {Array} data Provide initial data for the model. */ constructor (data) { super(data); this.populate(Array.isArray(data) ? _.cloneDeep(data) : [[0]]); } /** * Get a deep clone of the model's data. * * @method data * @return {Array} */ data () { let data = store.get(this); if (!data) { this.populate([[0]]); } return _.cloneDeep(store.get(this)); } /** * Destroy this model's data. * * @method destroy */ destroy () { this.emit('destroy'); store.delete(this); } /** * Populate the model with entirely new data. * * @method populate * @param {Array} data */ populate (data) { if (!Array.isArray(data)) { throw new Error('data must be an array'); } if (!Array.isArray(data[0]) || !_.isNumber(data[0][0])) { throw new Error('data[0] must be an array with at least one number'); } this.emit('populate', data); store.set(this, data); } /** * Kills all cells. * * @method genocide */ genocide () { let data = store.get(this); for (let i = 0; i < data.length; i++) { for (let j = 0; j < data[i].length; j++) { data[i][j] = 0; } } this.emit('genocide'); } /** * Randomizes all cells with an optional weight. * * @method randomize * @param {Number} [weight] * A number from zero to one, representing the ratio of living cells. */ randomize (weight) { if (!_.isNumber(weight) || weight < 0 || weight > 1) { weight = 0.25; } if (weight === 0) { this.genocide(); } else { let data = store.get(this); for (let i = 0; i < data.length; i++) { for (let j = 0; j < data[i].length; j++) { data[i][j] = Math.random() <= weight ? 1 : 0; } } } this.emit('randomize', weight); } /** * Get a single cell value from the model's data. * * @param {Number} row * @param {Number} col * @return {Number|null} * The value at the column and row given (or null). */ getCell (row, col) { let r = store.get(this)[row]; return Array.isArray(r) && _.isNumber(r[col]) ? r[col] : null; } /** * Set a single cell value in the model's data. The value is only set if * the cell exists. * * @param {Number} row * @param {Number} col * @param {Number|Boolean} value * Treated as truthy/falsy, set as one/zero respectively. * @param {Boolean} [silent] Whether or not to broadcast set-cell event. * @return {Number|null} */ setCell (row, col, value, silent) { let current = this.getCell(row, col); let updated = current === null ? null : Number(!!value); if (_.isNumber(updated)) { store.get(this)[row][col] = updated; } if (!silent) { this.emit('set-cell', current, updated); } return updated; } /** * Flip the value of a single cell between zero or one. The value is only * set if the cell exists. * * @param {Number} row * @param {Number} col * @param {Boolean} [silent] * @return {Number|null} */ flipCell (row, col, silent) { let value = this.getCell(row, col); if (value === null) { return value; } return this.setCell(row, col, !value, silent); } /** * Resize the model data. Newly created rows/cells will be populated with * zeros. * * @method resize * @param {Number} rowsCurr * @param {Number} colsCurr */ resize (rowsCurr, colsCurr) { let data = store.get(this); let rowsPrev = data.length; let rowsDiff = rowsCurr - rowsPrev; let colsPrev = data[0].length; let colsDiff = colsCurr - colsPrev; // Adding new row(s) of dead cells. if (rowsDiff > 0) { for (let i = rowsPrev; i < rowsCurr; i++) { data[i] = _.fill(Array(colsCurr), 0); } // Removing old row(s). } else if (rowsDiff < 0) { data.length += rowsDiff; } // Adding or removing dead cells from existing row(s). if (colsDiff !== 0) { // The `Math.min` call here ensures that we don't iterate too far if // the number of rows was reduced. for (let i = 0; i < Math.min(rowsPrev, data.length); i++) { if (colsDiff > 0) { data[i] = data[i].concat(_.fill(Array(colsDiff), 0)); } else { data[i].length += colsDiff; } } } this.emit('resize', { rowsCurr: rowsCurr, rowsPrev: rowsPrev, rowsDiff: rowsDiff, colsCurr: colsCurr, colsPrev: colsPrev, colsDiff: colsDiff, }); } /** * Algorithm to manage cells based on the rules of Conway's Game of Life. * * @see https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Rules * @method tick */ tick () { // We want a clone of the data here so that we can change the internal // data without affecting the results of the algorithm. let clone = this.data(); for (let i = 0; i < clone.length; i++) { let thisRow = clone[i]; let prevRow = clone[i - 1]; let nextRow = clone[i + 1]; for (let j = 0; j < thisRow.length; j++) { let thisCell = thisRow[j]; let hasPrevCell = _.isNumber(thisRow[j - 1]); let hasNextCell = _.isNumber(thisRow[j + 1]); let livingNeighbors = 0; if (hasPrevCell) { livingNeighbors += prevRow ? prevRow[j - 1] : 0; // left, up livingNeighbors += thisRow[j - 1]; // left livingNeighbors += nextRow ? nextRow[j - 1] : 0; // left, down } livingNeighbors += prevRow ? prevRow[j] : 0; // up livingNeighbors += nextRow ? nextRow[j] : 0; // down if (hasNextCell) { livingNeighbors += prevRow ? prevRow[j + 1] : 0; // right, up livingNeighbors += thisRow[j + 1]; // right livingNeighbors += nextRow ? nextRow[j + 1] : 0; // right, down } // Any live cell with fewer than two live neighbours dies, as if // caused by under-population. Any live cell with more than three // live neighbours dies, as if by overcrowding. if (thisCell && (livingNeighbors < 2 || livingNeighbors > 3)) { this.setCell(i, j, 0, true); // Any dead cell with exactly three live neighbours becomes a live // cell, as if by reproduction. } else if (!thisCell && livingNeighbors === 3) { this.setCell(i, j, 1, true); } } } this.emit('tick'); } }
JavaScript
class Google extends Component { responseGoogle = (response) => { } render() { return ( <div> <GoogleLogin clientId="141942233468-9aertq4rvk22nhalrg7g706ku6tljjfj.apps.googleusercontent.com" buttonText="Google" onSuccess={this.responseGoogle} onFailure={this.responseGoogle} cookiePolicy={'single_host_origin'} /> </div> ) } }
JavaScript
class MAGgSTB { /** * Initializes the player. Call this function before using the player. */ InitPlayer() {} /** * De-initialize the player. */ DeinitPlayer() {} /** * Start playing media content as specified in playStr * @param {string} playStr - string in the form: * "<solution> <URL> [atrack:<anum>] [vtrack:<vnum>] [strack:<snum>] [subURL:<subtitleUrl>]" * <solution> is one of rtp, rtsp, mp3, auto, mpegps, mpegts, mp4 * @param {string=} proxyParams - string in the following form: * "http://[username[:password]@]proxy_addr:proxy_port" * Parameters in square brackets are optional and can be omitted. * Note. Proxy server settings are valid till the next call of stb.Play(). * Note. Proxy server settings affect only http playback. */ Play(playStr, proxyParams) {} /** * @param {string} solution * @param {string} url */ PlaySolution(solution, url) {} /** * Stops playing. * Continue() shall begin playing from the beginning. */ Stop() {} /** * Pauses current playback. * Continue() continues playing from the current position. */ Pause() {} /** * Continues playing (after Pause()) or begin anew (after Stop()). */ Continue() {} /** * Sets the new position of playback in time * @param {number} time Positive number. The position in seconds from the beginning of the content where the * playback should start (positioning in the content). */ SetPosTime(time) {} /** * Sets the current playback position in time, ms. * @param {number} time Positive number. Position in ms from the beginning of the content where the * playback should start (positioning in the content). */ SetPosTimeEx(time) {} /** * Sets the current position in percent. * @param {number} percent Number between 0..100 The position in percent of the total duration of the * content where the playback should start. */ SetPosPercent(percent) {} /** * Set the current position in percent. * @param {number} percent Number between 0..10000 Position in hundredth fractions of percent of the * total duration of the content, from which the playback should start. */ SetPosPercentEx(percent) {} /** * Gets the current position in time. * @return {number} Current position in second from the beginning of content. */ GetPosTime() {} /** * Gets the current position in time in ms * @return {number} The current position in ms from the beginning of content. */ GetPosTimeEx() {} /** * Gets the current position in percent. * @return {number} The current position in percent of the whole duration of the content. */ GetPosPercent() {} /** * Gets the current position in hundredth fractions of percent. * @return {number} The current position in percent of the whole duration of content. */ GetPosPercentEx() {} /** * Gets the duration of the current content. * @return {number} Total duration of the current content in seconds. */ GetMediaLen() {} /** * Gets the duration of the current content in ms. * @return {number} Total duration of the current content in ms. */ GetMediaLenEx() {} /** * @param {number} speed */ SetSpeed(speed) {} /** * @param {number} pid */ SetAudioPID(pid) {} /** * @param {number} pid */ SetSubtitlePID(pid) {} /** * @param {number} state * @param {number} scale * @param {number} x * @param {number} y */ SetPIG(state, scale, x, y) {} /** * @param {number} alpha */ SetAlphaLevel(alpha) {} /** * @param {number} volume */ SetVolume(volume) {} /** * @param {number} mode */ SetUserFlickerControl(mode) {} /** * @param {number} state * @param {number} flk * @param {number} shp */ SetFlicker(state, flk, shp) {} /** * @param {number} state */ SetDefaultFlicker(state) {} /** * @param {number} loop */ SetLoop(loop) {} /** * @param {number} mode */ SetVideoControl(mode) {} /** * @param {number} state */ SetVideoState(state) {} /** * @param {number} key * @param {number} mask */ SetChromaKey(key, mask) {} /** * @param {number} mode */ SetMode(mode) {} /** * @param {number} winNum * @param {number} mode */ SetWinMode(winNum, mode) {} /** * @param {number} winNum */ SetTopWin(winNum) {} /** * @param {number} winNum * @param {number} alpha */ SetWinAlphaLevel(winNum, alpha) {} /** * @param {number} aspect */ SetAspect(aspect) {} /** * @param {number} angle */ Rotate(angle) {} /** * @param {number} mute */ SetMute(mute) {} /** * @param {number} micvol */ SetMicVolume(micvol) {} /** * @return {number} */ GetMicVolume() {} /** * @return {number} */ GetVolume() {} /** * @return {number} */ GetMute() {} /** * */ Step() {} /** * @param {number} type * @param {number} flags */ SetupRTSP(type, flags) {} /** * @param {number} xsize * @param {number} ysize * @param {number} x * @param {number} y */ SetViewport(xsize, ysize, x, y) {} /** * @param {number} xSize * @param {number} ySize * @param {number} xPos * @param {number} yPos * @param {number} cXSize * @param {number} cYSize * @param {number} cXPos * @param {number} cYPos * @param {boolean} saveClip */ SetViewportEx(xSize, ySize, xPos, yPos, cXSize, cYSize, cXPos, cYPos, saveClip) {} /** * @return {boolean} */ IsPlaying() {} /** * @return {string} */ Version() {} /** * @param {number} flags */ SetupSPdif(flags) {} /** * @param {boolean} enable */ SetSubtitles(enable) {} /** * @param {number} size */ SetSubtitlesSize(size) {} /** * @param {string} font */ SetSubtitlesFont(font) {} /** * @param {number} offs */ SetSubtitlesOffs(offs) {} /** * @return {number} */ GetSpeed() {} /** * @return {number} */ GetAudioPID() {} /** * @return {number} */ GetSubtitlePID() {} /** * @return {boolean} */ GetPIG() {} /** * @return {number} */ GetAlphaLevel() {} /** * @param {number} winNum * @return {number} */ GetWinAlphaLevel(winNum) {} /** * @param {number} color */ SetTransparentColor(color) {} /** * @return {number} */ GetTransparentColor() {} /** * @param {boolean} ignore */ IgnoreUpdates(ignore) {} /** * @param {string} action */ ExecAction(action) {} /** * @param {number} CASType */ SetCASType(CASType) {} /** * @param {string} serverAddr * @param {number} serverPort * @param {string} companyName * @param {number} opID * @param {number} errorLevel */ SetCASParam(serverAddr, serverPort, companyName, opID, errorLevel) {} /** * @param {string} paramName * @param {string} paramValue */ SetAdditionalCasParam(paramName, paramValue) {} /** * @param {string} iniFileName */ LoadCASIniFile(iniFileName) {} /** * @param {number} isSoftware */ SetCASDescrambling(isSoftware) {} /** * @return {number} */ GetAspect() {} /** * @param {boolean} standby */ StandBy(standby) {} /** * Выполнить скрипт /home/default/rdir.cgi с заданными параметрами, и вернуть * стандартный вывод данного скрипта. * В rdir.cgi, поставляемом с корневой файловой системой, уже предустановленны * несколько команд: * stb.RDir("SerialNumber",x) – в x вернёт серийный номер данного устройства. * stb.RDir("MACAddress",x) – получить MAC адрес * stb.RDir("IPAddress",x) – получить IP адрес * stb.RDir("HardwareVersion",x) – получить версию аппаратного обеспечения * stb.RDir("Vendor",x) – получить имя производителя STB * stb.RDir("Model ",x) – получить имя модели STB * stb.RDir("ImageVersion",x) – получить версию образа прошитого программного обеспечения * stb.RDir("ImageDescription",x) – получить информацию о образе прошитого программного обеспечения * stb.RDir("ImageDate",x) – получить дату создания образа прошитого программного обеспечения. * vstb.RDir("getenv v_name",x) – получить значение переменной среды с именем v_name. * stb.RDir("setenv v_name value") – установить переменную среды с именем v_name в значение value. * vstb.RDir("ResolveIP hostname") – получить IP адрес по имени хоста. * * @param {string} par Строка содержит параметры, с которыми будет запускаться скрипт /home/default/rdi.cgi. * @return {string} */ RDir(par) {} /** * @param {string} priLang * @param {string} secLang */ SetAudioLangs(priLang, secLang) {} /** * @param {string} priLang * @param {string} secLang */ SetSubtitleLangs(priLang, secLang) {} /** * @return {string} */ GetAudioPIDs() {} /** * @return {string} */ GetSubtitlePIDs() {} /** * @return {string} */ ReadCFG() {} /** * @param {string} cfg */ WriteCFG(cfg) {} /** * @param {string} prefs */ WritePrefs(prefs) {} /** * @param {string} debugString */ Debug(debugString) {} /** * @param {string} fileExts */ SetListFilesExt(fileExts) {} /** * @param {string} dirname * @return {string} */ ListDir(dirname) {} /** * @param {number} bri */ SetBrightness(bri) {} /** * @param {number} sat */ SetSaturation(sat) {} /** * @param {number} con */ SetContrast(con) {} /** * @return {number} */ GetBrightness() {} /** * @return {number} */ GetSaturation() {} /** * @return {number} */ GetContrast() {} /** * */ DeleteAllCookies() {} /** * @param {number} mode */ SetAudioOperationalMode(mode) {} /** * @param {number} type */ SetHDMIAudioOut(type) {} /** * @param {number} high * @param {number} low */ SetDRC(high, low) {} /** * @param {number} mode */ SetStereoMode(mode) {} /** * @param {boolean} enable */ EnableJavaScriptInterrupt(enable) {} /** * @param {number} start * @param {number} end * @param {number} text */ ShowSubtitle(start, end, text) {} /** * */ StartLocalCfg() {} /** * */ ShowVirtualKeyboard() {} /** * */ HideVirtualKeyboard() {} /** * @param {boolean} enable */ EnableServiceButton(enable) {} /** * @param {boolean} enable */ EnableVKButton(enable) {} /** * @param {boolean} enable */ EnableSpatialNavigation(enable) {} /** * @param {string} domain * @param {boolean} enable */ EnableSetCookieFrom(domain, enable) {} /** * @param {number} sizeInMs * @param {number} maxSizeInBytes */ SetBufferSize(sizeInMs, maxSizeInBytes) {} /** * @return {number} */ GetBufferLoad() {} /** * @param {string} proxyAddr * @param {number} proxyPort * @param {string=} userName * @param {string=} passwd * @param {string=} excludeList */ SetWebProxy(proxyAddr, proxyPort, userName, passwd, excludeList) {} /** * @return {string} Like: '{frameRate:23976,pictureWidth:1280,pictureHeight:544,hPAR:1,vPAR:1}' * or '{}' or empty string. */ GetVideoInfo() {} /** * @return {string} JSON string!!! */ GetMetadataInfo() {} /** * @param {number} mode */ SetAutoFrameRate(mode) {} /** * @param {number} forceDVI */ ForceHDMItoDV(forceDVI) {} /** * @param {string} url */ LoadExternalSubtitles(url) {} /** * @param {string} encoding */ SetSubtitlesEncoding(encoding) {} /** * @param {string} args JSON string!!! * @return {string} JSON string!!! */ GetEnv(args) {} /** * @param {string} args JSON string!!! * @return {boolean} */ SetEnv(args) {} /** * @return {string} */ GetDeviceSerialNumber() {} /** * @return {string} */ GetDeviceVendor() {} /** * @return {string} */ GetDeviceModel() {} /** * @return {string} */ GetDeviceVersionHardware() {} /** * @return {string} */ GetDeviceMacAddress() {} /** * @return {string} */ GetDeviceActiveBank() {} /** * @return {string} */ GetDeviceImageVersion() {} /** * @return {string} */ GetDeviceImageDesc() {} /** * @return {string} */ GetDeviceImageVersionCurrent() {} /** * @return {boolean} */ GetLanLinkStatus() {} /** * @return {boolean} */ GetWifiLinkStatus() {} /** * @param {string} passPhrase * @return {string} JSON string!!! */ GetWepKey64ByPassPhrase(passPhrase) {} /** * @param {string} passPhrase * @return {string} JSON string!!! */ GetWepKey128ByPassPhrase(passPhrase) {} /** * @return {string} JSON string!!! */ GetWifiGroups() {} /** * @param {string} serviceName * @param {string} action * @return {string} JSON string!!! */ ServiceControl(serviceName, action) {} /** * @return {string} JSON string!!! */ GetSmbGroups() {} /** * @param {string} args JSON string!!! * @return {string} JSON string!!! */ GetSmbServers(args) {} /** * @param {string} args JSON string!!! * @return {string} JSON string!!! */ GetSmbShares(args) {} /** * @param {string} fileName * @return {boolean} */ IsFolderExist(fileName) {} /** * @param {string} fileName * @return {boolean} */ IsFileExist(fileName) {} /** * @param {string} pargs */ SendEventToPortal(pargs) {} /** * @return {boolean} */ IsWebWindowExist() {} /** * @return {boolean} */ IsInternalPortalActive() {} /** * @param {boolean} enable */ EnableAppButton(enable) {} /** * @param {string} httpHeader */ SetCustomHeader(httpHeader) {} }
JavaScript
class Version{ /** * @param {String} str String to parse as version */ constructor(str){ this.channels = { alpha: false, beta: false, stable: false }; this.version = 0; this.major = 0; this.minor = 0; this.revision = ''; /** * @return {String} String representation of version */ function toString(){} this.toString = toString; /** * @return {Number} Number representation of version (for some reasons compatibility only!) */ function valueOf(){} this.valueOf = valueOf; }; }
JavaScript
class VARTISTEUtil { // Returns `{width, height}` as integers greater than 0 validateSize({width, height}) { width = parseInt(width) height = parseInt(height) if (!(Number.isInteger(width) && width > 0)) { console.trace() throw new Error(`Invalid composition width ${width}`) } if (!(Number.isInteger(height) && height > 0)) { console.trace() throw new Error(`Invalid composition height ${height}`) } return {width, height} } // Executes function `fn` when `entity` has finished loading, or immediately // if it has already loaded. `entity` may be a single `a-entity` element, or // an array of `a-entity` elements. If `fn` is not provided, it will return a // `Promise` that will resolve when `entity` is loaded (or immediately if // `entity` is already loaded). whenLoaded(entity, fn) { if (Array.isArray(entity) && fn) return whenLoadedAll(entity, fn) if (Array.isArray(entity)) return awaitLoadingAll(entity) if (fn) return whenLoadedSingle(entity, fn) return awaitLoadingSingle(entity) } // Copies `matrix` into `obj`'s (a `THREE.Object3D`) `matrix`, and decomposes // it to `obj`'s position, rotation, and scale applyMatrix(matrix, obj) { obj.matrix.copy(matrix) matrix.decompose(obj.position, obj.rotation, obj.scale) } // If `destination` is provided, resizes `destination` to the same size as // `canvas` and copies `canvas` contents to `destination`. If `destination` is // not provided, it creates a new canvas with the same size and contents as // `canvas`. cloneCanvas(canvas, destination = undefined) { if (typeof destination === 'undefined') destination = document.createElement('canvas') destination.width = canvas.width destination.height = canvas.height destination.getContext('2d').drawImage(canvas, 0, 0) return destination } // Resizes canvas only if it is not already `width` x `height` (Changing a // canvas size sometimes clears the canvas) ensureSize(canvas, width, height) { if (canvas.width !== width || canvas.height !== height) { canvas.width = width canvas.height = height } } // Moves `obj` (`THREE.Object3D`) to the same spot as `target` (`THREE.Object3D`), accounting for the various matrix // transformations and parentages to get it there. positionObject3DAtTarget(obj, target, {scale, transformOffset, transformRoot} = {}) { if (typeof transformRoot === 'undefined') transformRoot = obj.parent target.updateMatrixWorld() let destMat = this.pool('dest', THREE.Matrix4) destMat.copy(target.matrixWorld) if (transformOffset) { let transformMat = this.pool('transformMat', THREE.Matrix4) transformMat.makeTranslation(transformOffset.x, transformOffset.y, transformOffset.z) destMat.multiply(transformMat) } if (scale) { let scaleVect = this.pool('scale', THREE.Vector3) scaleVect.setFromMatrixScale(destMat) scaleVect.set(scale.x / scaleVect.x, scale.y / scaleVect.y, scale.z / scaleVect.z) destMat.scale(scaleVect) } let invMat = this.pool('inv', THREE.Matrix4) transformRoot.updateMatrixWorld() invMat.copy(transformRoot.matrixWorld).invert() destMat.premultiply(invMat) Util.applyMatrix(destMat, obj) } keepingWorldPosition(object3D, fn) { let positioner = this.pool('positioner', THREE.Object3D) object3D.el.sceneEl.object3D.add(positioner); let wm = new THREE.Matrix4; wm.copy(object3D.matrixWorld); let res = fn(); if (res && typeof res.then === 'function') { return res.then(() => { Util.applyMatrix(wm, positioner); Util.positionObject3DAtTarget(object3D, positioner) }) } Util.applyMatrix(wm, positioner); Util.positionObject3DAtTarget(object3D, positioner) return res; } autoScaleViewer(rootObj, viewer) { let boundingBox = this.pool('boundingBox', THREE.Box3) let tmpBox = this.pool('tmpBox', THREE.Box3) let firstModel = rootObj.getObjectByProperty('type', 'Mesh') || rootObj.getObjectByProperty('type', 'SkinnedMesh') rootObj.updateMatrixWorld() firstModel.geometry.computeBoundingBox() boundingBox.copy(firstModel.geometry.boundingBox) firstModel.updateMatrixWorld() boundingBox.applyMatrix4(firstModel.matrixWorld) rootObj.traverse(m => { if (!m.geometry) return m.geometry.computeBoundingBox() m.updateMatrixWorld() tmpBox.copy(m.geometry.boundingBox) tmpBox.applyMatrix4(m.matrixWorld) boundingBox.union(tmpBox) }) let maxDimension = Math.max(boundingBox.max.x - boundingBox.min.x, boundingBox.max.y - boundingBox.min.y, boundingBox.max.z - boundingBox.min.z) let targetScale = 0.5 / maxDimension viewer.setAttribute('scale', `${targetScale} ${targetScale} ${targetScale}`) boundingBox.getCenter(viewer.object3D.position) viewer.object3D.position.multiplyScalar(- targetScale) viewer.object3D.position.z = boundingBox.min.z * targetScale } // Returns the `THREE.Object3D` that contains the true world transformation // matrix for the camera. Works both on desktop and in VR cameraObject3D() { // return document.querySelector('#camera').object3D//.getObject3D('camera-matrix-helper') let scene = AFRAME.scenes[0] let camera = AFRAME.scenes[0].camera.el return scene.is('vr-mode') && document.querySelector('a-scene').hasWebXR ? camera.getObject3D('camera-matrix-helper') : camera.object3D } // Brings `initialEl` right in front of the camera flyToCamera(initialEl, {propogate = true, ...opts} = {}) { let target = this.cameraObject3D() let flyingEl = initialEl while (propogate && flyingEl['redirect-grab']) { flyingEl = flyingEl['redirect-grab'] } this.positionObject3DAtTarget(flyingEl.object3D, target, {transformOffset: {x: 0, y: 0, z: -0.5}, ...opts}) } // Registers a `ComponentSystem`. A `ComponentSystem` is a `Component` which // is automatically added to the `a-scene`, just like a system. It can be // accessed from both `sceneEl.systems` and `sceneEl.components`. The main // purpose of this is to have auto-registering systems which also have the // schema update events of components. registerComponentSystem(name, obj) { AFRAME.registerComponent(name, obj) AFRAME.registerSystem('_' + name, { init() { this.el.sceneEl.setAttribute(name, "") this.el.sceneEl.systems[name] = this.el.sceneEl.components[name] } }) } // Executes `fn` on all ancestors of `el` traverseAncestors(el, fn) { el = el.parentEl while (el) { fn(el) el = el.parentEl } } // Uses THREE.Object3D.traverse to find the first object where `fn` returns // `true` traverseFind(obj3D, fn, {visibleOnly = false} = {}) { if (fn(obj3D)) return obj3D; for (let c of obj3D.children) { if (visibleOnly && !c.visible) continue let res = this.traverseFind(c, fn, {visibleOnly}) if (res) return res } return; } // Uses THREE.Object3D.traverse to find all objects where `fn` returns // `true` traverseFindAll(obj3D, fn, {outputArray = [], visibleOnly = false} = {}) { if (fn(obj3D)) outputArray.push(obj3D) for (let c of obj3D.children) { if (visibleOnly && !c.visible) continue this.traverseFindAll(c, fn, {outputArray, visibleOnly}) } return outputArray; } visibleWithAncestors(obj) { if (!obj.visible) return false while (obj.parent) { obj = obj.parent if (!obj.visible) return false } return true } // Uppercases the first letter of each word titleCase(str) { return str.replace(/\w\S*/g, t => t.charAt(0).toUpperCase() + t.substr(1)) } unenumerable(obj, prop) { return let pname = "__" + prop let initVal = obj[prop] Object.defineProperty(obj, prop, {enumerable: false, get: () => obj[pname], set: (v) => obj[pname] = v}) obj[pname] = initVal } // Makes it easier to see what's going on with `canvas` (either downloads or displays it) debugCanvas(canvas) { document.querySelector('a-scene').systems['settings-system'].download(canvas.toDataURL(), {extension: 'png', suffix: 'debug'}, "Debug Image") } divideCanvasRegions(numberOfRegions, {margin = 0} = {}) { // There's a math way to do this. I can't figure it out right now... let numberOfHorizontalCuts = 1 let numberOfVerticalCuts = 1 while (numberOfHorizontalCuts * numberOfVerticalCuts < numberOfRegions) { if (numberOfVerticalCuts > numberOfHorizontalCuts) { numberOfHorizontalCuts++ } else { numberOfVerticalCuts++ } } let boxes = [] for (let y = 0; y < numberOfHorizontalCuts; ++y) { for (let x = 0; x < numberOfVerticalCuts; ++x) { let newBox = new THREE.Box2(new THREE.Vector2(x / numberOfVerticalCuts, y / numberOfHorizontalCuts), new THREE.Vector2((x + 1) / numberOfVerticalCuts, (y + 1) / numberOfHorizontalCuts)) newBox.expandByScalar(- margin) boxes.push(newBox) } } return boxes } uvWrapClamp(val) { val = val % 1.0 //v = (v === 0 && val > 0) ? 1.0 : v //v = (v < 0) ? 1.0 - v : v return val } applyUVBox(box, geometry) { let attr = geometry.attributes.uv; if (attr.data) { for (let i = 0; i < attr.count; ++i) { attr.setXY(i, THREE.Math.mapLinear(attr.getX(i) % 1.00000000000001, 0, 1, box.min.x, box.max.x), THREE.Math.mapLinear(attr.getY(i) % 1.00000000000001, 0, 1, box.min.y, box.max.y)) } } else { let indices = {has: function() { return true; }} if (geometry.index) { indices = new Set(geometry.index.array) } for (let i in geometry.attributes.uv.array) { if (!indices.has(Math.floor(i / 2))) continue; if (i %2 == 0) { attr.array[i] = THREE.Math.mapLinear(attr.array[i] % 1.00000000000001, 0, 1, box.min.x, box.max.x) } else { attr.array[i] = THREE.Math.mapLinear(attr.array[i] % 1.00000000000001, 0, 1, box.min.y, box.max.y) } } } attr.needsUpdate = true return geometry; } // Resolves all the manipulator grap redirections on `targetEl` and returns // the final element that should actually be grabbed when `targetEl` is // grabbed. resolveGrabRedirection(targetEl) { let target = targetEl for (let redirection = targetEl['redirect-grab']; redirection; redirection = target['redirect-grab']) { target = redirection } return target } deinterleaveAttributes(geometry) { for (let name in geometry.attributes) { let attr = geometry.attributes[name] if (!attr) continue if (!attr.isInterleavedBufferAttribute) continue let arr = [] // arr.length = attr.count * attr.itemSize console.log(name, attr) for (let i = 0; i < attr.count; ++i) { arr.push(attr.getX(i)) if (attr.itemSize >= 2) arr.push(attr.getY(i)) if (attr.itemSize >= 3) arr.push(attr.getZ(i)) if (attr.itemSize >= 4) arr.push(attr.getW(i)) } geometry.setAttribute(name, new THREE.Float32BufferAttribute(arr, attr.itemSize)) } } // Linearly interpolates two transformation matrices interpTransformMatrices(alpha, start, end, {result} = {}) { if (!result) result = new THREE.Matrix4 let startPose = this.pool('startPose', THREE.Vector3) let endPose = this.pool('endPose', THREE.Vector3) let startQuat = this.pool('startQuat', THREE.Quaternion) let endQuat = this.pool('endQuat', THREE.Quaternion) let startScale = this.pool('startScale', THREE.Vector3) let endScale = this.pool('endScale', THREE.Vector3) start.decompose(startPose, startQuat, startScale) end.decompose(endPose, endQuat, endScale) startPose.lerp(endPose, alpha) startQuat.slerp(endQuat, alpha) startScale.lerp(endScale, alpha) result.compose(startPose, startQuat, startScale) return result } // Returns true if `canvas` has no pixels with an alpha less than 1.0 isCanvasFullyOpaque(canvas, threshold = 255) { let ctx = canvas.getContext('2d') let data = ctx.getImageData(0, 0, canvas.width, canvas.height) for (let i = 3; i < data.data.length; i += 4) { if (data.data[i] < threshold) return false } return true } isCanvasFullyTransparent(canvas) { let ctx = canvas.getContext('2d') let data = ctx.getImageData(0, 0, canvas.width, canvas.height) for (let i = 3; i < data.data.length; i += 4) { if (data.data[i] > 0) return false } return true } autoCropBounds(canvas) { let ctx = canvas.getContext('2d') let data = ctx.getImageData(0, 0, canvas.width, canvas.height) let box = new THREE.Box2 let pixel = new THREE.Box2 for (let y = 0; y < canvas.height; ++y) { for (let x = 0; x < canvas.width; ++x) { if (data.data[(y*canvas.width + x) * 4 + 3] > 0) { pixel.min.set(x,y) pixel.max.set(x+1,y+1) box.union(pixel) } } } return box } autoCropCanvas(canvas) { let bounds = this.autoCropBounds(canvas) let dest = document.createElement('canvas') let size = new THREE.Vector2 bounds.getSize(size) dest.width = size.x dest.height = size.y dest.getContext('2d').drawImage(canvas, bounds.min.x, bounds.min.y, size.x, size.y, 0, 0, size.x, size.y) return dest } callLater(fn = function(){}) { return new Promise((r, e) => { window.setTimeout(() => { fn() r() }, 1) }) } mapFromFilename(filename) { for (let map in MAP_FROM_FILENAME) { if (MAP_FROM_FILENAME[map].some(exp => exp.test(filename))) { return map } } } fillDefaultCanvasForMap(canvas, map, {replace = false} = {}) { let shouldFill = false let ctx = canvas.getContext('2d') switch (map) { case 'normalMap': ctx.fillStyle = 'rgb(128, 128, 255)' shouldFill = true break; case 'metalnessMap': ctx.fillStyle = 'rgb(0, 0, 0)' shouldFill = true; break; case 'roughnessMap': ctx.fillStyle = 'rgb(255, 255, 255)' shouldFill = true; break; case 'bumpMap': ctx.fillStyle = 'rgb(0, 0, 0)' shouldFill = true; break; case 'aoMap': ctx.fillStyle = 'rgb(255, 255, 255)' shouldFill = true; break; case 'emissiveMap': ctx.fillStyle = 'rgb(0, 0, 0)' shouldFill = true; break; default: console.warn("Can't fill unknown map", map) break; } if (shouldFill) { Undo.pushCanvas(canvas) ctx.globalCompositeOperation = replace ? 'source-over' : 'destination-over' ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height) ctx.globalCompositeOperation = 'source-over' } return shouldFill } whenComponentInitialized(el, component, fn) { if (el && el.components[component] && el.components[component].initialized) { return Promise.resolve(fn ? fn() : undefined) } return new Promise((r, e) => { if (el && el.components[component] && el.components[component].initialized) { return Promise.resolve(fn ? fn() : undefined) } let listener = (e) => { if (e.detail.name === component) { el.removeEventListener('componentinitialized', listener); if (fn) fn(); r(); } }; el.addEventListener('componentinitialized', listener) }) } recursiveBoundingBox(rootObj, {box = undefined} = {}) { let boundingBox = box || this.pool('boundingBox', THREE.Box3) let tmpBox = this.pool('tmpBox', THREE.Box3) let firstModel = rootObj.getObjectByProperty('type', 'Mesh') || rootObj.getObjectByProperty('type', 'SkinnedMesh') rootObj.updateMatrixWorld() firstModel.geometry.computeBoundingBox() boundingBox.copy(firstModel.geometry.boundingBox) firstModel.updateMatrixWorld() boundingBox.applyMatrix4(firstModel.matrixWorld) rootObj.traverse(m => { if (!m.geometry) return m.geometry.computeBoundingBox() m.updateMatrixWorld() tmpBox.copy(m.geometry.boundingBox) tmpBox.applyMatrix4(m.matrixWorld) boundingBox.union(tmpBox) }) return boundingBox } emitsEvents(component) { component.emitDetails = AFRAME.utils.clone(Object.getPrototypeOf(component).emits) const debugEmitDocs = false; if (debugEmitDocs) { let oldEmit = component.emit component.emit = function(event, ...args) { if (!(event in component.emitDetails)) { console.warn("Undocumented event emitted:", event) console.trace() } oldEmit.call(this, ...args) } } } async busy(fn, opts) { let scene = AFRAME.scenes[0] let busy = scene.systems['busy-indicator'].busy(opts) try { await fn() busy.done() } catch (e) { busy.error(e) throw e } } busify(opts, fn, self) { let scene = AFRAME.scenes[0] return async function(...args) { let busy = scene.systems['busy-indicator'].busy(opts) try { await fn.call(self, ...args) busy.done() } catch (e) { busy.error(e) throw e } } } async delay(t) { return new Promise(r => setTimeout(r, t)); } isLowPower() { let lowPower = AFRAME.utils.device.isMobileVR(); let params = new URLSearchParams(document.location.search) if (params.get("lowPower")) { lowPower = true; } if (params.get("highPower")) { lowPower = false; } return lowPower; } meshPointsInContainerMesh(mesh, container) { if (mesh.type !== 'Mesh' || container.type !== 'Mesh') { console.warn("meshPointsInContainerMesh only works on meshes!", mesh, container) } const inverseMatrix = new THREE.Matrix4(); inverseMatrix.copy( mesh.matrixWorld ).invert(); container.geometry.computeBoundingSphere(); const sphere = new THREE.Sphere(); container.getWorldPosition(sphere.center).applyMatrix4( inverseMatrix ); sphere.radius = container.geometry.boundingSphere.radius; let meshToContainer = new THREE.Matrix4; meshToContainer.copy(container.matrixWorld).invert(); meshToContainer.premultiply(mesh.matrixWorld); let bvh = mesh.geometry.computeBoundsTree(); let containerBvh = container.geometry.computeBoundsTree(); let indices = [] let tempVec = new THREE.Vector3(); let index = mesh.geometry.index.array let raycaster = new THREE.Raycaster; raycaster.ray.direction.set(1, 0.1, 0); let oldSided = container.material.side; container.material.side = THREE.DoubleSide; bvh.shapecast(mesh, { intersectsBounds: box => { // console.log("Checking box", box, sphere) const intersects = sphere.intersectsBox( box ); const { min, max } = box; if ( intersects ) { for ( let x = 0; x <= 1; x ++ ) { for ( let y = 0; y <= 1; y ++ ) { for ( let z = 0; z <= 1; z ++ ) { tempVec.set( x === 0 ? min.x : max.x, y === 0 ? min.y : max.y, z === 0 ? min.z : max.z ); if ( ! sphere.containsPoint( tempVec ) ) { return INTERSECTED; } } } } return CONTAINED; } return intersects ? INTERSECTED : NOT_INTERSECTED; }, intersectsTriangle: ( tri, i, contained ) => { if ( contained || tri.intersectsSphere( sphere ) ) { const i3 = 3 * i; // tri.a.applyMatrix4(meshToContainer) // tri.b.applyMatrix4(meshToContainer) // tri.c.applyMatrix4(meshToContainer) raycaster.ray.origin.copy(tri.a) mesh.localToWorld(raycaster.ray.origin) let intersections = []; raycaster.intersectObject(container, false, intersections) if (intersections.length % 2 == 1) { indices.push( index[i3] ) } intersections.length = 0 raycaster.ray.origin.copy(tri.b) mesh.localToWorld(raycaster.ray.origin) raycaster.intersectObject(container, false, intersections) if (intersections.length % 2 == 1) { indices.push( index[i3 + 1] ) } intersections.length = 0 raycaster.ray.origin.copy(tri.c) mesh.localToWorld(raycaster.ray.origin) raycaster.intersectObject(container, false, intersections) if (intersections.length % 2 == 1) { indices.push( index[i3 + 2] ) } } return false; } } ); container.material.side = oldSided; return indices; } meshesIntersect(meshA, meshB, includeContained = false) { let bvh; if (meshA.geometry.attributes.position.itemSize !== 3) return; if (meshB.geometry.attributes.position.itemSize !== 3) return; bvh = meshA.geometry.computeBoundsTree() meshB.geometry.computeBoundsTree() let matrix = this.pool('matrix', THREE.Matrix4) meshA.updateMatrixWorld() meshB.updateMatrixWorld() matrix.copy(meshA.matrixWorld) matrix.invert() matrix.multiply(meshB.matrixWorld) if (bvh.intersectsGeometry(meshA, meshB.geometry, matrix)) return true if (!includeContained) return false let tmpBox = this.pool('tmpBox', THREE.Box3) tmpBox.copy(meshB.geometry.boundingBox) tmpBox.applyMatrix4(matrix) if (!tmpBox.intersectsBox(meshA.geometry.boundingBox)) return false // TODO Check boundng box let intersections = [] let raycaster = this.pool('raycaster', THREE.Raycaster); raycaster.ray.direction.set(1, 0.1, 0); let oldSided = meshA.material.side; meshA.material.side = THREE.DoubleSide; raycaster.ray.origin.fromBufferAttribute(meshB.geometry.attributes.position, 0) meshB.localToWorld(raycaster.ray.origin) raycaster.intersectObject(meshA, false, intersections) meshA.material.side = oldSided if (intersections.length % 2 == 1) return true intersections.length = 0 oldSided = meshB.material.side; meshB.material.side = THREE.DoubleSide; raycaster.ray.origin.fromBufferAttribute(meshA.geometry.attributes.position, 0) meshA.localToWorld(raycaster.ray.origin) raycaster.intersectObject(meshB, false, intersections) meshB.material.side = oldSided if (intersections.length % 2 == 1) return true return false } objectsIntersect(objA, objB, {visibleOnly = true, intersectionInfo, includeContained = true} = {}) { if (objA.object3D) objA = objA.object3D; if (objB.object3D) objB = objB.object3D; let intersected = false objA.traverseVisible(oA => { if (intersected) return if (!oA.isMesh) return; if (visibleOnly && oA.el && oA.el.className.includes("raycast-invisible")) return if (visibleOnly && !oA.visible) return objB.traverseVisible(oB => { if (intersected) return if (!oB.isMesh) return; if (visibleOnly && !oB.visible) return if (visibleOnly && oB.el && oB.el.className.includes("raycast-invisible")) return if (this.meshesIntersect(oA, oB, includeContained)) { if (intersectionInfo) { intersectionInfo.objectA = oA intersectionInfo.objectB = oB } intersected = true } }) }) return intersected } translate(str) { if (!this.el.sceneEl.systems['ui-translation']) return str return this.el.sceneEl.systems['ui-translation'].translate(str) } }
JavaScript
class RECCode { constructor(no,category,definition){ this.no=no; this.category=category; this.definition=definition; } }
JavaScript
class Users { /** * @method deleteById * @desc This method deletes the user with the specified user ID * This method is not yet implemented * * @param { object } req request * @param { object } res response * * @returns { object } response */ async deleteById(req, res) { return res.sendFailure(['This operation is not yet supported.']); } /** * @method get * @desc This method gets an array of users * * @param { object } req request * @param { object } res response * * @returns { object } response */ async get(req, res) { try { const { limit, offset } = req.meta.pagination; const { query } = req.meta.search; const { attribute, order } = req.meta.sort; let { where } = req.meta.filter; // if search query is present, overwrite the 'where' so that // the 'displayName', 'email', and 'githubUsername' // are checked to see if they contain // that search query (case-INsensitive) if (query) { where = { [Op.or]: [ { displayName: { [Op.iLike]: `%${query}%` } }, { email: { [Op.iLike]: `%${query}%` } }, { githubUsername: { [Op.iLike]: `%${query}%` } } ] }; } const dbResult = await models.User.findAndCountAll({ where }); const users = await models.User.findAll({ where, limit, offset, order: [[attribute, order]] }); if (users) { const pagination = helpers.Misc.generatePaginationMeta( req, dbResult, limit, offset ); const updatedUsers = []; // using await in loop as shown below // https://blog.lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795 // eslint-disable-next-line no-restricted-syntax for (const user of users) { // eslint-disable-next-line no-await-in-loop const u = await helpers.Misc.updateUserAttributes(user, req); updatedUsers.push(u); } return res.sendSuccess({ users: updatedUsers }, 200, { pagination }); } throw new Error('Could not retrieve users from the database.'); } catch (error) { return res.sendFailure([error.message]); } } /** * @method getById * @desc This method get the user with the specified user ID * * @param { object } req request * @param { object } res response * * @returns { object } response */ async getById(req, res) { try { const user = await helpers.Misc.updateUserAttributes(req.existingUser, req); return res.sendSuccess({ user }); } catch (error) { return res.sendFailure([error.message]); } } /** * @method updateById * @desc This method updates the user with the specified user ID * * @param { object } req request * @param { object } res response * * @returns { object } response */ async updateById(req, res) { try { // the only properties you can update using this endpoint are: // 'blocked', 'photo', 'role' const fieldsToUpdate = {}; if (typeof req.body.blocked !== 'undefined') { // only an admin can update 'blocked' if (req.user.role !== 'admin') { throw new Error('You need admin privilege to block or unblock a user.'); } // a user cannot update their own 'blocked' if (req.existingUser.id === req.user.id) { throw new Error('You cannot block or unblock yourself.'); } fieldsToUpdate.blocked = req.body.blocked; } if (typeof req.body.role !== 'undefined') { // only an admin can update 'role' if (req.user.role !== 'admin') { throw new Error('You need admin privilege to assign roles to a user.'); } // a user cannot update their own 'role' if (req.existingUser.id === req.user.id) { throw new Error('You cannot assign roles to yourself.'); } fieldsToUpdate.role = req.body.role; } if (typeof req.body.photo !== 'undefined') { // you cannot update another user's 'photo' if (req.existingUser.id !== req.user.id) { throw new Error('Cannot update another user\'s photo.'); } fieldsToUpdate.photo = req.body.photo; } if (typeof req.body.githubUsername !== 'undefined') { // you cannot update another user's 'githubUsername' if (req.existingUser.id !== req.user.id) { throw new Error('Cannot update another user\'s Github username.'); } fieldsToUpdate.githubUsername = req.body.githubUsername; } if (typeof req.body.slackId !== 'undefined') { // you cannot update another user's 'slackId' if (req.existingUser.id !== req.user.id) { throw new Error('Cannot update another user\'s Slack ID.'); } fieldsToUpdate.slackId = req.body.slackId; } const updatedUser = await req.existingUser.update(fieldsToUpdate); const user = await helpers.Misc.updateUserAttributes(updatedUser, req); return res.sendSuccess({ user }); } catch (error) { return res.sendFailure([error.message]); } } }
JavaScript
class CommandMap extends Map { constructor(...args) { super(...args); // Cached (maybe transfer to getter?) this.identifiers = []; // Primary cmd names this.references = []; // All cmd names } /** * Returns and order of the command map keys by how similar they are to a keyword. * * @param {string} keyword The keyword for comparison. * @returns {Array} The ordering. */ similar(keyword) { let similarityHeap = buckets.Heap((a, b) => a.similarity < b.similarity); for (let reference of this.references) { similarityHeap.add({ reference, similarity: String.levenshtein(reference, keyword) }); } return similarityHeap.toArray(); } /** * Adds a command to the map. * * @param {Command} command An instance of the command class. */ addCommand(command) { if (!(command instanceof Command)) { throw new TypeError('CommandMap only accepts instances of Command'); } for (let alias of [command.id, ...command.aliases]) { if (this.get(alias)) { throw new Error( `Command alias '${alias}' of command '${command.id}' has already been declared in the command map!` ); } this.set(alias, command); this.references.push(alias); } this.identifiers.push(command.id); } /** * Quickly retrives the command by id or alias. * * @param {string} idOrAlias String representing an id or alias of the command. * @returns {Command} The command, if any. */ retrieveCommand(idOrAlias) { return this.get(idOrAlias); } }
JavaScript
class RateLimitError extends Error { constructor(msBeforeNextReset) { super('Too many requests, please try again shortly.'); // * Determine when the rate limit will be reset so the client can try again const resetAt = new Date(); resetAt.setTime(resetAt.getTime() + msBeforeNextReset); /** * GraphQL will automatically use this field to return extensions data in the GraphQLError * * @see {@link https://github.com/graphql/graphql-js/pull/928|GitHub} */ this.extensions = { code: 'RATE_LIMITED', resetAt, } } }
JavaScript
class Limbo { /** * Verifies a limbo game for a given GAME_SEED_DATA object. * * @param {Object} GAME_SEED_DATA - The game seed data. * @param {string} GAME_SEED_DATA.serverSeed - The server seed. * @param {string} GAME_SEED_DATA.clientSeed - The client seed. * @param {integer} GAME_SEED_DATA.nonce - The nonce. * @return {float} The float. */ verify(GAME_SEED_DATA) { const MAX_MULTIPLIER = 1e8; const FLOAT_POINT = MAX_MULTIPLIER / (GameSeedUtils.extractFloat(GAME_SEED_DATA) * MAX_MULTIPLIER) * 0.99; return (Math.floor(FLOAT_POINT * 100) / 100).toFixed(2); } }
JavaScript
class TokensList extends React.Component { /* * tokens {Array} List of token objects {'uid', 'name', 'symbol'} from data arriving in the API * truncated {boolean} If data from API was truncated * loaded {boolean} If data was loaded from API * errorMessage {String} Error message */ state = { tokens: [], truncated: false, loaded: false, errorMessage: '', } componentDidMount() { this.updateData(); } /* * Call the API of tokens list and update component state with result */ updateData = () => { hathorLib.walletApi.getTokensList((response) => { if (response.success) { this.setState({ tokens: response.tokens, truncated: response.truncated, loaded: true, }); } else { this.setState({ errorMessage: response.message, loaded: true }); } }); } /* * Redirect to token detail screen when clicked on the token row * * @param {String} uid UID of the token clicked */ handleClickTr = (uid) => { this.props.history.push(`/token_detail/${uid}`); } render() { const renderList = () => { return ( <div className="table-responsive mt-5"> {this.state.truncated && <p className="text-warning">You are not seeing all tokens on this list. The data was truncated to {this.state.tokens.length} elements. </p>} <table className="table table-striped" id="tx-table"> <thead> <tr> <th className="d-none d-lg-table-cell">UID</th> <th className="d-none d-lg-table-cell">Name</th> <th className="d-none d-lg-table-cell">Symbol</th> <th className="d-table-cell d-lg-none" colSpan="2">UID<br/>Name (Symbol)</th> </tr> </thead> <tbody> {renderData()} </tbody> </table> </div> ); } const renderData = () => { return this.state.tokens.map((token, idx) => { return renderRow(token, idx); }); } const renderRow = (token, idx) => { return ( <tr key={idx} onClick={(e) => this.handleClickTr(token.uid)}> <td className="d-none d-lg-table-cell pr-3">{hathorLib.helpers.getShortHash(token.uid)}</td> <td className="d-none d-lg-table-cell pr-3">{token.name}</td> <td className="d-none d-lg-table-cell pr-3">{token.symbol}</td> <td className="d-lg-none d-table-cell pr-3" colSpan="2">{hathorLib.helpers.getShortHash(token.uid)}<br/>{token.name} ({token.symbol})</td> </tr> ) } return ( <div className="content-wrapper"> <div className="w-100"> <h1>Tokens</h1> {!this.state.loaded ? <ReactLoading type='spin' color={colors.purpleHathor} delay={500} /> : renderList()} {this.state.errorMessage ? <span className="text-danger">{this.state.errorMessage}</span> : null} </div> </div> ); } }
JavaScript
class MoviesPage extends mix(BasePage).with(BrowserTypeMixin) { // Wonton config static componentName() { return 'page-movies'; } template() { return template; } references() { return { 'movieCards': '.movie-cards', 'addBtn': '.movie-cards-new-control', 'dialog': '.movie-cards-dialog', 'dialogTitle': '.movie-cards-dialog-title', 'dialogForm': '.movie-cards-dialog-form', 'dialogFormSubmit': '.movie-cards-dialog-form-submit', 'rateDialog': '.movie-cards-rate-dialog', 'rateEditor': '.movie-cards-rate-editor', 'rateSubmit': '.movie-cards-rate-submit' } } listeners() { return { 'addBtn': { 'click': () => { this.getRef('dialogForm').reset(); this.getRef('dialogTitle').textContent = "New Movie"; this.getRef('dialog').show(); } }, 'dialogFormSubmit': { 'click': () => { this.getRef('dialogForm').submit(); } }, 'dialogForm': { 'add-movie': e => { const movie = e.detail; movie.author = SimpleStore.get('user').getData().uid; this._needsRefreshing = true; this._db.collection("movies").add(movie).then(() => { log.debug('Successfully added', movie); }, err => { alert('Could not add the movie!'); log.error('Movie creation error', err); }); this.getRef('dialog').hide(); }, 'update-movie': e => { const movie = e.detail; this._needsRefreshing = true; this._db.collection("movies").doc(movie.uid).update(movie).then(() => { log.debug('Successfully updated', movie); }, err => { alert('Could not update the movie!'); log.error('Movie update error', err); }); this.getRef('dialog').hide(); } }, 'movieCards': { 'edit-movie': e => { const movieToEdit = e.detail; const currentUser = SimpleStore.get('user').getData(); if (currentUser.uid !== movieToEdit.author && !currentUser.admin) { alert('Not authorized!'); return; } this.getRef('dialogTitle').textContent = "Edit Movie"; this.getRef('dialogForm').movie = movieToEdit; this.getRef('dialog').show(); }, 'rate-movie': e => { this._movieToRate = e.detail; const currentUser = SimpleStore.get('user').getData(); if (currentUser.isAnonymous) { alert('Not authorized!'); return; } this.getRef('rateEditor').rating = currentUser.ratings[this._movieToRate.uid] ? currentUser.ratings[this._movieToRate.uid].rating : 0; this.getRef('rateDialog').show(); }, 'delete-movie': e => { const currentUser = SimpleStore.get('user').getData(); if (!currentUser.admin) { alert('Not authorized!'); return; } const movieToDelete = e.detail; if (confirm(`You are about to delete the movie card "${movieToDelete.name}". Do you wish to proceed?`)) { this._needsRefreshing = true; this._db.collection('movies').doc(movieToDelete.uid).delete().then(() => { log.debug('Successfully deleted', movieToDelete); }, err => { alert('Could not delete the movie!'); log.error('Movie deletion error', err); }); } } }, 'rateSubmit': { 'click': () => { const currentUser = SimpleStore.get('user').getData(); const newRating = this.getRef('rateEditor').rating; this._movieToRate.ratingCount += currentUser.ratings[this._movieToRate.uid] ? 0 : 1; this._movieToRate.ratingTotal += newRating - (currentUser.ratings[this._movieToRate.uid] ? currentUser.ratings[this._movieToRate.uid].rating : 0); if (currentUser.ratings[this._movieToRate.uid]) { this._db.collection('users-ratings').doc(currentUser.ratings[this._movieToRate.uid].uid).update({ rating: newRating }); } else { this._db.collection('users-ratings').doc(`${this._movieToRate.uid}|${currentUser.uid}`).set({ user: currentUser.uid, movie: this._movieToRate.uid, rating: newRating }); } this._db.collection('movies').doc(this._movieToRate.uid).update({ ratingCount: this._movieToRate.ratingCount, ratingTotal: this._movieToRate.ratingTotal }); currentUser.ratings[this._movieToRate.uid] = { uid: `${this._movieToRate.uid}|${currentUser.uid}`, rating: newRating }; this.getRef('rateDialog').hide(); } } } } // Lifecycle connectedCallback() { super.connectedCallback(); this._userSub = SimpleStore.get('user') .pipe(debounceTime(100)) .subscribe(user => { this._needsRefreshing = true; // Only show the "Add Movie" button for non-anonymous users this.getRef('addBtn').style.visibility = (user.uid && !user.isAnonymous) ? 'visible' : 'hidden'; // Only download data if there is a logged-in user (even an anonymous one) and if the movies are not already pre-loaded if (user.uid && !SimpleStore.get('movies').getData('movies')) { this._db = firebase.firestore(); // Retrieve data this._firestoreUnsubsribe = this._db.collection("movies") .orderBy('name') .onSnapshot({ includeMetadataChanges: true }, querySnapshot => { this._needsRefreshing = true; const movies = []; querySnapshot.forEach(s => movies.push({ uid: s.id, ...s.data(), release: s.data().release && !isNaN(s.data().release.toDate()) ? s.data().release.toDate() : null })) SimpleStore.get('movies').setData({ movies }); }); } if (this._moviesSubscription) this._moviesSubscription.unsubscribe(); this._moviesSubscription = SimpleStore.get('movies').subscribe(data => { const movieCards = this.getRef('movieCards'); if (!movieCards.hasChildNodes() || this._needsRefreshing) { const currentUser = SimpleStore.get('user').getData(); // Displays the list of movies const fragment = document.createDocumentFragment(); (data.movies || []).forEach(movie => { const movieCard = document.createElement('wtn-movie-card'); movieCard.movie = movie; movieCard.hidedelete = !currentUser.admin; movieCard.hideedit = currentUser.isAnonymous || (!currentUser.admin && currentUser.uid !== movie.author); movieCard.hiderate = currentUser.isAnonymous; fragment.appendChild(movieCard); }); while (movieCards.lastElementChild) { movieCards.removeChild(movieCards.lastElementChild); } movieCards.appendChild(fragment); this._needsRefreshing = false; } }); }); } disconnectedCallback() { super.disconnectedCallback(); if (this._userSub) this._userSub.unsubscribe(); if (this._moviesSubscription) this._moviesSubscription.unsubscribe(); if (this._firestoreUnsubsribe) this._firestoreUnsubsribe(); } }
JavaScript
class GetaddrMessage extends Message { constructor ( arg, options ) { super( options ); this.command = 'getaddr'; } setPayload () { }; getPayload () { return Buffer.alloc( 32, 0 ); }; }
JavaScript
class Example { /** * Constructor function to hold stuff * @param {object} element DOM object */ constructor( el ) { const self = this; if ( el ) { console.log( el ); console.log( self ); } } /** * Init function definition * @param {object} el selector * @returns {object} The element itself */ static init( el ) { const elem = document.querySelector( el ); return elem ? new Example( elem ) : false; } }
JavaScript
class MainNavbar extends React.Component { constructor(props) { super(props); } render() { /* const token = this.props.token; if(token === null){ return <AnonymousNavbar/> } if(token.authorities[0] === "ROLE_ADMIN") {*/ return <AdminNavbar/> /*} return <NormalUserNavbar/>*/ } }
JavaScript
class VersionHandler { // The Foundry versions that have been implemented static implementedFoundryVersions = ["0.6.6", "0.7.5", "0.8.5"]; // The version we are treating Foundry as static effectiveVersion; /** * Sets the "effectiveVersion" parameter to the newest * supported Foundry version that is not newer than it. * @param {string} foundryVersion The current true version of Foundry */ static setEffectiveVersion(foundryVersion) { if(VersionHandler.effectiveVersion) { console.warn("Scene Defaults | Version is being set multiple times"); return; } VersionHandler.effectiveVersion = this.findClosestImplementedVersion(foundryVersion); } /** * Essentially "floors" the current Foundry version to an implemented version * @param {string} foundryVersion The current true version of Foundry * @returns {string} The closest implemented version */ static findClosestImplementedVersion(foundryVersion) { for(let i = VersionHandler.implementedFoundryVersions.length - 1; i >= 0; i--) { const version = VersionHandler.implementedFoundryVersions[i]; if(version === foundryVersion || isNewerVersion(foundryVersion, version)) { return version; } } console.error("Scene Defaults | Foundry Version is unsupported."); } /** * @returns {Object} The default data Foundry uses to create scenes for the current effective version of Foundry */ static getFoundryDefaultScene() { if(!VersionHandler.effectiveVersion) { console.error("Scene Defaults | Version was not set before getting Foundry defaults"); } const sceneData = defaultSceneData[VersionHandler.effectiveVersion]; //Default grid units/distance are set by the system sceneData.gridDistance = game.data.system.data.gridDistance ?? 5; sceneData.gridUnits = game.data.system.data.gridUnits ?? "ft"; return sceneData; } /** * @returns {string} the path to the template used to configure scene defaults for the current effective version of Foundry */ static getTemplate() { if(!VersionHandler.effectiveVersion) { console.error("Scene Defaults | Version was not set before getting template"); } const templates = { "0.6.6": "./modules/scene-defaults/templates/defaultSceneConfigs/defaultSceneConfig-0-6-6.html", "0.7.5": "./modules/scene-defaults/templates/defaultSceneConfigs/defaultSceneConfig-0-7-5.html", "0.8.5": "./modules/scene-defaults/templates/defaultSceneConfigs/defaultSceneConfig-0-8-6.html" } return templates[VersionHandler.effectiveVersion]; } /** * Migrates a scene's data to the current effective Foundry version, * adding any missing settings by using Foundry's default settings. * No data is (read: should be) overwritten. * The updated data is returned, rather than updated in place. * @param {Object} data Data from an existing preset. * @returns {Object} The migrated data */ static migrateSceneData(data) { const targetDefaultData = VersionHandler.getFoundryDefaultScene(); if(!data) { console.warn("Scene Defaults | Trying to migrate null data. Using default data instead") return targetDefaultData; } // Add all keys needed for the target version, but don't overwrite existing data // Extra keys that were saved but aren't used in the target version will last // until the scene default config window is opened and saved return mergeObject(data, targetDefaultData, { insertKeys: true, insertValues: true, overwrite: false, inplace: false }); } }
JavaScript
class Camera { /** * @param {Object} context The simulation context */ constructor(context) { // TODO(ian): Accept either context or container this._context = context; this._camera = null; this._cameraControls = null; // Optional mesh that we are following. this._followMesh = null; this.init(); } init() { const containerWidth = this._context.container.width; const containerHeight = this._context.container.height; this._camera = new THREE.PerspectiveCamera( 50, containerWidth / containerHeight, rescaleNumber(0.00001), rescaleNumber(2000), ); // Controls // TODO(ian): Set maxDistance to prevent camera farplane cutoff. // See https://discourse.threejs.org/t/camera-zoom-to-fit-object/936/6 // TODO(ian): Access this better const renderer = this._context.simulation._renderer; const controls = new OrbitControls(this._camera, renderer.domElement); controls.enableDamping = true; controls.enablePan = true; controls.zoomSpeed = 1.5; controls.userPanSpeed = 20; controls.rotateSpeed = 2; controls.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_ROTATE, }; this._cameraControls = controls; } /** * Move the camera to follow a SpaceObject as it moves. Currently only works * for non-particlesystems. * @param {SpaceObject} obj SpaceObject to follow. * @param {Array.<Number>} position Position of the camera with respect to * the object. */ followObject(obj, position) { const followMesh = obj.get3jsObjects()[0]; this._cameraControls.enablePan = false; const rescaled = rescaleArray(position); this._camera.position.add( new THREE.Vector3(rescaled[0], rescaled[1], rescaled[2]), ); this._cameraControls.update(); this._followMesh = followMesh; } /** * Stop the camera from following the object. */ stopFollowingObject() { if (this._followMesh) { this._followMesh.remove(this._camera); this._followMesh = null; this._cameraControls.enablePan = true; } } /** * @returns {boolean} True if camera is following object. */ isFollowingObject() { return !!this._followMesh; } /** * @returns {THREE.Camera} The THREE.js camera object. */ get3jsCamera() { return this._camera; } /** * @returns {THREE.CameraControls} The THREE.js CameraControls object. */ get3jsCameraControls() { return this._cameraControls; } /** * Update the camera position and process control inputs. */ update() { if (this.isFollowingObject()) { const newpos = this._followMesh.position.clone(); const offset = newpos.clone().sub(this._cameraControls.target); this._camera.position.add(offset); this._cameraControls.target.set(newpos.x, newpos.y, newpos.z); } // Handle control movements this._cameraControls.update(); // Update camera matrix this._camera.updateMatrixWorld(); } }
JavaScript
class PseudoSession { constructor(addressSpace, server, session) { this.requestedMaxReferencesPerNode = 0; this.addressSpace = addressSpace; this.server = server || {}; this.session = session || { channel: { clientCertificate: null, securityMode: node_opcua_types_1.MessageSecurityMode.None, securityPolicy: "http://opcfoundation.org/UA/SecurityPolicy#None" // SecurityPolicy.None } }; this.continuationPointManager = new continuation_point_manager_1.ContinuationPointManager(); } browse(nodesToBrowse, callback) { setImmediate(() => { const isArray = _.isArray(nodesToBrowse); if (!isArray) { nodesToBrowse = [nodesToBrowse]; } let results = []; for (let browseDescription of nodesToBrowse) { browseDescription.referenceTypeId = node_opcua_nodeid_1.resolveNodeId(browseDescription.referenceTypeId); browseDescription = new node_opcua_service_browse_1.BrowseDescription(browseDescription); const nodeId = node_opcua_nodeid_1.resolveNodeId(browseDescription.nodeId); const r = this.addressSpace.browseSingleNode(nodeId, browseDescription); results.push(r); } // handle continuation points results = results.map((result) => { node_opcua_assert_1.assert(!result.continuationPoint); const truncatedResult = this.continuationPointManager.register(this.requestedMaxReferencesPerNode, result.references || []); node_opcua_assert_1.assert(truncatedResult.statusCode === node_opcua_status_code_1.StatusCodes.Good); truncatedResult.statusCode = result.statusCode; return new node_opcua_service_browse_1.BrowseResult(truncatedResult); }); callback(null, isArray ? results : results[0]); }); } read(nodesToRead, callback) { const isArray = _.isArray(nodesToRead); if (!isArray) { nodesToRead = [nodesToRead]; } setImmediate(() => { // xx const context = new SessionContext({ session: null }); const dataValues = nodesToRead.map((nodeToRead) => { node_opcua_assert_1.assert(!!nodeToRead.nodeId, "expecting a nodeId"); node_opcua_assert_1.assert(!!nodeToRead.attributeId, "expecting a attributeId"); const nodeId = nodeToRead.nodeId; const attributeId = nodeToRead.attributeId; const indexRange = nodeToRead.indexRange; const dataEncoding = nodeToRead.dataEncoding; const obj = this.addressSpace.findNode(nodeId); if (!obj) { return new node_opcua_data_value_1.DataValue({ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown }); } const context = session_context_1.SessionContext.defaultContext; const dataValue = obj.readAttribute(context, attributeId, indexRange, dataEncoding); return dataValue; }); callback(null, isArray ? dataValues : dataValues[0]); }); } browseNext(continuationPoints, releaseContinuationPoints, callback) { setImmediate(() => { if (continuationPoints instanceof Buffer) { return this.browseNext([continuationPoints], releaseContinuationPoints, (err, _results) => { if (err) { return callback(err); } callback(null, _results[0]); }); return; } const session = this; let results; if (releaseContinuationPoints) { // releaseContinuationPoints = TRUE // passed continuationPoints shall be reset to free resources in // the Server. The continuation points are released and the results // and diagnosticInfos arrays are empty. results = continuationPoints.map((continuationPoint) => { return session.continuationPointManager.cancel(continuationPoint); }); } else { // let extract data from continuation points // releaseContinuationPoints = FALSE // passed continuationPoints shall be used to get the next set of // browse information. results = continuationPoints.map((continuationPoint) => { return session.continuationPointManager.getNext(continuationPoint); }); } results = results.map((r) => new node_opcua_service_browse_1.BrowseResult(r)); callback(null, results); }); } call(methodsToCall, callback) { const isArray = _.isArray(methodsToCall); if (!isArray) { methodsToCall = [methodsToCall]; } async.map(methodsToCall, (methodToCall, innerCallback) => { const callMethodRequest = new node_opcua_service_call_1.CallMethodRequest(methodToCall); call_helpers_1.callMethodHelper(this.server, this.session, this.addressSpace, callMethodRequest, (err, result) => { let callMethodResult; if (err) { callMethodResult = new node_opcua_service_call_1.CallMethodResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError }); } else { callMethodResult = new node_opcua_service_call_1.CallMethodResult(result); } innerCallback(null, callMethodResult); }); }, (err, callMethodResults) => { callback(null, isArray ? callMethodResults : callMethodResults[0]); }); } getArgumentDefinition(methodId, callback) { return node_opcua_pseudo_session_1.getArgumentDefinitionHelper(this, methodId, callback); } translateBrowsePath(browsePaths, callback) { const isArray = _.isArray(browsePaths); if (!isArray) { browsePaths = [browsePaths]; } // xx const context = new SessionContext({ session: null }); const browsePathResults = browsePaths.map((browsePath) => { return this.addressSpace.browsePath(browsePath); }); callback(null, isArray ? browsePathResults : browsePathResults[0]); } }
JavaScript
class StructError extends TypeError { constructor(attrs) { const { data, value, type, path, errors = [] } = attrs; const message = `Expected a value of type \`${type}\`${path.length ? ` for \`${path.join('.')}\`` : ''} but received \`${value}\`.`; super(message); this.data = data; this.path = path; this.value = value; this.type = type; this.errors = errors; if (!errors.length) errors.push(this); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error().stack; } } }
JavaScript
class Kind { constructor(name, type, validate) { this.name = name; this.type = type; this.validate = validate; } }
JavaScript
class App { /** * Wires up the main eventbus, invokes the private s_INITIALIZE_ROUTE function which creates `AppRouter` and sets up * a catch all handler then invokes `Backbone.history.start` with the root path and finally the constructor creates the main view.. */ constructor() { // Wire up the main eventbus to respond to the following events. By passing in `this` in the third field to // `on` that sets the context when the callback is invoked. eventbus.on('app:create:item', this.createItem, this); eventbus.on('app:select:filter', this.selectFilter, this); // Invokes a private method to initialize the `AppRouter`, add a default catch all handler, and start // `Backbone.history`. s_INITIALIZE_ROUTE(); /** * Creates the only displayed view of the app. * * @type {View} Stores the current active view. */ this.currentView = this.showTodos(); } /** * Creates a new Item in the todos list. * * @param {string} content - The text for the item. */ createItem(content) { // Ensure that content is a string. If so then create a new `Item` entry in `todoList`. if (typeof content === 'string') { todoList.create( { content, order: todoList.nextOrder(), done: false }); } } /** * Sets the app state with the new filter type and updates `Backbone.History`. * * @param {string} filter - Filter type to select. */ selectFilter(filter) { // When setting a value on a `Backbone.Model` if the value is the same as what is being set a change event will // not be fired. In this case we set the new state with the `silent` option which won't fire any events then // we manually trigger a change event so that any listeners respond regardless of the original state value. appState.set({ filter }, { silent: true }); appState.trigger('change', appState); // Update the history state with the new filter type. Backbone.history.navigate(filter); } /** * Creates and shows a new ManageTodosView then fetches the collection. * * @returns {*} */ showTodos() { if (this.currentView) { this.currentView.close(); } Backbone.history.navigate(appState.get('filter'), { replace: true }); this.currentView = new ManageTodosView(); // Fetch all the todos items from local storage. Any listeners for `todoList` reset events will be invoked. todoList.fetch({ reset: true }); return this.currentView; } }
JavaScript
class MultiColumnContainer extends BlockElement { /** * Adds another column. * * @param {VerticalFlowContainer|int} insertBefore index of column or * reference on column becoming successor of inserted one, null is * for appending column * @return {VerticalFlowContainer} created and added column */ addColumn( insertBefore = null ) { const { content } = this; const numColumns = content.length; let _index = -1; if ( insertBefore instanceof VerticalFlowContainer ) { for ( let i = 0; i < numColumns; i++ ) { if ( content[i] === insertBefore ) { _index = i; break; } } } else if ( insertBefore == null ) { _index = numColumns; } else if ( !isNaN( insertBefore ) ) { _index = Math.max( 0, Math.min( numColumns - 1, parseInt( insertBefore ) ) ); } if ( _index < 0 ) { throw new Error( "invalid reference/index for inserting column" ); } const column = new VerticalFlowContainer( this ); content.splice( _index, 0, column ); return column; } /** * Removes selected column from container returning reference on removed * column element. * * @param {VerticalFlowContainer|int} column reference on column element or index of column element to remove * @return {VerticalFlowContainer} removed column element * @throws Error on invalid selection of a column element */ removeColumn( column ) { const { content } = this; const numColumns = content.length; if ( column instanceof VerticalFlowContainer ) { for ( let i = 0; i < numColumns; i++ ) { if ( content[i] === column ) { content.splice( i, 1 ); return column; } } throw new TypeError( "column not found in container" ); } const _index = parseInt( column ); if ( _index > -1 && _index < numColumns ) { const removedColumn = content[_index]; content.splice( _index, 1 ); return removedColumn; } throw new TypeError( "invalid index for selecting column to remove" ); } }
JavaScript
class CookieOperator { /** * Create an instance * @param {Object} [attributes] - Parameter object. */ constructor(attributes = {}) { this.attributes = attributes } /** * Create an instance with a custom parameter object * @param {Object} [attribute] - parameter object. * */ create(attribute) { return new CookieOperator(attribute) } /** * Get the parameters of the current instance * */ getAttr() { return this.attributes } /** * Check if a set of cookies are present * @param {string} keys - cookies keys. * */ checkAll(keys = []) { if (Object.keys(keys).length === 0) { return false } let loseCookie = false; // 缺少某个cookie keys.forEach(name => { if (this.get(name) === 'undefined') { loseCookie = true; } }); return !loseCookie; } /** * Get the value of a cookie. * @param {string} key - cookie name. */ get(key) { let _key = encodeURIComponent(String(key)); let cookie = document.cookie; let pattern = /([^=]+)=([^;]+);?\s*/g; let result; let value = {}; while ((result = pattern.exec(cookie)) != null) { value[result[1]] = result[2]; } if (key) { return decodeURIComponent(value[_key]); } else { return value; } } /** * Set the value of a cookie. * @param {string} key - cookie name. * @param {string} value - cookie value. * @param {Object} [attributes] - parameter object. * @return {String} The current document's cookie string. */ set(key, value, attributes = this.attributes) { let _attributes = Object.assign({}, attributes); let { expires, path } = _attributes; // 0.转义 let _key = encodeURIComponent(String(key)); let _value = encodeURIComponent(String(value)); // 1.特殊处理超时时间 if (typeof expires === 'number') { let _expires = new Date(); _expires.setMilliseconds(_expires.getMilliseconds() + expires * 864e5); _attributes.expires = _expires.toGMTString(); } else if (expires instanceof Date) { _attributes.expires = expires.toGMTString(); } else { _attributes.expires = ''; } // 2.path默认值 _attributes.path = path ? path : '/'; // 3.拼接cookie字符串 let stringifiedAttributes = ''; for (let attributeName in _attributes) { if (!_attributes[attributeName]) { continue; } stringifiedAttributes += '; ' + attributeName; if (_attributes[attributeName] === true) { continue; } stringifiedAttributes += '=' + _attributes[attributeName]; } document.cookie = _key + '=' + _value + stringifiedAttributes; return document.cookie; } /** * Delete a cookie. * @param {string} key - cookie name. * @param {Object} [attributes] - parameter object. */ remove(key, attributes = this.attributes) { let value = ''; return this.set( key, value, Object.assign({}, attributes, { expires: -1 }) ); } /** * Delete a set of cookies. * @param {string} keys - cookie keys. * @param {Object} [attributes] - parameter object. */ removeAll(keys = [], attributes = this.attributes) { keys.forEach(name => { this.remove(name, attributes); }); } /** * Get a top-level domain. * @param {string} [domain] - Domain name to be processed. */ getTopDomain(domain) { let _domain = domain || document.domain; if (isIP(_domain)) { return _domain } else { // 删除三级域名 return _domain.substring(_domain.length, _domain.lastIndexOf('.', _domain.lastIndexOf('.') - 1) + 1); } } }
JavaScript
class ReadableEthersLiquity { /** @internal */ constructor(connection) { this.connection = connection; } /** @internal */ static _from(connection) { const readable = new ReadableEthersLiquity(connection); return connection.useStore === "blockPolled" ? new _BlockPolledReadableEthersLiquity(readable) : readable; } /** * Connect to the Liquity protocol and create a `ReadableEthersLiquity` object. * * @param signerOrProvider - Ethers `Signer` or `Provider` to use for connecting to the Ethereum * network. * @param optionalParams - Optional parameters that can be used to customize the connection. */ static async connect(signerOrProvider, optionalParams) { return ReadableEthersLiquity._from(await EthersLiquityConnection_1._connect(signerOrProvider, optionalParams)); } hasStore() { return false; } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getTotalRedistributed} */ async getTotalRedistributed(overrides) { const { troveManager } = EthersLiquityConnection_1._getContracts(this.connection); const [collateral, debt] = await Promise.all([ troveManager.L_ETH({ ...overrides }).then(_utils_1.decimalify), troveManager.L_LUSDDebt({ ...overrides }).then(_utils_1.decimalify) ]); return new lib_base_1.Trove(collateral, debt); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getTroveBeforeRedistribution} */ async getTroveBeforeRedistribution(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { troveManager } = EthersLiquityConnection_1._getContracts(this.connection); const [trove, snapshot] = await Promise.all([ troveManager.Troves(address, { ...overrides }), troveManager.rewardSnapshots(address, { ...overrides }) ]); if (trove.status === BackendTroveStatus.active) { return new lib_base_1.TroveWithPendingRedistribution(address, userTroveStatusFrom(trove.status), _utils_1.decimalify(trove.coll), _utils_1.decimalify(trove.debt), _utils_1.decimalify(trove.stake), new lib_base_1.Trove(_utils_1.decimalify(snapshot.ETH), _utils_1.decimalify(snapshot.LUSDDebt))); } else { return new lib_base_1.TroveWithPendingRedistribution(address, userTroveStatusFrom(trove.status)); } } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getTrove} */ async getTrove(address, overrides) { const [trove, totalRedistributed] = await Promise.all([ this.getTroveBeforeRedistribution(address, overrides), this.getTotalRedistributed(overrides) ]); return trove.applyRedistribution(totalRedistributed); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getNumberOfTroves} */ async getNumberOfTroves(overrides) { const { troveManager } = EthersLiquityConnection_1._getContracts(this.connection); return (await troveManager.getTroveOwnersCount({ ...overrides })).toNumber(); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getPrice} */ getPrice(overrides) { const { priceFeed } = EthersLiquityConnection_1._getContracts(this.connection); return priceFeed.callStatic.fetchPrice({ ...overrides }).then(_utils_1.decimalify); } /** @internal */ async _getActivePool(overrides) { const { activePool } = EthersLiquityConnection_1._getContracts(this.connection); const [activeCollateral, activeDebt] = await Promise.all([ activePool.getETH({ ...overrides }), activePool.getLUSDDebt({ ...overrides }) ].map(getBigNumber => getBigNumber.then(_utils_1.decimalify))); return new lib_base_1.Trove(activeCollateral, activeDebt); } /** @internal */ async _getDefaultPool(overrides) { const { defaultPool } = EthersLiquityConnection_1._getContracts(this.connection); const [liquidatedCollateral, closedDebt] = await Promise.all([ defaultPool.getETH({ ...overrides }), defaultPool.getLUSDDebt({ ...overrides }) ].map(getBigNumber => getBigNumber.then(_utils_1.decimalify))); return new lib_base_1.Trove(liquidatedCollateral, closedDebt); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getTotal} */ async getTotal(overrides) { const [activePool, defaultPool] = await Promise.all([ this._getActivePool(overrides), this._getDefaultPool(overrides) ]); return activePool.add(defaultPool); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getStabilityDeposit} */ async getStabilityDeposit(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { stabilityPool } = EthersLiquityConnection_1._getContracts(this.connection); const [{ frontEndTag, initialValue }, currentLUSD, collateralGain, lqtyReward] = await Promise.all([ stabilityPool.deposits(address, { ...overrides }), stabilityPool.getCompoundedLUSDDeposit(address, { ...overrides }), stabilityPool.getDepositorETHGain(address, { ...overrides }), stabilityPool.getDepositorLQTYGain(address, { ...overrides }) ]); return new lib_base_1.StabilityDeposit(_utils_1.decimalify(initialValue), _utils_1.decimalify(currentLUSD), _utils_1.decimalify(collateralGain), _utils_1.decimalify(lqtyReward), frontEndTag); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getRemainingStabilityPoolLQTYReward} */ async getRemainingStabilityPoolLQTYReward(overrides) { const { communityIssuance } = EthersLiquityConnection_1._getContracts(this.connection); const issuanceCap = this.connection.totalStabilityPoolLQTYReward; const totalLQTYIssued = _utils_1.decimalify(await communityIssuance.totalLQTYIssued({ ...overrides })); // totalLQTYIssued approaches but never reaches issuanceCap return issuanceCap.sub(totalLQTYIssued); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getLUSDInStabilityPool} */ getLUSDInStabilityPool(overrides) { const { stabilityPool } = EthersLiquityConnection_1._getContracts(this.connection); return stabilityPool.getTotalLUSDDeposits({ ...overrides }).then(_utils_1.decimalify); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getLUSDBalance} */ getLUSDBalance(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { lusdToken } = EthersLiquityConnection_1._getContracts(this.connection); return lusdToken.balanceOf(address, { ...overrides }).then(_utils_1.decimalify); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getLQTYBalance} */ getLQTYBalance(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { lqtyToken } = EthersLiquityConnection_1._getContracts(this.connection); return lqtyToken.balanceOf(address, { ...overrides }).then(_utils_1.decimalify); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getUniTokenBalance} */ getUniTokenBalance(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { uniToken } = EthersLiquityConnection_1._getContracts(this.connection); return uniToken.balanceOf(address, { ...overrides }).then(_utils_1.decimalify); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getUniTokenAllowance} */ getUniTokenAllowance(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { uniToken, unipool } = EthersLiquityConnection_1._getContracts(this.connection); return uniToken.allowance(address, unipool.address, { ...overrides }).then(_utils_1.decimalify); } /** @internal */ async _getRemainingLiquidityMiningLQTYRewardCalculator(overrides) { const { unipool } = EthersLiquityConnection_1._getContracts(this.connection); const [totalSupply, rewardRate, periodFinish, lastUpdateTime] = await Promise.all([ unipool.totalSupply({ ...overrides }), unipool.rewardRate({ ...overrides }).then(_utils_1.decimalify), unipool.periodFinish({ ...overrides }).then(_utils_1.numberify), unipool.lastUpdateTime({ ...overrides }).then(_utils_1.numberify) ]); return (blockTimestamp) => rewardRate.mul(Math.max(0, periodFinish - (totalSupply.isZero() ? lastUpdateTime : blockTimestamp))); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getRemainingLiquidityMiningLQTYReward} */ async getRemainingLiquidityMiningLQTYReward(overrides) { const [calculateRemainingLQTY, blockTimestamp] = await Promise.all([ this._getRemainingLiquidityMiningLQTYRewardCalculator(overrides), this._getBlockTimestamp(overrides === null || overrides === void 0 ? void 0 : overrides.blockTag) ]); return calculateRemainingLQTY(blockTimestamp); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getLiquidityMiningStake} */ getLiquidityMiningStake(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { unipool } = EthersLiquityConnection_1._getContracts(this.connection); return unipool.balanceOf(address, { ...overrides }).then(_utils_1.decimalify); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getTotalStakedUniTokens} */ getTotalStakedUniTokens(overrides) { const { unipool } = EthersLiquityConnection_1._getContracts(this.connection); return unipool.totalSupply({ ...overrides }).then(_utils_1.decimalify); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getLiquidityMiningLQTYReward} */ getLiquidityMiningLQTYReward(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { unipool } = EthersLiquityConnection_1._getContracts(this.connection); return unipool.earned(address, { ...overrides }).then(_utils_1.decimalify); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getCollateralSurplusBalance} */ getCollateralSurplusBalance(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { collSurplusPool } = EthersLiquityConnection_1._getContracts(this.connection); return collSurplusPool.getCollateral(address, { ...overrides }).then(_utils_1.decimalify); } async getTroves(params, overrides) { var _a, _b; const { multiTroveGetter } = EthersLiquityConnection_1._getContracts(this.connection); expectPositiveInt(params, "first"); expectPositiveInt(params, "startingAt"); if (!validSortingOptions.includes(params.sortedBy)) { throw new Error(`sortedBy must be one of: ${validSortingOptions.map(x => `"${x}"`).join(", ")}`); } const [totalRedistributed, backendTroves] = await Promise.all([ params.beforeRedistribution ? undefined : this.getTotalRedistributed({ ...overrides }), multiTroveGetter.getMultipleSortedTroves(params.sortedBy === "descendingCollateralRatio" ? (_a = params.startingAt) !== null && _a !== void 0 ? _a : 0 : -(((_b = params.startingAt) !== null && _b !== void 0 ? _b : 0) + 1), params.first, { ...overrides }) ]); const troves = mapBackendTroves(backendTroves); if (totalRedistributed) { return troves.map(trove => trove.applyRedistribution(totalRedistributed)); } else { return troves; } } /** @internal */ _getBlockTimestamp(blockTag) { return EthersLiquityConnection_1._getBlockTimestamp(this.connection, blockTag); } /** @internal */ async _getFeesFactory(overrides) { const { troveManager } = EthersLiquityConnection_1._getContracts(this.connection); const [lastFeeOperationTime, baseRateWithoutDecay] = await Promise.all([ troveManager.lastFeeOperationTime({ ...overrides }), troveManager.baseRate({ ...overrides }).then(_utils_1.decimalify) ]); return (blockTimestamp, recoveryMode) => new lib_base_1.Fees(baseRateWithoutDecay, MINUTE_DECAY_FACTOR, BETA, convertToDate(lastFeeOperationTime.toNumber()), convertToDate(blockTimestamp), recoveryMode); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getFees} */ async getFees(overrides) { const [createFees, total, price, blockTimestamp] = await Promise.all([ this._getFeesFactory(overrides), this.getTotal(overrides), this.getPrice(overrides), this._getBlockTimestamp(overrides === null || overrides === void 0 ? void 0 : overrides.blockTag) ]); return createFees(blockTimestamp, total.collateralRatioIsBelowCritical(price)); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getLQTYStake} */ async getLQTYStake(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireAddress(this.connection)); const { lqtyStaking } = EthersLiquityConnection_1._getContracts(this.connection); const [stakedLQTY, collateralGain, lusdGain] = await Promise.all([ lqtyStaking.stakes(address, { ...overrides }), lqtyStaking.getPendingETHGain(address, { ...overrides }), lqtyStaking.getPendingLUSDGain(address, { ...overrides }) ].map(getBigNumber => getBigNumber.then(_utils_1.decimalify))); return new lib_base_1.LQTYStake(stakedLQTY, collateralGain, lusdGain); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getTotalStakedLQTY} */ async getTotalStakedLQTY(overrides) { const { lqtyStaking } = EthersLiquityConnection_1._getContracts(this.connection); return lqtyStaking.totalLQTYStaked({ ...overrides }).then(_utils_1.decimalify); } /** {@inheritDoc @liquity/lib-base#ReadableLiquity.getFrontendStatus} */ async getFrontendStatus(address, overrides) { address !== null && address !== void 0 ? address : (address = EthersLiquityConnection_1._requireFrontendAddress(this.connection)); const { stabilityPool } = EthersLiquityConnection_1._getContracts(this.connection); const { registered, kickbackRate } = await stabilityPool.frontEnds(address, { ...overrides }); return registered ? { status: "registered", kickbackRate: _utils_1.decimalify(kickbackRate) } : { status: "unregistered" }; } }
JavaScript
class SvgList { constructor(nodeList) { const list = this; this.svgElements = []; for(let i = 0; i < nodeList.length; i++) { this.svgElements.push(new Svg(nodeList[i])); } // Add delegation methods for Svg Object.keys(Svg.prototype).filter((prototypeProperty) => [ 'constructor', 'parent', 'querySelector', 'querySelectorAll', 'replace', 'append', 'classes', 'height', 'width' ].indexOf(prototypeProperty) === -1) .forEach((prototypeProperty) => { list[prototypeProperty] = () => { const args = Array.from(arguments); list.svgElements.forEach((element) => Svg.prototype[prototypeProperty].apply(element, args)); return list; }; }); } }
JavaScript
class TypedMap { constructor() { _TypedMap_dict.set(this, void 0); _TypedMap_hasEntries.set(this, false); /** * Converts this SimpleMap into a string representation. Follows the format: * `{ key1: value1, key2:value2 }` * * @returns {string} String representation of the SimpleMap */ this.toString = () => { if (!__classPrivateFieldGet(this, _TypedMap_hasEntries, "f")) return '{ }'; // eslint-disable-next-line arrow-body-style return this.entries().reduce((acc, cur, ind, arr) => { return `${acc}${cur[0]}: ${cur[1].toString()}${ind === arr.length ? ' }' : ', '}`; }, '{ '); }; this.has = (key) => (Object.prototype.hasOwnProperty.call(__classPrivateFieldGet(this, _TypedMap_dict, "f"), key)); this.get = (key) => (__classPrivateFieldGet(this, _TypedMap_dict, "f")[key]); this.keys = () => (Object.keys(__classPrivateFieldGet(this, _TypedMap_dict, "f"))); this.values = () => (Object.values(__classPrivateFieldGet(this, _TypedMap_dict, "f"))); this.entries = () => (Object.entries(__classPrivateFieldGet(this, _TypedMap_dict, "f"))); /** * Sets a value within this SimpleMap. The value must be of the same type as * any previous values. If it is the first value, this will set the precedent * for future types. * * @param {string} key Entry key * @param {any} value Entry value * @throws {TypeError} If the key is not provided or not a string * @throws {TypeError} If the value is not provided or not the same type */ this.set = (key, value) => { if (!key || typeof key !== 'string') throw new TypeError(`SimpleMap.set() requires a string key, instead "${typeof key}" was found.`); if (typeof value === 'undefined' || value === null) throw new TypeError(`SimpleMap.set() requires a valid value (not undefined or null).`); if (!this.checkType(value)) throw new TypeError(`SimpleMap.set() must be called with an object of the same type as what exists already.`); __classPrivateFieldGet(this, _TypedMap_dict, "f")[key] = value; }; /** * Deletes (removes) a key and it's value from this SimpleMap. * * @param {String} key Entry key * @returns {boolean} True if found and deleted */ this.delete = (key) => { if (this.has(key)) { delete __classPrivateFieldGet(this, _TypedMap_dict, "f")[key]; return true; } return false; }; /** * Removes all keys and values from this SimpleMap. */ this.clear = () => { this.forEachKey((key) => (delete __classPrivateFieldGet(this, _TypedMap_dict, "f")[key])); }; /** * Iterate over each entry in this SimpleMap. * * @param {function} cb Callback receiving current value, index, and array */ // eslint-disable-next-line max-len this.forEach = (cb) => (this.entries().forEach(cb)); /** * Iterate over each string key in this SimpleMap. * * @param {function} cb Callback receiving current value, index, and array */ this.forEachKey = (cb) => (this.keys().forEach(cb)); /** * Iterate over each value in this SimpleMap. * * @param {function} cb Callback receiving current value, index, and array */ this.forEachvalue = (cb) => (this.values().forEach(cb)); /** * Checks that the provided object is the same type as what exists in this * SimpleMap. If nothing exists, then true is returned anyways. * * @see {@link objectsAreSameType} * @param {any} value Object to test * @returns {boolean} True if they are the same type */ this.checkType = (value) => { if (__classPrivateFieldGet(this, _TypedMap_hasEntries, "f")) { const [test] = this.values(); return (0, exports.objectsAreSameType)(value, test); } return true; }; __classPrivateFieldSet(this, _TypedMap_dict, {}, "f"); __classPrivateFieldSet(this, _TypedMap_hasEntries, false, "f"); } [(_TypedMap_dict = new WeakMap(), _TypedMap_hasEntries = new WeakMap(), Symbol.iterator)]() { const entries = Object.entries(__classPrivateFieldGet(this, _TypedMap_dict, "f")); let index = -1; return { next: () => { index++; return { value: entries[index], done: index >= entries.length, }; }, }; } }
JavaScript
class V1CronJobSpec { static getAttributeTypeMap() { return V1CronJobSpec.attributeTypeMap; } }
JavaScript
class Pattern { /** * Creates a new **pattern definition**. * * @param {string} id - The pattern identifier. Must equals the filename. * @param {string} summary - Shortly describes the pattern. * @param {Array<PatternRelation>} relations - A list of `PatternRelations`, * types relations between this pattern [source] and other(s) [target(s)]. */ constructor( id, summary, relations = [] ) { this._id = id this._summary = summary this._relations = relations } getId() { return this._id } getSummary() { return this._summary } getRelations() { return this._relations } }
JavaScript
class GitHubProjectsWidget extends LitElement { render() { return html` <style> a { text-decoration: none; color: rgb(30,144,255) } a:hover { color: rgb(65,105,225); } paper-tabs { --paper-tabs-selection-bar-color: rgb(30,144,255); } paper-button { height: 2.5em; } .paper-button-blue { color: rgb(240,248,255); background: rgb(30,144,255); height: 2.5em; } .paper-button-blue:hover { color: rgb(240,248,255); background: rgb(65,105,225); } </style> <div id="main" style="margin-left: 0.5em; margin-right: 0.5em"> <h3 style="margin-top: 0.5em; margin-bottom: 0.5em">GitHub Projects - <a href=${this.gitHubProjectHtmlUrl} target="_blank">${this.projectName}</a> </h3> ${this.accessToken ? html`` : html` <div>Go to Settings and connect with your GitHub account to view the GitHub project.</div> `} <div style="overflow-y: auto"> ${this.columns ? html` <paper-tabs id="column-tabs" selected="0"> ${this.columns.map(column => html` <paper-tab @click=${(e) => this.displayCards(column)}>${column.name}</paper-tab> `)} </paper-tabs> ` : html``} </div> <div id="cards-content"> </div> ${this.accessToken ? html` <div> <custom-style> <style is="custom-style"> .custom-parent { font-size: 12px; } paper-input.custom:hover { border: 1px solid rgb(30,144,255); } paper-input.custom { margin-bottom: 14px; --primary-text-color: #01579B; --paper-input-container-color: black; --paper-input-container-focus-color: black; --paper-input-container-invalid-color: black; border: 1px solid #BDBDBD; border-radius: 5px; /* Reset some defaults */ --paper-input-container: { padding: 0;}; --paper-input-container-underline: { display: none; height: 0;}; --paper-input-container-underline-focus: { display: none; }; /* New custom styles */ --paper-input-container-input: { box-sizing: border-box; font-size: inherit; padding: 4px; }; --paper-input-container-label: { top: -8px; left: 4px; background: white; padding: 2px; font-weight: bold; }; --paper-input-container-label-floating: { width: auto; }; } </style> </custom-style> <paper-input id="input-note" class="custom" label="Note" style="margin-top: 1em; margin-bottom: 0.5em" always-float-label></paper-input> <div style="display: flex"> <paper-button class="paper-button-blue" style="margin-left: auto" @click=${this._onAddCardClicked}>Add Card</paper-button> </div> </div> ` : html``} </div> `; } static get properties() { return { gitHubProjectId: { type: Number }, gitHubProjectHtmlUrl: { type: String }, projectName: { type: String }, accessToken: { type: String }, columns: { type: Array }, columnCards: { type: Object }, selectedColumn: { type: Object } } } constructor() { super(); // load id of GitHub project required for API requests const componentType = Common.getComponentTypeByVersionedModelId(Common.getVersionedModelId()); const modelingInfo = Common.getModelingInfo()[componentType]; this.gitHubProjectId = modelingInfo.gitHubProjectId; // get information used to display project name and to link to GitHub this.gitHubProjectHtmlUrl = modelingInfo.gitHubProjectHtmlUrl; this.projectName = modelingInfo.projectName; // get users access token GitHubHelper.getGitHubAccessToken(Auth.getAccessToken()).then(accessToken => { this.accessToken = accessToken; // load cards (and reload them every 10 seconds) this.loadCards(); this.interval = setInterval(this.loadCards.bind(this), 10000); }, error => { }); this.columnCards = {}; } clearIntervals() { clearInterval(this.interval); } /** * Loads the cards from GitHub API. * Loads cards of every column and updates the currently displayed column cards. */ loadCards() { this.getProjectColumns().then(c => { this.columns = c; let columnsLoaded = 0; for(const column of this.columns) { this.getColumnCards(column.id).then(cards => { this.columnCards[column.id] = cards; columnsLoaded++; if(columnsLoaded == this.columns.length) { if(this.selectedColumn) this.displayCards(this.selectedColumn); else this.displayCards(this.columns[0]); } }); } }); } /** * Displays the cards of the given column. * @param column */ displayCards(column) { this.selectedColumn = column; const cardsContent = this.shadowRoot.getElementById("cards-content"); while(cardsContent.firstChild) cardsContent.removeChild(cardsContent.firstChild); const cards = this.columnCards[column.id]; for(const card of cards) { const paperCard = document.createElement("paper-card"); paperCard.style.setProperty("width", "100%"); paperCard.style.setProperty("margin-top", "0.5em"); // check card type (issues are currently not supported) if(card.note != null) { // standard card const div = document.createElement("div"); div.style.setProperty("margin-left", "1em"); const pNote = document.createElement("p"); pNote.style.setProperty("margin-bottom", "0.5em"); pNote.innerText = card.note; div.appendChild(pNote); const pUser = document.createElement("p"); pUser.style.setProperty("margin-top", "0"); pUser.style.setProperty("font-size", "smaller"); pUser.style.setProperty("color", "#838383"); pUser.innerText = "Added by " + card.creator.login; div.appendChild(pUser); paperCard.appendChild(div); } cardsContent.appendChild(paperCard); } } /** * Loads the columns of a GitHub project. * Uses this.gitHubProjectId as the id of the GitHub project. * @returns {Promise<unknown>} */ getProjectColumns() { return new Promise((columnsLoaded, loadingFailed) => { fetch("https://api.github.com/projects/" + this.gitHubProjectId + "/columns", { method: "GET", headers: { "Accept": "application/vnd.github.inertia-preview+json", "Authorization": "token " + this.accessToken } }).then(response => { if(response.ok) { response.json().then(data => { columnsLoaded(data); }); } else { loadingFailed(); } }); }); } /** * Loads the cards of a column of a GitHub project. * @param columnId Id of the column where the cards should be returned for. * @returns {Promise<unknown>} */ getColumnCards(columnId) { return new Promise((cardsLoaded, loadingFailed) => { fetch("https://api.github.com/projects/columns/" + columnId + "/cards", { method: "GET", headers: { "Accept": "application/vnd.github.inertia-preview+json", "Authorization": "token " + this.accessToken } }).then(response => { if(response.ok) { response.json().then(data => { cardsLoaded(data); }); } else { laodingFailed(); } }); }); } _onAddCardClicked() { const note = this.shadowRoot.getElementById("input-note").value; if(!note) return; this.createNewCard(this.selectedColumn.id, note).then(_ => { this.shadowRoot.getElementById("input-note").value = "" this.loadCards(); }); } /** * Sends an API request to create a new card in the given column. * @param columnId Id of the column where the card should be added to. * @param note Note used for the card. * @returns {Promise<unknown>} */ createNewCard(columnId, note) { return new Promise((cardCreated, creationFailed) => { fetch("https://api.github.com/projects/columns/" + columnId + "/cards", { method: "POST", headers: { "Accept": "application/vnd.github.inertia-preview+json", "Authorization": "token " + this.accessToken }, body: JSON.stringify({ note }) }).then(response => { if(response.ok) { response.json().then(data => { cardCreated(); }); } else { creationFailed(); } }); }); } }