language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Label extends Phaser.Text { /** * @param {Object} game - Current game instance. * @param {string} label - The text to place on top of the label. * @param {Object} style - The style properties to be set on the Text. * @param {number} x - The x coordinate on screen where the textSprite will be placed. * @param {number} y - The y coordinate on screen where the textSprite will be placed. */ constructor(game, label, style, x, y) { super(game, x, y, label, style); game.add.existing(this); this.anchor.set(0.5, 0.5); } /** * @param {string} text - The new text to place on top of the sprite. */ setText(text) { super.setText(text); } }
JavaScript
class textSprite extends Phaser.Sprite { /** * @param {Object} game - Current game instance. * @param {string} image - The image to create a sprite with. * @param {string} label - The text to place on top of the sprite. * @param {Object} style - The style properties to be set on the Text. * @param {number} x - The x coordinate on screen where the textSprite will be placed. * @param {number} y - The y coordinate on screen where the textSprite will be placed. */ constructor(game, image, label, style, x, y) { super(game, x, y, image); game.add.existing(this); this.text = this.game.add.text(this.width / 2, this.height / 2, label, style); this.text.anchor.set(0.5, 0.5); this.addChild(this.text); } /** * @param {string} text - The new text to place on top of the sprite. */ setText(text) { this.text.setText(text); } }
JavaScript
class HypixelSkyblockProfile { constructor(data) { /** * Array of raw member data * @type {object[]} * @private */ this._rawMemberData = data.members; /** * Profiles's Hypixel ID * @type {string} */ this.id = data.profile_id; /** * Name of the profile * @type {string} */ this.name = data.cute_name; /** * Represents the Co-Op Bank of the profile * @type {Promise<HypixelSkyblockBank|null>} */ this.coopBank = data.banking ? new HypixelSkyblockBank(data.banking) : null; } /** * Fetch a member from a profile * @param {string} uuid The Player UUID to search for * @returns {Promise<HypixelSkyblockMember|null>} * @example * * profile.getMember('8069233e5b25410c9475daa6a044c365'); // Returns GamerCoder215's profile data */ getMember(uuid) { if (!uuid || typeof uuid !== 'string') throw err; return this._rawMemberData[`${uuid}`] ? new HypixelSkyblockMember(this._rawMemberData[`${uuid}`]) : null; } }
JavaScript
class ProvenanceTypeAttributeKind extends TypeAttributes_1.TypeAttributeKind { constructor() { super("provenance"); } appliesToTypeKind(_kind) { return true; } combine(arr) { return collection_utils_1.setUnionManyInto(new Set(), arr); } makeInferred(p) { return p; } stringify(p) { return Array.from(p) .sort() .map(i => i.toString()) .join(","); } }
JavaScript
class NServer extends require('../NObject') { /** * Create an App Server * * @param {Object} [options] - server config object * @param {Number} [options.port] - server listen port * @param {String} [options.hostname] - server hostname * @param {Object} [options.session] - session config * @param {Object} [options.view] - view resolver config * @param {Object} [options.roots] - root path config * @param {Object} [options.routes] - router config * @param {Object} [options.filters] - filter config * @param {Array} [options.keys] - koa session secret keys */ constructor(options) { super(); if (!(this instanceof NServer)) { return new NServer(); } // save server options this._options = [options.port || '80']; if (options.hostname) { this._options.push(options.hostname); } this._app = koa(); this._app.port = this._options; // proxy header fields will be trusted this._app.proxy = true; // error handler this._app.on('error', this._handleException.bind(this)); // overwrite session store let sess = Object.assign( { cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days } }, options.session, { store: new (require('../dao/cache/Redis'))() } ); this._app.keys = options.keys || ['NEI_SECRECT']; this._app.config = options; // add common middleware options.view.root = path.join( options.roots.appRoot, options.roots.viewRoot ); // bodyParser let bodyOpt = { strict: false, jsonLimit: '20mb' }; if (options.roots.uploadRoot) { // 存在文件上传的情况 let uploadDir = path.join(options.roots.appRoot, options.roots.uploadRoot); try { fs.accessSync(uploadDir); } catch (ex) { fs.mkdirSync(uploadDir); } bodyOpt = Object.assign({ multipart: true, uploadDir }, bodyOpt); } this.use([ require('koa-static')( path.join( options.roots.appRoot, options.roots.webRoot ), process.appConfig.static || {} ), require('koa-better-body')(bodyOpt), require('koa-generic-session')(sess), require('../middleware/error'), require('../middleware/filter')(options), require('../middleware/router')(options), require('../middleware/view')(options.view) ]); } /** * handle error * @private * @param {Error} err - error information * @return {Void} */ _handleException(err) { log.error(err); } /** * support use middleware list * @param {Array|GeneratorFunction} mw - middlewares * @return {Void} */ use(mw) { if (Array.isArray(mw)) { mw.forEach(this.use, this); return; } this._app.use(mw); } /** * startup server * @return {Void} */ start() { if (!this._server) { log.info( '[%s.constructor] start server on port %s', this.constructor.name, this._options[0] ); this._server = this._app.listen(...(this._options)); } } /** * stop server * @return {Void} */ stop() { if (this._server) { this._server.close(); delete this._server; } } }
JavaScript
class DSCryptography { /** * Generate a random string or salt. * Default salt size is used if not provided. * @param {number} [size] in bytes * @returns {Promise<string>} */ async random (size) {} /** * Generate a secret key. * @returns {Promise<string>} */ async secret () {} /** * Derive a secret key from a password and salt. * @param {string} pass * @param {string} salt * @returns {Promise<string>} */ async secretFromPass (pass, salt) {} /** * Encrypt plain text with secret. * @param {string} key * @param {string} text * @returns {Promise<string>} */ async secretEncrypt (key, text) {} /** * Decrypt encrypted text with secret. * @param {string} key * @param {string} text * @returns {Promise<string>} */ async secretDecrypt (key, text) {} /** * Generate a public-private key pair to establish a shared secret. * @returns {Promise<{public: string, private: string}>} */ async keysForAgreement () {} /** * Derive a secret key from a public-private key pair. * @param {string} privateA * @param {string} publicB * @returns {Promise<string>} */ async secretFromKeys (privateA, publicB) {} /** * Generate a public-private key pair for encryption and decryption. * @returns {Promise<{public: string, private: string}>} */ async keysForEncryption () {} /** * Encrypt plain text with public key. * @param {string} key * @param {string} text * @returns {Promise<string>} */ async publicEncrypt (key, text) {} /** * Decrypt encrypted text with private key. * @param {string} key * @param {string} text * @returns {Promise<string>} */ async privateDecrypt (key, text) {} }
JavaScript
class NextJsSsrImportPlugin { apply (compiler) { compiler.plugin('compilation', (compilation) => { compilation.mainTemplate.plugin('require-ensure', (code, chunk) => { // Update to load chunks from our custom chunks directory const outputPath = resolve('/') const pagePath = join('/', dirname(chunk.name)) const relativePathToBaseDir = relative(pagePath, outputPath) // Make sure even in windows, the path looks like in unix // Node.js require system will convert it accordingly const relativePathToBaseDirNormalized = relativePathToBaseDir.replace(/\\/g, '/') let updatedCode = code.replace('require("./"', `require("${relativePathToBaseDirNormalized}/"`) // Replace a promise equivalent which runs in the same loop // If we didn't do this webpack's module loading process block us from // doing SSR for chunks updatedCode = updatedCode.replace( 'return Promise.resolve();', `return require('next/dynamic').SameLoopPromise.resolve();` ) return updatedCode }) }) } }
JavaScript
class ImptProjectTestHelper { static get DEVICE_FILE() { return 'device.nut'; } static get AGENT_FILE() { return 'agent.nut'; } // check command`s result by exec project info command static checkProjectInfo(expectInfo = {}) { return ImptTestHelper.runCommand(`impt project info -z json`, (commandOut) => { const json = JSON.parse(commandOut.output); expect(json.Project).toBeDefined; expect(json.Project['Device file']).toBe(expectInfo.dfile ? expectInfo.dfile : ImptProjectTestHelper.DEVICE_FILE); expect(json.Project['Agent file']).toBe(expectInfo.afile ? expectInfo.afile : ImptProjectTestHelper.AGENT_FILE); expect(json.Project['Device Group'].id).toBe(expectInfo.dg_id ? expectInfo.dg_id : json.Project['Device Group'].id); expect(json.Project['Device Group'].type).toBe('development'); expect(json.Project['Device Group'].name).toBe(expectInfo.dg_name ? expectInfo.dg_name : DG_NAME); expect(json.Project['Device Group'].description).toBe(expectInfo.dg_descr ? expectInfo.dg_descr : DG_DESCR); expect(json.Project['Device Group'].Product.id).toBe(expectInfo.product_id ? expectInfo.product_id : json.Project['Device Group'].Product.id); expect(json.Project['Device Group'].Product.name).toBe(expectInfo.product_name ? expectInfo.product_name : PRODUCT_NAME); ImptTestHelper.checkSuccessStatus(commandOut); }); } // Checks if device and agent files exists static checkDeviceAgentFilesExists(expFiles = {}) { ImptTestHelper.checkFileExist(expFiles.dfile ? expFiles.dfile : ImptProjectTestHelper.DEVICE_FILE); ImptTestHelper.checkFileExist(expFiles.afile ? expFiles.afile : ImptProjectTestHelper.AGENT_FILE); } // Checks if device and agent files not exists static checkDeviceAgentFilesNotExists(expFiles = {}) { ImptTestHelper.checkFileNotExist(expFiles.dfile ? expFiles.dfile : ImptProjectTestHelper.DEVICE_FILE); ImptTestHelper.checkFileNotExist(expFiles.afile ? expFiles.afile : ImptProjectTestHelper.AGENT_FILE); } // Checks if project`s entities exists static checkProjectsEntitiesExists(expEntities = {}) { return ImptTestHelper.runCommand(`impt product info -p ${expEntities.product_name ? expEntities.product_name : PRODUCT_NAME}`, ImptTestHelper.checkSuccessStatus). then(() => ImptTestHelper.runCommand(`impt dg info -g ${expEntities.dg_name ? expEntities.dg_name : DG_NAME}`, ImptTestHelper.checkSuccessStatus)); } // Checks if project`s entities not exists static checkProjectsEntitiesNotExists(expEntities = {}) { return ImptTestHelper.runCommand(`impt product info -p ${expEntities.product_name ? expEntities.product_name : PRODUCT_NAME}`, ImptTestHelper.checkFailStatus). then(() => ImptTestHelper.runCommand(`impt dg info -g ${expEntities.dg_name ? expEntities.dg_name : DG_NAME}`, ImptTestHelper.checkFailStatus)); } }
JavaScript
class Navbar extends Component{ constructor(props) { super(props); this.state = { city:"", type:"" }; this.handleClick=this.handleClick.bind(this); this.handleChange=this.handleChange.bind(this); } handleChange(e) { this.setState({ [e.target.name]: e.target.value }); } handleClick(e){ e.preventDefault() localStorage.setItem("city",this.state.city) localStorage.setItem("type",this.state.type) window.open('/userHome','_self') } logout = e =>{ localStorage.clear() window.open("/",'_self') } render(){ let cartypes = []; cartypes.push(<option value="SMALL"> SMALL</option>); cartypes.push(<option value="SUV"> SUV</option>); cartypes.push(<option value="SEDAN"> SEDAN</option>); cartypes.push(<option value="TRUCK"> TRUCK</option>); cartypes.push(<option value=""> </option>); return ( <div> <AppBar position="static" style={{background:'#28a745'}}> <Toolbar> <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="open drawer" > </IconButton> <Typography className={classes.title} variant="h6" noWrap> Rent a Car </Typography> <Button href="/profile" variant="h6" noWrap> Profile </Button> <Button href="/userHome" variant="h6" noWrap> Home </Button> <Button href="/Pickup" variant="h6" noWrap> Bookings </Button> <div className={classes.search}> <InputBase style={{background:'white', paddingLeft: '12px', marginRight: '10px', borderRadius: '10px'}} placeholder="Search…" name="city" onChange={this.handleChange} classes={{ root: classes.inputRoot, input: classes.inputInput, }} inputProps={{ 'aria-label': 'search' }} /> </div> <div> <select style={{padding:'4%',borderRadius:'6px'}} name="type" value={this.state.cartype} onChange={this.handleChange} id="month" > {cartypes} </select> </div> <Button onClick={this.handleClick}>Search</Button> <br/> <Button variant="h6" noWrap onClick={this.logout}> Logout </Button> </Toolbar> </AppBar> </div> ); } }
JavaScript
class Person { /** * @param {string} name the person's name. * @param {number} age the person's age. */ constructor(name, age) { this.name = name; this.age = age; } }
JavaScript
class EditorSelection { constructor() { this.ranges = [] } addRange(range) { this.ranges.push(range) } forEach(...args) { return this.ranges.forEach(...args) } }
JavaScript
class MySqlAdapter { constructor(options) { /** * @private * @type {Connection} */ this.rawConnection = null; /** * Gets or sets database connection string * @type {*} */ this.options = options; /** * Gets or sets a boolean that indicates whether connection pooling is enabled or not. * @type {boolean} */ this.connectionPooling = false; } /** * Opens database connection */ open(callback) { callback = callback || function() {}; const self = this; if (this.rawConnection) { return callback(); } //get current timezone const offset = (new Date()).getTimezoneOffset(), timezone = (offset<=0 ? '+' : '-') + zeroPad(-Math.floor(offset/60),2) + ':' + zeroPad(offset%60,2); if (self.connectionPooling) { if (typeof MySqlAdapter.pool === 'undefined') { MySqlAdapter.pool = mysql.createPool(this.options); } MySqlAdapter.pool.getConnection(function(err, connection) { if (err) { return callback(err); } else { self.rawConnection = connection; self.execute("SET time_zone=?", timezone, function(err) { return callback(err); }); } }); } else { self.rawConnection = mysql.createConnection(this.options); self.rawConnection.connect(function(err) { if (err) { return callback(err); } else { //set connection timezone self.execute("SET time_zone=?", timezone, function(err) { return callback(err); }); } }); } } /** * @param {Function} callback */ close(callback) { const self = this; callback = callback || function() {}; if (!self.rawConnection) return; if (self.connectionPooling) { self.rawConnection.release(); self.rawConnection=null; } else { self.rawConnection.end(function(err) { if (err) { TraceUtils.log(err); //do nothing self.rawConnection=null; } callback(); }); } } /** * Begins a data transaction and executes the given function * @param {Function} fn * @param {Function} callback */ executeInTransaction(fn, callback) { const self = this; //ensure callback callback = callback || function () {}; //ensure that database connection is open self.open(function(err) { if (err) { return callback.bind(self)(err); } //execution is already in transaction if (self.__transaction) { //so invoke method fn.bind(self)(function(err) { //call callback callback.bind(self)(err); }); } else { self.execute('START TRANSACTION',null, function(err) { if (err) { callback.bind(self)(err); } else { //set transaction flag to true self.__transaction = true; try { //invoke method fn.bind(self)(function(error) { if (error) { //rollback transaction self.execute('ROLLBACK', null, function() { //st flag to false self.__transaction = false; //call callback callback.bind(self)(error); }); } else { //commit transaction self.execute('COMMIT', null, function(err) { //set flag to false self.__transaction = false; //call callback callback.bind(self)(err); }); } }); } catch(err) { //rollback transaction self.execute('ROLLBACK', null, function(err) { //set flag to false self.__transaction = false; //call callback callback.bind(self)(err); }); } } }); } }); } /** * Executes an operation against database and returns the results. * @param {DataModelBatch} batch * @param {Function} callback */ executeBatch(batch, callback) { callback = callback || function() {}; callback(new Error('DataAdapter.executeBatch() is obsolete. Use DataAdapter.executeInTransaction() instead.')); } /** * Produces a new identity value for the given entity and attribute. * @param {string} entity The target entity name * @param {string} attribute The target attribute * @param {Function=} callback */ selectIdentity(entity, attribute, callback) { const self = this; const migration = { appliesTo:'increment_id', model:'increments', description:'Increments migration (version 1.0)', version:'1.0', add:[ { name:'id', type:'Counter', primary:true }, { name:'entity', type:'Text', size:120 }, { name:'attribute', type:'Text', size:120 }, { name:'value', type:'Integer' } ] }; //ensure increments entity self.migrate(migration, function(err) { //throw error if any if (err) { callback.bind(self)(err); return; } self.execute('SELECT * FROM increment_id WHERE entity=? AND attribute=?', [entity, attribute], function(err, result) { if (err) { callback.bind(self)(err); return; } if (result.length===0) { //get max value by querying the given entity const q = new QueryExpression().from(entity).select([new QueryField().max(attribute)]); self.execute(q,null, function(err, result) { if (err) { callback.bind(self)(err); return; } let value = 1; if (result.length>0) { value = parseInt(result[0][attribute]) + 1; } self.execute('INSERT INTO increment_id(entity, attribute, value) VALUES (?,?,?)',[entity, attribute, value], function(err) { //throw error if any if (err) { callback.bind(self)(err); return; } //return new increment value callback.bind(self)(err, value); }); }); } else { //get new increment value const value = parseInt(result[0].value) + 1; self.execute('UPDATE increment_id SET value=? WHERE id=?',[value, result[0].id], function(err) { //throw error if any if (err) { callback.bind(self)(err); return; } //return new increment value callback.bind(self)(err, value); }); } }); }); } /** * @param query {*} * @param values {*} * @param {function} callback */ execute(query, values, callback) { const self = this; let sql = null; try { if (typeof query === 'string') { sql = query; } else { //format query expression or any object that may be act as query expression const formatter = new MySqlFormatter(); formatter.settings.nameFormat = MySqlAdapter.NAME_FORMAT; sql = formatter.format(query); } //validate sql statement if (typeof sql !== 'string') { callback.bind(self)(new Error('The executing command is of the wrong type or empty.')); return; } //ensure connection self.open(function(err) { if (err) { callback.bind(self)(err); } else { let startTime; if (process.env.NODE_ENV==='development') { startTime = new Date().getTime(); } //execute raw command self.rawConnection.query(sql, values, function(err, result) { if (process.env.NODE_ENV==='development') { TraceUtils.log(util.format('SQL (Execution Time:%sms):%s, Parameters:%s', (new Date()).getTime()-startTime, sql, JSON.stringify(values))); } callback.bind(self)(err, result); }); } }); } catch (err) { callback.bind(self)(err); } } /** * Formats an object based on the format string provided. Valid formats are: * %t : Formats a field and returns field type definition * %f : Formats a field and returns field name * @param {string} format * @param {*} obj */ static format(format, obj) { let result = format; if (/%t/.test(format)) result = result.replace(/%t/g,MySqlAdapter.formatType(obj)); if (/%f/.test(format)) result = result.replace(/%f/g,obj.name); return result; } static formatType(field) { const size = parseInt(field.size); const scale = parseInt(field.scale); let s = 'varchar(512) NULL'; const type=field.type; switch (type) { case 'Boolean': s = 'tinyint(1)'; break; case 'Byte': s = 'tinyint(3) unsigned'; break; case 'Number': case 'Float': s = 'float'; break; case 'Counter': return 'int(11) auto_increment not null'; case 'Currency': s = 'decimal(19,4)'; break; case 'Decimal': s = util.format('decimal(%s,%s)', (size>0 ? size : 19),(scale>0 ? scale : 8)); break; case 'Date': s = 'date'; break; case 'DateTime': case 'Time': s = 'timestamp'; break; case 'Integer': s = 'int(11)'; break; case 'Duration': s = size>0 ? util.format('varchar(%s,0)', size) : 'varchar(36)'; break; case 'URL': case 'Text': s = size>0 ? `varchar(${size})` : 'varchar(512)'; break; case 'Note': s = size>0 ? `varchar(${size})` : 'text'; break; case 'Image': case 'Binary': s = size > 0 ? `blob(${size})` : 'blob'; break; case 'Guid': s = 'varchar(36)'; break; case 'Short': s = 'smallint(6)'; break; default: s = 'int(11)'; break; } if (field.primary === true) { s += ' not null'; } else { s += (typeof field.nullable === 'undefined') ? ' null': ((field.nullable===true || field.nullable === 1) ? ' null': ' not null'); } return s; } /** * @param {string} name * @param {QueryExpression} query * @param {Function} callback */ createView(name, query, callback) { this.view(name).create(query, callback); } /** * * @param {DataModelMigration|*} obj - An Object that represents the data model scheme we want to migrate * @param {Function} callback */ migrate(obj, callback) { if (obj===null) return; const self = this; const migration = obj; if (migration.appliesTo===null) throw new Error("Model name is undefined"); self.open(function(err) { if (err) { callback.bind(self)(err); } else { async.waterfall([ //1. Check migrations table existence function(cb) { self.table('migrations').exists(function(err, exists) { if (err) { return cb(err); } cb(null, exists); }); }, //2. Create migrations table if not exists function(arg, cb) { if (arg>0) { return cb(null, 0); } self.table('migrations').create([ { name:'id', type:'Counter', primary:true, nullable:false }, { name:'appliesTo', type:'Text', size:'80', nullable:false }, { name:'model', type:'Text', size:'120', nullable:true }, { name:'description', type:'Text', size:'512', nullable:true }, { name:'version', type:'Text', size:'40', nullable:false } ], function(err) { if (err) { return cb(err); } cb(null,0); }); }, //3. Check if migration has already been applied function(arg, cb) { self.execute('SELECT COUNT(*) AS `count` FROM `migrations` WHERE `appliesTo`=? and `version`=?', [migration.appliesTo, migration.version], function(err, result) { if (err) { return cb(err); } cb(null, result[0].count); }); }, //4a. Check table existence function(arg, cb) { //migration has already been applied (set migration.updated=true) if (arg>0) { obj.updated=true; return cb(null, -1); } self.table(migration.appliesTo).exists(function(err, exists) { if (err) { return cb(err); } cb(null, exists); }); }, //4b. Migrate target table (create or alter) function(arg, cb) { //migration has already been applied if (arg<0) { return cb(null, arg); } if (arg===0) { //create table return self.table(migration.appliesTo).create(migration.add, function(err) { if (err) { return cb(err); } cb(null, 1); }); } //columns to be removed (unsupported) if (_.isArray(migration.remove)) { if (migration.remove.length>0) { return cb(new Error('Data migration remove operation is not supported by this adapter.')); } } //columns to be changed (unsupported) if (_.isArray(migration.change)) { if (migration.change.length>0) { return cb(new Error('Data migration change operation is not supported by this adapter. Use add collection instead.')); } } let column, newType, oldType; if (_.isArray(migration.add)) { //init change collection migration.change = []; //get table columns self.table(migration.appliesTo).columns(function(err, columns) { if (err) { return cb(err); } for (let i = 0; i < migration.add.length; i++) { const x = migration.add[i]; column = _.find(columns, function(y) { return (y.name===x.name); }); if (column) { //if column is primary key remove it from collection if (column.primary) { migration.add.splice(i, 1); i-=1; } else { //get new type newType = MySqlAdapter.format('%t', x); //get old type oldType = column.type1.replace(/\s+$/,'') + ((column.nullable===true || column.nullable === 1) ? ' null' : ' not null'); //remove column from collection migration.add.splice(i, 1); i-=1; if (newType !== oldType) { //add column to alter collection migration.change.push(x); } } } } //alter table const targetTable = self.table(migration.appliesTo); //add new columns (if any) targetTable.add(migration.add, function(err) { if (err) { return cb(err); } //modify columns (if any) targetTable.change(migration.change, function(err) { if (err) { return cb(err); } cb(null, 1); }); }); }); } else { cb(new Error('Invalid migration data.')); } }, //Apply data model indexes function (arg, cb) { if (arg<=0) { return cb(null, arg); } if (migration.indexes) { const tableIndexes = self.indexes(migration.appliesTo); //enumerate migration constraints async.eachSeries(migration.indexes, function(index, indexCallback) { tableIndexes.create(index.name, index.columns, indexCallback); }, function(err) { //throw error if (err) { return cb(err); } //or return success flag return cb(null, 1); }); } else { //do nothing and exit return cb(null, 1); } }, function(arg, cb) { if (arg>0) { //log migration to database self.execute('INSERT INTO `migrations` (`appliesTo`,`model`,`version`,`description`) VALUES (?,?,?,?)', [migration.appliesTo, migration.model, migration.version, migration.description ], function(err) { if (err) { return cb(err); } return cb(null, 1); }); } else cb(null, arg); } ], function(err, result) { callback(err, result); }); } }); } table(name) { const self = this; return { /** * @param {function(Error,Boolean=)} callback */ exists:function(callback) { callback = callback || function() {}; self.execute('SELECT COUNT(*) AS `count` FROM information_schema.TABLES WHERE TABLE_NAME=? AND TABLE_SCHEMA=DATABASE()', [ name ], function(err, result) { if (err) { return callback(err); } callback(null, result[0].count); }); }, /** * @param {function(Error,string=)} callback */ version:function(callback) { callback = callback || function() {}; self.execute('SELECT MAX(`version`) AS `version` FROM `migrations` WHERE `appliesTo`=?', [name], function(err, result) { if (err) { return callback(err); } if (result.length===0) callback(null, '0.0'); else callback(null, result[0].version || '0.0'); }); }, /** * @param {function(Error=,Array=)} callback */ columns:function(callback) { callback = callback || function() {}; self.execute('SELECT COLUMN_NAME AS `name`, DATA_TYPE as `type`, ' + 'CHARACTER_MAXIMUM_LENGTH as `size`,CASE WHEN IS_NULLABLE=\'YES\' THEN 1 ELSE 0 END AS `nullable`, ' + 'NUMERIC_PRECISION as `precision`, NUMERIC_SCALE as `scale`, ' + 'CASE WHEN COLUMN_KEY=\'PRI\' THEN 1 ELSE 0 END AS `primary`, ' + 'CONCAT(COLUMN_TYPE, (CASE WHEN EXTRA = NULL THEN \'\' ELSE CONCAT(\' \',EXTRA) END)) AS `type1` ' + 'FROM information_schema.COLUMNS WHERE TABLE_NAME=? AND TABLE_SCHEMA=DATABASE()', [ name ], function(err, result) { if (err) { return callback(err); } callback(null, result); }); }, /** * @param {Array} fields * @param {Function} callback */ create: function(fields, callback) { callback = callback || function() {}; fields = fields || []; if (!_.isArray(fields)) { return callback(new Error('Invalid argument type. Expected Array.')); } if (fields.length === 0) { return callback(new Error('Invalid argument. Fields collection cannot be empty.')); } let strFields = _.map(_.filter(fields,(x) => { return !x.oneToMany; }), (x) => { return MySqlAdapter.format('`%f` %t', x); }).join(', '); //add primary key constraint const strPKFields = _.map(_.filter(fields, (x) => { return (x.primary === true || x.primary === 1); }), (x) => { return MySqlAdapter.format('`%f`', x); }).join(', '); if (strPKFields.length>0) { strFields += ', ' + util.format('PRIMARY KEY (%s)', strPKFields); } const sql = util.format('CREATE TABLE %s (%s)', name, strFields); self.execute(sql, null, function(err) { callback(err); }); }, /** * Alters the table by adding an array of fields * @param {{name:string,type:string,primary:boolean|number,nullable:boolean|number,size:number,oneToMany:boolean}[]|*} fields * @param callback */ add:function(fields, callback) { callback = callback || function() {}; callback = callback || function() {}; fields = fields || []; if (!_.isArray(fields)) { //invalid argument exception return callback(new Error('Invalid argument type. Expected Array.')); } if (fields.length === 0) { //do nothing return callback(); } const formatter = new MySqlFormatter(); const strTable = formatter.escapeName(name); const statements = _.map(fields, function(x) { return MySqlAdapter.format('ALTER TABLE ' + strTable + ' ADD COLUMN `%f` %t', x); }); return async.eachSeries(statements, function(sql, cb) { self.execute(sql, [], function(err) { return cb(err); }); }, function(err) { return callback(err); }); }, /** * Alters the table by modifying an array of fields * @param {{name:string,type:string,primary:boolean|number,nullable:boolean|number,size:number,oneToMany:boolean}[]|*} fields * @param callback */ change:function(fields, callback) { callback = callback || function() {}; callback = callback || function() {}; fields = fields || []; if (!_.isArray(fields)) { //invalid argument exception return callback(new Error('Invalid argument type. Expected Array.')); } if (fields.length === 0) { //do nothing return callback(); } const formatter = new MySqlFormatter(); const strTable = formatter.escapeName(name); const statements = _.map(fields, function(x) { return MySqlAdapter.format('ALTER TABLE ' + strTable + ' MODIFY COLUMN `%f` %t', x); }); return async.eachSeries(statements, function(sql, cb) { self.execute(sql, [], function(err) { return cb(err); }); }, function(err) { return callback(err); }); } }; } view(name) { const self = this; let owner; let view; const matches = /(\w+)\.(\w+)/.exec(name); if (matches) { //get schema owner owner = matches[1]; //get table name view = matches[2]; } else { view = name; } return { /** * @param {function(Error,Boolean=)} callback */ exists:function(callback) { const sql = 'SELECT COUNT(*) AS `count` FROM information_schema.TABLES WHERE TABLE_NAME=? AND TABLE_TYPE=\'VIEW\' AND TABLE_SCHEMA=DATABASE()'; self.execute(sql, [name], function(err, result) { if (err) { callback(err); return; } callback(null, (result[0].count>0)); }); }, /** * @param {Function} callback */ drop:function(callback) { callback = callback || function() {}; self.open(function(err) { if (err) { return callback(err); } const sql = 'SELECT COUNT(*) AS `count` FROM information_schema.TABLES WHERE TABLE_NAME=? AND TABLE_TYPE=\'VIEW\' AND TABLE_SCHEMA=DATABASE()'; self.execute(sql, [name], function(err, result) { if (err) { return callback(err); } const exists = (result[0].count>0); if (exists) { const sql = util.format('DROP VIEW `%s`',name); self.execute(sql, undefined, function(err) { if (err) { callback(err); return; } callback(); }); } else { callback(); } }); }); }, /** * @param {QueryExpression|*} q * @param {Function} callback */ create:function(q, callback) { const thisArg = this; self.executeInTransaction(function(tr) { thisArg.drop(function(err) { if (err) { tr(err); return; } try { let sql = util.format('CREATE VIEW `%s` AS ',name); const formatter = new MySqlFormatter(); sql += formatter.format(q); self.execute(sql, [], tr); } catch(e) { tr(e); } }); }, function(err) { callback(err); }); } }; } indexes(table) { const self = this, formatter = new MySqlFormatter(); return { list: function (callback) { const this1 = this; if (this1.hasOwnProperty('indexes_')) { return callback(null, this1['indexes_']); } self.execute(util.format("SHOW INDEXES FROM `%s`", table), null , function (err, result) { if (err) { return callback(err); } const indexes = []; _.forEach(result, function(x) { const obj = _.find(indexes, function(y) { return y.name === x['Key_name']; }); if (typeof obj === 'undefined') { indexes.push({ name:x['Key_name'], columns:[ x['Column_name'] ] }); } else { obj.columns.push(x['Column_name']); } }); return callback(null, indexes); }); }, /** * @param {string} name * @param {Array|string} columns * @param {Function} callback */ create: function(name, columns, callback) { const cols = []; if (typeof columns === 'string') { cols.push(columns); } else if (_.isArray(columns)) { cols.push.apply(cols,columns); } else { return callback(new Error("Invalid parameter. Columns parameter must be a string or an array of strings.")); } const thisArg = this; thisArg.list(function(err, indexes) { if (err) { return callback(err); } const ix =_.find(indexes, function(x) { return x.name === name; }); //format create index SQL statement const sqlCreateIndex = util.format("CREATE INDEX %s ON %s(%s)", formatter.escapeName(name), formatter.escapeName(table), _.map(cols, function(x) { return formatter.escapeName(x); }).join(",")); if (typeof ix === 'undefined' || ix === null) { self.execute(sqlCreateIndex, [], callback); } else { let nCols = cols.length; //enumerate existing columns _.forEach(ix.columns, function(x) { if (cols.indexOf(x)>=0) { //column exists in index nCols -= 1; } }); if (nCols>0) { //drop index thisArg.drop(name, function(err) { if (err) { return callback(err); } //and create it self.execute(sqlCreateIndex, [], callback); }); } else { //do nothing return callback(); } } }); }, drop: function(name, callback) { if (typeof name !== 'string') { return callback(new Error("Name must be a valid string.")); } this.list(function(err, indexes) { if (err) { return callback(err); } const exists = typeof _.find(indexes, function(x) { return x.name === name; }) !== 'undefined'; if (!exists) { return callback(); } self.execute(util.format("DROP INDEX %s ON %s", formatter.escapeName(name), formatter.escapeName(table)), [], callback); }); } }; } queryFormat(query, values) { if (!values) return query; const self = this; return query.replace(/:(\w+)/g, function (txt, key) { if (values.hasOwnProperty(key)) { return self.escape(values[key]); } return txt; }.bind(this)); } }
JavaScript
class WhereisEmbed extends BaseEmbed { /** * @param {Genesis} bot - An instance of Genesis * @param {Object} resultsGroups details to derive data from * @param {string} query The query that this search corresponds to * @param {number} nameWidth Spacing for Names * @param {number} relicWidth Spacing for relics */ constructor(bot, resultsGroups, query, nameWidth, relicWidth) { super(); this.fields = []; resultsGroups.forEach((results, index) => { const mappedResults = results.map((result) => { const item = result.item.padEnd(nameWidth, '\u2003'); const place = (result.place.split('/')[1] || result.place).padEnd(relicWidth, '\u2003'); const chance = `${result.rarity.charAt(0)}@${result.chance}`; return `\`${item} | ${place} | ${chance}\``; }); const value = mappedResults.join('\n'); if (index > 0) { this.fields.push({ name: '\u200B', value }); } else { this.description = value; } }); this.title = `${query}`; this.color = 0x3498db; this.type = 'rich'; } }
JavaScript
class Client { /** * Establish a client to talk to HoloPlayService. * @constructor * @param {function} initCallback - optional; a function to trigger when * response is received * @param {function} errCallback - optional; a function to trigger when there * is a connection error * @param {function} closeCallback - optional; a function to trigger when the * socket is closed * @param {boolean} debug - optional; default is false * @param {string} appId - optional * @param {boolean} isGreedy - optional * @param {string} oncloseBehavior - optional, can be 'wipe', 'hide', 'none' */ constructor( initCallback, errCallback, closeCallback, debug = false, appId, isGreedy, oncloseBehavior) { this.reqs = []; this.reps = []; this.requestId = this.getRequestId(); this.debug = debug; this.isGreedy = isGreedy; this.errCallback = errCallback; this.closeCallback = closeCallback; this.alwaysdebug = false; this.isConnected = false; let initCmd = null; if (appId || isGreedy || oncloseBehavior) { initCmd = new InitMessage(appId, isGreedy, oncloseBehavior, this.debug); } else { if (debug) this.alwaysdebug = true; if (typeof initCallback == 'function') initCmd = new InfoMessage(); } this.openWebsocket(initCmd, initCallback); } /** * Send a message over the websocket to HoloPlayService. * @public * @param {Message} msg - message object * @param {integer} timeoutSecs - optional, default is 60 seconds */ sendMessage(msg, timeoutSecs = 60) { if (this.alwaysdebug) msg.cmd.debug = true; let cborData = msg.toCbor(); return this.sendRequestObj(cborData, timeoutSecs); } /** * Disconnects from the web socket. * @public */ disconnect() { this.ws.close(); } /** * Open a websocket and set handlers * @private */ openWebsocket(firstCmd = null, initCallback = null) { this.ws = new WebSocket('ws://localhost:11222/driver', ['rep.sp.nanomsg.org']); this.ws.parent = this; this.ws.binaryType = 'arraybuffer'; this.ws.onmessage = this.messageHandler; this.ws.onopen = (() => { this.isConnected = true; if (this.debug) { console.log('socket open'); } if (firstCmd != null) { this.sendMessage(firstCmd).then(initCallback); } }); this.ws.onerror = this.onSocketError; this.ws.onclose = this.onClose; } /** * Send a request object over websocket * @private */ sendRequestObj(data, timeoutSecs) { return new Promise((resolve, reject) => { let reqObj = { id: this.requestId++, parent: this, payload: data, success: resolve, error: reject, send: function() { if (this.debug) console.log('attemtping to send request with ID ' + this.id); this.timeout = setTimeout(reqObj.send.bind(this), timeoutSecs * 1000); let tmp = new Uint8Array(data.byteLength + 4); let view = new DataView(tmp.buffer); view.setUint32(0, this.id); tmp.set(new Uint8Array(this.payload), 4); this.parent.ws.send(tmp.buffer); } }; this.reqs.push(reqObj); reqObj.send(); }); } /** * Handles a message when received * @private */ messageHandler(event) { console.log('message'); let data = event.data; if (data.byteLength < 4) return; let view = new DataView(data); let replyId = view.getUint32(0); if (replyId < 0x80000000) { this.parent.err('bad nng header'); return; } let i = this.parent.findReqIndex(replyId); if (i == -1) { this.parent.err('got reply that doesn\'t match known request!'); return; } let rep = {id: replyId, payload: CBOR.decode(data.slice(4))}; if (rep.payload.error == 0) { this.parent.reqs[i].success(rep.payload); } else { this.parent.reqs[i].error(rep.payload); } clearTimeout(this.parent.reqs[i].timeout); this.parent.reqs.splice(i, 1); this.parent.reps.push(rep); if (this.debug) { console.log(rep.payload); } } getRequestId() { return Math.floor(this.prng() * (0x7fffffff)) + 0x80000000; } onClose(event) { this.parent.isConnected = false; if (this.parent.debug) { console.log('socket closed'); } if (typeof this.parent.closeCallback == 'function') this.parent.closeCallback(event); } onSocketError(error) { if (this.parent.debug) { console.log(error); } if (typeof this.parent.errCallback == 'function') { this.parent.errCallback(error); } } err(errorMsg) { if (this.debug) { console.log('[DRIVER ERROR]' + errorMsg); } // TODO : make this return an event obj rather than a string // if (typeof this.errCallback == 'function') // this.errCallback(errorMsg); } findReqIndex(replyId) { let i = 0; for (; i < this.reqs.length; i++) { if (this.reqs[i].id == replyId) { return i; } } return -1; } prng() { if (this.rng == undefined) { this.rng = generateRng(); } return this.rng(); } }
JavaScript
class Message { /** * Construct a barebone message. * @constructor */ constructor(cmd, bin) { this.cmd = cmd; this.bin = bin; } /** * Convert the class instance to the CBOR format * @public * @returns {CBOR} - cbor object of the message */ toCbor() { return CBOR.encode(this); } }
JavaScript
class InitMessage extends Message { /** * @constructor * @param {string} appId - a unique id for app * @param {boolean} isGreedy - will it take over screen * @param {string} oncloseBehavior - can be 'wipe', 'hide', 'none' */ constructor(appId = '', isGreedy = false, onclose = '', debug = false) { let cmd = {'init': {}}; if (appId != '') cmd['init'].appid = appId; if (onclose != '') cmd['init'].onclose = onclose; if (isGreedy) cmd['init'].greedy = true; if (debug) cmd['init'].debug = true; super(cmd, null); } }
JavaScript
class DeleteMessage extends Message { /** * @constructor * @param {string} name - name of the quilt */ constructor(name = '') { let cmd = {'delete': {'name': name}}; super(cmd, null); } }
JavaScript
class CheckMessage extends Message { /** * @constructor * @param {string} name - name of the quilt */ constructor(name = '') { let cmd = {'check': {'name': name}}; super(cmd, null); } }
JavaScript
class WipeMessage extends Message { /** * @constructor * @param {number} targetDisplay - optional, if not provided, default is 0 */ constructor(targetDisplay = null) { let cmd = {'wipe': {}}; if (targetDisplay != null) cmd['wipe'].targetDisplay = targetDisplay; super(cmd, null); } }
JavaScript
class InfoMessage extends Message { /** * @constructor */ constructor() { let cmd = {'info': {}}; super(cmd, null); } }
JavaScript
class UniformsMessage extends Message { /** * @constructor * @param {object} */ constructor() { let cmd = {'uniforms': {}}; super(cmd, bindata); } }
JavaScript
class ShaderMessage extends Message { /** * @constructor * @param {object} */ constructor() { let cmd = {'shader': {}}; super(cmd, bindata); } }
JavaScript
class ShowMessage extends Message { /** * @constructor * @param {object} */ constructor( settings = {vx: 5, vy: 9, aspect: 1.6}, bindata = '', targetDisplay = null) { let cmd = { 'show': { 'source': 'bindata', 'quilt': {'type': 'image', 'settings': settings} } }; if (targetDisplay != null) cmd['show']['targetDisplay'] = targetDisplay; super(cmd, bindata); } }
JavaScript
class CacheMessage extends Message { constructor( name, settings = {vx: 5, vy: 9, aspect: 1.6}, bindata = '', show = false) { let cmd = { 'cache': { 'show': show, 'quilt': { 'name': name, 'type': 'image', 'settings': settings, } } }; super(cmd, bindata); } }
JavaScript
class WorkgroupRelations extends BaseProvision { /** * @param {InternalOpenGateAPI} Reference to the API object. */ constructor(ogapi) { super(ogapi, "/domains", undefined, ["workgroup", "channels"]); this._ogapi = ogapi; this._action = "CREATE"; } /** * Set the workgroup attribute * @param {string} workgroup - required field * @return {WorkgroupRelations} */ withWorkgroup(workgroup) { if (workgroup.constructor.prototype != Workgroups.prototype) throw new Error('Parameter workgroup must be a workgroup'); this._workgroup = workgroup; return this; } /** * Set the channel attribute * @param {string} channel - required field for creation or update * @return {WorkgroupRelations} */ withChannel(channel) { if (channel.constructor.prototype != Channels.prototype) throw new Error('Parameter channel must be a channel'); if (!this._channels) this._channels = []; this._channels.push({ 'organization': channel._organization, 'channel': channel._name }); return this; } _composeElement() { this._checkRequiredParameters(); this._resource = 'provision/domains/' + this._workgroup._domainName + '/workgroups/' + this._workgroup._name + '/relations'; var workgroup = { "workgroupRelation": { "channels": this._channels ? this._channels : undefined } }; return workgroup; } _buildURL() { var url = 'provision/domains/' + this._workgroup._domainName + '/workgroups/' + this._workgroup._name + '/relations'; return url; } create() { var relations = this._composeElement(); var petitionUrl = this._resource; this._setUrlParameters({ action: 'CREATE' }); return this._doNorthPost(petitionUrl, relations); } delete() { this._setUrlParameters({ action: 'DELETE' }); var petitionUrl = this._buildURL(); if (this._channels) { var relations = this._composeElement(); return this._doNorthPost(petitionUrl, relations); } else { return this._doNorthPost(petitionUrl, { "workgroupRelation": { "channels": [] } }); } } /** * Update not allowed * @throws {Error} */ update() { throw new Error("Workgroup relation update not allowed"); } }
JavaScript
class BookForm extends React.Component{ constructor(props){ super(props); this.state={ show:true, } } hideForm=(event)=>{ event.preventDefault(); this.setState({ show:false, }) } render(){ return( <div> <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" centered show={this.props.show && this.state.show}> <Modal.Header > <Modal.Title id="contained-modal-title-vcenter"> Add Book to Your Collection </Modal.Title> </Modal.Header> <Modal.Body> <Form onSubmit={this.props.addBook}> <Form.Group controlId="formBasicEmail"> <Form.Label>Name: </Form.Label> <Form.Control type="text" placeholder="Enter the name of the book" required name="name"/> {/* <Form.Text className="text-muted"> We'll never share your email with anyone else. </Form.Text> */} </Form.Group> <Form.Group controlId="formBasicPassword"> <Form.Label>Description: </Form.Label> <Form.Control type="text" placeholder="Description" required name="description"/> </Form.Group> <Form.Group controlId="formBasicPassword"> <Form.Label>Cover: </Form.Label> <Form.Control type="text" placeholder="Path of Cover img" required name="cover"/> </Form.Group> <Form.Group controlId="formBasicPassword"> <Form.Label>Status: </Form.Label> <Form.Control type="text" placeholder="Status" required name="status"/> </Form.Group> <br/> <Button variant="primary" type="submit"> Add Book </Button> </Form> </Modal.Body> <Modal.Footer> <Button onClick={this.hideForm}>Close</Button> </Modal.Footer> </Modal> </div> ) } }
JavaScript
class Sebedius extends Discord.Client { /** * Sebedius Client * @param {*} config Config data (JSON file) */ constructor(config) { // ClientOptions: https://discord.js.org/#/docs/main/master/typedef/ClientOptions super({ messageCacheMaxSize: 100, messageCacheLifetime: 60 * 10, messageSweepInterval: 90, // partials: ['MESSAGE', 'REACTION'], ws: { // Intents: https://discordjs.guide/popular-topics/intents.html#the-intents-bit-field-wrapper // GUILD_PRESENCES & GUILD_MEMBERS are restricted by here are needed for !admin command. intents: [ 'GUILDS', // 'GUILD_PRESENCES', // 'GUILD_MEMBERS', 'GUILD_MESSAGES', 'GUILD_MESSAGE_REACTIONS', 'DIRECT_MESSAGES', 'DIRECT_MESSAGE_REACTIONS', ], }, }); this.state = 'init'; this.muted = false; this.config = config; this.version = require('./utils/version'); // Caching for the current session. this.blacklistedGuilds = new Set(); this.mutedUsers = new Set(); this.prefixes = new Discord.Collection(); this.games = new Discord.Collection(); this.langs = new Discord.Collection(); this.combats = new Discord.Collection(); this.initiatives = new Set(); this.cooldowns = new Discord.Collection(); /** * The bot's library of commands. * @type {Discord.Collection<string, import('./utils/Command')>} K: commandName, V: command */ this.commands = new Discord.Collection(); this.addCommands(); // Keyv Databases. console.log('[+] - Keyv Databases'); this.dbUri = process.env.NODE_ENV === 'production' ? process.env.DATABASE_URL : null; // this.dbUri = process.env.DATABASE_URL; console.log(' > Creation...'); this.kdb = {}; for (const name in DB_MAP) { console.log(` bot.kdb.${name}: "${DB_MAP[name]}"`); this.kdb[name] = new Keyv(this.dbUri, { namespace: DB_MAP[name] }); this.kdb[name].on('error', err => console.error(`Keyv Connection Error: ${name.toUpperCase()}\n`, err)); } // Managers. /** @type {CharacterManager} */ this.characters = new CharacterManager(this.kdb.characters); // Ready. console.log(' > Loaded & Ready!'); } /** * The ID of the user that the client is logged in as. * @type {Discord.Snowflake} */ get id() { return this.user.id; } /** * The bot's mention. * @type {string} `<@0123456789>` * @readonly */ get mention() { return Sebedius.getMention(this.user); } /** * The bot's invite link. * @type {string} * @readonly */ get inviteURL() { return `https://discord.com/oauth2/authorize?client_id=${this.id}&scope=bot&permissions=${this.config.perms.bitfield}`; } /** * Creates the list of commands. */ addCommands() { // Imports each command from subdirectories. // Warning: bot crashes if a command is not in a subdir. /* const dir = './commands/'; readdirSync(dir).forEach(d => { const commands = readdirSync(`${dir}/${d}/`).filter(f => f.endsWith('.js')); for (const file of commands) { const command = require(`${dir}/${d}/${file}`); this.commands.set(command.name, command); console.log(`[+] - Command loaded: ${command.name}.js`); } }); //*/ // Imports each command from a single directory. const commandFiles = readdirSync('./commands').filter(file => file.endsWith('.js')); for (const file of commandFiles) { const command = require('./commands/' + file); this.commands.set(command.name, command); console.log(`[+] - Command loaded: ${command.name}.js`); } } /** * Logs a message to the LogChannel of the bot. * @param {Discord.StringResolvable|Discord.APIMessage} [message=''] The message to log * @param {Discord.MessageOptions|Discord.MessageAdditions} [options={}] The options to provide * @see Discord.TextChannel.send() * @async */ async log(message = '', options = {}) { if (typeof message === 'string') console.log(`:>> ${message}`); else if (message instanceof Discord.MessageEmbed) console.log(`:>> ${message.title} — ${message.description}`); else console.log(':>> [LOG]\n', message); if (!message || this.state !== 'ready') return; const channel = this.logChannel || this.channels.cache.get(this.config.botLogChannelID) || await this.channels.fetch(this.config.botLogChannelID); if (channel) return await channel.send(message, options).catch(console.error); } /** * Gets all the entries of a database. * @param {string} name Database's name * @param {?string} namespace Database's namespace, if you one to specify another one. * @returns {Promise<Array<String, String>>} Promise of an Array of [Key, Value] * @async */ async kdbEntries(name, namespace = null) { let entries = []; const db = this.kdb[name]; if (db) { const store = db.opts.store; if (store instanceof Map) { entries = [...store.entries()]; } else { const nmspc = namespace ? namespace : DB_MAP[name] || name; entries = await store.query( `SELECT * FROM keyv WHERE key LIKE '${nmspc}%'`, ); entries = entries.map(kv => [kv.key, kv.value]); } } return entries; } /** * Removes all entries in the database for a guild. * @param {Discord.Snowflake} guildID * @returns {string[]} An array with the names of the databases where an entry has been removed. */ async kdbCleanGuild(guildID) { // List of databases' names that can contain entries from a guild. const kdbs = ['prefixes', 'initiatives', 'games', 'langs']; const deletedEntries = []; // Iterates over the databases for (const name of kdbs) { // Deletes the entry, if any. const del = await this.kdb[name].delete(guildID); if (del) { // If deleted, removes it also from the cache. this[name].delete(guildID); // And registers the occurence of a deletion. deletedEntries.push(name); } } return deletedEntries; } /** * Populates mutedUsers & blacklistedGuilds Sets. * @async */ async populateBans() { const bans = ['mutedUsers', 'blacklistedGuilds']; for (const b of bans) { (await this.kdbEntries(b)).forEach(e => { const regex = new RegExp(`${DB_MAP[b]}:(\\d+)`); const uid = e[0].replace(regex, '$1'); this[b].add(uid); console.log(`>! ${DB_MAP[b].toUpperCase()}: ${uid}`); }); } } /** * Gets a User. * @param {Discord.Snowflake} userId User ID * @returns {Promise<Discord.User>} * @async */ async getUser(userId) { let user = this.users.cache.get(userId); if (!user) user = await this.users.fetch(userId).catch(console.error); return user; } /** * Gets a Channel. * @param {Discord.Snowflake} chanId Channel ID * @returns {Promise<Discord.BaseChannel>} * @async */ async getChannel(chanId) { let chan = this.channels.cache.get(chanId); if (!chan) chan = await this.channels.fetch(chanId).catch(console.error); return chan; } /** * Gets a Guild. * @param {Discord.Snowflake} guildId Guild ID, or guild's Channel ID. * @returns {Promise<Discord.Guild>} * @async */ async getGuild(guildId) { let guild = this.guilds.cache.get(guildId); if (!guild) guild = await this.guilds.fetch(guildId).catch(console.error); if (!guild) { const chan = await this.getChannel(guildId); if (chan) guild = chan.guild; } return guild; } /** * Gets the prefix for the server. * @param {Discord.Message} message Discord message * @returns {string} * @async */ async getServerPrefix(message) { const prefixes = await this.getPrefixes(message); return prefixes[0]; } /** * Gets the list of prefixes in an array. * @param {Discord.Message} message Discord message * @returns {string[]} * @async */ async getPrefixes(message) { const fetchedPrefix = await Sebedius.getConf('prefixes', message, this, this.config.defaultPrefix); return whenMentionedOrPrefixed(fetchedPrefix, this); } /** * Gets the desired game (used for the dice icons skin). * @param {Discord.Message} message Discord message * @param {?string} defaultGame Fallback default game * @returns {string} * @async */ async getGame(message, defaultGame = null) { const game = await Sebedius.getConf('games', message, this, defaultGame); if (!game) return await Sebedius.getGameFromSelection(message); return game; } /** * Gets the desired game from a selection message. * @param {Discord.Message} message Discord message * @returns {string} * @async */ static async getGameFromSelection(message) { const gameChoices = SUPPORTED_GAMES.map(g => [SOURCE_MAP[g], g]); return await Sebedius.getSelection(message, gameChoices); } /** * Gets the language desired (used for the tables). * @param {Discord.Message} message Discord message * @returns {string} two-letters code for the desired language * @async */ async getLanguage(message) { return await Sebedius.getConf('langs', message, this, 'en'); } /** * Gets the a Combat instance. * @param {Discord.Message} message Discord message * @returns {string} two-letters code for the desired language * @async */ async getCombat(message) { return await Sebedius.getConf('combats', message.channel.id, this, null); } /** * Gets an item from a Collection tied to a Sebedius client. * @param {string} collectionName Name of the Collection * @param {string} dbNamespace Namespace for the database * @param {Discord.Message} message Discord message * @param {Discord.Client} client Discord client (the bot) * @param {?*} [defaultItem=null] The default item returned if nothing found. * @throws {SebediusError} If the collection doesn't exist. * @returns {*} * @static * @async */ static async getConf(collectionName, message, client, defaultItem = null) { if (!message.guild) return defaultItem; if (!client[collectionName]) throw new Errors.SebediusError(`Collection-property unknown: ${collectionName}`); const guildID = message.guild.id; let fetchedItem; // Checks if already cached. if (client[collectionName].has(guildID)) { fetchedItem = client[collectionName].get(guildID); } // Otherwise, loads from db and cache. else { fetchedItem = await client.kdb[collectionName].get(guildID) .catch(console.error); if (!fetchedItem) fetchedItem = defaultItem; if (fetchedItem) client[collectionName].set(guildID, fetchedItem); } // Returns the fetched prefixes. return fetchedItem; } /** * Increases by 1 the number of uses for this command. * Used for statistics purposes. * @param {string} commandName The command.name property * @param {Discord.Message} message Discord message * @returns {number} * @async */ async raiseCommandStats(commandName, message) { if (commandName === 'roll' || commandName === 'crit') { const defaultGame = await this.constructor.getConf('games', message, message.bot); if (defaultGame) commandName += defaultGame; } const count = await this.kdb.stats.get(commandName) || 0; return await this.kdb.stats.set(commandName, count + 1); } /** * Gets the commands' statistics. * @returns {Discord.Collection<String, Number>} Collection<CommandName, Count> * @async */ async getStats() { const out = new Discord.Collection(); for (const cmdName of this.commands.keyArray()) { const count = await this.kdb.stats.get(cmdName) || 0; out.set(cmdName, count); } return out; } /** * Gets a YZ table. * @param {string} type Type of table to return (`CRIT` or `null`) * @param {string} path Folder path to the file with the ending `/` * @param {string} fileName Filename without path, ext or lang-ext * @param {string} [lang='en'] The language to use, default is `en` English * @param {string} [ext='csv'] File extension * @returns {RollTable} * @static */ static getTable(type, path, fileName, lang = 'en', ext = 'csv') { const pathName = `${path}${fileName}`; let filePath = `${pathName}.${lang}.${ext}`; // If the language does not exist for this file, use the english default. if (!existsSync(filePath)) filePath = `${pathName}.en.${ext}`; let elements; try { const fileContent = readFileSync(filePath, 'utf8'); elements = Util.csvToJSON(fileContent); } catch(error) { console.error(`[Sebedius.getTable] - File Error: ${filePath}`); return null; } const table = new RollTable(`${fileName}.${lang}.${ext}`); for (const elem of elements) { if (type === 'CRIT') { const entry = new YZCrit(elem); table.set(entry.ref, entry); } else if (elem.hasOwnProperty('ref')) { table.set(elem.ref, elem); } else { throw new Errors.SebediusError('Unknown RollTable'); } } return table; } /** * Returns a text with all the dice turned into emojis. * @param {YZRoll} roll The roll * @param {Object} opts Options of the roll command * @param {boolean} [applyAliases=false] Whether to apply the aliases * @returns {string} The manufactured text */ static emojifyRoll(roll, opts, applyAliases = false) { const game = opts.iconTemplate || roll.game; let str = ''; for (const die of roll.dice) { const val = die.result; const errorIcon = ` \`{${val}}\``; let iconType = die.type; if (opts.alias) { // Skipping types. if (opts.alias[die.type] === '--' || die.type == null) continue; // Dice swaps, if any. if (applyAliases && opts.alias[die.type]) iconType = opts.alias[die.type]; } // Artifact Dice specific skin. if (iconType === 'arto') { str += DICE_ICONS.fbl.arto[val] || errorIcon; } // Twilight 2000 specific skin. else if (game === 't2k' && iconType === 'base' && die.range !== 6) { str += DICE_ICONS.t2k['d' + die.range][val] || errorIcon; } else { const diceTypeIcons = DICE_ICONS[game][iconType]; str += diceTypeIcons && diceTypeIcons[val] ? diceTypeIcons[val] : errorIcon; //str += DICE_ICONS[game][iconType][val] || errorIcon; } } return str; } /** * Returns the selected choice, or None. Choices should be a list of two-tuples of (name, choice). * If delete is True, will delete the selection message and the response. * If length of choices is 1, will return the only choice unless force_select is True. * @param {Discord.Message} ctx Discord message with context * @param {Array<string, Object>[]} choices An array of arrays with [name, object] * @param {string} text Additional text to attach to the selection message * @param {boolean} del Whether to delete the selection message * @param {boolean} pm Whether the selection message is sent in a PM (Discord DM) * @param {boolean} forceSelect Whether to force selection even if only one choice possible * @returns {*} The selected choice * @throws {NoSelectionElementsError} If len(choices) is 0. * @throws {SelectionCancelledError} If selection is cancelled. * @static * @async */ static async getSelection(ctx, choices, text = null, del = true, pm = false, forceSelect = false, lang = 'en') { if (choices.length === 0) throw new Errors.NoSelectionElementsError(); else if (choices.length === 1 && !forceSelect) return choices[0][1]; const paginatedChoices = Util.paginate(choices, 10); const msgFilter = m => m.author.id === ctx.author.id && m.channel.id === ctx.channel.id && Number(m.content) >= 1 && Number(m.content) <= choices.length; // Builds the pages. const pages = []; paginatedChoices.forEach((_choices, page) => { const names = _choices.map(o => o[0]); const embed = new Discord.MessageEmbed() .setTitle(__('selection-title', lang)) .setDescription( __('selection-description', lang) + '\n' + names .map((n, i) => `**[${i + 1 + page * 10}]** – ${n}`) .join('\n'), ); if (paginatedChoices.length > 1) { embed.setFooter(__('page', lang) + ` ${page + 1}/${paginatedChoices.length}`); } if (text) { embed.addField('Info', text, false); } if (pm) { embed.addField( __('instructions', lang), __('selection-instructions', lang), false, ); } pages.push(embed); }); // Sends the selection message. let msgCollector = null; const channel = pm ? ctx.author : ctx.channel; const time = 30000; const pageMenu = new PageMenu(channel, ctx.author.id, time * 2, pages, { stop: { icon: PageMenu.ICON_STOP, owner: ctx.author.id, fn: () => msgCollector.stop(), }, }); // Awaits for the answer. let msg = null; msgCollector = ctx.channel.createMessageCollector(msgFilter, { max: 1, time }); msgCollector.on('end', () => pageMenu.stop()); // Catches the answer or any rejection. try { msg = await msgCollector.next; } catch (rejected) { throw new Errors.SelectionCancelledError(); } if (!msg || msg instanceof Map) { return null; } // Deletes the answer message. if (del && !pm) { try { await msg.delete(); } catch (err) { console.warn('[getSelection] Failed to delete choice message.', err.name, err.code); } } // Returns the choice. return choices[Number(msg.content) - 1][1]; } /** * Confirms whether a user wants to take an action. * @param {Discord.Message} message The current message * @param {string} text The message for the user to confirm * @param {boolean} [deleteMessages=false] Whether to delete the messages * @returns {boolean|null} Whether the user confirmed or not. None if no reply was received */ static async confirm(message, text, deleteMessages = false) { const msg = await message.channel.send(text); const filter = m => m.author.id === message.author.id && m.channel.id === message.channel.id; const reply = (await message.channel.awaitMessages(filter, { max: 1, time: 30000 })).first(); const replyBool = Util.getBoolean(reply.content) || null; if (deleteMessages) { try { await msg.delete(); await reply.delete(); } catch (error) { console.error(error); } } return replyBool; } /** * Checks if the bot has all the required permissions. * @param {Discord.Message} ctx Discord message with context * @param {number} checkPerms Bitfield / Use this argument if you want to check just a few specific Permissions. * @returns {boolean} `true` if the bot has all the required Permissions. * @static */ static checkPermissions(ctx, checkPerms = null) { const channel = ctx.channel; // Exits early if we are in a DM. if (channel.type === 'dm') return true; const botMember = channel.guild.me; const perms = checkPerms || ctx.bot.config.perms.bitfield; const serverMissingPerms = botMember.permissions.missing(perms); const channelMissingPerms = channel.permissionsFor(botMember).missing(perms); // The above functions return an array // filled with the flag of the missing Permissions, if any. // If not, the arrays are empty (length = 0). if (serverMissingPerms.length || channelMissingPerms.length) { let msg = '🛑 **Missing Permissions!**' + '\nThe bot does not have sufficient permission in this channel and will not work properly.' + ` Check the Readme (\`${ctx.prefix}help\`) for the list of required permissions.` + ' Check the wiki for more troubleshooting.'; if (serverMissingPerms.length) { msg += `\n**Role Missing Permission(s):** \`${serverMissingPerms.join('`, `')}\``; } if (channelMissingPerms.length) { msg += `\n**Channel Missing Permission(s):** \`${channelMissingPerms.join('`, `')}\``; } ctx.reply(msg); return false; } else { return true; } } /** * Gets a user from its mention. * @param {string} mention The user mention * @param {Discord.Client} client The Discord client (the bot) * @returns {Promise<Discord.User>|Discord.User} * @static * @async */ static async getUserFromMention(mention, client) { // The id is the first and only match found by the RegExp. const matches = mention.match(/^<@!?(\d+)>$/); // If supplied variable was not a mention, matches will be null instead of an array. if (!matches) return; // However the first element in the matches array will be the entire mention, not just the ID, // so use index 1. const id = matches[1]; if (client.users.cache.has(id)) { return client.users.cache.get(id); } else { return await client.users.fetch(id); } } /** * Fetches a Member based on its name, mention or ID. * @param {string} needle Name, mention or ID * @param {Discord.Message} ctx The triggering message with context * @returns {Promise<Discord.Member>} * @static * @async */ static async fetchMember(needle, ctx) { if (Discord.MessageMentions.USERS_PATTERN.test(needle)) { return await Sebedius.getUserFromMention(needle, ctx.bot); } const members = ctx.channel.members; return members.find(mb => mb.id === needle || mb.displayName === needle, ); } /** * Gets the mention for this user * @param {Discord.User} user Discord user * @returns {string} In the form of `<@0123456789>` * @static */ static getMention(user) { return `<@${user.id}>`; } /** * Processes a Discord Message into a Message with context. * @param {Discord.Message} message The Discord message without context * @param {string} prefix The prefix of the command * @returns {ContextMessage} Discord message with context * @static */ static processMessage(message, prefix) { // Creates a message with context. const ctx = new ContextMessage(prefix, message.client); // Returns a shallow copy of the Discord message merged with the context. return Object.assign(ctx, message); } /** * Tries to delete a message. Catches errors. * @param {*} message Message to delete * @async */ static async tryDelete(message) { try { await message.delete(); } catch (error) { console.error(error); } } }
JavaScript
class Base extends HTMLElement { /** * Custom element's constructor */ constructor() { // MUST BE FIRST INSTRUCTION! super(); // Create the Shadow DOM this.attachShadow({mode : 'open'}); } /** * Called when the custom component is added to the page */ connectedCallback() { this.renderShadowDOM(); } /** * Called when an watched attribute changes * * @param {String} name Attribute's name * @param {String} oldValue previous attribute's value * @param {String} newValue new attribute's values (JSON accepted) * @returns */ attributeChangedCallback(name, oldValue, newValue) { let data = ""; try { data = JSON.parse(unescape(newValue)); } catch (e) { data = newValue; } this[name] = data; this.renderShadowDOM(); } /** * Update the component content and style */ renderShadowDOM() { this.shadowRoot.innerHTML = this.getHtml(); this.shadowRoot.appendChild(this.makeStyle()); } /** * Create a The style element with its content. * @returns {HTMLStyleElement} The style element with its content */ makeStyle() { const style = document.createElement('style'); style.textContent = this.getStyle(); return style; } /** * The custom element's HTML content * * @returns {string} The custom element's HTML content */ getHtml() { return `<!-- Empty element -->`; } /** * The custom element's CSS content * * @returns {string} The custom element's CSS content */ getStyle() { return STYLE; } /** * @type {Array>String>} Array of observed attributes */ static get observedAttributes() { return []; } }
JavaScript
class Detail extends React.PureComponent { render () { return ( <View style={styles.container}> <Text>Detail</Text> <Text>{`Item price: ${ItemStore.price}`}</Text> <Text>{`Vote counst: ${ItemStore.voteCount}`}</Text> </View> ) } }
JavaScript
class HeatMapModel extends models['ProxyResource'] { /** * Create a HeatMapModel. * @member {date} [startTime] The beginning of the time window for this * HeatMap, inclusive. * @member {date} [endTime] The ending of the time window for this HeatMap, * exclusive. * @member {array} [endpoints] The endpoints used in this HeatMap * calculation. * @member {array} [trafficFlows] The traffic flows produced in this HeatMap * calculation. */ constructor() { super(); } /** * Defines the metadata of HeatMapModel * * @returns {object} metadata of HeatMapModel * */ mapper() { return { required: false, serializedName: 'HeatMapModel', type: { name: 'Composite', className: 'HeatMapModel', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, startTime: { required: false, serializedName: 'properties.startTime', type: { name: 'DateTime' } }, endTime: { required: false, serializedName: 'properties.endTime', type: { name: 'DateTime' } }, endpoints: { required: false, serializedName: 'properties.endpoints', type: { name: 'Sequence', element: { required: false, serializedName: 'HeatMapEndpointElementType', type: { name: 'Composite', className: 'HeatMapEndpoint' } } } }, trafficFlows: { required: false, serializedName: 'properties.trafficFlows', type: { name: 'Sequence', element: { required: false, serializedName: 'TrafficFlowElementType', type: { name: 'Composite', className: 'TrafficFlow' } } } } } } }; } }
JavaScript
class GetPathComponent extends Component { constructor(props) { super(props); // Location initially remains invalid to indicate that no path has been returned from server yet. this.state = { directions: {}, currStartLocation: "", currEndLocation: "", currStartIdx: 0, currEndIdx: 1, }; this.responseJobs_ = []; this.directionsService_ = {}; } componentDidMount = async () => { await Promise.all([ this.fetchJobCoordinates_(), this.waitForMapsApiToLoad_(), ]); this.directionsService_ = new google.maps.DirectionsService(); this.displayDirections_(0, 1); }; render() { return ( <div> <GoogleMapComponent directions={this.state.directions} googleMapURL={MapsApi.MAPS_API_URL} loadingElement={<div />} containerElement={<div style={{ height: "80vh" }} />} mapElement={<div style={{ height: "100%" }} />} /> <p className="PathInformation" title="Path Info Success" style={this.state.currStartLocation === "" ? { display: "none" } : {}} > {this.state.currEndIdx}/{this.responseJobs_.length - 1}&nbsp; This delivery path goes <br></br> <b>From</b> {this.state.currStartLocation} <br></br> <b>To</b> {this.state.currEndLocation}<br></br> (Click on markers for more location information) </p> <p className="PathInformation" title="Path Info Processing" style={this.state.currStartLocation === "" ? {} : { display: "none" }} > Fetching deliveries. Please wait! </p> <div className="ControlButtonContainer"> <button tabIndex="0" className="PreviousPathButton" id="PreviousPathButton" onClick={this.onPreviousClick} disabled={this.state.currStartIdx <= 0} > Previous Path </button> <button tabIndex="0" className="NextPathButton" id="NextPathButton" onClick={this.onNextClick} disabled={this.state.currEndIdx >= this.responseJobs_.length - 1} > Next Path </button> </div> </div> ); } onPreviousClick = () => { this.displayDirections_( this.state.currStartIdx - 1, this.state.currEndIdx - 1 ); }; onNextClick = () => { this.displayDirections_( this.state.currStartIdx + 1, this.state.currEndIdx + 1 ); }; fetchJobCoordinates_ = async () => { return fetch(ServerApi.SERVER_GET_PATH_URL) .then((response) => response.json()) .then((responseJson) => { this.responseJobs_ = responseJson.responseJobs; }); }; waitForMapsApiToLoad_ = async () => { return new Promise((resolve, _) => { window.initMap = () => { resolve(); }; }); }; displayDirections_ = (startIdx, endIdx) => { this.directionsService_.route( { origin: { lat: this.responseJobs_[startIdx].latitude, lng: this.responseJobs_[startIdx].longitude, }, destination: { lat: this.responseJobs_[endIdx].latitude, lng: this.responseJobs_[endIdx].longitude, }, travelMode: google.maps.TravelMode.DRIVING, }, (result, status) => { if (status === google.maps.DirectionsStatus.OK) { this.setState({ directions: result, currStartLocation: this.responseJobs_[startIdx].name, currEndLocation: this.responseJobs_[endIdx].name, currStartIdx: startIdx, currEndIdx: endIdx, }); } else { this.setState({ error: result }); } } ); }; }
JavaScript
class Personality { /** * @param {PersonalityToolData} data - Tool's data * @param {PersonalityConfig} config - Tool's config * @param {API} api - Editor.js API */ constructor({ data, config, api }) { this.api = api; this.nodes = { wrapper: null, name: null, description: null, link: null, photo: null }; this.config = { endpoint: config.endpoint || '', field: config.field || 'image', types: config.types || 'image/*', namePlaceholder: config.namePlaceholder || 'Name', descriptionPlaceholder: config.descriptionPlaceholder || 'Description', linkPlaceholder: config.linkPlaceholder || 'Link' }; /** * Set saved state */ this._data = {}; this.data = data; /** * Module for image files uploading */ this.uploader = new Uploader({ config: this.config, onUpload: (response) => this.onUpload(response), onError: (error) => this.uploadingFailed(error) }); } /** * Get Tool toolbox settings * icon - Tool icon's SVG * title - title to show in toolbox */ static get toolbox() { return { icon: ToolboxIcon, title: 'Personality' }; } /** * File uploading callback * @param {UploadResponseFormat} response */ onUpload(response) { const { body: { success, file } } = response; if (success && file && file.url) { Object.assign(this.data, { photo: file.url }); this.showFullImage(); } } /** * On success: remove loader and show full image */ showFullImage() { setTimeout(() => { this.nodes.photo.classList.remove(this.CSS.loader); this.nodes.photo.style.background = `url('${this.data.photo}') center center / cover no-repeat`; }, LOADER_DELAY); } /** * On fail: remove loader and reveal default image placeholder */ stopLoading() { setTimeout(() => { this.nodes.photo.classList.remove(this.CSS.loader); this.nodes.photo.removeAttribute('style'); }, LOADER_DELAY); } /** * Show loader when file upload started */ addLoader() { this.nodes.photo.style.background = 'none'; this.nodes.photo.classList.add(this.CSS.loader); } /** * If file uploading failed, remove loader and show notification * @param {string} errorMessage - error message */ uploadingFailed(errorMessage) { this.stopLoading(); this.api.notifier.show({ message: errorMessage, style: 'error' }); } /** * Tool's CSS classes */ get CSS() { return { baseClass: this.api.styles.block, input: this.api.styles.input, loader: this.api.styles.loader, /** * Tool's classes */ wrapper: 'cdx-personality', name: 'cdx-personality__name', photo: 'cdx-personality__photo', link: 'cdx-personality__link', description: 'cdx-personality__description' }; } /** * Return Block data * @param {HTMLElement} toolsContent * @return {PersonalityToolData} */ save(toolsContent) { const link = toolsContent.querySelector(`.${this.CSS.link}`).textContent; const name = toolsContent.querySelector(`.${this.CSS.name}`).textContent; const description = toolsContent.querySelector(`.${this.CSS.description}`).textContent; Object.assign(this.data, { name: name || this._data.name, description: description || this._data.description, link: link || this._data.link }); return this.data; } /** * Stores all Tool's data * @param {PersonalityToolData} data */ set data({ name, description, link, photo }) { this._data = Object.assign({}, { name: name || this._data.name, description: description || this._data.description, link: link || this._data.link, photo: photo || this._data.photo }); } /** * Return Tool data * @return {PersonalityToolData} data */ get data() { return this._data; } /** * Renders Block content * @return {HTMLDivElement} */ render() { const { name, description, photo, link } = this.data; this.nodes.wrapper = this.make('div', this.CSS.wrapper); this.nodes.name = this.make('div', this.CSS.name, { contentEditable: true }); this.nodes.description = this.make('div', this.CSS.description, { contentEditable: true }); this.nodes.link = this.make('div', this.CSS.link, { contentEditable: true }); this.nodes.photo = this.make('div', this.CSS.photo); if (photo) { this.nodes.photo.style.background = `url('${photo}') center center / cover no-repeat`; } if (description) { this.nodes.description.textContent = description; } else { this.nodes.description.dataset.placeholder = this.config.descriptionPlaceholder; } if (name) { this.nodes.name.textContent = name; } else { this.nodes.name.dataset.placeholder = this.config.namePlaceholder; } if (link) { this.nodes.link.textContent = link; } else { this.nodes.link.dataset.placeholder = this.config.linkPlaceholder; } this.nodes.photo.addEventListener('click', () => { this.uploader.uploadSelectedFile({ onPreview: () => { this.addLoader(); } }); }); this.nodes.wrapper.appendChild(this.nodes.photo); this.nodes.wrapper.appendChild(this.nodes.name); this.nodes.wrapper.appendChild(this.nodes.description); this.nodes.wrapper.appendChild(this.nodes.link); return this.nodes.wrapper; } /** * Helper method for elements creation * @param tagName * @param classNames * @param attributes * @return {HTMLElement} */ make(tagName, classNames = null, attributes = {}) { const el = document.createElement(tagName); if (Array.isArray(classNames)) { el.classList.add(...classNames); } else if (classNames) { el.classList.add(classNames); } for (const attrName in attributes) { el[attrName] = attributes[attrName]; } return el; } }
JavaScript
class CanListener { constructor(cb, can_ids) { this.cb = cb; this.can_ids = can_ids; } // Returns true if the message is of interest to this listener. // A blank list of can_ids is treated like a subscribe-all interested(message_id) { if(this.can_ids == undefined || this.can_ids.length == 0) { return true; } return this.can_ids.includes(message_id); } }
JavaScript
class CanMessage { constructor(raw) { this.id = this._unpack_id(raw); this.idString = "0x" + this.id.toString(16).toUpperCase(); this.len = this._unpack_len(raw); this.data = this._unpack_data(raw, this.len); this._raw = raw; this._uint32 = this.getUint32(); this._float = this.getFloat() this.timestamp = performance.now(); } /** * Produce a CanMessage for a 4 byte float value * * @param {int32} id - CAN Message ID * @param {float32} char_val - Float value to send as data */ static fromFloat(id, float_val) { this._raw = Buffer.alloc(9); this._raw.writeUInt32BE(id, 0); // id this._raw.writeUInt8(1, 4); // data length this._raw.writeFloatBE(float_val, 5); // data return new CanMessage(data); } /** * Produce a CanMessage for a single char value * * @param {int32} id - CAN Message ID * @param {uint8} char_val - Character value to send as data */ static fromChar(id, char_val) { let data = Buffer.alloc(6); data.writeUInt32BE(id, 0); // id data.writeUInt8(1, 4); // data length data.writeUInt8(char_val, 5); // data return new CanMessage(data); } buffer() { return this._raw; } // Converts first four bytes of data to an uint32 value getUint32() { let binary = new Uint8Array([this._raw[5], this._raw[6], this._raw[7], this._raw[8]]); let dv = new DataView(binary.buffer); return dv.getUint32(); } // Converts first four bytes of data to a float getFloat() { let binary = new Uint8Array([this._raw[5], this._raw[6], this._raw[7], this._raw[8]]); let dv = new DataView(binary.buffer); return dv.getFloat32(0); } _unpack_id(buffer) { let binary = new Uint8Array([buffer[0], buffer[1], buffer[2], buffer[3]]); let dv = new DataView(binary.buffer); return dv.getUint32(); } _unpack_len(buffer) { return buffer[4]; } _unpack_data(buffer, len) { var out = []; for(let i=0; i<len; i++) { out.push(buffer[5 + i].toString(16)); } return out; } }
JavaScript
class CanNetwork { constructor(port) { this.listeners = [] this.port = port; this.ip = broadcastAddr; this.client = createSocket('udp4'); this.client.on('error', (err) => { console.log(`client error:\n${err.stack}`); this.client.close(); }); this.client.on('message', (raw_msg, rinfo) => { for(let l of this.listeners) { let can_msg = new CanMessage(raw_msg); // Send message to listeners if(l.interested(can_msg.id)) { l.cb(can_msg); } } }); this.client.on('listening', () => { this.client.setBroadcast(true); console.log(`client listening ${broadcastAddr}:${this.port}`); }); this.client.bind(this.port, () => { console.debug(`Bound to port ${this.port}`); }); } // Send a CAN message over the network to our registered port send(buffer) { send_to_port(buffer, this.port); } // send a CAN message over the network to a specified port send_to_port(buffer, dport) { this.client.send(buffer, dport, this.ip); } // Register a CanListener with the network register(listener) { console.info("Registering listener on port " + this.port); this.listeners.push(listener); } // Unregister a CanListener from the network unregister(listener) { this.listeners.splice(this.listeners.indexOf(listener), 1); } }
JavaScript
class PubSubMaker { /** * This class will handle the callbacks for a single job posting to the Redis messaging system. * @param publisher Redis Client set as a publisher * @param subscriber Redis Client set as a subscriber * @param pubChannel The channel to which the publisher should publish its job postings * @param subChannel The channel to which the subscriber shoud listen for job posting responses * @param identifier The identifying information for the job itself */ constructor(publisher, subscriber, pubChannel, subChannel, identifier) { this.publisher = publisher; this.subscriber = subscriber; this.pubChannel = pubChannel; this.subChannel = subChannel; this.identifier = identifier; this.responseNotifier = new events_1.EventEmitter(); // I would like to leave this undefined, but my linter is complaining about it. Don't @ me this.deleteTargetIp = setTimeout(() => { }, 0); // This will hold the listener function for subscriptions. It is needed to allow dynamic function naming // so that listeners can be deleted by name later without deleting all listeners this.callbackTracker = {}; } /** * This is the only public method for this class. It creates a dynamically named callback function, and then adds it as a * listener to the 'message' event on the subscriber. */ listenForAcceptors() { const newListener = (responseChannel, message) => this.subscriberListener(responseChannel, message); Object.defineProperty(newListener, 'name', { value: this.identifier.jobId, writable: false, enumerable: false, configurable: true }); this.callbackTracker[this.identifier.jobId] = newListener; this.subscriber.on('message', this.callbackTracker[this.identifier.jobId]); } /** * Creates a listener for the subscriber redis client. Emits an "accepted" event on the class instance's responseNotifier * event emitter when the job has been accepted. Also emits the IChannelIdentifier object for the job acceptor. * @param responseChannel This is passed by the subscriber's "message" event. The name of the channel where the job was heard * @param message This is passed by the subscriber's "message" event. The message that was sent. Should be parseable into JSON. */ subscriberListener(responseChannel, message) { const messageAsObj = JSON.parse(message); // Make sure that the response is meant for this specific listener if (responseChannel === this.subChannel && messageAsObj.jobId === this.identifier.jobId) { // If this job has not yet been by anyone, the targetIp will be empty. If the targetIp is already filled, we don't care about the message. if (!this.identifier.targetIp && messageAsObj.params === 'reporting') { this.identifier.targetIp = messageAsObj.responderIp; this.respondToReporters(this.pubChannel); } else if ( // If these fields are filled out in the message object, it means that it is not the first message this.identifier.targetIp && this.identifier.targetIp === messageAsObj.responderIp) { // Check if the message is an acceptance message and that it is meant for this poster's job if (messageAsObj.params === 'accepting') { if (this.identifier.jobId === messageAsObj.jobId) { // Acknowledge that the job has been accepted, and emit the acceptor's identifying information object. if (this.deleteTargetIp) clearTimeout(this.deleteTargetIp); this.respondToAcceptors(this.pubChannel, messageAsObj); } else { this.recastForReporters(); } } } } } /** * Generates a timeout that deletes the targetIP. Used to make sure that a job gets accepted in a timely manner * @returns */ targetIpDeleter() { return setTimeout(() => delete this.identifier.targetIp, 3000); } // Send out a message to a responder, whose targetIp is now written on the identifier. Sends the message "accept" respondToReporters(pubChannel) { const acceptanceIdentifier = { ...this.identifier, params: 'accept' }; this.publisher.publish(pubChannel, JSON.stringify(acceptanceIdentifier)); // In the case of timeouts (like if the acceptor accepted a different job), the parent will handle rerequesting. // This class just needs to make sure its identifier's targetIp is clear so that it is ready to accept another job. if (this.deleteTargetIp) clearTimeout(this.deleteTargetIp); this.deleteTargetIp = this.targetIpDeleter(); } // Send out a message to the responder, acknowledging that they have accepted the job. Sends the message "confirmed" respondToAcceptors(pubChannel, messageAsObj) { const confirmationIdentifier = { ...this.identifier, params: 'confirmed' }; this.publisher.publish(pubChannel, JSON.stringify(confirmationIdentifier)); // Now that we've received the response telling us the job has been accepted, we can remove our listener this.subscriber.removeListener('message', this.callbackTracker[this.identifier.jobId]); this.responseNotifier.emit('accepted', messageAsObj); } recastForReporters() { // Clear out the target IP to allow for a new target, then recast for a job acceptor delete this.identifier.targetIp; this.publisher.publish(this.pubChannel, JSON.stringify(this.identifier)); // Reset the timeout counter if (this.deleteTargetIp) clearTimeout(this.deleteTargetIp); this.deleteTargetIp = this.targetIpDeleter(); } }
JavaScript
class API { constructor(basePath = API_BASE) { this.basePath = basePath; } get({ uri, data }, callback) { let path = this.basePath + uri; if (data) { path += `?${qs.stringify(data)}`; } return xhr(path, { json: true, }, (err, res) => { if (err) { callback(`Error: Internal XMLHttpRequest Error: ${err.toString()}`); } else if (res.statusCode >= 400) { callback(res.rawRequest.statusText); } else { callback(null, res.body); } }); } /** * Get schedule metadata from the API. * * @param {function(string|null, ScheduleMetadata[]?)} callback */ getSchedules(callback) { this.get({ uri: API_RATES_SCHEDULES, data: null }, callback); } }
JavaScript
class Camera { constructor(camera) { this.camera = camera; this.worldView = this.camera.worldView; } /** * Move camera horizontal * @param {int} tile number of tiles to move * @return {none} */ scrollX(tile) { this.camera.scrollX = this.camera.scrollX + Map.getMapValue(tile); } /** * Move camera vertical * @param {int} tile number of tiles to move * @return {none} */ scrollY(tile) { this.camera.scrollY = this.camera.scrollY + Map.getMapValue(tile); } /** * get camera offset from left border * @return {int} */ getOffsetX() { return this.camera.scrollX/Constants.MAP_TILE_SIZE; } /** * Get camera offset from top border * @return {int} */ getOffsetY() { return this.camera.scrollY/Constants.MAP_TILE_SIZE; } }
JavaScript
class TestScript extends EventEmitter { /** * @author TechQuery <[email protected]> * * @param {string} URI - Path of a **Source module** * @param {string} sourcePath - Path of the **Source directory** * @param {string} testPath - Path of the **Test directory** */ constructor(URI, sourcePath, testPath) { super().length = 0; this.sourcePath = Path.join(process.cwd(), sourcePath); this.testPath = Path.join(process.cwd(), testPath); this.URI = ( Path.isAbsolute( URI ) ? Path.relative(this.sourcePath, URI) : URI ).replace(/\\/g, '/'); this.testURI = Path.join(this.testPath, this.URI); this.sourceURI = Path.relative( this.testURI, Path.join(this.sourcePath, this.URI) ).replace(/\\/g, '/'); this.ID = TestScript.toBigCamel( Path.basename(URI, '.js') ); this.header = [ ]; } static toBigCamel(raw) { return raw.replace(/^\w|[_\-](\w)/g, function (A, B) { return (B || A).toUpperCase(); }); } addHeader(raw) { if (raw && (this.header.indexOf( raw ) < 0)) this.header.push( raw ); } /** * Add Test unit * * @author TechQuery * @since 0.2.0 * * @param {object} Doclet * * @throws {SyntaxError} While the `title`, `script` or `expected` of * an Example is missing */ addUnit(Doclet) { if (! (Doclet.examples instanceof Array)) return; var case_key = ['title', 'script', 'expected']; this[ this.length++ ] = { title: Doclet.longname, item: Doclet.examples.map(function (item) { item = item.match( /^\/\/\s*(.+?)(?:\r|\n|\r\n){2,}([\s\S]+)\s+\/\/([\s\S]+)/ ) || [ ]; /** * **Test item** object * * @typedef {object} TestItem * * @property {string} title - **Comment text** in the * same line of `@example` * @property {string} script - **Source code** to be tested * @property {string} expected - Expected result * @property {string} [source=''] - Full source code of * this test */ var test_case = {source: ''}; for (let i = 0; case_key[i]; i++) if (! ( test_case[ case_key[i] ] = (item[i + 1] || '').trim() .replace(/\r\n|\r/g, "\n") )) throw SyntaxError( `The ${case_key[i]} of ${Doclet.longname} is missing` ); return test_case; }) }; } getHeader() { /** * **Test header** object * * @typedef {object} TestHeader * * @property {string} URI - Module URI relative to * the **Source directory** * @property {string} sourceURI - Module URI relative to * this **Test scirpt** * @property {string} [source=''] - The header's source code of * this **Test script** */ var header = { URI: this.URI, sourceURI: this.sourceURI, source: '' }; /** * Before the **Test script** writed * * @event TestScript#fileWrite */ this.emit('fileWrite', header); if ( header.source ) this.addHeader( header.source ); /** * Before the header of **Test script** writed * * @event TestScript#headerWrite */ header.source = ''; this.emit('headerWrite', header); return header.source; } /** * @author TechQuery <[email protected]> * @since 0.2.0 * * @return {string} Source code of this **Test script** */ toString() { var _this_ = this, header = this.getHeader(); return Beautify(`'use strict'; require('should'); ${this.header.join("\n\n")} describe('${this.URI}', function () { ${header} ${Array.from(this, function (test) { return `describe('${test.title}', function () { ${test.item.map(function (item) { /** * Before **Test item** writed * * @event TestScript#itemWrite */ _this_.emit('itemWrite', item); return item.source || `it('${item.title}', function () { var result = ${item.script}; result.should.be.deepEqual( ${item.expected} ); });`; }).join('')} }); `; }).join("\n")} });` ); } }
JavaScript
class DashaMail { /** * Update/Set apiKey * @public * @param {string} apiKey * @returns {this} */ setApiKey(apiKey) { if (apiKey) this.apiKey = apiKey; return this; } /** * @public * @returns {string|null} */ getApiKey() { return CObject.get(this, 'apiKey'); } /** * Update DashaMail host * @public * @param {string} host * @returns {this} */ setHost(host) { if (host && typeof host === 'string') this.host = host; return this; } /** * @public * @returns {string|*} */ getHost() { return CObject.get(this, 'host', 'api.dashamail.com'); } /** * @param {Format} format * @returns {DashaMail} */ setFormat(format) { if (format && Object.keys(Format).indexOf(format) !== -1) this.format = format; return this; } /** * @returns {Format} */ getFormat() { return CObject.get(this, 'format', Format.json); } /** * Update DashaMail method * @protected * @param {string} method * @returns {this} */ setMethod(method) { if (method) this.method = `${this.name}.${method}`; return this; } /** * @public * @returns {string|null} */ getMethod() { return CObject.get(this, 'method'); } /** * Update request timeout * * @param timeout * @returns {DashaMail} */ setTimeout(timeout) { if (timeout >= 0) this.timeout = timeout; return this; } /** * @returns {number} */ getTimeout() { return CObject.get(this, 'timeout', 5000); } /** * For ignoring unsubscribe from emails * * @param ignore * @returns {this} */ setIgnoreUnsubscribe(ignore) { this.ignoreUnsubscribe = ignore; return this; } /** * * @returns {boolean} */ getIgnoreUnsubscribe() { return CObject.get(this, 'ignoreUnsubscribe', false) } /** * @protected * @param {URLSearchParams} body * @returns {Promise<unknown>} */ request(body) { return new Promise((resolve, reject) => { if (!this.apiKey) return reject('apiKey not set'); if (!this.getMethod()) return reject('method not set'); body.set('api_key', this.getApiKey()); body.set('method', this.getMethod()); body.set('format', this.getFormat()); const headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'Content-Length': Buffer.byteLength(body.toString()) }; if (this.getIgnoreUnsubscribe()) Object.assign(headers, {'X-Dashamail-Unsub-Ignore': true}); const options = {host: this.getHost(), method: 'POST', timeout: this.getTimeout(), headers} const request = https.request(options, res => { let body = ''; res.on('data', chunk => body += chunk); res.on('end', () => { try { body = JSON.parse(body); } catch (e) { if (this.getFormat() !== 'xml') return reject(e); } if (res.statusCode === 200) { const status = CObject.get(body, 'response.msg.text'); if (status && status !== 'OK') return reject(status); else return resolve(body); } return reject(body); }); }) request.write(body.toString()); request.end(); request.on('error', e => reject(e)); }); } }
JavaScript
class AttributeSetFunctions extends PlantWorksBaseComponent { // #region Constructor constructor(parent, loader) { super(parent, loader); } // #endregion // #region Protected methods - need to be overriden by derived classes /** * @async * @function * @override * @instance * @memberof AttributeSetFunction * @name _addRoutes * * @returns {undefined} Nothing. * * @summary Adds routes to the Koa Router. */ async _addRoutes() { try { this.$router.get('/:attributeSetFunctionId', this.$parent._rbac('registered'), this._getAttributeSetFunction.bind(this)); this.$router.post('/', this.$parent._rbac('registered'), this._addAttributeSetFunction.bind(this)); this.$router.patch('/:attributeSetFunctionId', this.$parent._rbac('registered'), this._updateAttributeSetFunction.bind(this)); this.$router.delete('/:attributeSetFunctionId', this.$parent._rbac('registered'), this._deleteAttributeSetFunction.bind(this)); await super._addRoutes(); return null; } catch(err) { throw new PlantWorksComponentError(`${this.name}::_addRoutes error`, err); } } // #endregion // #region Route Handlers async _getAttributeSetFunction(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; const attributeSetFunctionData = await apiSrvc.execute('AttributeSetFunctions::getAttributeSetFunction', ctxt); ctxt.status = 200; ctxt.body = attributeSetFunctionData.shift(); return null; } catch(err) { throw new PlantWorksComponentError(`Error retrieving attribute set function data`, err); } } async _addAttributeSetFunction(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; const attributeSetFunctionData = await apiSrvc.execute('AttributeSetFunctions::createAttributeSetFunction', ctxt); ctxt.status = 200; ctxt.body = attributeSetFunctionData.shift(); return null; } catch(err) { throw new PlantWorksComponentError(`Error creating attribute set function data`, err); } } async _updateAttributeSetFunction(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; const attributeSetFunctionData = await apiSrvc.execute('AttributeSetFunctions::updateAttributeSetFunction', ctxt); ctxt.status = 200; ctxt.body = attributeSetFunctionData.shift(); return null; } catch(err) { throw new PlantWorksComponentError(`Error updating attribute set function data`, err); } } async _deleteAttributeSetFunction(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; await apiSrvc.execute('AttributeSetFunctions::deleteAttributeSetFunction', ctxt); ctxt.status = 204; return null; } catch(err) { throw new PlantWorksComponentError(`Error deleting attribute set function data`, err); } } // #endregion // #region Properties /** * @override */ get dependencies() { return ['DatabaseService'].concat(super.dependencies); } /** * @override */ get basePath() { return __dirname; } // #endregion }
JavaScript
class Layout { constructor() { this.lateral_menu_open = prop(false); } _toggle_menu() { this.lateral_menu_open(!this.lateral_menu_open()); return false; } /** * @param app {Application}: reference to the Application instance. * @param children */ view({attrs: {app}, children}) { return [ m('header', [ // TODO: adjust img width and/or height m('a#brand-logo', { onclick: () => this._toggle_menu()}, m('span#hamburger-icon.glyphicon.glyphicon-menu-hamburger'), m('img[height=30]', {src: loader('bajoo-logo.png')}) ), // #user-menu m('#user-menu', app.is_logged ? [ m('button.btn.btn-danger[type=button]', {onclick: () => app.reset()}, _('Log out')) ] : '' ), LanguageMenu.make(), m('span#app-name', 'Bajoo web interface'), TaskListModal.make(app.task_manager), // modals TaskManagerStatus.make(app.task_manager), PassphraseInputModal.make(app.task_manager.passphrase_input) ]), LateralMenu.make(app.user, this.lateral_menu_open, () => app.reset()), m('#side-column', app.is_logged ? StorageNav.make(app.user) : '' ), m('main', app.is_logged === null ? _('Connection ...') : children ), m('footer', StaticLinksNav.make()) ]; } }
JavaScript
class PlaylistContainer { /** * Constructor of the playlist container */ constructor(){ this.playlists = []; } addPlaylist(playlist){ if(typeof playlist!=='Playlist'){ return null; } else{ this.playlists.push(playlist); } } /** * Load saved playlists from chrome storage */ init(){ // TODO Retrieve playlists from chrome storage } }
JavaScript
class SlateNodePortal extends React.Component { /** * On portal open, store a reference to it and update the menu's position. * * @param {Element} portal */ onOpen = portal => { this.portal = portal; this.update(); this.props.onOpen(portal); }; /** * On portal update, update the menu's position. */ onUpdate = () => { this.update(); this.props.onUpdate(); }; /** * On portal close, remove the portal reference. */ onClose = () => { this.portal = null; this.props.onClose(); }; /** * Update the menu's position, relative to the current node. */ update = () => { if (!this.portal) return; const { node, nodeAnchor, menuAnchor } = this.props; const menuEl = this.portal.firstChild; menuEl.style.position = 'absolute'; const nodeEl = findDOMNode(node); const offset = getOffsets(menuEl, menuAnchor, nodeEl, nodeAnchor); menuEl.style.top = `${offset.top + 16}px`; menuEl.style.left = `${offset.left}px`; }; /** * Render. * * @return {Element} */ render = () => { const { children, menuAnchor, node, nodeAnchor, onClose, onOpen, onUpdate, ...props } = this.props; return ( <Portal {...props} isOpened onOpen={this.onOpen} onUpdate={this.onUpdate} onClose={this.onClose} > {children} </Portal> ); }; }
JavaScript
class ConfigPDB2PQR extends ConfigForm{ constructor(props){ super(props); if( hasAnalyticsId() ){ ReactGA.pageview(window.location.pathname + window.location.search) } // Dynamic command line building this.show_cli = true ? this.props.show_cli === 'true' : false this.options_mapping = this.getOptionsCliMapping() this.cli_options = this.getCommandLineArgsDict() this.state = { // File lists pdbFileList: [], userffFileList: [], namesFileList: [], ligandFileList: [], // Form visual toggle flags pdb_upload_hidden: true, ff_upload_hidden: true, mol2_upload_hidden: true, only_parse: false, no_NC_terminus: false, form_values: { PDBFILE: "", USERFFFILE: "", NAMESFILE: "", LIGANDFILE: "", PDBID: "", PDBSOURCE: "ID", PH: 7, PKACALCMETHOD: "propka", FF: "parse", FFOUT: "internal", OPTIONS: [ 'atomsnotclose', 'optimizeHnetwork', 'makeapbsin', 'removewater' ], }, // CLI Tracking cli_command: null, // Submission flags job_submit: false, job_date: null, successful_submit: false, // Registration button states show_register_button: false, } // this.handleJobSubmit = this.handleJobSubmit.bind(this); this.handleFormChange = this.handleFormChange.bind(this) // this.renderConfigForm = this.renderConfigForm.bind(this) } componentDidMount(){ // Initialize cli_command string this.setState({ cli_command: this.getCommandLine(this.state.form_values) }) // if(this.props.jobid){ // this.setState({ jobid: this.props.jobid }) // } // else{ // // AWS: We get new jobid at submission time // // this.getNewJobID() // } } getPdbName(){ let pdb_name if( this.state.form_values.PDBSOURCE === "ID"){ pdb_name = this.state.form_values.PDBID } else{ pdb_name = this.state.form_values.PDBFILE.slice(0, -4) } return pdb_name } getOptionsCliMapping(){ return({ 'atomsnotclose' : 'debump', 'optimizeHnetwork': 'opt', 'assignfrommol2' : 'ligand', 'makeapbsin' : 'apbsinput', 'keepchainids' : 'chain', 'insertwhitespace': 'whitespace', 'maketypemap' : 'typemap', 'neutralnterminus': 'neutraln', 'neutralcterminus': 'neutralc', 'removewater' : 'dropwater', }) } getCommandLineArgsDict(){ let cli_dict = { // PDB and PQR positional args pdb_path: { name: null, type: 'string', placeholder_text: 'PDB_PATH' }, pqr_path: { name: null, type: 'string', placeholder_text: 'PQR_OUTPUT_PATH' }, // pKa options ph_calc_method: { name: '--titration-state-method', type: 'string', placeholder_text: 'PH_METHOD' }, with_ph: { name: '--with-ph', type: 'float', placeholder_text: 'PH' }, // Forcefield options ff: { name: '--ff', type: 'string', placeholder_text: 'FIELD_NAME' }, userff: { name: '--userff', type: 'string', placeholder_text: 'USER_FIELD_FILE' }, usernames: { name: '--usernames', type: 'string', placeholder_text: 'USER_NAME_FILE' }, ffout: { name: '--ffout', type: 'string', placeholder_text: 'FIELD_NAME' }, // Ligand option ligand: { name: '--ligand', type: 'string', placeholder_text: 'LIGAND_FILE' }, // APBS input option apbsinput: { name: '--apbs-input', type: 'string', placeholder_text: 'APBS_INPUT_FILENAME' }, // Additional options debump: { name: '--nodebump', type: 'bool', placeholder_text: null }, opt: { name: '--noopt', type: 'bool', placeholder_text: null }, chain: { name: '--keep-chain', type: 'bool', placeholder_text: null }, whitespace: { name: '--whitespace', type: 'bool', placeholder_text: null }, typemap: { name: '--typemap', type: 'bool', placeholder_text: null }, neutraln: { name: '--neutraln', type: 'bool', placeholder_text: null }, neutralc: { name: '--neutralc', type: 'bool', placeholder_text: null }, dropwater: { name: '--drop-water', type: 'bool', placeholder_text: null }, } return cli_dict } getCommandLine(form_items){ let command = 'pdb2pqr30' let pdb_name = this.getPdbName() // Append pKa options if( form_items.PKACALCMETHOD !== 'none' ){ let pka_args = `${this.cli_options.ph_calc_method.name}=${form_items.PKACALCMETHOD} ${this.cli_options.with_ph.name}=${form_items.PH}` command = `${command} ${pka_args}` } // Append forcefield options let ff_args if( form_items.FF === 'user' ){ let userff_filename = form_items.USERFFFILE let names_filename = form_items.NAMESFILE if( userff_filename === '' ) userff_filename = this.cli_options.userff.placeholder_text if( names_filename === '' ) names_filename = this.cli_options.usernames.placeholder_text ff_args = `${this.cli_options.ff.name}=${userff_filename} ${this.cli_options.usernames.name}=${names_filename}` }else{ ff_args = `${this.cli_options.ff.name}=${form_items.FF.toUpperCase()}` } command = `${command} ${ff_args}` // Append output forcefield options let ffout_args = '' if( form_items.FFOUT !== 'internal' ){ ffout_args = `${this.cli_options.ffout.name}=${form_items.FFOUT.toUpperCase()}` command = `${command} ${ffout_args}` } // Append ligand options let ligand_args if( form_items.OPTIONS.includes('assignfrommol2')){ if( form_items.LIGANDFILE !== '' ){ ligand_args = `${this.cli_options.ligand.name}=${form_items.LIGANDFILE}` }else{ ligand_args = `${this.cli_options.ligand.name}=${this.cli_options.ligand.placeholder_text}` } command = `${command} ${ligand_args}` } // Append APBS input option let apbsinput_arg if( form_items.OPTIONS.includes('makeapbsin')){ if( pdb_name === '' ){ apbsinput_arg = `${this.cli_options.apbsinput.name}=${this.cli_options.apbsinput.placeholder_text}` }else{ apbsinput_arg = `${this.cli_options.apbsinput.name}=${pdb_name}.in` } command = `${command} ${apbsinput_arg}` } // Append other options let additional_args = '' let to_debump = true let to_opt = true for( let option of Object.keys(this.options_mapping) ){ if( form_items.OPTIONS.includes(option) && ['atomsnotclose', 'optimizeHnetwork'].includes(option) ){ if( option === 'atomsnotclose' ) to_debump = false else if( option === 'optimizeHnetwork' ) to_opt = false }else if( form_items.OPTIONS.includes(option) && !['assignfrommol2', 'makeapbsin'].includes(option) ){ let cli_arg = this.cli_options[ this.options_mapping[option] ].name additional_args = `${additional_args} ${cli_arg}` } } if( to_debump ) command = `${command} ${this.cli_options.debump.name}` if( to_opt ) command = `${command} ${this.cli_options.opt.name}` if( additional_args.length > 0 ) command = `${command} ${additional_args}` // Append PDB/PQR positional arguments let pdb_arg = this.cli_options.pdb_path.placeholder_text let pqr_arg = this.cli_options.pqr_path.placeholder_text if( pdb_name !== "" ){ pdb_arg = `${pdb_name}.pdb` pqr_arg = `${pdb_name}.pqr` } command = `${command} ${pdb_arg} ${pqr_arg}` return command } renderCommandLine(command_string){ return( <div> <Text code copyable> {command_string} </Text> </div> ) } renderCLIPopoverContents(additional_options){ let popover_titles let popover_contents = {} // PDB file let pdb_name = this.getPdbName() let pdb_text if(pdb_name) pdb_text = `${pdb_name}.pdb ${pdb_name}.pqr` else pdb_text = `${this.cli_options.pdb_path.placeholder_text} ${this.cli_options.pqr_path.placeholder_text}` popover_contents['pdb'] = <div> <code> <b>{pdb_text}</b> </code> </div> // Forcefield used let ff_text if( this.state.form_values['FF'] !== 'user' ){ ff_text = <div> {this.cli_options.ff.name}=<b>{this.state.form_values['FF'].toUpperCase()}</b> </div> }else{ let userff_filename = this.state.form_values['USERFFFILE'] let names_filename = this.state.form_values['NAMESFILE'] if( userff_filename === '' ) userff_filename = this.cli_options.userff.placeholder_text if( names_filename === '' ) names_filename = this.cli_options.usernames.placeholder_text ff_text = <div> {this.cli_options.userff.name}=<b>{userff_filename}</b> </div> ff_text = <div> {this.cli_options.userff.name}=<b>{userff_filename}</b> {this.cli_options.usernames.name}=<b>{names_filename}</b> </div> } popover_contents['ff'] = <div> <code> {/* {this.cli_options.ff.name}=<b>{this.state.form_values['FF']}</b> {this.cli_options.ff.name}=<b>{this.state.form_values['PH']}</b> */} {ff_text} </code> </div> // Forcefield output naming scheme let ffout_text if( this.state.form_values['FFOUT'] === 'internal' ){ // ffout_text = <div> {this.cli_options.ffout.name}=<b>{this.state.form_values['FFOUT']}</b> </div> ffout_text = <s> {this.cli_options.ffout.name}=<b>{this.cli_options.ffout.placeholder_text}</b> </s> }else{ ffout_text = <div> {this.cli_options.ffout.name}=<b>{this.state.form_values['FFOUT'].toUpperCase()}</b> </div> } popover_contents['ffout'] = <div> <code> {ffout_text} </code> </div> // pKa Options let pka_text if( this.state.form_values['PKACALCMETHOD'] === 'none' ){ pka_text = <div> <s>{this.cli_options.ph_calc_method.name}=<b>{this.state.form_values['PKACALCMETHOD']}</b> {this.cli_options.with_ph.name}=<b>{this.state.form_values['PH']}</b></s> </div> }else{ pka_text = <div> {this.cli_options.ph_calc_method.name}=<b>{this.state.form_values['PKACALCMETHOD']}</b> {this.cli_options.with_ph.name}=<b>{this.state.form_values['PH']}</b> </div> } popover_contents['pka'] = <div> <code> {pka_text} </code> </div> // Mol2 let ligand_filename = this.state.form_values['LIGANDFILE'] if( ligand_filename === '' ) ligand_filename = this.cli_options.ligand.placeholder_text popover_contents['ligand'] = <div> <code> {this.cli_options.ligand.name}=<b>{ligand_filename}</b> </code> </div> // APBS input file creation let apbsinput_filename = `${pdb_name}.in` if( pdb_name === '' ) apbsinput_filename = this.cli_options.apbsinput.placeholder_text popover_contents['apbsinput'] = <div> <code> {this.cli_options.apbsinput.name}=<b>{apbsinput_filename}</b> </code> </div> // Additional boolean options for( let option of additional_options ){ if( !(option.cli in popover_contents) ){ let cli_arg if( this.state.form_values.OPTIONS.includes(option.value) && ['atomsnotclose', 'optimizeHnetwork'].includes(option.value) ){ // Having these options checked means we don't use in command line cli_arg = <s> {this.cli_options[option.cli].name} </s> } else{ cli_arg = this.cli_options[option.cli].name } popover_contents[option.cli] = <div> <code> {cli_arg} </code> </div> } } return { title: 'CLI', contents: popover_contents } } /** Updates current state of form values when changed */ handleFormChange = (e, nameString) => { let itemName = (nameString === undefined) ? e.target.name : nameString; let itemValue = (e.target !== undefined) ? e.target.value : e; // let itemValue = e.target.value; // let itemName = e.target.name; // Update form values and update CLI string let form_values = this.state.form_values; form_values[itemName] = itemValue; let updated_command = this.getCommandLine( form_values ) console.log(updated_command) this.setState({ form_values: form_values, cli_command: updated_command, }) console.log(itemName +": "+ itemValue); switch(itemName){ case "PDBSOURCE": // this.setState({ // PDBSOURCE: itemValue // }); if( itemValue == "UPLOAD" ){ this.togglePdbUploadButton(true) }else{ this.togglePdbUploadButton(false) } // (itemValue == "UPLOAD") ? this.togglePdbUploadButton(true) : this.togglePdbUploadButton(false); break; case "PDBID": // TODO: 2021/03/01, Elvis - check if PDB ID exists in RCSB this.toggleRegisterButton(true) break; case "PH": // this.setState({ // PH: itemValue // }); break; case "PKACALCMETHOD": // this.setState({ // PKACALCMETHOD: itemValue // }); (itemValue == "pdb2pka") ? this.toggleMustUseParse(true) : this.toggleMustUseParse(false); break; case "FF": // this.setState({ // FF: itemValue // }); (itemValue != "parse")? this.toggleDisableForNoParse(true) : this.toggleDisableForNoParse(false); (itemValue == "user") ? this.toggleUserForcefieldUploadButton(true) : this.toggleUserForcefieldUploadButton(false); this.uncheckTerminusOptions() break; case "FFOUT": // this.setState({ // FFOUT: itemValue // }); break; case "OPTIONS": // this.setState({ // OPTIONS: itemValue // }); (itemValue.includes("assignfrommol2")) ? this.toggleMol2UploadButton(true) : this.toggleMol2UploadButton(false); (["neutralnterminus", "neutralcterminus"].some(opt=>itemValue.includes(opt))) ? this.toggleMustUseParse(true) : this.toggleMustUseParse(false); break; } } /** If user tries submitting job again, raise alert. */ /** Prepare form data to be sent via JSON request */ // handleJobSubmit = (e, self) => { newHandleJobSubmit = values => { // e.preventDefault(); let self = this if(this.state.job_submit) alert("Job is submitted. Redirecting to job status page"); else{ console.log("we're past rule checks. About to submit form:", values) this.setState({ job_submit: true }) // Map additional options to expected values; add to payload let form_and_options = this.state.form_values; for(let option of form_and_options['OPTIONS']){ form_and_options[OptionsMapping[option]] = option } let payload = { form : form_and_options, metadata: { cli: { command: this.state.cli_command } } } /** * Get presigned URLs for files we plan to upload */ // Prepare file list and token request payload let job_file_name = 'pdb2pqr-job.json' let upload_file_names = [] let upload_file_data = {} if( this.state.form_values['PDBFILE'] !== "" ){ upload_file_names.push( this.state.form_values['PDBFILE'] ) upload_file_data[this.state.form_values['PDBFILE'] ] = this.state.pdbFileList[0] } if( this.state.form_values['USERFFFILE'] !== "" ) { upload_file_names.push( this.state.form_values['USERFFFILE'] ) upload_file_data[this.state.form_values['USERFFFILE'] ] = this.state.userffFileList[0] } if( this.state.form_values['NAMESFILE'] !== "" ) { upload_file_names.push( this.state.form_values['NAMESFILE'] ) upload_file_data[this.state.form_values['NAMESFILE'] ] = this.state.namesFileList[0] } if( this.state.form_values['LIGANDFILE'] !== "" ) { upload_file_names.push( this.state.form_values['LIGANDFILE'] ) upload_file_data[this.state.form_values['LIGANDFILE'] ] = this.state.ligandFileList[0] } // Add job config file/data to upload lists upload_file_names.push( job_file_name ) upload_file_data[job_file_name] = JSON.stringify(payload) // Create upload payload let token_request_payload = { file_list: upload_file_names, } console.log( upload_file_names ) // Attempt to upload all input files this.uploadJobFiles(job_file_name, token_request_payload, upload_file_data) } } togglePdbUploadButton(show_upload){ this.setState({ pdb_upload_hidden: !show_upload }); } toggleUserForcefieldUploadButton(show_upload){ // console.log(this.state.ff_upload_hidden) this.setState({ ff_upload_hidden: !show_upload }); } toggleMol2UploadButton(show_upload){ this.setState({ mol2_upload_hidden: !show_upload }); } toggleMustUseParse(do_disable){ if(do_disable){ let form_values = this.state.form_values form_values["FF"] = "parse"; this.setState({ form_values, only_parse: do_disable, // FF: "parse", ff_upload_hidden: true, no_NC_terminus: !do_disable }) } this.setState({ only_parse: do_disable, }) } toggleDisableForNoParse(do_disable){ this.setState({ no_NC_terminus: do_disable }) if(do_disable == false){ this.uncheckTerminusOptions() } } uncheckTerminusOptions(){ let new_OPTIONS = []; // this.state.form_values.OPTIONS.forEach() for(let element of this.state.form_values.OPTIONS){ if( !["neutralnterminus", "neutralcterminus"].some(opt => {return element == opt;}) ){ console.log(element); new_OPTIONS.push(element) } } let form_values = this.state.form_values form_values["OPTIONS"] = new_OPTIONS; this.setState({ form_values }) // this.setState({ // OPTIONS: new_OPTIONS // }) } // togglePdbUploadButton = (e) => { // this.setState({ // pdb_upload_hidden: !this.state.pdb_upload_hidden // }) // } beforeUpload(file, fileList, self, file_type){ console.log("we in beforeUpload") // console.log(file) // console.log(file.name.endsWith('.pdb')) let form_values = self.state.form_values; let cli_command = self.state.cli_command if( file_type === 'pdb' ){ if(!file.name.toLowerCase().endsWith('.pdb')){ message.error('You must upload a PDB (*.pdb) file!'); return false; } else{ form_values['PDBFILE'] = file.name; self.setState({ pdbFileList: fileList.slice(-1), show_register_button: true, }) } } else if( file_type === 'userff' ){ if(!file.name.toLowerCase().endsWith('.dat')){ message.error('You must upload a Force Field (*.dat) file!'); return false; } else{ form_values['USERFFFILE'] = file.name; self.setState({ userffFileList: fileList.slice(-1) }) } } else if( file_type === 'names' ){ if(!file.name.toLowerCase().endsWith('.names')){ message.error('You must upload a Names (*.names) file!'); return false; } else{ form_values['NAMESFILE'] = file.name; self.setState({ namesFileList: fileList.slice(-1) }) } } else if( file_type === 'ligand' ){ if(!file.name.toLowerCase().endsWith('.mol2')){ message.error('You must upload a Ligand (*.mol2) file!'); return false; } else{ form_values['LIGANDFILE'] = file.name; self.setState({ ligandFileList: fileList.slice(-1) }) } } cli_command = self.getCommandLine( form_values ) // update CLI command string self.setState({ form_values, cli_command }) return false; } removeSelectedUploadFile(e, self, form_key, file_list_key){ // Reset form value keys when file is unselected let form_values = this.state.form_values; form_values[form_key] = ''; this.setState({ [file_list_key]: [], form_values: form_values, }) } renderRegistrationButton(){ if( this.state.show_register_button ){ return( <div> For continued support of this server, please register your use of this software: <br/> <a href={window._env_.REGISTRATION_URL} target="_blank" rel="noopener noreferrer"> <Button className='registration-button' type="default" // size='large' // shape='round' icon={<FormOutlined />} onClick={() => sendRegisterClickEvent('pdb2pqr')} > Register Here </Button> </a> <br/> <br/> </div> ) } } renderPdbSourceInput(){ // if(this.state.pdb_upload_hidden) return; let return_element = null if(this.state.form_values.PDBSOURCE == 'ID'){ return_element = <Form.Item name="pdbid" label="Please enter a PDB ID" rules={[ { required: true, message: 'Please input a PDB ID', }, ]}> <Input name="PDBID" placeholder="PDB ID" maxLength={4} onChange={this.handleFormChange}/> {/* <Input name="PDBID" placeholder="PDB ID" maxLength={4}/> */} </Form.Item> } else{ let upload_url = `${window._env_.AUTOFILL_URL}/upload/${this.state.jobid}/pdb2pqr` console.log(upload_url) return_element = <Form.Item name="pdbfile" label="Please upload a PDB file" rules={[ { required: true, message: 'Please upload a PDB file', }, ]} > <Upload name="file" accept=".pdb" action={upload_url} fileList={this.state.pdbFileList} beforeUpload={ (e, fileList) => this.beforeUpload(e, fileList, this, 'pdb')} // onChange={ (e) => this.handleUpload(e, this, 'pdb') } onRemove={ (e) => this.removeSelectedUploadFile(e, this, 'PDBFILE', 'pdbFileList') } > <Button icon={<UploadOutlined />}> Select File </Button> </Upload> </Form.Item> // return_element = <input className='ant-button' type="file" name="PDB" accept=".pdb"/> } // return return_element return ( <Row> <Col span={4}> {return_element} </Col> </Row> ); } handlePdbUpload(info, self){ if (info.file.status !== 'uploading') { console.log('uploading') } if (info.file.status === 'done') { message.success(`${info.file.name} file uploaded successfully`); console.log(`${info.file.name} file uploaded successfully`) // self.setState({ // jobid: info.file.response['job_id'], // }) // self.fetchAutofillData(this.state.jobid); } else if (info.file.status === 'error') { message.error(`${info.file.name} file upload failed.`); } console.log(self.state.pdbFileList) self.setState({ pdbFileList: info.fileList.slice(-1) }) console.log(self.state.pdbFileList) } handleUpload(info, self, file_type){ if (info.file.status !== 'uploading') { console.log('uploading') } if (info.file.status === 'done') { message.success(`${info.file.name} file uploaded successfully`); console.log(`${info.file.name} file uploaded successfully`) } else if (info.file.status === 'error') { message.error(`${info.file.name} file upload failed.`); } if( file_type == 'pdb' ){ self.setState({ pdbFileList: info.fileList.slice(-1), show_register_button: true, }) } else if( file_type == 'userff' ) self.setState({ userffFileList: info.fileList.slice(-1) }) else if( file_type == 'names' ) self.setState({ namesFileList: info.fileList.slice(-1) }) else if( file_type == 'ligand' ) self.setState({ ligandFileList: info.fileList.slice(-1) }) // console.log(self.state.pdbFileList) // console.log(self.state.pdbFileList) } renderUserForcefieldUploadButton(){ // console.log("hello world") if(this.state.ff_upload_hidden) { return; } else{ let upload_url = `${window._env_.AUTOFILL_URL}/upload/${this.state.jobid}/pdb2pqr` let userff_upload = <Upload name="file" accept=".DAT" action={upload_url} fileList={this.state.userffFileList} beforeUpload={ (e, fileList) => this.beforeUpload(e, fileList, this, 'userff')} // onChange={ (e) => this.handleUpload(e, this, 'userff') } onRemove={ (e) => this.removeSelectedUploadFile(e, this, 'USERFFFILE', 'userffFileList') } > <Button icon={<UploadOutlined />}> Select File </Button> </Upload> let names_upload = <Upload name="file" accept=".names" action={upload_url} fileList={this.state.namesFileList} beforeUpload={ (e, fileList) => this.beforeUpload(e, fileList, this, 'names')} // onChange={ (e) => this.handleUpload(e, this, 'names') } onRemove={ (e) => this.removeSelectedUploadFile(e, this, 'NAMESFILE', 'namesFileList') } > <Button icon={<UploadOutlined />}> Select File </Button> </Upload> return( <div> {/* Forcefield file: <input type="file" name="USERFF" /> Names file (*.names): <input type="file" name="USERNAMES" accept=".names" /> */} Forcefield file: {userff_upload} Names file (*.names): {names_upload} </div> ); } } renderMol2UploadButton(){ if(this.state.mol2_upload_hidden) return; else{ let upload_url = `${window._env_.AUTOFILL_URL}/upload/${this.state.jobid}/pdb2pqr` let ligand_upload = <Upload name="file" accept=".mol2" action={upload_url} fileList={this.state.ligandFileList} beforeUpload={ (e, fileList) => this.beforeUpload(e, fileList, this, 'ligand')} // onChange={ (e) => this.handleUpload(e, this, 'ligand') } onRemove={ (e) => this.removeSelectedUploadFile(e, this, 'LIGANDFILE', 'ligandFileList') } > <Button icon={<UploadOutlined />}> Select File </Button> </Upload> return( // <input type="file" name="LIGAND"/> <div> {ligand_upload} </div> ) } } /** Creates and returns the sidebar component. */ renderSidebar(){ return( <Affix offsetTop={80}> {/* <Affix offsetTop={16}> */} <Sider width={200} style={{ background: '#ffffff' }}> <Menu // theme="dark" mode="inline" defaultSelectedKeys={['which_pdb']} style={{ height: '100%', borderRight: 0 }} > <Menu.Item key="which_pdb" ><a href="#pdbid"> PDB ID Entry </a></Menu.Item> <Menu.Item key="which_pka" ><a href="#pka"> pKa Settings (optional) </a></Menu.Item> <Menu.Item key="which_ff" ><a href="#forcefield"> Forcefield </a></Menu.Item> <Menu.Item key="which_output" ><a href="#outputscheme"> Output Naming Scheme </a></Menu.Item> <Menu.Item key="which_options"><a href="#addedoptions"> Additional Options </a></Menu.Item> {/* <Menu.Item key="submission" href="#submission"> Start Job </Menu.Item> */} {/* <Menu.Item key="submission" style={{ background: '#73d13d' }}> Start Job </Menu.Item> */} </Menu> </Sider> </Affix> ) } /** Submission button rendered by default. If submission button's pressed, * button text changes with spinning icon to indicate data has been sent */ // renderSubmitButton(){ // if (!this.state.job_submit) // return <Button type="primary" htmlType="submit"> Start Job </Button> // else // return <div><Button type="primary" htmlType="submit"> Submitting job... </Button> <Spin hidden={!this.state.job_submit}/></div> // } /** Creates and returns the PDB2PQR configuration form. */ renderConfigForm(){ /** Labels for the Additional Options header */ const additionalOptions = [ {name: 'DEBUMP', value: 'atomsnotclose', cli: 'debump', label: 'Ensure that new atoms are not rebuilt too close to existing atoms', disabled: false}, {name: 'OPT', value: 'optimizeHnetwork', cli: 'opt', label: 'Optimize the hydrogen bonding network', disabled: false}, {name: 'LIGANDCHECK', value: 'assignfrommol2', cli: 'ligand', label: 'Assign charges to the ligand specified in a MOL2 file', disabled: false}, {name: 'INPUT', value: 'makeapbsin', cli: 'apbsinput', label: 'Create an APBS input file', disabled: false}, {name: 'CHAIN', value: 'keepchainids', cli: 'chain', label: 'Add/keep chain IDs in the PQR file', disabled: false}, {name: 'WHITESPACE', value: 'insertwhitespace', cli: 'whitespace', label: 'Insert whitespaces between atom name and residue name, between x and y, and between y and z', disabled: false}, // {name: 'TYPEMAP', value: 'maketypemap', cli: 'typemap', label: 'Create Typemap output', disabled: false}, {name: 'NEUTRALN', value: 'neutralnterminus', cli: 'neutraln', label: 'Make the protein\'s N-terminus neutral (requires PARSE forcefield)', disabled: this.state.no_NC_terminus, }, {name: 'NEUTRALC', value: 'neutralcterminus', cli: 'neutralc', label: 'Make the protein\'s C-terminus neutral (requires PARSE forcefield)', disabled: this.state.no_NC_terminus, }, {name: 'DROPWATER', value: 'removewater', cli: 'dropwater', label: 'Remove the waters from the output file', disabled: false}, ] /** Get customized header/label options for CLI popover */ const title_level = 5 const cli_popovers = this.renderCLIPopoverContents(additionalOptions) let cli_builder = null if( this.show_cli === true ){ // cli_builder = this.renderCommandLine(this.state.cli_command) cli_builder = <div> <Title level={title_level}>Command (debug):</Title> <Paragraph> {this.renderCommandLine(this.state.cli_command)} </Paragraph> </div> } /** Builds checkbox options for the Additional Options header */ let optionChecklist = []; additionalOptions.forEach(function(element){ if (element['name'] == 'LIGANDCHECK'){ optionChecklist.push( <div> <Popover placement="left" title={cli_popovers.title} content={cli_popovers.contents.ligand}> <Row> <Checkbox name={element['name']} value={element['value']} onChange={ (e) => this.handleFormChange(e, element['name'])}> {element['label']} </Checkbox> {this.renderMol2UploadButton()} </Row> </Popover> </div> ); } else{ optionChecklist.push( <div> <Popover placement="left" title={cli_popovers.title} content={cli_popovers.contents[element['cli']]}> <Row><Checkbox name={element['name']} value={element['value']} disabled={element['disabled']}> {element['label']} </Checkbox></Row> </Popover> </div> ); } }.bind(this)); /** Styling to have radio buttons appear vertical */ const radioVertStyle = { display: 'block', height: '25px', lineHeight: '30px', } const dummyRequest = ({ file, onSuccess }) => { setTimeout(() => { onSuccess("ok"); }, 0); }; if (this.state.successful_submit){ return this.redirectToStatusPage('pdb2pqr') } else{ return( <Col offset={1}> <Form layout="vertical" onFinish={ this.newHandleJobSubmit } > {/* <Form onSubmit={ (e) => this.handleJobSubmit(e, this) }> */} {cli_builder} {/** Form item for PDB Source (id | upload) */} <Title level={title_level}>PDB Selection</Title> <Form.Item // id="pdbid" label="PDB Source" required={true} > <Radio.Group name="PDBSOURCE" defaultValue={this.state.form_values.PDBSOURCE} buttonStyle='solid' onChange={this.handleFormChange}> <Radio.Button value="ID"> PDB ID {/* <Radio.Button value="ID"> PDB ID:&nbsp;&nbsp; */} {/* <Input name="PDBID" autoFocus="True" placeholder="PDB ID" maxLength={4}/> */} </Radio.Button> <Radio.Button value="UPLOAD"> Upload a PDB file {/* <Radio.Button value="UPLOAD"> Upload a PDB file:&nbsp;&nbsp; */} {/* {this.renderPdbSourceInput()} */} {/* <input type="file" name="PDB" accept=".pdb" hidden={this.state.pdb_upload_hidden}/> */} {/* <Row><Upload name="PDB" accept=".pdb" customRequest={dummyRequest} > <Button> <Icon type="upload" > </Icon> Click to upload </Button> </Upload></Row> */} </Radio.Button> </Radio.Group> </Form.Item> {this.renderPdbSourceInput()} {/* <Form.Item> */} {/* {this.renderPdbSourceInput()} */} {/* </Form.Item> */} {this.renderRegistrationButton()} {/** Form item for pKa option*/} <Title level={title_level}>pKa Options</Title> <Popover placement="bottomLeft" title={cli_popovers.title} content={cli_popovers.contents.pka}> <Form.Item // id="pka" // label="pKa Options" > {/* <Switch checkedChildren="pKa Calculation" unCheckedChildren="pKa Calculation" defaultChecked={true} /><br/> */} pH: <InputNumber name="PH" min={0} max={14} step={0.5} value={this.state.form_values.PH} onChange={(e) => this.handleFormChange(e, 'PH')} /><br/> <Radio.Group name="PKACALCMETHOD" defaultValue={this.state.form_values.PKACALCMETHOD} onChange={this.handleFormChange} > <Radio style={radioVertStyle} id="pka_none" value="none"> No pKa calculation </Radio> <Radio style={radioVertStyle} id="pka_propka" value="propka"> Use PROPKA to assign protonation states at provided pH </Radio> {/* <Tooltip placement="right" title="requires PARSE forcefield"> */} {/* <Radio style={radioVertStyle} id="pka_pdb2pka" value="pdb2pka"> Use PDB2PKA to parametrize ligands and assign pKa values <b>(requires PARSE forcefield)</b> at provided pH </Radio> */} {/* </Tooltip> */} </Radio.Group> </Form.Item> </Popover> {/** Form item for forcefield choice */} <Title level={title_level}>Forcefield Options</Title> <Popover placement="bottomLeft" title={cli_popovers.title} content={cli_popovers.contents.ff}> <Form.Item id="forcefield" label="Please choose a forcefield to use" > <Radio.Group name="FF" value={this.state.form_values.FF} buttonStyle="solid" onChange={this.handleFormChange}> <Radio.Button disabled={this.state.only_parse} value="amber"> AMBER </Radio.Button> <Radio.Button disabled={this.state.only_parse} value="charmm"> CHARMM </Radio.Button> <Radio.Button disabled={this.state.only_parse} value="peoepb"> PEOEPB </Radio.Button> <Radio.Button value="parse"> PARSE </Radio.Button> <Radio.Button disabled={this.state.only_parse} value="swanson">SWANSON </Radio.Button> <Radio.Button disabled={this.state.only_parse} value="tyl06"> TYL06 </Radio.Button> <Radio.Button disabled={this.state.only_parse} value="user"> User-defined Forcefield </Radio.Button> </Radio.Group><br/> {this.renderUserForcefieldUploadButton()} {/* Forcefield file: <input type="file" name="USERFF" /> Names file (*.names): <input type="file" name="USERNAMES" accept=".names" /> */} </Form.Item> </Popover> {/** Form item for output scheme choice*/} <Popover placement="bottomLeft" title={cli_popovers.title} content={cli_popovers.contents.ffout}> <Form.Item id="outputscheme" label="Please choose an output naming scheme to use" > <Radio.Group name="FFOUT" defaultValue={this.state.form_values.FFOUT} buttonStyle="solid" onChange={this.handleFormChange}> <Radio.Button value="internal"> Internal naming scheme </Radio.Button> {/* <Radio.Button value="internal"> Internal naming scheme <Tooltip placement="bottomLeft" title="This is placeholder help text to tell the user what this option means"><Icon type="question-circle" /></Tooltip> </Radio.Button> */} <Radio.Button value="amber"> AMBER </Radio.Button> <Radio.Button value="charmm"> CHARMM </Radio.Button> <Radio.Button value="parse"> PARSE </Radio.Button> <Radio.Button value="peoepb"> PEOEPB </Radio.Button> <Radio.Button value="swanson">SWANSON </Radio.Button> <Radio.Button value="tyl06"> TYL06 </Radio.Button> </Radio.Group> </Form.Item> </Popover> <Title level={title_level}>Additional Options</Title> {/** Form item for choosing additional options (defined earlier) */} <Form.Item id="addedoptions" // label="Additional Options" > <Checkbox.Group name="OPTIONS" value={this.state.form_values.OPTIONS} onChange={(e) => this.handleFormChange(e, "OPTIONS")}> {optionChecklist} </Checkbox.Group> </Form.Item> {/** Where the submission button lies */} <Form.Item> <Col offset={18}> <Affix offsetBottom={100}> <Row> <Col> {this.renderSubmitButton()} {/* </Col> <Col> */} {/* {this.renderRegistrationButton()} */} </Col> </Row> </Affix> </Col> </Form.Item> </Form> </Col> ) } } handleSampleForm = values => { console.log('Success:', values) } handleFailedSampleForm = values => { console.log('Failed:', values) } render(){ return( <Layout id="pdb2pqr" style={{ padding: '16px 0', marginBottom: 5, background: '#fff', boxShadow: "2px 4px 3px #00000033" }}> {/* {this.renderSidebar()} */} <Layout> <Content style={{ background: '#fff', padding: 16, paddingTop: 0, margin: 0, minHeight: 280 }}> <WorkflowHeader currentStep={0} stepList={WORKFLOW_TYPES.PDB2PQR} /><br/> {this.renderConfigForm()} </Content> </Layout> </Layout> ); } }
JavaScript
class AuthenticationService{ getAuthToken(){ return localStorage.getItem('authToken'); } setAuthToken(token){ localStorage.setItem('authToken', token); } removeAuthToken(){ localStorage.removeItem('authToken'); } isAuthenticated(){ /* this method will make sure there is an authenticated user */ /* first get the token from the local storage */ const token = this.getAuthToken(); /* if there is no token, then the user is not authenticated */ if(!token){ return false; } /* if there is a token, make sure this is a valid JWT token */ try{ const decoded = decode(token); /* if the token is valid, then the user is authenticated */ if ( decoded.exp > (Date.now() / 1000) ){ return true; } else return false; }catch(error){ return false; } } logout(){ this.removeAuthToken(); //TO-DO: remove user from local storage //TO-DO: think about redirecting to login/main page } }
JavaScript
class Slider extends React.Component { constructor(props) { super(props); this.state = { itemRows: [], profileLink: "" }; } blogURL = "https://api.rss2json.com/v1/api.json?rss_url=https://dev.to/feed/thepracticaldev"; componentDidMount() { fetch(this.blogURL) .then((res) => res.json()) .then((data) => { // create two-dimensional array with 3 elements per inner array const profileLink = data.feed.link; const res = data.items; //This is an array with the content. No feed, no info about author etc.. const posts = res.filter((item) => item.categories.length > 0); this.setState({ profileLink: profileLink }); const itemRows = []; posts.forEach((item, i) => { item["profilelink"] = this.state.profileLink; // push profile link inside the JSON const row = Math.floor(i / 3); if (!itemRows[row]) itemRows[row] = []; itemRows[row].push(item); }); this.setState({ itemRows: itemRows }); }); } render() { return ( <div className="blog__slider"> {this.state.itemRows.map((row, i) => ( <Row key={i}> {row.map((item, j) => ( <Col key={j} lg="4" md="6" sm="12" className="mb-4"> <BlogCard {...item} /> </Col> ))} </Row> ))} </div> ); } }
JavaScript
class HotSpot extends PlatePoint { constructor({ x, y, plate, radius, strength, lifeRatio = 1 }) { super({ x, y, plate }); this.radius = radius; this.strength = strength * Math.pow(this.radius, 0.6); this.active = false; this.lifeLeft = config.hotSpotLifeLength * radius * lifeRatio; } get alive() { return this.lifeLeft > 0 && !this.outOfBounds; } pointInside(point) { return this.dist(point) < this.radius; } collides(hotSpot) { return this.dist(hotSpot) < this.radius + hotSpot.radius; } heightChange(dist) { const normDist = dist / this.radius; return config.hotSpotStrength * (1 - normDist) * this.strength; } update(timeStep) { this.lifeLeft -= timeStep; } }
JavaScript
class Cookie { /** * Get a cookie by name. If the cookie is found a cookie object is returned otherwise null. * * @param {String} name * @returns cookie object */ static get(name) { if(navigator.cookieEnabled) { var retCookie = null; var cookies = document.cookie.split(";"); var i = 0; while(i < cookies.length) { var cookie = cookies[i]; var eq = cookie.search("="); var cn = cookie.substr(0, eq).trim(); var cv = cookie.substr(eq + 1, cookie.length).trim(); if(cn === name) { retCookie = new CookieInstance(cn, cv); break; } i++; } return retCookie; } } /** * Set a cookie. Name and value parameters are essential on saving the cookie and other parameters are optional. * * @param {string} name * @param {string} value * @param {string} expiresDate * @param {string} cookiePath * @param {string} cookieDomain * @param {boolean} setSecureBoolean */ static set(name, value, expiresDate, cookiePath, cookieDomain, setSecureBoolean) { if(navigator.cookieEnabled) { document.cookie = CookieInstance.create(name, value, expiresDate, cookiePath, cookieDomain, setSecureBoolean).toString(); } } /** * Remove a cookie by name. Method will set the cookie expired and then remove it. * @param {string} name */ static remove(name) { var co = Cookie.get(name); if(!Util.isEmpty(co)) { co.setExpired(); document.cookie = co.toString(); } } }
JavaScript
class CookieInstance { constructor(name, value, expiresDate, cookiePath, cookieDomain, setSecureBoolean) { this.cookieName = !Util.isEmpty(name) && Util.isString(name) ? name.trim() : ""; this.cookieValue = !Util.isEmpty(value) && Util.isString(value) ? value.trim() : ""; this.cookieExpires = !Util.isEmpty(expiresDate) && Util.isString(expiresDate) ? expiresDate.trim() : ""; this.cookiePath = !Util.isEmpty(cookiePath) && Util.isString(cookiePath) ? cookiePath.trim() : ""; this.cookieDomain = !Util.isEmpty(cookieDomain) && Util.isString(cookieDomain) ? cookieDomain.trim() : ""; this.cookieSecurity = !Util.isEmpty(setSecureBoolean) && Util.isBoolean(setSecureBoolean) ? "secure=secure" : ""; } setExpired() { this.cookieExpires = new Date(1970,0,1).toString(); } toString() { return this.cookieName+"="+this.cookieValue+"; expires="+this.cookieExpires+"; path="+this.cookiePath+"; domain="+this.cookieDomain+"; "+this.cookieSecurity; } static create(name, value, expires, cpath, cdomain, setSecure) { return new CookieInstance(name, value, expires, cpath, cdomain, setSecure); } }
JavaScript
class Updatable { constructor(properties) { return this.init(properties); } init(properties = {}) { // -------------------------------------------------- // defaults // -------------------------------------------------- /** * The game objects position vector. Represents the local position of the object as opposed to the [world](api/gameObject#world) position. * @property {Vector} position * @memberof GameObject * @page GameObject */ this.position = Vector(); // -------------------------------------------------- // optionals // -------------------------------------------------- // @ifdef GAMEOBJECT_VELOCITY /** * The game objects velocity vector. * @memberof GameObject * @property {Vector} velocity * @page GameObject */ this.velocity = Vector(); // @endif // @ifdef GAMEOBJECT_ACCELERATION /** * The game objects acceleration vector. * @memberof GameObject * @property {Vector} acceleration * @page GameObject */ this.acceleration = Vector(); // @endif // @ifdef GAMEOBJECT_TTL /** * How may frames the game object should be alive. * @memberof GameObject * @property {Number} ttl * @page GameObject */ this.ttl = Infinity; // @endif // add all properties to the object, overriding any defaults Object.assign(this, properties); } /** * Update the game objects position based on its velocity and acceleration. Calls the game objects [advance()](api/gameObject#advance) function. * @memberof GameObject * @function update * @page GameObject * * @param {Number} [dt] - Time since last update. */ update(dt) { this.advance(dt); } /** * Move the game object by its acceleration and velocity. If you pass `dt` it will multiply the vector and acceleration by that number. This means the `dx`, `dy`, `ddx` and `ddy` should be the how far you want the object to move in 1 second rather than in 1 frame. * * If you override the game objects [update()](api/gameObject#update) function with your own update function, you can call this function to move the game object normally. * * ```js * import { GameObject } from 'kontra'; * * let gameObject = GameObject({ * x: 100, * y: 200, * width: 20, * height: 40, * dx: 5, * dy: 2, * update: function() { * // move the game object normally * this.advance(); * * // change the velocity at the edges of the canvas * if (this.x < 0 || * this.x + this.width > this.context.canvas.width) { * this.dx = -this.dx; * } * if (this.y < 0 || * this.y + this.height > this.context.canvas.height) { * this.dy = -this.dy; * } * } * }); * ``` * @memberof GameObject * @function advance * @page GameObject * * @param {Number} [dt] - Time since last update. * */ advance(dt) { // @ifdef GAMEOBJECT_VELOCITY // @ifdef GAMEOBJECT_ACCELERATION let acceleration = this.acceleration; // @ifdef VECTOR_SCALE if (dt) { acceleration = acceleration.scale(dt); } // @endif this.velocity = this.velocity.add(acceleration); // @endif // @endif // @ifdef GAMEOBJECT_VELOCITY let velocity = this.velocity; // @ifdef VECTOR_SCALE if (dt) { velocity = velocity.scale(dt); } // @endif this.position = this.position.add(velocity); this._pc(); // @endif // @ifdef GAMEOBJECT_TTL this.ttl--; // @endif } // -------------------------------------------------- // velocity // -------------------------------------------------- // @ifdef GAMEOBJECT_VELOCITY /** * X coordinate of the velocity vector. * @memberof GameObject * @property {Number} dx * @page GameObject */ get dx() { return this.velocity.x; } /** * Y coordinate of the velocity vector. * @memberof GameObject * @property {Number} dy * @page GameObject */ get dy() { return this.velocity.y; } set dx(value) { this.velocity.x = value; } set dy(value) { this.velocity.y = value; } // @endif // -------------------------------------------------- // acceleration // -------------------------------------------------- // @ifdef GAMEOBJECT_ACCELERATION /** * X coordinate of the acceleration vector. * @memberof GameObject * @property {Number} ddx * @page GameObject */ get ddx() { return this.acceleration.x; } /** * Y coordinate of the acceleration vector. * @memberof GameObject * @property {Number} ddy * @page GameObject */ get ddy() { return this.acceleration.y; } set ddx(value) { this.acceleration.x = value; } set ddy(value) { this.acceleration.y = value; } // @endif // -------------------------------------------------- // ttl // -------------------------------------------------- // @ifdef GAMEOBJECT_TTL /** * Check if the game object is alive. * @memberof GameObject * @function isAlive * @page GameObject * * @returns {Boolean} `true` if the game objects [ttl](api/gameObject#ttl) property is above `0`, `false` otherwise. */ isAlive() { return this.ttl > 0; } // @endif _pc() {} }
JavaScript
class FeatureExportButton extends PureComponent { static createFeatureString(layer, projection, format) { if (format === KMLFormat) { return KML.writeFeatures(layer, projection); } // eslint-disable-next-line new-cap return new format().writeFeatures(layer.olLayer.getSource().getFeatures(), { featureProjection: projection, }); } static exportFeatures(layer, projection, format) { const now = new Date() .toJSON() .slice(0, 20) .replace(/[.:T-]+/g, ''); const featString = this.createFeatureString(layer, projection, format); const formatString = featString ? featString.match(/<(\w+)\s+\w+.*?>/)[1] : 'xml'; const fileName = `exported_features_${now}.${formatString}`; const charset = document.characterSet || 'UTF-8'; const type = `${ formatString === 'kml' ? 'data:application/vnd.google-earth.kml+xml' : 'data:text/xml' };charset=${charset}`; if (featString) { if (window.navigator.msSaveBlob) { // ie 11 and higher window.navigator.msSaveBlob(new Blob([featString], { type }), fileName); } else { const link = document.createElement('a'); link.download = fileName; link.href = `${type},${encodeURIComponent(featString)}`; link.click(); } } } render() { const { children, layer, projection, format, ...other } = this.props; return ( <div role="button" className="rs-feature-export-button" tabIndex={0} // eslint-disable-next-line react/jsx-props-no-spreading {...other} onClick={() => FeatureExportButton.exportFeatures(layer, projection, format) } onKeyPress={(evt) => evt.which === 13 && FeatureExportButton.exportFeatures(layer, projection, format) } > {children} </div> ); } }
JavaScript
class LimeFunctionMaximum extends LimeFunction { // Constructor constructor(lime, mode) { // Super from function class super(lime, { name: 'maximum', mode }); // Operations this.operations.r = [ 'er(arg{expr[@]})', ]; // Algorithms this.algorithms.set('r(arg{expr[@]})', (step) => { let t = 0; for (let i = 1; i < step.right.length; i++) { t = this.lime.direct([step.right.places[i], '>', step.right.places[t]]).value ? i : t; } step.rus(this.lime.direct([step.right.places[t]])); }); } }
JavaScript
class NzButtonGroupComponent { /** * @param {?} nzUpdateHostClassService * @param {?} elementRef */ constructor(nzUpdateHostClassService, elementRef) { this.nzUpdateHostClassService = nzUpdateHostClassService; this.elementRef = elementRef; this.isInDropdown = false; } /** * @return {?} */ get nzSize() { return this._size; } /** * @param {?} value * @return {?} */ set nzSize(value) { this._size = value; this.setClassMap(); } /** * @return {?} */ setClassMap() { /** @type {?} */ const prefixCls = 'ant-btn-group'; /** @type {?} */ const classMap = { [prefixCls]: true, [`ant-dropdown-button`]: this.isInDropdown, [`${prefixCls}-lg`]: this.nzSize === 'large', [`${prefixCls}-sm`]: this.nzSize === 'small' }; this.nzUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, classMap); } /** * @return {?} */ ngOnInit() { this.setClassMap(); } }
JavaScript
class WebSocketHost extends module.exports.Host { constructor({port, rootDir}) { port = port || 8080; rootDir = rootDir || "./"; super(); const server = http.createServer(function(request, response) { var filePath = rootDir + request.url; var extname = path.extname(filePath); var contentType = { ".js": "text/javascript", ".css": "text/css", ".json": "application/json", ".arrow": "arraybuffer", ".wasm": "application/wasm" }[extname] || "text/html"; fs.readFile(filePath, function(error, content) { if (error) { if (error.code == "ENOENT") { console.error(`404 ${request.url}`); response.writeHead(404); response.end(content, "utf-8"); } else { console.error(`500 ${request.url}`); response.writeHead(500); response.end(); } } else { console.log(`200 ${request.url}`); response.writeHead(200, {"Content-Type": contentType}); response.end(content, extname === ".arrow" ? "user-defined" : "utf-8"); } }); }); this.REQS = {}; this._wss = new WebSocket.Server({noServer: true, perMessageDeflate: true}); this._wss.on("connection", ws => { ws.id = CLIENT_ID_GEN++; ws.on("message", msg => { msg = JSON.parse(msg); this.REQS[msg.id] = ws; try { this.process(msg, ws.id); } catch (e) { console.error(e); } }); ws.on("close", () => { this.clear_views(ws.id); }); ws.on("error", console.error); }); server.on( "upgrade", function upgrade(request, socket, head) { console.log("200 *** websocket upgrade ***"); this._wss.handleUpgrade( request, socket, head, function done(sock) { this._wss.emit("connection", sock, request); }.bind(this) ); }.bind(this) ); server.listen(port); console.log(`Listening on port ${port}`); } post(msg) { this.REQS[msg.id].send(JSON.stringify(msg)); delete this.REQS[msg.id]; } open(name, data, options) { this._tables[name] = module.exports.table(data, options); } }
JavaScript
@connect(({ overview: { connections }, settings: { manualDaemon } }) => ({ manualDaemon, connections, })) class DaemonStatus extends React.Component { render() { const { manualDaemon, connections } = this.props; return ( connections === undefined && ( <span className="dim"> {manualDaemon && <Text id="Alert.ManualDaemonDown" />} {!manualDaemon && ( <> <Text id="Alert.DaemonLoadingWait" /> ... </> )} </span> ) ); } }
JavaScript
class MentorQuestionCollection extends BaseSlugCollection { /** * Creates the Mentor Question collection. */ constructor() { super('MentorQuestion', new SimpleSchema({ question: { type: String }, slugID: { type: SimpleSchema.RegEx.Id, optional: true }, studentID: { type: SimpleSchema.RegEx.Id }, moderated: { type: Boolean }, visible: { type: Boolean }, moderatorComments: { type: String, optional: true }, retired: { type: Boolean, optional: true }, })); } /** * Defines a new MentorSpace question. * @param question the question. * @param slug A unique identifier for this question. * @param student The student that asked this question. * @param moderated If the question is moderated. Defaults to false. * @param visible If the question is visible. Defaults to false. * @param moderatorComments comments (optional). * @param retired the retired status (optional). * @return { String } the docID of this question. */ define({ question, slug, student, moderated = false, visible = false, moderatorComments = '', retired, }) { const studentID = Users.getID(student); const slugID = Slugs.define({ name: slug, entityName: this.getType() }); const docID = this._collection.insert({ question, slugID, studentID, moderated, visible, moderatorComments, retired, }); Slugs.updateEntityID(slugID, docID); return docID; } /** * Updates the moderator question. * @param instance the id or slug (required). * @param question the question (optional). * @param student the student's id or username (optional). * @param moderated boolean (optional). * @param visible boolean (optional). * @param moderatorComments string (optional). * @param retired the new retired status (optional). */ update(instance, { question, student, moderated, visible, moderatorComments, retired, }) { const docID = this.getID(instance); const updateData = {}; if (question) { updateData.question = question; } if (student) { updateData.studentID = Users.getID(student); } if (_.isBoolean(moderated)) { updateData.moderated = moderated; } if (_.isBoolean(visible)) { updateData.visible = visible; } if (moderatorComments) { updateData.moderatorComments = moderatorComments; } if (_.isBoolean(retired)) { updateData.retired = retired; } this._collection.update(docID, { $set: updateData }); } /** * Remove the course instance. * @param docID The docID of the course instance. */ removeIt(docID) { this.assertDefined(docID); // remove the Answers associated with this question MentorAnswers.removeQuestion(docID); // OK, clear to delete. super.removeIt(docID); } /** * Implementation of assertValidRoleForMethod. Asserts that userId is logged in as an Admin, Advisor or * Student. * This is used in the define, update, and removeIt Meteor methods associated with each class. * @param userId The userId of the logged in user. Can be null or undefined * @throws { Meteor.Error } If there is no logged in user, or the user is not an Admin or Advisor. */ assertValidRoleForMethod(userId) { this._assertRole(userId, [ROLE.ADMIN, ROLE.ADVISOR, ROLE.STUDENT]); } getQuestions() { return this._collection.find({}) .fetch() .reverse(); } /** * Checks to see that slugID and studentID are defined. * @returns {Array} An array of error message(s) if either are not defined. */ checkIntegrity() { // eslint-disable-line class-methods-use-this const problems = []; this.find() .forEach(doc => { if (doc.slugID) { if (!Slugs.isDefined(doc.slugID)) { problems.push(`Bad slugID: ${doc.slugID}`); } } if (!Users.isDefined(doc.studentID)) { problems.push(`Bad studentID: ${doc.studentID}`); } }); return problems; } /** * Returns an object representing the MentorQuestion docID in a format acceptable to define(). * @param docID The docID of a MentorQuestion. * @returns { Object } An object representing the definition of docID. */ dumpOne(docID) { const doc = this.findDoc(docID); const { question } = doc; let slug; if (doc.slugID) { slug = Slugs.getNameFromID(doc.slugID); } const student = Users.getProfile(doc.studentID).username; const { moderated } = doc; const { visible } = doc; const { moderatorComments } = doc; const { retired } = doc; return { question, slug, student, moderated, visible, moderatorComments, retired, }; } }
JavaScript
class Command { constructor(service, repository) { this.repository = repository; this.service = service; } bind(event, id, fn) { let ele = document.getElementById(id); let repository = this.repository; let service = this.service; ele.addEventListener(event, function () { fn(service, repository); }); } }
JavaScript
class SecurityCenter extends ServiceClient { /** * Create a SecurityCenter. * @param {credentials} credentials - Credentials needed for the client to connect to Azure. * @param {string} subscriptionId - Azure subscription ID * @param {string} ascLocation - The location where ASC stores the data of the subscription. can be retrieved from Get locations * @param {string} [baseUri] - The base URI of the service. * @param {object} [options] - The parameter options * @param {Array} [options.filters] - Filters to be added to the request pipeline * @param {object} [options.requestOptions] - Options for the underlying request object * {@link https://github.com/request/request#requestoptions-callback Options doc} * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * @param {string} [options.acceptLanguage] - The preferred language for the response. * @param {number} [options.longRunningOperationRetryTimeout] - The retry timeout in seconds for Long Running Operations. Default value is 30. * @param {boolean} [options.generateClientRequestId] - Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ constructor(credentials, subscriptionId, ascLocation, baseUri, options) { if (credentials === null || credentials === undefined) { throw new Error('\'credentials\' cannot be null.'); } if (subscriptionId === null || subscriptionId === undefined) { throw new Error('\'subscriptionId\' cannot be null.'); } if (ascLocation === null || ascLocation === undefined) { throw new Error('\'ascLocation\' cannot be null.'); } if (!options) options = {}; super(credentials, options); this.acceptLanguage = 'en-US'; this.longRunningOperationRetryTimeout = 30; this.generateClientRequestId = true; this.baseUri = baseUri; if (!this.baseUri) { this.baseUri = 'https://management.azure.com'; } this.credentials = credentials; this.subscriptionId = subscriptionId; this.ascLocation = ascLocation; let packageInfo = this.getPackageJsonInfo(__dirname); this.addUserAgentInfo(`${packageInfo.name}/${packageInfo.version}`); if(options.acceptLanguage !== null && options.acceptLanguage !== undefined) { this.acceptLanguage = options.acceptLanguage; } if(options.longRunningOperationRetryTimeout !== null && options.longRunningOperationRetryTimeout !== undefined) { this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout; } if(options.generateClientRequestId !== null && options.generateClientRequestId !== undefined) { this.generateClientRequestId = options.generateClientRequestId; } this.pricings = new operations.Pricings(this); this.securityContacts = new operations.SecurityContacts(this); this.workspaceSettings = new operations.WorkspaceSettings(this); this.autoProvisioningSettings = new operations.AutoProvisioningSettings(this); this.compliances = new operations.Compliances(this); this.advancedThreatProtection = new operations.AdvancedThreatProtection(this); this.settings = new operations.Settings(this); this.informationProtectionPolicies = new operations.InformationProtectionPolicies(this); this.operations = new operations.Operations(this); this.locations = new operations.Locations(this); this.tasks = new operations.Tasks(this); this.alerts = new operations.Alerts(this); this.discoveredSecuritySolutions = new operations.DiscoveredSecuritySolutions(this); this.jitNetworkAccessPolicies = new operations.JitNetworkAccessPolicies(this); this.externalSecuritySolutions = new operations.ExternalSecuritySolutions(this); this.topology = new operations.Topology(this); this.allowedConnections = new operations.AllowedConnections(this); this.models = models; msRest.addSerializationMixin(this); } }
JavaScript
class NrViewTemplate { /** * Initializes the view template after first request to new session or each time for non-session requests. * * This is called once after NorJS has initialized the template using component's bindings configuration. * * It can return a promise, in which case the promise will be waited until the request is done. */ init () {} /** * Destroys the view template when session is destroyed, or for non-session requests each time the request ends. * * You should delete any references to outside objects here. * * You may start asynchronic operations, but you should not return a promise. Deletion should be instant. * * The same object should not be used after it has been destroyed. */ destroy () {} /** * Renders the view. This is called once for each request. * * @param result {*} The result from the controller * @returns {NrModel} */ render (result) {} }
JavaScript
class App extends React.Component { handleHome(){ this.props.router.push("/"); } handleAboutUs(){ this.props.router.push("/about"); } handlelogin(){ this.props.router.push("/login"); } handlelogout(){ this.props.router.push("/logout"); } handleMyPage(){ this.props.router.push("/mypage"); } componentWillReceiveProps(nextProps){ // if(nextProps.user.loggedIn) Router.browserHistory.push("/about"); } button(){ if(this.props.user.loggedIn){ return( <NavbarButton lable="Logout" Icon={<i className="sign out icon"></i>} handle={this.handlelogout.bind(this)}/> ); } return( <NavbarButton lable="Login" Icon={<i className="sign in calendar icon"></i>} handle={this.handlelogin.bind(this)}/> ) } profilebutton(){ if(this.props.user.loggedIn){ return( <div> <NavbarButton lable="MyPage" Icon={<i className="user icon"></i>} handle={this.handleMyPage.bind(this)}/> </div> ); } } profileDivider(){ if(this.props.user.loggedIn){ return( <ToolbarSeparator style={{ backgroundColor: "#607d8b", marginLeft:'2px', marginLeft:"0px", }}/> ); } } render() { return ( <div> <Toolbar style={styles.bar}> <ToolbarGroup> <FlatButton primary={true} labelStyle={{textTransform:'none', fontSize :'20px', paddingLeft:'0px', paddingRight: '0px', }} disableTouchRipple = {true} hoverColor="#37474f" onTouchTap = {this.handleHome.bind(this)} ><i className="home icon large"></i></FlatButton> <NavbarButton lable="Home" Icon={<i className="home icon"></i>} handle={this.handleHome.bind(this)}/> <ToolbarSeparator style={{ backgroundColor: "#607d8b", marginLeft:'2px', }}/> <NavbarButton lable="About Us" handle={this.handleAboutUs.bind(this)} Icon={<i className="info icon"></i>}><i className="add to calendar icon"></i></NavbarButton> <ToolbarSeparator style={{ backgroundColor: "#607d8b", marginLeft:'2px', marginLeft:"0px", }}/> {this.profilebutton()} {this.profileDivider()} {this.button()} </ToolbarGroup> </Toolbar> {this.props.children} </div> ); } }
JavaScript
class RkCalendar extends RkComponent { static propTypes = { type: PropTypes.oneOf([ BaseSelectionStrategy.description, RangeSelectionStrategy.description, ]), layout: PropTypes.oneOf([ VerticalLayout.description, HorizontalLayout.description, ]), min: PropTypes.instanceOf(Date).isRequired, max: PropTypes.instanceOf(Date).isRequired, boundingMonth: PropTypes.bool, filter: PropTypes.func, renderDay: PropTypes.func, onSelect: PropTypes.func, onVisibleMonthChanged: PropTypes.func, }; static defaultProps = { type: BaseSelectionStrategy.description, layout: VerticalLayout.description, boundingMonth: true, renderDay: undefined, filter: (() => true), onSelect: (() => null), onVisibleMonthChanged: (() => null), }; componentName = 'RkCalendar'; typeMapping = { container: {}, header: {}, month: {}, }; state = { selected: { start: today(), end: undefined, }, visibleMonth: today(), selectionStrategy: BaseSelectionStrategy, }; containerRef = undefined; constructor(props) { super(props); this.state.selectionStrategy = this.getSelectionStrategy(props.type); } /** * Override point. * Makes typeMapping keys be returned as objects instead of arrays */ getElementStyle(styles, element, key, value) { const style = styles[element] || {}; const styleKey = super.getElementStyleKey(element, style, key); style[styleKey.name] = super.getStyleValue(value); return style; } setContainerRef = (ref) => { this.containerRef = ref; }; onContainerLayoutCompleted = () => { const scrollToToday = () => { this.scrollToDate(today(), { animated: false }); }; setTimeout(scrollToToday, 100); }; onVisibleMonthChanged = (date) => { this.state.visibleMonth = date; this.props.onVisibleMonthChanged(date); }; /** * Scrolls to passed month index * * @param {object} params - should contain index property * and additional scroll parameters (optional) */ scrollToIndex(params) { this.containerRef.scrollToIndex(params); } /** * Scrolls to month containing passed date * * @param {Date} date - date to scroll to * @param {object} params - additional scroll parameters (optional) */ scrollToDate(date, params = defaultScrollParams) { this.containerRef.scrollToDate(date, params); } /** * Scrolls to month containing current date * * @param {object} params - additional scroll parameters (optional) */ scrollToToday(params = defaultScrollParams) { this.scrollToDate(today(), params); } /** * Scrolls to month going before visible * * @param {object} params - additional scroll parameters (optional) */ scrollToPreviousMonth(params = defaultScrollParams) { const currentMonth = this.state.visibleMonth; this.scrollToDate(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1), params); } /** * Scrolls to month going after visible * * @param {object} params - additional scroll parameters (optional) */ scrollToNextMonth(params = defaultScrollParams) { const currentMonth = this.state.visibleMonth; this.scrollToDate(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1), params); } onDaySelect = (date) => { const selectionState = this.state.selectionStrategy.getStateFromSelection(this.state, date); this.setState(selectionState); this.props.onSelect(date); }; getSelectionStrategy = (type) => { switch (type) { case BaseSelectionStrategy.description: return BaseSelectionStrategy; case RangeSelectionStrategy.description: return RangeSelectionStrategy; default: return BaseSelectionStrategy; } }; getLayout = (type) => { switch (type) { case VerticalLayout.description: return VerticalLayout; case HorizontalLayout.description: return HorizontalLayout; default: return VerticalLayout.layout; } }; render() { return ( <RkCalendarView style={this.defineStyles()} ref={this.setContainerRef} selectionStrategy={this.state.selectionStrategy} layout={this.getLayout(this.props.layout)} min={this.props.min} max={this.props.max} selected={this.state.selected} boundingMonth={this.props.boundingMonth} renderDay={this.props.renderDay} filter={this.props.filter} onSelect={this.onDaySelect} onLayoutCompleted={this.onContainerLayoutCompleted} onVisibleMonthChanged={this.onVisibleMonthChanged} /> ); } }
JavaScript
class Moon extends Planet { /** * constructor - Construct a Moon * * @param {number} x X coordinate of spawn * @param {number} y Y coordinate of spawn */ constructor(x, y) { super(x, y); } }
JavaScript
class YouPakMirrorFinder { constructor() {} findMirrors(url, callback) { if (Utils.isYoutubeVideoLink(url)) { console.log('>> Trying YouPak <<'); let request = this.createRequestToYouPak(url); request.onreadystatechange = function () { if (Utils.isXMLHttpRequestDone(request)) { let htmlDoc = Utils.getHTMLDocumentFromText(request.responseText), videoTag = htmlDoc.getElementsByTagName("video")[0], videoSources; if (videoTag === undefined) { callback(new NoVideoFoundException()); return; } videoSources = videoTag.children; if (videoSources.length === 0) { callback(new NoVideoFoundException()); return; } console.log('Video Sources: ' + videoSources.length); const links = Array.prototype.slice.call(videoSources).map(function (element) { return element.src; }); let numberLinksTested = 0; let validLinkFound = false; for (const link of links) { let r = new XMLHttpRequest(); r.open("GET", link, true); r.onreadystatechange = function () { if (validLinkFound) { return; } numberLinksTested += 1; if (this.status === 200) { validLinkFound = true; callback( [ { 'resolution': 720, 'link': this.responseURL } ] ); return; } if (numberLinksTested === links.length) { callback(new NoVideoFoundException()); } }; r.send(); } } }; request.send(); } else { throw new InvalidYouTubeVideoURLException(); } }; createRequestToYouPak(url) { let request = new XMLHttpRequest(); request.open("GET", url.replace("tube", "pak"), true); return request; }; }
JavaScript
class QueryBuilder extends OrderedStringKeyDictionary { constructor(query, decodeValues = true) { super(); this.importQuery(query, decodeValues); } static init(query, decodeValues = true) { return new QueryBuilder(query, decodeValues); } importQuery(query, decodeValues = true) { if (Type.isString(query)) { this.importFromString(query, decodeValues); } else if (isEnumerableOrArrayLike(query)) { this.importEntries(query); } else { this.importMap(query); } return this; } /** * Property parses the components of an URI into their values or array of values. * @param values * @param deserialize * @param decodeValues * @returns {QueryBuilder} */ importFromString(values, deserialize = true, decodeValues = true) { const _ = this; parse(values, (key, value) => { if (_.containsKey(key)) { const prev = _.getValue(key); if ((prev) instanceof (Array)) prev.push(value); else _.setValue(key, [prev, value]); } else _.setValue(key, value); }, deserialize, decodeValues); return this; } /** * Returns the encoded URI string */ encode(prefixIfNotEmpty) { return encode(this, prefixIfNotEmpty); } toString() { return this.encode(); } }
JavaScript
class SetGoal extends React.Component { constructor(props) { super(props); this.state = { calories: 0, protein: 0, carbs: 0, fats: 0, error: '', visible: true } }; onCaloriesChange = (e) => { const calories = e.target.value; if (!calories || calories.match(/^[0-9]*$/)){ this.setState(() => ({ calories })); } }; onCarbsChange = (e) => { const carbs = e.target.value; this.setState({ carbs }); }; onFatsChange = (e) => { const fats = e.target.value; this.setState({ fats }); }; onProteinChange = (e) => { const protein = e.target.value; this.setState({ protein }); }; onSubmit = (e) => { e.preventDefault(); if (this.state.calories && this.state.protein && this.state.carbs && this.state.fats) { const calories = parseInt(this.state.calories); const protein = parseInt(this.state.protein); const carbs = parseInt(this.state.carbs); const fats = parseInt(this.state.fats); this.props.startSetGoal(this.props.currentUser.id, calories, protein, carbs, fats); const form = document.getElementById('setGoalForm'); form.reset(); } else { this.setState({error: 'Please Fill Out All of The Goals!'}) } }; onClick = () => { if (this.state.visible) { this.setState({ visible: false }); this.props.sendBoolean(false, 'setGoalNotVisible'); } else { this.setState({ visible: true }); this.props.sendBoolean(true, 'setGoalNotVisible'); } } render() { return ( <div className='calorie-input-wrapper'> <div className='calorie-input-container'> <button className='set-calorie-button' onClick={this.onClick}>Set Calorie Goal</button> <div className='log-calorie-wrapper'> <div className='log-calorie-container' hidden={this.state.visible}> {this.state.error && <p>{this.state.error}</p>} <form id='setGoalForm' onSubmit={this.onSubmit}> <input className='add-calorie-input' type='text-input' onChange={this.onCaloriesChange} type='text' placeholder='Calories'/> <input className='add-calorie-input' type='text-input' onChange={this.onProteinChange} type='text' placeholder='Protein'/> <input className='add-calorie-input' type='text-input' onChange={this.onCarbsChange} type='text' placeholder='Carbs'/> <input className='add-calorie-input' type='text-input' onChange={this.onFatsChange} type='text' placeholder='Fats'/> <button className='submit-calorie-button'>Set Goal</button> </form> </div> </div> </div> </div> ) }; }
JavaScript
class MessageStripDesign extends DataType { static isValid(value) { return !!MessageStripDesigns[value]; } }
JavaScript
class TargetlessControl extends ObjectControl { /** * Constructor * * @param {boolean} [enabled=true] Whether the control will be enabled initially. */ constructor( controlCategories, enabled ) { super( controlCategories, enabled ); this._isActive = false; } /** * Signal the control that it is in the new control set when the * ObjectControlManager changes control sets. * * <p>Normally a call to this method will cause the controller to * remember something about the event in its state and to add * some or all of the objects in the intersections to the * control's set of controlled objects. * * <p>The controller will dispatch an event of the form <code>{ * type: 'start', objects: Object3D[] }</code>, where the * <code>objects</code> field will be an array of all objects * taken under control. A listener could use the events to * highlight or show the position or rotation of the objects * taken under control. * * @param {UIEvent} event - Probably a <code>mousedown</code>, a * <code>touchstart</code>, or a wheel event. * @param intersections - an array of intersections returned * by <code>THREE.Raycaster.intersectObjects()</code>. * * @returns {boolean} <code>true</code> (stop) if we should * stop processing this instance of the event using controls * in our list, <code>false if we should continue. */ startHandler( event /* , intersections */ ) { if ( ! this.enabled ) return; if ( this._doStart( event ) ) { this._isActive = true; this.dispatchEvent( { type: 'start', objects: [] } ); return true; } return false; } _doStart( /* event */ ) { return true; } /** * Handle an event that indicates a change in a pointer or wheel * value. Typically this change in value will trigger some * change in the properties of the objects under control. * * <p>A call to this method will dispatch an event of the form * <code>{ type: 'change', objects: Object3D[] }</code>. * * <p>If some of the objects under control are not contained in * the intersections passed to thie method, an 'end' event is * sent for them and they are removed from the set of objects * under control. If any new objects appear among the * intersections, they <i>may</i> be taken under control as in * <code>mousedownHandler</code> and a 'start' event is sent * for those that are taken under control. * * @param {MouseEvent} event - a mouse move event. * @param intersections - an array of intersections returned * by <code>THREE.Raycaster.intersectObjects()</code>. * * @returns {boolean} <code>true</code> (stop) if we should * stop processing this instance of the event using controls * in our list, <code>false if we should continue. */ changeHandler( event /* , intersections */ ) { if ( ! ( this.enabled && this._isActive ) ) return; if ( this._doChange( event ) ) { this.dispatchEvent( { type: 'change', objects: [] } ); return true; } return false; } _doChange( /* event */ ) { return true; } /** * Notify the control that it is leaving the active control set. * Usually the control will just reset itself to its initial * state, but the event that causes it to leave the control set * and the intersections are provided in case the control should * finalize its actions somehow. * * <p>This method will be called on each control in the old * control set before startHandler is called on the controls in * the new control set. * * <p>If there are any objects under control, send an event * <code>{ type: 'end', objects: Object3D[] }</code> where the * <code>objects</code> field is an array of all objects * under control. * * <p>No intersections are sent with this call because a) they * should not be relevant to this control; and b) they are not * always available, for example if a <code>mouseout</code> event * triggers a cancel. * * @param {UIEvent} event - The event that is causing this * control to leave the control set. Normally <code>event</code> * will be either a <code>mouseup</code> or <code>mouseout</code> * <code>MouseEvent</code> or a <code>touchend</code> * <code>TouchEvent</code>. */ endHandler( event ) { this._isActive = false; this._doEnd(); return this._isActive; } /** * Perform any finalization that the endHandler needs to do. The * triggering event will be passed to it. Usually does not need * to be overridden. */ _doEnd( /* event */ ) {} }
JavaScript
class Menu extends Component { onClickClose() { const menu = document.getElementById("drawer-menu") menu.classList.add("menu-hidden") } /** * Render method */ render() { return ( <MenuWrapper id="drawer-menu" className="menu-hidden"> <div className="menu-close-icon"> <FaTimes onClick={() => this.onClickClose()} /> </div> <div> <a className={"custom-link"} href={"https://crowd.rocktech.mx/proyectos-de-inversion"}> CROWDFUNDING </a> </div> <div> <a className={"custom-link"} href={"https://hub.rocktech.mx/"}> HUB </a> </div> <div className="bottom"> <BigLogo location="menu" /> </div> </MenuWrapper> ) } }
JavaScript
class OpenElementStack { constructor(document, treeAdapter, handler) { this.treeAdapter = treeAdapter; this.handler = handler; this.items = []; this.tagIDs = []; this.stackTop = -1; this.tmplCount = 0; this.currentTagId = html_js_1.TAG_ID.UNKNOWN; this.current = document; } get currentTmplContentOrNode() { return this._isInTemplate() ? this.treeAdapter.getTemplateContent(this.current) : this.current; } //Index of element _indexOf(element) { return this.items.lastIndexOf(element, this.stackTop); } //Update current element _isInTemplate() { return this.currentTagId === html_js_1.TAG_ID.TEMPLATE && this.treeAdapter.getNamespaceURI(this.current) === html_js_1.NS.HTML; } _updateCurrentElement() { this.current = this.items[this.stackTop]; this.currentTagId = this.tagIDs[this.stackTop]; } //Mutations push(element, tagID) { this.stackTop++; this.items[this.stackTop] = element; this.current = element; this.tagIDs[this.stackTop] = tagID; this.currentTagId = tagID; if (this._isInTemplate()) { this.tmplCount++; } this.handler.onItemPush(element, tagID, true); } pop() { const popped = this.current; if (this.tmplCount > 0 && this._isInTemplate()) { this.tmplCount--; } this.stackTop--; this._updateCurrentElement(); this.handler.onItemPop(popped, true); } replace(oldElement, newElement) { const idx = this._indexOf(oldElement); this.items[idx] = newElement; if (idx === this.stackTop) { this.current = newElement; } } insertAfter(referenceElement, newElement, newElementID) { const insertionIdx = this._indexOf(referenceElement) + 1; this.items.splice(insertionIdx, 0, newElement); this.tagIDs.splice(insertionIdx, 0, newElementID); this.stackTop++; if (insertionIdx === this.stackTop) { this._updateCurrentElement(); } this.handler.onItemPush(this.current, this.currentTagId, insertionIdx === this.stackTop); } popUntilTagNamePopped(tagName) { let targetIdx = this.stackTop + 1; do { targetIdx = this.tagIDs.lastIndexOf(tagName, targetIdx - 1); } while (targetIdx > 0 && this.treeAdapter.getNamespaceURI(this.items[targetIdx]) !== html_js_1.NS.HTML); this.shortenToLength(targetIdx < 0 ? 0 : targetIdx); } shortenToLength(idx) { while (this.stackTop >= idx) { const popped = this.current; if (this.tmplCount > 0 && this._isInTemplate()) { this.tmplCount -= 1; } this.stackTop--; this._updateCurrentElement(); this.handler.onItemPop(popped, this.stackTop < idx); } } popUntilElementPopped(element) { const idx = this._indexOf(element); this.shortenToLength(idx < 0 ? 0 : idx); } popUntilPopped(tagNames, targetNS) { const idx = this._indexOfTagNames(tagNames, targetNS); this.shortenToLength(idx < 0 ? 0 : idx); } popUntilNumberedHeaderPopped() { this.popUntilPopped(NAMED_HEADERS, html_js_1.NS.HTML); } popUntilTableCellPopped() { this.popUntilPopped(TABLE_CELLS, html_js_1.NS.HTML); } popAllUpToHtmlElement() { //NOTE: here we assume that the root <html> element is always first in the open element stack, so //we perform this fast stack clean up. this.tmplCount = 0; this.shortenToLength(1); } _indexOfTagNames(tagNames, namespace) { for (let i = this.stackTop; i >= 0; i--) { if (tagNames.includes(this.tagIDs[i]) && this.treeAdapter.getNamespaceURI(this.items[i]) === namespace) { return i; } } return -1; } clearBackTo(tagNames, targetNS) { const idx = this._indexOfTagNames(tagNames, targetNS); this.shortenToLength(idx + 1); } clearBackToTableContext() { this.clearBackTo(TABLE_CONTEXT, html_js_1.NS.HTML); } clearBackToTableBodyContext() { this.clearBackTo(TABLE_BODY_CONTEXT, html_js_1.NS.HTML); } clearBackToTableRowContext() { this.clearBackTo(TABLE_ROW_CONTEXT, html_js_1.NS.HTML); } remove(element) { const idx = this._indexOf(element); if (idx >= 0) { if (idx === this.stackTop) { this.pop(); } else { this.items.splice(idx, 1); this.tagIDs.splice(idx, 1); this.stackTop--; this._updateCurrentElement(); this.handler.onItemPop(element, false); } } } //Search tryPeekProperlyNestedBodyElement() { //Properly nested <body> element (should be second element in stack). return this.stackTop >= 1 && this.tagIDs[1] === html_js_1.TAG_ID.BODY ? this.items[1] : null; } contains(element) { return this._indexOf(element) > -1; } getCommonAncestor(element) { const elementIdx = this._indexOf(element) - 1; return elementIdx >= 0 ? this.items[elementIdx] : null; } isRootHtmlElementCurrent() { return this.stackTop === 0 && this.tagIDs[0] === html_js_1.TAG_ID.HTML; } //Element in scope hasInScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.tagIDs[i]; const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (tn === tagName && ns === html_js_1.NS.HTML) { return true; } if (SCOPING_ELEMENT_NS.get(tn) === ns) { return false; } } return true; } hasNumberedHeaderInScope() { for (let i = this.stackTop; i >= 0; i--) { const tn = this.tagIDs[i]; const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if ((0, html_js_1.isNumberedHeader)(tn) && ns === html_js_1.NS.HTML) { return true; } if (SCOPING_ELEMENT_NS.get(tn) === ns) { return false; } } return true; } hasInListItemScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.tagIDs[i]; const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (tn === tagName && ns === html_js_1.NS.HTML) { return true; } if (((tn === html_js_1.TAG_ID.UL || tn === html_js_1.TAG_ID.OL) && ns === html_js_1.NS.HTML) || SCOPING_ELEMENT_NS.get(tn) === ns) { return false; } } return true; } hasInButtonScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.tagIDs[i]; const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (tn === tagName && ns === html_js_1.NS.HTML) { return true; } if ((tn === html_js_1.TAG_ID.BUTTON && ns === html_js_1.NS.HTML) || SCOPING_ELEMENT_NS.get(tn) === ns) { return false; } } return true; } hasInTableScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.tagIDs[i]; const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (ns !== html_js_1.NS.HTML) { continue; } if (tn === tagName) { return true; } if (tn === html_js_1.TAG_ID.TABLE || tn === html_js_1.TAG_ID.TEMPLATE || tn === html_js_1.TAG_ID.HTML) { return false; } } return true; } hasTableBodyContextInTableScope() { for (let i = this.stackTop; i >= 0; i--) { const tn = this.tagIDs[i]; const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (ns !== html_js_1.NS.HTML) { continue; } if (tn === html_js_1.TAG_ID.TBODY || tn === html_js_1.TAG_ID.THEAD || tn === html_js_1.TAG_ID.TFOOT) { return true; } if (tn === html_js_1.TAG_ID.TABLE || tn === html_js_1.TAG_ID.HTML) { return false; } } return true; } hasInSelectScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.tagIDs[i]; const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (ns !== html_js_1.NS.HTML) { continue; } if (tn === tagName) { return true; } if (tn !== html_js_1.TAG_ID.OPTION && tn !== html_js_1.TAG_ID.OPTGROUP) { return false; } } return true; } //Implied end tags generateImpliedEndTags() { while (IMPLICIT_END_TAG_REQUIRED.has(this.currentTagId)) { this.pop(); } } generateImpliedEndTagsThoroughly() { while (IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) { this.pop(); } } generateImpliedEndTagsWithExclusion(exclusionId) { while (this.currentTagId !== exclusionId && IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) { this.pop(); } } }
JavaScript
class UnsupportedArrayElementTypeAnnotationParserError extends ParserError { constructor( hasteModuleName, arrayElementTypeAST, arrayType, invalidArrayElementType, ) { super( hasteModuleName, arrayElementTypeAST, `${arrayType} element types cannot be '${invalidArrayElementType}'.`, ); } }
JavaScript
class UnsupportedObjectPropertyTypeAnnotationParserError extends ParserError { constructor(hasteModuleName, propertyAST, invalidPropertyType) { let message = `'ObjectTypeAnnotation' cannot contain '${invalidPropertyType}'.`; if (invalidPropertyType === 'ObjectTypeSpreadProperty') { message = "Object spread isn't supported in 'ObjectTypeAnnotation's."; } super(hasteModuleName, propertyAST, message); } }
JavaScript
class UnnamedFunctionParamParserError extends ParserError { constructor(functionParam, hasteModuleName) { super( hasteModuleName, functionParam, 'All function parameters must be named.', ); } }
JavaScript
class NodeSettings extends PureComponent { static propTypes = { /** @ignore */ setSetting: PropTypes.func.isRequired, /** @ignore */ t: PropTypes.func.isRequired, /** @ignore */ generateAlert: PropTypes.func.isRequired, /** @ignore */ node: PropTypes.string.isRequired, /** @ignore */ theme: PropTypes.object.isRequired, /** @ignore */ isSendingTransfer: PropTypes.bool.isRequired, }; constructor() { super(); this.onNodeSelection = this.onNodeSelection.bind(this); this.onAddCustomNode = this.onAddCustomNode.bind(this); } componentDidMount() { leaveNavigationBreadcrumb('NodeSettings'); } /** * Navigates to node selection setting screen * * @method onNodeSelection */ onNodeSelection() { if (this.props.isSendingTransfer) { this.generateChangeNodeAlert(); } else { this.props.setSetting('nodeSelection'); } } /** * Navigates to add custom node setting screen * * @method onAddCustomNode */ onAddCustomNode() { if (this.props.isSendingTransfer) { this.generateChangeNodeAlert(); } else { this.props.setSetting('addCustomNode'); } } /** * Generates an alert if a user tries to navigate to change node or add custom node screen when a transaction is in progress * * @method generateChangeNodeAlert */ generateChangeNodeAlert() { this.props.generateAlert( 'error', this.props.t('settings:cannotChangeNode'), `${this.props.t('settings:cannotChangeNodeWhileSending')} ${this.props.t( 'settings:transferSendingExplanation', )}`, ); } /** * Render setting rows * * @method renderSettingsContent * @returns {function} */ renderSettingsContent() { const { theme, t, node } = this.props; const rows = [ { name: t('selectNode'), icon: 'node', function: this.onNodeSelection, currentSetting: node }, { name: t('addCustomNode'), icon: 'plusAlt', function: this.onAddCustomNode }, { name: 'back', function: () => this.props.setSetting('advancedSettings') }, ]; return renderSettingsRows(rows, theme); } render() { return <View style={styles.container}>{this.renderSettingsContent()}</View>; } }
JavaScript
class Checkbox extends PureComponent { render() { const { className, onClick, disabled, checked, label } = this.props; const classes = classNames('c_checkbox__box', { 'c_checkbox__box--disabled' : disabled, 'c_checkbox__box--checked' : checked, }, className ); return ( <div className="c_checkbox"> <input type="checkbox" onClick={disabled ? _noop : onClick} className={classes} disabled={disabled} /> { label ? <div className="c_checkbox__label">{label}</div> : null } </div> ); } }
JavaScript
class Tree { /** * Creates a Tree Object */ constructor() { } /** * Creates a node/edge structure and renders a tree layout based on the input data * * @param treeData an array of objects that contain parent/child information. */ createTree(treeData) { // ******* TODO: PART VI ******* //Create a tree and give it a size() of 800 by 300. //Create a root for the tree using d3.stratify(); //Add nodes and links to the tree. } /** * Updates the highlighting in the tree based on the selected team. * Highlights the appropriate team nodes and labels. * * @param row a string specifying which team was selected in the table. */ updateTree(row) { // ******* TODO: PART VII ******* } /** * Removes all highlighting from the tree. */ clearTree() { // ******* TODO: PART VII ******* // You only need two lines of code for this! No loops! } }
JavaScript
class Container extends Component { render() { return <Bucket {...this.props} {...this.state}/>; } }
JavaScript
class Gov { /** @hidden */ constructor(client) { this.client = client; } /** * Query details of a single proposal * @param proposalID Identity of a proposal * @returns * @since v0.17 */ queryProposal(proposalID) { return this.client.rpcClient.abciQuery('custom/gov/proposal', { ProposalID: String(proposalID), }); } /** * Query proposals by conditions * @param params * @returns * @since v0.17 */ queryProposals(params) { let queryParams = {}; if (params) { queryParams = { Voter: params.voter, Depositor: params.depositor, ProposalStatus: params.proposalStatus, Limit: String(params.limit), }; } return this.client.rpcClient.abciQuery('custom/gov/proposals', queryParams); } /** * Query a vote * @param proposalID Identity of a proposal * @param voter Bech32 voter address * @returns * @since v0.17 */ queryVote(proposalID, voter) { return this.client.rpcClient.abciQuery('custom/gov/vote', { ProposalID: String(proposalID), Voter: voter, }); } /** * Query all votes of a proposal * @param proposalID Identity of a proposal * @returns * @since v0.17 */ queryVotes(proposalID) { return this.client.rpcClient.abciQuery('custom/gov/votes', { ProposalID: String(proposalID), }); } /** * Query a deposit of a proposal * @param proposalID Identity of a proposal * @param depositor Bech32 depositor address * @returns * @since v0.17 */ queryDeposit(proposalID, depositor) { return this.client.rpcClient.abciQuery('custom/gov/deposit', { ProposalID: String(proposalID), Depositor: depositor, }); } /** * Query all deposits of a proposal * @param proposalID Identity of a proposal * @returns * @since v0.17 */ queryDeposits(proposalID) { return this.client.rpcClient.abciQuery('custom/gov/deposits', { ProposalID: String(proposalID), }); } /** * Query the statistics of a proposal * @param proposalID Identity of a proposal * @returns * @since v0.17 */ queryTally(proposalID) { return this.client.rpcClient.abciQuery('custom/gov/tally', { ProposalID: String(proposalID), }); } /** * Submit a ParameterChangeProposal along with an initial deposit * * The proposer must deposit at least 30% of the [MinDeposit](https://www.irisnet.org/docs/features/governance.html#proposal-level) to submit a proposal. * * [Read about which parameters can be changed online](https://www.irisnet.org/docs/concepts/gov-params.html) * * @param title Title of the proposal * @param description Description of the proposal * @param initialDeposit Initial deposit of the proposal(at least 30% of minDeposit) * @param params On-chain Parameter to be changed, eg. `[{"subspace":"mint","key":"Inflation","value":"0.05"}]` * @param baseTx * @returns * @since v0.17 */ submitParameterChangeProposal(title, description, initialDeposit, params, baseTx) { return __awaiter(this, void 0, void 0, function* () { const proposer = this.client.keys.show(baseTx.from); const coins = yield this.client.utils.toMinCoins(initialDeposit); const msgs = [ new gov_1.MsgSubmitParameterChangeProposal({ title, description, proposer, initial_deposit: coins, params, }), ]; return this.client.tx.buildAndSend(msgs, baseTx); }); } /** * Submit a PlainTextProposal along with an initial deposit * * The proposer must deposit at least 30% of the [MinDeposit](https://www.irisnet.org/docs/features/governance.html#proposal-level) to submit a proposal. * * @param title Title of the proposal * @param description Description of the proposal * @param initialDeposit Initial deposit of the proposal(at least 30% of minDeposit) * @param baseTx * @returns * @since v0.17 */ submitPlainTextProposal(title, description, initialDeposit, baseTx) { return __awaiter(this, void 0, void 0, function* () { const proposer = this.client.keys.show(baseTx.from); const coins = yield this.client.utils.toMinCoins(initialDeposit); const msgs = [ new gov_1.MsgSubmitPlainTextProposal({ title, description, proposer, initial_deposit: coins, }), ]; return this.client.tx.buildAndSend(msgs, baseTx); }); } /** * Submit a CommunityTaxUsageProposal along with an initial deposit * * There are three usages, Burn, Distribute and Grant. Burn means burning tokens from community funds. * Distribute and Grant will transfer tokens to the destination trustee's account from community funds. * * The proposer must deposit at least 30% of the [MinDeposit](https://www.irisnet.org/docs/features/governance.html#proposal-level) to submit a proposal. * * @param title Title of the proposal * @param description Description of the proposal * @param initialDeposit Initial deposit of the proposal(at least 30% of minDeposit) * @param usage Type of the CommunityTaxUsage * @param dest_address Bech32 destination address to receive the distributed or granted funds * @param percent Percentage of the current community pool to be used * @param baseTx * @since v0.17 */ submitCommunityTaxUsageProposal(title, description, initialDeposit, usage, destAddress, percent, baseTx) { return __awaiter(this, void 0, void 0, function* () { const proposer = this.client.keys.show(baseTx.from); const coins = yield this.client.utils.toMinCoins(initialDeposit); const msgs = [ new gov_1.MsgSubmitCommunityTaxUsageProposal({ title, description, proposer, initial_deposit: coins, usage: gov_1.CommunityTaxUsageType[usage], dest_address: destAddress, percent: String(percent), }), ]; return this.client.tx.buildAndSend(msgs, baseTx); }); } /** * Deposit tokens for an active proposal. * * When the total deposit amount exceeds the [MinDeposit](https://www.irisnet.org/docs/features/governance.html#proposal-level), the proposal will enter the voting procedure. * * @param proposalID Identity of a proposal * @param amount Amount to be deposited * @param baseTx * @returns * @since v0.17 */ deposit(proposalID, amount, baseTx) { return __awaiter(this, void 0, void 0, function* () { const depositor = this.client.keys.show(baseTx.from); const coins = yield this.client.utils.toMinCoins(amount); const msgs = [ new gov_1.MsgDeposit(String(proposalID), depositor, coins), ]; return this.client.tx.buildAndSend(msgs, baseTx); }); } /** * Vote for an active proposal, options: Yes/No/NoWithVeto/Abstain. * Only validators and delegators can vote for proposals in the voting period. * * @param proposalID Identity of a proposal * @param option Vote option * @param baseTx * @since v0.17 */ vote(proposalID, option, baseTx) { return __awaiter(this, void 0, void 0, function* () { const voter = this.client.keys.show(baseTx.from); const msgs = [new gov_1.MsgVote(String(proposalID), voter, option)]; return this.client.tx.buildAndSend(msgs, baseTx); }); } }
JavaScript
class CPURenderer extends BasicRenderer{ constructor(canvas,param){ super(canvas,param); this.ctx=canvas.getContext("2d"); // @TODO: check ctx==null if(!param.disableBuffer){ // if didn't mentioned creating a buffer if(param.imgData&&param.imgData.type=="CPURenderer"){ this._initBuffer(param.imgData.data.data); // Uint8[...] } else{ this._initBuffer(this.ctx.getImageData( // temp imgdata for buffer 0,0,canvas.width,canvas.height ).data); } } // init refresh range this.refreshRange=[Infinity,0,Infinity,0]; } /** * Init 16-bit buffer for drawing */ _initBuffer(data){ this.buffer=new Uint16Array(data); // buffer containing 16bit data const size=data.length; for(let i=0;i<size;i++){ // 8bit->16bit: 0~255 -> 0~65535 this.buffer[i]+=this.buffer[i]<<8; // *257 } } init(param){ if(!this.buffer)return; // do not init without buffer, if disabled super.init(param); // 16-bit color if(param.rgb){ this.rgba=new Uint16Array([ // fill all element to 0~65535 param.rgb[0]*257, param.rgb[1]*257, param.rgb[2]*257, 0 // opacity info in brush ]); } if(!this.antiAlias&&this.softness<1E-5){ // no soft edge this.softEdge=(()=>1); // always 1 } else{ // normal soft edge this.softEdge=this.softEdgeNormal; } // Assign render function if(this.isOpacityLocked){ this.blendFunction=(this.brush.blendMode==-1)? // Erase/draw CPURenderer.blendDestOutOpacityLocked: CPURenderer.blendNormalOpacityLocked; } else{ this.blendFunction=(this.brush.blendMode==-1)? // Erase/draw CPURenderer.blendDestOut: CPURenderer.blendNormal; } // render flags this.refreshRange=[Infinity,0,Infinity,0]; this.isRefreshRequested=false; } /** * render a series of key points (plate shapes) into the buffer * Slowest! @TODO: speed up */ renderPoints(wL,wH,hL,hH,kPoints){ const w=this.canvas.width; let rgba=[...this.rgba]; // spread is the fastest const hd=this.hardness; const fixedSoftEdge=this.antiAlias?2:0; // first sqrt for(let k=0;k<kPoints.length;k++){ // each circle in sequence const p=kPoints[k]; const r2=p[2]*p[2]; const rIn=p[2]*hd-fixedSoftEdge; // solid radius range, may be Negative! const softRange=this.softness+fixedSoftEdge/p[2]; const rI2=rIn>0?rIn*rIn:0; // if rIn is negative: all soft const jL=Math.max(Math.ceil(p[1]-p[2]),hL); // y lower bound const jH=Math.min(Math.floor(p[1]+p[2]),hH); // y upper bound // The 2-hd is to compensate the soft edge opacity const opa=p[3]*0xFFFF; // plate opacity 0~65535 const x=p[0]; for(let j=jL;j<=jH;j++){ // y-axis const dy=j-p[1]; const dy2=dy*dy; const sx=Math.sqrt(r2-dy2); const solidDx=rI2>dy2?Math.sqrt(rI2-dy2):0; // dx range of not soft edge const iL=Math.max(Math.ceil(x-sx),wL); // x lower bound const iH=Math.min(Math.floor(x+sx),wH); // x upper bound let idBuf=(j*w+iL)<<2; for(let i=iL;i<=iH;i++){ // x-axis, this part is the most time consuming const dx=i-x; if(dx<solidDx&&dx>-solidDx){ // must be solid rgba[3]=Math.min(Math.round(opa),0xFFFF); // opacity of this point } else{ // this part is also time-consuming // distance to center(0~1) const dis2Center=Math.sqrt((dx*dx+dy2)/r2); rgba[3]=Math.min(Math.round(this.softEdge((1-dis2Center)/softRange)*opa),0xFFFF); } this.blendFunction(this.buffer,idBuf,rgba,0); idBuf+=4; // avoid mult } } } // submit a request to refresh the area within (wL~wH,hL~hH) this.requestRefresh([wL,wH,hL,hH]); } /** * refresh screen in range=[wL,wH,hL,hH] */ /** * @TODO: Add performance monitor */ requestRefresh(range){ let nowRange=this.refreshRange; if(nowRange[0]>range[0])nowRange[0]=range[0]; // wL if(nowRange[1]<range[1])nowRange[1]=range[1]; // wH if(nowRange[2]>range[2])nowRange[2]=range[2]; // hL if(nowRange[3]<range[3])nowRange[3]=range[3]; // hH if(this.isRefreshRequested){ return; // already requested } this.isRefreshRequested=true; requestAnimationFrame(()=>this._refresh()); // refresh canvas at next frame } /** * for requestAnimationFrame */ _refresh(){ const range=this.refreshRange; const wL=range[0],wH=range[1]; const hL=range[2],hH=range[3]; const w=this.canvas.width; if(wL>wH||hL>hH)return; // not renewed // renew canvas // create is 5x faster than get image data // create square. smaller: faster const imgData=this.ctx.createImageData(wH-wL+1,hH-hL+1); const data=imgData.data; const buffer=this.buffer; let idImg=0; for(let j=hL;j<=hH;j++){ // copy content let idBuf=(j*w+wL)<<2; for(let i=wL;i<=wH;i++){ // It's OK to keep it this way data[idImg]=buffer[idBuf]/257; // not that time consuming data[idImg+1]=buffer[idBuf+1]/257; data[idImg+2]=buffer[idBuf+2]/257; data[idImg+3]=buffer[idBuf+3]/257; idImg+=4; // Avoid mult idBuf+=4; } } /** * These methods spend almost the same time: drawImage spent on painting * Need to be tested over more browsers * On some browsers putImageData is slow*/ // window.createImageBitmap(imgData,{ // low quality ! // resizeQuality:"high" // }).then(imgBitmap=>{ // this.ctx.drawImage(imgBitmap,wL,hL); // }); this.ctx.putImageData(imgData,wL,hL); // time is spent here this.refreshRange=[Infinity,0,Infinity,0]; this.isRefreshRequested=false; this.onRefresh(); // call refresh callback } fillColor(rgba,range,isOpacityLocked){ if(!range)range=[0,this.canvas.width,0,this.canvas.height]; const rgba16=new Uint16Array([ // fill all element to 0~65535 rgba[0]*257, rgba[1]*257, rgba[2]*257, rgba[3]*257 ]); // Fill buffer const wL=range[0],wH=range[1]; const hL=range[2],hH=range[3]; const w=this.canvas.width; const buffer=this.buffer; for(let j=hL;j<hH;j++){ // copy content let idBuf=(j*w+wL)<<2; for(let i=wL;i<wH;i++){ buffer[idBuf]=rgba16[0]; buffer[idBuf+1]=rgba16[1]; buffer[idBuf+2]=rgba16[2]; buffer[idBuf+3]=isOpacityLocked?buffer[idBuf+3]:rgba16[3]; idBuf+=4; } } // Fill image data const imgData=this.ctx.getImageData(wL,hL,wH-wL+1,hH-hL+1); const data=imgData.data; let idImg=0; for(let j=hL;j<=hH;j++){ // copy content for(let i=wL;i<=wH;i++){ // It's OK to keep it this way data[idImg]=rgba[0]; // not that time consuming data[idImg+1]=rgba[1]; data[idImg+2]=rgba[2]; data[idImg+3]=isOpacityLocked?data[idImg+3]:rgba[3]; idImg+=4; // Avoid mult } } this.ctx.putImageData(imgData,wL,hL); } /** * return ImageData */ getImageData(x,y,w,h){ const cv=this.canvas; if(typeof(x)=="number"){ // metrics provided return { type:"CPURenderer", data:this.ctx.getImageData(x,y,w,h) }; } return { type:"CPURenderer", data:this.ctx.getImageData(0,0,cv.width,cv.height) }; } /** * draw ImageData, must be the same size */ putImageData(imgData,x,y){ if(imgData.type=="CPURenderer"){ this.ctx.putImageData(imgData.data,x||0,y||0); if(this.buffer){ // buffer enabled const cv=this.canvas; this._initBuffer(this.ctx.getImageData(0,0,cv.width,cv.height)); } } } putImageData8bit(imgData,x,y){ // imgData is a image data from context2d this.ctx.putImageData(imgData,x||0,y||0); if(this.buffer){ // buffer enabled const cv=this.canvas; this._initBuffer(this.ctx.getImageData(0,0,cv.width,cv.height)); } } // ============= tools ============== /** * p1[id1..id1+3],p2[id2..id2+3]=[r,g,b,a], all 16-bits * Blend them in normal mode, p2 over p1, store in the same position p1 * (renew p1[id1..id1+3]) */ // @TODO: using pre-multiplied color for blending to speed up? static blendNormal(p1,id1,p2,id2){ const op1=p1[id1+3],op2=p2[id2+3]; // blended op, should be (op2*op1)/0xFFFF. The difference is negligible // @TODO: op==0? const op=Math.min(op2+op1-((op2*op1)>>>16),0xFFFF); const k=op2/op; p1[id1]+=k*(p2[id2]-p1[id1]); p1[id1+1]+=k*(p2[id2+1]-p1[id1+1]); p1[id1+2]+=k*(p2[id2+2]-p1[id1+2]); p1[id1+3]=op; } /** * p1[id1..id1+3],p2[id2..id2+3]=[r,g,b,a], all 16-bits * Blend them in normal mode, p2 over p1, store in the same position p1 * (renew p1[id1..id1+3]) * The opacity of p1 doesn't change */ static blendNormalOpacityLocked(p1,id1,p2,id2){ const op1=p1[id1+3],op2=p2[id2+3]; const op=Math.min(op2+op1-((op2*op1)>>>16),0xFFFF); const k=op2/op; p1[id1]+=k*(p2[id2]-p1[id1]); p1[id1+1]+=k*(p2[id2+1]-p1[id1+1]); p1[id1+2]+=k*(p2[id2+2]-p1[id1+2]); } /** * Destination-out blend mode * for eraser */ static blendDestOut(p1,id1,p2,id2){ const op1=p1[id1+3],op2=p2[id2+3]; const op=(op1*(0x10000-op2))>>>16; // blended op, shoud be (op1*(0xFFFF-op2))/0xFFFF // no change to color params, has nothing to do with the color of p2 // op holds op>=0 p1[id1+3]=op; // only change opacity } /** * Destination-out blend mode * for eraser * Opacity doesn't change, mix with white color */ static blendDestOutOpacityLocked(p1,id1,p2,id2){ const op1=p1[id1+3],op2=p2[id2+3]; const op=Math.min(op2+op1-((op2*op1)>>>16),0xFFFF); const k=op2/op; p1[id1]+=k*(0xFFFF-p1[id1]); p1[id1+1]+=k*(0xFFFF-p1[id1+1]); p1[id1+2]+=k*(0xFFFF-p1[id1+2]); } }
JavaScript
class User { ref = null; key = null; name = ""; score = 0; vote = false; admin = false; constructor(ref, key, userObject) { this.ref = ref; // location of users list. this.key = key; this.pull(userObject); } pull(userObject) { this.name = userObject.name; this.score = userObject.score; this.vote = userObject.vote; this.admin = userObject.admin; } update(validationElement, completed) { var realThis = this; // update the name or score of this user. this.ref.child(this.key).set({ "name": this.name, "score": this.score, "vote": this.vote, "admin": this.admin }, (error) => { if (error) { // The write failed... if (validationElement) { validationElement.text(error); } } else { // Data saved successfully! if (completed) { completed(realThis) } } }); } vote_truth(validationElement, completed) { console.log("Voting for truth"); this.vote = true; this.update(validationElement, completed); } vote_lie(validationElement, completed) { console.log("Voting it's a lie!"); this.vote = false; this.update(validationElement, completed); } }
JavaScript
class ObjectManager { constructor(game) { this.game = game; this.objects = { PoolTable: new PoolTable(), PoolBalls: [ new Ball(-6.8, 0, 0), new Ball(6.8, 0, 1), new Ball(7.35, -0.3, 9), new Ball(7.35, 0.3, 3), new Ball(7.9, -0.6, 14), new Ball(7.9, 0, 8), new Ball(7.9, 0.6, 12), new Ball(8.45, -0.9, 7), new Ball(8.45, -0.3, 10), new Ball(8.45, 0.3, 6), new Ball(8.45, 0.9, 5), new Ball(9, -1.2, 11), new Ball(9, -0.6, 4), new Ball(9, 0, 13), new Ball(9, 0.6, 2), new Ball(9, 1.2, 15), ], Keu: new Keu() }; this.objects.Keu.setupCueBall(this.objects.PoolBalls[0], game.gameScene); this.objects[Symbol.iterator] = function() { var keys = []; var ref = this; for (var key in this) { //note: can do hasOwnProperty() here, etc. keys.push(key); } return { next: function() { if (this._keys && this._obj && this._index < this._keys.length) { var key = this._keys[this._index]; this._index++; return { key: key, value: this._obj[key], done: false }; } else { return { done: true }; } }, _index: 0, _keys: keys, _obj: ref }; } } // ctorObj(child) // { // return $.extend(true, Object.create(Object.getPrototypeOf(child)), child); // } /** * Adds specified object to the game scene * @param {THREE.Object3D} obj - The object */ addToScene(obj) { if (obj instanceof THREE.Object3D && !obj.__skip) // check again, we could be called from outside setupScene() this.game.gameScene.add(obj); } // sets up scene setupScene() { // this function tries to add a mesh to the game scene // if an obj is not a mesh itself, it will look for it let tryToAdd = function(obj) { if (obj instanceof THREE.Object3D) // our obj is an Object3D, safe to add this.addToScene(obj); else if (obj.mesh && obj.mesh instanceof THREE.Object3D) // .mesh is defined and is an Object3D this.addToScene(obj.mesh); else { // no mesh found, iterate for (var prop in obj) { if (obj.hasOwnProperty(prop)) { if (prop instanceof THREE.Object3D && prop instanceof THREE.Mesh) { this.addToScene(prop); break; // found mesh, break the loop } } } } }.bind(this); // iterate .objects for(let arr of this.objects) { // key has an iterator, likely an array so for..of loop the array if (typeof arr[Symbol.iterator] === 'function') { for(let obj of arr) { tryToAdd(obj); } } else // no iterator, we imply it's an object tryToAdd(arr); } } // clears scene clearScene() { while(this.game.gameScene.children.length > 0) { disposeHierarchy(this.game.gameScene.children[0], disposeNode); this.game.gameScene.remove(this.game.gameScene.children[0]); } function disposeNode(node) { if (node instanceof THREE.Mesh) { if (node.geometry) { node.geometry.dispose(); } if (node.material) { if (node.material instanceof THREE.MeshFaceMaterial) { $.each (node.material.materials, function (idx, mtrl) { if (mtrl.map) mtrl.map.dispose(); if (mtrl.lightMap) mtrl.lightMap.dispose(); if (mtrl.bumpMap) mtrl.bumpMap.dispose(); if (mtrl.normalMap) mtrl.normalMap.dispose(); if (mtrl.specularMap) mtrl.specularMap.dispose(); if (mtrl.envMap) mtrl.envMap.dispose(); mtrl.dispose(); // disposes any programs associated with the material }); } else { if (node.material.map) node.material.map.dispose(); if (node.material.lightMap) node.material.lightMap.dispose(); if (node.material.bumpMap) node.material.bumpMap.dispose(); if (node.material.normalMap) node.material.normalMap.dispose(); if (node.material.specularMap) node.material.specularMap.dispose(); if (node.material.envMap) node.material.envMap.dispose(); node.material.dispose(); // disposes any programs associated with the material } } } } // recursive dispose function disposeHierarchy(node, callback) { for (var i = node.children.length - 1; i >= 0; i--) { var child = node.children[i]; disposeHierarchy (child, callback); callback(child); } } } // clears, then setup renewScene() { this.clearScene(); this.setupScene(); } }
JavaScript
class ZxcvbnAdjacencyGraphs { get qwerty() { return { "!": ["`~", null, null, "2@", "qQ", null], "\"": [";:", "[{", "]}", null, null, "/?"], "#": ["2@", null, null, "4$", "eE", "wW"], "$": ["3#", null, null, "5%", "rR", "eE"], "%": ["4$", null, null, "6^", "tT", "rR"], "&": ["6^", null, null, "8*", "uU", "yY"], "'": [";:", "[{", "]}", null, null, "/?"], "(": ["8*", null, null, "0)", "oO", "iI"], ")": ["9(", null, null, "-_", "pP", "oO"], "*": ["7&", null, null, "9(", "iI", "uU"], "+": ["-_", null, null, null, "]}", "[{"], ",": ["mM", "kK", "lL", ".>", null, null], "-": ["0)", null, null, "=+", "[{", "pP"], ".": [",<", "lL", ";:", "/?", null, null], "/": [".>", ";:", "'\"", null, null, null], "0": ["9(", null, null, "-_", "pP", "oO"], "1": ["`~", null, null, "2@", "qQ", null], "2": ["1!", null, null, "3#", "wW", "qQ"], "3": ["2@", null, null, "4$", "eE", "wW"], "4": ["3#", null, null, "5%", "rR", "eE"], "5": ["4$", null, null, "6^", "tT", "rR"], "6": ["5%", null, null, "7&", "yY", "tT"], "7": ["6^", null, null, "8*", "uU", "yY"], "8": ["7&", null, null, "9(", "iI", "uU"], "9": ["8*", null, null, "0)", "oO", "iI"], ":": ["lL", "pP", "[{", "'\"", "/?", ".>"], ";": ["lL", "pP", "[{", "'\"", "/?", ".>"], "<": ["mM", "kK", "lL", ".>", null, null], "=": ["-_", null, null, null, "]}", "[{"], ">": [",<", "lL", ";:", "/?", null, null], "?": [".>", ";:", "'\"", null, null, null], "@": ["1!", null, null, "3#", "wW", "qQ"], "A": [null, "qQ", "wW", "sS", "zZ", null], "B": ["vV", "gG", "hH", "nN", null, null], "C": ["xX", "dD", "fF", "vV", null, null], "D": ["sS", "eE", "rR", "fF", "cC", "xX"], "E": ["wW", "3#", "4$", "rR", "dD", "sS"], "F": ["dD", "rR", "tT", "gG", "vV", "cC"], "G": ["fF", "tT", "yY", "hH", "bB", "vV"], "H": ["gG", "yY", "uU", "jJ", "nN", "bB"], "I": ["uU", "8*", "9(", "oO", "kK", "jJ"], "J": ["hH", "uU", "iI", "kK", "mM", "nN"], "K": ["jJ", "iI", "oO", "lL", ",<", "mM"], "L": ["kK", "oO", "pP", ";:", ".>", ",<"], "M": ["nN", "jJ", "kK", ",<", null, null], "N": ["bB", "hH", "jJ", "mM", null, null], "O": ["iI", "9(", "0)", "pP", "lL", "kK"], "P": ["oO", "0)", "-_", "[{", ";:", "lL"], "Q": [null, "1!", "2@", "wW", "aA", null], "R": ["eE", "4$", "5%", "tT", "fF", "dD"], "S": ["aA", "wW", "eE", "dD", "xX", "zZ"], "T": ["rR", "5%", "6^", "yY", "gG", "fF"], "U": ["yY", "7&", "8*", "iI", "jJ", "hH"], "V": ["cC", "fF", "gG", "bB", null, null], "W": ["qQ", "2@", "3#", "eE", "sS", "aA"], "X": ["zZ", "sS", "dD", "cC", null, null], "Y": ["tT", "6^", "7&", "uU", "hH", "gG"], "Z": [null, "aA", "sS", "xX", null, null], "[": ["pP", "-_", "=+", "]}", "'\"", ";:"], "\\": ["]}", null, null, null, null, null], "]": ["[{", "=+", null, "\\|", null, "'\""], "^": ["5%", null, null, "7&", "yY", "tT"], "_": ["0)", null, null, "=+", "[{", "pP"], "`": [null, null, null, "1!", null, null], "a": [null, "qQ", "wW", "sS", "zZ", null], "b": ["vV", "gG", "hH", "nN", null, null], "c": ["xX", "dD", "fF", "vV", null, null], "d": ["sS", "eE", "rR", "fF", "cC", "xX"], "e": ["wW", "3#", "4$", "rR", "dD", "sS"], "f": ["dD", "rR", "tT", "gG", "vV", "cC"], "g": ["fF", "tT", "yY", "hH", "bB", "vV"], "h": ["gG", "yY", "uU", "jJ", "nN", "bB"], "i": ["uU", "8*", "9(", "oO", "kK", "jJ"], "j": ["hH", "uU", "iI", "kK", "mM", "nN"], "k": ["jJ", "iI", "oO", "lL", ",<", "mM"], "l": ["kK", "oO", "pP", ";:", ".>", ",<"], "m": ["nN", "jJ", "kK", ",<", null, null], "n": ["bB", "hH", "jJ", "mM", null, null], "o": ["iI", "9(", "0)", "pP", "lL", "kK"], "p": ["oO", "0)", "-_", "[{", ";:", "lL"], "q": [null, "1!", "2@", "wW", "aA", null], "r": ["eE", "4$", "5%", "tT", "fF", "dD"], "s": ["aA", "wW", "eE", "dD", "xX", "zZ"], "t": ["rR", "5%", "6^", "yY", "gG", "fF"], "u": ["yY", "7&", "8*", "iI", "jJ", "hH"], "v": ["cC", "fF", "gG", "bB", null, null], "w": ["qQ", "2@", "3#", "eE", "sS", "aA"], "x": ["zZ", "sS", "dD", "cC", null, null], "y": ["tT", "6^", "7&", "uU", "hH", "gG"], "z": [null, "aA", "sS", "xX", null, null], "{": ["pP", "-_", "=+", "]}", "'\"", ";:"], "|": ["]}", null, null, null, null, null], "}": ["[{", "=+", null, "\\|", null, "'\""], "~": [null, null, null, "1!", null, null] } } get dvorak() { return { "!": ["`~", null, null, "2@", "'\"", null], "\"": [null, "1!", "2@", ",<", "aA", null], "#": ["2@", null, null, "4$", ".>", ",<"], "$": ["3#", null, null, "5%", "pP", ".>"], "%": ["4$", null, null, "6^", "yY", "pP"], "&": ["6^", null, null, "8*", "gG", "fF"], "'": [null, "1!", "2@", ",<", "aA", null], "(": ["8*", null, null, "0)", "rR", "cC"], ")": ["9(", null, null, "[{", "lL", "rR"], "*": ["7&", null, null, "9(", "cC", "gG"], "+": ["/?", "]}", null, "\\|", null, "-_"], ",": ["'\"", "2@", "3#", ".>", "oO", "aA"], "-": ["sS", "/?", "=+", null, null, "zZ"], ".": [",<", "3#", "4$", "pP", "eE", "oO"], "/": ["lL", "[{", "]}", "=+", "-_", "sS"], "0": ["9(", null, null, "[{", "lL", "rR"], "1": ["`~", null, null, "2@", "'\"", null], "2": ["1!", null, null, "3#", ",<", "'\""], "3": ["2@", null, null, "4$", ".>", ",<"], "4": ["3#", null, null, "5%", "pP", ".>"], "5": ["4$", null, null, "6^", "yY", "pP"], "6": ["5%", null, null, "7&", "fF", "yY"], "7": ["6^", null, null, "8*", "gG", "fF"], "8": ["7&", null, null, "9(", "cC", "gG"], "9": ["8*", null, null, "0)", "rR", "cC"], ":": [null, "aA", "oO", "qQ", null, null], ";": [null, "aA", "oO", "qQ", null, null], "<": ["'\"", "2@", "3#", ".>", "oO", "aA"], "=": ["/?", "]}", null, "\\|", null, "-_"], ">": [",<", "3#", "4$", "pP", "eE", "oO"], "?": ["lL", "[{", "]}", "=+", "-_", "sS"], "@": ["1!", null, null, "3#", ",<", "'\""], "A": [null, "'\"", ",<", "oO", ";:", null], "B": ["xX", "dD", "hH", "mM", null, null], "C": ["gG", "8*", "9(", "rR", "tT", "hH"], "D": ["iI", "fF", "gG", "hH", "bB", "xX"], "E": ["oO", ".>", "pP", "uU", "jJ", "qQ"], "F": ["yY", "6^", "7&", "gG", "dD", "iI"], "G": ["fF", "7&", "8*", "cC", "hH", "dD"], "H": ["dD", "gG", "cC", "tT", "mM", "bB"], "I": ["uU", "yY", "fF", "dD", "xX", "kK"], "J": ["qQ", "eE", "uU", "kK", null, null], "K": ["jJ", "uU", "iI", "xX", null, null], "L": ["rR", "0)", "[{", "/?", "sS", "nN"], "M": ["bB", "hH", "tT", "wW", null, null], "N": ["tT", "rR", "lL", "sS", "vV", "wW"], "O": ["aA", ",<", ".>", "eE", "qQ", ";:"], "P": [".>", "4$", "5%", "yY", "uU", "eE"], "Q": [";:", "oO", "eE", "jJ", null, null], "R": ["cC", "9(", "0)", "lL", "nN", "tT"], "S": ["nN", "lL", "/?", "-_", "zZ", "vV"], "T": ["hH", "cC", "rR", "nN", "wW", "mM"], "U": ["eE", "pP", "yY", "iI", "kK", "jJ"], "V": ["wW", "nN", "sS", "zZ", null, null], "W": ["mM", "tT", "nN", "vV", null, null], "X": ["kK", "iI", "dD", "bB", null, null], "Y": ["pP", "5%", "6^", "fF", "iI", "uU"], "Z": ["vV", "sS", "-_", null, null, null], "[": ["0)", null, null, "]}", "/?", "lL"], "\\": ["=+", null, null, null, null, null], "]": ["[{", null, null, null, "=+", "/?"], "^": ["5%", null, null, "7&", "fF", "yY"], "_": ["sS", "/?", "=+", null, null, "zZ"], "`": [null, null, null, "1!", null, null], "a": [null, "'\"", ",<", "oO", ";:", null], "b": ["xX", "dD", "hH", "mM", null, null], "c": ["gG", "8*", "9(", "rR", "tT", "hH"], "d": ["iI", "fF", "gG", "hH", "bB", "xX"], "e": ["oO", ".>", "pP", "uU", "jJ", "qQ"], "f": ["yY", "6^", "7&", "gG", "dD", "iI"], "g": ["fF", "7&", "8*", "cC", "hH", "dD"], "h": ["dD", "gG", "cC", "tT", "mM", "bB"], "i": ["uU", "yY", "fF", "dD", "xX", "kK"], "j": ["qQ", "eE", "uU", "kK", null, null], "k": ["jJ", "uU", "iI", "xX", null, null], "l": ["rR", "0)", "[{", "/?", "sS", "nN"], "m": ["bB", "hH", "tT", "wW", null, null], "n": ["tT", "rR", "lL", "sS", "vV", "wW"], "o": ["aA", ",<", ".>", "eE", "qQ", ";:"], "p": [".>", "4$", "5%", "yY", "uU", "eE"], "q": [";:", "oO", "eE", "jJ", null, null], "r": ["cC", "9(", "0)", "lL", "nN", "tT"], "s": ["nN", "lL", "/?", "-_", "zZ", "vV"], "t": ["hH", "cC", "rR", "nN", "wW", "mM"], "u": ["eE", "pP", "yY", "iI", "kK", "jJ"], "v": ["wW", "nN", "sS", "zZ", null, null], "w": ["mM", "tT", "nN", "vV", null, null], "x": ["kK", "iI", "dD", "bB", null, null], "y": ["pP", "5%", "6^", "fF", "iI", "uU"], "z": ["vV", "sS", "-_", null, null, null], "{": ["0)", null, null, "]}", "/?", "lL"], "|": ["=+", null, null, null, null, null], "}": ["[{", null, null, null, "=+", "/?"], "~": [null, null, null, "1!", null, null] } } get azerty() { return { "!": ["77", null, null, "99", "oO", "iI"], "\"": ["22", null, null, "'4", "rR", "eE"], "#": ["`~", null, null, "&1", "aA", null], "$": ["pP", "a0", "))", "-_", "%%", "mM"], "%": ["mM", "$*", "-_", null, "=+", ":/"], "&": ["@#", null, null, "22", "zZ", "aA"], "'": ["\"3", null, null, "(5", "tT", "rR"], "(": ["'4", null, null, "66", "yY", "tT"], ")": ["a0", null, null, null, "-_", "$*"], "*": ["pP", "a0", "))", "-_", "%%", "mM"], "+": [":/", "%%", null, null, null, null], ",": ["nN", "kK", "lL", ";.", null, null], "-": ["$*", "))", null, null, null, "%%"], ".": [",?", "lL", "mM", ":/", null, null], "/": [";.", "mM", "%%", "=+", null, null], "0": ["99", null, null, "))", "$*", "pP"], "1": ["@#", null, null, "22", "zZ", "aA"], "2": ["&1", null, null, "\"3", "eE", "zZ"], "3": ["22", null, null, "'4", "rR", "eE"], "4": ["\"3", null, null, "(5", "tT", "rR"], "5": ["'4", null, null, "66", "yY", "tT"], "6": ["(5", null, null, "77", "uU", "yY"], "7": ["66", null, null, "!8", "iI", "uU"], "8": ["77", null, null, "99", "oO", "iI"], "9": ["!8", null, null, "a0", "pP", "oO"], ":": [";.", "mM", "%%", "=+", null, null], ";": [",?", "lL", "mM", ":/", null, null], "<": [null, "qQ", "sS", "wW", null, null], "=": [":/", "%%", null, null, null, null], ">": [null, "qQ", "sS", "wW", null, null], "?": ["nN", "kK", "lL", ";.", null, null], "@": ["`~", null, null, "&1", "aA", null], "A": [null, "@#", "&1", "zZ", "qQ", null], "B": ["vV", "hH", "jJ", "nN", null, null], "C": ["xX", "fF", "gG", "vV", null, null], "D": ["sS", "eE", "rR", "fF", "xX", "wW"], "E": ["zZ", "22", "\"3", "rR", "dD", "sS"], "F": ["dD", "rR", "tT", "gG", "cC", "xX"], "G": ["fF", "tT", "yY", "hH", "vV", "cC"], "H": ["gG", "yY", "uU", "jJ", "bB", "vV"], "I": ["uU", "77", "!8", "oO", "kK", "jJ"], "J": ["hH", "uU", "iI", "kK", "nN", "bB"], "K": ["jJ", "iI", "oO", "lL", ",?", "nN"], "L": ["kK", "oO", "pP", "mM", ";.", ",?"], "M": ["lL", "pP", "$*", "%%", ":/", ";."], "N": ["bB", "jJ", "kK", ",?", null, null], "O": ["iI", "!8", "99", "pP", "lL", "kK"], "P": ["oO", "99", "a0", "$*", "mM", "lL"], "Q": [null, "aA", "zZ", "sS", "<>", null], "R": ["eE", "\"3", "'4", "tT", "fF", "dD"], "S": ["qQ", "zZ", "eE", "dD", "wW", "<>"], "T": ["rR", "'4", "(5", "yY", "gG", "fF"], "U": ["yY", "66", "77", "iI", "jJ", "hH"], "V": ["cC", "gG", "hH", "bB", null, null], "W": ["<>", "sS", "dD", "xX", null, null], "X": ["wW", "dD", "fF", "cC", null, null], "Y": ["tT", "(5", "66", "uU", "hH", "gG"], "Z": ["aA", "&1", "22", "eE", "sS", "qQ"], "_": ["$*", "))", null, null, null, "%%"], "`": [null, null, null, "@#", null, null], "a": ["99", null, null, "))", "$*", "pP"], "b": ["vV", "hH", "jJ", "nN", null, null], "c": ["xX", "fF", "gG", "vV", null, null], "d": ["sS", "eE", "rR", "fF", "xX", "wW"], "e": ["zZ", "22", "\"3", "rR", "dD", "sS"], "f": ["dD", "rR", "tT", "gG", "cC", "xX"], "g": ["fF", "tT", "yY", "hH", "vV", "cC"], "h": ["gG", "yY", "uU", "jJ", "bB", "vV"], "i": ["uU", "77", "!8", "oO", "kK", "jJ"], "j": ["hH", "uU", "iI", "kK", "nN", "bB"], "k": ["jJ", "iI", "oO", "lL", ",?", "nN"], "l": ["kK", "oO", "pP", "mM", ";.", ",?"], "m": ["lL", "pP", "$*", "%%", ":/", ";."], "n": ["bB", "jJ", "kK", ",?", null, null], "o": ["iI", "!8", "99", "pP", "lL", "kK"], "p": ["oO", "99", "a0", "$*", "mM", "lL"], "q": [null, "aA", "zZ", "sS", "<>", null], "r": ["eE", "\"3", "'4", "tT", "fF", "dD"], "s": ["qQ", "zZ", "eE", "dD", "wW", "<>"], "t": ["rR", "'4", "(5", "yY", "gG", "fF"], "u": ["yY", "66", "77", "iI", "jJ", "hH"], "v": ["cC", "gG", "hH", "bB", null, null], "w": ["<>", "sS", "dD", "xX", null, null], "x": ["wW", "dD", "fF", "cC", null, null], "y": ["tT", "(5", "66", "uU", "hH", "gG"], "z": ["aA", "&1", "22", "eE", "sS", "qQ"], "~": [null, null, null, "@#", null, null] } } get keypad() { return { "*": ["/", null, null, null, "-", "+", "9", "8"], "+": ["9", "*", "-", null, null, null, null, "6"], "-": ["*", null, null, null, null, null, "+", "9"], ".": ["0", "2", "3", null, null, null, null, null], "/": [null, null, null, null, "*", "9", "8", "7"], "0": [null, "1", "2", "3", ".", null, null, null], "1": [null, null, "4", "5", "2", "0", null, null], "2": ["1", "4", "5", "6", "3", ".", "0", null], "3": ["2", "5", "6", null, null, null, ".", "0"], "4": [null, null, "7", "8", "5", "2", "1", null], "5": ["4", "7", "8", "9", "6", "3", "2", "1"], "6": ["5", "8", "9", "+", null, null, "3", "2"], "7": [null, null, null, "/", "8", "5", "4", null], "8": ["7", null, "/", "*", "9", "6", "5", "4"], "9": ["8", "/", "*", "-", "+", null, "6", "5"] } } get mac_keypad() { return { "*": ["/", null, null, null, null, null, "-", "9"], "+": ["6", "9", "-", null, null, null, null, "3"], "-": ["9", "/", "*", null, null, null, "+", "6"], ".": ["0", "2", "3", null, null, null, null, null], "/": ["=", null, null, null, "*", "-", "9", "8"], "0": [null, "1", "2", "3", ".", null, null, null], "1": [null, null, "4", "5", "2", "0", null, null], "2": ["1", "4", "5", "6", "3", ".", "0", null], "3": ["2", "5", "6", "+", null, null, ".", "0"], "4": [null, null, "7", "8", "5", "2", "1", null], "5": ["4", "7", "8", "9", "6", "3", "2", "1"], "6": ["5", "8", "9", "-", "+", null, "3", "2"], "7": [null, null, null, "=", "8", "5", "4", null], "8": ["7", null, "=", "/", "9", "6", "5", "4"], "9": ["8", "=", "/", "*", "-", "+", "6", "5"], "=": [null, null, null, null, "/", "9", "8", "7"] } } }
JavaScript
class Graphics3d extends AbstractGraphics{ constructor(width, height, container){ super(width, height, container); //resize listener this.container.on("finishResize, resize", function(event, size){ var newSize = { width:This.container.width(), height:This.container.height() }; This.size = newSize; This.camera.setWindowSize(newSize.width, newSize.height); This.renderer.setSize(newSize.width, newSize.height); // This.camera.__updateLoc(); }); //create an empty scene this.scene = new THREE.Scene(); //create a basic perspective camera var camera = new THREE.PerspectiveCamera( 75, this.getWidth()/this.getHeight(), 0.001, 2 ); //create a renderer with Antialiasing this.renderer = new THREE.WebGLRenderer({antialias:true, alpha:true}); this.renderer.setClearColor("#000000", 0); this.renderer.setSize(this.getWidth(), this.getHeight()); // this.renderer.vr.enabled = true; this.container.append($(this.renderer.domElement).addClass("three").attr("oncontextmenu","return false;")); //render Loop var This = this; this.renderListeners = []; this.updating = true; this.rendering = 1; this.lastUpdate = Date.now(); this.lastRender = Date.now(); this.deltaTime = 1/30; this.tick = 0; this.renderFunc = function(){ if(This.rendering==1) requestAnimationFrame(This.renderFunc); if(This.rendering==2) //indicate that there is no longer an animation frame request waiting This.rendering = 0; var now = Date.now(); if((now-This.lastUpdate)/1000>This.deltaTime){ //update tick //reset world transform that might have been done by VR camera This.__resetTransform(); //track the time /steps This.tick++;//increase the tick This.lastUpdate += This.deltaTime*1000; if(now-This.lastUpdate>2000) //skip some if needed This.lastUpdate = now; //interpolate images This.__interpolate(); //update the world if(This.updating) This.__onUpdate(This.deltaTime); //actually render the frame This.renderer.render(This.scene, camera); }else{ //render new interpolated frame // create interpolated frame /* This.__resetTransform(); This.__interpolate(); This.renderer.render(This.scene, camera); */ } This.lastRender = now; }; this.renderFunc(); //lighting this.ambientLight = { color: 0xffffff, intensity: 0.3, light: new THREE.AmbientLight(0xffffff), }; this.ambientLight.light.intensity = this.ambientLight.intensity; this.scene.add(this.ambientLight.light); //connect a camera and setup VR properties this.camera = new Camera3d(this, camera); this.camera.setWindowSize(this.getWidth(), this.getHeight()); this.VRproperties = { enabled: true, scale: 1.5, offset: new XYZ(0.2, 0.2, 0.2) }; //interaction data this.pointers = { types: ["mouse"], mouse: new XYZ(), hand1: new XYZ(), hand2: new XYZ() }; for(var i=0; i<3; i++){ var pointer = this.pointers[["mouse", "hand1", "hand2"][i]]; pointer.pressed = false; pointer.hoverShapes = []; } //set up event listeners { var canvas = this.getCanvas(); this.DOMEventListeners.mousemove = function(event){ This.__resetTransform(); var offset = canvas.offset(); This.pointers.mouse.x = event.pageX - offset.left; This.pointers.mouse.y = event.pageY - offset.top; var pos = new Vec(This.pointers.mouse); //send event to shapes This.__dispatchEvent(function(){ this.__triggerMouseMove(pos, event); }); This.__triggerMouseMove(pos, event); //hover events var shape = This.camera.rayTrace(This.pointers.mouse.x, This.pointers.mouse.y)[0]; var m = This.pointers.mouse; if(m.x>=0 && m.y>=0 && m.x<=This.getWidth() && m.y<=This.getHeight()) This.__dispatchHoverEvent(shape, "mouse", event); else This.__dispatchHoverEvent(null, "mouse", event); }; this.DOMEventListeners.scroll = function(event){ This.__resetTransform(); var delta = event.originalEvent.wheelDeltaY //chrome || event.originalEvent.deltaY*-40; //firefox //send event to shapes var caught = This.__dispatchEvent(function(){ return this.__triggerMouseScroll(delta, event); }); var m = This.pointers.mouse; if(!caught && m.x>=0 && m.y>=0 && m.x<=This.getWidth() && m.y<=This.getHeight()) This.__triggerMouseScroll(delta, event); }; this.DOMEventListeners.keypress = function(event){ This.__resetTransform(); event.key = keyNames[event.keyCode] || event.key; if(event.type=="keyup") //remove keys even if released outside of visualisation delete This.pressedKeys[event.key.toLowerCase()]; var isKeyDown = event.type=="keydown"; var key = event.key; var keyCode = key?key.toLowerCase():key; //send event to shapes var caught = This.__dispatchEvent(function(){ return this.__triggerKeyPress(isKeyDown, keyCode, event); }); var m = This.pointers.mouse; if(!caught && m.x>=0 && m.y>=0 && m.x<=This.getWidth() && m.y<=This.getHeight()) This.__triggerKeyPress(isKeyDown, keyCode, event); }; var startedIn = false; //if mousepress started in visualisation this.DOMEventListeners.mousepress = function(event){ This.__resetTransform(); var isMouseDown = event.type=="mousedown"; if($(event.target).is("canvas")) event.preventDefault(); //send event to shapes var caught = This.__dispatchEvent(function(){ if(!isMouseDown) this.__triggerClick(event); return this.__triggerMousePress(isMouseDown, event); }); var m = This.pointers.mouse; if((m.x>=0 && m.y>=0 && m.x<=This.getWidth() && m.y<=This.getHeight()) || startedIn){ if(startedIn) event.preventDefault(); if(!caught){ if(!isMouseDown) This.__triggerClick(event); This.__triggerMousePress(isMouseDown, event); } startedIn = isMouseDown; } }; $(window).on('wheel', this.DOMEventListeners.scroll); $(window).on('keydown', this.DOMEventListeners.keypress); $(window).on('keyup', this.DOMEventListeners.keypress); $(window).on("mousemove", this.DOMEventListeners.mousemove); $(window).on('mousedown', this.DOMEventListeners.mousepress); $(window).on('mouseup', this.DOMEventListeners.mousepress); } } getRenderer(){ return this.renderer; } getCanvas(){ return this.getContainer().find("canvas.three"); } __resetTransform(){ //resets the transform that might have been applied by the VR camera this.scene.position.set(0, 0, 0); this.scene.scale.set(1, 1, 1); this.scene.rotation.set(0, 0, 0); this.scene.updateMatrixWorld(); } //a method to add an event that fires whenever the screen is rendered onRender(listener){ var index = this.renderListeners.indexOf(listener); if(index==-1) this.renderListeners.push(listener); return this; } offRender(listener){ var index = this.renderListeners.indexOf(listener); if(index!=-1) this.renderListeners.splice(index, 1); return this; } __onRender(delta, per){ //general listeners for(var i=0; i<this.renderListeners.length; i++) this.renderListeners[i].apply(this, arguments); return this; } //frame intpolation for VR __interpolate(fromVR){ var now = Date.now(); var delta = (now-this.lastUpdate)/this.deltaTime/1000; this.__onRender(now-this.lastRender, delta); var shapes = this.getShapes(); for(var i=0; i<shapes.length; i++){ var shape = shapes[i]; shape.__interpolate(delta); } //make html visible or not depending on fromVR for(var i=0; i<this.shapes.html.length; i++){ var h = this.shapes.html[i]; if(!fromVR){ h.mesh.visible = false; }else if(h.isRendered){ h.mesh.visible = true; } } } //disposal destroy(){ $(window).off('wheel', this.DOMEventListeners.scroll); $(window).off('keydown', this.DOMEventListeners.keypress); $(window).off('keyup', this.DOMEventListeners.keypress); $(window).off('mousemove', this.DOMEventListeners.mousemove); $(window).off('mousedown', this.DOMEventListeners.mousepress); $(window).off('mouseup', this.DOMEventListeners.mousepress); if(this.inVR){ VRCamera.setVisualisation(null); }; super.destroy(); } //event handeling __dispatchEvent(func, pos){ var que; if(pos instanceof AbstractShape){ que = [pos]; }else{ if(!pos) pos = this.pointers.mouse; que = this.camera.rayTrace(pos.x, pos.y); } while(que.length>0){ var shape = que.shift(); var parentShape = shape.getParentShape(); if(parentShape) que.unshift(parentShape); //execute event if(!shape.interactionsDisabled && func.call(shape)) return true; } return false; } __dispatchHoverEvent(shape, pointer, event){ if(this.pointers.types.indexOf(pointer)==-1) pointer="mouse"; pointer = this.pointers[pointer]; //create some hover codes to recognize old and new hover states from pointers var oldHoverCode = pointer.hoverCode; var newHoverCode = Math.floor(Math.pow(10, 6)*Math.random())+""; pointer.hoverCode = newHoverCode; //get the list of shapes that the pointer was hovering over in the previous cycle var shapes = pointer.hoverShapes; //select new hover shape and parents while(shape){ shape.__hoverCodes.push(newHoverCode); if(shapes.indexOf(shape)==-1){ shapes.push(shape); shape.__triggerHover(true, event); } shape = shape.getParentShape(); } //remove old hover shapes if needed for(var i=shapes.length-1; i>=0; i--){ var shape = shapes[i]; //get rid of the old code that identified that this pointer hovers over the shape var oldCodeIndex = shape.__hoverCodes.indexOf(oldHoverCode); if(oldCodeIndex!=-1) shape.__hoverCodes.splice(oldCodeIndex, 1); //if new code isn't set, this pointer no longer hovers over it if(shape.__hoverCodes.indexOf(newHoverCode)==-1){ var index = shapes.indexOf(shape); if(index!=-1) shapes.splice(index, 1); //if the hoverCodes array is empty, no poijnter hovers over it anymore if(shape.__hoverCodes.length==0) shape.__triggerHover(false, event); } } } //start/stop rendering pause(fully){ this.lastUpdate = Date.now()+2000; if(!fully){ this.updating = false }else{ if(this.rendering==1) this.rendering = 2; } return this; } start(){ this.lastUpdate = Date.now(); this.updating = true; var wasNotRendering = this.rendering==0; this.rendering = 1; if(wasNotRendering) this.renderFunc(); return this; } //pixi specific methods __getScene(){ return this.scene; } __getRenderer(){ return this.renderer; } //light setAmbientLightIntensity(intensity){ this.ambientLight.intensity = intensity; this.ambientLight.light.intensity = intensity; return this; } getAmbientLightIntensity(){ return this.ambientLight.intensity; } setAmbientLightColor(color){ this.ambientLight.color = color; this.ambientLight.light.color.set(color); return this; } getAmbientLightColor(){ return this.ambientLight.color; } //mouse methods getMouseScreenLoc(){ return this.pointers.mouse; } getMouseLoc(distance, pointer){ if(typeof(distance)=="string"){ pointer = distance; distance = null; } //check if given pointer is allowed if(this.pointers.types.indexOf(pointer)==-1) pointer="mouse"; //if pointer isn't mouse, just straight up return the value if(pointer!="mouse") return this.pointers[pointer]; //translate mouse position to world coordinate return this.camera.translateScreenToWorldLoc(this.getMouseScreenLoc().setZ(distance!=null?distance:0)); } getMouseVec(x, y, z){ var xyz; if(x instanceof AbstractShape) xyz = new Vec(x.getWorldLoc()); else xyz = new Vec(x, y, z); //go through all pointers to find the closest one var closest = new Vec(xyz).sub(this.getMouseLoc()); for(var i=1; i<this.pointers.types.length; i++){ var type = this.pointers.types[i]; var pos = this.getMouseLoc(null, type); var vec = new Vec(xyz).sub(pos); if(vec.getLength()<closest.getLength()) closest = vec; } return vec; } getMousePressed(pointer){ if(this.pointers.types.indexOf(pointer)==-1) pointer="mouse"; return this.pointers[pointer].pressed; } //VR specific stuff __enableVR(){ this.pointers.types = ["mouse", "hand1", "hand2"]; this.inVR = true; } __disableVR(){ this.pointers.types = ["mouse"]; this.inVR = false; } isInVR(){ return this.inVR; } __setHand(pointer, pos, pressed){ var p = this.pointers[pointer]; p.set(pos); p.pressed = pressed; } }
JavaScript
class Pagination { /** * Create a generator object with the new rendered document. * @param { string } buttonSelector - CSS selector of the button that triggers the action * to go to the next pagination. * @param { object } waitFor - Selector of an element and timeout in milliseconds to wait for. * @param { number } waitFor.timeout - The number of milliseconds to wait for. * @param { string } waitFor.selector - A selector of an element to wait for. * @param { function } waitFor.customFunction - A function that performs others waiting processes. * @param { function } [stopLoad=(button) => button] - A function that * returns a boolean to control when the event needs to be stopped. * By default function is ```(button) => button```, * where the Pagination functionality needs to stop when the button is not available. */ static async * execute(buttonSelector, waitFor, stopLoad = (button) => button) { let nextButton = null; do { yield document; nextButton = document.querySelector(buttonSelector); await clickAndWait(buttonSelector, waitFor); } while(stopLoad(nextButton)); } }
JavaScript
class FilterDataSource extends EventEmitter { constructor(dataView, column, options = {}) { super(); // can we listen for destroy event ? this.dataSource = dataView; this.column = column; // this.dataCounts = undefined; // why do we need to store the range ? this.range = null; // TODO - works but ugly this.options = options; } async subscribe({ columns, range }, callback) { logger.log(`filter-data-view subscribe ${JSON.stringify(range)}`); this.columns = columns; //TODO make range s setter - DO WE EVEN NEED RANGE ? this.range = range; this.keyCount = range.hi - range.lo; const cb = (this.clientCallback = (message) => { console.log({ message }); if (message) { const { stats, ...data } = message; callback(data); // // this.dataCounts = dataCounts; if (stats) { logger.log(`emit stats`); this.emit('data-count', stats); } } }); this.dataSource.subscribeToFilterData(this.column, range, cb); // // This can't be called until subscribeToFilterData is called, as the filterSet will not have been created on dataView // if (this.options.filter){ // this.filter(this.options.filter) // } } unsubscribe() { this.dataSource.unsubscribeFromFilterData(); } destroy() { logger.log(`<destroy>`); this.dataSource.unsubscribeFromFilterData(this.column); } setRange(lo, hi) { if (lo !== this.range.lo || hi !== this.range.hi) { this.range = { lo, hi }; this.dataSource.setRange(lo, hi, DataTypes.FILTER_DATA); } } setGroupState(groupState) { console.log('why is this ever called', groupState); } setSubscribedColumns(columns) { console.log('why is this ever called', columns); } select(idx, rangeSelect, keepExistingSelection) { this.dataSource.select(idx, rangeSelect, keepExistingSelection, DataTypes.FILTER_DATA); } selectAll() { this.dataSource.selectAll(DataTypes.FILTER_DATA); } selectNone() { this.dataSource.selectNone(DataTypes.FILTER_DATA); } filter(filter, dataType = DataTypes.FILTER_DATA, incremental = false) { this.dataSource.filter(filter, dataType, incremental); } }
JavaScript
class Toolbar extends React.Component { constructor(props){ super(props); } render() { return <div className="toolbar"> {this.props.title} </div> } }
JavaScript
class MyNFTToken { async init() { const web3 = await Moralis.Web3.enable(); this.contract = new web3.eth.Contract(MyNFTTokenAbi, TOKEN_ADDRESS); } async name() { return this.contract.methods.name().call(); } async symbol() { return this.contract.methods.symbol().call(); } async mint(fromAddress) { return this.contract.methods.mint() .send({ from: fromAddress }); } async nextTokenId() { return this.contract.methods.nextTokenId() .call() } }
JavaScript
class Chart extends Component { constructor(props) { super(props); this.state = chartConfigs; this.updateData = this.updateData.bind(this); } //This function generates random number. getRandomNumber() { var max = 290, min = 30; return Math.round((max - min) * Math.random() + min); } //Handler for update button. //Randomly updates the values of the chart. updateData() { var prevDs = Object.assign({}, this.state.dataSource); prevDs.data[2].value = this.getRandomNumber(); prevDs.data[3].value = this.getRandomNumber(); this.setState({ dataSource: prevDs, }); } //Create the button render() { return ( <div> <ReactFC {...this.state} /> <center> <button className="btn btn-outline-secondary btn-sm" onClick={this.updateData}> Change Chart Data </button> </center> </div> ); } }
JavaScript
class tripHelper { /** * This method helps to validate if a location * exist in database * @param {Object} req user request * @returns {null} no return */ static async checkLocationExistance(req) { await Promise.all(req.body.map(async (trip, index) => { const origin = await locationServices.findLocation(trip.From); const destination = await locationServices.findLocation(trip.To); if (!origin) { req.errorMessage = `Origin of trip number ${index + 1} not found`; req.errorStatus = 404; } else if (!destination) { req.errorMessage = `Destination of trip number ${index + 1} not found`; req.errorStatus = 404; } })); } /** * This method helps to extract days between two dates * it will accept to date and find the days twee them * @param {Object} req user request * @returns {Object} not return */ static extractDaysInDate(req) { let firstTravelDate = ''; let secondTravelDate = ''; req.body.map((trip, index) => { req.body[index].leavingDays = 0; if (index > 0) { firstTravelDate = new Date(req.body[index - 1].departureDate); secondTravelDate = new Date(req.body[index].departureDate); const DifferenceInTime = (secondTravelDate > firstTravelDate) ? secondTravelDate.getTime() - firstTravelDate.getTime() : 0; const days = DifferenceInTime / (1000 * 3600 * 24); req.body[index].leavingDays = days; } return 0; }); return { firstTravelDate, secondTravelDate }; } /** * This method validate if the trips pattern * are consecutive * @param {Object} req user request * @param {Date} firstTravelDate privious trip date * @param {Date} secondTravelDate nexttrip date * @returns {null} not return */ static validateTripPattern(req, firstTravelDate, secondTravelDate) { req.body.map((trip, index) => { if (index > 0 && req.body[index - 1].To !== req.body[index].From) { req.errorMessage = `Destination of trip number ${index}, mush be equal to the Origin of trip number ${index + 1}`; req.errorStatus = 403; } else if ((index > 0 && firstTravelDate >= secondTravelDate)) { req.errorMessage = `Departure date of trip number ${index} can not be greater than Departure date of trip number ${index + 1}`; req.errorStatus = 403; } return 0; }); } /** * This method checks if a user request a trip twice * @param {Object} req user request * @param {Object} res user respnse * @returns { null} not return */ static async checkTripExistence(req, res) { await Promise.all(req.body.map(async (trip, index) => { const bookedTrips = []; const trips = await tripService.findUserTrip(res, req.body[index].From, req.body[index].To); trips.filter((trip2) => { const tripDepartureDate = moment(trip2.dataValues.departureDate).format('YYYY-MM-DD'); if (tripDepartureDate === trip.departureDate && trip2.userId === req.user.dataValues.id) { req.checker = true; } }); if (req.checker)bookedTrips.push(index + 1); req.errorMessage = (bookedTrips.length > 0) ? `Trip number ${bookedTrips} alread exist ` : req.errorMessage; req.errorStatus = (bookedTrips.length > 0) ? 409 : req.errorStatus; req.checker = false; })); } }
JavaScript
class Api { constructor() { this.resources = {} this.configs = {} if (!this._isProduction()) { this.configs.headers = { 'X-Requested-With': appUrl, } } this.axios = axios.create({ paramsSerializer(params) { // this mainly works for labelId in query params, e.g. // it converts: ...&labelId[]={id1}&labelId[]={id2} // to: ...&labelId={id1}&labelId={id2} // see https://stackoverflow.com/questions/52482203/axios-multiple-values-comma-separated-in-a-parameter const searchParams = new URLSearchParams() for (const key of Object.keys(params)) { const param = params[key] if (param === null) { continue } if (Array.isArray(param)) { for (const p of param) { searchParams.append(key, p) } } else { searchParams.append(key, param) } } return searchParams.toString() }, }) this._init() } /* The key method to request a resource. */ async request(resourceName, configs = {}) { // all options: https://github.com/axios/axios#request-config await this._checkResources() try { const url = this.resources[resourceName] configs.url = this._parseUrl(url) + (configs.appendUrl ? configs.appendUrl : '') configs = { ...configs, ...this.configs } const { data } = await this.axios(configs) return data } catch (e) { throw e // TODO: error handling } } /* Get all available resources. */ async _init() { try { const configs = { url: this._parseUrl(baseUrl), // url: corsHelper + "http://google.com/", ...this.configs, } const { data } = await this.axios(configs) const links = data._links this._initResources(links) Promise.resolve() } catch (e) { // TODO: error handling } } _initResources(resourceLinks) { Object.keys(resourceLinks).forEach(key => { this.resources[key] = resourceLinks[key].href }) } async _checkResources() { if (Object.keys(this.resources).length === 0) { // empty resources await this._init() } Promise.resolve() } _isProduction() { return process.env.NODE_ENV === 'production' } _parseUrl(url) { // return this._isProduction() ? url : corsHelper + url; return url } }
JavaScript
class ChangePasswordForm { constructor(vnode) { this.userController = vnode.attrs.userController; this.password_old = ''; this.password1 = ''; this.password2 = ''; this.notification = { type: 'info', label: i18n('profile.password.explanation') }; } static _createSession(user, password) { const username = user.nethz || user.email; return m.request({ method: 'POST', url: `${apiUrl}/sessions`, body: { username, password }, }); } static _deleteSession(session) { return m.request({ method: 'DELETE', url: `${apiUrl}/sessions/${session._id}`, headers: { Authorization: session.token, 'If-Match': session._etag, }, }); } async submit() { const password = this.password1; this.busy = true; try { const session = await this.constructor._createSession( this.userController.user, this.password_old ); await this.userController.update({ password }, session.token); await this.constructor._deleteSession(session); this.password1 = ''; this.notification = { type: 'success', label: i18n('profile.password.changed') }; } catch ({ _error: { code } }) { if (code === 401) { this.notification = { type: 'fail', label: i18n('profile.password.errors.current') }; this.valid_old = false; } else { this.notification = { type: 'fail', label: i18n('profile.password.errors.unknown') }; log(`An error occurred: ${code}`); } } this.busy = false; this.password_old = ''; this.password2 = ''; } // Password policy: // * Minimum length: 7 // * Maximum length: 100 validate() { this.valid_new1 = this.password1.length >= 7 && this.password1.length <= 100; this.valid_new2 = this.password1 === this.password2; this.valid = this.valid_old && this.valid_new1 && this.valid_new2; } view() { const { user } = this.userController; if (user === undefined) return m(); const buttonArgs = {}; let buttons; if (!this.valid || this.busy) { buttonArgs.disabled = true; } if (user.password_set) { buttons = [ m( 'div', { margin: 5 }, m(Button, { ...buttonArgs, label: i18n('profile.password.change'), events: { onclick: () => this.submit() }, }) ), m( 'div', { margin: 5 }, m(Button, { disabled: !this.valid_old || this.busy, label: i18n('profile.password.revertToLdap'), events: { onclick: () => { if (!this.valid_old) { this.validate(); return; } Dialog.show({ title: i18n('warning'), body: m.trust(marked(i18n('profile.password.revertToLdapWarning'))), modal: true, backdrop: true, footerButtons: [ m(Button, { label: i18n('button.cancel'), className: 'flat-button', events: { onclick: () => { Dialog.hide(); return false; }, }, }), m(Button, { label: i18n('button.proceed'), className: 'flat-button', events: { onclick: () => { this.password1 = ''; this.password2 = ''; Dialog.hide(); this.submit(); return false; }, }, }), ], }); }, }, }) ), ]; } else { buttons = m(Button, { ...buttonArgs, label: i18n('profile.password.set'), events: { onclick: () => this.submit() }, }); } let notification; if (this.notification) { let iconSource; if (this.notification.type === 'success') { iconSource = icons.checkboxMarked; } else if (this.notification.type === 'fail') { iconSource = icons.error; } else { iconSource = icons.info; } notification = m(Infobox, { icon: m(Icon, { svg: { content: m.trust(iconSource) } }), label: this.notification.label, }); } return m('div.change-password', [ notification, m(TextField, { name: 'password_old', label: i18n('profile.password.current'), floatingLabel: true, valid: this.valid_old, type: 'password', value: this.password_old, error: i18n('profile.password.errors.current'), events: { oninput: e => { this.password_old = e.target.value; this.valid_old = this.password_old.length > 0; this.validate(); }, }, }), m(TextField, { name: 'password1', label: i18n('profile.password.new'), floatingLabel: true, error: i18n('profile.password.requirements'), valid: this.valid_new1, type: 'password', value: this.password1, events: { oninput: e => { this.password1 = e.target.value; this.validate(); }, }, }), m(TextField, { name: 'password2', label: i18n('profile.password.repeatNew'), floatingLabel: true, valid: this.valid_new2, type: 'password', value: this.password2, error: i18n('profile.password.errors.notEqual'), events: { oninput: e => { this.password2 = e.target.value; this.validate(); }, }, }), buttons, ]); } }
JavaScript
class AbstractIntention { constructor(payload) { this.payload = payload; } toModel() { return this.payload; } toRequest() { return (0, adapter_1.mapIntention)(this.payload, this.map); } }
JavaScript
class Entity extends EventEmitter { /** * Do not instantiate this class directly, use the Engine.entity() method. * * @private * @param {String} name Entity name */ constructor(name) { super(); if (typeof name !== 'string') throw new Error('name must be a string'); this.name = name; this.components = {}; } /** * Returns this entity name * * @return {String} this entity name */ getName() { return _.clone(this.name); } /** * Check if the entity is associated to a component * * @param {String} componentName Name of the component * @return {Boolean} true if the entity has the component associated, false otherwise. */ hasComponent(componentName) { if (typeof componentName !== 'string') throw new Error('componentName must be a string'); return this.components[componentName] !== undefined; } /** * Associate the entity to a component. * The component can be any type. * * @param {String} componentName The component name * @param {*} componentData The component data */ setComponent(componentName, componentData) { if (typeof componentName !== 'string') throw new Error('componentName must be a string'); // If this is a new association update system vs entity associations let newComponent = false; if (this.components[componentName] === undefined) { newComponent = true; } // Set component data this.components[componentName] = componentData; if (newComponent) { this.emit('component:add', newComponent); } } /** * Retrieve a component by name * * @param {String} componentName The component name */ getComponent(componentName) { if (typeof componentName !== 'string') throw new Error('componentName must be a string'); return this.components[componentName]; } /** * Remove a component association * * @param {String} componentName */ deleteComponent(componentName) { if (typeof componentName !== 'string') throw new Error('componentName must be a string'); if (this.hasComponent(componentName)) { delete this.components[componentName]; // update system vs entity associations this.emit('component:remove', componentName); } } /** * Remove this entity from the engine */ destroy() { this.emit('entity:remove', this.name); } }
JavaScript
class MiddlewareSourceMapsPlugin { apply(compiler) { const PLUGIN_NAME = 'NextJsMiddlewareSourceMapsPlugin'; compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{ compilation.hooks.buildModule.tap(PLUGIN_NAME, (module)=>{ module.useSourceMap = module.layer === 'middleware'; }); }); } }
JavaScript
class SettingsService { constructor() { //on object creation load all settings and store them settingsPersistence.getAllSettings().then((settings) => { this.settings = settings //if a setting has not been persisted yet, set it to the default if (this.settings.autoplay === undefined || this.settings.autoplay === null) { this.settings.autoplay = constants.settings.defaults.autoplay } if (this.settings.capitalized === undefined || this.settings.capitalized === null) { this.settings.capitalized = constants.settings.defaults.capitalized } if (this.settings.repeat === undefined || this.settings.repeat === null) { this.settings.repeat = constants.settings.defaults.repeat } if (this.settings.extendedControls === undefined || this.settings.extendedControls === null) { this.settings.extendedControls = constants.settings.defaults.extendedControls } if (this.settings.muted === undefined || this.settings.muted === null) { this.settings.muted = constants.settings.defaults.muted } if (this.settings.showSeekbar === undefined || this.settings.showSeekbar === null) { this.settings.showSeekbar = constants.settings.defaults.showSeekbar } if (this.settings.overlay === undefined || this.settings.overlay === null) { this.settings.overlay = constants.settings.defaults.overlay } if (this.settings.reverseLearningDirection === undefined || this.settings.reverseLearningDirection === null) { this.settings.reverseLearningDirection = constants.settings.defaults.reverseLearningDirection } }) } async getSetting(key) { if(!this.settings) { return await this._getSetting(key) } else { return this.settings[key] } } async setSetting(key, value) { if(!this.settings) { this.settings = {} } this.settings[key] = value settingsPersistence.setSetting(key, value) } async _getSetting(key) { let setting = await settingsPersistence.getSetting(key) if(setting === undefined || setting === null) { setting = constants.settings.defaults[key] } return setting } /** * a function to visualize all text modalVisible to the user, * in this case capitalizes everything if the capitalized option is enabled */ visualizationFunction = (word) => { if (this.settings && this.settings.capitalized && word) { return word.toUpperCase() } else { return word } } /** * saves all values currently available in the persistence */ save() { for (let value in this.settings) { settingsPersistence.setSetting(value, settings[value]) } } }
JavaScript
class DataStream extends Stream.Readable { // Construct the class constructor(opt) { super(opt); this._remaining = contentSize; } // When the class is read _read(size) { if (this._remaining === 0) { this.push(null); } else { if (this._remaining < size) { // Push the remaining, set to 0 and finish read this.push(Buffer.alloc(this._remaining)); this._remaining = 0; } else { // Push the size being requested this.push(Buffer.alloc(size)); this._remaining = this._remaining - size; } } } }
JavaScript
class WorkerNode extends pc.EventHandler { constructor(id, nodePath, scriptsPath, templatesPath, useAmmo) { super(); this.id = id; this._worker = new Worker(nodePath, { workerData: { scriptsPath, templatesPath, useAmmo } }); this.channel = new Channel(this._worker); this.routes = { users: new Map(), rooms: new Map(), players: new Map(), networkEntities: new Map() }; this._worker.on('error', (err) => { console.error(err); this.fire('error', err); }); this.channel.on('_routes:add', ({ type, id }) => { this.routes[type].set(id, this); pn.routes[type].set(id, this); }); this.channel.on('_routes:remove', ({ type, id }) => { this.routes[type].delete(id); pn.routes[type].delete(id); }); this.channel.on('_user:message', ({ clientId, name, data, scope, msgId }) => { const client = pn.clients.get(clientId); if (client) client.send(name, data, scope, msgId); }); this.channel.on('_id:generate', (type, callback) => { callback(null, idProvider.make(type)); }); this.channel.on('_custom:message', ({ name, data }, callback) => { this.fire(name, data, callback); }); } send(name, data, callback) { this.channel.send('_custom:message', { name, data }, callback); } }
JavaScript
class Container { constructor() { /** * Actual container. */ this.container = { // Instantiated services services: new Map(), // Functions that return a service instantiators: new Map() }; } /** * Register a service instantiator. * @param force If not set to true and an instantiator has already been registered, an exception is thrown. */ set(id, instantiator, force = false) { if (!force && this.container.instantiators.has(id)) { throw `Tried to register twice service ${id} to DI container.`; } this.container.instantiators.set(id, instantiator); return this; } /** * Get asked service, instantiating it if not existent. */ get(id) { // if service already exists, return it const foundService = this.container.services.get(id); if (foundService !== undefined) { return foundService; } // otherwise instantiate it and return it const instantiator = this.container.instantiators.get(id); if (instantiator !== undefined) { const service = instantiator(); this.container.services.set(id, service); return service; } // service undefined throw `Tried to get non-existing service ${id}.`; } /** * Says if given service is registered. */ has(id) { return this.container.services.has(id) || this.container.instantiators.has(id); } }
JavaScript
class Ball { constructor(args){ this.x = args.x; //X position (center) this.y = args.y; //Y position (center) this.rad = args.rad; //Radius this.vec = args.vec; //Motion Vector this.color = args.color; // } /** * Called every frame */ timeStep(){ this.x = this.x+this.vec.x; this.y = this.y+this.vec.y; } /** * Called to render to a 2D context */ drawable(ctx){ ctx.beginPath(); ctx.arc(this.x, this.y, this.rad, 0, 2 * Math.PI, false); ctx.fillStyle = this.color; ctx.fill(); } }
JavaScript
class Paddle { constructor(args){ this.length = 150; //The "height" of the paddle this.width = 10; //The width of the paddle this.x = args.x; //The paddles top left x position this.y = args.y; //The paddles top left y position this.totalH = args.totalH; //The total height of the canvas this is in //TODO Make this dynamic this.direction = 0; //The direction that this paddle is moving (-1 up 1 down 0 not) this.speed = args.speed; //The speed factor to move this paddle at. this.color = "rgba(0,0,0,1)"; //The color of this paddle } /** * Called every frame */ timeStep(){ //Compute weather this is hitting the top or bottom (dont move further in that direction if so) if(this.y > 0 && this.direction < 0) this.y += this.direction*this.speed; else if(this.y < this.totalH-this.length && this.direction > 0) this.y += this.direction*this.speed; } /** * Called to render to a 2D context */ drawable(ctx){ ctx.fillStyle = this.color; ctx.fillRect(this.x,this.y,this.width,this.length); } }