language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class PfModalHeader extends HTMLElement { /* * An instance of the element is created or upgraded */ constructor () { super(); } /* * Called every time the element is inserted into the DOM */ connectedCallback () { pfUtil.addClass(this, 'modal-header'); if (!this.querySelector('.pf-hide-modal')) { this._template = document.createElement('template'); this._template.innerHTML = tmpl; this.appendChild(this._template.content); } if (this.modalTitle) { this._addModalTitle(); } } /* * Append cancel button * * @private */ _addModalTitle () { if (!this.querySelector('.modal-title')) { this.insertAdjacentHTML('beforeend', '<h4 class="modal-title">' + this.modalTitle + '</h4>'); } } /* * Get modal-title * * @returns {string} The modal title */ get modalTitle () { return this.getAttribute('modal-title'); } /* * Set modal-title * * @param {string} val Modal title */ set modalTitle (val) { if (val) { this.setAttribute('modal-title', val); } else { this.removeAttribute('modal-title'); } } /* * Only attributes listed in the observedAttributes property will receive this callback */ static get observedAttributes() { return ['modal-title']; } /* * Called when element's attribute value has changed * * @param {string} attrName The attribute name that has changed * @param {string} oldValue The old attribute value * @param {string} newValue The new attribute value */ attributeChangedCallback (attrName, oldValue, newValue) { if (attrName === 'modal-title') { if (newValue && !oldValue) { this._addModalTitle(); } if (newValue && oldValue) { this.querySelector('.modal-title').textContent = this.modalTitle; } if (!newValue) { let title = this.querySelector('.modal-title'); title.parentNode.removeChild(title); } } } }
JavaScript
class CorsBatchSender { constructor(config) { this._disableClientMetrics = this._disableClientMetrics.bind(this); this.sendDeferred = typeof window.requestIdleCallback === 'function' ? useRequestIdle : useSetTimeout; assign(this, defaultConfig, config); this._disabled = false; if (this.disableSending) { this._disableClientMetrics(); } this._eventQueue = []; } send(event) { this._eventQueue.push(event); this._sendBatches(); } flush() { this._sendBatches({ flush: true }); } getPendingEvents() { return this._eventQueue; } getMaxLength() { return this.maxLength; } _sendBatches(options) { let nextBatch = this._getNextBatch(options); while (nextBatch) { this._sendBatch(nextBatch); nextBatch = this._getNextBatch(options); } } _getNextBatch(options = {}) { if ( this._eventQueue.length === 0 || (this._eventQueue.length < this.minNumberOfEvents && !options.flush) ) { return null; } return this._eventQueue.splice(0, this.maxNumberOfEvents); } /** * Causes a batch to get sent out to the configured endpoint * * @private */ _sendBatch(batch) { if (!this._disabled) { this.onSend(batch); this.sendDeferred(() => this._makePOST(batch)); } } _disableClientMetrics() { this._disabled = true; } isDisabled() { return this._disabled; } _makePOST(events) { // from an array of individual events to an object of events with keys on them const data = events.reduce((acc, event, index) => { const eventToSend = appendIndexToKeys(omit(event, this.keysToIgnore), index); return assign(acc, eventToSend); }, {}); try { const xhr = createCorsXhr('POST', this.beaconUrl); if (xhr) { xhr.onerror = this._disableClientMetrics; xhr.send(JSON.stringify(data)); } else { this._disableClientMetrics(); } } catch (e) { this._disableClientMetrics(); } } }
JavaScript
class ClientComponentEndpoint extends ComponentEndpoint { /** * The DOM element visually representing this component instance. */ el; isInitialized; constructor() { super(); } get els() { return this.dom?.els; } /** * Use this to create the HTML node to represent this component. * * @virtual */ createEl() { this.logger.warn(this.debugTag, 'ClientComponentEndpoint did not implement `createEl`'); } /** * Use this to process your HTML node, at the end of the initialization phase. * * @virtual */ setupEl() { } init() { this.el = this.createEl(); if (!this.el) { throw new Error(`${this.debugTag} \`createEl\` must return a DOM element. If this component has no DOM, make sure to override \`init()\` instead.`); } // process DOM this.dom = new DOMWrapper(this); this.dom.process(); // call event this.setupEl(); } forceUpdate() { // tell host to update without a state change this._remoteInternal.forceUpdate(); } // ########################################################################### // private methods // ########################################################################### async _performInit() { await this.init(); this.isInitialized = true; } async _performUpdate() { try { await this.update(); } catch (err) { this.logger.error('Component update failed', err); } } // ########################################################################### // render utilities // ########################################################################### /** */ _repaint = () => { this.dom.repaint(); } // ########################################################################### // internally used remote commands // ########################################################################### /** * Functions that are called by Host internally. */ _publicInternal = { async updateClient(state) { this.state = state; await this._performUpdate(); }, dispose() { this.dom?.remove(); } }; toString() { return this.componentName; } }
JavaScript
class SituationApi { async getSituationsForLabels(labels) { return []; } async getLeafSituations(situation) { return []; } async getStemSituation(situation) { return null; } async getSituation(repositorySource, situationRepositoryUuId) { const situationDao = await container(this).get(SITUATION_DAO); return await situationDao.findByRepositoryUuId(repositorySource, situationRepositoryUuId); } async saveExistingSituation(situation) { if (!situation.repository || !situation.repository.id || !situation.actor || !situation.actor.id || !situation.actorRecordId) { throw new Error(`Cannot save EXISTING situation without a repository, actor or actorRecordId`); } const situationDao = await container(this).get(SITUATION_DAO); return await situationDao.saveExistingSituation(situation); } async saveNewSituation(situation) { situation.repository = null; situation.actor = null; delete situation.actorRecordId; const situationDao = await container(this).get(SITUATION_DAO); // const [entityStateManager, forumThreadApi, situationDao] = await container(this) // .get(ENTITY_STATE_MANAGER, FORUM_THREAD_API, SITUATION_DAO) // const forumThread = await forumThreadApi.createNew() // const forumThreadStub: IForumThread = { // actor: { // id: forumThread.actor.id // }, // actorRecordId: forumThread.actorRecordId, // repository: { // id: forumThread.repository.id // }, // } as IForumThread // entityStateManager.markAsStub(forumThreadStub) // situation.thread = forumThreadStub return await situationDao.saveNewSituation(situation); } }
JavaScript
class Container extends Component { static propTypes = { handleClick: PropTypes.func.isRequired, }; render() { return <UserDisplay {...this.props} />; } }
JavaScript
class Hexagon extends Tile { /** * Constructs the object. * * @param {Object|CubeCoordinates} coordinates The coordinates * @param {Object} options The options * @param {Boolean} options.interactive Set to true if the hexagon can catch mouse events. * @param {PIXI.Texture} options.texture Set texture if you need a sprite instead of an hexagon. * @param {Orientation} options.orientation Pointy or flatty topped hexagon. * @param {Number} options.radius radius of the hexagon to draw. * @param {Number} options.tint Color of the hexagon, formatted like `0xff5544`. * @param {Number} options.lineColor Color of the line to draw, formatted like `0xff5544`. (ignored if texture is used) * @param {Number} options.fillColor Color of the hexagon to draw, formatted like `0xff5544`. (ignored if texture is used) */ constructor (coordinates, options = {}) { super(coordinates) this.updateDisplayObject(options) // Make reactive if (options.interactive) { this.displayObject.interactive = true this.displayObject.buttonMode = true } this.displayObject.tint = options.tint || 0xFFFFFF } set tint (value) { if (this.displayObject) this.displayObject.tint = value } get tint () { return this.displayObject ? this.displayObject.tint : undefined } toString () { return `Hexagon{${this.coordinates}}` } updateDisplayObject (options) { if (this.displayObject) this.removeChild(this.displayObject) if (options.texture) { this.displayObject = PIXI.Sprite.from(options.texture) this.displayObject.anchor.set(0.5) } else { this.displayObject = drawHexagon( options.orientation || Orientation.FLAT_TOP, options.radius || 25, options.lineColor || 0xffffff, options.fillColor || 0xffffff ) } this.addChild(this.displayObject) } }
JavaScript
class PassportExtractor { constructor(profile = {}) { this.profile = profile; } get provider() { if (!this.profile.provider) { throw new Error('No provider'); } return this.profile.provider.toLowerCase(); } get firstname() { switch (this.provider) { case 'facebook': if (this.profile.name.givenName) { return this.profile.name.givenName; } break; case 'twitter': if (this.profile.displayName) { return this.profile.displayName; } break; default: throw new Error('Provider "' + this.provider + '" not supported for firstname'); } return ''; } get lastname() { switch (this.provider) { case 'facebook': if (this.profile.name.familyName) { return this.profile.name.familyName; } break; case 'twitter': break; default: throw new Error('Provider "' + this.provider + '" not supported for lastname'); } return ''; } get email() { switch (this.provider) { case 'facebook': if (this.profile.emails) { return this.profile.emails[0].value; } break; case 'twitter': break; default: throw new Error('Provider "' + this.provider + '" not supported for email'); } return ''; } get gender() { switch (this.provider) { case 'facebook': if (this.profile.gender && this.profile.gender !== '') { return this.profile.gender; } break; case 'twitter': break; default: throw new Error('Provider "' + this.provider + '" not supported for gender'); } return ''; } get username() { switch (this.provider) { case 'facebook': case 'twitter': if (this.profile.username && this.profile.username !== '') { return this.profile.username; } break; default: throw new Error('Provider "' + this.provider + '" not supported for username'); } return ''; } buildUsername() { if (this.username) { return this.cleanUsername(this.username); } if (this.firstname) { return this.cleanUsername(this.firstname); } if (this.lastname) { return this.cleanUsername(this.lastname); } throw new Error('Unable to build a username from the profile'); } cleanUsername(username) { return username.replace(/[^a-zA-Z0-9]/, '').toLowerCase(); } }
JavaScript
class TransactionTable extends Component { state = { transactions : [], openTxInfo: false, activateHash: '', page: 1 }; constructor(){ super(); this.loadTransactions = this.loadTransactions.bind(this); } handleTxInfoOpen = ( hash ) => { this.setState({ openTxInfo: true, activateHash: hash }); } handleTxInfoClose = () => { this.setState({ openTxInfo: false, activatehash: '' }) } handleChangePage = ( event, page ) => { this.setState({ page }); } async loadTransactions(){ let transactions = []; let response = await axios({ method: 'POST', dataType: 'json', url: 'http://localhost:3000/addr/crp', data: { addr: this.props.address } }).catch( (error) => { console.error(error); response.data = { data: [] } }); for( var data of response.data.data ){ let transaction = await web3.eth.getTransaction( data[0] ); if( transaction == null ) continue; transactions.push({ id: transaction.hash, hash: transaction.hash, blockNumber: transaction.blockNumber, from: transaction.from, to: transaction.to, value: web3._extend.utils.fromWei(transaction.value.toString()) }); } this.setState({ transactions: transactions }); } async componentWillMount(){ await this.loadTransactions(); } render() { return ( <div className="transactions"> <Table className="transaction-table"> <TableHead> <TableRow> <TableCell className="table-cell-medium"> Transaction Hash </TableCell> <TableCell className="table-cell-small"> Block </TableCell> <TableCell className="table-cell-medium"> From </TableCell> <TableCell> </TableCell> <TableCell className="table-cell-medium"> To </TableCell> <TableCell className="table-cell-small"> Value </TableCell> </TableRow> </TableHead> <TableBody> { this.state.transactions.slice( this.state.page * 10, this.state.page * 10 + 10 ).map((item, index) => { return ( <TableRow key={index}> <TableCell className="transaction-table-td" align="center"> <a href="#" onClick={this.handleTxInfoOpen.bind(this, item.hash)}>{item.hash}</a> </TableCell> <TableCell className="transaction-table-td">{item.blockNumber}</TableCell> <TableCell className="transaction-table-td">{item.from}</TableCell> <TableCell className="transaction-table-td" align="center"> <img className="icon-xsmall" src={path.join(__dirname, '../public/imgs/next.png')}/> </TableCell> <TableCell className="transaction-table-td">{item.to}</TableCell> <TableCell className="transaction-table-td" align="right">{item.value} CRP</TableCell> </TableRow> ); }) } </TableBody> <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[10]} colSpan={3} count={this.state.transactions.length} rowsPerPage={10} page={this.state.page} onChangePage={this.handleChangePage} /> <TableCell> <IconButton onClick={this.loadTransactions} aria-label="reload"> <RefreshIcon fontSize="small"/> </IconButton> </TableCell> </TableRow> </TableFooter> </Table> <Dialog maxWidth={false} open={this.state.openTxInfo} onClose={this.handleTxInfoClose} > <Transaction closeAction={this.handleTxInfoClose} hash={this.state.activateHash} /> </Dialog> </div> ); } }
JavaScript
class Storage { // Querying to blockchain for getting blockchain info getMCInfo() { mc.getInfo((err, info) => { if (err) { return err; } }); } // Querying to blockchain for creating new address. getNewAddress(callback) { mc.getNewAddress((err, address) => { if (err) { return callback(err, null); } else { callback(null, address); } }); } // Querying to blockchain for getting addreses from the blockchain. getAddresses(callback) { mc.getAddresses((err, addresses) => { if (err) { return callback(err, null); } else { callback(null, addresses); } }); } // Used to send smart assest form one address to another address. validateAddress(address, callback) { mc.validateAddress({ address: address }, (err, is_valid) => { if (err) { return callback(err, null); } else { callback(null, is_valid); } }); } // Granting Permissions for an address. grant(addresses, permissions, callback) { mc.grant({ addresses: addresses, permissions: permissions }, (err, is_granted) => { if (err) { return callback(err, null); } else { callback(null, true); } }); } // Querying data form the blockchain by passing stream name and key as parameters. getMostRecentStreamDatumForKey(stream_name, key, callback) { var that = this; // get the recent data in blockchain based on stream and key that.listStreamKeyItems(stream_name, key, 1, -1, (err, result) => { // return error in callback result if api fails if (err) { return callback(err, null) }; // check if result is not null and empty if (result && result.length) { // get the data from the result that.getDataFromDataItem(result[0]["data"], (err, data_item) => { if (err) { return callback(err, null); } else { callback(null, data_item); } }); } else { // return error in callback result as no items found callback(null, null); } }); } getDataFromDataItem(dataItem, callback) { // check if data is string if (typeof dataItem == 'string') { // convert the hex data to json object let data = common_utility.hex2json(dataItem); // return the data in callback as success callback(null, data); } else { // get the data from the blockchain by transaction id mc.getTxOutData({ txid: dataItem["txid"], vout: dataItem["vout"] }, (err, result) => { // return error in callback result if api fails if (err) callback(err, null); // convert the hex data to json object let data = common_utility.hex2json(result); // return the data in callback as success callback(null, data); }); } } // Pushing data to the blockchain publishDataToBlockchain(stream_name, key, data, address, callback) { if (address == null) { mc.publish({ stream: stream_name, key: key, data: data }, (err, publish_txid) => { if (err) { return callback(err, null); } else { callback(null, publish_txid); } }); } else { mc.publishFrom({ from: address, stream: stream_name, key: key, data: data }, (err, publish_txid) => { if (err) { return callback(err, null); } else { callback(null, publish_txid); } }); } } // This function is called from web application to push fromData and files to the blockchain. uploadFormDataToBlockchain(formData, key, address, data_stream_name, files = null, file_stream_name = null, callback) { let that = this; // check if file stream name is null the assign the data stream name if (!file_stream_name) file_stream_name = data_stream_name; let form_data = {}; // iterate through all formData object keys and add to form_data Object.keys(formData).forEach(function (_key) { form_data[_key] = formData[_key]; }); // check if files data object is not empty and has keys/values if (files && Object.keys(files).length) { let files_hash = {}; // upload the files to blockchain by iterating through files data object keys. // As the blockchain api is an async call, create promise objects with sucess(resolve) / failure(reject) details and assign its references to variable (promises array) var promises = Object.keys(files).map(function (_key) { // create new promise which returns success/failure of blockchain api call for uploading the file return new Promise(function (resolve, reject) { // create file object which needs to be saved in blockchain let file_info = { name: files[_key].name, mimetype: files[_key].mimetype, data: common_utility.bin2hex(files[_key].data) }; // get the file hash from the uploaded file data let file_hash = common_utility.getFileHash(files[_key].data); // assign the file hash to the file object files_hash[_key] = file_hash; // convert the json object to hexadecimal let file_data = common_utility.json2hex(file_info); // publish file data to blockchain that.publishDataToBlockchain(file_stream_name, file_hash, file_data, address, (err, result) => { // fail the api call (promise) by rejecting it and pass the error details as a parameter if (err) reject(err); // mark the api call (promise) as success by resolving it and pass the success result as a parameter resolve(); }); }); }); // wait till all api calls (promises) for uploading files in blockchain are proccessed Promise.all(promises).then(function () { // assign the uploaded files hashes to form data object if (files_hash && Object.keys(files_hash).length) form_data['files'] = files_hash; // convert the json object to hexadecimal let data = common_utility.json2hex(form_data); // publish the form data to blockchain that.publishDataToBlockchain(data_stream_name, key, data, address, callback); }).catch((err) => { // return error in callback if any of the api call fails callback(err, null); }); } else { // convert the json object to hexadecimal let data = common_utility.json2hex(form_data); // publish the form data to blockchain that.publishDataToBlockchain(data_stream_name, key, data, address, callback); } } // This function is called from web application to push fromData and files to the blockchain. the file will encrypted using aes-256-gcm algorithm. encryptAndUploadFormDataToBlockchain(password, iv, formData, key, address, data_stream_name, documents = null, document_stream_name = null, callback) { let that = this; // check if documents stream name is null the assign the data stream name if (!document_stream_name) document_stream_name = data_stream_name; let form_data = {}; // iterate through all formData object keys and add to form_data Object.keys(formData).forEach(function (_key) { form_data[_key] = formData[_key]; }); // check if documents data object is not empty and has keys/values if (documents && Object.keys(documents).length) { let documents_hash = {}; // upload the documents to blockchain by iterating through documents data object keys. // As the blockchain api is an async call, create promise objects with success(resolve) / failure(reject) details and assign its references to variable (promises array) var promises = Object.keys(documents).map(function (_key) { // create new promise which returns success/failure of blockchain api call for uploading the document return new Promise(function (resolve, reject) { // create document object which needs to be saved in blockchain let document_info = { name: documents[_key].name, mimetype: documents[_key].mimetype, data: common_utility.bin2hex(documents[_key].data) }; // get the document hash from the uploaded document data let document_hash = common_utility.getDocumentHash(documents[_key].data); // assign the document hash to the document object documents_hash[_key] = document_hash; // convert the json object to hexadecimal let document_data = common_utility.json2str(document_info); // encrypt the document data let encrypted_document_data = common_utility.encryptiv(document_data, password, iv); let encrypted_document_data_hex = common_utility.json2hex(encrypted_document_data); // publish document data to blockchain that.publishDataToBlockchain(document_stream_name, document_hash, encrypted_document_data_hex, address, (err, document_txid) => { // fail the api call (promise) by rejecting it and pass the error details as a parameter if (err) reject(err); // mark the api call (promise) as success by resolving it and pass the success result as a parameter resolve({ document_txid: document_txid }); }); }); }); // wait till all api calls (promises) for uploading documents in blockchain are proccessed Promise.all(promises).then(function (documents_result) { // assign the uploaded documents hashes to form data object if (documents_hash && Object.keys(documents_hash).length) form_data['document'] = documents_hash; // convert the json object to hexadecimal let data = common_utility.json2hex(form_data); // publish the form data to blockchain that.publishDataToBlockchain(data_stream_name, key, data, address, (err, txid) => { if (err) { return callback(err, null); } else { let transactionIds = { form_txid: txid, document_txid: documents_result[0]["document_txid"] }; callback(null, transactionIds); } }); }).catch((err) => { // return error in callback if any of the api call fails callback(err, null); }); } else { // convert the json object to hexadecimal let data = common_utility.json2hex(form_data); // publish the form data to blockchain that.publishDataToBlockchain(data_stream_name, key, data, address, (err, txid) => { if (err) { return callback(err, null); } else { callback(null, txid); } }); } } // Digitally sigining the data. signMessage(address, message, callback) { mc.signMessage({ address: address, message: message }, (err, signature) => { if (err) { return callback(err, null); } else { callback(null, signature); } }); } // Verfiying the signature by pasiing the address, signature, and message verifySignature(address, signature, message, callback) { mc.verifyMessage({ address: address, signature: signature, message: message }, (err, is_verified) => { if (err) { return callback(err, null); } else { callback(null, true); } }); } // Signing the documents and push to the blockchain. signDocuments(address, documents, signature_stream, callback) { let that = this; // upload the documents to blockchain by iterating through documents data object keys. // As the blockchain api is an async call, create promise objects with sucess(resolve) / failure(reject) details and assign its references to variable (promises array) var promises = Object.keys(documents).map(function (_key) { // create new promise which returns success/failure of blockchain api call for uploading the document return new Promise(function (resolve, reject) { // get the document hash from the uploaded document data let document_hash = common_utility.getDocumentHash(documents[_key].data); that.signMessage(address, document_hash, (err, signature) => { // fail the api call (promise) by rejecting it and pass the error details as a parameter if (err) reject(err); // convert the signature to hex let signatureInHex = common_utility.bin2hex(signature); that.publishDataToBlockchain(signature_stream, document_hash, signatureInHex, address, (err, result) => { // fail the api call (promise) by rejecting it and pass the error details as a parameter if (err) reject(err); // mark the api call (promise) as success by resolving it and pass the success result as a parameter resolve({ signature_transaction_id: result }); }); }); }); }); Promise.all(promises).then(function (result) { // return result in callback if any of the api call fails callback(null, result); }).catch((err) => { // return error in callback if any of the api call fails callback(err, null); }); } // Querying data from a particular stream from blockchain. getStreamItems(stream_name, count, start, callback) { mc.listStreamItems({ "stream": stream_name, "verbose": false, "count": count, "start": start, "local-ordering": true }, (err, stream_items) => { if (err) { return callback(err, null); } else { callback(null, stream_items); } }); } // Querying data from a particular stream from blockchain. listStreamItems(stream_name, callback) { this.getStreamItems(stream_name, 999999, -999999, (err, stream_items) => { if (err) { return callback(err, null); } else { callback(null, stream_items); } }); } // Querying data from the blockchain by passing stream name and txid. getStreamItem(stream_name, txid, callback) { mc.getStreamItem({ "stream": stream_name, "txid": txid, "verbose": true }, (err, stream_item) => { if (err) { return callback(err, null); } else { callback(null, stream_item); } }); } // Querying data from the blockchain by passing stream name and address. getPublisherStreamItems(stream_name, address, count, start, callback) { mc.listStreamPublisherItems({ "stream": stream_name, "address": address, "verbose": false, "count": count, "start": start, "local-ordering": true }, (err, publisher_items) => { if (err) { return callback(err, null); } else { callback(null, publisher_items); } }); } // Querying data from the blockchain by passing stream name and address listStreamPublisherItems(stream_name, address, callback) { this.getPublisherStreamItems(stream_name, address, 999999, -999999, (err, publisher_items) => { if (err) { return callback(err, null); } else { callback(null, publisher_items); } }); } // Querying data from the blockchain by sending stream name. getStreamKeys(stream_name, count, start, callback) { mc.listStreamKeys({ "stream": stream_name, "key": "*", "verbose": false, "count": count, "start": start, "local-ordering": true }, (err, stream_keys) => { if (err) { return callback(err, null); } else { callback(null, stream_keys); } }); } // Querying data from the blockchain by sending stream name and key. listStreamKeys(stream_name, callback) { this.getStreamKeys(stream_name, 999999, -999999, (err, stream_keys) => { if (err) { return callback(err, null); } else { callback(null, stream_keys); } }); } // Querying data from the blockchain by sending stream name and key. listStreamKeyItems(stream_name, key, count, start, callback) { mc.listStreamKeyItems({ stream: stream_name, key: key, verbose: true, count: count, start: start, "local-ordering": true }, (err, stream_key_items) => { if (err) { return callback(err, null); } else { callback(null, stream_key_items); } }); } // Fetching information from blockchain by passing txid. getTransactionInfo(txid, callback) { mc.getTxOut({ txid: txid, vout: 1 }, (err, tx_info) => { if (err) { return callback(err, null); } else { callback(null, tx_info); } }); } // Fetching data from blockchain by sending txid and vout. getTransactionData(txid, vout, callback) { mc.getTxOutData({ txid: txid, vout: vout }, (err, data_hex) => { if (err) { return callback(err, null); } else { callback(null, data_hex); } }); } }
JavaScript
class random { //get random number between 'min' and 'max' (both included) static range(min, max) { return Math.random() * (max - min + 1) + min; } }
JavaScript
class vector { //opposite direction static flip(v) { return { x: -v.y, y: v.x }; } //lenght, or magnitude as you like static length(v) { return Math.sqrt(v.x * v.x + v.y * v.y); } //normalize the vector static norm(v) { const length = vector.length(v); return vector.mul(v, 1 / length); } //add 2 vector static add(lhs, rhs) { return { x: lhs.x + rhs.x, y: lhs.y + rhs.y }; } //subtract 2 vector static sub(lhs, rhs) { return { x: lhs.x - rhs.x, y: lhs.y - rhs.y }; } //multiply a vector with a skalar static mul(v, sk) { return { x: v.x * sk, y: v.y * sk }; } //dot product of lhs and rhs static dot(lhs, rhs) { return lhs.x * rhs.x + lhs.y * rhs.y; } }
JavaScript
class Scope { constructor (m) { this.loop = _evalGenerator(m) // Init this.loop.next() // reach yield } run (code, cb) { this.loop.next({ code, cb }) } }
JavaScript
class Character { // Character constructor constructor(name = '') { // Character Name this.name = name; // Character Stats this.health = Math.floor(Math.random() * 10 + 95); this.strength = Math.floor(Math.random() * 5 + 7); this.agility = Math.floor(Math.random() * 5 + 7); } // Character Methods // Check to see if the character is alive isAlive() { if (this.health === 0) { return false; } return true; }; // Get character's health value getHealth() { return `${this.name}'s health is now ${this.health}!`; }; // Get the character's attack value based on their strength stat getAttackValue() { const min = this.strength - 5; const max = this.strength + 5; return Math.floor(Math.random() * (max - min) + min); }; // Reduce the character's health after being attacked reduceHealth(health) { this.health -= health; if (this.health < 0) { this.health = 0; } }; }
JavaScript
class Actions { /** *Creates an instance of Actions. * @memberof Actions */ constructor () { this.surveyBody = this.renderInstance().queryParentBody(); this.range = []; } /** * Create Singleton Render Instance * * @returns Render * @memberof Actions */ renderInstance () { return new Render; } /** * Bind events with pagination list * * @memberof Actions */ chosenEventListener () { document .querySelector( '.pagination-list' ) .addEventListener( 'click', this.activateSurvey.bind( this ) ); } /** * Activate Survey and display voc table * * @param {*} e * @memberof Actions */ activateSurvey ( e ) { let event = e || event, target = event.target; if (target.tagName.toLowerCase() !== 'a') return document.querySelector('.greeting').classList.remove('showing'); document.querySelector('.trainer').classList.add('showing'); this.range = target.innerHTML.split(' - '); this.rangeCaching = parseInt(this.range[0]) - 1, parseInt(this.range[1]) - 1; this.renderInstance().imutate(this.rangeCaching); this.docking() } /** * Docking with Survey Table * * @memberof Actions */ docking () { this.surveyBody.addEventListener('click', this.selectEvent.bind(this)) } /** * Chose the right or incorrect word * * @param {*} e * @memberof Actions */ selectEvent (e) { let event = e || event, target = event.target; if (target.tagName.toLowerCase() !== 'td') return this.selectCheck(target) ? this.successTick(target) : this.dangerTick(target); } /** * Check Words correct * * @param {*} target * @returns * @memberof Actions */ selectCheck ( target ) { return JSON.parse(target.parentElement.getAttribute('correct')) } /** * Inccorect Counter * * @param {*} target * @memberof Actions */ dangerTick ( target ) { target.parentElement.classList.add('has-background-danger') // if doesn't correct choise select the correct row line this.surveyBody.querySelector(`[correct="true"]`) .classList.add('has-background-success') this.tick(); this.renderInstance().incorrect++; this.renderInstance().score(); } /** * Correct Counter * * @param {*} target * @memberof Actions */ successTick ( target ) { target.parentElement.classList.add('has-background-success') this.tick() this.renderInstance().correct++; this.renderInstance().score(); } /** * Transition to the next scene * * @memberof Actions */ tick () { setTimeout(this.tickRunner.bind(this), 1000); } /** * Transition Runner * * @returns * @memberof Actions */ tickRunner () { if (this.renderInstance().start === this.renderInstance().dictionary.slice(this.rangeCaching).length - 1) { return this.renderInstance().trainingEnd(); } ++this.renderInstance().start; // i need the call imutate with new RANGE this.renderInstance().imutate(this.rangeCaching); } }
JavaScript
class MoneyTransferDialog extends Component { initialState = { // TextField values customerName: '', transferAmount: '', // search state is null targetCustomers: [], // The selected CustomerBO selectedCustomer: null, // Selected accountBO in the accounts array selectedAccount: null, // TextField validation errors transferAmountValidationFailed: false, transferAmountFieldEdited: false, // Network states loadingInProgress: false, customerSearchError: null, transactionError: null }; constructor(props) { super(props); // Init the state this.state = this.initialState; } /** Searches for customers with a customerName and loads the corresponding accounts */ searchCustomer = async () => { const { customerName } = this.state; if (customerName.length > 0) { try { // set loading to true this.setState({ targetCustomers: [], // Set empty array selectedCustomer: null, // the initial customer loadingInProgress: true, // show loading indicator customerSearchError: null // disable error message }); // Load customers first const customers = await BankAPI.getAPI().searchCustomer(customerName); // load accounts of each customers step by step and inject the acounts into the CustomerBO for (const customer of customers) { // Load account for each found customer let accounts = await BankAPI.getAPI().getAccountsForCustomer(customer.getID()); // Call sucessfull customer.accounts = accounts; } // Init the selections let selectedCustomer = null; let selectedAccount = null; if (customers.length > 0) { selectedCustomer = customers[0]; } if (selectedCustomer.accounts.length > 0) { selectedAccount = selectedCustomer.accounts[0]; } // Set the final state this.setState({ targetCustomers: customers, selectedCustomer: selectedCustomer, // the initially selected customer selectedAccount: selectedAccount, // the initially selected account loadingInProgress: false, // disable loading indicator customerSearchError: null // no error message }); } catch (e) { this.setState({ targetCustomers: [], // Set empty array selectedCustomer: null, loadingInProgress: false, // disable loading indicator customerSearchError: e // show error message }); } } else { this.setState({ customerNotFound: true }); } } /** Executes the requested transfer transaction */ transferMoney = () => { const { account } = this.props; const { selectedAccount, transferAmount } = this.state; let amount = transferAmount.replace(/,/g, '.'); const transaction = new TransactionBO(account.getID(), selectedAccount.getID(), amount); BankAPI.getAPI().addTransaction(transaction).then(transaction => { this.setState({ loadingInProgress: false, // disable loading indicator transactionError: null // show error message }); this.handleClose(transaction); }).catch(e => { this.setState({ loadingInProgress: false, // disable loading indicator transactionError: e // show error message }); }); this.setState({ loadingInProgress: true, // disable loading indicator transactionError: null // show error message }); } /** Handles the close / cancel button click event */ handleClose = (transaction) => { // Reset the state this.setState(this.initialState); this.props.onClose(transaction); } /** Handles value changes of the forms textfields and validates the transferAmout field */ textFieldValueChange = (event) => { const val = event.target.value; // Validate the amount field if (event.target.id === 'transferAmount') { let result = false; let amount = val.replace(/,/g, '.'); if (amount.length === 0) { // length must not be 0 result = true; } if (isNaN(amount)) { // Its not a numer in the text field result = true; } this.setState({ transferAmountValidationFailed: result, transferAmountFieldEdited: true }); } this.setState({ [event.target.id]: val }); } /** Handles value changes of the customer select textfield */ customerSelectionChange = (event) => { let customer = event.target.value; let selectedAccount = null; if (customer.accounts.length > 0) { selectedAccount = customer.accounts[0] } this.setState({ selectedCustomer: customer, selectedAccount: selectedAccount, }); } /** Handles value changes of the customer select textfield */ accountSelectionChange = (event) => { let selectedAccount = event.target.value; this.setState({ selectedAccount: selectedAccount }); } /** Renders the component */ render() { const { classes, show, customer, account } = this.props; const { customerName, targetCustomers, selectedCustomer, customerNotFound, selectedAccount, loadingInProgress, transferAmountValidationFailed, transferAmountFieldEdited, customerSearchError, transactionError } = this.state; return ( show ? <Dialog open={show} onClose={this.handleClose} maxWidth='md'> <DialogTitle id='form-dialog-title'>Transfer money <IconButton className={classes.closeButton} onClick={this.handleClose}> <CloseIcon /> </IconButton> </DialogTitle> <DialogContent> <Grid container spacing={1}> <Grid item xs={6}> <Typography variant='body1'> From customer: {customer.getLastName()}, {customer.getFirstName()} </Typography> </Grid> <Grid item xs={6}> <Typography variant='body1'> Account: {account.getID()} </Typography> </Grid> </Grid> <Typography variant='body1'> <br/> to customer: </Typography> <form noValidate autoComplete='off'> { // show a search text field if there are no searchedCustomer yet (targetCustomers.length === 0) ? <TextField autoFocus fullWidth margin='normal' type='text' required id='customerName' label='Customer name:' onChange={this.textFieldValueChange} onBlur={this.searchCustomer} error={customerNotFound} helperText={customerNotFound ? 'No customers with the given name have been found' : ' '} InputProps={{ endAdornment: <InputAdornment position='end'> <IconButton onClick={this.searchCustomer}> <SearchIcon /> </IconButton> </InputAdornment>, }} /> : // Show a selection of targetCustomers, if there are any. Provide no search button. <TextField select autoFocus fullWidth margin='normal' type='text' required id='customerName' label='Customer name:' value={selectedCustomer} onChange={this.customerSelectionChange}> { this.state.targetCustomers.map((customer) => ( <MenuItem key={customer.getID()} value={customer}> {customer.getLastName()}, {customer.getFirstName()} </MenuItem> )) } </TextField> } { // Render the account select field selectedAccount ? <TextField select fullWidth margin='normal' type='text' required id='account' label='Target account:' value={selectedAccount} onChange={this.accountSelectionChange}> { selectedCustomer.accounts.map((account) => ( <MenuItem key={account.getID()} value={account}> {account.getID()} </MenuItem> )) } </TextField> : <TextField select fullWidth margin='normal' type='text' required id='account' label='Target account:' value={0} onChange={this.accountSelectionChange}> <MenuItem value={0}> No accounts found </MenuItem> </TextField> } <TextField fullWidth margin='normal' type='text' required id='transferAmount' label='Amount:' onChange={this.textFieldValueChange} error={transferAmountValidationFailed} helperText={transferAmountValidationFailed ? 'The amount must be a number' : ' '} InputProps={{ startAdornment: <InputAdornment position='start'>{BankAPI.getAPI().getCurrency()} </InputAdornment>, }} /> </form> <LoadingProgress show={loadingInProgress} /> <ContextErrorMessage error={customerSearchError} contextErrorMsg={`Customer ${customerName} could not be searched.`} onReload={this.searchCustomer} /> <ContextErrorMessage error={transactionError} contextErrorMsg={`Transaction could not be executed.`} onReload={this.transferMoney} /> </DialogContent> <DialogActions> <Button onClick={this.handleClose} color='secondary'> Cancel </Button> <Button disabled={!selectedCustomer || !selectedAccount || !transferAmountFieldEdited || transferAmountValidationFailed} variant='contained' color='primary' onClick={this.transferMoney}> Transfer </Button> </DialogActions> </Dialog> : null ); } }
JavaScript
class EditableText extends React.Component { /** * * @param {Object} props * @param {string} props.className * @param {string} [props.mode=MODE_BUTTON] * @param {string} props.label - Label to display * @param {function(string)} props.onChange */ constructor(props) { super(props); this.enableUpdate = this.enableUpdate.bind(this); this.disableUpdate = this.disableUpdate.bind(this); this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); this.state = {updatable : this.mode === MODE_DIRECT}; } // ============================== // Component methods /** * Disable the edit mode * @public */ disableUpdate() { this.toggleUpdate(false); } /** * Enable the edit mode * @public */ enableUpdate() { this.toggleUpdate(true); this.focus(); } /** * Focus on the component * @public */ focus() { this.inputElement.focus(); } /** * Listener trigger each time the input change * @param {Event} event * @private */ onChange(event) { this.props.onChange(event.target.value); } /** * Listener trigger each time the form is submit * @param {Event} event * @private */ onSubmit(event) { event.preventDefault(); this.disableUpdate(); } /** * Toggle the edit mode * @param {boolean} [updatable] * @public */ toggleUpdate(updatable) { if (this.props.mode !== MODE_BUTTON) return; if (typeof updatable === 'undefined') updatable = !this.state.updatable; this.setState({...this.state , updatable: updatable}); } // ============================== // React methods componentDidMount() { this.focus(); } componentDidUpdate() { if (!this.state.updatable) return; this.focus(); } render() { let renameButton; if (this.props.mode === MODE_BUTTON) renameButton = <RenameButton onClick={this.enableUpdate}/>; return ( <form onSubmit={this.onSubmit} data-mode={this.props.mode} className={`editable-text ${this.props.className}`}> <input disabled={!this.state.updatable} onChange={this.onChange} onBlur={this.disableUpdate} ref={input => { this.inputElement = input; }} type="text" value={this.props.label}/> {renameButton} </form> ); } }
JavaScript
class NetworkClientFactory extends factoryBase_1.FactoryBase { /** * Don't allow manual construction of the factory. * @internal */ constructor() { super(); } /** * Get the instance of the factory. * @returns The factory instance. */ static instance() { if (!NetworkClientFactory._instance) { NetworkClientFactory._instance = new NetworkClientFactory(); } return NetworkClientFactory._instance; } /* @internal */ getInstance() { return NetworkClientFactory.instance(); } }
JavaScript
class OrTaskHandler extends MultiSubtaskHandler { /** * Creates a new Or task handler. */ constructor (goalSolver) { super('or', goalSolver) } /** @inheritdoc */ async getHeuristic (task) { if (task.taskType !== this.taskType) return null const { next } = await this.getNextSubtask(task.subtasks, task.searchDepth, task.easiestFirst) if (next == null) return null const heuristic = new Heuristic(this) heuristic.childTasks.push(next) return heuristic } /** @inheritdoc */ async execute (task) { // Make a copy of the subtask list to avoid editing the original object. const subtasks = [...task.subtasks] const errors = [] while (subtasks.length > 0) { const { next } = this.getNextSubtask(subtasks, task.searchDepth, task.easiestFirst) subtasks.splice(subtasks.indexOf(next), 1) try { await this.goalSolver.execute(next) return } catch (err) { errors.push(errors) } } throw new AggregateError(errors, 'All subtasks failed!') } }
JavaScript
class StorageS3 { constructor(options={}) { const {basePath="", bucket} = options; this.s3 = getAwsService("S3", options); this.bucket = bucket; this.basePath = basePath[0] === "/" ? basePath.substr(1) : basePath; } createReadStream(path, {start, end}={}) { return new Promise((resolve, reject) => { const _handleError = err => { reject(this._normalizeError(err, path)); }; const req = this.s3.getObject({ Bucket: this.bucket, Key: this._getKey(path), Range: start !== undefined && end !== undefined ? "bytes=" + start + "-" + end : undefined }); req.on("httpHeaders", status => { if (status >= 200 && status < 300) { stream.removeListener("error", _handleError); resolve(stream); } }); const stream = req.createReadStream(); stream.once("error", _handleError); return stream; }); } readFile(path) { return this.s3.getObject({ Bucket: this.bucket, Key: this._getKey(path) }).promise().then(data => { return data.Body; }).catch(err => { throw this._normalizeError(err, path); }); } // Intermediate directories don't matter because S3 doesn't have directories. // Data can be a Buffer, string or readable stream. // Returns a promise resolved when done. writeFile(path, data) { return this.s3.upload({ Bucket: this.bucket, Key: this._getKey(path), Body: data }, { partSize: 5*1024*1024, queueSize: 1 }).promise(); } // Works on files only. exists(path) { return this.s3.headObject({ Bucket: this.bucket, Key: this._getKey(path) }).promise().then(() => true, err => { if (err.code === "NoSuchKey" || err.code === "NotFound") return false; throw err; }); } // Works on files only. stat(path) { return this.s3.headObject({ Bucket: this.bucket, Key: this._getKey(path) }).promise().then(data => { return { size: parseInt(data.ContentLength, 10), mtime: data.LastModified }; }).catch(err => { throw this._normalizeError(err, path); }); } unlink(path) { return this.s3.deleteObject({ Bucket: this.bucket, Key: this._getKey(path) }).promise(); } // Gets an array of the file object as follows: // [{name: "file_name", mtime: <Date>, size: <Number>}, ...] // Only files are returned (no directories). // `chunkSize` is a S3 specific option and for debugging / testing only. listFiles(path, {chunkSize=1000}={}) { let prefix = posix.join(this._getKey(path), "/"); const files = []; let startAfter; if (prefix === "/") prefix = ""; return promiseRepeat(() => { return this.s3.listObjectsV2({ Bucket: this.bucket, Prefix: prefix, MaxKeys: chunkSize, StartAfter: startAfter }).promise().then(data => { const items = data.Contents; items.forEach(item => { const name = item.Key.substr(prefix.length); if (name.lastIndexOf("/") === -1) { // only leaf items files.push({ name, mtime: item.LastModified, size: item.Size }); } }); if (data.IsTruncated) startAfter = items[items.length - 1].Key; else return files; }); }); } rename(oldPath, newPath) { oldPath = this._getKey(oldPath); newPath = this._getKey(newPath); return this.s3.copyObject({ Bucket: this.bucket, Key: newPath, CopySource: this.bucket + "/" + oldPath }).promise().then(() => { return this.s3.deleteObject({ Bucket: this.bucket, Key: oldPath }).promise().then(() => {}); }); } _getKey(path) { path = posix.join(this.basePath, path); return path[0] === "/" ? path.substr(1) : path; } static create(options) { return new StorageS3(options); } _normalizeError(err, path) { if (err.code === "NoSuchKey" || err.code === "NotFound") { err = new Error("Path not found: " + path); err.code = "ENOENT"; err.path = path; } return err; } }
JavaScript
class BaseError extends Error { constructor(args = {}, codeFallback = 'ERROR') { super(args) const [code, originalCode] = wrapCode(args.code, codeFallback) this.isArgsError = true this.code = code this.originalCode = originalCode this.message = args.message ?? (args.code ?? '(No details available)') } }
JavaScript
class InternalError extends BaseError { constructor(args = {}) { super(args, 'INTERNAL_ERROR') this.message = args.message ?? '(No details available)' } }
JavaScript
class ParseError extends BaseError { constructor(args = {}) { super(args, 'PARSE_ERROR') this.argInput = args.argInput ?? {} this.argRef = args.argRef ?? {} this.invalidValues = args.invalidValues ?? [] this.argsMissing = args.argsMissing ?? {} this.activeCmd = args.activeCmd ?? {} } }
JavaScript
class ValidationError extends BaseError { constructor(args = {}) { super(args, 'OPTS_ERROR') const prefix = [args.type ?? '', args.argumentType ? ` type '${args.argumentType}'` : ''].join('') const message = args.message ? args.message : '' this.message = `${prefix ? `${prefix}: ` : ''}${message}${getErrorText(args.errors)}` } }
JavaScript
class Submarine extends ship_1.Ship { /** * [Submarine constructor] * @constructor * @param {Dictionary<string,MatriceCase>} shipPosition [The shipPosition is a Dictionary of all the boxes corresponding to the ship ] * @param {EnumOrientation} shipOrient [The ship orientation horizontal or vertical] */ constructor(shipPosition, shipOrient) { const name = 'Sous-marin'; super(name, enumShip_1.EnumShip.SHIP_SUBMARINE, 3, shipOrient, shipPosition); } }
JavaScript
class InlineResponse2004InstrumentIndustryClassificationRbics { /** * Constructs a new <code>InlineResponse2004InstrumentIndustryClassificationRbics</code>. * Classification based on FactSet Revere Business Industry Classification System (RBICS). * @alias module:model/InlineResponse2004InstrumentIndustryClassificationRbics */ constructor() { InlineResponse2004InstrumentIndustryClassificationRbics.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>InlineResponse2004InstrumentIndustryClassificationRbics</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/InlineResponse2004InstrumentIndustryClassificationRbics} obj Optional instance to populate. * @return {module:model/InlineResponse2004InstrumentIndustryClassificationRbics} The populated <code>InlineResponse2004InstrumentIndustryClassificationRbics</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new InlineResponse2004InstrumentIndustryClassificationRbics(); if (data.hasOwnProperty('level1')) { obj['level1'] = InlineResponse2004InstrumentIndustryClassificationRbicsLevel1.constructFromObject(data['level1']); } if (data.hasOwnProperty('level2')) { obj['level2'] = InlineResponse2004InstrumentIndustryClassificationRbicsLevel2.constructFromObject(data['level2']); } if (data.hasOwnProperty('level3')) { obj['level3'] = InlineResponse2004InstrumentIndustryClassificationRbicsLevel3.constructFromObject(data['level3']); } if (data.hasOwnProperty('level4')) { obj['level4'] = InlineResponse2004InstrumentIndustryClassificationRbicsLevel4.constructFromObject(data['level4']); } if (data.hasOwnProperty('level5')) { obj['level5'] = InlineResponse2004InstrumentIndustryClassificationRbicsLevel5.constructFromObject(data['level5']); } if (data.hasOwnProperty('level6')) { obj['level6'] = InlineResponse2004InstrumentIndustryClassificationRbicsLevel6.constructFromObject(data['level6']); } } return obj; } }
JavaScript
class GalacticAge { constructor(birthdate, sex, smoker) { this.birthdate = birthdate; this.sex = sex; this.smoker = smoker; this.earthAge = 0; this.mercuryAge = 0; this.venusAge = 0; this.marsAge = 0; this.jupiterAge = 0; this.saturnAge = 0; this.lifeExpectancy = 80; } calculateEarthAge(birthdate) { let dateParseMethod = Date.parse(birthdate); let dateNowMethod = Date.now(); let ageInMilliseconds = dateNowMethod - dateParseMethod; let second = 1000; let minute = second * 60; let hour = minute * 60; let day = hour * 24; let year = day * 365; let ageInYears = Math.floor(ageInMilliseconds / year); this.earthAge = ageInYears; return this.earthAge; } calculateYearsLeft() { if (this.sex === "female") { this.lifeExpectancy += 2; } else if (this.sex === "male") { this.lifeExpectancy -= 2; } if (this.smoker === "yes") { this.lifeExpectancy -= 10; } return this.lifeExpectancy; } calculateMercuryAge() { this.mercuryAge = Math.floor(this.earthAge / .24); return this.mercuryAge; } calculateVenusAge() { this.venusAge = Math.floor(this.earthAge / .62); return this.venusAge; } calculateMarsAge() { this.marsAge = Math.floor(this.earthAge / 1.88); return this.marsAge; } calculateJupiterAge() { this.jupiterAge = Math.floor(this.earthAge / 11.86); return this.jupiterAge; } calculateSaturnAge() { this.saturnAge = Math.floor(this.earthAge / 29.5); return this.saturnAge; } calculateEarthYearsLeft() { let earthYearsLeft = this.lifeExpectancy - this.earthAge; if (earthYearsLeft < 0) { earthYearsLeft = `Holy crap you're old! You've outlived your life expectancy by ${Math.abs(this.earthYearsLeft)} years!`; } return earthYearsLeft; } calculateMercuryYearsLeft() { let mercuryYearsLeft = this.lifeExpectancy - this.mercuryAge; if (mercuryYearsLeft < 0) { mercuryYearsLeft = `Holy crap you're old! You've outlived your life expectancy by ${Math.abs(mercuryYearsLeft)} years!`; } return mercuryYearsLeft; } calculateMarsYearsLeft() { let marsYearsLeft = this.lifeExpectancy - this.marsAge; if (marsYearsLeft < 0) { marsYearsLeft = `Holy crap you're old! You've outlived your life expectancy by ${Math.abs(marsYearsLeft)} years!`; } return marsYearsLeft; } calculateVenusYearsLeft() { let venusYearsLeft = this.lifeExpectancy - this.venusAge; if (venusYearsLeft < 0) { venusYearsLeft = `Holy crap you're old! You've outlived your life expectancy by ${Math.abs(venusYearsLeft)} years!`; } return venusYearsLeft; } calculateJupiterYearsLeft() { let jupiterYearsLeft = this.lifeExpectancy - this.jupiterAge; if (jupiterYearsLeft < 0) { jupiterYearsLeft = `Holy crap you're old! You've outlived your life expectancy by ${Math.abs(jupiterYearsLeft)} years!`; } return jupiterYearsLeft; } calculateSaturnYearsLeft() { let saturnYearsLeft = this.lifeExpectancy - this.saturnAge; if (saturnYearsLeft < 0) { saturnYearsLeft = `Holy crap you're old! You've outlived your life expectancy by ${Math.abs(saturnYearsLeft)} years!`; } return saturnYearsLeft; } }
JavaScript
class Sysdashboard { /** * Constructor */ constructor() { } }
JavaScript
class Octet { /** * Constructor for creating an instance of an Octet. * * The constructor parameter given could either be a string or number. * * If a string, it is the string representation of the numeric value of the octet * If a number, it is the numeric representation of the value of the octet * * @param {string | number} givenValue value of the octet to be created. */ constructor(givenValue) { let octetValue; if (typeof givenValue === 'string') { octetValue = parseInt(givenValue); } else { octetValue = givenValue; } let [isValid, message] = Validator_1.Validator.isValidIPv4Octet(BigInt(octetValue)); if (!isValid) { throw Error(message.filter(msg => { return msg !== ''; }).toString()); } this.value = octetValue; } /** * Convenience method for creating an Octet out of a string value representing the value of the octet * * @param {string} rawValue the octet value in string * @returns {Octet} the Octet instance */ static fromString(rawValue) { return new Octet(rawValue); } ; /** * Convenience method for creating an Octet out of a numeric value representing the value of the octet * * @param {number} rawValue the octet value in number * @returns {Octet} the Octet instance */ static fromNumber(rawValue) { return new Octet(rawValue); } ; /** * Method to get the numeric value of the octet * * @returns {number} the numeric value of the octet */ getValue() { return this.value; } /** * Returns a decimal representation of the value of the octet in string * * @returns {string} a decimal representation of the value of the octet in string */ toString() { return this.value.toString(10); } }
JavaScript
class Control extends React.Component { constructor(props) { super(props); var self = this; this.callbacks = { onChange: this.change.bind(self), onBlur: this.blur.bind(self) } this.state = {validationState: ''}; } _defaultValue(fromProps) { var fromModel = this.props.model.get(this.props.name); fromProps = fromProps || this.props.defaultValue; var modelIsNotSet; if (!fromModel) modelIsNotSet = true; if (typeof fromModel === 'object') if (Object.keys(fromModel).length === 0) modelIsNotSet = true; if (modelIsNotSet) return fromProps; return fromModel; } _defaultProps(o) { //@todo needs love https://www.youtube.com/watch?v=NEUX-HYRtUA var self = this; var props = {}; var o = o || {}; if (self.props.attrs) for (var key in self.props.attrs) if (self.props.attrs.hasOwnProperty(key)) props[key] = self.props.attrs[key]; //copy in unknown props for (var key in self.props) if (self.props.hasOwnProperty(key)) props[key] = self.props[key]; var firstMerge = { name: self.props.name, className: 'form-control', model: self.props.model, options: self.props.options, defaultValue: self._defaultValue(), onChange: self.change.bind(self), onBlur: self.blur.bind(self) }; for (var key in firstMerge) if (firstMerge.hasOwnProperty(key)) { props[key] = firstMerge[key]; } for (var key in o) { if (o.hasOwnProperty(key)) props[key] = o[key]; } return props; } shouldComponentUpdate(nextProps, nextState) { return (this.props.defaultValue !== nextProps.defaultValue); } componentDidMount() { this.props.model.set(this.props.name, this._defaultValue(), this); } change(e) { this.props.model.set(this.props.name, e.target.value, this, e.target); } blur(e) { this.props.model.validate(this.props.name, e.target.value, this, e.target); } renderComponent() { return (<b>Not implemented</b>); } render() { return this.renderComponent(); } }
JavaScript
class Modal extends Component { /** * @function shouldComponentUpdate * @param {*} nextProps * @param {*} nextState * * Check whether next props is same to current sate, if not then render, * othervise return false to stop render for better performence. */ shouldComponentUpdate(nextProps, nextState) { return nextProps.show !== this.props.show || nextProps.children !== this.props.children; } componentDidUpdate() { // console.log('[Modal] didUpdate') } render() { return ( <Aux> <Backdrop show={this.props.show} clicked={this.props.modalColsed} /> <div className={classes.Modal} style={{ transform: this.props.show ? 'translateY(0)' : 'translateY(-100vh)', opacity: this.props.show ? '1' : '0', }}> {this.props.children} </div> </Aux> ); } }
JavaScript
class StackedConnections { constructor(data, width=configurationDimension.width, height=configurationDimension.height, includeValueInLabel=true, paddingStackCell=configurationLayout.paddingStackCell, paddingStackText=configurationLayout.paddingStackText) { // update self this.artboard = null; this.barWidth = null; this.connectionGroup = null; this.container = null; this.dataSource = data; this.height = height; this.includeValueInLabel = includeValueInLabel; this.name = configuration.name; this.paddingStackCell = paddingStackCell; this.paddingStackText = paddingStackText; this.stackGroup = null; this.stackLabelGroup = null; this.width = width; // using font size as the base unit of measure make responsiveness easier to manage across devices this.artboardUnit = typeof window === "undefined" ? 16 : parseFloat(getComputedStyle(document.body).fontSize); // update self this.paddingAnnotations = this.artboardUnit * 2; } /** * Condition data for visualization requirements. * @returns A xx. */ get data() { let result = null; // verify valid source provided if (this.dataSource && Object.keys(this.dataSource).length == 2) { result = []; // loop through series' for (const s of this.dataSource.stacks) { // get key of series which correlates to its label let key = Object.keys(s)[0]; let stacked = this.generateStackLayout(s[key]); // format into consistent stack/connection object result.push({ connections: stacked ? this.dataSource.connections.filter(d => (stacked.series.map(x => x.key)).includes(d.source)) : null, key: key, scale: stacked ? stacked.scale : null, series: stacked ? stacked.series : [], totalValues: stacked ? stacked.totalValues : 0 }) } } return result; } /** * Construct horizonal scale. * @returns A d3 scale function. */ get horizontalScale() { return scaleBand() .domain(this.stacks ? this.stacks.map(d => d.key) : []) .rangeRound([0, this.width]) .paddingInner(0.94); } /** * Calculate the character width based of typographic em value. * @param {string} word - word to calculate * @param {float} unit - smallest atmoic unit of measure (should normally be the fontsize) * @returns A float representing the length of a given word based on provided unit and typographic rules of em sizing. */ characterWidth(word, unit) { let em = 0.6; let small = 0.25; let mid = 0.45; let reference = { a: em, b: mid, c: mid, d: em, e: mid, f: small, g: em, h: mid, i: small, j: mid, k: mid, l: small, m: em, n: 0.5, o: em, p: mid, q: mid, r: small, s: em, t: small, u: mid, v: mid, w: mid, x: mid, y: small, z: mid, A: em, B: em, C: em, D: em, E: em, F: em, G: em, H: em, I: small, J: mid, K: em, L: em, M: em, N: em, O: em, P: mid, Q: mid, R: mid, S: mid, T: em, U: mid, V: em, W: em, X: em, Y: em, Z: em }; let result = 0; // loop through characters for (const c of word) { // calculate percent difference from em unit let difference = reference[c]; // if it is null assume 1 em for punctuation etc. if (difference) { result += difference * unit; } else { result += em * unit; } } return result; } /** * Position and minimally style annotations in SVG dom element. * @param {node} domNode - d3.js SVG selection */ configureAnnotations(domNode) { domNode .attr("x", (d,i) => i == this.stacks.length - 1 ? this.width : this.horizontalScale(d.key)) .attr("y", this.paddingAnnotations / 2) .attr("text-anchor", (d,i) => i == this.stacks.length - 1 ? "end" : "start") .text(d => d.key); } /** * Configure data series. * @param {} */ configureData() { // get value for max keys in any stack let maxKeyCount = max(this.dataSource.stacks.map(d => Object.keys(d[Object.keys(d)[0]]).length)); // try to use the provided padding but // if requested would set a negative scale // use the largest possible padding given remaining space let paddingIsValid = this.paddingStackCell * (maxKeyCount - 1) < this.height; // padding is too big as requested if (!paddingIsValid) { // set new padding with available space this.paddingStackCell = (this.height / maxKeyCount) * 0.2; } // process data this.stacks = this.data; this.barWidth = this.horizontalScale.bandwidth(); this.connectionPaths = this.generateConnectionPaths(this.stacks); } /** * Generate SVG text elements in the HTML DOM. * @param {node} domNode - HTML node * @returns A d3.js selection. */ generateAnnotations(domNode) { return domNode .selectAll(".lgv-annotation") .data(this.stacks ? this.stacks : []) .join( enter => enter.append("text"), update => update, exit => exit.remove() ) .attr("class", "lgv-annotation"); } /** * Generate SVG artboard in the HTML DOM. * @param {selection} domNode - d3 selection * @returns A d3.js selection. */ generateArtboard(domNode) { return domNode .selectAll("svg") .data([{height: this.height, width: this.width}]) .join( enter => enter.append("svg"), update => update, exit => exit.remove() ) .attr("viewBox", d => `0 0 ${d.width} ${d.height}`) .attr("class", this.name); } /** * Construct bar shapes in HTML DOM. * @param {node} domNode - HTML node * @returns A d3.js selection. */ generateBars(domNode) { domNode.each((category, i, nodes) => { // render stack values select(nodes[i]) .selectAll(".lgv-bar") .data(category.series) .join( enter => enter.append("rect"), update => update, exit => exit.remove() ) .attr("data-key", d => d.key) .attr("class", "lgv-bar") .attr("x", this.horizontalScale(category.key)) .attr("y", (d,i) => category.scale(d[0][0]) + (this.paddingStackCell * i)) .attr("height", d => category.scale(d[0][1]) - category.scale(d[0][0])) .attr("width", this.barWidth) .on("mouseover", (e,d) => { // update class select(e.target).attr("class", "lgv-bar active"); // send event to parent this.artboard.dispatch("barmouseover", { bubbles: true, detail: { label: d.key, stack: category.key, paths: this.connectionPaths.filter(x => x.includes(d.key)), xy: [e.clientX + (this.artboardUnit / 2), e.clientY + (this.artboardUnit / 2)] } }); }) .on("mouseout", (e,d) => { // update class select(e.target).attr("class", "lgv-bar"); // send event to parent this.artboard.dispatch("barmouseout", { bubbles: true }); }); }); } /** * Construct connection group in HTML DOM. * @param {node} domNode - HTML node * @returns A d3.js selection. */ generateConnectionGroups(domNode) { return domNode .selectAll(".lgv-connections") .data(this.stacks ? this.stacks.slice(0, this.stacks.length - 1) : []) .join( enter => enter.append("g"), update => update, exit => exit.remove() ) .attr("class", "lgv-connections") } /** * Construct hierachial paths noting connections between stacks visually left to right. * @param {array} stacks - generated data array from get data() * @returns An array of strings where each is a period delimited representation of the connection path between stack from visual left-to-right. */ generateConnectionPaths(stacks) { let result = []; // loop through stacks stacks.forEach(d => { // loop through connections d.connections.forEach(dt => { // check for prefix already captured let segmentsWithSource = result.filter(d => d.split(".")[d.split(".").length - 1] === dt.source); let hasPrefix = segmentsWithSource.length > 0; // if prefixes are found if (hasPrefix) { // loop through matches segmentsWithSource.forEach(s => { // add to list result.push(`${s}.${dt.target}`); }); } else { // add to list result.push(`${dt.source}.${dt.target}`); } }); }); // one more loop to remove paths that were needed only to append to // but now are out-of-date since later children complete the path let prunedResult = []; result.forEach(d => { result.forEach(dt => { if (dt.includes(d) && dt.length > d.length) { prunedResult.push(dt); } }); }); return prunedResult; } /** * Generate SVG connection paths in the HTML DOM. * @param {node} domNode - HTML node * @returns A d3.js selection. */ generateConnections(domNode) { domNode .each((connection, i, nodes) => { let sourceStack = connection; let targetStack = this.stacks[i+1]; let tracked = 0; // render connection values select(nodes[i]) //.selectAll(`.${this.stacks[i].key}-to-${this.stacks[i+1].key}`) .selectAll(".lgv-connection") .data(this.stacks[i].connections) .join( enter => enter.append("path"), update => update, exit => exit.remove() ) .attr("class", "lgv-connection") .attr("data-path", d => [...new Set(this.connectionPaths.filter(x => x.includes(d.source) && x.includes(d.target)))]) .attr("data-source", d => d.source) .attr("data-target", d => d.target) .attr("d", d => { let sourceStackLayout = sourceStack.series.filter(x => x.key === d.source)[0]; let sourceStackItem = sourceStackLayout[0]; let targetStackLayout = targetStack.series.filter(x => x.key === d.target)[0]; let targetStackItem = targetStackLayout[0]; let sourceX = this.horizontalScale(sourceStack.key) + this.barWidth; let sourceY0 = sourceStack.scale(sourceStackItem[0]) + (this.paddingStackCell * sourceStackLayout.index); let sourceY1 = sourceStack.scale(sourceStackItem[1]) + (this.paddingStackCell * sourceStackLayout.index); let targetX = this.horizontalScale(targetStack.key); let targetY0 = targetStack.scale(targetStackItem[0]) + (this.paddingStackCell * targetStackLayout.index); let targetY1 = targetStack.scale(targetStackItem[1]) + (this.paddingStackCell * targetStackLayout.index); // define connection path let p = path(); // source top/left point of entire path shape p.moveTo(sourceX, sourceY0); // source top/left point cuved with 2 anchor points to top/right point of entire path shape p.bezierCurveTo( sourceX + (this.horizontalScale.step() / 2), sourceY0, targetX - (this.horizontalScale.step() / 2), targetY0, targetX, targetY0 ); // target straight line down the height of the stack item to bottom right point of entire path p.lineTo(targetX, targetY1); // target bottom/right point curved with 2 anchor points to bottom/left point of entire path shape p.bezierCurveTo( targetX - (this.horizontalScale.step() / 2), targetY0, sourceX + (this.horizontalScale.step() / 2), sourceY1, sourceX, sourceY1 ); // source bottom/left point straight up the height of the stack item to top/left point of entire path p.closePath(); return p; }); }); } /** * Generate SVG text labels in the HTML DOM. * @param {node} domNode - HTML node * @returns A d3.js selection. */ generateStackLabels(domNode) { domNode .each((d, i, nodes) => { // label container select(domNode.nodes()[i]) .selectAll(".lgv-label") .data(d.series) .join( enter => enter.append("g"), update => update, exit => exit.remove() ) .attr("class", "lgv-label") .attr("data-key", x => x.key) .attr("transform", (x,j) => { let tx = i == nodes.length - 1 ? this.horizontalScale(d.key) - this.paddingStackText - (this.characterWidth(x.key, this.artboardUnit)) : this.horizontalScale(d.key) + this.barWidth + this.paddingStackText; let ty = d.scale(x[0][0]) + (this.paddingStackCell * j) + (d.scale(x[0].data[x.key]) / 2) - (this.artboardUnit /2); return `translate(${tx},${ty})`; }) .each((x, j, nodes2) => { let g = select(nodes2[j]); // add background for when underlying layer makes text illegible g.selectAll("rect") .data(d => [d]) .join( enter => enter.append("rect"), update => update, exit => exit.remove() ) .attr("x", 0) .attr("y", 0) .attr("width", this.characterWidth(x.key, this.artboardUnit)) .attr("height", this.artboardUnit * 1.4); // add text g.selectAll("text") .data(d => [d]) .join( enter => enter.append("text"), update => update, exit => exit.remove() ) .attr("x", this.artboardUnit * 0.2) .attr("y", this.artboardUnit) .each((z, l, nodes3) => { select(nodes3[l]) .selectAll("tspan") .data(this.includeValueInLabel ? [z.key, `${((z[0].data[z.key]/d.totalValues) * 100).toFixed(2)}%`] : [z.key]) .join( enter => enter.append("tspan"), update => update, exit => exit.remove() ) .attr("dx", (a, m) => m == 0 ? "" : `${m * 0.35}em`) .text(z => z); }); }); }); } /** * Construct label groups for eac stack in HTML DOM. * @param {node} domNode - HTML node * @returns A d3.js selection. */ generateStackLabelGroups(domNode) { return domNode .selectAll(".lgv-labels") .data(this.stacks ? this.stacks : []) .join( enter => enter.append("g"), update => update, exit => exit.remove() ) .attr("class", "lgv-labels"); //.attr("class", d => `lgv-${d.key}-labels`); } /** * Construct stack group in HTML DOM. * @param {node} domNode - HTML node * @returns A d3.js selection. */ generateStackGroups(domNode) { return domNode .selectAll(".lgv-stack") .data(this.stacks ? this.stacks : []) .join( enter => enter.append("g"), update => update, exit => exit.remove() ) .attr("class", "lgv-stack"); //.attr("class", d => `lgv-stack-${d.key}`); } /** * Construct stack layout. * @param {object} data - series data to be stacked * @returns An object with key/value maps for series, scale, total values. */ generateStackLayout(data) { let result = null; // check for valid input if (data && Object.keys(data).length > 0) { // sort keys by decreasing value order then alpha let keysSorted = Object.keys(data) .map(d => ({ key: d, value: data[d] })) .sort((a,b) => b.value - a.value || a.key.localeCompare(b.key)) .map(d => d.key); // generate stack layout let stackLayout = stack() .keys(keysSorted); // generate series of 1 const series = stackLayout([data]); // calculate total value let dataValues = sum(Object.keys(data).map(d => data[d])); // determine how much padding is between stack value blocks let paddingValues = this.paddingStackCell * keysSorted.length; // y scale let yScale = scaleLinear() .domain([0, dataValues]) .range([0, (this.height - paddingValues - this.paddingAnnotations)]); result = { series: series, scale: yScale, totalValues: dataValues } } return result } /** * Generate visualization. */ generateVisualization() { // calculate series this.configureData(); // generate svg artboard this.artboard = this.generateArtboard(this.container); // chart content group const artwork = this.artboard .selectAll(".artwork") .data(d => [d]) .join( enter => enter.append("g"), update => update, exit => exit.remove() ) .attr("class", "artwork") .attr("transform", d => `translate(0,${this.paddingAnnotations})`); // generate chart annotations const annotations = this.generateAnnotations(this.artboard); this.configureAnnotations(annotations); // generate group for each connection set this.connectionGroup = this.generateConnectionGroups(artwork); // generate connections this.generateConnections(this.connectionGroup); // generate group for each stack this.stackGroup = this.generateStackGroups(artwork); // generate stack bars this.generateBars(this.stackGroup); // generate group for each stack text this.stackLabelGroup = this.generateStackLabelGroups(artwork); // generate labels this.generateStackLabels(this.stackLabelGroup); } /** * Render visualization. * @param {node} domNode - HTML node */ render(domNode) { // update self this.container = select(domNode); // generate visualization this.generateVisualization(); } /** * Update visualization. * @param {object} data - key/values where each key is a series label and corresponding value is an array of values * @param {integer} height - height of artboard * @param {integer} width - width of artboard */ update(data, width, height) { // update self this.dataSource = data; this.height = height; this.width = width; // generate visualization this.generateVisualization(); } }
JavaScript
class State { constructor(pos, depth, root) { this.pos = pos this.depth = depth this.root = root } }
JavaScript
class searchResult { constructor(value, move) { this.value = value this.move = move } }
JavaScript
class SynthesisTargetEmbed extends BaseEmbed { /** * @param {Genesis} bot - An instance of Genesis * @param {Array.<SynthesisTarget>} synthTargets - The synthesis targets to send info on * @param {string} query - The user's query */ constructor(bot, synthTargets, query) { super(); this.thumbnail = { url: scannerThumb, }; if (synthTargets.length === 1) { this.title = synthTargets[0].name; this.fields = synthTargets[0].locations.map(loc => ({ name: `${loc.mission}, ${loc.planet}`, value: `Faction: ${loc.faction}, Level: ${loc.level}, Spawn: ${loc.spawn_rate}`, inline: false, })); } else { this.title = `Multiple targets matching "${query}"`; this.fields = [{ name: '\u200B', value: synthTargets.map(t => t.name).join('\n') }]; this.footer.text = 'Search through the results using the arrows below.'; } } }
JavaScript
class App extends Component { constructor(props) { super(props); /** * The state are the variables used by the class. * corruptFile - Tells if the file loaded by the user had a wrong format. * loading - If true, means that the graphs are rendering and the user have to wait while it finishes. * exampleProteinsFile - Where the example protein file will be stored. * exampleGenesFile - Where the example gene file will be stored. * exampleCoronaFile - Where the example corona file will be stored. * isProtein - If the selected file is a protein alignment. * answer - Where the raw sequences wil be stored after splitting them by name. * dataFirstGraph - Data used by the first graph. * dataThirdGraph - Data used by the third and fourth graph. * namesGenes - Where the names of the sequences will be stored. * dataSecondGraph - Data used by the second graph. * valueFirstFilter - From what position sequences will be graphed. * valueSecondFilter - Until what position sequences will be graphed. * selectedBoxes - What sequences will be graphed. * information0 - Informative message of what the fiters do. * initialEntropy - The first position seen in the entropy chart. * finalEntropy - The final position seen in the entropy chart. * entropySelection - What type of selection is chosen in the entropy chart. * bigFile - A variable showing if the selected file is large. */ this.state = { initialEntropy: 0, finalEntropy: 0, entropySelection: "partial", bigFile: false, corruptFile: false, loading: false, exampleCoronaFile: [], exampleProteinsFile: [], exampleGenesFile: [], isProtein: false, answer: [], dataFirstGraph: [], dataThirdGraph: [], namesGenes: [], dataSecondGraph: [], valueFirstFilter: 0, valueSecondFilter: 0, selectedBoxes: [], information0: "The filters changes what sequences the graphs will use." }; //The binding of "this" to all methods used by the class. this.selections = this.selections.bind(this); this.filterAppJS = this.filterAppJS.bind(this); this.checkboxes = this.checkboxes.bind(this); this.filter = this.filter.bind(this); this.selectAll = this.selectAll.bind(this); this.deselectAll = this.deselectAll.bind(this); this.initialButtons = this.initialButtons.bind(this); this.shannon = this.shannon.bind(this); this.objectSecondGraph = this.objectSecondGraph.bind(this); this.objectSecondGraphProteins = this.objectSecondGraphProteins.bind(this); this.firstGraphFullPartial = this.firstGraphFullPartial.bind(this); this.handleFile = this.handleFile.bind(this); this.alertLength = this.alertLength.bind(this); this.rightChange = this.rightChange.bind(this); this.leftChange = this.leftChange.bind(this); //The reference to the gene translation table. this.tableref = React.createRef(); this.selectref = React.createRef(); this.optionref = React.createRef(); } /** * Function which calculates the shannon entropy. * @param array Array of the values of all sequences at a certain position. * @returns Integer repretenting the shannon entropy at a centain position. */ shannon = (array) => { if (array.length === 0) return 0; let modeMap = {}; let el; for (let i = 0; i < array.length; i++) { el = array[i]; if (modeMap[el] == null) { modeMap[el] = 1; } else { modeMap[el]++; } } let result = 0; let ArraySize = array.length; Object.keys(modeMap).forEach(element => { result += -1 * (modeMap[element] / ArraySize) * (Math.log2(modeMap[element] / ArraySize)) }); return result; } /** * Function which calculates the percentage of each value at a certain position for gene alignments. * @param array Array of the values of all sequences at a certain position. * @param position The position which percentages are being calculated. * @returns An instance of the class myObjectSecondGraphGenes which have the percentages per letter. */ objectSecondGraph = (array, position) => { if (array.length === 0) return new myObjectSecondGraphGenes(position, 0, 0, 0, 0, 0); let modeMap = {}; let el; for (let i = 0; i < array.length; i++) { el = array[i]; if (modeMap[el] == null) { modeMap[el] = 1; } else { modeMap[el]++; } } let arraySize = array.length; let numberA = modeMap["A"] ? modeMap["A"] / arraySize : 0; let numberC = modeMap["C"] ? modeMap["C"] / arraySize : 0; let numberG = modeMap["G"] ? modeMap["G"] / arraySize : 0; let numberT = modeMap["T"] ? modeMap["T"] / arraySize : 0; let numberDash = modeMap["-"] ? modeMap["-"] / arraySize : 0; let answer = new myObjectSecondGraphGenes(position, numberA, numberC, numberG, numberT, numberDash); return answer; } /** * Function called after the render function when the component is first build. * It saves the values of the example files in the class variables. */ componentDidMount() { let example1; let example2; let example3; d3.text(exampleProteins).then(data => { example1 = new File([data], "proteinfasta.txt", { type: "text/plain", }); d3.text(exampleGenes).then(data => { example2 = new File([data], "genefasta.txt", { type: "text/plain", }); d3.text(exampleCorona).then(data => { example3 = new File([data], "coronafasta.txt", { type: "text/plain", }); this.setState({ exampleProteinsFile: example1, exampleGenesFile: example2, exampleCoronaFile: example3 }) }) }) }) } /** * Function which calculates the percentage of each value at a certain position for protein alignments. * @param array Array of the values of all sequences at a certain position. * @param position The position which percentages are being calculated. * @returns An instance of the class myObjectSecondGraphProteins which have the percentages per letter. */ objectSecondGraphProteins = (array, position) => { if (array.length === 0) return new myObjectSecondGraphProteins(position, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); let modeMap = {}; let el; for (let i = 0; i < array.length; i++) { el = array[i]; if (modeMap[el] == null) { modeMap[el] = 1; } else { modeMap[el]++; } } let arraySize = array.length; let numberA = modeMap["A"] ? modeMap["A"] / arraySize : 0; let numberC = modeMap["C"] ? modeMap["C"] / arraySize : 0; let numberG = modeMap["G"] ? modeMap["G"] / arraySize : 0; let numberT = modeMap["T"] ? modeMap["T"] / arraySize : 0; let numberR = modeMap["R"] ? modeMap["R"] / arraySize : 0; let numberN = modeMap["N"] ? modeMap["N"] / arraySize : 0; let numberD = modeMap["D"] ? modeMap["D"] / arraySize : 0; let numberB = modeMap["B"] ? modeMap["B"] / arraySize : 0; let numberE = modeMap["E"] ? modeMap["E"] / arraySize : 0; let numberQ = modeMap["Q"] ? modeMap["Q"] / arraySize : 0; let numberZ = modeMap["Z"] ? modeMap["Z"] / arraySize : 0; let numberH = modeMap["H"] ? modeMap["H"] / arraySize : 0; let numberI = modeMap["I"] ? modeMap["I"] / arraySize : 0; let numberL = modeMap["L"] ? modeMap["L"] / arraySize : 0; let numberK = modeMap["K"] ? modeMap["K"] / arraySize : 0; let numberM = modeMap["M"] ? modeMap["M"] / arraySize : 0; let numberF = modeMap["F"] ? modeMap["F"] / arraySize : 0; let numberP = modeMap["P"] ? modeMap["P"] / arraySize : 0; let numberS = modeMap["S"] ? modeMap["S"] / arraySize : 0; let numberW = modeMap["W"] ? modeMap["W"] / arraySize : 0; let numberY = modeMap["Y"] ? modeMap["Y"] / arraySize : 0; let numberV = modeMap["V"] ? modeMap["V"] / arraySize : 0; let numberDash = modeMap["-"] ? modeMap["-"] / arraySize : 0; let answer = new myObjectSecondGraphProteins(position, numberA, numberC, numberG, numberT, numberR, numberN, numberD, numberB, numberE, numberQ, numberZ, numberH, numberI, numberL, numberK, numberM, numberF, numberP, numberS, numberW, numberY, numberV, numberDash); return answer; } /** * Function which calculates all the class variables with the selected file. * @param e File chosen. */ handleFile(e) { //Set the variable loading from the start, so the user knows when the file is being processed this.setState({ loading: true }) //Check of what file was chosen or if it was one of the examples. var file; if (e === "proteinExample") { file = this.state.exampleProteinsFile; } else if (e === "geneExample") { file = this.state.exampleGenesFile; } else if (e === "coronaExample") { file = this.state.exampleCoronaFile; } else { file = e; } let reader = new FileReader(); reader.onload = function () { const data = reader.result; let resultFirstGraph = []; let resultThirdGraph = []; let resultSecondGraph = []; const initialArrays = data.split(">"); let answer = []; let names = []; let myString; let isProtein = false; //Read the file and split it by names. Save the result in the answer variable without the names of the sequences. for (let index = 0; index < initialArrays.length; index++) { if (index === 0) { continue; } myString = initialArrays[index]; names.push(myString.substring(0, myString.indexOf('\n'))) myString = myString.substring(myString.indexOf('\n') + 1); answer.push(myString); } //If the split can not be done, change the corrupFile class variable to true. if (answer.length === 0) { this.setState({ corruptFile: true }) return; } //If the size of the Strings are of different size, change the corrupFile class variable to true. let addition = 0; answer.map(x => addition += x.length); if (addition !== (answer[0].length * answer.length) - 2) { this.setState({ corruptFile: true }) return; } //Check is the loaded file is a gene or protein alignment. const lettersOnlyProteins = ["R", "N", "D", "B", "E", "Q", "Z", "H", "I", "L", "K", "M", "F", "P", "S", "W", "Y", "V"]; if (lettersOnlyProteins.some(el => answer[0].includes(el))) { isProtein = true; } //Calculation of how long is the sequences, so the bigFile variable changes. let array1 = answer[answer.length - 1].split("A").length - 1; //3; let array2 = answer[answer.length - 1].split("T").length - 1; //3; let array3 = answer[answer.length - 1].split("C").length - 1; //3; let array4 = answer[answer.length - 1].split("G").length - 1; //3; let array5 = answer[answer.length - 1].split("-").length - 1; //3; let totalFullSize = array1 + array2 + array3 + array4 + array5; let bigFile = false; if (totalFullSize > 1000) { bigFile = true; } let posAverage = 0; let valAverage = 0; let fixJump = 0; let components; //Generate the data that the first graph will be using. //It uses the shannon function to generate the necessary data. for (let index = 0; index < answer[answer.length - 1].length; index++) { components = []; for (let innerIndex = 0; innerIndex < answer.length; innerIndex++) { components.push(answer[innerIndex].charAt(index)); } if (!isProtein) { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G")) { fixJump++; continue; } } else { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G" && v !== "R" && v !== "N" && v !== "D" && v !== "B" && v !== "E" && v !== "Q" && v !== "Z" && v !== "H" && v !== "I" && v !== "L" && v !== "K" && v !== "M" && v !== "F" && v !== "P" && v !== "S" && v !== "W" && v !== "Y" && v !== "V")) { fixJump++; continue; } } valAverage += this.shannon(components); if (posAverage >= 5 || index == 0 || index + 1 == answer[answer.length - 1].length) { let objectTemp = new myObject(index - fixJump + 1, valAverage / (posAverage + 1)); resultFirstGraph.push(objectTemp); valAverage = 0; posAverage = 0; } else { posAverage++; } } //Generate the data that the third and fourth graph will be using. fixJump = 0; components = []; for (let index = 0; index < answer[answer.length - 1].length; index++) { components = []; for (let innerIndex = 0; innerIndex < answer.length; innerIndex++) { components.push(answer[innerIndex].charAt(index)); } if (!isProtein) { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G")) { fixJump++; continue; } } else { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G" && v !== "R" && v !== "N" && v !== "D" && v !== "B" && v !== "E" && v !== "Q" && v !== "Z" && v !== "H" && v !== "I" && v !== "L" && v !== "K" && v !== "M" && v !== "F" && v !== "P" && v !== "S" && v !== "W" && v !== "Y" && v !== "V")) { fixJump++; continue; } } let objectTemp = "{\"position\":" + (index + 1 - fixJump) + ""; for (let pos = 0; pos < components.length; pos++) { objectTemp += ",\"" + names[pos] + "\":\"" + answer[pos][index] + "\""; } objectTemp += "}"; objectTemp = objectTemp.replace(/[\r\n]+/gm, ""); let res = JSON.parse(objectTemp) resultThirdGraph.push(res); } //Generate the data that the second graph will be using. let objectPosition = null; fixJump = 0; components = []; for (let index = 0; index < answer[answer.length - 1].length; index++) { components = [] for (let innerIndex = 0; innerIndex < answer.length; innerIndex++) { components.push(answer[innerIndex].charAt(index)); } if (!isProtein) { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G")) { fixJump++; continue; } objectPosition = this.objectSecondGraph(components, (index + 1 - fixJump)); resultSecondGraph.push(objectPosition); } else { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G" && v !== "R" && v !== "N" && v !== "D" && v !== "B" && v !== "E" && v !== "Q" && v !== "Z" && v !== "H" && v !== "I" && v !== "L" && v !== "K" && v !== "M" && v !== "F" && v !== "P" && v !== "S" && v !== "W" && v !== "Y" && v !== "V")) { fixJump++; continue; } objectPosition = this.objectSecondGraphProteins(components, (index + 1 - fixJump)); resultSecondGraph.push(objectPosition); } } //Generate the data that the fifth graph will be using. let resultFifthGraph = []; let keys = ["percentagea", "percentagec", "percentageg", "percentaget"]; let biggestName; let biggestValue; resultSecondGraph.map(function (item, i) { biggestName = null; biggestValue = 0; keys.forEach(element => { if (item[element] > biggestValue) { biggestName = element; biggestValue = item[element]; } }); resultFifthGraph.push(new myObjectFifthGraph(i + 1, biggestName)) }) //Set the data to the class variables. if (!bigFile) { this.setState({ dataFirstGraph: resultFirstGraph, dataThirdGraph: resultThirdGraph, dataSecondGraph: resultSecondGraph, dataFifthGraph: resultFifthGraph, valueFirstFilter: 1, initialEntropy: 1, valueSecondFilter: resultThirdGraph.length, finalEntropy: resultThirdGraph.length, selectedBoxes: names, bigFile: bigFile, namesGenes: names, answer: answer, isProtein: isProtein, loading: false }) } else { this.setState({ dataFirstGraph: resultFirstGraph, dataThirdGraph: resultThirdGraph, dataSecondGraph: resultSecondGraph, dataFifthGraph: resultFifthGraph, valueFirstFilter: 1, initialEntropy: 1, valueSecondFilter: 1000, finalEntropy: 1000, selectedBoxes: names, bigFile: bigFile, namesGenes: names, answer: answer, isProtein: isProtein, loading: false }) } //Change the size of the fourth table if it's too big thanks to the amount of sequences being processed. if (this.tableref.current.offsetHeight > 300) { d3.selectAll(".table-check") .style("height", "300px") .style("overflow", "auto"); } else { d3.selectAll(".table-check") .style("height", null) .style("overflow", "auto"); } }.bind(this); reader.readAsText(file); } /** * Set the start and end position filtered to change all the graphs and tables data. * @param event Is the value chosen by the user. */ filterAppJS(event) { const firstValue = parseInt(event.target.value.split(" - ")[0]); const secondValue = parseInt(event.target.value.split(" - ")[1]); if(firstValue === this.state.valueFirstFilter && secondValue === this.state.valueSecondFilter) return; this.optionref.current.text = ""; if (this.state.entropySelection === "partial") { this.setState({ valueSecondFilter: secondValue, valueFirstFilter: firstValue, initialEntropy: firstValue, finalEntropy: secondValue }); } else { this.setState({ valueSecondFilter: secondValue, valueFirstFilter: firstValue }); } } /** * This function return the arrays to be used by the translation table. */ selections() { const totalSize = this.state.dataThirdGraph.length; const remainingNumbers = totalSize % 1000; let arrayMapping = [] if (totalSize < 1000) { arrayMapping.push(1 + " - " + totalSize); } else { for (let index = 0; index < totalSize - remainingNumbers; index += 1000) { arrayMapping.push((index + 1) + " - " + (index + 1000)); } if ((totalSize - remainingNumbers) != 0) { arrayMapping.push((totalSize - remainingNumbers + 1) + " - " + totalSize); } } return ( arrayMapping.map(function (item, i) { return <option value={item} key={i}>{item}</option> })) } rightChange(leftValue, rightValue) { let cambio; const tamanoMax = this.state.dataThirdGraph.length; if (rightValue + 500 >= tamanoMax + 1) { cambio = tamanoMax - rightValue; } else { cambio = 500; } const bigFile = this.state.bigFile; const entropySelection = this.state.entropySelection; this.selectref.current.selectedIndex = this.selectref.current.length-1; this.optionref.current.text = "" + (leftValue + 500) + " - " + (rightValue + cambio); if (entropySelection === "full" && bigFile) { this.setState({ valueFirstFilter: leftValue + 500, valueSecondFilter: rightValue + cambio }); } else if (bigFile) { this.setState({ initialEntropy: leftValue + 500, finalEntropy: rightValue + cambio, valueFirstFilter: leftValue + 500, valueSecondFilter: rightValue + cambio }); } } leftChange(leftValue, rightValue) { let cambio; const tamanoMax = this.state.dataThirdGraph.length; if (tamanoMax === (rightValue)) { if (leftValue + 500 >= tamanoMax) { cambio = 0; } else { cambio = - rightValue + leftValue + 499; } } else { cambio = - 500; } const bigFile = this.state.bigFile; const entropySelection = this.state.entropySelection; this.selectref.current.selectedIndex = this.selectref.current.length-1; this.optionref.current.text = "" + (leftValue - 500) + " - " + (rightValue + cambio); if (entropySelection === "full" && bigFile) { this.setState({ valueFirstFilter: leftValue - 500, valueSecondFilter: rightValue + cambio }); } else if (bigFile) { this.setState({ initialEntropy: leftValue - 500, finalEntropy: rightValue + cambio, valueFirstFilter: leftValue - 500, valueSecondFilter: rightValue + cambio }); } } /** * This function creates the checkboxes using the sequence names. */ checkboxes() { const names = this.state.namesGenes; return ( names.map(function (item, i) { return (<div className="form-check spaceCheckbox" key={i}> <input className="form-check-input" type="checkbox" id={i} value={item} defaultChecked /> <label className="form-check-label" htmlFor={i}>{item}</label> </div>) })) } /** * This function updates the values in the class variables when the user filters the names of the sequences he wants to see. */ filter() { let namesArray = []; const isProtein = this.state.isProtein; let boxes = d3.selectAll(".form-check-input").nodes() boxes.map(function (item, i) { if (item.checked === true) { namesArray.push(item.value); } }) let objectTemp = null; let posAverage = 0; let resultFirstGraph = []; let valAverage = 0; let fixJump = 0; const answer = this.state.answer; const namesGenes = this.state.namesGenes; let components = []; //Generate the data that the first graph will be using. //It uses the shannon function to generate the necessary data. for (let index = 0; index < answer[answer.length - 1].length; index++) { components = [] for (let innerIndex = 0; innerIndex < answer.length; innerIndex++) { if (namesArray.includes(namesGenes[innerIndex])) { components.push(answer[innerIndex].charAt(index)); } } if (!isProtein) { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G")) { fixJump++; continue; } } else { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G" && v !== "R" && v !== "N" && v !== "D" && v !== "B" && v !== "E" && v !== "Q" && v !== "Z" && v !== "H" && v !== "I" && v !== "L" && v !== "K" && v !== "M" && v !== "F" && v !== "P" && v !== "S" && v !== "W" && v !== "Y" && v !== "V")) { fixJump++; continue; } } valAverage += this.shannon(components); if (posAverage >= 5 || index == 0 || index + 1 == answer[answer.length - 1].length) { objectTemp = new myObject(index - fixJump + 1, valAverage / (posAverage + 1)); resultFirstGraph.push(objectTemp); valAverage = 0; posAverage = 0; } else { posAverage++; } } //Generate the data that the second graph will be using. let objectPosition = null; fixJump = 0; let resultSecondGraph = []; components = []; for (let index = 0; index < answer[answer.length - 1].length; index++) { components = []; for (let innerIndex = 0; innerIndex < answer.length; innerIndex++) { if (namesArray.includes(namesGenes[innerIndex])) { components.push(answer[innerIndex].charAt(index)); } } if (!isProtein) { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G")) { fixJump++; continue; } objectPosition = this.objectSecondGraph(components, (index + 1 - fixJump)); resultSecondGraph.push(objectPosition); } else { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G" && v !== "R" && v !== "N" && v !== "D" && v !== "B" && v !== "E" && v !== "Q" && v !== "Z" && v !== "H" && v !== "I" && v !== "L" && v !== "K" && v !== "M" && v !== "F" && v !== "P" && v !== "S" && v !== "W" && v !== "Y" && v !== "V")) { fixJump++; continue; } objectPosition = this.objectSecondGraphProteins(components, (index + 1 - fixJump)); resultSecondGraph.push(objectPosition); } } //Update the class variables with the results. this.setState({ selectedBoxes: namesArray, dataSecondGraph: resultSecondGraph, dataFirstGraph: resultFirstGraph, }); } /** * This function is called when the user selects the "select all sequences" option. */ selectAll() { const boxes = d3.selectAll(".form-check-input").nodes() boxes.map(function (item, i) { item.checked = true; }) this.filter(); } /** * This function is called when the user selects the "deselect all sequences" option. */ deselectAll() { const boxes = d3.selectAll(".form-check-input").nodes() boxes.map(function (item, i) { item.checked = false; }) this.filter(); } /** * This function return a piece of HTML depending on what needs to be loaded in the website. * The first option is if the information is loading. * The second option is if the file was corrupted or couldnt be loaded. * The third option is first screen the user sees, where he needs to select one of the example files of upload a file. */ initialButtons() { if (this.state.loading && !this.state.corruptFile) { return <h1 className="innerLoad">Loading...</h1>; } else if (this.state.corruptFile) { return (<div className="body innerLoad"> <h1>File Error</h1> <button className="btn btn-dark btn-lg" onClick={() => window.location.reload()}>Load new file</button></div>); } else { return (<div className="body innerLoad"> <div className="container"> <div className="row"> <div className="col-md"> <div className="card border-primary mb-3 cardWidth"> <div className="card-header">Upload a File</div> <div className="card-body text-dark"> <form> <div className="form-group"> <input type="file" className="hoverHand form-control-file" onChange={e => this.handleFile(e.target.files[0])} /> </div> </form> </div> </div> </div> </div> <div className="row"> <div className="col-md"> <div className="hoverHand card border-dark mb-3 cardWidth" onClick={() => this.handleFile("proteinExample")}> <div className="card-header">Example protein sequence</div> <div className="card-body text-dark"> <p className="card-text">Use an example file which contains 3 protein sequences.</p> </div> </div> </div> </div> <div className="row"> <div className="col-md"> <div className="hoverHand card border-dark mb-3 cardWidth" onClick={() => this.handleFile("geneExample")}> <div className="card-header">Example gene sequence</div> <div className="card-body text-dark"> <p className="card-text">Use an example file which contains 45 gene sequences.</p> </div> </div> </div> </div> <div className="row"> <div className="col-md"> <div className="hoverHand card border-dark mb-3 cardWidth" onClick={() => this.handleFile("coronaExample")}> <div className="card-header">Covid-19 sequences</div> <div className="card-body text-dark"> <p className="card-text">Use an example file which contains covid-19 sequences.</p> </div> </div> </div> </div> </div> </div>) } } /** * The function which changes the entropy chart between partial and full depending on the size of the selected file and what the user wants to see. */ firstGraphFullPartial(type) { if (type !== this.state.entropySelection) { let sizeGroups; let firstValue; let lastValue; if (type === "partial") { sizeGroups = 5; firstValue = this.state.valueFirstFilter; lastValue = this.state.valueSecondFilter; } else { sizeGroups = 50; firstValue = 1; lastValue = this.state.dataThirdGraph.length; } let namesArray = []; const isProtein = this.state.isProtein; let boxes = d3.selectAll(".form-check-input").nodes() boxes.map(function (item, i) { if (item.checked === true) { namesArray.push(item.value); } }) let objectTemp = null; let posAverage = 0; let resultFirstGraph = []; let valAverage = 0; let fixJump = 0; const answer = this.state.answer; const namesGenes = this.state.namesGenes; let components = []; //Generate the data that the first graph will be using. //It uses the shannon function to generate the necessary data. for (let index = 0; index < answer[answer.length - 1].length; index++) { components = [] for (let innerIndex = 0; innerIndex < answer.length; innerIndex++) { if (namesArray.includes(namesGenes[innerIndex])) { components.push(answer[innerIndex].charAt(index)); } } if (!isProtein) { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G")) { fixJump++; continue; } } else { if (components.some(v => v !== "-" && v !== "A" && v !== "T" && v !== "C" && v !== "G" && v !== "R" && v !== "N" && v !== "D" && v !== "B" && v !== "E" && v !== "Q" && v !== "Z" && v !== "H" && v !== "I" && v !== "L" && v !== "K" && v !== "M" && v !== "F" && v !== "P" && v !== "S" && v !== "W" && v !== "Y" && v !== "V")) { fixJump++; continue; } } valAverage += this.shannon(components); if (posAverage >= sizeGroups || index == 0 || index + 1 == answer[answer.length - 1].length) { objectTemp = new myObject(index - fixJump + 1, valAverage / (posAverage + 1)); resultFirstGraph.push(objectTemp); valAverage = 0; posAverage = 0; } else { posAverage++; } } this.setState({ dataFirstGraph: resultFirstGraph, entropySelection: type, initialEntropy: firstValue, finalEntropy: lastValue }) } } /** * The function which renders the alert if the sequence is long enough. */ alertLength() { if (this.state.dataThirdGraph.length > 1000) { return ( <div className="row"> <div className="col-md"> <div className="alert alert-warning" role="alert">Due to the length of the sequences, there's a limit of how many positions you can see at a time. You can still see the whole entropy graph with the following button. <div className="btn-group btn-group-toggle" data-toggle="buttons"> <label className="btn btn-dark active familyButtons"> <input type="radio" name="options" id="option1" onClick={() => this.firstGraphFullPartial("partial")} /> Partial </label> <label className="btn btn-dark familyButtons"> <input type="radio" name="options" id="option2" onClick={() => this.firstGraphFullPartial("full")} /> Full </label> </div> </div> </div> </div> ) } } /** * The render function will draw everything on the website. */ render() { return ( <div className="App"> {this.state.dataThirdGraph.length > 0 ? <div> <button className="btn btn-dark btn-lg" onClick={() => window.location.reload()}>Load new file</button> {!this.state.isProtein ? <Translation dataFifthGraph={this.state.dataFifthGraph} /> : <p></p>} <h1 className="marginTitle0">Table Filters <Tooltip placement="right" trigger="click" tooltip={this.state.information0}> <span type="button" className="badge badge-pill badge-primary">i</span> </Tooltip></h1> <div className="container"> <div className="row"> <div className="col-md"> <button className="btn btn-dark" type="submit" onClick={this.filter}>Filter</button> <button className="btn btn-dark" type="submit" onClick={this.selectAll}>Select All Sequences</button> <button className="btn btn-dark" type="submit" onClick={this.deselectAll}>Deselect All Sequences</button> </div> </div> <div className="row table-check" ref={this.tableref}> <div className="col-md"> {this.checkboxes()} </div> </div> <div className="row"> <div className="col-md"> <form> <select width="500" id="numberBar" className="form-control" onChange={this.filterAppJS} ref={this.selectref}> {this.selections()} <option value="" disabled ref={this.optionref}></option> </select> </form> </div> </div> {this.alertLength()} </div> <EntropyAndProfile leftChange={this.leftChange} rightChange={this.rightChange} bigFile={this.state.bigFile} isProtein={this.state.isProtein} dataSecondGraph={this.state.dataSecondGraph} dataFirstGraph={this.state.dataFirstGraph} valueFirstFilterMatrix={this.state.valueFirstFilter} valueSecondFilterMatrix={this.state.valueSecondFilter} valueFirstFilterEntropy={this.state.initialEntropy} valueSecondFilterEntropy={this.state.finalEntropy} /> <SequenceComparison leftChange={this.leftChange} rightChange={this.rightChange} bigFile={this.state.bigFile} isProtein={this.state.isProtein} dataThirdGraph={this.state.dataThirdGraph} namesGenes={this.state.namesGenes} valueFirstFilter={this.state.valueFirstFilter} valueSecondFilter={this.state.valueSecondFilter} /> <SequenceMatrix namesGenes={this.state.selectedBoxes} dataFourthGraph={this.state.dataThirdGraph} valueFirstFilter={this.state.valueFirstFilter} valueSecondFilter={this.state.valueSecondFilter} /> </div> : <div>{this.initialButtons()}</div>} </div> ); } }
JavaScript
class myObject { constructor(position, percentage) { this.position = position; this.percentage = percentage; } }
JavaScript
class myObjectSecondGraphGenes { constructor(position, percentagea, percentagec, percentageg, percentaget, percentagedash) { this.position = position; this.percentagea = percentagea; this.percentagec = percentagec; this.percentageg = percentageg; this.percentaget = percentaget; this.percentagedash = percentagedash; } }
JavaScript
class myObjectFifthGraph { constructor(position, letter) { this.position = position; this.letter = letter; } }
JavaScript
class myObjectSecondGraphProteins { constructor(position, percentagea, percentagec, percentageg, percentaget, percentager, percentagen, percentaged, percentageb, percentagee, percentageq, percentagez, percentageh, percentagei, percentagel, percentagek, percentagem, percentagef, percentagep, percentages, percentagew, percentagey, percentagev, percentagedash) { this.position = position; this.percentagea = percentagea; this.percentagec = percentagec; this.percentageg = percentageg; this.percentaget = percentaget; this.percentager = percentager; this.percentagen = percentagen; this.percentaged = percentaged; this.percentageb = percentageb; this.percentagee = percentagee; this.percentageq = percentageq; this.percentagez = percentagez; this.percentageh = percentageh; this.percentagei = percentagei; this.percentagel = percentagel; this.percentagek = percentagek; this.percentagem = percentagem; this.percentagef = percentagef; this.percentagep = percentagep; this.percentages = percentages; this.percentagew = percentagew; this.percentagey = percentagey; this.percentagev = percentagev; this.percentagedash = percentagedash; } }
JavaScript
class UserAccountActionTokenModel extends BaseModel { /** * UserAccountActionTokenModel Constructor * * @protected */ constructor() { super(); /** * The User Account Action Token ID * * @type {string} * @public */ this.id = undefined; /** * The Account this Action Token belongs to * * @type {string} * @public */ this.accountId = undefined; /** * The Company this Action Token belongs to * * @type {string} * @public */ this.companyId = undefined; /** * The Action that can be Performed using this Action Token * * @type {string} * @public */ this.action = undefined; /** * When the Action Token was issued * * @type {Date} * @public */ this.issueTimestamp = undefined; /** * When the Action Token will expire * * @type {Date} * @public */ this.expireTimestamp = undefined; /** * When the last API call using this Action Token was made * * @type {?Date} * @public */ this.activityTimestamp = undefined; /** * When the Action was Completed * * @type {?Date} * @public */ this.completedTimestamp = undefined; /** * When the Action Email was Sent * * @type {?Date} * @public */ this.emailTimestamp = undefined; /** * Whether the User Account Action Token has been deleted * * @type {boolean} * @public */ this.deleted = undefined; /** * When the User Account Action Token was last updated * * @type {Date} * @public */ this.updateTimestamp = undefined; } /** * Create a new **UserAccountActionTokenModel** from a JSON Object or JSON String * * @static * @public * @param {Object<string, any>|string} json A JSON Object or JSON String * @return {UserAccountActionTokenModel} */ static fromJSON(json) { let model = new UserAccountActionTokenModel(); /** * The JSON Object * * @type {Object<string, any>} */ let jsonObject = {}; if(typeof json === 'string') { jsonObject = JSON.parse(json); } else if(typeof json === 'object') { jsonObject = json; } if('id' in jsonObject) { model.id = (function(){ if(typeof jsonObject['id'] !== 'string') { return String(jsonObject['id']); } return jsonObject['id']; }()); } if('accountId' in jsonObject) { model.accountId = (function(){ if(typeof jsonObject['accountId'] !== 'string') { return String(jsonObject['accountId']); } return jsonObject['accountId']; }()); } if('companyId' in jsonObject) { model.companyId = (function(){ if(typeof jsonObject['companyId'] !== 'string') { return String(jsonObject['companyId']); } return jsonObject['companyId']; }()); } if('action' in jsonObject) { model.action = (function(){ if(typeof jsonObject['action'] !== 'string') { return String(jsonObject['action']); } return jsonObject['action']; }()); } if('issueTimestamp' in jsonObject) { model.issueTimestamp = (function(){ if(typeof jsonObject['issueTimestamp'] !== 'string') { return new Date(String(jsonObject['issueTimestamp'])); } return new Date(jsonObject['issueTimestamp']); }()); } if('expireTimestamp' in jsonObject) { model.expireTimestamp = (function(){ if(typeof jsonObject['expireTimestamp'] !== 'string') { return new Date(String(jsonObject['expireTimestamp'])); } return new Date(jsonObject['expireTimestamp']); }()); } if('activityTimestamp' in jsonObject) { model.activityTimestamp = (function(){ if(jsonObject['activityTimestamp'] === null) { return null; } if(typeof jsonObject['activityTimestamp'] !== 'string') { return new Date(String(jsonObject['activityTimestamp'])); } return new Date(jsonObject['activityTimestamp']); }()); } if('completedTimestamp' in jsonObject) { model.completedTimestamp = (function(){ if(jsonObject['completedTimestamp'] === null) { return null; } if(typeof jsonObject['completedTimestamp'] !== 'string') { return new Date(String(jsonObject['completedTimestamp'])); } return new Date(jsonObject['completedTimestamp']); }()); } if('emailTimestamp' in jsonObject) { model.emailTimestamp = (function(){ if(jsonObject['emailTimestamp'] === null) { return null; } if(typeof jsonObject['emailTimestamp'] !== 'string') { return new Date(String(jsonObject['emailTimestamp'])); } return new Date(jsonObject['emailTimestamp']); }()); } if('deleted' in jsonObject) { model.deleted = (function(){ if(typeof jsonObject['deleted'] !== 'boolean') { return Boolean(jsonObject['deleted']); } return jsonObject['deleted']; }()); } if('updateTimestamp' in jsonObject) { model.updateTimestamp = (function(){ if(typeof jsonObject['updateTimestamp'] !== 'string') { return new Date(String(jsonObject['updateTimestamp'])); } return new Date(jsonObject['updateTimestamp']); }()); } return model; } }
JavaScript
class Demo extends React.Component { render() { return ( <div> <div> <h3>Component with placeholder text</h3> <pre> {` <InlineEdit placeholder="Add text here..." /> `} </pre> <InlineEdit placeholder="Add text here..." /> </div> <div> <h3>Component with minRows and maxRows</h3> <pre> {` <InlineEdit minRows={3} maxRows={6} defaultValue="Click here and edit..." /> `} </pre> <InlineEdit minRows={3} maxRows={6} defaultValue="Click here and edit..." /> </div> <div> <h3>Component with maxRows</h3> <pre> {` <InlineEdit maxRows={5} defaultValue="..." /> `} </pre> <InlineEdit maxRows={5} defaultValue=" Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. " /> </div> <div> <h3>Component with maxHeight</h3> <pre> {` <InlineEdit style={{maxHeight: 100}} defaultValue="Click here and edit..." /> `} </pre> <InlineEdit style={{maxHeight: 100}} defaultValue="Click here and edit..." /> </div> <div> <h3>Component with set # of rows</h3> <pre> {` <InlineEdit rows={4} defaultValue="Click here and edit..." /> `} </pre> <InlineEdit rows={4} defaultValue="Click here and edit..." /> </div> </div> ); } }
JavaScript
class Car { constructor (name,year){ this.year=year; this.name = name; } // below is a funtion that finds the age of the car age(x){ let years = x-this.year; return years; } }
JavaScript
class WebhookClient extends BaseClient { /** * @param {Snowflake} id 웹훅의 ID * @param {string} token 웹훅의 토큰 * @param {ClientOptions} [options] 웹훅에 대한 옵션 * @example * // 새로운 웹훅을 생성하고 메세지를 보냅니다. * const hook = new Discord.WebhookClient('1234', 'ㅁㄴㅇㄹ'); * hook.send('이것이 메세지를 전송할 것입니다.').catch(console.error); */ constructor(id, token, options) { super(options); Object.defineProperty(this, 'client', { value: this }); this.id = id; Object.defineProperty(this, 'token', { value: token, writable: true, configurable: true }); } }
JavaScript
class JobsPagination { /** * Constructs a new <code>JobsPagination</code>. * @alias module:model/JobsPagination * @class */ constructor() { } /** * Constructs a <code>JobsPagination</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/JobsPagination} obj Optional instance to populate. * @return {module:model/JobsPagination} The populated <code>JobsPagination</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new JobsPagination(); if (data.hasOwnProperty('current_page')) { obj['current_page'] = ApiClient.convertToType(data['current_page'], 'Number'); } if (data.hasOwnProperty('last_page')) { obj['last_page'] = ApiClient.convertToType(data['last_page'], 'Number'); } if (data.hasOwnProperty('next_page_url')) { obj['next_page_url'] = ApiClient.convertToType(data['next_page_url'], 'String'); } if (data.hasOwnProperty('prev_page_url')) { obj['prev_page_url'] = ApiClient.convertToType(data['prev_page_url'], 'String'); } } return obj; } /** * @member {Number} current_page */ 'current_page' = undefined; /** * @member {Number} last_page */ 'last_page' = undefined; /** * @member {String} next_page_url */ 'next_page_url' = undefined; /** * @member {String} prev_page_url */ 'prev_page_url' = undefined; }
JavaScript
class Accumulator extends Transform { /** * @param {Object} [options={}] - Stream options * @example <caption>Class is abstract</caption> */ constructor(options) { super(options); } /** * Charging stream * * @abstract * @param {*} data - charged data * @param {String} encoding - data encoding * @param {Function} next - pass function */ _charge(data, encoding, next) { // eslint-disable-line no-unused-vars throw new Error('Method _charge is abstract'); } /** * Release charged data * * @abstract * @returns {*} - left data */ _release() { throw new Error('Method _release is not defined'); } /** * @private */ _transform(chunk, encoding, next) { this._charge(chunk, encoding, next); } /** * @private */ _flush(next) { this.push(this._release()); next(); } }
JavaScript
class NRContainer extends NRObject { /** * constructor - Description * * @param {type} config Description * */ constructor(config) { super(config); this.nodes = new Map(); } /** * addNode - Description * @param {NRNode} node Description */ addNode(node) { this.nodes.set(node.id, node); node.setParent(this); } exportContents() { let result = []; this.nodes.forEach((n,_) => { result.push(n.export()); }) return result; } walkContents(callback) { this.nodes.forEach(n => n.walk(callback)); } }
JavaScript
class validations { /** * @description validate user details * @function signupValidations * @param {object} body * @returns {Array} signupErrors */ static async signupValidations(body) { const { email, password, confirmPassword } = body; const signupErrors = {}; const emailAlreadyExist = await checkEmail(email); if (!email || !validEmail.test(email)) { signupErrors.message = 'Invalid Email Format'; } if (emailAlreadyExist) { signupErrors.message = 'Employer with this email already exist'; } if (!password || password.length < 3) { signupErrors.message = 'Password is required, with at least three characters'; } if (!confirmPassword || confirmPassword !== password) { signupErrors.message = 'Passwords don\'t match'; } return signupErrors; } /** * @description validate user details * @function signinValidations * @param {object} body * @returns {Array} signinErrors */ static signinValidations(body) { const { email, password } = body; const signinErrors = {}; if (!email || !validEmail.test(email)) { signinErrors.message = 'Invalid Email Format'; } if (!password || password.length < 2) { signinErrors.message = 'Password must be at least three characters'; } return signinErrors; } }
JavaScript
class Chip8Wrapper { /** * @param {Function} debugFunc will be passed the chip8 state, numBase and executed every cycle */ constructor(debugFunc) { autoBind(this); this.debugFunc = debugFunc || function () {}; this.loop = 0; this.chip8 = new Chip8(); this.ROMS = []; this.keyDownEvent = this.chip8.keyboard.keyDown; this.keyUpEvent = this.chip8.keyboard.keyUp; this.debugNumBase = 16; } emuCycleLoop() { this.emulateCycle(); this.debugFunc(this.chip8, this.debugNumBase); this.loop = requestAnimationFrame(this.emuCycleLoop); } startEmuCycleLoop() { this.loop = requestAnimationFrame(this.emuCycleLoop); } stopemuCycleloop() { cancelAnimationFrame(this.loop); } /** * pause emulator before next cycle execution * if paused, will resume */ pauseEmu() { if (this.chip8.pause === false) { this.chip8.pause = true; } else { this.chip8.pause = false; } } /** * @param {Number} speed the speed to execute instructions */ setEmuSpeed(speed) { this.chip8.speed = speed; } /** * @param {Boolean} sound value to turn on (true) or off (false) */ setEmuSoundEnabled(sound) { this.chip8.soundOff = sound; } /** * @param {Number} blinkLevel the level of blink reduction (0-3) */ setEmuScreenBlinkLevel(blinkLevel) { if (blinkLevel < 0 || blinkLevel > 3) throw new Error('invalid blink level'); this.chip8.screen.blinkReductionLevel = blinkLevel; } emulateCycle() { this.chip8.emulateCycle(); } /** * @param {Number} numBase 10 or 16 */ setEmuDebugNumBase(numBase) { if (numBase !== 10 || numBase !== 16) throw new Error('Invalid number base'); this.debugNumBase = numBase; } /** * @param {Function} debugFunc function to call */ setEmuDebugFunc(debugFunc) { this.debugFunc = debugFunc; } /** * @param {Object} context browsers sound context */ setEmuSoundCtx(context) { this.chip8.sound = new Sound(context); } /** * execute key up emulation * @param {Number} charCode pressed keys character code */ emuKeyUp(charCode) { this.chip8.keyboard.keyUp({ which: charCode }); } /** * execute key down emulation * @param {Number} charCode key pressed character code */ emuKeyDown(charCode) { this.chip8.keyboard.keyDown({ which: charCode }); } /** * @param {*} canvas canvas context */ setEmuCanvasCtx(canvas) { this.chip8.screen.setCanvas(canvas); } /** * fetch all ROM names from file. * Insert names into array property */ async loadROMNames() { const romNames = await fetch('https://balend.github.io/chip8-emulator-js/roms/names.txt'); // resolve body to UTF-8 string const bodyString = await romNames.text(); // split string by comma // trim and turn each string to uppercase const names = bodyString.split(',').map((name) => name.trim().toUpperCase()); // filter out empty strings const filteredNames = names.filter((name) => name !== ''); this.ROMS = filteredNames; } /** * fetches binary data in a ROM and starts the emulator * @param {String} name name of the ROM to fetch */ async loadROM(name) { const ROMData = await fetch(`https://balend.github.io/chip8-emulator-js/roms/${name.toLowerCase()}`); this.stopemuCycleloop(); this.chip8.resetState(); this.chip8.loadROM(new Uint8Array(await ROMData.arrayBuffer())); this.startEmuCycleLoop(); } }
JavaScript
class DrReShellSessionEngine extends PhantomCore { constructor({ posSpeechAnalyzer }) { super({ isAsync: true }); this._lastTextInputTime = null; this._history = []; this._posSpeechAnalyzer = posSpeechAnalyzer; this.registerCleanupHandler(() => (this._posSpeechAnalyzer = null)); // Initial phase this._phase = null; this._totalInteractions = 0; this._sentiment = DEFAULT_SENTIMENT; this._score = 0; this._elizaBot = new ElizaBotController(); this.registerCleanupHandler(() => this._elizaBot.destroy()); this._response = null; this._init(); } async _init() { await this._elizaBot.onceReady(); // Create initiating conversation this._response = await this._elizaBot.start(); // Simulate auto-typing phase this._phase = PHASE_AUTO_RESPONSE_TYPING; return super._init(); } /** * Processes input text. * * @param {string} text * @return {Promise<void>} */ async processText(text) { text = text.trim(); if (!text.length) { return; } // Concatenate the input prompt with the text // // FIXME: This could use some additional refactoring to not need to include // the input prompt at all in this class this._history.push(`${INPUT_PROMPT}${text}`); // Increment the interactions ++this._totalInteractions; const { title: sentiment, score } = (await this._posSpeechAnalyzer.fetchSentimentAnalysis(text)) || { title: "Neutral", }; if (score !== 0 || this._sentiment === DEFAULT_SENTIMENT) { this._sentiment = sentiment; } const scoreAddend = score * 1000; if (scoreAddend) { // If score is positive, add "+" (plus) sign // A negative score will already include the "-" (minus) sign this._history.push(`${scoreAddend > 0 ? "+" : ""}${scoreAddend}`); } this._score += scoreAddend; // Add intentional empty line this._history.push(""); // Update the UI this.emit(EVT_UPDATED); this._response = await this._elizaBot.reply(text); this.switchPhase(PHASE_AUTO_RESPONSE_TYPING); } /** * Retrieves the text history string array. * * @return {string[]} */ getHistory() { return this._history; } /** * Retrieves the bot's most recent response. * * @return {string} */ getResponse() { return this._response; } /** * Adds the bot's most recent response to history. * * This is a public method to help facilitate the UI's typing effect. * * @param {string} responseText */ addResponseToHistory(responseText) { this._history.push(responseText); this.switchPhase(PHASE_AWAITING_USER_INPUT); } /** * Switches the input / output phase. * * @param {PHASE_AUTO_RESPONSE_TYPING | PHASE_AWAITING_USER_INPUT} phase * @return {void} */ switchPhase(phase) { this._phase = phase; this.emit(EVT_UPDATED); } /** * Retrieves the current phase. * * @return {PHASE_AUTO_RESPONSE_TYPING | PHASE_AWAITING_USER_INPUT} */ getPhase() { return this._phase; } /** * Retrieves the current number of interactions. * * @return {number} */ getTotalInteractions() { return this._totalInteractions; } /** * Retrieves the current sentiment. * * @return {string} */ getSentiment() { return this._sentiment; } /** * Retrieves the overall score. * * @return {number} */ getScore() { return this._score; } }
JavaScript
class CreatePortal extends React.Component { static propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.element), PropTypes.element, ]).isRequired, }; // Only executes on the client-side componentDidMount() { // Get the document body this.body = document.body; // Create a container <div /> for React Portal this.portalContainer = document.createElement('div'); // Append the container to the document body this.body.appendChild(this.portalContainer); // Force a re-render as we're on the client side now // children prop will render to portalContainer this.forceUpdate(); } componentWillUnmount() { // Cleanup Portal from DOM this.body.removeChild(this.portalContainer); } render() { // Return null during SSR if (this.portalContainer === undefined) return null; const { children } = this.props; return ReactDOM.createPortal(children, this.portalContainer); } }
JavaScript
class NavigationControl { constructor () { this._container = window.document.createElement ("div"); this._container.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; this._container.addEventListener ("contextmenu", e => e.preventDefault ()); } addButton (button) { this._container.appendChild (button); } removeButton (button) { this._container.removeChild (button); } onAdd (map) { this._map = map; for (let i = 0; i < this._container.children.length; i++) { const child = this._container.children[i]; if (child.onAdd) child.onAdd (map) } return (this._container); } onRemove () { if (this._container.parentNode) this._container.parentNode.removeChild (this._container); for (let i = 0; i < this._container.children.length; i++) { const child = this._container.children[i]; if (child.onRemove) child.onRemove () } delete this._map; } }
JavaScript
class NavMeshFlowFieldBehavior extends SteeringBehavior { /** * * @param {NavMeshFlowField} flowField For now, only accepts a persistant NavMeshFLowField. (todo: non-persitant flowfield case) */ constructor(flowField, finalDestPt, pathRef, epsilon = 1e-3, arrivalDist = 0, arrivalCallback=null) { super(); this.flowField = flowField; this.finalDestPt = finalDestPt; this.epsilon = epsilon; this.pathRef = pathRef; this.arrivalSqDist = arrivalDist === 0 ? this.epsilon : arrivalDist; this.arrivalSqDist *= this.arrivalSqDist; this.arrivalCallback = arrivalCallback; } onAdded(vehicle) { vehicle.agent = new FlowAgent(); } onRemoved(vehicle) { vehicle.agent = null; } calculate( vehicle, force /*, delta */ ) { let agent = vehicle.agent; desiredVelocity.x = 0; desiredVelocity.z = 0; let refPosition = vehicle.position; if (agent.lane === false || agent.lane === true) { // arrival routine if (vehicle.position.squaredDistanceTo(this.finalDestPt) < this.arrivalSqDist) { if (agent.lane === false) { if (this.arrivalCallback !== null) this.arrivalCallback(vehicle); agent.lane = true; } } else { agent.calcDir(refPosition, desiredVelocity); } desiredVelocity.x *= vehicle.maxSpeed; desiredVelocity.z *= vehicle.maxSpeed; force.x = desiredVelocity.x - vehicle.velocity.x; force.z = desiredVelocity.z - vehicle.velocity.z; return force; } if (!agent.curRegion) { this.setCurRegion(vehicle); if (!agent.curRegion) { force.x = -vehicle.velocity.x; force.z = -vehicle.velocity.z; return force; } } else { let region; if (agent.lane === null) { region = agent.getCurRegion(); if (this.flowField.hasFlowFromRegion(region)) this.setCurRegion(vehicle, region); else { force.x = -vehicle.velocity.x; force.z = -vehicle.velocity.z; return force; } } if (!agent.withinCurrentTriangleBounds(refPosition)) { region = agent.getCurRegion(); if ((region.edge.next.next.next !== region.edge && agent.withinCurrentRegionBounds(vehicle.position)) && agent.withinFlowPlane(vehicle.position, this.epsilon) ) { // update triangle from triangulation agent.curRegion.updateLane(refPosition, agent); //console.log("New lane:"+agent.lane); agent.curRegion.updateFlowTriLaned(refPosition, agent, this.flowField.edgeFieldMap); } else { // doesn't belong to current region let lastRegion = agent.curRegion; if (this.setCurRegion(vehicle) === false) { // ARRIVED //vehicle.velocity.x = 0; //vehicle.velocity.y = 0; agent.lane = false; agent.calcDir(refPosition, desiredVelocity); desiredVelocity.x *= vehicle.maxSpeed; desiredVelocity.z *= vehicle.maxSpeed; force.x = desiredVelocity.x - vehicle.velocity.x; force.z = desiredVelocity.z - vehicle.velocity.z; return force; } if (!agent.curRegion) { refPosition = clampPointWithinRegion(region, refPosition); agent.curRegion = lastRegion; if (region.edge.next.next.next !== region.edge && lastRegion !== region) { // 2nd && case for FlowTriangulate lastRegion.updateLane(refPosition, agent); //console.log("New lane222:"+agent.lane); lastRegion.updateFlowTriLaned(refPosition, agent, this.flowField.edgeFieldMap); } } } } } agent.calcDir(refPosition, desiredVelocity); /* if (isNaN(desiredVelocity.x)) { console.log([agent.a, agent.b, agent.c, agent.curRegion]) throw new Error("NaN desired velocity calculated!"+agent.currentTriArea() + " :: "+agent.lane); } */ // desiredVelocity.multiplyScalar( vehicle.maxSpeed ); desiredVelocity.x *= vehicle.maxSpeed; desiredVelocity.z *= vehicle.maxSpeed; // The steering force returned by this method is the force required, // which when added to the agent’s current velocity vector gives the desired velocity. // To achieve this you simply subtract the agent’s current velocity from the desired velocity. //return force.subVectors( desiredVelocity, vehicle.velocity ); force.x = desiredVelocity.x - vehicle.velocity.x; force.z = desiredVelocity.z - vehicle.velocity.z; //force.x = desiredVelocity.x; //force.z = desiredVelocity.z; return force; } /** * Set current region based on vehicle's position to vehicle's agent * @param {Vehicle} vehicle The vehicle * @param {Polygon} forceSetRegion (Optional) A region to force a vehicle to be assosiated with, else attempt will search a suitable region on navmesh. * Setting this parameter to a falsey value that isn't undefined (eg. null) will perform additional within bounds refPosition clamp check. * WARNING: It is assumed this `forceSetRegion` will be able to reach final destination node * @return {Null|Number|Boolean} * Null if no region could be picked. * True if same region detected from last saved region * False if no flow path could be found due to reaching final destination. * Zero `0` if no flow path ould be found at all to reach final destination. * One `1` if no flow path could be found (not yet reached final destination). */ setCurRegion(vehicle, forceSetRegion) { let agent = vehicle.agent; let flowField = this.flowField; let lastRegion = !forceSetRegion ? agent.getCurRegion() : null; let regionPicked = !forceSetRegion ? flowField.navMesh.getRegionForPoint(vehicle.position, this.epsilon) : forceSetRegion; if (!regionPicked) { agent.curRegion = null; return null; } let refPosition = vehicle.position; // ensure refPosition clamped is within forceSetRegion if (forceSetRegion !== undefined && !FlowAgent.pointWithinRegion(refPosition, regionPicked)) { refPosition = clampPointWithinRegion(regionPicked, refPosition); } if (regionPicked === lastRegion) { if (agent.curRegion !== regionPicked) { agent.curRegion.updateLane(refPosition, agent); agent.curRegion.updateFlowTriLaned(refPosition, agent, flowField.edgeFieldMap); } return true; } let lastNodeIndex = lastRegion ? flowField.getFromNodeIndex(lastRegion, regionPicked, this.pathRef) : -1; //console.log(lastNodeIndex + ">>>"); let edgeFlows = flowField.calcRegionFlow(lastNodeIndex, flowField.navMesh.getNodeIndex(regionPicked), this.pathRef, this.finalDestPt); if (!edgeFlows) { agent.curRegion = null; console.log("setCurRegion:: Could not find flow path from current position") return 0; } if (regionPicked.edge.next.next.next === regionPicked.edge) { // triangle agent.curRegion = regionPicked; if (edgeFlows.length ===0) { //console.log("ARRIVED at last triangle region"); FlowTriangulate.updateNgonFinalTri(regionPicked, refPosition, agent, flowField.edgeFieldMap, this.finalDestPt, this.epsilon); return false; } agent.lane = 0; FlowTriangulate.updateTriRegion(agent.curRegion, agent, flowField.edgeFieldMap); } else { // non-tri zone if (edgeFlows.length === 0) { //console.log("ARRIVED at last non-tri region"); agent.curRegion = regionPicked; FlowTriangulate.updateNgonFinalTri(regionPicked, refPosition, agent, flowField.edgeFieldMap, this.finalDestPt, this.epsilon); return false; } /* (lastNodeIndex >= 0 ? regionPicked.getEdgeTo(flowField.navMesh.regions[lastNodeIndex]) : flowField.triangulationMap.get(regionPicked) */ agent.curRegion = flowField.triangulationMap.get(edgeFlows[0]); if (!agent.curRegion) { agent.curRegion = flowField.setupTriangulation(null, edgeFlows[0], edgeFlows[0]); } agent.curRegion.updateLane(refPosition, agent); agent.curRegion.updateFlowTriLaned(refPosition, agent, flowField.edgeFieldMap); } return 1; } }
JavaScript
class Animal extends service.Service { _find (params) { const knexQuery = this.createQuery(params); knexQuery .select('ancestors.name as ancestor_name') .leftJoin( 'animals as ancestors', 'ancestors.id', '=', 'animals.ancestor_id' ); params.knex = knexQuery; return super._find(params); } }
JavaScript
class BottomNavigationComponent extends React.Component { constructor() { super(...arguments); this.onTabSelect = (index) => { if (this.props.onSelect && this.props.selectedIndex !== index) { this.props.onSelect(index); } }; this.getComponentStyle = (source) => { const { indicatorHeight, indicatorBackgroundColor } = source, containerParameters = __rest(source, ["indicatorHeight", "indicatorBackgroundColor"]); return { container: containerParameters, item: {}, indicator: { height: indicatorHeight, backgroundColor: indicatorBackgroundColor, }, }; }; this.renderIndicatorElement = (positions, style) => { const { indicatorStyle, selectedIndex } = this.props; return (<TabIndicator key={0} style={[style, styles.indicator, indicatorStyle]} selectedPosition={selectedIndex} positions={positions}/>); }; this.renderTabElement = (element, index) => { return React.cloneElement(element, { key: index, style: [styles.item, element.props.style], selected: index === this.props.selectedIndex, onSelect: () => this.onTabSelect(index), }); }; this.renderTabElements = (source) => { return React.Children.map(source, this.renderTabElement); }; this.renderComponentChildren = (style) => { const tabElements = this.renderTabElements(this.props.children); const hasIndicator = style.indicator.height > 0; return [ hasIndicator && this.renderIndicatorElement(tabElements.length, style.indicator), ...tabElements, ]; }; } render() { const _a = this.props, { themedStyle, style } = _a, derivedProps = __rest(_a, ["themedStyle", "style"]); const _b = this.getComponentStyle(themedStyle), { container } = _b, componentStyles = __rest(_b, ["container"]); const [indicatorElement, ...tabElements] = this.renderComponentChildren(componentStyles); return (<View {...derivedProps} style={[container, styles.container, style]}> {indicatorElement} {tabElements} </View>); } }
JavaScript
class MiddleSquare extends Generator { /** * Minimum value for RNG based on bits. * * @type {BigInt} */ get min() {return 0n} constructor(args) { console.warn('Number sequence may repeat and definitely do on smaller bit ranges.') super(args) if(this.bits == 1) { this.seedBits = 3 } else { this.seedBits = 2 * this.bits } this.seedState = this.toBigInt(this.seed, this.bits) this.weylState = 0n } /** * Attempt to make a Weyl value for a Weyl sequence. Unsure if it actually works. * * @returns {BigInt} */ makeWeyl() { if(typeof this.weyl == typeof undefined) { let maxWeyl = (2n ** BigInt(this.seedBits)) - 1n // Try using 90% of max as a Weyl sequence // let mid = (maxWeyl * 9n) / 10n let mid = maxWeyl/(BigInt(this.seedBits) * 2n) // Means it's even, but we want odd if(mid % 2n == 0n) { mid++ } this.weyl = mid } return this.fixBits(this.weyl, this.seedBits) } /** * Returns the middle this.bits of a value. * * @param {BigInt} value - The value to get the middle of. * * @returns {BigInt} - The middle of value. */ getMiddle(value) { let bitDiff = BigInt(this.seedBits - this.bits) let left = 0n let right = 0n // If the difference between bits is odd, move left more than we move right. if(bitDiff % 2n != 0n) { left = (bitDiff/2n) + 1n right = left + (bitDiff/2n) } else { left = (bitDiff/2n) right = left * 2n } let newValue = this.leftShift(value, left, this.seedBits) newValue = newValue >> right return newValue } random() { let newState = this.seedState ** 2n this.weylState = this.fixBits(this.weylState + this.makeWeyl(), this.seedBits) newState = this.fixBits(newState + this.weylState, this.seedBits) /* let left = this.leftShift(newState, BigInt(this.bits), this.seedBits) let right = newState >> BigInt(this.bits) newState = right | left */ newState = this.getMiddle(newState) this.seedState = newState return this.fixBits(newState) } }
JavaScript
class Dispatch { /** * Creates an instance of Dispatch. * @param {deps} deps * @memberof Dispatch */ constructor(deps) { this._mod = deps.mod; this._dispatch = deps.mod; this.__hooks = []; } /** * Add hook. * @param {*} args * @memberof Dispatch */ hook(...args) { this.__hooks.push(this._mod.hook(...args)); } /** * Add hook once. * @param {*} args * @memberof Dispatch */ hookOnce(...args) { this._mod.hookOnce(...args); } /** * Remove hook. * @memberof Dispatch */ unhook() { throw new Error("Unhook not supported for TERA-Guide"); } /** * Remove all loaded hooks. * @memberof Dispatch */ unhookAll() { this.__hooks.forEach(hook => this._mod.unhook(hook)); this.__hooks = []; } /** * Require a module. * @readonly * @memberof Dispatch */ get require() { return this._mod.require; } /** * Set timeout. * @param {*} args * @memberof Dispatch */ setTimeout(...args) { return this._mod.setTimeout(...args); } /** * Clear timeout. * @param {*} args * @memberof Dispatch */ clearTimeout(...args) { return this._mod.clearTimeout(...args); } /** * Send packet. * @param {*} args * @memberof Dispatch */ toServer(...args) { return this.send(...args); } /** * Send packet. * @param {*} args * @memberof Dispatch */ toClient(...args) { return this.send(...args); } /** * Send packet. * @param {*} args * @memberof Dispatch */ send(...args) { return this._mod.send(...args); } /** * Removes all loaded hooks. * @memberof Dispatch */ destructor() { this.unhookAll(); } }
JavaScript
class ArrayWriter { /** * Creates an instance of ArrayPrinter. * @constructor * @param {Array} list The desired array to fill the ArrayPrinter with. */ constructor(list) { this._list = list; } /** * Getter * @returns {Array} The current array of this instance of ArrayWriter. */ get list() { return this._list; } /** * Setter * @param {Array} list The desired array to fill the ArrayPrinter with. */ set list(list) { this._list = list; } /** * Writes the contents of _list to the document between the entered tags. * @param {String} startTag The desired start tag to write. * @param {String} endTag The desired end tag to write. */ writeArray(startTag, endTag) { this._list.forEach(function(element) { document.write(startTag + element + endTag); }); } /** Writes the contents of _list to the document in paragraph tags. */ writeArrayP() { this.writeArray('<p>','</p>') } /** * Writes the contents of _list to the document in paragraph tags that are assigned to the specified class. * @param {String} eClass The desired class to assign to all elements. */ writeArrayClassP(eClass) { this.writeArray('<p class=' + eClass + '>','</p>') } /** * Writes the contents of _list to the document in header tags at a specified level. * @param {Number} headerLevel The desired header level to write (1-6). */ writeArrayH(headerLevel) { this.writeArray('<h' + String(headerLevel) + '>','</h' + String(headerLevel) + '>') } /** * Writes the contents of _list to the document in header tags at a specified level that are assigned to the specified class. * @param {Number} headerLevel The desired header level to write (1-6). * @param {String} eClass The desired class to assign to all elements. */ writeArrayClassH(headerLevel, eClass) { this.writeArray('<h' + String(headerLevel) + ' class=' + eClass + '>','</h' + String(headerLevel) + '>') } /** Writes the contents of _list to the document in divider tags. */ writeArrayDiv() { this.writeArray('<div>','</div>') } /** * Writes the contents of _list to the document in divider tags that are assigned to the specified class. * @param {String} eClass The desired class to assign to all elements. */ writeArrayClassDiv(eClass) { this.writeArray('<div class=' + eClass + '>','</div>') } /** Writes the contents of _list to the document in span tags. */ writeArraySpan() { this.writeArray('<span>','</span>') } /** * Writes the contents of _list to the document in span tags that are assigned to the specified class. * @param {String} eClass The desired class to assign to all elements. */ writeArrayClassSpan(eClass) { this.writeArray('<span class=' + eClass + '>','</span>') } /** Writes the contents of _list to the document in list item tags. */ writeArrayLI() { this.writeArray('<li>','</li>') } /** * Writes the contents of _list to the document in list item tags that are assigned to the specified class. * @param {String} eClass The desired class to assign to all elements. */ writeArrayClassLI(eClass) { this.writeArray('<li class=' + eClass + '>','</li>') } /** * Writes the contents of _list to the document between the entered tags in addition to adding an incrementing id based on the prefix. * Removes last character of startTag under the assumption it's '>' in order to insert the id. * @param {String} startTag The desired start tag to write. * @param {String} endTag The desired end tag to write. * @param {String} prefix The prefix for every element's id. */ writeArrayIDs(startTag, endTag, prefix) { let eNum = 0; this._list.forEach(function(element) { eNum++; document.write(startTag.substring(0, startTag.length - 1) + ' id=' + prefix + String(eNum) + '>' + element + endTag); }); } /** * Writes the contents of _list to to the document between two sets of entered tags determined by the evaluation of the passed boolean function for each element. * @param {String} startTagTrue The desired start tag to write if the condition is true for the element. * @param {String} endTagTrue The desired end tag to write if the condition is true for the element. * @param {String} startTagFalse The desired start tag to write if the condition is false for the element. * @param {String} endTagFalse The desired end tag to write if the condition is false for the element. * @param {Function} boolFunction The desired boolean function to be evaluated for each element. */ writeArrayConditional(startTagTrue, endTagTrue, startTagFalse, endTagFalse, boolFunction) { this._list.forEach(function(element) { document.write(boolFunction(element) ? startTagTrue + element + endTagTrue : startTagFalse + element + endTagFalse) }); } /** * Writes the contents of _list to to the document between two sets of entered tags determined by the evaluation of the passed boolean function for each element. * Modifies element based on the passed mod functions depending on the condition result for the element. * @param {String} startTagTrue The desired start tag to write if the condition is true for the element. * @param {String} endTagTrue The desired end tag to write if the condition is true for the element. * @param {String} startTagFalse The desired start tag to write if the condition is false for the element. * @param {String} endTagFalse The desired end tag to write if the condition is false for the element. * @param {Function} boolFunction The desired boolean function to be evaluated for each element. * @param {Function} modFuncTrue The desired function to modify element if the condition is true for the element. * @param {Function} modFuncFalse The desired function to modify element if the condition is false for the element. */ writeArrayConditionalModifiable(startTagTrue, endTagTrue, startTagFalse, endTagFalse, boolFunction, modFuncTrue, modFuncFalse) { this._list.forEach(function(element) { document.write(boolFunction(element) ? startTagTrue + modFuncTrue(element) + endTagTrue : startTagFalse + modFuncFalse(element) + endTagFalse); }); } }
JavaScript
class ObjectChoiceView extends React.Component{ /** * {Object} leftTreeViewData contains processed API data in right format for showing in TreeView * {title: String, id: String} leftTreeInput contains the id and title of selected object in left TreeView * {title: String, id: String} rightTreeInput contains the id and title of selected object in right TreeView */ constructor() { super(); this.state = { leftTreeViewData: [], leftTreeViewFilterList: [], leftTreeInput: {title:"", id: ""}, rightTreeInput: {title:"", id: ""} }; this.handleSelectedNodeRightTree = this.handleSelectedNodeRightTree.bind(this); this.handleSelectedNodeLeftTree = this.handleSelectedNodeLeftTree.bind(this); this.handleStartMatching = this.handleStartMatching.bind(this); this.handleFilterListChanged = this.handleFilterListChanged.bind(this); } /** * Event handler. * Sets {@link leftTreeInput} to selected item in left TreeView component in {@link LeftTreeView}. * Only does that for elements with no children. * * @param args information about selected node in left TreeView (including id and title of node) */ handleSelectedNodeLeftTree(args){ if(args.selectedNodes.length > 0 && args.selectedNodes[0].children.length === 0) { let selectedNode = args.selectedNodes[0]; this.setState({leftTreeInput: {title: selectedNode.title, id: selectedNode.key}}); } else { this.setState({leftTreeInput: {title: "", id: ""}}); } } /** * Event handler. * Sets {@link rightTreeInput} to selected item in right TreeView component in {@link RightTreeView}. * Only does that for elements with type "equipment". * * @param args information about selected node in right TreeView (like id and title of node) */ handleSelectedNodeRightTree(args){ if(args.selectedNodes.length !== 0) { let selectedNode = args.selectedNodes[0]; let type = undefined, title; const objectType = "equipment"; const typeSeparator = ":"; if (selectedNode.title.includes(typeSeparator)) { let splitTitle = selectedNode.title.replace(" ", "").split(typeSeparator); type = splitTitle[0]; title = splitTitle[1].replace(typeSeparator, ""); } if (type === objectType) { this.setState({rightTreeInput: {title: title, id: selectedNode.key}}); return; } } this.setState({rightTreeInput: {title: "", id: ""}}); } /** * Event handler. * Calls {@link LeftTreeView.updateTreeViewContent} * * @param filterList containing the current filter from {@link FilterComponent} */ handleFilterListChanged(filterList){ this.leftTreeView.updateTreeViewContent(filterList).then(); } /** * Event handler. * Links to {@link MatchingView} with current selection {@link leftTreeInput} and {@link rightTreeInput}. */ handleStartMatching(){ const matchingViewLink = '/MatchingView/' + this.state.leftTreeInput.id + '/' + this.state.rightTreeInput.id; this.props.history.push(matchingViewLink); } /** * While {@link leftTreeInput} and {@link rightTreeInput} are empty, button to next page is disabled. * Contains {@link FilterComponent}. * Contains {@link LeftTreeView}. * Contains Input for left TreeView, Input for right TreeView and Button to start matching. * Contains {@link RightTreeView}. */ render() { const root = { flexGrow: 1, padding: 10, fontSize: "16px", } let leftOrRightTreeInputEmpty = this.state.leftTreeInput.title === "" || this.state.rightTreeInput.title === ""; return( <div style={root}> <FilterComponent filterListChange={this.handleFilterListChanged}/> <br/> <Grid container spacing={1} alignItems={"center"}> <Grid item xs={4}> <LeftTreeView ref={ref => this.leftTreeView = ref} onSelection={this.handleSelectedNodeLeftTree}/> </Grid> <Grid item xs={"auto"}> <input placeholder={"Pick object..."} readOnly={true} value={this.state.leftTreeInput.title}/> </Grid> <Grid item xs={"auto"}> <button disabled={leftOrRightTreeInputEmpty} onClick={this.handleStartMatching}>Perform matching</button> </Grid> <Grid item xs={2}> <input placeholder={"Pick object..."} readOnly={true} value={this.state.rightTreeInput.title}/> </Grid> <Grid item> <RightTreeView onSelection={this.handleSelectedNodeRightTree}/> </Grid> </Grid> <ScriptTag type="text/javascript" src="/Credits.js"/> </div> ); } }
JavaScript
class DeleteMany extends CollectionOperation { constructor(options) { super({ method: 'DELETE', statusCode: NO_CONTENT, ...options, }); } }
JavaScript
class SocketIoService { get isInitialized() { return (this.io != null); } attachServer(server) { this.io = socketIo(server, { transports: ['websocket'], }); // create namespace for admin this.adminNamespace = this.io.of('/admin'); } getDefaultSocket() { if (this.io == null) { throw new Error('Http server has not attached yet.'); } return this.io.sockets; } getAdminSocket() { if (this.io == null) { throw new Error('Http server has not attached yet.'); } return this.adminNamespace; } }
JavaScript
class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }
JavaScript
class SvelteComponentDev extends SvelteComponent { constructor(options) { if (!options || (!options.target && !options.$$inline)) { throw new Error("'target' is a required option"); } super(); } $destroy() { super.$destroy(); this.$destroy = () => { console.warn('Component was already destroyed'); // eslint-disable-line no-console }; } $capture_state() { } $inject_state() { } }
JavaScript
class SvelteComponent$1 { $destroy() { destroy_component$1(this, 1); this.$destroy = noop$1; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty$1($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }
JavaScript
class SvelteComponentDev$1 extends SvelteComponent$1 { constructor(options) { if (!options || (!options.target && !options.$$inline)) { throw new Error("'target' is a required option"); } super(); } $destroy() { super.$destroy(); this.$destroy = () => { console.warn('Component was already destroyed'); // eslint-disable-line no-console }; } $capture_state() { } $inject_state() { } }
JavaScript
class Controller extends EventBus { /** * `aroundActions` are functions or methods that are run around a controller * action. * * `aroundActions` are inherited. If you set a around action on * ApplicationController it will be run on every controller that inherits * from ApplicationController. * * If a string is given the function on the controller will be called. If * a function is given that function will be called. Both methods and * functions will revieve a callback to execute to continue processing the * action. * * <caption>An around filter requiring a user to be logged in</caption> * ```javascript * class ApplicationController extends VikingController { * static aroundActions = ['requireAccount']; * * requireAccount(callback) { * let session = await Session.current(); * * if (session) { * callback(); * } else { * this.redirectTo('/login'); * } * } * } * ``` * * If you want an aroundAction to only be called on certain actions you can * pass the `only` options: * * ```javascript * class ApplicationController extends VikingController { * static aroundActions = [ * ['requireAccount', {only: ['protectedAction']}] * ]; * } * ``` * * You may also pass the except option for every action except a certain * action: * * ```javascript * class ApplicationController extends VikingController { * static aroundActions = [ * ['requireAccount', {except: ['publicPage']}] * ]; * } * ``` * * @type {AroundActionCallback[]} */ static aroundActions = []; /** * `skipAroundActions` allows extended controllers to skip defined * `aroundActions` that were defined in the ApplicationController: * * ```javascript * class LoginController extends ApplicationController { * static skipAroundActions = [['requireAccount', {only: ['new']}]]; * // ... * } * ``` * * ```javascript * class LoginController extends ApplicationController { * static skipAroundActions = [['requireAccount', {except: ['show']}]]; * // ... * } * ``` * * ```javascript * class PublicController extends ApplicationController { * static skipAroundActions = ['requireAccount']; * // ... * } * ``` * @type {AroundActionCallback[]} */ static skipAroundActions = []; /** * The name of the action currently being processed, otherwise null; * @type {string|null} */ action_name = null; /** * All request parameters, weather they come from the query string in the URL * or extracted from URL path via the {@link Router}. * @type {Object} */ params = {}; /** @ignore */ static getAroundActions() { if (this.hasOwnProperty('_aroundActions')) { return this._aroundActions; } if (!this.hasOwnProperty('aroundActions')) { if (Object.getPrototypeOf(this).getAroundActions) { /** @ignore */ this._aroundActions = Object.getPrototypeOf(this).getAroundActions(); } else { this._aroundActions = []; } return this._aroundActions; } this._aroundActions = []; if (Object.getPrototypeOf(this).getAroundActions) { each(Object.getPrototypeOf(this).getAroundActions(), (v) => { this._aroundActions.push(v); }); } each(this.aroundActions, (v) => { if (Array.isArray(v)) { this._aroundActions = this._aroundActions.filter( (nv) => { return (nv[0] !== v[0]); }); this._aroundActions.push(v); } else { this._aroundActions = this._aroundActions.filter( (nv) => { return (nv[0] !== v); }); this._aroundActions.push([v, {}]); } }); return this._aroundActions; } /** @ignore */ static getSkipAroundActions() { if (this.hasOwnProperty('_skipAroundActions')) { return this._skipAroundActions; } if (!this.hasOwnProperty('skipAroundActions')) { if (Object.getPrototypeOf(this).getSkipAroundActions) { /** @ignore */ this._skipAroundActions = Object.getPrototypeOf(this).getSkipAroundActions(); } else { this._skipAroundActions = []; } return this._skipAroundActions; } this._skipAroundActions = []; if (Object.getPrototypeOf(this).getSkipAroundActions) { each(Object.getPrototypeOf(this).getSkipAroundActions(), (v) => { this._skipAroundActions.push(v); }); } each(this.skipAroundActions, (v) => { if (Array.isArray(v)) { this._skipAroundActions = this._skipAroundActions.filter( (nv) => { return (nv[0] !== v[0]); }); this._skipAroundActions.push(v); } else { this._skipAroundActions = this._skipAroundActions.filter( (nv) => { return (nv[0] !== v); }); this._skipAroundActions.push([v, {}]); } }); return this._skipAroundActions; } /** * @param {Application} application - An instance of an Application. * `application` delegated */ constructor(application) { super(); /** @type {Application} */ this.application = application; } dispatch(name) { // console.log('Processing ' + this.constructor.name + '#' + name); this.params = arguments[arguments.length - 1] this.action_name = name; this.constructor.getAroundActions().reverse().reduce((a, v) => { return () => { if ( (!v[1].only || v[1].only === name || v[1].only.includes(name)) && (!v[1].except || !(v[1].except === name || v[1].except.includes(name))) ) { let skip = this.constructor.getSkipAroundActions().find((s) => { return s[0] == v[0] && (!s[1].only || s[1].only.includes(name)) && (!s[1].except || !s[1].except.includes(name)) }); if (skip) { a(); } else { if(typeof v[0] === 'function') { v[0].call(this, a, ...arguments); } else { this[v[0]](a, ...arguments); } } } else { a(); } }; }, () => { this.process(...arguments); this.action_name = null; })(); } /** @ignore */ process(action, ...args) { /** @ignore */ this._responded = false; try { if (!this[action]) { throw new ActionNotFound(`The action '${action}' could not be found for ${this.constructor.name}`) } else { this[action](...args) } } catch (e) { if (e instanceof ActionNotFound) { console.log(e.message); } else { throw e; } } } /** * A helper function to tell the Application to navigate to the given URL * or Path. * * @param {string} path - The URL or path to navigate to. * @throws {DoubleRenderError} - A DoubleRenderError will be thrown if * {@link display} or {@link redirectTo} are * called multiple times in an action. */ redirectTo(path) { if (this._responded) { throw new Errors.DoubleRenderError(); } this._responded = true; this.application.navigateTo(path); } /** * A helper function to tell the Application to display the given view as * the main view. The arguments are dependent on the application but * typically something like: * * - `this.display(UserView, {user: user})` * - `this.display(myview)` * * @param {View} view - An instance of a Viking View to display or a Viking * Viking View to instantiate and display. * @param {*} args - When instantiating a View these args will be passed to * the constructor. * @return {View} - The view that was passed or the instantiated View * @throws {DoubleRenderError} - A DoubleRenderError will be thrown if * {@link display} or {@link redirectTo} are * called multiple times in an action. */ display(view, ...args) { if (this._responded) { throw new Errors.DoubleRenderError(); } this._responded = true; return this.application.display(view, ...args); } }
JavaScript
class ModalComponent extends React.Component { render() { return ( <div className="modal" style={{display: 'none'}}> <div className="modal-overlay" /> <div className="modal-content"> <a href="javascript:;" className="modal-close">╋</a> <h1>Liked what you see?</h1> <p>Soon we are launching more correlation inspired projects. Subscribe and be the first to know when we launch tools for designers, developers and entrepreneurs.</p> <input type="email" placeholder="Your e-mail" /> <a href="javascript:;" className="submit">Subscribe</a> <div className="result">Only new products, no spam.</div> </div> </div> ); } }
JavaScript
class TypeWriter { constructor(txtElement, words, wait) { this.txtElement = txtElement this.words = words this.txt = '' this.wordIndex = 0 this.wait = parseInt(wait, 10) this.isDeleting = false this.type() } type() { const current = this.wordIndex % this.words.length const fullText = this.words[current] let typeSpeed = 150 if (this.isDeleting) { this.txt = fullText.substring(0, this.txt.length - 1) typeSpeed /= 2 } else { this.txt = fullText.substring(0, this.txt.length + 1) } this.txtElement.innerHTML = `<span class="txt">${this.txt}</span>` this.txtElement.style.display = 'inline' if (!this.isDeleting && this.txt === fullText) { this.isDeleting = true typeSpeed = this.wait } else if (this.isDeleting && this.txt === '') { this.isDeleting = false this.wordIndex++ typeSpeed = 500 this.txtElement.style.display = 'none' } // Cyclic function call setTimeout(() => this.type(), typeSpeed) } static start() { const words = JSON.parse(txtElement.getAttribute('data-words')) const wait = txtElement.getAttribute('data-wait') new TypeWriter(txtElement, words, wait) } }
JavaScript
class CatanContext { constructor (player, subspace, location, global, preferred_ids = []) { this.player = player; this.subspace = subspace; this.location = location; this.global = global; this.preferred_ids = preferred_ids; } // We prioritize the environment over the player inventory here. getLocal (name_or_id, is_lenient = true) { var env_search = ci.getItemInInventory(this.subspace.inventory, name_or_id, is_lenient); if (env_search != null) return env_search; return getInPlayer(name_or_id, is_lenient); } getNotInPlayer (name_or_id, is_lenient = true) { if (this.subspace == null) return null; return ci.getItemInInventory(this.subspace.inventory, name_or_id, is_lenient); } getInPlayer (name_or_id, is_lenient = true) { return ci.getItemInInventory(this.player.inventory, name_or_id, is_lenient); } }
JavaScript
class SasAuthentication extends models['Authentication'] { /** * Create a SasAuthentication. * @member {string} sasUri The SAS URI to the Azure Storage blob container. * Any offset from the root of the container to where the artifacts are * located can be defined in the artifactRoot. */ constructor() { super(); } /** * Defines the metadata of SasAuthentication * * @returns {object} metadata of SasAuthentication * */ mapper() { return { required: false, serializedName: 'Sas', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'type', clientName: 'type' }, uberParent: 'Authentication', className: 'SasAuthentication', modelProperties: { type: { required: true, serializedName: 'type', isPolymorphicDiscriminator: true, type: { name: 'String' } }, sasUri: { required: true, serializedName: 'properties.sasUri', type: { name: 'String' } } } } }; } }
JavaScript
class Map { /***************************************************************************\ Local Properties \***************************************************************************/ anchorPoint = { x: 0, y: 0, } bodies = undefined isReady = false mapData = undefined offscreenCanvas = document.createElement('canvas') stackableCanvases = [] options = undefined points = [] scale = 1 size = { x: 0, y: 0, } tiles = {} /***************************************************************************\ Private Methods \***************************************************************************/ _mapTiles = async () => { const promises = [] this.mapData.tilesets.forEach(tilesetDatum => { const imageURL = `${this.options.mapPath}/${tilesetDatum.image}` const image = document.createElement('img') promises.push(new Promise(resolve => { image.onload = resolve })) image.src = imageURL tilesetDatum.image = image }) await Promise.all(promises) this.mapData.tilesets.forEach(tilesetDatum => { const { firstgid } = tilesetDatum // const lengthAfterProcessingLastTileset = Object.values(this.tiles).length let loopIndex = 0 const finder = ({ id }) => id === loopIndex while (loopIndex <= tilesetDatum.tilecount) { const tileIndex = (loopIndex - 1) + firstgid const tile = tilesetDatum.tiles.find(finder) this.tiles[tileIndex] = { ...(tile || {}), height: tilesetDatum.tileheight, image: tilesetDatum.image, width: tilesetDatum.tilewidth, x: (tilesetDatum.tilewidth * (loopIndex % tilesetDatum.columns)), y: Math.floor(loopIndex / tilesetDatum.columns) * tilesetDatum.tileheight, } loopIndex += 1 } }) } _renderTile = (context, tileID, destination) => { const tile = this.tiles[tileID] if (tile) { if (tile.objectgroup) { const foo = [] tile.objectgroup.objects.forEach(object => { const objectX = destination.x + object.x const objectY = destination.y + object.y const body = Bodies.rectangle(objectX, objectY, object.width, object.height, { label: object.name, isStatic: true, restitution: 0, }) Composite.add(this.bodies, body) foo.push({ x: objectX, y: objectY, width: object.width, height: object.height, }) }) } context.drawImage(tile.image, tile.x, tile.y, tile.width, tile.height, destination.x, destination.y, tile.width, tile.height) // context.font = '14px Cormorant, serif' // context.fillStyle = 'white' // context.textAlign = 'center' // context.strokeStyle = 'blue' // context.lineWidth = 1 // context.fillText( // tileID, // destination.x + (tile.width / 2), // destination.y + (tile.height / 2), // ) // context.strokeText( // tileID, // destination.x + (tile.width / 2), // destination.y + (tile.height / 2), // ) } } /***************************************************************************\ Public Methods \***************************************************************************/ constructor (options) { window.maps = window.maps || [] window.maps.push(this) this.options = options } initialize = async () => { const context = this.offscreenCanvas.getContext('2d', { alpha: false }) this.mapData = await fetch(`${this.options.mapPath}/${this.options.mapName}.json`).then(response => response.json()) await this._mapTiles() const { backgroundcolor, layers, tileheight, tilewidth, } = this.mapData const tileLayers = layers.filter(({ type }) => type === 'tilelayer') tileLayers.forEach(layer => { this.size = { x: Math.max(this.size.x, layer.width), y: Math.max(this.size.y, layer.height), } this.anchorPoint = { x: Math.min(this.anchorPoint.x, layer.startx), y: Math.min(this.anchorPoint.y, layer.starty), } }) this.size = { x: this.size.x * tilewidth, y: this.size.y * tileheight, } this.anchorPoint = { x: ~(this.anchorPoint.x * tilewidth) + 1, y: ~(this.anchorPoint.y * tileheight) + 1, } this.offscreenCanvas.setAttribute('height', this.size.y) this.offscreenCanvas.setAttribute('width', this.size.x) if (backgroundcolor) { context.fillStyle = backgroundcolor context.fillRect(0, 0, this.size.x, this.size.y) } this.bodies = Composite.create({ label: `map::${this.options.mapName}` }) layers.forEach(layer => { switch (layer.type) { case 'objectgroup': layer.objects.forEach(object => { object.x += this.anchorPoint.x object.y += this.anchorPoint.y if (object.point) { this.points.push(object) } else { Composite.add(this.bodies, Bodies.rectangle(object.x, object.y, object.width, object.height, { label: object.name, isStatic: true, restitution: 0, })) } }) break case 'tilelayer': default: if (layer.chunks) { layer.chunks.forEach(chunk => { const chunkOffsetX = this.anchorPoint.x - (~(chunk.x * tilewidth) + 1) const chunkOffsetY = this.anchorPoint.y - (~(chunk.y * tileheight) + 1) Object.entries(chunk.data).forEach(([index, tileID]) => { this._renderTile(context, tileID - 1, { x: (tilewidth * (index % chunk.width)) + chunkOffsetX, y: (Math.floor(index / chunk.width) * tileheight) + chunkOffsetY, }) }) }) } else { Object.entries(layer.data).forEach(([index, tileID]) => { this._renderTile(context, tileID - 1, { x: (tilewidth * (index % layer.width)) + layer.x, y: (Math.floor(index / layer.width) * tileheight) + layer.y, }) }) } break } }) this.isReady = true } }
JavaScript
class MyLogin extends PolymerElement { static get template() { return html` <style> :host { display: block; } </style> <h2>This is [[prop1]] web component</h2> <form name="loginForm" method="POST"> <fieldset> <legend></legend> <span></span> <div> <label for="user">Usuario</label> <input type="text" name="user"></input> </div> <div> <label for="password">Contraseña</label> <input type="text" name="password"></input> </div> <a></a> </fieldset> <input type="submit" value="Entrar"></input> <a target='_blank' href="javascript:void(0)">¿Todavía no eres usuario? Regístrate</a> </form> `; } static get properties() { return { prop1: { type: String, value: 'my-login', }, }; } }
JavaScript
class SkillsFactory { constructor() { // make a hash table from skill id to data. var skillMap = {}; skillsConfig.skills.forEach((skillSpec) => { skillMap[skillSpec.Id] = skillSpec; }) this.skillMap = skillMap; } /** * Returns the skills for a champion * @param {*} champ - the champion * @returns skills. An array, one per skill. Each entry in the array * is a dictionary with {id, name, level, maxLevel} * if (maxLevel) is < 0, then it's unknown. */ SkillsFor(champ) { var skills = []; if (!champ || !champ.skills) return skills; champ.skills.forEach((skillBundle) => { var id = skillBundle.typeId; var level = skillBundle.level; var name = "Skill #" + level; var maxLevel = -1; if (id in this.skillMap) { name = this.skillMap[id].Name; maxLevel = this.skillMap[id].Levels + 1; } skills.push({ id: id, name: name, level: level, maxLevel: maxLevel }); }) return skills; } }
JavaScript
class CSSResult { constructor(cssText, safeToken) { // This property needs to remain unminified. this['_$cssResult$'] = true; if (safeToken !== constructionToken) { throw new Error('CSSResult is not constructable. Use `unsafeCSS` or `css` instead.'); } this.cssText = cssText; } // Note, this is a getter so that it's lazy. In practice, this means // stylesheets are not created until the first element instance is made. get styleSheet() { // Note, if `supportsAdoptingStyleSheets` is true then we assume // CSSStyleSheet is constructable. let styleSheet = styleSheetCache.get(this.cssText); if (supportsAdoptingStyleSheets && styleSheet === undefined) { styleSheetCache.set(this.cssText, (styleSheet = new CSSStyleSheet())); styleSheet.replaceSync(this.cssText); } return styleSheet; } toString() { return this.cssText; } }
JavaScript
class ReactiveElement extends HTMLElement { constructor() { super(); this.__instanceProperties = new Map(); /** * True if there is a pending update as a result of calling `requestUpdate()`. * Should only be read. * @category updates */ this.isUpdatePending = false; /** * Is set to `true` after the first update. The element code cannot assume * that `renderRoot` exists before the element `hasUpdated`. * @category updates */ this.hasUpdated = false; /** * Name of currently reflecting property */ this.__reflectingProperty = null; this._initialize(); } /** * Adds an initializer function to the class that is called during instance * construction. * * This is useful for code that runs against a `ReactiveElement` * subclass, such as a decorator, that needs to do work for each * instance, such as setting up a `ReactiveController`. * * ```ts * const myDecorator = (target: typeof ReactiveElement, key: string) => { * target.addInitializer((instance: ReactiveElement) => { * // This is run during construction of the element * new MyController(instance); * }); * } * ``` * * Decorating a field will then cause each instance to run an initializer * that adds a controller: * * ```ts * class MyElement extends LitElement { * @myDecorator foo; * } * ``` * * Initializers are stored per-constructor. Adding an initializer to a * subclass does not add it to a superclass. Since initializers are run in * constructors, initializers will run in order of the class hierarchy, * starting with superclasses and progressing to the instance's class. * * @nocollapse */ static addInitializer(initializer) { var _a; (_a = this._initializers) !== null && _a !== void 0 ? _a : (this._initializers = []); this._initializers.push(initializer); } /** * Returns a list of attributes corresponding to the registered properties. * @nocollapse * @category attributes */ static get observedAttributes() { // note: piggy backing on this to ensure we're finalized. this.finalize(); const attributes = []; // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays this.elementProperties.forEach((v, p) => { const attr = this.__attributeNameForProperty(p, v); if (attr !== undefined) { this.__attributeToPropertyMap.set(attr, p); attributes.push(attr); } }); return attributes; } /** * Creates a property accessor on the element prototype if one does not exist * and stores a {@linkcode PropertyDeclaration} for the property with the * given options. The property setter calls the property's `hasChanged` * property option or uses a strict identity check to determine whether or not * to request an update. * * This method may be overridden to customize properties; however, * when doing so, it's important to call `super.createProperty` to ensure * the property is setup correctly. This method calls * `getPropertyDescriptor` internally to get a descriptor to install. * To customize what properties do when they are get or set, override * `getPropertyDescriptor`. To customize the options for a property, * implement `createProperty` like this: * * ```ts * static createProperty(name, options) { * options = Object.assign(options, {myOption: true}); * super.createProperty(name, options); * } * ``` * * @nocollapse * @category properties */ static createProperty(name, options = defaultPropertyDeclaration) { var _a; // if this is a state property, force the attribute to false. if (options.state) { // Cast as any since this is readonly. // eslint-disable-next-line @typescript-eslint/no-explicit-any options.attribute = false; } // Note, since this can be called by the `@property` decorator which // is called before `finalize`, we ensure finalization has been kicked off. this.finalize(); this.elementProperties.set(name, options); // Do not generate an accessor if the prototype already has one, since // it would be lost otherwise and that would never be the user's intention; // Instead, we expect users to call `requestUpdate` themselves from // user-defined accessors. Note that if the super has an accessor we will // still overwrite it if (!options.noAccessor && !this.prototype.hasOwnProperty(name)) { const key = typeof name === 'symbol' ? Symbol() : `__${name}`; const descriptor = this.getPropertyDescriptor(name, key, options); if (descriptor !== undefined) { Object.defineProperty(this.prototype, name, descriptor); if (DEV_MODE) { // If this class doesn't have its own set, create one and initialize // with the values in the set from the nearest ancestor class, if any. if (!this.hasOwnProperty('__reactivePropertyKeys')) { this.__reactivePropertyKeys = new Set((_a = this.__reactivePropertyKeys) !== null && _a !== void 0 ? _a : []); } this.__reactivePropertyKeys.add(name); } } } } /** * Returns a property descriptor to be defined on the given named property. * If no descriptor is returned, the property will not become an accessor. * For example, * * ```ts * class MyElement extends LitElement { * static getPropertyDescriptor(name, key, options) { * const defaultDescriptor = * super.getPropertyDescriptor(name, key, options); * const setter = defaultDescriptor.set; * return { * get: defaultDescriptor.get, * set(value) { * setter.call(this, value); * // custom action. * }, * configurable: true, * enumerable: true * } * } * } * ``` * * @nocollapse * @category properties */ static getPropertyDescriptor(name, key, options) { return { // eslint-disable-next-line @typescript-eslint/no-explicit-any get() { return this[key]; }, set(value) { const oldValue = this[name]; this[key] = value; this.requestUpdate(name, oldValue, options); }, configurable: true, enumerable: true, }; } /** * Returns the property options associated with the given property. * These options are defined with a `PropertyDeclaration` via the `properties` * object or the `@property` decorator and are registered in * `createProperty(...)`. * * Note, this method should be considered "final" and not overridden. To * customize the options for a given property, override * {@linkcode createProperty}. * * @nocollapse * @final * @category properties */ static getPropertyOptions(name) { return this.elementProperties.get(name) || defaultPropertyDeclaration; } /** * Creates property accessors for registered properties, sets up element * styling, and ensures any superclasses are also finalized. Returns true if * the element was finalized. * @nocollapse */ static finalize() { if (this.hasOwnProperty(finalized)) { return false; } this[finalized] = true; // finalize any superclasses const superCtor = Object.getPrototypeOf(this); superCtor.finalize(); this.elementProperties = new Map(superCtor.elementProperties); // initialize Map populated in observedAttributes this.__attributeToPropertyMap = new Map(); // make any properties // Note, only process "own" properties since this element will inherit // any properties defined on the superClass, and finalization ensures // the entire prototype chain is finalized. if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) { const props = this.properties; // support symbols in properties (IE11 does not support this) const propKeys = [ ...Object.getOwnPropertyNames(props), ...Object.getOwnPropertySymbols(props), ]; // This for/of is ok because propKeys is an array for (const p of propKeys) { // note, use of `any` is due to TypeScript lack of support for symbol in // index types // eslint-disable-next-line @typescript-eslint/no-explicit-any this.createProperty(p, props[p]); } } this.elementStyles = this.finalizeStyles(this.styles); // DEV mode warnings if (DEV_MODE) { const warnRemovedOrRenamed = (name, renamed = false) => { if (this.prototype.hasOwnProperty(name)) { issueWarning(renamed ? 'renamed-api' : 'removed-api', `\`${name}\` is implemented on class ${this.name}. It ` + `has been ${renamed ? 'renamed' : 'removed'} ` + `in this version of LitElement.`); } }; warnRemovedOrRenamed('initialize'); warnRemovedOrRenamed('requestUpdateInternal'); warnRemovedOrRenamed('_getUpdateComplete', true); } return true; } /** * Takes the styles the user supplied via the `static styles` property and * returns the array of styles to apply to the element. * Override this method to integrate into a style management system. * * Styles are deduplicated preserving the _last_ instance in the list. This * is a performance optimization to avoid duplicated styles that can occur * especially when composing via subclassing. The last item is kept to try * to preserve the cascade order with the assumption that it's most important * that last added styles override previous styles. * * @nocollapse * @category styles */ static finalizeStyles(styles) { const elementStyles = []; if (Array.isArray(styles)) { // Dedupe the flattened array in reverse order to preserve the last items. // Casting to Array<unknown> works around TS error that // appears to come from trying to flatten a type CSSResultArray. const set = new Set(styles.flat(Infinity).reverse()); // Then preserve original order by adding the set items in reverse order. for (const s of set) { elementStyles.unshift((0,_css_tag_js__WEBPACK_IMPORTED_MODULE_0__.getCompatibleStyle)(s)); } } else if (styles !== undefined) { elementStyles.push((0,_css_tag_js__WEBPACK_IMPORTED_MODULE_0__.getCompatibleStyle)(styles)); } return elementStyles; } /** * Returns the property name for the given attribute `name`. * @nocollapse */ static __attributeNameForProperty(name, options) { const attribute = options.attribute; return attribute === false ? undefined : typeof attribute === 'string' ? attribute : typeof name === 'string' ? name.toLowerCase() : undefined; } /** * Internal only override point for customizing work done when elements * are constructed. * * @internal */ _initialize() { var _a; this.__updatePromise = new Promise((res) => (this.enableUpdating = res)); this._$changedProperties = new Map(); this.__saveInstanceProperties(); // ensures first update will be caught by an early access of // `updateComplete` this.requestUpdate(); (_a = this.constructor._initializers) === null || _a === void 0 ? void 0 : _a.forEach((i) => i(this)); } /** * Registers a `ReactiveController` to participate in the element's reactive * update cycle. The element automatically calls into any registered * controllers during its lifecycle callbacks. * * If the element is connected when `addController()` is called, the * controller's `hostConnected()` callback will be immediately called. * @category controllers */ addController(controller) { var _a, _b; ((_a = this.__controllers) !== null && _a !== void 0 ? _a : (this.__controllers = [])).push(controller); // If a controller is added after the element has been connected, // call hostConnected. Note, re-using existence of `renderRoot` here // (which is set in connectedCallback) to avoid the need to track a // first connected state. if (this.renderRoot !== undefined && this.isConnected) { (_b = controller.hostConnected) === null || _b === void 0 ? void 0 : _b.call(controller); } } /** * Removes a `ReactiveController` from the element. * @category controllers */ removeController(controller) { var _a; // Note, if the indexOf is -1, the >>> will flip the sign which makes the // splice do nothing. (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.splice(this.__controllers.indexOf(controller) >>> 0, 1); } /** * Fixes any properties set on the instance before upgrade time. * Otherwise these would shadow the accessor and break these properties. * The properties are stored in a Map which is played back after the * constructor runs. Note, on very old versions of Safari (<=9) or Chrome * (<=41), properties created for native platform properties like (`id` or * `name`) may not have default values set in the element constructor. On * these browsers native properties appear on instances and therefore their * default value will overwrite any element default (e.g. if the element sets * this.id = 'id' in the constructor, the 'id' will become '' since this is * the native platform default). */ __saveInstanceProperties() { // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays this.constructor.elementProperties.forEach((_v, p) => { if (this.hasOwnProperty(p)) { this.__instanceProperties.set(p, this[p]); delete this[p]; } }); } /** * Returns the node into which the element should render and by default * creates and returns an open shadowRoot. Implement to customize where the * element's DOM is rendered. For example, to render into the element's * childNodes, return `this`. * * @return Returns a node into which to render. * @category rendering */ createRenderRoot() { var _a; const renderRoot = (_a = this.shadowRoot) !== null && _a !== void 0 ? _a : this.attachShadow(this.constructor.shadowRootOptions); (0,_css_tag_js__WEBPACK_IMPORTED_MODULE_0__.adoptStyles)(renderRoot, this.constructor.elementStyles); return renderRoot; } /** * On first connection, creates the element's renderRoot, sets up * element styling, and enables updating. * @category lifecycle */ connectedCallback() { var _a; // create renderRoot before first update. if (this.renderRoot === undefined) { this.renderRoot = this.createRenderRoot(); } this.enableUpdating(true); (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.forEach((c) => { var _a; return (_a = c.hostConnected) === null || _a === void 0 ? void 0 : _a.call(c); }); } /** * Note, this method should be considered final and not overridden. It is * overridden on the element instance with a function that triggers the first * update. * @category updates */ enableUpdating(_requestedUpdate) { } /** * Allows for `super.disconnectedCallback()` in extensions while * reserving the possibility of making non-breaking feature additions * when disconnecting at some point in the future. * @category lifecycle */ disconnectedCallback() { var _a; (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.forEach((c) => { var _a; return (_a = c.hostDisconnected) === null || _a === void 0 ? void 0 : _a.call(c); }); } /** * Synchronizes property values when attributes change. * * Specifically, when an attribute is set, the corresponding property is set. * You should rarely need to implement this callback. If this method is * overridden, `super.attributeChangedCallback(name, _old, value)` must be * called. * * See [using the lifecycle callbacks](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks) * on MDN for more information about the `attributeChangedCallback`. * @category attributes */ attributeChangedCallback(name, _old, value) { this._$attributeToProperty(name, value); } __propertyToAttribute(name, value, options = defaultPropertyDeclaration) { var _a, _b; const attr = this.constructor.__attributeNameForProperty(name, options); if (attr !== undefined && options.reflect === true) { const toAttribute = (_b = (_a = options.converter) === null || _a === void 0 ? void 0 : _a.toAttribute) !== null && _b !== void 0 ? _b : defaultConverter.toAttribute; const attrValue = toAttribute(value, options.type); if (DEV_MODE && this.constructor.enabledWarnings.indexOf('migration') >= 0 && attrValue === undefined) { issueWarning('undefined-attribute-value', `The attribute value for the ${name} property is ` + `undefined on element ${this.localName}. The attribute will be ` + `removed, but in the previous version of \`ReactiveElement\`, ` + `the attribute would not have changed.`); } // Track if the property is being reflected to avoid // setting the property again via `attributeChangedCallback`. Note: // 1. this takes advantage of the fact that the callback is synchronous. // 2. will behave incorrectly if multiple attributes are in the reaction // stack at time of calling. However, since we process attributes // in `update` this should not be possible (or an extreme corner case // that we'd like to discover). // mark state reflecting this.__reflectingProperty = name; if (attrValue == null) { this.removeAttribute(attr); } else { this.setAttribute(attr, attrValue); } // mark state not reflecting this.__reflectingProperty = null; } } /** @internal */ _$attributeToProperty(name, value) { var _a, _b, _c; const ctor = this.constructor; // Note, hint this as an `AttributeMap` so closure clearly understands // the type; it has issues with tracking types through statics const propName = ctor.__attributeToPropertyMap.get(name); // Use tracking info to avoid reflecting a property value to an attribute // if it was just set because the attribute changed. if (propName !== undefined && this.__reflectingProperty !== propName) { const options = ctor.getPropertyOptions(propName); const converter = options.converter; const fromAttribute = (_c = (_b = (_a = converter) === null || _a === void 0 ? void 0 : _a.fromAttribute) !== null && _b !== void 0 ? _b : (typeof converter === 'function' ? converter : null)) !== null && _c !== void 0 ? _c : defaultConverter.fromAttribute; // mark state reflecting this.__reflectingProperty = propName; // eslint-disable-next-line @typescript-eslint/no-explicit-any this[propName] = fromAttribute(value, options.type); // mark state not reflecting this.__reflectingProperty = null; } } /** * Requests an update which is processed asynchronously. This should be called * when an element should update based on some state not triggered by setting * a reactive property. In this case, pass no arguments. It should also be * called when manually implementing a property setter. In this case, pass the * property `name` and `oldValue` to ensure that any configured property * options are honored. * * @param name name of requesting property * @param oldValue old value of requesting property * @param options property options to use instead of the previously * configured options * @category updates */ requestUpdate(name, oldValue, options) { let shouldRequestUpdate = true; // If we have a property key, perform property update steps. if (name !== undefined) { options = options || this.constructor.getPropertyOptions(name); const hasChanged = options.hasChanged || notEqual; if (hasChanged(this[name], oldValue)) { if (!this._$changedProperties.has(name)) { this._$changedProperties.set(name, oldValue); } // Add to reflecting properties set. // Note, it's important that every change has a chance to add the // property to `_reflectingProperties`. This ensures setting // attribute + property reflects correctly. if (options.reflect === true && this.__reflectingProperty !== name) { if (this.__reflectingProperties === undefined) { this.__reflectingProperties = new Map(); } this.__reflectingProperties.set(name, options); } } else { // Abort the request if the property should not be considered changed. shouldRequestUpdate = false; } } if (!this.isUpdatePending && shouldRequestUpdate) { this.__updatePromise = this.__enqueueUpdate(); } // Note, since this no longer returns a promise, in dev mode we return a // thenable which warns if it's called. return DEV_MODE ? requestUpdateThenable(this.localName) : undefined; } /** * Sets up the element to asynchronously update. */ async __enqueueUpdate() { this.isUpdatePending = true; try { // Ensure any previous update has resolved before updating. // This `await` also ensures that property changes are batched. await this.__updatePromise; } catch (e) { // Refire any previous errors async so they do not disrupt the update // cycle. Errors are refired so developers have a chance to observe // them, and this can be done by implementing // `window.onunhandledrejection`. Promise.reject(e); } const result = this.scheduleUpdate(); // If `scheduleUpdate` returns a Promise, we await it. This is done to // enable coordinating updates with a scheduler. Note, the result is // checked to avoid delaying an additional microtask unless we need to. if (result != null) { await result; } return !this.isUpdatePending; } /** * Schedules an element update. You can override this method to change the * timing of updates by returning a Promise. The update will await the * returned Promise, and you should resolve the Promise to allow the update * to proceed. If this method is overridden, `super.scheduleUpdate()` * must be called. * * For instance, to schedule updates to occur just before the next frame: * * ```ts * override protected async scheduleUpdate(): Promise<unknown> { * await new Promise((resolve) => requestAnimationFrame(() => resolve())); * super.scheduleUpdate(); * } * ``` * @category updates */ scheduleUpdate() { return this.performUpdate(); } /** * Performs an element update. Note, if an exception is thrown during the * update, `firstUpdated` and `updated` will not be called. * * Call `performUpdate()` to immediately process a pending update. This should * generally not be needed, but it can be done in rare cases when you need to * update synchronously. * * Note: To ensure `performUpdate()` synchronously completes a pending update, * it should not be overridden. In LitElement 2.x it was suggested to override * `performUpdate()` to also customizing update scheduling. Instead, you should now * override `scheduleUpdate()`. For backwards compatibility with LitElement 2.x, * scheduling updates via `performUpdate()` continues to work, but will make * also calling `performUpdate()` to synchronously process updates difficult. * * @category updates */ performUpdate() { var _a, _b; // Abort any update if one is not pending when this is called. // This can happen if `performUpdate` is called early to "flush" // the update. if (!this.isUpdatePending) { return; } debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: 'update' }); // create renderRoot before first update. if (!this.hasUpdated) { // Produce warning if any class properties are shadowed by class fields if (DEV_MODE) { const shadowedProperties = []; (_a = this.constructor.__reactivePropertyKeys) === null || _a === void 0 ? void 0 : _a.forEach((p) => { var _a; if (this.hasOwnProperty(p) && !((_a = this.__instanceProperties) === null || _a === void 0 ? void 0 : _a.has(p))) { shadowedProperties.push(p); } }); if (shadowedProperties.length) { throw new Error(`The following properties on element ${this.localName} will not ` + `trigger updates as expected because they are set using class ` + `fields: ${shadowedProperties.join(', ')}. ` + `Native class fields and some compiled output will overwrite ` + `accessors used for detecting changes. See ` + `https://lit.dev/msg/class-field-shadowing ` + `for more information.`); } } } // Mixin instance properties once, if they exist. if (this.__instanceProperties) { // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays // eslint-disable-next-line @typescript-eslint/no-explicit-any this.__instanceProperties.forEach((v, p) => (this[p] = v)); this.__instanceProperties = undefined; } let shouldUpdate = false; const changedProperties = this._$changedProperties; try { shouldUpdate = this.shouldUpdate(changedProperties); if (shouldUpdate) { this.willUpdate(changedProperties); (_b = this.__controllers) === null || _b === void 0 ? void 0 : _b.forEach((c) => { var _a; return (_a = c.hostUpdate) === null || _a === void 0 ? void 0 : _a.call(c); }); this.update(changedProperties); } else { this.__markUpdated(); } } catch (e) { // Prevent `firstUpdated` and `updated` from running when there's an // update exception. shouldUpdate = false; // Ensure element can accept additional updates after an exception. this.__markUpdated(); throw e; } // The update is no longer considered pending and further updates are now allowed. if (shouldUpdate) { this._$didUpdate(changedProperties); } } /** * Invoked before `update()` to compute values needed during the update. * * Implement `willUpdate` to compute property values that depend on other * properties and are used in the rest of the update process. * * ```ts * willUpdate(changedProperties) { * // only need to check changed properties for an expensive computation. * if (changedProperties.has('firstName') || changedProperties.has('lastName')) { * this.sha = computeSHA(`${this.firstName} ${this.lastName}`); * } * } * * render() { * return html`SHA: ${this.sha}`; * } * ``` * * @category updates */ willUpdate(_changedProperties) { } // Note, this is an override point for polyfill-support. // @internal _$didUpdate(changedProperties) { var _a; (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.forEach((c) => { var _a; return (_a = c.hostUpdated) === null || _a === void 0 ? void 0 : _a.call(c); }); if (!this.hasUpdated) { this.hasUpdated = true; this.firstUpdated(changedProperties); } this.updated(changedProperties); if (DEV_MODE && this.isUpdatePending && this.constructor.enabledWarnings.indexOf('change-in-update') >= 0) { issueWarning('change-in-update', `Element ${this.localName} scheduled an update ` + `(generally because a property was set) ` + `after an update completed, causing a new update to be scheduled. ` + `This is inefficient and should be avoided unless the next update ` + `can only be scheduled as a side effect of the previous update.`); } } __markUpdated() { this._$changedProperties = new Map(); this.isUpdatePending = false; } /** * Returns a Promise that resolves when the element has completed updating. * The Promise value is a boolean that is `true` if the element completed the * update without triggering another update. The Promise result is `false` if * a property was set inside `updated()`. If the Promise is rejected, an * exception was thrown during the update. * * To await additional asynchronous work, override the `getUpdateComplete` * method. For example, it is sometimes useful to await a rendered element * before fulfilling this Promise. To do this, first await * `super.getUpdateComplete()`, then any subsequent state. * * @return A promise of a boolean that resolves to true if the update completed * without triggering another update. * @category updates */ get updateComplete() { return this.getUpdateComplete(); } /** * Override point for the `updateComplete` promise. * * It is not safe to override the `updateComplete` getter directly due to a * limitation in TypeScript which means it is not possible to call a * superclass getter (e.g. `super.updateComplete.then(...)`) when the target * language is ES5 (https://github.com/microsoft/TypeScript/issues/338). * This method should be overridden instead. For example: * * ```ts * class MyElement extends LitElement { * override async getUpdateComplete() { * const result = await super.getUpdateComplete(); * await this._myChild.updateComplete; * return result; * } * } * ``` * * @return A promise of a boolean that resolves to true if the update completed * without triggering another update. * @category updates */ getUpdateComplete() { return this.__updatePromise; } /** * Controls whether or not `update()` should be called when the element requests * an update. By default, this method always returns `true`, but this can be * customized to control when to update. * * @param _changedProperties Map of changed properties with old values * @category updates */ shouldUpdate(_changedProperties) { return true; } /** * Updates the element. This method reflects property values to attributes. * It can be overridden to render and keep updated element DOM. * Setting properties inside this method will *not* trigger * another update. * * @param _changedProperties Map of changed properties with old values * @category updates */ update(_changedProperties) { if (this.__reflectingProperties !== undefined) { // Use forEach so this works even if for/of loops are compiled to for // loops expecting arrays this.__reflectingProperties.forEach((v, k) => this.__propertyToAttribute(k, this[k], v)); this.__reflectingProperties = undefined; } this.__markUpdated(); } /** * Invoked whenever the element is updated. Implement to perform * post-updating tasks via DOM APIs, for example, focusing an element. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values * @category updates */ updated(_changedProperties) { } /** * Invoked when the element is first updated. Implement to perform one time * work on the element after update. * * ```ts * firstUpdated() { * this.renderRoot.getElementById('my-text-area').focus(); * } * ``` * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values * @category updates */ firstUpdated(_changedProperties) { } }
JavaScript
class LitElement extends _lit_reactive_element__WEBPACK_IMPORTED_MODULE_0__.ReactiveElement { constructor() { super(...arguments); /** * @category rendering */ this.renderOptions = { host: this }; this.__childPart = undefined; } /** * @category rendering */ createRenderRoot() { var _a; var _b; const renderRoot = super.createRenderRoot(); // When adoptedStyleSheets are shimmed, they are inserted into the // shadowRoot by createRenderRoot. Adjust the renderBefore node so that // any styles in Lit content render before adoptedStyleSheets. This is // important so that adoptedStyleSheets have precedence over styles in // the shadowRoot. (_a = (_b = this.renderOptions).renderBefore) !== null && _a !== void 0 ? _a : (_b.renderBefore = renderRoot.firstChild); return renderRoot; } /** * Updates the element. This method reflects property values to attributes * and calls `render` to render DOM via lit-html. Setting properties inside * this method will *not* trigger another update. * @param changedProperties Map of changed properties with old values * @category updates */ update(changedProperties) { // Setting properties in `render` should not trigger an update. Since // updates are allowed after super.update, it's important to call `render` // before that. const value = this.render(); if (!this.hasUpdated) { this.renderOptions.isConnected = this.isConnected; } super.update(changedProperties); this.__childPart = (0,lit_html__WEBPACK_IMPORTED_MODULE_1__.render)(value, this.renderRoot, this.renderOptions); } /** * Invoked when the component is added to the document's DOM. * * In `connectedCallback()` you should setup tasks that should only occur when * the element is connected to the document. The most common of these is * adding event listeners to nodes external to the element, like a keydown * event handler added to the window. * * ```ts * connectedCallback() { * super.connectedCallback(); * addEventListener('keydown', this._handleKeydown); * } * ``` * * Typically, anything done in `connectedCallback()` should be undone when the * element is disconnected, in `disconnectedCallback()`. * * @category lifecycle */ connectedCallback() { var _a; super.connectedCallback(); (_a = this.__childPart) === null || _a === void 0 ? void 0 : _a.setConnected(true); } /** * Invoked when the component is removed from the document's DOM. * * This callback is the main signal to the element that it may no longer be * used. `disconnectedCallback()` should ensure that nothing is holding a * reference to the element (such as event listeners added to nodes external * to the element), so that it is free to be garbage collected. * * ```ts * disconnectedCallback() { * super.disconnectedCallback(); * window.removeEventListener('keydown', this._handleKeydown); * } * ``` * * An element may be re-connected after being disconnected. * * @category lifecycle */ disconnectedCallback() { var _a; super.disconnectedCallback(); (_a = this.__childPart) === null || _a === void 0 ? void 0 : _a.setConnected(false); } /** * Invoked on each update to perform rendering tasks. This method may return * any value renderable by lit-html's `ChildPart` - typically a * `TemplateResult`. Setting properties inside this method will *not* trigger * the element to update. * @category rendering */ render() { return lit_html__WEBPACK_IMPORTED_MODULE_1__.noChange; } }
JavaScript
class Directive { constructor(_partInfo) { } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { return this._$parent._$isConnected; } /** @internal */ _$initialize(part, parent, attributeIndex) { this.__part = part; this._$parent = parent; this.__attributeIndex = attributeIndex; } /** @internal */ _$resolve(part, props) { return this.update(part, props); } update(_part, props) { return this.render(...props); } }
JavaScript
class ClassMapDirective extends _directive_js__WEBPACK_IMPORTED_MODULE_1__.Directive { constructor(partInfo) { var _a; super(partInfo); if (partInfo.type !== _directive_js__WEBPACK_IMPORTED_MODULE_1__.PartType.ATTRIBUTE || partInfo.name !== 'class' || ((_a = partInfo.strings) === null || _a === void 0 ? void 0 : _a.length) > 2) { throw new Error('`classMap()` can only be used in the `class` attribute ' + 'and must be the only part in the attribute.'); } } render(classInfo) { // Add spaces to ensure separation from static classes return (' ' + Object.keys(classInfo) .filter((key) => classInfo[key]) .join(' ') + ' '); } update(part, [classInfo]) { var _a, _b; // Remember dynamic classes on the first render if (this._previousClasses === undefined) { this._previousClasses = new Set(); if (part.strings !== undefined) { this._staticClasses = new Set(part.strings .join(' ') .split(/\s/) .filter((s) => s !== '')); } for (const name in classInfo) { if (classInfo[name] && !((_a = this._staticClasses) === null || _a === void 0 ? void 0 : _a.has(name))) { this._previousClasses.add(name); } } return this.render(classInfo); } const classList = part.element.classList; // Remove old classes that no longer apply // We use forEach() instead of for-of so that we don't require down-level // iteration. this._previousClasses.forEach((name) => { if (!(name in classInfo)) { classList.remove(name); this._previousClasses.delete(name); } }); // Add or remove classes based on their classMap value for (const name in classInfo) { // We explicitly want a loose truthy check of `value` because it seems // more convenient that '' and 0 are skipped. const value = !!classInfo[name]; if (value !== this._previousClasses.has(name) && !((_b = this._staticClasses) === null || _b === void 0 ? void 0 : _b.has(name))) { if (value) { classList.add(name); this._previousClasses.add(name); } else { classList.remove(name); this._previousClasses.delete(name); } } } return _lit_html_js__WEBPACK_IMPORTED_MODULE_0__.noChange; } }
JavaScript
class TemplateInstance { constructor(template, parent) { /** @internal */ this._parts = []; /** @internal */ this._$disconnectableChildren = undefined; this._$template = template; this._$parent = parent; } // Called by ChildPart parentNode getter get parentNode() { return this._$parent.parentNode; } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { return this._$parent._$isConnected; } // This method is separate from the constructor because we need to return a // DocumentFragment and we don't want to hold onto it with an instance field. _clone(options) { var _a; const { el: { content }, parts: parts, } = this._$template; const fragment = ((_a = options === null || options === void 0 ? void 0 : options.creationScope) !== null && _a !== void 0 ? _a : d).importNode(content, true); walker.currentNode = fragment; let node = walker.nextNode(); let nodeIndex = 0; let partIndex = 0; let templatePart = parts[0]; while (templatePart !== undefined) { if (nodeIndex === templatePart.index) { let part; if (templatePart.type === CHILD_PART) { part = new ChildPart(node, node.nextSibling, this, options); } else if (templatePart.type === ATTRIBUTE_PART) { part = new templatePart.ctor(node, templatePart.name, templatePart.strings, this, options); } else if (templatePart.type === ELEMENT_PART) { part = new ElementPart(node, this, options); } this._parts.push(part); templatePart = parts[++partIndex]; } if (nodeIndex !== (templatePart === null || templatePart === void 0 ? void 0 : templatePart.index)) { node = walker.nextNode(); nodeIndex++; } } return fragment; } _update(values) { let i = 0; for (const part of this._parts) { if (part !== undefined) { debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: 'set part', part, value: values[i], valueIndex: i, values, templateInstance: this, }); if (part.strings !== undefined) { part._$setValue(values, part, i); // The number of values the part consumes is part.strings.length - 1 // since values are in between template spans. We increment i by 1 // later in the loop, so increment it by part.strings.length - 2 here i += part.strings.length - 2; } else { part._$setValue(values[i]); } } i++; } } }
JavaScript
class Validators { /** * Throws an error in case the given object is null or undefined. * @param {Object} obj the object we want to validate. * @param {String} errMsg the error message we want to raise. */ static throwIfNotDefined(obj, errMsg) { if (!obj) { throw new Error(errMsg); } } /** * Throws an error in case the given object is not of type URL. * @param {Object} obj the potential url object. * @param {String} errMsg the error message which we want to throw in case of a failed assert. */ static throwIfNotUrl(obj, errMsg) { if (!(obj instanceof URL)) { throw new Error(errMsg); } } }
JavaScript
class VectorLayerFillOpacity extends AbstractVectorStyle { /** * Constructor. * @param {string} layerId The layer id. * @param {number} opacity The new fill opacity value. * @param {number|null=} opt_oldOpacity The old fill opacity value. */ constructor(layerId, opacity, opt_oldOpacity) { super(layerId, opacity, opt_oldOpacity); this.title = 'Change Layer Fill Opacity'; this.metricKey = LayerKeys.VECTOR_FILL_OPACITY; if (this.value == null) { this.value = osStyle.DEFAULT_FILL_ALPHA; } } /** * @inheritDoc */ getOldValue() { var config = StyleManager.getInstance().getLayerConfig(this.layerId); var color = osStyle.getConfigColor(config, true, StyleField.FILL); return color && color.length === 4 ? color[3] : osStyle.DEFAULT_FILL_ALPHA; } /** * @inheritDoc */ applyValue(config, value) { var color = osStyle.getConfigColor(config, true, StyleField.FILL) || osStyle.getConfigColor(config, true); if (color) { color[3] = value; var colorString = osStyle.toRgbaString(color); osStyle.setFillColor(config, colorString); } super.applyValue(config, value); } }
JavaScript
class PaymentMethodType { /** * Create a OvhPaymentMethodType. * * @param {String} paymentType The name of the payment type. */ constructor(paymentType) { /** * Name of the type of a payment method. * Will be use for helper class below. * @type {String} */ this.paymentType = paymentType; } /** * Determine if payment method type is a Bank Account. * * @return {Boolean} */ isBankAccount() { return this.paymentType === AVAILABLE_PAYMENT_METHOD_TYPE_ENUM.BANK_ACCOUNT; } /** * Determine if payment method type is a Credit Card. * * @return {Boolean} */ isCreditCard() { return this.paymentType === AVAILABLE_PAYMENT_METHOD_TYPE_ENUM.CREDIT_CARD; } /** * Determine if payment method type is a Deferred Payment Account. * * @return {Boolean} */ isDeferredPaymentAccount() { return ( this.paymentType === AVAILABLE_PAYMENT_METHOD_TYPE_ENUM.DEFERRED_PAYMENT_ACCOUNT ); } /** * Determine if payment method type is a Paypal account. * * @return {Boolean} */ isPaypal() { return this.paymentType === AVAILABLE_PAYMENT_METHOD_TYPE_ENUM.PAYPAL; } }
JavaScript
class ShowMatches extends React.Component { //binds the 'this' keyword to triggerDeleteApi method constructor(props) { super(props); //binds the 'this' keyword to triggerDeleteApi method this.triggerDeleteApi = this.triggerDeleteApi.bind(this); } //DELETE http request is sent //We get a response after the request is complete //Prints the data to the console that is located in the web browser triggerDeleteApi() { //DELETE http request is sent axios.delete("https://mathskills-mw5-6-back.herokuapp.com/deleteProblem?userId=99&problemId=1") //We get a response after the request is complete .then((response) => { //Prints the data to the console that is located in the web browser console.log(response.data); alert('Entry Deleted. Please refresh.') }) } //HTML is shown to the user render() { if(this.props.matches.length > 0) { return ( //This setups a striped table which makes it easier to keep track of <Table striped> <thead> <tr> <th>ID</th> <th>Problem</th> <th>Answer</th> <th></th> </tr> </thead> <tbody> { this.props.matches.map((question, id) => ( <tr key={id}> <th>{question.problemId}</th> <td>{question.problem}</td> <td>{question.answer}</td> <Button size="sm" onClick={this.triggerDeleteApi} >Delete</Button> </tr> )) } </tbody> </Table> ); } else { return <></> } } }
JavaScript
class ViewCourseScreen extends React.Component { static navigationOptions = ({ navigation }) => { const { params = {} } = navigation.state; return { headerStyle: { backgroundColor: params.navbarColor, borderBottomColor: 'transparent', }, headerTintColor: '#fff', headerRight: ( <TouchableOpacity onPress={() => params.handleEditCourse()}> <View style={{marginRight: 8}}><MaterialCommunityIcons name="pencil" size={30} color={'#fff'} /></View> </TouchableOpacity> ) }; }; constructor(props) { super(props); this._fetchCourse = this._fetchCourse.bind(this); this._fetchSessions = this._fetchSessions.bind(this); this._fetchStudents = this._fetchStudents.bind(this); this._fetchTeachers = this._fetchTeachers.bind(this); this._handleSelectStudent = this._handleSelectStudent.bind(this); this._deleteCourse = this._deleteCourse.bind(this); this._renderDeleteCourseButton = this._renderDeleteCourseButton.bind(this); this._renderCourseDate = this._renderCourseDate.bind(this); this._renderSessions = this._renderSessions.bind(this); this._renderTeachers = this._renderTeachers.bind(this); this.state = { course_id : this.props.navigation.state.params.course_id, sessions: [], course : { }, isLoading : true, students: [], navbarColor: this.props.navigation.state.params.navbarColor } } componentDidMount() { this._fetchCourse(); // const _enrollStudent = () => { // this.props.navigation.navigate('StudentPersonalDetails', // { refreshStudents: this._fetchStudents, // course_id: this.state.course_id, // navbarColor: this.state.navbarColor, // newStudent: true }) // } const _editCourse = () => { this.props.navigation.navigate('EditCourse', { refreshCourses: this._fetchCourse, newCourse: false, course_id: this.state.course_id, navbarColor: this.state.navbarColor, is_active: this.state.course.is_active, title__c: this.state.course.title__c, facilitator_1__c: this.state.course.f1_email__c, facilitator_2__c: this.state.course.f2_email__c, start_date__c: this.state.course.start_date__c, end_date__c: this.state.course.end_date__c, sessions: this.state.sessions, })} this.props.navigation.setParams({ navbarColor: this.state.navbarColor, handleEditCourse: _editCourse }); } /* * Fetch record for single course. */ _fetchCourse() { const successFunc = (responseData) => { this.setState({ course: responseData }); this._fetchSessions(); } getRequest(APIRoutes.getCoursePath(this.state.course_id), successFunc, standardError); } /* * Fetch record for single course. */ _fetchSessions() { const successFunc = (responseData) => { this.setState({ sessions: responseData.sessions }); this._fetchTeachers(); } getRequest(APIRoutes.getSessionsPath(this.state.course_id), successFunc, standardError); } /* * Fetch record for the course. */ _fetchTeachers() { const successFunc = (responseData) => { this.setState({ teachers: responseData.teachers}); this._fetchStudents(); } getRequest(APIRoutes.getTeachersPath(this.state.course_id), successFunc, standardError); } /* * Fetch students for the course. */ _fetchStudents() { const successFunc = (responseData) => { this.setState({ students: responseData, isLoading: false }); } getRequest(APIRoutes.getStudentsInCoursePath(this.state.course_id), successFunc, standardError); } _handleSelectStudent(id) { this.props.navigation.navigate('StudentProfile', { refreshStudents: this._fetchStudents(), studentId: id, courseId: this.state.course_id, navbarColor: this.state.navbarColor, }); } /* * Make a delete request. On success, re-render the component. */ _deleteCourse() { const successFunc = (responseData) => { this.props.navigation.navigate('Courses'); } deleteRequest(APIRoutes.getCoursePath(this.state.course_id), successFunc, standardError); } _renderDeleteCourseButton() { return ( <StyledButton onPress={() => confirmDelete("Are you sure you want to delete this course?", this._deleteCourse)} text='Delete Course' linkButton> </StyledButton> ); } /* * Display course dates. */ _renderCourseDate() { const start_date__c = new Date(this.state.course.start_date__c) const end_date__c = new Date(this.state.course.end_date__c) const course_start = start_date__c.toLocaleDateString() const course_end = end_date__c.toLocaleDateString() return ( <Text style={textStyles.bodySmallLight}>{`${course_start} to ${course_end}`}</Text> ); } /* * Display course teachers. */ _renderTeachers() { if (this.state.course.f2_first_name__c == undefined) { return ( `${this.state.course.f1_first_name__c} ${this.state.course.f1_last_name__c}` ); } else { return ( `${this.state.course.f1_first_name__c} ${this.state.course.f1_last_name__c}, ${this.state.course.f2_first_name__c} ${this.state.course.f2_last_name__c}` ); } } /* * Display course sessions. */ _renderSessions() { if (this.state.sessions.length != 0) { return this.state.sessions.map((session, index) => { const start = timeFormat(new Date(session.start_time)) const end = timeFormat(new Date(session.end_time)) return ( <View key={index}> <Text style={textStyles.bodySmallLight}>{`${session.weekday}, ${ start } - ${ end }` } </Text> </View> ); }); } else { const { params = {} } = this.props.navigation.state; return ( <TouchableOpacity onPress={() => params.handleEditCourse()}> <View> <Text style={textStyles.buttonTextAddSessionCourse} >+ Add Session</Text> </View> </TouchableOpacity> ); } } /* * Display course students */ _renderStudents() { const { navigate } = this.props.navigation; return this.state.students.map((student, i) => ( <StudentCard key={i} student={student} onSelectStudent={this._handleSelectStudent} /> ) ); } render() { const { navigate } = this.props.navigation; if (this.state.isLoading) { return ( <View style={commonStyles.containerStatic}> <Image style={commonStyles.icon} source={require('../../icons/spinner.gif')} /> </View> ); } else { return ( <ScrollView style={{backgroundColor: this.state.navbarColor, borderBottomWidth: 400, borderBottomColor: '#fff'}}> <View style={{backgroundColor: this.state.navbarColor, paddingBottom: 24}}> <View style={formViewStyles.div_1}> <View style={formViewStyles.div_2}> <Text style={[textStyles.titleLargeLight, {marginBottom: 16}]}>{ this.state.course.title__c }</Text> <View style={formViewStyles.div_2}> { this._renderSessions() } </View> <View style={formViewStyles.div_2}> <Text style={textStyles.bodySmallLight}>{ this._renderTeachers() }</Text> </View> <View style={formViewStyles.div_2}> { this._renderCourseDate() } </View> </View> </View> </View> <View style={{backgroundColor: colors.backgroundWhite}}> <View style={{marginTop: 16}}> <StyledButton onPress={() => navigate('Attendances', { courseId: this.state.course.id, courseTitle: this.state.course.title__c, date: attendanceDate(new Date()), })} text="Take Attendance" // secondaryButtonLarge variableButton={ this.state.navbarColor } /> <StyledButton onPress={() => navigate('RecentAttendances', { courseId: this.state.course.id, courseTitle: this.state.course.title__c})} text="View Past Attendance" secondaryButtonLarge /> </View> <View style={[commonStyles.divider, {marginTop: 16, marginBottom: 16}]}/> <View style={[formViewStyles.div_1, {marginBottom: 16}]}> <View style={{flex: 1, flexDirection: 'row'}}> <View style={{flex: 0.6}}> <Text style={textStyles.titleMedium}>Students</Text> </View> <View style={{flex: 0.4, flexDirection: 'row', justifyContent: 'flex-end'}}> <StyledButton onPress={() => this.props.navigation.navigate('SearchStudent', { refreshStudents: this._fetchStudents, course_id: this.state.course_id, navbarColor: this.state.navbarColor, })} text="+ Enroll Student" enrollSmall /> </View> </View> <View style={{marginTop: 8, marginBottom: 40}}> { this._renderStudents() } </View> </View> </View> </ScrollView> ); } } }
JavaScript
class RenderTarget { /** * Create the render target. * @param {PintarJS.Point} size Render target size. * @param {*} data Internal data used by the renderer. */ constructor(size, data) { this.size = size.clone(); this._data = data; } /** * Is this a valid render target? */ get isRenderTarget() { return true; } /** * Get texture width. */ get width() { return this.size.x; } /** * Get texture height. */ get height() { return this.size.y; } /** * Get render target viewport. */ get viewport() { return new Viewport(Point.zero(), new Rectangle(0, 0, this.width, this.height)); } }
JavaScript
class Office { constructor(id, officeName, officePostcode) { this.id= id; this.officeName = officeName; this.officePostcode = officePostcode; this.officeSkillsetsList = []; } addSkillset(skillset) { this.officeSkillsetList.push(skillset); } addSkillsetsList(skillsetsList) { this.officeSkillsetsList = skillsetsList; } }
JavaScript
class MarkTheWords extends LitElement { // a convention I enjoy so you can change the tag name in 1 place static get tag() { return 'mark-the-words'; } // HTMLElement life-cycle, built in; use this for setting defaults constructor() { super(); this.answers = ""; this.correctAnswers = []; //parse text this.wordList = this.innerText.split(/\s+/g); this.innerText = ""; } // properties that you wish to use as data in HTML, CSS, and the updated life-cycle static get properties() { return { wordList: { type: Array }, answers: { type: String, reflect: true }, correctAnswers: { type: Array } }; } // updated fires every time a property defined above changes // this allows you to react to variables changing and use javascript to perform logic updated(changedProperties) { changedProperties.forEach((oldValue, propName) => { if (propName === "wordList") { this.rebuildContents(this[propName]); } if (propName === "answers" && this[propName]) { this.correctAnswers = this[propName].split(","); this.answers = null; } }); } rebuildContents(ary) { //wipe out inner this.shadowRoot.querySelector("#textArea").innerHTML = ""; ary.forEach((word) => { let span = document.createElement("span"); span.innerText = word; span.setAttribute("tabindex", "-1"); span.addEventListener("click", this.selectWord.bind(this)); this.shadowRoot.querySelector("#textArea").appendChild(span); }); } // Lit life-cycle; this fires the 1st time the element is rendered on the screen // this is a sign it is safe to make calls to this.shadowRoot firstUpdated(changedProperties) { if (super.firstUpdated) { super.firstUpdated(changedProperties); } } // HTMLElement life-cycle, element has been connected to the page / added or moved // this fires EVERY time the element is moved connectedCallback() { super.connectedCallback(); } // HTMLElement life-cycle, element has been removed from the page OR moved // this fires every time the element moves disconnectedCallback() { super.disconnectedCallback(); } // CSS - specific to Lit static get styles() { return [css` :host { display: block; padding: 16px; margin: 16px; border: 2px solid black; } span { display: inline-flex; font-size: var(--x-ample-font-size, 24px); padding: 2px; margin: 0 2px; } span:hover,span:focus { outline: 2px dashed blue; cursor: pointer; } span[data-selected] { outline: 2px solid purple; } span[data-selected]:hover, span[data-selected]:focus { outline: 2px solid blue; } span[data-status="correct"] { outline: 2px solid purple; } span[data-status="correct"]::after { content: "+1"; font-size: 14px; color: green; font-weight: bold; border-radius: 50%; border: 2px solid purple; padding: 4px; margin-left: 8px; line-height: 14px; } span[data-status="incorrect"] { outline: 2px solid red; } span[data-status="incorrect"]::after { content: "-1"; font-size: 14px; color: red; font-weight: bold; border-radius: 50%; border: 2px solid red; padding: 4px; margin-left: 8px; line-height: 14px; } .buttons,.correct { margin: 8px; } `]; } selectWord(e) { const el = e.target; if (el.getAttribute("data-selected")) { el.removeAttribute("data-selected") } else { el.setAttribute("data-selected", "data-selected"); } } checkAnswer(e) { const selected = this.shadowRoot.querySelectorAll("#textArea span[data-selected]"); console.log(selected); for (var i = 0; i < selected.length; i++) { const el = selected[i]; console.log(this.correctAnswers); console.log(el.innerText); console.log(this.correctAnswers.includes(el.innerText)); if (this.correctAnswers.includes(el.innerText.replace(/[&#^,+()$~%.":*?<>{}]/g, ''))) { el.setAttribute("data-status", "correct"); } else { el.setAttribute("data-status", "incorrect"); } } } // HTML - specific to Lit render() { return html` <div id="textArea"> </div> <div class = "buttons"> <button @click="${this.checkAnswer}">Check</button> </div> <div class="correct"> <h1>Correct Answers</h1> <ul> ${this.correctAnswers.map((item, i) => html`<li data-index="${i}">${item}</li>`)} </ul> </div> `; } // HAX specific callback // This teaches HAX how to edit and work with your web component /** * haxProperties integration via file reference */ static get haxProperties() { return new URL(`../lib/mark-the-words.haxProperties.json`, import.meta.url).href; } }
JavaScript
class LinkedList { /** * Unlike a graph, a linked list has a single node that starts off the entire * chain. This is known as the "head" of the linked list. * * We're also going to track the length. */ constructor() { this.head = null; this.length = 0; } /** * First we need a way to retrieve a value in a given position. * * This works differently than normal lists as we can't just jump to the * correct position. Instead, we need to move through the individual nodes. */ find(position) { // Throw an error if position is greater than the length of the LinkedList if (position >= this.length) { throw new Error('Position outside of list range'); } // Start with the head of the list. let current = this.head; // Slide through all of the items using node.next until we reach the // specified position. for (let index = 0; index < position; index++) { current = current.next; } // Return the node we found. return current; } /** * Next we need a way to add nodes to the specified position. * * We're going for a generic add method that accepts a value and a position. */ add(value, position) { // First create a node to hold our value. let node = { value, next: null }; // We need to have a special case for nodes being inserted at the head. // We'll set the "next" field to the current head and then replace it with // our new node. if (position === 0) { node.next = this.head; this.head = node; // If we're adding a node in any other position we need to splice it in // between the current node and the previous node. } else { // First, find the previous node and the current node. let prev = this.find(position - 1); let current = prev.next; // Then insert the new node in between them by setting its "next" field // to the current node and updating the previous node's "next" field to // the new one. node.next = current; prev.next = node; } // Finally just increment the length. this.length++; } /** * The last method we need is a remove method. We're just going to look up a * node by its position and splice it out of the chain. */ remove(position) { // We should not be able to remove from an empty list if (!this.head) { throw new Error('Removing from empty list'); } // If we're removing the first node we simply need to set the head to the // next node in the chain if (position === 0) { this.head = this.head.next; // For any other position, we need to look up the previous node and set it // to the node after the current position. } else { let prev = this.get(position - 1); prev.next = prev.next.next; } // Then we just decrement the length. this.length--; } }
JavaScript
class Bit_Range { constructor(ui8a, bii_start, bii_end) { // Spec is a buffer, and its bit positions. // These bit ranges will be used to access / use the values in the Huffman table. // Then be able to access the individual bits in this range by position. } }
JavaScript
class Ui32BinaryTree { constructor(spec = {}) { // number of nodes. let i_max_nodes = spec.max_nodes || 64; // Each node takes 3 ui32 positions. // 0: left, 1: right, 2: self value // Or: 0: self index, 1: self value, 2: left index, 3: right index // add item with code? // just add item. // (index?), left, right, value. // one of the 32 bit values for each node as a mask? // saying if it is using the value, left, right. // or have 0 signify nowhere? // may want 'no value' as well as value '0'. // index 0 could mean does not point anywhere. let i_next_new_node = 0; const ta_items_per_node = 6; let ta = new Uint32Array(i_max_nodes * ta_items_per_node); // add_node may be a better API? // .set // .get // where appropriate. /// ???? ------------------------------------ const set = (key, value) => { } const get = (key) => { } // ??????? ------------------------------------ // Set everything in a single node? let num_nodes = 0; let i_root_node; const node_exists = (i_node) => { return i_node < i_next_new_node; } this.node_exists = node_exists; const create_root_node = () => { if (i_root_node === undefined) { i_root_node = i_next_new_node++; num_nodes++; let p = i_root_node * ta_items_per_node; const is_root = true; // const has_key = false; const has_value = false; const has_l_child = false; const has_r_child = false; const has_parent = false; const is_leaf = true; const mask = mask_bools(is_root, is_leaf, has_key, has_value, has_l_child, has_r_child, has_parent); //console.log('[is_root, is_leaf, has_key, has_value, has_l_child, has_r_child, has_parent]', [is_root, is_leaf, has_key, has_value, has_l_child, has_r_child, has_parent]); //const mask = def(value) | (def(left) * 2) | (def(right) * 4); //console.log('mask', mask); //throw 'stop'; ta[p++] = mask; if (has_key) { ta[p++] = key; } else { p++; } if (has_value) { ta[p++] = value; } else { p++; } if (has_l_child) { ta[p++] = i_left; } else { p++; } if (has_r_child) { ta[p++] = i_right; } else { p++; } if (has_parent) { ta[p++] = i_parent; } else { p++; } return i_root_node; //set_node(i_root_node = i_next_new_node++, undefined, undefined, undefined, undefined); //num_nodes++; //return i_root_node; } else { if (typeof i_root_node === 'number') { console.trace(); throw 'NYI - Cannot create more than 1 root node.' } } } ro(this, 'ta', () => ta); ro(this, 'num_nodes', () => num_nodes); // insert_node may work better? // set_node_l_child // set_node_r_child const _get_node_mask_bit = (i_node, i_bit) => { const mask_val = ta[i_node * ta_items_per_node]; //console.log('mask_val', mask_val); //const i_match = Math.pow(2, i_bit); const i_match = 1 << i_bit; //console.log('i_bit', i_bit); //console.log('i_match', i_match); const has_match = (i_match & mask_val) !== 0; //console.log('i_match & mask_val', i_match & mask_val); //console.log('has_match', has_match); return has_match; } /* const set_node_parent = (i, i_parent) => { const p_node = i * ta_items_per_node; const p_node_i_parent = p_node + 5; //i_parent ta[p_node_i_parent] = i_parent; set_node_mask_bit(i, 6, true); //has_parent } */ const node_to_right_of = (i_node) => { console.log('node_to_right_of i_node', i_node); console.log('ta', ta); if (i_node === null || i_node === undefined) { return i_node; } else { // Node is the left child of its parent, then the parent's // right child is its right level order node. //if ( node->parent != nullptr && node->parent->lChild == node ) // return node->parent->rChild; let i_parent = get_node_parent(i_node); console.log('i_parent', i_parent); if (i_parent === undefined) { return undefined; } else { // a number // get the index of the parent lchild - check it's i_node. // then it's the rchild which will be to the right of it. const i_parent_l_child = get_node_l_child(i_parent); if (i_parent_l_child === i_node) { return get_node_r_child(i_parent); } else { // Some kind of traversal needed.... let count = 0, index = i_node; //let i_parent; i_parent = get_node_parent(index); while (i_parent !== undefined && get_node_r_child(i_parent) === undefined) { index = i_parent; i_parent = get_node_parent(index); //console.log('i_parent', i_parent); count++; } console.log('count', count); /* while ( nptr->parent != nullptr && nptr->parent->rChild == nptr ) { nptr = nptr->parent; count++; } */ // if ( nptr->parent == nullptr ) return nullptr; i_parent = get_node_parent(index); if (i_parent === undefined) { return undefined; } else { /* nptr = nptr->parent->rChild; int i = 1; while ( count > 0 ) { nptr = nptr->lChild; count--; } return nptr; */ index = get_node_r_child(index); let i2 = 1; while (count > 0) { index = get_node_l_child(index); count--; } console.log('pre return index', index); return index; } } } } //const t_i_node = typeof i_node; /* NodePtr getRightLevelNode( NodePtr node ) { if ( node == nullptr ) return nullptr; // Node is the left child of its parent, then the parent's // right child is its right level order node. if ( node->parent != nullptr && node->parent->lChild == node ) return node->parent->rChild; // Else node is the right child of its parent, then traverse // back the tree and find its right level order node int count = 0; NodePtr nptr = node; while ( nptr->parent != nullptr && nptr->parent->rChild == nptr ) { nptr = nptr->parent; count++; } if ( nptr->parent == nullptr ) return nullptr; nptr = nptr->parent->rChild; int i = 1; while ( count > 0 ) { nptr = nptr->lChild; count--; } return nptr; } */ } this.node_to_right_of = node_to_right_of; const node_has_left_child = i_node => get_node_mask_bit(i_node, 4); const node_has_right_child = i_node => get_node_mask_bit(i_node, 5); const node_is_root = i_node => get_node_mask_bit(i_node, 0); const node_is_leaf = i_node => get_node_mask_bit(i_node, 1); const node_has_key = i_node => get_node_mask_bit(i_node, 2); const node_has_value = i_node => get_node_mask_bit(i_node, 3); const node_has_parent = i_node => get_node_mask_bit(i_node, 6); const set_node_mask_bit = (i_node, i_bit, value) => { const p_node = i_node * ta_items_per_node; const p_node_mask = p_node; if (value === 1 || value === true) { ta[p_node_mask] = ta[p_node_mask] | (1 << i_bit); } else { ta[p_node_mask] = ta[p_node_mask] & (~(1 << i_bit)); } //const i_value = (value === true) ? 1 | 0 : 0 | 0; } /* const check_mask_bit_get_ta_item_ui32 = (i_node, i_mask_bit, i_byte_index_in_ta_item) => { //const has_required_bit = ; if (get_node_mask_bit(i_node, i_mask_bit)) { return ta[i_node * ta_items_per_node + i_byte_index_in_ta_item]; } } */ const get_node_mask_bit = (i_node, i_bit) => ((1 << i_bit) & (ta[i_node * ta_items_per_node])) !== 0 const check_mask_bit_get_ta_item_ui32 = (i_node, i_mask_bit, i_byte_index_in_ta_item) => get_node_mask_bit(i_node, i_mask_bit) ? ta[i_node * ta_items_per_node + i_byte_index_in_ta_item] : undefined; const get_node_parent = i_node => check_mask_bit_get_ta_item_ui32(i_node, 6, 5); const get_node_value = i_node => check_mask_bit_get_ta_item_ui32(i_node, 3, 2); const get_node_l_child = i_node => check_mask_bit_get_ta_item_ui32(i_node, 4, 3); const get_node_r_child = i_node => check_mask_bit_get_ta_item_ui32(i_node, 5, 4); /* const _get_node_parent = (i_node) => { //console.log('get_node_parent i_node', i_node); const has_parent = get_node_mask_bit(i_node, 6); //console.log('has_parent', has_parent); if (has_parent) { const p_node = i_node * ta_items_per_node; const p_node_i_parent = p_node + 5; //i_parent as 5 return ta[p_node_i_parent]; } //const p_node = i * ta_items_per_node; //const p_node_i_parent = p_node + 5; } */ /* const get_node_value = (i_node) => { const has_value = get_node_mask_bit(i_node, 3); if (has_value) { const p_node = i_node * ta_items_per_node; const p_node_i_value = p_node + 2; return ta[p_node_i_value]; } } const get_node_l_child = (i_node) => { const has_l_child = get_node_mask_bit(i_node, 4); //console.log('[i_node, has_l_child]', [i_node, has_l_child]); if (has_l_child) { const p_node = i_node * ta_items_per_node; const p_node_i_l_child = p_node + 3; //console.log('ta[p_node_i_l_child]', ta[p_node_i_l_child]); return ta[p_node_i_l_child]; } } const get_node_r_child = (i_node) => { const has_r_child = get_node_mask_bit(i_node, 5); //console.log('[i_node, has_r_child]', [i_node, has_r_child]); if (has_r_child) { const p_node = i_node * ta_items_per_node; const p_node_i_r_child = p_node + 4; return ta[p_node_i_r_child]; } } */ // is_left_child_of(o_node.index, o_node.parent) const is_left_child_of = (i_node, i_parent) => { if (node_has_left_child(i_parent)) { console.log('hlc'); //console.lo return ta[i_parent * ta_items_per_node + 3] === i_node; } else { return false; } } const is_right_child_of = (i_node, i_parent) => { if (node_has_right_child(i_parent)) { return ta[i_parent * ta_items_per_node + 4] === i_node; } else { return false; } } // Be able to take a value too.... // left or right...? const create_left_child_node = (i_node, value) => { // need a new id for the child node. const i_new_child_node = i_next_new_node++; num_nodes++; let p = i_new_child_node * ta_items_per_node; const is_root = false; const has_key = false; const has_value = value !== undefined; const has_l_child = false; const has_r_child = false; const has_parent = true; const is_leaf = true; const mask = mask_bools(is_root, is_leaf, has_key, has_value, has_l_child, has_r_child, has_parent); ta[p] = mask; //p += 4; if (has_value) ta[p + 2] = value ta[p + 5] = i_node; let idx_node = i_node * ta_items_per_node; let idx_node_l_child = idx_node + 3; ta[idx_node_l_child] = i_new_child_node; // and set the has_l_child bit. set_node_mask_bit(i_node, 1, false); set_node_mask_bit(i_node, 4, true); // then adjust it with own mask. // adjust the parent node so that it has got the children. // set_node_i_left_child // and that's all it does. return i_new_child_node; } const create_right_child_node = (i_node, value) => { // need a new id for the child node. // test if it already has that child node...? const i_new_child_node = i_next_new_node++; num_nodes++; let p = i_new_child_node * ta_items_per_node; const is_root = false; const has_key = false; const has_value = value !== undefined; const has_l_child = false; const has_r_child = false; const has_parent = true; const is_leaf = true; const mask = mask_bools(is_root, is_leaf, has_key, has_value, has_l_child, has_r_child, has_parent); ta[p] = mask; //p += 4; if (has_value) ta[p + 2] = value ta[p + 5] = i_node; let idx_node = i_node * ta_items_per_node; let idx_node_r_child = idx_node + 4; ta[idx_node_r_child] = i_new_child_node; // and set the has_l_child bit. set_node_mask_bit(i_node, 1, false); set_node_mask_bit(i_node, 5, true); const nbm_1 = get_node_mask_bit(i_node, 1); const nbm_5 = get_node_mask_bit(i_node, 5); console.log('[nbm_1, nbm_5]', [nbm_1, nbm_5]); // then adjust it with own mask. // adjust the parent node so that it has got the children. // set_node_i_left_child // and that's all it does. //throw 'stop'; return i_new_child_node; } const add_empty_children = (i_node) => { const i_l_child = create_left_child_node(i_node); const i_r_child = create_right_child_node(i_node); } this.add_empty_children = add_empty_children; // The key is basically the path through the tree. // A binary path. Understanding binary trees better now :). /* inOrder: perform inorder traversal of the Huffman tree with specified root node */ const traverse = (i_start, callback) => { // callback on the node itself. //console.log('traverse i_start', i_start); const value = get_node_value(i_start); const i_lc = get_node_l_child(i_start); const i_rc = get_node_r_child(i_start); const i_parent = get_node_parent(i_start); // And a stop function...? let ctu = true; const fn_stop = () => { ctu = false; } callback({ index: i_start, value: value, parent: i_parent, left_child: i_lc, right_child: i_rc }, fn_stop); if (ctu) { //console.log('i_lc', i_lc); if (i_lc !== undefined) { traverse(i_lc, callback); } //console.log('i_rc', i_rc); if (i_rc !== undefined) { traverse(i_rc, callback); } } } this.traverse = traverse; const toArray = () => { console.log('toArray()'); const res_root = [[], []]; const map_nodes_by_index = {}; const map_arr_res_nodes_by_index = {}; // An array entry for each node... // Nodes will hold values too. // Will need to use that in the Huffman tree decoding lookups. // The key of a node is the path to reach it (so I think). let current; traverse(0, (o_node) => { // [value, left_branch, right_branch] console.log('o_node', o_node); map_nodes_by_index[o_node.index] = o_node; const {value, parent} = o_node; let parent_arr_node; if (parent === undefined) { // it's the root node current = res_root; } else { //const parent_node = map_nodes_by_index[parent]; current = [value, [], []]; parent_arr_node = map_arr_res_nodes_by_index[o_node.parent]; // is it on the left or the right of the parent? console.log('[o_node.index, o_node.parent]', o_node.index, o_node.parent); if (is_left_child_of(o_node.index, o_node.parent)) { parent_arr_node[0] = current; } else if (is_right_child_of(o_node.index, o_node.parent)) { parent_arr_node[1] = current; } else { console.trace(); throw 'stop'; } //map_arr_res_nodes_by_index[o_node.parent] } map_arr_res_nodes_by_index[o_node.index] = current; // lookup the parent array. }); return res_root; } this.toArray = toArray; const setup_3_node_structure = () => { const i_root = create_root_node(); add_empty_children(i_root); //console.log('i_root', i_root); // Maybe add_node of some sort will help? /* const i_l1_left = set_node(i_next_new_node++, undefined, undefined, undefined, i_root); set_node_l_child(i_root, i_l1_left); //i_leftmost = i_l1_left; //console.log('i_l1_left', i_l1_left); const i_l1_right = set_node(i_next_new_node++, undefined, undefined, undefined, i_root); set_node_r_child(i_root, i_l1_right); */ //console.log('i_l1_right', i_l1_right); // And the parent as the root. //const i_left = set_node(i_node++, undefined, undefined, undefined, i_root); //const i_right = set_node(i_node++, undefined, undefined, undefined, i_root); // insert_left and insert_right would work better here. console.log('setup_structure complete'); } //setup_3_node_structure(); this.setup_3_node_structure = setup_3_node_structure; // // Will also need to navigate structure when placing / putting nodes. //console.log('ta', ta); //throw 'End of Ui32BinaryTree constructor'; } }
JavaScript
class Huffman_Tree { // With binary tree implementation inside. constructor(spec) { //console.log('Huffman_Tree spec', spec); // a local btree. const btree = new Ui32BinaryTree(); if (spec.format) { if (spec.format === 'jpeg') { const {value} = spec; if (value) { const {code_counts, buf_huffman} = value; //console.log('code_counts.length', code_counts.length); //let sum_l_bits = 0; // Number of codes in total let count_codes = 0; for (let c = 0; c < 16; c++) { //sum_l_bits += (code_counts[c]) * (c + 1); count_codes += code_counts[c]; } // Could try doing this without the buildHuffmanTable function. /* // Using error checking now. console.log('sum_l_bits', sum_l_bits); console.log('buf_huffman.length', buf_huffman.length); console.log('count_codes', count_codes); console.log('buf_huffman.length * 8', buf_huffman.length * 8); */ if (count_codes === buf_huffman.length) { // As it should be. // Will read these (at first) into an OO TA tree structure. // Would also work as a basis for a TA Linked List. Could also hold strings / other values / binary values. const use_jpegjs_ht = () => { const ht = buildHuffmanTable(code_counts, buf_huffman); console.log('ht', ht); console.log('ht', JSON.stringify(ht)); } // Will have my own build Huffman Table // or Huffman Tree.... // Will use fast ta tree access for the moment. Is a small tree anyway. // Worth iterating through the codes here. // Reading what data we can get from them where possible. // Each of them will be byte codes. // Seems a bit difficult. Maybe they are the leaves of the tree? The tree itself is encoded in a neatly compressed way (mostly). //const htree = build_huffman_tree_jpeg(code_counts, buf_huffman); const res_build = build_huffman_tree_jpeg(btree, code_counts, buf_huffman); console.log('res_build', res_build); console.log('btree', btree); //throw 'stop'; //console.log('\n'); // And I'll use my own Huffman Tree system. // See if I can get my own decode of DHT producing the same results, but using a faster TA system. } else { console.trace(); throw 'stop'; } } else { console.trace(); throw 'JSON format HT - Expected spec.value'; } // count the sum... } else { console.trace(); throw 'Unsupported format: ' + spec.format; } } ro(this, 'ta', () => btree.ta); ro(this, 'num_nodes', () => btree.num_nodes); // Want efficient storage of the internal data // Need to be able to give it the binary JPEG definition of the Huffman Tree / Table? // Expecting the spec as an object makes most sense right now. // Function to decode JPEG-encoded Huffman tree / block data // Initial part: The lengths (counts) at each number of bits // Next part: the values at each number of bits. // Requires reading sub-8-bit / non-byte separated values from the typed array. // Create the Huffman tree from JPEG DHT block... } }
JavaScript
class Field { constructor(data, name, value) { this.data = data; this.name = name; this.value = value; } verifyType(...expected) { const type = typeof (this.value ?? undefined); if (!expected.includes(type)) { console.warn( `Expected ${expected.join(', ')} for field ${this.name}, got "${type}" for "${np.relative( process.cwd(), this.data.path, )}"`, ); this.value = null; } return this; } verifyUrl(...hostname) { if (typeof this.value === 'string') { let url; try { url = new URL(/^https?:\/\//i.test(this.value) ? this.value : `https://${this.value}`); if (hostname.length > 0 && !hostname.includes(url.hostname.replace(/^www\./i, ''))) { console.warn(`Manifest contains incorrect ${this.name} url "${np.relative(process.cwd(), this.data.path)}"`); } this.value = `https://${url.hostname}${url.pathname}`; } catch (e) { if (e.code === 'ERR_INVALID_URL') { console.error( `Manifest contains invalid url in field ${this.name} "${np.relative(process.cwd(), this.data.path)}"`, ); } else { console.error(e); process.exit(1); } } } return this; } async fetchRepositoryData() { if (this.value) { this.value = { url: this.value }; const url = new URL(this.value.url); switch (url.hostname.replace(/^www\./i, '')) { case 'github.com': { const res = await fetch(`https://api.github.com/repos${url.pathname}`, { method: 'get', }); if (res.status === 200) { const data = await res.json(); if (data.license) this.value.license = data.license.name; if (data.owner) this.owner = data.owner.login; if (!this.data.fields.name.value) this.data.fields.name.value = data.name; } break; } } } return this; } parseEmail() { if (typeof this.value === 'string' && !this.data.fields.contact.value) { const matched = this.value.match(/<(\w+@\w+\.\w+)>/i) ?? this.value.match(/(\w+@\w+\.\w+)/i); if (matched) { if (matched.index === 0) this.value = this.value.slice(matched[0].length).trim(); else this.value = this.value.slice(0, matched.index).trim(); this.data.fields.contact.value = matched[1]; } } return this; } }
JavaScript
class LocalTTS { constructor() { this.speaking = false; this.synthesis = window.speechSynthesis; } /** * Speak given text. * * @param {String} text text to pronounce * @param {String} language language of text * @param {String} speed "fast" or "slow" * * @returns {boolean} is speaking succeeded? */ speak(text, language, speed) { // Check if the language is supported. if (!this.synthesis.getVoices().find((voice) => voice.lang.startsWith(language))) { console.log(`No voice for language: "${language}"`); return false; } this.speaking = true; let utter = new SpeechSynthesisUtterance(text); utter.rate = speed === "fast" ? 1.0 : 0.6; // Set speaking to false when finished speaking. utter.onend = (() => (this.speaking = false)).bind(this); this.synthesis.speak(utter); return true; } /** * Pause speaking. */ pause() { if (this.speaking) { this.synthesis.cancel(); this.speaking = false; } } }
JavaScript
class Triangle { constructor(vertices) { this.vertices = vertices; this.indices = []; this.normal = null; this.resetBounds(); this.count = 0; this.surfaceArea = null; this.signedVolume = null; } // Add a new index idx and update the bounds based on this.vertices[idx], the // corresponding vertex object. addVertex(idx) { if (this.count>=3) { console.log("ERROR: tried to push a fourth vertex onto a triangle"); return; } this.indices.push(idx); const vertex = this.vertices[idx]; this.count++; if (this.count==1) { this.xmin = vertex.x; this.xmax = vertex.x; this.ymin = vertex.y; this.ymax = vertex.y; this.zmin = vertex.z; this.zmax = vertex.z; } else { this.updateBoundsV(vertex); } } // All bounds to Inifinity. resetBounds() { this.xmin = Infinity; this.xmax = -Infinity; this.ymin = Infinity; this.ymax = -Infinity; this.zmin = Infinity; this.zmax = -Infinity; } // Update bounds with the addition of a new vertex. updateBoundsV({x, y, z}) { this.xmin = x<this.xmin ? x : this.xmin; this.xmax = x>this.xmax ? x : this.xmax; this.ymin = y<this.ymin ? y : this.ymin; this.ymax = y>this.ymax ? y : this.ymax; this.zmin = z<this.zmin ? z : this.zmin; this.zmax = z>this.zmax ? z : this.zmax; } // Recalculate all bounds. updateBounds() { this.resetBounds(); for (let i=0; i<3; i++) { this.updateBoundsV(this.vertices[this.indices[i]]); } } // Set the normal. setNormal(normal) { this.normal = normal; } // Calculate triangle area via cross-product. calcSurfaceArea() { if (this.surfaceArea!==null) return this.surfaceArea; const v = new THREE.Vector3(); const v2 = new THREE.Vector3(); v.subVectors(this.vertices[this.indices[0]], this.vertices[this.indices[1]]); v2.subVectors(this.vertices[this.indices[0]], this.vertices[this.indices[2]]); v.cross(v2); this.surfaceArea = 0.5 * v.length(); return this.surfaceArea; } // Calculate the volume of a tetrahedron with one vertex on the origin and // with the triangle forming the outer face; sign is determined by the inner // product of the normal with any of the vertices. calcSignedVolume() { if (this.signedVolume!==null) return this.signedVolume; const sign = Math.sign(this.vertices[this.indices[0]].dot(this.normal)); const v1 = this.vertices[this.indices[0]]; const v2 = this.vertices[this.indices[1]]; const v3 = this.vertices[this.indices[2]]; let volume = (-v3.x*v2.y*v1.z + v2.x*v3.y*v1.z + v3.x*v1.y*v2.z); volume += (-v1.x*v3.y*v2.z - v2.x*v1.y*v3.z + v1.x*v2.y*v3.z); this.signedVolume = sign * Math.abs(volume/6.0); return this.signedVolume; } // Calculate the endpoints of the segment formed by the intersection of this // triangle and a plane normal to the given axis. // Returns an array of two Vector3s in the plane. intersection(axis, pos) { if (this[`${axis}max`]<=pos || this[`${axis}min`]>=pos) return []; const segment = []; for (let i=0; i<3; i++) { const v1 = this.vertices[this.indices[i]]; const v2 = this.vertices[this.indices[(i+1)%3]]; if ((v1[axis]<pos && v2[axis]>pos) || (v1[axis]>pos && v2[axis]<pos)) { const d = v2[axis]-v1[axis]; if (d==0) return; const factor = (pos-v1[axis])/d; // more efficient to have a bunch of cases than being clever and calculating // the orthogonal axes and building a Vector3 from basis vectors, etc. if (axis=="x") { var y = v1.y + (v2.y-v1.y)*factor; var z = v1.z + (v2.z-v1.z)*factor; segment.push(new THREE.Vector3(pos,y,z)); } else if (axis=="y") { var x = v1.x + (v2.x-v1.x)*factor; var z = v1.z + (v2.z-v1.z)*factor; segment.push(new THREE.Vector3(x,pos,z)); } else { // axis=="z" var x = v1.x + (v2.x-v1.x)*factor; var y = v1.y + (v2.y-v1.y)*factor; segment.push(new THREE.Vector3(x,y,pos)); } } } if (segment.length!=2) console.log("Plane-triangle intersection: strange segment length: ", segment); return segment; } }
JavaScript
class QuickHighlightView { static initClass () { this.viewByEditor = new Map() } // prettier-ignore static register (view) { this.viewByEditor.set(view.editor, view) } // prettier-ignore static unregister (view) { this.viewByEditor.delete(view.editor) } // prettier-ignore static destroyAll () { this.viewByEditor.forEach(view => view.destroy()) } // prettier-ignore static clearAll () { this.viewByEditor.forEach(view => view.clear()) } // prettier-ignore static refreshVisibles () { const editors = getVisibleEditors() for (const editor of editors) { const view = this.viewByEditor.get(editor) if (view) { view.refresh() } } } constructor (editor, {keywordManager, statusBarManager, emitter}) { this.editor = editor this.keywordManager = keywordManager this.statusBarManager = statusBarManager this.emitter = emitter this.markerLayerByKeyword = new Map() this.highlightSelection = this.highlightSelection.bind(this) let highlightSelection this.disposables = new CompositeDisposable( atom.config.observe('auto-highlight.highlightSelectionDelay', delay => { highlightSelection = _.debounce(this.highlightSelection, delay) }), this.editor.onDidDestroy(() => this.destroy()), this.editor.onDidChangeSelectionRange(({selection}) => { if (selection.isEmpty()) { this.clearSelectionHighlight() } else { highlightSelection(selection) } }), this.editor.onDidStopChanging(() => { this.clear() if (isVisibleEditor(this.editor)) { this.refresh() } }) ) QuickHighlightView.register(this) } needSelectionHighlight (text) { return ( getConfig('highlightSelection') && !matchScopes(this.editor.element, getConfig('highlightSelectionExcludeScopes')) && text.length >= getConfig('highlightSelectionMinimumLength') && !/\n/.test(text) && /\S/.test(text) ) } highlightSelection (selection) { this.clearSelectionHighlight() const keyword = selection.getText() if (this.needSelectionHighlight(keyword)) { this.markerLayerForSelectionHighlight = this.highlight(keyword, 'box-selection') } } clearSelectionHighlight () { if (this.markerLayerForSelectionHighlight) this.markerLayerForSelectionHighlight.destroy() this.markerLayerForSelectionHighlight = null } highlight (keyword, color) { const markerLayer = this.editor.addMarkerLayer() this.editor.decorateMarkerLayer(markerLayer, {type: 'highlight', class: `auto-highlight ${color}`}) const regex = new RegExp(`${_.escapeRegExp(keyword)}`, 'g') this.editor.scan(regex, ({range}) => markerLayer.markBufferRange(range, {invalidate: 'inside'})) if (markerLayer.getMarkerCount()) { this.emitter.emit('did-change-highlight', { editor: this.editor, markers: markerLayer.getMarkers(), color: color }) } return markerLayer } getDiff () { const masterKeywords = this.keywordManager.getKeywords() const currentKeywords = [...this.markerLayerByKeyword.keys()] const newKeywords = _.without(masterKeywords, ...currentKeywords) const oldKeywords = _.without(currentKeywords, ...masterKeywords) if (newKeywords.length || oldKeywords.length) { return {newKeywords, oldKeywords} } } render ({newKeywords, oldKeywords}) { // Delete for (const keyword of oldKeywords) { this.markerLayerByKeyword.get(keyword).destroy() this.markerLayerByKeyword.delete(keyword) } // Add for (const keyword of newKeywords) { const color = this.keywordManager.getColorForKeyword(keyword) if (color) { const decorationColor = atom.config.get('auto-highlight.decorate') const markerLayer = this.highlight(keyword, `${decorationColor}-${color}`) this.markerLayerByKeyword.set(keyword, markerLayer) } } } clear () { this.markerLayerByKeyword.forEach(layer => layer.destroy()) this.markerLayerByKeyword.clear() } refresh () { const diff = this.getDiff() if (diff) { this.render(diff) } this.updateStatusBarIfNecesssary() } updateStatusBarIfNecesssary () { if (getConfig('displayCountOnStatusBar') && isActiveEditor(this.editor)) { this.statusBarManager.clear() const keyword = this.keywordManager.latestKeyword const layer = this.markerLayerByKeyword.get(keyword) const count = layer ? layer.getMarkerCount() : 0 if (count) this.statusBarManager.update(count) } } destroy () { this.disposables.dispose() this.clear() this.clearSelectionHighlight() QuickHighlightView.unregister(this) } }
JavaScript
class File extends FileBase { constructor(options) { super(options); var fileSprite = new PIXI.Sprite(PIXI.Texture.fromImage("assets/file.png")); fileSprite.anchor.set(0.5); this.damageSprites = new PIXI.Container(); _.each(_.range(1, 10), (i) => { var sprite = new PIXI.Sprite(PIXI.Texture.fromImage("assets/dmg_" + i + ".png")); sprite.visible = false; sprite.anchor.set(0.5); this.damageSprites.addChild(sprite); }); var text = new PIXI.Text(options.name,{fontFamily : 'Arial', fontSize: 10, fill : 'white', align : 'center', stroke: 'black', strokeThickness: 2}); text.anchor.set(0.5); text.position.y = 40; this.addChild(fileSprite); this.addChild(text); this.addChild(this.damageSprites); this.state = { hitpoints: 10 } } /* Update graphics of the file */ gfxTick() { _.each(this.damageSprites.children, (sprite, i) => { sprite.visible = false; if (9 - this.state.hitpoints === i) { sprite.visible = true; } }) } /* Check if the file should be destroyed (if it's HP is lower or equal to zero) Returns true if the file was destroyed; false otherwise. */ lifetimeTick(delta) { if (this.state.hitpoints <= 0) { this.destroy(); return true; } return false; } /* Register a hit on this file */ registerHit() { this.state.hitpoints -= 1; } getHitboxSize() { return {width: 30, height: 20} } }
JavaScript
class Cocoon { constructor(container, options={}) { this.container = this.getNodeFromOption(container, false) if (!this.container) throw new Error('Container selector string or element must be supplied') // Start options this.addFieldsLink = this.getNodeFromOption(options.addFieldsLink, this.container.querySelector('.add_fields')) if (!this.addFieldsLink) throw new Error('Cannot find link to add fields. Make sure your `addFieldsLink` option or `link_to_add_association` is correct.') this.insertionNode = this.getNodeFromOption(options.insertionNode, this.addFieldsLink.parentNode) if (!this.insertionNode) throw new Error('Cannot find the element to insert the template. Make sure your `insertionNode` option is correct.') this.insertionFunction = options.insertionFunction || function(refNode, content) { refNode.insertAdjacentHTML('beforebegin', content) return refNode.previousElementSibling } this.removeWrapperClass = options.removeWrapperClass || 'nested-fields' this.addCount = Math.max(parseInt(options.addCount), 1) || 1 this.removeTimeout = Math.max(parseInt(options.removeTimeout), 0) || 0 this.beforeInsert = options.beforeInsert this.afterInsert = options.afterInsert this.beforeRemove = options.beforeRemove this.afterRemove = options.afterRemove // End options // Build regexs to edit content of template later var associationRegex = `(?:${this.addFieldsLink.getAttribute('data-associations')}|${this.addFieldsLink.getAttribute('data-association')})` this.regexId = new RegExp(`_new_${associationRegex}_(\\w*)`, 'g') this.regexParam = new RegExp(`\\[new_${associationRegex}\\](.*?\\s)`, 'g') this.insertionTemplate = this.addFieldsLink.getAttribute('data-association-insertion-template') this.elementCount = 0 this.attachEventListeners() } getNodeFromOption(option, defaultOpt) { if (!option) return defaultOpt if (typeof option == 'string') return document.querySelector(option) else return option } replaceContent(content) { var id = new Date().getTime() + this.elementCount++ var newContent = content.replace(this.regexId, `_${id}_$1`) newContent = newContent.replace(this.regexParam, `[${id}]$1`) return newContent } addFields(e) { e.preventDefault() var html, newNode for (var i = 0; i < this.addCount; i++) { html = this.replaceContent(this.insertionTemplate) if (typeof this.beforeInsert == 'function') html = this.beforeInsert(html) if (!html) return newNode = this.insertionFunction(this.insertionNode, html) if (typeof this.afterInsert == 'function') { if (newNode instanceof HTMLElement) this.afterInsert(newNode) else throw new Error('Cannot run `afterInsert`, please check that your `insertionFunction` returns a DOM element') } } } findNodeToRemove(el) { var toRemove = el.parentNode while (!toRemove.classList.contains(this.removeWrapperClass)) { toRemove = toRemove.parentNode if (!toRemove) { throw new Error('Cannot find element to remove, please check `removeWrapperClass` configuration') } } return toRemove } removeFields(e) { var removeLink = e.target var toRemove = this.findNodeToRemove(removeLink) e.preventDefault() e.stopPropagation() var container = toRemove.parentNode if (typeof this.beforeRemove == 'function') { var result = this.beforeRemove(toRemove) if (!result && typeof result == 'boolean') return } setTimeout(() => { if (removeLink.classList.contains('dynamic')) container.removeChild(toRemove) else { var input = removeLink.previousSibling if (input.matches('input[type="hidden"]')) input.value = '1' toRemove.style.display = 'none' } if (typeof this.afterRemove == 'function') this.afterRemove(toRemove) }, this.removeTimeout) } attachEventListeners() { document.addEventListener('click', (e) => { if (e.target.classList.contains('add_fields')) this.addFields(e) else if (e.target.classList.contains('remove_fields')) this.removeFields(e) }) var _this = this; var removeFunc = function() { [...document.querySelectorAll('.remove_fields.existing.destroyed')].forEach(function(el) { var removed = _this.findNodeToRemove(el) removed.style.display = 'none' }) } document.addEventListener('DOMContentLoaded', removeFunc) document.addEventListener('turbolinks:load', removeFunc) } }
JavaScript
class CharUtils { constructor() { } static __static_initialize() { if (!CharUtils.__static_initialized) { CharUtils.__static_initialized = true; CharUtils.__static_initializer_0(); } } static CHAR_STRING_ARRAY_$LI$() { CharUtils.__static_initialize(); if (CharUtils.CHAR_STRING_ARRAY == null) { CharUtils.CHAR_STRING_ARRAY = (s => { let a = []; while (s-- > 0) a.push(null); return a; })(128); } return CharUtils.CHAR_STRING_ARRAY; } static CHAR_ARRAY_$LI$() { CharUtils.__static_initialize(); if (CharUtils.CHAR_ARRAY == null) { CharUtils.CHAR_ARRAY = (s => { let a = []; while (s-- > 0) a.push(null); return a; })(128); } return CharUtils.CHAR_ARRAY; } static __static_initializer_0() { for (let i = 127; i >= 0; i--) { { CharUtils.CHAR_STRING_ARRAY_$LI$()[i] = CharUtils.CHAR_STRING.substring(i, i + 1); CharUtils.CHAR_ARRAY_$LI$()[i] = new String(String.fromCharCode(i)); } ; } } static toCharacterObject$char(ch) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) < CharUtils.CHAR_ARRAY_$LI$().length) { return CharUtils.CHAR_ARRAY_$LI$()[(ch).charCodeAt(0)]; } return new String(ch); } static toCharacterObject$java_lang_String(str) { if (org.openprovenance.apache.commons.lang.StringUtils.isEmpty(str)) { return null; } return CharUtils.toCharacterObject$char(str.charAt(0)); } /** * <p>Converts the String to a Character using the first character, returning * null for empty Strings.</p> * * <p>For ASCII 7 bit characters, this uses a cache that will return the * same Character object each time.</p> * * <pre> * CharUtils.toCharacterObject(null) = null * CharUtils.toCharacterObject("") = null * CharUtils.toCharacterObject("A") = 'A' * CharUtils.toCharacterObject("BA") = 'B' * </pre> * * @param {string} str the character to convert * @return {string} the Character value of the first letter of the String */ static toCharacterObject(str) { if (((typeof str === 'string') || str === null)) { return org.openprovenance.apache.commons.lang.CharUtils.toCharacterObject$java_lang_String(str); } else if (((typeof str === 'string') || str === null)) { return org.openprovenance.apache.commons.lang.CharUtils.toCharacterObject$char(str); } else throw new Error('invalid overload'); } static toChar$java_lang_Character(ch) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) == null) { throw Object.defineProperty(new Error("The Character must not be null"), '__classes', { configurable: true, value: ['java.lang.Throwable', 'java.lang.Object', 'java.lang.RuntimeException', 'java.lang.IllegalArgumentException', 'java.lang.Exception'] }); } return /* charValue */ ch; } static toChar$java_lang_Character$char(ch, defaultValue) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) == null) { return defaultValue; } return /* charValue */ ch; } /** * <p>Converts the Character to a char handling <code>null</code>.</p> * * <pre> * CharUtils.toChar(null, 'X') = 'X' * CharUtils.toChar(' ', 'X') = ' ' * CharUtils.toChar('A', 'X') = 'A' * </pre> * * @param {string} ch the character to convert * @param {string} defaultValue the value to use if the Character is null * @return {string} the char value of the Character or the default if null */ static toChar(ch, defaultValue) { if (((typeof ch === 'string') || ch === null) && ((typeof defaultValue === 'string') || defaultValue === null)) { return org.openprovenance.apache.commons.lang.CharUtils.toChar$java_lang_Character$char(ch, defaultValue); } else if (((typeof ch === 'string') || ch === null) && ((typeof defaultValue === 'string') || defaultValue === null)) { return org.openprovenance.apache.commons.lang.CharUtils.toChar$java_lang_String$char(ch, defaultValue); } else if (((typeof ch === 'string') || ch === null) && defaultValue === undefined) { return org.openprovenance.apache.commons.lang.CharUtils.toChar$java_lang_Character(ch); } else if (((typeof ch === 'string') || ch === null) && defaultValue === undefined) { return org.openprovenance.apache.commons.lang.CharUtils.toChar$java_lang_String(ch); } else throw new Error('invalid overload'); } static toChar$java_lang_String(str) { if (org.openprovenance.apache.commons.lang.StringUtils.isEmpty(str)) { throw Object.defineProperty(new Error("The String must not be empty"), '__classes', { configurable: true, value: ['java.lang.Throwable', 'java.lang.Object', 'java.lang.RuntimeException', 'java.lang.IllegalArgumentException', 'java.lang.Exception'] }); } return str.charAt(0); } static toChar$java_lang_String$char(str, defaultValue) { if (org.openprovenance.apache.commons.lang.StringUtils.isEmpty(str)) { return defaultValue; } return str.charAt(0); } static toIntValue$char(ch) { if (CharUtils.isAsciiNumeric(ch) === false) { throw Object.defineProperty(new Error("The character " + ch + " is not in the range \'0\' - \'9\'"), '__classes', { configurable: true, value: ['java.lang.Throwable', 'java.lang.Object', 'java.lang.RuntimeException', 'java.lang.IllegalArgumentException', 'java.lang.Exception'] }); } return (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) - 48; } static toIntValue$char$int(ch, defaultValue) { if (CharUtils.isAsciiNumeric(ch) === false) { return defaultValue; } return (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) - 48; } static toIntValue$java_lang_Character(ch) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) == null) { throw Object.defineProperty(new Error("The character must not be null"), '__classes', { configurable: true, value: ['java.lang.Throwable', 'java.lang.Object', 'java.lang.RuntimeException', 'java.lang.IllegalArgumentException', 'java.lang.Exception'] }); } return CharUtils.toIntValue$char(/* charValue */ ch); } static toIntValue$java_lang_Character$int(ch, defaultValue) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) == null) { return defaultValue; } return CharUtils.toIntValue$char$int(/* charValue */ ch, defaultValue); } /** * <p>Converts the character to the Integer it represents, throwing an * exception if the character is not numeric.</p> * * <p>This method coverts the char '1' to the int 1 and so on.</p> * * <pre> * CharUtils.toIntValue(null, -1) = -1 * CharUtils.toIntValue('3', -1) = 3 * CharUtils.toIntValue('A', -1) = -1 * </pre> * * @param {string} ch the character to convert * @param {number} defaultValue the default value to use if the character is not numeric * @return {number} the int value of the character */ static toIntValue(ch, defaultValue) { if (((typeof ch === 'string') || ch === null) && ((typeof defaultValue === 'number') || defaultValue === null)) { return org.openprovenance.apache.commons.lang.CharUtils.toIntValue$java_lang_Character$int(ch, defaultValue); } else if (((typeof ch === 'string') || ch === null) && ((typeof defaultValue === 'number') || defaultValue === null)) { return org.openprovenance.apache.commons.lang.CharUtils.toIntValue$char$int(ch, defaultValue); } else if (((typeof ch === 'string') || ch === null) && defaultValue === undefined) { return org.openprovenance.apache.commons.lang.CharUtils.toIntValue$java_lang_Character(ch); } else if (((typeof ch === 'string') || ch === null) && defaultValue === undefined) { return org.openprovenance.apache.commons.lang.CharUtils.toIntValue$char(ch); } else throw new Error('invalid overload'); } static toString$char(ch) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) < 128) { return CharUtils.CHAR_STRING_ARRAY_$LI$()[(ch).charCodeAt(0)]; } return [ch].join(''); } static toString$java_lang_Character(ch) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) == null) { return null; } return CharUtils.toString$char(/* charValue */ ch); } /** * <p>Converts the character to a String that contains the one character.</p> * * <p>For ASCII 7 bit characters, this uses a cache that will return the * same String object each time.</p> * * <p>If <code>null</code> is passed in, <code>null</code> will be returned.</p> * * <pre> * CharUtils.toString(null) = null * CharUtils.toString(' ') = " " * CharUtils.toString('A') = "A" * </pre> * * @param {string} ch the character to convert * @return {string} a String containing the one specified character */ static toString(ch) { if (((typeof ch === 'string') || ch === null)) { return org.openprovenance.apache.commons.lang.CharUtils.toString$java_lang_Character(ch); } else if (((typeof ch === 'string') || ch === null)) { return org.openprovenance.apache.commons.lang.CharUtils.toString$char(ch); } else throw new Error('invalid overload'); } static unicodeEscaped$char(ch) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) < 16) { return "\\u000" + javaemul.internal.IntegerHelper.toHexString(ch); } else if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) < 256) { return "\\u00" + javaemul.internal.IntegerHelper.toHexString(ch); } else if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) < 4096) { return "\\u0" + javaemul.internal.IntegerHelper.toHexString(ch); } return "\\u" + javaemul.internal.IntegerHelper.toHexString(ch); } static unicodeEscaped$java_lang_Character(ch) { if ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) == null) { return null; } return CharUtils.unicodeEscaped$char(/* charValue */ ch); } /** * <p>Converts the string to the unicode format ' '.</p> * * <p>This format is the Java source code format.</p> * * <p>If <code>null</code> is passed in, <code>null</code> will be returned.</p> * * <pre> * CharUtils.unicodeEscaped(null) = null * CharUtils.unicodeEscaped(' ') = " " * CharUtils.unicodeEscaped('A') = "A" * </pre> * * @param {string} ch the character to convert, may be null * @return {string} the escaped unicode string, null if null input */ static unicodeEscaped(ch) { if (((typeof ch === 'string') || ch === null)) { return org.openprovenance.apache.commons.lang.CharUtils.unicodeEscaped$java_lang_Character(ch); } else if (((typeof ch === 'string') || ch === null)) { return org.openprovenance.apache.commons.lang.CharUtils.unicodeEscaped$char(ch); } else throw new Error('invalid overload'); } /** * <p>Checks whether the character is ASCII 7 bit.</p> * * <pre> * CharUtils.isAscii('a') = true * CharUtils.isAscii('A') = true * CharUtils.isAscii('3') = true * CharUtils.isAscii('-') = true * CharUtils.isAscii('\n') = true * CharUtils.isAscii('&copy;') = false * </pre> * * @param {string} ch the character to check * @return {boolean} true if less than 128 */ static isAscii(ch) { return (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) < 128; } /** * <p>Checks whether the character is ASCII 7 bit printable.</p> * * <pre> * CharUtils.isAsciiPrintable('a') = true * CharUtils.isAsciiPrintable('A') = true * CharUtils.isAsciiPrintable('3') = true * CharUtils.isAsciiPrintable('-') = true * CharUtils.isAsciiPrintable('\n') = false * CharUtils.isAsciiPrintable('&copy;') = false * </pre> * * @param {string} ch the character to check * @return {boolean} true if between 32 and 126 inclusive */ static isAsciiPrintable(ch) { return (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= 32 && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) < 127; } /** * <p>Checks whether the character is ASCII 7 bit control.</p> * * <pre> * CharUtils.isAsciiControl('a') = false * CharUtils.isAsciiControl('A') = false * CharUtils.isAsciiControl('3') = false * CharUtils.isAsciiControl('-') = false * CharUtils.isAsciiControl('\n') = true * CharUtils.isAsciiControl('&copy;') = false * </pre> * * @param {string} ch the character to check * @return {boolean} true if less than 32 or equals 127 */ static isAsciiControl(ch) { return (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) < 32 || (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) == 127; } /** * <p>Checks whether the character is ASCII 7 bit alphabetic.</p> * * <pre> * CharUtils.isAsciiAlpha('a') = true * CharUtils.isAsciiAlpha('A') = true * CharUtils.isAsciiAlpha('3') = false * CharUtils.isAsciiAlpha('-') = false * CharUtils.isAsciiAlpha('\n') = false * CharUtils.isAsciiAlpha('&copy;') = false * </pre> * * @param {string} ch the character to check * @return {boolean} true if between 65 and 90 or 97 and 122 inclusive */ static isAsciiAlpha(ch) { return ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= 'A'.charCodeAt(0) && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) <= 'Z'.charCodeAt(0)) || ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= 'a'.charCodeAt(0) && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) <= 'z'.charCodeAt(0)); } /** * <p>Checks whether the character is ASCII 7 bit alphabetic upper case.</p> * * <pre> * CharUtils.isAsciiAlphaUpper('a') = false * CharUtils.isAsciiAlphaUpper('A') = true * CharUtils.isAsciiAlphaUpper('3') = false * CharUtils.isAsciiAlphaUpper('-') = false * CharUtils.isAsciiAlphaUpper('\n') = false * CharUtils.isAsciiAlphaUpper('&copy;') = false * </pre> * * @param {string} ch the character to check * @return {boolean} true if between 65 and 90 inclusive */ static isAsciiAlphaUpper(ch) { return (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= 'A'.charCodeAt(0) && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) <= 'Z'.charCodeAt(0); } /** * <p>Checks whether the character is ASCII 7 bit alphabetic lower case.</p> * * <pre> * CharUtils.isAsciiAlphaLower('a') = true * CharUtils.isAsciiAlphaLower('A') = false * CharUtils.isAsciiAlphaLower('3') = false * CharUtils.isAsciiAlphaLower('-') = false * CharUtils.isAsciiAlphaLower('\n') = false * CharUtils.isAsciiAlphaLower('&copy;') = false * </pre> * * @param {string} ch the character to check * @return {boolean} true if between 97 and 122 inclusive */ static isAsciiAlphaLower(ch) { return (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= 'a'.charCodeAt(0) && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) <= 'z'.charCodeAt(0); } /** * <p>Checks whether the character is ASCII 7 bit numeric.</p> * * <pre> * CharUtils.isAsciiNumeric('a') = false * CharUtils.isAsciiNumeric('A') = false * CharUtils.isAsciiNumeric('3') = true * CharUtils.isAsciiNumeric('-') = false * CharUtils.isAsciiNumeric('\n') = false * CharUtils.isAsciiNumeric('&copy;') = false * </pre> * * @param {string} ch the character to check * @return {boolean} true if between 48 and 57 inclusive */ static isAsciiNumeric(ch) { return (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= '0'.charCodeAt(0) && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) <= '9'.charCodeAt(0); } /** * <p>Checks whether the character is ASCII 7 bit numeric.</p> * * <pre> * CharUtils.isAsciiAlphanumeric('a') = true * CharUtils.isAsciiAlphanumeric('A') = true * CharUtils.isAsciiAlphanumeric('3') = true * CharUtils.isAsciiAlphanumeric('-') = false * CharUtils.isAsciiAlphanumeric('\n') = false * CharUtils.isAsciiAlphanumeric('&copy;') = false * </pre> * * @param {string} ch the character to check * @return {boolean} true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive */ static isAsciiAlphanumeric(ch) { return ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= 'A'.charCodeAt(0) && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) <= 'Z'.charCodeAt(0)) || ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= 'a'.charCodeAt(0) && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) <= 'z'.charCodeAt(0)) || ((c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) >= '0'.charCodeAt(0) && (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) <= '9'.charCodeAt(0)); } /** * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit * that is used for representing supplementary characters in UTF-16 * encoding. * * @param {string} ch * the character to test. * @return {boolean} {@code true} if {@code ch} is a high-surrogate code unit; * {@code false} otherwise. */ static isHighSurrogate(ch) { return ('\ud800'.charCodeAt(0) <= (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch) && '\udbff'.charCodeAt(0) >= (c => c.charCodeAt == null ? c : c.charCodeAt(0))(ch)); } }
JavaScript
class Foundation extends EventSystem { #_schemas #_name #_dataStrategy #_started #_models #_guid #_useWorker #_workers #_tabId constructor ({ name = 'My Foundation Name', dataStrategy = 'offline', useWorker = false, schemas }) { super() this.#_name = name this.#_dataStrategy = dataStrategy this.#_useWorker = useWorker this.#_schemas = schemas this.#_started = false this.#_guid = uuid() this.#_models = {} this.#_useWorker = useWorker || false this.#_workers = {} this.localDatabaseTransport = new LocalDatabaseTransport({ dbName: genDbName(name) }) this.#_tabId = uuid() // assume new Id on every refresh } /** * @member {getter} Foundation.dataStrategy * @Description Get the data strategy being used.<br> Possible values are: offlineFirst, onlineFirst, offline, online. <br> Default: offlineFirst * @example console.log(Foundation.dataStrategy) * @return {string} this.#_dataStrategy */ get dataStrategy () { return this.#_dataStrategy } /** * @member {getter} Foundation.guid * @description Get the Foundation Session guid currently being used. * @example console.log(Foundation.guid) */ get guid () { return this.#_guid } /** * @member {getter} Foundation.data * @description Get the Foundation data API(DataEntity) * @example const { User, Product } = foundation.data const Eduardo = await User.add({ name: 'Eduardo Almeida', username: 'web2' }) console.debug(Eduardo) // { // data: {__id: 1, _id: "600e0ae8d9d7f50000e1444b", name: "Eduardo Almeida", username: "web2", id: "600e0ae8d9d7f50000e1444b"} // error: null // } */ get data() { return this.#_models } /** * @member {getter} Foundation.tabId * @description Get the Browser tab ID * @example console.log(foundation.tabId) */ get tabId() { return this.#_tabId } /** * @member {getter} Foundation.name * @name Foundation.name * @description Get the Foundation name * @example console.log(Foundation.name) */ get name () { return this.#_name } /** * @member {setter} Foundation.name * @name Foundation.name * @description Set the Foundation name * @example Foundation.name = 'Provide the name here' * @param {string} name - Foundation name */ set name (name) { this.#_name = name } /** * @member {getter} Foundation.started * @description Get the start state * @example console.log(Foundation.started) */ get started () { return this.#_started } /** * @memberof Foundation * @member {getter} Foundation.applicationWorker * @example Foundation.applicationWorker.postMessage() * @description Get the Foundation worker */ get applicationWorker() { return this.#_workers.foundation } /** * @Method Foundation.mapToDataEntityAPI * @summary Maps an Data Entity abstraction to foundation Data API * @description An Data Entity abstraction is an instance of the {@link DataEntity}. * Once it is mapped to foundation Data API, you can reach every Data Entity in the system from a single source point. * This method dont works as expected if you call it after {@link Foundation.start} method. * See {@link Foundation.importDataEntity} for usage further information. * @param {string} entity - Data Entity name * @param {dataEntity} dataEntity - An {@link DataEntity} instance */ mapToDataEntityAPI(entity, dataEntity) { let _error = null let _data = null // if call mapToDataEntityAPI('Product') more than once, it will ovewrite the previous set Product model this.#_models[entity] = dataEntity _data = this.#_models[entity] return createMethodSignature(_error, _data) } /** * @memberof Foundation * @member {getter} Foundation.Schema * @example new Foundation.Schema({}) * @description Creates new data schema * @returns schema creator */ static get Schema() { return Schema } /** * @Method Foundation.importDataEntity * @summary Alias to Foundation.mapToDataEntityAPI(entity = '', dataEntity = {}) * @description An Data Entity abstraction is an instance of the {@link DataEntity}. * Once it is mapped to foundation Data API, you can reach every Data Entity in the system from a single source point. * This method dont works as expected if you call it after {@link Foundation.start} method * @param {object} spec - Data Entity abstraction specification * @param {string} spec.entity - Data Entity name * @param {dataEntity} spec.dataEntity - An {@link DataEntity} instance for the entity defined on `spec.entity` * @example const productSchema = new Foundation.Schema({ name: { type: String, required: true, index: true }, vendor: { type: String, required: true, index: true }, price: { type: Number, required: true, index: true } }) // start the foundation const foundation = new Foundation({ name: 'My Test app', schemas: { // Customer: schema } }) // Build a customized Data Entity abstraction const MyCustomizedDataEntity = class extends DataEntity { constructor (config) { super(config) } sell (primaryKey, orderId) { // primaryKey is Product primary key value // orderId is the primaryKey of an Order // const foundOrder = await Order.findById(orderId) // if (foundOrder.error) { // CAN NOT TO SELL // } // const items = foundOrder.data.lineItems.filter(i => (i.productId === primaryKey)) // If Order has the product listed item // if(items[0]) // { // await this.delete(primaryKey) // deletes a Product from Products // } } } // instance of the custimized Data Entity const productDataEntity = new MyCustomizedDataEntity({ foundation, entity: 'Product', schema: productSchema }) // import data entity foundation.importDataEntity({ entity: 'Product', dataEntity: productDataEntity }) // start the foundation await foundation.start() // you can now do things like: const { Product } = foundation.data await Product.add({ name: 'Big Mac', vendor: 'McDonalds', price: 3 }) */ importDataEntity({ entity, dataEntity}) { this.mapToDataEntityAPI(entity, dataEntity) } #mapModels(schemas) { let _error = null let _data = null for (const entity in schemas) { if (Object.prototype.hasOwnProperty.call(schemas, entity)) { // console.debug('for (const entity in schemas)', entity) const strategy = 'offlineFirst' const schema = schemas[entity] const dataEntity = new DataEntity({ foundation: this, entity, strategy, schema }) this.mapToDataEntityAPI(entity, dataEntity) } } // _data = this.#_models // return createMethodSignature(_error, _data) } /** * @member {getter} Foundation.useWorker * @Description flag if is there ServiceWorker being used * @return {boolean} */ get useWorker () { return this.#_useWorker } /** * @Method Foundation.setGuidStorage * @description save Foundation uuid to localStorage * @param {string} guid * @return Foundation uuid saved on localStorage */ setGuidStorage (guid) { window.localStorage.setItem('guid', guid) return window.localStorage.getItem('guid') } /** * @Method Foundation.setupAppGuid * @description check if Foundation has a uuid saved o * @return Foundation uuid saved on localStorage */ setupAppGuid () { const guidCache = window.localStorage.getItem('guid') || false if (guidCache) { this.#_guid = guidCache } else { this.setGuidStorage(this.#_guid) } return window.localStorage.getItem('guid') } /** * @async * @Method Foundation.#registerApplicationWorker * @description Setup and Register the main Service worker used by foundation core * @return {object} signature - Default methods signature format { error, data } * @return {string|object} signature.error - Execution error * @return {object} signature.data - Worker Registration Object */ /* #registerApplicationWorker (workerFile = 'ServiceWorker.js') { const self = this return new Promise((resolve, reject) => { if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/' + workerFile, { // scope: '/' }) .then(function (reg) { // registration worked navigator.serviceWorker.addEventListener('message', workerOnMessage.bind(self)) if (reg.installing) { self.#_workers['foundation'] = reg.installing self.#_workers['foundation'].postMessage({ cmd: 'getClientId', message: null }) } else if (reg.active) { self.#_workers['foundation'] = reg.active self.#_workers['foundation'].postMessage({ cmd: 'getClientId', message: null }) } resolve(createMethodSignature(null, reg)) }) .catch(function (error) { // registration failed resolve(createMethodSignature(error, null)) }) } }) } */ /** * @async * @Method Foundation.#registerWorker * @description Setup and Register a Service worker and get it ready for usage into your application scope * @param {string} name - Worker name. Used to access it from the namespace * @param {string} workerFile - Worker file name * @return {object} signature - Default methods signature format { error, data } * @return {string|object} signature.error - Execution error * @return {object} signature.data - Worker Registration Object */ /* #registerWorker (name = '', workerFile = 'ServiceWorker.js') { const self = this return new Promise((resolve, reject) => { if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/' + workerFile, { // scope: '/' }) .then(function (reg) { // registration worked navigator.serviceWorker.addEventListener('message', workerOnMessage.bind(self)) if (reg.installing) { self.#_workers[name] = reg.installing self.#_workers[name].postMessage({ cmd: 'getClientId', message: null }) } else if (reg.active) { self.#_workers[name] = reg.active self.#_workers[name].postMessage({ cmd: 'getClientId', message: null }) } resolve(createMethodSignature(null, reg)) }) .catch(function (error) { // registration failed resolve(createMethodSignature(error, null)) }) } }) } */ /** * @async * @Method Foundation.start * @description Starts foundation stack and get it ready to use. <br> it calls this.#startVitals() internally * @return {object} signature - Default methods signature format { error, data } * @return {string|object} signature.error - Execution error * @return {object} signature.data - Foundation data */ async start () { let _error = null let _data = null try { this.setupAppGuid() const mapModels = this.#mapModels(this.#_schemas) const connection = await this.localDatabaseTransport.connect() if (connection.error) { _error = connection.error } else { this.#_started = true _data = { status: { mapModels, connection }, started: this.#_started } } } catch (error) { _error = error _data = null } this.triggerEvent('foundation:start', { foundation: this, error: _error, data: _data }) // console.warn('STARTED>>>>>>>>>>>', this) return createMethodSignature(_error, _data) } }
JavaScript
class SceneManager { /** * Create a new SceneManager */ constructor() { this.stack = []; } /** * Add a a single entity or an array of entities to the scene to be rendered. * @param {Entity | Entity[]} entity * @return {SceneManager} Returns the instance of the SceneManager. */ push(entity) { if (Array.isArray(entity)) { this.stack = this.stack.concat(entity); } else { this.stack.push(entity); } return this; } /** * Pop the next entity off the scene's stack. * @returns {Entity} The next entity to render. */ nextEntity() { return this.stack.shift(); } /** * Determine if the stack is empty or not. * @returns {boolean} */ fullyRendered() { return !(this.stack.length > 0); } /** * Removes all entities from the stack. */ clear() { this.stack = []; } getStack() { return this.stack; } serializeStack() { return JSON.stringify(this.stack); } }
JavaScript
class KuzzleDocumentEntity { /** * Convert Kuzzle document into GeoJSON * @param KuzzleDocument document * @returns {*} */ fromDocumentToFeature(document) { let dataGeoJson = {}; if (document) { let datasGeometry = document.content.location; let dataProperties = document.content.fields; dataGeoJson = { "id": document.id, 'type': 'Feature', 'geometry': datasGeometry, 'properties': dataProperties }; } return dataGeoJson; } /** * Transform a feature into a kuzzle document */ fromFeatureToDocument() { } }