language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class MongoCollectionDelegate extends _defaultDelegate { insert(doc, options = {}) { return getDb().then((db) => { const coll = db.collection(this.db.modelName); return coll.insert(doc, options); }).then((res) => doc._id); } remove(query, options = {}) { const queryObject = selectorIdToObject(query); return getDb().then((db) => { const limit = options.multi ? 0 : 1; const coll = db.collection(this.db.modelName); return coll.find(queryObject).limit(limit).toArray().then((docs) => { const deleter = options.multi ? coll.deleteMany.bind(coll) : coll.deleteOne.bind(coll); return deleter(queryObject, options).then(() => docs); }); }); } update(query, modifier, {sort = {_id: 1}, upsert = false, multi = false}) { const queryObject = selectorIdToObject(query); const preparedModifier = upsert ? _prepareModifierForUpsert(modifier, queryObject) : modifier; return getDb().then((db) => { const coll = db.collection(this.db.modelName); const updater = multi ? _updateMany : _updateOne; return updater(queryObject, preparedModifier, coll, { sort, upsert }); }); } count(query, options = {}) { return this.find(query, {...options, count: true}); } ids(query, options = {}) { return this.find(query).project({_id: 1}) .map((doc) => doc._id); } }
JavaScript
class CustomToolbar extends React.Component { navigate = action => { const { onNavigate } = this.props onNavigate(action) } render() { const { date } = this.props const label = format(date, 'MMM yyyy', { locale: fi }) return ( <div className='rbc-toolbar row'> <div className='col-lg-4'> <h2 className='rbc-toolbar-label'> {label.toUpperCase()} </h2> </div> <div className='col-lg-4'> <span className='rbc-btn-group'> <button type='button' className='rbc-toolbar button' onClick={() => this.navigate('PREV')} > <PrevIcon /> </button> <button type='button' className='rbc-toolbar button' onClick={() => this.navigate('TODAY')} > Tänään </button> <button type='button' className='rbc-toolbar button' onClick={() => this.navigate('NEXT')} > <NextIcon /> </button> </span> </div> </div> ) } }
JavaScript
class CallbackMerger { constructor(n, callback) { this._callback = callback; this._n = n; this._arg = {}; } call(arg) { if (this._n <= 0) { throw Error('CallbackMerger has completed its iterations'); } _.merge(this._arg, arg); this._n -= 1; if (this._n === 0) { this._callback(this._arg); } } }
JavaScript
class Enum { constructor(values={}) { if (Array.isArray(values)) { values = _.fromPairs(values.map((x, i) => [x, i])); } for (let key in values) { let v = values[key]; Object.defineProperty(this, key, { get: () => v }); } } }
JavaScript
class CargoInput extends LightDispatcher { /** * @param {CargoInputParams} params */ constructor(params){ super(); this.params = params; } /** @ignore ignore */ _Bind(value){ /** @type {App} */ let app = value; this[_cargoList] = app.packer.cargoList; } /** Creates a new BoxEntry, required for inputs. (Can be reused) */ CreateBoxEntry(){ let boxEntry = new BoxEntry(); renewBoxEntry(boxEntry); return boxEntry; } /** @param {string} entryUID @returns {BoxEntry} a copy of the entry if it exists */ GetEntry(entryUID){ /** @type {CargoList} */ let cargoList = this[_cargoList]; let entry = cargoList.GetEntry(entryUID); let entryMirror = boxEntryPool.Request(); entryMirror.Copy(entry); return entry; } /** @returns {Array<BoxEntry>} an array of copies of all entries */ GetEntries(){ /** @type {CargoList} */ let cargoList = this[_cargoList]; let entries = []; cargoList.groups.forEach(value => { let entryMirror = boxEntryPool.Request(); entryMirror.Copy(value.entry); entries.push(entryMirror); }); return entries; } /** * Return BoxEntry objects to object pool (less memory usage) * @param {BoxEntry | Array<BoxEntry>} objects */ Recycle(objects){ if(objects instanceof Array){ objects.forEach( (object) => { if(object instanceof BoxEntry) boxEntryPool.Return(object); }); } else if(objects instanceof BoxEntry){ boxEntryPool.Return(objects); } } /** Shows/updates entry 3D display * @param {BoxEntry} entry * @returns {Boolean} */ Show(entry){ if(BoxEntry.Assert(entry)){ try{ this.Dispatch(signals.show, entry); return true; } catch(error){ Logger.Warn('Error in CargoInput.Show, error/entry:', error, entry); } return false; } Logger.Warn('BoxEntry.Assert failed in CargoInput.Show, entry:', entry); return false; } /** Hides entry 3D display */ Hide(){ this.Dispatch(signals.hide); } /** Adds a new entry and obtain its uid * @param {BoxEntry} entry * @returns {Number|Boolean} uid or false if error */ Add(entry){ if(BoxEntry.Assert(entry)){ if( Dimensions.IsVolume(entry.dimensions.Abs()) === false ){ Logger.Warn('CargoInput.Add, entry rejected, dimensions != Volume:', entry.dimensions); return false; } try{ let commitedEntry = entry.Clone(); let uid = commitedEntry.SetUID(); renewBoxEntry(entry); this.Dispatch(signals.insert, commitedEntry); return uid; } catch(error){ Logger.Warn('Error in CargoInput.Add, error/entry:', error, entry); } return false; } Logger.Warn('BoxEntry.Assert failed in CargoInput.Add, entry:', entry); return false; } /** Modify an existing BoxEntry, referenced by its uid, using a modifed template * @param {string} entryUID * @param {BoxEntry} boxEntry * @returns {Boolean} success */ Modify(entryUID, boxEntry){ let existing = this.GetEntry(entryUID); if(!existing){ Logger.Warn('CargoInput.Modify, entry not found for:', entryUID); return false; } if(BoxEntry.Assert(boxEntry)){ if( Dimensions.IsVolume(boxEntry.dimensions.Abs()) === false ){ Logger.Warn('CargoInput.Modify, entry rejected, dimensions != Volume:', boxEntry); return false; } try{ existing.Copy(boxEntry); this.Dispatch(signals.modify, existing); return true; } catch(error){ Logger.Warn('Error in CargoInput.Modify, error/entry:', error, boxEntry); } return false; } Logger.Warn('BoxEntry.Assert failed in CargoInput.Modify, entry:', boxEntry); return false; } /** Removes an existing box entry * @param {string} entryUID * @returns {Boolean} success */ Remove(entryUID){ /** @type {CargoList} */ let cargoList = this[_cargoList]; let existing = cargoList.GetEntry(entryUID); if(!existing){ Logger.Warn('CargoInput.Remove, entry not found for:', entryUID); return false; } this.Dispatch(signals.remove, existing); return true; } /** Enumeration of dispatched types */ static get signals(){ return signals; } }
JavaScript
class BlankToken extends BaseLineToken { static type = 'BLANK'; isIgnoredToken() { return true; } canHandle(line) { checkTypes.assert.string(line); return line.length === 0; } tokenize(line, lineNumber) { const token = new BlankToken({ tokenTypes: this.tokenTypes }); checkTypes.assert.string(line); checkTypes.assert.integer(lineNumber); token.tokenized = { line, lineNumber }; return token; } getAllowedNextTokens() { const { BLANK_TOKEN, AC_TOKEN, COMMENT_TOKEN, EOF_TOKEN, SKIPPED_TOKEN } = this.tokenTypes; return [BLANK_TOKEN, AC_TOKEN, COMMENT_TOKEN, EOF_TOKEN, SKIPPED_TOKEN]; } }
JavaScript
class Page { /** * Page constructor. * @param {{work: Function}} source Child worker * @param {cache} cache Enable / disable page cache * @param {winston.Logger} logger Target for errors * * @public */ constructor(source, cache, logger) { this.source = source; this.cache = cache; this.logger = logger; } /** * Create page and pass to worker callback. * * @param {puppeteer.Browser} browser Chromium instance * @param {Object} request Screenshot parameters * @param {function} callback Worker callback * * @void * @public */ async work(browser, request, callback) { try { const page = await this.page(browser); await this.source.work(page, request, callback); if (! page.isClosed()) { // close page asynchronously page.close() .catch( error => this.logger.log( "error", "Unable to close page", { "error": error } ) ); } } catch (error) { callback(error, null); } } /** * Create a browser page * * @param {puppeteer.Browser} browser Browser * * @void * @private */ async page(browser) { const { logger } = this; const page = await browser.newPage(); // add listeners page.on( "error", error => { throw error; } ); page.on( "pageerror", error => { throw error; } ); // then push to different levels page.on( "console", message => logger.log( "debug", "Page console", { "message": message.text() } ) ); page.on( "requestfailed", httpRequest => logger.log( "warn", "HTTP failed request", { "method": httpRequest.method(), "url": httpRequest.url() } ) ); await page.setCacheEnabled(this.cache); return page; } }
JavaScript
class ScreenShot { constructor(settings = {}) { this.settings = Object.assign( { callback: null, method: 'w', // 'w'|'d' - New Window or Download name: 'LtScreenShot', target: $('body')[0], excluded: [], flash: true, debug: false, }, settings ); this.DOMURL = window.URL || window.webkitURL || window; } /** * Take the screenshot * * @returns undefined */ take() { if (this.settings.flash) { this.flash().then(() => { this.createImage(); }); } else { this.createImage(); } this.beforeScreenshot(); } /** * Open a new window with the image * * @param {String} dataUrl Image data * @returns undefined */ toNewWindow(dataUrl) { let image = new Image(); image.src = dataUrl; let openWindow = window.open(`${this.name}`); if (openWindow) { openWindow.document.open('text/html', 'replace'); openWindow.document.write(image.outerHTML); openWindow.document.close(); } else { alerts .error( `Couldn't create a new window, check your pop-ups blocking preferences.` ) .replace(/\n/gm, ''); } } /** * Create a link and download the image * @param {String} dataUrl Image data */ toDownload(dataUrl) { let anchor = document.createElement('a'); anchor.href = dataUrl; anchor.download = `${this.name}.png`; document.body.appendChild(anchor); anchor.click(); anchor.remove(); } /** * Before screenshot */ beforeScreenshot() { // Hide all elements for (let elem of this.settings.excluded) $(elem).hide(); } /** * After screenshot */ afterScreenshot() { // Show all elements excluded before for (let elem of this.settings.excluded) $(elem).show(); // Callback for after render if (this.settings.callback) this.settings.callback(); } /** * Create the image */ createImage() { html2canvas(this.settings.target, { async: true, logging: this.settings.debug, useCORS: true, allowTaint: false, scale: 1, onclone(document) { if (window.chrome) { var transform = $(document) .find('.gm-style>div:first>div') .css('transform'); if (transform) { // var comp=transform.split(","); //split up the transform matrix // var mapright=parseFloat(comp[3]); // var mapleft=parseFloat(comp[4]); //get left value // var maptop=parseFloat(comp[5]); //get top value // var mapbottom=parseFloat(comp[6]); $(document).find('.gm-style>div:first>div:first>div:last>div').css({ //get the map container. not sure if stable transform: transform, top: 0, left: 0, }); } } }, }) .then((canvas) => { const dataUrl = canvas.toDataURL(); if (this.settings.method === 'w') { // If mode is new window this.toNewWindow(dataUrl); } else if (this.settings.method === 'd') { // If mode is download this.toDownload(dataUrl); } this.afterScreenshot(); }) .catch((err) => { console.error(`Error with screenshot module on toPng function.`); // console.error(err); this.afterScreenshot(); }); } /** * Do flash effect */ flash() { const $el = $(this.settings.target); let lt_vapp = document.getElementsByClassName('lt-vapp')[0]; let overlay = document.createElement('div'); lt_vapp.appendChild(overlay); overlay.classList.add('lt-vapp-flashing'); $(overlay).css({ top: $el.position().top, left: $el.position().left, width: $el.width(), height: $el.height(), }); if ($el.hasClass('lt-vapp')) { $(overlay).css({ left: $el.position().left - $('#main-navigation').width(), }); } return new Promise(function (resolve) { $(overlay).fadeOut(600, () => { overlay.parentNode.removeChild(overlay); resolve(); }); }); } }
JavaScript
class Exception extends Error { /** * Constructor * Set exception message * @param {*} message */ constructor(message) { super(message); this.name = this.constructor.name; //Set correct stack trace if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { this.stack = (new Error(message)).stack; } } }
JavaScript
class Room extends Model { /** * Initializes the Room model. * * @param {Sequelize} sequelize A sequelize connection instance object. * @return A sequelize model describing the Room entity. */ static createModel(sequelize) { Room.init({ id: { type: DataTypes.INTEGER, allowNull: false, unique: true, autoIncrement: true, primaryKey: true, }, name: { type: DataTypes.STRING, allowNull: false, }, grid: { type: DataTypes.ARRAY(DataTypes.INTEGER), allowNull: false, }, }, { sequelize, modelName: "Room", freezeTableName: true, paranoid: false, }); return Room; } }
JavaScript
class Projects { /* @ngInject */ constructor() { // var vm = this; } }
JavaScript
class HyperId { constructor(Hyperdrive) { _Hyperdrive.set(this, { writable: true, value: void 0 }); _defineProperty(this, "create", async (drive, operations) => { await assertDrive(drive); const did = await getDid(drive); try { // try to read it to ensure it doesnt already exist await drive.readFile(_constants.DID_DOC_FILENAME, "utf8"); } catch (error) { // if it fails to read, we are allowed to create it const document = (0, _document.default)(did); operations(document); return await this.publish(drive, document.getContent()); } // if it reads successfully, DID Doc exists already, we need to throw IllegalCreate throw new _errors.IllegalCreate(); }); _defineProperty(this, "update", async (drive, operations) => { await assertDrive(drive); const did = await getDid(drive); let contentString; try { contentString = await drive.readFile(_constants.DID_DOC_FILENAME, "utf8"); } catch (error) { throw new _errors.UnavailableHyperdrive(); } const content = JSON.parse(contentString); const document = (0, _document.default)(did, content); operations(document); return await this.publish(drive, document.getContent()); }); _defineProperty(this, "publish", async (drive, content) => { try { await drive.writeFile(_constants.DID_DOC_FILENAME, JSON.stringify(content)); return content; } catch (error) { console.log(error); throw new _errors.UnavailableHyperdrive(); } }); _defineProperty(this, "resolve", async did => { const { identifier } = (0, _utils.parseDid)(did); try { let content, contentString; // not self, get a copy of the drive const copy = _classPrivateFieldGet(this, _Hyperdrive).call(this, identifier); try { await copy.ready(); } catch (error) { throw new _errors.UnavailableHyperdrive(); } // Wait for the connection to be made if (!copy.writable && !copy.peers.length) { await (0, _events.default)(copy, "peer-open"); // TODO: add timeout? } if (!copy.writable) await (0, _events.default)(copy, "content-feed"); // wait for the content to be fed from the remote peer contentString = await copy.readFile(_constants.DID_DOC_FILENAME, "utf8"); content = JSON.parse(contentString); (0, _document.assertDocument)(content); return content; } catch (err) { console.log("resolve Error: ", err); if (err.code === "INVALID_DOCUMENT") { throw err; } throw new _errors.InvalidDid(did, `Unable to resolve document with DID: ${did}`, { originalError: err.message }); } }); _classPrivateFieldSet(this, _Hyperdrive, Hyperdrive); } }
JavaScript
class PSVNavbar extends AbstractComponent { /** * @param {PhotoSphereViewer} psv */ constructor(psv) { super(psv, 'psv-navbar'); /** * @summary List of buttons of the navbar * @member {module:components/buttons.AbstractButton[]} * @override */ this.children = []; /** * @summary List of collapsed buttons * @member {module:components/buttons.AbstractButton[]} * @private */ this.collapsed = []; if (this.psv.config.navbar) { this.setButtons(this.psv.config.navbar); } } /** * @summary Change the buttons visible on the navbar * @param {Array<string|object>} buttons */ setButtons(buttons) { this.children.forEach(item => item.destroy()); this.children.length = 0; /* eslint-disable no-new */ buttons.forEach((button) => { if (typeof button === 'object') { new PSVCustomButton(this, button); } else if (STANDARD_BUTTONS_BY_ID[button]) { new STANDARD_BUTTONS_BY_ID[button](this); } else if (button === 'caption') { new PSVNavbarCaption(this, this.psv.config.caption); } else if (button === 'zoom') { new PSVZoomOutButton(this); new PSVZoomRangeButton(this); new PSVZoomInButton(this); } else { throw new PSVError('Unknown button ' + button); } }); new PSVMenuButton(this); /* eslint-enable no-new */ } /** * @summary Sets the bar caption * @param {string} html */ setCaption(html) { const caption = this.getButton('caption', false); if (!caption) { throw new PSVError('Cannot set caption, the navbar caption container is not initialized.'); } caption.setCaption(html); } /** * @summary Returns a button by its identifier * @param {string} id * @param {boolean} [warnNotFound=true] * @returns {module:components/buttons.AbstractButton} */ getButton(id, warnNotFound = true) { let button = null; this.children.some((item) => { if (item.prop.id === id) { button = item; return true; } else { return false; } }); if (!button && warnNotFound) { logWarn(`button "${id}" not found in the navbar`); } return button; } /** * @summary Shows the navbar */ show() { this.container.classList.add('psv-navbar--open'); this.prop.visible = true; } /** * @summary Hides the navbar */ hide() { this.container.classList.remove('psv-navbar--open'); this.prop.visible = false; } /** * @override */ refresh() { super.refresh(); if (this.psv.prop.uiRefresh === true) { const availableWidth = this.container.offsetWidth; let totalWidth = 0; const visibleButtons = []; const collapsableButtons = []; this.children.forEach((item) => { if (item.prop.visible) { totalWidth += item.prop.width; visibleButtons.push(item); if (item.collapsable) { collapsableButtons.push(item); } } }); if (!visibleButtons.length) { return; } if (availableWidth < totalWidth && collapsableButtons.length > 0) { collapsableButtons.forEach(item => item.collapse()); this.collapsed = collapsableButtons; this.getButton(PSVMenuButton.id).show(false); } else if (availableWidth >= totalWidth && this.collapsed.length > 0) { this.collapsed.forEach(item => item.uncollapse()); this.collapsed = []; this.getButton(PSVMenuButton.id).hide(false); } const caption = this.getButton(PSVNavbarCaption.id, false); if (caption) { caption.refresh(); } } } }
JavaScript
class MeWelcomeController extends Controller { @tracked isSubmitting = false; @tracked showSuccessDialog = false; passwordValidations = { password: [ validatePresence({presence: true, message: 'Enter the new password.'}), validateLength({min: 5, message: 'The password should be 5 characters or more.'}) ], password_confirmation: [ validateConfirmation({on: 'password', message: 'The password do not match.'}) ] }; @action submitAction(model, isValid) { if (!isValid) { return; } const passwords = { password: model.password, password_confirmation: model.password_confirmation, temp_token: this.session.tempLoginToken }; this.isSubmitting = true; return this.ajax.request(`person/${this.session.userId}/password`, {method: 'PATCH', data: passwords}) .then(() => { this.session.tempLoginToken = null; this.session.isWelcome = false; this.showSuccessDialog = true; }).catch((response) => this.house.handleErrorResponse(response)) .finally(() => this.isSubmitting = false); } @action closeAction() { this.transitionToRoute('me.homepage'); } }
JavaScript
class CalciteActionGroup { constructor() { // -------------------------------------------------------------------------- // // Properties // // -------------------------------------------------------------------------- /** * Indicates whether widget is expanded. */ this.expanded = false; /** * Indicates the horizontal, vertical, or grid layout of the component. */ this.layout = "vertical"; /** * Opens the action menu. */ this.menuOpen = false; // -------------------------------------------------------------------------- // // Private Methods // // -------------------------------------------------------------------------- this.setMenuOpen = (event) => { this.menuOpen = !!event.detail; }; } expandedHandler() { this.menuOpen = false; } // -------------------------------------------------------------------------- // // Component Methods // // -------------------------------------------------------------------------- renderTooltip() { const { el } = this; const hasTooltip = getSlotted(el, SLOTS.menuTooltip); return hasTooltip ? h("slot", { name: SLOTS.menuTooltip, slot: ACTION_MENU_SLOTS.tooltip }) : null; } renderMenu() { const { el, expanded, intlMore, menuOpen } = this; const hasMenuItems = getSlotted(el, SLOTS.menuActions); return hasMenuItems ? (h("calcite-action-menu", { expanded: expanded, flipPlacements: ["left", "right"], label: intlMore || TEXT.more, onCalciteActionMenuOpenChange: this.setMenuOpen, open: menuOpen, placement: "leading-start" }, h("calcite-action", { icon: ICONS.menu, slot: ACTION_MENU_SLOTS.trigger, text: intlMore || TEXT.more, textEnabled: expanded }), h("slot", { name: SLOTS.menuActions }), this.renderTooltip())) : null; } render() { return (h(Fragment, null, h("slot", null), this.renderMenu())); } static get is() { return "calcite-action-group"; } static get encapsulation() { return "shadow"; } static get originalStyleUrls() { return { "$": ["calcite-action-group.scss"] }; } static get styleUrls() { return { "$": ["calcite-action-group.css"] }; } static get properties() { return { "expanded": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Indicates whether widget is expanded." }, "attribute": "expanded", "reflect": true, "defaultValue": "false" }, "layout": { "type": "string", "mutable": false, "complexType": { "original": "Layout", "resolved": "\"grid\" | \"horizontal\" | \"vertical\"", "references": { "Layout": { "location": "import", "path": "../interfaces" } } }, "required": false, "optional": false, "docs": { "tags": [], "text": "Indicates the horizontal, vertical, or grid layout of the component." }, "attribute": "layout", "reflect": true, "defaultValue": "\"vertical\"" }, "columns": { "type": "number", "mutable": false, "complexType": { "original": "Columns", "resolved": "1 | 2 | 3 | 4 | 5 | 6", "references": { "Columns": { "location": "import", "path": "../interfaces" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Indicates number of columns." }, "attribute": "columns", "reflect": true }, "intlMore": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Text string for the actions menu." }, "attribute": "intl-more", "reflect": false }, "menuOpen": { "type": "boolean", "mutable": true, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Opens the action menu." }, "attribute": "menu-open", "reflect": true, "defaultValue": "false" } }; } static get elementRef() { return "el"; } static get watchers() { return [{ "propName": "expanded", "methodName": "expandedHandler" }]; } }
JavaScript
class ItransTable { constructor() { /** * Array of rows containing itrans to Unicode mapping. Each row * is a array of items that drive the input to output conversion. */ this.itransRows = []; /** all the column titles representing languages */ this.languages = []; /** [column title] -> index of column, to access items in each itransRows[i] array */ this.columnIndex = {}; /** columnIndex frequently accessed items stored individually: */ this.inputColumnIndex = -1 ; // columnIndex of column TITLES.input this.typeColumnIndex = -1 ; // columnIndex of column TITLES.type this.nameColumnIndex = -1 ; // columnIndex of column TITLES.unicodeName /** RegExp(): all the itrans input codes - k ka etc including languages, unicode names */ this.itransRe = undefined; /** RegExp(): all the itrans language on/off codes #sanskrit ## etc */ this.languagesRe = undefined; /** RegExp(): all the itrans input codes that are Unicode names {DDHA} etc */ this.namesRe = undefined; /** * Dictionary to map all input codes to table row index. * Uses Map() derived class to only allow unique keys - provides a setIfUnset() call * which only allows a single .set() operation per key, will throw Error otherwise. * The input codes here include all non-empty TITLES.input column entries (k kh etc), * and the BRACES wrapped TITLES.name column entries ({DDHA}, {NUKTA}, etc). */ // this.allInputRowIndex = new UniqueKeyMap(); this.allInputRowIndex = new Map(); } /** * Functions to provide access to individual columns for a given row of itrans data, * each itransRow[i] entry which is an array. */ rowInput(row) { return row[this.inputColumnIndex]; } rowType(row) { return row[this.typeColumnIndex]; } rowName(row) { return row[this.nameColumnIndex]; } rowLanguage(row, name) { return row[this.columnIndex[name]]; } isLanguage(language) { return language && this.languages.indexOf(language) >= 0; } /** * Returns the row that corresponds to the given unicode name. * @param {string} name Unicode name * @returns {array} The row that matches this name if present. */ getRowForName(name) { const wrappedName = BRACES.wrap(name); const rowIndex = this.allInputRowIndex.get(wrappedName); const row = rowIndex >= 0 && this.itransRows[rowIndex]; return row; } /** * Returns the dependent vowel version of the given unicode vowel name. * Example: ('II') -> 'DV-II' * @param {string} name Unicode name (a vowel) to be converted. * @returns {string} The dependent vowel variation of the vowel name. */ getDependentVowelName(name) { const dvCodeName = DEPENDENT_VOWEL_PREFIX + name; return dvCodeName; } /** * Prepares and loads required tables for the conversion to be done. * @param {string} tsvString Tab-Separated-Values representing the table. * Table size is usually small: 300 rows (== each itrans code), * and 10 columns (== each language), but larger tables with 1000+ rows * should not be a problem even for interative web browser execution. */ load(tsvString) { const rows = tsvString.split(/\r?\n/); const rowsLen = rows.length; let columnNames; let columnNamesLength = 0; let columnIndex; this.languages = []; for (let i = 0; i < rowsLen; i++) { let rowString = rows[i]; // skip empty rows if (BLANK_RE.test(rowString)) { continue; } const columns = rowString.split('\t'); // Keep looping until we see title row, skipping rows until then if (!columnIndex) { columnIndex = getTitleColumns(columns); if (columnIndex) { columnNames= Object.keys(columnIndex); columnNamesLength = columnNames.length; columnNames.forEach(name => { if (isLanguageWord(name)) { this.languages.push(name); } }); } } else { // We have seen header row, all subsequent rows are itrans data we need to collect const row = []; columnNames.forEach(name => { const index = columnIndex[name]; let item = (index !== undefined) && columns[index]; if (index === undefined) { throw Error('Internal error undefined column ' + name); } if (item === undefined) { let rowNum = i + 1; const msg = 'itrans: Warning: Row ' + rowNum + ' Column ' + rowString + ' missing name ' + name + ' at column number ' + index; console.log(msg); item = ''; } row[index] = item.trim(); // spaces not allowed in itrans spreadsheet }); this.itransRows.push(row); } } this.columnIndex = columnIndex; if (!this.itransRows.length) { throw Error('No data in spreadsheet, found 0 itrans rows.'); } console.log('itrans: Loaded table rows, count: ', this.itransRows.length); //console.log(' itrans: Loaded table[0] ', this.itransRows[0]); console.log('itrans: Example row table[62] ', this.itransRows[62]); //console.log(' itrans: Example row table[122] ', this.itransRows[122]); // Prepare all data structures necessary for mapping input to Unicode. setupTablesAndMaps.call(this); expandLanguageData.call(this); //console.log('itransRe ', this.itransRe); return this; } /** * Match the next word in the input to the input itrans codes, and return the matched * characters and ItransTable row index. * * @param {string} current This is a line or word or syllable to match. * @param {RegExp} inputRe Use this RegExp to match the start of the current string. * @returns {object} {matched: string matched, row: itrans row data } * matched: is in the portion of the current string matched. * row: is the row at itransRows[index] */ matchRe(current, inputRe) { let row; let index = -1; let matched = inputRe.exec(current); if (matched) { const name = matched[1]; // first group that matched, which is the itrans code matched = matched[0]; // whole pattern matched, this may have trailing spaces matched index = this.allInputRowIndex.get(name); row = this.itransRows[index]; console.assert(index >= 0, 'Found a itrans code match, but it is missing from map', matched); } return {matched, row}; } }
JavaScript
class FetchError extends Error { constructor(errorId, message) { super(message); this.errorId = errorId; } }
JavaScript
class RegionManagerHelper { _regionManager; _regionName; _model; _regionSettings; constructor( regionName, regionManager, model, regionSettings ) { this._regionManager = regionManager; this._regionName = regionName; this._model = model; this._regionSettings = regionSettings; } init() { this.addToRegion(); if (this._regionManager.shouldPopoutFromRegion(this._regionName, this._model.modelId)) { this.popout(); } } addToRegion() { this._regionManager.addToRegion(this._regionName, this._model); } removeFromRegion(){ this._regionManager.removeFromRegion(this._regionName, this._model); } popout(onExternallyRemovedCallback) { this._regionManager.removeFromRegion(this._regionName, this._model); this._regionManager.addToRegion( RegionNames.popout, this._model, { onExternallyRemovedCallback: () => { // if the popout is closed, we add it back into the initial region this._regionManager.addToRegion(this._regionName, this._model, null, true); if(onExternallyRemovedCallback) { onExternallyRemovedCallback(); } }, regionSettings: this._regionSettings }, true ); } }
JavaScript
class Tracker { constructor() { debug("Initialize Tracker class") this.trackers = [] } /** * Register the tracker Instance to track. * Each tracker must be initialize before register to the tracker * @example * const tracker = new Tracker() * const gaTracker = new GATracker({trackerId: "hello-tracker"}) * tracker.registerTracker(gaTracker) * // with this the gaTracker event handler will be fired everytime * // the tracker got an event * @param {BaseTracker} trackerInstance the tracker to be tracked */ registerTracker(trackerInstance) { debug("pushing %o tracker to main tracker", trackerInstance) this.trackers.push(trackerInstance) } /** * pass track page view parameter to every registeredTracker * @param {String} url the url to track * @param {String} path the path to track * @param {Object} properties the additional properties object to be passed to trackers */ trackPageView(url, path, properties = {}) { const obj = { url, path, properties } debug("track page view for object %0", obj) this.trackers.forEach( t => t.trackPageView && t.trackPageView(url, path, properties) ) } /** * pass identify user parameter to every registered tracker * @param {Object} profile the profile object that will be passed through `mapUserIdentity` and `mapUserProfile` for each tracker instance. */ identifyUser(profile) { debug("identify user %O", profile) this.trackers.forEach(t => t.identifyUser && t.identifyUser(profile)) } /** * pass identify user on the amplitude only * @param {Object} profile the profile object that will be passed through `mapUserIdentity` and `mapUserProfile` for only amplitude tracker instance. */ identifyAmplitude(profile) { debug("identify amplitude user %O", profile) this.trackers.forEach( t => t.identifyAmplitude && t.identifyAmplitude(profile) ) } /** * pass track event parameter to every registered tracker * @param {String} eventName the event name * @param {Object} eventProperties the event properties object to be passed to trackers */ trackEvent(eventName, eventProperties) { debug("track event name:%s, withProp:%o", eventName, eventProperties) this.trackers.forEach( t => t.trackEvent && t.trackEvent(eventName, eventProperties) ) } /** * pass alias user parameter to every registered tracker * @param {String} alias the alias to define alias of user */ setAliasUser(alias) { debug("set alias user with name:%s", alias) this.trackers.forEach(t => t.setAliasUser && t.setAliasUser(alias)) } /** * trigger logout method on each trackers */ logout() { debug("=== RentSpree tracker logout method running... ===") this.trackers.forEach(t => t.logout && t.logout()) } }
JavaScript
class MicroParser { _start(txt) { this._txt = txt; this._pos = 0; this._c = null; this._p = null; } // Function to get the next char and adjust the internal pointer _next() { if (this._pos < this._txt.length) { this._p = this._c; this._c = this._txt[this._pos]; this._pos++; return true; } this._c = null; return false; } /** * Function that eats the blank characters */ _eatblanks() { while ([ ' ', '\t', '\n', '\r' ].indexOf(this._c) >= 0) { this._next(); } } /** * Obtains an identifier to act as the name of an attribute, class or id * @returns {String} the name of the attribute (null if error) */ _getAttr() { let chars = /[a-zA-Z]/; let charsEx = /[a-zA-Z0-9_-]/; // Skip blanks this._eatblanks(); if (!chars.test(this._c)) { return null; } let attr = this._c; while (this._next() && charsEx.test(this._c)) { attr += this._c; } // Skip blanks this._eatblanks(); return attr; } /** * Reads a string inside double quotes (or any of character that may enclose the string; the first one found is used) * @returns {String} the string value of the string */ _getString() { let str = ""; let dchar = this._c; // Start skipping the beggining string character while (this._next()) { if ((this._c === dchar) && (this._p !== "\\")) { break; } str += this._c; } // If no quote has been closed the whole file will be eaten; so inform the user at this place if (this._c === null) { this._syntaxError("unclosed quote"); } // Skip the ending string character this._next(); return str; } /** * * @returns {String} the value of the attribute (null if "null" keyword is found); blank if no value is found */ _getValue() { let value = ""; this._eatblanks(); switch (this._c) { case '"': case "'": value = this._getString(); break; default: while ([ ',', ')', ' ', '\t' ].indexOf(this._c) < 0) { value += this._c; if (!this._next()) { return value; } } value = value.trim(); // The special value if (value === "null") { value = null; } break; } this._eatblanks(); return value; } _syntaxError(x) { console.error(`syntax error near ${this._pos} (${this._c}): ${x}`); return null; } /** * Function that parses the "jade-like" string and returns the object structure * @param {*} txt - the string to parse * @returns {*} the object structure */ parse(txt) { this._start(txt); let results = []; while (true) { let attrs = {}; this._next(); // Get the tag name let tag = this._getAttr(); if (tag === null) { tag = "div"; } // Get the ID let id = null; if (this._c === '#') { this._next(); id = this._getAttr(); if (id === null) { return this._syntaxError("invalid ID"); } } // Get the list of classes let classes = []; while (this._c === '.') { this._next(); let c_class = this._getAttr(); if (c_class === null) { return this._syntaxError("unexpected class"); } classes.push(c_class); } // Get the attributes if (this._c === '(') { this._next(); while (true) { let attr = this._getAttr(); if (attr === null) { return this._syntaxError("unexpected attribute"); } this._eatblanks(); let value = null; if (this._c === '=') { this._next(); this._eatblanks(); value = this._getValue(); } attrs[attr] = value; if (this._c === ')') { break; } if (this._c !== ',') { return this._syntaxError("unexpected character"); } this._next(); } if (this._c !== ')') { return this._syntaxError("expected )"); } this._next(); } this._eatblanks(); results.push({ tag: tag, id: id, classes: classes, attrs: attrs }); if (this._c === null) { break; } if (this._c !== '>') { return this._syntaxError("expected > or EOF"); } } return results; } }
JavaScript
class DependencyGraph { constructor() { /** * A dictionary of all unique nodes in the entire graph */ this.nodes = {}; this.onchangeEmitter = new eventemitter3_1.EventEmitter(); } /** * Add a node to the graph. */ addOrReplace(key, dependencies) { var _a; //sort the dependencies dependencies = (_a = dependencies === null || dependencies === void 0 ? void 0 : dependencies.sort()) !== null && _a !== void 0 ? _a : []; let existingNode = this.nodes[key]; //dispose the existing node existingNode === null || existingNode === void 0 ? void 0 : existingNode.dispose(); //create a new dependency node let node = new Node(key, dependencies, this); this.nodes[key] = node; this.onchangeEmitter.emit(key, key); } /** * Add a new dependency to an existing node (or create a new node if the node doesn't exist */ addDependency(key, dependencyKey) { let existingNode = this.nodes[key]; if (existingNode) { let dependencies = existingNode.dependencies.includes(dependencyKey) ? existingNode.dependencies : [dependencyKey, ...existingNode.dependencies]; this.addOrReplace(key, dependencies); } else { this.addOrReplace(key, [dependencyKey]); } } /** * Remove a dependency from an existing node. * Do nothing if the node does not have that dependency. * Do nothing if that node does not exist */ removeDependency(key, dependencyKey) { var _a; let existingNode = this.nodes[key]; let idx = ((_a = existingNode === null || existingNode === void 0 ? void 0 : existingNode.dependencies) !== null && _a !== void 0 ? _a : []).indexOf(dependencyKey); if (existingNode && idx > -1) { existingNode.dependencies.splice(idx, 1); this.addOrReplace(key, existingNode.dependencies); } } /** * Get a list of the dependencies for the given key, recursively. * @param key the key for which to get the dependencies * @param exclude a list of keys to exclude from traversal. Anytime one of these nodes is encountered, it is skipped. */ getAllDependencies(key, exclude) { var _a, _b; return (_b = (_a = this.nodes[key]) === null || _a === void 0 ? void 0 : _a.getAllDependencies(exclude)) !== null && _b !== void 0 ? _b : []; } /** * Remove the item. This will emit an onchange event for all dependent nodes */ remove(key) { delete this.nodes[key]; this.onchangeEmitter.emit(key, key); } /** * Emit event that this item has changed */ emit(key) { this.onchangeEmitter.emit(key, key); } /** * Listen for any changes to dependencies with the given key. * @param emitImmediately if true, the handler will be called once immediately. */ onchange(key, handler, emitImmediately = false) { this.onchangeEmitter.on(key, handler); if (emitImmediately) { this.onchangeEmitter.emit(key, key); } return () => { this.onchangeEmitter.off(key, handler); }; } dispose() { for (let key in this.nodes) { let node = this.nodes[key]; node.dispose(); } this.onchangeEmitter.removeAllListeners(); } }
JavaScript
class MappingList { constructor() { this._array = []; this._sorted = true; // Serves as infimum this._last = { generatedLine: -1, generatedColumn: 0 }; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ unsortedForEach(callback, thisArg) { this._array.forEach(callback, thisArg); }; /** * Add the given source mapping. * * @param {Object} mapping */ add(mapping) { if (generatedPositionAfter(this._last, mapping)) { this._last = mapping; this._array.push(mapping); } else { this._sorted = false; this._array.push(mapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ toArray() { if (!this._sorted) { this._array.sort(compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; } }
JavaScript
class Endpoint { constructor(client, clientID, connectionID) { this.client = client; this.clientID = clientID; this.connectionID = connectionID; } chainId() { return this.client.chainId; } async getLatestCommit() { return this.client.getCommit(); } // returns all packets (auto-paginates, so be careful about not setting a minHeight) async querySentPackets({ minHeight, maxHeight, } = {}) { let query = `send_packet.packet_connection='${this.connectionID}'`; if (minHeight) { query = `${query} AND tx.height>=${minHeight}`; } if (maxHeight) { query = `${query} AND tx.height<=${maxHeight}`; } const search = await this.client.tm.txSearchAll({ query }); const resultsNested = search.txs.map(({ hash, height, result }) => { const parsedLogs = stargate_1.parseRawLog(result.log); // we accept message.sender (cosmos-sdk) and message.signer (x/wasm) let sender = ''; try { sender = launchpad_1.logs.findAttribute(parsedLogs, 'message', 'sender').value; } catch (_a) { try { sender = launchpad_1.logs.findAttribute(parsedLogs, 'message', 'signer').value; } catch (_b) { this.client.logger.warn(`No message.sender nor message.signer in tx ${encoding_1.toHex(hash)}`); } } return utils_1.parsePacketsFromLogs(parsedLogs).map((packet) => ({ packet, height, sender, })); }); return [].concat(...resultsNested); } // returns all acks (auto-paginates, so be careful about not setting a minHeight) async queryWrittenAcks({ minHeight, maxHeight, } = {}) { let query = `write_acknowledgement.packet_connection='${this.connectionID}'`; if (minHeight) { query = `${query} AND tx.height>=${minHeight}`; } if (maxHeight) { query = `${query} AND tx.height<=${maxHeight}`; } const search = await this.client.tm.txSearchAll({ query }); const resultsNested = search.txs.map(({ height, result }) => { const parsedLogs = stargate_1.parseRawLog(result.log); // const sender = logs.findAttribute(parsedLogs, 'message', 'sender').value; return utils_1.parseAcksFromLogs(parsedLogs).map((ack) => (Object.assign({ height }, ack))); }); return [].concat(...resultsNested); } }
JavaScript
class RepositoryList extends React.PureComponent { /** * Render the RepositoryList component */ render() { return <section className="RepositoryList"> <h1>RepositoryList</h1> </section>; } }
JavaScript
class Instances { async get () { const instances = [{ title: 'Nordic photo collection site', description: 'The site where we collection photos.' }, { title: 'Nordic photo collection site', description: 'The site where we collection photos.' }, { title: 'Nordic photo collection site', description: 'The site where we collection photos.' }, { title: 'Nordic photo collection site', description: 'The site where we collection photos.' }, { title: 'Nordic photo collection site', description: 'The site where we collection photos.' }, { title: 'Nordic photo collection site', description: 'The site where we collection photos.' }, { title: 'Nordic photo collection site', description: 'The site where we collection photos.' }, { title: 'Nordic photo collection site', description: 'The site where we collection photos.' }] return instances } }
JavaScript
class AcceptOrRejectChanges { static async Run() { try { let source = new comparison_cloud.FileInfo(); source.filePath = "source_files/word/source.docx"; let target = new comparison_cloud.FileInfo(); target.filePath = "target_files/word/target.docx"; let options = new comparison_cloud.UpdatesOptions(); options.sourceFile = source; options.targetFiles = [target]; options.outputPath = "output/result.docx"; let changes = await compareApi.postChanges(new comparison_cloud.PostChangesRequest(options)); changes.forEach(change => { change.comparisonAction = comparison_cloud.ChangeInfo.ComparisonActionEnum.Reject; }); changes[0].comparisonAction = comparison_cloud.ChangeInfo.ComparisonActionEnum.Accept; options.changes = changes; let response = await compareApi.putChangesDocument(new comparison_cloud.PutChangesDocumentRequest(options)); console.log("Output file link: " + response.href); } catch (error) { console.log(error.message); } } }
JavaScript
class Cam { constructor() { // need eventhandling to send "cam_moved" event THREE.EventDispatcher.prototype.apply(this); // booleans needed by the controller to determine what to do this.is_tweening = false; this.is_in_close_view = false; this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000); // camera rotation arc, we'll use that amount for vertical values instead of horizontal ones like bodies do this.circle = new Circle(1000, 0, -0.9); // static variable so we can always look-at the origin point without having to create new Vectors this.ORIGIN = new THREE.Vector3(0, 0, 0); // those two are needed for tweening this.current_view_target = this.ORIGIN; this.new_view_target = null; this.scroll(2.25); } /** * Moves the camera in an arc vertical to the scene. Allows us to move between overview and side-view. * Capped at -1.5 (side-view) and 0 (top view) * @param amount integer determining scroll amount */ scroll(amount) { amount = amount * -1; // avoid gimbal lock problems // also, we don't need to scroll that far, so why not just limit it if (this.circle.current >= 0 && amount > 0) return; else if (this.circle.current <= -1.5 && amount < 0) return; else if (this.is_tweening || this.is_in_close_view) return; var point = this.circle.get_next(amount * 0.1); this.camera.position.z = point.x; //!! this.camera.position.y = point.y; this.camera.lookAt(this.current_view_target); // dispatch change message this.dispatchEvent({ type: "cam_moved", info: this }); } /** * * Moves the camera to a given body by tweening it * * @param object * @param scene * @returns Promise resolves once tweening finished, rejects if cam is already moving */ lock_on(object, scene) { var deferred = new Deferred(); // abort if cam is already moving if (this.is_tweening) { console.warn("#Cam: Can't start new movement, already tweening"); deferred.reject(); return deferred.promise; } this.new_view_target = object.mesh.position; // execute tweening var p = this.tween( this.camera.position.clone(), new THREE.Vector3( object.mesh.position.x, object.mesh.position.y, object.info.size * 3 ), scene ); p.then(function () { this.is_in_close_view = true; deferred.resolve(); }.bind(this)); return deferred.promise; } /** * * Opposite of lock_on, see documentation for that * * @param scene * @returns promise */ remove_lock(scene) { var deferred = new Deferred(); // abort if cam is already moving if (this.is_tweening) { console.warn("#Cam: Can't start new movement, already tweening"); deferred.reject(); return deferred.promise; } this.new_view_target = this.ORIGIN; // cheap trick: we get the original position by asking for the current position in the circle :) var old = this.circle.get_next(0); //execute tween var p = this.tween( this.camera.position.clone(), new THREE.Vector3(0, old.y, old.x), scene ); p.then(function () { this.is_in_close_view = false; deferred.resolve(); }.bind(this)); return deferred.promise; } /** * * Moves the camera between two points, performing a move every time the scene updates * * @param start * @param stop * @param scene * @returns promise - resolves when tweening is done * @dispatch "cam_moved" everytime an update is performed so the bodies text can face the camera again */ tween(start, stop, scene) { var deferred = new Deferred(); var frames = 60 * 1; var i = 0; this.is_tweening = true; // generate inbetween-points for translation var steps = new THREE.Vector3( (stop.x - start.x) / 60, (stop.y - start.y) / 60, (stop.z - start.z) / 60 ); // generate inbetween-points for rotation by creating a second camera and measuring it's rotation, // calculating intermediate points based on it's eventual rotation. // TODO: kinda needlessly complicated, replace once I find a better way to tween rotation var test_camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 ); test_camera.position.x = stop.x; test_camera.position.y = stop.y; test_camera.position.z = stop.z; test_camera.lookAt(this.new_view_target); var rotation_steps = new THREE.Euler( (test_camera.rotation.x - this.camera.rotation.x) / 60, (test_camera.rotation.y - this.camera.rotation.y) / 60, (test_camera.rotation.z - this.camera.rotation.z) / 60 ); // the actual tweening function. changes rotation and position each frame var move_tween_func = function () { i++; // tween movement this.camera.position.x += steps.x; this.camera.position.y += steps.y; this.camera.position.z += steps.z; // tween rotation this.camera.rotation.set( this.camera.rotation.x + rotation_steps.x, this.camera.rotation.y + rotation_steps.y, this.camera.rotation.z + rotation_steps.z ); // dispatch change message this.dispatchEvent({ type: "cam_moved", info: this }); // when done if (i >= frames) { scene.removeEventListener("scene_updated", move_tween_func); this.current_view_target = this.new_view_target; this.new_view_target = null; this.is_tweening = false; deferred.resolve(); } }.bind(this); scene.addEventListener("scene_updated", move_tween_func); return deferred.promise; } }
JavaScript
class OpcodeBuffer { /** * Constructor. */ constructor() { this.buffer = new ArrayBuffer(4096); this.view = new DataView(this.buffer); this.byteIndex = 0; } /** * Gets the byte length. * * @return {number} byte length. */ get byteLength() { return this.byteIndex; } /** * Save opcodes. * * @return {Uint8Array} opcode list. */ save() { return new Uint8Array(this.buffer, 0, this.byteLength); } /** * Put byte. * * @param {number} value byte value. */ putByte(value) { this.view.setUint8(this.byteIndex, value); this.byteIndex++; } /** * Put instruction. * * @param {number} value instruction value. */ put(value) { this.view.setUint16(this.byteIndex, value, false); this.byteIndex += 2; } /** * Put instruction with address. * * @param {TokenIterator} it token iterator. * @param {Object} sections address list. * @param {number} opcode opcode value. */ putWithAddress(it, sections, opcode) { const p1 = it.expect(TokenName.NAME, TokenName.HEX); let address; if (p1.is(TokenName.NAME)) { address = sections[p1.value]; } else { address = p1.asAddress(); } this.put(opcode | address); } /** * Put instruction with the register X. * * @param {TokenIterator} it token iterator. * @param {number} opcode opcode value. */ putWithRegisterX(it, opcode) { const p1 = it.expect(TokenName.REGISTER); this.put(opcode | p1.asRegisterX()); } /** * Put instruction with register X and register Y. * * @param {TokenIterator} it token iterator. * @param {number} opcode opcode value. */ putWithRegisterXY(it, opcode) { const p1 = it.expect(TokenName.REGISTER); const p2 = it.expect(TokenNane.REGISTER); this.put(opcode | p1.asRegisterX() | p2.asRegisterY()); } /** * Put insturction with register X and hex or register Y. * * @param {TokenIterator} it token iterator. * @param {number} opcodeWithHex opcode with hex value. * @param {number} opcodeWithRegister opcode with register value. */ putWithRegisterXHexOrY(it, opcodeWithHex, opcodeWithRegister) { const p1 = it.expect(TokenName.REGISTER); const p2 = it.expect(TokenName.HEX, TokenName.REGISTER); if (p2.is(TokenName.HEX)) { this.put(opcodeWithHex | p1.asRegisterX() | p2.asByte()); } else { this.put(opcodeWithRegister | p1.asRegisterX() | p2.asRegisterY()); } } }
JavaScript
class KidsPage extends Component { state = { allKids: [], kidsOfUser: [], selectedKidId: '', }; // get user id from Login // connect to api - Get all kids for User // let id = 2; // const response = await fetch(`${baseURL}/:id/kids`); componentDidMount = async () => { try { console.log('in kids page...'); const response = await fetch(`${baseURL}/users/2/kids`); const kidsJson = await response.json(); console.log('kidsJson>>>', kidsJson); this.setState({ allKids: kidsJson }); } catch (error) { console.warn(error); } }; render() { console.log('props', this.props); const { fixed } = this.state; return ( <div> {/* NAVIGATION at top */} <Segment inverted textAlign="center" style={{ minHeight: 30, padding: '1em 0em', backgroundColor: 'green', }} vertical> <Menu fixed={fixed ? 'top' : null} inverted={!fixed} pointing={!fixed} secondary={!fixed} size="large"> <Container style={{ margin: 0 }}> <Menu.Item as={Link} to="/"> Home </Menu.Item> <Menu.Item as={Link} to="/kids" active> Kids </Menu.Item> <Menu.Item as={Link} to="/charities"> Charities </Menu.Item> <Menu.Item as={Link} to="/dashboard"> Donate Dashboard </Menu.Item> </Container> </Menu> </Segment> <div className="Kids"> <h1 style={{ marginTop: '40px' }}>Who is giving today?</h1> <div className="Kids-names" align="center"> {this.state.allKids.map(kid => ( <Kid key={kid.id} kid={kid} avatarImage={kid.avatarImage} name={kid.name} onSelect={this.props.onSelect} /> ))} <p className="message"> Add or Edit a child?{' '} <Link to="/charities">Create a new child</Link> </p> </div> </div> </div> ); } }
JavaScript
class CacheManager { /** * Path to cache log. * @member {string} */ #cacheLogPath = null; /** * Options. * @member {object} */ #options = {}; /** * Cache log file. * @member {Map} */ #cacheLog = null; /** * Default options. * @member {object} */ #defaultOptions = {basePath: null}; /** * Constructor. * * @param {string} cacheLogPath Path to the cache log. * @param {object} options Options. * * @return {CacheManager} */ constructor(cacheLogPath, options = {}) { this.#cacheLogPath = cacheLogPath; this.#options = merge.merge(this.#defaultOptions, options); this.loadMap(); } /** * Load the map from the source file. * * @return {CacheManager} */ loadMap() { if (!fs.existsSync(this.#cacheLogPath)) { debug(`No map file found at ${this.#cacheLogPath}.`); this.#cacheLog = new Map(); } else { debug(`Found map file at ${this.#cacheLogPath}.`); let serialised = fs.readFileSync(this.#cacheLogPath, 'utf8'); this.#cacheLog = new Map(JSON.parse(serialised)); } return this; } /** * Save the map. * * @return {CacheManager} */ saveMap() { let serialised = JSON.stringify(Array.from(this.#cacheLog.entries())); fsutils.mkdirRecurse(path.dirname(this.#cacheLogPath)); fs.writeFileSync(this.#cacheLogPath, serialised, 'utf8'); debug(`Wrote map file to disk.`); return this; } /** * See if we have a particular key. * * @param {string} key Key to test. * * @return {boolean} */ has(key) { return this.#cacheLog.has(key); } /** * Get a value for a key. * * @param {string} key Key to get value for. * * @return {mixed} */ get(key) { if (this.has(key)) { return this.#cacheLog.get(key); } return false; } /** * Set a value for a key. * * @param {string} key Key to set. * @param {mixed} val Value to set. * * @return {CacheManager} */ _set(key, val) { this.#cacheLog.set(key, val); return this; } /** * Clear all keys. * * @param {boolean} write Write out too? * * @return {CacheManager} */ clear(write = false) { this.#cacheLog.clear(); if (write) { this.saveMap; } return this; } /** * Do a cache check. * * @param {string} key Key to check. * @param {boolean} save Save immediately if changed. * @param {boolean} upd Update if necessary? * * @return {boolean} True means the file is new or was modified. */ check(key, save = false, upd = true) { // If we have no key, this is a new entry. if (!this.has(key)) { debug(`Key does not yet exist for asset: ${key}`); let fn = key; if (this.#options.basePath) { fn = path.join(this.#options.basePath, key); } if (!fs.existsSync(fn)) { throw new GAError(`No physical file found for cache key, yet cache key exists. File is: ${fn}.`); } let stats = fs.statSync(fn); let cd = { modified: stats.mtimeMs, size: stats.size }; this._set(key, cd); debug(`Created key for asset: ${key}`); if (save) { this.saveMap(); } return true; // We do have a key ... } else { debug(`Key already exists for asset: ${key}`); let fn = key; if (this.#options.basePath) { fn = path.join(this.#options.basePath, key); } let current = this.get(key); // We have a key and the file exists ... if (fs.existsSync(fn)) { let stats = fs.statSync(fn); // If the file has changed ... if (stats.mtimeMs > current.modified || stats.size != current.size) { debug(`Asset has expired for key: ${key}`); if (upd) { let cd = { modified: stats.mtimeMs, size: stats.size }; this._set(key, cd); debug(`Updated cache details for asset: ${key}`); if (save) { this.saveMap(); } } return true; // If the file has not changed ... } else { debug(`Asset has not changed for key: ${key}`); return false; } // We have a key but the file does not exist. } else { this.#cacheLog.delete(key); debug(`File for asset no longer exists so will delete cache: ${key}`); if (save) { this.saveMap(); } return false; } } } }
JavaScript
class SyncLoopHook { constructor(args) { this.args = args; this.taps = []; } tap(name, fn) { this.taps.push(fn); } call() { let args = Array.prototype.slice.call(arguments, 0, this.args.length); let loop = true; while (loop) { for (let i = 0; i < this.taps.length; i++) { let fn = this.taps[i]; let result = fn(...args); //如果返回值不是undefined就要继续循环 loop = typeof result != 'undefined'; if (loop) break; } } } }
JavaScript
class Player extends Phaser.Sprite { constructor({ game, x, y, key, frame }) { super(game, x, y, key); // Add walk animation this.walkAnimation = this.animations.add('walk', [2, 1, 3, 1], 10, true); this.animations.play('walk'); // Player this.isAlive = true; this.lives = 3; // Has landed on the ground. (For jumping) this.hasGrounded = false; this.wasDown = true; this.jumpPower = 0; this.jumpIndicator = new Phaser.Graphics(this.game, this.x, this.y); this.game.add.existing(this.jumpIndicator); // Add the sprite to the game. this.game.physics.enable(this, Phaser.Physics.ARCADE); this.game.add.existing(this); this.body.bounce.y = 0.1; this.anchor.setTo(0.5); } /** * Update the player in the gameloop */ update() { // Mouse input let mouse = this.game.input.activePointer; if(mouse.leftButton.isUp && this.wasDown){ this.wasDown = false; if(this.hasGrounded){ this.hasGrounded = false; this.body.velocity.y = -this.jumpPower; this.jumpPower = 0; } } if (mouse.leftButton.isDown) { this.wasDown = true; this.jumpPower = this.jumpPower + 50; // Set up velocity for the jump } else { this.jumpPower = 0; } // Update the jump indicator this.jumpIndicator.clear(); this.jumpIndicator.position.x = this.x; this.jumpIndicator.position.y = this.y; this.jumpIndicator.beginFill(0xFF6E40); this.jumpIndicator.drawCircle(0, 0, this.jumpPower); this.jumpIndicator.endFill(); if(mouse.rightButton.isDown){ this.frameName = 'fly.png'; } } }
JavaScript
class RequestOnlinePlayers extends IntentHandler { /** * This is invoked by the service provider when the AI * returns a matching response action the intent. */ handle() { let maxPlayers = this.getMessage().guild.member_count; let onlinePlayers = 0; _.each(this.getMessage().guild.members, member => { if (member.status !== 'offline') { onlinePlayers++; } }); app.envoyer.sendSuccess(this.getMessage(), `There are **:online** online people out of **:total** people on the server.`, { online: onlinePlayers, total: maxPlayers }); } }
JavaScript
class UserEdit extends Component { constructor(props) { super(props); this.state = { changePassword: false, f_name: this.props.f_name, l_name: this.props.l_name, oldPassword: null, newPassword: null, confirmPassword: null }; this.handleChange = this.handleChange.bind(this); this.changePassword = this.changePassword.bind(this); this.onUpdate = this.onUpdate.bind(this); } /**************************** Helper functions ****************************/ /** * Updates user information - password defaults to current password * if new password is not provided as argument. */ updateUser(password = this.props.currentPassword) { this.props.updateUser({ f_name: this.state.f_name, l_name: this.state.l_name, password: password }); } /** * Checks for any errors if a submission has been attempted and user password * is being changed. */ checkForError() { if (this.state.attemptedSubmit && this.state.changePassword) { if (!this.compareOldPasswords()) return ( <div className="alert alert-danger"> Old password does not match current password. </div> ); if (this.compareNewPasswords()) return ( <div className="alert alert-danger">New passwords do not match.</div> ); } return null; } /** * Compares the current password to the users input. */ compareOldPasswords() { if (this.state.oldPassword !== this.props.currentPassword) { return false; } return true; } /** * Compares the new password to its confirmation. */ compareNewPasswords() { if (this.state.newPassword !== this.state.confirmPassword) { return false; } return true; } /***************************** Core functions *****************************/ /** * Updates the users information with their new password or with original. * Returns the modal to view mode from edit mode. * Sets the attemptedSubmit state to true to detect errors if any are encountered. */ onUpdate() { this.setState({ attemptedSubmit: true }); if (this.state.changePassword) this.updateWithNewPassword(); else this.updateUser(); this.props.onReturn(); } /** * Updates the users information with their new password if conditions * are satisfied. */ updateWithNewPassword() { if (this.compareOldPasswords() && this.compareNewPasswords()) { this.updateUser(this.state.newPassword); } } /** * Handles input changes by assigning values to target names. Resets an * attempted submission in case user is attempting to correct an error. * @param e */ handleChange(e) { this.setState({ [e.target.name]: e.target.value, attemptedSubmit: false }); } /** * Toggles whether a user wants to change their password or not. */ changePassword() { this.setState({ changePassword: !this.state.changePassword }); } /**************************** Visual component ****************************/ render() { let errorMessage = this.checkForError(); return ( <div> <Form> {/* Name change */} <Form.Row> <Col> <Form.Label>Your first name</Form.Label> <Form.Control placeholder={this.props.f_name} name={'f_name'} onChange={this.handleChange} /> </Col> <Col> <Form.Label>Your last name</Form.Label> <Form.Control placeholder={this.props.l_name} name={'l_name'} onChange={this.handleChange} /> </Col> </Form.Row> </Form> {/* Password change */} <TogglePasswordChange toggle={this.changePassword} /> {errorMessage} <PasswordChange changePassword={this.state.changePassword} handleChange={this.handleChange} /> {/* Buttons */} <div className={'buttons'}> {/* Submit */} <div className={'submit-button'}> <SubmitButton handleChange={this.onUpdate} /> </div> {/* Return */} <div className={'return-button'}> <ReturnButton handleChange={this.props.onReturn} /> </div> </div> </div> ); } }
JavaScript
class I18n { /** * Creates an instance of I18n. * * @param {Object} [translations={}] - translations map */ constructor(translations = {}, lang = 'en-US') { this.translations = translations; this.lang = lang; } static getDecorateOutput(id, str) { return window.aoflDevtools && window.aoflDevtools.showI18nIds? `<span id="${id}" class="aofl-i18n-string" title="${id}" style="position: relative;">${str}<span style="font-size: 12px; color: #000; position: absolute; left: 0; bottom: 0; transform: translateY(60%); white-space: pre; background: yellow; line-height: 1; padding: 0 2px; font-weight: 400; z-index: 1;">${id.replace('<', '&lt;').replace('>', '&gt;')}</span></span>`: str; } /** * Lazy-load the translation map * * @param {String} lang * @return {Promise} */ getTranslationMap(lang) { if (typeof this.translations !== 'undefined' && typeof this.translations[lang] === 'function') { return this.translations[lang]() .then((langModule) => langModule.default); } return Promise.resolve({}); } /** * Language translation function. * * @param {String} id * @param {String} str * @return {String} */ async __(id, str) { const languageMap = await this.getTranslationMap(this.lang); let out = str; if (typeof languageMap !== 'undefined' && typeof languageMap[id] === 'object' && typeof languageMap[id].text === 'string') { out = languageMap[id].text; } return I18n.getDecorateOutput(id, out); } /** * Replace function. When invoked it will replace %r(number)% with the number matching the index * of the arguments passed to the _r function. * * @param {String} _str * @param {*} args * @return {String} */ async _r(_str, ...args) { let str = await Promise.resolve(_str); /* istanbul ignore next */ if (typeof str === 'object' && Array.isArray(str.strings) && str.strings.length) { str = str.strings[0]; } let matches = REPLACE_REGEX.exec(str); let pivot = 0; let out = ''; while (matches !== null) { const match = matches[0]; const argIndex = matches[1] - 1; const offset = match.length; out += str.slice(pivot, matches.index) + args[argIndex]; pivot = matches.index + offset; matches = REPLACE_REGEX.exec(str); } out += str.slice(pivot); return out; } /** * Conditional translation function. When invoked it finds the correct string based on the labels * specified in ...args. * * @param {*} id * @param {*} str * @param {*} args * @return {String} */ async _c(id, str, ...args) { let out = ''; const languageMap = await this.getTranslationMap(this.lang); /* istanbul ignore else */ if (typeof languageMap !== 'undefined' && typeof languageMap === 'object') { const idParts = []; for (let i = 0; i < args.length; i = i + 2) { const nextI = i + 1; /* istanbul ignore next */ if (nextI >= args.length) continue; let key = args[nextI]; if (typeof args[i][key] === 'undefined') { key = '%other%'; } idParts.push(key); } id += '-' + idParts.join('^^'); if (typeof languageMap[id] === 'object' && typeof languageMap[id].text === 'string') { str = languageMap[id].text; } } // when language map is not matched we still need to replace %c#% in the default text let matches = CONDITIONAL_REPLACE_REGEX.exec(str); let pivot = 0; while (matches !== null) { const match = matches[0]; const argIndex = (matches[1] - 1) * 2; let argCountIndex = args[argIndex + 1]; const offset = match.length; if (typeof args[argIndex][argCountIndex] === 'undefined') { argCountIndex = '%other%'; } out += str.slice(pivot, matches.index) + args[argIndex][argCountIndex]; pivot = matches.index + offset; matches = CONDITIONAL_REPLACE_REGEX.exec(str); } out += str.slice(pivot); return I18n.getDecorateOutput(id, out); } }
JavaScript
class OptParser { /* *@constructor */ constructor() { this.shortMap = {}; this.longMap = {}; } /* *@function addOption *@param {string} all arguments, 'boolean' | 'string' | 'list' for valueType *@return {boolean} whether succeed *@example op.addOption('t', 'target', 'list', 'pack target') */ addOption(shortName, longName, valueType, description) { if (!['boolean', 'string', 'list'].includes(valueType)) return false; var newOpt = { type: valueType, desc: description, name: longName }; this.shortMap[shortName] = newOpt; this.longMap[longName] = newOpt; return true; } /* *@function printHelp */ printHelp() { var name, opt, val; var slen = 0, llen = 0; for (name in this.shortMap) { opt = this.shortMap[name]; if (name.length > slen) slen = name.length; if (opt.name.length > llen) llen = opt.name.length; } var genStrN = (n) => { var ret = ''; while (n > 0) { ret += ' '; n--; } return ret; }; var padding; for (name in this.shortMap) { opt = this.shortMap[name]; padding = slen + llen - name.length - opt.name.length; console.log(`-${name},--${opt.name} ${genStrN(padding)} ${opt.desc || ''}`); } } /* *@function parseArgs *@param {array} args *@return {object} parsed result *@example op.parseArgs(['-t', 'portal']) */ parseArgs(args) { var i = 0; var arg, opt; var ret = {}; while (i < args.length) { arg = args[i]; i++; let k = 0; while (arg[k] === '-') k++; let argName = arg.substr(k); if (k === 1) { opt = this.shortMap[argName]; } else if (k === 2) { opt = this.longMap[argName]; } if (!opt) continue; if (opt.type === 'boolean') { ret[opt.name] = true; } else if (opt.type === 'string') { if (i >= args.length || args[i][0] === '-') { console.log(`\x1b[33mWarning: [${arg}] Missing argument\x1b[0m`); continue; } ret[opt.name] = args[i]; i++; } else if (opt.type === 'list' && i < args.length) { if (!ret[opt.name]) ret[opt.name] = []; ret[opt.name].push(args[i]); i++; } } return ret; } }
JavaScript
class Top { constructor() { this.version = require("./lib/version.js"); // command-line arguments let file = ''; let n = app.isPackaged ? 2 : 3; if (process.argv.length == n) { process.argv.forEach((val, index) => { // optional argument: use file as data source if (index == n - 1) { file = val; } }); } this.presetter = new Presetter(this); this.boxer = new Boxer(this, file); this.serverer = new Serverer(this); this.artifacter = new Artifacter(this); this.win = null; // created later } getVersion() { return this.version; } getPresetter() { return this.presetter; } getBoxer() { return this.boxer; } getServerer() { return this.serverer; } getArtifacter() { return this.artifacter; } getWindow() { return this.win; } }
JavaScript
class OpleidingPage { // constructor for used components constructor () { this.compOptionsList = new OptionsList(); this.compArticle = new Article(); this.compTechnologiesList = new TechnologiesList(); } // render the content async render () { return ` <div class="page page--opleiding container"> <div class="opleiding__intro"> <p><a href="https://www.arteveldehogeschool.be/opleidingen/graduaat/programmeren?wvideo=9xnjw678pi"><img src="https://embedwistia-a.akamaihd.net/deliveries/68858ab24ed17c9489fcc2533dc5f99470cb584e.jpg?image_play_button_size=2x&amp;image_crop_resized=960x540&amp;image_play_button=1&amp;image_play_button_color=000000e0"></a></p> <h1>Graduaat Programmeren</h1> <p>120 studiepunten, VDAB-traject mogelijk, Campus Mariakerke</p> <p>Tijdens het Graduaat Programmeren specialiseer je je in JavaScript, HTML, CSS, UI/UX en software engineering. Naast deze technische kant, leer je ook om creatief en commercieel te denken. Als programmeur creëer je namelijk niet alleen aantrekkelijke en functionele websites, maar werk je ook samen met heel wat bedrijven. Na deze opleiding kan je aan de slag als front-end developer, CMS Themer of full-stack JavaScript developer.</p> </div> <div class="opleiding__info"> <h2>Kies waar u meer over wil weten:</h2> <form id="info-selection" class="filter opleiding__info-form"> <select id="title" name="title" class="filter__item"> ${await this.compOptionsList.render()} </select> <button type="submit" class="filter__button">Lees dit artikel <i class="fas fa-book-reader no-borders"></i></button> </form> <div class="opleiding__info-content"> ${await this.compArticle.render()} </div> </div> <a href="https://www.pgm.gent/info/" target="_blank" class="d-flex justify-content-center opleiding__curriculum"> <p>Bekijk het curriculum <i class="fas fa-location-arrow no-borders"></i></p> </a> <div class="opleiding__technologies"> <ul class="row opleiding__technologies-list"> ${await this.compTechnologiesList.render()} </ul> </div> </div> `; } async afterRender () { // afterRender all components on the page this.compOptionsList.afterRender(); this.compArticle.afterRender(); this.compTechnologiesList.afterRender(); // Connect the listeners const selectionForm = document.getElementById('info-selection'); selectionForm.addEventListener(('submit'), (ev) => { ev.preventDefault(); /* eslint-disable no-undef */ const formData = new FormData(selectionForm); const selectedArticle = formData.get('title'); this.compArticle.replaceContent(selectedArticle); }); return this; } async mount () { // Before the rendering of the page // scroll to the top window.scrollTo(0, 0); return this; } async unmount () { // After leaving the page return this; } }
JavaScript
class Rect { constructor( x, y, width, height, fillStyle, ctx ) { this.x = x; this.y = y; this.width = width; this.height = height; this.ctx = ctx this.fillStyle = fillStyle } setFillStyle( color ) { this.fillStyle = color } fill() { this.ctx.fillStyle = this.fillStyle this.ctx.fillRect( this.x, this.y, this.width, this.height ); } stroke() { this.ctx.strokeRect( this.x, this.y, this.width, this.height ); } clear() { this.ctx.clearRect( this.x, this.y, this.width, this.height ); } }
JavaScript
class EditKitController extends ContainerController { /** * Constructor of EditKitController * @param {object} element default object * @param {object} history default object */ constructor(element, history) { super(element, history); this.model = this.setModel(JSON.parse(JSON.stringify(model))); // sets model this.model.user = DSUManager.getUser(); // sets user this.model.courier = DSUManager.getCourier(); // sets courier let state = this.History.getState(); // loads ID of kit from previous page this.id = typeof state !== "undefined" ? state.id : undefined; // loads ID of kit from previous page this.model.kit = getKit(this.id); this.on("closeModal", () => this.model.modal.opened = false); // saves kit with new data this.on("saveKit", async() => { this.model.kit.statusLabel = this.model.statusSelect.options[this.model.kit.status - 1].label; // stores status label await DSUManager.createKit(this.model.kit); showModal(this.model); }); // shows and hides datamatrix this.on("toggleDatamatrix", () => { if (this.model.isDatamatrixShown) { this.model.isDatamatrixShown = false; this.model.datamatrixLabel = "Show Datamatrix"; } else { this.model.isDatamatrixShown = true; this.model.datamatrixLabel = "Hide Datamatrix"; } }); } }
JavaScript
class Texture { constructor(gl, name, width, height, createTexture) { this.gl = gl; this.name = name; this.w = width; this.h = height; this._glTex = createTexture(gl); } bindTexture() { this.gl.bindTexture(this.gl.TEXTURE_2D, this._glTex); } passSize(anchor) { this.gl.uniform2f(anchor, this.w, this.h); } rawTexture() { return this._glTex; } }
JavaScript
class Person extends Component{ constructor(props) { super(props); this.inputElementRef = React.createRef() } static contextType = AuthContext; // Method for accessing context in React Class-based components. // It's managed by context API // const style = { // '@media (min-width: 500px)': { // default css media query in jsx // width: "450px", // } // }; componentDidMount() { // Both of methods are uses references to get focused on last element // this.inputElement.focus() this.inputElementRef.current.focus(); console.log(this.context.authenticated); } render() { console.log('[Person.js] rendering') return ( // <div className="Person" style={style}> //<div className={classes.Person}> // In react 16.2 was introduced React.Fragment, works like an Aux <React.Fragment> {this.context.authenticated ? <p>Authenticated</p> : <p>Please, log in!</p>} <p onClick={this.props.click}>I'm contain {this.props.name} name and {this.props.age} age!</p> <p>{this.props.children}</p> <input type="text" // ref={(inputEL) => {this.inputElement = inputEL}} ref={this.inputElementRef} onChange={this.props.changed} value={this.props.name}/> </React.Fragment> //</div> ) } }
JavaScript
class CmBlockNodeRenderer extends NodeRenderer { /** * @inheritDoc */ static get className() { return 'export.renderer/CmBlockNodeRenderer'; } /** * @return {Promise<Boolean>} */ willRender(node, configuration) { return Promise.resolve(node && node.is('BlockNode')); } /** * @return {Promise<String>} */ render(node, configuration) { if (!node || !configuration) { return Promise.resolve(''); } const promise = co(function*() { let result = yield configuration.renderer.renderComment('Block ' + node.name + ' start'); if (node.children.length) { result+= yield configuration.renderer.renderList(node.children, configuration); } else { result+= '<c:if test="${ not empty self.placementMap.' + node.name + '.items }">'; result+= '<cm:include self="${ self.placementMap.' + node.name + ' }" view="' + node.name + '"/>'; result+= '</c:if>'; } result+= yield configuration.renderer.renderComment('Block ' + node.name + ' end'); return result; }); return promise; } }
JavaScript
class Inhabitant { constructor ( name, gender, friends, say, biologicalSpecies ) { this.name = name; this.biologicalSpecies = biologicalSpecies; this.gender = gender; this.friends = friends; this.say = say } toString() { return `${this.say} I'm ${this.biologicalSpecies}! My name is ${this.name}, my gender is ${this.gender}, and I have friends: ${this.friends}.`; } }
JavaScript
class AppointmentMdl { constructor(data) { this.id = data.ID; this.userID = data.UserID; this.date = data.Date; this.serviceID = data.ServiceID; this.Service = data.Name; this.status = data.Status; this.placeID = data.PlaceID; } /** * [create is a function for add a new instance in the table(database] * @param {[Object]} obj [Add New object in table with body form] * @return {Promise} [Try to conect the data of the object in the table "Appointment"] */ static async create(obj) { let data; try { data = await db.create('Appointment', obj); } catch (e) { throw e; } return data; } /** * [findByDate Its a funcion try to search and show the Appointment register per date] * @param {[object]} date [Body date"Attribute the table] * @return {Promise} [Function to throw error affter catch] */ static async findByDate(date) { let data; try { data = await db.findByAttribute('Appointment', 'Date', date); } catch (e) { throw e; } return this.processData(data); } /** * [Its a funcion try to search and show the Appointment register per id of user] * @param {[Obejct]} UserId [Body.Id interger, key Attribute foreigh in the table ] * @return {Promise} [Function for tour ans search data UserId register in database] */ static async findByUserID(userID) { let data; try { data = await db.select(`SELECT A.*, B.Name FROM Appointment AS A JOIN Services AS B ON A.serviceID = B.ID WHERE userID = ${userID}`); } catch (e) { throw e; } return this.processData(data); } /** * [findByPlaceID Its a funcion try to search and show the Appointment register per id of place] * @param {[Obejct]} placeID [Key interget Attribute foreigh in the table to find] * @return {Promise} [Function for tour ans search data register place in database] */ static async findByPlaceID(placeID) { let data; try { data = await db.findByAttribute('Appointment', 'PlaceID', placeID); } catch (e) { throw e; } return this.processData(data); } /** * [update is a funtion that modify data in the objeto previusly create] * @param {[Object]} obj [recive the object of the class with changes to modify] * @param {[Obejct]} id [Bodi.Id its a integer, key value , identificador of every object] * @return {Promise} [Try to change the new data register modified] */ static async update(obj, appId) { let data; try { data = await db.update('Appointment', obj, appId); } catch (e) { throw e; } return data; } /** * [processData is a funcion for tour registers and show all] * @param {[Object]} data [Atrribute for tour the register in table Appointment ] * @return {[Array]} [Its a array that contain the register tour previusly] */ static processData(data) { const array = []; data.forEach((d) => { array.push(new AppointmentMdl(d)); }); return array; } }
JavaScript
class Verse { constructor(url, method = 'GET', payload = null, timeout = 5000, title = null, auth = {}, headers = []) { // check if url is actually object let targetURL = ''; if (typeof url == 'object') { Object.keys(url).forEach((k) => { this[k] = url[k]; }); this.CodeGreen = 200; this.CodeYellow = 404; } else { targetURL = url; // store in class this.title = title; this.timeout = timeout; this.url = targetURL; this.method = method; this.auth = auth; this.payload = payload; this.headers = headers; this.statusCode = null; this.response = null; this.statusText = null; this.responseText = null; this.colorKey = 'red'; this.timeElapsed = 0; } if (!this.title) { this.title = this.url; } this.hash = md5(this.title); this.cliResult = ''; verses.push(this); } }
JavaScript
class Router extends Component { componentDidMount() { this.hashListener = this.updateHash.bind(this); window.addEventListener("hashchange", this.hashListener); this.updateHash(); } componentWillUnmount() { window.removeEventListener("hashchange", this.hashListener); } updateHash() { this.setState({ hash: window.location.hash.substr(1), }); } render({ children }, { hash }) { if (!children.find) { // ugly fallback for older browsers -- TODO, should clean up return null; } // return first child that renders (meaning it has a matching route) for (let child of children) { if (child) { return child; } } return null; } }
JavaScript
class ScriptElements extends FRGatherer { /** @type {LH.Gatherer.GathererMeta<'DevtoolsLog'>} */ meta = { supportedModes: ['timespan', 'navigation'], dependencies: {DevtoolsLog: DevtoolsLog.symbol}, }; /** * @param {LH.Gatherer.FRTransitionalContext} context * @param {LH.Artifacts.NetworkRequest[]} networkRecords * @return {Promise<LH.Artifacts['ScriptElements']>} */ async _getArtifact(context, networkRecords) { const executionContext = context.driver.executionContext; const scripts = await executionContext.evaluate(collectAllScriptElements, { args: [], useIsolation: true, deps: [ pageFunctions.getNodeDetailsString, pageFunctions.getElementsInDocument, ], }); const scriptRecords = networkRecords .filter(record => record.resourceType === NetworkRequest.TYPES.Script) // Ignore records from OOPIFs .filter(record => !record.sessionId); for (let i = 0; i < scriptRecords.length; i++) { const record = scriptRecords[i]; const matchedScriptElement = scripts.find(script => script.src === record.url); if (!matchedScriptElement) { scripts.push({ type: null, src: record.url, id: null, async: false, defer: false, source: 'network', node: null, }); } } return scripts; } /** * @param {LH.Gatherer.FRTransitionalContext<'DevtoolsLog'>} context */ async getArtifact(context) { const devtoolsLog = context.dependencies.DevtoolsLog; const networkRecords = await NetworkRecords.request(devtoolsLog, context); return this._getArtifact(context, networkRecords); } /** * @param {LH.Gatherer.PassContext} passContext * @param {LH.Gatherer.LoadData} loadData */ async afterPass(passContext, loadData) { const networkRecords = loadData.networkRecords; return this._getArtifact({...passContext, dependencies: {}}, networkRecords); } }
JavaScript
class Invokable { /** * @param {Function} fn [required] function reference that is executed during * invokation * @param {String} name [required] required if function is anonymous * will override function name property * @param {Array} args [optional] arguments to be applied to the function * @param {Boolean} memoize [optional] when true, function calls are memoized */ constructor(fn, name = '', args = [], memoize = false) { if (!fn || typeof fn !== 'function') { throw 'Invokable must be instantiated with a function'; } if (fn.name === '' && name === '') { throw 'Invokable anonymous functions must have a name argument'; } if (!Array.isArray(args)) { throw 'Invokable arguments must be an array'; } if (typeof memoize !== 'boolean') { throw 'Invokable memoize argument must be boolean'; } this._name = name && name.length ? name : fn.name; this._fn = fn; this._args = args; this._memoize = memoize; if (this._memoize) { this.memoize(); } } /** * Executes a validation function against a subject and any predefined arguments * * @method invoke * @param {Any} subject the value to be validated * @return {Boolean} the result of the validation */ invoke(...subjects) { let fn = this._fn; let args = subjects.concat(this._args); if (this._memoize && this._memoizedFn) { fn = this._memoizedFn; args = [this._fn].concat(args); } return fn.apply(this, args); } /** * Create a private, non-enumerable and non-writable `_cache` property, as well * as a `_memoizedFn` property. Calling an `Invokable`'s `_memoizedFn` rather * than its `_fn` will cause the result to be stored in the `_cache`, keyed by * the function arguments. * * @method memoize */ memoize() { Object.defineProperty(this, '_cache', { value: {}, writable: false, configurable: true, enumerable: false }); const memoized = function(fn, ...args) { const key = args && args.length ? args[0] : 'none'; const cache = memoized.cache; if (cache[key]) { return cache[key]; } const result = fn.apply(fn, args); cache[key] = result; return result; }; memoized.cache = this._cache; this._memoizedFn = memoized; } /** * Remove the `_cache` property and `_memoizedFn`. Set `_memoize` to false * so that `_fn` is called. * @method dememoize */ dememoize() { delete this._cache; delete this._memoizedFn; this._memoize = false; } /** * Represent an Invokable as a string. * @method serialize * @return {String} a stringified JSON blob representing an * `Invokable` and its arguments */ serialize() { return JSON.stringify(this); } }
JavaScript
class HeaderButton extends PosComponent { constructor() { super(...arguments); this.state = useState({ label: 'Close' }); this.confirmed = null; } get translatedLabel() { return this.env._t(this.state.label); } onClick() { if (!this.confirmed) { this.state.label = 'Confirm'; this.confirmed = setTimeout(() => { this.state.label = 'Close'; this.confirmed = null; }, 2000); } else { this.trigger('close-pos'); } } }
JavaScript
class TemplateFactory { constructor(templateProxy) { this.templateProxy = templateProxy; this.instance = new TemplateConstructor(); } addElement(type, parentElem, data, eventCallback) { switch ('' + type) { case 'button': this.instance.setHtml(this.templateProxy.template.settings.button(data)) .setNode() .setInnerHtml() .setEvent('onclick', eventCallback) .appendOnParent(parentElem); break; case 'category': this.instance.setHtml(this.templateProxy.template.settings['category-selector'](data)) .setNode() .setInnerHtml() .toggleClass('article-headlines') .setEvent('onchange', eventCallback) .appendOnParent(parentElem); break; case 'checkbox': this.instance.setHtml(this.templateProxy.template.settings.sourceList.checkbox(data)) .setNode() .setInnerHtml() .setEvent('onclick', eventCallback) .appendOnParent(parentElem); break; case 'article': this.instance.setHtml(this.templateProxy.template.articles.itemList(data)) .setNode() .setInnerHtml() .setEvent('onclick', eventCallback) .appendOnParent(parentElem); break; default: } } cleanDOM(parentDom) { this.templateProxy.cleanParentDomList(parentDom); } getElemBySelector(selectName) { const suffixClass = '-selector'; return this.templateProxy.getSelectorValue(selectName, suffixClass); } }
JavaScript
class UserDataLiveUpdater { start() { this.listenToSocket(); } listenToSocket() { const socket = IoC.make('userUpdatesSocket'); socket.on('event', event => { this.handleEvent(event); }); } handleEvent(event) { const auth = IoC.make('auth'); if (!auth.isAuthenticated()) { return; } if (event.type === UserUpdatesSocket.EVENTS.TOKEN_RECEIVED) { this.updateTokensBalance(); } if (event.type === UserUpdatesSocket.EVENTS.FRIENDSHIP_RECEIVED) { this.updateReceivedFriendRequests(); } if (event.type === UserUpdatesSocket.EVENTS.FRIENDSHIP_ACCEPTED) { this.updateSentFriendRequests(); this.updateFriends(); } } updateTokensBalance() { /** @type {Authentication} */ const auth = IoC.make('auth'); // We update from the server instead of adding to the user's tokenBalance to be sure to // show the real amount auth.getUser().fill(['id', 'tokenBalance'], true); } updateReceivedFriendRequests() { /** @type {ReceivedFriendRequestRepository} */ const repo = IoC.make('receivedFriendRequestRepository'); repo.loadAll(['id'], true); } updateSentFriendRequests() { /** @type {SentFriendRequestRepository} */ const repo = IoC.make('sentFriendRequestRepository'); repo.loadAll(['id'], true); } updateFriends() { /** @type {Authentication} */ const auth = IoC.make('auth'); auth.getUser().loadFriends(['id'], true); } }
JavaScript
class Mesh { constructor(positionVector, rotationVector) { this.position = positionVector this.rotation = rotationVector this.vertices = [] } rotateMesh (rotationVector) { this.vertices.forEach(v => { let rotated = Mesh.rotateVertex(v, rotationVector.x, rotationVector.y, rotationVector.z) v.x = rotated.x v.y = rotated.y v.z = rotated.z }) } translateMesh (translationVector) { this.vertices.forEach(v => { v.x = v.x + translationVector.x v.y = v.y + translationVector.y v.z = v.z + translationVector.z }) } static rotateVertex (v, xAngle, yAngle, zAngle) { // matrix for euler order zxy let rm = { x1: cos(zAngle) * cos(yAngle), x2: cos(zAngle) * sin(yAngle) * sin(xAngle) - sin(zAngle) * cos(xAngle), x3: cos(zAngle) * sin(yAngle) * cos(xAngle) + sin(zAngle) * sin(xAngle), y1: sin(zAngle) * cos(yAngle), y2: sin(zAngle) * sin(yAngle) * sin(xAngle) + cos(zAngle) * cos(xAngle), y3: sin(zAngle) * sin(yAngle) * cos(xAngle) - cos(zAngle) * sin(xAngle), z1: sin(yAngle) * -1, z2: cos(yAngle) * sin(xAngle), z3: cos(yAngle) * cos(xAngle) } let vm = { x: v.x, y: v.y, z: v.z } let result = { x: 0, y: 0, z: 0 } result.x = rm.x1 * vm.x + rm.x2 * vm.y + rm.x3 * vm.z result.y = rm.y1 * vm.x + rm.y2 * vm.y + rm.y3 * vm.z result.z = rm.z1 * vm.x + rm.z2 * vm.y + rm.z3 * vm.z return createVector(result.x, result.y, result.z) } static rotateVertices (vertices, rotationVector) { vertices.forEach(v => { let rotated = Mesh.rotateVertex(v, rotationVector.x, rotationVector.y, rotationVector.y) v.x = rotated.x v.y = rotated.y v.z = rotated.z }) } static translateVertices (vertices, translationVector) { vertices.forEach(v => { v.x = v.x + translationVector.x v.y = v.y + translationVector.y v.z = v.z + translationVector.z }) } }
JavaScript
class Dictionary extends Array { constructor() { super(); } /** * Add an entry to the Dictionary. * * Will Error if Key already exists. * @param {T} Key - Value * @param {A} Value - Value * @memberof Dictionary * @instance */ Add(Key, Value) { if (this.ContainsKey(Key)) throw new Error( "ArgumentException: An element with the same key already exists" ); this.push({ Key, Value, }); } /** * Attempt to add an entry to the Dictionary * @param {T} Key * @param {A} Value * @memberof Dictionary * @instance * @returns {Boolean} - Was the Add command successfull */ TryAdd(Key, Value) { if (this.ContainsKey(Key)) return false; this.push({ Key, Value, }); return true; } /** * Replace Key's value with new Value * @param {T} key * @param {A} Value * @instance * @memberof Dictionary * @returns {boolean} - Was replace successful */ Replace(key, Value) { if (!this.ContainsKey(key)) return false; for (let object of this) { if (object.Key === key) { this[this.indexOf(object)].Value = Value; return true; } } return false; } /** * Clear the Dictionary * @instance * @memberof Dictionary */ Clear() { this.splice(0, this.length); } CheckCount(func) { if (func == null) return this.length; return this.filter(func).length; } /** * Check if a Key exists * @param {T} Key * @instance * @memberof Dictionary * @returns {boolean} - Key Found */ ContainsKey(Key) { for (let object of this) { if (object.Key === Key) return true; } return false; } /** * Check if a Value exists in the Dictionary * @param {A} Value * @instance * @memberof Dictionary * @returns {boolean} - Value Exists */ ContainsValue(Value) { for (let object of this) { if (object.Value === Value) return true; } return false; } /** * Get the Capacity * @deprecated * @instance * @memberof Dictionary */ EnsureCapacity() { return this.length; } /** * Remove an Item at a given Index * @param {number} iIndex * @instance * @memberof Dictionary */ RemoveAt(iIndex) { var vItem = this[iIndex]; if (vItem) { this.splice(iIndex, 1); } return vItem; } /** * Remove a Key. Will error if Key does not exist * @param {T} key * @instance * @memberof Dictionary * @returns {boolean} - Key Removed */ Remove(key) { if (!this.ContainsKey(key)) return false; for (let object of this) { if (object.Key === key) { this.RemoveAt(this.indexOf(object)); return true; } } return false; } /** * Attempt to remove a Key. * @memberof Dictionary * @instance * @param {T} key * @returns {boolean} - Key Removed */ TryRemove(key) { if (!this.ContainsKey(key)) return false; for (let object of this) { if (object.Key === key) { this.RemoveAt(this.indexOf(object)); return true; } } return false; } /** * Get the amount of items * @instance * @readonly * @memberof Dictionary */ get Count() { return this.length; } /** * Get a key's value * @param {T} key - Key * @param {Out<A>} out - Output Var * @returns {boolean} - Key Exists */ Get(key, out) { if (!this.ContainsKey(key)) return false; for (let object of this) { if (object.Key === key) { out.Out = object.Value; return true; } } return false; // How tf you manage that?? } /** * Generate a Dictionary from an Object using Key:Value Pairs * @param {Object} obj */ static ToDictionary(obj) { let Dict = new Dictionary(); for (let key in obj) { Dict.Add(key, obj[key]); } return Dict; } /** * Reduce Callback * @callback Dictionary.Reduce~callback * @param {*} [previousValue] * @param {*} [currentValue] * @param {number} [currentIndex] * @param {any[]} [array] * @returns {*} Returned Value will set to set previousValue */ /** * Reduce a Dictionary's values down * @param {Dictionary.Reduce~callback} callbackfn - Computation function * @param {*} InitialValue - Initial Value * @returns {*} * @instance * @memberof Dictionary */ Reduce(callbackfn, InitialValue) { if (this.length === 0) return 0; return this.reduce(callbackfn, InitialValue); } /** * @callback Dictionary.AddOrUpdate~callback * @param {T} Key - Current Key * @param {A} Value - Current Value * @returns {A} New Value */ /** * Adds a new Value at Key * * if Key exists, Updates Key * * if func is set, Programatically updates Key * @param {T} key * @param {A} value * @param {Dictionary.AddOrUpdate~callback} [func] * @returns {Boolean} Added * @instance * @memberof Dictionary */ AddOrUpdate(key, value, func) { if (!this.ContainsKey(key)) { if (this.TryAdd(key, value)) return value; return false; } if (func == null) { if (this.Replace(key, value)) return value; return false; } let oldValue = new Out(); this.Get(key, oldValue); let newValue = func(key, oldValue.Out); if (this.Replace(key, newValue)) return newValue; } /** * Attempt to get Value, Sets Value to Out. Returns Boolean valueExists * @param {A} value * @param {Out<A>} out * @returns {boolean} - Value Existed */ TryGetValue(value, out) { if (value == null) return false; if (!this.ContainsKey(value)) return false; if (out) this.Get(value, out); return true; } GetEnumerator() { return new (require("./Enumerator").Enumerator)(this); } }
JavaScript
class MetricsRequest { /** * Constructs a new <code>MetricsRequest</code>. * Metrics Request Body * @alias module:model/MetricsRequest */ constructor() { MetricsRequest.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>MetricsRequest</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/MetricsRequest} obj Optional instance to populate. * @return {module:model/MetricsRequest} The populated <code>MetricsRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new MetricsRequest(); if (data.hasOwnProperty('category')) { obj['category'] = Category.constructFromObject(data['category']); } if (data.hasOwnProperty('subcategory')) { obj['subcategory'] = Subcategory.constructFromObject(data['subcategory']); } } return obj; } }
JavaScript
class MySpriteText extends CGFobject { constructor(scene, text){ super(scene); this.text = text; this.texture = this.scene.textures['mySpriteTextTexture']; this.spriteSheet = new MySpriteSheet(this.scene, this.texture, 16, 16); this.board = new MyRectangle(this.scene, -this.text.length/2 -1, -0.5, -this.text.length/2, 0.5); } getCharacterPosition(character){ // Unicode // Supports all important characters: [a-z], [A-Z], [0-9], [!#$%/()=?.-,+-_;*^~\@'], [&lt;, &gt;, &quot;] return character.charCodeAt(0); } display(){ var cell; // For each char in text for(var i = 0; i < this.text.length; i++){ // Get c,l position for the given char cell = this.getCharacterPosition(this.text[i]); this.scene.translate(1,0,0); this.spriteSheet.activateCellP(cell); // Display the rectangle this.board.display(); } // Resume default shader this.scene.setActiveShader(this.scene.defaultShader); } setText(text) { this.text = text; } }
JavaScript
class Binding { node; property = ''; targets = []; targetProperties = new WeakMap(); /** * Creates a binding object for specified `node` and `property`. * @param {IoNode} node - Property owner node * @param {string} property - Name of the property */ constructor(node, property) { this.node = node; this.property = property; this.onTargetChanged = this.onTargetChanged.bind(this); this.onSourceChanged = this.onSourceChanged.bind(this); this.node.addEventListener(`${this.property}-changed`, this.onSourceChanged); } set value(value) { this.node[this.property] = value; } get value() { return this.node[this.property]; } /** * Adds a target `node` and `targetProp` and corresponding `[property]-changed` listener, unless already added. * @param {IoNode} node - Target node * @param {string} property - Target property */ addTarget(node, property) { debug: { if (node._properties[property].binding && node._properties[property].binding !== this) { console.warn('Binding target alredy has binding!'); } } node._properties[property].binding = this; node.setProperty(property, this.node[this.property]); const target = node; if (this.targets.indexOf(target) === -1) this.targets.push(target); const targetProperties = this.getTargetProperties(target); if (targetProperties.indexOf(property) === -1) { targetProperties.push(property); target.addEventListener(`${property}-changed`, this.onTargetChanged); } else { // console.warn('Binding target alredy added!'); WHY? } } /** * Removes target `node` and `property` and corresponding `[property]-changed` listener. * If `property` is not specified, it removes all target properties. * @param {IoNode} node - Target node * @param {string} property - Target property */ removeTarget(node, property) { const targetIoNode = node; const targetProperties = this.getTargetProperties(targetIoNode); if (property) { const i = targetProperties.indexOf(property); if (i !== -1) targetProperties.splice(i, 1); targetIoNode.removeEventListener(`${property}-changed`, this.onTargetChanged); } else { for (let i = targetProperties.length; i--;) { targetIoNode.removeEventListener(`${targetProperties[i]}-changed`, this.onTargetChanged); } targetProperties.length = 0; } if (targetProperties.length === 0) this.targets.splice(this.targets.indexOf(targetIoNode), 1); } /** * Retrieves a list of target properties for specified target node. * @param {IoNode} node - Target node. * @return {Array.<string>} list of target property names. */ getTargetProperties(node) { let targetProperties = this.targetProperties.get(node); if (targetProperties) { return targetProperties; } else { targetProperties = []; this.targetProperties.set(node, targetProperties); return targetProperties; } } /** * Event handler that updates source property when one of the targets emits `[property]-changed` event. * @param {ChangeEvent} event - Property change event. */ onTargetChanged(event) { debug: { if (this.targets.indexOf(event.target) === -1) { console.error('onTargetChanged() should never fire when target is removed from binding. Please file an issue at https://github.com/arodic/iogui/issues.'); return; } } const oldValue = this.node[this.property]; const value = event.detail.value; if (oldValue !== value) { // JavaScript is weird NaN != NaN if ((typeof value === 'number' && isNaN(value) && typeof oldValue === 'number' && isNaN(oldValue))) return; this.node[this.property] = value; } } /** * Event handler that updates bound properties on target nodes when source node emits `[property]-changed` event. * @param {ChangeEvent} event - Property change event. */ onSourceChanged(event) { debug: { if (event.target !== this.node) { console.error('onSourceChanged() should always originate form source node. Please file an issue at https://github.com/arodic/iogui/issues.'); return; } } const value = event.detail.value; for (let i = this.targets.length; i--;) { const target = this.targets[i]; const targetProperties = this.getTargetProperties(target); for (let j = targetProperties.length; j--;) { const propName = targetProperties[j]; const oldValue = target[propName]; if (oldValue !== value) { // JavaScript is weird NaN != NaN if ((typeof value === 'number' && isNaN(value) && typeof oldValue === 'number' && isNaN(oldValue))) continue; target[propName] = value; } } } } /** * Dispose of the binding by removing all targets and listeners. * Use this when node is no longer needed. */ dispose() { this.node.removeEventListener(`${this.property}-changed`, this.onSourceChanged); for (let i = this.targets.length; i--;) { this.removeTarget(this.targets[i]); } this.targets.length = 0; delete this.node; delete this.property; delete this.targets; delete this.targetProperties; delete this.onTargetChanged; delete this.onSourceChanged; } }
JavaScript
class NetworkUrls { // ------------------------------------------------ // - Base urls static get baseUrl() { return "https://itunes.apple.com"; } // ------------------------------------------------ // - Options static get action() { return "search?"; } static get resultLimit() { return "limit=10"; } // ------------------------------------------------ // - Nekfeu Songs static get nekfeuSongs() { return "term=nekfeu"; } }
JavaScript
class Stars extends Phaser.GameObjects.Group { static CONFIG = CONFIG.PREFABS.STAR; /** * Creates an instance of Stars * @param {Phaser.Scene} scene - The Scene to which this Stars group belongs */ constructor(scene) { super(scene); this.scene.add.existing(this); } /** * Update stars group * @param {number} speed - Current game speed */ update(speed) { const { width } = this.scene.scale.gameSize; this.children.each(star => { star.update(speed); if (star.x + star.width < 0) { star.setX(width); star.setY(this.getRandomYPos()); star.setFrame(this.getRandomFrame()); } }); } /** * Spawn stars */ spawnItems() { const { MAX_COUNT } = CONFIG.SCENES.GAME.NIGHTMODE.STARS; for (let i = this.getLength(); i < MAX_COUNT; i += 1) { this.add(new Star(this.scene)); } this.shuffleItems(); } /** * Shuffle stars */ shuffleItems() { const { width } = this.scene.scale.gameSize; const { MAX_COUNT } = CONFIG.SCENES.GAME.NIGHTMODE.STARS; const xWidth = width / MAX_COUNT; this.children.each((star, i) => { const frame = this.getRandomFrame(); const x = this.getRandomXPos(xWidth, i); const y = this.getRandomYPos(); star.setPosition(x, y); star.setFrame(frame); }); } /** * Get random star frame */ // eslint-disable-next-line class-methods-use-this getRandomFrame() { return Phaser.Math.RND.pick(Stars.CONFIG.FRAMES); } /** * Get random star x position */ // eslint-disable-next-line class-methods-use-this getRandomXPos(xWidth, i) { return Phaser.Math.RND.between(xWidth * i, xWidth * (i + 1)); } /** * Get random star y position */ // eslint-disable-next-line class-methods-use-this getRandomYPos() { const { MIN, MAX } = Stars.CONFIG.POS.Y; return Phaser.Math.RND.between(MIN, MAX); } /** * Reset stars group */ reset() { this.clear(true, true); } }
JavaScript
class S10 { /** * Returns the ninth digit (checksum) based on the first eight digits of the * postal tracking number. * @param {string|number} firstEightDigits - First eight digits as string or * number, e.g. '00071759' or 71759. * @returns {number} A single-digit number which is the ninth number in the * postal tracking number. */ static calculateCheckDigit(firstEightDigits) { if (!firstEightDigits) { throw new Error('Empty or incorrect first eight digits passed.'); } if (typeof firstEightDigits === 'number') { firstEightDigits = firstEightDigits.toString().padStart(8, '0'); } const digits = firstEightDigits.split(''); const sum = digits[0] * 8 + digits[1] * 6 + digits[2] * 4 + digits[3] * 2 + digits[4] * 3 + digits[5] * 5 + digits[6] * 9 + digits[7] * 7; let checkDigit = 11 - (sum % 11); if (checkDigit === 10) { return 0; } if (checkDigit === 11) { return 5; } return checkDigit; } static trackingNumberIsValid(trackingNumber) { if (!trackingNumber) { return false; } if (trackingNumber.length !== 13) { return false; } if (!trackingNumber.match(/[A-Z]{2}\d{9}[A-Z]{2}/)) { return false; } const eightNumbers = trackingNumber.substr(2, 8); const checkDigit = parseInt(trackingNumber.substr(10, 1)); const expectedCheckDigit = S10.calculateCheckDigit(eightNumbers); if (checkDigit === expectedCheckDigit) { return true; } return false; } }
JavaScript
class AuthService { constructor() { this.journey = []; this.userJourneys = [ { message: 'User tends to home', journey: ['/home', '/account', '/home'], }, { message: 'User tends to account', journey: ['/account', '/home', '/account'], }, { message: 'User loves journeys', journey: ['/home', '/account', '/accessories'], }, ]; } userMessage() { const filtered = this.userJourneys.filter((e) => { const journeyLength = e.journey.slice(0, this.journey.length); return JSON.stringify(journeyLength) == JSON.stringify(this.journey); }); if (filtered.length) { if (filtered[0].journey.length == this.journey.length) { console.log(filtered[0].message); this.journey = []; } } else { this.journey = []; } } journeyUrl(url) { this.journey.push(url); this.userMessage(); } }
JavaScript
class ConveyorView extends PIXI.Container { constructor(id) { super() this.id = id this.addItem() } addItem() { const itemBg = new PIXI.Sprite(getRes('rotation').texture) const dish = new PIXI.Sprite(getRes('dish_sm').texture) const material = new PIXI.Sprite(getRes(`m${this.id}`).texture) const nameBoard = new PIXI.Sprite(getRes('name_bg').texture) const name = new PIXI.Sprite(getRes(`n${this.id}`).texture) dish.x = (itemBg.width - dish.width) / 2 dish.y = 40 material.x = (itemBg.width - material.width) / 2 nameBoard.x = (itemBg.width - nameBoard.width) / 2 nameBoard.y = 400 name.x = (nameBoard.width - name.width) / 2 name.y = (nameBoard.height - name.height) / 2 nameBoard.addChild(name) this.addChild(itemBg, dish, material, nameBoard) } }
JavaScript
class KeyboardDirection extends Base { /** * Invoked when the user wants to go/navigate down. * The default implementation of this method does nothing. */ [symbols.goDown]() { if (super[symbols.goDown]) { return super[symbols.goDown](); } } /** * Invoked when the user wants to go/navigate to the end (e.g., of a list). * The default implementation of this method does nothing. */ [symbols.goEnd]() { if (super[symbols.goEnd]) { return super[symbols.goEnd](); } } /** * Invoked when the user wants to go/navigate left. * The default implementation of this method does nothing. */ [symbols.goLeft]() { if (super[symbols.goLeft]) { return super[symbols.goLeft](); } } /** * Invoked when the user wants to go/navigate right. * The default implementation of this method does nothing. */ [symbols.goRight]() { if (super[symbols.goRight]) { return super[symbols.goRight](); } } /** * Invoked when the user wants to go/navigate to the start (e.g., of a * list). The default implementation of this method does nothing. */ [symbols.goStart]() { if (super[symbols.goStart]) { return super[symbols.goStart](); } } /** * Invoked when the user wants to go/navigate up. * The default implementation of this method does nothing. */ [symbols.goUp]() { if (super[symbols.goUp]) { return super[symbols.goUp](); } } [symbols.keydown](event) { let handled = false; const orientation = this.orientation; const horizontal = (orientation === 'horizontal' || orientation === 'both'); const vertical = (orientation === 'vertical' || orientation === 'both'); // Ignore Left/Right keys when metaKey or altKey modifier is also pressed, // as the user may be trying to navigate back or forward in the browser. switch (event.keyCode) { case 35: // End handled = this[symbols.goEnd](); break; case 36: // Home handled = this[symbols.goStart](); break; case 37: // Left if (horizontal && !event.metaKey && !event.altKey) { handled = this[symbols.goLeft](); } break; case 38: // Up if (vertical) { handled = event.altKey ? this[symbols.goStart]() : this[symbols.goUp](); } break; case 39: // Right if (horizontal && !event.metaKey && !event.altKey) { handled = this[symbols.goRight](); } break; case 40: // Down if (vertical) { handled = event.altKey ? this[symbols.goEnd]() : this[symbols.goDown](); } break; } // Prefer mixin result if it's defined, otherwise use base result. return handled || (super[symbols.keydown] && super[symbols.keydown](event)) || false; } // Default orientation implementation defers to super, // but if not found, looks in state. get orientation() { return super.orientation || this.state && this.state.orientation || 'both'; } }
JavaScript
class DocumentationRoute extends TerminalRoute { constructor() { super("docs", StateDependentElement(DocumentationPanel), "Documentation"); this.subroutes = [ new TerminalRoute("edit", StateDependentElement(AdminDocumentationPanel), [], "Edit Documentation") ]; } matchesOwnNode(urlParts) { return urlParts.length === 0 || urlParts[0] !== "edit"; } }
JavaScript
class App extends Component { constructor(props) { super(props); // Name the state videos, which will be an array this.state = { videos: [], selectedVideo: null }; this.videoSearch('puppies'); } // Define callback videoSearch(term) { YTSearch({key: API_KEY, term: term}, (videos) => { // Update this.state with the new list of videos here // When the key and value are the same string (ex: videos), can condense from // this.setState({ videos: videos }) to : this.setState({ videos }) this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render() { const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300); // This html lookin ish is JSX - js code that can produce html // Compiles into ugly vanilla js (with methods from react library) // JSX can be nested // Pass prop videos to video list, so when App rerenders, VideoList will get new list of videos as well // onVideoSelect updates selectedVideo property...passed as prop into VideoList, // which passes it to VideoListItem. // VideoListItem says when li is clicked, call this function on the clicked video to set selected. return ( <div> <SearchBar onSearchTermChange={videoSearch} /> <VideoDetail video={this.state.selectedVideo} /> <VideoList onVideoSelect={ selectedVideo => this.setState({selectedVideo}) } videos={this.state.videos} /> </div> ); } }
JavaScript
class AppCore extends LitElement { constructor() { super(); this.speakers = []; this.talks = []; } static get properties() { return { speakers: Array, talks: Array, }; } render() { return html` <style> :host { display: block; } .App { display: flex; height: 100vh; flex-direction: column; flex-wrap: nowrap; align-content: space-between; overflow: hidden; background-color: #323230; } main { display: block; } custom-header, custom-footer { flex: 0; } main { flex: 1; overflow-y: scroll; } </style> <div class="App"> <custom-header headerLogo='{"logourl":"#","imageurl":"./src/assets/logo.png","imagealt":"BucharestJS logo","imagetitle":"B JS"}'> <h1>P.W.A. w/ LitHTML</h1> </custom-header> <main> <speakers-list title="Speakers:" .speakers="${this.speakers}" ></speakers-list> <talks-list title="Talks:" .talks="${this.talks}" ></talks-list> </main> <custom-footer>Copyright &copy; BucharestJS 2019 - Răzvan Roșu</custom-footer> </div> ` } firstUpdated() { // get speakers fetch('https://jsonplaceholder.typicode.com/users') .then((r) => { if (!r.ok) { throw Error(r.statusText); } return r; }) .then((r) => r.json()) .then((r) => { window.__SPEAKERS__ = r; this.speakers = r; }).catch(function(error) { console.log("failed to load speakers", error); }); // get talks window.addEventListener("injectTalks",() => { this.talks = window.__TALKS__; }, false); // Hide Loader when app is loaded const s = document.getElementById('loader').style; s.opacity = 1; (function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,70)})(); } }
JavaScript
class Dropoff { constructor(options) { _.each(options, (value, key) => { if (key == 'contact' && !(value instanceof Contact)) { value = new Contact(value); } else if (key == 'location' && !(value instanceof Location)) { value = new Location(value); } else if (key == 'eta') { value = parseInt(key, 10); if (isNaN(value)) { value = null; } } this[key] = value; }); } check() { if (this.eta) throw new Error('Delivery in progress; dropoff cannot be modified'); } }
JavaScript
class IndexPage extends Component { constructor(props){ super(props); this.state = { user: null } } /** * Handle KeyUp * @param {Object} e Event object */ handleKeyUp = e => { if(e.keyCode === 13){ const user = e.target.value; this.setState({ user }) } } render(){ const { user } = this.state; return ( <Layout pageTitle="RealTime Chat"> <main className="container-fluid position-absolute h-100 bg-dark"> <div className="row position-absolute w-100 h-100"> <section className="col-md-8 d-flex flex-row flex-wrap align-items-center align-content-center px-5"> <div className="px-5 mx-5"> <span className="d-block w-100 h1 text-light" style={{marginTop: -50}}> { user ? (<span> <span style={{ color: "#999"}}>Hello!</span> {user} </span>): "What is your name?" } </span> { !user && <input type="text" className="form-control mt-3 px-3 py-2" onKeyUp={this.handleKeyUp} autoComplete="off" style={nameInputStyles}/> } </div> </section> <section className="col-md-4 position-relative d-flex flex-wrap h-100 align-items-start align-content-between bg-white px-0"> { user && <Chat activeUser={user}/>} </section> </div> </main> </Layout> ) } }
JavaScript
class Account { constructor(userClaims, userid) { this.userClaims = userClaims; this.accountId = userid; } /** * Returns the OIDC claims for the id-token. * * This function is used by oidc-provider. * The claims method transposes the LDAP object into an id-token object. * If this function returns null, no user is set. */ claims() { return this.userClaims; } }
JavaScript
class NotificationCommitter { // Notification Event Data: // // { // targetUsername: 'derpo123' // notification: 'Somebody viewed your profile', // read: '0', // origUsername: 'diVid3' // } static commitNotification(data) { BlockedUsersModel.getBlockedUsersByUsername({ username: data.targetUsername }) .then((json) => { if (json && json.body && json.body.rows) { // The user should not receive notifications from me if I'm on their blocked list. if (json.body.rows.some(blockedUser => blockedUser.blocked_username === data.origUsername)) { return } // Forward notification here. const targetSocket = SocketStore.getSocket(data.targetUsername) // If the targetUser is currently connected. if (targetSocket) { targetSocket.emit('fromServerNotification', data) } // Saving notification to DB. NotificationsModel.createNotificationByUsername({ username: data.targetUsername, notification: data.notification, read: data.read }) .then((json) => { // Nothing to do. }) .catch((json) => { console.log('commitNotification, NotificationsModel.createNotificationByUsername failed, JSON: ', json) }) } }) .catch((json) => { console.log('commitNotification, BlockedUsersModel.getBlockedUsersByUsername failed, JSON: ', json) }) } }
JavaScript
class Preference { constructor(args) { this.key = args.key; this.name = args.name; this.pack = args.packer || JSON_Packer; this.unpack = args.unpacker || JSON_Unpacker; this.def = args.def; this.fields = args.fields || {key: {name: args.name, validators: []}}; this.validators = []; args.validators.forEach( (validator) => { this.validators.push(validator); } ); this.init(); } validate(input) { // Check candidate value with all registered validators let messages = ""; let status = "PASS"; for (let validator of this.validators) { const result = validator(input, this); messages += result.message; if (result.status == "FAIL") { status = "FAIL"; break; } else if (result.status == "WARN") { status = ((status == "FAIL") ? "FAIL" : "WARN"); } } return {status: status, message: messages}; } reset() { // Revert to default this.value = this.def; localStorage[this.key] = this.pack(this.value); } init() { // Load saved value or revert to default if (localStorage[this.key] === undefined) { // No value saved console.log("[Prefs] No value for " + this.name + " in localStorage[" + this.key + "], using default '" + this.def + "'"); this.reset(); } else { // We've got something in localStorage const result = this.validate(this.unpack(localStorage[this.key])); if (result.status == "FAIL") { // Validation faliure on saved value console.warn(result.message); console.warn("[Prefs] Saved value for " + this.name + " in localStorage[" + this.key + "] failed validation! Using default '" + this.def + "'"); this.reset(); } else { // All is well this.value = this.unpack(localStorage[this.key]); } } } set(input) { const result = this.validate(input); if (result.status == "FAIL") { console.warn(result.message); console.warn("[Prefs] New value '" + input + "' for '" + this.name + "' failed validation! Keeping current '" + this.value + "'"); } else { this.value = input; localStorage[this.key] = this.pack(this.value); } return result; } get() { this.init(); return this.value; } }
JavaScript
class MicxFormmail extends HTMLElement { constructor() { super(); /** * The observed Form Element * * @type {HTMLFormElement} */ this.formEl = null; } show(selector) { MicxFormmail.log("show(", selector, ")"); for (let sube of this.parentElement.querySelectorAll(selector)) { sube.removeAttribute("hidden"); } } hide(selector) { MicxFormmail.log("hide(", selector, ")"); for (let sube of this.parentElement.querySelectorAll(selector)) { sube.setAttribute("hidden", "hidden"); } } async connectedCallback() { let log = MicxFormmail.log; let fe = this.formEl = this.parentElement; log("Micx formmailer ", this, "initializing on form ", fe); if (fe.tagName !== "FORM") throw ["Invalid parent node tagName (!= 'form') on MicxFormmailer node: ", this, "Parent is", fe]; // Prevent submit on enter fe.addEventListener("submit", (e) => { e.preventDefault(); }); this.setAttribute("hidden", "hidden"); fe.addEventListener("click", async (e) => { log("click event", e); if (typeof e.explicitOriginalTarget !== "undefined") { // Safari & Firefox if ( ! MicxFormmail.isFormButtonDescendant(e.explicitOriginalTarget)) return false; } else { // Chrome if ( ! MicxFormmail.isFormButtonDescendant(e.target)) return false; if (e.pointerType === '') return false; // Triggered by Enter in Input Form } log ("button submit click event", e); e.preventDefault(); e.target.setAttribute("disabled", "disabled"); let formdata, invalid; [formdata, invalid] = MicxFormmail.collectFormData(fe); if (invalid.length > 0) { console.warn("Form data is invalid", invalid); this.dispatchEvent(new Event("invalid", {invalid_forms: invalid})); e.target.removeAttribute("disabled"); return; } this.dispatchEvent(new Event("waiting", {invalid_forms: invalid})); let preset = "default"; if (this.hasAttribute("preset")) preset = this.getAttribute("preset"); try { let result = await MicxFormmail.sendMail(formdata, preset); this.dispatchEvent(new Event("submit", {ok: result})); } catch (e) { this.dispatchEvent(new Event("error", {error: e})); } e.target.removeAttribute("disabled"); }); this.dispatchEvent(new Event("load", {"ref": this})); } }
JavaScript
class Task { /** * Constructs a new <code>Task</code>. * @alias module:model/Task * @class */ constructor() { } /** * Constructs a <code>Task</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/Task} obj Optional instance to populate. * @return {module:model/Task} The populated <code>Task</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Task(); if (data.hasOwnProperty('title')) obj.title = ApiClient.convertToType(data['title'], 'String'); if (data.hasOwnProperty('description')) obj.description = ApiClient.convertToType(data['description'], 'String'); if (data.hasOwnProperty('status')) obj.status = ApiClient.convertToType(data['status'], 'Number'); if (data.hasOwnProperty('notes')) obj.notes = ApiClient.convertToType(data['notes'], 'String'); if (data.hasOwnProperty('changes')) obj.changes = ApiClient.convertToType(data['changes'], 'String'); if (data.hasOwnProperty('dueDate')) obj.dueDate = ApiClient.convertToType(data['dueDate'], 'Number'); if (data.hasOwnProperty('firstReminderStatus')) obj.firstReminderStatus = ApiClient.convertToType(data['firstReminderStatus'], 'Number'); if (data.hasOwnProperty('_syncFields')) obj.syncFields = ApiClient.convertToType(data['_syncFields'], ['String']); if (data.hasOwnProperty('id')) obj.id = ApiClient.convertToType(data['id'], 'Number'); if (data.hasOwnProperty('foreignId')) obj.foreignId = ApiClient.convertToType(data['foreignId'], 'String'); if (data.hasOwnProperty('language')) obj.language = ApiClient.convertToType(data['language'], 'Number'); if (data.hasOwnProperty('createDate')) obj.createDate = ApiClient.convertToType(data['createDate'], 'Number'); if (data.hasOwnProperty('changeDate')) obj.changeDate = ApiClient.convertToType(data['changeDate'], 'Number'); if (data.hasOwnProperty('deleted')) obj.deleted = ApiClient.convertToType(data['deleted'], 'Number'); if (data.hasOwnProperty('hidden')) obj.hidden = ApiClient.convertToType(data['hidden'], 'Number'); if (data.hasOwnProperty('sorting')) obj.sorting = ApiClient.convertToType(data['sorting'], 'Number'); if (data.hasOwnProperty('tags')) obj.tags = ApiClient.convertToType(data['tags'], 'String'); } return obj; } }
JavaScript
class Main { constructor(container) { // Set container property to container element this.container = container const loadingManager = new THREE.LoadingManager( () => { // 3D assets are loaded, now load nav mesh console.log('test loading manager') } ); // Start Three clock this.clock = new THREE.Clock() // Main scene creation this.scene = new THREE.Scene() this.scene.fog = new THREE.FogExp2(Config.fog.color, Config.fog.near) // const boxGeometry = new THREE.BoxBufferGeometry( 10, 10, 10 ); // const boxMaterial = new THREE.MeshBasicMaterial( {color: 0x00ff00} ); // const cube = new THREE.Mesh( boxGeometry, boxMaterial ); // cube.matrixAutoUpdate = false; // this.scene.add(cube); // this.enemy = new Enemy(); // this.enemy.boundingRadius = 0.25; // this.enemy.setRenderComponent(cube, this.syncEnemy); // this.enemy.position.set( 0, 0, 0); const loader = new YUKA.NavMeshLoader(); loader.load( './assets/models/navmesh3.glb', { epsilonCoplanarTest: 0.25 } ).then( ( navMesh ) => { // visualize convex regions const navMeshGroup = createConvexRegionHelper( navMesh ); navMeshGroup.scale.multiplyScalar(10) this.scene.add( navMeshGroup ); // player.navMesh = navMesh; enemy.navMesh = navMesh; console.log('loaded navmesh') } ); // Get Device Pixel Ratio first for retina if (window.devicePixelRatio) { Config.dpr = window.devicePixelRatio } // Main renderer constructor this.renderer = new Renderer(this.scene, container) // Components instantiations this.camera = new Camera(this.renderer.threeRenderer) this.controls = new Controls(this.camera.threeCamera, container) this.light = new Light(this.scene) // Create and place lights in scene const lights = ['ambient', 'directional', 'point', 'hemi'] lights.forEach(light => this.light.place(light)) // Create and place geo in scene // this.geometry = new Geometry(this.scene) // this.geometry.make('plane')(150, 150, 10, 10) // this.geometry.place([0, 1, 0], [Math.PI / 2, 0, 0]) // this.box = new Geometry(this.scene) // this.box.make('box')(10, 10, 10, 8, 8, 8) // this.box.place([0, 10, 20], [0, 0, 0]) // Set up rStats if dev environment if (Config.isDev && Config.isShowingStats) { this.stats = new Stats(this.renderer) this.stats.setUp() } // Instantiate texture class this.texture = new Texture() // Start loading the textures and then go on to load the model after the texture Promises have resolved this.texture.load().then(() => { this.manager = new THREE.LoadingManager() // Textures loaded, load model this.model = new Model(this.scene, this.manager, this.texture.textures) this.model.load() // onProgress callback this.manager.onProgress = (item, loaded, total) => { console.log(`${item}: ${loaded} ${total}`) } // All loaders done now this.manager.onLoad = () => { // Set up interaction manager with the app now that the model is finished loading new Interaction( this.renderer.threeRenderer, this.scene, this.camera.threeCamera, this.controls.threeControls ) // Add dat.GUI controls if dev if (Config.isDev) { new DatGUI(this, this.model.obj) } // Everything is now fully loaded Config.isLoaded = true this.container.querySelector('#loading').style.display = 'none' // TweenMax.to(this.lift.position, 2, { // y: 4, // repeat: -1, // yoyo: true, // ease: Power2.easeInOut // }) } }) // Start render which does not wait for model fully loaded this.render() } syncEnemy( entity, renderComponent ) { renderComponent.matrix.copy( entity.worldMatrix ) } render() { // Render rStats if Dev if (Config.isDev && Config.isShowingStats) { Stats.start() } // Call render function and pass in created scene and camera this.renderer.render(this.scene, this.camera.threeCamera) // rStats has finished determining render call now if (Config.isDev && Config.isShowingStats) { Stats.end() } // Delta time is sometimes needed for certain updates //const delta = this.clock.getDelta(); // Call any vendor or module frame updates here this.controls.threeControls.update() // RAF requestAnimationFrame(this.render.bind(this)) // Bind the main class instead of window object } }
JavaScript
class AutorotateButton extends AbstractButton { static id = 'autorotate'; static icon = play; static iconActive = playActive; /** * @param {PSV.components.Navbar} navbar */ constructor(navbar) { super(navbar, 'psv-button--hover-scale psv-autorotate-button', true); this.psv.on(EVENTS.AUTOROTATE, this); } /** * @override */ destroy() { this.psv.off(EVENTS.AUTOROTATE, this); super.destroy(); } /** * @summary Handles events * @param {Event} e * @private */ handleEvent(e) { /* eslint-disable */ switch (e.type) { // @formatter:off case EVENTS.AUTOROTATE: this.toggleActive(e.args[0]); break; // @formatter:on } /* eslint-enable */ } /** * @override * @description Toggles autorotate */ onClick() { this.psv.toggleAutorotate(); } }
JavaScript
class AssetCompute { /** * @typedef {Object} AssetComputeOptions * @property {String} accessToken JWT access token * @property {String} org IMS organization * @property {String} apiKey API key used to communicate with Asset Compute * @property {String} [url=] Asset Compute url (defaults to https://asset-compute.adobe.io) * @property {Number} [interval=] Override interval at which to poll I/O events * @property {Object} [retryOptions=] Fetch retry options for `@adobe/node-fetch-retry` See README.md for more information */ /** * Construct Asset Compute client * * @param {AssetComputeOptions} options Options */ constructor(options) { this.accessToken = options.accessToken; this.org = options.org; this.apiKey = options.apiKey; this.url = options.url || ASSET_COMPUTE_PROD_URL; this.interval = options.interval; this.retryOptions = options.retryOptions || true; // default retry options } /** * @typedef {Object} AssetComputeRegisterResponse * * @property {String} journal Journal URL to use with AssetComputeEventEmitter */ /** * Register I/O events and journal * * @returns {AssetComputeRegisterResponse} Journal url */ async register() { const response = await fetch(`${this.url}/register`, { method: "POST", headers: { authorization: `Bearer ${this.accessToken}`, "x-gw-ims-org-id": this.org, "x-ims-org-id": this.org, "x-api-key": this.apiKey }, retryOptions: this.retryOptions }); if (!response.ok) { const msg = await response.text(); throw Error(`Unable to invoke /register: ${response.status} ${msg}`); } else { return response.json(); } } /** * Unregister I/O events and journal */ async unregister() { const response = await fetch(`${this.url}/unregister`, { method: "POST", headers: { authorization: `Bearer ${this.accessToken}`, "x-gw-ims-org-id": this.org, "x-ims-org-id": this.org, "x-api-key": this.apiKey } }); if (!response.ok) { const msg = await response.text(); throw Error(`Unable to invoke /unregister: ${response.status}: ${msg} (details: ${JSON.stringify(response)})`); } else { return response.json(); } } /** * @typedef {Object} AssetComputeProcessResponse * * @property {String} activationId Activation Identifier */ /** * Asynchronously process an asset. The result is returned as an event * emitted from AssetComputeEventEmitter. * * @param {AssetComputeSource|String} [source=] Source asset, may be null or undefined * @param {AssetComputeRendition[]} renditions Requested renditions * @param {Object} userData User data associated with the request * @returns {AssetComputeProcessResponse} Response with the activation id */ async process(source, renditions, userData) { if (Array.isArray(source)) { userData = renditions; renditions = source; source = undefined; } const response = await fetch(`${this.url}/process`, { method: "POST", headers: { authorization: `Bearer ${this.accessToken}`, "x-gw-ims-org-id": this.org, "x-ims-org-id": this.org, "x-api-key": this.apiKey, "content-type": "application/json" }, body: JSON.stringify({ // TODO: providing source name, and size confuses Asset Compute so just provide the url source: (source && source.url) || source, renditions, userData }), retryOptions: this.retryOptions }); if (!response.ok) { const msg = await response.text(); throw Error(`Unable to invoke /process: ${response.status} ${msg}`); } else { return response.json(); } } }
JavaScript
class SlotContentTest extends SlotContentMixin(HTMLElement) { constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.innerHTML = ` <div id="static">This is static content</div> <slot></slot> `; // Simulate key bits of ReactiveMixin. this.state = this.defaultState; this.componentDidMount(); } setState(state) { Object.assign(this.state, state); } }
JavaScript
class WrappedContentTest extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.innerHTML = `<slot-content-test><slot></slot></default-slotcontent-test>`; } }
JavaScript
class SectionMenuPage extends Page { /** * define selectors using getter methods */ get sectionMenu() { return $('#wb-sec') } get menuLink() { return $('#wb-sec section:first-of-type ul li:nth-child(1) a') } get subLink() { return $('#wb-sec section:first-of-type ul li:nth-child(1) ul li:nth-child(1) a') } get subLinkNewWindow() { return $('#wb-sec section:first-of-type ul li:nth-child(1) ul li:nth-child(3) a') } get secondSectionLink() { return $('#wb-sec section:nth-of-type(2) h3') } get secondSectionLinkNewWin() { return $('#wb-sec section:nth-of-type(2) h3 a') } get thirdSectionText() { return $('#wb-sec section:nth-of-type(3) h3') } get skipSecLink() { return $('//li/a[@href="#wb-sec"]') } get menuLinkNewWindow() { return $('//nav[@id="wb-sec"]/h2/following-sibling::section/following-sibling::section/h3/a'); } /** * Opens a sub page of the page * @param theme theme of the sub page (e.g. gcweb, gcintranet) * @param lang language of the sub page (e.g. en, fr) */ //Return the various test pages open(theme, lang) { return super.open(theme, `${theme}-sectionmenu-${lang}.html`); } }
JavaScript
class SendAText extends React.Component { constructor(props) { super(props) this.state = { toPhoneNumbers: '', phoneNumberArray: [], badPhoneNumberArray: [], message: '', formErrors: { toPhoneNumbers: '', phoneNumberArray: '', message: '', }, phoneNumberValid: false, messageValid: false, formValid: false, formSubmitted: false } this.validateForm = this.validateForm.bind(this) this.validatePhone = this.validatePhone.bind(this) this.validateField = this.validateField.bind(this) this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) this.errorClass = this.errorClass.bind(this) this.submitTextInformation = this.submitTextInformation.bind(this) } validateForm() { this.setState({ formValid: this.state.phoneNumberValid && this.state.messageValid, }) } validatePhone() { const goodPhoneNumberArray = [] const badPhoneNumberArray = [] const toPhoneNumbers = this.state.toPhoneNumbers if (!toPhoneNumbers) { return false } const phoneNumbersSplit = toPhoneNumbers.split(' ') phoneNumbersSplit.forEach(phoneNumber => { const cleanedPhoneNumber = phone(phoneNumber, 'USA') if (cleanedPhoneNumber.length > 0) { goodPhoneNumberArray.push(cleanedPhoneNumber[0]) } else { badPhoneNumberArray.push(phoneNumber) } }) let formValid = this.state.formValid let fieldValidationErrors = this.state.formErrors if (goodPhoneNumberArray.length < 1) { formValid = false fieldValidationErrors.toPhoneNumbers = ' is invalid' } this.setState( { goodPhoneNumberArray, badPhoneNumberArray, formValid, formErrors: fieldValidationErrors } ) } validateField(fieldName, fieldValue) { let fieldValidationErrors = this.state.formErrors let phoneNumberValid = this.state.phoneNumberValid let messageValid = this.state.messageValid switch (fieldName) { case 'message': messageValid = !!fieldValue && fieldValue.length fieldValidationErrors.message = messageValid ? '' : ' is invalid' break case 'toPhoneNumbers': phoneNumberValid = !!fieldValue fieldValidationErrors.toPhoneNumbers = phoneNumberValid ? '' : ' is invalid' break default: break } this.setState( { formErrors: fieldValidationErrors, phoneNumberValid, messageValid, }, this.validateForm ) } handleChange(e) { const { name, value } = e.target this.setState( { [name]: value, }, () => { this.validateField(name, value) } ) } async submitTextInformation() { const sendATextInformation = { message: this.state.message, toPhoneNumbers: this.state.goodPhoneNumberArray, } const authToken = JSON.parse(localStorage.getItem('user')).token // [matt]: Need auth headers to be attached console.log('[matt] ', sendATextInformation) await fetch(`${endpoint}/sendSMS`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` }, body: JSON.stringify(sendATextInformation) }) .then(response => { if (!response.ok) { throw Error(response.statusText) } else { this.setState({formSubmitted: true}) } console.log('[matt] response', response.json()) }) .catch(err => { // [matt]: TODO If Err, should not go to follow up confirmation page console.log('[matt] err', err) }) } async handleSubmit(e) { e.preventDefault() await this.validatePhone() if (!this.state.formValid) { return false } await this.submitTextInformation() if (this.state.formSubmitted && typeof window !== 'undefined') { navigate( `/sendATextConfirmation`, { state: { goodPhoneNumberArray: this.state.goodPhoneNumberArray, badPhoneNumberArray: this.state.badPhoneNumberArray, message: this.state.message } } ) } else { let fieldValidationErrors = this.state.formErrors fieldValidationErrors.toPhoneNumbers = ' is invalid' this.setState( { formErrors: fieldValidationErrors, }) } } errorClass(error) { return error.length === 0 ? 'no-error' : 'has-error' } render() { return ( <div> <Form onSubmit={this.handleSubmit}> <h1>Send A Mass Text</h1> <p>If adding more than one phone number, use spaces in between the numbers</p> <fieldset> <label htmlFor="toPhoneNumber"> Phone Number(s): <br /> <span className={`${this.errorClass( this.state.formErrors.toPhoneNumbers )}`}>Please enter correct phone numbers</span> </label> <input type="tel" // [matt]: CHANGE to something else id="toPhoneNumbers" name="toPhoneNumbers" value={this.state.toPhoneNumbers} onChange={this.handleChange} /> </fieldset> <fieldset> <label htmlFor="message"> Message: <br /> <span className={`${this.errorClass( this.state.formErrors.message )}`}>Please enter a message</span> </label> <textarea type="textarea" id="message" name="message" value={this.state.message} onChange={this.handleChange} > </textarea> </fieldset> <button type="submit">Send the Text!</button> </Form> </div> ) } }
JavaScript
class Pager { constructor(config = {}) { this.before = []; this.after = []; this.historyList = []; this.history = new Map(); /** * Change page * @param href the href URL */ const switchTo = (HTMLText, callback = null) => { // Create DOM Object from loaded HTML const doc = document.implementation.createHTMLDocument(''); doc.documentElement.innerHTML = HTMLText; const newTitle = doc.title; // Take the specified element const shell = doc.querySelector(`[${this.config.shellMark}]`); const scripts = Array.from(shell.getElementsByTagName('script')) .filter((el) => (el.getAttribute('type') === null || el.getAttribute('type') === 'text/javascript') && !el.hasAttribute(this.config.ignoreScript)); scripts.forEach(el => el.remove()); const runBefore = scripts.filter(el => el.hasAttribute(this.config.runBefore)) .map(copyScriptTag); const runAfter = scripts.filter(el => !el.hasAttribute(this.config.runBefore)) .map(copyScriptTag); runBefore.forEach(scr => this.shell.appendChild(scr)); window.requestAnimationFrame(() => { this.shell.innerHTML = shell.innerHTML; runAfter.forEach(scr => this.shell.appendChild(scr)); window.scrollTo(0, 0); window.document.title = newTitle; callback && callback(); }); }; const handleMouseOver = (e) => { const linkNode = this._getIfLink(e.target); if (!this._isLegalLink(linkNode)) { return; } if (this.curRequest) { if (linkNode === this.curRequest.source) { return; } this._cancelRequest(); } const req = new PagerRequest(linkNode); this.curRequest = req; }; const handleClick = (e) => { const linkNode = this._getIfLink(e.target); if (!linkNode) { return; } e.preventDefault(); const href = linkNode.href; const cont = text => { switchTo(text, () => { this._addHistory(href); history.pushState(null, null, href); }); }; if (this.curRequest && linkNode === this.curRequest.source) { this.curRequest.continue(cont); return; } const req = new PagerRequest(linkNode); this.curRequest = req; req.continue(cont); }; window.onpopstate = (e) => { this._cancelRequest(); const href = window.location.href; const st = this.history.get(href); if (!st) { window.location.reload(); return; } window.document.title = st.title; this.shell.innerHTML = st.content; }; this.config = Object.assign({}, defaultConfig); if (typeof config === 'string') { this.config.shellMark = config; } else { Object.assign(this.config, config); } const shell = document.querySelector(`[${this.config.shellMark}]`); this.shell = shell || null; this._addHistory(window.location.href); document.addEventListener('mouseover', handleMouseOver); // document.addEventListener('mouseout', clearPreload) document.addEventListener('click', handleClick); } _cancelRequest() { this.curRequest && this.curRequest.cancel(); this.curRequest = null; } _addHistory(href) { if (!this.history.has(href)) { this.historyList.push(href); } this.history.set(href, { title: window.document.title, content: this.shell.innerHTML }); if (this.historyList.length > this.config.historyToSave) { const first = this.historyList.shift(); this.history.delete(first); } } /** * Check if the element that mouse overed is or is child of `<a>`, * and its `href` should be load * @param el */ _isLegalLink(el) { const loc = window.location; return el && el.nodeName === 'A' && !el.getAttribute(`${this.config.disableMark}`) && el.hostname === loc.hostname && el.port === loc.port && el.pathname !== loc.pathname; } _getIfLink(el) { while (el && (el.nodeName != 'A' || !el.getAttribute('href'))) { el = el.parentElement; } if (this._isLegalLink(el)) { return el; } return null; } mount(el) { if (typeof el === 'string') { this.shell = document.querySelector(el); } else { this.shell = el; } } }
JavaScript
class ImageCache { constructor() { /** * @type {string} * @private */ this.tempDirPath_ = path.join(os.tmpdir(), 'mdc-web-image-cache'); } /** * @param {string} uri * @return {!Promise<!Buffer>} */ async getImageBuffer(uri) { await fsx.ensureDir(this.tempDirPath_); const imageFileName = this.getFilename_(uri); const imageFilePath = path.join(this.tempDirPath_, imageFileName); if (await fs.exists(imageFilePath)) { return await fs.readFile(imageFilePath); } const imageData = await this.downloadImage_(uri); fs.writeFile(imageFilePath, imageData) .catch(async (err) => { console.error(`getImageBuffer("${uri}"):`); console.error(err); if (await fs.exists(imageFilePath)) { await fs.unlink(imageFilePath); } return Promise.reject(err); }); return imageData; } /** * @param {string} uri * @return {!Promise<!Buffer>} * @private */ async downloadImage_(uri) { // For binary data, set `encoding: null` to return the response body as a `Buffer` instead of a `string`. // https://github.com/request/request#requestoptions-callback return request({uri, encoding: null}) .then( (body) => body, (err) => { console.error(`FAILED to download "${uri}"`); return Promise.reject(err); } ); } /** * @param {string} uri * @return {string} * @private */ getFilename_(uri) { return uri .replace(/[^a-zA-Z0-9_.-]+/g, '_') .replace(/_{2,}/g, '_') ; } }
JavaScript
class TwingNodeBody extends node_1.TwingNode { constructor(nodes = new Map(), attributes = new Map(), lineno = 0, columnno = 0, tag = null) { super(nodes, attributes, lineno, columnno, tag); this.type = node_1.TwingNodeType.BODY; } }
JavaScript
class CDATASectionAssembler extends TextAssembler { /** * Create the specified CDATASection node * @param {{}} init * @returns {CDATASection} * @override */ static create(init) { return document.createCDATASection(this.data) } /** * @returns {interface} CDATASection * @override */ static get interface() { return CDATASection } }
JavaScript
class GenericOauth { /** * @constructor * @param {Object} context Current request context. * @param {String} provider Id of provider. * @param {Object} [tokens] Access tokens previously obtained. */ constructor (context, provider, tokens) { this.context = context; this.provider = provider; this.App = this.context.App; this.logger = logger.create(`Oauth-${provider}`); this.config = _.get(this.App.config.oauth, this.provider, {}); this.callbackURL = this.App.routes.url('oauth_callback', { provider: provider, }, null, { absolute: true }); this.oauth2 = new OAuth2( this.config.clientId, this.config.clientSecret, this.config.baseURL, this.config.authorizePath, this.config.accessTokenPath, this.config.customHeaders ); if (tokens) { this._setTokens(tokens); } } /** * Get OAuth authorization URL. * @return {String} */ getAuthorizeUrl () { let params = this._buildAuthorizeParams(); let url = this.oauth2.getAuthorizeUrl(params); this.logger.debug('authorize url', url); return url; } * handleAuthorizationCallback() { let user = this._user(); this.App.emit('record', 'oauth_callback', user || 'anon', { provider: this.provider, query: this.context.request.query, }); try { let errorMsg = this.context.request.query.error, errorDesc = this.context.request.query.error_description; if (errorMsg) { throw new OauthError(errorMsg, 400, errorDesc); } // we got the code! let code = this.context.request.query.code; if (!code) { throw new OauthError('Failed to obtain OAuth code', 400); } let response = yield this.getAccessToken(code); yield this._handlePostAuthorizationSuccess(response); } catch (err) { yield this._handleError(err); } } /** * Get OAuth access token. * @param {String} code Code returned by OAuth provider. */ * getAccessToken (code) { let user = this._user(); this.logger.info(`Get access token: user=${user ? user.id : 'anon'} code=${code}`); try { return yield new Q((resolve, reject) => { let params = this._buildAccessTokenParams(); this.oauth2.getOAuthAccessToken(code, params, (err, access_token, refresh_token, result) => { if (err) { return reject(new OauthError('Get access token error', err.statusCode || 400, err)); } if (_.get(result, 'error')) { return reject( new OauthError(`Get access token error: ${result.error}`, 400, { error: result.error }) ); } this.logger.debug(`Get access token result: ${access_token}, ${refresh_token}, ${JSON.stringify(result)}`); this._setTokens({ access_token: access_token, refresh_token: refresh_token, }); resolve({ access_token: access_token, refresh_token: refresh_token, result: result, }); }); }); } catch (err) { yield this._handleError(err, { method: 'getOAuthAccessToken', }); } } _setTokens (tokens) { this.tokens = tokens; if (this.tokens) { this.authHeader = { 'Authorization': `Bearer ${this.tokens.access_token}`, }; } } * _get (url, queryParams) { return yield this._request('GET', url, queryParams); } * _post (url, queryParams, body) { return yield this._request('POST', url, queryParams, body); } _buildRequestUrl (url, queryParams) { let apiBaseUrl = this.config.apiBaseUrl; if (!_.get(apiBaseUrl, 'length')) { throw new OauthError(`${this.provider}: apiBaseUrl must be provided`); } url = apiBaseUrl + url; queryParams = qs.stringify(queryParams || {}); if (queryParams.length) { url += '?' + queryParams; } return url; } * _request (method, url, queryParams, body) { url = this._buildRequestUrl(url, queryParams); this.logger.debug(method, url); if (body) { body = JSON.stringify(body); } try { return yield new Q((resolve, reject) => { this.oauth2._request(method, url, this.authHeader, body, this.accessToken, (err, result) => { if (err) { return reject(new OauthError(method + ' error', err.statusCode || 400, err)); } try { result = JSON.parse(result); } catch (e) { // nothing to do here } resolve(result); }); }); } catch (err) { yield this._handleError(err, { method: method, url: url, body: body, }); } } _buildAuthorizeParams () { let params = _.extend({}, _.get(this.config, 'authorizeParams')); let callbackParamName = _.get(this.config, 'callbackParam', 'redirect_uri'); params[callbackParamName] = this.callbackURL; return params; } _buildAccessTokenParams () { let params = _.extend({}, _.get(this.config, 'accessTokenParams')); let callbackParamName = _.get(this.config, 'callbackParam', 'redirect_uri'); params[callbackParamName] = this.callbackURL; return params; } _user () { return this.context.currentUser; } * _handlePostAuthorizationSuccess (accessTokenResponse) { yield this.context.redirect("/"); } * _handleError (err, attrs) { this.logger.error(err); this.App.emit('record', 'oauth_request', this._user() || 'anon', _.extend({}, attrs, { type: 'error', provider: this.provider, message: err.message, details: err.details, })); throw err; } }
JavaScript
class VCache { constructor(state, cmpFn, renderFn) { this.type = 'Thunk'; this.renderFn = renderFn; this.cmpFn = cmpFn; this.state = state; } render(previous) { // The first time the Thunk renders, there will be no previous state var previousState = previous ? previous.state : null; // We run the comparison function to see if the state has changed enough // for us to re-render. If it returns truthy, then we call the render // function to give us a new VNode if ((!previousState || !this.state) || this.cmpFn(previousState, this.state)) { return this.renderFn(previous, this); } else { // vnode will be set automatically when a thunk has been created // it contains the VNode, VText, Thunk, or Widget generated by // our render function. return previous.vnode; } } }
JavaScript
class ProtobufConverter { /** * Converts a single protobuf file into a * Composer model, generated in an output directory. * @param {String} protoFile - the name of the proto file * @param {String} outputDir - the output directory for the generated Composer models * @returns {String} the path to the generated file */ static convert(protoFile, outputDir) { console.log('Parsing: ' + protoFile); const root = new protobuf.Root(); root.loadSync(protoFile); //console.log(JSON.stringify(root)); const writer = new FileWriter(outputDir); const outputFile = path.parse(protoFile).name + '.cto'; writer.openFile(outputFile); const ns = ProtobufConverter.convertItem(writer, root, 0); writer.writeBeforeLine(0, 'namespace ' + ns.substring(1)); // discard the leading . writer.closeFile(); console.log('Generated: ' + outputFile); return outputDir + '/' + outputFile; } /** * Process this protobuf object recursively, writing the CTO to the FileWriter * @param {FileWriter} writer - the FileWriter to use * @param {ReflectionObject} obj - the object * @param {Integer} indent - the indentation to use * @returns {String} the namespace to use * @private */ static convertItem(writer, obj, indent) { let ns = '.unknown'; // we assume anything with a field is a concept if (obj.fieldsArray) { writer.writeLine(indent, 'concept ' + obj.name + '{'); for (let n = 0; n < obj.fieldsArray.length; n++) { const field = obj.fieldsArray[n]; let optional = ''; let array = ''; const type = ProtobufConverter.toComposerType(field.type); if (field.repeated) { array = '[]'; } if (field.optional) { optional = 'optional'; } const hasDefault = ['String', 'DateTime', 'Integer', 'Double', 'Long', 'Boolean']; let def = ''; if(field.options && !field.repeated && field.options.default && hasDefault.indexOf(type) >= 0) { def = 'default='; if(type === 'String' || type === 'DateTime') { def += '"'; } def += field.options.default; if(type === 'String' || type === 'DateTime') { def += '"'; } } writer.writeLine(indent + 1, ' o ' + type + array + ' ' + ProtobufConverter.unqualify(field.name) + ' ' + def + ' ' + optional); } writer.writeLine(indent, '}'); } // we assume anything with value is an enum else if (obj.values) { writer.writeLine(indent, 'enum ' + obj.name + '{'); for (let n = 0; n < Object.keys(obj.values).length; n++) { writer.writeLine(indent + 1, ' o ' + Object.keys(obj.values)[n]); } writer.writeLine(indent, '}'); } // if it has a name and no fields or values, we assume it is a namespace else if (obj.fullName) { ns = obj.fullName; } // we then recurse on any nested elements if (obj.nestedArray) { for (let n = 0; n < obj.nestedArray.length; n++) { const childNs = ProtobufConverter.convertItem(writer, obj.nestedArray[n], indent); if(childNs !== '.unknown') { ns = childNs; } } } return ns; } /** * Converts a Protobuf type to a Composer type * @param {String} protoType - the Protobuf type name * @return {String} the Composer type to use * @private */ static toComposerType(protoType) { let result = ProtobufConverter.unqualify(protoType); switch (protoType) { case 'string': case 'bytes': result = 'String'; break; case 'double': case 'float': result = 'Double'; break; case 'int32': case 'uint32': case 'sint32': case 'fixed32': case 'sfixed32': result = 'Integer'; break; case 'int64': case 'uint64': case 'sint64': case 'fixed64': case 'sfixed64': result = 'Long'; break; case 'bool': result = 'Boolean'; break; } return result; } /** * Discards everthing before the last dot * @param {String} name - the Protobuf type name * @return {String} the unqualified string * @private */ static unqualify(name) { let result = name; // discard the qualified name for types let lastDotIndex = name.lastIndexOf('.'); if(lastDotIndex >= 0) { result = result.substring(lastDotIndex+1); } return result; } }
JavaScript
class Cat { /** * Generates cats randomly. * * @returns {Cat} a randomly generated cat */ static generateRandom() { const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const charLength = characters.length; const length = 32; let dna = ""; for (let i = 0; i < length; i++) { dna += characters.charAt(Math.floor(Math.random() * charLength)); } return new Cat(dna); // return new instance of cat } /** * Creates new cat from provided DNA sequence. * * @param {string} dna a string of 32 characters with range `[A-Z]`. * @param {[catADNA: string, catBDNA: string]} parents dna of two cat parents * @param {number} id of persisted cat * */ constructor(dna, parents = [], id = null) { // validate DNA const regex = new RegExp("[A-Z]{32}"); if (!regex.test(dna)) { throw "DNA must match [A-Z]{32}"; } // set DNA this._dna = dna; // set id this._id = id; // set parents this._parents = parents; } /** * @returns {string} DNA sequence of cat */ get dna() { return this._dna; } /** * @returns {number} id of cat */ get id() { return this._id; } /** * @returns {[catADNA: string, catBDNA: string]} parents of cat */ get parents() { return this._parents; } /** * @returns {boolean} true if parents not empty */ get isKitten() { return this._parents && this._parents.length !== 0; } /** * Produces new cat from DNA of this cat and given cat. * * @param {Cat} cat will share DNA with this cat. * @returns {Cat} new cat from combined DNA. */ mate(cat) { const parents = [this.dna, cat.dna]; // generate new dna const a = this.dna.slice(0, 16).split(""); const b = cat.dna.slice(0, 16).split(""); let newDna = ""; for (let i = 0; i < a.length && i < b.length; i++) { newDna += a[i] + b[i]; } return new Cat(newDna, parents); } }
JavaScript
class ElementHandler { // Set elements for extra credit 1: Changing copy/URLs constructor(attribute) { this.attribute = attribute; } element(element) { element.setInnerContent(this.attribute); if (element.tagName === 'a') { // Redirect users to my personal website element.setAttribute('href', 'https://companion-cats.herokuapp.com/'); } } }
JavaScript
class RoleCache extends BaseCache_1.default { /** * Create a new RoleCache * * **This class is automatically instantiated by RainCache** * @param storageEngine Storage engine to use for this cache * @param boundObject Optional, may be used to bind a role object to the cache */ constructor(storageEngine, rain, boundObject) { super(rain); this.storageEngine = storageEngine; this.namespace = "role"; if (boundObject) { this.bindObject(boundObject); } } /** * Get a role via id and guild id of the role * @param id id of the role * @param guildId id of the guild belonging to the role * @returns Returns a Role Cache with a bound role or null if no role was found */ async get(id, guildId) { var _a; if (this.boundObject) { return this; } const role = await ((_a = this.storageEngine) === null || _a === void 0 ? void 0 : _a.get(this.buildId(id, guildId))); if (!role) { return null; } return new RoleCache(this.storageEngine, this.rain, role); } /** * Update a role * @param id - id of the role * @param guildId - id of the guild belonging to the role * @param data - new role data * @returns returns a bound RoleCache once the data was updated. */ async update(id, guildId, data) { var _a; if (this.boundObject) { this.bindObject(data); } if (!guildId) { return Promise.reject("Missing guild id"); } // @ts-ignore if (!data.guild_id) { // @ts-ignore data.guild_id = guildId; } if (!data.id) { data.id = id; } await this.addToIndex(id, guildId); await ((_a = this.storageEngine) === null || _a === void 0 ? void 0 : _a.upsert(this.buildId(id, guildId), this.structurize(data))); if (this.boundObject) return this; return new RoleCache(this.storageEngine, this.rain, data); } /** * Remove a role from the cache * @param id id of the role * @param guildId id of the guild belonging to the role */ async remove(id, guildId) { var _a, _b; const role = await ((_a = this.storageEngine) === null || _a === void 0 ? void 0 : _a.get(this.buildId(id, guildId))); if (role) { await this.removeFromIndex(id, guildId); return (_b = this.storageEngine) === null || _b === void 0 ? void 0 : _b.remove(this.buildId(id, guildId)); } else { return undefined; } } /** * Filter for roles by providing a filter function which returns true upon success and false otherwise * @param fn filter function to use for the filtering * @param guildId id of the guild belonging to the roles * @param ids array of role ids that should be used for the filtering * @returns array of bound role caches */ async filter(fn, guildId = this.boundGuild, ids = undefined) { var _a; const roles = await ((_a = this.storageEngine) === null || _a === void 0 ? void 0 : _a.filter(fn, ids, super.buildId(guildId))); if (!roles) return []; return roles.map(r => new RoleCache(this.storageEngine, this.rain, r)); } /** * Find a role by providing a filter function which returns true upon success and false otherwise * @param fn filter function to use for filtering for a single role * @param guildId id of the guild belonging to the roles * @param ids array of role ids that should be used for the filtering * @returns bound role cache */ async find(fn, guildId = this.boundGuild, ids = undefined) { var _a; const role = await ((_a = this.storageEngine) === null || _a === void 0 ? void 0 : _a.find(fn, ids, super.buildId(guildId))); if (!role) return null; return new RoleCache(this.storageEngine, this.rain, role); } /** * Build a unique key for the role cache entry * @param roleId id of the role * @param guildId id of the guild belonging to the role * @returns the prepared key */ buildId(roleId, guildId) { if (!guildId) { return super.buildId(roleId); } return `${this.namespace}.${guildId}.${roleId}`; } }
JavaScript
class RealtimeControlStep extends AbstractStep { constructor(reporter, buffer, config) { super(reporter, buffer, config, 'RealTimeControlStep', 'Real-time control step, measuring raw Kuzzle response time'); } run(callback) { super.run(); const fn = (client, doc, cb) => { client.benchmarkListener = cb; client.send(JSON.stringify({ index: this.config.kuzzle.index, collection: this.config.kuzzle.collection, controller: 'realtime', action: 'publish', body: doc })); }; this.benchmark(fn, callback); } }
JavaScript
class ActorContextPreprocess extends core_1.Actor { constructor(args) { super(args); } }
JavaScript
class Store { static status = { DEFAULT: 'default state', RESTING: 'resting', ACTION: 'action', MUTATION: 'mutation' } /** * The states should not be muted directly and are therefor we store * the states in a private object. */ #states = {} /** * Creates a Proxy for the state. * This allows the store to notify whenever a specific state has been modified. * @param {string} name * @param {object} initialState * @returns {Proxy} */ #createState = (name, initialState) => new Proxy(initialState, { set: (state, key, value) => { Reflect.set(state, key, value) const changeEvent = `${name}Change` console.debug(`${changeEvent}: ${key}`, value) this.events.publish(`${changeEvent}`, state) this.status = Store.status.RESTING return true } }) constructor(name, { actions, mutations, states }) { this.name = name this.actions = {} this.mutations = {} this.status = Store.status.DEFAULT this.events = new PubSub() if (actions) { this.actions = actions } if (mutations) { this.mutations = mutations } if (states) { this.states = states } } /** * Returns the states object. * Return a copy of the states to prevent any mutations being made directly * to the state. */ get states() { return this.#states } /** * Loops over an array of states and creates a Proxy for each of them * to notify the user whenever that particular state has been changed. */ set states(states) { states.forEach(({ name, state }) => { this.#states[name] = this.#createState(name, state) }) } dispatch(stateKey, actionKey, payload) { if (typeof this.actions[actionKey] !== 'function') { console.error(`Action "${actionKey} doesn't exist.`) return false } if (typeof this.#states[stateKey] === 'undefined') { console.error(`State "${stateKey} doesn't exist.`) return false } // console.groupCollapsed(`ACTION: ${actionKey}`) this.status = Store.status.ACTION const action = this.actions[actionKey] action(stateKey, this, payload) // console.groupEnd() return true } commit(stateKey, mutationKey, payload) { if (typeof this.mutations[mutationKey] !== 'function') { console.log(`Mutation "${mutationKey}" doesn't exist`) return false } this.status = Store.status.MUTATION const mutation = this.mutations[mutationKey] const currentState = this.#states[stateKey] const newState = mutation(currentState, payload) this.#states[stateKey] = Object.assign(currentState, newState) return true } }
JavaScript
class Survey extends React.Component { static propTypes = { history: ReactRouterPropTypes.history, }; static defaultProps = { history: null, }; state = { formState: {}, surveyDetails: null, loading: true, sessionId: null, surveyType: null, errors: {}, }; componentDidMount() { // grab the unique url at the end which gives us survey type and session id const { location } = this.props; const survey = `/get${location.pathname}`; const responseId = survey.split("/")[2]; console.log(survey); // util function that will fetch the questions and session details getQuestions(survey) .then((res) => { const { sessionId, surveyId } = res; this.setState({ surveyDetails: res, loading: false, responseId, sessionId, surveyType: surveyId, }); }) .then(() => { swal({ text: "Many thanks for agreeing to fill in this form. Your feedback will be kept anonymous and will only take you a couple of minutes to complete. Your feedback helps us evaluate and improve the program.", button: "Begin", }); }) .catch(err => console.error(err.stack)); } // function that will check if the div for the answer has been selected and if so add that answer to the formstate selectCheckedItem = (value, questionId) => { const state = this.state.formState; state[questionId] = value; this.setState({ formState: state }); // this.checkSelected(elementId, questionId) console.log("FORMSTATE", this.state.formState); }; // check for any changes to the survey inputs and add them to the formstate handleChange = (e) => { const question = e.target.name; const state = this.state.formState; let answer; // if a checkbox we need to treat differently as this will be an array of answers if (e.target.type === "checkbox") { answer = e.target.value; if (!state[question]) { state[question] = [answer]; } else if (!state[question].includes(answer)) { state[question].push(answer); } else if (state[question].includes(answer)) { const index = state[question].indexOf(answer); state[question].splice(index, 1); } } else { // if any other type we assign the value to answer and put it in the state answer = e.target.value; state[question] = answer; } this.setState(() => ({ formState: state, })); console.log("FORMSTATE", this.state.formState); }; handleOther = (e) => { const question = e.target.name; const state = this.state.formState; let answer; if (e.target.id === "other-checkbox") { answer = `Other: ${e.target.value}`; if (!state[question].includes(answer)) { state[question].push(answer); } else if (state[question].includes(answer)) { const index = state[question].indexOf(answer); state[question].splice(index, 1); } if (state[question].includes("Other: ")) { const index = state[question].indexOf("Other: "); state[question].splice(index, 1); } } else { answer = `Other: ${e.target.value}`; state[question] = answer; } this.setState(() => ({ formState: state, })); console.log("FORMSTATE", this.state.formState); }; // function to deal with the matrix rating questions // where there are multiple rows with sub questions and options handleMatrix = (row, answer, question) => { const state = this.state.formState; if (!state[question]) { state[question] = {}; state[question][row] = answer; } else { state[question][row] = answer; } this.setState(() => ({ formState: state, })); console.log("FORMSTATE", this.state.formState); }; // when participant submits form // this puts the required info into an object and sends to server handleSubmit = (e) => { e.preventDefault(); const { history } = this.props; const { responseId, formState, sessionId, surveyType, } = this.state; console.log("RESPONSEID", responseId); const formSubmission = { formState, sessionId, surveyType }; // console.log(formSubmission); axios .post(`/submit/${responseId}`, formSubmission) .then((result) => { swal("Done!", "Thanks for submitting your feedback!", "success").then(() => history.push("/")); }) .catch((err) => { console.log("ERR", err); this.setState({ errors: err.response.data, }); swal({ icon: "error", title: "Please answer all required questions", }); }); }; render() { const { loading, surveyDetails, formState, errors, } = this.state; if (loading) { return <h3>Loading...</h3>; } const { sessionDate, trainerName, surveyQs } = surveyDetails; return ( <SurveyQs> <SurveyHeader> <h1>Training Survey</h1> <Image src={Logo} alt="Logo" /> </SurveyHeader> <main> <SessionDetails> <h3>Session Details:</h3> <p> <span>Session Date: </span> {sessionDate} </p> <p> <span>Trainer: </span> {trainerName} </p> </SessionDetails> <Disclaimer> <h3>Privacy notice</h3> <p> RSPH will use your information to evaluate the outcomes of our mental health promotion project Connect 5 at national and regional level. The quantitative results of this survey will be presented in an aggregated manner and all comments will be anonymous. </p> <p> Our legal basis for processing your information is to fulfill our legitimate interests as a developer of public health projects and manage the programs we offer. Managing development projects includes administering records, providing and organising activities; arranging training; events; webinars; conferences; special interest groups; awards; CPD; education; research; monitoring for equal opportunity purposes; advising you of our services; maintaining our own accounts and records. </p> <p> We will retain your personal information for the duration of your association with RSPH. When your association with us expires we will continue to retain some of your information in order to be able to prove your association if needed. We will delete the information which is no longer required for six years after your association expires. We will send you relevant information about the services we provide to our members. </p> <p> We may share some of your personal information with our commissioners such as Health Education England or the organisation that has commissioned the Connect 5 training you received. We will not share your personal information with any other organisation without your prior consent, unless we are required to do so by law. For further information on how your information is used, how we maintain the security of your information, and your rights to access the information we hold on you, please see our {" "} <a href="https://www.rsph.org.uk/privacy-policy.html">privacy policy</a> . </p> </Disclaimer> <Form onSubmit={this.handleSubmit}> <h3>Survey Questions:</h3> <Questions questions={surveyQs} onChange={this.handleChange} handleMatrix={this.handleMatrix} handleOther={this.handleOther} answers={formState} selectCheckedItem={this.selectCheckedItem} errors={errors} /> <button type="submit">Submit Feedback</button> </Form> </main> </SurveyQs> ); } }
JavaScript
class AppRequests { constructor() { /** * Get all github repositories of the user by username request. * @param {string} userName */ this.getUserRepositories = (userName) => { return axios .get(`https://api.github.com/users/${userName}/repos`) .then((response) => response.data) .catch((error) => { console.log(error); return []; }); }; } }
JavaScript
class Json { constructor() { this.defaultColors = { text: "#6666ff", level0: "#aa4400", level1: "#aaaa00", level2: "#66aa00", level3: "#444488", level4: "#884488", level5: "#882244", }; this.useColors = true; this.useOwnColors = false; this.ownColors = false; this.actualColors = this.defaultColors; this.response = { success: true, data: "", }; this.spaces = 2; } /********** Getters and Getters **********/ get defaultColors() { return this._defaultColors; } set defaultColors(value) { this._defaultColors = value; } get useColors() { return this._useColors; } set useColors(value) { this._useColors = value; this.loadColorProfile(); } get useOwnColors() { return this._useOwnColors; } set useOwnColors(value) { this._useOwnColors = value; this.loadColorProfile(); } get ownColors() { return this._ownColors; } set ownColors(value) { this._ownColors = value; this.loadColorProfile(); } get spaces() { return this._spaces; } set spaces(value) { this._spaces = value; } loadColorProfile() { if (this.useColors) { if (this.useOwnColors) { this.actualColors = this.defaultColors; for (let color in this.ownColors) { this.actualColors[color] = this.ownColors[color]; } this.actualColors = this.defaultColors; } else this.actualColors = this.defaultColors; } } minimize(json) { let jsonArray = json.split(/\r?\n/); jsonArray = jsonArray.map((line) => line.trim()); let result = ""; jsonArray.forEach((res) => (result += res)); return result; } humanize(js) { let json = this.minimize(js); let result = ""; let level = 0; for (let i = 0; i < json.length; i++) { switch (json[i]) { case "{": result += json[i]; level += 1; result += "\n" + this.getSpaces(level); break; case "[": result += json[i]; json[i + 1] === "{" ? () => {} : (result += "\n" + this.getSpaces(level)); break; case ",": result += json[i] + "\n" + this.getSpaces(level); break; case "]": if (json[i - 1] != "}") { result += "\n"; //level--; result += this.getSpaces(level); } if (json[i + 1] == ",") { result += json[i]; } else { if (json[i - 1] == "}") result += json[i] + "\n" + this.getSpaces(level); else { result += json[i] + "\n" + this.getSpaces(level); } } break; case "}": level -= 1; if (i != json.length - 1) result += "\n" + this.getSpaces(level); else result = result.slice(0, -this.spaces); if ( json[i + 1] == "," || json[i + 1] == "]" || i == json.length - 1 ) { result += json[i]; } else { if (i != json.length - 1) { result += "\n"; result += "\n" + this.getSpaces(level); } else { level = 0; } this.getSpaces(level) + json[i]; } break; default: result += json[i]; break; } } return result; } getSpaces = (level) => { let outcome = ""; for (let j = 1; j <= level * this.spaces; j++) { outcome += " "; } return outcome; }; getHtml = (json) => { let res = this.humanize(json); let theJson; let result = `<div class='terminal-json'>`; if (res) { theJson = res; for (let i = 0; i < theJson.length; i++) { switch (theJson[i]) { case " ": result += "&nbsp"; break; case "\n": result += "<br>"; default: result += theJson[i]; } } this.response.success = true; this.response.data = result + "</div>"; console.log(this.response); if (this.useColors && this.response.success) { this.response = this.colorizeHtmlJson(this.response.data); } return this.response; } else return this.response; }; colorizeHtmlJson = (json) => { this.loadColorProfile(); console.log(this.actualColors); let result = ""; let inQuotes = false; const { text, level1, level2, level3, level4, level5 } = this.actualColors; let level = 1; for (let char = 0; char < json.length; char++) { const actualCharacter = json[char]; switch (actualCharacter) { case "{": console.log(level); result += this.startSpan(level); result += actualCharacter; result += this.endSpan(); level++; break; case "[": result += this.startSpan(level); result += actualCharacter; result += this.endSpan(); break; case '"': if (inQuotes) { result += actualCharacter; result += this.endSpan(); inQuotes = false; } else { result += this.startSpan(); result += actualCharacter; inQuotes = true; } break; case "}": level--; result += this.startSpan(level); result += actualCharacter; result += this.endSpan(); break; case "]": result += this.startSpan(level); result += actualCharacter; result += this.endSpan(); break; default: result += actualCharacter; } } return result; }; startSpan = (level) => { let color = ""; if (level) { color = "level" + level; } else { color = "text"; } return `<span style='color: ${this.actualColors[color]}'>`; }; endSpan = () => { return "</span>"; }; }
JavaScript
class Example3 extends Phaser.Scene { constructor() { super({key: "Example3"}); } preload() { this.load.audio('fire', ['assets/fire.mp3']); } create() { this.soundFX = this.sound.add("fire", {loop: "true"}); this.soundFX.play(); this.soundFX.rate = 4.0; this.input.keyboard.on('keydown_L', (e) => { this.soundFX.loop = !this.soundFX.loop; if (this.soundFX.loop) this.soundFX.play(); }); this.input.keyboard.on("keydown_P", (e) => { if(this.soundFX.isPlaying) this.soundFX.pause(); else this.soundFX.resume(); }) } update(delta) { } }
JavaScript
class Customer { /** * Creates an instance of Customer. * @param {number} [id] the unique id of a customer * @memberof Customer */ constructor (id) { if (typeof id !== 'undefined') { this.id = parseInt(id); } } /** * Create a customer in the database. * @param {object} values JSON formatted object containing * the customer values with which to handle a query * @memberof Customer */ post (values) { return new Promise((resolve, reject) => { if (typeof values === 'object') { this.values = values; db.execute('INSERT INTO users SET username = ?, email = ?, password = ?', [values.id, values.email, values.password], (err, row) => { if (err) reject(err); resolve(row); }); } else { reject(new Error('Missing or bad set of values')); } }); } /** * Get customers from the database. * @memberof Customer */ get () { if (typeof this.id === 'number') { const id = this.id; return new Promise((resolve, reject) => { db.execute(`SELECT ID, name, address, \`zip code\`, phone, city, country, notes, SID FROM customer_list WHERE ID = ?`, [id], (err, row) => { if (err) reject(err); resolve(row); }); }); } else { return new Promise((resolve, reject) => { db.execute(`SELECT ID, name, address, \`zip code\`, phone, city, country, notes, SID FROM customer_list`, (err, rows) => { if (err) reject(err); resolve(rows); }); }); } } /** * Update a customer in the database. * @param {object} values JSON formatted object containing * the customer values with which to handle a query * @memberof Customer */ patch (values) { const id = this.id; return new Promise((resolve, reject) => { if (typeof values === 'object') { const SQLarray = []; for (const key in values) { SQLarray.push(`${key} = '${values[key]}'`); } db.execute(`UPDATE users SET ${SQLarray.toString()} WHERE username = ?`, [id], (err, row) => { if (err) reject(err); resolve(row); }); } else { reject(new Error('Missing or bad set of values')); } }); } /** * Delete a customer from the database * @memberof Customer */ delete () { const id = this.id; return new Promise((resolve, reject) => { db.execute('DELETE FROM customer WHERE ID = ?', [id], (err, row) => { if (err) reject(err); resolve(row); }); }); } /** * Get full payment history of a customer * @param {number} [paymentId] - the unique id of a payment * @memberof Customer */ payments (paymentId) { const id = this.id; if (typeof paymentId !== 'undefined') { const payId = parseInt(paymentId); return new Promise((resolve, reject) => { db.execute(`SELECT payment_id, customer_id, staff_id, rental_id, amount, payment_date, last_update FROM sakila.payment WHERE customer_id = ? AND payment_id = ?`, [id, payId], (err, rows) => { if (err) reject(err); resolve(rows); }); }); } else { return new Promise((resolve, reject) => { db.execute(`SELECT payment_id, customer_id, staff_id, rental_id, amount, payment_date, last_update FROM sakila.payment WHERE customer_id = ?`, [id], (err, rows) => { if (err) reject(err); resolve(rows); }); }); } } }
JavaScript
class SasDefinitionBundle { /** * Create a SasDefinitionBundle. * @member {string} [id] The SAS definition id. * @member {string} [secretId] Storage account SAS definition secret id. * @member {object} [parameters] The SAS definition metadata in the form of * key-value pairs. * @member {object} [attributes] The SAS definition attributes. * @member {boolean} [attributes.enabled] the enabled state of the object. * @member {date} [attributes.created] Creation time in UTC. * @member {date} [attributes.updated] Last updated time in UTC. * @member {object} [tags] Application specific metadata in the form of * key-value pairs */ constructor() { } /** * Defines the metadata of SasDefinitionBundle * * @returns {object} metadata of SasDefinitionBundle * */ mapper() { return { required: false, serializedName: 'SasDefinitionBundle', type: { name: 'Composite', className: 'SasDefinitionBundle', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, secretId: { required: false, readOnly: true, serializedName: 'sid', type: { name: 'String' } }, parameters: { required: false, readOnly: true, serializedName: 'parameters', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, attributes: { required: false, readOnly: true, serializedName: 'attributes', type: { name: 'Composite', className: 'SasDefinitionAttributes' } }, tags: { required: false, readOnly: true, serializedName: 'tags', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } } } } }; } }
JavaScript
class ChildMixinOne { /** * Tests $construct logic for classes and, especially, mixins. * * @private * @param {*} cmoOne - A class dependency for test. * @param {*} cmoTwo - A class dependency for test. * @returns {Object|boolean|void} Can return overrides or can halt $construct execution * for classes down the line by returning false. */ $construct( cmoOne, cmoTwo ) { this.__cmoOne = cmoOne; this.__cmoTwo = cmoTwo; // This method is being provided by a simple helper mixin // (`Core.debug.mixin.CallTrackerMixin`) this.logManualMethodCall( "$construct", "ChildMixinOne", arguments, this ); } /** * This should execute... * * @returns {void} */ $beforeConstruct() { // This method is being provided by a simple helper mixin (`Core.debug.mixin.CallTrackerMixin`) this.logManualMethodCall( "$beforeConstruct", "ChildMixinOne", arguments, this ); } /** * This should execute... * * @returns {void} */ $afterConstruct() { // This method is being provided by a simple helper mixin (`Core.debug.mixin.CallTrackerMixin`) this.logManualMethodCall( "$afterConstruct", "ChildMixinOne", arguments, this ); } /** * This should execute... * * @returns {void} */ $beforeReady() { // This method is being provided by a simple helper mixin (`Core.debug.mixin.CallTrackerMixin`) this.logManualMethodCall( "$beforeReady", "ChildMixinOne", arguments, this ); } /** * This should execute... * * @returns {void} */ $afterReady() { // This method is being provided by a simple helper mixin (`Core.debug.mixin.CallTrackerMixin`) this.logManualMethodCall( "$afterReady", "ChildMixinOne", arguments, this ); } }