language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Node { constructor(key, value) { this.parent = null; this.child = null; this.key = key; this.value = value; } }
JavaScript
class App extends Component { render() { let routes = ( <Switch> {/*<Route path="/auth" component={asyncAuth}/>*/} <Route path="/service_description" exact component={ServiceDescription}/> <Route path="/search_result" exact component={SearchResult}/> <Route path="/product_review" exact component={ProductReview}/> <Route path="/location" exact component={Location}/> <Route path="/about" exact component={About}/> <Route path="/home" exact component={Home}/> <Route path="/feedback" exact component={Feedback}/> <Route path="/subscription" exact component={Subscription}/> <Route path="/" exact component={Main}/> <Redirect to={'/'}/> </Switch> ) return ( <div> {routes} </div> ) } }
JavaScript
class Beeper { constructor(freq=440, length=0.5) { this.freq = freq; this.length = length; this._synth = new Tone.Synth().toMaster(); } beep() { this._synth.triggerAttackRelease(this.freq, this.length); } }
JavaScript
class CycleBeeper { constructor(baseFreq=440, cycleFreq=3) { this.baseFreq = baseFreq; this.cycleFreq = cycleFreq; this._main = new Tone.Oscillator(this.baseFreq).toMaster(); this._lfo = new Tone.LFO(this.cycleFreq, 0, 1000); this._lfo.type = 'square'; this._lfo.connect(this._main.detune); this._sources = [this._lfo, this._main]; } start() { this._sources.map(x => x.start()); } stop() { this._sources.map(x => x.stop()); } }
JavaScript
class Rectangle extends Polygon { /** * The Rectangle constructor. * @constructor * @param {Number} width - the width. * @param {Number} height - the height. */ constructor({width, height}){ if(!width || width <= 0){ throw new Error('Invalid width value'); } if(!height || height <= 0){ throw new Error('Invalid height value'); } const sides = { a: width, b: height, c: height, d: width }; const angles = { a: 90, b: 90, c: 90, d: 90 }; super({vertices: 4, sides: sides, angles: angles}); } /** * For the given values, returns a solved Rectangle * @param {Number} width - the width. * @param {Number} height - the height. * @return {Rectangle} - the solved Rectangle */ static of(width, height) { const i = new Rectangle({width: width, height: height}); return i.solve(); } /** * Solves the Rectangle * @return {Rectangle} the solved Rectangle. */ solve() { if(this.solved){ return this; } this.perimeter = this.sides.a.plus(this.sides.b).mul(2); this.area = this.sides.a.times(this.sides.b); this.diagonals.a = this.sides.a.pow(2).plus(this.sides.b.pow(2)).sqrt(2); this.diagonals.b = this.diagonals.a; this.solved = true; return this; } }
JavaScript
class ServiceLoader { /** * A map containing all the instantiated services of the application. */ /** * The protected constructor of the service loader class. */ constructor() {// NOP _defineProperty(this, "_services", {}); } /** * The instance of the Service Loader. */ /** * Service loader instance getter. */ static get instance() { if (!ServiceLoader._instance) { ServiceLoader._instance = new ServiceLoader(); } return ServiceLoader._instance; } /** * Static method used to get a service from the service loader. * * @param serviceName The name of the service we want to get. */ static get(serviceName) { return ServiceLoader.instance._get(serviceName); } /** * Static method used to add a service to the service loader. * * @param serviceName The name of the service we want to add. * @param serviceInstance The service instance we want to add. */ static set(serviceName, serviceInstance) { return ServiceLoader.instance._set(serviceName, serviceInstance); } /** * Method used to get the services from the database. * * @param serviceName The name of the service. */ _get(serviceName) { return this._services[serviceName] || null; } /** * Method used to add a service to the service loader. * * @param serviceName The name of the service we want to add. * @param serviceInstance The service instance we want to add. */ _set(serviceName, serviceInstance) { this._services[serviceName] = serviceInstance; return serviceInstance; } }
JavaScript
class TraitSelector5e extends FormApplication { static get defaultOptions() { const options = super.defaultOptions; options.id = "trait-selector"; options.classes = ["pf2e"]; options.title = "Actor Trait Selection"; options.template = "systems/pf2e/templates/actors/trait-selector.html"; options.width = 200; return options; } /* -------------------------------------------- */ /** * Return a reference to the target attribute * @type {String} */ get attribute() { return this.options.name; } /* -------------------------------------------- */ /** * Provide data to the HTML template for rendering * @type {Object} */ getData() { // Get current values let attr = getProperty(this.object.data, this.attribute); if ( typeof attr.value === "string" ) attr.value = this.constructor._backCompat(attr.value, this.options.choices); if (!attr.value) attr.value = ""; // Populate choices const choices = duplicate(this.options.choices); for ( let [k, v] of Object.entries(choices) ) { choices[k] = { label: v, chosen: attr.value.includes(k) } } // Return data return { choices: choices, custom: attr.custom } } /* -------------------------------------------- */ /** * Support backwards compatibility for old-style string separated traits * @private */ static _backCompat(current, choices) { if ( !current || current.length === 0 ) return []; current = current.split(/[\s,]/).filter(t => !!t); return current.map(val => { for ( let [k, v] of Object.entries(choices) ) { if ( val === v ) return k; } return null; }).filter(val => !!val); } /* -------------------------------------------- */ /** * Update the Actor object with new trait data processed from the form * @private */ _updateObject(event, formData) { const choices = []; for ( let [k, v] of Object.entries(formData) ) { if ( v ) choices.push(k); } this.object.update({ [`${this.attribute}.value`]: choices, [`${this.attribute}.custom`]: formData.custom }); } }
JavaScript
class Headers extends Map { constructor(headers) { Object.freeze(super()); if (headers == null) return; if (typeof headers !== 'object') throw new TypeError(`Expected ${getName(this)}s to be an object ${hint(headers)}`); if (!isPlain(headers)) throw new TypeError(`Expected ${getName(this)}s to be a plain object ${hint(headers)}`); for (const name of Object.keys(headers)) this.set(name, headers[name]); } get(name) { if (typeof name !== 'string') throw new TypeError(`Expected ${getName(this)} name to be a string ${hint(name)}`); return super.get(name.toLowerCase()); } has(name) { if (typeof name !== 'string') throw new TypeError(`Expected ${getName(this)} name to be a string ${hint(name)}`); return super.has(name.toLowerCase()); } set(name, value) { if (typeof name !== 'string') throw new TypeError(`Expected ${getName(this)} name to be a string ${hint(name)}`); if (typeof value !== 'string') throw new TypeError(`Expected ${getName(this)} value to be a string ${hint(value)}`); return super.set(name.toLowerCase(), value); } delete(name) { if (typeof name !== 'string') throw new TypeError(`Expected ${getName(this)} name to be a string ${hint(name)}`); return super.delete(name.toLowerCase()); } }
JavaScript
class HttpService { /** * Gets the base url. * * @returns API's URL */ static _getBaseUrl = () => { if (isLocalServer) { return 'https://localhost:5001/v1/'; } return 'https://pokeapi.co/api/v2/'; }; /** * Gets the default headers. * * @returns default headers */ static _getDefaultHeaders = () => { }; /** * Makes the HTTP request. * * @static * @param {string} method HTTP request method * @param {string} url URL * @param {Object} data Payload that will be sent along with request * @param {Object} [headers={}] Request headers * @returns {Promise<any>} Promise * @memberof HttpService */ static async _request(method, url, data, headers) { // Prepares the request payload let request = { url: `${HttpService._getBaseUrl()}${url}`, method, headers: { ...(HttpService._getDefaultHeaders()), ...headers } }; // Depending on the method, set the request data if (method.toLowerCase() !== 'get') { request = { ...request, data }; } else if (data instanceof String) { request = data; } else if (data instanceof Object) { request = { ...request, params: data }; } // Makes the post request return axios(request); } /** * Makes the GET HTTP request. * * @static * @param {string} url URL * @param {Object} data Payload that will be sent along with request * @param {Object} [headers={}] Request headers * @returns {Promise<any>} Promise * @memberof HttpService */ static async get(url, data, headers) { return HttpService._request('get', url, data, headers, {}); } /** * Makes the POST HTTP request. * * @static * @param {string} url URL * @param {Object} data Payload that will be sent along with request * @param {Object} [headers={}] Request headers * @returns {Promise<any>} Promise * @memberof HttpService */ static async post(url, data, headers, config) { // Remove comment when API is finished return HttpService._request('post', url, data, headers, config); } /** * Makes the PUT HTTP request. * * @static * @param {string} url URL * @param {Object} data Payload that will be sent along with request * @param {Object} [headers={}] Request headers * @returns {Promise<any>} Promise * @memberof HttpService */ static async put(url, data, headers) { // Remove comment when API is finished return HttpService._request('put', url, data, headers); } /** * Makes the DELETE HTTP request. * * @static * @param {string} url URL * @param {Object} data Payload that will be sent along with request * @param {Object} [headers={}] Request headers * @returns {Promise<any>} Promise * @memberof HttpService */ static async delete(url, data, headers) { return HttpService._request('delete', url, data, headers); } }
JavaScript
class Delegator { /** * Constructor to delegate jobs to associate or disassociate tags to a channel video. * * @param {object} params * @param {array} params.tagIds * @param {array} [params.videoIds] * @param {array} [params.channelIds] * @param {boolean} params.isAddInChannelTagVideo * * @constructor */ constructor(params) { const oThis = this; oThis.tagIds = params.tagIds; oThis.videoIds = params.videoIds || []; oThis.channelIds = params.channelIds || []; oThis.isAddInChannelTagVideo = params.isAddInChannelTagVideo; oThis.channelIdToVideoTagsMap = {}; oThis.videoIdToVideoDetailsMap = {}; } /** * Main performer for class. * * @returns {Promise<void>} */ async perform() { const oThis = this; await oThis._validateAndSanitize(); await oThis._prepareDataForProcessing(); if (CommonValidator.validateNonEmptyObject(oThis.channelIdToVideoTagsMap)) { await oThis._performSpecificOperation(); } return responseHelper.successWithData({}); } /** * Validate and sanitize. * * @returns {Promise<void>} * @private */ async _validateAndSanitize() { const oThis = this; // Presently, either multiple video ids OR multiple channel ids are supported. Not both. if (oThis.videoIds.length > 0 && oThis.channelIds.length > 0) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_ctv_d_1', api_error_identifier: 'something_went_wrong', debug_options: { videoIds: oThis.videoIds, channelIds: oThis.channelIds } }) ); } // Nothing to do. if (oThis.tagIds.length === 0) { logger.error('Tag ids array cannot by empty'); return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_ctv_d_2', api_error_identifier: 'something_went_wrong', debug_options: { tagIds: oThis.tagIds } }) ); } } /** * Prepare data for processing. * * @sets oThis.channelIdToVideoTagsMap, oThis.videoIdTagIdToVideoDetailsMap * * @returns {Promise<void>} * @private */ async _prepareDataForProcessing() { const oThis = this; let preparedData = null; if (oThis.videoIds.length > 0) { preparedData = await new PrepareDataByVideoIdAndTagIds({ videoId: oThis.videoIds[0], tagIds: oThis.tagIds }).perform(); } else if (oThis.channelIds.length > 0) { preparedData = await new PrepareDataByChannelIdAndTagIds({ channelId: oThis.channelIds[0], tagIds: oThis.tagIds }).perform(); } else { logger.error('Both channel ids array and video ids array cannot be empty.'); return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_ctv_d_3', api_error_identifier: 'something_went_wrong', debug_options: { tagIds: oThis.tagIds } }) ); } if (preparedData.isFailure()) { return Promise.reject(preparedData); } oThis.channelIdToVideoTagsMap = preparedData.data.channelIdToVideoTagsMap; oThis.videoIdTagIdToVideoDetailsMap = preparedData.data.videoIdTagIdToVideoDetailsMap; } /** * Perform specific operation. * * @returns {Promise<void>} * @private */ async _performSpecificOperation() { const oThis = this; if (oThis.isAddInChannelTagVideo) { await new AddInChannelTagVideo({ channelIdToVideoTagsMap: oThis.channelIdToVideoTagsMap, videoIdTagIdToVideoDetailsMap: oThis.videoIdTagIdToVideoDetailsMap }).perform(); } else { if (CommonValidator.validateNonEmptyObject(oThis.videoIdTagIdToVideoDetailsMap)) { await new RemoveFromChannelTagVideo({ channelIdToVideoTagsMap: oThis.channelIdToVideoTagsMap, videoIdTagIdToVideoDetailsMap: oThis.videoIdTagIdToVideoDetailsMap }).perform(); } } } }
JavaScript
class _Union { /** * An empty type union * @type {_Union} */ static get empty() { return new _Union() } /** * @param {?_Any} [initial_type] */ constructor(initial_type = null) { /** @type {{[x: string]: _Any}} */ this.uniqueTypes = {} if(initial_type) { this.uniqueTypes[initial_type.typeSignature] = initial_type } } get asFalse() { let type = _Union.empty this.types.forEach(v => { let f = v.asFalse if(f) type.addType(f) }) return type } get asTrue() { let type = _Union.empty this.types.forEach(v => { let t = v.asTrue if(t) type.addType(t) }) return type } /** * @type {boolean} */ get isEmpty() { return !this.types.length } /** * @type {boolean} True if this is a "mixed" type */ get isMixed() { return( this.types.some( t => t.isMixed ) ) } /** * @type {_Any[]} */ get types() { return Object.values(this.uniqueTypes) } /** * @type {string} A string representation of the types, as meaningful for type * checking. */ get typeSignature() { if(this.isEmpty) { return "void" } else { return this.types.map(t => t.typeSignature).join(" | ") } } /** * @type {string} As typeSignature but bracketed if needed. */ get typeSignatureToken() { if(this.types.length > 1) { return `(${this.typeSignature})` } else { return this.typeSignature } } /** * Adds a type. Returns a derived type union which may not be the original. * @param {_Any} type * @returns {_Union} */ addType(type) { let merge_type = this.uniqueTypes[type.typeSignature] let new_type = merge_type ? merge_type.combineWith(type) : type if(merge_type && merge_type === new_type) { return this } if(this.types.length == 1) { let n = new _Union() n.uniqueTypes = Object.assign( { [type.typeSignature]: new_type, }, this.uniqueTypes ) return n } else { this.uniqueTypes[type.typeSignature] = new_type return this } } /** * Adds types. Returns a derived type union which may not be the original. * @param {_Union} union * @returns {_Union} */ addTypesFrom(union) { if(this.types.length == 0) { return union } else if(this.types.length == 1) { let n = this.copy() Object.assign(n.uniqueTypes, union.uniqueTypes) return n } else { Object.keys(union.uniqueTypes).forEach( k => { if(this.uniqueTypes[k]) { let merge_type = this.uniqueTypes[k].combineWith( union.uniqueTypes[k] ) if(merge_type !== this.uniqueTypes[k]) { this.uniqueTypes[k] = merge_type } } else { this.uniqueTypes[k] = union.uniqueTypes[k] } } ) return this } } /** * Returns all the known values coerced into the given type. If the values * are not all known, this will be null. * * @param {string} type eg "bool" * @returns {?Object[]} All values should be distinct. */ coercedValues(type) { if(this.isEmpty) return null if(this.types.some(t => !(t.values && t.values.length))) return null let out = {} switch(type) { case "bool": this.types.forEach(t => t.values.forEach(v => { out[+!!v] = !!v })) return Object.values(out) case "string": this.types.forEach(t => t.values.forEach(v => { out["" + v] = "" + v })) return Object.values(out) default: console.log(`Coercion to ${type} not yet implemented`) return null } } /** * Returns true if this set of types does not violate behaviour defined by * the supplied set of types. In other words, every type here must be * compliant with at least one type on the supplied union. * * (int) is compliant with (int|null); (int|null) is not compliant with (int). * * @param {?_Union} expected_type The other type * @param {(string) => string[]} resolver * @returns {boolean} */ compliesWith(expected_type, resolver) { if(!expected_type) { return false; } return ( expected_type.isMixed || this === expected_type || this.types.every( t => expected_type.types.some(et => t.compliesWith(et, resolver)) ) ) } /** * Produces a copy of this union, to shadow a variable copy * * @returns {_Union} */ copy() { let n = new _Union() Object.assign(n.uniqueTypes, this.uniqueTypes) return n } /** * * @param {_Union} union * @returns {_Union} */ difference(union) { let n = new _Union() Object.keys(this.uniqueTypes).forEach( t => { if(!union.uniqueTypes[t]) { n.addType(this.uniqueTypes[t]) } else { let tv = this.uniqueTypes[t].difference(union.uniqueTypes[t]) if(tv) { n.addType(tv) } } } ) return n } /** * Returns a derived type union which may not be the original, without the * named type. * * @param {string} type * @returns {_Union} */ excluding(type) { if(this.uniqueTypes[type]) { let n = this.copy() delete n.uniqueTypes[type] return n } else { return this } } /** * * @param {_Union} union * @returns {_Union} */ intersection(union) { let n = new _Union() Object.keys(this.uniqueTypes).forEach( t => { if(union.uniqueTypes[t]) { let tv = this.uniqueTypes[t].intersection(union.uniqueTypes[t]) if(tv) { n.addType(tv) } } } ) return n } /** * @type {string} Represents best expression of the object, rather than * simply its type signature. */ toString() { if(this.isEmpty) { return "void" } else { return this.types.join(" | ") } } /** * Adds a known value * * @param {string | number | boolean} v * @returns {_Union} */ withValue(v) { if(this.types.length == 1) { let n = new _Union() n.uniqueTypes = { [this.types[0].typeSignature]: this.types[0].withValue(v), } return n } else { return this } } }
JavaScript
class BasicView { constructor() { /** @private @type {string} */ this.pageTitle_ = DEFAULT_PAGE_TITLE; /** @private @type {?googSoy.data.SanitizedHtml} */ this.currentContent_ = null; } /** * Returns the current page's title. * @return {string} Title. */ getPageTitle() { return this.pageTitle_; } /** * @param {string} title */ setPageTitle(title) { this.pageTitle_ = title; } /** * Returns the main content of the page and null if blank. * @return {?googSoy.data.SanitizedHtml} */ getCurrentContent() { return this.currentContent_; } /** * Returns the raw content element. * @return {!Element} */ getCurrentContentElement() { return /** @type {!Element} */ (googDom.getElement('content')); } /** * @param {?googSoy.data.SanitizedHtml} currentContent */ setCurrentContent(currentContent) { this.currentContent_ = currentContent; } /** * Helper function for resetting and updating the whole page. Note that this * will reset any JSAction listeners registered. */ resetAndUpdate() { googDom.getDocument().documentElement.innerHTML = root(/** @type {!root.Params} */ ( {pageTitle: this.pageTitle_, content: this.currentContent_})); } /** * Public method for updating the current view. */ async renderView() { this.resetAndUpdate(); } }
JavaScript
class RdbCMSATranslationMatcher extends RdbaDatatables { /** * Class constructor. * * @param {object} options */ constructor(options) { super(options); this.dialogIDSelector = '#translationmatcher-editing-dialog'; this.formIDSelector = '#translationmatcher-list-form'; this.datatableIDSelector = '#translationMatcherListTable'; this.defaultSortOrder = [[2, 'desc']]; this.dataTableColumns = []; }// constructor /** * Activate data table. * * @private This method was called from `init()` method. * @returns {undefined} */ activateDataTable() { let $ = jQuery.noConflict(); let thisClass = this; let addedCustomResultControls = false; $.when(uiXhrCommonData)// uiXhrCommonData is variable from /assets/js/Controllers/Admin/UI/XhrCommonDataController/indexAction.js file .then(function() { return thisClass.buildColumns(); }) .done(function() { let dataTable = $(thisClass.datatableIDSelector).DataTable({ 'ajax': { 'url': RdbCMSATranslationMatcherIndexObject.getTranslationMatchRESTUrl, 'method': RdbCMSATranslationMatcherIndexObject.getTranslationMatchRESTMethod, 'dataSrc': 'listItems',// change array key of data source. see https://datatables.net/examples/ajax/custom_data_property.html 'data': function(data) { data['filter-tm_table'] = ($('#rdba-filter-tm_table').val() ? $('#rdba-filter-tm_table').val() : ''); } }, 'autoWidth': false,// don't set style="width: xxx;" in the table cell. 'columnDefs': thisClass.dataTableColumns, 'dom': thisClass.datatablesDOM, 'fixedHeader': true, 'language': datatablesTranslation,// datatablesTranslation is variable from /assets/js/Controllers/Admin/UI/XhrCommonDataController/indexAction.js file 'order': thisClass.defaultSortOrder, 'pageLength': parseInt(RdbaUIXhrCommonData.configDb.rdbadmin_AdminItemsPerPage), 'paging': true, 'pagingType': 'input', 'processing': true, 'responsive': { 'details': { 'type': 'column', 'target': 0 } }, 'searchDelay': 1300, 'serverSide': true, // state save ( https://datatables.net/reference/option/stateSave ). // to use state save, any custom filter should use `stateLoadCallback` and set input value. // maybe use keepconditions ( https://github.com/jhyland87/DataTables-Keep-Conditions ). 'stateSave': false });//.DataTable() // datatables events dataTable.on('xhr.dt', function(e, settings, json, xhr) { if (addedCustomResultControls === false) { // if it was not added custom result controls yet. // set additional data. json.RdbCMSATranslationMatcherIndexObject = RdbCMSATranslationMatcherIndexObject; // add search controls. thisClass.addCustomResultControls(json); // add bulk actions controls. thisClass.addActionsControls(json); addedCustomResultControls = true; } // add pagination. thisClass.addCustomResultControlsPagination(json); if (json && json.formResultMessage) { RdbaCommon.displayAlertboxFixed(json.formResultMessage, json.formResultStatus); } if (json) { if (typeof(json.csrfKeyPair) !== 'undefined') { RdbCMSATranslationMatcherIndexObject.csrfKeyPair = json.csrfKeyPair; } } })// datatables on xhr complete. .on('draw', function() { // add listening events. thisClass.addCustomResultControlsEvents(dataTable); })// datatables on draw complete. ; });// uiXhrCommonData.done() }// activateDataTable /** * Build data table dynamic columns. * * @private This method was called from `activateDataTable()`. * @returns {undefined} */ buildColumns() { let thisClass = this; return new Promise((resolve, reject) => { thisClass.dataTableColumns = []; let columns = []; columns[0] = { 'className': 'control', 'data': 'tm_id', 'orderable': false, 'searchable': false, 'targets': 0, 'render': function () { // make first column render nothing (for responsive expand/collapse button only). // this is for working with responsive expand/collapse column and AJAX. return ''; } }; columns[1] = { 'className': 'column-checkbox', 'data': 'tm_id', 'orderable': false, 'searchable': false, 'targets': 1, 'render': function(data, type, row, meta) { return '<input type="checkbox" name="tm_id[]" value="' + row.tm_id + '">'; } }; columns[2] = { 'data': 'tm_id', 'targets': 2, 'visible': false }; columns[3] = { 'data': 'tm_table', 'targets': 3, 'render': function(data, type, row, meta) { let source = document.getElementById('rdba-datatables-row-actions').innerHTML; let template = Handlebars.compile(source); row.RdbCMSATranslationMatcherIndexObject = RdbCMSATranslationMatcherIndexObject; let html = '<a class="rdbcmsa-translationmatcher-edit-openform" href="#' + row.tm_id + '" data-tm_id="' + row.tm_id + '">' + data + '</a>'; html += template(row); return html; } }; // below is dynamic columns depend on languages. let dynamicColumnStart = 4; if (RdbCMSATranslationMatcherIndexObject.languages) { for (const languageId in RdbCMSATranslationMatcherIndexObject.languages) { columns[dynamicColumnStart] = { 'data': 'matches', 'targets': dynamicColumnStart, 'render': function(data, type, row, meta) { let jsonMatches = JSON.parse(data); if (jsonMatches[languageId]) { let data_id = jsonMatches[languageId]; return '(' + data_id + ') ' + jsonMatches['data_id' + data_id].data_name + ' ' + '<small><em> &mdash; ' + jsonMatches['data_id' + data_id].data_type + '</em></small> ' ; } else { return ''; } } }; dynamicColumnStart++; } } // set defined columns to class property to use later. thisClass.dataTableColumns = columns; // done. resolve(columns); }); }// buildColumns /** * Initialize the class. * * @returns {undefined} */ init() { // activate data table. this.activateDataTable(); // Listn on click add button to open new dialog. this.listenClickAddOpenForm(); // Listn on click edit link to open new dialog. this.listenClickEditOpenForm(); // Listen on keyup and find data ID. this.listenKeyupFindDataId(); this.listenOnChangeAutocomplete(); // Listen editing form submit and make ajax request. this.listenEditingFormSubmit(); // Listen bulk actions form submit and make ajax request. this.listenBulkActionsFormSubmit(); }// init /** * Listen bulk actions form submit and make ajax request. * * @private This method was called from `init()` method. * @returns {undefined} */ listenBulkActionsFormSubmit() { let thisClass = this; document.addEventListener('submit', function(event) { if (event.target && '#' + event.target.id === thisClass.formIDSelector) { event.preventDefault(); let thisForm = event.target; // validate selected item. let formValidated = false; let itemIdsArray = []; thisForm.querySelectorAll('input[type="checkbox"][name="tm_id[]"]:checked').forEach(function(item, index) { itemIdsArray.push(item.value); }); if (itemIdsArray.length <= 0) { RDTAAlertDialog.alert({ 'text': RdbCMSATranslationMatcherIndexObject.txtPleaseSelectAtLeastOne, 'type': 'error' }); formValidated = false; } else { formValidated = true; } // validate selected action. let selectAction = thisForm.querySelector('#translationmatcher-list-actions'); if (formValidated === true) { if (selectAction && selectAction.value === '') { RDTAAlertDialog.alert({ 'text': RdbCMSATranslationMatcherIndexObject.txtPleaseSelectAction, 'type': 'error' }); formValidated = false; } else { formValidated = true; } } if (formValidated === true) { // if form validated. if (selectAction.value === 'delete') { // if action is delete. // ajax permanently delete post here. thisClass.listenBulkActionsFormSubmitDelete(itemIdsArray); } } }// endif event id is matched form. }); }// listenBulkActionsFormSubmit /** * Ajax delete items. * * @private This method was called from `listenBulkActionsFormSubmit()`. * @param {array} itemIdsArray * @returns {undefined} */ listenBulkActionsFormSubmitDelete(itemIdsArray) { if (!_.isArray(itemIdsArray)) { console.error('The IDs are not array.'); return false; } let thisClass = this; let thisForm = document.querySelector(this.formIDSelector); let submitBtn = thisForm.querySelector('button[type="submit"]'); let confirmValue = confirm(RdbCMSATranslationMatcherIndexObject.txtConfirmDelete); let formData = new FormData(thisForm); formData.append(RdbCMSATranslationMatcherIndexObject.csrfName, RdbCMSATranslationMatcherIndexObject.csrfKeyPair[RdbCMSATranslationMatcherIndexObject.csrfName]); formData.append(RdbCMSATranslationMatcherIndexObject.csrfValue, RdbCMSATranslationMatcherIndexObject.csrfKeyPair[RdbCMSATranslationMatcherIndexObject.csrfValue]); if (confirmValue === true) { // reset form result placeholder thisForm.querySelector('.form-result-placeholder').innerHTML = ''; // add spinner icon thisForm.querySelector('.action-status-placeholder').insertAdjacentHTML('beforeend', '<i class="fas fa-spinner fa-pulse fa-fw loading-icon" aria-hidden="true"></i>'); // lock submit button submitBtn.disabled = true; RdbaCommon.XHR({ 'url': RdbCMSATranslationMatcherIndexObject.deleteTranslationMatchRESTUrlBase + '/' + itemIdsArray.join(','), 'method': RdbCMSATranslationMatcherIndexObject.deleteTranslationMatchRESTMethod, 'contentType': 'application/x-www-form-urlencoded;charset=UTF-8', 'data': new URLSearchParams(_.toArray(formData)).toString(), 'dataType': 'json' }) .catch(function(responseObject) { // XHR failed. let response = responseObject.response; if (response && response.formResultMessage) { RDTAAlertDialog.alert({ 'type': 'danger', 'text': response.formResultMessage }); } if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { RdbCMSATranslationMatcherIndexObject.csrfKeyPair = response.csrfKeyPair; } return Promise.reject(responseObject); }) .then(function(responseObject) { // XHR success. let response = responseObject.response; // reload datatable. thisClass.reloadDataTable(); if (typeof(response) !== 'undefined') { RdbaCommon.displayAlertboxFixed(RdbCMSATranslationMatcherIndexObject.txtDeletedSuccessfully, 'success'); } if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { RdbCMSATranslationMatcherIndexObject.csrfKeyPair = response.csrfKeyPair; } return Promise.resolve(responseObject); }) .finally(function() { // remove loading icon thisForm.querySelector('.loading-icon').remove(); // unlock submit button submitBtn.disabled = false; }); }// endif confirmValue; }// listenBulkActionsFormSubmitDelete /** * Listn on click add button to open new dialog. * * @private This method was called from `init()` method. * @returns {undefined} */ listenClickAddOpenForm() { let thisClass = this; let addOpenFormButton = document.querySelector('.rdbcmsa-translationmatcher-add-openform'); if (addOpenFormButton) { addOpenFormButton.addEventListener('click', (event) => { event.preventDefault(); RdbCMSATranslationMatcherIndexObject.editingMode = 'add'; // set dialog header and reset editing form to its default values. document.getElementById('translationmatcher-editing-dialog-label').innerText = RdbCMSATranslationMatcherIndexObject.txtAddNew; thisClass.resetEditingForm(); (new RDTADialog).activateDialog(thisClass.dialogIDSelector); }); } }// listenClickAddOpenForm /** * Listn on click edit link to open new dialog. * * @private This method was called from `init()` method. * @returns {undefined} */ listenClickEditOpenForm() { let thisClass = this; const editLinkClass = 'rdbcmsa-translationmatcher-edit-openform'; document.addEventListener('click', (event) => { if (event.currentTarget.activeElement) { let thisLink = event.currentTarget.activeElement; if (thisLink.classList.contains(editLinkClass)) { event.preventDefault(); RdbCMSATranslationMatcherIndexObject.editingMode = 'edit'; // set dialog header and reset editing form to its default values. document.getElementById('translationmatcher-editing-dialog-label').innerText = RdbCMSATranslationMatcherIndexObject.txtEdit; thisClass.resetEditingForm(); // ajax get form data and render to the form fields. RdbaCommon.XHR({ 'url': RdbCMSATranslationMatcherIndexObject.getATranslationMatchRESTUrlBase + '/' + thisLink.dataset.tm_id, 'method': RdbCMSATranslationMatcherIndexObject.getATranslationMatchRESTMethod, 'contentType': 'application/x-www-form-urlencoded;charset=UTF-8', 'dataType': 'json' }) .then(function(responseObject) { // XHR success. let response = responseObject.response; // render data to form fields. let thisForm = document.getElementById('rdbcmsa-translationmatcher-editing-form'); thisForm.querySelector('#rdbcmsa-translationmatcher-tm_id').value = thisLink.dataset.tm_id; thisForm.querySelector('#rdbcmsa-translationmatcher-tm_table').value = response.result.tm_table; let matches = JSON.parse(response.result.matches); for (const languageId in RdbCMSATranslationMatcherIndexObject.languages) { let inputDataId = thisForm.querySelector('#rdbcmsa-translationmatcher-matches-' + languageId); let inputDataDisplay = thisForm.querySelector('#rdbcmsa-translationmatcher-matches-' + languageId + '-display'); if (matches[languageId]) { let thisDataId = matches[languageId]; inputDataId.value = thisDataId; let matchesDataId = matches['data_id' + thisDataId]; inputDataDisplay.value = '(' + thisDataId + ') ' + matchesDataId.data_name + ' - ' + matchesDataId.data_type; } }// endfor; }, function(error) { // prevent Uncaught (in promise) error. return Promise.reject(error); }) .then(function(responseObject) { // activate dialog. (new RDTADialog).activateDialog(thisClass.dialogIDSelector); }, function(error) { // prevent Uncaught (in promise) error. return Promise.reject(error); }) .catch(function(responseObject) { // XHR failed. console.error('XHR error', responseObject); }); } } }); }// listenClickEditOpenForm /** * Listen editing form submit and make ajax request. * * @private This method was called from `init()` method. * @returns {undefined} */ listenEditingFormSubmit() { let thisClass = this; let thisForm = document.getElementById('rdbcmsa-translationmatcher-editing-form'); let submitBtn = thisForm.querySelector('button[type="submit"]'); let ajaxSubmitting = false; if (thisForm) { thisForm.addEventListener('submit', (event) => { event.preventDefault(); // reset form result placeholder thisForm.querySelector('.form-result-placeholder').innerHTML = ''; // add spinner icon thisForm.querySelector('.submit-button-row .control-wrapper').insertAdjacentHTML('beforeend', '<i class="fas fa-spinner fa-pulse fa-fw loading-icon" aria-hidden="true"></i>'); // lock submit button submitBtn.disabled = true; let ajaxFormUrl = ''; let ajaxFormMethod = 'POST'; if (RdbCMSATranslationMatcherIndexObject.editingMode === 'add') { // if it is adding new data. ajaxFormUrl = RdbCMSATranslationMatcherIndexObject.addTranslationMatchRESTUrl; } else { // if it is editing exists data. ajaxFormUrl = RdbCMSATranslationMatcherIndexObject.editTranslationMatchRESTUrlBase + '/' + thisForm.querySelector('#rdbcmsa-translationmatcher-tm_id').value; ajaxFormMethod = RdbCMSATranslationMatcherIndexObject.editTranslationMatchRESTMethod; } let formData = new FormData(thisForm); formData.append(RdbCMSATranslationMatcherIndexObject.csrfName, RdbCMSATranslationMatcherIndexObject.csrfKeyPair[RdbCMSATranslationMatcherIndexObject.csrfName]); formData.append(RdbCMSATranslationMatcherIndexObject.csrfValue, RdbCMSATranslationMatcherIndexObject.csrfKeyPair[RdbCMSATranslationMatcherIndexObject.csrfValue]); if (ajaxSubmitting === false) { ajaxSubmitting = true; // ajax submit form. RdbaCommon.XHR({ 'url': ajaxFormUrl, 'method': ajaxFormMethod, 'contentType': 'application/x-www-form-urlencoded;charset=UTF-8', 'data': new URLSearchParams(_.toArray(formData)).toString(), 'dataType': 'json' }) .then(function(responseObject) { // XHR success. let response = responseObject.response; if (response.savedSuccess === true) { // if saved successfully. // reset form. thisClass.resetEditingForm(); // this is opening in dialog, close the dialog and reload page. document.querySelector(thisClass.dialogIDSelector + ' [data-dismiss="dialog"]').click(); // reload datatable. jQuery(thisClass.datatableIDSelector).DataTable().ajax.reload(null, false); } if (response && response.formResultMessage) { // if there is form result message, display it. RdbaCommon.displayAlertboxFixed(response.formResultMessage, response.formResultStatus); } if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { RdbCMSATranslationMatcherIndexObject.csrfKeyPair = response.csrfKeyPair; } return Promise.resolve(responseObject); }, function(error) { // prevent Uncaught (in promise) error. return Promise.reject(error); }) .catch(function(responseObject) { // XHR failed. let response = responseObject.response; if (response && response.formResultMessage) { let alertClass = RdbaCommon.getAlertClassFromStatus(response.formResultStatus); let alertBox = RdbaCommon.renderAlertHtml(alertClass, response.formResultMessage); thisForm.querySelector('.form-result-placeholder').innerHTML = alertBox; } if (typeof(response) !== 'undefined' && typeof(response.csrfKeyPair) !== 'undefined') { RdbCMSATranslationMatcherIndexObject.csrfKeyPair = response.csrfKeyPair; } return Promise.reject(responseObject); }) .finally(function() { // remove loading icon let loadingIcon = thisForm.querySelector('.loading-icon'); if (loadingIcon) { loadingIcon.remove(); } // unlock submit button submitBtn.disabled = false; // restore ajax submitting. ajaxSubmitting = false; }); }// endif; ajaxSubmitting });// event listener } }// listenEditingFormSubmit /** * Listen on keyup and find data ID. * * @private This method was called from `init()` method. * @returns {undefined} */ listenKeyupFindDataId() { let thisClass = this; let matchesInputId = document.querySelectorAll('.rdbcmsa-translationmatcher-matches-input-id-display'); let tmId = document.querySelector('#rdbcmsa-translationmatcher-editing-form #rdbcmsa-translationmatcher-tm_id'); let tmTable = document.querySelector('#rdbcmsa-translationmatcher-editing-form #rdbcmsa-translationmatcher-tm_table'); if (matchesInputId) { matchesInputId.forEach((item, index) => { item.addEventListener( 'keyup', RdsUtils.delay(function(event) { let inputIdHidden = item.previousElementSibling; let dataResultList = document.getElementById('prog_data-result'); inputIdHidden.value = ''; dataResultList.innerHTML = ''; RdbaCommon.XHR({ 'url': RdbCMSATranslationMatcherIndexObject.searchEditingTranslationMatchRESTUrl + '?tm_table=' + tmTable.value + '&prog_data-input=' + item.value + '&prog_language-id=' + item.dataset.languageId + '&editingMode=' + RdbCMSATranslationMatcherIndexObject.editingMode + '&tm_id=' + tmId.value, 'method': RdbCMSATranslationMatcherIndexObject.searchEditingTranslationMatchRESTMethod, 'dataType': 'json' }) .then(function(responseObject) { // XHR success. let response = responseObject.response; if (RdbaCommon.isset(() => response.items)) { response.items.forEach((item, index) => { // option value must contain everything user typed or it won't show up. // example: user type 1 but result in value is "my post" then it won't show up. it must be "(1) my post". let option = '<option data-data_name="' + item.data_name + '" data-data_id="' + item.data_id + '" value="(' + item.data_id + ') ' + item.data_name + ' - ' + item.data_type + '"></option>'; dataResultList.insertAdjacentHTML('beforeend', option); }); } return Promise.resolve(responseObject); }, function(error) { // prevent Uncaught (in promise) error. return Promise.reject(error); }) .catch(function(responseObject) { // XHR failed. let response = responseObject.response; console.error(responseObject); return Promise.resolve(responseObject); }); }, 500) ); }); } }// listenKeyupFindDataId /** * Listen on change (on select) auto complete value of find tag field and make the custom result from datalist. * * @private This method was called from `init()` method. * @returns {undefined} */ listenOnChangeAutocomplete() { document.addEventListener('input', function(event) { if ( RdbaCommon.isset(() => event.target.classList) && event.target.classList.contains('rdbcmsa-translationmatcher-matches-input-id-display') ) { event.preventDefault(); let thisInput = event.target; let selectedValue = event.target.value;// <option value="xxx"> let selectedDatalist = document.querySelector('#prog_data-result option[value="' + selectedValue + '"]'); let inputIdHidden = thisInput.previousElementSibling; if (selectedDatalist) { thisInput.value = selectedValue; inputIdHidden.value = selectedDatalist.dataset.data_id; } } }); }// listenOnChangeAutocomplete /** * Reload data table and filters. * * @private This method was called from `listenFormSubmitAjaxBulkActions()`, `listenFormSubmitAjaxDelete()` methods. * @returns {undefined} */ reloadDataTable() { let thisClass = this; jQuery(thisClass.datatableIDSelector).DataTable().ajax.reload(null, false); }// reloadDataTable /** * Reset data tables. * * Call from HTML button.<br> * Example: <pre> * &lt;button onclick=&quot;return ThisClassName.resetDataTable();&quot;&gt;Reset&lt;/button&gt; * </pre> * * @returns {false} */ static resetDataTable() { let $ = jQuery.noConflict(); let thisClass = new this(); // reset form document.getElementById('rdba-filter-tm_table').value = ''; document.getElementById('rdba-filter-search').value = ''; // datatables have to call with jQuery. $(thisClass.datatableIDSelector).DataTable().order(thisClass.defaultSortOrder).search('').draw();// .order must match in columnDefs. return false; }// resetDataTable /** * Reset editing form (in dialog) to its default values. * * @private This method was called from `listenClickAddOpenForm()`, `listenClickEditOpenForm()`, `listenEditingFormSubmit()`. * @returns {undefined} */ resetEditingForm() { let thisForm = document.getElementById('rdbcmsa-translationmatcher-editing-form'); thisForm.querySelector('.form-result-placeholder').innerHTML = ''; thisForm.querySelector('#rdbcmsa-translationmatcher-tm_id').value = ''; thisForm.querySelector('#rdbcmsa-translationmatcher-tm_table').value = 'posts'; thisForm.querySelectorAll('.rdbcmsa-translationmatcher-matches-input-id') .forEach((item, index) => { item.value = ''; }); thisForm.querySelectorAll('.rdbcmsa-translationmatcher-matches-input-id-display') .forEach((item, index) => { item.value = ''; }); thisForm.querySelector('#prog_data-result').innerHTML = ''; let loadingIcon = thisForm.querySelector('.submit-button-row .loading-icon'); if (loadingIcon) { loadingIcon.remove(); } }// resetEditingForm }// RdbCMSATranslationMatcher
JavaScript
class FieldSchema extends HashBrown.Entity.Resource.SchemaBase { static get type() { return 'field'; } /** * Structure */ structure() { super.structure(); this.def(String, 'editorId'); this.name = 'New field schema'; } /** * Instantiates a resource * * @param {Object} params * * @return {HashBrown.Entity.Resource.FieldSchema} Instance */ static new(params = {}) { checkParam(params, 'params', Object) params = params || {}; return new this(params); } /** * Appends properties to this config * * @param {Object} config */ appendConfig(config) { function recurse(source, target) { for(let k in source) { // If key doesn't exist, append immediately if(!target[k]) { target[k] = source[k]; } else if( (target[k] instanceof Object && source[k] instanceof Object) || (target[k] instanceof Array && source[k] instanceof Array) ) { recurse(source[k], target[k]); } } } recurse(config, this.config); } /** * Merges two sets of schema data * * @param {HashBrown.Entity.Resource.SchemaBase} parentSchema */ merge(parentSchema) { super.merge(parentSchema); this.editorId = this.editorId || parentSchema.editorId; } }
JavaScript
class Nodo{ constructor(indice){ this.indice = indice this.lista = [] // lista de llaves } }
JavaScript
class Key{ constructor(clave, valor){ this.clave = clave this.valor = valor } }
JavaScript
class SocketToAccountMap { /** * An organized way to store sockets and their account details. */ constructor() { this.accounts = {}; this.delimiter = '\n'; } /** * Get all the web client sockets listening of a particular account name. * @param {string} accountName * @returns {SocketIO.Socket[]} */ getClients(accountName) { var result = []; var account = this.accounts[accountName]; if (account && account.clients) { result = account.clients; } return result; } /** * Adds a new web client socket to our list for a particular account. * @param {string} accountName * @param {SocketIO.Socket} clientSocket */ addClient(accountName, clientSocket) { this.accounts[accountName] = this.accounts[accountName] || {}; var account = this.accounts[accountName]; account.clients = account.clients || []; account.clients.push(clientSocket); if (!clientSocket.cli) { for (var robotSocket of this.getRobots(accountName)) { this.sendRobotStateToClients(robotSocket); } } } /** * Gets rid of a web client socket from our list for a particular account. * @param {string} accountName * @param {SocketIO.Socket} clientSocket * @returns {boolean} */ removeClient(accountName, clientSocket) { clientSocket.removeAllListeners(); var result = false; var account = this.accounts[accountName]; if (account && account.clients) { account.clients = account.clients.filter(socket => socket !== clientSocket); result = true; } return result; } /** * Send something to all web clients listening for a particular account. * @param {string} accountName * @param {string} eventName * @param {object} data * @returns {boolean} */ sendToClients(accountName, eventName, data) { var result = false; this.getClients(accountName).forEach((clientSocket)=>{ clientSocket.emit(eventName, data); result = true; }); return result; } /** * Get the socket for all robots of a certain account. * @param {string} accountName * @returns {object[]} */ getRobots(accountName) { var result = []; var account = this.accounts[accountName]; if (account && account.robots) { result = Object.keys(account.robots).filter(key=>account.robots[key]).map(key => account.robots[key]); } return result; } /** * Get the socket for a certain robot of a certain account. * @param {string} accountName * @param {string} robotName * @returns {object} */ getRobot(accountName, robotName) { var result = undefined; var account = this.accounts[accountName]; if (account && account.robots) { result = account.robots[robotName]; } return result; } /** * Set the socket for a certain robot of a certain account. * @param {string} accountName * @param {string} robotName * @param {object} robotSocket * @returns {boolean} */ setRobot(accountName, robotName, robotSocket) { this.accounts[accountName] = this.accounts[accountName] || {}; var account = this.accounts[accountName]; account.robots = account.robots || {}; account.robots[robotName] = robotSocket; if (robotSocket) {this.sendRobotStateToClients(robotSocket);} } /** * Send some data to a specific robot of a specific account. * @param {string} accountName * @param {string} robotName * @param {object} commandInformation * @returns {boolean} */ sendToRobot(accountName, robotName, commandInformation) { let result = false; var robotSocket = this.getRobot(accountName, robotName); if (robotSocket) { robotSocket.write(JSON.stringify(commandInformation) + this.delimiter); result = true; } return result; } /** * Used when robots or web clients connect to the server to send the current state of robots. * @param {object} robotSocket */ sendRobotStateToClients(robotSocket) { this.sendToClients(robotSocket.id.account, "listen start", {robot: robotSocket.id.robot}); this.sendToRobot(robotSocket.id.account, robotSocket.id.robot, {name: "sendPosition", parameters: []}); this.sendToRobot(robotSocket.id.account, robotSocket.id.robot, {name: "scanArea", parameters: [1]}); this.sendToRobot(robotSocket.id.account, robotSocket.id.robot, {name: "sendComponents", parameters: []}); } }
JavaScript
class mxDefaultPopupMenuCodec extends mxObjectCodec { constructor() { super(new mxDefaultPopupMenu()); } /** * Function: encode * * Returns null. */ encode(enc, obj) { return null; } /** * Function: decode * * Uses the given node as the config for <mxDefaultPopupMenu>. */ decode(dec, node, into) { const inc = node.getElementsByTagName('include')[0]; if (inc != null) { this.processInclude(dec, inc, into); } else if (into != null) { into.config = node; } return into; } }
JavaScript
class ALMemoryBridge { static logger = new Logger(debug.ALMemoryBridge, "AlMemoryBridge"); static initBridge = () => { const toolbarState = common.toolbarState; Promise.all([ QiWrapper.listen(toolbarState["ALMemory"], this.handleToolbarChange(toolbarState)), QiWrapper.listen(generalManagerHRI["currentStep"]["ALMemory"], this.handleChangeCurrentStep()), QiWrapper.listen(generalManagerHRI["stepCompleted"]["ALMemory"], this.handleStepCompleted()), QiWrapper.listen(generalManagerHRI["stepSkipped"]["ALMemory"], this.handleSetStepSkipped()), QiWrapper.listen(generalManagerHRI["timerState"]["ALMemory"], this.handleToggleTimer()), QiWrapper.listen(generalManagerHRI["currentScenario"]["ALMemory"], this.handleChangeCurrentScenario()), QiWrapper.listen(tabletLM["currentView"]["ALMemory"], this.handleChangeCurrentView()), QiWrapper.listen(generalManagerHRI["resetSteps"]["ALMemory"], this.handleResetSteps()) ]).then(() => { setInterval(async () => { await QiWrapper.raise(common.jsHeartbeat["ALMemory"], {'time': Date.now()}); dispatch({ 'type': comAction.extHeartbeat.type, 'time': { lm: JSON.parse(await QiWrapper.getALValue(common["localManagerHeartbeat"]["ALMemory"])).time, // gm: JSON.parse(await QiWrapper.getALValue(common.generalManagerHeartbeat.ALMemory)).time } }) }, 1000) }) }; static handleChangeCurrentView = () => data => { ALMemoryBridge.logger.log("handleChangeCurrentView", data) if (data.view !== undefined || data.data !== undefined) { dispatch({ type: viewAction.changeView.type, view: data.view, data: data.data }) } }; static handleChangeCurrentScenario = () => (data) => { ALMemoryBridge.logger.log("handleChangeCurrentScenario", data) dispatch({ type: scenarioAction.currentScenario.type, scenarioName: data["scenarioName"] }); dispatch({ type: timeAction.replaceAllSteps.type, steps: data["stepsList"] }) }; static handleToggleTimer = () => (data) => { if ([timeAction.timerState.state.on, timeAction.timerState.state.off].includes(data.state)) { dispatch({ type: timeAction.timerState.type, state: data.state }) } else { ALMemoryBridge.logger.warn("Unknown mode for timerState"); } }; static handleSetStepSkipped = () => (data) => { ALMemoryBridge.logger.log("handleSetStepSkipped", data) dispatch({ type: timeAction.stepSkipped.type, indexes: data.indexes }) }; static handleStepCompleted = () => (data) => { ALMemoryBridge.logger.log("handleStepCompleted", data) dispatch({ type: timeAction.stepCompleted.type, indexes: data.indexes }) }; static handleChangeCurrentStep = () => (data) => { ALMemoryBridge.logger.log("handleStepCompleted", data) dispatch({ type: timeAction.currentStep.type, index: data.index }) }; static handleToolbarChange = changeToolbar => data => { ALMemoryBridge.logger.log("handleToolbarChange", data) const possibleState = [changeToolbar.state.ok, changeToolbar.state.error]; if (possibleState.includes(data.state)) { const possibleSystems = []; const systemKeys = Object.keys(changeToolbar.system); systemKeys.forEach(key => { possibleSystems.push(common.toolbarState.system[key]) }); if (possibleSystems.includes(data.system)) { dispatch({ type: toolbarAction.toolbarState.type, system: data.system, state: data.state }) } else { ALMemoryBridge.logger.warn("Listen toolbarState", "Unknown data.system") } } else { ALMemoryBridge.logger.warn("Listen toolbarState", "Unknown data.state") } }; static handleResetSteps = () => data => { ALMemoryBridge.logger.log("handleResetSteps", data) dispatch({ type: timeAction.resetStepsProgression.type, state: true }) } }
JavaScript
class Vector { constructor(x, y, z) { this.x = x || 0 this.y = y || 0 this.z = z || 0 } set(x, y, z) { this.x = x || 0 this.y = y || 0 this.z = z || 0 } equals(x, y, z) { if (x instanceof Vector) return this.x === x.x && this.y === x.y && this.z === x.z else return this.x === x || (0 && this.y === y) || (0 && this.z === z) || 0 } copy() { return new Vector(this.x, this.y, this.z) } add(x, y, z) { if (x instanceof Vector) { this.x += x.x this.y += x.y this.z += x.z return this } this.x += x || 0 this.y += y || 0 this.z += z || 0 return this } sub(x, y, z) { if (x instanceof Vector) { this.x -= x.x this.y -= x.y this.z -= x.z return this } this.x -= x || 0 this.y -= y || 0 this.z -= z || 0 return this } mul(other) { this.x *= other.x this.y *= other.y this.z *= other.z return this } div(other) { this.x /= other.x this.y /= other.y this.z /= other.z return this } get mag() { return Math.hypot(this.x, this.y, this.z) } norm() { const x = this.x / this.mag const y = this.y / this.mag const z = this.z / this.mag return new Vector(x, y, z) } dist(other) { const dx = this.x - other.x const dy = this.y - other.y const dz = this.z - other.z return Math.hypot(dx, dy, dz) } rotate(angle) { this.x = this.x * Math.cos(angle) - this.y * Math.sin(angle) this.y = this.x * Math.sin(angle) + this.y * Math.cos(angle) return this } }
JavaScript
class Observable extends _events.default { /** * Registers an Observable * * @param entityName The name of the entity * @param type The type of the Observable * @param isPost if the action is a post action * @param callback The callback to be executed * */ registerObservable(entityName, type, isPost, callback) { this.on(`${entityName}:${type}:${isPost ? "post" : "pre"}`.toLowerCase(), callback); } /** * Registers a Save Post Observable * * @param entityName The entity name * @param callback The callback to be executed * */ registerSavePost(entityName, callback) { this.registerObservable(entityName, ObservableType.SAVE, true, callback); } /** * Registers a Remove Post Observable * * @param entityName The entity name * @param callback The callback to be executed * */ registerRemovePost(entityName, callback) { this.registerObservable(entityName, ObservableType.REMOVE, true, callback); } /** * Registers a Pre Save Observable * * @param entityName The entity name * @param callback The callback to be executed * */ registerSavePre(entityName, callback) { this.registerObservable(entityName, ObservableType.SAVE, false, callback); } /** * Registers a Pre Remove Observable * * @param entityName The entity name * @param callback The callback to be executed * */ registerRemovePre(entityName, callback) { this.registerObservable(entityName, ObservableType.REMOVE, false, callback); } }
JavaScript
class HTTPError extends Error { constructor(response) { super(); Error.captureStackTrace(this, HTTPError); this.name = this.constructor.name; this.message = JSON.stringify(response); Object.assign(this, response); } }
JavaScript
class Event { /** * * @param model {EventDTO} */ constructor (model) { TypeUtils.assert(model, "EventDTO"); TypeUtils.assert(model.name, "string"); /** * @member {EventDTO} */ this[PRIVATE.model] = model; } /** * * @returns {EventDTO} */ valueOf () { return this[PRIVATE.model]; } /** * Converts the internal value as a string presentation of EventDTO. * * @returns {string} */ toString () { return `Event:${TypeUtils.stringify(this[PRIVATE.model])}`; } /** * * @returns {EventDTO} */ toJSON () { return this[PRIVATE.model]; } /** * * @returns {string} */ get name () { return this[PRIVATE.model].name; } /** * * @returns {string} */ get time () { return this[PRIVATE.model].time; } /** * * @returns {string|undefined} */ get requestId () { return this[PRIVATE.model].requestId; } /** * * @returns {EventPayloadType} */ get payload () { return this[PRIVATE.model].payload; } /** * Freeze model from changes. * * @param model {Event} */ static freeze (model) { TypeUtils.assert(model, "Event"); Object.freeze(model[PRIVATE.model].payload); Object.freeze(model[PRIVATE.model]); Object.freeze(model); } /** * Converts a string presentation of EventDTO to Event object. * * @param model {string} * @return {Event} */ static fromString (model) { TypeUtils.assert(model, "string"); return new Event(JSON.parse(model)); } }
JavaScript
class FourfrontLogo extends React.PureComponent { static defaultProps = { 'id' : "fourfront_logo_svg", 'circlePathDefinitionOrig' : "m1,30c0,-16.0221 12.9779,-29 29,-29c16.0221,0 29,12.9779 29,29c0,16.0221 -12.9779,29 -29,29c-16.0221,0 -29,-12.9779 -29,-29z", 'circlePathDefinitionHover' : "m3.33331,34.33326c-2.66663,-17.02208 2.97807,-23.00009 29.99997,-31.33328c27.02188,-8.33321 29.66667,22.31102 16.6669,34.66654c-12.99978,12.35552 -15.64454,20.00017 -28.66669,19.00018c-13.02214,-0.99998 -15.33356,-5.31137 -18.00018,-22.33344z", 'textTransformOrig' : "translate(9, 37)", 'textTransformHover' : "translate(48, 24) scale(0.2, 0.6)", 'fgCircleTransformOrig' : "translate(50, 20) scale(0.35, 0.35) rotate(-135)", 'fgCircleTransformHover' : "translate(36, 28) scale(0.7, 0.65) rotate(-135)", 'hoverDelayUntilTransform' : 400, 'title' : "Data Portal" }; static svgElemStyle = { 'verticalAlign' : 'middle', 'display' : 'inline-block', 'height' : '100%', 'paddingBottom' : 10, 'paddingTop' : 10, 'transition' : "padding .3s, transform .3s", 'maxHeight' : 80 }; static svgBGCircleStyle = { 'fill' : "url(#fourfront_linear_gradient)", "stroke" : "transparent", "strokeWidth" : 1 }; static svgTextStyleOut = { 'transition' : "letter-spacing 1s, opacity .7s, stroke .7s, stroke-width .7s, fill .7s", 'fontSize' : 23, 'fill' : '#fff', 'fontFamily' : '"Mada","Work Sans",Helvetica,Arial,sans-serif', 'fontWeight' : '600', 'stroke' : 'transparent', 'strokeWidth' : 0, 'strokeLinejoin' : 'round', 'opacity' : 1, 'letterSpacing' : 0 }; static svgTextStyleIn = { 'transition' : "letter-spacing 1s .4s linear, opacity .7s .4s, stroke .7s 4s, stroke-width .7s 4s, fill .7s .4s", 'letterSpacing' : -14, 'stroke' : 'rgba(0,0,0,0.2)', 'opacity' : 0, 'fill' : 'transparent', 'strokeWidth' : 15 }; static svgInnerCircleStyleOut = { 'transition': "opacity 1.2s", 'opacity' : 0, 'fill' : 'transparent', 'strokeWidth' : 15, 'stroke' : 'rgba(0,0,0,0.2)', 'fontSize' : 23, 'fontFamily' : '"Mada","Work Sans",Helvetica,Arial,sans-serif', 'fontWeight' : '600', 'strokeLinejoin' : 'round' }; static svgInnerCircleStyleIn = { 'transition': "opacity 1.2s .6s", 'opacity' : 1 }; constructor(props){ super(props); this.setHoverStateOnDoTiming = _.throttle(this.setHoverStateOnDoTiming.bind(this), 1000); this.setHoverStateOn = this.setHoverStateOn.bind(this); this.setHoverStateOff = this.setHoverStateOff.bind(this); this.svgRef = React.createRef(); this.bgCircleRef = React.createRef(); this.fgTextRef = React.createRef(); this.fgCircleRef = React.createRef(); this.state = { hover : false }; } setHoverStateOn(e){ this.setState({ 'hover': true }, this.setHoverStateOnDoTiming); } setHoverStateOnDoTiming(e){ const { circlePathDefinitionHover, textTransformHover, fgCircleTransformHover, hoverDelayUntilTransform } = this.props; // CSS styles controlled via stylesheets setTimeout(()=>{ const { hover } = this.state; if (!hover) return; // No longer hovering. Cancel. d3.select(this.bgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('d', circlePathDefinitionHover); d3.select(this.fgTextRef.current) .interrupt() .transition() .duration(700) .attr('transform', textTransformHover); d3.select(this.fgCircleRef.current) .interrupt() .transition() .duration(1200) .attr('transform', fgCircleTransformHover); }, hoverDelayUntilTransform); } setHoverStateOff(e){ const { circlePathDefinitionOrig, textTransformOrig, fgCircleTransformOrig } = this.props; this.setState({ 'hover' : false }, ()=>{ d3.select(this.bgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('d', circlePathDefinitionOrig); d3.select(this.fgTextRef.current) .interrupt() .transition() .duration(1200) .attr('transform', textTransformOrig); d3.select(this.fgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('transform', fgCircleTransformOrig); }); } renderDefs(){ return ( <defs> <linearGradient id="fourfront_linear_gradient" x1="1" y1="30" x2="59" y2="30" gradientUnits="userSpaceOnUse"> <stop offset="0" stopColor="#238bae"/> <stop offset="1" stopColor="#8ac640"/> </linearGradient> <linearGradient id="fourfront_linear_gradient_darker" x1="1" y1="30" x2="59" y2="30" gradientUnits="userSpaceOnUse"> <stop offset="0" stopColor="#238b8e"/> <stop offset="1" stopColor="#8aa640"/> </linearGradient> </defs> ); } render(){ const { id, circlePathDefinitionOrig, textTransformOrig, fgCircleTransformOrig, onClick, title } = this.props; const { hover } = this.state; return ( <div className={"img-container" + (hover ? " is-hovering" : "")} onClick={onClick} onMouseEnter={this.setHoverStateOn} onMouseLeave={this.setHoverStateOff}> <svg id={id} ref={this.svgRef} viewBox="0 0 60 60" style={FourfrontLogo.svgElemStyle}> { this.renderDefs() } <path d={circlePathDefinitionOrig} style={FourfrontLogo.svgBGCircleStyle} ref={this.bgCircleRef} /> <text transform={textTransformOrig} style={hover ? { ...FourfrontLogo.svgTextStyleOut, ...FourfrontLogo.svgTextStyleIn } : FourfrontLogo.svgTextStyleOut} ref={this.fgTextRef}> 4DN </text> <text transform={fgCircleTransformOrig} style={hover ? { ...FourfrontLogo.svgInnerCircleStyleOut, ...FourfrontLogo.svgInnerCircleStyleIn } : FourfrontLogo.svgInnerCircleStyleOut} ref={this.fgCircleRef}> O </text> </svg> <span className="navbar-title">Data Portal</span> </div> ); } }
JavaScript
class Cache { /** * Tests if local storage is available * * https://stackoverflow.com/q/16427636 * * @returns {boolean} */ static canUseLocalStorage() { if (typeof window.localStorage === 'undefined' || !window.localStorage) { return false; // well, no, guess not } const testKey = 'piccest-test-key'; try { window.localStorage.setItem(testKey, testKey); window.localStorage.removeItem(testKey); } catch (e) { return false; } return true; } /** * Sets a JSON value into storage via key * Handles JSON-encoding * * @param {string} key - The key to store & retrieve the cached value * @param {*} value - Any valid JSON */ static setItem(key, value) { if (Cache.canUseLocalStorage()) { let json = JSON.stringify(value); if (typeof json !== 'string') { throw new Error('Invalid JSON'); } localStorage.setItem(key, json); } else { // json encoding & decoding is expensive Cache.sessionData[key] = value; } } /** * Retrieves a JSON value from storage via key * Will return null if the key was not previously set, * or is invalid JSON in localStorage * Handles JSON-decoding * * @param {string} key - The key to store & retrieve the cached value * @returns {*} */ static getItem(key) { if (Cache.canUseLocalStorage()) { let json = localStorage.getItem(key); try { return JSON.parse(json); } catch (e) { return null; } } return ( key in Cache.sessionData ? Cache.sessionData[key] : null ); } }
JavaScript
class TralisLayer extends mixin(TrackerLayer) { constructor(options = {}) { super({ ...options }); /** @ignore */ this.onMove = this.onMove.bind(this); /** @ignore */ this.onMoveEnd = this.onMoveEnd.bind(this); } /** * Add listeners from the Mapbox Map. * * @param {mapboxgl.Map} map * @param {string} beforeId See [mapboxgl.Map#addLayer](https://docs.mapbox.com/mapbox-gl-js/api/map/#map#addlayer) beforeId documentation. */ init(map, beforeId) { super.init(map); if (!this.map) { return; } this.map.on('zoomend', this.onZoomEnd); this.map.on('move', this.onMove); this.map.on('moveend', this.onMoveEnd); this.map.addSource('canvas-source', { type: 'canvas', canvas: this.tracker.canvas, coordinates: getSourceCoordinates(this.map, this.pixelRatio), // Set to true if the canvas source is animated. If the canvas is static, animate should be set to false to improve performance. animate: true, }); this.map.addLayer( { id: 'canvas-layer', type: 'raster', source: 'canvas-source', paint: { 'raster-opacity': 1, 'raster-fade-duration': 0, }, }, beforeId, ); } /** * Remove listeners from the Mapbox Map. */ terminate() { if (this.map) { this.map.off('zoomend', this.onZoomEnd); this.map.off('move', this.onMove); this.map.off('moveend', this.onMoveEnd); } super.terminate(); } /** * Callback on 'move' event. * * @private */ onMove() { this.map .getSource('canvas-source') .setCoordinates(getSourceCoordinates(this.map, this.pixelRatio)); const { width, height } = this.map.getCanvas(); this.renderTrajectories( [width / this.pixelRatio, height / this.pixelRatio], getResolution(this.map), this.map.getBearing(), ); } /** * Callback on 'moveend' event. * * @private */ onMoveEnd() { this.updateTrajectories(); } }
JavaScript
class EyesJsExecutor { /** * Schedules a command to execute JavaScript in the context of the currently selected frame or window. The script * fragment will be executed as the body of an anonymous function. If the script is provided as a function object, * that function will be converted to a string for injection into the target window. * * @param {!(string|Function)} script The script to execute. * @param {...*} varArgs The arguments to pass to the script. * @return {Promise<T>} A promise that will resolve to the scripts return value. * @template T */ executeScript(script, ...varArgs) { throw new TypeError('The method is not implemented!') } /** * Schedules a command to make the driver sleep for the given amount of time. * * @param {number} ms The amount of time, in milliseconds, to sleep. * @return {Promise<void>} A promise that will be resolved when the sleep has finished. */ sleep(ms) { throw new TypeError('The method is not implemented!') } }
JavaScript
class Collector { constructor () { this.ignore = [ '#', 'about:', 'data:', 'mailto:', 'javascript:', 'js:', '{', '*', 'ftp:', 'tel:' ] this.good = { 'http:': true, 'https:': true } this.ilen = this.ignore.length this.outlinks = [] this.links = [] this.linksSeen = new Set() this.urlParer = new window.URL('about:blank') this.urlParts = /^(https?:\/\/)?([^/]*@)?(.+?)(:\d{2,5})?([/?].*)?$/ this.dot = /\./g } static extractLinks () { const collector = new Collector() return collector.getOutlinks() } /** * @desc Determines if the supplied URL is to be ignored or not * @param {string} test - A URL * @return {boolean} */ shouldIgnore (test) { let ignored = false for (let i = 0; i < this.ilen; ++i) { if (test.startsWith(this.ignore[i])) { ignored = true break } } if (!ignored) { let parsed = true try { this.urlParer.href = test } catch (error) { parsed = false } return !(parsed && this.good[this.urlParer.protocol]) } return ignored } /** * @desc Collects the outlink information for a frame * @return {{outlinks: string, links: Array<string>, location: string}} */ getOutlinks () { const found = document.querySelectorAll( 'a[href],link[href],img[src],script[src],area[href]' ) let flen = found.length let elem for (let i = 0; i < flen; ++i) { elem = found[i] switch (elem.nodeName) { case 'LINK': if (elem.href !== '') { this.outlinks.push(`${elem.href} E link/@href\r\n`) } break case 'IMG': if (elem.src !== '') { this.outlinks.push(`${elem.src} E =EMBED_MISC\r\n`) } break case 'SCRIPT': if (elem.src !== '') { this.outlinks.push(`${elem.src} E script/@src\r\n`) } break default: let href = elem.href.trim() if (href !== '' && href !== ' ') { if (!this.shouldIgnore(href) && !this.linksSeen.has(href)) { this.linksSeen.add(href) this.links.push({ href, pathname: this.urlParer.pathname, host: this.urlParer.host }) } this.outlinks.push(`outlink: ${href} L a/@href\r\n`) } break } } let location try { location = window.location.href } catch (error) {} return { outlinks: this.outlinks.join(''), links: this.links, location } } }
JavaScript
class CustomTemplateModel { static getAttributeTypeMap() { return CustomTemplateModel.attributeTypeMap; } }
JavaScript
class ReedSolomonEncoder { encode(array) { const output = new Array(array.length + this.coefficients.length); for (let l = array.length; l--;) { output[l] = array[l]; } const ecc = new Array(this.coefficients.length).fill(0); for (let i = 0; i < array.length; i++) { ecc.push(0); const factor = this.field.Add(array[i], ecc.shift()); for (var j = 0; j < this.coefficients.length; j++) ecc[j] = this.field.Add(ecc[j], this.field.Multiply(this.coefficients[j], factor)); } ecc.forEach((that, i) => { output[array.length + i] = that; }); return output; } }
JavaScript
class FetchError extends Error { /** * Creat a fetch error. * @param {Response} response - The fetch response. * @param {...any} params - Any other Error params. */ constructor(response, ...params) { super(...params) if (Error.captureStackTrace) { Error.captureStackTrace(this, FetchError) } this.name = 'FetchError' this.response = response } }
JavaScript
class morris { /** * Check if Library is Loaded */ isReady() { if (typeof Raphael === "undefined") { console.warn("Splash Widgets : Raphael not Found"); return false; } if (typeof Morris === "undefined") { console.warn("Splash Widgets : Morris.js not Found"); return false; } return true; } /** * Iinit All Sparkline Charts */ buildAll() { //------------------------------------------------------------------------------ // Safety Check if (!this.isReady()) { return false; } this.buildDonutCharts(); this.buildOthersCharts(); console.log("Splash Widgets : Created Morris Charts"); } /* * INITIALIZE MORRIS DONUT CHARTS */ buildDonutCharts() { //------------------------------------------------------------------------------ // Safety Check if (!this.isReady()) { return false; } //------------------------------------------------------------------------------ // Walk on Morris Donuts Charts $('.morris-donut:not(:has(>svg))').each(function () { var $this = $(this); //------------------------------------------------------------------------------ // Prepare Main Option Object var splashMorrisDonut = { //------------------------------------------------------------------------------ // ID of the element in which to draw the chart. element: $this[0].id, //------------------------------------------------------------------------------ // Chart data records data: $this.data('morris-dataset'), }; //------------------------------------------------------------------------------ // Merge with Chart Options jQuery.extend(splashMorrisDonut, $this.data('morris-options') || []); //------------------------------------------------------------------------------ // Render Morris Donut Chart new Morris.Donut(splashMorrisDonut); return true; }); } /* * INITIALIZE MORRIS COMMONS CHARTS */ buildOthersCharts() { //------------------------------------------------------------------------------ // Safety Check if (!this.isReady()) { return false; } //------------------------------------------------------------------------------ // Walk on Morris Charts $('.morris-chart:not(:has(>svg))').each(function () { //------------------------------------------------------------------------------ var $this = $(this); //------------------------------------------------------------------------------ // Prepare Chart Type var splashMorrisType = $this.data('morris-type') || "Line"; //------------------------------------------------------------------------------ // Prepare Main Option Object var splashMorrisChart = { // ID of the element in which to draw the chart. element: $this[0].id, // Chart data records data: $this.data('morris-dataset'), // The name of the data record attribute that contains x-values. xkey: $this.data('morris-xkey'), // A list of names of data record attributes that contain y-values. ykeys: $this.data('morris-ykeys'), // Labels for the ykeys labels: $this.data('morris-labels') }; //------------------------------------------------------------------------------ // Merge with Chart Options jQuery.extend(splashMorrisChart, $this.data('morris-options') || []); switch (splashMorrisType) { case "Line": // Render Morris Line Chart new Morris.Line(splashMorrisChart); break; case "Area": // Render Morris Area Chart new Morris.Area(splashMorrisChart); break; case "Bar": // Render Morris Bar Chart new Morris.Bar(splashMorrisChart); break; } return true; }); } }
JavaScript
class App extends React.Component { render() { return ( // Routing Component <NativeRouter> {/* Provider for the redux store */} <Provider store={store}> {/* Setting up routes here, will add more edge cases and routes later */} <Route path={'/'} render={(props) => <NavBar {...props}/>} /> <Route exact path="/" render={(props) => <HomePage {...props}/>} /> <Route path="/chat-list" render={(props) => <ChatList {...props}/>} /> <Route path="/create_chat_room" render={(props) => <CreateChatRoom {...props}/>} /> <Route path="/chatroom/:id" render={(props) => <Chatroom {...props}/>} /> {/* <Route render={()=> <ErrorPage />} /> This will be for the error page that we will hopefully not need */} </Provider> </NativeRouter> ); } }
JavaScript
class KeyStoreGenerateCommandBuilder { static build() { const keyStoreGenerateCommandValidator = new KeyStoreGenerateCommandValidator(logger) const keyStoreGenerateCommand = new KeyStoreGenerateCommand( logger, keyStoreGenerateCommandValidator, privateKeyService, privateKeyValidator, ) return keyStoreGenerateCommand } }
JavaScript
class Mask extends Renderable { //region Config static get $name() { return 'Mask'; } // Factoryable type name static get type() { return 'mask'; } static get configurable() { return { /** * Set this config to trigger an automatic close after the desired delay: * ``` * mask.autoClose = 2000; * ``` * If the mask has an `owner`, its `onMaskAutoClosing` method is called when the close starts and its * `onMaskAutoClose` method is called when the close finishes. * @config {Number} * @private */ autoClose : null, /** * The portion of the {@link #config-target} element to be covered by this mask. By default, the mask fully * covers the `target`. In some cases, however, it may be desired to only cover the `'body'` (for example, * in a grid). * * This config is set in conjunction with `owner` which implements the method `syncMaskCover`. * * @config {String} * @private */ cover : null, /** * The icon to show next to the text. Defaults to showing a spinner * @config {String} * @default */ icon : 'b-icon b-icon-spinner', /** * The maximum value of the progress indicator * @property {Number} */ maxProgress : null, /** * Mode: bright, bright-blur, dark or dark-blur * @config {String} * @default */ mode : 'dark', /** * Number expressing the progress * @property {Number} */ progress : null, // The owner is involved in the following features: // // - The `autoClose` timer calls `onMaskAutoClose`. // - The `cover` config calls `syncMaskCover`. // - If the `target` is a string, that string names the property of the `owner` that holds the // `HTMLElement` reference. /** * The owning widget of this mask. This is required if `target` is a string. * * @config {Object|Core.widget.Widget} */ owner : null, /** * The element to be masked. If this config is a string, that string is the name of the property of the * `owner` that holds the `HTMLElement` that is the actual target of the mask. * * NOTE: In prior releases, this used to be specified as the `element` config, but that is now, as with * `Widget`, the primary element of the mask. * * @config {String|HTMLElement} */ target : null, /** * The text (or HTML) to show in mask * @config {String} */ text : null, // TODO - perhaps a better way to deal w/multiple reasons to mask something would be a mask FIFO behind // the scenes so that only one mask is visible at a time. That would take a bit of tinkering in the // hide/show mechanism but feels like a more natural way to go. In which case, this config would go away // and multiple masks would simply cooperate. https://github.com/bryntum/support/issues/190 type : null, /** * The number of milliseconds to delay before making the mask visible. If set, the mask will have an * initial `opacity` of 0 but will function in all other ways as a normal mask. Setting this delay can * reduce flicker in cases where load operations are typically short (for example, a second or less). * * @config {Number} */ showDelay : null, useTransition : false }; } static get delayable() { return { deferredClose : 0, delayedShow : 0 }; } //endregion //region Init construct(config) { if (config) { let el = config.element, cfg; // Upgrade config -> cfg // Treat config as readonly, cfg is lazily copied and writable if (el) { VersionHelper.deprecate('Core', '4.0.0', 'Mask "element" config has been renamed to "target"'); config = cfg = Object.assign({}, config); delete cfg.element; cfg.target = el; } el = config.target; if (typeof el === 'string') { config = cfg = cfg || Object.assign({}, config); cfg.target = config.owner[el]; // must supply "owner" in this case } } super.construct(config); if (!this.target) { this.target = document.body; } this.show(); } doDestroy() { const me = this, { element } = me; if (element) { me.element = null; if (me.mode.endsWith('blur')) { DomHelper.forEachChild(element, child => { child.classList.remove(`b-masked-${me.mode}`); }); } me.target[me.maskName] = null; } super.doDestroy(); } get maskElement() { // TODO log on use of deprecated property? return this.element; } get maskName() { const type = this.type; return `mask${typeof type === 'string' ? type.trim() : ''}`; } renderDom() { const me = this, { maxProgress } = me; return { class : { 'b-mask' : 1, 'b-delayed-show' : me.showDelay, 'b-widget' : 1, [`b-mask-${me.mode}`] : 1, 'b-progress' : maxProgress, 'b-prevent-transitions' : !me.useTransition }, children : [{ reference : 'maskContent', class : 'b-mask-content', children : [ maxProgress ? { reference : 'progressElement', class : 'b-mask-progress-bar', style : { width : `${Math.max(0, Math.min(100, Math.round(me.progress / maxProgress * 100)))}%` } } : null, { reference : 'maskText', class : 'b-mask-text', html : (me.icon ? `<i class="b-mask-icon ${me.icon}"></i>` : '') + me.text } ] }] }; } //endregion //region Static static mergeConfigs(...sources) { const ret = {}; for (const src of sources) { if (typeof src === 'string') { ret.text = src; } else { ObjectHelper.assign(ret, src); // not Object.assign! } } return ret; } /** * Shows a mask with the specified message * @param {String|Object} text Message * @param {HTMLElement} target The element to mask * @returns {Core.widget.Mask} */ static mask(text, target = document.body) { return new Mask(typeof text !== 'string' ? Object.assign({ target }, text) : { target, text }); } /** * Unmask * @param {HTMLElement} element Element to unmask * @returns {Promise} A promise which is resolved when the mask is gone */ static unmask(element = document.body) { return element.mask && element.mask.close(); } //endregion //region Config updateAutoClose(delay) { const me = this; me.deferredClose.cancel(); if (delay) { me.deferredClose.delay = delay; me.deferredClose(); } } updateCover() { const owner = this.owner; if (owner && owner.syncMaskCover) { owner.syncMaskCover(this); } } updateShowDelay(delay) { const delayedShow = this.delayedShow; delayedShow.delay = delay; if (!delay) { delayedShow.flush(); } } //endregion //region Show & hide deferredClose() { const owner = this.owner; this.close().then(() => { if (owner && owner.onMaskAutoClose) { owner.onMaskAutoClose(this); } }); if (owner && owner.onMaskAutoClosing) { owner.onMaskAutoClosing(this); } } delayedShow() { this.classes.remove('b-delayed-show'); } /** * Show mask */ show() { const me = this, { element, target, hiding, maskName } = me; // We don't do this because we may want to show but automatically close after a // brief delay. The order of applying those configs should not be an issue. In // other words, to stop the deferredClose, you must set autoClose to falsy. // me.deferredClose.cancel(); if (hiding) { // Resolving seems much better than the only other options: // 1. Never settling // 2. Rejecting hiding.resolve(); // This will be nulled out as the promise resolves but that is a race condition // compared to the next hide() call. me.hiding = null; me.clearTimeout('hide'); } if (me.showDelay) { element.classList.add('b-delayed-show'); me.delayedShow(); } element.classList.add('b-visible'); element.classList.remove('b-hidden'); target.classList.add('b-masked'); if (!target[maskName]) { target[maskName] = me; target.appendChild(element); } me.shown = true; // blur has to blur child elements if (me.mode.endsWith('blur')) { DomHelper.forEachChild(target, child => { if (child !== element) { child.classList.add(`b-masked-${me.mode}`); } }); } } /** * Hide mask * @returns {Promise} A promise which is resolved when the mask is hidden, or immediately if already hidden */ hide() { const me = this, { target, element } = me; let hiding = me.hiding; if (!hiding) { if (!me.shown) { return Promise.resolve(); } me.hiding = hiding = new Promissory(); me.shown = false; element.classList.remove('b-visible'); element.classList.add('b-hidden'); target.classList.remove('b-masked'); if (me.mode.endsWith('blur')) { DomHelper.forEachChild(target, child => { if (child !== element) { child.classList.remove(`b-masked-${me.mode}`); } }); } hiding.promise = hiding.promise.then(() => { if (me.hiding === hiding) { me.hiding = null; } }); // TODO: use AnimationHelper when available me.setTimeout(() => hiding.resolve(), 500, 'hide'); } return hiding.promise; } /** * Close mask (removes it) * @returns {Promise} A promise which is resolved when the mask is closed */ close() { return this.hide().then(() => { this.destroy(); }); } //endregion }
JavaScript
class DemoToolbarComponent { constructor(hostRef) { registerInstance(this, hostRef); } componentDidLoad() { this.rootEl = this.el.shadowRoot.querySelector('.mdc-toolbar'); this.toolbar = new MDCToolbar(this.rootEl); const elResizer = this.el.parentElement; this.toolbar.fixedAdjustElement = elResizer; } componentDidUnload() { this.toolbar.destroy(); } render() { return (h("div", { class: "mdc-typography" }, h("header", { class: "mdc-toolbar mdc-toolbar--fixed" }, h("div", { class: "mdc-toolbar__row" }, h("section", { id: "left-panel", class: "mdc-toolbar__section mdc-toolbar__section--align-start" }, h("h3", { class: "mdc-typography--subheading2" }, this.name), h("slot", { name: "left" })), h("section", { id: "center-panel", class: "mdc-toolbar__section" }, h("slot", { name: "center" })), h("section", { id: "right-panel", class: "mdc-toolbar__section mdc-toolbar__section--align-end", role: "toolbar" }, h("slot", { name: "right" }))), h("slot", { name: "base" })))); } get el() { return getElement(this); } static get style() { return ".mdc-toolbar{background-color:#6200ee;background-color:var(--mdc-theme-primary,#6200ee);color:#fff;display:-ms-flexbox;display:flex;position:relative;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-sizing:border-box;box-sizing:border-box;width:100%}.mdc-toolbar .mdc-toolbar__icon{color:#fff}.mdc-toolbar .mdc-toolbar__icon:after,.mdc-toolbar .mdc-toolbar__icon:before{background-color:#fff}.mdc-toolbar .mdc-toolbar__icon:hover:before{opacity:.08}.mdc-toolbar .mdc-toolbar__icon.mdc-ripple-upgraded--background-focused:before,.mdc-toolbar .mdc-toolbar__icon:not(.mdc-ripple-upgraded):focus:before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.24}.mdc-toolbar .mdc-toolbar__icon:not(.mdc-ripple-upgraded):after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.mdc-toolbar .mdc-toolbar__icon:not(.mdc-ripple-upgraded):active:after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.24}.mdc-toolbar .mdc-toolbar__icon.mdc-ripple-upgraded{--mdc-ripple-fg-opacity:0.24}.mdc-toolbar__row{display:-ms-flexbox;display:flex;position:relative;-ms-flex-align:center;align-items:center;-webkit-box-sizing:border-box;box-sizing:border-box;width:100%;height:auto;min-height:64px}\@media (max-width:959px) and (orientation:landscape){.mdc-toolbar__row{min-height:48px}}\@media (max-width:599px){.mdc-toolbar__row{min-height:56px}}.mdc-toolbar__section{display:-ms-inline-flexbox;display:inline-flex;-ms-flex:1;flex:1;-ms-flex-align:start;align-items:start;-ms-flex-pack:center;justify-content:center;-webkit-box-sizing:border-box;box-sizing:border-box;min-width:0;height:100%;padding:8px;z-index:1}\@media (max-width:959px) and (orientation:landscape){.mdc-toolbar__section{padding:0}}\@media (max-width:599px){.mdc-toolbar__section{padding:4px 0}}.mdc-toolbar__section--align-start{padding-left:12px;padding-right:0;-ms-flex-pack:start;justify-content:flex-start;-ms-flex-order:-1;order:-1}.mdc-toolbar__section--align-start[dir=rtl],[dir=rtl] .mdc-toolbar__section--align-start{padding-left:0;padding-right:12px}\@media (max-width:959px) and (orientation:landscape){.mdc-toolbar__section--align-start{padding-left:4px;padding-right:0}.mdc-toolbar__section--align-start[dir=rtl],[dir=rtl] .mdc-toolbar__section--align-start{padding-left:0;padding-right:4px}}\@media (max-width:599px){.mdc-toolbar__section--align-start{padding-left:4px;padding-right:0}.mdc-toolbar__section--align-start[dir=rtl],[dir=rtl] .mdc-toolbar__section--align-start{padding-left:0;padding-right:4px}}.mdc-toolbar__section--align-end{padding-left:0;padding-right:12px;-ms-flex-pack:end;justify-content:flex-end;-ms-flex-order:1;order:1}.mdc-toolbar__section--align-end[dir=rtl],[dir=rtl] .mdc-toolbar__section--align-end{padding-left:12px;padding-right:0}\@media (max-width:959px) and (orientation:landscape){.mdc-toolbar__section--align-end{padding-left:0;padding-right:4px}.mdc-toolbar__section--align-end[dir=rtl],[dir=rtl] .mdc-toolbar__section--align-end{padding-left:4px;padding-right:0}}\@media (max-width:599px){.mdc-toolbar__section--align-end{padding-left:0;padding-right:4px}.mdc-toolbar__section--align-end[dir=rtl],[dir=rtl] .mdc-toolbar__section--align-end{padding-left:4px;padding-right:0}}.mdc-toolbar__title{font-family:Roboto,sans-serif;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;font-size:1.25rem;line-height:2rem;font-weight:500;letter-spacing:.0125em;text-decoration:inherit;text-transform:inherit;text-overflow:ellipsis;white-space:nowrap;overflow:hidden;margin-left:24px;margin-right:0;-ms-flex-item-align:center;align-self:center;padding:12px 0;line-height:1.5rem;z-index:1}.mdc-toolbar__title[dir=rtl],[dir=rtl] .mdc-toolbar__title{margin-left:0;margin-right:24px}.mdc-toolbar__icon,.mdc-toolbar__menu-icon{--mdc-ripple-fg-size:0;--mdc-ripple-left:0;--mdc-ripple-top:0;--mdc-ripple-fg-scale:1;--mdc-ripple-fg-translate-end:0;--mdc-ripple-fg-translate-start:0;-webkit-tap-highlight-color:rgba(0,0,0,0);will-change:transform,opacity;display:-ms-flexbox;display:flex;position:relative;-ms-flex-align:start;align-items:start;-ms-flex-pack:center;justify-content:center;-webkit-box-sizing:border-box;box-sizing:border-box;width:48px;height:48px;padding:12px;border:none;outline:none;background-color:transparent;fill:currentColor;color:inherit;text-decoration:none;cursor:pointer}.mdc-toolbar__icon:after,.mdc-toolbar__icon:before,.mdc-toolbar__menu-icon:after,.mdc-toolbar__menu-icon:before{position:absolute;border-radius:50%;opacity:0;pointer-events:none;content:\"\"}.mdc-toolbar__icon:before,.mdc-toolbar__menu-icon:before{-webkit-transition:opacity 15ms linear,background-color 15ms linear;transition:opacity 15ms linear,background-color 15ms linear;z-index:1}.mdc-toolbar__icon.mdc-ripple-upgraded:before,.mdc-toolbar__menu-icon.mdc-ripple-upgraded:before{-webkit-transform:scale(var(--mdc-ripple-fg-scale,1));transform:scale(var(--mdc-ripple-fg-scale,1))}.mdc-toolbar__icon.mdc-ripple-upgraded:after,.mdc-toolbar__menu-icon.mdc-ripple-upgraded:after{top:0;left:0;-webkit-transform:scale(0);transform:scale(0);-webkit-transform-origin:center center;transform-origin:center center}.mdc-toolbar__icon.mdc-ripple-upgraded--unbounded:after,.mdc-toolbar__menu-icon.mdc-ripple-upgraded--unbounded:after{top:var(--mdc-ripple-top,0);left:var(--mdc-ripple-left,0)}.mdc-toolbar__icon.mdc-ripple-upgraded--foreground-activation:after,.mdc-toolbar__menu-icon.mdc-ripple-upgraded--foreground-activation:after{-webkit-animation:mdc-ripple-fg-radius-in 225ms forwards,mdc-ripple-fg-opacity-in 75ms forwards;animation:mdc-ripple-fg-radius-in 225ms forwards,mdc-ripple-fg-opacity-in 75ms forwards}.mdc-toolbar__icon.mdc-ripple-upgraded--foreground-deactivation:after,.mdc-toolbar__menu-icon.mdc-ripple-upgraded--foreground-deactivation:after{-webkit-animation:mdc-ripple-fg-opacity-out .15s;animation:mdc-ripple-fg-opacity-out .15s;-webkit-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1))}.mdc-toolbar__icon:after,.mdc-toolbar__icon:before,.mdc-toolbar__menu-icon:after,.mdc-toolbar__menu-icon:before{top:0;left:0;width:100%;height:100%}.mdc-toolbar__icon.mdc-ripple-upgraded:after,.mdc-toolbar__icon.mdc-ripple-upgraded:before,.mdc-toolbar__menu-icon.mdc-ripple-upgraded:after,.mdc-toolbar__menu-icon.mdc-ripple-upgraded:before{top:var(--mdc-ripple-top,0);left:var(--mdc-ripple-left,0);width:var(--mdc-ripple-fg-size,100%);height:var(--mdc-ripple-fg-size,100%)}.mdc-toolbar__icon.mdc-ripple-upgraded:after,.mdc-toolbar__menu-icon.mdc-ripple-upgraded:after{width:var(--mdc-ripple-fg-size,100%);height:var(--mdc-ripple-fg-size,100%)}.mdc-toolbar__menu-icon+.mdc-toolbar__title{margin-left:8px;margin-right:0}.mdc-toolbar__menu-icon+.mdc-toolbar__title[dir=rtl],[dir=rtl] .mdc-toolbar__menu-icon+.mdc-toolbar__title{margin-left:0;margin-right:8px}\@media (max-width:599px){.mdc-toolbar__title{margin-left:16px;margin-right:0}.mdc-toolbar__title[dir=rtl],[dir=rtl] .mdc-toolbar__title{margin-left:0;margin-right:16px}}.mdc-toolbar--fixed{-webkit-box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);position:fixed;top:0;left:0;z-index:4}.mdc-toolbar--flexible{--mdc-toolbar-ratio-to-extend-flexible:4}.mdc-toolbar--flexible .mdc-toolbar__row:first-child{height:256px;height:calc(64px*var(--mdc-toolbar-ratio-to-extend-flexible, 4))}\@media (max-width:599px){.mdc-toolbar--flexible .mdc-toolbar__row:first-child{height:224px;height:calc(56px*var(--mdc-toolbar-ratio-to-extend-flexible, 4))}}.mdc-toolbar--flexible .mdc-toolbar__row:first-child:after{position:absolute;content:\"\"}.mdc-toolbar--flexible-default-behavior .mdc-toolbar__title{font-family:Roboto,sans-serif;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;font-size:1.25rem;line-height:2rem;font-weight:500;letter-spacing:.0125em;text-decoration:inherit;text-transform:inherit;-ms-flex-item-align:end;align-self:flex-end;line-height:1.5rem}.mdc-toolbar--flexible-default-behavior .mdc-toolbar__row:first-child:after{top:0;left:0;width:100%;height:100%;-webkit-transition:opacity .2s ease;transition:opacity .2s ease;opacity:1}.mdc-toolbar--flexible-default-behavior.mdc-toolbar--flexible-space-minimized .mdc-toolbar__row:first-child:after{opacity:0}.mdc-toolbar--flexible-default-behavior.mdc-toolbar--flexible-space-minimized .mdc-toolbar__title{font-weight:500}.mdc-toolbar--waterfall.mdc-toolbar--fixed{-webkit-box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12);box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12);-webkit-transition:-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:box-shadow .28s cubic-bezier(.4,0,.2,1);transition:box-shadow .28s cubic-bezier(.4,0,.2,1), -webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);will-change:box-shadow}.mdc-toolbar--waterfall.mdc-toolbar--fixed.mdc-toolbar--flexible-space-minimized{-webkit-box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.mdc-toolbar--waterfall.mdc-toolbar--fixed.mdc-toolbar--fixed-lastrow-only.mdc-toolbar--flexible-space-minimized{-webkit-box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12);box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mdc-toolbar--waterfall.mdc-toolbar--fixed.mdc-toolbar--fixed-lastrow-only.mdc-toolbar--fixed-at-last-row{-webkit-box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.mdc-toolbar-fixed-adjust{padding-top:64px}\@media (max-width:959px) and (max-height:599px){.mdc-toolbar-fixed-adjust{padding-top:48px}}\@media (max-width:599px){.mdc-toolbar-fixed-adjust{padding-top:56px}}.mdc-toolbar__section--shrink-to-fit{-ms-flex:none;flex:none}:host{--mdc-theme-primary:#fff;--mdc-theme-text-primary-on-primary:#494949;--mdc-theme-background:#c3c3c3;--vh:1vh;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif}:host .mdc-toolbar--fixed{z-index:5}:host section{margin:0 1.5em 0 1.2em;transition:opacity .25s ease-in-out;-moz-transition:opacity .25s ease-in-out;-webkit-transition:opacity .25s ease-in-out}:host section .mdc-typography--subheading2{color:var(--mdc-theme-text-primary-on-primary,#000);font-size:1.1rem;text-overflow:ellipsis}\@media only screen and (max-width:900px){:host #left-panel{max-width:30%}:host #center-panel{min-width:40%}:host #right-panel{max-width:30%}}\@media only screen and (max-width:700px){:host #right-panel{display:none}:host #center-panel{min-width:100%;padding:0}:host #left-panel{display:none}}"; } }
JavaScript
class TodoList extends React.Component{ render() { return ( <TodoItem/> ); } }
JavaScript
class MongoLib { constructor() { console.log(`MONGO_URI -> ${MONGO_URI}`); this.client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }); this.dbName = DB_NAME; } connect() { if (!MongoLib.connection) { MongoLib.connection = new Promise((resolve, reject) => { this.client.connect((err) => { if (err) { reject(err); } console.log("Connected succesfully to mongo 🚀"); resolve(this.client.db(this.dbName)); }); }); } return MongoLib.connection; } // LISTAR TODOS LOS PRODUCTOS getAll(collection) { return this.connect().then((db) => { return db .collection(collection) .find() // REGRESA EL RESULTADO .toArray(); // SE CONVIERTE A ARRELGO PARA QUE SE PUEDA MANIPULAR }); } // CREAR NUEVO PRODUCTO create(collection, data) { return this.connect() .then((db) => { // REGRESA EL RESULTADO DEL insertOne return db.collection(collection).insertOne(data); }) .then((result) => result.insertedId); } }
JavaScript
class ProductService { /** * @param {object} Product information * @returns {object} function to create a Product */ static createProduct(product) { return Product.create(product); } /** * @param {object} attribute * @returns {object} function to display a product */ static findProduct(attribute) { return Product.findOne({ where: attribute }); } /** * @param {integer} data * @param {string} property * @returns {object} function to display a product */ static updateProduct(data, property) { return Product.update(property, { where: data, returning: true, }); } /** * delete product function * @param {object} attribute * @returns {object} function to display a product */ static DeleteProduct(attribute) { return Product.destroy({ where: attribute }); } /** * function to get all product * @param {object} attribute * @returns {object} function to display a all product */ static findAllProducts(attribute) { return Product.findAll(); } }
JavaScript
class Accessibility { constructor(){ this.visual = new Visual(); this.physical = new Physical(); } }
JavaScript
class User { /** * @property {string} username - The username. */ get username() { return this._username; } /** * @property {Array} roles - The user roles. */ get roles() { return this._roles; } /** * @property {object} credentials - The credentials that were used to authenticate the user. */ get credentials() { return this._credentials; } /** * @property {object} proxyCredentials - User credentials to be used in requests to Elasticsearch performed by either the transport client * or the query engine. */ get proxyCredentials() { return this._proxyCredentials; } constructor(username, credentials, proxyCredentials, roles) { this._username = username; this._credentials = credentials; this._proxyCredentials = proxyCredentials; this._roles = roles; } }
JavaScript
class Texture { constructor(imagePath, scaleX = 1, scaleY = 1) { this.pixiTexture = PIXI.Texture.fromImage(imagePath); this.scaleX = scaleX; this.scaleY = -scaleY; /* Stage of pixi.js get flipped by Y that is why we need to flip each texture to display it correctly */ } getPixiTexture() { return this.pixiTexture; } getScaleX() { return this.scaleX; } getScaleY() { return this.scaleY; } }
JavaScript
class SymbolType { /** * Determine the name and whether it's a declared partial based on info * from the provided node. * @param {N2MatrixCell} cell The object to select the type from. * @param {ModelData} model Reference to the model to get some info from it. */ constructor(cell, model) { this.name = null; this.potentialDeclaredPartial = false; this.declaredPartial = false; // Update properties based on the the referenced node. this.getType(cell, model); } /** * Decide what object the cell will be drawn as, based on its position * in the matrix, type, source, target, and/or other conditions. */ getType(cell, model) { if (cell.onDiagonal()) { if (cell.srcObj.isSubsystem()) { this.name = 'group'; return; } if (cell.srcObj.isParamOrUnknown()) { if (cell.srcObj.dtype == "ndarray") { this.name = 'vector'; return; } this.name = 'scalar'; return; } throw ("Unknown symbol type for cell on diagonal."); } if (cell.srcObj.isSubsystem()) { if (cell.tgtObj.isSubsystem()) { this.name = 'groupGroup'; return; } if (cell.tgtObj.isParamOrUnknown()) { if (cell.tgtObj.dtype == "ndarray") { this.name = 'groupVector'; return; } this.name = 'groupScalar'; return; } throw ("Unknown group symbol type."); } if (cell.srcObj.isParamOrUnknown()) { if (cell.srcObj.dtype == "ndarray") { if (cell.tgtObj.isParamOrUnknown()) { if (cell.tgtObj.dtype == "ndarray" || cell.tgtObj.isParam()) { this.name = 'vectorVector'; this.potentialDeclaredPartial = true; this.declaredPartial = model.isDeclaredPartial(cell.srcObj, cell.tgtObj); return; } this.name = 'vectorScalar'; this.potentialDeclaredPartial = true; this.declaredPartial = model.isDeclaredPartial(cell.srcObj, cell.tgtObj); return; } if (cell.tgtObj.isSubsystem()) { this.name = 'vectorGroup'; return; } throw ("Unknown vector symbol type."); } if (cell.tgtObj.isParamOrUnknown()) { if (cell.tgtObj.dtype == "ndarray") { this.name = 'scalarVector'; this.potentialDeclaredPartial = true; this.declaredPartial = model.isDeclaredPartial(cell.srcObj, cell.tgtObj); return; } this.name = 'scalarScalar'; this.potentialDeclaredPartial = true; this.declaredPartial = model.isDeclaredPartial(cell.srcObj, cell.tgtObj); return; } if (cell.tgtObj.isSubsystem()) { this.name = 'scalarGroup'; return; } throw ("Unknown vector or scalar symbol type."); } throw ("Completely unrecognized symbol type.") } }
JavaScript
class WholesaleAccountPage extends React.Component { constructor(props) { super(props) this.state = { products: [ { model: "Kenn-U-Style", "price": 0.0 }, { model: "Kenn-U-Active", "price": 0.0 }, { model: "Kenn-U-Flex", "price": 0.0 } ], accountName: '', email: '', shippingState: '', shippingStreetAddress :'', shippingTown: '', shippingZip: '', created: false } this.handleFormChange = this.handleFormChange.bind(this) this.shouldDisableSubmit = this.shouldDisableSubmit.bind(this) this.handlePriceChange = this.handlePriceChange.bind(this) this.getImgFromModel = this.getImgFromModel.bind(this) this.getProductPrice = this.getProductPrice.bind(this) } getImgFromModel(model) { switch(model){ case "Kenn-U-Flex": return flexImg case "Kenn-U-Style": return styleImg case "Kenn-U-Active": return activeImg } } getProductPrice(modelName) { var productsArr = this.state.products.filter(e => e.model === modelName) if (productsArr.length > 0) { return productsArr[0].price } } shouldDisableSubmit() { return ( this.state.email.length <= 0 || this.state.shippingState.length <= 0 || this.state.shippingStreetAddress.length <= 0 || this.state.shippingTown.length <= 0 || this.state.accountName.length <= 0 || this.state.shippingZip.length <= 0 ) } handleFormChange = prop => event => { this.setState({ [prop]: event.target.value} ) } handlePriceChange = modelName => event => { var productsArr = this.state.products productsArr.forEach(function(product) { if(product.model === modelName){ product.price = event.target.value } }) this.setState({ products: productsArr }) } handleSubmit(){ // Create the post request body var request = { "configuredPrice": this.state.products, "email": this.state.email, "name": this.state.accountName, "shippingAddress": this.state.shippingStreetAddress, "shippingState": this.state.shippingState, "shippingTown": this.state.shippingTown, "shippingZip": this.state.shippingZip } //POST the request axios.post('/api/wholesale/account/new', request ).then(function(response) { this.setState({ created: true }) }.bind(this)).catch(function(error) { alert("error!" + error) }) } render() { const { classes } = this.props if (this.state.created) { return <WholesaleAccountCreated /> } const productList = this.state.products.map(function(product){ return( <span> <img className={ classes.productImg } src={this.getImgFromModel(product.model) } /> <TextField label={ product.model + " Price" } value={ this.getProductPrice(product.model) } type="number" onChange={ this.handlePriceChange(product.model) } className={ classes.productQuant } /> <br /> </span> ) }, this) return ( <div> <Typography type="subheading" variant="display1" align="center" className={ classes.title } > Create a Wholesale Account </Typography> <Card className={ classes.card }> <Link to="/employee/dashboard"> <IconButton> <ArrowBack /> </IconButton> </Link> <TextField required="true" placeholder="Account Name" className={ classes.textbox } onChange = { this.handleFormChange('accountName') } /> <div className= {classes.productWrapper }> {productList} </div> <TextField required="true" placeholder="Email" className={ classes.textbox } onChange = { this.handleFormChange('email') } /> <TextField required="true" placeholder="Street Address" className={ classes.textbox } onChange = { this.handleFormChange('shippingStreetAddress') } /> <TextField required="true" placeholder="Town/City" className={ classes.textbox } onChange = { this.handleFormChange('shippingTown') } /> <TextField required="true" placeholder="State" className={ classes.textbox } onChange = { this.handleFormChange('shippingState') } /> <TextField required="true" placeholder="Zip Code" className={ classes.finalTextBox } onChange = { this.handleFormChange('shippingZip') } /> <Button disabled={ this.shouldDisableSubmit() } className={ classes.submitButton } onClick={ this.handleSubmit.bind(this) } > Create Wholesale Account </Button> </Card> </div> ) } }
JavaScript
class Cache { static async getColumnGroups({db, logger}) { // get column groups from the database and apply transformation to the column on receipt of the data const results = await db.request( { sql: `SELECT ColumnGroupID, ColumnGroup FROM MI_ColumnGroup`, options: { transformers: [ { column: 'ColumnGroup', transform: (value, metadata) => value.trim().toLowerCase().replace(/\s-\s/g, ' ').replace(/\s/g, '_') } ] } }); return results[0]; // results is an array of result sets, we only want the first result set, i.e. results[0] } static async getContactTypes({db, logger}) { // get contact types from the database and apply transformation to the column on receipt of the data const results = await db.request( { sql: `SELECT ContactTypeID, ContactType FROM ContactType`, options: { transformers: [ { column: 'ContactType', transform: (value, metadata) => value.trim().toLowerCase().replace(/\s-\s/g, ' ').replace(/\s/g, '_') } ] } }); return results[0]; // results is an array of result sets, we only want the first result set, i.e. results[0] } static getEventTypes() { // example object for jstree - https://www.jstree.com/docs/json/ const eventTypes = { core: { data: [ { id: 1, text: 'Event 1' }, { id: 2, text: 'Event 2' }, { id: 3, text: 'Event 3' } ] } } return eventTypes; } static async refresh({db, logger}) // update the cache by calling the methods above to get the data { const cache = {}; cache.columnGroups = await this.getColumnGroups({db, logger}); cache.contactTypes = await this.getContactTypes({db, logger}); cache.eventTypes = this.getEventTypes(); return cache; } }
JavaScript
class StateMachine { constructor(game) { /** @private {!SpellcastGame} */ this.game_ = game; /** * @private {!Object.<GameStateId, * !State>} */ this.states_ = Object.create(null); /** @private {GameStateId} */ this.currentStateId_ = GameStateId.UNKNOWN; /** @private {State} */ this.currentState_ = null; }; /** * Adds a state. * @param {GameStateId} id * @param {!State} state */ addState(id, state) { this.states_[id] = state; }; /** * Removes a state. * @param {GameStateId} id */ removeState(id) { delete this.states_[id]; }; /** * Go to state and broadcast current game status to all players. * @param {GameStateId} id */ goToState(id) { if (this.currentState_) { this.currentState_.onExit(id); } let previousStateId = this.currentStateId_; this.currentStateId_ = id; this.currentState_ = this.states_[id]; if (!this.currentState_) { throw Error('No state found for ' + id); } this.currentState_.onEnter(previousStateId); this.game_.broadcastGameStatus(this.currentStateId_); }; /** * Returns the state object with the provided id, if it exists. * @param {GameStateId} id * @return {State} The state associated with the * provided id, or null if not found. */ getState(id) { return this.states_[id]; }; /** @return {State} Returns the current state if any. */ getCurrentState() { return this.currentState_; }; /** Updates the current state. Should be called in game animation loop. */ update() { if (this.currentState_) { this.currentState_.onUpdate(); } }; }
JavaScript
class AppConfig { /** * @param {Object} data Configuration data, represented as a simple * javascript object. */ constructor(data) { _argValidator.checkObject(data, 'Invalid configuration data (arg #1)'); this._data = data; } /** * Returns the value of the requested configuration property. Properties * can be specified as dot separated strings to reference nested properties * within complicated object structures. * * @param {String} prop The name of the property to fetch. This value can * be a dot separated string to idenfity a nested property value. * * @return {*} The value of the configuration property identified by the * property name. If this property (or any of the properties in * the dot separated value) is not found, undefined will be * returned. */ get(prop) { if (_dp.has(this._data, prop)) { return _dp.get(this._data, prop); } } }
JavaScript
class ClientLib { constructor() { this.color = { consoleScheme(value) { const colorName = Common.validatingString(value); let result = 0; if (colorName) { const color = Common.config.runtime.colorScheme.console[colorName]; if (typeof color === 'undefined') { Common.console.warn(`${Common.config.serviceApp.consoleEOL}Warning: unknown color name "${colorName}" in the color scheme "console".`); } else { result = color; } } return result; }, get popupScheme() { return Common.config.runtime.colorScheme.popup; }, getColor: value => `color: ${value}`, get heading() { return this.getColor(this.consoleScheme('heading')); }, get master() { return this.getColor(this.consoleScheme('master')); }, get slave() { return this.getColor(this.consoleScheme('slave')); }, get attention() { return this.getColor(this.consoleScheme('attention')); }, }; this.appName = [ '[', 'slave', Common.config.serviceApp.appName, 'heading', '] ', 'slave', ]; this.serviceApp = Common.config.serviceApp; this.runtime = Common.config.runtime; this.testPointTime = 0; this.windowObj = window; this.userAgent = window.navigator.userAgent; this.performanceObj = window.performance; } //-------------------------------------------------- /** * Returns the timestamp (DOMHighResTimeStamp). * @returns {*} */ get performanceNow() { let result = null; if (typeof this.performanceObj === 'object' && typeof this.performanceObj.now === 'function') { result = this.performanceObj.now(); } return result; } //-------------------------------------------------- /** * Which browser? * @returns {string} */ get getBrowserSignature() { let result = ''; // By default. if (typeof this.runtime.cache.browserSignature === 'string') { result = this.runtime.cache.browserSignature; } else { if (typeof this.userAgent !== 'undefined') { if (this.userAgent.toLowerCase().match(/applewebkit\//)) { result = 'Webkit'; } if (this.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) { result = 'Firefox'; } } this.runtime.cache.browserSignature = result; } return result; } //-------------------------------------------------- /** * Returns a Boolean value: whether the browser console supports coloring. * @returns {boolean} */ isColoringAvailable() { // TODO: refactoring. let result = false; // By default. if (this.serviceApp.allowColorization === true) { if (typeof this.runtime.cache.colorizationStatus === 'boolean') { result = this.runtime.cache.colorizationStatus; } else { switch (this.getBrowserSignature) { case 'Webkit': result = true; break; case 'Firefox': result = true; break; default: } this.runtime.cache.colorizationStatus = result; } } return result; } //-------------------------------------------------- /** * Returns the correct array for outputting colored data to the console. * @param {Array} value - An array with data pairs in the format: string, color. * @returns {Array} */ prepareColoring(value) { // TODO: refactoring. const result = []; if (Common.getValueType(value) === 'Array' && (value.length / 2) === Math.round(value.length / 2)) { if (this.isColoringAvailable()) { const textsArr = []; const colorsArr = []; value.forEach((v, i) => { if ((i / 2) === Math.round(i / 2)) { textsArr.push(`%c${v}`); } else { const colorStyle = this.color[v]; colorsArr.push((colorStyle === undefined) ? 'color: none' : colorStyle); } }); if (textsArr.length) { result.push(textsArr.join('')); result.push(...colorsArr); } } else { const textsArr = []; value.forEach((v, i) => { if ((i / 2) === Math.round(i / 2)) { textsArr.push(v); } }); result.push(textsArr.join('')); } } return result; } //-------------------------------------------------- /** * Returns the final version of the debug message. * @param {*} value - A value of any type. * @param {string} comment - Explanatory comment to the displayed value. * @returns {Array} */ getDebugMessage(value, comment) { const msgComment = Common.validatingString(comment); const result = []; this.runtime.globalIndentSize = 0; result.push(...[`Type: ${Common.getValueType(value)}`, 'slave']); if (msgComment) { result.push(...[ ' | ', 'slave', msgComment, 'master', ]); } result.push(...[ `${this.serviceApp.consoleEOL}Value: `, 'slave', Common.getResult(value), 'master', ]); return result; } //-------------------------------------------------- /** * Create main DOM-element for pop-up message. * This method returns nothing. */ createMsgBox() { if (this.runtime.msgContainer === null) { const popupParams = Common.config.popupMsg; const popupColorScheme = this.color.popupScheme; const verticalIndent = (popupParams.verticalPosition === 'bottom') ? popupParams.bottomIndent : 0; const popupStyleObj = document.createElement('style'); popupStyleObj.innerHTML = `.popupMsgBox{position:fixed;${popupParams.horizontalPosition}:0;${popupParams.verticalPosition}:${verticalIndent}px;background-color:${popupColorScheme.background};font-size:${popupParams.fontSize};font-family:monospace;color:${popupColorScheme.master};}` + `.popupMsgContainer{max-height:${popupParams.maxHeight}px;padding:7px;overflow:auto;border:1px solid ${popupColorScheme.border};cursor:default;}` + `.popupMsgUnit{max-width:${popupParams.maxWidth}px;margin-bottom:3px;padding:3px 21px 3px 0;border-bottom:1px dashed #d0d0d0;white-space:pre;}` + `.popupMsgUnit:hover{background-color:${popupColorScheme.hoverBG};}` + `.popupMsgObserver{padding:7px;border:1px solid ${popupColorScheme.border};cursor:default;}` + '.appendAnimation{-webkit-animation:append 600ms ease-out 1;animation:append 600ms ease-out 1;}' + `@-webkit-keyframes append {from { background-color: ${popupColorScheme.appendBG};} to { background-color: inherit; }}` + `@keyframes append {from { background-color: ${popupColorScheme.appendBG};} to { background-color: inherit; }}`; document.body.appendChild(popupStyleObj); const popupMsgBox = document.createElement('div'); popupMsgBox.className = 'popupMsgBox'; document.body.appendChild(popupMsgBox); const msgContainer = document.createElement('div'); msgContainer.className = 'popupMsgContainer'; msgContainer.style.display = 'none'; if (popupParams.showClearTitle === true) { msgContainer.setAttribute('title', 'Click to clear.'); } msgContainer.onclick = () => this.popupContainerClear(); this.runtime.msgContainer = popupMsgBox.appendChild(msgContainer); const observer = document.createElement('div'); observer.style.display = 'none'; if (popupParams.showClearTitle === true) { observer.setAttribute('title', 'Click to clear.'); } observer.onclick = () => { observer.style.display = 'none'; }; this.runtime.observer = popupMsgBox.appendChild(observer); } } //-------------------------------------------------- /** * Returns a string wrapped in the specified color. * @param {string} value - The string to be wrapped. * @param {string} color - One of the colors defined in the class constructor. * @returns {string} */ wrapString(value, color) { const stringForWrapping = Common.validatingString(value); const wrapColor = Common.validatingString(color); let result = ''; if (stringForWrapping) { if (wrapColor) { result = `<span style="color: ${wrapColor}">${stringForWrapping}</span>`; } else { result = stringForWrapping; } } return result; } //-------------------------------------------------- /** * Returns a string where data types that require special attention are highlighted. * @param {string} value - The source string. * @returns {string} */ highlightAttentions(value) { let result = Common.validatingString(value); const warningsArr = [ 'Undefined', 'Null', 'NaN', 'Infinity', '-Infinity', ]; warningsArr.forEach((item) => { if (result.indexOf(`: ${item}`) !== -1) { result = result.split(`: ${item}`).join(`: ${this.wrapString(item, this.color.popupScheme.attention)}`); } }); return result; } //-------------------------------------------------- /** * Returns a string where commas are highlighted. * @param {string} value - The source string. * @returns {string} */ highlightCommas(value) { let result = Common.validatingString(value); const commaSymbol = `,${this.serviceApp.consoleEOL}`; if (result.indexOf(commaSymbol) !== -1) { const coloredComma = this.wrapString(commaSymbol, this.color.popupScheme.slave); result = result.split(commaSymbol).join(coloredComma); } return result; } //-------------------------------------------------- /** * Deleting debugging information in a pop-up message. * This method returns nothing. */ popupContainerClear() { const container = this.runtime.msgContainer; if (container) { container.style.display = 'none'; container.innerHTML = ''; } } //-------------------------------------------------- /** * Adds debugging information to the pop-up message. * This method returns nothing. * @param {Array} value - Debug information. */ addMessage(value) { const container = this.runtime.msgContainer; const message = document.createElement('div'); let result = ''; message.className = 'popupMsgUnit appendAnimation'; if (Common.getValueType(value) === 'Array' && (value.length / 2) === Math.round(value.length / 2)) { // if (this.serviceApp.allowColorization === true) { const textsArr = []; const colorsArr = []; value.forEach((v, i) => { if ((i / 2) === Math.round(i / 2)) { textsArr.push(v); } else { colorsArr.push(this.color.popupScheme[v]); } }); textsArr.forEach((text, i) => { result += this.wrapString(text, colorsArr[i]); }); result = this.highlightAttentions(result); result = this.highlightCommas(result); // } else { // const textsArr = []; // value.forEach((v, i) => { // if ((i / 2) === Math.round(i / 2)) { // textsArr.push(v); // } // }); // result += textsArr.join(''); // } } if (result) { message.innerHTML = result; container.insertBefore(message, container.firstChild); container.style.display = 'block'; } } //-------------------------------------------------- /** * Resets the "observer" element to its original state. * Returns a reference to an element to display debugging information. * For a fixed field in a pop-up message. * @returns {Element} */ getObserver() { const observerValue = document.createElement('div'); const observerObj = this.runtime.observer; const observerFirstChild = observerObj.firstChild; observerValue.className = 'popupMsgObserver appendAnimation'; if (observerFirstChild === null) { observerObj.appendChild(observerValue); } else { observerObj.replaceChild(observerValue, observerFirstChild); } observerObj.style.display = 'block'; return observerValue; } }
JavaScript
class TestConfigParser extends ConfigParser { addPlugin (plugin) { return (super.addPlugin(plugin, plugin.variables), this); } addEngine (...args) { return (super.addEngine(...args), this); } }
JavaScript
class TraineeAll extends React.Component { constructor(props){ super(props) this.state = { trainee :[] } // this.postCourse=this.postCourse.bind(this); // this.updateCourse=this.updateCourse.bind(this); // this.deletecourse=this.deletecourse.bind(this); } componentDidMount(){ traineeservice.getTrainee().then((response) => { this.setState({ trainee: response.data}) }); } // postCourse(){ // this.props.history.push('/postcourse'); // } updateTainee(tid){ this.props.history.push(`/updatetraineemod/${tid}`, { headers: authHeader() }); } // deletecourse(cid){ // this.props.history.push(`/deletecourse/${cid}`, { headers: authHeader() }); // } render (){ return ( <div> <h1 className = "text-center"> All Trainee</h1> {/* <button style={{align : "center"}} className="btn btn-primary" onClick={this.postCourse}>Post Job</button> */} <table className="table table-striped table-bordered table-hover "> <thead> <tr> <th>Trainee Id</th> <th>Trainee FirstName</th> <th>Trainee LastName</th> <th>Trainee PhoneNo</th> <th>Trainee Qualification</th> <th>Country</th> <th>Status</th> <th>user id</th> <th>Action</th> </tr> </thead> <tbody> { this.state.trainee.map( trainee => <tr key = {trainee.tid}> <td> {trainee.tid}</td> {/* <td> {trainee.username}</td> <td> {trainee.user_id}</td> */} <td> {trainee.fname}</td> <td> {trainee.lname}</td> <td> {trainee.phoneno}</td> <td> {trainee.qualification}</td> <td> {trainee.country}</td> <td> {trainee.status}</td> <td> {trainee.user.id}</td> <td> <Button variant="contained" size="medium" color="primary" onClick = {() => this.updateTainee(trainee.tid)} > Update </Button> {/*<button style={{marginLeft: "10px"}} className="btn btn-danger" onClick={()=>this.deletecourse(course.cid)}> Delete </button> */} </td> </tr> ) } </tbody> </table> </div> ) } }
JavaScript
class Component { #timeSlice = 22 get timeSlice() { return this.#timeSlice } }
JavaScript
class Calculator { /** * Validates that the value is of the given type * @param {Unit} value - a unit * @param {String} expected - the expected type. * @throws {Error} if the value is not valid. * @returns {undefined} */ validate(value, expected){ if(!value){ return; } if(!(value instanceof Unit)){ throw new Error('Invalid argument. A Unit is expected.'); } if(value.type !== expected){ throw new Error(`Invalid unit type ${expected} for value ${value.type}`); } } /** * Test whether a value is prime: has no divisors other than itself and one. * @param {Number|Decimal} n - the number to check. * @return {Boolean} true if n is prime. */ isPrime(n) { if(n && n.isDecimal && n.isDecimal()){ n = n.toDP(0).toNumber(); } if (n < 2){ return false; } if (n === 2){ return true; } if (n % 2 === 0){ return false; } for (let i = 3; i * i <= n; i += 2){ if (n % i === 0){ return false; } } return true; } /** * Factorial of a number * @param {Decimal} n - the number * @return {Decimal} the factorial of n */ factorial(n) { if (n.isZero()) { return new Decimal(1); // 0! => 1 } let res = n; let value = n.toNumber() - 1; while (value > 1) { res = res.times(value); value--; } return res; } }
JavaScript
class Calendar extends React.Component { constructor(props) { super(props); this.state = { selectedTimeSlot: null, motorcycle_address: null, contact_number: null, note: null, touchedNote: false, }; this.moveEvent = this.moveEvent.bind(this); this.onSelect = this.onSelect.bind(this); this.onSuggestSelect = this.onSuggestSelect.bind(this); this.onSuggestChange = this.onSuggestChange.bind(this); this.onNoteChange = this.onNoteChange.bind(this); this.onNoteBlur = this.onNoteBlur.bind(this); this.onPhoneChange = this.onPhoneChange.bind(this); } // check if user is authenticated. if authenticated, save event to state. otherwise reroute. onSelect(event) { if (!this.props.authenticated) { browserHistory.push('/login'); } this.setState({ selectedTimeSlot: event }); window.scrollTo(0, 0); } onSuggestSelect(mapsObj) { this.setState({ motorcycle_address: mapsObj.label }); } onSuggestChange() { this.setState({ motorcycle_address: false }); } onNoteChange(e) { this.setState({ touchedNote: true }); this.setState({ note: e.target.value }); } onNoteBlur() { this.setState({ touchedNote: true }); } onPhoneChange(e) { const phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/; if (phoneNumberPattern.test(e.target.value)) { this.setState({ contact_number: e.target.value }); } else { this.setState({ contact_number: false }); } } moveEvent() { } render() { let conditionallyRenderStripeButton = null; // "insert the following below" && this.props.paid !== 'error' if (this.state.motorcycle_address && this.state.note && this.state.contact_number) { conditionallyRenderStripeButton = ( <div> <div className="payTextMarginBottom"> Pre-authorize your card for the quote total to schedule your appointment. </div> <StripeCheckout calendarAppointmentState={this.state} voucherCodeStatus={this.props.voucherCodeStatus} userId={this.props.userId} onSuccessfulOrder={this.props.onSuccessfulOrder} onPaymentAppointmentError={this.props.onPaymentAppointmentError} /> </div> ); } else { conditionallyRenderStripeButton = null; } const formats = { dateFormat: 'MMM Do YYYY', dayFormat: (date, culture, localizer) => localizer.format(date, 'Do', culture), }; let timeSlotSelectedMessage = null; let paymentResponseMessage = null; if (this.props.paid === true) { paymentResponseMessage = ( <Message positive> <Message.Content> Thank you for your payment! Routing you in just a sec... </Message.Content> </Message> ); } else if (this.props.paid === false) { paymentResponseMessage = ( <Message negative> <Message.Content> Oh no :( Something went wrong with the payment. Please check your card details and try again. </Message.Content> </Message> ); } else if (this.props.paid === 'error') { paymentResponseMessage = ( <Message negative> <Message.Header> Appointment Scheduling Error </Message.Header> <Message.Content> Your payment has been successful, but something went wrong when scheduling the appointment. Do not try to pay again. <br /> <a href="javascript:void(Tawk_API.toggle())"> Click here </a> to live chat or call us @ (929)356-4313 at your soonest convenience and let us know. </Message.Content> </Message> ); } if (this.state.selectedTimeSlot) { timeSlotSelectedMessage = ( <div> {paymentResponseMessage} <Message info> <span>{moment(this.state.selectedTimeSlot.start).format('MMM D @ h:mm A')} to {moment(this.state.selectedTimeSlot.end).format('MMM D @ h:mm A')}</span> <Message.Content> <Form> <div className="ui large icon input calendarGeosuggestMargin"> <Geosuggest placeholder="Appointment Address" country="us" types={['geocode']} onSuggestSelect={(mapObj) => this.onSuggestSelect(mapObj)} onChange={this.onSuggestChange} /> <i className="location arrow icon"></i> </div> { this.state.motorcycle_address === false && <Label basic color="yellow">Please select an address from the suggestions list</Label> } <div className="phoneNumberMarginBottom"> <Input icon="mobile" placeholder="Mobile number" size="large" onChange={this.onPhoneChange} /> {this.state.contact_number === false && <Label basic color="yellow">Please enter a valid number</Label> } </div> <div className="phoneNumberMarginBottom"> <Input icon="sticky note" placeholder="Add any notes here" size="large" onChange={this.onNoteChange} onBlur={this.onNoteBlur} /> {this.state.touchedNote && !this.state.note && <Label basic color="yellow">Please enter a note for your mechanic or write {'none'}</Label> } </div> </Form> {conditionallyRenderStripeButton} </Message.Content> </Message> </div> ); } return ( <div> {timeSlotSelectedMessage} <DragAndDropCalendar formats={formats} selectable events={this.props.availableAppointments} onSelectEvent={this.onSelect} onEventDrop={this.moveEvent} eventPropGetter={ (event) => ({ className: `category-${event.category.toLowerCase()}` }) } views={['month', 'week', 'day']} defaultView="week" min={new Date(1970, 1, 1, 8)} max={new Date(1970, 1, 1, 19)} /> </div> ); } }
JavaScript
class OeDate extends mixinBehaviors([IronFormElementBehavior, PaperInputBehavior], PolymerElement) { static get is() { return 'oe-date'; } static get template() { return html` <style> .suffix-btn { color: var(--paper-input-container-color, var(--secondary-text-color)); padding: 0; margin: 0; min-width: 0; @apply --oe-date-suffix; } .vertical { height: 100%; @apply --layout-vertical; } .filler { @apply --layout-flex; } .horizontal { @apply --layout-horizontal; height: 46px; } .dropdown-content{ min-height: 340px; min-width: 300px; } .date-button:focus{ color: var(--paper-input-container-focus-color, --primary-color); } oe-input { @apply --oe-input-date; } </style> <dom-if if=[[_computeAttachDialog(dropdownMode,dialogAttached)]]> <template> <oe-datepicker-dlg value="{{value}}" id="_picker" max=[[max]] min=[[min]] start-of-week="[[startOfWeek]]" disabled-days="[[disabledDays]]" holidays="[[holidays]]" locale="[[locale]]" on-oe-date-picked="_datePicked" default-date=[[_resolveReferenceDate(referenceDate,referenceTimezone)]]></oe-datepicker-dlg> </template> </dom-if> <oe-input id="display" label=[[label]] required$=[[required]] readonly="[[readonly]]" disabled=[[disabled]] validator=[[validator]] no-label-float=[[noLabelFloat]] always-float-label="[[alwaysFloatLabel]]" invalid={{invalid}} value={{_dateValue}} error-message={{errorMessage}} error-placeholders={{errorPlaceholders}} max=[[max]] min=[[min]]> <paper-button aria-label="clear date from calendar" hidden$=[[!disableTextInput]] slot="suffix" class="suffix-btn" on-tap="_clearDate"> <iron-icon icon="clear"></iron-icon> </paper-button> <paper-button aria-label="Select date from calendar" hidden$=[[hideIcon]] slot="suffix" class="suffix-btn date-button" disabled=[[disabled]] on-tap="_showDatePicker"> <iron-icon icon="today"></iron-icon> </paper-button> </oe-input> <dom-if if=[[_computeAttachDropdown(dropdownMode,dropdownAttached)]]> <template> <iron-dropdown id="dropdown" no-cancel-on-outside-click=[[openOnFocus]] no-animations horizontal-align="right" vertical-align="{{verticalAlign}}" vertical-offset="{{verticalOffset}}" no-auto-focus opened={{expand}}> <paper-card tabindex="-1" slot="dropdown-content" class="dropdown-content layout vertical" disabled$="[[disabled]]"> <div class="vertical flex"> <oe-datepicker tabindex="-1" disable-initial-load class="flex" id="datePicker" value="{{localValue}}" locale="[[locale]]" start-of-week="[[startOfWeek]]" disabled-days="[[disabledDays]]" holidays="[[holidays]]" max=[[max]] min=[[min]] on-selection-double-click="_onOK"></oe-datepicker> <div class="horizontal"> <div class="filler"></div> <paper-button id="cancelBtn" on-tap="_onCancel">Cancel</paper-button> <paper-button id="okBtn" on-tap="_onOK">OK</paper-button> </div> </div> </paper-card> </iron-dropdown> </template> </dom-if> `; } static get properties() { return { /** * Initial/default value for the control */ init: { type: String }, /** * Setting to true hides the calender icon in the control which open the datepicker dialog */ hideIcon: { type: Boolean, value: false }, /** * Setting to true makes the datepicker open as a dropdown instead of a dialog */ dropdownMode: { type: Boolean, value: false }, /** * vertical offset for date picker dropdown */ verticalOffset: { type: String, value: 62 }, /** * vertical alignment for date picker dropdown */ verticalAlign: { type: String, value: 'top' }, /** * Setting to true makes the datepicker open as a dropdown on focus of this element. * This will work only if the oe-date component is in dropdown-mode. */ openOnFocus: { type: Boolean, value: false }, /** * Maximum allowed date (accepts date shorthands) */ max: { type: Object, observer: '_maxChanged' }, /** * Minimum allowed date (accepts date shorthands) */ min: { type: Object, observer: '_minChanged' }, /** * flag allows enabling/disabling the control */ disabled: { type: Boolean, value: false }, /** * Start of the week for calendar display [0(Sunday)-6(Saturday)] */ startOfWeek: { type: Number, value: 1 }, /** * Weekly off days [0(Sunday)-6(Saturday)] */ disabledDays: { type: Array }, /** * control's validity flag */ invalid: { type: Boolean, value: false, notify: true, reflectToAttribute: true }, /** * Fired when a date is selected by pressing the Ok button. * * @event oe-date-picked */ /** * Fired when the value is changed by the user. * * @event oe-field-changed */ }; } _computeAttachDialog(dropdownMode, dialogAttached) { return !dropdownMode && dialogAttached; } _computeAttachDropdown(dropdownMode, dropdownAttached) { return dropdownMode && dropdownAttached; } constructor() { super(); this._hasUserTabIndex = this.hasAttribute('tabindex'); this.dialogAttached = false; this.dropdownAttached = false; } /** * Connected Callback to initiate 'change' listener with validation function. */ connectedCallback() { super.connectedCallback(); if (!this._hasUserTabIndex) { //Removing the tabindex=0 set by paper-input-behavior //This prevents the focus from moving to the next field in FireFox this.removeAttribute('tabindex'); } this.inputElement.addEventListener('change', e => this._displayChanged(e)); this.$.display.addEventListener('focus', e => this._focusHandle(e)); this.addEventListener('blur', e => this._blurHandle(e)); //if value is set instead of date-value, trigger parsing of init-value if (!this.value && this.init) { this.$.display.set('value', this.init); this.$.display.inputElement.fire('change'); } this.set('expand', false); //this.set('localValue', new Date()); if (this.max && typeof this.max === 'string') { var newDate = this._parseShorthand(this.max); if (newDate) { this.set('max', newDate); } else { console.warn("Invalid 'max' date value", this.max); } } if (this.min && typeof this.max === 'string') { var newDate = this._parseShorthand(this.min); // eslint-disable-line no-redeclare if (newDate) { this.set('min', newDate); } else { console.warn("Invalid 'min' date value", this.min); } } if (!this.dropdownMode && this.openOnFocus) { console.warn("open-on-focus is only available in dropdown-mode."); } /** oe-input.Iron-Input.inputElement remains undefined * (looks like _initSlottedInput only for subsequent dom-change) */ this.inputElement._initSlottedInput(); } _forwardFocus(e) { this.$.display.focus(); } _focusHandle(e) { // eslint-disable-line no-unused-vars if (this.openOnFocus && this.dropdownMode && !this.expand) { this.__expandDropDown(); } } _blurHandle(e) { // eslint-disable-line no-unused-vars if (this.openOnFocus && this.dropdownMode) { this.set('expand', false); } } /** * Returns a reference to the focusable element. Overridden from * PaperInputBehavior to correctly focus the native input. * * @return {HTMLElement} */ get _focusableElement() { return PolymerElement ? this.inputElement._inputElement : this.inputElement; } /** * Returns a reference to the input element. */ get inputElement() { return this.$.display.inputElement; } /** * Launches date-picker as dialog or a dropdown * */ _showDatePicker(e) { // eslint-disable-line no-unused-vars if (!this.readonly && !this.disabled) { if (this.dropdownMode) { if (!this.expand && !this.openOnFocus) { this.__expandDropDown(); } } else { if (!this.dialogAttached) { this.set('dialogAttached', true); this.async(function () { this.$$('#_picker').open(); }.bind(this), 0); } else { this.$$('#_picker').open(); } } } } __expandDropDown() { if (!this.dropdownAttached) { this.set('dropdownAttached', true); this.async(function () { this.set('expand', true); this.set('localValue', this.value || this._resolveReferenceDate(this.referenceDate, this.referenceTimezone)); }.bind(this), 0); } else { this.set('expand', true); this.set('localValue', this.value || this._resolveReferenceDate(this.referenceDate, this.referenceTimezone)); } } /** * Called when date is selected using dialog */ _datePicked(e) { // eslint-disable-line no-unused-vars if(this.fieldId) { this.fire('oe-field-changed', {fieldId: this.fieldId, value: e.detail}); } } // /** // * Selects the icon to display inside the oe-date input // * @param {boolean} dropdownMode // * @return {string} icon for dropdown or calendar // */ // _computeIcon(dropdownMode) { // return dropdownMode ? "arrow-drop-down" : "today"; // } /** * Sets the selected value and closes the dropdown */ _onOK() { this.set('value', this.localValue); this.fire('oe-date-picked', this.value); this.set('expand', false); if(this.fieldId) { this.fire('oe-field-changed', {fieldId: this.fieldId, value: this.value}); } } /** * Closes the dropdown */ _onCancel() { //this.set('localValue', this.value); this.set('expand', false); } /** * Parses the shorthand for "max" and validates the value. * @param {Object} newMax */ _maxChanged(newMax) { if (newMax && typeof newMax === 'string') { var newDate = this._parseShorthand(newMax); if (newDate) { this.set('max', newDate); this.value && this.validate(); } else { console.warn("Invalid 'max' date value", this.max); } } } /** * Parses the shorthand for "min" and validates the value. * @param {Object} newMin */ _minChanged(newMin) { if (newMin && typeof newMin === 'string') { var newDate = this._parseShorthand(newMin); if (newDate) { this.set('min', newDate); this.value && this.validate(); } else { console.warn("Invalid 'min' date value", this.max); } } } }
JavaScript
class SSRAssetsMatcher { /** * Assets to browser matcher. * @param {object} options - Options to create matcher. * @param {object} [options.assets] - Assets collection object. * @param {string} [options.assetsFile] - Path to JSON file with assets collection. * @param {object} [options.fs] - NodeJS's FS compatible module. */ constructor({ assets, assetsFile, fs = realFs }) { /** * @type {Map<string, RegExp>} */ this.envsMap = new Map(); /** * @type {string} */ this.defaultEnv = null; /** * @type {Map<string, SSRAssetsContainer>} */ this.containersMap = new Map(); if (assets) { this.parseAssetsCollection(assets); } else { this.readAssetsCollection(fs, assetsFile); } } parseAssetsCollection({ matchers, assets }) { const { envsMap, containersMap } = this; this.defaultEnv = Object.keys(matchers).pop(); Object.entries(matchers).forEach(([env, regExp]) => { envsMap.set(env, new RegExp(regExp)); }); Object.entries(assets).forEach(([env, container]) => { containersMap.set(env, SSRAssetsContainer.fromJS(env, container)); }); } readAssetsCollection(fs, assetsFile) { const file = fs.readFileSync(assetsFile, 'utf8'); const collection = JSON.parse(file); this.parseAssetsCollection(collection); } /** * Get assets for browser by useragent. * @param {string} userAgent - UserAgent to match assets. * @return {SSRAssetsContainer} Assets container. */ match(userAgent) { const { envsMap, defaultEnv, containersMap } = this; const matchers = envsMap.entries(); for (const [env, regExp] of matchers) { if (regExp.test(userAgent)) { return containersMap.get(env); } } return containersMap.get(defaultEnv); } }
JavaScript
class CustomHeaderEditing extends Plugin { /** * @inheritDoc */ static get pluginName() { return "CustomHeaderEditing"; } /** * @inheritDoc */ init() { const editor = this.editor; // Allow bold attribute on text nodes. editor.model.schema.extend("$text", { allowAttributes: CUSTOMHEADER }); editor.model.schema.setAttributeProperties(CUSTOMHEADER, { isFormatting: true, copyOnEnter: true }); // Build converter from model to view for data and editing pipelines. editor.conversion.attributeToElement({ model: CUSTOMHEADER, view: "h2", upcastAlso: [ { styles: { "font-size": "24px" } } ] }); // Create bold command. editor.commands.add(CUSTOMHEADER, new AttributeCommand(editor, CUSTOMHEADER)); // Set the Ctrl+B keystroke. // editor.keystrokes.set( 'CTRL+B', CUSTOMHEADER ); } }
JavaScript
class TemplateResult { /** * Constructor * * @param { Template } template * @param { Array<unknown> } values */ constructor(template, values) { this.template = template; this.values = values; this.id = id++; this.index = 0; } /** * Consume template result content. * * @param { RenderOptions } [options] * @returns { unknown } */ read(options) { let buffer = EMPTY_STRING_BUFFER; let chunk; /** @type { Array<Buffer> | undefined } */ let chunks; while ((chunk = this.readChunk(options)) !== null) { if (isBuffer(chunk)) { buffer = Buffer.concat([buffer, chunk], buffer.length + chunk.length); } else { if (chunks === undefined) { chunks = []; } buffer = reduce(buffer, chunks, chunk) || EMPTY_STRING_BUFFER; } } if (chunks !== undefined) { chunks.push(buffer); return chunks.length > 1 ? chunks : chunks[0]; } return buffer; } /** * Consume template result content one chunk at a time. * @param { RenderOptions } [options] * @returns { unknown } */ readChunk(options) { const isString = this.index % 2 === 0; const index = (this.index / 2) | 0; // Finished if (!isString && index >= this.template.strings.length - 1) { // Reset this.index = 0; return null; } this.index++; if (isString) { return this.template.strings[index]; } const part = this.template.parts[index]; let value; if (isAttributePart(part)) { // AttributeParts can have multiple values, so slice based on length // (strings in-between values are already handled the instance) if (part.length > 1) { value = part.getValue(this.values.slice(index, index + part.length), options); this.index += part.length; } else { value = part.getValue([this.values[index]], options); } } else { value = part && part.getValue(this.values[index], options); } return value; } }
JavaScript
class ResonanceAudioNode extends BaseWebAudioNode { /** * Creates a new spatializer that uses Google's Resonance Audio library. */ constructor(id, source, audioContext, res) { const resNode = res.createSource(undefined); super(id, source, audioContext, resNode.input); this.resScene = res; this.resNode = resNode; Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. */ update(loc, _t) { const { p, f, u } = loc; this.resNode.setPosition(p); this.resNode.setOrientation(f, u); } /** * Sets parameters that alter spatialization. **/ setAudioProperties(minDistance, maxDistance, rolloff, algorithm, transitionTime) { super.setAudioProperties(minDistance, maxDistance, rolloff, algorithm, transitionTime); this.resNode.setMinDistance(this.minDistance); this.resNode.setMaxDistance(this.maxDistance); this.resNode.setGain(1 / this.rolloff); this.resNode.setRolloff(this.algorithm); } /** * Discard values and make this instance useless. */ dispose() { this.resScene.removeSource(this.resNode); this.resNode = null; super.dispose(); } }
JavaScript
class DB { constructor (option) { this.option = option; } /** * send * @param {Object} name */ send(option) { return new Sender(this, option); }; }
JavaScript
class CMDBGroupAPI { constructor() {} /** * Returns all CIs for this group. This includes all manual CIs and the list of CIs from * the Query Builder's saved query. * @param {String} groupId The sysId of the CMDB group. * @param {Boolean} requireCompleteSet When true, returns an empty string if any CIs are filtered out by ACL * restrictions. * @returns A JSON formated string in the format * { 'result':false, * 'errors':[ {'message':'Group does not exist', * 'error':'GROUP_SYS_ID_IS_NOT_FOUND'}, * { } // another error if it exists * ], * 'partialCIListDueToACLFlag':false, * 'idList':['sys_id_1', 'sys_id2'] } * Where * result - a boolean flag. When true the method was successful. * errors - a list of errors with a message and error code. * partialCIListDueToACLFlag -  a Boolean flag. When true, the idList is * incomplete due to an ACL restriction. When false, the idList is complete. * idList - an array of cmdb_ci sys_ids * When not successful, returns one of the errors GROUP_SYS_ID_IS_NOT_FOUND, * GROUP_SYS_ID_IS_EMPTY, FAIL_TO_INSERT_GROUP_CI_PAIR, * FAIL_TO_INSERT_GROUP_QUERY_ID_PAIR, CI_CAN_NOT_FOUND, SAVED_QUERY_ID_NOT_FOUND, * ERROR_DURING_QUERY_BUILDER_PROCESS_QUERY, * TIMEOUT_DURING_QUERY_BUILDER_PROCESS_QUERY, * NOT_COMPLETE_DURING_QUERY_BUILDER_PROCESS_QUERY, * MAX_LIMIT_DURING_QUERY_BUILDER_PROCESS_QUERY, GROUP_API_TIMEOUT, * EXCEPTION_FROM_EXECUTE_QUERY, * SOME_CI_NOT_VISIBLE_DUE_TO_SECURITY_CONSTRAINT * @example // Script example: * var getAllCIFunc = function(groupSysId) { * var parser = new JSONParser(); * var response = sn_cmdbgroup.CMDBGroupAPI.getAllCI(groupSysId, false); * var parsed = parser.parse(response); * if (parsed.result) { * gs.print("succeed to retrieve ci list: " + parsed.idList); * } else { * gs.print("fail to retrieve list, errors: " + JSON.stringify(parsed.errors)); * } * } * var groupExists = "d0d2d25113152200eef2dd828144b0e4"; * var groupContainsInvalidSavedQuery = "e685a2c3d7012200de92a5f75e610387"; * getAllCIFunc(groupExists); * getAllCIFunc(groupContainsInvalidSavedQuery); */ getAllCI(groupId, requireCompleteSet) {} /** * Returns all CIs returned from all saved query builder's query IDs for the specified * group. * @param {String} groupId The sysId of the CMDB group. * @param {Boolean} requireCompleteSet When true, returns an empty string if any CIs are filtered out by ACL * restrictions. * @returns A JSON formated string in the format * { 'result':false, * 'errors':[ {'message':'Group does not exist', * 'error':'GROUP_SYS_ID_IS_NOT_FOUND'}, * { } // another error if it exists * ], * 'partialCIListDueToACLFlag':false, * 'idList':['sys_id_1', 'sys_id2'] } * Where * result - a boolean flag. When true the method was successful. * errors - a list of errors with a message and error code. * partialCIListDueToACLFlag -  a Boolean flag. When true, the idList is * incomplete due to an ACL restriction. When false, the idList is complete. * idList - an array of cmdb_ci sys_ids * When not successful, returns one of the errors GROUP_SYS_ID_IS_NOT_FOUND, * GROUP_SYS_ID_IS_EMPTY, FAIL_TO_INSERT_GROUP_CI_PAIR, * FAIL_TO_INSERT_GROUP_QUERY_ID_PAIR, CI_CAN_NOT_FOUND, SAVED_QUERY_ID_NOT_FOUND, * ERROR_DURING_QUERY_BUILDER_PROCESS_QUERY, * TIMEOUT_DURING_QUERY_BUILDER_PROCESS_QUERY, * NOT_COMPLETE_DURING_QUERY_BUILDER_PROCESS_QUERY, * MAX_LIMIT_DURING_QUERY_BUILDER_PROCESS_QUERY, GROUP_API_TIMEOUT, * EXCEPTION_FROM_EXECUTE_QUERY, * SOME_CI_NOT_VISIBLE_DUE_TO_SECURITY_CONSTRAINT * @example // Script example: * var getAllCIFromQueryBuilderFunc = function(groupSysId) { * var parser = new JSONParser(); * var response = sn_cmdbgroup.CMDBGroupAPI.getAllCIFromQueryBuilder(groupSysId, false); * var parsed = parser.parse(response); * if (parsed.result) { * gs.print("succeed to retrieve ci list: " + parsed.idList); * } else { * gs.print("fail to retrieve list, errors: " + JSON.stringify(parsed.errors)); * } * } * var groupExists = "d0d2d25113152200eef2dd828144b0e4"; * var groupContainsInvalidSavedQuery = "e685a2c3d7012200de92a5f75e610387"; * getAllCIFromQueryBuilderFunc(groupExists); * getAllCIFromQueryBuilderFunc(groupContainsInvalidSavedQuery); */ getAllCIFromQueryBuilder(groupId, requireCompleteSet) {} /** * Returns the CMDB group's manual CI list. * @param {String} groupId The sysId of the CMDB group. * @param {Boolean} requireCompleteSet When true, returns an error string if any CIs are filtered out by ACL * restrictions. * @returns A JSON formated string in the format * { 'result':false, * 'errors':[ {'message':'Group does not exist', * 'error':'GROUP_SYS_ID_IS_NOT_FOUND'}, * { } // another error if it exists * ], * 'partialCIListDueToACLFlag':false, * 'idList':['sys_id_1', 'sys_id2'] } * Where * result - a boolean flag. When true the method was successful. * errors - a list of errors with a message and error code. * partialCIListDueToACLFlag -  a Boolean flag. When true, the idList is * incomplete due to an ACL restriction. When false, the idList is complete. * idList - an array of cmdb_ci sys_ids * When not successful, returns one of the errors GROUP_SYS_ID_IS_NOT_FOUND, * GROUP_SYS_ID_IS_EMPTY, FAIL_TO_INSERT_GROUP_CI_PAIR, * FAIL_TO_INSERT_GROUP_QUERY_ID_PAIR, CI_CAN_NOT_FOUND, SAVED_QUERY_ID_NOT_FOUND, * ERROR_DURING_QUERY_BUILDER_PROCESS_QUERY, * TIMEOUT_DURING_QUERY_BUILDER_PROCESS_QUERY, * NOT_COMPLETE_DURING_QUERY_BUILDER_PROCESS_QUERY, * MAX_LIMIT_DURING_QUERY_BUILDER_PROCESS_QUERY, GROUP_API_TIMEOUT, * EXCEPTION_FROM_EXECUTE_QUERY, * SOME_CI_NOT_VISIBLE_DUE_TO_SECURITY_CONSTRAINT * @example // Script example for requireCompleteSet being false: * var getManualCIList = function(groupSysId) { * var parser = new JSONParser(); * var response = sn_cmdbgroup.CMDBGroupAPI.getManualCIList(groupSysId, false); * var parsed = parser.parse(response); * if (parsed.result) { * gs.print("succeed to retrieve ci list: " + parsed.idList); * } else { * gs.print("fail to retrieve list, errors: " + JSON.stringify(parsed.errors)); * } * } * // create a group in cmdb_group, and add CIs to this group in Edit Manual CI form * var groupExists = "d0d2d25113152200eef2dd828144b0e4"; * // use a non-exist group * var groupDoesNotExists = "d0d2d25113152200eef2dd828144b0e4111"; * getManualCIList(groupExists); * getManualCIList(groupDoesNotExists); * * @example // Script example for requireCompleteSet being true * var getManualCIList = function(groupSysId) { * var parser = new JSONParser(); * var response = sn_cmdbgroup.CMDBGroupAPI.getManualCIList(groupSysId, true); * var parsed = parser.parse(response); * if (parsed.result) { * gs.print("succeed to retrieve ci list: " + parsed.idList); * } else { * gs.print("fail to retrieve list, errors: " + JSON.stringify(parsed.errors)); * } * } * // create a group in cmdb_group, and add CIs to this group in Edit Manual CI form * var groupExists = "d0d2d25113152200eef2dd828144b0e4"; * getManualCIList(groupExists); */ getManualCIList(groupId, requireCompleteSet) {} /** * Returns the query builder's query IDs for the specified CMDB group. * @param {String} groupId The sysId of the CMDB group. * @param {Boolean} requireCompleteSet When true, returns an empty string if any CIs are filtered out by ACL * restrictions. * @returns A JSON formated string in the format * { 'result':false, * 'errors':[ {'message':'Group does not exist', * 'error':'GROUP_SYS_ID_IS_NOT_FOUND'}, * { } // another error if it exists * ], * 'partialCIListDueToACLFlag':false, * 'idList':['sys_id_1', 'sys_id2'] } * Where * result - a boolean flag. When true the method was successful. * errors - a list of errors with a message and error code. * partialCIListDueToACLFlag -  a Boolean flag. When true, the idList is * incomplete due to an ACL restriction. When false, the idList is complete. * idList - an array of cmdb_ci sys_ids * When not successful, returns one of the errors GROUP_SYS_ID_IS_NOT_FOUND, * GROUP_SYS_ID_IS_EMPTY, FAIL_TO_INSERT_GROUP_CI_PAIR, * FAIL_TO_INSERT_GROUP_QUERY_ID_PAIR, CI_CAN_NOT_FOUND, SAVED_QUERY_ID_NOT_FOUND, * ERROR_DURING_QUERY_BUILDER_PROCESS_QUERY, * TIMEOUT_DURING_QUERY_BUILDER_PROCESS_QUERY, * NOT_COMPLETE_DURING_QUERY_BUILDER_PROCESS_QUERY, * MAX_LIMIT_DURING_QUERY_BUILDER_PROCESS_QUERY, GROUP_API_TIMEOUT, * EXCEPTION_FROM_EXECUTE_QUERY, * SOME_CI_NOT_VISIBLE_DUE_TO_SECURITY_CONSTRAINT * @example // Script example: * var getSavedQueryIdList = function(groupSysId) { * var parser = new JSONParser(); * var response = sn_cmdbgroup.CMDBGroupAPI.getSavedQueryIdList(groupSysId, false); * var parsed = parser.parse(response); * if (parsed.result) { * gs.print("succeed to retrieve saved query id list: " + parsed.idList); * } else { * gs.print("fail to retrieve list, errors: " + JSON.stringify(parsed.errors)); * } * } * var groupExists = "d0d2d25113152200eef2dd828144b0e4"; * var groupDoesNotExists = "d0d2d25113152200eef2dd828144b0e4111"; * getSavedQueryIdList(groupExists); * getSavedQueryIdList(groupDoesNotExists); */ getSavedQueryIdList(groupId, requireCompleteSet) {} /** * Sets the manual CI list for the specified group. The existing manual CI list is * overwritten. CI sysIds not found in the cmdb_ci table are ignored. * @param {String} groupId The sysId of the CMDB group. * @param {String} ciSysIds Comma separated list of CI sysIds. * @returns A JSON formated string in the format * { 'result':false, * 'errors':[ {'message':'Group does not exist', * 'error':'GROUP_SYS_ID_IS_NOT_FOUND'}, * { } // another error if it exists * ], * 'partialCIListDueToACLFlag':false, * 'idList':['sys_id_1', 'sys_id2'] } * Where * result - a boolean flag. When true the method was successful. * errors - a list of errors with a message and error code. * partialCIListDueToACLFlag -  a Boolean flag. When true, the idList is * incomplete due to an ACL restriction. When false, the idList is complete. * idList - an array of cmdb_ci sys_ids * When not successful, returns one of the errors GROUP_SYS_ID_IS_NOT_FOUND, * GROUP_SYS_ID_IS_EMPTY, FAIL_TO_INSERT_GROUP_CI_PAIR, * FAIL_TO_INSERT_GROUP_QUERY_ID_PAIR, CI_CAN_NOT_FOUND, SAVED_QUERY_ID_NOT_FOUND, * ERROR_DURING_QUERY_BUILDER_PROCESS_QUERY, * TIMEOUT_DURING_QUERY_BUILDER_PROCESS_QUERY, * NOT_COMPLETE_DURING_QUERY_BUILDER_PROCESS_QUERY, * MAX_LIMIT_DURING_QUERY_BUILDER_PROCESS_QUERY, GROUP_API_TIMEOUT, * EXCEPTION_FROM_EXECUTE_QUERY, * SOME_CI_NOT_VISIBLE_DUE_TO_SECURITY_CONSTRAINT * @example // Script example: * var setManualCIListFunc = function(groupSysId, manualCIList) { * var parser = new JSONParser(); * var response = sn_cmdbgroup.CMDBGroupAPI.setManualCIList(groupSysId, manualCIList); * var parsed = parser.parse(response); * if (parsed.result) { * gs.print("succeed to set manual ci list"); * } else { * gs.print("fail to set manual ci list, errors: " + JSON.stringify(parsed.errors)); * } * } * var group = "d0d2d25113152200eef2dd828144b0e4"; * var groupDoesNotExist = "1234"; * var manualCIList = "b4fd7c8437201000deeabfc8bcbe5dc1, affd3c8437201000deeabfc8bcbe5dc3"; * setManualCIListFunc(group, manualCIList); * setManualCIListFunc(groupDoesNotExist, manualCIList); */ setManualCIList(groupId, ciSysIds) {} /** * Sets the saved query ID list for the specified group. The existing query ID list is * overwritten. Query sysIds not found in the qb_saved_query table are ignored. * @param {String} groupId The sysId of the CMDB group. * @param {String} queryIds Comma separated list of saved query sysIds. * @returns A JSON formated string in the format * { 'result':false, * 'errors':[ {'message':'Group does not exist', * 'error':'GROUP_SYS_ID_IS_NOT_FOUND'}, * { } // another error if it exists * ], * 'partialCIListDueToACLFlag':false, * 'idList':['sys_id_1', 'sys_id2'] } * Where * result - a boolean flag. When true the method was successful. * errors - a list of errors with a message and error code. * partialCIListDueToACLFlag -  a Boolean flag. When true, the idList is * incomplete due to an ACL restriction. When false, the idList is complete. * idList - an array of cmdb_ci sys_ids * When not successful, returns one of the errors GROUP_SYS_ID_IS_NOT_FOUND, * GROUP_SYS_ID_IS_EMPTY, FAIL_TO_INSERT_GROUP_CI_PAIR, * FAIL_TO_INSERT_GROUP_QUERY_ID_PAIR, CI_CAN_NOT_FOUND, SAVED_QUERY_ID_NOT_FOUND, * ERROR_DURING_QUERY_BUILDER_PROCESS_QUERY, * TIMEOUT_DURING_QUERY_BUILDER_PROCESS_QUERY, * NOT_COMPLETE_DURING_QUERY_BUILDER_PROCESS_QUERY, * MAX_LIMIT_DURING_QUERY_BUILDER_PROCESS_QUERY, GROUP_API_TIMEOUT, * EXCEPTION_FROM_EXECUTE_QUERY, * SOME_CI_NOT_VISIBLE_DUE_TO_SECURITY_CONSTRAINT * @example // Script example: * var setSavedQueryIdListFunc = function(groupSysId, queryIdList) { * var parser = new JSONParser(); * var response = sn_cmdbgroup.CMDBGroupAPI.setSavedQueryIdList(groupSysId, queryIdList); * var parsed = parser.parse(response); * if (parsed.result) { * gs.print("succeed to set saved query id list"); * } else { * gs.print("fail to set saved query id list, errors: " + JSON.stringify(parsed.errors)); * } * } * var group = "d0d2d25113152200eef2dd828144b0e4"; * var savedQueryBuilderIdList = "394585fed7812200de92a5f75e6103e8"; * var savedQueryBuilderIdNotExistList = "b4fd7c8437201000deeabfc8bcbe5dc1, * affd3c8437201000deeabfc8bcbe5dc3"; * setSavedQueryIdListFunc(group, savedQueryBuilderIdList); * setSavedQueryIdListFunc(group, savedQueryBuilderIdNotExistList); * */ setSavedQueryIdList(groupId, queryIds) {} }
JavaScript
class NoConnectionOptionError extends TypeORMError_1.TypeORMError { constructor(optionName) { super(`Option "${optionName}" is not set in your connection options, please ` + `define "${optionName}" option in your connection options or ormconfig.json`); } }
JavaScript
class Meetings extends SparkPlugin { namespace = MEETINGS; /** * Initializes the Meetings Plugin * * @returns {null} * @memberof Meetings */ constructor(...args) { super(...args); this.meetingInfo = new MeetingInfo({}, {parent: this.spark}); this.request = new Request({}, {parent: this.spark}); this.personalMeetingRoom = new PersonalMeetingRoom({}, {parent: this.spark}); this.onReady(); } handleLocusEvent(data) { let meeting = null; meeting = this.getMeetingByType(LOCUS_URL, data.locusUrl); if (!meeting) { // TODO: create meeting when we get a meeting object // const checkForEnded = (locus) => { // TODO: you already ended the meeting but you got an event later // Mainly for 1:1 Callsor meeting // Happens mainly after refresh // 1:1 Meeting // 1) You ended a call before but you got a mercury event // Make sure end the call and cleanup the meeting only if the mercury // event says so // 2) Maintain lastSync time in the meetings object which helps to compare // If the meeting came befor or after the sync . ANy meeting start time before the sync time is invalid // For space Meeting // Check the locus object and see who has joined // }; // rather then locus object change to locus url this.create(data.locus, LOCUS_ID).then(() => { if (data.eventType === LOCUSEVENT.DIFFERENCE) { // its a delta object and we have a new meeting meeting.locusInfo.initialSetup(data.locus, meeting); } else { // Its a new meeting and have a fresh locus object meeting.locusInfo.initialSetup(data.locus); } }); } else { meeting.locusInfo.parse(meeting, data); } } /** * registers for locus and roap mercury events * @returns {object} returns nothing */ listenForEvents() { this.spark.internal.mercury.on(LOCUSEVENT.LOCUS_MERCURY, (envelope) => { const {data} = envelope; const {eventType} = data; if (eventType !== LOCUSEVENT.MESSAGE_ROAP) { this.handleLocusEvent(data); } }); this.spark.internal.mercury.on(ROAP.ROAP_MERCURY, (envelope) => { const {data} = envelope; const {eventType} = data; if (eventType === LOCUSEVENT.MESSAGE_ROAP) { const meeting = this.getMeetingByType(CORRELATION_ID, data.correlationId); if (meeting) { meeting.roap.roapEvent(data); } else { console.log('no meeting associated to roap event'); // This should never happen } } }); } /** * listens for internal events and triggers correct top level function * @returns {undefined} */ listenInternal() { Events.on(EVENTS.DESTROY_MEETING_DECLINE_1_1, (payload) => { this.destroy(payload.meeting, payload.response, payload.type); }); } /** * @returns {undefined} * @memberof Meetings */ onReady() { this.spark.once(READY, () => { if (this.spark.canAuthorize) { this.listenForEvents(); this.listenInternal(); this.trigger(EVENT_TRIGGERS.MEETINGS_READY); } }); } getReachability() { this.reachability = new Reachability({}, {parent: this.spark}); } /** * gets the personal meeting room instance, for saved PMR values for this user * @returns {PersonalMeetingRoom} */ getPersonalMeetingRoom() { return this.personalMeetingRoom; } /** * gets the locus events instance * @returns {LocusEvents} */ getLocusEvents() { return this.locusEvents; } /** * @param {Meeting} meeting * @param {Object} response * @param {String} type * @returns {Object} */ destroy(meeting, response, type) { MeetingCollection.remove(meeting.id); this.trigger(EVENT_TRIGGERS.MEETING_REMOVED, { meeting, response, type }); return response; } /** * Create a meeting. * @param {string} destination - sipURL, spaceId, phonenumber, meeting link, or locus object} * @param {string} type - the optional specified type, such as locusId * @returns {Promise} A new Meeting. */ create(destination, type = null) { return this.createMeeting(destination, type); } /** * @param {String} destination see create() * @param {String} type see create() * @returns {Meeting} a new meeting instance complete with meeting info and destination */ createMeeting(destination, type = null) { const meeting = new Meeting( { userId: this.spark.internal.device.userId, deviceUrl: this.spark.internal.device.url, roapSeq: 0, locus: type === LOCUS_ID ? destination : null // pass the locus object if present }, { parent: this.spark } ); MeetingCollection.set(meeting); return this.meetingInfo .fetchMeetingInfo(MeetingsUtil.extractDestination(destination, type), type) .then((info) => { meeting.parseMeetingInfo(info); meeting.meetingInfo = info; }) .catch((err) => { console.error(err); }) .then(() => { if (!meeting.sipUri) { meeting.setSipUri(destination); } // TODO: check if we have to move this to parser const meetingAddedType = MeetingsUtil.getMeetingAddedType(type); // We typically shouldn't need to trigger both and event and return a promise. // Is this a special case? We want to make the public API usage as simple as possible. this.trigger(EVENT_TRIGGERS.MEETING_ADDED, { meeting, type: meetingAddedType }); return meeting; }); // Create the meeting calling the necessary service endpoints. // Internally, there are many more destinations: // // - locusID // - meetingURL // - globalMeetingID, e.g, *00*meetingID // - meetingID // - meetingURL // - PSTN // - phone number // // Our job is to determine the appropriate one // and its corresponding service so that developers // need only sipURL or spaceID to get a meeting // and its ID, but have the option to use createWithType() // and specify those types to get meetingInfo } /** * get a specifc meeting given it's type matched to the value, i.e., locus url * @param {String} type * @param {Object} value * @returns {Meeting} * @memberof Meetings */ getMeetingByType(type, value) { return MeetingCollection.getByKey(type, value); } /** * Get all meetings. * @param {object} options * @param {object} options.startDate - get meetings after this start date * @param {object} options.endDate - get meetings before this end date * @returns {Object} All active and scheduled meetings. * @memberof Meetings */ getAll() { // Options may include other parameters to filter this collection // of meetings. return MeetingCollection.getAll({}); } /** * syncs all the meeting from server * @returns {object}returns nothing */ syncMeetings() { return this.request.getActiveMeetings().then((locus) => { if (locus.loci && locus.loci.length > 0) { locus.loci.forEach((locus) => { const meeting = this.getMeetingByType(LOCUS_URL, locus.url); if (meeting) { meeting.locusInfo.onFullLocus(locus); } else { this.create(locus, LOCUS_ID) .then((meeting) => { meeting.locusInfo.initialSetup(locus); }); } }); } }); } /** * Get all active meetings. * @returns {Object} All active meetings. * @memberof Meetings */ static getActiveMeetings() { return MeetingCollection.getAll({active: true}); } /** * Get all scheduled meetings. * @param {object} options * @param {object} options.startDate - get meetings after this start date * @param {object} options.endDate - get meetings before this end date * @returns {Object} All scheduled meetings. * @memberof Meetings */ static getScheduledMeetings() { return MeetingCollection.getAll({scheduled: true}); } }
JavaScript
class Footer extends Component { /** * Handler for when a language option is clicked on * Get data-lan attribute and pass to the outer handler */ handleLanguageChange (e) { this.props.onLanguageChange(e.currentTarget.getAttribute('data-lan')) } render () { const handleLanguageChange = this.handleLanguageChange.bind(this) return ( <footer className='dim sm-text'> <span>{this.props.pageView} {lan('pageView')}</span> <span> <a href='#' data-lan='en' onClick={handleLanguageChange}>English</a> <a href='#' data-lan='zh-cn' onClick={handleLanguageChange}>中文</a> </span> </footer> ) } }
JavaScript
class DebtInstrumentNotationScreenerValueRangesGetDataRating { /** * Constructs a new <code>DebtInstrumentNotationScreenerValueRangesGetDataRating</code>. * Parameters related to a rating of a debt instrument. If a rating system is not selected by either specifying it directly (see parameter &#x60;rating.system.ids&#x60;) or by implying it via the minimum rating grade (see parameter &#x60;rating.grade.minimum.ids&#x60;) the result contains no data on ratings. * @alias module:model/DebtInstrumentNotationScreenerValueRangesGetDataRating */ constructor() { DebtInstrumentNotationScreenerValueRangesGetDataRating.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>DebtInstrumentNotationScreenerValueRangesGetDataRating</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/DebtInstrumentNotationScreenerValueRangesGetDataRating} obj Optional instance to populate. * @return {module:model/DebtInstrumentNotationScreenerValueRangesGetDataRating} The populated <code>DebtInstrumentNotationScreenerValueRangesGetDataRating</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new DebtInstrumentNotationScreenerValueRangesGetDataRating(); if (data.hasOwnProperty('system')) { obj['system'] = DebtInstrumentNotationScreenerValueRangesGetDataRatingSystem.constructFromObject(data['system']); } if (data.hasOwnProperty('grade')) { obj['grade'] = DebtInstrumentNotationScreenerSearchDataRatingGrade.constructFromObject(data['grade']); } } return obj; } }
JavaScript
class MeowErrorDB extends Error { /** * @param {string} msg Descriptive message of the error */ constructor(msg = "Unknow error") { super(); this.name = "MeowDB"; this.message = msg; } }
JavaScript
class Quiz extends Component { state = { score: 0, currentCard: 0, isAnswer: false, }; // method to handle the submitted answer: handleAnswer = (answer) => { if (answer === "correct") { this.setState((prevState) => ({ ...prevState, currentCard: this.state.currentCard + 1, score: this.state.score + 1, isAnswer: false, })); } else { this.setState((prevState) => ({ ...prevState, currentCard: this.state.currentCard + 1, isAnswer: false, })); } clearLocalNotification().then(setLocalNotification); }; // method to swith between question and answer: handleCardSwitch = (event) => { this.setState({ isAnswer: event }); }; // method for restarting the Quiz: start = () => { this.setState((prevState) => ({ ...prevState, currentCard: 0, score: 0, isAnswer: false, })); }; render() { // get the deck from route params: const { deck } = this.props.route.params; // get the lenght of all decks: const allDecks = deck.questions.length; const { currentCard, score, isAnswer } = this.state; return ( <QuizContainer> {currentCard === allDecks ? ( <QuizCard> <Card.Cover source={cardPicture} /> <Content> <Title>Your Score</Title> <Text>{`${ (score / allDecks) * 100 }% of your answers were correct.`}</Text> <Content> <Button onPress={this.start}>Restart Quiz</Button> </Content> </Content> </QuizCard> ) : ( <QuizCard> <Card.Cover source={cardPicture} /> <Content> {isAnswer === false ? ( <View> <Title variant="caption"> {deck.questions[currentCard].question} </Title> <Button onPress={() => this.handleCardSwitch(true)}> Answer </Button> </View> ) : ( <View> <Title variant="caption"> {deck.questions[currentCard].answer} </Title> <Button onPress={() => this.handleCardSwitch(false)}> Question </Button> </View> )} <Button onPress={this.start}>Restart Quiz</Button> <StyledButton mode="contained" color={green} onPress={() => this.handleAnswer("correct")} > Correct </StyledButton> <StyledButton mode="contained" color={red} onPress={() => this.handleAnswer("incorrect")} > Incorrect </StyledButton> </Content> </QuizCard> )} </QuizContainer> ); } }
JavaScript
class Observable { constructor(subscribe) { this._subscribe = subscribe; } subscribe(observer) { return this._subscribe(observer); } // hot observable, because the underline data source is hot. DOM event is infinite data source. static fromEvent(dom, eventName) { return new Observable(function subscribe(observer) { // can not create handler inside event listener because "this" changes const handler = (ev) => { observer.next(ev); } const handler = dom.addEventListener(eventName, handler) return { unsubscribe(){ dom.removeEventListener(handler); } } }) } }
JavaScript
class Collect extends PassThrough { constructor(options) { super(options); addToStream(this); this._collected = null; } collect() { if (!this._collected) { this._collected = new Promise((resolve, reject) => { this.on('collect', resolve); this.on('error', reject); }); } return this._collected; } /** @depreacted */ then(resolve, reject) { return this.collect().then(resolve, reject); } /** @depreacted */ catch(reject) { return this.collect().then(null, reject); } }
JavaScript
class CollectObjects extends Collect { constructor(options = {}) { options.objectMode = true; super(options); } }
JavaScript
class Index extends Controller { /** * Constructor * @returns {Object} */ constructor(bot) { super(bot); // define routes return { index: { method: 'get', uri: '/', handler: this.index.bind(this), }, commands: { method: 'get', uri: '/commands', handler: this.commands.bind(this), }, discord: { method: 'get', uri: '/discord', handler: (_, req, res) => res.redirect(config.invite), }, invite: { method: 'get', uri: '/invite', handler: (_, req, res) => res.redirect(`https://discordapp.com/oauth2/authorize?client_id=${config.client.id}&scope=bot%20identify%20guilds&response_type=code&redirect_uri=https://www.dynobot.net/return&permissions=${config.defaultPermissions}`), }, donate: { method: 'get', uri: '/donate', handler: (_, req, res) => res.redirect(`https://www.patreon.com/dyno`), }, stats: { method: 'get', uri: '/stats', handler: (_, req, res) => res.redirect('https://p.datadoghq.com/sb/6ac51d7ba-f48fd68210'), }, faq: { method: 'get', uri: '/faq', handler: (_, req, res) => res.render('faq'), }, upgrade: { method: 'get', uri: '/upgrade', handler: (_, req, res) => res.redirect('https://www.patreon.com/bePatron?c=543081&rid=1233178'), }, ping: { method: 'get', uri: '/ping', handler: (_, req, res) => res.send('OK'), }, terms: { method: 'get', uri: '/terms', handler: (_, req, res) => res.render('terms'), }, privacy: { method: 'get', uri: '/privacy', handler: (_, req, res) => res.render('privacy'), }, }; } /** * Index handler * @param {Bot} bot Bot instance * @param {Object} req Express request * @param {Object} res Express response */ index(bot, req, res) { if (req.query && req.query.code) { const tokenUrl = 'https://discordapp.com/api/oauth2/token'; return superagent .post(tokenUrl) .set('Content-Type', 'application/x-www-form-urlencoded') .set('Accept', 'application/json') .send({ grant_type: 'authorization_code', code: req.query.code, redirect_uri: `https://www.carbonitex.net/discord/data/botoauth.php`, client_id: config.client.id, client_secret: config.client.secret, }) .end((err, r) => { if (err) { logger.error(err); return res.redirect('/'); } if (r.body && r.body.access_token) { req.session.auth = r.body; } if (req.query.guild_id) { return res.redirect(`/server/${req.query.guild_id}`); } if (req.get('Referer')) { const guildMatch = new RegExp('guild_id=([0-9]+)&').exec(req.get('Referer')); if (guildMatch && guildMatch.length > 1) { return res.redirect(`/server/${guildMatch[1]}`); } } return res.redirect('/'); }); } const timeout = setTimeout(() => res.render('index'), 1000); res.locals.title = 'Dyno Discord Bot - Home'; res.locals.t = moment().format('YYYYMMDDHHmm'); redis.hgetallAsync(`dyno:guilds:${config.client.id}`).then(data => { let guildCount = Object.values(data).reduce((a, b) => a += parseInt(b), 0); res.locals.guildCount = accounting.formatNumber(guildCount); clearTimeout(timeout); return res.render('index'); }); } commands(bot, req, res) { let commands = config.commands; // filter commands that shouldn't be shown commands = commands.filter(o => (!o.hideFromHelp && !o.disabled) && o.permissions !== 'admin'); // remove duplicates commands = [...new Set(commands)]; // index by group commands = commands.reduce((i, o) => { i[o.group || o.module] = i[o.group || o.module] || []; i[o.group || o.module].push(o); return i; }, {}); let commandGroups = []; for (let key in commands) { commandGroups.push({ name: key, commands: commands[key], }); } commandGroups[0].isActive = true; res.locals.title = 'Dyno Discord Bot - Commands'; res.locals.commands = commandGroups; return res.render('commands'); } }
JavaScript
class BabylonUI { static changeMyHealthBar(health, maxHealth) { if (!match.healthBar) { return } let potentialWidth = 8 * 80 let actualWidth = health / maxHealth * potentialWidth let di = potentialWidth - actualWidth match.healthBar.width = actualWidth + "px" match.healthBar.left = 0 - (di / 2) } static setHealth(t) { if (match.tag === t.tag) { BabylonUI.changeMyHealthBar(t.health, t.maxHealth) } const rect1 = match.getHealthBarByTag(t.tag) if (rect1) { BabylonUI.setHealthRectangle(rect1, t.health, t.maxHealth) } } static setHealthRectangle(rect1, health, totalHealth) { rect1.width = health / totalHealth * 0.2 if (match.miniMapOn !== rect1.isVisible) { rect1.isVisible = match.miniMapOn } } static displayScores() { baby.textScores.forEach(ro => { ro.dispose() }) match.scores.forEach((row, i) => { BabylonUI.createRightText(i, row.key, row.value) }) } static scoreboard(obj) { Object.keys(obj.tags) .forEach(key => BabylonUtils.createSphereIfNotExists(obj.tags[key], key)) match.scores = [] Object.keys(obj.scores) .forEach(key => match.scores.push( { key: key, value: obj.scores[key] } )) match.scores.sort((a, b) => a.value - b.value) BabylonUI.displayScores() } static createGui() { baby.advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI") baby.panelScores = new BABYLON.GUI.StackPanel() baby.panelScores.width = "220px" baby.panelScores.height = "200px" baby.panelScores.fontSize = "14px" baby.panelScores.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT baby.panelScores.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER baby.advancedTexture.addControl(baby.panelScores) } static createTopPowerBar() { let powerBack = new BABYLON.GUI.Rectangle(); let w = 10 * 80 + 10 powerBack.width = w + "px" powerBack.height = "95px" powerBack.cornerRadius = 20 powerBack.color = "Black" powerBack.thickness = 4 powerBack.background = "Black" powerBack.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER powerBack.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP baby.advancedTexture.addControl(powerBack) passiveIconInfo .filter(p => p.usable) .forEach(p => { BabylonUI.createTopPowerBarItem(p.key, p.ico) PowerCooldownBar.set( (p.key), new PowerCooldownBar(BabylonUI.createPowerBarCooldownTile(p.id - 1, BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP), p.cooldown) ) }) } static createBotPowerBar() { let powerBack = new BABYLON.GUI.Rectangle(); let w = 10 * 80 + 10 powerBack.width = w + "px" powerBack.height = "95px" powerBack.cornerRadius = 20 powerBack.color = "White" powerBack.thickness = 4 powerBack.background = "Black" powerBack.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER powerBack.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM baby.advancedTexture.addControl(powerBack) powerIconInfo .filter(p => p.usable) .forEach(p => { BabylonUI.createBotPowerBarItem(p.powerNumber - 1, p.ico, p.key) PowerCooldownBar.set( (p.powerNumber).toString(), new PowerCooldownBar(BabylonUI.createPowerBarCooldownTile(p.powerNumber - 1, BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM), p.cooldown) ) }) } static createPowerBarCooldownTile(n, vAlign) { let image = new BABYLON.GUI.Image("cooldownTile" + n, TEXTURES_DIR + "ico-blank.jpg") image.height = "75px" image.width = "75px" image.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER image.verticalAlignment = vAlign //Left position let x = (75 + 5) * +n //Defaul space for a tile x = x - ((75 + 5) * (10 / 2 - 0.5)) //Center in middle image.left = x + "px" image.top = "-10px" baby.advancedTexture.addControl(image) return image } static createBotPowerBarItem(n, fileImage, key, level = 1) { let image = new BABYLON.GUI.Image("powerBot" + n, fileImage) image.height = "75px" image.width = "75px" image.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER image.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM //Left position let x = (75 + 5) * +n //Defaul space for a tile x = x - ((75 + 5) * (10 / 2 - 0.5)) //Center in middle image.left = x + "px" image.top = "-10px" baby.advancedTexture.addControl(image) const text1 = new BABYLON.GUI.TextBlock("textblock" + n) text1.text = key text1.color = "white" text1.fontSize = 24 text1.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER text1.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM text1.left = (x - 75 / 2 + 7) + "px" text1.top = "-10px" baby.advancedTexture.addControl(text1) const text2 = new BABYLON.GUI.TextBlock("textblockLevel" + n) text2.text = (+level).toString() text2.color = "white" text2.fontSize = 24 text2.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER text2.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM text2.left = (x - 75 / 2 + 7) + "px" text2.top = "-58px" baby.advancedTexture.addControl(text2) baby.levelLabels.set(key, text2) } static createTopPowerBarItem(n, fileImage) { let image = new BABYLON.GUI.Image("powerBot" + n, fileImage) image.height = "75px" image.width = "75px" image.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER image.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP //Left position let x = (75 + 5) * +n //Defaul space for a tile x = x - ((75 + 5) * (10 / 2 - 0.5)) //Center in middle image.left = x + "px" image.top = "-10px" baby.advancedTexture.addControl(image) var text1 = new BABYLON.GUI.TextBlock("textblock" + n) text1.text = n text1.color = "black" text1.fontSize = 24 text1.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER text1.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP text1.left = (x - 75 / 2 + 7) + "px" text1.top = "-10px" baby.advancedTexture.addControl(text1) } static createOwnHealthBar() { let w = 8 * 80 let healthBarRed = new BABYLON.GUI.Rectangle(); healthBarRed.width = w + "px" healthBarRed.height = "10px" healthBarRed.top = "-95px" healthBarRed.cornerRadius = 20 healthBarRed.color = "Red" healthBarRed.thickness = 1 healthBarRed.background = "Red" healthBarRed.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER healthBarRed.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM baby.advancedTexture.addControl(healthBarRed) let healthBarGreen = new BABYLON.GUI.Rectangle(); healthBarGreen.width = (w) + "px" healthBarGreen.height = "10px" healthBarGreen.top = "-95px" healthBarGreen.cornerRadius = 20 healthBarGreen.color = "Green" healthBarGreen.thickness = 1 healthBarGreen.background = "Green" healthBarGreen.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER healthBarGreen.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM baby.advancedTexture.addControl(healthBarGreen) match.healthBar = healthBarGreen } static createRightText(num, name, score) { const current = BABYLON.GUI.Button.CreateSimpleButton("but" + BabylonUtils.getCounter(), name + ": " + score) current.width = 1 current.height = "50px" current.color = "white" current.background = "black" baby.panelScores.addControl(current) baby.textScores.push(current) } static createRadar(obj) { BabylonUI.stopRadar() obj.things.forEach(thing => BabylonUI.createTinyBlockFromThing(thing)) } static createTinyBlockFromThing(thing) { if (thing.tag === match.tag) { BabylonUI.createTinyBlock(thing.point.x, thing.point.z, "blue") } else { BabylonUI.createTinyBlock(thing.point.x, thing.point.z, "red") } } static createTinyBlock(x, y, color) { const tinyBlock = new BABYLON.GUI.Rectangle(); tinyBlock.width = BLOCK_SIZE + "px" tinyBlock.height = BLOCK_SIZE + "px" tinyBlock.color = color tinyBlock.left = (BLOCK_SIZE * x) + "px" tinyBlock.top = (BLOCK_SIZE * y) + "px" tinyBlock.background = color tinyBlock.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER tinyBlock.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER baby.advancedTexture.addControl(tinyBlock) baby.radar.push(tinyBlock) } static stopRadar() { baby.radar.forEach(item => item.dispose()) baby.radar = [] } static setPowerLabelLevel(key, level) { const textLabel = baby.levelLabels.get(key) textLabel.text = (+level).toString() } }
JavaScript
class Cube extends ThreeJsObject { constructor(params) { super(params); } /** * Create the object and all necesary elements to render it. * @returns */ create() { const { size = 1, x = 0, y = 0, z = 0, color = 0xff0000 } = this.params; this.color = color; this.scale = 1; this.material = new this.THREE.MeshBasicMaterial({ color }); this.geometry = new this.THREE.BoxGeometry(size, size, size); this.mesh = new this.THREE.Mesh(this.geometry, this.material); this.mesh.position.z = z; this.mesh.position.y = y; this.mesh.position.x = x; return this.mesh; } /** * This method will be executed in the loop * @param {*} elapsedTime */ update(elapsedTime) { this.mesh.rotation.y = (elapsedTime / 5) * Math.PI * 2; } /** * This method will be executed when the mouse is intersecting the object */ onIntersect() { this.material.color.set(new this.THREE.Color()); } /** * This method is intersecting when the mouse is no longer intersenction the object */ offIntersect() { this.material.color.set(this.color); } /** * This are the properties to debug with dat.gui * @returns */ getDebugProperties() { return [ { baseObj: this.mesh.position, property: 'y', min: -2, max: 2, step: 0.001, name: 'Height' }, { baseObj: this, property: 'scale', min: 0, max: 3, step: 0.001, callback: (value) => { this.mesh.scale.set(value, value, value); } }, { baseObj: this.material, property: 'wireframe' }, { baseObj: this, property: 'color', isColor: true, callback: (value) => { this.material.color.set(value); } } ]; } }
JavaScript
class VigenereCipheringMachine { a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; constructor(direction = true) { this.direction = direction; } encrypt(message, key) { if (typeof message == "undefined" || typeof key == "undefined") { throw Error("Incorrect arguments!"); } message = message.toUpperCase(); key = key.toUpperCase(); var encrResult = this.Vizhener(message, key, "encrypt"); if (!this.direction) { return encrResult.split("").reverse().join(""); } return (encrResult); } decrypt(message, key) { if (typeof message == "undefined" || typeof key == "undefined") { throw Error("Incorrect arguments!"); } message = message.toUpperCase(); key = key.toUpperCase(); var decrResult = this.Vizhener(message, key, "decrypt"); if (!this.direction) { return decrResult.split("").reverse().join(""); } return (decrResult); } Vizhener(m, k, mode) { var a = this.a; var r = ''; //Пустой результат var c; var j = 0; for (let i = 0; i < m.length; i++) { //encrypt/decrypt //Vizhener - encrypt/decrypt one forumula (encrypt - by default; decrypt - when (mode === 'decrypt') ) var mi = a.indexOf(m[((i >= m.length) ? i % m.length : i)]); //подгон сообщения/шифротекста - к ключу (если меньше) if (mi == -1) { r += m[i]; continue; } var ki_s = k[((j >= k.length) ? j % k.length : j)]; //подгон ключа к сообщению/шифротексту (если короткий) var ki = (typeof mode !== 'undefined' && mode.indexOf('gronsfeld') !== -1) ? parseInt(ki_s) : a.indexOf(ki_s); //вычитание при дешифровании, либо сложение. ki = ((typeof mode !== 'undefined' && mode.indexOf('decrypt') !== -1) ? (-ki) : ki); c = a[(((a.length + (mi + ki)) % a.length))]; //символ по таблице Виженера. c = (mode === 'shifted_atbash') ? a[a.length - 1 - a.indexOf(c)] : c; //Атбаш символа или символ. r += c; //Добавить символ к результату. j++; } return r; //вернуть строку результата } }
JavaScript
class Panel extends ConcreteCell { constructor(props, ...args){ super(props, ...args); // Bind Cell methods this.getClasses = this.getClasses.bind(this); } build(){ return h('div', { id: this.getElementId(), "data-cell-id": this.identity, "data-cell-type": "Panel", class: this.getClasses() }, [this.renderChildNamed('content')]); } _computeFillSpacePreferences() { return this.namedChildren['content'].getFillSpacePreferences(); } allotedSpaceIsInfinite(child) { return this.parent.allotedSpaceIsInfinite(this); } getClasses(){ let res = 'cell allow-child-to-fill-space cell-panel'; if (this.props.applyBorder) { return res + " cell-panel-border"; } else { return res; } } }
JavaScript
class Pill extends GameObject { constructor(ctx, x, y, type) { let rnd = utils.randomInt(0, 0); super(ctx, x, y, preloadImages[type].img); // super(ctx, x, y, img) this.type = type; } reset(x, y) { var rnd = utils.randomInt(0, 0); super.reset(x, y, preloadImages[Block.data[rnd].type].img); this.type = Block.data[rnd].type; } static get data() { return [ { type: 'pill0', } ]; } }
JavaScript
class MapEventManager { constructor(_ngZone) { this._ngZone = _ngZone; /** Pending listeners that were added before the target was set. */ this._pending = []; this._listeners = []; } /** Clears all currently-registered event listeners. */ _clearListeners() { for (let listener of this._listeners) { listener.remove(); } this._listeners = []; } /** Gets an observable that adds an event listener to the map when a consumer subscribes to it. */ getLazyEmitter(name) { const observable = new Observable(observer => { // If the target hasn't been initialized yet, cache the observer so it can be added later. if (!this._target) { this._pending.push({ observable, observer }); return undefined; } const listener = this._target.addListener(name, (event) => { this._ngZone.run(() => observer.next(event)); }); this._listeners.push(listener); return () => listener.remove(); }); return observable; } /** Sets the current target that the manager should bind events to. */ setTarget(target) { if (target === this._target) { return; } // Clear the listeners from the pre-existing target. if (this._target) { this._clearListeners(); this._pending = []; } this._target = target; // Add the listeners that were bound before the map was initialized. this._pending.forEach(subscriber => subscriber.observable.subscribe(subscriber.observer)); this._pending = []; } /** Destroys the manager and clears the event listeners. */ destroy() { this._clearListeners(); this._pending = []; this._target = undefined; } }
JavaScript
class nemUtils { /** * Initialize services and properties * * @param {service} Wallet - The Wallet service * @param {service} $http - The angular $http service * @param {service} DataBridge - The DataBridge service * @param {service} NetworkRequests - The NetworkRequests service */ constructor($q, $http, $filter, $timeout, Wallet, WalletBuilder, DataBridge, NetworkRequests, Alert, Transactions) { 'ngInject'; /*** * Declare services */ this._$q = $q; this._$http = $http; this._$timeout = $timeout; this._$filter = $filter; this._Wallet = Wallet; this._WalletBuilder = WalletBuilder; this._DataBridge = DataBridge; this._NetworkRequests = NetworkRequests; this._Alert = Alert; this._Transactions = Transactions; this.disableSuccessAlert = false; } disableSuccessAlerts() { this.disableSuccessAlert = true; } enableSuccessAlerts() { this.disableSuccessAlert = false; } /** * getFirstMessagesWithString(address,str,start) Obtains the last Message that contains string after position start * * @param {string} address - NEM Address to explore * @param {string} str - String to find on addresses txs * @param {object} options - Dictionary that can contain: * options.fromAddress (only return transactions) * options.start (starting character of the string to look into) * * @return {promise} - A promise of the NetworkRequests service that returns a string with the filtered message */ getFirstMessageWithString(address, str, options) { // Get ALL Transactions since the API only allows us to iterate on a descending order return this.getTransactionsWithString(address, str, options).then((result) => { let message; if (result && result.length > 0) { // Get the first message ever message = result[result.length - 1].transaction.message; } return message; }); } /** * getTransactionsWithString(address, str, start) Obtains every transaction message that contains a certain string (starting from position start) * * @param {string} address - NEM Address to explore * @param {string} str - String to find on addresses txs * @param {object} options - Dictionary that can contain: * options.fromAddress (only return transactions) * options.start (starting character of the string to look into) * options.limit - Limit amount of results to return * options.block - Return only transactions made until this block * * @return {promise} - A promise of the NetworkRequests service that returns an Array with the filtered messages */ getTransactionsWithString(address, str, options) { var trans = []; // Options is optional if (!options || options.constructor != Object) options = {}; if (!options.start) options.start = 0; // Recursive promise that will obtain every transaction from/to <address>, order it chronologically and return the ones // whose message contains <str>. var getTx = (function(txID) { // Obtain all transactions to/from the address return this._NetworkRequests.getAllTransactionsFromID(helpers.getHostname(this._Wallet.node), address, txID).then((result) => { var transactions = result.data; // If there transactions were returned and the limit was not reached if (transactions.length > 0 && (!options.limit || trans.length < options.limit)) { // IDs are ordered, we grab the latest var last_id = transactions[transactions.length - 1].meta.id; // Order transactions chronologically transactions.sort(function(a, b) { return b.meta.height - a.meta.height; }); // Iterate every transaction and add the valid ones to the array for (var i = 0; transactions.length > i && (!options.limit || trans.length < options.limit); i++) { let transaction = transactions[i].transaction; let meta = transactions[i].meta; // Multisig transactions if (transaction.type == 4100) { transaction = transaction.otherTrans; } // Regular transactions (multisig otherTrans is of type 257) if (transaction.type == 257) { // On this version we are only using decoded messages! let msg = this._$filter('fmtHexMessage')(transaction.message); // Check if transaction should be added depending on the message and its signer if (msg.includes(str, options.start) && (!options.fromAddress || Address.toAddress(transaction.signer, this._Wallet.network) == options.fromAddress)) { // We decode the message and store it transaction.message = msg; transactions[i].transaction = transaction; trans[trans.length] = transactions[i]; } } } // Keep searching for more transactions after last_id return getTx(last_id); } else { return trans; } }); }).bind(this); return getTx(); } /** * processTxData(transferData) Processes transferData * * @param {object} tx - The transaction data * * @return {promise} - An announce transaction promise of the NetworkRequests service */ processTxData(transferData) { // return if no value or address length < to min address length if (!transferData || !transferData.recipient || transferData.recipient.length < 40) { return; } // Clean address let recipientAddress = transferData.recipient.toUpperCase().replace(/-/g, ''); // Check if address is from the same network if (Address.isFromNetwork(recipientAddress, this._Wallet.network)) { // Get recipient account data from network return this._NetworkRequests.getAccountData(helpers.getHostname(this._Wallet.node), recipientAddress).then((data) => { // Store recipient public key (needed to encrypt messages) transferData.recipientPubKey = data.account.publicKey; // Set the address to send to transferData.recipient = recipientAddress; }, (err) => { this._Alert.getAccountDataError(err.data.message); return; }); } else { // Error this._Alert.invalidAddressForNetwork(recipientAddress, this._Wallet.network); // Reset recipient data throw "invalidAddressForNetwork"; } } /** * send(entity) Sends a transaction to the network based on an entity * * @param {object} entity - The prepared transaction object * @param {object} common - A password/privateKey object * * @return {promise} - An announce transaction promise of the NetworkRequests service */ send(entity, common) { if (!common.privateKey) { this._Alert.invalidPassword(); throw "privateKey is empty"; } // Construct transaction byte array, sign and broadcast it to the network return this._Transactions.serializeAndAnnounceTransaction(entity, common).then((result) => { // Check status if (result.status === 200) { // If code >= 2, it's an error if (result.data.code >= 2) { this._Alert.transactionError(result.data.message); throw(result.data.message); } else { if (this.disableSuccessAlert == false) { this._Alert.transactionSuccess(); } } } }, (err) => { this._Alert.transactionError('Failed ' + err.data.error + " " + err.data.message); throw(err); }); } /** * sendMessage(recipientAccount, message, common) Sends a minimal transaction containing a message to poin * * @param {object} receiver - Transaction receiver's account * @param {string} message - Message to be sent * @param {object} common - password/privateKey object * * @return {promise} - An announce transaction promise of the NetworkRequests service */ sendMessage(receiver, message, common, amount) { if (!amount) amount = 0; var transferData = {}; // Check that the receiver is a valid account and process it's public key transferData.recipient = receiver; this.processTxData(transferData); // transferData.receiverPubKey is set now transferData.amount = amount; transferData.message = message; transferData.encryptMessage = false; // Maybe better to encrypt? transferData.isMultisig = false; transferData.isMosaicTransfer = false; // Build the entity to be sent let entity = this._Transactions.prepareTransfer(common, transferData, this.mosaicsMetaData); return this.send(entity, common); } /** * createNewAccount() creates a new account using a random seed */ createNewAccount() { var deferred = this._$q.defer(); var promise = deferred.promise; var rk = CryptoHelpers.randomKey(); var seed = this._Wallet.currentAccount.address + " is creating an account from " + rk; // console.log("creating a HDW from "+seed); // Create the brain wallet from the seed this._WalletBuilder.createBrainWallet(seed, seed, this._Wallet.network).then((wallet) => { this._$timeout(() => { if (wallet) { var mainAccount = {}; mainAccount.address = wallet.accounts[0].address; mainAccount.password = seed; mainAccount.privateKey = ""; // Decrypt/generate private key and check it. Returned private key is contained into mainAccount if (!CryptoHelpers.passwordToPrivatekeyClear(mainAccount, wallet.accounts[0], wallet.accounts[0].algo, false)) { this._Alert.invalidPassword(); deferred.reject(false); } mainAccount.publicKey = KeyPair.create(mainAccount.privateKey).publicKey.toString(); deferred.resolve(mainAccount); } }, 10); }, (err) => { this._Alert.createWalletFailed(err); deferred.reject(false); console.log(err); }); return deferred.promise; } /** * ownsMosaic(address,namespace, mosaic) Checks if address owns any mosaics from namespace:mosaic * * @param {string} address - NEM Address to check for the mosaic * @param {string} namespaceId - Mosaic's namespace name * @param {string} mosaic - Mosaic's name * * @return {promise} - A promise of the NetworkRequests service that returns wether if address owns any mosaics from namespace:mosaic or not */ ownsMosaic(address, namespace, mosaic) { var deferred = this._$q.defer(); var promise = deferred.promise; this._NetworkRequests.getMosaicsDefinitions(helpers.getHostname(this._Wallet.node), address).then((result) => { let owns = false; if (result.data.length) { for (let i = 0; i < result.data.length; ++i) { let rNamespace = result.data[i].id.namespaceId; let rMosaic = result.data[i].id.name; if (namespace == rNamespace && mosaic == rMosaic) { owns = true; } } } deferred.resolve(owns); }, (err) => { if (err.status === -1) { this._Alert.connectionError(); } else { this._Alert.errorGetMosaicsDefintions(err.data.message); } }); return deferred.promise; } /** * isValidAddress(address) checks if address is a valid address in the current network * * @param {string} address - NEM Address to check * * @return {boolean} - Returns wether the address is valid in the current network or not */ isValidAddress(address) { let addr = address.toUpperCase().replace(/-/g, ''); return (Address.isValid(addr) && Address.isFromNetwork(addr, this._Wallet.network)); } /** * getImportance(address) gets the importance score of an account * * @param {string} address - NEM address * @param {integer} block - the block in which to request importance. Optional * * @return {promise} - A promise that returns the account's importance score */ getImportance(address, block) { if (!block || (block < 0)) { return this._NetworkRequests.getAccountData(helpers.getHostname(this._Wallet.node), address).then((data) => { return data.account.importance; }).catch(); } else { let historicalNode = (this._Wallet.network < 0) ? ('104.128.226.60') : ('88.99.192.82'); return this._NetworkRequests.getHistoricalAccountData(historicalNode, address, block).then((data) => { return data.data.data[0].importance; }).catch(); } } /** * getImportances(timestamp) returns an array of importances for an array of addresses * * @param {array} addresses - array with the addresses you want the importance for * @param {integer} block - the block in which to request importances. Optional * * @return {promise} - a promise that returns an array with all the importances */ getImportances(addresses, block) { if (!block || (block < 0)) { return this._NetworkRequests.getBatchAccountData(helpers.getHostname(this._Wallet.node), addresses).then((data) => { return data.map((account)=>{ return account.account.importance; }); }).catch(); } else { let historicalNode = (this._Wallet.network < 0) ? ('104.128.226.60') : ('88.99.192.82'); return this._NetworkRequests.getBatchHistoricalAccountData(historicalNode, addresses, block).then((data) => { return data.map((account)=>{ return account.data[0].importance; }); }).catch(); } } /** * getOwnedMosaics(address) returns the number of a certain mosaic owned by an account * * @param {string} address - NEM address * @param {string} namespace - NEM namespace * @param {string} name - the name of the mosaic * * @return {promise} - A promise that returns the account's number of owned mosaics */ getOwnedMosaics(address, namespace, name) { return this._NetworkRequests.getOwnedMosaics(helpers.getHostname(this._Wallet.node), address).then((data) => { var filtered = data.filter((mosaic) => { return (mosaic.mosaicId.namespaceId === namespace) && (mosaic.mosaicId.name === name); }); return (filtered.length < 1) ? (0) : (filtered[0].quantity); }).catch(); } /** * getCurrentHeight(address) returns the current blockchain height * * @return {promise} - A promise that returns the blockchain's height */ getCurrentHeight() { return this._NetworkRequests.getHeight(helpers.getHostname(this._Wallet.node)); } /** * getMessageFee(message, amount) returns the fee that a message would cost * * @param {string} message - message to be sent * @param {integer} amount - xm amount to be sent * * @return {integer} - An integer value that represents the fee in xem */ getMessageFee(message, amount) { if (!amount) amount = 0; var common = { "password": "", "privateKey": "" }; var formData = {}; formData.rawRecipient = ''; formData.recipient = ''; formData.recipientPubKey = ''; formData.message = message; //var rawAmount = amount; formData.fee = 0; formData.encryptMessage = false; // Multisig data formData.innerFee = 0; formData.isMultisig = false; formData.multisigAccount = ''; // Mosaics data var counter = 1; formData.mosaics = null; var mosaicsMetaData = this._DataBridge.mosaicDefinitionMetaDataPair; formData.isMosaicTransfer = false; formData.amount = helpers.cleanAmount(amount); let entity = this._Transactions.prepareTransfer(common, formData, mosaicsMetaData); formData.innerFee = 0; formData.fee = entity.fee; return formData.fee; } /** * getMessageLength(message) returns the real length in bytes for a string * * @param {string} message - message to be sent * * @return {integer} - An integer value that represents the byte length */ getMessageLength(message) { var common = { "password": "", "privateKey": "" }; var formData = {}; formData.rawRecipient = ''; formData.recipient = ''; formData.recipientPubKey = ''; formData.message = message; //var rawAmount = amount; formData.fee = 0; formData.encryptMessage = false; // Multisig data formData.innerFee = 0; formData.isMultisig = false; formData.multisigAccount = ''; // Mosaics data var counter = 1; formData.mosaics = null; var mosaicsMetaData = this._DataBridge.mosaicDefinitionMetaDataPair; formData.isMosaicTransfer = false; formData.amount = helpers.cleanAmount(0); let entity = this._Transactions.prepareTransfer(common, formData, mosaicsMetaData); return entity.message.payload.length/2; } /** * getMultisigTransaction(transaction) returns the inner transaction from a multisig transaction * * @param {object} transaction - the transaction object * * @return {object} - the inner transaction if it is multisig */ getMultisigTransaction(transaction){ if(transaction.transaction.type === 4100){ transaction.transaction = transaction.transaction.otherTrans; return transaction; } else{ return transaction; } } /** * existsTransaction(address1, address2) returns wether address 1 has ever sent a transaction to address2 * * @param {string} address1 - sender address * @param {string} address2 - receiver address * * @return {number} - a promise that returns: * 0 if the transaction doesn't exist * 1 if the transaction exists but is unconfirmed * 2 if the transaction exists and is confirmed */ existsTransaction(address1, address2) { var options = { fromAddress: address1, limit: 1 } return this.getTransactionsWithString(address2, '', options).then((data) => { if (data.length !== 0) { return 2; } else { return this._NetworkRequests.getUnconfirmedTxes(helpers.getHostname(this._Wallet.node), address1).then((resp) => { let transactions = resp.data.map((transaction)=>{ return this.getMultisigTransaction(transaction); }); for (var i = 0; i < transactions.length; i++) { if ((transactions[i].transaction.recipient === address2) && (Address.toAddress(transactions[i].transaction.signer, this._Wallet.network) === address1)) { return 1; } } return 0; }).catch(); } }); } /** * getHeightByTimestamp(timestamp) returns the last harvested block at the time of the timestamp * * @param {integer} timestamp - javascript timestamp * * @return {promise} - a promise that returns the block height */ getHeightByTimestamp(timestamp) { //1.Approximate (60s average block time) let nemTimestamp = helpers.toNEMTimeStamp(timestamp); let now = helpers.toNEMTimeStamp((new Date()).getTime()); let elapsed = now - nemTimestamp; //get current height and approx from there return this.getCurrentHeight().then((curHeight) => { let height = Math.floor(curHeight - (elapsed / 60)); console.log("block estimation->", height); //2.Find exact block const findBlock = function(height) { return this._NetworkRequests.getBlockByHeight(helpers.getHostname(this._Wallet.node), height).then((block) => { let x = Math.floor((nemTimestamp - block.data.timeStamp) / 60); if (x < 0 && x > -10) x = -1; if (x >= 0 && x <= 10) x = 1; if (block.data.timeStamp <= nemTimestamp) { return this._NetworkRequests.getBlockByHeight(helpers.getHostname(this._Wallet.node), height + 1).then((nextBlock) => { //check if target if (nextBlock.data.timeStamp > nemTimestamp) { console.log("found", height); return height; } else { console.log("go up", height, "+", x); return findBlock(height + x); } }); } else { console.log("go down", height, x); return findBlock(height + x); } }); }.bind(this); return findBlock(height); }); } }
JavaScript
class GameObject{ constructor(game){ this.game = game; this.childrens = []; this.components = []; this.parent = null; this.collider = null; this.tag = ""; } draw(ctx){ if(this.Renderer) this.Renderer.draw(ctx); for (let child of this.childrens){ child.draw(ctx); } } update(){ for (let child of this.childrens){ child.update(); } for (let comp of this.components){ comp.update(); } } AddChild(child){ child.Parent = this; this.childrens.push(child); } AddComponent(child){ child.Parent = this; this.components.push(child); } GetComponent(component, prop){ for (let i=0; i < this.components.length;i++) { if(this.components[i].constructor.name == component) return this.components[i][prop]; } } UpdateComponent(component, prop, value){ for (let i=0; i < this.components.length;i++) { if(this.components[i].constructor.name == component) this.components[i][prop] = value; } } set Parent(obj){ this.parent = obj; } get Parent(){ return this.parent; } set Collider(collider){ collider.parent = this; this.collider = collider; } get Collider(){ return this.collider; } set Transform(transform){ this.transform = transform; } get Transform(){ return this.transform; } set Renderer(render){ this.renderer = render; this.renderer.Parent = this; } get Renderer(){ return this.renderer; } set Tag(tag){ this.tag = tag; } get Tag(){ return this.tag; } }
JavaScript
class SwitchValue extends AdjustFunction { /** * Constructor */ constructor() { super(); this.setInput("input", SourceData.create("prop", "input")); this.setInput("options", SourceData.create("prop", "options")); this.setInput("defaultKey", null); this.setInput("defaultValue", null); this.setInput("outputName", "output"); } /** * Function that removes the used props * * @param aProps Object The props object that should be adjusted */ removeUsedProps(aProps) { //METODO: change this to actual source cleanup delete aProps["input"]; delete aProps["options"]; } /** * Switches the value * * @param aData * The data to adjust * @param aManipulationObject WprrBaseObject The manipulation object that is performing the adjustment. Used to resolve sourcing. * * @return * The modified data */ adjust(aData, aManipulationObject) { //console.log("wprr/manipulation/adjustfunctions/logic/SwitchValue::adjust"); let input = this.getInput("input", aData, aManipulationObject); let options = this.getInput("options", aData, aManipulationObject); let outputName = this.getInput("outputName", aData, aManipulationObject); let defaultKey = this.getInput("defaultKey", aData, aManipulationObject); this.removeUsedProps(aData); let defaultOption = null; let returnValue = null; let currentArray = options; let currentArrayLength = currentArray.length; for(let i = 0; i < currentArrayLength; i++) { let currentOption = currentArray[i]; if(currentOption.key === input) { returnValue = currentOption.value; } if(currentOption.key === defaultKey) { defaultOption = currentOption.value; } } if(!returnValue && defaultOption) { returnValue = defaultOption; } if(!returnValue) { returnValue = this.getInput("defaultValue", aData, aManipulationObject); } aData[outputName] = returnValue; return aData; } /** * Creates a new instance of this class. * * @param aInput SourceData|Array The data to group. * @param aOptions SourceData|Function The options to switch between * @param aOutputName SourceData|String The output name to stroe the data in * * @return SwitchValue The new instance. */ static create(aInput = null, aOptions = null, aOutputName = null) { let newSwitchValue = new SwitchValue(); newSwitchValue.setInputWithoutNull("input", aInput); newSwitchValue.setInputWithoutNull("options", aOptions); newSwitchValue.setInputWithoutNull("outputName", aOutputName); return newSwitchValue; } }
JavaScript
class Auth { constructor({ name = 'default', apiKey, redirectUri, storage = storageApi } = {}) { if (typeof apiKey !== 'string') throw Error('The argument "apiKey" is required'); Object.assign(this, { name, apiKey, storage, redirectUri, listeners: [] }); this.storage.get(this.sKey('User')).then(user => { this.setState(JSON.parse(user), false); if (this.user) this.refreshIdToken() .then(() => this.fetchProfile()) .catch(e => { if (e.message === 'TOKEN_EXPIRED' || e.message === 'INVALID_ID_TOKEN') return this.signOut(); throw e; }); }); // Because this library is used in react native, outside the browser as well, // we need to first check if this environment supports `addEventListener` on the window. 'addEventListener' in window && window.addEventListener('storage', e => { // This code will run if localStorage for this user // data was updated from a different browser window. if (e.key !== this.sKey('User')) return; this.setState(JSON.parse(e.newValue), false); }); } /** * Emits an event and triggers all of the listeners. * @param {string} name The name of the event to trigger. * @param {any} data The data you want to pass to the event listeners. * @private */ emit() { this.listeners.forEach(cb => cb(this.user)); } /** * Set up a function that will be called whenever the user state is changed. * @param {function} cb The function to call when the event is triggered. * @returns {function} function that will unsubscribe your callback from being called. */ listen(cb) { this.listeners.push(cb); // Return a function to unbind the callback. return () => (this.listeners = this.listeners.filter(fn => fn !== cb)); } /** * Generates a unique storage key for this app. * @private */ sKey(key) { return `Auth:${key}:${this.apiKey}:${this.name}`; } /** * Make post request to a specific endpoint, and return the response. * @param {string} endpoint The name of the endpoint. * @param {any} request Body to pass to the request. * @private */ api(endpoint, body) { const url = endpoint === 'token' ? `https://securetoken.googleapis.com/v1/token?key=${this.apiKey}` : `https://identitytoolkit.googleapis.com/v1/accounts:${endpoint}?key=${this.apiKey}`; return fetch(url, { method: 'POST', body: typeof body === 'string' ? body : JSON.stringify(body) }).then(async response => { let data = await response.json(); // If the response returned an error, try to get a Firebase error code/message. // Sometimes the error codes are joined with an explanation, we don't need that(its a bug). // So we remove the unnecessary part. if (!response.ok) { const code = data.error.message.replace(/: [\w ,.'"()]+$/, ''); throw Error(code); } // Add a hidden date property to the returned object. // Used mostly to calculate the expiration date for tokens. Object.defineProperty(data, 'expiresAt', { value: Date.parse(response.headers.get('date')) + 3600 * 1000 }); return data; }); } /** * Makes sure the user is logged in and has up-to-date credentials. * @throws Will throw if the user is not logged in. * @private */ async enforceAuth() { if (!this.user) throw Error('The user must be logged-in to use this method.'); return this.refreshIdToken(); // Won't do anything if the token is valid. } /** * Updates the user data in the localStorage. * @param {Object} userData the new user data. * @param {boolean} [updateStorage = true] Whether to update local storage or not. * @private */ async setState(userData, persist = true, emit = true) { this.user = userData; persist && (await this.storage[userData ? 'set' : 'remove'](this.sKey('User'), JSON.stringify(userData))); emit && this.emit(); } /** * Sign out the currently signed in user. * Removes all data stored in the storage that's associated with the user. */ signOut() { return this.setState(null); } /** * Refreshes the idToken by using the locally stored refresh token * only if the idToken has expired. * @private */ async refreshIdToken() { // If the idToken didn't expire, return. if (Date.now() < this.user.tokenManager.expiresAt) return; // If a request for a new token was already made, then wait for it and then return. if (this._ref) { return void (await this._ref); } try { // Save the promise so that if this function is called // anywhere else we don't make more than one request. this._ref = this.api('token', { grant_type: 'refresh_token', refresh_token: this.user.tokenManager.refreshToken }).then(data => { const tokenManager = { idToken: data.id_token, refreshToken: data.refresh_token, expiresAt: data.expiresAt }; return this.setState({ ...this.user, tokenManager }, true, false); }); await this._ref; } finally { this._ref = null; } } /** * Uses native fetch, but adds authorization headers otherwise the API is exactly the same as native fetch. * @param {Request|Object|string} resource the resource to send the request to, or an options object. * @param {Object} init an options object. */ async authorizedRequest(resource, init) { const request = resource instanceof Request ? resource : new Request(resource, init); if (this.user) { await this.refreshIdToken(); // Won't do anything if the token didn't expire yet. request.headers.set('Authorization', `Bearer ${this.user.tokenManager.idToken}`); } return fetch(request); } /** * Signs in or signs up a user by exchanging a custom Auth token. * @param {string} token The custom token. */ async signInWithCustomToken(token) { // Try to exchange the Auth Code for an idToken and refreshToken. // And then get the user profile. return await this.fetchProfile( await this.api('signInWithCustomToken', { token, returnSecureToken: true }) ); } /** * Start auth flow of a federated Id provider. * Will redirect the page to the federated login page. * @param {oauthFlowOptions|string} options An options object, or a string with the name of the provider. */ async signInWithProvider(options) { if (!this.redirectUri) throw Error('In order to use an Identity provider you should initiate the "Auth" instance with a "redirectUri".'); // The options can be a string, or an object, so here we make sure we extract the right data in each case. const { provider, oauthScope, context, linkAccount } = typeof options === 'string' ? { provider: options } : options; // Make sure the user is logged in when an "account link" was requested. if (linkAccount) await this.enforceAuth(); // Get the url and other data necessary for the authentication. const { authUri, sessionId } = await this.api('createAuthUri', { continueUri: this.redirectUri, authFlowType: 'CODE_FLOW', providerId: provider, oauthScope, context }); // Save the sessionId that we just received in the local storage. // Is required to finish the auth flow, I believe this is used to mitigate CSRF attacks. // (No docs on this...) await this.storage.set(this.sKey('SessionId'), sessionId); // Save if this is a fresh log-in or a "link account" request. linkAccount && (await this.storage.set(this.sKey('LinkAccount'), true)); // Finally - redirect the page to the auth endpoint. location.assign(authUri); } /** * Signs in or signs up a user using credentials from an Identity Provider (IdP) after a redirect. * Will fail silently if the URL doesn't have a "code" search param. * @param {string} [requestUri] The request URI with the authorization code, state etc. from the IdP. * @private */ async finishProviderSignIn(requestUri = location.href) { // Get the sessionId we received before the redirect from storage. const sessionId = await this.storage.get(this.sKey('SessionId')); // Get the indication if this was a "link account" request. const linkAccount = await this.storage.get(this.sKey('LinkAccount')); // Check for the edge case in which the user signed out before completing the linkAccount // Request. if (linkAccount && !this.user) throw Error('Request to "Link account" was made, but user is no longer signed-in'); await this.storage.remove(this.sKey('LinkAccount')); // Try to exchange the Auth Code for an idToken and refreshToken. const { idToken, refreshToken, expiresAt, context } = await this.api('signInWithIdp', { // If this is a "link account" flow, then attach the idToken of the currently logged in account. idToken: linkAccount ? this.user.tokenManager.idToken : undefined, requestUri, sessionId, returnSecureToken: true }); // Now get the user profile. await this.fetchProfile({ idToken, refreshToken, expiresAt }); // Remove sensitive data from the URLSearch params in the location bar. history.replaceState(null, null, location.origin + location.pathname); return context; } /** * Handles all sign in flows that complete via redirects. * Fails silently if no redirect was detected. */ async handleSignInRedirect() { // Oauth Federated Identity Provider flow. if (location.href.match(/[&?]code=/)) return this.finishProviderSignIn(); // Email Sign-in flow. if (location.href.match(/[&?]oobCode=/)) { const oobCode = location.href.match(/[?&]oobCode=([^&]+)/)[1]; const email = location.href.match(/[?&]email=([^&]+)/)[1]; const expiresAt = Date.now() + 3600 * 1000; const { idToken, refreshToken } = await this.api('signInWithEmailLink', { oobCode, email }); // Now get the user profile. await this.fetchProfile({ idToken, refreshToken, expiresAt }); // Remove sensitive data from the URLSearch params in the location bar. history.replaceState(null, null, location.origin + location.pathname); } } /** * Signs up with email and password or anonymously when no arguments are passed. * Automatically signs the user in on completion. * @param {string} [email] The email for the user to create. * @param {string} [password] The password for the user to create. */ async signUp(email, password) { // Sign up and then retrieve the user profile and persists the session. return await this.fetchProfile( await this.api('signUp', { email, password, returnSecureToken: true }) ); } /** * Signs in a user with email and password. * @param {string} email * @param {string} password */ async signIn(email, password) { // Sign up and then retrieve the user profile and persists the session. return await this.fetchProfile( await this.api('signInWithPassword', { email, password, returnSecureToken: true }) ); } /** * Sends an out-of-band confirmation code for an account. * Can be used to reset a password, to verify an email address and send a Sign-in email link. * The `email` argument is not needed only when verifying an email(In that case it will be completely ignored, even if specified), otherwise it is required. * @param {'PASSWORD_RESET'|'VERIFY_EMAIL'|'EMAIL_SIGNIN'} requestType The type of out-of-band (OOB) code to send. * @param {string} [email] When the `requestType` is `PASSWORD_RESET` or `EMAIL_SIGNIN` you need to provide an email address. * @returns {Promise} */ async sendOobCode(requestType, email) { const verifyEmail = requestType === 'VERIFY_EMAIL'; if (verifyEmail) { await this.enforceAuth(); email = this.user.email; } return void this.api('sendOobCode', { idToken: verifyEmail ? this.user.tokenManager.idToken : undefined, requestType, email, continueUrl: this.redirectUri + `?email=${email}` }); } /** * Sets a new password by using a reset code. * Can also be used to very oobCode by not passing a password. * @param {string} code * @returns {string} The email of the account to which the code was issued. */ async resetPassword(oobCode, newPassword) { return (await this.api('resetPassword', { oobCode, newPassword })).email; } /** * Returns info about all providers associated with a specified email. * @param {string} email The user's email address. * @returns {ProvidersForEmailResponse} */ async fetchProvidersForEmail(email) { const response = await this.api('createAuthUri', { identifier: email, continueUri: location.href }); delete response.kind; return response; } /** * Gets the user data from the server, and updates the local caches. * @param {Object} [tokenManager] Only when not logged in. * @throws Will throw if the user is not signed in. */ async fetchProfile(tokenManager = this.user && this.user.tokenManager) { if (!tokenManager) await this.enforceAuth(); const userData = (await this.api('lookup', { idToken: tokenManager.idToken })).users[0]; delete userData.kind; userData.tokenManager = tokenManager; await this.setState(userData); } /** * Update user's profile. * @param {Object} newData An object with the new data to overwrite. * @throws Will throw if the user is not signed in. */ async updateProfile(newData) { await this.enforceAuth(); // Calculate the expiration date for the idToken. const updatedData = await this.api('update', { ...newData, idToken: this.user.tokenManager.idToken, returnSecureToken: true }); const { idToken, refreshToken, expiresAt } = updatedData; if (updatedData.idToken) { updatedData.tokenManager = { idToken, refreshToken, expiresAt }; } else { updatedData.tokenManager = this.user.tokenManager; } delete updatedData.kind; delete updatedData.idToken; delete updatedData.refreshToken; await this.setState(updatedData); } /** * Deletes the currently logged in account and logs out. * @throws Will throw if the user is not signed in. */ async deleteAccount() { await this.enforceAuth(); await this.api('delete', `{"idToken": "${this.user.tokenManager.idToken}"}`); this.signOut(); } }
JavaScript
class GamepadHandler extends EventEmitter { constructor(index, gamepad, options = {}) { super(); this.index = index; this.options = this.constructor.resolveOptions(options); this.sticks = new Array(gamepad.axes.length / 2).fill(null).map(() => [null, null]); this.buttons = new Array(gamepad.buttons.length).fill(null); this.updateStick = this.updateStick.bind(this); this.updateButton = this.updateButton.bind(this); } /** * Resolve options * * @param {Object} sourceOptions * * @return {Object} */ static resolveOptions(sourceOptions) { const customStick = typeof sourceOptions.stick !== 'undefined'; const customButton = typeof sourceOptions.button !== 'undefined'; const options = { stick: this.optionResolver.resolve(customStick ? sourceOptions.stick : (customButton ? {} : sourceOptions)), button: this.optionResolver.resolve(customButton ? sourceOptions.button : (customStick ? {} : sourceOptions)) }; options.stick.deadZone = Math.max(Math.min(options.stick.deadZone, 1), 0); options.button.deadZone = Math.max(Math.min(options.button.deadZone, 1), 0); options.stick.precision = options.stick.precision ? Math.pow(10, options.stick.precision) : 0; options.button.precision = options.button.precision ? Math.pow(10, options.button.precision) : 0; return options; } /** * Update */ update(gamepad) { let index = 0; const sticks = this.sticks.length; for (let stick = 0; stick < sticks; stick++) { for (let axis = 0; axis < 2; axis++) { this.updateStick(gamepad, stick, axis, gamepad.axes[index++]); } } const buttons = this.buttons.length; for (index = 0; index < buttons; index++) { this.updateButton(gamepad, gamepad.buttons[index], index); } } /** * Set stick * * @param {Number} stick * @param {Number} axis * @param {Number} value */ updateStick(gamepad, stick, axis, value) { const { deadZone, analog, precision } = this.options.stick; if (deadZone && value < deadZone && value > -deadZone) { value = 0; } if (!analog) { value = value > 0 ? 1 : value < 0 ? -1 : 0; } else if (precision) { value = Math.round(value * precision) / precision; } if (this.sticks[stick][axis] !== value) { this.sticks[stick][axis] = value; this.emit('axis', { gamepad, stick, axis, value, index: this.index }); } } /** * Set button * * @param {Gamepad} gamepad * @param {GamepadButton} button * @param {Number} index */ updateButton(gamepad, button, index) { const { deadZone, analog, precision } = this.options.button; const { value: currentValue, pressed } = button; let value = currentValue; if (deadZone && button.value < deadZone && button.value > -deadZone) { value = 0; } if (!analog) { value = pressed ? 1 : 0; } else if (precision) { value = Math.round(value * precision) / precision; } if (this.buttons[index] !== value) { this.buttons[index] = value; this.emit('button', { gamepad, button: index, pressed, value, index: this.index }); } } }
JavaScript
class Canvas { constructor(canvasWidth, canvasHeight, quads) { // The line bellow can be change to create the canvas element and insert it on the document.body; this.canvas = document.getElementById('canvas'); this.ctx = this.canvas.getContext('2d'); this.canvas.width = canvasWidth; this.canvas.height = canvasHeight; this.quads = quads; this.shapes = []; this.canvas.addEventListener('click', () => { this.addShape(); }); } // Drawing points on the canvas drawPoints() { const color = this.changeColorRandomly(); this.ctx.strokeStyle = color; this.ctx.beginPath(); this.shapes.forEach((points) => { points.drawPoints(this.ctx); points.decreaseLifeTime(1); }); this.ctx.stroke(); } // Responsible to randomly change the point values changePoints() { this.shapes.forEach((points) => { points.distortAllPoints( Math.floor(Math.random() * (6 - (-5)) + (-5)), Math.floor(Math.random() * (6 - (-5)) + (-5)) ); }); } // Responsible to randomly change the color changeColorRandomly() { const newColor = [ Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.random(), ]; return `rgba(${newColor.join(", ")})`; } changeWindowSize(newWidth, newHeight) { this.canvas.width = newWidth; this.canvas.height = newHeight; } // add new shapes for the shapes array addShape() { this.shapes.push(new Points(this.quads)); } // delete dead shapes from the shapes array buryDeadShapes() { this.shapes = this.shapes.filter((points) => points.isDead === false); } }
JavaScript
class ViewSet { /** * @param {Homonym} homonym - Data about inflections we need to build views for */ constructor (homonym = undefined) { this.homonym = homonym this.matchingViews = [] this.matchingViewsMap = new Map() this.inflectionData = null this.enabled = false if (this.homonym) { this.languageID = homonym.languageID this.datasets = LanguageDatasetFactory.getDatasets(homonym.languageID) /** * Whether inflections are enabled for the homonym's language */ this.enabled = LanguageModelFactory.getLanguageModel(homonym.languageID).canInflect() if (this.enabled) { for (const lexeme of homonym.lexemes) { for (const inflection of lexeme.inflections) { // Inflections are grouped by part of speech try { this.datasets.forEach(dataset => { dataset.setInflectionData(inflection, lexeme.lemma) }) } catch (e) { console.error(`Cannot set inflection data: ${e}`) } } } this.matchingViews.push(...this.constructor.views.reduce( (acc, view) => acc.concat(...view.getMatchingInstances(this.homonym)), [])) this.updateMatchingViewsMap(this.matchingViews) } } } /** * Returns a list of views available within a view set. Should be redefined in descendant classes. * @return {View[]} A list of views available within the view set. */ static get views () { return [] } get partsOfSpeech () { return Array.from(this.matchingViewsMap.keys()) } get hasMatchingViews () { return this.matchingViewsMap.size > 0 } updateMatchingViewsMap (views) { for (const view of views) { if (!this.matchingViewsMap.has(view.partOfSpeech)) { this.matchingViewsMap.set(view.partOfSpeech, []) } let storedInstances = this.matchingViewsMap.get(view.partOfSpeech) // eslint-disable-line prefer-const // Filter out instances that are already stored in a view set const isNew = !storedInstances.find(v => v.sameAs(view)) if (isNew) { storedInstances.push(view) } } } /** * Returns all matching views available, or matching views available only for a particular part of speech. * Views are sorted according to sorting rules defined for each part of speech. * Each view might have linked views specified within a view class. Those view will be added after * an original view * @param {string | undefined} partOfSpeech - A part of speech for which views should be returned. * If not specify, will result in views returned for all parts of speech available for ViewSet's inflection data. * @return {View[]} */ getViews (partOfSpeech = undefined) { if (partOfSpeech) { // Return views for a particular part of speech return this.matchingViewsMap.has(partOfSpeech) ? this.matchingViewsMap.get(partOfSpeech) : [] } else { // Return all matching views return Array.from(this.matchingViewsMap.values()).reduce((acc, views) => acc.concat(...views), []) } } static getViewByID (viewID) { return this.views.find(v => v.viewID === viewID) } static getStandardForm (options) { if (!options || !options.viewID) { throw new Error(`Obligatory options property, "viewID", is missing`) } const view = this.getViewByID(options.viewID) return view ? view.getStandardFormInstance(options) : null } }
JavaScript
class PomodoroComponent extends Component { constructor() { super(); this.state = this.getBaselineState(); } getBaselineState() { return { isPaused : true, minutes : 24, seconds : 59, buttonLabel : 'Start' } } componentDidMount() { this.timer = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.timer); delete this.timer; } resetPomodoro() { this.setState(this.getBaselineState()); } tick() { if (!this.state.isPaused) { const newState = {}; newState.buttonLabel = 'Pause'; newState.seconds = this.state.seconds - 1; if (newState.seconds < 0) { newState.seconds = 59; newState.minutes = this.state.minutes - 1; if (newState.minutes < 0) { return this.resetPomodoro(); } } this.setState(newState); } } togglePause() { const newState = {}; newState.isPaused = !this.state.isPaused; if (this.state.minutes < 24 || this.state.seconds < 59) { newState.buttonLabel = newState.isPaused ? 'Resume' : 'Pause'; } this.setState(newState); } render() { return React.createElement('div', { className : 'text-center' }, [ React.createElement(ImageComponent, { key : 'image' }), React.createElement(CounterComponent, { key : 'counter', minutes : this.state.minutes, seconds : this.state.seconds }), React.createElement(ButtonComponent, { key : 'button', buttonLabel : this.state.buttonLabel, onClick : this.togglePause.bind(this) }) ]); } }
JavaScript
class Level extends Phaser.Scene { constructor() { super("Level"); /* START-USER-CTR-CODE */ // Write your code here. /* END-USER-CTR-CODE */ } /** @returns {void} */ editorCreate() { // dino const dino = this.add.image(400, 218, "dino"); // text_1 const text_1 = this.add.text(400, 408, "", {}); text_1.setOrigin(0.5, 0.5); text_1.text = "Phaser 3 + Phaser Editor 2D"; text_1.setStyle({"fontFamily":"Arial","fontSize":"30px"}); // dino (components) new PushOnClick(dino); this.events.emit("scene-awake"); } /* START-USER-CODE */ // Write more your code here create() { this.editorCreate(); } /* END-USER-CODE */ }
JavaScript
class User extends AbstractModel { static get schema() { return { group: { type: 'enum', enum: this.groups, default: this.groups[1], }, username: { type: 'string', index: true, default: '', required: true, pattern: /^[a-z0-9_-]+$/i, }, email: { type: 'email', required: true, }, password: { type: 'string', required: true, range: { min: 8, }, }, firstName: { type: 'string', index: true, }, lastName: { type: 'string', }, birthDate: { type: 'date', }, gender: { type: 'enum', enum: ['male', 'female'], }, isActive: { type: 'boolean', default: true, }, }; } static get groups() { return ['admin', 'user', 'guest']; } static get permissions() { const [admin, user, guest] = this.groups; return { [admin]: { users: { create: true, view: true, edit: true, delete: true, }, links: { create: true, view: true, edit: true, delete: true, }, }, [user]: { users: { self: { view: true, edit: true, delete: true, }, }, links: { create: true, view: true, edit: true, delete: true, }, }, [guest]: { links: { view: true, }, }, }; } /** * Checks if passed users is the same. * * @param {User} user1 * @param {User} user2 * @returns {Boolean} */ static isEqual(user1, user2) { return isEqual(user1._id, user2._id); } static async updateAll({ filter = {}, update = {}, } = {}) { if ('password' in update) { const hashedPassword = await hashPassword(update.password); await super.updateAll({ filter, update: Object.assign(update, { password: hashedPassword }), }); } else { await super.updateAll({ filter, update }); } } get isAdmin() { return this.group === this.constructor.groups[0]; } get isUser() { return this.group === this.constructor.groups[1]; } get isGuest() { return this.group === this.constructor.groups[2]; } /** * Returns true if user has at least one permission from a given permissions list. * * @param {Array} permissions * @returns {Boolean} */ hasPermission(permissions = []) { return permissions.some( permission => get(this.constructor.permissions, `${this.group}.${permission}`, false), ); } /** * Creates and returns new jwt token for user using user id. * * @returns {Promise} */ async generateJwtToken() { return new Promise((resolve, reject) => { jwt.sign({ id: this._id }, config.secret, config.jwt, (error, token) => { if (error) { reject(error); } else { resolve(token); } }); }); } /** * Checks if a submitted password is correct. * * @param {String} password * @returns {Promise.<Boolean>} */ async checkPassword(password) { const hashedSubmittedPassword = await hashPassword(password); return this.password === hashedSubmittedPassword; } /** * Hashes password if password was modified. * * @returns {Promise.<void>} */ async encryptPassword() { const passwordModified = await this.isModified('password'); if (passwordModified) { this.password = await hashPassword(this.password); } } async save() { await this.encryptPassword(); await super.save(); } async update(update = {}) { if ('password' in update) { this.password = update.password; } await this.encryptPassword(); await super.update(update); } toObject() { const object = super.toObject(); delete object.password; return object; } }
JavaScript
class TXMatrix2D{ /** * @param {Vec2[]} source */ constructor(source){ if(source){ this.m = []; this.clone(source); }else{ this.m = [1,0,0,0,1,0]; } } /**Toggle this into an `Identity` matrix * @return {TXMatrix2D} self */ identity(){ const m = this.m; m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 1; m[5] = 0; return this; } /**Deep clone a matrix. * @param {TXMatrix2D} * @return {TXMatrix2D} self */ clone(matrix){ let d = this.m, s = matrix.m; d[0]=s[0]; d[1]=s[1]; d[2] = s[2]; d[3]=s[3]; d[4]=s[4]; d[5] = s[5]; return this; } /**Multiply by this matrix * @param {TXMatrix2D} matrix * @return {TXMatrix2D} self */ multiply(matrix){ let a = this.m, b = matrix.m; let m11 = a[0]*b[0] + a[1]*b[3]; let m12 = a[0]*b[1] + a[1]*b[4]; let m13 = a[0]*b[2] + a[1]*b[5] + a[2]; let m21 = a[3]*b[0] + a[4]*b[3]; let m22 = a[3]*b[1] + a[4]*b[4]; let m23 = a[3]*b[2] + a[4]*b[5] + a[5]; a[0]=m11; a[1]=m12; a[2] = m13; a[3]=m21; a[4]=m22; a[5] = m23; return this; } /**Apply rotation. * @param {number} radians * @return {TXMatrix2D} self */ rotate(radians){ if(!_.feq0(radians)){ let m=this.m, cos = Math.cos(radians), sin = Math.sin(radians); let m11 = m[0]*cos + m[1]*sin; let m12 = -m[0]*sin + m[1]*cos; let m21 = m[3]*cos + m[4]*sin; let m22 = -m[3]*sin + m[4]*cos; m[0] = m11; m[1] = m12; m[3] = m21; m[4] = m22; } return this; } /**Apply rotation (in degrees). * @param {number} degrees * @return {TXMatrix2D} self */ rotateDeg(degrees){ return _.feq0(degrees)? this: this.rotate(Math.PI * degrees / 180) } /**Apply scaling. * @param {number} sx * @param {number} sy * @return {TXMatrix2D} self */ scale(sx,sy){ let m = this.m; if(sy===undefined){ sy=sx } m[0] *= sx; m[1] *= sy; m[3] *= sx; m[4] *= sy; return this; } /**Apply translation. * @param {number} tx * @param {number} ty * @return {TXMatrix2D} self */ translate(tx,ty){ let m = this.m; m[2] += m[0]*tx + m[1]*ty; m[5] += m[3]*tx + m[4]*ty; return this; } /**Transform this point. * @param {number} x * @param {number} y * @return {Vec2} */ transform(x,y){ return [ x * this.m[0] + y * this.m[1] + this.m[2], x * this.m[3] + y * this.m[4] + this.m[5] ]; } /**@see {@link module:mcfud/gfx.TXMatrix2D#transform} * @param {object} obj * @return {object} obj */ transformPoint(obj){ const [x,y]= this.transform(obj.x,obj.y); obj.x = x; obj.y = y; return obj; } /**@see {@link module:mcfud/gfx.TXMatrix2D#transform} * @param {Vec2} inArr * @return {Vec2} */ transformArray(inArr){ return this.transform(inArr[0],inArr[1]) } /**Set HTML5 2d-context's transformation matrix. * @param {object} html5 2d-context */ setContextTransform(ctx){ const m = this.m; // source: // m[0] m[1] m[2] // m[3] m[4] m[5] // 0 0 1 // // destination: // m11 m21 dx // m12 m22 dy // 0 0 1 // setTransform(m11, m12, m21, m22, dx, dy) ctx.transform(m[0],m[3],m[1],m[4],m[2],m[5]); } }
JavaScript
class Rect{ /** * @param {number} x * @param {number} y * @param {number} width * @param {number} height */ constructor(x,y,width,height){ switch(arguments.length){ case 2: this.pos= _V.vec(); this.width=x; this.height=y; break; case 4: this.pos=_V.vec(x,y); this.width=width; this.height=height; break; default: throw "Error: bad input to Rect()"; } } }
JavaScript
class Area{ /** * @param {number} w * @param {number} h */ constructor(w,h){ this.width=w; this.height=h; } /** * @return {Area} */ half(){ return new Area(MFL(this.width/2),MFL(this.height/2)) } }
JavaScript
class Line{ /** * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 */ constructor(x1,y1,x2,y2){ this.p= _V.vec(x1,y1); this.q= _V.vec(x2,y2); } }
JavaScript
class Polygon{ /** * @param {number} x * @param {number} y */ constructor(x,y){ this.calcPoints=null; this.normals=null; this.edges=null; this.points=null; this.orient = 0; this.pos=_V.vec(); this.setPos(x,y); } /**Set origin. * @param {number} x * @param {number} y * @return {Polygon} self */ setPos(x=0,y=0){ _V.set(this.pos,x,y); return this; } /**Set vertices. * @param {Vec2[]} points * @return {Polygon} self */ set(points){ this.calcPoints= this.calcPoints || []; this.normals= this.normals || []; this.edges= this.edges || []; this.calcPoints.length=0; this.normals.length=0; this.edges.length=0; this.points= _.assert(points.length>2) && _orderPoints(points); _.doseq(this.points, p=>{ this.calcPoints.push(_V.vec()); this.edges.push(_V.vec()); this.normals.push(_V.vec()); }); return this._recalc(); } /**Set rotation. * @param {number} rot * @return {Polygon} self */ setOrient(rot){ this.orient = rot; return this._recalc(); } /**Move the points. * @param {number} x * @param {number} y * @return {Polygon} self */ translate(x, y){ _.doseq(this.points,p=>{ p[0] += x; p[1] += y; }); return this._recalc(); } /** @ignore */ _recalc(){ if(this.points){ _.doseq(this.points,(p,i)=>{ _V.copy(this.calcPoints[i],p); if(!_.feq0(this.orient)) _V.rot$(this.calcPoints[i],this.orient); }); let i2,p1,p2; _.doseq(this.points,(p,i)=>{ i2= (i+1) % this.calcPoints.length; p1=this.calcPoints[i]; p2=this.calcPoints[i2]; this.edges[i]= _V.sub(p2,p1); this.normals[i]= _V.unit(_V.normal(this.edges[i])); }); } return this; } }
JavaScript
class Manifold{ /** * @param {Vec2} overlapN * @param {Vec2} overlapV * @param {object} A * @param {object} B */ constructor(A,B){ this.overlapN = _V.vec(); this.overlapV = _V.vec(); this.A = A; this.B = B; this.clear(); } swap(){ let m=new Manifold(); let aib=this.AInB; let bia=this.BInA; let a=this.A; m.overlap=this.overlap; m.A=this.B; m.B=a; m.AInB=bia; m.BInA=aib; m.overlapN=_V.flip(this.overlapN); m.overlapV=_V.flip(this.overlapV); //m.overlapV[0]=m.overlapN[0]*this.overlap; //m.overlapV[1]=m.overlapN[1]*this.overlap; return m; } /**Reset to zero. */ clear(){ this.overlap = Infinity; this.AInB = true; this.BInA = true; return this; } }
JavaScript
class GameBoard{ constructor(){} /**Get the function that copies a game state. * @return {function} */ getStateCopier(){} /**Get the first move. * @param {GFrame} frame * @return {any} */ getFirstMove(frame){} /**Get the list of next possible moves. * @param {GFrame} frame * @return {any[]} */ getNextMoves(frame){} /**Calculate the score. * @param {GFrame} frame * @return {number} */ evalScore(frame){} /**Check if game is a draw. * @param {GFrame} frame * @return {boolean} */ isStalemate(frame){} /**Check if game is over. * @param {GFrame} frame * @return {boolean} */ isOver(frame){} /**Reverse previous move. * @param {GFrame} frame * @param {any} move */ unmakeMove(frame, move){ if(!this.undoMove) throw Error("Need Implementation"); this.switchPlayer(frame); this.undoMove(frame, move); } //undoMove(frame, move){} //doMove(frame, move){ } /**Make a move. * @param {GFrame} frame * @param {any} move */ makeMove(frame, move){ if(!this.doMove) throw Error("Need Implementation!"); this.doMove(frame, move); this.switchPlayer(frame); } /**Switch to the other player. * @param {GFrame} frame */ switchPlayer(snap){ let t = snap.cur; snap.cur= snap.other; snap.other= t; } /**Get the other player. * @param {any} pv player * @return {any} */ getOtherPlayer(pv){ if(pv === this.actors[1]) return this.actors[2]; if(pv === this.actors[2]) return this.actors[1]; } /**Get the current player. * @return {any} */ getPlayer(){ return this.actors[0] } /**Take a snapshot of current game state. * @return {GFrame} */ takeGFrame(){} run(seed,actor){ this.getAlgoActor=()=>{ return actor } this.syncState(seed,actor); let pos= this.getFirstMove(); if(_.nichts(pos)) pos= _$.evalNegaMax(this); return pos; } }
JavaScript
class GameBoard{ constructor(){ this.aiActor=null; } /**Get the function that copies a game state. * @return {function} */ getStateCopier(){} /**Get the first move. * @param {GFrame} frame * @return {any} */ getFirstMove(frame){} /**Get the list of next possible moves. * @param {GFrame} frame * @return {any[]} */ getNextMoves(frame){} /**Calculate the score. * @param {GFrame} frame * @param {number} depth * @param {number} maxDepth * @return {number} */ evalScore(frame,depth,maxDepth){} /**Check if game is a draw. * @param {GFrame} frame * @return {boolean} */ isStalemate(frame){} /**Check if game is over. * @param {GFrame} frame * @return {boolean} */ isOver(frame,move){} /**Reverse previous move. * @param {GFrame} frame * @param {any} move */ unmakeMove(frame, move){ if(!this.undoMove) throw Error("Need Implementation"); this.switchPlayer(frame); this.undoMove(frame, move); } //undoMove(frame, move){} //doMove(frame, move){ } /**Make a move. * @param {GFrame} frame * @param {any} move */ makeMove(frame, move){ if(!this.doMove) throw Error("Need Implementation!"); this.doMove(frame, move); this.switchPlayer(frame); } /**Take a snapshot of current game state. * @return {GFrame} */ takeGFrame(){} /**Switch to the other player. * @param {GFrame} snap */ switchPlayer(snap){ let t = snap.cur; snap.cur= snap.other; snap.other= t; } /**Get the other player. * @param {any} pv player * @return {any} */ getOtherPlayer(pv){ if(pv === this.actors[1]) return this.actors[2]; if(pv === this.actors[2]) return this.actors[1]; } /**Get the current player. * @return {any} */ getPlayer(){ return this.actors[0] } /**Run the algo and get a move. * @param {any} seed * @param {any} actor * @return {any} the next move */ run(seed,actor){ this.getAlgoActor=()=>{ return actor } this.syncState(seed,actor); let pos= this.getFirstMove(); if(_.nichts(pos)) pos= _$.evalMiniMax(this); return pos; } }
JavaScript
class MicroGameShell { constructor(domElement = null, pollTime = 10, skipFramesAfter = 100) { // settings this.stickyPointerLock = false this.stickyFullscreen = false this.tickRate = 30 this.maxRenderRate = 0 // API this.pointerLock = false this.fullscreen = false // for client to override this.onTick = function (dt) { } this.onRender = function () { } this.onInit = function () { } this.onResize = function () { } this.onPointerLockChanged = function (hasPL) { } this.onFullscreenChanged = function (hasFS) { } // init domReady(() => { setupTimers(this, pollTime, skipFramesAfter) setupDomElement(this, domElement) this.onInit() }) } }
JavaScript
class ExtensibleObjectLoader extends THREE.ObjectLoader { delegate(special_handler, base_handler, json, additional_objects) { let result = {}; if (json === undefined) { return result; } let remaining_json = []; for (let data of json) { let x = special_handler(data); if (x !== null) { result[x.uuid] = x; } else { remaining_json.push(data); } } return Object.assign(result, base_handler(remaining_json, additional_objects)); } parseTextures(json, images) { return this.delegate(handle_special_texture, super.parseTextures, json, images); } parseGeometries(json, shapes) { return this.delegate(handle_special_geometry, super.parseGeometries, json, shapes); } parseObject(json, geometries, materials) { if (json.type == "_meshfile_object") { let geometry; let material; let manager = new THREE.LoadingManager(); let path = (json.url === undefined) ? undefined : THREE.LoaderUtils.extractUrlBase(json.url); manager.setURLModifier(url => { if (json.resources[url] !== undefined) { return json.resources[url]; } return url; }); if (json.format == "obj") { let loader = new OBJLoader(manager); if (json.mtl_library) { let mtl_loader = new MTLLoader(manager); let mtl_parse_result = mtl_loader.parse(json.mtl_library + "\n", ""); console.log(mtl_parse_result); // let materials = MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result); // console.log(materials); // loader.addMaterials(materials); // this.onTextureLoad(); } let obj = loader.parse(json.data + "\n", path); geometry = merge_geometries(obj, true); geometry.uuid = json.uuid; material = geometry.material; } else if (json.format == "dae") { let loader = new ColladaLoader(manager); loader.onTextureLoad = this.onTextureLoad; let obj = loader.parse(json.data, path); geometry = merge_geometries(obj.scene, true); geometry.uuid = json.uuid; material = geometry.material; } else if (json.format == "stl") { let loader = new STLLoader(); geometry = loader.parse(json.data.buffer, path); geometry.uuid = json.uuid; material = geometry.material; } else { console.error("Unsupported mesh type:", json); return null; } let object = new THREE.Mesh(geometry, material); // Copied from ObjectLoader object.uuid = json.uuid; if (json.name !== undefined) object.name = json.name; if (json.matrix !== undefined) { object.matrix.fromArray(json.matrix); if (json.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = json.matrixAutoUpdate; if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale); } else { if (json.position !== undefined) object.position.fromArray(json.position); if (json.rotation !== undefined) object.rotation.fromArray(json.rotation); if (json.quaternion !== undefined) object.quaternion.fromArray(json.quaternion); if (json.scale !== undefined) object.scale.fromArray(json.scale); } if (json.castShadow !== undefined) object.castShadow = json.castShadow; if (json.receiveShadow !== undefined) object.receiveShadow = json.receiveShadow; if (json.shadow) { if (json.shadow.bias !== undefined) object.shadow.bias = json.shadow.bias; if (json.shadow.radius !== undefined) object.shadow.radius = json.shadow.radius; if (json.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(json.shadow.mapSize); if (json.shadow.camera !== undefined) object.shadow.camera = this.parseObject(json.shadow.camera); } if (json.visible !== undefined) object.visible = json.visible; if (json.frustumCulled !== undefined) object.frustumCulled = json.frustumCulled; if (json.renderOrder !== undefined) object.renderOrder = json.renderOrder; if (json.userjson !== undefined) object.userjson = json.userData; if (json.layers !== undefined) object.layers.mask = json.layers; return object; } else if (json.type == "CameraHelper") { console.log("processing CameraHelper"); console.log(json); console.log(geometries); console.log(materials); return super.parseObject(json, geometries, materials); } else { return super.parseObject(json, geometries, materials); } } }
JavaScript
class HumanGuiStrategy { constructor(board){ this.isHuman = true; this.board = board; } selectColumn(model){ let selectColumnFromPos = function(board, x){ let selectedColumn = board.getColumn(x); if ( selectedColumn && ! selectedColumn.isComplete()){ board.setSelectedColnum(selectedColumn.num); }else{ selectedColumn = null; } return selectedColumn; } return new Promise((resolve, reject)=>{ //reset the selected column to the current mouse position let selectedColumn = selectColumnFromPos(this.board, mousePos.x); //listen to mouse event, find the selected column and play let mousemove = (evt)=>{ var rect = this.board.canvas.getBoundingClientRect(); mousePos.out = false; mousePos.x = evt.clientX - rect.left; mousePos.y = evt.clientY - rect.top; selectedColumn = selectColumnFromPos(this.board, mousePos.x); //console.debug(mousePos); }; this.board.canvas.addEventListener('mousemove', mousemove, false); let mouseout = ()=> (mousePos.out = true); this.board.canvas.addEventListener('mouseout', mouseout, false); let click = ()=> { if (selectedColumn != null){ //current player has played, let's clean the listener and resolve the promise removeEventListeners(false); } }; this.board.canvas.addEventListener('click', click, false); let removeEventListeners = (isInterrupted)=>{ this.board.canvas.removeEventListener('mousemove', mousemove, false); this.board.canvas.removeEventListener('mouseout', mouseout, false); this.board.canvas.removeEventListener('click', click, false); this.$clearAll = null; if(isInterrupted){ resolve(null); }else{ resolve(selectedColumn.num); } }; this.$clearAll = removeEventListeners; }); } /** * */ interrupt(){ //we have been interrupted, we clean the listener (if exist) and abort (reject) the play if (this.$clearAll) this.$clearAll(true); } }
JavaScript
class FormsValidationView extends View { constructor(model, $failBehaviour = false, $successBehaviour = false) { super(); this.model = model; if (!$failBehaviour) $failBehaviour = new DefaultFailBehaviour; this.failBehaviour = $failBehaviour; if (!$successBehaviour) $successBehaviour = new DefaultSuccessBehaviour; this.successBehaviour = $successBehaviour; this.defineUI(); this.model.registerObserver(this); } /** * @see View update() method * @param {Array} valData Array with fields validation responses * @return {Void} */ update(valData) { // Just looping backwards. Why so? // Because toasts about validation results appears one ABOVE other // and as valData normally consists of fields ordered by their position in // form, to make validation result more understandable I need to do this here. // Fields position in form: (1st 2nd 3rd ...) // Toasts with messagies position WITHOUT backward loop: (3rd, 2nd, 1st ...) // WITH backward loop (1st 2nd 3rd ...) <- Exactly the thing I need // I KNOW IT'S BAD SOLUTION, BUT I'VE NO CLUE HOW TO FIX IT FAST. // And it's not so crucial here btw. // Opened issue on GitHub: https://github.com/marcelodolza/iziToast/issues/170 for (let i = (valData.length - 1); i >= 0; i--) { if (valData[i].result) this.successBehaviour.success(valData[i]); else this.failBehaviour.fail(valData[i]); } } /** * Abstract method where UI for each form should be defined * @return {Void} */ defineUI() { throw new Error(`It's abstract method, which requires implementation!`); } }
JavaScript
class Parent { age = 34; constructor() { } foo(){ } bar(){ } }
JavaScript
class Ball{ //special method that gets called at the instantiation constructor(x, y, r){ this.x = x; this.y = y; this.r = r; this.player = false; //pushing the Ball object into the BALLZ array BALLZ.push(this); } drawBall(){ ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI); ctx.strokeStyle = "black"; ctx.stroke(); ctx.fillStyle = "red"; ctx.fill(); ctx.closePath(); } }