language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class RuleRegion extends RuleBase { name = 'region'; isUniques = true; constructor(cells, size) { assert.ok(cells.length === size, 'A Region must contain all used symbols once each; to use an Incomplete Region, use a Killer Cage instead'); super(cells); } }
JavaScript
class RuleOdd extends RuleBase { name = 'odd'; isSum = true; sum = n => n % 2 === 1; constructor(cells) { super(cells); } }
JavaScript
class RuleEven extends RuleBase { name = 'even'; isSum = true; sum = n => n % 2 === 0; constructor(cells) { super(cells); } }
JavaScript
class RuleThermometer extends RuleBase { name = 'thermometer'; isRelation; relation = (a, b) => a < b; constructor(cells) { super(cells); } }
JavaScript
class RulePalindrome extends RuleBase { name = 'palindrome'; constructor(cells) { super(cells); } check() { return this.cellValues.every((value, i) => value === this.cellValues[this.cellValues.length - 1 - i]); } }
JavaScript
class RuleKillerCage extends RuleBase { name = 'killer-cage'; isUniques = true; isSum = true; sum; constructor(cells, sum) { super(cells); this.sum = sum; } }
JavaScript
class RuleLittleKiller extends RuleBase { name = 'little-killer'; isSum = true; sum; constructor(cells, sum) { super(cells); this.sum = sum; } }
JavaScript
class RuleSandwich extends RuleBase { name = 'sandwich'; minSymbol = undefined; maxSymbol = undefined; sum; constructor(cells, minSymbol, maxSymbol, sum) { assert.ok(cells.length >= 2, 'A sandwich requires at least two cells for the crust, even if the contents are empty'); super(cells); this.minSymbol = minSymbol; this.maxSymbol = maxSymbol; this.sum = sum; } check() { const min = this.cellValues.indexOf(this.minSymbol); const max = this.cellValues.indexOf(this.maxSymbol); const sum = this.cellValues.slice(Math.min(min, max) + 1, Math.max(min, max)).reduce((acc, cell) => acc + cell, 0); return sum === this.sum; } }
JavaScript
class RuleDifference extends RuleBase { name = 'difference'; isRelation = true; relation = (a, b) => a - b === this.difference || b - a === this.difference; difference; constructor(cells, difference) { super(cells); this.difference = difference; } }
JavaScript
class RuleRatio extends RuleBase { name = 'ratio'; isRelation = true; relation = (a, b) => a * this.ratio === b || b * this.ratio === a; ratio; constructor(cells, difference) { super(cells); this.ratio = difference; } }
JavaScript
class RuleClone extends RuleBase { name = 'clone'; constructor(cells) { assert.ok(cells.length > 1 && cells.every(clone => clone.length === cells[0].length), 'A clone is defined as multiple separate groups of cells, all of the same size'); super(cells); } check() { return this.cellValues.every(clone => clone.every((cell, i) => cell === this.cellValues[0][i])); } }
JavaScript
class RuleArrow extends RuleBase { name = 'arrow'; isSum = true; sum = n => n === 2 * this.cellValues[0]; constructor(cells) { super(cells); } }
JavaScript
class RuleBetweenLine extends RuleBase { name = 'between-line'; constructor(cells) { assert.ok(cells.length >= 2, 'A between line requires at least two cells for the delimiter circles, line itself is empty'); super(cells); } check() { const left = this.cellValues[0]; const right = this.cellValues[this.cellValues.length - 1]; return this.cellValues.slice(1, -1).every((cell, i) => Math.min(left, right) < cell && cell < Math.max(left, right)); } }
JavaScript
class RuleMinimum extends RuleBase { name = 'minimum'; constructor(cells) { super(cells); } check() { return this.cellValues.slice(1).every(cell => this.cellValues[0] < cell); } }
JavaScript
class RuleMaximum extends RuleBase { name = 'maximum'; constructor(cells) { super(cells); } check() { return this.cellValues.slice(1).every(cell => this.cellValues[0] > cell); } }
JavaScript
class RuleXV extends RuleBase { name = 'xv'; isSum = true; constructor(cells, sum) { super(cells); this.sum = sum; } }
JavaScript
class RuleQuadruple extends RuleBase { name = 'quadruple'; constructor(cells, quadruple) { assert.ok(cells.length <= 4 && quadruple.length <= cells.length, 'By design, a quadruple can only span up to four cells and cannot contain more digits than it spans cells'); super(cells); this.quadruple = quadruple; } check() { return this.quadruple.every(quad => this.cellValues.includes(quad)); } }
JavaScript
class Videos extends Component { constructor(props) { super(props); this.state = { isAuthorized: false, playlistName: null, playlistId: props.match.params.playlistid, videos: null, playlists: null, moveToPlaylistId: null, filter: '', videosLoading: false, }; } static getDerivedStateFromProps(props, state) { if (props.isAuthorized !== state.isAuthorized) { return { isAuthorized: props.isAuthorized, }; } // No state update necessary return null; } componentDidMount() { if (this.state.isAuthorized) this.refresh(); } componentDidUpdate(prevProps, prevState) { if (!this.state.isAuthorized) return; if (this.state.playlistName === null) { // Only retrieve data if state.playlistName is empty; otherwise this will generate an endless loop. this.retrievePlaylistName(); } if ( !this.state.videosLoading && this.state.playlistId && this.state.videos === null ) { this.retrieveVideos(); } if (this.state.playlists === null) { this.retrievePlaylists(); } } storePlaylists = data => { if (!data) return; let list = data.items; list.sort(snippetTitleSort); this.setState({ playlists: list }); }; storeVideos = (data, currentToken) => { if (!data) return; let list = data.items; list.sort(snippetTitleSort); if (currentToken === undefined || !currentToken) { this.setState({ videos: list }); } else { this.setState(prevState => ({ videos: [...prevState.videos, ...list] })); } if (data.nextPageToken) { this.retrieveVideos(data.nextPageToken); } }; updatePlaylistName = playlistName => { this.setState({ playlistName }); }; retrievePlaylistName = () => { if (!this.state.playlistId) { return; } let req = buildPlaylistNameRequest(this.state.playlistId); if (!req) { console.warn('req is null'); return; } req.then( function(response) { try { this.updatePlaylistName( response.result.items[0].snippet.title ); } catch (e) { if (e instanceof TypeError) { console.log('buildPlaylistNameRequest incomplete response', e); } else { console.error('buildPlaylistNameRequest unexpected error', e); } } }, function() { // onRejected handler console.warn('buildPlaylistNameRequest rejected'); }, this ); }; retrieveVideos = nextPageToken => { this.setState({ videosLoading: true }); executeRequest( buildPlaylistItemsRequest(this.state.playlistId, nextPageToken), data => this.storeVideos(data, nextPageToken) ); }; retrievePlaylists = () => { executeRequest(buildPlaylistsRequest(), this.storePlaylists); }; removeFromPlaylistState = videoItemId => { let videos = this.state.videos; let i = videos.findIndex(function f(e) { return e.id === videoItemId; }); videos.splice(i, 1); this.setState({ videos }); }; removeError = error => { console.log('Videos.removeError', error.code, error.message); }; /** * Remove a video from the current playlist * @param videoItemId ID of the video-item in the current playlist */ remove = videoItemId => { if (!videoItemId) return; let request = buildApiRequest('DELETE', '/youtube/v3/playlistItems', { id: videoItemId, }); executeRequest( request, () => this.removeFromPlaylistState(videoItemId), this.removeError ); }; createError = error => { console.log('Videos.insertError', error); }; insertError = error => { console.log('Videos.insertError', error); }; move = (videoItemId, videoId, moveToPlaylistId) => { /* moveIntoPlaylist(videoItemId, videoId, moveToPlaylistId) .then(function(response) { console.log('movep.moveIntoPlaylist resolved', response); }) .catch(function(reason) { console.log( 'movep.moveIntoPlaylist rejected', reason, reason.result.error.message ); }); */ }; moveSuccess = ({ operation, data, videoId, videoItemId }) => { switch (operation) { case 'insert': break; case 'delete': this.removeFromPlaylistState(videoItemId); break; default: console.error(`moveSuccess: unknown operation ${operation}`); } }; moveFailure = r => { console.log('moveFailure', r); }; moveVisible = () => { let videoItemIds = []; let videoIds = []; this.state.videos .filter(video => video.snippet.title.toLowerCase().indexOf(this.state.filter.toLowerCase()) > -1) .forEach(video => { videoItemIds.push(video.id); if (!videoIds.includes(video.contentDetails.videoId)) { // avoid pushing duplicates videoIds.push(video.contentDetails.videoId); } }); moveMultipleIntoPlaylist( videoItemIds, videoIds, this.state.moveToPlaylistId, this.moveSuccess, this.moveFailure ); }; setMoveToList = event => { this.setState({ moveToPlaylistId: event.target.value }); }; updateFilter = event => { let f = event.target.value; this.setState({ filter: f }); }; refresh = (clearFilter = false) => { if (!this.state.isAuthorized) return; this.setState({ playlistName: null, videos: null, playlists: null, videosLoading: false, filter: clearFilter ? '' : this.state.filter, }); this.retrievePlaylistName(); this.retrieveVideos(); this.retrievePlaylists(); }; render() { const { isAuthorized, playlistId, playlistName, videos, playlists, moveToPlaylistId, filter, } = this.state; if (!isAuthorized) { return null; } else { if (videos) { let visibleVideos = videos.filter(video => video.snippet.title.toLowerCase().indexOf(filter.toLowerCase()) > -1); visibleVideos.sort(snippetTitleSort); return ( <div className="videos"> <h2>Videos in {playlistName} :</h2> <h3>{videos.length} videos</h3> <button onClick={this.refresh}>refresh</button> <div className="playlist-selector"> target playlist: {playlists && ( <select onChange={this.setMoveToList}> <option value=""> select list to move to </option> {playlists.map((p, i) => { return p.id === playlistId ? null : ( <option key={i} value={p.id}> {p.snippet.title} </option> ); })} </select> )} </div> {moveToPlaylistId && <div> <button onClick={this.moveVisible}> move visible to target playlist </button> </div> } <div className="filter"> filter: <input type="text" value={filter} onChange={this.updateFilter} /> </div> <div> { visibleVideos.map( (video, index) => { return ( <div key={index}> <a href={`https://www.youtube.com/watch?v=${video.contentDetails.videoId}`} target="_blank" rel="noopener noreferrer">{video.snippet.title}</a> {' '} <button onClick={() => this.remove(video.id)}>remove</button> {moveToPlaylistId && <button onClick={() => this.move(video.id, video.contentDetails.videoId, moveToPlaylistId)}>move</button> } </div> ); } ) } </div> </div> ); } else { return <div>Retrieving the list of videos...</div>; } } } }
JavaScript
class Store extends Directory { /** * Create a Store. * @param {string} name The CLI package name. * @return {Store} */ constructor(name) { super(path.join(CONFIG_DIR, name)); // create the store.json file for configurations. this.configFile = this.file('store.json'); if (!this.configFile.exists()) { this.configFile.writeJson({}); } this.config = this.configFile.readJson(); } /** * Get a shallow clone of the config object. * @return {Object} */ toJSON() { return JSON.parse(JSON.stringify(this.config)); } /** * Check if the store has a configuration set. * @param {string} path The object path to check. * @return {boolean} */ has(path) { return keypath.has(this.config, path); } /** * Get a configuration value. * @param {string} path The object path to retrieve. * @return {*} The actual value for the given path. */ get(path) { return keypath.get(this.config, path); } /** * Set a configuration value. * @param {string} path The object path to update. * @param {*} value The value to store. * @return {void} */ set(path, value) { keypath.set(this.config, path, value); this.configFile.writeJson(this.config); } /** * Remove a configuration value. * @param {string} path The object path to remove. * @return {void} */ remove(path) { keypath.del(this.config, path); this.configFile.writeJson(this.config); } }
JavaScript
class ClientSyncStateManager { constructor( clientOptions ) { this.socket = new SocketClient( clientOptions ); } updateState( update ) { this.socket.sendData( { action: CONSTANTS.WS_ACTIONS.CLIENT_STATE_UPDATE, type: CONSTANTS.WS_CLIENT_TYPE.CLIENT, update: update } ); } }
JavaScript
class PhraseBuilder { /** * @param {HTMLElement} container - the container for the phrase builder html * @param {Object} [options] */ constructor( container, options ) { options = merge( { withParameterNaming: false // basically a flag to opt into this being a part of the ID design tool. }, options ); this.vars = []; // {TemplateVariable[]} this.input = document.createElement( 'textarea' ); this.varUI = document.createElement( 'div' ); this.outputSentence = document.createElement( 'div' ); this.withParameterNaming = options.withParameterNaming; this.name = null; this.populateContainerHTML( container ); this.input.addEventListener( 'input', () => { this.onInput( this.input.value ); } ); // autosave on each new input change from the input sentence, variable UIs, or output sentence (select box change) container.addEventListener( 'input', () => { this.save( AUTO ); } ); // @public this.descriptionSentenceCreatedEmitter = new Emitter( { parameters: [ { valueType: Object } ] } ); } /** * Responsible for creating the expected HTML for the phrase builder. Elements created in the constructor are used, * elsewhere, but their HTML presence is edited and created here. * @param {HTMLElement} container * @private */ populateContainerHTML( container ) { if ( this.withParameterNaming ) { const nameInput = document.createElement( 'input' ); nameInput.type = 'text'; nameInput.id = 'description-name'; nameInput.addEventListener( 'input', () => { this.name = nameInput.value; } ); const nameLabel = document.createElement( 'label' ); nameLabel.innerText = 'Description Name:'; nameLabel.setAttribute( 'for', 'description-name' ); container.appendChild( nameLabel ); container.appendChild( nameInput ); container.appendChild( document.createElement( 'br' ) ); } const inputLabel = document.createElement( 'label' ); inputLabel.innerHTML = '<strong>Input raw sentence with template variables:</strong>'; inputLabel.setAttribute( 'for', 'sentenceInput' ); this.input.rows = 10; this.input.cols = 60; this.input.id = 'sentenceInput'; inputLabel.setAttribute( 'for', this.input.id ); container.appendChild( inputLabel ); appendBR( container ); container.appendChild( this.input ); appendBR( container ); appendBR( container ); const optionAddingDescriptionP = document.createElement( 'p' ); optionAddingDescriptionP.innerText = 'As template variables are added above, text areas will be added below. For ' + 'each, specify options for each variable separated by a new line.'; container.appendChild( optionAddingDescriptionP ); container.appendChild( this.varUI ); appendBR( container ); appendBR( container ); const outputLabel = document.createElement( 'label' ); outputLabel.innerHTML = '<strong>Output sentence:</strong>'; this.outputSentence.id = 'sentenceOutput'; outputLabel.setAttribute( 'for', this.outputSentence.id ); container.appendChild( outputLabel ); container.appendChild( this.outputSentence ); if ( this.withParameterNaming ) { const save = document.createElement( 'button' ); save.id = 'description-save'; save.innerText = 'Create Description'; save.addEventListener( 'click', () => { this.descriptionSentenceCreatedEmitter.emit( this.serialize() ); } ); container.appendChild( save ); } } /** * Update the output container * @param string * @private */ updateOutputPhrase( string ) { this.outputSentence.innerHTML = ''; let currentIndex = 0; this.vars.forEach( templateVar => { const toAppend = string.slice( currentIndex, templateVar.index ); appendSpanText( this.outputSentence, toAppend ); this.outputSentence.appendChild( templateVar.select ); currentIndex = templateVar.index + templateVar.name.length + 4; // 4 for the curly braces `{{}}` } ); appendSpanText( this.outputSentence, string.slice( currentIndex ) ); } /** * update the ui controlling options for each variable * @private */ updateVarUI() { this.varUI.innerHTML = ''; this.vars.forEach( templateVar => { this.varUI.appendChild( templateVar.ui ); } ); } /** * On input change in the input sentence * @param string * @private */ onInput( string ) { const newVars = []; findAll( TEMPLATE_VAR_REGEX, string ).forEach( variableOutput => { // For `ohhi{{fdsa}}` output looks like `["{{fdsa}}", "fdsa", index: 4, groups: undefined]` const variableName = variableOutput[ 1 ]; let alreadyExists = false; // TODO: use lodash instead? this.vars.forEach( templateVar => { if ( templateVar.name === variableName ) { alreadyExists = true; newVars.push( templateVar ); } } ); // if it didn't already exist, then let's create a new one !alreadyExists && newVars.push( new TemplateVariable( variableName, variableOutput.index ) ); } ); this.vars = newVars; this.updateUI( string ); // autosave on each new input from the input sentence this.save( AUTO ); } /** * Update UI elements of the phrase builder * @param {string} inputValue - the value of the input text box * @private */ updateUI( inputValue ) { this.updateVarUI(); this.updateOutputPhrase( inputValue ); } /** * @private * @returns {Object} */ serialize() { return { input: this.input.value, variables: this.vars.map( variable => variable.serialize() ), name: this.name }; } /** * @public * Autoload whatever was most recently autosaved */ autoload() { this.load( AUTO ); } /** * @public * @param {string} name - the name of the phrase builder instance to load */ load( name ) { const storedPhraseBuilder = window.localStorage.getItem( `${SAVING_KEY_PREFIX}${name}` ); if ( storedPhraseBuilder ) { const serializedPhraseBuilder = JSON.parse( storedPhraseBuilder ); this.input.value = serializedPhraseBuilder.input; this.vars = serializedPhraseBuilder.variables.map( variable => TemplateVariable.deserialize( variable ) ); this.updateUI( this.input.value ); } } /** * Save this phrase builder instance under the name provided * @param {string} name * @public */ save( name ) { window.localStorage.setItem( `${SAVING_KEY_PREFIX}${name}`, JSON.stringify( this.serialize() ) ); } /** * Creator method * @param {HTMLElement} input - the input element to monitor for sentence changes * @param {HTMLElement} varDiv - container for the variable uis * @param {HTMLElement} output - container for the output sentence * @returns {PhraseBuilder} * @public */ static create( input, varDiv, output ) { return new PhraseBuilder( input, varDiv, output ); } }
JavaScript
class LinkedListNode { constructor() { this.Hash = false; this.Datum = false; // This is where expiration and other elements are stored; this.Metadata = {}; this.LeftNode = false; this.RightNode = false; // To allow safe specialty operations on nodes this.__ISNODE = true; } }
JavaScript
class Student extends Person { constructor(name, age, group, course) { super(name, age); this.group = ''; this.course = 0; this.group = group; this.course = course; } // sayHello(): string { // return `Hello! My name is ${this.name}. I'm from ${this.group} group,` // } sayHello() { const text = super.sayHello(); return `${text} I'm from ${this.group} group.`; } }
JavaScript
class ForgotPasswordForm extends React.Component{ constructor(props) { super(props) this.state = { email: '' } this.handleSubmit = this.handleSubmit.bind(this) this.handleChange = this.handleChange.bind(this) } handleChange(e) { const target = e.target const name = target.name const value = target.value this.setState({ [name]: value }) } handleSubmit(e) { e.preventDefault() var req_body = { "email": this.state.email } fetch(process.env.REACT_APP_API_URL + '/forgotpassword', { method: 'POST', body: JSON.stringify(req_body) }) .then((response) => { return response.json() }) .then((data) => { if(data.error) { alert("There was an error resetting your password: " + data.error) } else { alert("Please check your email for a link to reset your password.") window.location.replace('/login') } }) } render() { return ( <div className=""> <form> <Input id="email" name="email" required="true" type="email" placeholder="Email" value={this.state.email} onChange={this.handleChange} /> <button value="Log In" className='rounded cursor-pointer my-6 py-2 px-4 lg:px-48 bg-purple-700 font-bold text-white' onClick={this.handleSubmit}>Submit</button> </form> </div> ) } }
JavaScript
class AdvancedSearch { exec(target) { return this.query.exec(new Source(target)); } constructor() { this.whitespace = Parser.char("  "); this.separator = Parser.map( Parser.seq(this.whitespace, Parser.many(this.whitespace)), parsed => { return null; } ); this.phrase = Parser.map( Parser.seq( Parser.token('"'), Parser.regex(/([^"]|"")+/), Parser.token('"') ), parsed => { return { value: parsed[1].replace('""', '"'), phrased: true }; } ); this.word = Parser.map( Parser.regex(/[^  \"\(\)]([^  ]*[^  \)])*/), parsed => { return { value: parsed, phrased: false }; } ); this.clause = Parser.map( Parser.seq( Parser.option(Parser.token("-")), Parser.choice(this.phrase, this.word) ), parsed => { parsed[1].not = parsed[0] === "-" ? true : false; return parsed[1]; } ); this.factor = Parser.lazy(() => { const parser = Parser.seq( Parser.token("("), Parser.option(this.separator), this.query, Parser.option(this.separator), Parser.token(")") ); return Parser.map(parser, parsed => { return parsed[2]; }); }); this.sentence = Parser.choice(this.factor, this.clause); this.query = Parser.map( Parser.seq( this.sentence, Parser.many( Parser.seq( this.separator, Parser.option(Parser.seq(Parser.token("OR"), this.separator)), this.sentence ) ) ), parsed => { let res = new Result(parsed[0]); for (let i = 0; i < parsed[1].length; i++) { if (isOrQuery(parsed[1][i][1])) { res.pushOr(parsed[1][i][2]); } else { res.pushAnd(parsed[1][i][2]); } } return res.getQuery(); } ); const isOrQuery = parsed => { return parsed !== null && parsed[0] === "OR"; }; } }
JavaScript
class Abstract extends Section { /** * @returns {String} */ static get role() { return DPUB_ROLE_PREFIX + super.role } /** * @returns {Boolean} */ static get abstract() { return false } }
JavaScript
class AzureDBI extends CloudDBI { /* ** ** Extends CloudDBI enabling operations on Azure Blob Containers rather than a local file system. ** ** !!! Make sure your head is wrapped around the following statements before touching this code. ** ** An Export operaton involves reading data from the Azure Blob store ** An Import operation involves writing data to the Azure Blob store ** */ static #_YADAMU_DBI_PARAMETERS static get YADAMU_DBI_PARAMETERS() { this.#_YADAMU_DBI_PARAMETERS = this.#_YADAMU_DBI_PARAMETERS || Object.freeze(Object.assign({},DBIConstants.YADAMU_DBI_PARAMETERS,AzureConstants.DBI_PARAMETERS)) return this.#_YADAMU_DBI_PARAMETERS } get YADAMU_DBI_PARAMETERS() { return AzureDBI.YADAMU_DBI_PARAMETERS } get DATABASE_KEY() { return AzureConstants.DATABASE_KEY}; get DATABASE_VENDOR() { return AzureConstants.DATABASE_VENDOR}; get SOFTWARE_VENDOR() { return AzureConstants.SOFTWARE_VENDOR}; get PROTOCOL() { return AzureConstants.PROTOCOL } get CONTAINER() { this._CONTAINER = this._CONTAINER || (() => { const container = this.parameters.CONTAINER || AzureConstants.CONTAINER this._CONTAINER = YadamuLibrary.macroSubstitions(container, this.yadamu.MACROS) return this._CONTAINER })(); return this._CONTAINER } get STORAGE_ID() { return this.CONTAINER } constructor(yadamu,settings,parameters) { // Export File Path is a Directory for in Load/Unload Mode super(yadamu,settings,parameters) } getVendorProperties() { /* ** ** Connection is described by a single object made up of key value pairs seperated by semi-colons ';', E.G. ** ** "DefaultEndpointsProtocol=http;AccountName=${this.properties.USERNAME};AccountKey=${this.properties.PASSWORD};BlobEndpoint=${this.properties.HOSTNAME}:${this.properties.PORT}/${this.properties.USERNAME}" ** ** DefaultEndpointsProtocol=http; ** AccountName=devstoreaccount1; ** AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==; ** BlobEndpoint=http://yadamu-db1:10000/devstoreaccount1" ** */ const keyValues = this.vendorProperties = typeof this.vendorProperties === 'string' ? this.vendorProperties.split(';') : ['DefaultEndpointsProtocol=','AccountName=','AccountKey=','BlobEndpoint='] let keyValue = keyValues[0].split('=') keyValue[1] = this.parameters.PROTOCOL || keyValue[1] keyValues[0] = keyValue.join('=') keyValue = keyValues[1].split('=') keyValue[1] = this.parameters.USERNAME || keyValue[1] keyValues[1] = keyValue.join('=') keyValue = keyValues[2].split('=') keyValue[1] = this.parameters.PASSWORD || keyValue[1] keyValues[2] = keyValue.join('=') keyValue = keyValues[3].split('=') let url = keyValue[1] try { url = new URL(url ? url : 'http://0.0.0.0') } catch (e) { this.logger.error([this.DATABASE_VENDOR,'CONNECTION'],`Invalid endpoint specified: "${vendorProperties.endpoint}"`) this.yadamuLogger.handleException([this.DATABASE_VENDOR,'CONNECTION'],e) url = new URL('http://0.0.0.0') } url.protocol = this.parameters.PROTOCOL || url.protocol url.hostname = this.parameters.HOSTNAME || url.hostname url.port = this.parameters.PORT || url.port url = url.toString() keyValue[1] = url keyValues[3] = keyValue.join('=') return keyValues.join(';'); } async createConnectionPool() { // this.yadamuLogger.trace([this.constructor.name],`BlobServiceClient.fromConnectionString()`) this.cloudConnection = BlobServiceClient.fromConnectionString(this.vendorProperties); this.cloudService = new AzureStorageService(this.cloudConnection,this.CONTAINER,{},this.yadamuLogger) } parseContents(fileContents) { return JSON.parse(fileContents.toString()) } async finalize() { await Promise.all(Array.from(this.cloudService.writeOperations)); super.finalize() } classFactory(yadamu) { return new AzureDBI(yadamu) } }
JavaScript
class AdminQueryHandler extends QueryHandler { constructor(data={}) { super(data); [ /** * @member {String[]} Defiant.Plugin.QueryApi.AdminQueryHandler#permissions * An array of permissions that would grant a user access to this * handler. */ 'permissions', ].map(val => this[val] = data[val] ? data[val] : (this[val] ? this[val] : this.constructor[val])); } }
JavaScript
class Dialog extends React.Component { constructor(props) { super(props); } componentWillUpdate() { console.log('Component is about to update...'); } // change code below this line componentWillReceiveProps(nextProps) { console.log(this.props, nextProps); } componentDidUpdate() { console.log('component updated....'); } render() { return <h1>{this.props.message}</h1>; } }
JavaScript
class CharAverage { constructor () { this.fileContents = '' this.parsedFilePerLine = [] this.listOfCharPerLine = [] this.listOfCharCountPerLine = [] this.charAverage = 0 } readFileContents (inputFileName) { let that = this fs.readFile(inputFileName, function (err, data) { if (err) return err that.fileContents = data.toString() that.parseFileLine() that.getListOfCharPerLine() that.getCharCountPerLine() that.getCharAverage() console.log('This file has an average char per line of: ' + that.charAverage) }) } parseFileLine () { this.parsedFilePerLine = this.fileContents.trim().split('\n') } getListOfCharPerLine () { //this.listOfCharPerLine = this.parsedFilePerLine.map((x) => (x.split('')/*.filter((y)=>(y != ' '))*/)) this.listOfCharPerLine = this.parsedFilePerLine.map((x) => (x.split('').filter((y)=>(y != ' ')))) } getCharCountPerLine () { this.listOfCharCountPerLine = this.listOfCharPerLine.map((x) => (x.length)) } getCharAverage () { this.charAverage = this.listOfCharCountPerLine.reduce((sum,x,index,array) => { if (index != array.length-1) { return sum + x } else { return (sum + x)/array.length } }) } }
JavaScript
class BadgeTab extends Component { constructor(props) { super(props) console.log(this.props.badges) } render() { return ( <View style={styles.container}> { this.props.badges ? this.props.badges.map((badge, index) => { return ( <TouchableOpacity key={index} onPress={() => this.props.onPress(badge.id, badge.type)}> <View style={styles.badgeContainer} > <Image source={ badge.iconUrl ? {uri: this.getBadgeWithStatus(badge) } : require('@assets/images/greenPin_old.png')} style={styles.badgeImage}/> </View> </TouchableOpacity> ) }) : null } { this.props.badges.length % 3 == 2 ? ( <View style={styles.emptyElement}> </View> ) : null } </View> ); } getBadgeWithStatus(badge) { if ( badge.receivedBy.length == 0 ) { return getGrayImage(badge.iconUrl) } else { return badge.iconUrl } } }
JavaScript
class Utils { static get NS_XML_URI() { return "http://www.w3.org/XML/1998/namespace"; } static get NS_TTML_URI() { return "http://www.w3.org/ns/ttml"; } static get NS_TTML_PARAMETER_URI() { return "http://www.w3.org/ns/ttml#parameter"; } static get NS_TTML_STYLING_URI() { return "http://www.w3.org/ns/ttml#styling"; } static get NS_TTML_AUDIO_URI() { return "http://www.w3.org/ns/ttml#audio"; } static get NS_TTML_METADATA_URI() { return "http://www.w3.org/ns/ttml#metadata"; } static get NS_TTML_ISD_URI() { return "http://www.w3.org/ns/ttml#isd"; } static isUndefined(element) { return ( element === null || element === undefined || element.attributes === undefined || element.name === undefined ); } static isAudioType(fullyQualifiedName) { return ( fullyQualifiedName === `${Utils.NS_TTML_URI}%%body` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%div` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%p` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%span` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%animate` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%audio` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%source` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%data` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%chunk` || fullyQualifiedName === "" ); } static hasAudioAttribute(element) { return ( this.getAttributeByFullyQualifiedName(element, `${Utils.NS_TTML_URI}#audio%%gain`) !== undefined || this.getAttributeByFullyQualifiedName(element, `${Utils.NS_TTML_URI}#audio%%pan`) !== undefined || this.getAttributeByFullyQualifiedName(element, `${Utils.NS_TTML_URI}#audio%%pitch`) !== undefined || this.getAttributeByFullyQualifiedName(element, `${Utils.NS_TTML_URI}#audio%%speak`) !== undefined ); } static isAudioElement(element) { if (Utils.isUndefined(element)) { return false; } const fullyQualifiedName = element.fullyQualifiedName; if (fullyQualifiedName === `${Utils.NS_TTML_URI}%%audio` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%source` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%data` || fullyQualifiedName === `${Utils.NS_TTML_URI}%%chunk`) { return true; } return Utils.isAudioType(fullyQualifiedName) && Utils.hasAudioAttribute(element); } static gleanNamespaces(element) { const namespaces = { xml: Utils.NS_XML_URI }; for (const key in element.attributes) { if (element.attributes.hasOwnProperty(key)) { if (key === "xmlns") { namespaces.default = element.attributes[key]; } else if (key === "xmlns:xml" && element.attributes[key] !== Utils.NS_XML_URI) { console.warn("Namespace xmlns:xml is reserved in XML and must not be bound to another namespace!"); console.warn(`${key}=${element.attributes[key]} is ignored.`); } else if (key.startsWith("xmlns:")) { namespaces[key.split(":")[1]] = element.attributes[key]; } else continue; } } return namespaces; } static getFullyQualifiedName(element) { if (element.name.includes(":")) { const prefix = element.name.split(":")[0]; const suffix = element.name.split(":")[1]; if (element.namespaces.hasOwnProperty(prefix)) { return `${element.namespaces[prefix]}%%${suffix}`; } else { console.warn(`Cannot find the namespace for element ${element.name}. Make sure your TTML2 file is valid XML.`); return undefined; } } return element.name === "" ? "" : `${element.namespaces.default}%%${element.name}`; } static getAttributeByFullyQualifiedName(element, fullyQualifiedAttributeName) { if (fullyQualifiedAttributeName.includes("%%")) { const namespaceURI = fullyQualifiedAttributeName.split("%%")[0]; const name = fullyQualifiedAttributeName.split("%%")[1]; if (namespaceURI === "" && element.attributes.hasOwnProperty(name)) { return element.attributes[name]; } for (const prefix in element.namespaces) { if (namespaceURI === element.namespaces[prefix] && element.attributes.hasOwnProperty(`${prefix}:${name}`)) { return element.attributes[`${prefix}:${name}`]; } } } return undefined; } }
JavaScript
class ElementStream extends Stream { constructor(elementList, startIndex = 0) { super(); this.elementList = Array.prototype.slice.call(elementList); this.index = startIndex; } get hasNext() { return this.index < this.elementList.length; } next() { return this.elementList[this.index++]; } peek() { return this.elementList[this.index]; } invalidate() { this.index = this.elementList.length; } }
JavaScript
class ViewModule extends Component { static contextType = MyContext; constructor(props) { super(props); this.state = {}; } render() { const items = [{ text: "abc" }, { text: "abc" }, { text: "abc" }]; return ( <Panel> <div className="fb fb-col"> <div className="fb fb-row fb-sb fb-wrap"> <div className="fb fb-col fb-center px-5"> <Spring from={{ marginTop: -20000 }} to={{ marginTop: 0 }}> {(props) => <ProfileImage src="/img/1902619.jpg" style={props} />} </Spring> <div className="fb fb-col fb-center mt-2"> <label>Welcome back, Max</label> <label>What would you like to do today?</label> </div> </div> <div className="fb fb-col fb-se px-5"> <button className="btn btn-primary">View Feedback</button> <button className="btn btn-primary">View Achievements</button> <button className="btn btn-primary">View Ladder</button> </div> </div> <div className="fb fb-col pt-5"> <label> <h2 className="text-center fb-fw">Achievement Progress</h2> </label> <div className="fb fb-row"> <Trail items={items} keys={(item) => item.key} from={{ marginTop: -20000 }} to={{ marginTop: 0 }} config={{ delay: 500 }}> {(item) => (props) => ( <div> <Achievement style={props} src="/img/1902619.jpg" /> </div> )} </Trail> </div> </div> </div> </Panel> ); } }
JavaScript
class For0 extends MigrationGeneration { supports(version) { return version === 0; } execute(item) { item.backgroundColor = this._config.defaultBackgroundColor(); return item; } }
JavaScript
class For1 extends MigrationGeneration { supports(version) { return version === 1; } execute(item) { item.displayPosition = this._config.defaultDisplayPosition(); return item; } }
JavaScript
class For2 extends MigrationGeneration { supports(version) { return version === 2; } execute(item) { item.status = this._config.defaultStatus(); return item; } }
JavaScript
class For3 extends MigrationGeneration { supports(version) { return version === 3; } execute(item) { return item; } }
JavaScript
class Animal{ constructor(specie, sound){ this.specie = specie; this.sound = sound; } speak(){ return this.sound; } }
JavaScript
class Cat extends Animal{ //define other methods move(steps){ var initial_step = 0; initial_step += steps; return "Taken " + initial_step + " steps"; } }
JavaScript
class CardDetailsPopup extends Component { static propTypes = { cardData: PropTypes.object, show: PropTypes.bool, coordinates: PropTypes.object, cardDetailsPopupDelay: PropTypes.oneOfType([ PropTypes.bool, PropTypes.number ]) } state = { popupVisible: false, popupPosition: {} } timeout = null componentWillReceiveProps (nextProps) { if (nextProps.cardDetailsPopupDelay === false) return if (this.props.show && !nextProps.show) { this.hideDetailsPopup() return } // On mouse move... if (nextProps.coordinates.pageX !== undefined && nextProps.coordinates.pageY !== undefined) { clearTimeout(this.timeout) // If popup is visible if (this.state.popupVisible) { if (this.props.cardDetailsPopupDelay > 0) { // Hide it this.hideDetailsPopup() } // If popup is hidden } else if (nextProps.show) { // Show it this.timeout = setTimeout(() => { this.showDetailsPopup() }, this.props.cardDetailsPopupDelay) } } } componentWillUnmount () { clearTimeout(this.timeout) } showDetailsPopup () { this.setState({ popupVisible: true }) this.updateDetailsPopupPosition(this.props.coordinates) } hideDetailsPopup () { clearTimeout(this.timeout) this.setState({ popupVisible: false }) } updateDetailsPopupPosition = ({ pageX, pageY }) => { if (!this.state.popupVisible) return const offset = 10 const popupWidth = this.refs.detailsPopup.clientWidth const popupHeight = this.refs.detailsPopup.clientHeight const windowWidth = window.innerWidth const windowHeight = window.innerHeight let top = pageY + offset let left = pageX + offset if (pageY + popupHeight > windowHeight) top = top - popupHeight if (pageX + popupWidth > windowWidth) left = left - popupWidth this.setState({ popupPosition: { top, left } }) } render () { const { cardData, cardDetailsPopupDelay } = this.props const { popupPosition, popupVisible } = this.state if (cardDetailsPopupDelay === false || !popupVisible) return null return ( <div className="card__details-popup" style={popupPosition} ref="detailsPopup" > <CardDetails card={cardData} /> </div> ) } }
JavaScript
class LexGrammar { /** * A lexical grammar is used for a string tokenization. An example of the * lexical grammar data: * * { * "macros": { * "digit": "[0-9]", * }, * * "rules": [ * ["a", "return 'a';"], * ["\\(", "return '(';"], * ["\\)", "return ')';"], * ["\\+", "return '+';"], * ["{digit}+(\\.{digit}+)?\\b", "return 'NUMBER';"], * * // A rule with start conditions. Such rules are matched only * // when a scanner enters these states. * [["string", "code"], '[^"]', "return 'STRING';"], * ], * * // https://gist.github.com/DmitrySoshnikov/f5e2583b37e8f758c789cea9dcdf238a * "startConditions": { * "string": 1, // inclusive condition %s * "code": 0, // exclusive consition %x * }, * } */ constructor({macros, rules, startConditions, options}) { this._macros = macros; this._originalRules = rules; this._options = options; this._extractMacros(macros, this._originalRules); this._rules = this._processRules(this._originalRules); this._rulesToIndexMap = this._createRulesToIndexMap(); this._startConditions = Object.assign({INITIAL: 0}, startConditions); this._rulesByStartConditions = this._processRulesByStartConditions(); } /** * Returns options. */ getOptions() { return this._options; } /** * Returns start conditions types for a lexer. */ getStartConditions() { return this._startConditions; } /** * Returns lexical rules. */ getRules() { return this._rules; } /** * Returns a rule by index. */ getRuleByIndex(index) { return this._rules[index]; } /** * Returns rule's index. */ getRuleIndex(rule) { return this._rulesToIndexMap.get(rule); } /** * Returns original lexical rules data. */ getOriginalRules() { return this._originalRules; } /** * Returns macros. */ getMacros() { return this._macros; } /** * Returns lexical rules for a specific start condition. */ getRulesForState(state) { return this._rulesByStartConditions[state]; } /** * Returns rules by start conditions. */ getRulesByStartConditions() { return this._rulesByStartConditions; } /** * Creates rules to index map. */ _createRulesToIndexMap() { const rulesToIndexMap = new Map(); this.getRules().forEach((rule, index) => { rulesToIndexMap.set(rule, index); }); return rulesToIndexMap; } /** * Processes lexical rules data, creating `LexRule` instances for each. */ _processRules(rules) { return rules.map(tokenData => { // Lex rules may specify start conditions. Such rules are // executed if a tokenizer enters such state. let startConditions; let matcher; let tokenHandler; let options = {}; // Default options of a particular LexRule are initialized to the // global options of the whole lexical grammar. const defaultOptions = Object.assign({}, this.getOptions()); if (tokenData.length === 2) { [matcher, tokenHandler] = tokenData; } else if (tokenData.length === 3) { // Start conditions, no options. if (Array.isArray(tokenData[0]) && typeof tokenData[2] === 'string') { [startConditions, matcher, tokenHandler] = tokenData; } // Trailing options, no start conditions. else if ( typeof tokenData[0] === 'string' && typeof tokenData[2] === 'object' ) { [matcher, tokenHandler, options] = tokenData; } } else if (tokenData.length === 4) { [startConditions, matcher, tokenHandler, options] = tokenData; } return new LexRule({ startConditions, matcher, tokenHandler, options: Object.assign(defaultOptions, options), }); }); } /** * Builds a map from a start condition to a list of * lex rules which should be executed once a lexer * enters this state. */ _processRulesByStartConditions() { const rulesByConditions = {}; for (const condition in this._startConditions) { const inclusive = this._startConditions[condition] === 0; const rules = this._rules.filter(lexRule => { // A rule is included if a lexer is in this state, // or if a condition is inclusive, and a rule doesn't have // any explicit start conditions. Also if the condition is `*`. // https://gist.github.com/DmitrySoshnikov/f5e2583b37e8f758c789cea9dcdf238a return ( (inclusive && !lexRule.hasStartConditions()) || (lexRule.hasStartConditions() && (lexRule.getStartConditions().indexOf(condition) !== -1 || lexRule.getStartConditions().indexOf('*') !== -1)) ); }); rulesByConditions[condition] = rules; } return rulesByConditions; } /** * If lexical grammar provides "macros" property, and has e.g entry: * "digit": "[0-9]", with later usage of {digit} in the lex rules, * this functions expands it to [0-9]. */ _extractMacros(macros, rules) { rules.forEach(lexData => { const index = lexData.length === 3 ? 1 : 0; // Standard macros. for (let macro in StandardMacros) { if (lexData[index].indexOf(macro) !== -1) { lexData[index] = lexData[index].replace( new RegExp(macro, 'g'), () => StandardMacros[macro] ); } } if (!macros) { return; } for (let macro in macros) { // User-level macros. if (lexData[index].indexOf(`{${macro}}`) !== -1) { lexData[index] = lexData[index].replace( new RegExp(`\\{${macro}\\}`, 'g'), () => macros[macro] ); } } }); } }
JavaScript
class ActiveArea extends Canvas { static get properties () { return { position: { defaultValue: pt(TIMELINE_CONSTANTS.SEQUENCE_INITIAL_X_OFFSET, 0) }, fill: { defaultValue: COLOR_SCHEME.SURFACE_VARIANT }, name: { defaultValue: 'active area' }, borderStyle: { defaultValue: { bottom: 'solid', left: 'none', right: 'none', top: 'solid' } }, acceptsDrops: { defaultValue: false }, halosEnabeld: { defaultValue: false } }; } get isActiveArea () { return true; } onMouseDown (event) { this.owner.onMouseDown(event); } }
JavaScript
class CubicBezier { points_ = null; samples_ = null; constructor(x1, y1, x2, y2) { this.points_ = [ x1, y1, x2, y2 ]; this.points_.forEach(validatePoint); this.samples_ = new Float32Array(kSampleCount); for (let sample = 0; sample < kSampleCount; ++sample) this.samples_[sample] = this.calculateBezier(sample * kSampleStepSize, x1, x2); } // Calculates the |position| on the curve, which must be in range of [0, 1]. Has a fast path for // curves with two linear points, will otherwise calculate the appropriate position. calculate(position) { if (typeof position !== 'number' || position < 0 || position > 1) throw new Error(`The position on a Bézier curve must be in range of [0, 1].`); if (this.points_[0] === this.points_[1] && this.points_[2] === this.points_[3]) return position; // linear progression if (position === 0 || position === 1) return position; // boundaries const time = this.calculateTimeForPosition(position); return this.calculateBezier(time, this.points_[1], this.points_[3]); } // Calculates the Bézier on either axis given |t|, |p0| and |p1|. calculateBezier(t, p0, p1) { return (((1.0 - 3.0 * p1 + 3.0 * p0) * t + (3.0 * p1 - 6.0 * p0)) * t + 3.0 * p0) * t; } // Calculates d[xy]/dt on either axis given |t|, |p0| and |p1|. calculateSlope(t, p0, p1) { return 3.0 * (1.0 - 3.0 * p1 + 3.0 * p0) * t * t + 2.0 * (3.0 * p1 - 6 * p0) * t + 3.0 * p0; } // Calculates the |t| based on the given |position| ([0, 1]). calculateTimeForPosition(position) { let sampleEnd = 1; let time = 0; // (1) Calculate the |sampleStart| value based on the x-progression on the Bézier curve. for (; sampleEnd < kSampleCount && this.samples_[sampleEnd] <= position; ++sampleEnd) time += kSampleStepSize; let sampleStart = sampleEnd - 1; // (2) Amend the calculated |time| with an interpolation between the two samples. This would // be accurate given linear progression, but is unlikely to be accurate on other curves. const distribution = (position - time) / (this.samples_[sampleEnd] - this.samples_[sampleStart]); time = time + distribution * kSampleStepSize; // (3) Calculate the slope on the X-axis at the given |time|. If there is no |slope|, simply // return the calculated |time|, otherwise either apply a Newton-Raphson iteration or do // a binary subdivision to find the right |time| value. const slope = this.calculateSlope(time, this.points_[0], this.points_[2]); if (!slope) return time; if (slope >= 0.001) { for (let iteration = 0; iteration < 4; ++iteration) { const iterationSlope = this.calculateSlope(time, this.points_[0], this.points_[2]); if (!iterationSlope) return time; const x = this.calculateBezier(time, this.points_[0], this.points_[2]) - position; time -= x / iterationSlope; } } else { let timeLowerBoundary = time; let timeUpperBoundary = time + kSampleStepSize; for (let iteration = 0; iteration < 10; ++iteration) { time = timeLowerBoundary + (timeUpperBoundary - timeLowerBoundary) / 2; const difference = this.calculateBezier(time, this.points_[0], this.points_[2]) - position; difference > 0 ? timeUpperBoundary = time : timeLowerBoundary = time; if (Math.abs(difference) < 0.0000001) break; } } return time; } }
JavaScript
class Player extends Phaser.Sprite { constructor(game, x, y) { super(game, x, y, 'player', 0); this.anchor.setTo(0.5, 0); this.animations.add('walk', [0, 1, 2, 3, 4], 10, true); game.add.existing(this); game.physics.enable(this, Phaser.Physics.ARCADE); game.input.gamepad.start(); this.gamepadIndicator = game.add.sprite(10, 10, 'gamepadIndicator'); this.gamepadIndicator.scale.x = 2; this.gamepadIndicator.scale.y = 2; this.gamepadIndicator.animations.frame = 1; // Setup a Phaser controller for keyboard input. this.cursors = game.input.keyboard.createCursorKeys(); // Setup a Phaser controller for gamepad input. // To listen to buttons from a specific pad listen directly on // that pad game.input.gamepad.padX, where X = pad 1-4. this.gamePad1 = game.input.gamepad.pad1; } /** * Handle actions in the main game loop. */ update() { this.body.velocity.x = 0; // Gamepad "connected or not" indicator. if (this.game.input.gamepad.supported && this.game.input.gamepad.active && this.gamePad1.connected) { this.gamepadIndicator.animations.frame = 0; // Gamepad controls. if (this.gamePad1.isDown(Phaser.Gamepad.XBOX360_DPAD_LEFT) || this.gamePad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1) { this.walkToLeft(); } else if (this.gamePad1.isDown(Phaser.Gamepad.XBOX360_DPAD_RIGHT) || this.gamePad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) > 0.1) { this.walkToRight(); } else { this.animations.frame = 0; } } else { this.gamepadIndicator.animations.frame = 1; // Keyboard controls. if (this.cursors.left.isDown) { this.walkToLeft(); } else if (this.cursors.right.isDown) { this.walkToRight(); } else { this.animations.frame = 0; } } } /** * Player moves left. */ walkToLeft() { this.body.velocity.x = -150; this.animations.play('walk'); if (this.scale.x === 1) { this.scale.x = -1; } } /** * Player moves right. */ walkToRight() { this.body.velocity.x = 150; this.animations.play('walk'); if (this.scale.x === -1) { this.scale.x = 1; } } }
JavaScript
class jsonArray extends Array{ constructor(array=[], inplace, dtypes) { super() // to avoid max recursion depth, we push each row separately array.map( row => this.push(row)) } // returns all columns in the jsonArray get columns(){ var columns = [] var max_length = this.length if( max_length > 50 ) max_length = 50 for( var i=0; i < max_length; i++ ){ columns = columns.concat(Object.keys(this[i])) } return [...new Set(columns.filter(x => !['__index__'].includes(x)))] } /** * Replace the column names with those provided by the column array * @param {Array} columns array of column names * @return {Array} jsonArray with new column names */ set columns( columns ){ const keys = this.columns // define a mapping between the current and new column names var mapping = {} for( var i=0; i < Math.min(keys.length, columns.length); i++ ){ mapping[keys[i]] =columns[i] } // return a json array with the new mapping applied return this.rename( mapping, {inplace: true} ) } // resets the index value reset_index(props={}){ // duplicate the array to avoid mutation var array = this.__inplace__(props['inplace']) for( var i=0; i < array.length; i++ ){ array[i]['__index__'] = i } return array } // return all values for the specified column values( col ){ return [...this].map(row => row[col]) } /** * Returns an array of index values * @return {Array} Array of index values */ get index(){ return [...this].map(row => row.__index__) } append( df ){ return new jsonArray([...this].concat(df)) } /** * Applies a given function to a column and returns a DataFrame * with the results. The results can be written inplace or a nedw * column created when specified as a parameter * @param {string} col column name * @param {function} func function to apply to the column * @param {string} newCol when provided a new column is produced * @return {[type]} [description] */ apply( col, func, newCol ){ if( newCol === undefined ) newCol = col for( var i=0; i < this.length; i++ ){ this[i][newCol] = func(this[i][col]) } return this } /** * cretes a new column by applying the provided function to each row * @param {string} col name of the column to create * @param {function} func function to apply to the column */ create_column( col, func){ for( var i=0; i < this.length; i++ ){ this[i][col] = func(this[i]) } return this } /** * overwrites the local index column with the provided column * @param {String} col Column name */ set_index( col, params={} ){ var array = this.__inplace__(params['inplace']) for( var i=0; i < array.length; i ++ ){ array[i].__index__ = array[i][col] delete array[i][col] } return array } // sorts the json array by the provided column sort_values( col, ascending=true){ var array //sort the table based on the ascending flag if( ascending === true ){ array = this.sort((a, b) => a[col] > b[col] ? 1 : -1 ) }else{ array = this.sort((a, b) => a[col] < b[col] ? 1 : -1 ) } return new jsonArray( array ) } /** * Merge two DataFrames together * @param {Array} json_array DataFrame to be merged * @param {Object} [params={how:'left'] how the DataFrames should be merged * @param {string} on index (col) to use for merging * @return {Array} DataFrame containing the merged columns */ merge( json_array, params={how:'left', on:'__index__'} ){ var array = [] var df1, df2, index, a, b // var primary_col, secondary_col, value var col_left, col_right // determine the columns to use for merging the left/right // DataFrames based on the specified parameters if( params.on !== undefined ){ col_left = params.on col_right = params.on } if( params.on_right !== undefined ) col_right = params.on_right if( params.on_left !== undefined ) col_left = params.on_left // determine the merging criteria switch( params.how ){ case 'left': df1 = [...this] df2 = [...json_array] // primary_col = col_left // secondary_col = col_right index = this.unique(col_left) break; case 'right': df1 = [...json_array] df2 = [...this] // primary_col = col_right // secondary_col = col_left index = json_array.unique(col_right) break; // default to merge on left default: df1 = [...this] df2 = [...json_array] // primary_col = col_left // secondary_col = col_right index = this.unique(col_left) break; } // var lookup = {} // for( a = 0; a < df2.length; a++ ){ // value = df2[a][secondary_col] // // const keys = Object.keys(lookup) // if( keys.includes(value) ){ // lookup[value].push( df2[a] ) // }else{ // lookup[value] = [df2[a]] // } // } // // // pull the rows corresponding to the provided index value // for( var a=0; a < df1.length; a++ ){ // value = df1[a][secondary_col] // // const lookupVal = lookup[value ] // // // merge rows with similar index values (intersection). Create // // multiple rows when duplicate index values are present // if( lookupVal.length > 0 ){ // for( b=0; b < lookupVal.length; b++ ){ // array.push({...lookupVal[b], ...df1[a]}) // } // } // // // add the rows that have no overlap // if( lookupVal.length === 0 ){ // array.push(df1[a]) // } // // } // pull the rows corresponding to the provided index value for( var i=0; i < index.length; i++ ){ const value = index[i] const df1_rows = df1.filter(r => r[col_left] === value) const df2_rows = df2.filter(r => r[col_right] === value) // merge rows with similar index values (intersection). Create // multiple rows when duplicate index values are present if( (df1_rows.length > 0)&(df2_rows.length > 0) ){ for( a=0; a < df1_rows.length; a++ ){ for( b=0; b < df2_rows.length; b++ ){ array.push({...df2_rows[b], ...df1_rows[a]}) } } } // add the rows that have no overlap if( (df1_rows.length > 0)&(df2_rows.length === 0) ){ for( a=0; a < df1_rows.length; a++ ){ array.push(df1_rows[a]) } } } return new jsonArray( array, true ) } /** * Replaces undefined data with a given value. The values * can be assigned globally or by column * @param {Object} [params={}] When a value is provided, it is assigned to all columns. * Values can be assigne by column, by providing a value * per colum in the parameter dictionary * @return {Array} DataFrame with missing values replaed */ fillna( params={} ){ // duplicate the array to avoid mutation var array = this.__inplace__(params['inplace']) var i, j, columns, col, val // fill missing values with unique values per column // This assumes that the input is an object with a // value for each column name if( typeof params === 'object'){ columns = Object.keys(params) // nothing to do when no inputs are provided if( columns.length === 0) return array for( i=0; i < array.length; i ++ ){ for( j=0; j < columns.length; j++ ){ col = columns[j] val = params[col] if( array[i][col] === undefined ) array[i][col] = val if( array[i][col] === null ) array[i][col] = val // if( isNaN(array[i][col]) ) array[i][col] = val } } }else{ // fill all missing values with the same value columns = array.columns for( i=0; i < array.length; i ++ ){ for( j=0; j < columns.length; j++ ){ col = columns[j] if( array[i][col] === undefined ) array[i][col] = params if( array[i][col] === null ) array[i][col] = params // if( isNaN(array[i][col]) ) array[i][col] = params } } } return array } // filters the json array based on the column and the provided value. // The value can be either a single variable or an array filter_column( col, value ){ if( Array.isArray(value) ){ return new jsonArray( [...this].filter(row => value.includes(row[col])), false ) }else{ return new jsonArray( [...this].filter(row => row[col] === value ), false ) } } filter( func ){ return new jsonArray( [...this].filter(func), false ) } map( func ){ return [...this].map(func) } groupby( col ){ return new jsonArray( this.__groupby__( this, col ), true ) } __groupby__( json_obj, atts, keys ){ // append the keys with the json object if( atts.length === 0 ){ keys['json_obj'] = new jsonArray(json_obj) keys['count'] = json_obj.length return keys } // initial conditions for keys if( keys === undefined ){ keys = {} } var results = [] // const values = [...new Set(json_obj.map(row => row[atts[0]]))] const values = json_obj.unique(atts[0], true) for( var i=0; i < values.length; i++ ){ const val = values[i] const group = json_obj.filter( row => row[atts[0]] === val ) // deep copy the keys and append with the current key var temp_keys = Object.assign({}, keys) temp_keys[atts[0]] = values[i] results = results.concat( this.__groupby__(group, atts.slice(1), temp_keys) ) } return results } // Drops duplicates based on the specified column names. Only // the first occurance is kept. Other duplicate management must // be implemented count_values( columns=[]){ if( columns.length === 0 ) columns = this.columns const values = this.map(r => columns.map(s => r[s]).toString()) // create a buffer to hold the unique values // and the rows corresponding to the unique values var unique = [] var counts = [] // track the unique values and only add the row to // the buffer when it's value is unique for( var i=0; i < values.length; i++ ){ const val = values[i] if( !unique.includes(val) ){ unique.push(val) counts[val] = 0 } counts[val]++ } // map the unique object count back to a flat object var buffer = [] for( i=0; i < unique.length; i++ ){ const split_val = unique[i].split(',') // const obj = {count: counts[unique[i]]} for( var j=0; j < split_val.length; j++ ){ obj[columns[j]] = split_val[j] } buffer.push( obj ) } return new jsonArray( buffer, true ) } // Drops duplicates based on the specified column names. Only // the first occurance is kept. Other duplicate management must // be implemented drop_duplicates( columns=[]){ if( columns.length === 0 ) columns = this.columns const values = this.map(r => columns.map(s => r[s]).toString()) // create a buffer to hold the unique values // and the rows corresponding to the unique values var unique = [] var buffer = [] // track the unique values and only add the row to // the buffer when it's value is unique for( var i=0; i < values.length; i++ ){ if( !unique.includes(values[i]) ){ unique.push( values[i] ) buffer.push( this[i] ) } } return new jsonArray( buffer, true ) } pivot( columns ){ var pivot_table = [] if( columns === undefined ) columns = this.columns for( var i=0; i < columns.length; i++ ){ // initialize the row to contain the column name var temp = {column: columns[i]} // add the column value for each row for( var j=0; j < this.length; j++ ){ temp[j] = this[j][columns[i]] } // add the results to the final pivot table pivot_table.push( temp ) } return new jsonArray(pivot_table, true ) } // converts a matrix into a flatten table (opposite of pivot table) flatten( id_att = '__index__' ){ // extract a list of column names const columns = this.columns var table = [] for( var i=0; i < this.length; i++ ){ const row = this[i] for( var j=0; j < columns.length; j++ ){ const col = columns[j] // avoid a duplicate entry as the id attribute if( col === id_att ) continue table.push({ column: col, row: row[id_att], value: row[col] }) } } return new jsonArray( table, true ) } // creates a pivot table based on the specified row and column. // The summary type is used to compute the value of the pivot. pivot_table( row, column, summaryType='count', value=undefined ){ var pivot_table = [] const row_val = this.unique( row ) const column_val = this.unique( column ) for( var i=0; i < row_val.length; i++ ){ // initialize the row to contain the column name var temp = {row: row_val[i]} const rval = row_val[i] // const by_row = this.filter( r => r[row] === rval ) const by_row = [...this].filter( r => r[row] === rval ) // add the column value for each row for( var j=0; j < column_val.length; j++ ){ const cval = column_val[j] // const by_col = by_row.filter( r => r[column] === cval ) const by_col = [...by_row].filter( r => r[column] === cval ) // const by_col = [...this].filter( r => (r[row] === rval)&(r[column] === cval) ) // console.log( by_col ) var temp_json switch( summaryType ){ // returns the number of rows for the current split case 'count': temp[column_val[j]] = by_col.length break; // returns the number of unique values for the current split case 'unique': // set defaults for missing parameter values if( value === undefined ) value = '__index__' temp_json = new jsonArray( by_col ) temp[column_val[j]] = temp_json.unique( value ).length break; default: temp[column_val[j]] = by_col.length break } } // add the results to the final pivot table pivot_table.push( temp ) } return new jsonArray(pivot_table, true ) } /** * Creates a new column by merging the content from the columns * specified in the columns attribute * @param {array} columns array of column names * @param {String} col_name Name of the resulting column * @param {String} [sep=' '] string delimiter * @return {OBJECT} jsonArray with the new column */ combine( columns, col_name, sep=' ', params={} ){ var array = this.__inplace__(params['inplace']) for( var i=0; i < this.length; i++ ){ // seed the value with the value from the first column var temp = this[i][columns[0]] for( var j=1; j < columns.length; j++ ){ temp = temp + sep + this[i][columns[j]] } array[i][col_name] = temp } array.dtypes[col_name] = 'string' return array } combine_columns( col1, col2, col_name, sep=' ' ){ // creates a new column by merging the content of col 1 and 2 to // form a new column return this.combine([col1, col2], col_name, sep ) } unique( col, ordered=false ){ // return all unique values for the specified column. When // ordered is set to true, these values are sorted. var unique_values = [...new Set([...this].map(row => row[col] ))] if( ordered === true ){ // try to conver the values to numbers prior to sorting. // use a non standard sorting to get the values sorted properly switch( typeof unique_values[0] ){ case "string": return unique_values.sort() case "boolean": return unique_values.sort() default : try{ unique_values = unique_values.map( x => +x) unique_values = unique_values.sort(function(a,b){return a - b}) }catch{ // default to the standard sort unique_values.sort() } } } return unique_values } /** * Applies a threshold to the specified column * @param {function} func function used to partition dataset * @param {string} res_col column name containing the results * @return {Array} jsonArray containing res_col */ label( func, params={} ){ const param_keys = Object.keys(params) // set defaults for missing parameter values if( !param_keys.includes('output_col') ) params['output_col'] = 'label' if( !param_keys.includes('value') ) params['value'] = true if( !param_keys.includes('default') ) params['default'] = false if( !param_keys.includes('inplace') ) params['inplace'] = false var array = this.__inplace__(params['inplace']) // identify all samples identified by the rule const sample_index = array.filter( func ).map( row => row.__index__ ) // create a boolean label, where parts in the sample set are true for( var i=0; i < array.length; i ++ ){ // extract a list of columns name for the given row const columns = Object.keys( array[i] ) // the value is true when it is included in the sample set if( sample_index.includes( array[i].__index__ ) ){ array[i][params['output_col']] = params['value'] continue } // set the default value when no value exists if( !columns.includes(params['output_col']) ){ array[i][params['output_col']] = params['default'] continue } } return array } /** * Copies the content from one column to a new column. This is * non destructive, so if the column already exists, only the * missing data will be copied over * @param {String} col original column name * @param {String} new_col new column name * @return {Object} jsonArray with the new column added */ copy_column( col, new_col, params={} ){ // clone the local copy to avoid mutation var array = this.__inplace__(params['inplace']) // delete the specified column(s) from the DataFrame for( var i = 0; i < array.length; i++ ){ const columns = Object.keys(array[i] ) if(!columns.includes( new_col) ){ array[i][new_col] = array[i][col] } } return new jsonArray( array ) } /** * Returns a DataFrame containing only the specified column * and the index * @param {array} columns array of column names * @return {array} json array containing the specified columns */ select_columns( columns ){ var array = [] // delete the specified column(s) from the DataFrame for( var i = 0; i < this.length; i++ ){ var row = {__index__: this[i].__index__} // copy the specified columns for each row for( var j=0; j < columns.length; j++ ){ const col = columns[j] row[col] = this[i][col] } array.push( row ) } return new jsonArray( array ) } /** * Drops columns from the DataFrame * @param {String or Array} columns String or Array of column names * @return {OBJECT} JsonArray without the specified columns */ drop_columns( columns, params={} ){ // clone the local copy to avoid mutation var array = this.__inplace__(params['inplace']) // delete the specified column(s) from the DataFrame for( var i = 0; i < array.length; i++ ){ // delete the specified column when of string type if( typeof columns === 'string' ){ delete array[columns] // when a list is provided, delete all columns in the string }else{ for( var j=0; j < columns.length; j++ ){ delete array[i][columns[j]] } } } return new jsonArray( array ) } /** * renames columns * @param {object} mapping object containing the existing column name and new column name * @return {object} json array with the new column naming */ rename( mapping, params={} ){ // clone the local copy to avoid mutation var array = this.__inplace__(params['inplace']) const columns = Object.keys( mapping ) // rename the specified columns for( var i = 0; i < array.length; i++ ){ const ex_columns = Object.keys( array[i] ) // create a new column based on the mapping and delete // the existing one (taht was replaced) for( var j=0; j < columns.length; j++ ){ // only replace the column when data exists for that column if( ex_columns.includes(columns[j]) ){ const new_col = mapping[columns[j]] array[i][new_col] = array[i][columns[j]] // console.log( columns[j], typeof columns[j], typeof columns[j] instanceof 'string' ) delete array[i][columns[j]] } } } return new jsonArray( array ) } /** * replaces the values in the specified column with the given value * based on the mapping * @param {String} col original column name * @param {Object} mapping Object containing the value mapping * @return {Object} jsonArray with the new column added */ replace( col, mapping={}, params={} ){ // clone the local copy to avoid mutation var array = this.__inplace__(params['inplace']) const values = Object.keys( mapping ) // delete the specified column(s) from the DataFrame for( var i = 0; i < array.length; i++ ){ const columns = Object.keys(array[i] ) // do not perform mapping when no data nor the mapping exists if(!columns.includes(col) ) continue if(!values.includes(array[i][col])) continue array[i][col] = mapping[array[i][col]] } return new jsonArray( array ) } /** * returns the data object. When enable is true, the original * jsonArray is returned so the values are modified directly. Otherwise * the jsonArray is cloned to avoid mutation of the original object * * @param {Boolean} [enable] when inplace is True, the data is not cloned. Defaults to returning a clone * @return {Object} current jsonArray content */ __inplace__( enable=false ){ // clone the local copy to avoid mutation when inplace is disabled if( enable ) return this return new jsonArray( this ) } }
JavaScript
class BioMechanic { constructor() { this.debug = false; this.width = 1024; this.height = 768; this.game = new Phaser.Game(this.width, this.height, Phaser.CANVAS, ''); this.game.reporter = new GameReporter() this.game.state.add("Loading", loading); this.game.state.add("PlayLevel", playLevel); this.game.state.add("Ending", ending); this.game.levels = 7; this.game.currentLevel = 0; this.game.progress = 0 this.game.score = 0 this.game.level = []; this.game.level[0] = { intro : true } this.game.level[1] = { velocityControl : true, graphVisibleBeforeGo : false, graphVisibleAfterGo : false, velocityInfo : true, betInfo : true, } this.game.level[2] = { velocityControl : true, graphVisibleBeforeGo : true, graphVisibleAfterGo : true, responsiveGraph : true, graphInfo : true, } this.game.level[3] = { velocityControl : true, graphVisibleBeforeGo : false, graphVisibleAfterGo : true, livePlot : true, liveInfo : true } this.game.level[4] = { delayControl : true, graphVisibleBeforeGo : false, graphVisibleAfterGo : true, livePlot : true, delayInfo : true } this.game.level[5] = { velocityControl : true, graphVisibleBeforeGo : true, graphVisibleAfterGo : true, speedInfo : true, // ? } this.game.level[6] = { velocityControl : true, graphVisibleBeforeGo : true, positionGraphInvisible : true, speedInvisible : true, graphVisibleAfterGo : true, useGraphInfo : true, } this.game.level[7] = { velocityControl : true, graphVisibleBeforeGo : true, velocityGraphInvisible : true, mousePlotInvisible : true, graphVisibleAfterGo : true, zeroDelay : true, matchInfo : true } this.game.en = { introTextBoxA : "Looks like Kitty needs your help...", introTextBoxB : "In Run Kitty Run, you are training Kitty to be the best mouse catcher! \nPlayer 1: On each level, you have different tools to control Kitty. Kitty needs to catch Mouse at the finish line in every race. Catching the Mouse early does not count as success. \nPay Attention: Kitty and Mouse can have different start times and speeds.", introTextBoxC : "Each time Kitty catches Mouse at the finish line, Player 1 earns a star.", introTextBoxD : "After Player 1 is ready to race, PLAYER 2 will make a Bet. ", introTextBoxE : "Each time race earns a star.\nThree stars advances to the next level.\n Scores reset with each new level. Students are encouraged \nto swap who is Player 1 and Player 2.", introCatSpeech : "Hmmmmm", introMouseSpeech : "You can't catch me!", footerText : "Make Kitty reach the finish line at the same time to catch Mouse. Ready?", betBox : "Player 2 Make a Bet: Will Kitty arrive", velocityInfoA : "PLAYER 1: Set Kitty’s SPEED using the up and down arrows. Adjust Kitty’s speed to finish at the same time as Mouse.", velocityInfoB : "PLAYER 2: Make a bet and predict what will happen.", graphInfoA : "Now you have a POSITION graph and a SPEED graph. Use them to help Kitty catch Mouse.", liveInfoA : "Now, both graphs will appear after the race has started. Adjust Kitty’s speed to finish at the same time as Mouse.", delayInfoA : "On this level, set Kitty’s DELAY so she finishes at the same time as Mouse. Try it.", speedInfoA : "Set Kitty’s SPEED using the up and down arrows. Adjust Kitty’s speed to finish at the same time as Mouse.", useGraphInfoA : "Set Kitty’s SPEED using clues from the SPEED graph to finish at the same time as Mouse.", matchInfoA : "Now, Kitty does NOT have a delay. Match Kitty to Mouse’s speed. Use the up and down arrows to adjust the graph.", rightontime : "Player 2:\nYour BET was CORRECT\nKitty was ON TIME.", wrongontime : "Player 2:\nYour BET was WRONG.\nKitty was ON TIME.", rightlate : "Player 2:\nYour BET was CORRECT\nKitty was LATE.", wronglate : "Player 2:\nYour BET was WRONG.\nKitty was LATE.", rightearly : "Player 2:\nYour BET was CORRECT\nKitty was EARLY.", wrongearly : "Player 2:\nYour BET was WRONG.\nKitty was EARLY.", kittyearly : "Player 1:\nSORRY! KITTY WAS EARLY!", kittylate : "Player 1:\nSORRY! KITTY WAS LATE!", kittyontime : "Player 1:\nNICE JOB! KITTY TIED!", wrongfooter : "Sorry, Kitty didn’t finish at the same time as Mouse.", catch : "Player 1:\nNICE JOB! KITTY TIED!", nobet : "No bet was made.", nope : "Nope!", nextlevel : "Next Level", nextrace : "Next Race", late : "LATE", ontime : "ON TIME", soon : "EARLY", level : "LEVEL", tutorial : "TUTORIAL", time : "Time (s)", great : "Great!", unknown : "???", continue : "CONTINUE", locked : 'LOCKED', ok : "OK!", position : "Position (m)", speed : "Speed (m/s)", go : "Go!", restart : "RESTART", } } start() { this.game.state.start("Loading"); } }
JavaScript
class DataMapper { constructor (recordTypes, options) { if (typeof recordTypes !== 'object') throw new TypeError('First argument must be an object.') if (!Object.keys(recordTypes).length) throw new Error('At least one type must be specified.') this.recordTypes = recordTypes options = options || {} this.transforms = options.transforms || {} validateTransforms(this.transforms, this.recordTypes) this.transforms = validateRecordTypes(this.transforms, this.recordTypes) validateSchemaLinks(this.recordTypes) this.adapter = new Adapter({ options: {dsn: options.dsn}, recordTypes: recordTypes }) } /** * This is the primary method for initiating a request. * The options object may contain the following keys: * * - `method`: The method is either a function or a constant, * which may be one of `find`, `create`, `update`, or `delete`. * To implement a custom method, pass a function that accepts * one argument, the context. It may return the context synchronously or * as a Promise. Default: `find`. * * - `type`: Name of a type. Required. * * - `ids`: An array of IDs. Used for `find` and `delete` methods only. * * - `include`: For example: * `[['comments'], ['comments', { ... }]]`. The last item within * the list may be an `options` object, useful for specifying how the * included records should appear. Optional. * * - `options`: Exactly the same as the adapter's `find` method options. The * options apply only to the primary type on `find` requests. Optional. * * - `payload`: Payload of the request. Used for `create` and `update` methods * only, and must be an array of objects. The objects must be the records * to create, or update objects as expected by the Adapter. * * The response object may contain the following keys: * * - `payload`: An object containing the following keys: * - `records`: An array of records returned. * - `include`: An object keyed by type, valued by arrays of included records. * * The resolved response object should always be an instance of a response type. */ request (options) { return Promise.resolve(new Context(options)) .then((context) => { const req = context.request if (req.type == null) throw new BadRequestError('UnspecifiedType') if (!this.recordTypes[req.type]) throw new NotFoundError(`InvalidType: "${req.type}"`) if (!~['find', 'create', 'update', 'delete'].indexOf(req.method)) { throw new MethodError(`InvalidMethod: "${req.method}"`) } if (req.ids) req.ids = _.uniq(req.ids) // ensure return this[req.method](context) }) .then((context) => { const response = context.response response.status = 'ok' if (!response.payload) response.status = 'empty' if (context.request.method === 'create') response.status = 'created' return response }) } // middleware methods: find, create, update, delete /** * Fetch the primary records. * * It fetches only belongsTo fields data. * 'hasMany' ids are fetched by 'include()'. * * It mutates `context.response`. */ find (context) { const request = context.request this._ensureIncludeFields(request) const options = request.options options.ids = request.ids return this.adapter.connect() .then(() => this.adapter.find(request.type, options)) .then((records) => { if (records && records.length) context.response.records = records }) .then(() => this.include(context)) // next 'include' .then(() => this.adapter.disconnect()) // This makes sure to call `adapter.disconnect` before re-throwing the error. .catch((error) => this.adapter.disconnect().then(() => { throw error })) .then(() => this.end(context)) // next 'end' } /** * Runs incoming records through 'create' transformer. * Starts transaction. * Creates them in db in one transaction. * Closes transaction. * Gets from db created records with their newly assigned IDs (by db). * Runs created records through output transformer. */ create (context) { const request = context.request if (!request.payload || !request.payload.length) { return Promise.reject(new BadRequestError('CreateRecordsInvalid')) } let transaction return this.adapter.beginTransaction() .then((newTransaction) => { context.transaction = transaction = newTransaction }) .then(() => { const transformers = this.transforms[request.type] const transformer = transformers && transformers.input && transformers.input.create const records = request.payload if (!transformer) return records // `create` transformer has access to context.transaction to make additional db-requests return Promise.all(records.map((record) => transformer(context, record))) }) .then((records) => this._ensureRIofAllRecords(request.type, records)) .then((records) => transaction.create(request.type, records)) .then((createdRecords) => { context.response.records = createdRecords }) .then(() => transaction.endTransaction()) // This makes sure to call `endTransaction` before re-throwing the error. .catch((error) => { if (!transaction) throw error return transaction.endTransaction(error).then(() => { throw error }) }) .then(() => this.end(context)) } /** * First off it finds the records to update. * Then run update-transform and validation. * Then apply the update as well as links on related records. */ update (context) { const request = context.request const updates = request.payload const primaryType = request.type if (!updates || !updates.length) { return Promise.reject(new BadRequestError('UpdateRecordsInvalid')) } // ids should be present and be more than 0 if (!_.every(updates, 'id')) { return Promise.reject(new BadRequestError('UpdateRecordMissingID')) } let transaction return this.adapter.beginTransaction() .then((newTransaction) => { context.transaction = transaction = newTransaction }) .then(() => { // should we apply transform function const transformers = this.transforms[primaryType] const transformer = transformers && transformers.input && transformers.input.update if (!transformer) return updates const ids = updates.map((u) => u.id) return transaction.find(primaryType, {ids}) .then((records) => Promise.all(updates.map((update) => { const record = _.find(records, {id: update.id}) // `update` transformer receives `records` - previous state - and `updates` return transformer(context, record, update) }))) }) .then((transformedUpdates) => this._ensureRIofAllRecords(request.type, transformedUpdates)) // apply updates .then((validatedUpdates) => transaction.update(primaryType, validatedUpdates)) .then(() => transaction.endTransaction()) // This makes sure to call `endTransaction` before re-throwing the error. .catch((error) => { if (!transaction) throw error return transaction.endTransaction(error).then(() => { throw error }) }) .then(() => this.end(context)) } /** * Delete records by IDs. * context.type = 'aType' * context.ids = [1, 2, 3] * delete(context) // deletes only rows with 'id' IN (1, 2, 3) * * Or delete the entire collection if IDs are undefined. * context.type = 'aType' * delete(context) // deletes all rows * * It does not mutate context. */ delete (context) { const request = context.request const ids = request.ids let transaction let recordsFound return this.adapter.connect() .then(() => this.adapter.find(request.type, ids ? {ids} : undefined)) .then((records) => { if (ids && !records.length) { throw new NotFoundError('DeleteRecordsInvalid') } recordsFound = records }) .catch((error) => this.adapter.disconnect().then(() => { throw error })) .then(() => this.adapter.disconnect()) .then(() => this.adapter.beginTransaction()) .then((newTransaction) => { context.transaction = transaction = newTransaction }) .then(() => { // run some business logic before delete them const transformers = this.transforms[request.type] const transformer = transformers && transformers.input && transformers.input.delete if (!transformer) return // nothing to do // `delete` transformer has access to context.transaction to make additional db-requests return Promise.all(recordsFound.map((record) => transformer(context, record))) }) .then(() => transaction.delete(request.type, request.ids)) // referential integrity .then(() => { const primaryIds = recordsFound.map((record) => record.id) const nullify = (relationType, linkName) => { const options = {fieldsOnly: ['id'], match: {}} options.match[linkName] = primaryIds return transaction.find(relationType, options) .then((records) => records.map((record) => { record[linkName] = null return record // {id: 1, postTag: null} })) .then((updates) => transaction.update(relationType, updates)) } const typesLinks = this._getRelationTypesLinks(request.type) return Promise.all(Object.keys(typesLinks).map((relationType) => { // for all type return Promise.all(typesLinks[relationType].map((linkName) => { // for all links in type return nullify(relationType, linkName) })) })) .then(() => 'ok') }) .then(() => transaction.endTransaction()) // This makes sure to call `endTransaction` before re-throwing the error. .catch((error) => { if (!transaction) throw error return transaction.endTransaction(error).then(() => { throw error }) }) .then(() => this.end(context)) } // it mutates 'request' _ensureIncludeFields (request) { const options = request.options const includeOption = request.include this._validateIncludeOption(request.type, includeOption) const fieldsOnly = options.fieldsOnly if (includeOption && includeOption.length && fieldsOnly && fieldsOnly.length) { const descriptors = this.recordTypes[request.type] includeOption.map((linkFieldDescriptor) => { const linkField = linkFieldDescriptor[0] const isArray = descriptors[linkField].isArray // only belongsTo if (!isArray && !~fieldsOnly.indexOf(linkField)) fieldsOnly.push(linkField) }) } return request } // general middleware: include, end /** * Fetch included records. It mutates `context.response`. * * Given: * user: { * group: { link: 'group' }, * rights: { link: 'rights' }, * posts: { link: 'post', isArray: true }, * } * * find's option * include: [ * ['group'], * ['rights', {match: {deleted: false}}], * ['posts', {fields: ['name'], match: {deleted: false}}] * ] * * 'group', 'rights', and 'post' should be fetched and included * * 'post' records should contain only 'name'-field * 'post' and 'rights' both should be filtered by {deleted: false} * * "adapter's" connection has to be opened already */ include (context) { const request = context.request const response = context.response const primaryType = request.type const primaryRecords = response.records const includeOption = request.include const fieldsOnly = request.options && request.options.fieldsOnly if (!primaryRecords || !primaryRecords.length) return context // includeOption is validated in 'find()' at this moment const includeFields = this._mergeIncludeWithArrayLinks(primaryType, includeOption, fieldsOnly) if (!includeFields.length) return context const primaryModelDescriptors = this.recordTypes[primaryType] return Promise.all(includeFields.map((linkFieldDescriptor) => { const [linkField, fieldOptions] = linkFieldDescriptor const fieldDescriptor = primaryModelDescriptors[linkField] const relationType = fieldDescriptor.link if (fieldDescriptor.isArray) { // hasMany // for now only one inverse relation TODO const relationModelFields = this.recordTypes[relationType] const foreignKeyField = _.findKey(relationModelFields, { link: primaryType }) // fetch foreign relation's records by primary IDs const primaryIDs = primaryRecords.map((record) => record.id) const options = Object.assign({match: {}}, fieldOptions) options.match[foreignKeyField] = primaryIDs return this.adapter.find(relationType, options) .then((relationRecords) => { if (!relationRecords || !relationRecords.length) return // nothing to do // embed hasMany IDs to primaryRecords primaryRecords.forEach((primaryRecord) => { primaryRecord[linkField] = relationRecords.reduce((acc, relationRecord) => { if (relationRecord[foreignKeyField] === primaryRecord.id) acc.push(relationRecord.id) return acc }, []) }) const includeOptionFieldsNameArray = includeOption ? includeOption.map((el) => el[0]) : [] if (~includeOptionFieldsNameArray.indexOf(linkField)) { response.include = response.include || {} response.include[relationType] = relationRecords } }) } else { // belongsTo // record[linkField] is already loaded in find() const ids = primaryRecords.map((record) => record[linkField]).filter((id) => !!id) if (!ids || !ids.length) return // nothing to do const options = Object.assign({}, fieldOptions, {ids: _.uniq(ids)}) // ensure unique return this.adapter.find(relationType, options) .then((relationRecords) => { if (relationRecords && relationRecords.length) { response.include = response.include || {} response.include[relationType] = relationRecords } }) } })) .then(() => context) } /** * `inverse` keyword should be used for 'hasMany' relations disambiguation * * recordTypes = { * person: { * ownPets: { link: 'pet', isArray: true, inverse: 'owner' }, * groomingPets: { link: 'pet', isArray: true, inverse: 'groomer' } * }, * pet: { * owner: { link: 'person' } // or inverse: 'ownPets' * groomer: { link: 'person' } // or inverse: 'groomingPets' * } * } * * _getInverseLink('person', 'ownPets') => 'owner' */ _getInverseLink (primaryType, isArrayLinkName) { // schema links are already validated at this moment const primaryDescriptors = this.recordTypes[primaryType] const isArrayLinkDescriptor = primaryDescriptors[isArrayLinkName] const relationType = isArrayLinkDescriptor.link const relationDescriptors = this.recordTypes[relationType] return isArrayLinkDescriptor.inverse || // `inverse` in hasMany _.findKey(relationDescriptors, { inverse: isArrayLinkName }) || // `inverse` in belongsTo _.findKey(relationDescriptors, { link: primaryType }) // unambiguous inverse belongsTo link } /** * w/ empty `include` it generates (in include's format) options for hasMany fields * w/ `include` option present it merges them and their options * * recordTypes = { * person: { * ownPets: { link: 'pet', isArray: true }, * accounts: { link: 'account', isArray: true } * }, * pet: { * owner: { link: 'person', inverse: 'ownPets' } * }, * account: { * name: { type: String }, deleted: { type: Boolean }, * user: { link: 'person', inverse: 'accounts' } * } * } * * type: 'person', * include: [ * ['accounts', {fieldsOnly: ['name'], match: {deleted: false}}] * ] * * it returns: * [ * ['ownPets', {fieldsOnly: ['id', 'owner']}], // IDs will be embedded * ['accounts', {fieldsOnly: ['name', 'id', 'user'], match: {deleted: false}}] * ] */ _mergeIncludeWithArrayLinks (primaryType, includeOption, fieldsOnly) { if (fieldsOnly && !_.includes(fieldsOnly, 'id')) { if (includeOption && includeOption.length) { throw new BadRequestError('wrong query: `include` option with `id` filtered out by `fieldsOnly`') } return [] } const includeOptionFieldsNameArray = includeOption ? includeOption.map((el) => el[0]) : [] if (fieldsOnly) { // fieldsOnly should not filter out requested links includeOptionFieldsNameArray.forEach((includeName) => { if (!_.includes(fieldsOnly, includeName)) { throw new BadRequestError('wrong query: `include` option is in conflict with `fieldsOnly`') } }) } const primaryModelDescriptors = this.recordTypes[primaryType] return _.reduce( primaryModelDescriptors, (result, desc, key) => { if (!desc.link || !desc.isArray) return result // is hasMany link const inverseLinkName = this._getInverseLink(primaryType, key) const defaultOptions = {fieldsOnly: ['id', inverseLinkName]} const index = includeOptionFieldsNameArray.indexOf(key) if (index !== -1) { // hasMany link is already present in "include" option const options = result[index][1] if (options && options.fieldsOnly) { // merge 'fieldsOnly' option options.fieldsOnly = _.union(options.fieldsOnly, defaultOptions.fieldsOnly) } } else if (!fieldsOnly) { result.push([key, defaultOptions]) } else if (_.includes(fieldsOnly, key)) { // fieldsOnly can request array links as well result.push([key, defaultOptions]) } return result }, includeOption ? includeOption.slice(0) : [] // start w/ includeOption by cloning it ) } _validateIncludeOption (type, includeOption) { if (includeOption === undefined) return if (!Array.isArray(includeOption)) throw new TypeError('"include" option should be an array') const descriptors = this.recordTypes[type] includeOption.forEach((linkFieldDescriptor) => { if (!Array.isArray(linkFieldDescriptor)) { throw new TypeError( `"include" '${linkFieldDescriptor}' field descriptor should be an array` + " ['link field name', {optional options}]" ) } const [linkField, fieldOptions] = linkFieldDescriptor const fieldDescriptor = descriptors[linkField] if (!fieldDescriptor) { throw new TypeError(`include: there is no '${linkField}' field in '${type}' type`) } const relationType = fieldDescriptor.link if (!relationType) { throw new TypeError(`include: '${linkField}' field is not a link`) } if (fieldOptions) { if (typeof fieldOptions !== 'object' || fieldOptions.constructor !== Object) { throw new TypeError(`include: options for '${linkField}' is not an object`) } } return {} }) } /** * Apply `output` transform per record. It mutates `context.response`. */ end (context) { const response = context.response return Promise.resolve(response.records) // start promises chain .then((records) => { // transform primary type records const transformers = this.transforms[context.request.type] const outputTransformer = transformers && transformers.output if (!records || !outputTransformer) return return Promise.all(records.map((record) => outputTransformer(context, record))) .then((transformed) => { response.records = transformed }) }) .then(() => { // transform records of 'included' types const includedTypesRecords = response.include if (!includedTypesRecords) return const types = Object.keys(includedTypesRecords) return Promise.all(types.map((type) => { const records = includedTypesRecords[type] const transformers = this.transforms[type] const outputTransformer = transformers && transformers.output if (!records || !outputTransformer) return // do nothing return Promise.all(records.map((record) => outputTransformer(context, record))) .then((transformed) => { response.include[type] = transformed }) })) }) .then(() => { if (response.records && response.records.length) { response.payload = { records: response.records } if (response.include) response.payload.include = response.include } delete response.records delete response.include delete context.transaction return context }) } /** * with * recordTypes = { * user: { * group: { link: 'group' }, * rights: { link: 'rights' } * }, * group: { * users: { link: 'user', isArray: true } * }, * rights: { * } * } * * for user: * links = { * group: { link: 'group' }, * rights: { link: 'rights' } * } */ _ensureReferentialIntegrity (record, links) { return Promise.all( Object.keys(links).map((linkKey) => { const relationIdToCheck = record[linkKey] if (relationIdToCheck == null) return // nothing to check // the connection is opened already by adapter.beginTransaction() const relationType = links[linkKey].link return this.adapter.find(relationType, {ids: [relationIdToCheck], fieldsOnly: ['id']}) .then((rows) => { if (!rows.length) { throw new BadRequestError('RelatedRecordNotFound: there is no record' + ` with id: '${relationIdToCheck}' in '${relationType}' type`) } }) }) ) .then(() => record) } _ensureRIofAllRecords (type, records) { const links = getLinks(this.recordTypes[type]) if (!Object.keys(links).length) return records // nothing to do return Promise.all( records.map((record) => this._ensureReferentialIntegrity(record, links)) ) } /** * returns types and their one-to-many links * relating to primary type * * for recordTypes = { * post: { * $id: 'PostID', text: { type: String }, * postTag: { link: 'tag' } * }, * message: { * $table: 'msg', text: { type: String }, * msgTag: { link: 'tag' } * }, * tag: { * $id: 'tagId', name: { type: String }, * posts: { link: 'post', isArray: true, inverse: 'postTag' }, * messages: { link: 'message', isArray: true, inverse: 'msgTag' } * } * } * * returns: * { * post: ['postTag'], * message: ['msgTag'] * } */ _getRelationTypesLinks (primaryType) { let result = {} for (let type in this.recordTypes) { const fields = this.recordTypes[type] for (let field in fields) { if (/^\$/.test(field)) continue const descr = fields[field] if (descr.link === primaryType && !descr.isArray) { if (!result[type]) result[type] = [] result[type].push(field) } } } return result } }
JavaScript
class Head extends React.Component { constructor(props) { super(props); this.state = {}; } render() { return ( <TableHead> <TableRow> <TableSelectAll {...this.props.getSelectionProps()} /> {this.props.headers.map((header) => ( <TableHeader key={header.header} {...this.props.getHeaderProps({ header })}> {header.header} </TableHeader> ))} </TableRow> </TableHead> ) } }
JavaScript
class ExecutableRoute extends Executable { /** * Create a ExecutableRoute instance. * @abstract */ constructor() { super(context, runtime.get_logger_manager()) /** * Executable settings. * @protected * @type {object} */ this.store_config = undefined /** * Executable server. * @protected * @type {object} */ this.server = undefined } /** * Prepare an execution with contextual informations. * @override * * @param {object} arg_settings - execution settings. * * @returns {nothing} */ prepare(arg_settings) { // console.log(context + ':prepare:arg_settings', arg_settings) assert( T.isObject(arg_settings), context + ':no given config') this.store_config = arg_settings assert(T.isObject(this.store_config), context + ':bad config object') assert(T.isObject(this.store_config.server), context + ':bad server object') assert(this.store_config.server.is_server, context + ':bad server instance') this.server = this.store_config.server } /** * Execution with contextual informations. * @override * * @param {object} arg_data - Application instance. * * @returns {object} promise. */ execute(arg_data) { // console.log(context + ':execute:store_config', this.store_config) // CHECK APPLICATION assert(T.isObject(arg_data), context + ':bad application object') assert(arg_data.is_topology_define_application, context + ':bad application instance') const application = arg_data this.info('Execute: add server route for ' + application.get_name()) // CHECK SERVER const server_instance = this.server assert(T.isString(server_instance.server_type), context + ':bad server_instance.server_type string') assert(T.isObject(server_instance.server) || T.isFunction(server_instance.server), context + ':bad server_instance.server object or function') // LOOP ON ROUTES this.debug('this.store_config.routes', this.store_config.routes) let routes_registering_promises = [] assert(T.isArray(this.store_config.routes), context + ':bad store_config.routes object') const cfg_routes = this.store_config.routes // PROBLEM WITH NODEJS 0.10 // for(let cfg_route of cfg_routes) // { for(let cfg_route_index = 0 ; cfg_route_index < cfg_routes.length ; cfg_route_index++) { // GET ROUTE CONFIG let cfg_route = cfg_routes[cfg_route_index] this.debug('loop on cfg_route', cfg_route) assert(T.isObject(cfg_route), context + ':bad cfg_route object') assert(T.isString(cfg_route.route), context + ':bad route string') // GET APPLICATION URL const app_url = T.isString(application.app_url) ? application.app_url : '' this.debug('app_route', app_url) // GET ROUTE IS GLOBAL (HAS FULL ROUTE INSIDE) const route_is_global = (T.isBoolean(cfg_route.is_global) && cfg_route.is_global == true) // GET APPLICATION ROUTE let app_route = route_is_global ? cfg_route.route : app_url + cfg_route.route app_route = (app_route[0] == '/' ? '' : '/') + app_route cfg_route.full_route = app_route // DEBUG // console.log('route=%s, app_route=%s, cfg.route=%s, is_global=%s, cond=%s', route, app_route, cfg_route.route, cfg_route.is_global, (cfg_route.is_global && cfg_route.is_global == true)) // GET REGEXP cfg_route.route_regexp = undefined if ( app_route.indexOf('.*') > -1 || app_route.indexOf('$') > -1 || app_route.indexOf('^') > -1 ) { cfg_route.route_regexp = new RegExp( app_route.replace('/', '\/') ) } this.debug('route', cfg_route.full_route.toString()) this.debug('directory', cfg_route.directory) const route_resistering_promise = this.process_route(server_instance, application, cfg_route, arg_data) routes_registering_promises.push(route_resistering_promise) this.info('registering route [' + app_route + '] for application [' + application.$name + ']') } return Promise.all(routes_registering_promises) } /** * Process a route registering. * * @param {Server} arg_server - Server instance. * @param {TopologyDefineApplication} arg_application - Application instance. * @param {object} arg_cfg_route - plain object route configuration. * @param {object} arg_data - plain object contextual datas. * * @returns {Promise} - Promise(boolean) with (true:success, false: failure). */ process_route(arg_server, arg_application, arg_cfg_route, arg_data) { // DEBUG // console.log(arg_cfg_route, 'arg_cfg_route') // GET ROUTE CALLBACK const route_cb = this.get_route_cb(arg_application, arg_cfg_route, arg_data) if (!route_cb) { console.error('bad route callback', context) return Promise.reject(context + ':process_route:bad route callback') } // CHECK SERVER if ( ! T.isObject(arg_server) || ! arg_server.is_server || ! arg_server.is_routable_server ) { return Promise.reject(context + ':process_route:bad server type') } // ADD ROUTE HANDLER try { arg_server.add_get_route(arg_cfg_route, route_cb) return Promise.resolve(true) } catch(e) { console.error(e, context) const cfg_route_str = JSON.stringify(arg_cfg_route) return Promise.reject(context + ':process_route:' + e.toString() + ' for route config=[' + cfg_route_str + ']') } } /** * Callback for route handling. * @abstract * * @param {TopologyDefineApplication} arg_application - Application instance. * @param {object} arg_cfg_route - plain object route configuration. * @param {object} arg_data - plain object contextual datas. * * @param {function} route handler. */ get_route_cb(/*arg_application, arg_cfg_route, arg_data*/) { assert(false, context + ':get_route_cb(cfg_route) should be implemented') } /** * Callback for redirect route handling. * * @param {TopologyDefineApplication} arg_application - Application instance. * @param {object} arg_cfg_route - plain object route configuration. * @param {object} arg_data - plain object contextual datas. * * @param {function} route handler. */ get_route_redirect_cb(arg_application, arg_cfg_route/*, arg_data*/) { assert(T.isString(arg_cfg_route.redirect), context + ':bad redirect route string') return (req, res/*, next*/) => { const url = runtime.context.get_url_with_credentials(arg_cfg_route.redirect, req) res.redirect(url) } } }
JavaScript
class SecondPlot extends Component{ render(){ var player =this.props.player var data = this.props.data var pdata = data.filter(function(item){ return item.player.toLowerCase() === player.toLowerCase() }); return( <Plot data={[ { x: data.map(item => item.mp), y: data.map(item => item.pts), type: "scatter", mode: "markers", marker: {color: "Blue"}, hoverinfo: "text", hovertext: data.map(item => item.player), }, { x: pdata.map(item => item.mp), y: pdata.map(item => item.pts), type: "scatter", mode: "markers", marker: {color: "Red"}, hoverinfo: "text", hovertext: pdata.map(item => item.player), } ]} layout ={{ autosize: true, title: "Points Scored vs Minutes Played", showlegend: false, yaxis:{ title: "Points Scored per Game" }, xaxis: { title: "Minutes Played per Game" }, }} /> ) } }
JavaScript
class InputSource { constructor() { } enable() { throw new Error('enable() must be overridden'); } disable() { throw new Error('disable() must be overridden'); } getState() { throw new Error('getState() must be overridden'); } }
JavaScript
class Employee { constructor(name, id, email) { this.id = id; this.name = name; this.email = email; this.role = "Employee"; } getName(){ return this.name; }; getId() { return this.id; }; getEmail() { return this.email; }; getRole() { return this.role; }; }
JavaScript
class Result { #msg; #entities; constructor(){ this.#msg = null; this.#entities = null; }; getMsg() { return this.#msg; }; setMsg(msg) { this.#msg = msg; }; getEntities() { return this.#entities; }; setEntities(entities) { this.#entities = entities; }; }
JavaScript
class AggregateTransaction extends Transaction_1.Transaction { /** * @param networkType * @param type * @param version * @param deadline * @param maxFee * @param innerTransactions * @param cosignatures * @param signature * @param signer * @param transactionInfo */ constructor(networkType, type, version, deadline, maxFee, /** * The array of innerTransactions included in the aggregate transaction. */ innerTransactions, /** * The array of transaction cosigners signatures. */ cosignatures, signature, signer, transactionInfo) { super(type, networkType, version, deadline, maxFee, signature, signer, transactionInfo); this.innerTransactions = innerTransactions; this.cosignatures = cosignatures; } /** * Create an aggregate complete transaction object * @param deadline - The deadline to include the transaction. * @param innerTransactions - The array of inner innerTransactions. * @param networkType - The network type. * @param cosignatures * @param maxFee - (Optional) Max fee defined by the sender * @param signature - (Optional) Transaction signature * @param signer - (Optional) Signer public account * @returns {AggregateTransaction} */ static createComplete(deadline, innerTransactions, networkType, cosignatures, maxFee = new UInt64_1.UInt64([0, 0]), signature, signer) { return new AggregateTransaction(networkType, TransactionType_1.TransactionType.AGGREGATE_COMPLETE, TransactionVersion_1.TransactionVersion.AGGREGATE_COMPLETE, deadline, maxFee, innerTransactions, cosignatures, signature, signer); } /** * Create an aggregate bonded transaction object * @param {Deadline} deadline * @param {InnerTransaction[]} innerTransactions * @param {NetworkType} networkType * @param {AggregateTransactionCosignature[]} cosignatures * @param {UInt64} maxFee - (Optional) Max fee defined by the sender * @param {string} signature - (Optional) Transaction signature * @param {PublicAccount} signer - (Optional) Signer public account * @return {AggregateTransaction} */ static createBonded(deadline, innerTransactions, networkType, cosignatures = [], maxFee = new UInt64_1.UInt64([0, 0]), signature, signer) { return new AggregateTransaction(networkType, TransactionType_1.TransactionType.AGGREGATE_BONDED, TransactionVersion_1.TransactionVersion.AGGREGATE_BONDED, deadline, maxFee, innerTransactions, cosignatures, signature, signer); } /** * Create a transaction object from payload * @param {string} payload Binary payload * @returns {AggregateTransaction} */ static createFromPayload(payload) { /** * Get transaction type from the payload hex * As buffer uses separate builder class for Complete and bonded */ const builder = catbuffer_typescript_1.AggregateCompleteTransactionBuilder.loadFromBinary(format_1.Convert.hexToUint8(payload)); const type = builder.type; const innerTransactions = builder.getTransactions(); const networkType = builder.getNetwork().valueOf(); const signerPublicKey = format_1.Convert.uint8ToHex(builder.getSignerPublicKey().key); const signature = Transaction_1.Transaction.getSignatureFromPayload(payload, false); const consignatures = builder.getCosignatures().map((cosig) => { return new AggregateTransactionCosignature_1.AggregateTransactionCosignature(format_1.Convert.uint8ToHex(cosig.signature.signature), account_1.PublicAccount.createFromPublicKey(format_1.Convert.uint8ToHex(cosig.signerPublicKey.key), networkType), new UInt64_1.UInt64(cosig.version)); }); return type === TransactionType_1.TransactionType.AGGREGATE_COMPLETE ? AggregateTransaction.createComplete(Deadline_1.Deadline.createFromDTO(builder.deadline.timestamp), innerTransactions.map((transactionRaw) => { return transaction_1.CreateTransactionFromPayload(format_1.Convert.uint8ToHex(transactionRaw.serialize()), true); }), networkType, consignatures, new UInt64_1.UInt64(builder.fee.amount), signature, signerPublicKey.match(`^[0]+$`) ? undefined : account_1.PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : AggregateTransaction.createBonded(Deadline_1.Deadline.createFromDTO(builder.deadline.timestamp), innerTransactions.map((transactionRaw) => { return transaction_1.CreateTransactionFromPayload(format_1.Convert.uint8ToHex(transactionRaw.serialize()), true); }), networkType, consignatures, new UInt64_1.UInt64(builder.fee.amount), signature, signerPublicKey.match(`^[0]+$`) ? undefined : account_1.PublicAccount.createFromPublicKey(signerPublicKey, networkType)); } /** * @description add inner transactions to current list * @param {InnerTransaction[]} transaction * @returns {AggregateTransaction} * @memberof AggregateTransaction */ addTransactions(transactions) { const innerTransactions = this.innerTransactions.concat(transactions); return utils_1.DtoMapping.assign(this, { innerTransactions }); } /** * @description add cosignatures to current list * @param {AggregateTransactionCosignature[]} transaction * @returns {AggregateTransaction} * @memberof AggregateTransaction */ addCosignatures(cosigs) { const cosignatures = this.cosignatures.concat(cosigs); return utils_1.DtoMapping.assign(this, { cosignatures }); } /** * @internal * Sign transaction with cosignatories creating a new SignedTransaction * @param initiatorAccount - Initiator account * @param cosignatories - The array of accounts that will cosign the transaction * @param generationHash - Network generation hash hex * @returns {SignedTransaction} */ signTransactionWithCosignatories(initiatorAccount, cosignatories, generationHash) { const signedTransaction = this.signWith(initiatorAccount, generationHash); const transactionHashBytes = format_1.Convert.hexToUint8(signedTransaction.hash); let signedPayload = signedTransaction.payload; cosignatories.forEach((cosigner) => { const keyPairEncoded = crypto_1.KeyPair.createKeyPairFromPrivateKeyString(cosigner.privateKey); const signature = crypto_1.KeyPair.sign(keyPairEncoded, transactionHashBytes); signedPayload += UInt64_1.UInt64.fromUint(0).toHex() + cosigner.publicKey + format_1.Convert.uint8ToHex(signature); }); // Calculate new size const size = `00000000${(signedPayload.length / 2).toString(16)}`; const formatedSize = size.substr(size.length - 8, size.length); const littleEndianSize = formatedSize.substr(6, 2) + formatedSize.substr(4, 2) + formatedSize.substr(2, 2) + formatedSize.substr(0, 2); signedPayload = littleEndianSize + signedPayload.substr(8, signedPayload.length - 8); return new SignedTransaction_1.SignedTransaction(signedPayload, signedTransaction.hash, initiatorAccount.publicKey, this.type, this.networkType); } /** * @internal * Sign transaction with cosignatories collected from cosigned transactions and creating a new SignedTransaction * For off chain Aggregated Complete Transaction co-signing. * @param initiatorAccount - Initiator account * @param {CosignatureSignedTransaction[]} cosignatureSignedTransactions - Array of cosigned transaction * @param generationHash - Network generation hash hex * @return {SignedTransaction} */ signTransactionGivenSignatures(initiatorAccount, cosignatureSignedTransactions, generationHash) { const signedTransaction = this.signWith(initiatorAccount, generationHash); let signedPayload = signedTransaction.payload; cosignatureSignedTransactions.forEach((cosignedTransaction) => { signedPayload += cosignedTransaction.version.toHex() + cosignedTransaction.signerPublicKey + cosignedTransaction.signature; }); // Calculate new size const size = `00000000${(signedPayload.length / 2).toString(16)}`; const formatedSize = size.substr(size.length - 8, size.length); const littleEndianSize = formatedSize.substr(6, 2) + formatedSize.substr(4, 2) + formatedSize.substr(2, 2) + formatedSize.substr(0, 2); signedPayload = littleEndianSize + signedPayload.substr(8, signedPayload.length - 8); return new SignedTransaction_1.SignedTransaction(signedPayload, signedTransaction.hash, initiatorAccount.publicKey, this.type, this.networkType); } /** * Check if account has signed transaction * @param publicAccount - Signer public account * @returns {boolean} */ signedByAccount(publicAccount) { return (this.cosignatures.find((cosignature) => cosignature.signer.equals(publicAccount)) !== undefined || (this.signer !== undefined && this.signer.equals(publicAccount))); } /** * @internal * @returns {TransactionBuilder} */ createBuilder() { const transactions = this.innerTransactions.map((transaction) => transaction.toEmbeddedTransaction()); const cosignatures = this.cosignatures.map((cosignature) => { const signerBytes = format_1.Convert.hexToUint8(cosignature.signer.publicKey); const signatureBytes = format_1.Convert.hexToUint8(cosignature.signature); return new catbuffer_typescript_1.CosignatureBuilder(cosignature.version.toDTO(), new catbuffer_typescript_1.KeyDto(signerBytes), new catbuffer_typescript_1.SignatureDto(signatureBytes)); }); const builder = this.type === TransactionType_1.TransactionType.AGGREGATE_COMPLETE ? catbuffer_typescript_1.AggregateCompleteTransactionBuilder : catbuffer_typescript_1.AggregateBondedTransactionBuilder; return new builder(this.getSignatureAsBuilder(), this.getSignerAsBuilder(), this.versionToDTO(), this.networkType.valueOf(), this.type.valueOf(), new catbuffer_typescript_1.AmountDto(this.maxFee.toDTO()), new catbuffer_typescript_1.TimestampDto(this.deadline.toDTO()), new catbuffer_typescript_1.Hash256Dto(this.calculateInnerTransactionHash()), transactions, cosignatures); } /** * @internal * @returns {EmbeddedTransactionBuilder} */ toEmbeddedTransaction() { throw new Error('Method not implemented'); } /** * @internal * Generate inner transaction root hash (merkle tree) * @returns {Uint8Array} */ calculateInnerTransactionHash() { // Note: Transaction hashing *always* uses SHA3 const hasher = crypto_1.SHA3Hasher.createHasher(32); const builder = new crypto_1.MerkleHashBuilder(32); this.innerTransactions.forEach((transaction) => { const entityHash = new Uint8Array(32); // for each embedded transaction hash their body hasher.reset(); const byte = transaction.toEmbeddedTransaction().serialize(); const padding = new Uint8Array(catbuffer_typescript_1.GeneratorUtils.getPaddingSize(byte.length, 8)); hasher.update(catbuffer_typescript_1.GeneratorUtils.concatTypedArrays(byte, padding)); hasher.finalize(entityHash); // update merkle tree (add transaction hash) builder.update(entityHash); }); // calculate root hash with all transactions return builder.getRootHash(); } /** * @internal * @returns {AggregateTransaction} */ resolveAliases(statement) { const transactionInfo = this.checkTransactionHeightAndIndex(); return utils_1.DtoMapping.assign(this, { innerTransactions: this.innerTransactions .map((tx) => tx.resolveAliases(statement, transactionInfo.index)) .sort((a, b) => a.transactionInfo.index - b.transactionInfo.index), }); } /** * Set transaction maxFee using fee multiplier for **ONLY AGGREGATE TRANSACTIONS** * @param feeMultiplier The fee multiplier * @param requiredCosignatures Required number of cosignatures * @returns {AggregateTransaction} */ setMaxFeeForAggregate(feeMultiplier, requiredCosignatures) { if (this.type !== TransactionType_1.TransactionType.AGGREGATE_BONDED && this.type !== TransactionType_1.TransactionType.AGGREGATE_COMPLETE) { throw new Error('setMaxFeeForAggregate can only be used for aggregate transactions.'); } // Check if current cosignature count is greater than requiredCosignatures. const calculatedCosignatures = requiredCosignatures > this.cosignatures.length ? requiredCosignatures : this.cosignatures.length; // version + public key + signature const sizePerCosignature = 8 + 32 + 64; // Remove current cosignature length and use the calculated one. const calculatedSize = this.size - this.cosignatures.length * sizePerCosignature + calculatedCosignatures * sizePerCosignature; return utils_1.DtoMapping.assign(this, { maxFee: UInt64_1.UInt64.fromUint(calculatedSize * feeMultiplier), }); } /** * @internal * Check a given address should be notified in websocket channels * @param address address to be notified * @returns {boolean} */ shouldNotifyAccount(address) { return (super.isSigned(address) || this.cosignatures.find((_) => _.signer.address.equals(address)) !== undefined || this.innerTransactions.find((innerTransaction) => innerTransaction.shouldNotifyAccount(address)) !== undefined); } }
JavaScript
class ApiError extends Error { constructor(message) { super(message); this.name = this.constructor.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { this.stack = (new Error(message)).stack; } } }
JavaScript
class FrameDependency extends AbstractDependency { constructor( name ) { super( name, new Promise( resolve => requestAnimationFrame( resolve ) ) ); } }
JavaScript
class CausalNetSamplers extends causal_net_utils__WEBPACK_IMPORTED_MODULE_1__["platform"].mixWith(causal_net_core__WEBPACK_IMPORTED_MODULE_0__["Functor"], [_subSampling_mixins__WEBPACK_IMPORTED_MODULE_3__["default"], _negSampling_mixins__WEBPACK_IMPORTED_MODULE_4__["default"]]) { constructor(random) { super(); } }
JavaScript
class Bloquote extends React.Component { constructor(props) { super(props); this.state = { quote: "", author: "" }; this.changeQuoteAuthor = this.changeQuoteAuthor.bind(this); } // Initiating an author and your quote componentDidMount() { this.changeQuoteAuthor(); } // An array of quotes arrayQuotes = () => { return [ { quote: "Quem quer vencer um obstáculo deve armar-se da força do leão e da prudência da serpente.", author: "Pindaro" }, { quote: "É erro vulgar confundir o desejar com o querer. O desejo mede os obstáculos; a vontade vence-os.", author: "Alexandre Herculano" }, { quote: "A força não vem de vencer. Suas lutas desenvolvem suas forças. Quando você atravessa dificuldades e decide não se render, isso é força.", author: "Arnold Schwarzenegger" }, { quote: "Construí amigos, enfrentei derrotas, venci obstáculos, bati na porta da vida e disse-lhe: Não tenho medo de vivê-la.", author: "Augusto Cury" }, { quote: "Muitos homens devem a grandeza da sua vida aos obstáculos que tiveram que vencer.", author: "C. H. Spurgeon" } ]; }; // change an quote randomly changeQuoteAuthor = () => { const quotes = this.arrayQuotes(); const randomPosition = Math.floor(Math.random() * quotes.length); this.setState({ quote: quotes[randomPosition]["quote"], author: quotes[randomPosition]["author"] }); } render() { //=== Styling let styleCardFooter = { backgroundColor: "transparent", border: "transparent" }; let stylePadding = { padding: "5% 5%", width: '50%' }; //=== url of twitter, when clicked to share the quote. const urlTwitter = "https://twitter.com/intent/tweet?url=https%3A%2F%2Flearn.freecodecamp.org%2F&via=klis_sousa&text=" + this.state.quote + "&hashtags=freecodecamp"; return ( <div style={stylePadding}> <div className="card"> {/* show an quote */} <blockquote className="card-body"> <h1 id="text">"{this.state.quote}</h1> <h6 style={{ textAlign: "right" }} id="author"> - {this.state.author} </h6> </blockquote> <div className="card-footer" style={styleCardFooter}> {/* Buttons of twitter and tumblr */} <a href={urlTwitter} id="tweet-quote" className="btn btn-link" style={{ float: 'left' }}> <FontAwesomeIcon icon={faTwitter} /> </a> <a href="#" id="tumblr-quote" className="btn btn-link" style={{ float: 'left' }}> <FontAwesomeIcon icon={faTumblr} /> </a> {/* Create new quote */} <button className="btn btn-primary" id="new-quote" style={{ float: 'right' }} onClick={this.changeQuoteAuthor}>New quote</button> </div> </div> </div> ); } }
JavaScript
class CanvasBuilder { /** * Constructs a new CanvasBuilder object. * @param {CanvasState} initialState - Initial state. */ constructor(initialState = {}) { this.url = initialState.url || ''; this.suppressMic = initialState.suppressMic || false; this.action = initialState.action || ''; this.template = initialState.template || ''; this.speech = initialState.speech || ''; this.config = initialState.config || {}; this.data = initialState.data || {}; this.suggestions = initialState.suggestions || []; this.next = initialState.next || null; } /** * Sets canvas states by state object. * @param {CanvasState} newState - New state object. * @return {CanvasBuilder} - This instance. */ setState(newState = {}) { util.object.forOwn(newState, (val, prop) => { switch (prop) { case 'url': case 'suppressMic': case 'action': case 'template': case 'speech': case 'next': this.set(prop, val); break; case 'config': case 'data': case 'suggestions': this.add(prop, val); break; default: break; } }); return this; } /** * Sets new value for prop. * @param {string} prop - Property name. * @param {*} value - New value. * @return {CanvasBuilder} - This instance. */ set(prop, value) { if (this.hasOwnProperty(prop)) { this[prop] = value; } return this; } /** * Adds new values for existing prop with array/object value type. * @param {string} prop - Property name. * @param {!Object|Array} values - New values. * @return {CanvasBuilder} - This instance. */ add(prop, values) { if (this.hasOwnProperty(prop)) { if (Array.isArray(this[prop])) { this[prop] = this[prop].concat(values); } else if (typeof this[prop] === 'object') { this[prop] = Object.assign(this[prop], values); } else { this.set(prop, values); } } return this; } /** * Builds state object. * @return {Object} - Constructed state object. */ buildState() { return CanvasBuilder.clean({ action: this.action, template: this.template, speech: this.speech, config: this.config, data: this.data, suggestions: this.suggestions, next: this.next, }); } /** * Builds Canvas Response for ConversationV3. * @param {string} url - URL for canvas init. * @return {Canvas} - Canvas response. */ build(url) { if (typeof url === 'string' && url) { this.url = url; } const slides = [this.buildState()]; while (slides[slides.length - 1].next) { const last = slides[slides.length - 1]; slides.push(last.next); delete last.next; } return new Canvas({ url: this.url, suppressMic: this.suppressMic, data: slides, }); } /** * Cleans the SSML fields, and remove all empty properties. * @param {Object} state - Canvas response state. * @return {Object} - Cleaned canvas response state. */ static clean(state) { if (state.speech) { state.speech = util.ssml.clean(state.speech).trim(); } const cleanedNext = state.next instanceof CanvasBuilder ? state.next.buildState() : null; state.next = null; // deep clean on next is already done above const cleanedState = util.object.deepClean(state); if (!util.object.isEmpty(cleanedNext)) { cleanedState.next = cleanedNext; } return cleanedState; } /** * Creates either an CanvasBuilder instance or one with Proxy wrapper. * If using Proxy object: * - Routes all method invocation to do nothing. * - Routes all property lookup to return undefined. * - Skips redundant work when immersive response is not needed. * @param {boolean} hasCanvas - False to create a Proxy wrapper object. * @param {...any} args - Args to pass to CanvasBuilder constructor. * @return {CanvasBuilder|Proxy} - CanvasBuilder or Proxy wrapper. */ static create(hasCanvas, ...args) { // Wrap instance with Proxy object const wrap = function(obj) { const handler = { get(target, prop, receiver) { if (target[prop] instanceof Function) { return () => (prop.startsWith('build') ? undefined : receiver); } }, }; return new Proxy(obj, handler); }; const instance = new CanvasBuilder(...args); return hasCanvas ? instance : wrap(instance); } }
JavaScript
class KeyBag extends _PrivateKeyInfo.default { //********************************************************************************** /** * Constructor for Attribute class * @param {Object} [parameters={}] * @param {Object} [parameters.schema] asn1js parsed value to initialize the class from */ constructor(parameters = {}) { super(parameters); } //********************************************************************************** } //**************************************************************************************
JavaScript
class SheetView extends Component { shouldRerender() { return false } didMount() { this.props.viewport.on('scroll', this._onScroll, this) this._updateViewport() } didUpdate() { this._updateViewport() } dispose() { this.props.viewport.off(this) } update() { this.rerender() } render($$) { const sheet = this.props.sheet const viewport = this.props.viewport const M = sheet.getColumnCount() let el = $$('table').addClass('sc-table-view') let head = $$('tr').addClass('se-head').ref('head') let corner = $$('th').addClass('se-corner').ref('corner') .on('click', this._selectAll) // ATTENTION: we have a slight problem here. // <table> with fixed layout needs the exact width // so that the column widths are correct. // To avoid that corrupting the layout we need // to make sure to set the correct value here // Unfortunately this means that we must set the corner width here let width = this.props.cornerWidth || 50 corner.css({ width }) head.append(corner) for(let colIdx = 0; colIdx < M; colIdx++) { let columnMeta = sheet.getColumnMeta(colIdx) let th = $$(SheetColumnHeader, { node: columnMeta, colIdx }).ref(columnMeta.id) let w = th.getWidth() if (colIdx < viewport.startCol) { th.addClass('sm-hidden') } else { width += w } head.append(th) } el.css({ width }) el.append(head) el.append( $$(TableBody, { sheet, viewport }).ref('body') ) return el } _updateViewport() { this._updateHeader() this._updateBody() } _updateHeader() { let viewport = this.props.viewport // Note: in contrast to the render method // we can use the real width here viewport.width = this.refs.corner.el.getWidth() viewport.endCol = viewport.startCol const W = viewport.getContainerWidth() let cols = this.refs.head.el.children let i for (i = 1; i < cols.length; i++) { let colIdx = i-1 let th = cols[i] if (colIdx < viewport.startCol) { th.addClass('sm-hidden') } else { th.removeClass('sm-hidden') let w = th.getWidth() viewport.width += w if (viewport.width > W) { break } viewport.endCol++ } } for (i = i+1; i < cols.length; i++) { let th = cols[i] th.addClass('sm-hidden') } this.el.css({ width: viewport.width }) } _updateBody() { let viewport = this.props.viewport viewport.height = this.refs.corner.el.getHeight() viewport.endRow = viewport.startRow const H = viewport.getContainerHeight() // show only cells which are inside the viewport let rowIt = this.refs.body.el.getChildNodeIterator() let rowIdx = viewport.startRow while (rowIt.hasNext()) { let row = rowIt.next() let cols = row.children for (let i = 1; i < cols.length; i++) { let td = cols[i] let colIdx = i-1 if (colIdx < viewport.startCol || colIdx > viewport.endCol) { td.addClass('sm-hidden') } else { td.removeClass('sm-hidden') } } let h = row.getHeight() viewport.height += h if (viewport.height < H) { viewport.endRow = rowIdx } rowIdx++ } } getBoundingRect(rowIdx, colIdx) { let top = 0, left = 0, height = 0, width = 0 // in header let rowComp if (rowIdx === -1) { rowComp = this.refs.head } else { rowComp = this.refs.body.getRowComponent(rowIdx) } if (rowComp) { let rect = getRelativeBoundingRect(rowComp.el, this.el) top = rect.top height = rect.height } let colComp if (colIdx === -1) { colComp = this.refs.corner } else { colComp = this.refs.head.getChildAt(colIdx+1) } if (colComp) { let rect = getRelativeBoundingRect(colComp.el, this.el) left = rect.left width = rect.width } return { top, left, width, height } } getCellComponent(rowIdx, colIdx) { if (rowIdx === -1) { // retrieve a header cell return this.refs.head.getChildAt(colIdx+1) } else { let tr = this.refs.body.getRowComponent(rowIdx) if (tr) { return tr.getCellComponent(colIdx) } } // otherwise return null } getCellComponentForCell(cell) { // TODO: need to revisit this for a better implementation return this.refs.body.find(`td[data-cell-id="${cell.id}"]`) } getCornerComponent() { return this.refs.corner } /* * Tries to resolve row and column index, and type of cell * for a given event */ getTargetForEvent(e) { const clientX = e.clientX const clientY = e.clientY let colIdx = this.getColumnIndexForClientX(clientX) let rowIdx = this.getRowIndexForClientY(clientY) let type if (colIdx >= 0 && rowIdx >= 0) { type = 'cell' } else if (colIdx === -1 && rowIdx >= 0) { type = 'row' } else if (colIdx >= 0 && rowIdx === -1) { type = 'column' } else if (colIdx === -1 && rowIdx === -1) { type = 'corner' } else { type = 'outside' } return { type, rowIdx, colIdx } } // TODO: rename this to indicate usage: map clientX to column getColumnIndexForClientX(x) { const headEl = this.refs.head.el const children = headEl.children for (let i = 0; i < children.length; i++) { let child = children[i] if (_isXInside(x, getBoundingRect(child))) { return i-1 } } return undefined } // TODO: rename this to indicate usage: map clientY to row getRowIndexForClientY(y) { const headEl = this.refs.head.el if (_isYInside(y, getBoundingRect(headEl))) { return -1 } const bodyEl = this.refs.body.el const children = bodyEl.children for (let i = 0; i < children.length; i++) { let child = children[i] if (_isYInside(y, getBoundingRect(child))) { return parseInt(child.getAttribute('data-row'), 10) } } return undefined } _onScroll(dr, dc) { if (dc && !dr) { this._updateViewport() } else if (dr && !dc) { this.refs.body.update() this._updateViewport() } else { this.refs.body.update() this._updateViewport() } } _selectAll() { this.send('selectAll') } }
JavaScript
class RequestPool { constructor() { this.mempool = {}; // address:Request this.timeoutRequests = {}; // Storing removal triggers this.validRequests = {} // Move a Request here after validation console.log(`New RequestPool with timeout window of ${config.TimeoutRequestsWindowTime / 1000} s`); } /** * * @param {*} address */ removeValidationRequest(address) { delete this.mempool[address] delete this.timeoutRequests[address] console.log(`Removed ${address} from mempool`); } removeInvitation(address) { delete this.validRequests[address] console.log(`Removed ${address} from invitation pool.`); } /** * * @param {*} address */ addRequest(address) { if (address in this.mempool) { // TODO: console.log('Already in requests pool!'); } else if (address in this.validRequests) { // TODO: console.log('Already validated, submit your star!'); } else { var self = this // Need to keep the instance in scope, this is not in scope! // This is a new Request this.mempool[address] = new Request(address); // Add a countdown to this address key this.timeoutRequests[address] = setTimeout( function () { self.removeValidationRequest(address) }, config.TimeoutRequestsWindowTime); console.log(`Added ${address} to mempool`); return this.mempool[address].respond() } } /** * After signing the request, a wallet is approved for all time. * Remove the wallet from the mempool and the timeout. * Add the wallet the invitation pool. * @param {*} address */ approveWallet(address) { // Create the invite, add to the pool this.validRequests[address] = this.mempool[address].invite() console.log(this.validRequests[address]); console.log(`Added ${address} to approved pool.`); // Remove the old request this.removeValidationRequest(address) } /** * Utility. */ listRequests() { for (const [key, value] of Object.entries(this.mempool)) { console.log(key, value); } } }
JavaScript
class ParseError extends core_1.RequestError { constructor(error, response) { const { options } = response.request; super(`${error.message} in "${options.url.toString()}"`, error, response.request); this.name = 'ParseError'; } }
JavaScript
class CancelError extends core_1.RequestError { constructor(request) { super('Promise was canceled', {}, request); this.name = 'CancelError'; } get isCanceled() { return true; } }
JavaScript
class RequestError extends Error { constructor(message, error, self) { var _a; super(message); Error.captureStackTrace(this, this.constructor); this.name = 'RequestError'; this.code = error.code; if (self instanceof Request) { Object.defineProperty(this, 'request', { enumerable: false, value: self }); Object.defineProperty(this, 'response', { enumerable: false, value: self[kResponse] }); Object.defineProperty(this, 'options', { // This fails because of TS 3.7.2 useDefineForClassFields // Ref: https://github.com/microsoft/TypeScript/issues/34972 enumerable: false, value: self.options }); } else { Object.defineProperty(this, 'options', { // This fails because of TS 3.7.2 useDefineForClassFields // Ref: https://github.com/microsoft/TypeScript/issues/34972 enumerable: false, value: self }); } this.timings = (_a = this.request) === null || _a === void 0 ? void 0 : _a.timings; // Recover the original stacktrace if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) { const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); // Remove duplicated traces while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) { thisStackTrace.shift(); } this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; } } }
JavaScript
class MaxRedirectsError extends RequestError { constructor(request) { super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); this.name = 'MaxRedirectsError'; } }
JavaScript
class HTTPError extends RequestError { constructor(response) { super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); this.name = 'HTTPError'; } }
JavaScript
class CacheError extends RequestError { constructor(error, request) { super(error.message, error, request); this.name = 'CacheError'; } }
JavaScript
class UploadError extends RequestError { constructor(error, request) { super(error.message, error, request); this.name = 'UploadError'; } }
JavaScript
class TimeoutError extends RequestError { constructor(error, timings, request) { super(error.message, error, request); this.name = 'TimeoutError'; this.event = error.event; this.timings = timings; } }
JavaScript
class ReadError extends RequestError { constructor(error, request) { super(error.message, error, request); this.name = 'ReadError'; } }
JavaScript
class UnsupportedProtocolError extends RequestError { constructor(options) { super(`Unsupported protocol "${options.url.protocol}"`, {}, options); this.name = 'UnsupportedProtocolError'; } }
JavaScript
class LokaliseClient { constructor(args) { Object.assign(this, args); this.lokaliseApi = new _lokalise_node_api__WEBPACK_IMPORTED_MODULE_0__.LokaliseApi({ apiKey: args.apiKey }); } }
JavaScript
class Apps { constructor (helperFile) { this.helpers = helperFile } /** * Gets all enabled and non-enabled apps downloaded on the instance. * @returns {Promise.<apps>} object: {for each app: Boolean("enabled or not")} * @returns {Promise.<error>} string: error message, if any. */ getApps () { const send = {} const allAppsP = this.helpers._makeOCSrequest('GET', this.helpers.OCS_SERVICE_CLOUD, 'apps') const allEnabledAppsP = this.helpers._makeOCSrequest('GET', this.helpers.OCS_SERVICE_CLOUD, 'apps?filter=enabled') return Promise.all([allAppsP, allEnabledAppsP]) .then(apps => { if (parseInt(this.helpers._checkOCSstatusCode(apps[0].data)) === 999) { return Promise.reject('Provisioning API has been disabled at your instance') } if ((!(apps[0].data.ocs.data)) || (!(apps[1].data.ocs.data))) { return Promise.reject(apps[0].data.ocs) } const allApps = apps[0].data.ocs.data.apps.element const allEnabledApps = apps[1].data.ocs.data.apps.element for (let i = 0; i < allApps.length; i++) { send[allApps[i]] = false } for (let i = 0; i < allEnabledApps.length; i++) { send[allEnabledApps[i]] = true } return Promise.resolve(send) }) } /** * Enables an app via the Provisioning API * @param {string} appName name of the app to be enabled * @returns {Promise.<status>} boolean: true if successful * @returns {Promise.<error>} string: error message, if any. */ enableApp (appName) { return this.helpers._makeOCSrequest('POST', this.helpers.OCS_SERVICE_CLOUD, 'apps/' + encodeURIComponent(appName)) .then(data => { if (!data.body) { return Promise.reject('No app found by the name "' + appName + '"') } const statusCode = parseInt(this.helpers._checkOCSstatusCode(data.data)) if (statusCode === 999) { return Promise.reject('Provisioning API has been disabled at your instance') } return Promise.resolve(true) }) } /** * Disables an app via the Provisioning API * @param {string} appName name of the app to be disabled * @returns {Promise.<status>} boolean: true if successful * @returns {Promise.<error>} string: error message, if any. */ disableApp (appName) { return this.helpers._makeOCSrequest('DELETE', this.helpers.OCS_SERVICE_CLOUD, 'apps/' + encodeURIComponent(appName)) .then(data => { const statusCode = parseInt(this.helpers._checkOCSstatusCode(data.data)) if (statusCode === 999) { return Promise.reject('Provisioning API has been disabled at your instance') } return Promise.resolve(true) }) } }
JavaScript
class DateInputx extends React.Component { render() { return <Input usage="Date" name="date" extraClasses="datepicker" />; } componentDidMount() { let { onChange, value } = this.props; $(".datepicker").datepicker({ onSelect: function(dateText) { onChange($(".datepicker").datepicker("getDate")); }, dateFormat: "dd/mm/yy" }); $(".datepicker").datepicker("setDate", value); } }
JavaScript
class Custom extends React.Component { constructor ( props ) { super ( props ); // Binds method this.ToggleMenu = this.ToggleMenu.bind ( this ); this.UpdateChart = this.UpdateChart.bind ( this ); this.UpdateChartList = this.UpdateChartList.bind ( this ); // Sets the state this.state = { charts: { ALLSKY_SFC_SW_DWN: { chart: ( state ) => { var labels = []; for ( var x = 0; x < state.charts.ALLSKY_SFC_SW_DWN.data.length; x++ ) { labels.push ( ( x + 1 ).toString () ); } return { labels: labels, datasets: [{ label: 'Solar Irradiance (kWh / m²)', data: state.charts.ALLSKY_SFC_SW_DWN.data, fill: false, backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgba(255, 99, 132, 0.2)' }] } }, data: undefined }, T2MDEW: { chart: ( state ) => { var labels = []; for ( var x = 0; x < state.charts.T2MDEW.data.length; x++ ) { labels.push ( ( x + 1 ).toString () ); } return { labels: labels, datasets: [{ label: 'Frost (C)', data: state.charts.T2MDEW.data, fill: false, backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgba(255, 99, 132, 0.2)' }] } }, data: undefined }, QV2M: { chart: ( state ) => { var labels = []; for ( var x = 0; x < state.charts.QV2M.data.length; x++ ) { labels.push ( ( x + 1 ).toString () ); } return { labels: labels, datasets: [{ label: 'Humidity (g / kg)', data: state.charts.QV2M.data, fill: false, backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgba(255, 99, 132, 0.2)' }] } }, data: undefined }, PRECTOTCORR: { chart: ( state ) => { var labels = []; for ( var x = 0; x < state.charts.PRECTOTCORR.data.length; x++ ) { labels.push ( ( x + 1 ).toString () ); } return { labels: labels, datasets: [{ label: 'Precipitation (mm)', data: state.charts.PRECTOTCORR.data, fill: false, backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgba(255, 99, 132, 0.2)' }] } }, data: undefined }, T2M: { chart: ( state ) => { var labels = []; for ( var x = 0; x < state.charts.T2M.data.length; x++ ) { labels.push ( ( x + 1 ).toString () ); } return { labels: labels, datasets: [{ label: 'Temperature (C)', data: state.charts.T2M.data, fill: false, backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgba(255, 99, 132, 0.2)' }] } }, data: undefined }, WS10M: { chart: ( state ) => { var labels = []; for ( var x = 0; x < state.charts.WS10M.data.length; x++ ) { labels.push ( ( x + 1 ).toString () ); } return { labels: labels, datasets: [{ label: 'Windspeed (m / s)', data: state.charts.WS10M.data, fill: false, backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgba(255, 99, 132, 0.2)' }] } }, data: undefined } }, menuVisible: false, } } ToggleMenu () { // Updates the state this.setState ({ menuVisible: !this.state.menuVisible }); } UpdateChart ( longitude, latitude, start, end, parameter ) { ApiHandler.FetchAPIData ([parameter], longitude, latitude, start, end ) .then ( async ( result ) => { const data = Object.values ( JSON.parse ( result.data ).properties.parameter[parameter] ); const values = []; // Loops through the values and removes the ones that haven't been indexed for ( var x = 0; x < data.length; x++ ) { if ( data[x] > 0 ) { values.push ( data[x] ); } } var finalResult = Object.assign ( this.state ); finalResult["charts"][parameter]["data"] = values; this.setState ( finalResult ); }); } UpdateChartList ( charts ) { // Loops through each chart Object.entries ( charts ).map ( async ( chart ) => { // Checks if the chart should be visible if ( chart[1] ) { ApiHandler.FetchAPIData ([chart[0]]) .then ( async ( result ) => { const data = Object.values ( JSON.parse ( result.data ).properties.parameter[chart[0]] ); const values = []; // Loops through the values and removes the ones that haven't been indexed for ( var x = 0; x < data.length; x++ ) { if ( data[x] > 0 ) { values.push ( data[x] ); } } var finalResult = Object.assign ( this.state ); finalResult["charts"][chart[0]]["data"] = values; this.setState (finalResult); }); } return; }) } render () { return ( <div className="w-full h-screen"> <Sidebar Visible={ this.state.menuVisible } ToggleMenu={ this.ToggleMenu } /> <Navbar ToggleMenu={ this.ToggleMenu } /> <DataSelector OnChange={ this.UpdateChartList } /> { Object.entries ( this.state.charts ).map ( ( item, i ) => { if ( this.state.charts[item[0]].data ) { return <Chart key={ item[0] } Data={ item[1].chart ( this.state ) } Options={{ responsive: true, scales: { yAxes: [{ beginAtZero: true }] } }} UpdateCallback={ this.UpdateChart } Maximized={ false } Parameter={ item[0] } />; } else { return <div key={ item[0] } className="hidden"></div>; } }) } </div> ) } }
JavaScript
class DisableUpgradeClass extends superClass { /** @override */ static get observedAttributes() { return super.observedAttributes.concat(DISABLED_ATTR); } /** @override */ attributeChangedCallback(name, old, value) { if (name == DISABLED_ATTR) { if (!this.__dataEnabled && value == null && this.isConnected) { super.connectedCallback(); } } else { super.attributeChangedCallback(name, old, value); } } /* NOTE: cannot gate on attribute because this is called before attributes are delivered. Therefore, we stub this out and call `super._initializeProperties()` manually. */ /** @override */ _initializeProperties() {} // prevent user code in connected from running /** @override */ connectedCallback() { if (this.__dataEnabled || !this.hasAttribute(DISABLED_ATTR)) { super.connectedCallback(); } } // prevent element from turning on properties /** @override */ _enableProperties() { if (!this.hasAttribute(DISABLED_ATTR)) { if (!this.__dataEnabled) { super._initializeProperties(); } super._enableProperties(); } } // only go if "enabled" /** @override */ disconnectedCallback() { if (this.__dataEnabled) { super.disconnectedCallback(); } } }
JavaScript
class Workspace { static itemType = 'workspace' constructor ( owner_id=undefined, title='My new workspace', description='My workspace description', creationDate=undefined, id=undefined, color='black', icon='icon-apps', datasets=[], read='owner-only', comment='owner-only', // patch='owner-only', write='owner-only', manage='owner-only', tags=[], ) { this.owner_id = owner_id this.id = id this.title = title this.description = description this.creationDate = creationDate this.color = color this.icon = icon this.datasets = datasets this.read = read this.comment = comment // this.patch = patch this.write = write this.manage = manage this.tags = tags } get data () { return { owner_id: this.owner, id: this.id, title: this.title, description: this.description, creationDate: this.creationDate, color: this.color, icon: this.icon, datasets: this.datasets, read: this.read, comment: this.comment, // patch: this.patch, write: this.write, manage: this.manage, itemType: this.itemType, tags: this.tags } } get infos () { return [ ...models.itemInfosModel, ...models.itemTagsModel, ] } get auth () { return [ ...models.itemAuthModelBasic, ] } get share () { return [ ...models.itemUserSharingModel, ] } get prefs () { return [ ...models.itemPrefsModel, ] } get meta () { return [ ...models.itemMetaModel, ] } set randomBasics (value) { let iconsList = models.itemPrefsModel.find(pref => pref.name === 'icon').options.items const randomIconIdx = Math.floor(Math.random() * iconsList.length) this.icon = iconsList[randomIconIdx] } }
JavaScript
class ToDoList extends Component { constructor(props) { super(props) this.state = { inputedText: '', toDoList: props.list } // console.log('hi'); // let str0 = 'hello' // if (str0.includes('ll')) { // console.log('contain'); // } else { // console.log('not contain'); // } } // 获取当前store的state static contextTypes = { store: PropTypes.object, } getStoreState = () => { let list = this.context.store.getState() return list } onInputedTextChange = (e) => { let value = e.target.value this.setState({ inputedText: value }) if (!value.length) this.setState({toDoList: this.props.list}) } addItem = () => { let path = {pathname: '/to-do-item', itemId: -1} this.props.history.push(path) } pressEnterKey = (e) => { if(e.key === 'Enter') { this.search() } } deleteItem = (e, index) => { e.stopPropagation() // stop event bubbling this.props.deleteItem(index) this.setState({ toDoList: this.getStoreState() }) } search = () => { let inputedText = this.state.inputedText if (!inputedText.length) return let resultList = this.props.list.filter((item) => { return item.title.includes(inputedText) }) this.setState({toDoList: resultList}) } testAction = () => { } clickListItem = (index) => { // const path = `/repos/${userName}/${repo}` let path = {pathname: '/to-do-item', itemId: index} this.props.history.push(path) } render() { let listItems = this.state.toDoList.map((item, index) => { let listItem = ( <li className='to-do-item' onClick={(e) => this.clickListItem(item.id)} key={item.id}> <div className='item-left'> <div className='item-title'>{item.title} </div> <div className='item-content'>{item.completed ? '已完成' : '未完成'}</div> </div> <div className='item-delete' type='button' onClick={(e) => this.deleteItem(e, item.id)}>Delete</div> </li> ) // return <Link to={{pathname: '/to-do-item', itemId: index}} key={index}>{listItem}</Link> return listItem } ) return ( <div> <div className='container'> <div className='header'>待办事项</div> <div className='input-view'> <input className='input-field' type='text' value={this.state.inputedText} onChange={this.onInputedTextChange} placeholder='Input text to search' onKeyPress={this.pressEnterKey} /> {/* <button className='header-button' type='button' onClick={this.search}>Search</button> */} {/* <Link to='/to-do-item'> */} <button className='header-button' type='button' onClick={this.addItem}>Add</button> {/* </Link> */} <div className='input-view-bg'></div> </div> <div className='to-do-list'>{listItems}</div> </div> {/* <Link to='/about'> */} {/* <button className='test-button' onClick={this.testAction}>Test</button> */} {/* </Link> */} </div> ) } }
JavaScript
class SlideShow extends Component { async componentDidMount() { loadImages(); clearTimeout(this.slide_changer); this.changeSlide("right"); } // Move to next slide changeSlide(direction, component) { if (!component) { component = this; } // Reset auto timer clearTimeout(component.slide_changer); component.slide_changer = setTimeout( () => { component.changeSlide("right", component); }, 5000, { component }, ); // Remove animation class $("#SlideShow-list").attr("class", ""); // Dont move if less than 2 articles if (!this.props.news || this.props.news?.length < 2) { return; } // Timeout because css is funky like that setTimeout(() => { var children = Object.values($("#SlideShow-list").children()).slice( 0, -2, ); // Move last article to front or vice versa, depending on direction if (this.props.news?.length === 2) { children = [children[1], children[0], children[1]]; } else { if (direction === "left") { children = [children.slice(-1)[0], ...children.slice(0, -1)]; } else { children = [...children.slice(1), children[0]]; } } $("#SlideShow-list").html( children.map(i => { if (i) { return i.outerHTML; } }), ); // Add animation class $("#SlideShow-list").attr("class", direction); }, 10); } render() { return ( <div className="SlideShow"> {/* Wrapper */} <div className="wrap"> <ul id="SlideShow-list"> {(this.props.news || [{ skeleton: true }]).map((article, index) => { // Hidden article if (article.hide) { return ""; } return ( <li key={index} className={article.skeleton ? "skeleton" : ""}> <Link to={!this.props.news ? "." : "/news/" + article.id} reloadDocument tabIndex={-1} > {/* Image behind text */} <div className="img-wrap"> <img src={article.image} alt={article.alt || "Headline image"} title={article.alt || "Headline image"} className="unloaded" /> </div> {/* Watermark in top right */} <img src="/image/logo-short.png" alt={"Logo: Megaphone & Handshake"} className="watermark unloaded" /> {/* Text in front - headline and subtitle */} <div className="text-wrap"> <h1 className="headline"> <span> {article.headline || "Important News Headline"} </span> </h1> <h2 className="subtitle"> <span> {article.subtitle || "Subtitle of the Article"} </span> </h2> </div> </Link> </li> ); })} </ul> {/* Navigation buttons - Only show if more than one article */} {(() => { if (this.props.news?.length > 1) { return ( <div className="nav-buttons"> <button className="nav-button left" onClick={() => this.changeSlide("left")} > <i className="fa fa-chevron-left"></i> </button> <button className="nav-button right" onClick={() => this.changeSlide("right")} > <i className="fa fa-chevron-right"></i> </button> </div> ); } })()} </div> </div> ); } }
JavaScript
class PTapisRoulant { createBox() { const box = new Box(); return box; } createPaper() { const paper = new GiftWrap(); return paper; } createConveyorBelt() { const tapis = new ConveyorBelt(); return tapis; } }
JavaScript
class App extends Component { constructor(props) { super(props) console.log('[App.js] constructor', props) this.state = { humans: [ { id: 'asdfa1', name: 'Janko', age: 28 }, { id: 'asdfa2', name: 'Duri', age: 27 }, { id: 'asdfa3', name: 'Vierka', age: 20 }, ], showHumans: false, } } static getDerivedStateFromProps(props, state) { console.log('[App.js] getDrivedFromProps', props, state) return state } componentDidMount() { console.log('[App.js] componentDidMount') } deleteHumanHendler = indexOfHuman => { // nove pole, do ktoreho vlozim povodne pole humans const newHumans = [...this.state.humans] // toto nove pole vdaka splice zmazem newHumans.splice(indexOfHuman, 1) this.setState({ humans: newHumans }) } changeHumanName = (event, humanId) => { // v poli humans hladam konkretny index const indexOfHuman = this.state.humans.findIndex(item => { return item.id === humanId }) // nove pole do ktoreho vlozim povodne pole humans aj s indexom const human = { ...this.state.humans[indexOfHuman] } // meno sa mi bude menit podla toho co budem pisat do inputu human.name = event.target.value const newHumans = [...this.state.humans] newHumans[indexOfHuman] = human this.setState({ humans: newHumans }) } toggleHumansHandler = () => { this.setState({ showHumans: !this.state.showHumans }) } render() { console.log('[App.js] render', this.props, this.state) let humansNewElement = null if (this.state.showHumans) { humansNewElement = ( <Persons humans={this.state.humans} changed={this.changeHumanName} click={this.deleteHumanHendler} /> ) } return ( <Wrapper> <Text humans={this.state.humans}>Example text</Text> <Button onClick={this.toggleHumansHandler} showHumans={this.showHumans}> Switch name </Button> {humansNewElement} </Wrapper> ) } }
JavaScript
class SearchBar extends Component{ constructor(props){ super(props); //calls parent class Component constructor with super keyword. this.state = {term: ''} //init it with a new object. term is like search term for our app //we only use this.state in the constructor... everywhere else we use setstate. } render() { //{this.onInputChange} is a js variable.. so it's wrapped in brackets inside the jsx // return <input onChange={ event => console.log(event.target.value)} />; //only use setState outside of the constructor. return ( <div> <input value = {this.state.term} onChange={ event => this.setState({term: event.target.value})} /> </div> ); }; /* onInputChange(event){ console.log(event.target.value); added for after input as example. Value of the input : {this.state.term} } */ }
JavaScript
class FrontFrame { constructor(name) { this.name = name this.blob = null this.image = new Image() this.url = null this.loading = false this.loaded = false this.fresh = false this.onLoad = function () { this.loading = false this.loaded = true this.fresh = true // this.clean() }.bind(this) this.onError = function () { this.loading = false this.loaded = false }.bind(this) } load(blob) { // If someone's calling load() they're already sure that they don't need // the the current frame anymore. this.reset(); // Convenience check that must come after the reset. if(!blob) { return; } this.blob = blob this.url = URL.createObjectURL(this.blob) this.loading = true this.loaded = false this.fresh = false this.image.onload = this.onLoad this.image.onerror = this.onError this.image.src = this.url } // clean() { // this.image.onload = this.image.onerror = null; // this.image.src = BLANK_IMG; // this.image = null; // this.blob = null; // URL.revokeObjectURL(this.url); // this.url = null; // } reset() { this.loading = false this.loaded = false if (this.blob) { this.blob = null URL.revokeObjectURL(this.url) this.url = null } } consume() { if (!this.fresh) { return null } this.fresh = false return this } destory() { this.reset() this.image = null } }
JavaScript
class TimeDialogComponent { /** * @param {?} data * @param {?} color * @param {?} dialogRef */ constructor(data, color, dialogRef) { this.data = data; this.color = color; this.dialogRef = dialogRef; this.VIEW_HOURS = CLOCK_TYPE.HOURS; this.VIEW_MINUTES = CLOCK_TYPE.MINUTES; this.currentView = this.VIEW_HOURS; this.userTime = data.time; this.color = data.color; } /** * @return {?} */ revert() { this.dialogRef.close(-1); } /** * @return {?} */ submit() { this.dialogRef.close(this.userTime); } }
JavaScript
class TimeComponent { constructor() { this.userTimeChange = new EventEmitter(); this.onRevert = new EventEmitter(); this.onSubmit = new EventEmitter(); this.VIEW_HOURS = CLOCK_TYPE.HOURS; this.VIEW_MINUTES = CLOCK_TYPE.MINUTES; this.currentView = this.VIEW_HOURS; } /** * @return {?} */ ngOnInit() { if (!this.userTime) { this.userTime = { hour: 6, minute: 0, meriden: 'PM', format: 12 }; } if (!this.revertLabel) { this.revertLabel = 'Cancel'; } if (!this.submitLabel) { this.submitLabel = 'Okay'; } } /** * @return {?} */ formatHour() { if (this.userTime.format === 24) { if (this.userTime.hour === 24) { return '00'; } else if (this.userTime.hour < 10) { return '0' + String(this.userTime.hour); } } return String(this.userTime.hour); } /** * @return {?} */ formatMinute() { if (this.userTime.minute === 0) { return '00'; } else if (this.userTime.minute < 10) { return '0' + String(this.userTime.minute); } else { return String(this.userTime.minute); } } /** * @param {?} type * @return {?} */ setCurrentView(type) { this.currentView = type; } /** * @param {?} m * @return {?} */ setMeridien(m) { this.userTime.meriden = m; } /** * @return {?} */ revert() { this.onRevert.emit(); } /** * @return {?} */ submit() { this.onSubmit.emit(this.userTime); } /** * @param {?} event * @return {?} */ emituserTimeChange(event) { this.userTimeChange.emit(this.userTime); } }
JavaScript
class MouseManager { constructor() { this.x = 0; this.y = 0; this.windowX = 0; this.windowY = 0; this.buttons = { left: 0, middle: 1, right: 2, }; this.isDown = {}; window.addEventListener("mousemove", this._mousemove.bind(this)); window.addEventListener("mousedown", this._mousedown.bind(this)); window.addEventListener("mouseup", this._mouseup.bind(this)); window.addEventListener("contextmenu", e => e.preventDefault()); // Right click show options } /** * @description * Returns the mouse position relative to the canvas. * * @example * const { x, y } = Impacto.Inputs.Mouse.getPosition(); * * @returns {Object} The current mouse position {x, y} * @memberof MouseManager */ getPosition() { return { x: this.x, y: this.y, }; } /** * Returns the mouse position relative to the window. * * @example * const { x, y } = Impacto.Inputs.Mouse.getWindowPosition(); * * @returns {Object} The current mouse position {x, y} * @memberof MouseManager */ getWindowPosition() { return { x: this.windowX, y: this.windowY, }; } /** * Returns the name of the button by the button code. * * @example * console.log(Impacto.Inputs.Mouse.getNameByButtonCode(1)); // "middle" * * @param {number} buttonCode - The button code * @returns {string} The name of the button * @memberof MouseManager */ getNameByButtonCode(buttonCode) { switch (buttonCode) { case this.buttons.left: return "left"; case this.buttons.middle: return "middle"; case this.buttons.right: return "right"; default: return ""; } } /** * Returns the code of the button by the button name. * * @example * console.log(Impacto.Inputs.Mouse.getButtonCodeByName("left")); // 0 * * @param {string} buttonName - The name of the button * @returns {number} The button code * @memberof MouseManager */ getButtonKeyByName(name) { switch (name) { case "left": return this.buttons.left; case "middle": return this.buttons.middle; case "right": return this.buttons.right; default: return -1; } } /** * Returns if the button is pressed. * * @example * Impacto.Inputs.Mouse.isButtonPressed("left") // True * * @param {string|number} button - The button name or code * @returns {boolean} True if the button is pressed * @memberof MouseManager */ isButtonDown(button) { if (typeof button === "string") return this.isButtonDownByName(button); else if (typeof button === "number") return this.isButtonDownByButtonCode(button); } /** * Returns if the button is pressed by the button name. * * @example * Impacto.Inputs.Mouse.isButtonDownByName("left") // True * * @param {string|number} button - The button name * @returns {boolean} True if the button is pressed * @memberof MouseManager */ isButtonDownByName(name) { return !!this.isDown[name]; } /** * Returns if the button is pressed by the button code. * * @example * Impacto.Inputs.Mouse.isButtonDownByName(2) // True * * @param {string|number} button - The button code * @returns {boolean} True if the button is pressed * @memberof MouseManager */ isButtonDownByButtonCode(buttonCode) { return !!this.isDown[this.getNameByButtonCode(buttonCode)]; } // ------ /** * @description * Private (Core) function to handle the mouse position. * * @memberof KeyBoard * @private */ _updateMousePosition(e) { this.windowX = e.clientX; this.windowY = e.clientY; this.x = this.windowX - CanvasStateInstance.canvas.offsetLeft; this.y = this.windowY - CanvasStateInstance.canvas.offsetTop; } /** * @description * Private (Core) function to handle the mouse position. * * @memberof KeyBoard * @private */ _mousemove(e) { this._updateMousePosition(e); } /** * @description * Private (Core) function to handle the mouse position. * * @memberof KeyBoard * @private */ _mousedown(e) { this._updateMousePosition(e); this.isDown[this.getNameByButtonCode(e.button)] = true; } /** * @description * Private (Core) function to handle the mouse position. * * @memberof KeyBoard * @private */ _mouseup(e) { this._updateMousePosition(e); this.isDown[this.getNameByButtonCode(e.button)] = false; } }
JavaScript
class LicenceIntegrityError extends Error { constructor(status, message, description) { super(message); this.status = status; this.description = description; } getHttpResponse() { const responseBody = { status: this.status, title: this.message, detail: this.description, }; return { statusCode: this.status, body: JSON.stringify(responseBody), }; } }
JavaScript
class ConfigFile extends configStore_1.BaseConfigStore { /** * Returns the config's filename. * @returns {string} */ static getFileName() { // Can not have abstract static methods, so throw a runtime error. throw new sfdxError_1.SfdxError('Unknown filename for config file.'); } /** * Returns the default options for the config file. * @param {boolean} isGlobal If the file should be stored globally or locally. * @param {string} filename The name of the config file. * @return {ConfigOptions} The ConfigOptions. */ static getDefaultOptions(isGlobal = false, filename) { return { isGlobal, isState: true, filename: filename || this.getFileName() }; } /** * Helper used to determined what the local and global folder point to. * * @param {boolean} isGlobal True if the config should be global. False for local. * @returns {Promise<string>} The file path of the root folder. */ static async resolveRootFolder(isGlobal) { if (!lodash_1.isBoolean(isGlobal)) { throw new sfdxError_1.SfdxError('isGlobal must be a boolean', 'InvalidTypeForIsGlobal'); } return isGlobal ? os_1.homedir() : await internal_1.resolveProjectPath(); } /** * Create an instance of this config file, without actually reading or writing the file. * After the instance is created, you can call {@link ConfigFile.read} to read the existing * file or {@link ConfigFile.write} to create or overwrite the file. * * **Note:** Cast to the extended class. e.g. `await MyConfig.create<MyConfig>();` * * @param {ConfigOptions} [options] The options used to create the file. Will use {@link ConfigFile.getDefaultOptions} by default. * {@link ConfigFile.getDefaultOptions} with no parameters by default. */ static async create(options) { const config = new this(); config.options = options || this.getDefaultOptions(); if (!config.options.filename) { throw new sfdxError_1.SfdxError('The ConfigOptions filename parameter is invalid.', 'InvalidParameter'); } const _isGlobal = lodash_1.isBoolean(config.options.isGlobal) && config.options.isGlobal; const _isState = lodash_1.isBoolean(config.options.isState) && config.options.isState; // Don't let users store config files in homedir without being in the // state folder. let configRootFolder = config.options.rootFolder ? config.options.rootFolder : await this.resolveRootFolder(config.options.isGlobal); if (_isGlobal || _isState) { configRootFolder = path_1.join(configRootFolder, global_1.Global.STATE_FOLDER); } config.path = path_1.join(configRootFolder, config.options.filePath ? config.options.filePath : '', config.options.filename); return config; } /** * Creates the config instance and reads the contents of the existing file, if there is one. * * This is the same as * ``` * const myConfig = await MyConfig.create<MyConfig>(); * await myConfig.read(); * ``` * * **Note:** Cast to the extended class. e.g. `await MyConfig.retrieve<MyConfig>();` * * @param {ConfigOptions} [options] The options used to create the file. Will use {@link ConfigFile.getDefaultOptions} by default. * {@link ConfigFile.getDefaultOptions} with no parameters by default. */ static async retrieve(options) { const config = await this.create(options); await config.read(); return config; } /** * Determines if the config file is read/write accessible. * @param {number} perm The permission. * @returns {Promise<boolean>} `true` if the user has capabilities specified by perm. * @see {@link https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback|fs.access} */ async access(perm) { try { await fs.access(this.getPath(), perm); return true; } catch (err) { return false; } } /** * Read the config file and set the config contents. * @param {boolean} [throwOnNotFound = false] Optionally indicate if a throw should occur on file read. * @returns {Promise<object>} The config contents of the config file. * @throws {SfdxError} * **`{name: 'UnexpectedJsonFileFormat'}`:** There was a problem reading or parsing the file. */ async read(throwOnNotFound = false) { try { const obj = await json_1.readJsonMap(this.getPath()); this.setContentsFromObject(obj); return this.getContents(); } catch (err) { if (err.code === 'ENOENT') { if (!throwOnNotFound) { this.setContents(); return this.getContents(); } } throw err; } } /** * Write the config file with new contents. If no new contents are passed in * it will write the existing config contents that were set from {@link ConfigFile.read}, or an * empty file if {@link ConfigFile.read} was not called. * * @param {object} [newContents] The new contents of the file. * @returns {Promise<object>} The written contents. */ async write(newContents) { if (!lodash_1.isNil(newContents)) { this.setContents(newContents); } await fs.mkdirp(path_1.dirname(this.getPath())); await json_1.writeJson(this.getPath(), this.toObject()); return this.getContents(); } /** * Check to see if the config file exists. * * @returns {Promise<boolean>} True if the config file exists and has access, false otherwise. */ async exists() { return await this.access(fs_1.constants.R_OK); } /** * Get the stats of the file. * * @returns {Promise<fs.Stats>} stats The stats of the file. * @see {@link https://nodejs.org/api/fs.html#fs_fs_fstat_fd_callback|fs.stat} */ async stat() { return fs.stat(this.getPath()); } /** * Delete the config file if it exists. * * @returns {Promise<boolean>} True if the file was deleted, false otherwise. * @see {@link https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback|fs.unlink} */ async unlink() { const exists = await this.exists(); if (exists) { return await fs.unlink(this.getPath()); } throw new sfdxError_1.SfdxError(`Target file doesn't exist. path: ${this.getPath()}`, 'TargetFileNotFound'); } /** * Returns the path to the config file. * @returns {string} */ getPath() { return this.path; } /** * Returns true if this config is using the global path, false otherwise. * @returns {boolean} */ isGlobal() { return this.options.isGlobal; } }
JavaScript
class PropertyRadioGroup extends PureComponent { constructor(props) { super(props); this.handleRadioGroupChange = this.handleRadioGroupChange.bind(this); } handleRadioGroupChange(event) { this.props.onPropertyChanged(event.target.name, event.target.value); } render() { return ( <div> <Typography style={{ padding: '12px 0 0 0', }} type="body1" > {this.props.label} </Typography> <RadioGroup className={this.props.classes.subProperty} name={this.props.name} onChange={this.handleRadioGroupChange} selectedValue={this.props.selectedValue} > {this.props.values.map((value, i) => <FormControlLabel className={this.props.classes.radioButton} control={<Radio />} key={value} label={value} value={value} /> )} </RadioGroup> </div> ); } }
JavaScript
class JsonTemplates { constructor() { this.templates = {}; } contextCreated(context, next) { context.templateManager.register(this); return next(); } renderTemplate(context, language, templateId, data) { var result = this.render(`${language}-${templateId}`, data); if (result) return Promise.resolve(JSON.parse(result)); return Promise.resolve(undefined); } /** * Registers a new JSON template. The template will be compiled and cached. * * @param name Name of the template to register. * @param json JSON template. */ add(name, json) { this.templates[name] = JsonTemplates.compile(json, this.templates); return this; } /** * Registers a named function that can be called within a template. * * @param name Name of the function to register. * @param fn Function to register. */ addFunction(name, fn) { this.templates[name] = fn; return this; } /** * Renders a registered JSON template to a string using the given data object. * * @param name Name of the registered template to render. * @param data Data object to render template against. */ render(name, data) { let template = this.templates[name]; if (!template) return undefined; return template(data); } /** * Renders a registered JSON template using the given data object. The rendered string will * be `JSON.parsed()` into a JSON object prior to returning. * * @param name Name of the registered template to render. * @param data Data object to render template against. * @param postProcess (Optional) if `true` the rendered output object will be scanned looking * for any processing directives, such as @prune. The default value is `true`. */ renderAsJSON(name, data, postProcess) { var json = this.render(name, data); if (!json) return null; let obj = JSON.parse(json); if (postProcess || postProcess === undefined) { obj = this.postProcess(obj); } return obj; } /** * Post processes a JSON object by walking the object and evaluating any processing directives * like @prune. * @param object Object to post process. */ postProcess(object) { if (!processNode(object, {})) { // Failed top level @if condition return undefined; } return object; } /** * Compiles a JSON template into a function that can be called to render a JSON object using * a data object. * * @param json The JSON template to compile. * @param templates (Optional) map of template functions (and other compiled templates) that * can be called at render time. */ static compile(json, templates) { // Convert objects to strings for parsing if (typeof json !== 'string') { json = JSON.stringify(json); } // Parse JSON into an array of template functions. These will be called in order // to build up the output JSON object as a string. const parsed = parse(json, templates); // Return closure that will execute the parsed template. return (data, path) => { // Check for optional path. // - Templates can be executed as children of other templates so the path // specifies the property off the parent to execute the template for. let obj = ''; if (path) { const value = getValue(data, path); if (Array.isArray(value)) { // Execute for each child object let connector = ''; obj += '['; value.forEach((child) => { obj += connector; parsed.forEach((fn) => obj += fn(child)); connector = ','; }); obj += ']'; } else if (typeof value === 'object') { parsed.forEach((fn) => obj += fn(value)); } } else { parsed.forEach((fn) => obj += fn(data)); } return obj; }; } }
JavaScript
class ContentHolderAttachmentAction extends Component { constructor(props){ super(props) this.downloadAttachmentContent = this.downloadAttachmentContent.bind(this) this.viewAttachmentContent = this.viewAttachmentContent.bind(this) this.setAttachmentContent = this.setAttachmentContent.bind(this) } /** * Download the primary content */ downloadAttachmentContent(e){ e.preventDefault() contentHolderService .downloadAttachmentContentBlob(this.props.contentHolderId, this.props.containerId) .then( blob => { FileSaver.saveAs(blob, 'primary.txt'); }) } /** * View the primary content */ viewAttachmentContent(e){ e.preventDefault() contentHolderService .downloadAttachmentContent(this.props.contentHolderId, this.props.containerId) .then( response => { var blob = new Blob([response], { type: 'text/plain' }); var blobUrl = URL.createObjectURL(blob); var w = window.open(blobUrl) }) } /** * Upload the primary content */ setAttachmentContent(e){ e.preventDefault() } render(){ return (<> <Button onClick={this.viewAttachmentContent}><i className="fa fa-file fa-md"></i></Button> <Button onClick={this.setAttachmentContent}><i className="fa fa-upload fa-md"></i></Button> <Button onClick={this.downloadAttachmentContent}><i className="fa fa-download fa-md"></i></Button> </>) } }
JavaScript
class UserList extends React.Component { constructor(props) { super(props); this.state = { composed: null }; } /** * Receive new props and calculate and concat list * @param {Prop} newProps */ componentWillReceiveProps(newProps) { if (newProps.loading) return; console.log(newProps); let composed = newProps.followers && this.props.following ? { user: { edges: [ ...newProps.followers.user.edges, ...newProps.following.user.edges ] }, hasNextPage: newProps.followers.hasNextPage || newProps.following.hasNextPage, fetchNextPage: _.flow([ newProps.followers.fetchNextPage, newProps.following.fetchNextPage ]) } : newProps.followers ? newProps.followers : newProps.following ? newProps.following : null; this.setState({ composed }); this.props = newProps; } /** * Render function * @return {ReactDOM} */ render() { let { dispatch } = this.props; let composed = this.state.composed; if (!composed) { return <Spinner color='#00a6de' />; } let userList = _.chain(composed.user.edges).map(({ node }) => node).value(); return ( <List scrollEnabled={false} style={styles.container}> <FlatList data={userList} onEndReached={() => { if (!this.props.loading) { return composed.fetchNextPage(); } }} keyExtractor={({ id }) => id} renderItem={({ item: { id, login, name, avatarUrl, bio } }) => ( <ListItem avatar onPress={() => dispatch({ type: 'UserProfile', params: { user: { login } } })}> <Left> <Thumbnail small source={{ uri: avatarUrl }} /> </Left> <Body> <Text>{name}</Text> <Text note>{bio}</Text> </Body> <Right> <Text note>{login}</Text> </Right> </ListItem> )} /> </List> ); } }
JavaScript
class VideosService { constructor() { this.collection = 'videos'; this.db = new Db(); } // hint: pass the params as object to pass the key and forget about the params order async getVideos({ tags }) { // getAll will be in the lib/db module const videos = await this.db.getAll(this.collection, tags); return videos || []; } async getVideo({ videoId }) { const video = await this.db.get(this.collection, videoId); return video || []; } async createVideo({ video }) { const createVideoId = await this.db.create(this.collection, video); return createVideoId; } // hint: pass the params as object to pass the key and forget about the params order async updateVideo({ videoId, video }) { const updateVideoId = await this.db.update(this.collection, videoId, video); return updateVideoId; } async delete({ videoId }) { const deleteVideoId = await this.db.delete(this.collection, videoId); return deleteVideoId; } }
JavaScript
class ISOOnTCPParser extends Transform { constructor(opts) { opts = opts || {}; opts.readableObjectMode = true; opts.decodeStrings = true; super(opts); this._nBuffer = null; debug("new ISOOnTCPParser"); } _transform(chunk, encoding, cb) { debug("ISOOnTCPParser _transform"); let ptr = 0; if (this._nBuffer !== null) { chunk = Buffer.concat([this._nBuffer, chunk]); this._nBuffer = null; } // test for minimum length if (chunk.length < 7) { this._nBuffer = chunk; cb(); return; } while (ptr < chunk.length) { // TPKT header let tpktStart = ptr; let tpkt_version = chunk.readUInt8(ptr); let tpkt_reserved = chunk.readUInt8(ptr + 1); let tpkt_length = chunk.readUInt16BE(ptr + 2); let tpktEnd = tpktStart + tpkt_length; //we don't have enough data, let's backup it if (chunk.length < (ptr + tpkt_length)) { this._nBuffer = chunk.slice(ptr); cb(); return; } ptr += 4; let obj = { tpkt: { version: tpkt_version, reserved: tpkt_reserved } }; // TPDU let tpduStart = ptr; let tpdu_length = chunk.readUInt8(ptr) + 1; //+1, because the length itself is not included in protocol ptr += 1; let tpduEnd = tpduStart + tpdu_length; // test if TPDU header is within TPKT boundaries if (tpduEnd > tpktEnd){ cb(new Error(`TPDU header length [${tpdu_length}] out of bounds, TPKT lenght is [${tpkt_length}]`)); return; } // TPDU - fixed part let type_and_credit = chunk.readUInt8(ptr); ptr += 1; obj.type = type_and_credit >> 4; obj.credit = type_and_credit & 0xf; switch (obj.type) { case constants.tpdu_type.CR: case constants.tpdu_type.CC: case constants.tpdu_type.DR: if (tpduEnd - ptr < 5) { cb(new Error(`Not enough bytes for parsing TPDU header of type [${obj.type}], needs 5, has [${tpduEnd - ptr}]`)); return; } obj.destination = chunk.readUInt16BE(ptr); ptr += 2; obj.source = chunk.readUInt16BE(ptr); ptr += 2; let varfield = chunk.readUInt8(ptr); if (obj.type === constants.tpdu_type.DR) { obj.reason = varfield; } else { obj.class = varfield >> 4; obj.no_flow_control = (varfield & 0x1) > 0; obj.extended_format = (varfield & 0x2) > 0; } ptr += 1; break; case constants.tpdu_type.DT: case constants.tpdu_type.ED: if (tpduEnd - ptr < 1) { cb(new Error(`Not enough bytes for parsing TPDU header of type [${obj.type}], needs 1, has [${tpduEnd - ptr}]`)); return; } let nr_and_eot = chunk.readUInt8(ptr); obj.tpdu_number = nr_and_eot & 0x7f; obj.last_data_unit = (nr_and_eot & 0x80) > 0; ptr += 1; break; default: //throw if we can't handle it cb(new Error(`Unknown or not implemented TPDU type [${obj.type}]:[${constants.tpdu_type_desc[obj.type]}]`)); return; } // TPDU - variable part let var_params = []; while ((ptr - tpduStart) < tpdu_length) { if (tpduEnd - ptr < 2) { cb(new Error(`Not enough bytes for TPDU variable part header, ptr [${ptr}], start [${tpduStart}], length [${tpdu_length}]`)); return; } let var_code = chunk.readUInt8(ptr); ptr += 1; let var_length = chunk.readUInt8(ptr); ptr += 1; if (tpduEnd - ptr < var_length) { cb(new Error(`Not enough bytes for TPDU variable part item, ptr [${ptr}], start [${tpduStart}], length [${tpdu_length}]`)); return; } var_params.push({ code: var_code, data: chunk.slice(ptr, ptr + var_length) }); ptr += var_length; } for(let elm of var_params) { switch (elm.code) { case constants.var_type.TPDU_SIZE: obj.tpdu_size = 1 << elm.data.readUInt8(0); break; case constants.var_type.SRC_TSAP: obj.srcTSAP = elm.data.readUInt16BE(0); break; case constants.var_type.DST_TSAP: obj.dstTSAP = elm.data.readUInt16BE(0); break; default: //for now, throw if we don't have it implemented cb(new Error(`Unknown or not implemented variable parameter code [${elm.code}]:[${constants.var_type_desc[elm.code]}]`)); return; } } // TPDU - user data - data between tpduEnd and tpktEnd obj.payload = chunk.slice(tpduEnd, tpktEnd); this.push(obj); ptr = tpktEnd; } cb(); } }
JavaScript
class Transmitter { constructor() { this.callbacksMap = new Map() this.lastUid = -1 } subscribe(topic, callback) { if (typeof topic !== 'string' || typeof callback !== 'function') { return false } // topic is not registered yet if (!this.callbacksMap.has(topic)) { this.callbacksMap.set(topic, new Map()) } const token = `transmitter_uid_${String(++this.lastUid)}` this.callbacksMap.get(topic).set(token, callback) return token } publish(topic, message) { if (typeof topic !== 'string') { return false } if (this._topicHasSubscribers(topic)) { setTimeout(() => { if (this._topicHasSubscribers(topic)) { this._callSubscribers(this.callbacksMap.get(topic), topic, message) } }, 0) } return true } unsubscribe(value) { let result = false const isTopic = typeof value === 'string' && this.callbacksMap.has(value) const isToken = !isTopic && typeof value === 'string' const isFunction = typeof value === 'function' if (isTopic) { this.callbacksMap.delete(value) return true } if (!isToken && !isFunction) { return false } for (const topicCallbacks of this.callbacksMap.values()) { if (isToken && topicCallbacks.has(value)) { topicCallbacks.delete(value) result = true break } if (isFunction) { for (const [token, tokenCallback] of topicCallbacks) { if (tokenCallback === value) { topicCallbacks.delete(token) result = true } } } } return result } clearAllSubscriptions() { this.callbacksMap = new Map() return true } _topicHasSubscribers(topic) { return this.callbacksMap.has(topic) && this.callbacksMap.get(topic).size } _callSubscribers(subscribers, topic, message) { for (const callback of subscribers.values()) { try { callback(topic, message) } catch (e) { this._asyncReThrowException(e) } } } _asyncReThrowException(e) { setTimeout(() => { this._triggerException(e) }, 0) } // this code in a separate function to allow cover by unit tests _triggerException(e) { throw e } }
JavaScript
class Extender { static getType(x) { let sType = typeof x; if (sType === 'object') { if (x === null) { return 'null'; } if (Array.isArray(x)) { return 'array'; } } return sType; } static objectKeyMap(oObj, path = '') { let a = []; for (let key in oObj) { if (oObj.hasOwnProperty(key)) { let newPath = path + '.' + key; if (Extender.getType(oObj[key]) === 'object') { a = a.concat(Extender.objectKeyMap(oObj[key], newPath)); } else { a.push(newPath.substr(1)); } } } return a; } /** * list all keys that are present in a2 and absent in a1 * @param a1 {*} * @param a2 {*} * @return {{common: *[], missing: *[]}} */ static objectDiffKeys(a1, a2) { const m1 = Extender.objectKeyMap(a1); const m2 = Extender.objectKeyMap(a2); const common = m2.filter(l => m1.includes(l)); const missing = m2.filter(l => !m1.includes(l)); return {common, missing}; } /** * navigates into an object structure, according to the given path, and retrieves the node and key * in order to either set or get the values * @param oObj {*} * @param sBranch {string} * @returns {{node: *, key: string}} */ static objectReachBranch(oObj, sBranch) { const aBranches = sBranch.split('.'); const key = aBranches.pop(); const node = aBranches.reduce((prev, next) => { if (next in prev) { return prev[next]; } else { throw new Error('this key : "' + next + '" does not exist in this object'); } }, oObj); return {node, key}; } static objectMkBranch(oObj, sBranch) { const aBranches = sBranch.split('.'); aBranches.pop(); aBranches.reduce((prev, next) => { if (!(next in prev) || prev[next] === null || typeof prev[next] !== 'object') { prev[next] = {}; } return prev[next]; }, oObj); } /** * changes the value of an item, inside an objet at the given path * @param oObj {*} * @param sBranch {string} * @param newValue {*} */ static objectSet(oObj, sBranch, newValue) { const {node, key} = Extender.objectReachBranch(oObj, sBranch); if (Object.isSealed(node) && !(key in node)) { throw new Error('cannot set ' + key + ' property : object is sealed'); } node[key] = newValue; } /** * get the value of an item, inside an object at the given path * @param oObj {*} * @param sBranch {string} * @return {*} */ static objectGet(oObj, sBranch) { if (oObj === undefined) { throw new Error('objectGet : undefined object') } const {node, key} = Extender.objectReachBranch(oObj, sBranch); return node[key]; } /** * copies the items from "source" to "target" * @param oTarget * @param oSource * @param bExtends {boolean} if true, then the target will inherit all aditional branches present in oSource */ static objectExtends(oTarget, oSource, bExtends = false) { const {common, missing} = Extender.objectDiffKeys(oTarget, oSource); common.forEach(path => { Extender.objectSet(oTarget, path, Extender.objectGet(oSource, path)); }); if (bExtends) { missing.forEach(path => { Extender.objectMkBranch(oTarget, path); Extender.objectSet(oTarget, path, Extender.objectGet(oSource, path)); }); } return oTarget; } }
JavaScript
class Flic2Button extends EventEmitter { /** * Constructor. * * @class * @version 1.0.0 */ constructor(buttonData) { // extended class initialisation super(); // initialise this.setData(buttonData); } setData(buttonData) { // initialise this.uuid = buttonData.uuid; this.bluetoothAddress = buttonData.bluetoothAddress; this.name = buttonData.name; this.batteryLevelIsOk = buttonData.batteryLevelIsOk; this.voltage = buttonData.voltage; this.pressCount = buttonData.pressCount; this.firmwareRevision = buttonData.firmwareRevision; this.isUnpaired = !!buttonData.isUnpaired; this.isReady = !!buttonData.isReady; this.serialNumber = buttonData.serial; // check unpaired if (this.isUnpaired === true) { // the session is no longer valid // Flic docs tell us to forget the button this.forget(); } } /** * Event: did receive button event. * Emits the event we received from the button. * * @version 1.0.0 */ didReceiveButtonEvent(eventData){ // emit to application this.emit(eventData.event, { event: eventData.event, queued: eventData.queued, age: eventData.age, button: this, }); } connect(){ return Flic2.buttonConnect(this.uuid); } disconnect(){ // proxy call to parent return Flic2.buttonDisconnect(this.uuid); } forget(){ // proxy call to parent return Flic2.buttonForget(this.uuid); } setMode(mode){ // proxy call to parent return Flic2.buttonSetMode(this.uuid, mode); } setName(name){ // proxy call to parent return Flic2.buttonSetName(this.uuid, name); } getUuid(){ return this.uuid; } getBluetoothAddress(){ return this.bluetoothAddress; } getName(){ return this.name; } getBatteryLevelIsOk(){ return this.batteryLevelIsOk; } getVoltage(){ return this.voltage; } getPressCount(){ return this.pressCount; } getFirmwareRevision(){ return this.firmwareRevision; } getIsReady(){ return this.isReady; } getIsUnpaired(){ return this.isUnpaired; } getSerialNumber(){ return this.serialNumber; } }
JavaScript
class BotUsersController extends base_1.BaseFetchController { constructor(bot) { super(bot); } /** * Fetches the bot user * @returns {Promise<BotUser>} */ async fetchBot() { const user = await this.bot.api.fetchBotUser(); this.cache.add(user); if (this.bot.user) { this.bot.user.update(user.structure); } else { this.bot.user = user; } return user; } /** * Fetches a user by its ID * @param {Snowflake} id The user ID * @returns {Promise<User>} */ async fetch(id) { const user = await this.bot.api.fetchUser(id); this.cache.add(user); return user; } }