language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Help extends React.Component { constructor(props) { super(props); this.handleBackButtonClick = this.handleBackButtonClick.bind(this); this.handleListItemClick = this.handleListItemClick.bind(this); this.handleLinkClick = this.handleLinkClick.bind(this); this.render = this.render.bind(this) this.renderHelpListItems = this.renderHelpListItems.bind(this) this.renderHelpListItem = this.renderHelpListItem.bind(this) this.renderPage = this.renderPage.bind(this) this.renderRules = this.renderRules.bind(this) this.renderRulesEn = this.renderRulesEn.bind(this) this.renderContact = this.renderContact.bind(this) this.renderLegal = this.renderLegal.bind(this) this.state = { rulesPageIsOpen: false, contactPageIsOpen: false, legalPageIsOpen: false, } } /** * Localize a string in the context of the help page * @param {string} string to be localized */ l(string) { return this.props.l(`help.${string}`); } /** * Handle clicks on items in the list * @param {itemId} id of the item * @param {e} click event */ handleListItemClick(item, e) { this.setState({ rulesPageIsOpen: item == "rules", contactPageIsOpen: item == "contact", legalPageIsOpen: item == "legal", }); } /** * Handle clicks on items in the list * @param {itemId} id of the item * @param {e} click event */ handleLinkClick(url, e) { window.open(url, "_blank"); } handleBackButtonClick() { this.setState({ rulesPageIsOpen: false, contactPageIsOpen: false, legalPageIsOpen: false, }); } render() { if (this.state.rulesPageIsOpen) { return this.renderPage("rules", this.renderRules); } else if (this.state.contactPageIsOpen) { return this.renderPage("contact", this.renderContact); } else if (this.state.legalPageIsOpen) { return this.renderPage("legal", this.renderLegal); } else { return ( <Ons.Page> <Ons.Row height="100%"> <Ons.Col verticalAlign="center"> <Ons.List> {this.renderHelpListItems()} </Ons.List> </Ons.Col> </Ons.Row> </Ons.Page> ); } } renderHelpListItems() { var websiteBaseUrl = "https://lbraun.github.io/geofreebie/"; var wikiBaseUrl = "https://github.com/lbraun/geofreebie/wiki/"; var rules = "Rules-(English)"; var privacy_policy = "privacy_policy_en.html"; var consent_form = "consent_form_en.pdf"; if (this.props.locale == "de") { rules = "Rules-(German)"; privacy_policy = "privacy_policy_de.html"; consent_form = "consent_form_de.pdf"; } var listItems = []; listItems.push(this.renderHelpListItemLink( "help", wikiBaseUrl )); listItems.push(this.renderHelpListItemLink( "rules", wikiBaseUrl + rules )); // listItems.push(this.renderHelpListItem("rules")); listItems.push(this.renderHelpListItem("contact")); // listItems.push(this.renderHelpListItem("legal")); listItems.push(this.renderHelpListItemLink( "privacy", websiteBaseUrl + privacy_policy )); listItems.push(this.renderHelpListItemLink( "consent", websiteBaseUrl + consent_form )); return listItems; } renderHelpListItem(pageId) { return ( <Ons.ListItem modifier={"chevron"} tappable={true} onClick={this.handleListItemClick.bind(this, pageId)} id={`help-list-item-${pageId}`} key={pageId}> {this.l(pageId)} </Ons.ListItem> ); } renderHelpListItemLink(pageId, url) { return ( <Ons.ListItem modifier={"chevron"} tappable={true} onClick={this.handleLinkClick.bind(this, url)} id={`help-list-item-${pageId}`} key={pageId}> {this.l(pageId)} </Ons.ListItem> ); } renderPage(pageName, renderContent) { return ( <Ons.Page> <div style={{margin: "15px"}}> <Ons.Row> <Ons.Col> <Ons.Button onClick={this.handleBackButtonClick}> {this.props.l("app.back")} </Ons.Button> </Ons.Col> <Ons.Col style={{textAlign: "right"}}> <localeMenu.LocaleMenu locale={this.props.locale} handleLocaleChange={this.props.handleLocaleChange} /> </Ons.Col> </Ons.Row> <h1> {this.l(pageName)} </h1> {renderContent()} </div> </Ons.Page> ); } renderRules() { if (this.props.locale == "de") { return this.renderRulesDe(); } else { return this.renderRulesEn(); } } renderRulesEn() { return ( <div> <p>1. Only post things that you want to give away for free. Those who offer something should not expect anything in exchange.</p> <p>2. Users are not allowed to offer anything illegal.</p> <p>3. The person offering can choose the recipient of their offer any way they like.</p> <p>4. Private messages from strangers on Facebook might not end up in your inbox. Check your message requests too!</p> <p>5. Be kind and respectful. You may be blocked from the app if you do not respect the community, its rules, and its members.</p> </div> ); } renderRulesDe() { return ( <div> <p>1. Only post things that you want to give away for free. Those who offer something should not expect anything in exchange.</p> <p>2. Users are not allowed to offer anything illegal.</p> <p>3. The person offering can choose the recipient of their offer any way they like.</p> <p>4. Private messages from strangers on Facebook might not end up in your inbox. Check your message requests too!</p> <p>5. Be kind and respectful. You may be blocked from the app if you do not respect the community, its rules, and its members.</p> </div> ); } renderContact() { return ( <div> {this.l("questionsOrConcerns")} <br /> <br /> <a href={`mailto:${config.app.adminEmail}`}>{config.app.adminEmail}</a> <br /> <br /> {this.l("thanks")}! <br /> Lucas Braun </div> ); } renderLegal() { } }
JavaScript
class Channel { constructor(data) { this.id = data.id; this.createdAt = (this.id / 4194304) + 1420070400000; this.type = data.type; } }
JavaScript
class TextArea extends Component { constructor(data) { super(data); if (!data.name) data.name = data.id; if (!data.label) data.label = data.id; this.textareaId = this.id + '-textarea'; this.template = ` <div class="form-elem form-elem--text-textarea"> <label for="${this.textareaId}"> <span class="form-elem__label">${data.label}</span> <textarea id="${this.textareaId}" class="form-elem__textarea" name="${data.name}" placeholder="${data.placeholder || ''}" ${data.maxlength ? 'maxlength="' + data.maxlength + '"' : ''} ${data.disabled ? 'disabled' : ''} >${data.value || ''}</textarea> </label> </div> `; this.value = data.value || ''; this.errorComp = this.addChild({ id: this.id + '-error-msg', class: 'form-elem__error-msg', }); if (data.error) data.class = 'form-elem--error'; } addListeners(data) { this.addListener({ id: this.textareaId + '-keyup', target: document.getElementById(this.textareaId), type: 'keyup', fn: (e) => { this.value = e.target.value; this.data.value = this.value; if (data.changeFn) data.changeFn(e); }, }); } paint(data) { const textareaElem = document.getElementById(this.textareaId); if (data.value !== undefined) { this.value = data.value; this.data.value = data.value; } textareaElem.value = this.value; if (data.error) { this.elem.classList.add('form-elem--error'); if (data.error.errorMsg) { this.elem.classList.add('form-elem--error-msg'); this.errorComp.draw({ text: data.error.errorMsg }); } } if (data.disabled) textareaElem.setAttribute('disabled', ''); } error(err) { if (err) { this.errorComp.discard(); this.elem.classList.add('form-elem--error'); if (err.errorMsg && !this.data.hideMsg) { this.elem.classList.add('form-elem--error-msg'); this.errorComp.draw({ text: err.errorMsg }); } } else { this.errorComp.discard(); this.elem.classList.remove('form-elem--error'); this.elem.classList.remove('form-elem--error-msg'); } } setValue(newValue, noChangeFn) { this.value = String(newValue); const textareaElem = document.getElementById(this.textareaId); textareaElem.value = this.value; this.data.value = this.value; if (noChangeFn) return; if (this.data.changeFn) this.data.changeFn({ target: textareaElem }); } }
JavaScript
class CalendarEvent { /** * Creates a new event instance given the id, the event paired with the * schedule, the schedule, the time span of the event, and the day on the * calendar the event belongs to. * * @param id The relatively unique identifier of this event. * @param event The event which created this instance. * @param time The time span of this event. * @param actualDay The day on the calendar this event is for. */ constructor(id, event, time, actualDay) { /** * The row this event is on in a visual calendar. An event can span multiple * days and it is desirable to have the occurrence on each day to line up. * This is only set when [[Calendar.updateRows]] is true or manually set. * This value makes sense for visual calendars for all day events or when the * visual calendar is not positioning events based on their time span. */ this.row = 0; /** * The column this event is on in a visual calendar. An event can have its * time overlap with another event displaying one of the events in another * column. This is only set when [[Calendar.updateColumns]] is true or * manually set. This value makes sense for visual calendars that are * displaying event occurrences at specific times positioned accordingly. */ this.col = 0; this.id = id; this.event = event; this.time = time; this.day = actualDay; this.fullDay = event.schedule.isFullDay(); this.meta = event.schedule.getMeta(time.start); this.cancelled = event.schedule.isCancelled(time.start); this.starting = time.isPoint || time.start.sameDay(actualDay); this.ending = time.isPoint || time.end.relative(-1).sameDay(actualDay); } /** * The id of the schedule uniqe within the calendar which generated this event. */ get scheduleId() { return Math.floor(this.id / Constants.MAX_EVENTS_PER_DAY); } /** * The start timestamp of the event. */ get start() { return this.time.start; } /** * The end timestamp of the event. */ get end() { return this.time.end; } /** * The schedule which generated this event. */ get schedule() { return this.event.schedule; } /** * The related event data. */ get data() { return this.event.data; } /** * An [[IdentifierInput]] for the start of this event. */ get identifier() { return this.identifierType.get(this.start); } /** * The [[Identifier]] for this event. Either [[Identifier.Day]] or * [[Identifier.Time]]. */ get identifierType() { return this.schedule.identifierType; } /** * Returns a delta value between 0 and 1 which represents where the * [[CalendarEvent.start]] is relative to [[CalendarEvent.day]]. The delta * value would be less than 0 if the start of the event is before * [[CalendarEvent.day]]. */ get startDelta() { return this.time.startDelta(this.day); } /** * Returns a delta value between 0 and 1 which represents where the * [[CalendarEvent.end]] is relative to [[CalendarEvent.day]]. The delta value * would be greater than 1 if the end of the event is after * [[CalendarEvent.day]]. */ get endDelta() { return this.time.endDelta(this.day); } /** * Calculates the bounds for this event if it were placed in a rectangle which * represents a day (24 hour period). By default the returned values are * between 0 and 1 and can be scaled by the proper rectangle dimensions or the * rectangle dimensions can be passed to this function. * * @param dayHeight The height of the rectangle of the day. * @param dayWidth The width of the rectangle of the day. * @param columnOffset The offset in the rectangle of the day to adjust this * event by if it intersects or is contained in a previous event. This also * reduces the width of the returned bounds to keep the bounds in the * rectangle of the day. * @param clip `true` if the bounds should stay in the day rectangle, `false` * and the bounds may go outside the rectangle of the day for multi-day * events. * @param offsetX How much to translate the left & right properties by. * @param offsetY How much to translate the top & bottom properties by. * @returns The calculated bounds for this event. */ getTimeBounds(dayHeight = 1, dayWidth = 1, columnOffset = 0.1, clip = true, offsetX = 0, offsetY = 0) { return this.time.getBounds(this.day, dayHeight, dayWidth, this.col * columnOffset, clip, offsetX, offsetY); } /** * Changes the cancellation status of this event. By default this cancels * this event - but `false` may be passed to undo a cancellation. * * @param cancelled Whether the event should be cancelled. */ cancel(cancelled = true) { this.schedule.setCancelled(this.start, cancelled); this.cancelled = cancelled; return this; } /** * Changes the exclusion status of this event. By default this excludes this * event - but `false` may be passed to undo an exclusion. * * @param excluded Whether the event should be excluded. */ exclude(excluded = true) { this.schedule.setExcluded(this.start, excluded); return this; } /** * Moves this event to potentially another day and time. A move is * accomplished by excluding the current event and adding an inclusion of the * new day & time. Any [[CalendarEvent.meta]] on this event will be moved to * the new event. If the schedule represents a single event * ([[Schedule.isSingleEvent]]) then the schedule frequencies are updated * to match the timestamp provided. * * @param toTime The timestamp to move this event to. * @returns Whether the event was moved to the given time. */ move(toTime) { return this.schedule.move(toTime, this.start); } }
JavaScript
class ApiCredentialCache extends BaseCacheManagement { /** * Constructor for API credential cache. * * @param {object} params: cache key generation & expiry related params * @param {string} params.apiKey: api key * * @augments BaseCacheManagement * * @constructor */ constructor(params) { super(params); const oThis = this; oThis.apiKey = params.apiKey; // Call sub class method to set cache level oThis._setCacheLevel(); // Call sub class method to set cache key using params provided oThis._setCacheKeySuffix(); // Call sub class method to set cache expiry using params provided oThis._setCacheExpiry(); // Call sub class method to set cache implementer using params provided oThis._setCacheImplementer(); } /** * Fetch data from cache and decrypt. * * @return {Promise<Result>} */ async fetchDecryptedData() { const oThis = this; const fetchFromCacheRsp = await oThis.fetch(); if (fetchFromCacheRsp.isFailure()) { return Promise.reject(fetchFromCacheRsp); } const cachedResponse = fetchFromCacheRsp.data; if (!cachedResponse.apiKey) { return responseHelper.successWithData(cachedResponse); } cachedResponse.apiSecret = await localCipher.decrypt(coreConstants.CACHE_SHA_KEY, cachedResponse.apiSecret); return responseHelper.successWithData(cachedResponse); } /** * Set cache level. * * @sets oThis.cacheLevel * * @private */ _setCacheLevel() { const oThis = this; oThis.cacheLevel = cacheManagementConst.kitSaasSubEnvLevel; } /** * Set cache key. * * @sets oThis.cacheKeySuffix * * @private */ _setCacheKeySuffix() { const oThis = this; // It uses shared cache key between company api and saas. Any changes in key here should be synced. oThis.cacheKeySuffix = `cs_${oThis.apiKey.toLowerCase()}`; } /** * Set cache expiry in oThis.cacheExpiry. * * @sets oThis.cacheExpiry * @private */ _setCacheExpiry() { const oThis = this; oThis.cacheExpiry = 86400; // 24 hours } /** * Fetch data from source and return client secrets using local encryption. * * @returns {Promise<Promise<*|*|Promise<any>>|*|result>} * @private */ async _fetchDataFromSource() { const oThis = this; const clientApiCredentialData = await new ApiCredentialModel().fetchByApiKey(oThis.apiKey); if (!clientApiCredentialData[0]) { return responseHelper.paramValidationError({ internal_error_identifier: 'scm_ac_1', api_error_identifier: 'client_api_credentials_expired', params_error_identifiers: ['invalid_api_key'], error_config: errorConfig }); } const dbRecord = clientApiCredentialData[0]; const KMSObject = new KmsWrapper(ApiCredentialModel.encryptionPurpose); const decryptedSalt = await KMSObject.decrypt(dbRecord.api_salt); if (!decryptedSalt.Plaintext) { return responseHelper.paramValidationError({ internal_error_identifier: 'cm_cs_2', api_error_identifier: 'client_api_credentials_expired', params_error_identifiers: ['invalid_api_key'], error_config: errorConfig }); } const infoSalt = decryptedSalt.Plaintext; const apiSecret = await localCipher.decrypt(infoSalt, dbRecord.api_secret); const apiSecretEncr = await localCipher.encrypt(coreConstants.CACHE_SHA_KEY, apiSecret); return Promise.resolve( responseHelper.successWithData({ clientId: dbRecord.client_id, apiKey: oThis.apiKey, apiSecret: apiSecretEncr, expiryTimestamp: dbRecord.expiry_timestamp }) ); } }
JavaScript
class IMTHITL extends IMTBase { constructor() { super(); this.type = IMTBase.MODULETYPE_HITL; } /** * Executes the HITL flow. * * @param {Object} bundle Collection of data to process. * @callback done Callback to call when operations are done. * @param {Error} err Error on error, otherwise null. */ execute(bundle, done) { throw new Error("Must override a superclass method 'execute'."); } }
JavaScript
class Editable { constructor (instanceConfig) { const defaultInstanceConfig = { window: window, defaultBehavior: true, mouseMoveSelectionChanges: false, browserSpellcheck: true } this.config = Object.assign(defaultInstanceConfig, instanceConfig) this.win = this.config.window this.editableSelector = `.${config.editableClass}` if (!rangy.initialized) { rangy.init() } this.dispatcher = new Dispatcher(this) if (this.config.defaultBehavior === true) { this.dispatcher.on(createDefaultEvents(this)) } } /** * @returns the default Editable configs from config.js */ static getGlobalConfig () { return config } /** * Set configuration options that affect all editable * instances. * * @param {Object} global configuration options (defaults are defined in config.js) * log: {Boolean} * logErrors: {Boolean} * editableClass: {String} e.g. 'js-editable' * editableDisabledClass: {String} e.g. 'js-editable-disabled' * pastingAttribute: {String} default: e.g. 'data-editable-is-pasting' * boldTag: e.g. '<strong>' * italicTag: e.g. '<em>' */ static globalConfig (globalConfig) { Object.assign(config, globalConfig) clipboard.updateConfig(config) } /** * Adds the Editable.JS API to the given target elements. * Opposite of {{#crossLink "Editable/remove"}}{{/crossLink}}. * Calls dispatcher.setup to setup all event listeners. * * @method add * @param {HTMLElement|Array(HTMLElement)|String} target A HTMLElement, an * array of HTMLElement or a query selector representing the target where * the API should be added on. * @chainable */ add (target) { this.enable(target) // TODO check css whitespace settings return this } /** * Removes the Editable.JS API from the given target elements. * Opposite of {{#crossLink "Editable/add"}}{{/crossLink}}. * * @method remove * @param {HTMLElement|Array(HTMLElement)|String} target A HTMLElement, an * array of HTMLElement or a query selector representing the target where * the API should be removed from. * @chainable */ remove (target) { const targets = domArray(target, this.win.document) this.disable(targets) for (const element of targets) { element.classList.remove(config.editableDisabledClass) } return this } /** * Removes the Editable.JS API from the given target elements. * The target elements are marked as disabled. * * @method disable * @param { HTMLElement | undefined } elem editable root element(s) * If no param is specified all editables are disabled. * @chainable */ disable (target) { const targets = domArray(target || `.${config.editableClass}`, this.win.document) for (const element of targets) { block.disable(element) } return this } /** * Adds the Editable.JS API to the given target elements. * * @method enable * @param { HTMLElement | undefined } target editable root element(s) * If no param is specified all editables marked as disabled are enabled. * @chainable */ enable (target, normalize) { const shouldSpellcheck = this.config.browserSpellcheck const targets = domArray(target || `.${config.editableDisabledClass}`, this.win.document) for (const element of targets) { block.init(element, {normalize, shouldSpellcheck}) this.dispatcher.notify('init', element) } return this } /** * Temporarily disable an editable. * Can be used to prevent text selection while dragging an element * for example. * * @method suspend * @param { HTMLElement | undefined } target */ suspend (target) { const targets = domArray(target || `.${config.editableClass}`, this.win.document) for (const element of targets) { element.removeAttribute('contenteditable') } this.dispatcher.suspend() return this } /** * Reverse the effects of suspend() * * @method continue * @param { HTMLElement | undefined } target */ continue (target) { const targets = domArray(target || `.${config.editableClass}`, this.win.document) for (const element of targets) { element.setAttribute('contenteditable', true) } this.dispatcher.continue() return this } /** * Set the cursor inside of an editable block. * * @method createCursor * @param { HTMLElement } element * @param { 'beginning' | 'end' | 'before' | 'after' } position */ createCursor (element, position = 'beginning') { const host = Cursor.findHost(element, this.editableSelector) if (!host) return undefined const range = rangy.createRange() if (position === 'beginning' || position === 'end') { range.selectNodeContents(element) range.collapse(position === 'beginning') } else if (element !== host) { if (position === 'before') { range.setStartBefore(element) range.setEndBefore(element) } else if (position === 'after') { range.setStartAfter(element) range.setEndAfter(element) } } else { error('EditableJS: cannot create cursor outside of an editable block.') } return new Cursor(host, range) } createCursorAtCharacterOffset ({element, offset}) { const textNodes = textNodesUnder(element) const {node, relativeOffset} = getTextNodeAndRelativeOffset({textNodes, absOffset: offset}) const newRange = rangy.createRange() newRange.setStart(node, relativeOffset) newRange.collapse(true) const host = Cursor.findHost(element, this.editableSelector) const nextCursor = new Cursor(host, newRange) nextCursor.setVisibleSelection() return nextCursor } createCursorAtBeginning (element) { return this.createCursor(element, 'beginning') } createCursorAtEnd (element) { return this.createCursor(element, 'end') } createCursorBefore (element) { return this.createCursor(element, 'before') } createCursorAfter (element) { return this.createCursor(element, 'after') } /** * Extract the content from an editable host or document fragment. * This method will remove all internal elements and ui-elements. * * @param {DOM node or Document Fragment} The innerHTML of this element or fragment will be extracted. * @returns {String} The cleaned innerHTML. */ getContent (element) { return content.extractContent(element) } /** * @param {String | DocumentFragment} content to append. * @returns {Cursor} A new Cursor object just before the inserted content. */ appendTo (inputElement, contentToAppend) { const element = content.adoptElement(inputElement, this.win.document) const cursor = this.createCursor(element, 'end') // TODO create content in the right window cursor.insertAfter(typeof contentToAppend === 'string' ? content.createFragmentFromString(contentToAppend) : contentToAppend ) return cursor } /** * @param {String | DocumentFragment} content to prepend * @returns {Cursor} A new Cursor object just after the inserted content. */ prependTo (inputElement, contentToPrepend) { const element = content.adoptElement(inputElement, this.win.document) const cursor = this.createCursor(element, 'beginning') // TODO create content in the right window cursor.insertBefore(typeof contentToPrepend === 'string' ? content.createFragmentFromString(contentToPrepend) : contentToPrepend ) return cursor } /** * Get the current selection. * Only returns something if the selection is within an editable element. * If you pass an editable host as param it only returns something if the selection is inside this * very editable element. * * @param {DOMNode} Optional. An editable host where the selection needs to be contained. * @returns A Cursor or Selection object or undefined. */ getSelection (editableHost) { let selection = this.dispatcher.selectionWatcher.getFreshSelection() if (!(editableHost && selection)) return selection const range = selection.range // Check if the selection is inside the editableHost // The try...catch is required if the editableHost was removed from the DOM. try { if (range.compareNode(editableHost) !== range.NODE_BEFORE_AND_AFTER) { selection = undefined } } catch (e) { selection = undefined } return selection } /** * Enable spellchecking * * @chainable */ setupHighlighting (hightlightingConfig) { this.highlighting = new Highlighting(this, hightlightingConfig) return this } // For backwards compatibility setupSpellcheck (conf) { let marker if (conf.markerNode) { marker = conf.markerNode.outerHTML } this.setupHighlighting({ throttle: conf.throttle, spellcheck: { marker: marker, spellcheckService: conf.spellcheckService } }) this.spellcheck = { checkSpelling: (elem) => { this.highlighting.highlight(elem) } } } /** * Highlight text within an editable. * * By default highlights all occurrences of `text`. * Pass it a `textRange` object to highlight a * specific text portion. * * The markup used for the highlighting will be removed * from the final content. * * * @param {Object} options * @param {DOMNode} options.editableHost * @param {String} options.text * @param {String} options.highlightId Added to the highlight markups in the property `data-word-id` * @param {Object} [options.textRange] An optional range which gets used to set the markers. * @param {Number} options.textRange.start * @param {Number} options.textRange.end * @param {Boolean} options.raiseEvents do throw change events * @return {Number} The text-based start offset of the newly applied highlight or `-1` if the range was considered invalid. */ highlight ({editableHost, text, highlightId, textRange, raiseEvents, type = 'comment'}) { if (!textRange) { return highlightSupport.highlightText(editableHost, text, highlightId, type) } if (typeof textRange.start !== 'number' || typeof textRange.end !== 'number') { error( 'Error in Editable.highlight: You passed a textRange object with invalid keys. Expected shape: { start: Number, end: Number }' ) return -1 } if (textRange.start === textRange.end) { error( 'Error in Editable.highlight: You passed a textRange object with equal start and end offsets, which is considered a cursor and therefore unfit to create a highlight.' ) return -1 } return highlightSupport.highlightRange(editableHost, highlightId, textRange.start, textRange.end, raiseEvents ? this.dispatcher : undefined, type) } /** * Extracts positions of all DOMNodes that match `[data-word-id]` and the `[data-highlight]` * * Returns an object where the keys represent a highlight id and the value * a text range object of shape: * ``` * { start: number, end: number, text: string} * ``` * * @param {Object} options * @param {DOMNode} options.editableHost * @param {String} [options.type] * @return {Object} ranges */ getHighlightPositions ({editableHost, type}) { return highlightSupport.extractHighlightedRanges( editableHost, type ) } removeHighlight ({editableHost, highlightId, raiseEvents}) { highlightSupport.removeHighlight(editableHost, highlightId, raiseEvents ? this.dispatcher : undefined) } decorateHighlight ({editableHost, highlightId, addCssClass, removeCssClass}) { highlightSupport.updateHighlight(editableHost, highlightId, addCssClass, removeCssClass) } /** * Subscribe a callback function to a custom event fired by the API. * * @param {String} event The name of the event. * @param {Function} handler The callback to execute in response to the * event. * * @chainable */ on (event, handler) { // TODO throw error if event is not one of EVENTS // TODO throw error if handler is not a function this.dispatcher.on(event, handler) return this } /** * Unsubscribe a callback function from a custom event fired by the API. * Opposite of {{#crossLink "Editable/on"}}{{/crossLink}}. * * @param {String} event The name of the event. * @param {Function} handler The callback to remove from the * event or the special value false to remove all callbacks. * * @chainable */ off (...args) { this.dispatcher.off.apply(this.dispatcher, args) return this } /** * Unsubscribe all callbacks and event listeners. * * @chainable */ unload () { this.dispatcher.unload() return this } /** * Takes coordinates and uses its left value to find out how to offset a character in a string to * closely match the coordinates.left value. * Takes conditions for the result being on the first line, used when navigating to a paragraph from * the above paragraph and being on the last line, used when navigating to a paragraph from the below * paragraph. * * Internally this sets up the methods used for a binary cursor search and calls this. * * @param {DomNode} element * - the editable hostDOM Node to which the cursor jumps * @param {object} coordinates * - The bounding rect of the preceding cursor to be matched * @param {boolean} requiredOnFirstLine * - set to true if you want to require the cursor to be on the first line of the paragraph * @param {boolean} requiredOnLastLine * - set to true if you want to require the cursor to be on the last line of the paragraph * * @return {Object} * - object with boolean `wasFound` indicating if the binary search found an offset and `offset` to indicate the actual character offset */ findClosestCursorOffset ({ element, origCoordinates, requiredOnFirstLine = false, requiredOnLastLine = false }) { const positionX = this.dispatcher.switchContext ? this.dispatcher.switchContext.positionX : origCoordinates.left return binaryCursorSearch({ host: element, requiredOnFirstLine, requiredOnLastLine, positionX }) } }
JavaScript
class WidgetClass extends BaseModel { static initialize(sequelize) { WidgetClass.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, appId: { type: DataTypes.INTEGER, allowNull: true, comment: 'WidgetClass id where this widget class belongs to' }, name: { type: DataTypes.STRING, allowNull: false, comment: 'User friendly widget name' }, type: { type: DataTypes.STRING, allowNull: false, comment: 'Canonical type of widget' }, connectionType: {type: DataTypes.ENUM('INPUT', 'OUTPUT', 'BOTH'), allowNull: false, defaultValue: 'BOTH', comment: 'This Widget can be connected as input, output or both?'}, description: { type: DataTypes.STRING, allowNull: true }, version: { type: DataTypes.INTEGER, allowNull: false, comment: 'Incrementing version number' }, environment: { type: DataTypes.STRING, allowNull: false, comment: 'Target environment' }, primitive: { type: DataTypes.BOOLEAN, allowNull: true, comment: 'Is this a core Widget Class ?' }, tabs: { type: DataTypes.JSONB, allowNull: false, comment: 'Specification for subnav tabs to show on widget' }, config: { type: DataTypes.JSONB, allowNull: false, comment: 'Specification for component UI and connections' }, parameters: { type: DataTypes.JSONB, allowNull: false, comment: 'Array of parameters used in widgetClass' }, }, { sequelize, modelName: MODEL_NAME, tableName: TABLE_NAME, }); } static associate(models) { WidgetClass.hasMany(models.WidgetInstance); WidgetClass.belongsTo(models.App); } }
JavaScript
class IsLoggedIn { /** * Verify whether a token is passed in the request * * * @param { object } req - The request object * @param { object } res - The response object * @param { function }next - Callback function * * @returns { object } A token with the userId */ static hasToken(req, res, next) { req.token = req.headers['x-access-token'] || req.headers.token || req.query.token; if (!req.token) { return res .status(401) .send({ message: 'You need to be logged in to perform this action.' }); } return next(); } }
JavaScript
class AddUser extends Command { keywords = ["add"]; description = "Add user to group"; guide = "<uid|link|username|full name (mutual)>"; permission = { "*": "*" }; async load() {} async onCall(thread, message, reply, api) { const input = message.args.join(" ") const uid = await getIdByEverything(api, thread.id, input) if (uid === null) { // fullname const users = (await api.getUserID(input)) .filter(u => u.type == "user") .slice(0, 3) if (users.length == 0 || !users[0].userID) throw new Error("We tried our best but failed getting userid") const uids = users.map(u => u.userID) const info = await api.getUserInfo(uids) return uids .map(uid => { const inf = info[uid] return [ `Name: ${inf.name}`, `Gender: ${inf.gender}`, `Mutual to bot: ${inf.isFriend ? "YES" : "NO"}`, `Profile: ${inf.profileUrl}`, `${thread.prefix}${this.keywords[0]} ${uid}` ].join("\n") }) .join("\n\n") } else { await api.addUserToGroup(uid, thread.id) return `Successfully added "${uid}"` } } }
JavaScript
class ContainerRegistryArtifactEventTarget { /** * Create a ContainerRegistryArtifactEventTarget. * @member {string} [mediaType] The MIME type of the artifact. * @member {number} [size] The size in bytes of the artifact. * @member {string} [digest] The digest of the artifact. * @member {string} [repository] The repository name of the artifact. * @member {string} [tag] The tag of the artifact. * @member {string} [name] The name of the artifact. * @member {string} [version] The version of the artifact. */ constructor() { } /** * Defines the metadata of ContainerRegistryArtifactEventTarget * * @returns {object} metadata of ContainerRegistryArtifactEventTarget * */ mapper() { return { required: false, serializedName: 'ContainerRegistryArtifactEventTarget', type: { name: 'Composite', className: 'ContainerRegistryArtifactEventTarget', modelProperties: { mediaType: { required: false, serializedName: 'mediaType', type: { name: 'String' } }, size: { required: false, serializedName: 'size', type: { name: 'Number' } }, digest: { required: false, serializedName: 'digest', type: { name: 'String' } }, repository: { required: false, serializedName: 'repository', type: { name: 'String' } }, tag: { required: false, serializedName: 'tag', type: { name: 'String' } }, name: { required: false, serializedName: 'name', type: { name: 'String' } }, version: { required: false, serializedName: 'version', type: { name: 'String' } } } } }; } }
JavaScript
class TaskList extends Component { state = { reading_materials: [] } componentDidMount() { if ( this.props && this.props.ready === true ){ this.accountReady(this.props) } } // detect props changed componentWillReceiveProps(nextProps) { // current state let current_ready = false if ( this.props && this.props.ready ){ current_ready = this.props.ready } // next state let next_ready = false if (nextProps.ready) { next_ready = nextProps.ready } if ( current_ready !== next_ready){ this.accountReady(nextProps) } } accountReady = ({ login_token }) => { if (login_token) { this.getReadingMaterials(login_token) } else { console.log("user has not login") } } // get reading materials getReadingMaterials = (login_token) => { if (!login_token) { login_token = this.props.login_token } if (!login_token){ console.log("login_token is not ready yet"); return; } const params = { login_token: login_token } MyAPI.getReadingMaterials(params) .then((results) => { if (!results){ return Promise.reject(Error("no results! maybe server error")) } if (results.status !== 'success'){ return Promise.reject(Error(results.message)) } return Promise.resolve(results) }) .then((results) => { if (!results || !results.list || results.list.length === 0){ return Promise.reject(Error("no reading materials found")) } this.setState({ reading_materials: results.list, }) }) .catch((err) => { console.log("err:", err) }) } _materialSelected = ({reading_material_id}) => { const { reading_materials } = this.state const array = reading_materials.map((item) => { if (item._id === reading_material_id){ item.selected = true } else { item.selected = false } return item }) this.setState({ reading_materials: array }) } // render view render() { const { profile, login_token } = this.props const { reading_materials } = this.state if ( !profile || !login_token ){ return (<Loading text="loading..." />) } return( <Container className='completed_task_list' style={{textAlign: 'center'}}> {/* header */} <HeaderAfterLogin /> <Row> <Col> {reading_materials && reading_materials.map((item) => ( <TaskListItem materialSelected={this._materialSelected} item={item} selected={item.selected} key={item._id} /> ))} </Col> </Row> </Container> ) } }
JavaScript
class NavList extends Component { /** * Upgrades all NavList AUI components. * @returns {Array} Returns an array of all newly upgraded components. */ static upgradeElements() { let components = []; Array.from(document.querySelectorAll(SELECTOR_COMPONENT)).forEach(element => { if (!Component.isElementUpgraded(element)) { components.push(new NavList(element)); } }); return components; }; /** * Constructor * @constructor * @param {HTMLElement} element The element of the AUI component. */ constructor(element) { super(element); } /** * Initialize component. */ init() { super.init(); // Refer elements this._actionElements = Array.from(this._element.querySelectorAll(`.${CLASS_ACTION}`)); // Add event handler this._element.addEventListener('click', this._clickHandler = (event) => this._onClick(event)); // Set initial action element active this.setActive(this._element.querySelector(`.${CLASS_IS_ACTIVE}`)); } /** * Dispose component. */ dispose() { super.dispose(); this._element.removeEventListener('click', this._clickHandler); } /** * Updates inidcator position and visibility of paddles. */ update() { this.setActive(this._element.querySelector(`.${CLASS_IS_ACTIVE}`)); } /** * Set an action element at given index active. * @param {index} index The index of action element to set active. */ setActiveByIndex(index) { const i = limit(index, 0, this._actionElements.length); this.setActive(this._actionElements[i]); } /** * Set an action element active. * @param {HTMLElement} activeTarget The action element to set active. */ setActive(activeTarget) { this._actionElements.forEach((item, index) => { const active = (item === activeTarget); item.classList.toggle(CLASS_IS_ACTIVE, active); if (active) { this._index = index; } }); } /** * Handle click of element. * @param {Event} event The event that fired. * @private */ _onClick(event) { // Find closest action element let currentElement = event.target; while (currentElement !== event.currentTarget) { if (currentElement.classList.contains(CLASS_ACTION)) { if (!currentElement.disabled) { this.setActive(currentElement); } break; } currentElement = currentElement.parentNode; } } /** * Returns index. * @returns {number} the index of current active action element. */ get index() { return this._index; } /** * Returns length. * @returns {number} the number of action elements. */ get length() { return this._actionElements.length; } }
JavaScript
class GenerateSitemap { constructor() { // Store total # of file entries generated this.total = 0; // Init terminal logging Util.initLogging.call(this); } // INIT // ----------------------------- // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js async init() { // Early Exit: No user-defined site domain in `/config/main.js` if (!sitemap || !sitemap.url || !sitemap.url.length) return; // ADD TERMINAL SECTION HEADING Logger.persist.header(`\nCreate /sitemap.xml`); // START LOGGING this.startLog(); try { // Get directory and .html file paths from `/dist` let files = await fs.readdir(distPath); this.total = files.length; // Format file paths for XML files = this.formatFilesForXML(files); // Filter out unwanted entry paths files = this.excludeFiles(files); // Build XML source let xmlSrc = this.buildXML(files); // Create `sitemap.xml` and write source to it await fs.writeFile(`${distPath}/sitemap.xml`, xmlSrc); } catch (e) { Util.customError(e, 'Generate sitemap.xml'); Logger.error(`Requires /${distPath} directory - please run the build process first`); } // END LOGGING this.endLog(); } // PROCESS METHODS // ----------------------------- /** * @description Build the .xml file source from the site files' paths * @param {Array} files - The array of site file paths * @returns {String} */ buildXML(files) { let date = this.formattedDate(); let xml = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; // If `sitemap.url` has a trailing /, remove it to avoid potential double slashes (ex: https://domain.com//path/to/file) const domain = sitemap.url[sitemap.url.length - 1] === '/' ? sitemap.url.slice(0, -1) : sitemap.url; files.forEach(f => { // Set homepage to higher priority const priority = f === '' ? '1.0' : '0.9'; // Add entry xml += ` <url> <loc>${domain}${f}</loc> <lastmod>${date}</lastmod> <changefreq>monthly</changefreq> <priority>${priority}</priority> </url> `.trim(); }); xml += '</urlset>'; // Return src return xml; } /** * @description Exclude a file path from the sitemap if it matches a * default or user-provided regex exclusion. * @param {Array} files - Array of file paths to be used for creating the sitemap * @returns {Array} * @private */ excludeFiles(files) { // Default path regexes: Any `/assets`, `/includes`, and root-level `404.html` files const defaultExcludePaths = [/^\/assets/, /^\/includes/, /^\/404.html/]; // User defined regexes from `/config/main.js` const userExcludePaths = sitemap && sitemap.excludePaths || []; // Combine the default and user regexes const excludePaths = [...defaultExcludePaths, ...userExcludePaths]; // Filter out unwanted paths return files.filter(f => { // Allow by default let state = true; // For each exclude path regex excludePaths.forEach(path => { // If the file entry path matches, change state to FALSE, so it gets filtered out if (f.match(path)) state = false; }); // Return current state to filter in or out the entry return state; }); } /** * @description Remove `/dist` path and drop any `index.html` parts from the file path * @param {Array} files - The array of site file paths * @returns {Array} */ formatFilesForXML(files) { // Allowed page extensions const allowedExt = ['html']; const excludedPaths = []; // Get files in `/dist` files = Util.getPaths(distPath, distPath, excludedPaths); // Get only the allowed files by extension (.css, .html) files = files.filter(fileName => Util.isExtension(fileName, allowedExt)); // Format for xml: Remove `/dist` files = files.map(fileName => fileName.split(distPath)[1]); // Format for xml: Remove `filename` files = files.map(fileName => this.formatDirPath(fileName)); // Alphabetize files files.sort(); // Return formatted files return files; } // HELPER METHODS // ----------------------------- /** * @description Format current date in `yyyy-mm-dd` format * @returns {String} * @private */ formattedDate() { const dateRaw = new Date(); const formatter = new Intl.DateTimeFormat('en-us', { day: '2-digit', month: '2-digit', year: 'numeric', }); const dateStringRaw = formatter.formatToParts(dateRaw); const dateStringParts = [,,]; dateStringRaw.forEach(({type, value}) => { switch (type) { case 'year': dateStringParts[0] = value; break; case 'month': dateStringParts[1] = value; break; case 'day': dateStringParts[2] = value; break; } }); return `${dateStringParts[0]}-${dateStringParts[1]}-${dateStringParts[2]}`; } /** * @description Remove `index.html` from file path * @param {String} filePath - The current file path string * @returns {String} * @private */ formatDirPath(filePath) { let filePathSplit = filePath.split('/'); const last = filePathSplit.pop(); if (last !== 'index.html') filePathSplit[filePathSplit.length] = last; return filePathSplit.join('/'); } // LOGGING // ----------------------------- startLog() { // Start Spinner this.loading.start(`Building ${chalk.magenta('sitemap.xml')}`); // Start timer this.timer.start(); } endLog() { // Stop Spinner and Timer if (this.total > 0) this.loading.stop(`Generated ${chalk.magenta(this.total)} site entries ${this.timer.end()}`); // If no matches found, stop logger but don't show line in terminal else this.loading.kill(); } // EXPORT WRAPPER // ----------------------------- // Export function wrapper instead of class for `build.js` simplicity static async export(opts) { return new GenerateSitemap(opts).init(); } }
JavaScript
class KeyHelpComponent extends Component_1.ComponentBase { constructor(eventHub, source) { super(eventHub); this.source = source; } getWidgetOpts(opts) { return new Component_1.WidgetOpts(blessed.list, { label: "Keys", selectedBg: "green", focusable: true, hidden: true, keys: true, mouse: true, vi: true, }); } setWidget(widget) { this.list = widget; } configure(widget, opts) { this.list.on("select", this.onSelected.bind(this)); } onSelected(item, index) { this.list.hide(); // TODO: execute the command selected in the help } async load(opts) { this.list.clearItems(); this.keybindings = await this.source.getData(null); const sorted = this.keybindings.sort((a, b) => a.keys[0].localeCompare(b.keys[0])); for (const k of sorted) { this.list.pushItem(`${k.description}`); } } toggleVisibility() { super.toggleVisibility(this.list); } }
JavaScript
class RouteTransition { constructor (router, to, from) { this.router = router this.to = to this.from = from this.next = null this.aborted = false this.done = false } /** * Abort current transition and return to previous location. */ abort () { if (!this.aborted) { this.aborted = true // if the root path throws an error during validation // on initial load, it gets caught in an infinite loop. const abortingOnLoad = !this.from.path && this.to.path === '/' if (!abortingOnLoad) { // When aborting, we have to decode the Path, because router.replace() // will encode it again. (https://github.com/vuejs/vue-router/issues/760) const path = this.from.path ? tryDecode(this.from.path, true) : '/' this.router.replace(path) } } } /** * Abort current transition and redirect to a new location. * * @param {String} path */ redirect (path) { if (!this.aborted) { this.aborted = true if (typeof path === 'string') { path = mapParams(path, this.to.params, this.to.query) } else { path.params = path.params || this.to.params path.query = path.query || this.to.query } this.router.replace(path) } } /** * A router view transition's pipeline can be described as * follows, assuming we are transitioning from an existing * <router-view> chain [Component A, Component B] to a new * chain [Component A, Component C]: * * A A * | => | * B C * * 1. Reusablity phase: * -> canReuse(A, A) * -> canReuse(B, C) * -> determine new queues: * - deactivation: [B] * - activation: [C] * * 2. Validation phase: * -> canDeactivate(B) * -> canActivate(C) * * 3. Activation phase: * -> deactivate(B) * -> activate(C) * * Each of these steps can be asynchronous, and any * step can potentially abort the transition. * * @param {Function} cb */ start (cb) { const transition = this // determine the queue of views to deactivate let deactivateQueue = [] let view = this.router._rootView while (view) { deactivateQueue.unshift(view) view = view.childView } let reverseDeactivateQueue = deactivateQueue.slice().reverse() // determine the queue of route handlers to activate let activateQueue = this.activateQueue = toArray(this.to.matched).map(match => match.handler) // 1. Reusability phase let i, reuseQueue for (i = 0; i < reverseDeactivateQueue.length; i++) { if (!canReuse(reverseDeactivateQueue[i], activateQueue[i], transition)) { break } } if (i > 0) { reuseQueue = reverseDeactivateQueue.slice(0, i) deactivateQueue = reverseDeactivateQueue.slice(i).reverse() activateQueue = activateQueue.slice(i) } // 2. Validation phase transition.runQueue(deactivateQueue, canDeactivate, () => { transition.runQueue(activateQueue, canActivate, () => { transition.runQueue(deactivateQueue, deactivate, () => { // 3. Activation phase // Update router current route transition.router._onTransitionValidated(transition) // trigger reuse for all reused views reuseQueue && reuseQueue.forEach(view => reuse(view, transition)) // the root of the chain that needs to be replaced // is the top-most non-reusable view. if (deactivateQueue.length) { const view = deactivateQueue[deactivateQueue.length - 1] const depth = reuseQueue ? reuseQueue.length : 0 activate(view, transition, depth, cb) } else { cb() } }) }) }) } /** * Asynchronously and sequentially apply a function to a * queue. * * @param {Array} queue * @param {Function} fn * @param {Function} cb */ runQueue (queue, fn, cb) { const transition = this step(0) function step (index) { if (index >= queue.length) { cb() } else { fn(queue[index], transition, () => { step(index + 1) }) } } } /** * Call a user provided route transition hook and handle * the response (e.g. if the user returns a promise). * * If the user neither expects an argument nor returns a * promise, the hook is assumed to be synchronous. * * @param {Function} hook * @param {*} [context] * @param {Function} [cb] * @param {Object} [options] * - {Boolean} expectBoolean * - {Boolean} postActive * - {Function} processData * - {Function} cleanup */ callHook (hook, context, cb, { expectBoolean = false, postActivate = false, processData, cleanup } = {}) { const transition = this let nextCalled = false // abort the transition const abort = () => { cleanup && cleanup() transition.abort() } // handle errors const onError = err => { postActivate ? next() : abort() if (err && !transition.router._suppress) { warn('Uncaught error during transition: ') throw err instanceof Error ? err : new Error(err) } } // since promise swallows errors, we have to // throw it in the next tick... const onPromiseError = err => { try { onError(err) } catch (e) { setTimeout(() => { throw e }, 0) } } // advance the transition to the next step const next = () => { if (nextCalled) { warn('transition.next() should be called only once.') return } nextCalled = true if (transition.aborted) { cleanup && cleanup() return } cb && cb() } const nextWithBoolean = res => { if (typeof res === 'boolean') { res ? next() : abort() } else if (isPromise(res)) { res.then((ok) => { ok ? next() : abort() }, onPromiseError) } else if (!hook.length) { next() } } const nextWithData = data => { let res try { res = processData(data) } catch (err) { return onError(err) } if (isPromise(res)) { res.then(next, onPromiseError) } else { next() } } // expose a clone of the transition object, so that each // hook gets a clean copy and prevent the user from // messing with the internals. const exposed = { to: transition.to, from: transition.from, abort: abort, next: processData ? nextWithData : next, redirect: function () { transition.redirect.apply(transition, arguments) } } // actually call the hook let res try { res = hook.call(context, exposed) } catch (err) { return onError(err) } if (expectBoolean) { // boolean hooks nextWithBoolean(res) } else if (isPromise(res)) { // promise if (processData) { res.then(nextWithData, onPromiseError) } else { res.then(next, onPromiseError) } } else if (processData && isPlainOjbect(res)) { // data promise sugar nextWithData(res) } else if (!hook.length) { next() } } /** * Call a single hook or an array of async hooks in series. * * @param {Array} hooks * @param {*} context * @param {Function} cb * @param {Object} [options] */ callHooks (hooks, context, cb, options) { if (Array.isArray(hooks)) { this.runQueue(hooks, (hook, _, next) => { if (!this.aborted) { this.callHook(hook, context, next, options) } }, cb) } else { this.callHook(hooks, context, cb, options) } } }
JavaScript
class Router { constructor() { this._bindHandlers(); this._hostname = location.host; this._enabled = false; } enable() { if (!this._enabled) { document.addEventListener('click', this._onLinkClick); window.addEventListener('popstate', this._onPopState); this._enabled = true; } } _bindHandlers() { this._onLinkClick = this._onLinkClick.bind(this); this._onPopState = this._onPopState.bind(this); } _getParentByTagName(node, tagname) { let parent; if (node === null || tagname === '') return; parent = node.parentNode; tagname = tagname.toUpperCase(); while (parent.tagName !== 'HTML') { if (parent.tagName === tagname) { return parent; } parent = parent.parentNode; } return parent; } _onPopState(event) { this.navigate(new URL(location.href), event.state.scrollTop, false); } async _onLinkClick(event) { let target = event.target; if (target.tagName !== 'A') { target = this._getParentByTagName(target, 'A'); if (!target) return; } // If no href, just let the click pass through. if (!target.href) { return; } const link = new URL(target.href); // If it’s an external link, just navigate. if (link.host !== this._hostname) { return; } event.preventDefault(); this.navigate(link) .catch((err) => console.error(err.stack)); } static get TRANSITION_DURATION() { return '0.3s'; } async _animateOut(oldView) { oldView.style.transition = `opacity ${Router.TRANSITION_DURATION} linear`; oldView.style.opacity = '0'; return transitionEndPromise(oldView); } async _animateIn(newView) { newView.style.opacity = '0'; await requestAnimationFramePromise(); await requestAnimationFramePromise(); newView.style.transition = `opacity ${Router.TRANSITION_DURATION} linear`; newView.style.opacity = '1'; await transitionEndPromise(newView); } async _loadFragment(link) { const newView = document.createElement('div'); newView.setAttribute('id', 'main-view'); link.searchParams.append('fragment', true); const fragmentURL = link.toString(); const load = async function() { let fragment; try { fragment = await fetch(fragmentURL, {credentials: 'include'}).then((resp) => resp.text()); } catch (e) { fragment = 'This content is not available.'; } return fragment; }; newView.innerHTML = await load(); return newView; } async navigate(link, scrollTop = 0, pushState = true) { // Manually handle the scroll restoration. history.scrollRestoration = 'manual'; if (pushState) { history.replaceState({scrollTop: document.scrollingElement.scrollTop}, ''); history.pushState({scrollTop}, '', link.toString()); } const oldView = document.querySelector('#main-view'); const viewAnimation = this._animateOut(oldView); const newView = await this._loadFragment(link); await viewAnimation; oldView.parentNode.replaceChild(newView, oldView); document.scrollingElement.scrollTop = scrollTop; // Set to auto in case user hits page refresh. history.scrollRestoration = 'auto'; await this._animateIn(newView); pageInit(); } loadCurrentRoute() { this.navigate(new URL(location.href), document.body.scrollTop, false); } }
JavaScript
class Decider { /** * Creates an instance of Decider. * @param {string} word * @memberof Decider */ constructor(word) { this.word = word; } /** * * * @returns {string} word after conversion * @memberof Decider */ decide() { let cardinalObj = new Cardinal(this.word); let specialMiddleObj = new SpecialMiddle(this.word); let suffixPrefixObj = new SuffixPrefix(this.word); if (cardinalObj.isCardinal()) { return cardinalObj.doCardinalWord(); } else if (suffixPrefixObj.isSuffixPrefix()) { return suffixPrefixObj.doSuffixPrefixWord(); } else if (specialMiddleObj.isSpecialMiddle()) { return specialMiddleObj.doSpecialMiddleWord(); } return this.word; } }
JavaScript
class HarmonyDevice extends Device { constructor(adapter, hub, id, device) { super(adapter, id); this.name = device.label; this.description = `${device.manufacturer} ${device.deviceTypeDisplayName} ${device.model}`; this.hub = hub; this.actionInfo = {}; this.pendingActions = new Set(); this.rawId = device.id; this.rawType = device.type; // this.activities = new Set(); const handledActions = this.getHandledActions(); for(const g of device.controlGroup) { if(g.function.length) { for(const action of g.function) { if(!handledActions.includes(action.name)) { this.addAction(action.name, { title: action.label }); } this.actionInfo[action.name] = action.action; } } } // this.addEvent('on', { // type: 'string', // title: 'activity ID' // }); // // this.addEvent('off', { // type: 'string', // title: 'activity ID' // }); //TODO figure out how a device <-> activity association is found this.finalize(handledActions); } // addActivity(activityId) { // this.activities.add(activityId); // } // // shouldHandleActivity(activityId) { // return this.activities.has(activityId); // } // // handleActivity(activityId, direction) { // if(this.shouldHandleActivity(activityId)) { // this.eventDispatch(new Event(diection ? 'on' : 'off', activityId)); // } // } getHandledActions() { if(this.rawType == 'DigitalMusicServer') { return HANDLED_ACTIONS; } return []; } async getMetadata() { // if(this.rawType == 'DigitalMusicServer') { // const metadata = await new Promise((resolve) => { // const metaId = Math.floor(Math.random() * 1000000); // this.hub.client._responseHandlerQueue.push({ // canHandleStanza: (s) => s.attr('id') == metaId, // deferred: { resolve }, // responseType: 'json' // }); // this.hub.client._xmppClient.send(`<iq type="get" id="${metaId}"><oa xmlns="connect.logitech.com" mime="vnd.logitech.setup/vnd.logitech.setup.content?getAllMetadata">deviceId=${this.rawId}</oa></iq>`); // }); // return metadata.musicMeta; // } return {}; } async finalize(handledActions) { if(handledActions.length) { const meta = await this.getMetadata(); for(const prop in RECOGNIZTED_PROPERTIES) { if(prop in meta) { this.properties.set(prop, new ActionProperty(this, prop, RECOGNIZTED_PROPERTIES[prop], meta[prop])); } } } this.adapter.handleDeviceAdded(this); } async sendAction(actionName) { if(actionName in this.actionInfo) { const actionSpec = this.actionInfo[actionName]; await this.hub.client.send('holdAction', actionSpec, 1000); } else { console.warn("Unknown action", actionName); } } async performAction(action) { // Ensure we only perform the action once at a time (since else we're essentially rolling over IR keys). if(action.name in this.actionInfo && !this.pendingActions.has(action.name)) { this.pendingActions.add(action.name); try { action.start(); this.sendAction(action.name); action.finish(); } catch(e) { console.error(e); } this.pendingActions.delete(action.name); } } updateMeta(meta) { for(const key in meta) { if(key in RECOGNIZTED_PROPERTIES) { const prop = this.findProperty(key); prop.setCachedValue(prop.spec.map(meta[key])); this.notifyPropertyChanged(prop); } } } }
JavaScript
class ParentNodeHook { constructor(doc) { this.doc = doc // parents by id of child nodes this.parents = {} doc.data.on('operation:applied', this._onOperationApplied, this) } _onOperationApplied(op) { const doc = this.doc const parents = this.parents let node = doc.get(op.path[0]) switch(op.type) { case 'create': { if (node._childNodes) { _setParent(node, node._childNodes) } _setRegisteredParent(node) break } case 'update': { // ATTENTION: we only set parents but don't remove when they are deleted // assuming that if the parent gets deleted, the children get deleted too let update = op.diff if (op.path[1] === '_childNodes') { if (update.isInsert()) { _setParent(node, update.getValue()) } else if (update.isDelete()) { _setParent(null, update.getValue()) } } break } case 'set': { if (op.path[1] === '_childNodes') { _setParent(null, op.getOldValue()) _setParent(node, op.getValue()) } break } default: // } function _setParent(parent, ids) { if (ids) { if (isArray(ids)) { ids.forEach(_set) } else { _set(ids) } } function _set(id) { // Note: it can happen, e.g. during deserialization, that the child node // is created later than the parent node // so we store the parent for later parents[id] = parent let child = doc.get(id) if (child) { child.parentNode = parent } } } function _setRegisteredParent(child) { let parent = parents[child.id] if (parent) { child.parentNode = parent } } } }
JavaScript
class ElementsOverlapController extends Controller { static values = { throttleInterval: { type: Number, default: 10 }, minWindowWidth: { type: Number, default: 1023 }, // 1023 - touch device threshold gap: { type: Number, default: 16 } } static targets = ['dynamicElement', 'fixedElement'] connect () { const fixedElementPositionProperties = this.fixedElementTarget.getBoundingClientRect() this.fixedElementBottom = fixedElementPositionProperties.bottom + this.gapValue this.throttledPreventOverlap = throttle( this.preventOverlaping, this.throttleIntervalValue ) document.addEventListener('scroll', this.throttledPreventOverlap) window.addEventListener('resize', this.throttledPreventOverlap) } preventOverlaping = () => { if (window.innerWidth <= this.minWindowWidthValue) { return } const { top } = this.dynamicElementTarget.getBoundingClientRect() const areElementsOverlaping = this.fixedElementBottom >= top if (areElementsOverlaping) { this.fixedElementTarget.style.bottom = `${window.innerHeight - top + this.gapValue}px` } else { this.fixedElementTarget.style.bottom = 'unset' } } }
JavaScript
class Vector3 extends Float32Array { /** * @param {*} arguments... Variable arguments * @example * Vector3() // [0, 0, 0] * Vector3(1) // [1, 1, 1] * Vector3(1, 2, 3) // [1, 2, 3] * Vector3([1, 2, 3]) // [1, 2, 3] * Vector3(Vector3) // Copy the vector */ constructor() { if (arguments.length) { if (arguments.length == 1 && !arguments[0]) { super(3); } else if (arguments.length == 1 && isNumber(arguments[0])) { super(3); const x = arguments[0]; this[0] = x; this[1] = x; this[2] = x; } else if (arguments.length == 3 && isNumber(arguments[0])) { super(3); const x = arguments[0]; const y = arguments[1]; const z = arguments[2]; this[0] = x; this[1] = y; this[2] = z; } else { super(...arguments); } } else { super(3); } } /** * Create a copy of this vector. * @returns {Vector3} */ clone() { return new Vector3(this); } /** * Set the components of this vector. * @param {number|Array} x * @param {number} [y] * @param {number} [z] * @returns {Vector3} Returns this vector. */ setFrom(x, y, z) { if (y === undefined) { this[0] = x[0]; this[1] = x[1]; this[2] = x[2]; } else { this[0] = x; this[1] = y; this[2] = z; } return this; } /** * Set all components to 0. * @returns {Vector3} Returns this vector. */ setZero() { this[0] = 0; this[1] = 0; this[2] = 0; return this; } /** * Convert the vector to an Array. * @returns {Array} */ toArray() { return [this[0], this[1], this[2]]; } /** * Get the string representation of the vector. * @returns {String} */ toString() { return `[${this.x}, ${this.y}, ${this.z}]`; } /** * @property {number} x The x component. */ get x() { return this[0]; } set x(v) { this[0] = v; } /** * @property {number} y The y component. */ get y() { return this[1]; } set y(v) { this[1] = v; } /** * @property {number} z The z component. */ get z() { return this[2]; } set z(v) { this[2] = v; } /** * Remap the channels of this vector. * @param {number} xi The index of the channel to set x to. * @param {number} yi The index of the channel to set y to. * @param {number} zi The index of the channel to set z to. * @return {Vector3} * @example * remap(1, 2, 0) // returns [y, z, x] */ remap(xi, yi, zi) { const x = this[clamp(xi, 0, 2)]; const y = this[clamp(yi, 0, 2)]; const z = this[clamp(zi, 0, 2)]; this[0] = x; this[1] = y; this[2] = z; return this; } /** * Map this vector to a new vector. * @param {number} arguments... The variable component indices to map. * @returns {number|Vector2|Vector3} * @example * map(1) // Returns a number with the y value of this vector. * map(0, 2) // Returns a Vector2 as [x, z]. * map(2, 1, 0) // Returns a Vector3 with as [z, y, x]. */ map() { switch (arguments.length) { case 3: return new Vector3(this[arguments[0]], this[arguments[1]], this[arguments[2]]); case 2: return new Vector2(this[arguments[0]], this[arguments[1]]); case 1: return this[arguments[0]]; } return null; } /** * Returns the sum of the components, x + y + z. * @returns {number} */ sum() { return this[0] + this[1] + this[2]; } /** * Returns the length of the vector. * @returns {number} */ getLength() { return Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]); } /** * Returns the squared length of the vector. * @returns {number} */ getLengthSquared() { return this[0] * this[0] + this[1] * this[1] + this[2] * this[2]; } /** * Normalize the vector. * @returns {Vector3} Returns self. */ normalize() { const out = this; const l = this.getLength(); if (!l) { return out; } out[0] = this[0] / l; out[1] = this[1] / l; out[2] = this[2] / l; return out; } /** * Negate the vector, as [-x, -y, -z]. * @returns {Vector3} Returns self. */ negate() { const out = this; out[0] = -this[0]; out[1] = -this[1]; out[2] = -this[2]; return out; } /** * Make each component its absolute value, [abs(x), abs(y), abs(z)] * @returns {Vector3} Returns self. */ abs() { const out = this; out[0] = Math.abs(this[0]); out[1] = Math.abs(this[1]); out[2] = Math.abs(this[2]); return out; } /** * Add a vector to this, this + b. * @param {Vector3} b * @returns {Vector3} Returns self. */ add(b) { const out = this; out[0] = this[0] + b[0]; out[1] = this[1] + b[1]; out[2] = this[2] + b[2]; return out; } /** * Subtract a vector from this, this - b. * @param {Vector3} b * @returns {Vector3} Returns self. */ subtract(b) { const out = this; out[0] = this[0] - b[0]; out[1] = this[1] - b[1]; out[2] = this[2] - b[2]; return out; } /** * Multiply a vector with this, this * b. * @param {Vector3} b * @returns {Vector3} Returns self. */ multiply(b) { const out = this; out[0] = this[0] * b[0]; out[1] = this[1] * b[1]; out[2] = this[2] * b[2]; return out; } /** * Divide a vector to this, this / b. * @param {Vector3} b * @returns {Vector3} Returns self. */ divide(b) { const out = this; out[0] = b[0] ? this[0] / b[0] : 0; out[1] = b[1] ? this[1] / b[1] : 0; out[2] = b[2] ? this[2] / b[2] : 0; return out; } /** * Scale the vector by a number, this * s. * @param {number} s * @returns {Vector3} */ scale(s) { const out = this; out[0] = this[0] * s; out[1] = this[1] * s; out[2] = this[2] * s; return out; } rotateX(origin, rad) { const out = this; const a = this; const b = origin; // Translate point to the origin const p = [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; const r = [p[0], p[1] * Math.cos(rad) - p[2] * Math.sin(rad), p[1] * Math.sin(rad) + p[2] * Math.cos(rad)]; // translate to correct position out[0] = r[0] + b[0]; out[1] = r[1] + b[1]; out[2] = r[2] + b[2]; return out; } rotateY(origin, rad) { const out = this; const a = this; const b = origin; // Translate point to the origin const p = [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; const r = [p[2] * Math.sin(rad) + p[0] * Math.cos(rad), p[1], p[2] * Math.cos(rad) - p[0] * Math.sin(rad)]; // translate to correct position out[0] = r[0] + b[0]; out[1] = r[1] + b[1]; out[2] = r[2] + b[2]; return out; } rotateZ(origin, rad) { const out = this; const a = this; const b = origin; // Translate point to the origin const p = [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; const r = [p[0] * Math.cos(rad) - p[1] * Math.sin(rad), p[0] * Math.sin(rad) + p[1] * Math.cos(rad), p[2]]; // translate to correct position out[0] = r[0] + b[0]; out[1] = r[1] + b[1]; out[2] = r[2] + b[2]; return out; } /** * Reflect the direction vector against the normal. * @param {Vector3} direction * @param {Vector3} normal * @param {Vector3} [out] * @return {Vector3} */ static reflect(direction, normal, out) { out = out || new Vector3(); const s = -2 * Vector3.dot(normal, direction); out[0] = normal[0] * s + direction[0]; out[1] = normal[1] * s + direction[1]; out[2] = normal[2] * s + direction[2]; return out; } /** * Calculate the refraction vector against the surface normal, from IOR k1 to IOR k2. * @param {Vector3} incident Specifies the incident vector * @param {Vector3} normal Specifies the normal vector * @param {number} eta Specifies the ratio of indices of refraction * @param {Vector3} [out] Optional output storage * @return {Vector3} */ static refract(incident, normal, eta, out) { out = out || new Vector3(); // If the two index's of refraction are the same, then // the new vector is not distorted from the old vector. if (equals(eta, 1.0)) { out[0] = incident[0]; out[1] = incident[1]; out[2] = incident[2]; return out; } const dot = -Vector3.dot(incident, normal); let cs2 = 1.0 - eta * eta * (1.0 - dot * dot); // if cs2 < 0, then the new vector is a perfect reflection of the old vector if (cs2 < 0.0) { Vector3.reflect(incident, normal, out); return out; } cs2 = eta * dot - Math.sqrt(cs2); out[0] = normal[0] + (incident[0] * eta) + (normal[0] * cs2); out[1] = normal[1] + (incident[1] * eta) + (normal[1] * cs2); out[2] = normal[2] + (incident[2] * eta) + (normal[2] * cs2); return out.normalize(); } /** * Return the negated value of a vector. * @param {Vector3} a * @param {Vector3} [out] Optional storage for the output. * @returns {Vector3} */ static negated(a, out) { out = out || new Vector3(); out.setFrom(-a[0], -a[1], -a[2]); return out; } /** * Return the absoluate value of a vector. * @param {Vector3} a * @param {Vector3} [out] Optional storage for the output. * @returns {Vector3} */ static abs(a, out) { out = out || new Vector3(); out.setFrom(Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])); return out; } /** * Calculate the length of a vector. * @param {Vector3} a * @returns {number} */ static length(a) { return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); } /** * Calculate the squared lenth of a vector. * @param {Vector3} a * @returns {number} */ static lengthSquared(a) { return a[0] * a[0] + a[1] * a[1] + a[2] * a[2]; } /** * Calculate the squared distance between two points. * @param {Vector3} a * @param {Vector3} b * @returns {number} */ static distanceSquared(a, b) { const dx = b[0] - a[0]; const dy = b[1] - a[1]; const dz = b[2] - a[2]; return dx * dx + dy * dy + dz * dz; } /** * Calculate the distance between two points. * @param {Vector3} a * @param {Vector3} b * @returns {number} */ static distance(a, b) { const dx = b[0] - a[0]; const dy = b[1] - a[1]; const dz = b[2] - a[2]; return Math.sqrt(dx * dx + dy * dy + dz * dz); } /** * Calculate the dot product of two vectors. * @param {Vector3} a * @param {Vector3} b * @returns {number} */ static dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } /** * Calculate the cross product of two vectors. * @param {Vector3} a * @param {Vector3} b * @param {Vector3} [out] Optional storage for the output. * @returns {Vector3} */ static cross(a, b, out) { out = out || new Vector3(); const ax = a[0]; const ay = a[1]; const az = a[2]; const bx = b[0]; const by = b[1]; const bz = b[2]; out[0] = ay * bz - az * by; out[1] = az * bx - ax * bz; out[2] = ax * by - ay * bx; return out; } /** * Return the normalized version of the vector. * @param {Vector3} a * @param {Vector3} [out] Optional storage for the output. * @returns {Vector3} */ static normalize(a, out) { out = out || new Vector3(); const l = Vector3.length(a); if (!l) { out.set(a); return out; } out[0] = a[0] / l; out[1] = a[1] / l; out[2] = a[2] / l; return out; } /** * Add two vectors. * @param {Vector3} a * @param {Vector3} b * @param {Vector3} [out] Optional storage for the output. * @returns {Vector3} */ static add(a, b, out) { out = out || new Vector3(); out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; return out; } /** * Subtract two vectors * @param {Vector3} a * @param {Vector3} b * @param {Vector3} [out] * @returns {Vector3} */ static subtract(a, b, out) { out = out || new Vector3(); out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; return out; } /** * Multiply two vectors * @param {Vector3} a * @param {Vector3} b * @param {Vector3} [out] * @returns {Vector3} */ static multiply(a, b, out) { out = out || new Vector3(); out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; out[2] = a[2] * b[2]; return out; } /** * Divide two vectors. * @param {Vector3} a * @param {Vector3} b * @param {Vector3} [out] * @returns {Vector3} */ static divide(a, b, out) { out = out || new Vector3(); out[0] = b[0] ? a[0] / b[0] : 0; out[1] = b[1] ? a[1] / b[1] : 0; out[2] = b[2] ? a[2] / b[2] : 0; return out; } /** * Scale a vector by a number. * @param {Vector3} a * @param {number} s * @param {Vector3} [out] * @returns {Vector3} */ static scale(a, s, out) { out = out || new Vector3(); out[0] = a[0] * s; out[1] = a[1] * s; out[2] = a[2] * s; return out; } /** * Each component will be the minimum of either a or b. * @param {Vector3} a * @param {Vector3} b * @param {Vector3} [out] Optional storage for the output. * @returns {Vector3} */ static min(a, b, out) { out = out || new Vector3(); out[0] = Math.min(a[0], b[0]); out[1] = Math.min(a[1], b[1]); out[2] = Math.min(a[2], b[2]); return out; } /** * Each component will be the maximum of either a or b. * @param {Vector3} a * @param {Vector3} b * @param {Vector3} [out] Optional storage for the output. * @returns {Vector3} */ static max(a, b, out) { out = out || new Vector3(); out[0] = Math.max(a[0], b[0]); out[1] = Math.max(a[1], b[1]); out[2] = Math.max(a[2], b[2]); return out; } /** * Scale and add two numbers, as out = a + b * s. * @param {Vector3} a * @param {Vector3} b * @param {number} s * @param {Vector3} [out] * @returns {Vector3} */ static scaleAndAdd(a, b, s, out) { out = out || new Vector3(); out[0] = a[0] + b[0] * s; out[1] = a[1] + b[1] * s; out[2] = a[2] + b[2] * s; return out; } /** * Linear interpolate between two vectors. * @param {Vector3} a * @param {Vector3} b * @param {number} t Interpolator between 0 and 1. * @param {Vector3} [out] Optional storage for the output. * @returns {Vector3} */ static lerp(a, b, t, out) { out = out || new Vector3(); const ax = a[0]; const ay = a[1]; const az = a[2]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); out[2] = az + t * (b[2] - az); return out; } }
JavaScript
class PriceCard extends Component { static propTypes = { /** * The index of the card. Used for theming. */ cardIndex: PropTypes.number.isRequired, /** * The className passed in by styled-components when styled(MyComponent) notation is used on * this component. */ className: PropTypes.string }; /** * Create a PriceCard object. * @constructor */ constructor(props) { super(props); this.state = { percentChange: null, price: null, error: 0 }; } /** * Invoked by React immediately after a component is mounted (inserted into the tree). * @public */ componentDidMount() { // Update the price using intervals. this.pollForPrice(); this.interval = setInterval( () => { this.pollForPrice() }, Constants.PRICE_POLL_INTERVAL_MS); } /** * Invoked by React immediately before a component is unmounted and destroyed. * @public */ componentWillUnmount() { clearInterval(this.interval); this.interval = null; } /** * Return a reference to a React element to render into the DOM. * @return {Object} A reference to a React element to render into the DOM. * @public */ render() { let { cardIndex, className } = this.props; let { percentChange, price, error } = this.state; let priceText; if (error >= Constants.NETWORK_ERROR_THRESHOLD) priceText = 'Network error'; else if (percentChange === null || price === null) priceText = 'Loading...'; else priceText = <Fragment> <span>{'$' + price.toFixed(2) + ' '}</span> <SpanPercentChange isnegative={percentChange < 0}> { (percentChange < 0 ? '\u2193' : '\u2191') + ' ' + Math.abs(percentChange).toFixed(2) + '%' } </SpanPercentChange> </Fragment>; return ( <DashCard className={className} cardIndex={cardIndex} title='Price - ICP' value={priceText} iconImageSrc={icpLogo} /> ); } /** * Update the price. * @private */ pollForPrice() { const url = `https://api.nomics.com/v1/currencies/ticker?key=${Constants.NOMICS_API_KEY}&ids=ICP&interval=1d`; axios.get(url) .then(res => { const percentChange = parseFloat(res.data[0]['1d'].price_change_pct) * 100; const price = parseFloat(res.data[0].price); this.setState({ percentChange: percentChange, price: price, error: 0 }); }) .catch(() => { this.setState(prevState => ({ error: prevState.error + 1 })); }); } /** * Return a string for the date in RFC 3339 (URI escaped) format. * @param {Object} date The date to create the string for. * @return {String} A string for the date in RFC 3339 (URI escaped) format. * @private */ dateToRfc3339(date) { // Duplicated function, move to utils!!! // Use toISOString(), removing the fraction of seconds (i.e, after decimal point). const isoNoFraction = date.toISOString().split('.')[0] + 'Z' // Escape all ':' characters. return isoNoFraction.replace(/:/g, '%3A'); } }
JavaScript
class Validator { /** * Create a new validator instance. * * @public * @param {?Map.<string, Function>} validations Available validations. * @param {?ValidationStrategy} validationStrategy Validation strategy to use. */ constructor(validations = new Map(), validationStrategy = ValidationStrategy.RUN_ALL_VALIDATIONS) { /** * Available validations. * * @private * @type {Map.<string, Function>} */ this.validations = validations; /** * Validation strategy to use. * * @private * @type {ValidationStrategy} */ this.validationStrategy = validationStrategy; /** * Last encountered error. * * For every encountered error this gets replaced by a new one, adding * this (the now second to last error) to the list of previous errors. * This enables a chain of errors thrown in the validation process. * * @private * @type {?ValidatorError} */ this.error = null; } /** * Set validation strategy. * * @public * @param {ValidationStrategy} validationStrategy Validation strategy to use. * @return {this} Same instance for method chaining. */ useValidationStrategy(validationStrategy) { this.validationStrategy = validationStrategy; return this; } /** * Add validation to available validations. * * @public * @param {ValidationInterface} validation Validation instance. * @return {this} Same instance for method chaining. */ addValidation(validation) { this.validations.set(validation.getIdentifier(), validation.validate.bind(validation)); return this; } /** * Add validation function to available validations. * * @public * @param {string} identifier Validation identifier. * @param {Function} validate Validation function. * @return {this} Same instance for method chaining. */ addValidationFunction(identifier, validate) { return this.addValidation({getIdentifier: () => identifier, validate}); } /** * Validate object against the given rules. * * @public * @param {Object} object Object to validate. * @param {Object.<string, string>} rules Rules to validate the object against. * @param {boolean} [clearPreviousErrors=true] Whether to clear any errors from previous invocations. * @throws {ValidatorError} When object is invalid. */ validate(object, rules, clearPreviousErrors = true) { if (clearPreviousErrors) { this.error = null; } for (const [property, rule] of Object.entries(rules)) { this.validateRule(object, property, rule); if (this.validationStrategy === ValidationStrategy.STOP_AT_FIRST_INVALID_PROPERTY && this.error) { throw this.error; } } if (this.error !== null) { throw this.error; } } /** * Validate object property against the given rule. * * @private * @param {Object} object Object to validate. * @param {string} property Object property to validate. * @param {string} rule Rule to validate the property against. * @throws {ValidatorError} */ validateRule(object, property, rule) { for (const identifier of rule.split("|")) { this.runValidation(object, property, identifier); if (this.validationStrategy === ValidationStrategy.STOP_AT_FIRST_INVALID_VALIDATION && this.error) { throw this.error; } } } /** * Validate object property against the given validation. * * @private * @param {Object} object Object to validate. * @param {string} property Object property to validate. * @param {string} definition Validator definition. */ runValidation(object, property, definition) { const [identifier, parameterString = ""] = definition.split(":"); const parameters = parameterString.split(",") .filter(parameter => parameter.length > 0) .map(parameter => parameter.trim()); if (identifier === "present") { return this.validatePresence(object, property); } if (!this.validations.has(identifier)) { throw new Error(`Unrecognized validation identifier: ${identifier}`); } if (!(property in object)) { return; } try { this.validations.get(identifier)(object[property], ...parameters); } catch (error) { if (!(error instanceof ValidationError)) { throw error; } this.error = new ValidatorError(error.message, property, this.error); } } /** * Validate the presence of the given property. * * @private * @param {*} object Object to validate. * @param {string} property Property to check for. */ validatePresence(object, property) { if (!(property in object)) { this.error = new ValidatorError("Must be present", property, this.error); } } }
JavaScript
class NodeCrawlerBase extends events_1.EventEmitter { constructor(session) { super(); this.maxNodesPerRead = 0; this.maxNodesPerBrowse = 0; this.startTime = new Date(); this.readCounter = 0; this.browseCounter = 0; this.browseNextCounter = 0; this.transactionCounter = 0; this._prePopulatedSet = new WeakSet(); this.session = session; // verify that session object provides the expected methods (browse/read) (0, node_opcua_assert_1.assert)(typeof session.browse === "function"); (0, node_opcua_assert_1.assert)(typeof session.read === "function"); this.browseNameMap = {}; this._objectCache = {}; this._objMap = {}; this._crawled = new Set(); this._visitedNode = new Set(); this._initialize_referenceTypeId(); this.pendingReadTasks = []; this.pendingBrowseTasks = []; this.pendingBrowseNextTasks = []; this.taskQueue = async.queue((task, callback) => { // use process next tick to relax the stack frame /* istanbul ignore next */ if (doDebug) { debugLog(" executing Task ", task.name); // JSON.stringify(task, null, " ")); } setImmediate(() => { task.func.call(this, task, () => { this.resolve_deferred_browseNext(); this.resolve_deferred_browseNode(); this.resolve_deferred_readNode(); callback(); }); }); }, 1); // MaxNodesPerRead from Server.ServerCapabilities.OperationLimits // VariableIds.ServerType_ServerCapabilities_OperationLimits_MaxNodesPerRead this.maxNodesPerRead = 0; // MaxNodesPerBrowse from Server.ServerCapabilities.OperationLimits // VariableIds.Server_ServerCapabilities_OperationLimits_MaxNodesPerBrowse this.maxNodesPerBrowse = 0; // 0 = no limits // statistics this.startTime = new Date(); this.readCounter = 0; this.browseCounter = 0; this.transactionCounter = 0; } static follow(crawler, cacheNode, userData, referenceType, browseDirection) { const referenceTypeNodeId = getReferenceTypeId(referenceType); for (const reference of cacheNode.references) { if (browseDirection === node_opcua_data_model_1.BrowseDirection.Forward && !reference.isForward) { continue; } if (browseDirection === node_opcua_data_model_1.BrowseDirection.Inverse && reference.isForward) { continue; } if (!referenceTypeNodeId) { crawler.followReference(cacheNode, reference, userData); } else { if (node_opcua_nodeid_1.NodeId.sameNodeId(referenceTypeNodeId, reference.referenceTypeId)) { crawler.followReference(cacheNode, reference, userData); } } } } dispose() { (0, node_opcua_assert_1.assert)(this.pendingReadTasks.length === 0); (0, node_opcua_assert_1.assert)(this.pendingBrowseTasks.length === 0); (0, node_opcua_assert_1.assert)(this.pendingBrowseNextTasks.length === 0); this.pendingReadTasks.length = 0; this.pendingBrowseTasks.length = 0; this.pendingBrowseNextTasks.length = 0; (0, node_opcua_assert_1.assert)(this.taskQueue.length() === 0); Object.values(this._objectCache).map((cache) => cache.dispose()); Object.values(this._objMap).map((obj) => { Object.keys(obj).map((k) => (obj[k] = undefined)); }); this.taskQueue.kill(); this.session = null; this.browseNameMap = null; this.taskQueue = null; this._objectCache = {}; this._objMap = null; this._crawled = null; this._visitedNode = null; this._prePopulatedSet = null; } toString() { return ("" + `reads: ${this.readCounter}\n` + `browses: ${this.browseCounter} \n` + `transaction: ${this.transactionCounter} \n`); } crawl(nodeId, userData, ...args) { const endCallback = args[0]; (0, node_opcua_assert_1.assert)(endCallback instanceof Function, "expecting callback"); nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(nodeId); (0, node_opcua_assert_1.assert)(typeof endCallback === "function"); this._readOperationalLimits((err) => { /* istanbul ignore next */ if (err) { return endCallback(err); } this._inner_crawl(nodeId, userData, endCallback); }); } /** * @internal * @private */ _inner_crawl(nodeId, userData, endCallback) { (0, node_opcua_assert_1.assert)(userData !== null && typeof userData === "object"); (0, node_opcua_assert_1.assert)(typeof endCallback === "function"); let hasEnded = false; this.taskQueue.drain(() => { debugLog("taskQueue is empty !!", this.taskQueue.length()); if (!hasEnded) { hasEnded = true; this._visitedNode = new Set(); this._crawled = new Set(); this.emit("end"); endCallback(); } }); let cacheNode = this._getCacheNode(nodeId); if (!cacheNode) { cacheNode = this._createCacheNode(nodeId); } (0, node_opcua_assert_1.assert)(cacheNode.nodeId.toString() === nodeId.toString()); // ----------------------- Read missing essential information about node // such as nodeClass, typeDefinition browseName, displayName // this sequence is only necessary on the top node being crawled, // as browseName,displayName,nodeClass will be provided by ReferenceDescription later on for child nodes // async.parallel({ task1: (callback) => { this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.BrowseName, (err, value) => { /* istanbul ignore else */ if (err) { return callback(err); } (0, node_opcua_assert_1.assert)(value instanceof node_opcua_data_model_1.QualifiedName); cacheNode.browseName = value; setImmediate(callback); }); }, task2: (callback) => { this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.NodeClass, (err, value) => { /* istanbul ignore else */ if (err) { return callback(err); } cacheNode.nodeClass = value; setImmediate(callback); }); }, task3: (callback) => { this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.DisplayName, (err, value) => { /* istanbul ignore else */ if (err) { return callback(err); } (0, node_opcua_assert_1.assert)(value instanceof node_opcua_data_model_1.LocalizedText); cacheNode.displayName = value; setImmediate(callback); }); }, task4: (callback) => { this._resolve_deferred_readNode(callback); } }, (err, data) => { this._add_crawl_task(cacheNode, userData); }); } _add_crawl_task(cacheNode, userData) { (0, node_opcua_assert_1.assert)(userData); (0, node_opcua_assert_1.assert)(this !== null && typeof this === "object"); const key = cacheNode.nodeId.toString(); /* istanbul ignore else */ if (this._crawled.has(key)) { return; } this._crawled.add(key); const task = { func: NodeCrawlerBase.prototype._crawl_task, param: { cacheNode, userData } }; this._push_task("_crawl task", task); } followReference(parentNode, reference, userData) { (0, node_opcua_assert_1.assert)(reference instanceof node_opcua_service_browse_1.ReferenceDescription); let referenceTypeIdCacheNode = this._getCacheNode(reference.referenceTypeId); if (this._prePopulatedSet.has(referenceTypeIdCacheNode)) { this._prePopulatedSet.delete(referenceTypeIdCacheNode); this._add_crawl_task(referenceTypeIdCacheNode, userData); } if (!referenceTypeIdCacheNode) { referenceTypeIdCacheNode = this._createCacheNode(reference.referenceTypeId); referenceTypeIdCacheNode.nodeClass = node_opcua_data_model_1.NodeClass.ReferenceType; this._add_crawl_task(referenceTypeIdCacheNode, userData); } let childCacheNode = this._getCacheNode(reference.nodeId); if (!childCacheNode) { childCacheNode = this._createCacheNode(reference.nodeId, parentNode, reference); childCacheNode.browseName = reference.browseName; childCacheNode.displayName = reference.displayName; childCacheNode.typeDefinition = reference.typeDefinition; childCacheNode.nodeClass = reference.nodeClass; (0, node_opcua_assert_1.assert)(childCacheNode.parent === parentNode); (0, node_opcua_assert_1.assert)(childCacheNode.referenceToParent === reference); this._add_crawl_task(childCacheNode, userData); } else { if (userData.setExtraReference) { const task = { func: _setExtraReference, param: { childCacheNode, parentNode, reference, userData } }; this._push_task("setExtraRef", task); } } } /** * perform pending read Node operation * @method _resolve_deferred_readNode * @param callback * @private * @internal */ _resolve_deferred_readNode(callback) { if (this.pendingReadTasks.length === 0) { // nothing to read callback(); return; } debugLog("_resolve_deferred_readNode = ", this.pendingReadTasks.length); const selectedPendingReadTasks = _fetch_elements(this.pendingReadTasks, this.maxNodesPerRead); const nodesToRead = selectedPendingReadTasks.map((e) => e.nodeToRead); this.readCounter += nodesToRead.length; this.transactionCounter++; this.session.read(nodesToRead, (err, dataValues) => { /* istanbul ignore else */ if (err) { return callback(err); } for (const pair of (0, underscore_1.zip)(selectedPendingReadTasks, dataValues)) { const readTask = pair[0]; const dataValue = pair[1]; (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(dataValue, "statusCode")); if (dataValue.statusCode.equals(node_opcua_status_code_1.StatusCodes.Good)) { /* istanbul ignore else */ if (dataValue.value === null) { readTask.action(null, dataValue); } else { readTask.action(dataValue.value.value, dataValue); } } else { readTask.action({ name: dataValue.statusCode.toString() }, dataValue); } } callback(); }); } _resolve_deferred_browseNode(callback) { if (this.pendingBrowseTasks.length === 0) { callback(); return; } debugLog("_resolve_deferred_browseNode = ", this.pendingBrowseTasks.length); const objectsToBrowse = _fetch_elements(this.pendingBrowseTasks, this.maxNodesPerBrowse); const nodesToBrowse = objectsToBrowse.map((e) => { (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(e, "referenceTypeId")); return new node_opcua_service_browse_1.BrowseDescription({ browseDirection: node_opcua_data_model_1.BrowseDirection.Forward, includeSubtypes: true, nodeId: e.nodeId, referenceTypeId: e.referenceTypeId, resultMask }); }); this.browseCounter += nodesToBrowse.length; this.transactionCounter++; this.session.browse(nodesToBrowse, (err, browseResults) => { /* istanbul ignore else */ if (err) { debugLog("session.browse err:", err); return callback(err || undefined); } (0, node_opcua_assert_1.assert)(browseResults.length === nodesToBrowse.length); browseResults = browseResults || []; const task = { func: NodeCrawlerBase.prototype._process_browse_response_task, param: { browseResults, objectsToBrowse } }; this._unshift_task("process browseResults", task); callback(); }); } _resolve_deferred_browseNext(callback) { /* istanbul ignore else */ if (this.pendingBrowseNextTasks.length === 0) { callback(); return; } debugLog("_resolve_deferred_browseNext = ", this.pendingBrowseNextTasks.length); const objectsToBrowse = _fetch_elements(this.pendingBrowseNextTasks, this.maxNodesPerBrowse); const continuationPoints = objectsToBrowse.map((e) => e.continuationPoint); this.browseNextCounter += continuationPoints.length; this.transactionCounter++; this.session.browseNext(continuationPoints, false, (err, browseResults) => { if (err) { debugLog("session.browse err:", err); return callback(err || undefined); } (0, node_opcua_assert_1.assert)(browseResults.length === continuationPoints.length); browseResults = browseResults || []; const task = { func: NodeCrawlerBase.prototype._process_browse_response_task, param: { browseResults, objectsToBrowse } }; this._unshift_task("process browseResults", task); callback(); }); } /** * @method _unshift_task * add a task on top of the queue (high priority) * @param name * @param task * @private */ _unshift_task(name, task) { (0, node_opcua_assert_1.assert)(typeof task.func === "function"); (0, node_opcua_assert_1.assert)(task.func.length === 2); this.taskQueue.unshift(task); debugLog("unshift task", name); } /** * @method _push_task * add a task at the bottom of the queue (low priority) * @param name * @param task * @private */ _push_task(name, task) { (0, node_opcua_assert_1.assert)(typeof task.func === "function"); (0, node_opcua_assert_1.assert)(task.func.length === 2); debugLog("pushing task", name); this.taskQueue.push(task); } /*** * @method _emit_on_crawled * @param cacheNode * @param userData * @private */ _emit_on_crawled(cacheNode, userData) { this.emit("browsed", cacheNode, userData); } _crawl_task(task, callback) { const cacheNode = task.param.cacheNode; const nodeId = task.param.cacheNode.nodeId; const key = nodeId.toString(); if (this._visitedNode.has(key)) { debugLog("skipping already visited", key); callback(); return; // already visited } // mark as visited to avoid infinite recursion this._visitedNode.add(key); const browseNodeAction = (err, cacheNode1) => { if (err || !cacheNode1) { return; } for (const reference of cacheNode1.references) { // those ones come for free if (!this.has_cache_NodeAttribute(reference.nodeId, node_opcua_data_model_1.AttributeIds.BrowseName)) { this.set_cache_NodeAttribute(reference.nodeId, node_opcua_data_model_1.AttributeIds.BrowseName, reference.browseName); } if (!this.has_cache_NodeAttribute(reference.nodeId, node_opcua_data_model_1.AttributeIds.DisplayName)) { this.set_cache_NodeAttribute(reference.nodeId, node_opcua_data_model_1.AttributeIds.DisplayName, reference.displayName); } if (!this.has_cache_NodeAttribute(reference.nodeId, node_opcua_data_model_1.AttributeIds.NodeClass)) { this.set_cache_NodeAttribute(reference.nodeId, node_opcua_data_model_1.AttributeIds.NodeClass, reference.nodeClass); } } this._emit_on_crawled(cacheNode1, task.param.userData); const userData = task.param.userData; if (userData.onBrowse) { userData.onBrowse(this, cacheNode1, userData); } }; this._defer_browse_node(cacheNode, referencesNodeId, browseNodeAction); callback(); } _initialize_referenceTypeId() { const appendPrepopulatedReference = (browseName) => { const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.ReferenceTypeIds[browseName], 0); (0, node_opcua_assert_1.assert)(nodeId); const cacheNode = this._createCacheNode(nodeId); cacheNode.browseName = new node_opcua_data_model_1.QualifiedName({ name: browseName }); cacheNode.nodeClass = node_opcua_data_model_1.NodeClass.ReferenceType; this._prePopulatedSet.add(cacheNode); }; // References // +->(hasSubtype) NonHierarchicalReferences // +->(hasSubtype) HasTypeDefinition // +->(hasSubtype) HierarchicalReferences // +->(hasSubtype) HasChild/ChildOf // +->(hasSubtype) Aggregates/AggregatedBy // +-> HasProperty/PropertyOf // +-> HasComponent/ComponentOf // +-> HasHistoricalConfiguration/HistoricalConfigurationOf // +->(hasSubtype) HasSubtype/HasSupertype // +->(hasSubtype) Organizes/OrganizedBy // +->(hasSubtype) HasEventSource/EventSourceOf appendPrepopulatedReference("HasSubtype"); /* istanbul ignore else */ if (false) { appendPrepopulatedReference("HasTypeDefinition"); appendPrepopulatedReference("HasChild"); appendPrepopulatedReference("HasProperty"); appendPrepopulatedReference("HasComponent"); appendPrepopulatedReference("HasHistoricalConfiguration"); appendPrepopulatedReference("Organizes"); appendPrepopulatedReference("HasEventSource"); appendPrepopulatedReference("HasModellingRule"); appendPrepopulatedReference("HasEncoding"); appendPrepopulatedReference("HasDescription"); } } _readOperationalLimits(callback) { const n1 = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_OperationLimits_MaxNodesPerRead); const n2 = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_OperationLimits_MaxNodesPerBrowse); const nodesToRead = [ { nodeId: n1, attributeId: node_opcua_data_model_1.AttributeIds.Value }, { nodeId: n2, attributeId: node_opcua_data_model_1.AttributeIds.Value } ]; this.transactionCounter++; this.session.read(nodesToRead, (err, dataValues) => { /* istanbul ignore else */ if (err) { return callback(err); } dataValues = dataValues; const fix = (self, maxNodePerX, dataValue) => { if (dataValue.statusCode.equals(node_opcua_status_code_1.StatusCodes.Good)) { const value = dataValue.value.value; // if this.maxNodesPerRead has been set (<>0) by the user before call is made, // then it serve as a minimum if (self[maxNodePerX]) { if (value > 0) { self[maxNodePerX] = Math.min(self[maxNodePerX], value); } } else { self[maxNodePerX] = value; } } else { debugLog("warning: server does not provide a valid dataValue for " + maxNodePerX, dataValue.statusCode.toString()); } // ensure we have a sensible maxNodesPerRead value in case the server doesn't specify one self[maxNodePerX] = self[maxNodePerX] || 100; debugLog("maxNodesPerRead", self[maxNodePerX]); }; fix(this, "maxNodesPerRead", dataValues[0]); fix(this, "maxNodesPerBrowse", dataValues[1]); callback(); }); } set_cache_NodeAttribute(nodeId, attributeId, value) { const key = make_node_attribute_key(nodeId, attributeId); this.browseNameMap[key] = value; } has_cache_NodeAttribute(nodeId, attributeId) { const key = make_node_attribute_key(nodeId, attributeId); return Object.prototype.hasOwnProperty.call(this.browseNameMap, key); } get_cache_NodeAttribute(nodeId, attributeId) { const key = make_node_attribute_key(nodeId, attributeId); return this.browseNameMap[key]; } _defer_readNode(nodeId, attributeId, callback) { nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(nodeId); const key = make_node_attribute_key(nodeId, attributeId); if (this.has_cache_NodeAttribute(nodeId, attributeId)) { callback(null, this.get_cache_NodeAttribute(nodeId, attributeId)); } else { this.browseNameMap[key] = { "?": 1 }; this.pendingReadTasks.push({ action: (value, dataValue) => { if (attributeId === node_opcua_data_model_1.AttributeIds.Value) { this.set_cache_NodeAttribute(nodeId, attributeId, dataValue); callback(null, dataValue); return; } if (dataValue.statusCode === node_opcua_status_code_1.StatusCodes.Good) { this.set_cache_NodeAttribute(nodeId, attributeId, value); callback(null, value); } else { callback(new Error("Error " + dataValue.statusCode.toString() + " while reading " + nodeId.toString() + " attributeIds " + node_opcua_data_model_1.AttributeIds[attributeId])); } }, nodeToRead: { attributeId, nodeId } }); } } _resolve_deferred(comment, collection, method) { debugLog("_resolve_deferred ", comment, collection.length); if (collection.length > 0) { this._push_task("adding operation " + comment, { func: (task, callback) => { method.call(this, callback); }, param: {} }); } } resolve_deferred_readNode() { this._resolve_deferred("read_node", this.pendingReadTasks, this._resolve_deferred_readNode); } resolve_deferred_browseNode() { this._resolve_deferred("browse_node", this.pendingBrowseTasks, this._resolve_deferred_browseNode); } resolve_deferred_browseNext() { this._resolve_deferred("browse_next", this.pendingBrowseNextTasks, this._resolve_deferred_browseNext); } // --------------------------------------------------------------------------------------- _getCacheNode(nodeId) { const key = (0, node_opcua_nodeid_1.resolveNodeId)(nodeId).toString(); return this._objectCache[key]; } _createCacheNode(nodeId, parentNode, referenceToParent) { const key = (0, node_opcua_nodeid_1.resolveNodeId)(nodeId).toString(); let cacheNode = this._objectCache[key]; /* istanbul ignore else */ if (cacheNode) { throw new Error("NodeCrawlerBase#_createCacheNode :" + " cache node should not exist already : " + nodeId.toString()); } const nodeClass = (referenceToParent ? referenceToParent.nodeClass : node_opcua_data_model_1.NodeClass.Unspecified); switch (nodeClass) { case node_opcua_data_model_1.NodeClass.Method: cacheNode = new cache_node_1.CacheNode(nodeId); cacheNode.nodeClass = node_opcua_data_model_1.NodeClass.Method; break; case node_opcua_data_model_1.NodeClass.Object: cacheNode = new cache_node_1.CacheNode(nodeId); cacheNode.nodeClass = node_opcua_data_model_1.NodeClass.Object; break; case node_opcua_data_model_1.NodeClass.ObjectType: cacheNode = new cache_node_1.CacheNode(nodeId); cacheNode.nodeClass = node_opcua_data_model_1.NodeClass.ObjectType; break; case node_opcua_data_model_1.NodeClass.Variable: cacheNode = new cache_node_1.CacheNodeVariable(nodeId); break; case node_opcua_data_model_1.NodeClass.VariableType: cacheNode = new cache_node_1.CacheNodeVariableType(nodeId); break; default: cacheNode = new cache_node_1.CacheNode(nodeId); cacheNode.nodeClass = nodeClass; break; } cacheNode.parent = parentNode; cacheNode.referenceToParent = referenceToParent; (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(this._objectCache, key)); this._objectCache[key] = cacheNode; return cacheNode; } /** * perform a deferred browse * instead of calling session.browse directly, this function add the request to a list * so that request can be grouped and send in one single browse command to the server. * * @method _defer_browse_node * @private * */ _defer_browse_node(cacheNode, referenceTypeId, actionOnBrowse) { this.pendingBrowseTasks.push({ action: (object) => { (0, node_opcua_assert_1.assert)(object === cacheNode); (0, node_opcua_assert_1.assert)(Array.isArray(object.references)); (0, node_opcua_assert_1.assert)(cacheNode.browseName.name !== "pending"); actionOnBrowse(null, cacheNode); }, cacheNode, nodeId: cacheNode.nodeId, referenceTypeId }); } _defer_browse_next(cacheNode, continuationPoint, referenceTypeId, actionOnBrowse) { this.pendingBrowseNextTasks.push({ action: (object) => { (0, node_opcua_assert_1.assert)(object === cacheNode); (0, node_opcua_assert_1.assert)(Array.isArray(object.references)); (0, node_opcua_assert_1.assert)(cacheNode.browseName.name !== "pending"); actionOnBrowse(null, cacheNode); }, cacheNode, continuationPoint, nodeId: cacheNode.nodeId, referenceTypeId }); } /** * @method _process_single_browseResult * @param _objectToBrowse * @param browseResult * @private */ _process_single_browseResult(_objectToBrowse, browseResult) { const cacheNode = _objectToBrowse.cacheNode; // note : some OPCUA may expose duplicated reference, they need to be filtered out // dedup reference cacheNode.references = cacheNode.references.concat(browseResult.references); if (browseResult.continuationPoint) { // this._defer_browse_next(_objectToBrowse.cacheNode, browseResult.continuationPoint, _objectToBrowse.referenceTypeId, (err, cacheNode1) => { this._process_single_browseResult2(_objectToBrowse); }); } else { this._process_single_browseResult2(_objectToBrowse); } } _process_single_browseResult2(_objectToBrowse) { const cacheNode = _objectToBrowse.cacheNode; cacheNode.references = (0, private_1.dedup_reference)(cacheNode.references); // extract the reference containing HasTypeDefinition const tmp = cacheNode.references.filter((x) => (0, node_opcua_nodeid_1.sameNodeId)(x.referenceTypeId, hasTypeDefinitionNodeId)); if (tmp.length) { cacheNode.typeDefinition = tmp[0].nodeId; } async.parallel({ task1_read_browseName: (callback) => { if (cacheNode.browseName !== private_1.pendingBrowseName) { return callback(); } this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.BrowseName, (err, browseName) => { cacheNode.browseName = browseName; callback(); }); }, task2_read_displayName: (callback) => { if (cacheNode.displayName) { return callback(); } this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.DisplayName, (err, value) => { if (err) { return callback(err); } cacheNode.displayName = value; callback(); }); }, task3_read_description: (callback) => { this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.Description, (err, value) => { if (err) { // description may not be defined and this is OK ! return callback(); } cacheNode.description = (0, node_opcua_data_model_1.coerceLocalizedText)(value); callback(); }); }, task4_variable_dataType: (callback) => { // only if nodeClass is Variable || VariableType if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.Variable && cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.VariableType) { return callback(); } const cache = cacheNode; // read dataType and DataType if node is a variable this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.DataType, (err, dataType) => { if (!(dataType instanceof node_opcua_nodeid_1.NodeId)) { return callback(); } cache.dataType = dataType; callback(); }); }, task5_variable_dataValue: (callback) => { // only if nodeClass is Variable || VariableType if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.Variable && cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.VariableType) { return callback(); } const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.Value, (err, value) => { if (!err) { (0, node_opcua_assert_1.assert)(value instanceof node_opcua_data_value_1.DataValue); cache.dataValue = value; } callback(); }); }, task6a_variable_arrayDimension: (callback) => { if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.Variable && cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.VariableType) { return callback(); } const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.ArrayDimensions, (err, value) => { if (!err) { const standardArray = convertToStandardArray(value); cache.arrayDimensions = standardArray; // xxx console.log("arrayDimensions XXXX ", cache.arrayDimensions); } else { cache.arrayDimensions = undefined; // set explicitly } callback(); }); }, task6b_variable_valueRank: (callback) => { if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.Variable && cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.VariableType) { return callback(); } const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.ValueRank, (err, value) => { if (!err) { cache.valueRank = value; } callback(); }); }, task7_variable_minimumSamplingInterval: (callback) => { if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.Variable) { return callback(); } const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.MinimumSamplingInterval, (err, value) => { cache.minimumSamplingInterval = value; callback(); }); }, task8_variable_accessLevel: (callback) => { if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.Variable) { return callback(); } const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.AccessLevel, (err, value) => { if (err) { return callback(err); } cache.accessLevel = value; callback(); }); }, task9_variable_userAccessLevel: (callback) => { if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.Variable) { return callback(); } const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.UserAccessLevel, (err, value) => { if (err) { return callback(err); } cache.userAccessLevel = value; callback(); }); }, taskA_referenceType_inverseName: (callback) => { if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.ReferenceType) { return callback(); } const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.InverseName, (err, value) => { if (err) { return callback(err); } cache.inverseName = value; callback(); }); }, taskB_isAbstract: (callback) => { if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.ReferenceType) { return callback(); } const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.IsAbstract, (err, value) => { if (err) { return callback(err); } cache.isAbstract = value; callback(); }); }, taskC_dataTypeDefinition: (callback) => { if (cacheNode.nodeClass !== node_opcua_data_model_1.NodeClass.DataType) { return callback(); } // dataTypeDefinition is new in 1.04 const cache = cacheNode; this._defer_readNode(cacheNode.nodeId, node_opcua_data_model_1.AttributeIds.DataTypeDefinition, (err, value) => { if (err) { // may be we are crawling a 1.03 server => DataTypeDefinition was not defined yet return callback(); } cache.dataTypeDefinition = value; callback(); }); } }, () => { _objectToBrowse.action(cacheNode); }); } _process_browse_response_task(task, callback) { const objectsToBrowse = task.param.objectsToBrowse; const browseResults = task.param.browseResults; for (const pair of (0, underscore_1.zip)(objectsToBrowse, browseResults)) { const objectToBrowse = pair[0]; const browseResult = pair[1]; (0, node_opcua_assert_1.assert)(browseResult instanceof node_opcua_service_browse_1.BrowseResult); this._process_single_browseResult(objectToBrowse, browseResult); } setImmediate(callback); } }
JavaScript
class LegacyConditions extends Entity { conditions() { if (!this._entity) { return []; } return this._entity .getSubEntitiesByRel('item') .filter(entity => entity.hasClass(Classes.conditions.legacyCondition)) .map(entity => ({ id: entity.properties.conditionId, text: entity.title })); } /** @returns {bool} Whether the attach existing dialog opener sub entity is present. */ canAttachExisting() { if (!this._entity) { return false; } return this._entity.hasSubEntityByRel(Rels.Conditions.attachDialogOpener); } /** @returns {string} Attach existing dialog url */ attachExistingDialogUrl() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.attachDialogOpener); return entity ? entity.properties.url : undefined; } /** @returns {String} Attach existing open button text*/ attachExistingOpenButtonText() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.attachDialogOpener); return entity ? entity.title : undefined; } /** @returns {String} Attach existing dialog title */ attachExistingDialogTitle() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.attachDialogOpener); return entity ? entity.properties.dialogTitle : undefined; } /** @returns {String} Attach existing positive button text */ attachExistingPositiveButtonText() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.attachDialogOpener); return entity ? entity.properties.positiveText : undefined; } /** @returns {String} Attach existing negative button text */ attachExistingNegativeButtonText() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.attachDialogOpener); return entity ? entity.properties.negativeText : undefined; } /** @returns {bool} Whether the create new dialog opener sub entity is present. */ canCreateNew() { if (!this._entity) { return false; } return this._entity.hasSubEntityByRel(Rels.Conditions.createDialogOpener); } /** @returns {string} Create new dialog url */ createNewDialogUrl() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.createDialogOpener); return entity ? entity.properties.url : undefined; } /** @returns {String} Create new open button text*/ createNewOpenButtonText() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.createDialogOpener); return entity ? entity.title : undefined; } /** @returns {String} Create new dialog title */ createNewDialogTitle() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.createDialogOpener); return entity ? entity.properties.dialogTitle : undefined; } /** @returns {String} Create new positive button text */ createNewPositiveButtonText() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.createDialogOpener); return entity ? entity.properties.positiveText : undefined; } /** @returns {String} Create new negative button text */ createNewNegativeButtonText() { const entity = this._entity.getSubEntityByRel(Rels.Conditions.createDialogOpener); return entity ? entity.properties.negativeText : undefined; } /** @returns {bool} Whether operator can be edited */ canEditOperator() { if (!this._entity) { return false; } return this._entity.hasSubEntityByRel(Rels.Conditions.operators); } /** @returns {Array} Operator options */ operatorOptions() { if (!this._entity) { return []; } const entity = this._entity.getSubEntityByRel(Rels.Conditions.operators); return entity ? entity.properties.options : []; } /** @returns {bool} Whether they can save. */ canSave() { if (!this._entity) { return false; } return this._entity.hasActionByName(Actions.conditions.legacyReplace); } /** Saves. */ async save(changes) { if (!this._entity) { return; } const action = this._entity.getActionByName(Actions.conditions.legacyReplace); if (!action) { return; } const fields = [{ name: 'changes', value: changes }]; await performSirenAction(this._token, action, fields); } }
JavaScript
class FilterLogEventsCommand extends smithy_client_1.Command { // Start section: command_properties // End section: command_properties constructor(input) { // Start section: command_constructor super(); this.input = input; // End section: command_constructor } /** * @internal */ resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "CloudWatchLogsClient"; const commandName = "FilterLogEventsCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.FilterLogEventsRequest.filterSensitiveLog, outputFilterSensitiveLog: models_0_1.FilterLogEventsResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return Aws_json1_1_1.serializeAws_json1_1FilterLogEventsCommand(input, context); } deserialize(output, context) { return Aws_json1_1_1.deserializeAws_json1_1FilterLogEventsCommand(output, context); } }
JavaScript
class LoggerExtended extends Logger { /** * Overriding namespace for current repo. * * @returns {*} */ getRequestNameSpace() { return getNamespace('pepoApiNameSpace'); } }
JavaScript
class DialogueFromBot extends React.Component { // eslint-disable-line react/prefer-stateless-function getBubbles() { const bubbles = this.props.dialogue.bubbles; return bubbles.map((bubble, index) => { switch (bubble.type) { case 'text': return this.textBubble(bubble, index); case 'transformedText': return this.transformedTextBubble(bubble, index); case 'link': return this.linkBubble(bubble, index); case 'media': return this.mediaBubble(bubble, index); default: return this.textBubble(bubble, index); } }); } textBubble(bubble, keyIndex) { return ( <article key={keyIndex} className="qt-chat__bubble"> <div> <p>{Parser(bubble.content)}</p> </div> </article> ); } transformedTextBubble(bubble, keyIndex) { return ( <article key={keyIndex} className="qt-chat__bubble"> <div> <p>{Parser(bubble.content.replace('@varName', this.props[bubble.varName]))}</p> </div> </article> ); } linkBubble(bubble, keyIndex) { return ( <article key={keyIndex} className="qt-chat__bubble is-link"> <div> <a href={bubble.content} target="_blank"> <h3 className="qt-chat__specialText ">{bubble.title}</h3> <p>{bubble.description}</p> <span className="qt-chat__specialText"> {Parser(bubble.content)} </span> </a> </div> </article> ); } mediaBubble(bubble, keyIndex) { return ( <article key={keyIndex} className="qt-chat__media"> <img src={bubble.content} alt="fun" /> </article> ); } render() { const bubbles = this.getBubbles(); return ( <div className="qt-chat__dialogue from-bot"> <div className="qt-avatar"></div> <div className="qt-chat__bubbles"> {bubbles} </div> </div> ); } }
JavaScript
class Vector { /** * Creates an instance of Vector. * * @param {Number} x - The initial X component of the vector. * @param {Number} y - The initial Y component of the vector. */ constructor(x, y) { this.x = x; this.y = y; } /** * The magnitude of the Vector. * * @readonly * * @memberOf Vector */ get magnitude() { return Math.sqrt(this.x * this.x + this.y * this.y); } /** * The magnitude of the Vector, squarred. * * @readonly * * @memberOf Vector */ get magnitudeSqr() { return this.x * this.x + this.y * this.y; } /** * Gives the angle of the Vector. * * @readonly * * @memberOf Vector */ get angle() { if (this.y < 0) { return 2 * Math.PI - Math.acos(this.x / this.magnitude); } return Math.acos(this.x / this.magnitude); } /** * Get the normalized version of this Vector. * * @readonly * * @memberOf Vector */ get normalized() { let mag = this.magnitude; if (mag === 0) { return new Vector(0, 0); } return Vector.Multiply(this, 1 / mag); } /** * Clamp the current Vector to a certain maximum. * * @param {Number} max - The maximum value of the resulting vector's magnitude * * @memberOf Vector */ Clamp(max) { let mag = this.magnitude; if (mag === 0) return; if (mag > max) { let tmp = Vector.Multiply(this, (max / mag)); this.x = tmp.x; this.y = tmp.y; } } /** * Find the distance between the two vector, squarred. * * @static * @param {Vector} v1 - The first vector * @param {Vector} v2 - The second vector * @returns {Number} * * @memberOf Vector */ static DistanceSqr(v1, v2) { if (!(v1 instanceof Vector) || !(v2 instanceof Vector)) { console.error("The arguments are not vectors") return null; } return ((v2.x - v1.x) * (v2.x - v1.x)) + ((v2.y - v1.y) * (v2.y - v1.y)); } /** * Find the distance between the two vector. * * @static * @param {Vector} v1 - The first vector * @param {Vector} v2 - The second vector * @returns {Number} The distance between the two Vectors. * * @memberOf Vector */ static Distance(v1, v2) { if (!(v1 instanceof Vector) || !(v2 instanceof Vector)) { console.error("The arguments are not vectors") return null; } return Math.sqrt(Vector.DistanceSqr(v1, v2)); } /** * Verify if the provided object is a Vector. * * @static * @param {any} vector - The object to test. * @returns {boolean} * * @memberOf Vector */ static IsVector(vector) { return (vector instanceof Vector); } /** * Adds two Vectors together * * @static * @param {Vector} v1 - The first vector. * @param {Vector} v2 - The second vector. * @returns {Vector} The resulting vector. * * @memberOf Vector */ static Add(v1, v2) { if (!(v1 instanceof Vector) || !(v2 instanceof Vector)) { console.error("The arguments are not vectors") return null; } return new Vector(v1.x + v2.x, v1.y + v2.y); } /** * Subtract one Vector from another one. * * @static * @param {Vector} v1 - The first vector. * @param {Vector} v2 - The second vector. * @returns {Vector} The resulting vector. * * @memberOf Vector */ static Subtract(v1, v2) { if (!(v1 instanceof Vector) || !(v2 instanceof Vector)) { console.error("The arguments are not vectors") return null; } return new Vector(v1.x - v2.x, v1.y - v2.y); } /** * Multiply a Vector by a scalar * * @static * @param {Vector} v1 - The vector to multiply. * @param {Number} s - The scalar to multiply with. * @returns {Vector} The resulting Vector. * * @memberOf Vector */ static Multiply(v1, s) { if (!(v1 instanceof Vector)) { console.error("The arguments are not vectors") return null; } return new Vector(v1.x * s, v1.y * s); } /** * Calculate the dot product between two vectors. * * @static * @param {Vector} v1 - The first Vector. * @param {Vector} v2 - The second Vector. * @returns {Number} The resulting scalar. * * @memberOf Vector */ static DotProduct(v1, v2) { if (!(v1 instanceof Vector) || !(v2 instanceof Vector)) { console.error("The arguments are not vectors") return null; } return (v1.x * v2.x + v1.y * v2.y); } /** * Calculate the projection of a Vector on another Vector. * * @static * @param {Vector} v1 - The Vector to project from. * @param {Vector} v2 - The Vector to project on. * @returns {Vector} The resulting Vector. * * @memberOf Vector */ static Project(v1, v2) { if (!(v1 instanceof Vector) || !(v2 instanceof Vector)) { console.error("The arguments are not vectors") return null; } if (v2.magnitudeSqr === 0) return Vector.zero; return Vector.Multiply(v2, Vector.DotProduct(v1, v2) / v2.magnitudeSqr); } /** * The zero Vector. * * @readonly * @static * * @memberOf Vector */ static get zero() { return new Vector(0, 0); } }
JavaScript
class GridFocusKeyManager extends GridKeyManager { /** * @param {?} cell * @return {?} */ setActiveCell(cell) { super.setActiveCell(cell); if (this.activeCell) { this.activeCell.focus(); } } }
JavaScript
class TreeNodeCtrl { constructor($element, $scope) { 'ngInject'; this.$element = $element; this.$scope = $scope; } /** * Lookup for the tree component scope recursevly */ _getTreeScope() { let treeScope = this.$scope; do { treeScope = treeScope.$parent; } while (treeScope && !treeScope.hasOwnProperty('hippoTree')); return treeScope; } /** * Get the external scope via a parent of transcluded scope */ _getOuterScope() { const treeScope = this._getTreeScope(); const transcludedScope = treeScope && treeScope.$parent; return transcludedScope && transcludedScope.$parent; } /** * Render component */ _render() { if (!this.scope.hippoTree) { return; } this.scope.hippoTree.renderTreeTemplate( this.scope, dom => this.$element.replaceWith(dom), ); } $onInit() { this.scope = this._getOuterScope() .$new(); this.$scope.$watch(() => this.item, (item) => { this.scope.item = item; }); this.$scope.$watch(() => this.uiTreeNode, (uiTreeNode) => { this.scope.toggle = uiTreeNode && uiTreeNode.scope.toggle; }); this.$scope.$watch(() => this.hippoTree, (hippoTree) => { this.scope.hippoTree = hippoTree; this._render(); }); } }
JavaScript
class Icon extends React.Component { static propTypes = { className: PropTypes.string, title: PropTypes.string, }; render() { const { className, title } = this.props; return ( <i className={ cx("fas", className) } title={ title } /> ) } }
JavaScript
class ApiDeployerEditor extends HashBrown.Views.Editors.Editor { // Alias static get alias() { return 'api'; } /** * Renders this editor */ template() { return _.div({class: 'editor__field-group'}, this.field( { label: 'URL', description: 'The base URL of the API' }, new HashBrown.Views.Widgets.Input({ type: 'text', value: this.model.url, placeholder: 'Input URL', onChange: (newValue) => { this.model.url = newValue; } }) ), this.field( { label: 'Token', description: 'An authenticated API token' }, new HashBrown.Views.Widgets.Input({ type: 'text', value: this.model.token, placeholder: 'Input token', onChange: (newValue) => { this.model.token = newValue; } }) ) ); } }
JavaScript
class Link { constructor (left, right, type, delay, energy, cost) { this.left = left this.right = right this.type = type this.delay = delay this.energy = energy this.cost = cost } }
JavaScript
class Simulator { constructor (context) { this.ctx = context this.id = this.ctx.getImageData(0, 0, 1, 1) this.intervalid = -1 } generate (width, height, count, hotspotFraction, hotspotRange, dHotspotFraction, internetFraction) { if (this.intervalid !== -1) { clearInterval(this.intervalid) } this.width = width this.height = height this.count = count this.wifiHotspotFraction = hotspotFraction this.wifiHotspotRange = hotspotRange this.wifiDirectHotspotFraction = dHotspotFraction this.internetFraction = internetFraction this.links = [] this.devices = [] for (let counter = 0; counter < this.count; counter++) { let x = Math.floor(Math.random() * 500) // TODO: globals let y = Math.floor(Math.random() * 500) let device = new Device(x, y, CLAMP_BOUNCE) if (Math.floor(Math.random() * 100) < hotspotFraction) { let range = Math.floor(Math.random() * hotspotRange) + (2 / 3 * hotspotRange) device.addRadio(WIFI_RADIO, range) device.radioMode(WIFI_RADIO, WIFI_HOTSPOT) } else { device.addRadio(WIFI_RADIO, INFINITE_RANGE) device.radioMode(WIFI_RADIO, WIFI_CLIENT) } if (Math.floor(Math.random() * 100) < dHotspotFraction) { let range = Math.floor(Math.random() * hotspotRange) + (2/3 * hotspotRange) device.addRadio(WIFI_DIRECT_RADIO, range) device.radioMode(WIFI_DIRECT_RADIO, WIFI_DIRECT_HOTSPOT) } else { device.addRadio(WIFI_DIRECT_RADIO, INFINITE_RANGE) device.radioMode(WIFI_DIRECT_RADIO, WIFI_DIRECT_CLIENT) } if (Math.floor(Math.random() * 100) < internetFraction) { device.addRadio(CELL_RADIO, INFINITE_RANGE) device.radioMode(CELL_RADIO, INTERNET_CONNECTED) } else { device.addRadio(CELL_RADIO, INFINITE_RANGE) device.radioMode(CELL_RADIO, NOT_INTERNET_CONNECTED) } this.devices.push(device) } } run (continuous) { if (continuous === false) { this.frame() } else { this.intervalid = setInterval(this.frame.bind(this), 100) } } pause () { clearInterval(this.intervalid) } frame () { this.clear() this.update() this.draw() } clear () { this.ctx.clearRect(0, 0, 500, 500) } update () { let counter = 0 while (counter < this.devices.length) { let device = this.devices[counter] this.moveDevice(device) counter++ } this.links = [] this.updateLinks() this.updateBTLinks() this.updateWDLinks() } moveDevice (device) { let xStep = (Math.random() * 0.2) - 0.1 let yStep = (Math.random() * 0.2) - 0.1 device.dx += xStep device.dy += yStep device.x += device.dx device.y += device.dy } getHotspots (device) { let index = 0 let hotspots = [] let counter = 0 while (counter < this.devices.length) { if (this.devices[counter].is(WIFI_RADIO, WIFI_HOTSPOT) === true) { let distance = Math.sqrt(Math.pow(this.devices[counter].x - device.x, 2) + Math.pow(this.devices[counter].y - device.y, 2)) if (distance < this.devices[counter].range(WIFI_RADIO)) { hotspots[index] = this.devices[counter] index++ } } counter++ } return hotspots } getClients (device) { if (!device.is(WIFI_RADIO, WIFI_HOTSPOT)) { return [] } let index = 0 let clients = [] let counter = 0 while (counter < this.devices.length) { let distance = Math.sqrt(Math.pow(this.devices[counter].x - device.x, 2) + Math.pow(this.devices[counter].y - device.y, 2)) if (distance < device.range(WIFI_RADIO)) { clients[index] = this.devices[counter] index++ } counter++ } return clients } updateLinks () { // Wifi links for (let counterLeft in this.devices) { let deviceLeft = this.devices[counterLeft] let hotspots = this.getHotspots(deviceLeft) for (let counterRight in hotspots) { let deviceRight = hotspots[counterRight] // TODO: figure out where this bug comes from // Wifi is self-linking, which means that every device is // being reported as a hotspot of itself. // We remove self-links here, for now. if (deviceLeft !== deviceRight) { this.links.push(new EnergyLink( deviceLeft, deviceRight, WIFI_LINK, WIFI_ENERGY )) } } } // Internet links for (let counterLeft = 0; counterLeft < this.devices.length; counterLeft++) { let deviceLeft = this.devices[counterLeft] for (let counterRight = counterLeft + 1; counterRight < this.devices.length; counterRight++) { let deviceRight = this.devices[counterRight] if (deviceLeft.is(CELL_RADIO, INTERNET_CONNECTED) && deviceRight.is(CELL_RADIO, INTERNET_CONNECTED)) { this.links.push(new EnergyLink( deviceLeft, deviceRight, INTERNET_LINK, CELL_ENERGY )) } } } } updateWDLinks () { for (let counterLeft = 0; counterLeft < this.devices.length; counterLeft++) { let deviceLeft = this.devices[counterLeft] for (let counterRight = counterLeft + 1; counterRight < this.devices.length; counterRight++) { let deviceRight = this.devices[counterRight] let distance = Math.sqrt(Math.pow(deviceLeft.x - deviceRight.x, 2) + Math.pow(deviceLeft.y - deviceRight.y, 2)) let rangeLimit = 0 let canHazHotspot = false if (deviceLeft.is(WIFI_DIRECT_HOTSPOT)) { rangeLimit = deviceLeft.range(WIFI_DIRECT_RADIO) canHazHotspot = true } else if (deviceRight.is(WIFI_DIRECT_HOTSPOT)) { rangeLimit = deviceRight.range(WIFI_DIRECT_RADIO) canHazHotspot = true } if (canHazHotspot) { if (distance < rangeLimit) { this.links.push(new EnergyLink( deviceLeft, deviceRight, WIFI_DIRECT_LINK, WIFI_DIRECT_ENERGY )) } } } } } updateBTLinks () { for (let counterLeft = 0; counterLeft < this.devices.length; counterLeft++) { let deviceLeft = this.devices[counterLeft] for (let counterRight = counterLeft + 1; counterRight < this.devices.length; counterRight++) { let deviceRight = this.devices[counterRight] let distance = Math.sqrt(Math.pow(deviceLeft.x - deviceRight.x, 2) + Math.pow(deviceLeft.y - deviceRight.y, 2)) if (distance < BT_RANGE) { this.links.push(new EnergyLink( deviceLeft, deviceRight, BT_LINK, BT_ENERGY )) } } } } draw () { let counter = 0 while (counter < this.devices.length) { this.drawDevice(this.devices[counter]) counter++ } this.drawLinks() this.computeStats() } drawDevice (device) { this.id.data[RED_CHAN] = 0 this.id.data[GREEN_CHAN] = 0 this.id.data[BLUE_CHAN] = 0 this.id.data[ALPHA_CHAN] = 255 this.ctx.putImageData(this.id, device.x, device.y) if (device.is(WIFI_RADIO, WIFI_HOTSPOT) === true) { this.ctx.fillStyle = 'rgba(255, 10, 10, .2)' this.ctx.beginPath() this.ctx.arc(device.x, device.y, device.range(WIFI_RADIO), 0, Math.PI * 2, true) this.ctx.closePath() this.ctx.fill() } if (device.is(WIFI_DIRECT_RADIO, WIFI_DIRECT_HOTSPOT)) { this.ctx.fillStyle = 'rgba(155, 155, 10, .2)' this.ctx.beginPath() this.ctx.arc(device.x, device.y, device.range(WIFI_DIRECT_RADIO), 0, Math.PI * 2, true) this.ctx.closePath() this.ctx.fill() } this.ctx.fillStyle = 'rgba(10, 10, 255, .2)' this.ctx.beginPath() this.ctx.arc(device.x, device.y, BT_RANGE, 0, Math.PI * 2, true) this.ctx.closePath() this.ctx.fill() if (device.is(CELL_RADIO, INTERNET_CONNECTED)) { this.ctx.beginPath() this.ctx.fillStyle = 'rgba(0,0,0,.2)' this.ctx.strokeStyle = 'rgba(0,0,0,1)' this.ctx.arc(device.x, device.y, 5, 0, 2 * Math.PI) this.ctx.closePath() this.ctx.fill() this.ctx.stroke() } } drawLinks () { for (let counter in this.links) { let link = this.links[counter] if (link.type === WIFI_LINK) { this.ctx.strokeStyle = 'rgba(100, 10, 10, 1)' this.ctx.beginPath() this.ctx.moveTo(link.left.x, link.left.y) this.ctx.lineTo(link.right.x, link.right.y) this.ctx.stroke() } else if (link.type === BT_LINK) { this.ctx.strokeStyle = 'rgba(10, 10, 100, 1)' this.ctx.beginPath() this.ctx.moveTo(link.left.x, link.left.y) this.ctx.lineTo(link.right.x, link.right.y) this.ctx.stroke() } else if (link.type === WIFI_DIRECT_LINK) { this.ctx.strokeStyle = 'rgba(80, 80, 10, 1)' this.ctx.beginPath() this.ctx.moveTo(link.left.x, link.left.y) this.ctx.lineTo(link.right.x, link.right.y) this.ctx.stroke() } else if (link.type === INTERNET_LINK) { this.ctx.strokeStyle = 'rgba(0, 0, 0, .1)' this.ctx.beginPath() this.ctx.moveTo(link.left.x, link.left.y) this.ctx.lineTo(link.right.x, link.right.y) this.ctx.stroke() } } } /** * Return the set of all devices that are connected to this one * by a local mesh. A local mesh is composed of devices that are connected * to each other not via the internet. */ getLocalMeshDevices (device) { let nodesVisited = [] let nodesToVisit = [] let nodesToConsider = [] nodesToVisit.push(device) while (nodesToVisit.length !== 0) { let visit = nodesToVisit[0] for (let counter in this.links) { let link = this.links[counter] nodesToConsider = [] if (link.type !== INTERNET_LINK) { if (link.left === visit) { nodesToConsider.push(link.right) } else if (link.right === visit) { nodesToConsider.push(link.left) } } for (let considerCounter in nodesToConsider) { let consider = nodesToConsider[considerCounter] if (nodesVisited.indexOf(consider) === -1 && nodesToVisit.indexOf(consider) === -1) { nodesToVisit.push(consider) } } } nodesVisited.push(visit) nodesToVisit.splice(nodesToVisit.indexOf(visit), 1) } return nodesVisited } /** * Return the set of all unconnected devices. */ getUnconnectedDevices () { let unconnectedDevices = [] for (let counter in this.devices) { let device = this.devices[counter] unconnectedDevices.push(device) } for (let counter in this.links) { let link = this.links[counter] let index = -1; index = unconnectedDevices.indexOf(link.left) if (index !== -1) { unconnectedDevices.splice(index, 1) } index = unconnectedDevices.indexOf(link.right) if (index !== -1) { unconnectedDevices.splice(index, 1) } } return unconnectedDevices } computeStats () { let largestLocalMeshSize = 0 hasHotspot = 0 avgHotspots = 0 avgClients = 0 let counter = 0 let totalHotspots = 0 let device = this.devices[0] while (counter < this.devices.length) { device = this.devices[counter] let hotspots = this.getHotspots(device) if (hotspots.length !== 0) { hasHotspot++ } avgHotspots += hotspots.length counter++ if (device.is(WIFI_RADIO, WIFI_HOTSPOT)) { totalHotspots++ let clients = this.getClients(device) avgClients += clients.length } // Find largest local mesh let currentLocalMeshSize = 0 if ((currentLocalMeshSize = this.getLocalMeshDevices(device).length) > largestLocalMeshSize) { largestLocalMeshSize = currentLocalMeshSize } } let totalEnergy = 0 for (let counter in this.links) { let link = this.links[counter] totalEnergy += link.energy } $('#stat-density').text(this.count) $('#stat-wifi-hotspot-percent').text(this.wifiHotspotFraction) $('#stat-wifi-hotspot-range').text(this.wifiHotspotRange) $('#stat-wifi-hotspot-coverage').text(((hasHotspot / this.count) * 100).toFixed(2)) $('#stat-wifi-average-hotspots').text((avgHotspots / hasHotspot).toFixed(2)) $('#stat-wifi-average-clients').text((avgClients / totalHotspots).toFixed(2)) $('#stat-total-energy').text(totalEnergy) $('#stat-unconnected').text(this.getUnconnectedDevices().length) $('#stat-largest-local').text(largestLocalMeshSize) } }
JavaScript
class YourComponent extends Component { constructor(props) { super(props) this.state = { markers: [], favorites: [] } this.addFavorite = this.addFavorite.bind(this) this.removeFavorite = this.removeFavorite.bind(this) } componentDidMount() { const request = axios.get(URL_LOCATION) request.then(data => { this.setState({ markers: data.data.map(store => Object.assign(store, { favorite: false, showInfo: false })) }) }) } addFavorite(marker) { const markers = this.state.markers.map(m => { if (m._id === marker._id) { return { ...m, favorite: true, icon: favoriteIcon } } return m }) this.setState({ markers, favorites: [marker, ...this.state.favorites] }) } removeFavorite(marker) { const markers = this.state.markers.map(m => { if (m._id === marker._id) { return { ...m, favorite: false, icon: '' } } return m }) const favorites = markers.filter(m => m.favorite) this.setState({ markers, favorites }) } render() { return ( <div className="solution-container"> <div className="d-flex flex-row justify-content-center"> <div className="d-flex flex-column w-50 map-container"> <div className="card"> <div className="card-body"> <h3 className="card-title">Stores</h3> <MexicoMap markers={this.state.markers} addFavorite={this.addFavorite}/> </div> </div> </div> <div className="w-50"> <FavoriteStores favorites={this.state.favorites} removeFavorite={this.removeFavorite}></FavoriteStores> </div> </div> </div > ); } }
JavaScript
class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } strBuffer = s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); const stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } const errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); if (this.options.input) { if (!cp.stdin) { throw new Error('child process missing stdin'); } cp.stdin.end(this.options.input); } }); }); } }
JavaScript
class RequestError extends Error { constructor(message, statusCode, options) { super(message); // Maintains proper stack trace (only available on V8) /* istanbul ignore next */ if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = "HttpError"; this.status = statusCode; Object.defineProperty(this, "code", { get() { logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); return statusCode; } }); this.headers = options.headers || {}; // redact request credentials without mutating original request options const requestCopy = Object.assign({}, options.request); if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") }); } requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); this.request = requestCopy; } }
JavaScript
class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; const headers = new Headers(opts.headers); if (body != null && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS$1] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } }
JavaScript
class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parse_url(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parse_url(`${input}`); } input = {}; } else { parsedURL = parse_url(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } }
JavaScript
class Intern extends Employee { constructor(name, id, email, school) { // calls parent constructor and adds the school info to its arguments/parameters super(name, id, email); this.school = school; } getSchool() { return this.school; } getRole() { return "Intern"; } }
JavaScript
class NewWellFull extends Component { constructor(props) { super(props); this.state = { ...INITIAL_STATE }; } peaceOutSquirrelScout() { this.props.history.push('/my-wells'); } handleSubmit = (state,event,uid) => { event.preventDefault(); let surveyData=state.surveyData let temp = data[state.description][state.normSize][state.pipeId][state.normWeight][state.adjustWeight][state.grade][state.upset][state.thread] //create objects to pass to database let wellProperties = { "description":state.description, "NorminalSize":state.normSize, "pipeInnerDiameter":state.pipeId, "norminalWeight":state.norminalWeight, "adjustWeight":state.adjustWeight, "grade":state.grade, "upset":state.upset, "thread":state.thread, } let wellObj = { latitude:state.metaData.Latitude, longitude:state.metaData.Longitude, wellName:state.metaData.wellName, wellUWI:state.metaData.wellWUID, wellLocation:state.metaData.wellLocation, pipeData:{wellProperties:wellProperties,labTestedData:temp}, surveyData:surveyData, comment:state.metaData.comment } //pass to database API.saveWell({ userId: uid, wellData: wellObj }).then(response=>{ //get data and save to session storage.then() redirect to mywells else throw an error API.getUserAndWells({uid:uid}).then(response=> {sessionStorage.setItem("userData",JSON.stringify(response.data.userData)); sessionStorage.setItem('wellData',JSON.stringify(response.data.wellData)); //redirect now this.peaceOutSquirrelScout(); }) }) } handleData = data => { this.setState(byPropKey('surveyData',data)) alert('survey data processed'); } handleError = error => { alert(error); } handleChange = (state,event) => { let name = event.target.name; let value = event.target.value; {/*have a concept of how to do all this with a for loop*/} switch(name) { case "description": if(value!="undecided") { this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:value, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:state.grade, upset:state.upset, thread:state.thread, normSizeDisabled:false, pipeIdDisabled:true, normWeightDisabled:true, adjustWeightDisabled:true, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }); }else{ this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:'', normSize:'', pipeId:'', normWeight:'', adjustWeight:'', grade:'', upset:'', thread:'', normSizeDisabled:true, pipeIdDisabled:true, normWeightDisabled:true, adjustWeightDisabled:true, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }) } break; case "normSize": if(value!="undecided") { this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:value, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:state.grade, upset:state.upset, thread:state.thread, normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:true, adjustWeightDisabled:true, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }); }else{ this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:'', pipeId:'', normWeight:'', adjustWeight:'', grade:'', upset:'', thread:'', normSizeDisabled:false, pipeIdDisabled:true, normWeightDisabled:true, adjustWeightDisabled:true, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }) } break; case "pipeId": if(value!="undecided") { this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:value, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:state.grade, upset:state.upset, thread:state.thread, normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:true, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }) }else{ this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:'', normWeight:'', adjustWeight:'', grade:'', upset:'', thread:'', normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:true, adjustWeightDisabled:true, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }) } break; case "normWeight": if(value!="undecided") { this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:value, adjustWeight:state.adjustWeight, grade:state.grade, upset:state.upset, thread:state.thread, normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }) }else{ this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:'', adjustWeight:'', grade:'', upset:'', thread:'', normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:true, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }) } break; case "adjustWeight": if(value!="undecided") { this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:value, grade:state.grade, upset:state.upset, thread:state.thread, normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:false, upsetDisabled:true, threadDisabled:true, canSubmit:true, }); }else{ this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:'', grade:'', upset:'', thread:'', normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:true, upsetDisabled:true, threadDisabled:true, canSubmit:true, }) } break; case "grade": if(value!="undecided") { this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:value, upset:state.upset, thread:state.thread, normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:false, upsetDisabled:false, threadDisabled:true, canSubmit:true, }) }else{ this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:'', upset:'', thread:'', normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:false, upsetDisabled:true, threadDisabled:true, canSubmit:true, }) } break; case "upset": if(value!="undecided") { this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:state.grade, upset:value, thread:state.thread, normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:false, upsetDisabled:false, threadDisabled:false, canSubmit:true,}); }else{ this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:state.grade, upset:'', thread:'', normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:false, upsetDisabled:false, threadDisabled:true, canSubmit:true, }) } break; case "thread": if(value!="undecided") { this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:state.grade, upset:state.upset, thread:value, normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:false, upsetDisabled:false, threadDisabled:false, canSubmit:false, }); }else{ this.setState({ metaData:{wellName:state.metaData.wellName,wellWUID:state.metaData.wellWUID,wellLocation:state.metaData.wellLocation,Longitude:state.metaData.Longitude,Latitude:state.metaData.Latitude,quickNote:state.metaData.quickNote}, surveyData:state.surveyData, description:state.description, normSize:state.normSize, pipeId:state.pipeId, normWeight:state.normWeight, adjustWeight:state.adjustWeight, grade:state.grade, upset:state.upset, thread:'', normSizeDisabled:false, pipeIdDisabled:false, normWeightDisabled:false, adjustWeightDisabled:false, gradeDisabled:false, upsetDisabled:false, threadDisabled:false, canSubmit:true, }) } break; default: alert('something went wrong in the on change function') break; } } render(){ const { metaData, surveyData, description, normSize, pipeId, normWeight, adjustWeight, grade, upset, thread, normSizeDisabled, pipeIdDisabled, normWeightDisabled, adjustWeightDisabled, gradeDisabled, upsetDisabled, threadDisabled, canSubmit, } = this.state; const keys = [ 'Depth (ft)', 'Incl (Deg)', 'Azim (Deg)', 'XXXX', 'XXXX', 'XXXX', 'XXXX', 'XXXX', 'XXXX', 'XXXX', 'XXXX', 'XXXX', ] return ( <div> <hr /> <form onSubmit={(event)=>{this.handleSubmit(this.state,event,this.props.uid)}}> <table style={{"width":"100%"}}> <thead> <tr> <th>Well name</th> <th>Well UWI</th> <th>Well Location</th> <th>Longitude</th> <th>Latitude</th> <th>Quick Note</th> <th>Upload Survey Data</th> </tr> </thead> <tbody> <tr> <td><input value={metaData.wellName} onChange={event => {let obj=metaData; obj.wellName=event.target.value; this.setState(byPropKey('metaData',obj))}} type="text" placeholder="enter here" size="20" required /></td> <td><input value={metaData.wellWUID} onChange={event => {let obj=metaData; obj.wellWUID=event.target.value; this.setState(byPropKey('metaData',obj))}} type="text" placeholder="enter here" size="20" required /></td> <td><input value={metaData.wellLocation} onChange={event => {let obj=metaData; obj.wellLocation=event.target.value; this.setState(byPropKey('metaData',obj))}} type="text" placeholder="enter here" size="20" required /></td> <td><input value={metaData.Longitude} onChange={event => {let obj=metaData; obj.Longitude=event.target.value; this.setState(byPropKey('metaData',obj))}} type="text" placeholder="enter here" size="20" required /></td> <td><input value={metaData.Latitude} onChange={event => {let obj=metaData; obj.Latitude=event.target.value; this.setState(byPropKey('metaData',obj))}} type="text" placeholder="enter here" size="20" required /></td> <td><input value={metaData.quickNote} onChange={event => {let obj=metaData; obj.quickNote=event.target.value; this.setState(byPropKey('metaData',obj))}} type="text" placeholder="enter here" size="20" required /></td> <td> <CsvParse keys={keys} onDataUploaded={this.handleData} onError={this.handleError} render={onChange => <input type="file" onChange={onChange} />} /></td> </tr> </tbody> </table> <br /> <br /> <table style={{"width":"100%"}}> <thead> <tr>{/*literally could have done all this with a for loop*/} <th>Description</th> <th>Norminal Size</th> <th>Pipe Inner Diameter</th> <th>Norminal Weight</th> <th>Adjust Weight</th> <th>Grade</th> <th>Upset</th> <th>Thread</th> <th>Submit</th> </tr> </thead> <tbody> <tr>{/*literally could have done all this with a for loop*/} <td> <select id="description" name="description" ref="description" onChange={(event)=>this.handleChange(this.state,event)} dangerouslySetInnerHTML={renderOptions(this.state,"description")} > </select> </td> <td> <select id="normSize" name="normSize" ref="normSize" onChange={(event)=>this.handleChange(this.state,event)} dangerouslySetInnerHTML={renderOptions(this.state,"normSize")} disabled={normSizeDisabled}> </select> </td> <td> <select id="pipeId" name="pipeId" ref="pipeId" onChange={(event)=>this.handleChange(this.state,event)} dangerouslySetInnerHTML={renderOptions(this.state,"pipeId")} disabled={pipeIdDisabled}> </select> </td> <td> <select id="normWeight" name="normWeight" ref="normWeight" onChange={(event)=>this.handleChange(this.state,event)} dangerouslySetInnerHTML={renderOptions(this.state,"normWeight")} disabled={normWeightDisabled}> </select> </td> <td> <select id="adjustWeight" name="adjustWeight" ref="adjustWeight" onChange={(event)=>this.handleChange(this.state,event)} dangerouslySetInnerHTML={renderOptions(this.state,"adjustWeight")} disabled={adjustWeightDisabled}> </select> </td> <td> <select id="grade" name="grade" ref="grade" onChange={(event)=>this.handleChange(this.state,event)} dangerouslySetInnerHTML={renderOptions(this.state,"grade")} disabled={gradeDisabled}> </select> </td> <td> <select id="upset" name="upset" ref="upset" onChange={(event)=>this.handleChange(this.state,event)} dangerouslySetInnerHTML={renderOptions(this.state,"upset")} disabled={upsetDisabled}> </select> </td> <td> <select id="thread" name="thread" ref="thread" onChange={(event)=>this.handleChange(this.state,event)} dangerouslySetInnerHTML={renderOptions(this.state,"thread")} disabled={threadDisabled}> </select> </td> <td> <input type="submit" value="submit" disabled={canSubmit} /> </td> </tr> </tbody> </table> </form> </div> ) } }
JavaScript
class GenericTokenizer extends AbstractTokenizer_1.AbstractTokenizer { constructor() { super(); this.symbolState = new GenericSymbolState_1.GenericSymbolState(); this.symbolState.add("<>", TokenType_1.TokenType.Symbol); this.symbolState.add("<=", TokenType_1.TokenType.Symbol); this.symbolState.add(">=", TokenType_1.TokenType.Symbol); this.numberState = new GenericNumberState_1.GenericNumberState(); this.quoteState = new GenericQuoteState_1.GenericQuoteState(); this.whitespaceState = new GenericWhitespaceState_1.GenericWhitespaceState(); this.wordState = new GenericWordState_1.GenericWordState(); this.commentState = new GenericCommentState_1.GenericCommentState(); this.clearCharacterStates(); this.setCharacterState(0x0000, 0x00ff, this.symbolState); this.setCharacterState(0x0000, ' '.charCodeAt(0), this.whitespaceState); this.setCharacterState('a'.charCodeAt(0), 'z'.charCodeAt(0), this.wordState); this.setCharacterState('A'.charCodeAt(0), 'Z'.charCodeAt(0), this.wordState); this.setCharacterState(0x00c0, 0x00ff, this.wordState); this.setCharacterState(0x0100, 0xfffe, this.wordState); this.setCharacterState('-'.charCodeAt(0), '-'.charCodeAt(0), this.numberState); this.setCharacterState('0'.charCodeAt(0), '9'.charCodeAt(0), this.numberState); this.setCharacterState('.'.charCodeAt(0), '.'.charCodeAt(0), this.numberState); this.setCharacterState('\"'.charCodeAt(0), '\"'.charCodeAt(0), this.quoteState); this.setCharacterState('\''.charCodeAt(0), '\''.charCodeAt(0), this.quoteState); this.setCharacterState('#'.charCodeAt(0), '#'.charCodeAt(0), this.commentState); } }
JavaScript
class I18n { /** Create a new object, ready to be used. * * @param {string} defaultLanguage Initial base language to base all translations on. * @param {string} baseLanguageKey Key to use for base language overrides. (Default = _base) * @throws Exception on invalid parameters. */ constructor(defaultLanguage, baseLanguageKey = "_base") { this._sanitizeLanguage(defaultLanguage); this._verifyKey(baseLanguageKey); this.languages = new Map(); this.chains = new Map(); this.baseLanguage = defaultLanguage; this.baseLanguageKey = baseLanguageKey; this.events = { missingkey: new Map(), missinglanguage: new Map(), change: new Map() }; this.dirtyTs = performance.now(); this.chainsTs = performance.now(); } /** Update the global base language. * * @param {string} language */ setBaseLanguage(language) { this._sanitizeLanguage(language); this.baseLanguage = language; this.dirtyTs = performance.now(); // Event: onchange this._callEvent("change"); } /** Retrieve the global base language. * * @return {string} name of base language. */ getBaseLanguage() { return this.baseLanguage; } /** Check if a language is known. * * @param {string} language Name of the language * @returns {bool} true if known. */ hasLanguage(language) { language = this._sanitizeLanguage(language); return this.languages.has(language); } /** Create a new language. * * @param {string} language Name of the language. * @throws Exception on invalid parameters. */ createLanguage(language) { language = this._sanitizeLanguage(language); this.languages.set(language, new Map()); this.dirtyTs = performance.now(); // Event: onchange this._callEvent("change"); } /** Load a new language. * * @param {string} language Name of the language. * @param {File/Blob/object/string} data Data containing a JSON representation of the language. * @param {string} encoding (Optional) Encoding to use when reading File or Blob. * @returns {Promise} * @throws Exception on invalid parameters or invalid data. */ loadLanguage(language, data, encoding = "utf-8") { // Verify input. language = this._sanitizeLanguage(language); this._verifyData(data); return new Promise((resolve, reject) => { // Decode data from various forms. let decodePromise; if (data instanceof File || data instanceof Blob) { decodePromise = new Promise((fileResolve, fileReject) => { let freader = new FileReader(); freader.onload(() => { fileResolve(JSON.parse(freader.result)); }); freader.onabort(ev => { fileReject(ev); }); freader.onerror(ev => { fileReject(ev); }); freader.readAsText(data, encoding); }); } else if (typeof data == "string") { decodePromise = new Promise((parseResolve, parseReject) => { parseReject; parseResolve(JSON.parse(data)); }); } else if (typeof data == "object") { decodePromise = new Promise((passResolve, passReject) => { passReject; passResolve(data); }); } else { reject("invalid data"); } // Load Data decodePromise.then( result => { let language_map = new Map(); for (let key in result) { language_map.set(key, result[key]); } this.languages.set(language, language_map); this.dirtyTs = performance.now(); // Event: onchange this._callEvent("change"); resolve(language); }, reason => { reject(reason); } ); }); } /** Save a language. * * @param {string} language Name of the language. * @returns {Promise} Promise that eventually returns the JSON data of the language. * @throws Exception on invalid parameters and missing language. */ saveLanguage(language) { language = this._sanitizeLanguage(language); this._verifyLanguageKnown(language); return new Promise((resolve, reject) => { reject; this._verifyLanguageKnown(language); let language_data = {}; let language_map = this.languages.get(language); language_map.forEach((value, key, map) => { map; language_data[key] = value; }); let json_data = JSON.stringify(language_data); resolve(json_data); }); } /** Destroy/unload a language. * * @param {string} language Name of the language. * @throws Exception on invalid parameters and missing language. */ destroyLanguage(language) { language = this._sanitizeLanguage(language); this._verifyLanguageKnown(language); this.languages.delete(language); this.dirtyTs = performance.now(); // Event: onchange this._callEvent("change"); } /** Clear a key from a language. * * @param {string} language Language to edit. * @param {string} key Key to clear. * @return {bool} true on success. * @throws Exception on invalid parameters and missing language. */ clearKey(language, key) { // Verify and sanitize input. language = this._sanitizeLanguage(language); this._verifyKey(key); // Check if language exists. this._verifyLanguageKnown(language); // Delete key if exists. let language_map = this.languages.get(language); if (!language_map.has(key)) { return false; } language_map.delete(key); // If the key was the base language key, set dirty timestamp. if (key == this.baseLanguageKey) { this.dirtyTs = performance.now(); } // Event: onchange this._callEvent("change"); return true; } /** Set a key in a language. * * @param {string} language Language to edit. * @param {string} key Key to set. * @param {*} value New value to set. * @param {bool} force Force the update if the key exists. (Default = true) * @return {bool} true on success. * @throws Exception on invalid parameters and missing language. */ setKey(language, key, value, force = true) { // Verify and sanitize input. language = this._sanitizeLanguage(language); this._verifyKey(key); // Check if language exists. this._verifyLanguageKnown(language); // Set key. let language_map = this.languages.get(language); if (language_map.has(key) && !force) { return false; } language_map.set(key, value); // If the key was the base language key, set dirty timestamp. if (key == this.baseLanguageKey) { this.dirtyTs = performance.now(); } // Event: onchange this._callEvent("change"); return true; } /** Get a key in a language. * * @param {string} language * @param {string} key * @return {*} the value * @throws Exception on invalid parameters, missing language and missing key. */ getKey(language, key) { // Verify and sanitize input. language = this._sanitizeLanguage(language); this._verifyKeyKnown(language, key); // Get Key let language_map = this.languages.get(language); return language_map.get(key); } /** Hook into an event. * * @param {string} event Event to hook into. * @param {function} callback Callback to call. * @return {string} Id of the event (for unhooking). */ hook(event, callback) { if (typeof event != "string") { throw "event must be a string"; } event = event.toLowerCase(); if (typeof callback != "function") { throw "callback must be a function"; } if (this.events[event] == undefined) { throw "event is unknown"; } let uid = this._uuid(); this.events[event].set(uid, callback); return uid; } unhook(event, callbackid) { if (typeof event != "string") { throw "event must be a string"; } event = event.toLowerCase(); if (typeof event != "number") { throw "callbackid must be a number"; } if (this.events[event] == undefined) { throw "event is unknown"; } if (!this.events[event].has(callbackid)) { return false; } this.events[event].remove(callbackid); return true; } /** Translate a single string to any loaded language. * * @param {string} key String to translate * @param {string} language Language to translate to * @return {string} Translated string, or if failed the string plus the language appended. * @throws Exception on invalid parameters. */ translate(key, language) { // Verify and sanitize input. language = this._sanitizeLanguage(language); this._verifyKey(key); // Translate using the translation chain. let chain = this._cacheChain(language); let translated = key; for (let language of chain) { let languageMap = this.languages.get(language); if (languageMap.has(key)) { translated = languageMap.get(key); break; } else { // Event: onMissingKey this._callEvent("missingKey", key, language); } } return translated; } /** Automatically translate the entire page using the specified property on elements. * * @param {string} language Language to translate to * @param {string} property Property to search for (default 'data-i18n') * @param {function} resolver Function to call to find the proper translation, called with parameters ({string}language, {string}key, {Node}element) and must return a string. * @param {function} applier Function to call to apply the proper translation, called with parameters ({string}language, {string}key, {string}translation, {Node}element) and must return a boolean. * @returns {Promise} resolved when successful, rejected if applier returns false. * @throws Exception on invalid parameters. */ domTranslate( language, property = "data-i18n", resolver = undefined, applier = undefined ) { language = this._sanitizeLanguage(language); if (resolver != undefined && typeof resolver != "function") { throw "resolver must be a function"; } else if (resolver == undefined) { let self = this; resolver = (language, key, el) => { return self._defaultResolver(language, key, el); }; } if (applier != undefined && typeof applier != "function") { throw "applier must be a function"; } else if (applier == undefined) { let self = this; applier = (language, key, translation, el) => { return self._defaultApplier(language, key, translation, el); }; } return new Promise((resolve, reject) => { let els = document.querySelectorAll(`[${property}]`); for (let el of els) { let key = el.getAttribute(property); if (!applier(language, key, resolver(language, key, el), el)) { reject(); return; } } resolve(); }); } // Private Functions _verifyLanguageKnown(language) { if (!this.languages.has(language)) { throw "language unknown"; } } _verifyKey(key) { if (typeof key == "string") { return; } throw "key must be of type string"; } _verifyKeyKnown(language, key) { this._verifyLanguageKnown(language); this._verifyKey(key); if (!this.languages.get(language).has(key)) { throw "key unknown in language"; } } _verifyData(data) { if (typeof data == "string") { return; } if (typeof data == "object") { return; } if (data instanceof File) { return; } if (data instanceof Blob) { return; } throw "data must be of type string, object, File or Blob"; } _sanitizeLanguage(language) { try { this._verifyKey(language); } catch (e) { throw "language must be of type string"; } return language.toLowerCase(); } _defaultResolver(language, key, element) { element; return this.translate(key, language); } _defaultApplier(language, key, translation, element) { try { element.textContent = translation; return true; } catch (e) { return false; } } /** Caches the necessary language chain for translation. * * Creates and returns a language chain required for translation, avoiding * recursive loops that never end in the process. The chain will not * evalute the entire branch first, instead it will check all branches * and then list the childs of those branches. This is an expensive * operation and should only be done once on every language update. * * Example: * de-DE +- en-GB - en-US - de-DE (- en-GB, en-US, ... [recursive]) * \- en-US - de-DE (- en-GB, en-US, ... [recursive]) * Result: [de-DE, en-GB, en-US] * Explanation: de-DE depends on both en-GB and en-US, and will check both * before considering the next branch. Since all dependencies are resolved * early, a recursive lookup is prevented here. * * Example: * de-BE +- de-DE - en-GB - en-US * +- en-GB - en-US * +- de-AU - de-DE - en-GB - en-US * +- en-US * Result: [de-Be, de-DE, en-GB, de-AU, en-US] * Explanation: de-BE depends on [de-DE, en-GB, de-AU, en-US], resolving * de-DE returns en-GB (if loaded), which we already have. en-GB resolves * to en-US, which we also already have. de-AU resolves to de-DE, also * known. And finally en-US resolves to nothing as the global base language. * * @param {string} language * @returns {array} Translation chain */ _cacheChain(language) { // This caches a chain so that we do not have to rebuild this every // lookup. It is important that there are no recursive loops in this // code, which means we can't rely on this function to work until the // cache is completed. // Have there been changes to the timestamp? if (this.chainsTs < this.dirtyTs) { // If yes, clear all chains for rebuilding. this.chainsTs = this.dirtyTs; this.chains.clear(); } // Do we have a chain cached? if (this.chains.has(language)) { // Yes, return the cached chain and go back to translation. return this.chains.get(language); } // Create a new chain without relying on our own function. let chain = new Array(); let missing = new Array(); chain.push(language); // Chains always contain the language itself. // Now we walk through the chain manually, modifying it as we go. for (let pos = 0; pos < chain.length; pos++) { // Check if the language is loaded, if not skip it. if (!this.languages.has(chain[pos])) { missing.push(chain[pos]); continue; } let languageMap = this.languages.get(chain[pos]); // Check if there is a base language override. if (!languageMap.has(this.baseLanguageKey)) { continue; } let baseLanguages = languageMap.get(this.baseLanguageKey); // Convert to array for for...in. if (typeof baseLanguages == "string") { baseLanguages = [baseLanguages]; } else if (!(baseLanguages instanceof Array)) { continue; } for (let base of baseLanguages) { base = this._sanitizeLanguage(base); if (!chain.includes(base) && this.languages.has(base)) { chain.push(base); } else if (!missing.includes(base) && !this.languages.has(base)) { missing.push(base); } } // Append the global base languages if there are no other languages left. if (pos == chain.length - 1) { let baseLanguages = this.baseLanguage; if (typeof this.baseLanguage == "string") { baseLanguages = [this.baseLanguage]; } for (let base of baseLanguages) { if (!chain.includes(base) && this.languages.has(base)) { chain.push(base); } else if (!missing.includes(base) && !this.languages.has(base)) { missing.push(base); } } } } // Trigger event for all missing languages for (let missingLanguage of missing) { // Event: onMissingLanguage this._callEvent("missingLanguage", missingLanguage); } // Store. this.chains.set(language, chain); // Return. return chain; } /** Generate a UUID compliant string * * Source: https://stackoverflow.com/a/21963136 */ _uuid() { const lut = []; for (var i = 0; i < 256; i++) { lut[i] = (i < 16 ? "0" : "") + i.toString(16); } var d0 = (Math.random() * 0xffffffff) | 0; var d1 = (Math.random() * 0xffffffff) | 0; var d2 = (Math.random() * 0xffffffff) | 0; var d3 = (Math.random() * 0xffffffff) | 0; return ( lut[d0 & 0xff] + lut[(d0 >> 8) & 0xff] + lut[(d0 >> 16) & 0xff] + lut[(d0 >> 24) & 0xff] + "-" + lut[d1 & 0xff] + lut[(d1 >> 8) & 0xff] + "-" + lut[((d1 >> 16) & 0x0f) | 0x40] + lut[(d1 >> 24) & 0xff] + "-" + lut[(d2 & 0x3f) | 0x80] + lut[(d2 >> 8) & 0xff] + "-" + lut[(d2 >> 16) & 0xff] + lut[(d2 >> 24) & 0xff] + lut[d3 & 0xff] + lut[(d3 >> 8) & 0xff] + lut[(d3 >> 16) & 0xff] + lut[(d3 >> 24) & 0xff] ); } _callEvent(name) { if (typeof name != "string") { throw "name must be a string"; } name = name.toLowerCase(); if (this.events[name] == undefined) { throw "invalid event call"; } if (this.events[name].size == 0) { return; } let args = Array.prototype.slice.call(arguments, 1); this.events[name].forEach((value, key, map) => { key; map; if (typeof value != "function") { return; } try { value.apply(null, args); } catch (e) { e; } }); } }
JavaScript
class Footer extends Component { shouldComponentUpdate() { return false; } render() { return ( <div className="footer"> <div className="copyright"> © Copyright 2017 | Mohamed K. Eid </div> </div> ); } }
JavaScript
class BodyWrapper extends Component { componentDidMount = () => { this.props.updateData("SET_ACTIVE_ITEM", { key: "activeFormDetails", item: null }); this.props.updateData("SET_ACTIVE_ITEM", { key: "isSimpliBuilderActive", item: false }); }; /* when draggin elements from side bar to work place */ handleElementMoveAcrossColumns = (source, destination) => { /* add elements to droppable if it does not need a popup */ const popUpElements = [ "shortText", "dropList", "radioChoice", "checkBox", "image", "uploadFile", "grid", "uploadSvg", "block", "textBlock" ]; let sourceColumn; if ( this.props.currentActivePage === "formContainer" || source.droppableId === "paper" ) { sourceColumn = this.props.sideBarAllButtons[this.props.sideBarTitle][ this.props.sideBarBlock ]; } else { if (!this.props.isRightDroppableActive) { sourceColumn = this.props.sideBarAllButtons[this.props.sideBarTitle][ this.props.sideBarBlock ]; } else { sourceColumn = this.props.droppables[source.droppableId]; } } // const sourceColumn = this.props.sideBarAllButtons[this.props.sideBarTitle][ // this.props.sideBarBlock // ]; const destinationColumn = this.props.droppables[destination.droppableId]; const newElementId = generateRandromString(); let element = sourceColumn[source.index]; /* set id for each new dropped element */ element = { ...element, id: element.type + newElementId }; const newButton = { ...element, value: element.title }; sourceColumn.splice(source.index, 1, newButton); destinationColumn.splice(destination.index, 0, element); if ( this.props.currentActivePage === "paperContainer" && source.droppableId === "formWorkplaceElements" ) { this.props.updateData("SET_POPUP_ACTIVE_ELEMENT", { droppableId: destination.droppableId, column: destinationColumn, id: "block" + newElementId, type: "block" }); this.props.updateData(`show_block`.toUpperCase(), true); return; } // console.log(); /* which popup currently is active */ this.props.updateData("SET_POPUP_ACTIVE_ELEMENT", { droppableId: destination.droppableId, column: destinationColumn, id: element.type + newElementId, type: element.type }); /* show corresponding pop up (if any)*/ this.props.updateData(`show_${element.type}`.toUpperCase(), true); if (popUpElements.indexOf(element.type) === -1) { /* initiat new form details */ this.props.updateData("SET_FORM_DETAILS", { key: element.id, details: [element], type: "activeDetails" }); /* add this new element (short text,textblock,....) to corresponding droppable (heading ,askAnswer , .....) */ this.props.updateData("ADD_ELEMENT_TO_DROPPABLE", { key: destination.droppableId, column: destinationColumn }); } }; /* when dragging elements across the same workplace container */ handleElementMoveAtTheSameColumn = (source, destination) => { let arr; const { droppables } = this.props; const array = droppables[source.droppableId]; const result = [...array]; result.splice(source.index, 1); const element = array[source.index]; arr = [ ...result.slice(0, destination.index), element, ...result.slice(destination.index) ]; this.props.updateData("ADD_ELEMENT_TO_DROPPABLE", { key: source.droppableId, column: arr }); }; /* when dragging elements between 2 different workplace containers */ handleElementMoveAcrossWokplaceContainers = (source, destination) => { const { droppables } = this.props; const sourceColumn = droppables[source.droppableId]; const destinationColumn = droppables[destination.droppableId]; const element = sourceColumn[source.index]; sourceColumn.splice(source.index, 1); destinationColumn.splice(destination.index, 0, element); const newData = { sourceKey: source.droppableId, destinationKey: destination.droppableId, sourceColumn, destinationColumn }; this.props.updateData("MOVE_ELEMENT_ACROSS_WORKPLACE_CONTAINERS", newData); }; /* when user drop the element */ handleDragEnd = result => { const sideBarDroppables = [ "form", "paper", "pop-up", "filter", "formWorkplaceElements", "rightDroppable" ]; const { source, destination } = result; /* if the user dropped the element in a none droppabpe place */ if (!destination) { return; } if (destination.droppableId !== source.droppableId) { // if user drags element that represent a container to a container if ( source.droppableId === "paperWorkplaceElements" && destination.droppableId.startsWith("block") ) { return; } if (sideBarDroppables.indexOf(source.droppableId) !== -1) { /* dragging element from side-bar to workeplace */ this.handleElementMoveAcrossColumns(source, destination); return; } /* dragging element across 2 different workplace containers */ this.handleElementMoveAcrossWokplaceContainers(source, destination); return; } /* dragging element across the same workplace container */ this.handleElementMoveAtTheSameColumn(source, destination); }; /* when user clicks the open button */ handleOpen = () => { this.props.updateData("SHOW_SELECT_SCREEN", true); }; /* when user clicks the new button */ handleNew = () => { const { currentActivePage } = this.props; this.setState({ showStarterScreen: false }); this.props.updateData("SHOW_BUTTONS", true); this.props.updateData("TOGGLE_STARTER_SCREEN", false); /* what side bar buttons should appear */ this.props.updateData("SIDEBAR_BLOCK", "form"); /* active buttons in toolbar*/ this.props.updateData("UPDATE_SELECTED", ["btn-Form_Nav"]); /* change dropdown menu */ this.props.updateData("SET_ACTIVE_ITEM", { key: "isSimpliBuilderActive", item: true }); this.props.updateData("SET_DROPABLES", {}); !currentActivePage && this.props.updateData( "PAGE", "btn-Form_Nav" ); /* display workplace page */ this.props.updateData("SET_ACTIVE_ITEM", { key: "selectedForm", item: { title: "", category: null, img: null, data: {}, is_private: false, isNew: true, originalTitle: "", default_lang: null } }); this.props.updateData("SHOW_SELECTE_LANG", true); }; /* create new form */ addNewForm = payload => { const { selectedForm, language, activeTreeNode, userOpensExistingForm, forms } = this.props; /* to which simpliadmin tag should be added */ const key = activeTreeNode.slug === "root" ? "master" : `form_${activeTreeNode.id}`; request("forms/", payload) .then(resp => { const messageTitle = messages[language]["successSaved"]["title"]; const messageText = messages[language]["successSaved"]["text"]; const updatedSelectedForm = { ...selectedForm, isNew: false, originalTitle: selectedForm.title, id: resp.data.id, slug: resp.data.slug, category: { id: resp.data.category }, default_lang: { id: resp.data.default_lang }, is_empty: payload.is_empty, date: resp.data.date }; /* show success message */ this.props.updateData("SET_MESSAGE_DATA", { title: messageTitle, text: messageText, showMessage: true }); this.props.updateData("SET_ACTIVE_ITEM", { key: "selectedForm", item: updatedSelectedForm }); /* if user clikced on open button in simpliBuilder */ /* after saving data show him select form screen */ if (userOpensExistingForm) { this.props.updateData("SHOW_SELECT_SCREEN", true); this.props.updateData("SET_OPEN_EXISTING_FORM", false); } /*empty newWords (words needs to be saved)*/ this.props.updateData("RESET_NEW_WORDS"); /* whether to add this new form to simplisend */ if (forms[key]) { const key = activeTreeNode.slug === "root" ? "master" : `form_${activeTreeNode.id}`; this.props.updateData("ADD_FORM", { key, form: { ...updatedSelectedForm, category: { id: resp.data.category }, default_lang: { id: resp.data.default_lang }, type: payload.type, isCreated: true, is_empty: payload.is_empty } }); } }) .catch(e => { const key = e.message === "Request failed with status code 400" ? "formDuplicateTitle" : "error"; const messageTitle = messages[language][key]["title"]; const messageText = messages[language][key]["text"]; this.props.updateData("SET_MESSAGE_DATA", { title: messageTitle, text: messageText, showMessage: true }); }); return; }; /* update an existing form */ updateForm = payload => { const { selectedForm, language, userOpensExistingForm, formDetails, langsTable } = this.props; /* if user opend an old form */ request(`forms/${selectedForm.slug}/`, payload, "put") .then(resp => { const messageTitle = messages[language]["successSaved"]["title"]; const messageText = messages[language]["successSaved"]["text"]; this.props.updateData("SET_MESSAGE_DATA", { title: messageTitle, text: messageText, showMessage: true }); /*empty newWords (words need to be saved)*/ this.props.updateData("RESET_NEW_WORDS"); /* empty form words in simpliadmin to get all new words */ this.props.updateData("SET_LANG_WORDS", { key: selectedForm.id, words: null }); /* if form was empty and user opened it and added data to it*/ if (!payload.is_empty && selectedForm.is_empty) { const k = selectedForm.category.id === 1 ? "all" : selectedForm.category.id; this.props.updateData("SET_FORMS", { key: "all", forms: null }); this.props.updateData("SET_FORMS", { key: k, forms: null }); } /* add new changes to form */ if (formDetails[selectedForm.id]) { this.props.updateData("SET_FORM_DETAILS", { key: selectedForm.id, details: null, type: "details" }); } if (langsTable[selectedForm.id]) { this.props.updateData("SET_LANG_WORDS", { key: selectedForm.id, words: null }); } /* if user clikced on open button in simpliBuilder */ /* after saving data show him select form screen */ if (userOpensExistingForm) { this.props.updateData("SHOW_SELECT_SCREEN", true); this.props.updateData("SET_OPEN_EXISTING_FORM", false); } }) .catch(e => { const key = e.message === "Request failed with status code 400" ? "formDuplicateTitle" : "error"; const messageTitle = messages[language][key]["title"]; const messageText = messages[language][key]["text"]; this.props.updateData("SET_MESSAGE_DATA", { title: messageTitle, text: messageText, showMessage: true }); }); }; // //get input ids for shortText // getShortTextInputId = data => { // const ids = data.slice(1).map(item => { // return { content: item.inputId, id: data[0]["id"] }; // }); // return ids; // }; // //get input ids for dropList // getDropdownInputId = data => { // const ids = data.slice(1).map(item => { // return { content: item.inputId, id: data[0]["elementId"] }; // }); // return ids; // }; // //get input id for radioChoice, checkbox // getRadioCheckInputId = data => { // return [{ content: data[0]["inputId"], id: data[0]["id"] }]; // }; // // get input ids for upload file // getFileInputId = data => { // return [{ content: data["inputId"], id: data["elementId"] }]; // }; // // get all input ids to save them in inputIds tabel // getInputId = data => { // const { droppables, formDetails, activeDetails } = this.props; // const ids = []; // const MAP_TYPE_TO_METHOD = { // shortText: this.getShortTextInputId, // dropList: this.getDropdownInputId, // radioChoice: this.getRadioCheckInputId, // checkBox: this.getRadioCheckInputId, // uploadFile: this.getFileInputId // }; // Object.keys(droppables).map(k => { // if (k !== "formWorkplaceElements" && droppables[k].length > 0) { // const item = droppables[k][0]; // const action = MAP_TYPE_TO_METHOD[item.type]; // action && ids.push(...action(activeDetails[item.id])); // } // }); // return ids; // }; /* warpas whole save form login (create or update) */ saveForm = () => { const { selectedForm, droppables, activeTreeNode, activeDetails, activeFormsListTag, newWords } = this.props; // form name should be translatable const key = `${selectedForm.title}_${selectedForm.default_lang.label}`; let words; //const ids = this.getInputId(); //console.log(ids); /* if user opend new form */ if (selectedForm && activeTreeNode) { if ( selectedForm.isNew || selectedForm.originalTitle !== selectedForm.title ) { // form name should be translatable words = { ...newWords, [key]: { translation_id: null, content: selectedForm.title, language: selectedForm.default_lang.id } }; } else { words = { ...newWords }; } const texts = Object.keys(words).map(key => words[key]); console.log(words); console.log(texts); const category = selectedForm.isNew ? activeTreeNode.id : selectedForm.category.id; const payload = { ...selectedForm, default_lang: selectedForm.default_lang.id, category: category, //inputIds: ids, type: selectedForm.isNew ? activeTreeNode.slug === "root" ? "form" : activeFormsListTag : selectedForm.type, data: JSON.stringify({ elements: droppables, details: activeDetails }), texts, is_empty: droppables && activeDetails && Object.keys(droppables).length > 0 && Object.keys(activeDetails).length ? false : true }; /* if user creating new form */ if (selectedForm.isNew) { this.addNewForm(payload); return; } this.updateForm(payload); this.props.updateData("REMOVE_FORM_TEMP_DATA", selectedForm.id); } }; changeFormTitle = e => { const { selectedForm } = this.props; const updatedSelectedForm = { ...selectedForm, title: e.target.value }; this.props.updateData("SET_SELECTED_FORM", updatedSelectedForm); }; /* select tree item in which user wants to save the form */ selectFile = () => { const { activeTreeNode, selectedForm, isSaveAsClicked } = this.props; if (!selectedForm.title) { this.props.updateData("SHOW_ERROR", { key: "showFormNamelessError", value: true }); return; } if (activeTreeNode) { isSaveAsClicked && this.props.updateData("SET_ACTIVE_ITEM", { key: "selectedForm", item: { ...selectedForm, isNew: true } }); this.props.updateData("SHOW_SELECT_FILE", false); this.props.updateData("SHOW_ERROR", { key: "showFormNamelessError", value: false }); this.saveForm(); } }; /* when user confirms he wants to open new form */ openNewForm = () => { const { selectedForm, currentActivePage } = this.props; if (selectedForm) { this.props.updateData("SET_ACTIVE_ITEM", { key: "selectedForm", item: { title: "", category: null, img: null, data: {}, is_private: false, isNew: true /* saveForm method will decide wether to save new form or update existing one based on this */, /* if user change the name of an existing form show him a message whether he wants to save it to new form or just change current form title */ originalTitle: "" } }); /* set acttive workplace page if it is null or if it does not equal formContainer*/ if ( !currentActivePage || (currentActivePage && currentActivePage !== "formContainer") ) { this.props.updateData("RESET_PAGES"); } /* set sidebar buttons */ this.props.updateData("SIDEBAR_BLOCK", "form"); /*set title for side bar */ this.props.updateData("SIDEBAR_TITLE", "container"); /* set header active button */ this.props.updateData("UPDATE_SELECTED", ["btn-Form_Nav"]); /* empty all elements */ this.props.updateData("SET_DROPABLES", {}); /* show languages dropdown to choose from */ this.props.updateData("SHOW_SELECTE_LANG", true); this.props.updateData("SET_ACTIVE_ITEM", { key: "isNewFormButtonClicked", item: false }); } }; /* hide the tree when user clicks on cancel button */ hideSelectFile = () => { const { selectedForm } = this.props; this.props.updateData("SET_ACTIVE_TREE_NODE", null); this.props.updateData("SHOW_SELECT_FILE", false); this.props.updateData("SET_ACTIVE_ITEM", { key: "isSaveAsClicked", item: false }); this.props.updateData("SHOW_ERROR", { key: "showFormNamelessError", value: false }); selectedForm.id && this.props.updateData("SET_ACTIVE_ITEM", { key: "selectedForm", item: { ...selectedForm, isNew: false } }); }; SaveAs = () => { const { selectedForm } = this.props; if (selectedForm && selectedForm.title) { this.props.updateData("SHOW_SAVE_AS_NAME_INPUT", false); this.props.updateData("SHOW_SELECT_FILE", true); this.props.updateData("SET_ACTIVE_ITEM", { key: "selectedForm", item: { ...selectedForm, isNew: true } }); } }; /* when user clicks on discard chages button when a message appears */ discardChanges = () => { const { isSimpliBuilderActive, isSimpliBuilderNavButtonClicked, userOpensExistingForm, activeNavLink } = this.props; if ( (!isSimpliBuilderActive && !isSimpliBuilderNavButtonClicked) || (isSimpliBuilderActive && !isSimpliBuilderNavButtonClicked) ) { this.props.updateData("SHOW_ERROR", { key: "showFormSaveWarning", value: false }); if (userOpensExistingForm) { this.props.updateData("SHOW_SELECT_SCREEN", true); this.props.updateData("SET_OPEN_EXISTING_FORM", false); } else { this.openNewForm(); } return; } if (isSimpliBuilderActive && !isSimpliBuilderNavButtonClicked) { } activeNavLink && this.props.history.push(activeNavLink); this.props.activeNavLink && this.props.updateData("UPDATE_FORM_TOOL_BAR_ACTIVE", "btn-Select"); this.props.updateData("SHOW_ERROR", { key: "showFormSaveWarning", value: false }); }; render = () => { const { showSelectFile, selectedForm, language, showRenameFormWarning, showMessage, messageText, messageTitle, showFormSaveWarning, isNewFormButtonClicked, currentActivePage } = this.props; return ( <DragDropContext onDragEnd={this.handleDragEnd}> <div id="bodyContainer"> {/* tool bar */} <ToolBar /> {/* workplace */} <div id="workPlace"> <div id="wPtagGroup"> <WorkPlaceContainer /> </div> </div> {/* left side bar */} <div id="left" className="sb_sideBarContainer"> <SideBar /> </div> {/*right side bar */} <div id="right" className="sb_sideBarContainer"> <ElementsTree droppableName={"formWorkplaceElements"} disabled={currentActivePage !== "formContainer"} /> </div> </div> {this.props.showStarterScreen && ( <StarterScreen handleOpen={this.handleOpen} handleNew={this.handleNew} /> )} <SelectForm /> <div className="sb-main-popup-wrapper"> <PopUp show={showSelectFile}> <div className="popup-header"> <Translator string="selectFormHeading" /> </div> <SelectFile /> <div className="pop-up-bottons-wrapper"> <button className="pop-up-button" onClick={this.selectFile}> <Translator string="select" /> </button> <button className="pop-up-button" onClick={this.hideSelectFile}> <Translator string="cancel" /> </button> </div> </PopUp> </div> <div className="sb-main-popup-wrapper"> <PopUp show={showRenameFormWarning}> <div className="popup-header"> {messages[language]["changeFormName"]["title"]} </div> <div className="popup-body"> <div className="massage"> {messages[language]["changeFormName"]["text"]} </div> </div> <div className="pop-up-bottons-wrapper"> <button className="pop-up-button" onClick={() => { this.props.updateData("SHOW_RENAME_FORM_WARNING", false); this.saveForm(); }} > <Translator string="rename" /> </button> <button className="pop-up-button" onClick={() => { this.props.updateData("SET_ACTIVE_ITEM", { key: "selectedForm", item: { ...selectedForm, isNew: true } }); this.props.updateData("SHOW_RENAME_FORM_WARNING", false); this.props.updateData("SHOW_SELECT_FILE", true); }} > <Translator string="newSave" /> </button> <button className="pop-up-button" onClick={() => { this.props.updateData("SHOW_RENAME_FORM_WARNING", false); }} > <Translator string="cancel" /> </button> </div> </PopUp> </div> <SelectLanguage /> <div className="sb-main-popup-wrapper"> <PopUp show={showMessage}> <div className="popup-header">{messageTitle}</div> <div className="popup-body"> <div className="massage">{messageText}</div> </div> <div className="pop-up-bottons-wrapper"> <button className="pop-up-button" onClick={() => { this.props.updateData("SET_MESSAGE_DATA", { title: "", text: "", showMessage: false }); this.props.isSimpliBuilderNavButtonClicked && this.props.history.push(this.props.activeNavLink); isNewFormButtonClicked && this.openNewForm(); this.props.activeNavLink && this.props.updateData( "UPDATE_FORM_TOOL_BAR_ACTIVE", "btn-Select" ); }} > <Translator string="ok" /> </button> </div> </PopUp> </div> <div className="sb-main-popup-wrapper"> <PopUp show={showFormSaveWarning}> <div className="popup-header">{messageTitle}</div> <div className="popup-body"> <div className="massage">{messageText}</div> </div> <div className="pop-up-bottons-wrapper"> <button className="pop-up-button" onClick={() => { this.props.updateData("SHOW_ERROR", { key: "showFormSaveWarning", value: false }); if (selectedForm.isNew) { this.props.updateData("SHOW_SELECT_FILE", true); } else { this.saveForm(); } }} > <Translator string="save" /> </button> <button className="pop-up-button" onClick={this.discardChanges}> <Translator string="discardChanges" /> </button> <button className="pop-up-button" onClick={() => { this.props.updateData("SHOW_ERROR", { key: "showFormSaveWarning", value: false }); this.props.updateData("SET_OPEN_EXISTING_FORM", false); this.props.updateData("SET_ACTIVE_ITEM", { key: "activeNavLink", item: null }); this.props.updateData("SET_ACTIVE_ITEM", { key: "isSimpliBuilderNavButtonClicked", item: false }); this.props.updateData("SET_ACTIVE_ITEM", { key: "isNewFormButtonClicked", item: false }); }} > <Translator string="cancel" /> </button> </div> </PopUp> </div> </DragDropContext> ); }; }
JavaScript
class FileStorage { /** * Creates an instance of FileStorage * @param {string|PouchDB} [database] - The name of the database to use or a PouchDB instance * @param {object} [pouchdbOptions] - PouchDb database creation options */ constructor(database, pouchdbOptions = {}) { this.db = getPouchDatabase(database, pouchdbOptions) const initializedDocument = getInitializedFlagDocument(this.db) if (!initializedDocument || !initializedDocument.initialized) { initializeDatabase(this.db) } } generateFileId(file) { return file.path } /** * Cleans the whole filesystem in database * @returns {boolean} True if does it sucesfully */ async format() { let allDocs = await this.db.allDocs({ include_docs: true, startkey: DOCUMENT_ID_PREFIX, endkey: DOCUMENT_ID_PREFIX + '\uffff' }) .catch((err) => { if (err.name !== 'not_found') { throw unknowError(err) } }) allDocs = allDocs.rows.map(row => { return { _id: row.id, _rev: row.doc._rev, _deleted: true } }) await this.db.bulkDocs(allDocs) .catch((err) => { if (err.name !== 'not_found') { throw unknowError(err) } }) return true } /** * Adds a file to the filesystem * @param file File that contains the data and the metadata * @param {object} [options] - Options * @param {object} [options.overwrite] - Overwrites any existing previous file * @return {string} File path */ async addFile(file, options = { overwrite: false }) { const pathElements = file.getPathElements() if (pathElements.length === 0) { throw new InvalidPathError(`Invalid file path ${file.path}`) } const fileId = this.generateFileId(file) const documentId = DOCUMENT_ID_PREFIX + fileId // Verify that father directory exists await verifyFatherDirectoryExists(this.db, pathElements, true) const document = new DbDocument(documentId, pathElements, file.label, file instanceof Directory, file.lastModified, file.blob, file.type) // Check file duplication const originalDoc = await this.db.get(documentId) .catch((err) => { if (err.name !== 'not_found') { throw unknowError(err) } }) if (originalDoc !== undefined) { if (!options.overwrite) { throw new FileWithSamePath(`File with the same path exists. Use options.overwrite = true to replace it. Path: ${file.path}`) } else { document._rev = originalDoc._rev } } await this.db.put(document) .catch((err) => { throw unknowError(err) }) return fileId } /** * Generates a directory * * A directory consists on a special file with empty data * @param {string} path - Path of the directory * @param {object} [options - Options * @param {object} [options.parent] - Makes father directories. If father directories exists, don't fail * @return {string} Directory path */ async mkDir(path, options = { parents: false }) { const directory = new Directory(path) if (options.parents) { const pathElements = directory.getPathElements().map((val, index, arr) => { if (index === 0) { return val } return arr.slice(0, index + 1).join(PATH_SEPARATOR) }) for (const element of pathElements) { await this.addFile(new Directory(element)) .catch(err => { if (!(err instanceof FileWithSamePath)) { throw err } }) } return directory.path } return this.addFile(directory) } /** * Deletes a directory * @param {string} path - Path of the directory * @param {object} [options] - Options * @param {object} [options.recursive] - Delete all content of the directory on a recursive way * @returns {boolean} True if deletes sucesfully one or more directories or files. False if not deleted anything */ async rmDir(path, options = { recursive: false }) { path = normalizePath(path) const docId = DOCUMENT_ID_PREFIX + path const doc = await this.db.get(docId, { attachments: false }) .catch(err => { if (err.name !== 'not_found') { throw unknowError(err) } return false }) if (!doc) { return false } if (!doc.isDirectory) { return false } // Check if it have childrens and implement the logic of options.recursive const childrens = await this.listAllFilesOnAPath(path, { onlyPaths: true }) if (childrens.length > 0 && !options.recursive) { return false } else if (options.recursive) { await Promise.all(childrens.map(children => { this.rmDir(children, options) })) } return this.db.remove(doc._id, doc._rev) .catch(err => { throw unknowError(err) }) .then(result => { return result.ok }) } /** * Return a file using his path * @param {string} path Path to the file * @return {File} A instance of File if the path points to a valid file or directory */ async getFile(path) { path = normalizePath(path) const docId = DOCUMENT_ID_PREFIX + path const doc = await this.db.get(docId, { attachments: true, binary: true }) .catch(err => { if (err.name === 'not_found') { throw new FileNotFoundError(`File with path ${path} not found.`) } else { throw unknowError(err) } }) return dbDocumentToFileAdapter(doc) } /** * Return all the files stored * @param {object} options * @param {object} [options.onlyPaths] - Only retrives the paths * @return {array} A sorted array of File or a sorted array of strings with the paths if onlyPaths is true */ async listAllFiles(options = { onlyPaths: false }) { const allDocs = await this.db.query('path', { include_docs: true, attachments: !options.onlyPaths, binary: !options.onlyPaths }) .catch(err => { throw unknowError(err) }) if (options.onlyPaths) { return allDocs.rows.map(row => dbDocumentToFileAdapter(row.doc).path) } else { return allDocs.rows.map(row => dbDocumentToFileAdapter(row.doc)) } } /** * Return all the files stored on a subdir * @param {object} options * @param {object} [options.onlyPaths] - Only retrives the paths * @return {array} A sorted array of File or a sorted array of strings with the paths if onlyPaths is true */ async listAllFilesOnAPath(path, options = { onlyPaths: false }) { path = normalizePath(path) const level = (path.match(new RegExp(PATH_SEPARATOR, 'g')) || []).length const allFiles = await this.listAllFiles(options) if (options.onlyPaths) { let files = allFiles.filter(file => file.startsWith(path)) files = files.filter(file => { const fileLevel = (file.match(new RegExp(PATH_SEPARATOR, 'g')) || []).length return (level + 1) === fileLevel }) return files } else { let files = allFiles.filter(file => file.path.startsWith(path)) files = files.filter(file => { const pathLevel = (file.path.match(new RegExp(PATH_SEPARATOR, 'g')) || []).length return (level + 1) === pathLevel }) return files } } /** * Search a file by his id and deleted it * @param fileid - Id of the file to be deleted * @return {boolean} True if the file exists and is been deleted. False if the file doesn't exists */ async delete(filePath) { const docId = DOCUMENT_ID_PREFIX + normalizePath(filePath) const doc = await this.db.get(docId, { attachments: false }) .catch(err => { if (err.name !== 'not_found') { throw unknowError(err) } return false }) if (!doc) { return false } if (doc.isDirectory) { return false } return this.db.remove(doc._id, doc._rev) .catch(err => { throw unknowError(err) }) .then(result => { return result.ok }) } /** * Unwraps the PouchDb instance */ unwrap() { return this.db } /** * Checks if a PouchDb database has been initialized as a FileStorage */ static async isInitialized(database) { const initializedDocument = await getInitializedFlagDocument(database) return initializedDocument && initializedDocument.initialized } }
JavaScript
class AlbumListItem extends Component { constructor(props) { super(props); this.renderArtist = this.renderArtist.bind(this); } renderArtist() { return ( <span>{this.props.album.artists[0].name} <i class="bi bi-dot"></i> </span> ); } render() { let album = this.props.album; return ( <a href={"/album/" + album.id} class="list-group-item list-group-item-action"> <div class="row"> <div class="col-3"> {album.images[album.images.length - 1] !== undefined && <span> <img src={album.images[album.images.length - 1].url} class="img-fluid list-img"/> </span> } </div> <div class="col-9 justify-content-center align-self-center"> <div>{album.name}</div> <div>{this.props.showArtist && this.renderArtist() }{album.release_date.substring(0, 4)}</div> </div> </div> </a> ); } }
JavaScript
class AccountTypeController { /** * Method to fetch all customers * @param {object} req * @param {object} res * @return {object} JSON response */ static async fetchAllAccountTypes(req, res) { try { const accountTypes = await AccountTypeRepo.getAll(); const message = 'Array of 0 or more accountTypes has been fetched successfully'; return response.success(res, { message, accountTypes }); } catch (error) { return response.internalError(res, { error }); } } }
JavaScript
class YZCharacter { /** * Defines a character. * @param {*} data The raw data of the character */ constructor(data) { /** * The ID of the character. * @type {number} * @readonly * @private */ Object.defineProperty(this, Symbol('id'), { value: Math.floor(Math.random() * Date.now()), enumerable: true, }); if (!data) throw new Error('No data entered for the character!'); /** * The name of the character. * @type {?string} */ this.name = data.name || null; /** * The gender of the character. * @type {?string} */ this.gender = data.gender || null; /** * The kin/race/species of the character. */ this.kin = data.kin || null; /** * The description of the character. * @type {?string} */ this.description = data.description || null; /** * The attributes of the character. * @type {Object} * @property {number} strength * @property {number} agility * @property {number} wits * @property {number} empathy */ this.attributes = this._parseAttributes(data.attributes); /** * The traumas of the character. * @type {Object} * @property {number} strength * @property {number} agility * @property {number} wits * @property {number} empathy */ this.traumas = this._parseAttributes(0); /** * The health's conditions of the character. */ this.conditions = { broken: false, starving: false, dehydrated: false, sleepless: false, hypothermic: false, }; if (data.conditions) { for (const cond in data.conditions) { if (cond in this.conditions) { this.conditions[cond] = data.conditions[cond]; } } } /** * The critical injuries of the character. * @type {string[]} */ this.crits = []; /** * The skills of the character. * @type {Object} * @property {number} "skillName" */ this.skills = data.skills || {}; /** * The talents of the character. * @type {string[]} */ this.talents = data.talents || []; /** * The mutations of the character. * @type {string[]} */ this.mutations = data.mutations || []; /** * The mana points of the character * @type {object} * @property {number} mp Mutation * @property {number} fp Feral * @property {number} ep Energy * @property {number} rp Reputation */ this.mana = { mp: data.mana.mp || 0, fp: data.mana.fp || 0, ep: data.mana.ep || 0, rp: data.mana.rp || 0, }; /** * The rot gauge of the character * @type {number} */ this.rot = data.rot || 0; /** * The number of permanent Rot points. * @type {number} */ this.permanentRot = data.permanentRot || 0; /** * The gear of the character, listed in a Map object. * * Key: item's name * * Value: item's weight * * 0 = tiny item * * 0.1–1.9 = standard item * * 2+ = heavy item * @type {Map} */ this.gear = new Map(data.gear); } _parseAttributes(data) { let str = 0, agi = 0, wit = 0, emp = 0; if (typeof data === 'number') { str = agi = wit = emp = data; } else if (data instanceof Array) { if (data.length === 4) [str, agi, wit, emp] = data; else throw new RangeError('Attributes array\'s length must be 4!'); } else if (typeof data === 'object' && data !== null) { str = data.strength || 0; agi = data.agility || 0; wit = data.wits || 0; emp = data.empathy || 0; } else { throw new TypeError('Attributes data type is incorrect!'); } return { strength: Math.max(str, 0), agility: Math.max(agi, 0), wits: Math.max(wit, 0), empathy: Math.max(emp, 0), }; } // Attributes getters shortcuts get str() { return this.attributes.strength - this.traumas.strength; } get agi() { return this.attributes.agility - this.traumas.agility; } get wit() { return this.attributes.wits - this.traumas.wits; } get emp() { return this.attributes.empathy - this.traumas.empathy; } }
JavaScript
class PastefyAPI extends Cajax { constructor(baseURL = "https://pastefy.ga"){ super(baseURL) this.promiseInterceptor = async res =>{ const json = await res.json() if (json.error) throw new Error() return json } } createPaste(data){ return this.post("/api/v2/paste", data).then(res=>res.paste) } editPaste(id, data){ return this.put(`/api/v2/paste/${id}`, data).then(() => null) } }
JavaScript
class CalendarStrip extends Component { static propTypes = { style: React.PropTypes.any, calendarColor: React.PropTypes.string, highlightColor: React.PropTypes.string, borderHighlightColor: React.PropTypes.string, startingDate: React.PropTypes.any, selectedDate: React.PropTypes.any, onDateSelected: React.PropTypes.func, useIsoWeekday: React.PropTypes.bool, iconLeft: React.PropTypes.any, iconRight: React.PropTypes.any, iconStyle: React.PropTypes.any, iconLeftStyle: React.PropTypes.any, iconRightStyle: React.PropTypes.any, iconContainer: React.PropTypes.any, calendarHeader: React.PropTypes.any, calendarHeaderStyle: React.PropTypes.any, calendarHeaderFormat: React.PropTypes.string, calendarAnimation: React.PropTypes.object, selection: React.PropTypes.string, selectionAnimation: React.PropTypes.object, dateNameStyle: React.PropTypes.any, dateNumberStyle: React.PropTypes.any, weekendDateNameStyle: React.PropTypes.any, weekendDateNumberStyle: React.PropTypes.any, locale: React.PropTypes.object }; static defaultProps = { startingDate: moment(), useIsoWeekday: true, iconLeft: require('./img/left-arrow-black.png'), iconRight: require('./img/right-arrow-black.png'), calendarHeaderFormat: 'MMMM YYYY', calendarHeader: false, locale: { name: 'zh', config: { months : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), monthsShort : "1_2_3_4_5_6_7_8_9_10_11_12".split("_"), weekdays : "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysShort : "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysMin : "周日_周一_周二_周三_周四_周五_周六日".split("_"), longDateFormat : { LT : "HH:mm", LTS : "HH:mm:ss", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[今天] LT", nextDay: '[明天] LT', nextWeek: 'dddd [下周] LT', lastDay: '[昨天] LT', lastWeek: 'dddd [上周] LT', sameElse: 'L' }, relativeTime : { future : "in %s", past : "there are %s", s : "a couple of seconds", m : "wait a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "one day", dd : "%d days", M : "a month", MM : "%d months", y : "one year", yy : "%d years" }, ordinalParse : /\d{1,2}(er|ème)/, ordinal : function (number) { return number + (number === 1 ? 'er' : 'ème'); }, meridiemParse: /PD|MD/, isPM: function (input) { return input.charAt(0) === 'M'; }, // in case the meridiem units are not separated around 12, then implement // this function (look at locale/id.js for an example) // meridiemHour : function (hour, meridiem) { // return /* 0-23 hour, given meridiem token and hour 1-12 */ // }, meridiem : function (hours, minutes, isLower) { return hours < 12 ? 'PD' : 'MD'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } } } }; constructor(props) { super(props); if(props.locale) { if(props.locale.name && props.locale.config) { moment.locale(props.locale.name, props.locale.config); } else { throw new Error('Locale prop is not in the correct format. \b Locale has to be in form of object, with params NAME and CONFIG!'); } } const startingDate = this.setLocale(moment(this.props.startingDate)); const selectedDate = this.setLocale(moment(this.props.selectedDate)); this.state = { startingDate, selectedDate }; this.resetAnimation(); this.componentDidMount = this.componentDidMount.bind(this); this.componentWillUpdate = this.componentWillUpdate.bind(this); this.getDatesForWeek = this.getDatesForWeek.bind(this); this.getPreviousWeek = this.getPreviousWeek.bind(this); this.getNextWeek = this.getNextWeek.bind(this); this.onDateSelected = this.onDateSelected.bind(this); this.isDateSelected = this.isDateSelected.bind(this); this.formatCalendarHeader = this.formatCalendarHeader.bind(this); this.animate = this.animate.bind(this); this.resetAnimation = this.resetAnimation.bind(this); } //Animate showing of CalendarDay elements componentDidMount() { this.animate(); } //Receiving props and set selected date componentWillReceiveProps(nextProps) { if (nextProps.selectedDate !== this.props.selectedDate) { const selectedDate = this.setLocale(moment(nextProps.selectedDate)); this.setState({ selectedDate }); } } //Only animate CalendarDays if the selectedDate is the same //Prevents animation on pressing on a date componentWillUpdate(nextProps, nextState) { if (nextState.selectedDate === this.state.selectedDate) { this.resetAnimation(); this.animate(); } } //Function that checks if the locale is passed to the component and sets it to the passed moment instance setLocale(momentInstance) { if (this.props.locale) { momentInstance.locale(this.props.locale.name); } return momentInstance; } //Set startingDate to the previous week getPreviousWeek() { this.setState({startingDate: this.state.startingDate.subtract(1, 'w')}); } //Set startingDate to the next week getNextWeek() { this.setState({startingDate: this.state.startingDate.add(1, 'w')}); } //Get dates for the week based on the startingDate //Using isoWeekday so that it will start from Monday getDatesForWeek() { const me = this; let dates = []; let startDate = moment(this.state.startingDate); arr.forEach((item, index) => { let date; if (me.props.useIsoWeekday) { date = me.setLocale(moment(startDate.isoWeekday(index + 1))); } else { date = me.setLocale(moment(startDate).add(index, 'days')); } dates.push(date); }); return dates; } //Handling press on date/selecting date onDateSelected(date,time) { this.setState({selectedDate: date}); if (this.props.onDateSelected) { this.props.onDateSelected(time); } } //Function to check if provided date is the same as selected one, hence date is selected //using isSame moment query with 'day' param so that it check years, months and day isDateSelected(date) { return date.isSame(this.state.selectedDate, 'day'); } //Function for reseting animations resetAnimation() { this.animatedValue = []; arr.forEach((value) => { this.animatedValue[value] = new Animated.Value(0); }); } //Function to animate showing the CalendarDay elements. //Possible cases for animations are sequence and parallel animate() { if (this.props.calendarAnimation) { let animations = arr.map((item) => { return Animated.timing( this.animatedValue[item], { toValue: 1, duration: this.props.calendarAnimation.duration, easing: Easing.linear } ); }); if (this.props.calendarAnimation.type.toLowerCase() === 'sequence') { Animated.sequence(animations).start(); } else { if (this.props.calendarAnimation.type.toLowerCase() === 'parallel') { Animated.parallel(animations).start(); } else { throw new Error('CalendarStrip Error! Type of animation is incorrect!'); } } } } //Function that formats the calendar header //It also formats the month section if the week is in between months formatCalendarHeader() { let firstDay = this.getDatesForWeek()[0]; let lastDay = this.getDatesForWeek()[this.getDatesForWeek().length - 1]; let monthFormatting = ''; //Parsing the month part of the user defined formating if ((this.props.calendarHeaderFormat.match(/Mo/g) || []).length > 0) { monthFormatting = 'Mo'; } else { if ((this.props.calendarHeaderFormat.match(/M/g) || []).length > 0) { for (let i = (this.props.calendarHeaderFormat.match(/M/g) || []).length; i > 0; i--) { monthFormatting += 'M'; } } } if (firstDay.month() === lastDay.month()) { return firstDay.format(this.props.calendarHeaderFormat); } if (firstDay.year() !== lastDay.year()) { return `${firstDay.format(this.props.calendarHeaderFormat)} / ${lastDay.format(this.props.calendarHeaderFormat)}`; } return `${monthFormatting.length > 1 ? firstDay.format(monthFormatting) : ''} ${monthFormatting.length > 1 ? '/' : ''} ${lastDay.format(this.props.calendarHeaderFormat)}`; } render() { let opacityAnim = 1; let datesRender = this.getDatesForWeek().map((date, index) => { if (this.props.calendarAnimation) { opacityAnim = this.animatedValue[index]; } return ( <Animated.View key={date} style={{opacity: opacityAnim, flex: 1}}> <CalendarDay date={date} key={date} selected={this.isDateSelected(date)} onDateSelected={this.onDateSelected} calendarColor={this.props.calendarColor} highlightColor={this.props.highlightColor} dateNameStyle={this.props.dateNameStyle} dateNumberStyle={this.props.dateNumberStyle} weekendDateNameStyle={this.props.weekendDateNameStyle} weekendDateNumberStyle={this.props.weekendDateNumberStyle} selection={this.props.selection} selectionAnimation={this.props.selectionAnimation} borderHighlightColor={this.props.borderHighlightColor} /> </Animated.View> ); }); let headerView = this.props.calendarHeader? (<Text style={[styles.calendarHeader, this.props.calendarHeaderStyle]}>{this.formatCalendarHeader()}</Text>):null return ( <View style={[styles.calendarContainer, this.props.style]}> {headerView} <View style={styles.datesStrip}> <TouchableOpacity style={[styles.iconContainer, this.props.iconContainer]} onPress={this.getPreviousWeek}> <Image style={[styles.icon, this.props.iconStyle, this.props.iconLeftStyle]} source={this.props.iconLeft}/> </TouchableOpacity> <View style={styles.calendarDates}> {datesRender} </View> <TouchableOpacity style={[styles.iconContainer, this.props.iconContainer]} onPress={this.getNextWeek}> <Image style={[styles.icon, this.props.iconStyle, this.props.iconRightStyle]} source={this.props.iconRight}/> </TouchableOpacity> </View> </View> ); } }
JavaScript
class JwtAuth { // Issue new token. static issueToken(data, key, jwtOptions) { return jwt.sign(data, key, jwtOptions); } /** * Verify token * * @param {string} token * @param {string} key * @param {object} jwtOptions * * @returns {Promise<unknown>} */ static verifyToken(token, key, jwtOptions) { return new Promise(function(onResolve, onReject) { const jwtCB = function(err, decodedToken) { if (err) { onReject(err); } else { onResolve(decodedToken); } }; jwt.verify(token, key, jwtOptions, jwtCB); }); } }
JavaScript
class OffersPage extends BasePage { /** * define selectors using getter methods */ get firstOffer() { return $('.offer') } get allOffers() { return $$('.offer') } async open() { await super.open('offers') } }
JavaScript
class LanguageBarFixer extends Fixer { /** @inheritdoc */ isApplieble(location) { return isRepoRoot(location) && !isRepoSetup(location); } /** @inheritdoc */ async waitUntilFixerReady() { return (await waitUntilElementsReady("main:nth-child(1) .BorderGrid-row:last-child")) && (await checkIfElementsReady("main:nth-child(1) .BorderGrid-row .Progress")); } /** @inheritdoc */ apply() { let langsBar = createElement("div", "d-flex repository-lang-stats-graph"); let langsContainer = createElement("ol", "repository-lang-stats-numbers"); let langsWrapper = createElement("details", { className: "details-reset mb-3", children: [ createElement("summary", { title: "Click for language details", children: [langsBar] }), createElement("div", { className: "repository-lang-stats", children: [langsContainer] }) ], attributes: settings.openLanguagesByDefault.value ? { open: "" } : { } }); let languagesData = [...document.querySelector("main .BorderGrid-row .Progress").parentElement.nextElementSibling.children]; for (let langData of languagesData.map(this._extractLanguageData)) { let barItem = createElement("span", { className: "language-color", attributes: { "aria-label": `${langData.name} ${langData.percent}`, "itemprop": "keywords" }, innerText: langData.name, style: { width: langData.percent, backgroundColor: langData.color } }); langsBar.append(barItem); let langItem = createElement(langData.link ? "a" : "span", { href: langData.link, children: [ createElement("span", { className: "color-block language-color", style: { backgroundColor: langData.color } }), createElement("span", { className: "lang", innerText: ` ${langData.name} ` }), createElement("span", { className: "percent", innerText: langData.percent }) ] }); langsContainer.append(createElement("li", { children: [langItem] })); } document.querySelector(".repository-content").prepend(langsWrapper); } /** * Extracts language details from the DOM element. * * @param {HTMLElement} element Language element. * @returns {{ name: string, percent: string, color: string, link: string }} * Language details. */ _extractLanguageData(element) { if (element.querySelector("a")) { return { name: element.querySelector("span").innerText, percent: element.querySelectorAll("span")[1].innerText, color: element.querySelector("svg").style.color, link: element.querySelector("a").href }; } else { return { name: element.querySelectorAll("span")[1].innerText, percent: element.querySelectorAll("span")[2].innerText, color: element.querySelector("svg").style.color, link: "" } } } }
JavaScript
class Recorder { constructor() { this.recording = null; this.events = new EventSubscription(); this.on = this.events.on.bind(this.events); this._trigger = this.events.trigger.bind(this.events); } tick() { if (this.recording == null || this.recording.state !== "started") return; this._update(); } async initialize() { const stream = await navigator.mediaDevices.getUserMedia ({ audio: true }); const options = { mimeType: MIME_TYPE }; this.recording = { state: "ready", recorder: new MediaRecorder(stream, options), isMyLine: false, breaks: [], }; this._trigger("initialized"); } async start() { if (this.recording == null || this.recording.state !== "ready") return; this.recording.recorder.start(); this.recording.startTime = new Date(); this.recording.state = "started"; this._trigger("started", { elapsedMs: 0, isMyLine: false }); } setMyLine(isMyLine) { if (this.recording.isMyLine !== isMyLine) { this.recording.breaks.push(new Date() - this.recording.startTime); } this.recording.isMyLine = isMyLine; this._update(); } async finish({ trackId }) { const data = await this._stopRecording(); this.recording = null; this._trigger("finished", { trackId, data }); } cancel() { this.recording = null; } _stopRecording() { return new Promise((resolve, reject) => { const { breaks, recorder, startTime } = this.recording; recorder.ondataavailable = (ev) => { const blob = new Blob([ev.data], { 'type': MIME_TYPE }); resolve({ blob, breaks, durationMs: new Date() - startTime }) }; // Browsers differ on standard way to stop, thus the two lines here. recorder.stop(); recorder.stream.getTracks().map(t => t.stop()); }); } _update() { this._trigger("update", { elapsedMs: new Date() - this.recording.startTime, isMyLine: this.recording.isMyLine }); } }
JavaScript
class GetPreviousSibling extends BaseElementCommand { get extraArgsCount() { return 0; } async protocolAction() { return this.executeProtocolAction('getPreviousSibling'); } }
JavaScript
class GameView { /** * When the Game object is created, the labyrinth (walls and dots), * the Pacman and the ghosts are displayed on the page. */ constructor(game, gameCtrl) { this._game = game; this._gameCtrl = gameCtrl; this._nbRows = game.maze.nbRows; this._nbColumns = game.maze.nbColumns; this._updateMazeArea(); this._createMaze(); this.updateLives(); this.showHighScore(); $("#pacman-container").append( $("<button>", { text: "Start", id: "start", class: "jdb-button jdb-round-xl jdb-margin-8 jdb-black" + " jdb-hover-blue-o jdb-border jdb-border-w2 jdb-ripple" + " jdb-text-shadow-multiple-dark" }).one("click", (event) => { this.startGame(); $(event.target).click(() => { if (!this._game.isGameOver()) { this._togglePause(); } }).html( $("<span>",{ "aria-hidden": true, class: "fa jdb-margin-right fa-pause", style: "top:-3px; position:relative" }) ).append($("<span>").text("Pause")); $(".mz-pacman").removeClass("not-started"); }) ); $(window).on("keydown", (event) => { switch (event.key.toLowerCase()) { case "p": if (this._game.hasStarted) { this._togglePause(); } break; case "s": if (!this._game.hasStarted) { $("#start").click(); } break; case "r": window.location.reload(); break; } }); } /** * Toggle pause state and the pause button. */ _togglePause() { let $startButton = $("#pacman-container").find("#start"); if (this._game.isPaused) { this._game.markPlay(); this._gameCtrl.play(); $(".mz-pacman").removeClass("not-started"); $startButton.find("span:first-child").removeClass("fa-play").addClass("fa-pause"); $startButton.find("span:last-child").text("Pause"); } else { this._game.markPause(); this._gameCtrl.pause(); $(".mz-pacman").addClass("not-started"); $startButton.find("span:first-child").removeClass("fa-pause").addClass("fa-play"); $startButton.find("span:last-child").text("Play"); } } /** * Sets the height and width of the scene according * to the number of rows and columns in this maze. */ _updateMazeArea() { $("#maze-area").css({ height: `${TILE_SIZE * this._nbRows}px`, width: `${TILE_SIZE * this._nbColumns}px` }); } /** * Adds the maze components in the page. */ _createMaze() { /** * Returns a span element created by jQuery. * * @param {object} properties an object of html attributes and CSS. * @param {string} properties.class the class name. * @param {string} properties.id the element id. * @param {number} properties.top the absolute top position. * @param {number} properties.left the absolute let position. * @returns {object} the jQuery object element. */ const $newTile = (properties) => $("<span>", { class: properties.class, id: properties.id }).css({ top, left } = properties); let $mazeArea = $("#maze-area"); let i, j, left, top, id = 1; for (i = 0; i < this._nbRows; i++) { for (j = 0; j < this._nbColumns; j++, id++) { top = `${TILE_SIZE * i}px`; left = `${TILE_SIZE * j}px`; if (this._game.maze.getWallLayerTile(new Position(i, j))) { $mazeArea.append($newTile({ class: "mz-wall", top, left })); } else if (this._game.maze.getDotLayerTile(new Position(i, j))) { if (this._game.maze.getDotLayerTile(new Position(i, j)).isEnergizer) { $mazeArea.append( $newTile({ class: "mz-pac-dot energizer", id: `d_${id}`, top, left }) ); } else { $mazeArea.append( $newTile({ class: "mz-pac-dot", id: `d_${id}`, top, left }) ); } } } } // Add the pacman to the UI. $mazeArea.append( $newTile({ class: "mz-pacman not-started", top: `${TILE_SIZE * this._game.maze.pacmanRespawn.row}px`, left: `${TILE_SIZE * this._game.maze.pacmanRespawn.column}px` }) ); // Add ghosts to the UI. GHOSTS_ID.forEach((ghostClass) => { $mazeArea.append( $newTile({ class: `ghost ${ghostClass}`, top: `${TILE_SIZE * this._game.maze.ghostRespawn.row}px`, left: `${TILE_SIZE * this._game.maze.ghostRespawn.column}px` }) ); }); } /** * Updates the game in the UI. */ updateFrame() { // Update the position of the pacman on the page. $(".mz-pacman").css({ top: `${TILE_SIZE * this._game.pacman.position.row}px`, left: `${TILE_SIZE * this._game.pacman.position.column}px` }).attr("data-dir", () => { switch (this._game.pacman.direction) { case Direction.NORTH: return "to-top" case Direction.EAST: return "to-right" case Direction.WEST: return "to-left" case Direction.SOUTH: return "to-bottom" } }); // Update the position of the ghosts on the page. $.each(GHOSTS_ID, (index, id) => { $(`.ghost.${id}`).css({ top: `${TILE_SIZE * this._game.ghosts[index].position.row}px`, left: `${TILE_SIZE * this._game.ghosts[index].position.column}px` }); }); if (this._game.removedDot) { $(`#${this._game.removedDot.id}`).remove(); $("#current-score").find("span").text(this._game.score); if (this._game.removedDot.isEnergizer && this._game.pacman.isSuper) { $("#current-score").find("span") .addClass("jdb-text-green").delay(1e3).queue(function(){ $(this).removeClass("jdb-text-green").dequeue(); }); } } } /** * Updates the number of views in the UI. */ updateLives() { let $liveArea = $("#lives-area"); $liveArea.empty(); for (let i = 0; i < this._game.pacman.nbLives; i++) { $liveArea.append($("<span>")); } } /** * Displays the given message on the * info panel at the end of the game. * @param {string} message the message to display. */ displayEndOfGameMsg(message) { $("#info-panel").html(message).slideDown(); } /** * Hides the info panel. */ hideEndOfGameMsg() { $("#info-panel").html("").slideUp(); } /** * Displays the current high score in the UI. */ showHighScore() { $("#high-score").text(this._game.highScore); } /** * Marks the Pacman as not eating. */ disablePacman() { $(".mz-pacman").addClass("not-started"); } /** * Marks the Pacman as eating. */ enablePacman() { $(".mz-pacman").removeClass("not-started"); } /** * Updates the UI of the game for the next level. */ nextLevel() { $("#maze-area").empty(); this._updateMazeArea(); this._createMaze(); } /** * Asks to start the game. */ startGame() { this._gameCtrl.startHasBeenRequested(); } }
JavaScript
class CardContainer extends HTMLElement { constructor(info) { super() this.innerHTML = ` <div class="card card-horizontal card-type-album ${info.imgUri ? "" : "card-hidden-image"}" data-uri="${info.uri}" data-contextmenu=""> <div class="card-attention-highlight-box"></div> <div class="card-horizontal-interior-wrapper"> ${info.imgUri ? ` <div class="card-image-wrapper"> <div class="card-image-hit-area"> <a class="card-image-link" link="${info.uri}"> <div class="card-hit-area-counter-scale-left"></div> <div class="card-image-content-wrapper"> <div class="card-image" style="background-image: url('${info.imgUri}')"></div> </div> </a> <div class="card-overlay"></div> </div> </div> ` : ""} <div class="card-info-wrapper"> <div class="order-controls"> <div class="order-controls-up"> <button class="button button-green button-icon-only spoticon-chevron-up-16" data-tooltip="Move Up"></button> </div> <div class="order-controls-remove"> <button class="button button-green button-icon-only spoticon-x-16" data-tooltip="Remove"></button> </div> <div class="order-controls-down"> <button class="button button-green button-icon-only spoticon-chevron-down-16" data-tooltip="Move Down"></button> </div> </div> <a class="card-info-link" ${info.uri}> <div class="card-info-content-wrapper"> <div class="card-info-title"><span class="card-info-title-text">${info.name}</span></div> <div class="card-info-subtitle-owner"><span>${info.owner}</span></div> <div class="card-info-subtitle-tracks"><span>${info.tracks.length === 1 ? "1 Track" : `${info.tracks.length} Tracks`}</span></div> </div> </a> </div> </div> </div>` const up = this.querySelector(".order-controls-up") up.onclick = (event) => { LIST.moveItem(info.uri, -1) event.stopPropagation() } const remove = this.querySelector(".order-controls-remove") remove.onclick = (event) => { LIST.removeFromStorage(info.id) event.stopPropagation() } const down = this.querySelector(".order-controls-down") down.onclick = (event) => { LIST.moveItem(info.uri, +1) event.stopPropagation() } const imageLink = this.querySelector(".card-image-link"); const infoLink = this.querySelector(".card-info-link"); if (imageLink) imageLink.addEventListener("click", ((e) => showPlaylist(e))); if (infoLink) infoLink.addEventListener("click", ((e) => showPlaylist(e))); } }
JavaScript
class ShortAnswerResponse extends Component { constructor(props){ super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); } // handle change to Short Answer QUESTION content handleChange(event){ this.props.onUpdate(this.props.id, event.target.value); this.setState({value: event.target.value}); } render() { return( <div className="ShortAnswerResponse"> <ControlLabel>{this.props.title}</ControlLabel> <div className="ShortResponseInput"> <FormControl type="text" value={this.state.value} onChange={this.handleChange}/> </div> </div> ); } }
JavaScript
class LongAnswerResponse extends Component { constructor(props){ super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event){ this.props.onUpdate(this.props.id, event.target.value); this.setState({value: event.target.value}); } render() { return( <div className="LongAnswerResponse"> <ControlLabel>{this.props.title}</ControlLabel> <div className="LongResponseInput"> <FormControl componentClass="textarea" value={this.state.value} onChange={this.handleChange}/> </div> </div> ); } }
JavaScript
class NumberAnswerResponse extends Component { constructor(props){ super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event){ this.props.onUpdate(this.props.id, event.target.value); this.setState({value: event.target.value}); } render() { return( <div className="NumberAnswerResponse"> <ControlLabel>{this.props.title}</ControlLabel> <div className="NumberResponseInput"> <FormControl type="number" value={this.state.value} onChange={this.handleChange}/> </div> </div> ); } }
JavaScript
class MultipleChoiceResponse extends Component { constructor(props){ super(props); this.state = { value: '', options: [] }; this.handleOptionChange = this.handleOptionChange.bind(this); } componentDidMount(){ var newOptions = [] for(var i=0; i<this.props.options.length; i++){ var groupName = "MC "+this.props.id; newOptions = newOptions.concat(<Radio onClick={this.handleOptionChange.bind(this, this.props.options[i])} name={groupName} key={newOptions.length}> {this.props.options[i]} </Radio>); } this.setState({ options: newOptions }); } handleOptionChange(option){ this.props.onUpdate(this.props.id, option); } render() { return( <div className="MultipleChoiceResponse"> <ControlLabel>{this.props.title}</ControlLabel> <div className="MultipleChoiceOptions"> <FormGroup> {this.state.options} </FormGroup> </div> </div> ) } }
JavaScript
class DataService extends AbstractDataService { constructor() { super(); /** * Centralised data, which is shared by all other components */ this._data = { //Component states object componentStates: { detailsPanelVisibility: false, historyListMenuVisibility: false, loadingCurrentHistory: false, }, apiConfig: {}, histories : [], currentHistory : {}, currentVisualTest: {}, currentVisualReference: {}, }; } getTestResultRootPath() { return config.outputPath; } /** * Get global configuration from the remote server */ fetchConfig() { return new Promise((resolve, reject)=> { m.request({ method: 'GET', url: `${config.apiRootPath}`, }).then((result)=> { if(result) { Object.assign( this._data.apiConfig, result ); resolve(this._data.apiConfig); } else { reject(undefined); } }).catch((err)=> { console.warn('Get api config wrong', err); reject(undefined); }); }); } /** * Fetch a list number of latest histories * @param {number} limit maximum number of latest histories. default is 20 */ fetchHistoryList(limit=20) { return new Promise((resolve, reject)=> { if(_.isEmpty(this._data.histories)) { m.request({ method: 'GET', url: `${historyEndpoint}?limit=${limit}`, }).then((result)=> { if(result && result.data) { Object.assign( this._data.histories, ComponentHelpers.History.sortHistory(result.data) ); this.broadcastDataChanges('histories'); resolve(this._data.histories); } else { reject(undefined); } }).catch((err)=> { console.warn('List history err', err); reject(undefined); }); } else { resolve(this._data.histories); } }); } /** * Set current history with its id * @param {*} id - history ID */ setCurrentHistory(id) { this.setLoadingCurrentHistoryState(true); return new Promise((resolve, reject)=> { m.request({ method: 'GET', url: `${historyEndpoint}?id=${id}`, }).then((result)=> { if(result && result.data) { Objects.empty(this._data.currentHistory); Object.assign( this._data.currentHistory, result.data, {visualTests: ComponentHelpers.Visual.sortTestResults(result.data.visualTests)} ); this.broadcastDataChanges('currentHistory'); resolve(this._data.currentHistory); } else { reject(undefined); } }).catch((err)=> { console.warn('setCurrentHistory err', err); reject(undefined); }).finally(()=> { this.setLoadingCurrentHistoryState(false); }); }); } getCurrentHistory() { return this._data.currentHistory; } setCurrentVisualTest(test) { Objects.empty(this._data.currentVisualTest); Object.assign(this._data.currentVisualTest, test); this.broadcastDataChanges('currentVisualTest'); return this._data.currentVisualTest; } getCurrentVisualTest() { return this._data.currentVisualTest; } approveTest(test) { return new Promise((resolve, reject)=> { m.request({ method: 'PUT', url: visualEndpoint, data: { historyId: test.historyId, visualReferenceId: test.visualReferenceId, visualScreenshot: test.visualScreenshot, browser: test.browser, url: test.url, name: test.name, visualScreenshotPath: test.visualScreenshotPath, _id: test._id, }, }).then((result)=> { if(result && result.data) { Object.assign( this._data.currentHistory.visualTests.find((test)=> { return test._id === result.data.approvedVisualTest._id; }), result.data.approvedVisualTest); resolve(result.data); } else { reject(undefined); } }).catch((err)=> { console.warn('Approve test err', err); reject(undefined); }); }); } setCurrentVisualTestReference(test) { Objects.empty(this._data.currentVisualReference); Object.assign(this._data.currentVisualReference, ComponentHelpers.Visual.findTestReference(test, this._data.currentHistory.visualReferences)); this.broadcastDataChanges('currentVisualReference'); return this._data.currentVisualReference; } setLoadingCurrentHistoryState(state=true) { this._data.componentStates.loadingCurrentHistory = state; this.broadcastDataChanges('componentStates'); } getCurrentVisualTestReference() { return this._data.currentVisualReference; } setDetailsPanelVisibility(value=true) { this._data.componentStates.detailsPanelVisibility = value; this.broadcastDataChanges('componentStates'); } isDetailsPanelVisible() { return this._data.componentStates.detailsPanelVisibility; } setHistoryListMenuVisibility(value=true) { this._data.componentStates.historyListMenuVisibility = value; this.broadcastDataChanges('componentStates'); } isHistoryListMenuVisible() { return this._data.componentStates.historyListMenuVisibility; } isLoadingHistory() { return this._data.componentStates.loadingCurrentHistory; } /*---------------------- helpers -------------------------*/ }
JavaScript
class UserFilter extends Component { onFilterChange = (fieldName, newValue) => { const { getList, entityType, updateFilter, filter } = this.props if (filter[fieldName] === newValue) { return } updateFilter(fieldName, newValue) getList(entityType) } createInactiveMonthsOptions() { const month = i18n.t('month') const months = i18n.t('months') return Array(12) .fill() .map((_, index) => { const id = index + 1 const displayName = id === 1 ? `${id} ${month}` : `${id} ${months}` return { id, displayName } }) } renderDropDown(config) { const mergedConfig = { ...config, includeEmpty: true, emptyLabel: i18n.t('<No value>'), } return <DropDown {...mergedConfig} /> } renderInactiveMonthsFilter() { const dropDownConfig = { menuItems: this.createInactiveMonthsOptions(), floatingLabelText: i18n.t('Inactivity'), value: this.props.filter.inactiveMonths, onChange: event => this.onFilterChange(INACTIVE_MONTHS, event.target.value), style: { ...style, width: '132px' }, } return this.renderDropDown(dropDownConfig) } renderInvitationStatusFilter() { const dropDownConfig = { menuItems: [ { id: 'all', displayName: i18n.t('All invitations') }, { id: 'expired', displayName: i18n.t('Expired invitations') }, ], floatingLabelText: i18n.t('Invitations'), value: this.props.filter.invitationStatus, onChange: event => this.onFilterChange(INVITATION_STATUS, event.target.value), style: { ...style, width: '172px' }, } return this.renderDropDown(dropDownConfig) } renderSelfRegisteredFilter() { const value = this.props.filter.selfRegistered const baseClassName = 'data-table__filter-bar__checkbox' const checkedClassName = `${baseClassName}--checked` return ( <Checkbox value={value} onCheck={(event, value) => this.onFilterChange(SELF_REGISTERED, value) } label={i18n.t('Self registrations')} className={value ? checkedClassName : baseClassName} style={selfRegisteredStyle} /> ) } render() { const { entityType } = this.props return ( <div> <SearchFilter entityType={entityType} /> <OrganisationUnitInput /> {this.renderInactiveMonthsFilter()} {this.renderInvitationStatusFilter()} {this.renderSelfRegisteredFilter()} </div> ) } }
JavaScript
class Queue { constructor() { this.data = [] } enqueue(item) { // Elemento entra na fila this.data.push(item) // push() para inserir o item dentro do array console.log(`${item} ENTROU na fila!`) } dequeue() { // Elemento sai na fila const item = this.data.shift() // shift() para remover o elemento de índice 0 do array (diminui em 1 os índices dos demais valores do vetor) console.log(`${item} SAIU da fila!`) } }
JavaScript
class ScaleColumn extends Column { //region Config static get $name() { return 'ScaleColumn'; } static get type() { return 'scale'; } static get isScaleColumn() { return true; } static get fields() { return [ 'scalePoints' ]; } static get defaults() { return { text : '\xa0', width : 120, minWidth : 120, cellCls : 'b-scale-cell', scalePoints : [ { value : 4 }, { value : 8, text : 8 } ] }; } //endregion //region Constructor/Destructor onDestroy() { this.scaleWidget.destroy(); } //endregion //region Internal set width(width) { super.width = width; this.scaleWidget.width = width; } get width() { return super.width; } applyValue(useProp, key, value) { // pass value to scaleWidget if (key === 'scalePoints') { this.scaleWidget[key] = value; } return super.applyValue(...arguments); } get scaleWidget() { const me = this; if (!me._scaleWidget) { me._scaleWidget = new Scale({ owner : me.grid, appendTo : Widget.floatRoot, cls : 'b-hide-offscreen', align : 'right', scalePoints : me.scalePoints, monitorResize : false }); Object.defineProperties(me._scaleWidget, { width : { get() { return me.width; }, set(width) { this.element.style.width = `${width}px`; this._width = me.width; } }, height : { get() { return this._height; }, set(height) { this.element.style.height = `${height}px`; this._height = height; } } }); me._scaleWidget.width = me.width; } return me._scaleWidget; } //endregion //region Render renderer({ cellElement }) { const { scaleWidget } = this; scaleWidget.height = this.grid.rowHeight; scaleWidget.refresh(); // Clone the scale widget element since every row is supposed to have // the same scale settings const scaleCloneElement = scaleWidget.element.cloneNode(true); scaleCloneElement.removeAttribute('id'); scaleCloneElement.classList.remove('b-hide-offscreen'); cellElement.innerHTML = ''; cellElement.appendChild(scaleCloneElement); } //endregion }
JavaScript
class SimulateColorBlindEffectAction extends Action { constructor() { super(); this._actionModel = {}; this._actionModel.actionType = 'simulateColorblind'; this.addQualifier(new Qualifier('e', `simulate_colorblind`)); } setQualifier(val) { const strToAppend = `:${val}`; if (val) { this.addQualifier(new Qualifier('e', `simulate_colorblind${strToAppend}`)); } return this; } /** * @description Sets the color blind condition to simulate. * @param {Qualifiers.simulateColorBlindValues | SimulateColorBlindType | string} cond * @return {this} */ condition(cond) { this._actionModel.condition = cond; return this.setQualifier(cond); } static fromJson(actionModel) { const { actionType, condition } = actionModel; // We are using this() to allow inheriting classes to use super.fromJson.apply(this, [actionModel]) // This allows the inheriting classes to determine the class to be created const result = new this(); condition && result.condition(condition); return result; } }
JavaScript
class SummaryListComponent extends LitElement { static get styles() { return [componentStyles]; } constructor() { super(); } connectedCallback() { super.connectedCallback(); } firstUpdated() { this.shadowRoot.addEventListener('slotchange', (e) => { const slot = this.shadowRoot.querySelector('slot'); const nodes = Array.from( this.querySelectorAll('govukwc-summary-list-row'), ); const slotNodes = nodes.map((node) => { const wrapper = document.createElement('div'); wrapper.innerHTML = node.shadowRoot.innerHTML; const wrapperNode = wrapper.firstElementChild; const value = wrapperNode.querySelector('.govuk-summary-list__value'); value.innerHTML = node.innerHTML; return wrapperNode; }); const container = slot.parentNode; container.removeChild(slot); slotNodes.forEach((node) => container.appendChild(node)); const rows = Array.from(container.children); rows.forEach((row, index) => { row.addEventListener('click', (e) => { e.preventDefault(); const event = new CustomEvent('govukwc:click', { detail: { selectedIndex: index, key: row.getAttribute('data-key'), }, }); this.dispatchEvent(event); }); }); }); } render() { return html`<dl class="govuk-summary-list"> <slot></slot> </div>`; } }
JavaScript
class SignupPage extends React.Component { constructor(props) { super(props); this.state = { username: '', password: '', name: '', openError: false } } handleInputChange = (e) => { const target = e.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value, }); } handleOpenError = () => { this.setState({ openError: true }) } onSubmit = (e) => { e.preventDefault(); if (!this.state.username || !this.state.password || !this.state.name) { this.setState({ openError: true }) return; } this.props.onSignup(this.state.username, this.state.password, this.state.name) } render() { // const classes = useStyles(); const { classes } = this.props; const { openError } = this.state; return ( // <Container component="main" maxWidth="xs"> <div> <Grid container component="div" className={classes.root}> <CssBaseline /> <Grid item xs={false} sm={4} md={7} className={classes.image} /> <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square> <Helmet> <title>Signup Page</title> <meta name="description" content="Description of SigninPage" /> </Helmet> <CssBaseline /> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign Up </Typography> <form className={classes.form} noValidate onSubmit={this.onSubmit}> <TextField required error={openError} variant="outlined" margin="normal" fullWidth id="username" label="Username" name="username" autoComplete="username" autoFocus onChange={this.handleInputChange} /> <TextField error={openError} variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" onChange={this.handleInputChange} /> <TextField error={openError} variant="outlined" margin="normal" required fullWidth name="name" label="name" id="name" autoComplete="name" onChange={this.handleInputChange} /> {/* <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> */} <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} > Create a User </Button> </form> </div> <Box mt={5}> <MadeWithLove /> </Box> {/* </Container> */} </Grid> </Grid> </div> ); } }
JavaScript
class SoftwareUpdateConfigurationCollectionItem { /** * Create a SoftwareUpdateConfigurationCollectionItem. * @member {string} [name] Name of the software update configuration. * @member {string} [id] Resource Id of the software update configuration * @member {object} [updateConfiguration] Update specific properties of the * software update configuration. * @member {array} [updateConfiguration.azureVirtualMachines] List of azure * resource Ids for azure virtual machines targeted by the software update * configuration. * @member {moment.duration} [updateConfiguration.duration] Maximum time * allowed for the software update configuration run. Duration needs to be * specified using the format PT[n]H[n]M[n]S as per ISO8601 * @member {string} [frequency] execution frequency of the schedule * associated with the software update configuration. Possible values * include: 'OneTime', 'Day', 'Hour', 'Week', 'Month' * @member {date} [startTime] the start time of the update. * @member {date} [creationTime] Creation time of the software update * configuration, which only appears in the response. * @member {date} [lastModifiedTime] Last time software update configuration * was modified, which only appears in the response. * @member {string} [provisioningState] Provisioning state for the software * update configuration, which only appears in the response. * @member {date} [nextRun] ext run time of the update. */ constructor() { } /** * Defines the metadata of SoftwareUpdateConfigurationCollectionItem * * @returns {object} metadata of SoftwareUpdateConfigurationCollectionItem * */ mapper() { return { required: false, serializedName: 'softwareUpdateConfigurationCollectionItem', type: { name: 'Composite', className: 'SoftwareUpdateConfigurationCollectionItem', modelProperties: { name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, updateConfiguration: { required: false, serializedName: 'properties.updateConfiguration', type: { name: 'Composite', className: 'CollectionItemUpdateConfiguration' } }, frequency: { required: false, serializedName: 'properties.frequency', type: { name: 'String' } }, startTime: { required: false, nullable: false, serializedName: 'properties.startTime', type: { name: 'DateTime' } }, creationTime: { required: false, nullable: false, readOnly: true, serializedName: 'properties.creationTime', type: { name: 'DateTime' } }, lastModifiedTime: { required: false, nullable: false, readOnly: true, serializedName: 'properties.lastModifiedTime', type: { name: 'DateTime' } }, provisioningState: { required: false, readOnly: true, serializedName: 'properties.provisioningState', type: { name: 'String' } }, nextRun: { required: false, nullable: true, serializedName: 'properties.nextRun', type: { name: 'DateTime' } } } } }; } }
JavaScript
class EmisorHookAll { /** * @type {Set<EmisorHookCallback>} */ #allCallbacks = new Set(); get pluginApi () { return { /** * Register a hook all events * @param {EmisorHookCallback} callback */ all: (callback) => { if (!isFunction(callback)) { throw new EmisorPluginTypeError('callback', 'function', callback); } this.#allCallbacks.add(callback); } }; } /** * * @param {import('./').EmisorHookAPI} Emisor * @returns {EmisorHookFnc[]} */ getHooks (Emisor) { return Array.from(this.#allCallbacks) .map((callback) => { let storage = {}; return (event, payload) => callback({ event, payload, storage }, Emisor); }); } }
JavaScript
class EmisorHookEventStr { /** * @type {string} */ #postfixSeparator /** * @type {RegExp} */ #allowedPrefixRegex /** * @type {string} */ #postfixDivider /** * @type {Map<RegExp, EmisorHookEventStrCallBack>} */ #postfixCallbacks = new Map(); /** * @type {Map<RegExp, EmisorHookEventStrCallBack>} */ #prefixCallbacks = new Map(); /** * @param {string} s */ set postfixSeparator(s) { if (!isString(s)) { throw new EmisorPluginTypeError('postfixSeparator', 'string', s); } if(s.length !== 1) { throw new EmisorPluginError('postfixSeparator can not be longer then 1'); } this.#postfixSeparator = s; this.#updateAllowedPrefixRegex(); } /** * @param {string} s */ set postfixDivider(s) { if (!isString(s)) { throw new EmisorPluginTypeError('postfixDivider', 'string', s); } if(s.length !== 1) { throw new EmisorPluginError('postfixDivider can not be longer then 1'); } this.#postfixDivider = s; this.#updateAllowedPrefixRegex(); } get pluginApi () { return { /** * Register a postfix hook * @param {RegExp} regex * @param {EmisorHookEventStrCallBack} callback */ postfix: (regex, callback) => { if (!isRegExp(regex)) { throw new EmisorPluginTypeError('regex', 'RegExp', regex); } if (!isFunction(callback)) { throw new EmisorPluginTypeError('callback', 'function', callback); } this.#postfixCallbacks.set(regex, callback); }, /** * Register a prefix hook * @param {string} char any char that is not a-z, 0-9 or postfix separator * @param {EmisorHookEventStrCallBack} callback */ prefix: (char, callback) => { if (!isString(char)) { throw new EmisorPluginTypeError('char', 'string', char); } if (char.length !== 1) { throw new EmisorPluginError('char can not be longer then 1'); } if (!this.#allowedPrefixRegex.test(char)) { throw new EmisorPluginError(`char "${char}" is not allowed`); } if (!isFunction(callback)) { throw new EmisorPluginTypeError('callback', 'function', callback); } if (this.#prefixCallbacks.has(char)) { throw new EmisorPluginError(`There is already a hook registered with "${char}"`); } this.#prefixCallbacks.set(char, callback); } }; } constructor () { this.#updateAllowedPrefixRegex(); } /** * Parse event string * @param {string} event * @return {{event:string, options: Object<string|Symbol, any>}} */ parseStr (event) { let postfix = this.#postfixStr(event), prefix = this.#prefixStr(postfix.event); return { event: prefix.event, options: { ...postfix.options, ...prefix.options } }; } /** * Parse prefix string and runs prefix hooks if any * @param {string} rawEvent * @return {{event:string, options: Object<string|Symbol, any>}} */ #prefixStr (rawEvent) { let char = rawEvent[0], hook = this.#prefixCallbacks.get(char); //run hook if (hook) { return { event: rawEvent.substr(1), options: { ...hook(char) } }; } return { event: rawEvent, options: {} }; } /** * Parse postfix string and runs postfix hooks if any * @param {string} rawEvent * @return {{event:string, options: Object<string|Symbol, any>}} */ #postfixStr (rawEvent) { let options = {}, [event, ...postfix] = rawEvent.split(this.#postfixDivider); postfix = postfix.join(this.#postfixDivider); //only when event has a postfix if (postfix) { postfix.split(this.#postfixSeparator) .forEach((plugin) => { this.#postfixCallbacks.forEach((hook, reg) => { if (reg.test(plugin)) { options = { ...options, ...hook(plugin) }; } }); }); } return { event, options }; } /** * update allowed prefix regex */ #updateAllowedPrefixRegex () { let needsEscaping = [ '-', ']' ], disallowed = [ this.#postfixDivider, this.#postfixSeparator, '*' //wild card ], allowed = PREFIX_ALLOWED.split('') .filter((char) => !disallowed.includes(char)) .map((char) => { if (needsEscaping.includes(char)) { return `\\${char}`; } return char; }) .join(''); this.#allowedPrefixRegex = new RegExp(`[${allowed}]`); } }
JavaScript
class Switch extends Base { state() { const state = get(this.data, 'state'); if (isUndefined(state)) { return; } return state; } async turnOn() { const { success } = await this.api._deviceControl(this.device.id, 'turnOnOff', { value: '1' }); if (success) { this.data.state = true; } } async turnOff() { const { success } = await this.api._deviceControl(this.device.id, 'turnOnOff', { value: '0' }); if (success) { this.data.state = false; } } update() { // Avoid get cache value after control. return setTimeout(async () => { const devices = await this.api.discovery() if (isUndefined(devices)) { return; } const device = find(devices, { id: this.device.id }); if (device) { this.data = device.data; return true; } }, 500); } }
JavaScript
class App extends AbstractApp { /** * Initializes a new App instance. * * @param {Object} props - The read-only React Component props with which * the new instance is to be initialized. */ constructor(props) { super(props); // Bind event handlers so they are only bound once for every instance. this._navigatorRenderScene = this._navigatorRenderScene.bind(this); this._onLinkingURL = this._onLinkingURL.bind(this); } /** * Subscribe to notifications about activating URLs registered to be handled * by this app. * * @inheritdoc * @see https://facebook.github.io/react-native/docs/linking.html * @returns {void} */ componentWillMount() { super.componentWillMount(); Linking.addEventListener('url', this._onLinkingURL); } /** * Unsubscribe from notifications about activating URLs registered to be * handled by this app. * * @inheritdoc * @see https://facebook.github.io/react-native/docs/linking.html * @returns {void} */ componentWillUnmount() { Linking.removeEventListener('url', this._onLinkingURL); super.componentWillUnmount(); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const store = this.props.store; /* eslint-disable brace-style, react/jsx-no-bind */ return ( <Provider store = { store }> <Navigator initialRoute = { _getRouteToRender(store.getState) } ref = { navigator => { this.navigator = navigator; } } renderScene = { this._navigatorRenderScene } /> </Provider> ); /* eslint-enable brace-style, react/jsx-no-bind */ } /** * Navigates to a specific Route (via platform-specific means). * * @param {Route} route - The Route to which to navigate. * @returns {void} */ _navigate(route) { const navigator = this.navigator; // TODO Currently, the replace method doesn't support animation. Work // towards adding it is done in // https://github.com/facebook/react-native/issues/1981 // XXX React Native's Navigator adds properties to the route it's // provided with. Clone the specified route in order to prevent its // modification. navigator && navigator.replace({ ...route }); } /** * Renders the scene identified by a specific route in the Navigator of this * instance. * * @param {Object} route - The route which identifies the scene to be * rendered in the associated Navigator. In the fashion of NavigatorIOS, the * specified route is expected to define a value for its component property * which is the type of React component to be rendered. * @private * @returns {ReactElement} */ _navigatorRenderScene(route) { // We started with NavigatorIOS and then switched to Navigator in order // to support Android as well. In order to reduce the number of // modifications, accept the same format of route definition. return this._createElement(route.component, {}); } /** * Notified by React's Linking API that a specific URL registered to be * handled by this App was activated. * * @param {Object} event - The details of the notification/event. * @param {string} event.url - The URL registered to be handled by this App * which was activated. * @private * @returns {void} */ _onLinkingURL(event) { this._openURL(event.url); } }
JavaScript
class MeetingSessionStatus { constructor(_statusCode) { this._statusCode = _statusCode; } statusCode() { return this._statusCode; } isFailure() { switch (this._statusCode) { case MeetingSessionStatusCode_1.default.AudioAuthenticationRejected: case MeetingSessionStatusCode_1.default.AudioCallAtCapacity: case MeetingSessionStatusCode_1.default.AudioInternalServerError: case MeetingSessionStatusCode_1.default.AudioServiceUnavailable: case MeetingSessionStatusCode_1.default.AudioDisconnected: case MeetingSessionStatusCode_1.default.VideoCallAtSourceCapacity: case MeetingSessionStatusCode_1.default.SignalingBadRequest: case MeetingSessionStatusCode_1.default.SignalingInternalServerError: case MeetingSessionStatusCode_1.default.SignalingRequestFailed: case MeetingSessionStatusCode_1.default.StateMachineTransitionFailed: case MeetingSessionStatusCode_1.default.ICEGatheringTimeoutWorkaround: case MeetingSessionStatusCode_1.default.ConnectionHealthReconnect: case MeetingSessionStatusCode_1.default.RealtimeApiFailed: case MeetingSessionStatusCode_1.default.TaskFailed: case MeetingSessionStatusCode_1.default.NoAttendeePresent: return true; default: return false; } } isTerminal() { switch (this._statusCode) { case MeetingSessionStatusCode_1.default.Left: case MeetingSessionStatusCode_1.default.AudioJoinedFromAnotherDevice: case MeetingSessionStatusCode_1.default.AudioAuthenticationRejected: case MeetingSessionStatusCode_1.default.AudioCallAtCapacity: case MeetingSessionStatusCode_1.default.MeetingEnded: case MeetingSessionStatusCode_1.default.AudioDisconnected: case MeetingSessionStatusCode_1.default.TURNCredentialsForbidden: case MeetingSessionStatusCode_1.default.SignalingBadRequest: case MeetingSessionStatusCode_1.default.SignalingRequestFailed: case MeetingSessionStatusCode_1.default.VideoCallAtSourceCapacity: case MeetingSessionStatusCode_1.default.RealtimeApiFailed: case MeetingSessionStatusCode_1.default.AudioAttendeeRemoved: return true; default: return false; } } isAudioConnectionFailure() { switch (this._statusCode) { case MeetingSessionStatusCode_1.default.AudioAuthenticationRejected: case MeetingSessionStatusCode_1.default.AudioInternalServerError: case MeetingSessionStatusCode_1.default.AudioServiceUnavailable: case MeetingSessionStatusCode_1.default.StateMachineTransitionFailed: case MeetingSessionStatusCode_1.default.ICEGatheringTimeoutWorkaround: case MeetingSessionStatusCode_1.default.SignalingBadRequest: case MeetingSessionStatusCode_1.default.SignalingInternalServerError: case MeetingSessionStatusCode_1.default.SignalingRequestFailed: case MeetingSessionStatusCode_1.default.RealtimeApiFailed: case MeetingSessionStatusCode_1.default.NoAttendeePresent: return true; default: return false; } } toString() { switch (this._statusCode) { case MeetingSessionStatusCode_1.default.OK: return 'Everything is OK so far.'; case MeetingSessionStatusCode_1.default.Left: return 'The attendee left the meeting.'; case MeetingSessionStatusCode_1.default.AudioJoinedFromAnotherDevice: return 'The attendee joined from another device.'; case MeetingSessionStatusCode_1.default.AudioDisconnectAudio: return 'The audio connection failed.'; case MeetingSessionStatusCode_1.default.AudioAuthenticationRejected: return 'The meeting rejected the attendee.'; case MeetingSessionStatusCode_1.default.AudioCallAtCapacity: return "The attendee couldn't join because the meeting was at capacity."; case MeetingSessionStatusCode_1.default.AudioCallEnded: case MeetingSessionStatusCode_1.default.TURNMeetingEnded: case MeetingSessionStatusCode_1.default.MeetingEnded: return 'The meeting ended.'; case MeetingSessionStatusCode_1.default.AudioInternalServerError: case MeetingSessionStatusCode_1.default.AudioServiceUnavailable: case MeetingSessionStatusCode_1.default.AudioDisconnected: return 'The audio connection failed.'; case MeetingSessionStatusCode_1.default.VideoCallSwitchToViewOnly: return "The attendee couldn't start the local video because the maximum video capacity was reached."; case MeetingSessionStatusCode_1.default.VideoCallAtSourceCapacity: return 'The connection failed due to an internal server error.'; case MeetingSessionStatusCode_1.default.SignalingBadRequest: case MeetingSessionStatusCode_1.default.SignalingInternalServerError: case MeetingSessionStatusCode_1.default.SignalingRequestFailed: return 'The signaling connection failed.'; case MeetingSessionStatusCode_1.default.StateMachineTransitionFailed: return 'The state transition failed.'; case MeetingSessionStatusCode_1.default.ICEGatheringTimeoutWorkaround: return 'Gathering ICE candidates timed out. In Chrome, this might indicate that the browser is in a bad state after reconnecting to VPN.'; case MeetingSessionStatusCode_1.default.ConnectionHealthReconnect: return 'The meeting was reconnected.'; case MeetingSessionStatusCode_1.default.RealtimeApiFailed: return 'The real-time API failed. This status code might indicate that the callback you passed to the real-time API threw an exception.'; case MeetingSessionStatusCode_1.default.TaskFailed: return 'The connection failed. See the error message for more details.'; case MeetingSessionStatusCode_1.default.AudioDeviceSwitched: return 'The attendee chose another audio device.'; case MeetingSessionStatusCode_1.default.IncompatibleSDP: return 'The connection failed due to incompatible SDP.'; case MeetingSessionStatusCode_1.default.TURNCredentialsForbidden: return 'The meeting ended, or the attendee was removed.'; case MeetingSessionStatusCode_1.default.NoAttendeePresent: return 'The attendee was not present.'; case MeetingSessionStatusCode_1.default.AudioAttendeeRemoved: return 'The meeting ended because attendee removed.'; /* istanbul ignore next */ default: { // You get a compile-time error if you do not handle any status code. const exhaustiveCheck = this._statusCode; throw new Error(`Unhandled case: ${exhaustiveCheck}`); } } } static fromSignalFrame(frame) { if (frame.error && frame.error.status) { return this.fromSignalingStatus(frame.error.status); } else if (frame.type === SignalingProtocol_js_1.SdkSignalFrame.Type.AUDIO_STATUS) { if (frame.audioStatus) { return this.fromAudioStatus(frame.audioStatus.audioStatus); } return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.SignalingRequestFailed); } return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.OK); } static fromAudioStatus(status) { // TODO: Add these numbers to proto definition and reference them here. switch (status) { case 200: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.OK); case 301: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.AudioJoinedFromAnotherDevice); case 302: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.AudioDisconnectAudio); case 403: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.AudioAuthenticationRejected); case 409: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.AudioCallAtCapacity); case 410: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.MeetingEnded); case 411: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.AudioAttendeeRemoved); case 500: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.AudioInternalServerError); case 503: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.AudioServiceUnavailable); default: switch (Math.floor(status / 100)) { case 2: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.OK); default: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.AudioDisconnected); } } } static fromSignalingStatus(status) { // TODO: Add these numbers to proto definition and reference them here. switch (status) { case 206: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.VideoCallSwitchToViewOnly); case 509: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.VideoCallAtSourceCapacity); default: switch (Math.floor(status / 100)) { case 2: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.OK); case 4: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.SignalingBadRequest); case 5: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.SignalingInternalServerError); default: return new MeetingSessionStatus(MeetingSessionStatusCode_1.default.SignalingRequestFailed); } } } }
JavaScript
class BaseDatasource { fetchRecord(recordId) { throw Error("Unimplemented abstract method."); } }
JavaScript
class NoiseGenerator extends AudioWorkletProcessor { static get parameterDescriptors() { return [{name: 'amplitude', defaultValue: 0.25, minValue: 0, maxValue: 1}]; } process(inputs, outputs, parameters) { const output = outputs[0]; const amplitude = parameters.amplitude; const isAmplitudeConstant = amplitude.length === 1; for (let channel = 0; channel < output.length; ++channel) { const outputChannel = output[channel]; for (let i = 0; i < outputChannel.length; ++i) { // This loop can branch out based on AudioParam array length, but // here we took a simple approach for the demonstration purpose. outputChannel[i] = 2 * (Math.random() - 0.5) * (isAmplitudeConstant ? amplitude[0] : amplitude[i]); } } return true; } }
JavaScript
class PaymentsResource extends Resource { /** * Set the parent * @param {Object} params * @since 2.0.0 */ setParent(params = {}) { if (!params.paymentId && !this.hasParentId()) { throw TypeError('Missing parameter "paymentId".'); } else if (params.paymentId) { this.setParentId(params.paymentId); } } }
JavaScript
class SearchUtils { constructor() { this.path = searchConfig.FOLDERS_CONSTANTS.USER_DATA_PATH; } /** * This function returns true if the available disk space * is more than the constant MINIMUM_DISK_SPACE * @returns {Promise<boolean>} */ checkFreeSpace() { return new Promise((resolve, reject) => { if (!isMac) { try { this.path = this.path.substring(0, 1); } catch (e) { reject(new Error('Invalid Path : ' + e)); } } checkDiskSpace(this.path, resolve, reject); }); } /** * This function return the user search config * @param userId * @returns {Promise<object>} */ getSearchUserConfig(userId) { return new Promise((resolve, reject) => { readFile.call(this, userId, resolve, reject); }); } /** * This function updates the user config file * with the provided data * @param userId * @param data * @returns {Promise<object>} */ updateUserConfig(userId, data) { return new Promise((resolve, reject) => { updateConfig.call(this, userId, data, resolve, reject); }); } }
JavaScript
class ParticleSystem { constructor(scene){ console.log('ParticleSystem()'); this.scene = scene; this.cfg = config.flowers; this.animations = this.cfg.animations; this.geo = ParticleSystem.createParticleGeometry(); this.particles = []; this._fillParticleArray(this.cfg.count); /* this._animate('material.opacity', lifeMoment => { return lifeMoment > 0.5 ? 1.0 : lifeMoment * 2; }); this._animate('scale', (lifeMoment, p) => { var sc = p.__scale; if(lifeMoment > 0.9){ sc *= 1 - (lifeMoment - 0.9) * 10; } p.scale.set(sc,sc,sc); }); */ this._emit(this.cfg.count / 3); } _fillParticleArray(cnt){ var i = this.particles.length; for(; i < cnt; i++){ var material = this._createMaterial(); var p = new Particle(this.geo, material); p.onDie(); this.particles.push(p); this.scene.add(p); } console.log(`particle array has ${this.particles.length} entries`); } _createMaterial(){ var m = this.cfg.material, material = new THREE.MeshLambertMaterial(); _.chain(m) .keys() .filter( k => { return !_.isFunction(m[k]); }) .each( k => { material[k] = m[k]; }); material.transparent = true; return material; } update(){ this._updateExisting(); this._emit(this.cfg.emitRate); } refreshCount(){ this._fillParticleArray(this.cfg.count); } _emit(cnt){ var slotIdx = 0, maxParticles = Math.min(this.cfg.count, this.particles.length); for(var i = 0; i < cnt; i++){ for(; slotIdx < maxParticles; slotIdx++){ var p = this.particles[slotIdx]; if(!p.isAlive()) break; } if(slotIdx < maxParticles){ // console.log('spawn, slot: ', slotIdx); var p = this.particles[slotIdx]; p.onSpawn(this.cfg); ++slotIdx; } else { // console.log('no free particle slot'); break; } } } _updateExisting(){ var windOpt = this.cfg.wind; _.chain(this.particles) .filter( e => {return e.isAlive()} ) .each((p, i) => { var wind = windOpt.force.clone().multiplyScalar(windOpt.speed); p.position.add(wind); p.update(); if(p.life < 0 ){ p.onDie(); } else { this._applyAnimations(p); } }); } _applyAnimations(p){ _.each(this.animations, anim => { var lifeMoment = p.life / p.maxLife; anim.apply(p, lifeMoment); }); } static createParticleGeometry(){ var geo = new THREE.Geometry(); v(0,0,0); v(0,1,0); v(1,0,0); v(1,1,0); f3(0, 2, 1); f3(3, 1, 2); geo.computeFaceNormals(); geo.dynamic = false; return geo; function v(x,y,z) { geo.vertices.push( new THREE.Vector3(x,y,z)); } function f3(a,b,c){ geo.faces .push( new THREE.Face3(a,b,c)); } } }
JavaScript
class SuperClass { /** * Sample function for testing. * * @returns {String} a string */ functionOne() { return 'functionOne'; } /** * Sample function for testing. * * @returns {String} a string */ functionTwo() { return 'functionTwo'; } }
JavaScript
class SubClass extends SuperClass { /** * Sample function for testing. * * @returns {String} a string */ functionThree() { return 'functionThree'; } }
JavaScript
class Scene { /** * constructs a scene * @constructor * @param {number} w - width of the scene * @param {number} h - height of the scene */ constructor(w, h) { // element this.element = document.createElement("canvas"); this.element.style.backgroundColor = "#000"; this.element.style.width = w; this.element.style.height = h; this.ctx = this.element.getContext("2d"); this.clearColor = undefined; // props this.projectionMatrix = Mat4x4.create(); this.objects = []; this.toRaster = []; this.camera = { position: new Vector3(), rotation: new Vector3() }; this.updateProjectionMatrix(0, w, h, 0, 0.1, 100); } /** * Clear the scene * @param {number} _x - starting position on the x-axis * @param {number} _y - starting position on the y-axis * @param {number} _w - width of the clearing rectangle * @param {number} _h - height of the clearing rectangle */ clear(_x, _y, _w, _h) { const x = _x || 0; const y = _y || 0; const w = _w || this.width; const h = _h || this.height; if(this.clearColor) { this.ctx.fillStyle = this.clearColor; this.ctx.fillRect(x, y, w, h); } else this.ctx.clearRect(x, y, w, h) } /** * Rotates the scene: Note that rotation on the y-axis has been diabled * @param {number} x - rotation on the x-axis * @param {number} y - rotation on the y-axis * @param {number} z - rotation on the z-axis */ setRotation(x = 0, y = 0, z = 0) { this.camera.rotation.x = x; this.camera.rotation.y = y; this.camera.rotation.z = z; } set width(w) { this.element.width = w; } set height(h) { this.element.height = h; } get width() { return this.element.width; } get height() { return this.element.height; } /** * Creates an orthographic projection matrix. * as described on { @link https://en.wikipedia.org/wiki/Orthographic_projection } * @param {number} left - leftmost boundary * @param {number} right - rightmost boundary * @param {number} bottom - bottom boundary * @param {number} top - top boundary * @param {number} near - near plane * @param {number} far - farthest distance */ updateProjectionMatrix(left, right, bottom, top, near, far) { this.projectionMatrix[0] = 2 / (right - left); this.projectionMatrix[3] = -(right + left) / (right - left); this.projectionMatrix[5] = 2 / (top - bottom); this.projectionMatrix[7] = -(top + bottom) / (top - bottom); this.projectionMatrix[10] = -2 / (far - near); this.projectionMatrix[11] = -(far + near) / (far - near); this.projectionMatrix[15] = 1; } /** * Adds an object to the scene for rendering and other processes * @param {Mesh} obj - Mesh to be added */ add(obj) { if(!(obj instanceof Mesh)) throw TypeError("You can only Add an instance of a `Mesh` object to the scene"); this.objects.push(obj); } /** * render the scene */ render() { this.toRaster = []; this.objects.forEach(obj => { obj.process(this) }); /** * To raster is an array of objects containing data of triangles * relative to their mesh [projected, color] */ this.toRaster.sort((a, b) => a.zAverage < b.zAverage); let ctx = this.ctx; this.toRaster.forEach((tri, i) => { let saturation = 50; let light = Math.max(20, tri[3] * 50); let v = tri.vertices; let c = tri.color; // show polygon vertex if(tri.showVertex) { ctx.save(); v.forEach((vertex, i) => { ctx.fillStyle = c; ctx.beginPath(); ctx.arc(vertex.x, vertex.y, 2, 0, 2*Math.PI); ctx.closePath(); ctx.fill(); }); ctx.restore(); }; if(tri.showWireFrame || tri.fillShader) { ctx.strokeStyle = tri.wireFrameColor ? tri.wireFrameColor : `hsla(${c.h}, ${c.s}%, ${c.l}%, ${c.a})`; ctx.fillStyle = `hsla(${c.h}, ${c.s}%, ${c.l}%, ${c.a})`; ctx.beginPath(); ctx.moveTo(v[0].x, v[0].y); ctx.lineTo(v[1].x, v[1].y); ctx.lineTo(v[2].x, v[2].y); ctx.closePath(); if(tri.fillShader) ctx.fill(); ctx.stroke(); }; }); // END TO RASTER this.toRaster = []; } }
JavaScript
class AnonymousAuthenticationListener extends implementationOf(ListenerInterface) { /** * Constructor. * * @param {Jymfony.Component.Security.Authentication.Token.Storage.TokenStorageInterface} tokenStorage * @param {string} secret * @param {Jymfony.Component.Logger.LoggerInterface} [logger] * @param {Jymfony.Component.Security.Authentication.AuthenticationManagerInterface} [authenticationManager] */ __construct(tokenStorage, secret, logger = undefined, authenticationManager = undefined) { /** * @type {Jymfony.Component.Security.Authentication.Token.Storage.TokenStorageInterface} * * @private */ this._tokenStorage = tokenStorage; /** * @type {string} * * @private */ this._secret = secret; /** * @type {Jymfony.Component.Logger.LoggerInterface} * * @private */ this._logger = logger || new NullLogger(); /** * @type {undefined|Jymfony.Component.Security.Authentication.AuthenticationManagerInterface} * * @private */ this._authenticationManager = authenticationManager; } /** * @param {Jymfony.Component.HttpServer.Event.GetResponseEvent} event * * @returns {Promise<void>} */ async handle(event) { let token = this._tokenStorage.getToken(event.request); if (!! token) { return; } try { token = new AnonymousToken(this._secret, []); if (this._authenticationManager) { token = await this._authenticationManager.authenticate(token); } this._tokenStorage.setToken(event.request, token); this._logger.info('Populated the TokenStorage with an anonymous Token.'); } catch (e) { if (e instanceof AuthenticationException) { this._logger.info('Anonymous authentication failed.', { exception: e }); } else { throw e; } } } }
JavaScript
class Graph { /** * Create an empty graph with v vertices. * * @param {int} v Number of vertices. */ constructor(v) { this._E = 0; if (v < 0) { throw new Error('Number of vertices must be nonnegative'); } // create empty graph with V vertices this._V = v; this._adj = new Array(v); for (let vrtx = 0; vrtx < v; vrtx++) { this._adj[vrtx] = new Bag(); } } /** * Adds the undirected edge v-w to this graph. * * @param {int} v * @param {int} w * @returns {void} */ addEdge(v, w) { this._validateVertex(v); this._validateVertex(w); this._E++; this._adj[v].add(w); this._adj[w].add(v); } /** * Returns the vertices adjacent to vertex {@code v}. * * @param {int} v * @returns {Iterable<int>} "Iterator"(Bag) for vertices adjacent to v. */ adj(v) { this._validateVertex(v); return this._adj[v]; } /** * Returns the number of vertices in this graph. * * @returns {int} */ V() { return this._V; } /** * Returns the number of edges in this graph. * * @returns {int} */ E() { return this._E; } /** * Throw an error unless {@code 0 <= v < V} * * @param {number} v */ _validateVertex(v) { if (v < 0 || v >= this._V) { throw new Error('No valid vertex'); } } /** * Returns the degree of vertex {@code v}. * * @param {number} v */ degree(v) { this._validateVertex(v); return this._adj[v].size(); } /** * String representation. * * @returns {string} */ toString() { let s = ''; s = `${this._V} vertices, ${this._E} edges.` for (let v = 0; v < this._V; v++) { s = `${s}${v}: `; this._adj[v].entries().forEach(w => { s = `${s}${w}, `; }); s = `${s}.`; } return s; } }
JavaScript
class EventSocketWatchdog extends EventEmitter { constructor(eventSocket, { panicTimeout = 31000, checkInterval = 10000, threshold = 2, heartbeatWorld = 'Jaeger_19' }) { super() this.eventSocket = eventSocket // The socket we're watching this.panicTimeout = panicTimeout // The time in ms before the watchdog should panic this.checkInterval = checkInterval // The time in ms to run watchdog checks this.threshold = threshold // The amount of times we panic before confirming it's a panic. this.heartbeatWorld = heartbeatWorld // The world we care about in heartbeats. All others we don't care about. // This is set to Jaeger by default. Format is Servername_WorldID, e.g. Jaeger_19 // Set state constants this.WAITING = 0 this.WATCHING = 1 this.PANIC = 2 this.FATAL = 3 // See class docstring for this this.state = this.WAITING this.__setDefaults() // Mount heartbeat and close handlers eventSocket.on('heartbeat', this.handleHeartbeat.bind(this)) eventSocket.on('close', this.handleClose.bind(this)) } //// // @private // Sets default attributes. __setDefaults() { this.__lastHeartbeat = null // Last heartbeat Date() this.__lastPanicCounterSeen = 0 // Counter reset value. this.__panicCheckIntv = null // Panic reset interval this.__panicCounter = 0 // Panic counter for threshold. this.__panicReason = null // Last reason for panicing. this.__socketClosed = null // Is socket closed? null or false is a good value. this.__watchdogCheckIntv = null // Watchdog interval this.__watchdogStartTime = null // Watchdog start Date(), used for setup checks } //// // @internal // Smoke-checks the underlying socket for a good state. _earlySetup() { // Check if the socket's readyState is CLOSING (2) or CLOSED (3) if (this.eventSocket.socket.readyState >= 2) { this.__socketClosed = true } } //// // Starts the watchdog. start() { this.state = this.WATCHING this._earlySetup() this.__watchdogStartTime = new Date() this.__watchdogCheckIntv = setInterval(this._watchdogCheck.bind(this), this.checkInterval) //this.__panicCheckIntv = setInterval(this._panicCheck, this.panicTimeout - this.checkInterval) } //// // Stops the watchdog, and resets it's state. stop() { this.state = this.WAITING if (this.__watchdogCheckIntv !== null) { clearInterval(this.__watchdogCheckIntv) } if (this.__panicCheckIntv !== null) { clearInterval(this.__panicCheckIntv) } this.__setDefaults() } //// // @internal // Watchdog runner. Fatals if socket is closed. Panics if successful heartbeat was too far away. _watchdogCheck() { log.debug('running watchdog') // Simplest watchdog step. Socket will not be closed, watchdog here. // This won't panic, it only fatals. if (this.__socketClosed === true || this.eventSocket.socket.readyState >= 2) { this._fatal() return } // In setup mode, the last heartbeat won't be available and the socket won't be closed. if (this.__lastHeartbeat === null && this.__socketClosed !== true) { // We want to make sure we don't stay in setup mode forever, watchdog here. if (this.__watchdogStartTime + this.panicTimeout > Date.now()) { // Timeout is still in the future, return. return } else { // Timeout is in the past, we have to panic here. this._panic('SETUP_TIMEOUT') return } } // Heartbeat is set so we aren't in setup mode anymore. // That heartbeat should have been within panicTimeout of now, watchdog here. if (this.__lastHeartbeat !== null) { if (+this.__lastHeartbeat + this.panicTimeout < Date.now()) { this._panic('HEARTBEAT_TIMEOUT') return } } log.debug('watchdog reached end') } //// // @internal // General panic check, will reset the counter if it hasn't changed in a while. _panicCheck() { if (this.__lastPanicCounterSeen === this.__panicCounter) { this.__panicCounter = 0 log.debug('panic counter reset') } this.__lastPanicCounterSeen = this.__panicCounter } //// // Handles heartbeat events from the eventSocket // // Arguments // d obj{online obj[string]string{}} handleHeartbeat(d) { if (d.online[`EventServerEndpoint_${this.heartbeatWorld}`] === undefined) { log.fatal('heartbeat lacks watchdog server in payload', { lookingFor: this.heartbeatWorld, got: Object.keys(d.online).join(',') }) } else { if (d.online[`EventServerEndpoint_${this.heartbeatWorld}`] === "true") { // Heartbeat has given us good data, let's do it! this.__lastHeartbeat = Date.now() log.debug(`got a heartbeat for ${+this.__lastHeartbeat}`) } else { // If this heartbeat is actually false, it's not data we care about. // We just log and move on. log.warning('heartbeat untrue', d.online) } } } //// // Handles closed events from eventSocket handleClose() { log.warn('handleClose') this.__socketClosed = true } //// // @internal // Report a panic. Unless the counter isn't beyond the threshold, this just counts. // // Arguments // reason str{} _panic(reason) { if(this.__panicCounter >= this.threshold) { log.warn('panic threshold reached', reason) this.__panicReason = reason this.emit('panic', reason) } log.debug('panic', reason) this.__panicCounter = this.__panicCounter + 1 } //// // @internal // Report that the socket has died. We can't do anything else. _fatal() { log.warn('watchdog fatalled') this.stop() this.emit('fatal') } }
JavaScript
class MoonPhasesCard extends HTMLElement { set hass(hass) { if (!this.content) { // Get current date const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1; const day = now.getDate(); // Get current moon phase w/moon entity const entities = this.config.entities; const moonState = hass.states[entities[0]].state; const phase = getMoonPhase(moonState); const sunState = hass.states[entities[1]].state; console.log(`Current phase - ${phase} 🌙`); // Render card let card = document.createElement('ha-card'); this.content = document.createElement('div'); this.content.style.padding = '0 16px 16px'; card.appendChild(this.content); this.appendChild(card); // Styles let style = document.createElement("style"); style.textContent = ` ha-card { color: #FAFAFA; } .header { display: flex; justify-content: space-between; padding: 1em 0; font-weight: bold; } .title, .date { font-size: 1em; } .content { display: flex; align-items: center; justify-content: center; padding-top: 1em; font-weight: bold; } .content a { color: #FAFAFA; text-decoration: none; } .img, .name { padding: 0 1em; } `; card.appendChild(style); // Toggle background based on sun above/below horizon const backgroundColor = (sunState === 'above_horizon' ? '#87CEFA' : '#39006c'); card.style['background-color'] = backgroundColor; // DOM this.content.innerHTML = ` <div class="header"> <div class="title">CURRENT PHASE</div> <div class="date">${month}/${day}/${year}</div> </div> <div class="content"> <img src="/hacsfiles/moon-phases/images/${phase.name}.png" class="img"> <span class="name"><a href="${phase.link}" target="_blank">${phase.name}</a></span> </div> `; } } setConfig(config) { if (!config.entities) { throw new Error('You need to define an entity'); } if (!config.entities[0].includes('moon')) { throw new Error('Moon entity must be included first'); } this.config = config; } }
JavaScript
class LKNSValueCodingProxy extends CACodingProxy { /** * */ static initWithCoder(coder) { //console.log('LKNSValueCodingProxy: ' + JSON.stringify(Object.keys(coder._refObj), null, 2)) const obj = coder._refObj const kind = obj.kind switch(kind) { case 0: { // CGPoint (x, y) return new CGPoint(obj.x, obj.y) } case 1: { // CGSize (width, height) return new CGSize(obj.width, obj.height) } case 2: { // CGRect (x, y, width, height) const point = new CGPoint(obj.x, obj.y) const size = new CGSize(obj.width, obj.height) return new CGRect(point, size) } case 3: { // CATransform3D (m11, m12, ..., m44) break } case 4: { // CAPoint3D (x, y, z) return new CGPoint(obj.x, obj.y) } case 5: { // CADoublePoint (x, y) return new CGPoint(obj.x, obj.y) } case 6: { // CADoubleSize (width, height) return new CGSize(obj.width, obj.height) } case 7: { // CADoubleRect (x, y, width, height) const point = new CGPoint(obj.x, obj.y) const size = new CGSize(obj.width, obj.height) return new CGRect(point, size) } case 8: { // CAColorMatrix (m11, ..., m15, m21, ..., m45) break } } throw new Error('LKNSValueCodingProxy unsupported type: ' + kind) } /** * constructor * @access public * @constructor */ constructor() { super() } }
JavaScript
class Main extends LitElement { image = null; imageByteArray = []; models = []; wsUri = 'ws://localhost:'; wsPort = '8080'; modeloptions = ['GFPGAN', 'ARCANE']; static get styles() { return [ css` .row { display: flex; flex-wrap: wrap; } .column { padding: 7px 0px; } `, boostrapStyle, ]; } render() { return html` <div style="padding: 1%;" class="page-content"> <h1>Hier k&ouml;nnte Ihre Werbung stehen</h1> <div style="padding:7px;" class="row"> <div class="column"> <div style="padding: 7px 0px;"> Upload your image: <input id="inputImage" class="form-control" type="file" value="${this.image || ''}" @change="${this._updateFile}" /> <img id="inputImage-preview" src="" style="width:100%; padding: 5%;" /> </div> <div style="width: 100%;" class="row"> <div class="col-2"> <select name="model" id="model" class="btn btn-primary" width="100%" > ${repeat( this.modeloptions, (option) => html` <option value="${option}">${option}</option> ` )} </select> </div> <div class="col-9"> <button id="submit" type="button" class="btn btn-primary" @click="${this._submit}" style="width: 100%;" > Submit ! </button> </div> </div> </div> <div class="column"> <img id="output-preview" src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg" style="width:100%; padding: 5%;" /> <p id="message"></p> </div> </div> </div> `; } _applyModel = function (model) { this.models.push(model); console.log(this.models); }; _updateFile = function () { // get latest file. let fileInput = this.renderRoot.querySelector('#inputImage'); let file = fileInput.files[0]; console.log(file); this.image = file; console.log(this.image); // preview file. let filePreviewer = this.renderRoot.querySelector('#inputImage-preview'); let reader = this._previewImage(file, filePreviewer); }; _previewImage = function (file, imageComponent) { this._readAsBase64(file, (base64) => { imageComponent.src = base64; }); }; _readAsBase64 = function (file, callback) { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (event) { let base64 = reader.result; callback(base64); }; }; _submit = function () { let messageComponent = this.renderRoot.querySelector('#message'); // --- SEND REQUEST TO CONTROLLER. --------------------------------------- if (!this.image) { messageComponent.innerHTML = ` <span style="color: red; font-weight: bolder;"> Could not upload this image. </span>`; return; } //// with multi model support // if (!this.models || this.models.length < 1) { // this.models = [this.modeloptions[0]]; // console.log('adding default model', this.models); // } // const models = this.models; const extension = this.image.type.split('/').pop(); const models = [this.renderRoot.querySelector('#model').value]; const wsUri = this.wsUri + this.wsPort + '/websocket'; let outputImageComponent = this.renderRoot.querySelector('#output-preview'); this._previewImage(this.image, outputImageComponent); this._readAsBase64(this.image, function (base64) { // max 65.536 let chunks64 = []; let i = 0; const n = base64.length; const chunk = 10000; for (i; i < n; i += chunk) { chunks64.push(base64.slice(i, i + chunk)); } // console.log(chunks64); console.log(`Websocket to '${wsUri}'`); const socket = new WebSocket(wsUri); const sessionkey = '_' + Math.random().toString(36).substr(2, 9); // EXPECTED: // { session: string, img: bytecode, extension: string(png|jpeg|...), models: string[] } socket.addEventListener('open', function (event) { // create request. const request = { session: sessionkey, extension, models: models, count: chunks64.length, }; socket.send(JSON.stringify(request)); console.log('Send request', JSON.stringify(request)); let i = 0; let n = chunks64.length; for (; i < n; i++) { const request0 = { session: sessionkey, index: i, img: chunks64[i], }; socket.send(JSON.stringify(request0)); // console.log('Send request', JSON.stringify(request0)); } }); // EXPECTED: // receive image as string. let receivedMessages = []; let expectedCount = -1; socket.addEventListener('message', function (event) { console.log('Received Message: ' + event.data); const message = JSON.parse(event.data); if (message && message.count) { expectedCount = message.count; } else if (message) { receivedMessages.push(message); } if (receivedMessages.length >= expectedCount) { console.log('Rebuild image. ' + event.data); receivedMessages.sort((a, b) => a.index - b.index); const recvImage = receivedMessages.map((msg) => msg.img).join(""); outputImageComponent.src = recvImage; } }); }); // show state. messageComponent.innerHTML = ` <span style="color: blue; font-weight: normal;"> Uploading ... </span>`; }; }
JavaScript
class Sidebar extends Component { state = {}; toggleMenuState(menuState) { if (this.state[menuState]) { this.setState({[menuState] : false}); } else if(Object.keys(this.state).length === 0) { this.setState({[menuState] : true}); } else { Object.keys(this.state).forEach(i => { this.setState({[i]: false}); }); this.setState({[menuState] : true}); } } componentDidUpdate(prevProps) { if (this.props.location !== prevProps.location) { this.onRouteChanged(); } } onRouteChanged() { document.querySelector('#sidebar').classList.remove('active'); Object.keys(this.state).forEach(i => { this.setState({[i]: false}); }); const dropdownPaths = [ {path:'/apps', state: 'appsMenuOpen'}, {path:'/data-entry', state: 'dataEntryOpen'}, {path:'/admins', state: 'basicUiMenuOpen'}, {path:'/form-elements', state: 'formElementsMenuOpen'}, {path:'/tables', state: 'tablesMenuOpen'}, {path:'/icons', state: 'iconsMenuOpen'}, {path:'/charts', state: 'chartsMenuOpen'}, {path:'/user-pages', state: 'userPagesMenuOpen'}, {path:'/error-pages', state: 'errorPagesMenuOpen'}, ]; dropdownPaths.forEach((obj => { if (this.isPathActive(obj.path)) { this.setState({[obj.state] : true}) } })); } render () { return ( <nav className="sidebar sidebar-offcanvas" id="sidebar"> <div className="text-center sidebar-brand-wrapper d-flex align-items-center"> <a className="sidebar-brand brand-logo" href="#"><img src="/assets/images/logo.svg" alt="logo" /></a> <a className="sidebar-brand brand-logo-mini pt-3" href="#"><img src="/assets/images/logo-mini.svg" alt="logo" /></a> </div> <ul className="nav"> <li className={ this.isPathActive('/appAdmin/dashboard') ? 'nav-item active' : 'nav-item' }> <Link className="nav-link" to="/appAdmin/dashboard"> <i className="mdi mdi-television menu-icon"></i> <span className="menu-title"><>Dashboard</></span> </Link> </li> {/* <li className={ this.isPathActive('/appAdmin/appSettings') ? 'nav-item active' : 'nav-item' }> <div className={ this.state.basicUiMenuOpen ? 'nav-link menu-expanded' : 'nav-link' } onClick={ () => this.toggleMenuState('basicUiMenuOpen') } data-toggle="collapse"> <i className="mdi mdi-crosshairs-gps menu-icon"></i> <span className="menu-title"><>App Settings</></span> <i className="menu-arrow"></i> </div> <Collapse in={ this.state.basicUiMenuOpen }> <ul className="nav flex-column sub-menu"> <li className="nav-item"> <Link className={ this.isPathActive('/appAdmin/app-setting-menubar') ? 'nav-link active' : 'nav-link' } to="/appAdmin/app-setting-menubar"><>Menubar</></Link></li> <li className="nav-item"> <Link className={ this.isPathActive('/appAdmin/appSettings/') ? 'nav-link active' : 'nav-link' } to="/appAdmin/appSettings"><>Dropdowns</></Link></li> </ul> </Collapse> </li> */} { isSuperAdmin ? <li className={ this.isPathActive('/appAdmin/admins') ? 'nav-item active' : 'nav-item' }> <Link className="nav-link" to="/appAdmin/admins"> <i className="mdi mdi-crosshairs-gps menu-icon"></i> <span className="menu-title"><>Admins</></span> </Link> </li> : null } <li className={ this.isPathActive('/appAdmin/companies') ? 'nav-item active' : 'nav-item' }> <Link className="nav-link" to="/appAdmin/companies"> <i className="mdi mdi-crosshairs-gps menu-icon"></i> <span className="menu-title"><>Company Managment</></span> </Link> </li> {/* <li className={ this.isPathActive('/basic-ui') ? 'nav-item active' : 'nav-item' }> <Link className="nav-link" to="/appAdmin/users"> <i className="mdi mdi-crosshairs-gps menu-icon"></i> <span className="menu-title"><>Softwares Managment</></span> </Link> </li> <li className={ this.isPathActive('/basic-ui') ? 'nav-item active' : 'nav-item' }> <Link className="nav-link" to="/appAdmin/users"> <i className="mdi mdi-crosshairs-gps menu-icon"></i> <span className="menu-title"><>Services Managment</></span> </Link> </li> */} <li className={ this.isPathActive('/appAdmin/data-entry') ? 'nav-item active' : 'nav-item' }> <div className={ this.state.dataEntryOpen ? 'nav-link menu-expanded' : 'nav-link' } onClick={ () => this.toggleMenuState('dataEntryOpen') } data-toggle="collapse"> <i className="mdi mdi-crosshairs-gps menu-icon"></i> <span className="menu-title"><>Data Entry</></span> <i className="menu-arrow"></i> </div> <Collapse in={ this.state.dataEntryOpen }> <ul className="nav flex-column sub-menu"> <li className="nav-item"> <Link className={ this.isPathActive('/appAdmin/data-entry-software-categories') ? 'nav-link active' : 'nav-link' } to="/appAdmin/data-entry-software-categories"><>Software Categories</></Link></li> {/* <li className="nav-item"> <Link className={ this.isPathActive('/appAdmin/appSettings/') ? 'nav-link active' : 'nav-link' } to="/appAdmin/appSettings"><>Dropdowns</></Link></li> */} </ul> </Collapse> </li> </ul> </nav> ); } isPathActive(path) { return this.props.location.pathname.startsWith(path); } componentDidMount() { this.onRouteChanged(); // add className 'hover-open' to sidebar navitem while hover in sidebar-icon-only menu const body = document.querySelector('body'); document.querySelectorAll('.sidebar .nav-item').forEach((el) => { el.addEventListener('mouseover', function() { if(body.classList.contains('sidebar-icon-only')) { el.classList.add('hover-open'); } }); el.addEventListener('mouseout', function() { if(body.classList.contains('sidebar-icon-only')) { el.classList.remove('hover-open'); } }); }); } }
JavaScript
class StatefulPager extends React.Component { static displayName = 'StatefulPager'; static propTypes = { steps: PropTypes.number.isRequired, onChange: PropTypes.func, defaultValue: PropTypes.number, } static defaultProps = { defaultValue: 0, onChange: e => e, } state = { value: this.props.defaultValue, } onChange = (value) => { this.props.onChange(value); this.setState({ value }); } render() { return (<Pager {...this.props} current={this.state.value} onChange={this.onChange} />); } }
JavaScript
class TwilioFormatter { /** * Class constructor * @returns {TwilioFormatter} - the TwilioFormatter object */ constructor () { } /** * Generate a Twilio XML MessagingResponse from an array of messages * @param {Array<string>} messages - an array of SMS messages to be sent * @param {boolean} numberMessages - (optional) whether or not to number messages before formatting (default: true) * @returns {MessagingResponse} - the formatted MessageResponse */ format (messages, numberMessages = true) { let validatedMessages; if (numberMessages) { const numberedMessages = this.numberMessages(messages); validatedMessages = this.validateMessages(numberedMessages); } else { validatedMessages = this.validateMessages(messages); } const messagingResponse = new MessagingResponse(); for (let msg of validatedMessages) { messagingResponse.message(msg); } return messagingResponse; } /** * Add numbering prefixes (e.g., "[1 of 5] ") to collections of more than one message * @param {Array<string>} messages - messages to be numbered * @returns {Array<string>} - array of numbered messages */ numberMessages (messages) { if (messages.length === 1) return messages; return messages.map((message, idx, ary) => `[${idx + 1} of ${ary.length}] ${message}`); } /** * Validate messages for length, and truncate if needed * @param {Array<string>} messages - messages to be validated * @returns {Array<string>} - the validated (and truncated if needed) messages */ validateMessages (messages) { const validatedMessages = []; for (let msg of messages) { if (msg.length > TwilioFormatter.MAX_MESSAGE_SIZE) { console.error(`ERROR SENDING MESSAGE: Message length of ${msg.length} exceeds Twilio message character limit of 1600 characters for message "${msg}"`); } validatedMessages.push(msg.substring(0, TwilioFormatter.MAX_MESSAGE_SIZE)); } return validatedMessages; } }
JavaScript
@withStyles(styles) class ChannelSearchInput extends Component { render () { var inputClass = (this.props.type == "large" ? "topcoat-text-input" : "topcoat-text-input--large"); inputClass += (this.props.className ? " " + this.props.className : ""); return ( <div className="ChannelSearchInput"> <input className={inputClass} type="text" placeholder="Search for channels" onChange={this.props.handleChange} onPaste={this.props.handleChange} > </input> </div> ) } }
JavaScript
class CompositeArchiveLoader { /** * Create the CompositeArchiveLoader. Used to delegate to a set of ArchiveLoaders. */ constructor() { this.archiveLoaders = []; } /** * Adds a ArchiveLoader implemenetation to the ArchiveLoader * @param {ArchiveLoader} archiveLoader - The archive to add to the CompositeArchiveLoader */ addArchiveLoader(archiveLoader) { this.archiveLoaders.push(archiveLoader); } /** * Get the array of ArchiveLoader instances * @return {ArchiveLoaders[]} The ArchiveLoader registered * @private */ getArchiveLoaders() { return this.archiveLoaders; } /** * Remove all registered ArchiveLoaders */ clearArchiveLoaders() { this.archiveLoaders = []; } /** * Returns true if this ArchiveLoader can process the URL * @param {string} url - the URL * @return {boolean} true if this ArchiveLoader accepts the URL * @abstract */ accepts(url) { for (let n = 0; n < this.archiveLoaders.length; n++) { const ml = this.archiveLoaders[n]; if (ml.accepts(url)) { return true; } } return false; } /** * Load a Archive from a URL and return it * @param {string} url - the url to get * @param {object} options - additional options * @return {Promise} a promise to the Archive */ load(url, options) { for (let n = 0; n < this.archiveLoaders.length; n++) { const ml = this.archiveLoaders[n]; if (ml.accepts(url)) { return ml.load(url, options); } } throw new Error('Failed to find a model file loader that can handle: ' + url); } }
JavaScript
class UpdatePhonesScreen extends Component { constructor(props) { super(props); const { params } = props.navigation.state; this.state = { name: params ? params.name : null, phone: params ? params.phone : null, number: params ? params.phone.number : null }; } /** * * @method UpdatePhonesScreen#update * @description Method that update a customer's phone from the database. */ update() { let props = this.props; let id = this.state.phone.id; let number = this.state.number; let db = SQLite.openDatabase('syncapp', '1.0', 'SyncApp Database', 200000, this.openCB, this.errorCB); db.executeSql('UPDATE phone SET number = ? WHERE id = ?;', [number, id]); Events.publish('RefreshNumbers'); props.navigation.goBack(); } errorCB(err) { console.error("SQLite3 Error: " + err); } openCB() { console.log("Database OPENED"); } render() { let props = this.props; return ( <Container> <Header> <Left> <Button transparent onPress={() => props.navigation.goBack()}> <Icon name='arrow-back' /> </Button> </Left> <Body> <Title>{this.state.name}</Title> </Body> <Right /> </Header> <Content> <Form> <Item floatingLabel last> <Label>Telefone</Label> <Input value={this.state.number} onChangeText={(number) => this.setState({ number })} /> </Item> </Form> <View style={{ margin: 15 }}> <Button full danger onPress={ () => { Keyboard.dismiss(); this.update(); } } > <Text>Atualizar</Text> </Button> </View> </Content> </Container> ); } }
JavaScript
class ProcessUtils { /** * From a "complex" JSON Schema with allOf/anyOf/oneOf, make separate schemas. * * So afterwards each schema has it's own array entry. * It merges allOf, resolves anyOf/oneOf into separate schemas. * May also split the JSON Schema type arrays into separate entries by setting `splitTypes` to `true`. * * @param {object|array} schemas - The JSON Schema(s) to convert * @returns {array} */ static normalizeJsonSchema(schemas, splitTypes = false) { // Make schemas always an array if (Utils.isObject(schemas)) { schemas = [schemas]; } else if (Array.isArray(schemas)) { schemas = schemas; } else { schemas = []; } // Merge allOf, resolve anyOf/oneOf into separate schemas let normalized = []; for(let schema of schemas) { if (Array.isArray(schema.allOf)) { normalized.push(Object.assign({}, ...schema.allOf)); } else if (Array.isArray(schema.oneOf) || Array.isArray(schema.anyOf)) { let copy = Utils.omitFromObject(schema, ['oneOf', 'anyOf']); let subSchemas = schema.oneOf || schema.anyOf; for(let subSchema of subSchemas) { normalized.push(Object.assign({}, copy, subSchema)); } } else { normalized.push(schema); } } if (!splitTypes) { return normalized; } // Split type field into separate schemas schemas = []; for(let schema of normalized) { if (Array.isArray(schema.type)) { /* jshint ignore:start */ schemas = schemas.concat(schema.type.map(type => Object.assign({}, schema, {type: type}))); /* jshint ignore:end */ } else { schemas.push(schema); } } return schemas; } /** * Returns the callback parameters for a given process parameter. * * @param {object} processParameter - The process parameter spec to parse. * @returns {array} * @throws {Error} */ static getCallbackParameters(processParameter, keyPath = []) { if (!Utils.isObject(processParameter) || !processParameter.schema) { return []; } let schemas = ProcessUtils.normalizeJsonSchema(processParameter.schema); let key; while(key = keyPath.shift()) { // jshint ignore:line schemas = schemas.map(schema => ProcessUtils.normalizeJsonSchema(ProcessUtils.getElementJsonSchema(schema, key))); // jshint ignore:line schemas = schemas.concat(...schemas); } let cbParams = []; for(let schema of schemas) { if (Array.isArray(schema.parameters)) { if (cbParams.length > 0 && !Utils.equals(cbParams, schema.parameters)) { throw new Error("Multiple schemas with different callback parameters found."); } cbParams = schema.parameters; } } return cbParams; } /** * Returns the callback parameters for a given process parameter from a full process spec. * * @param {object} process - The process to parse. * @param {string} parameterName - The name of the parameter to get the callback parameters for. * @returns {array} * @throws {Error} */ static getCallbackParametersForProcess(process, parameterName, path = []) { if (!Utils.isObject(process) || !Array.isArray(process.parameters)) { return []; } let param = process.parameters.find(p => p.name === parameterName); return ProcessUtils.getCallbackParameters(param, path); } /** * Returns *all* the native JSON data types allowed for the schema. * * @param {object} schema * @param {boolean} anyIsEmpty * @returns {array} */ static getNativeTypesForJsonSchema(schema, anyIsEmpty = false) { if (Utils.isObject(schema) && Array.isArray(schema.type)) { // Remove duplicate and invalid types let validTypes = Utils.unique(schema.type).filter(type => ProcessUtils.JSON_SCHEMA_TYPES.includes(type)); if (validTypes.length > 0 && validTypes.length < ProcessUtils.JSON_SCHEMA_TYPES.length) { return validTypes; } else { return anyIsEmpty ? [] : ProcessUtils.JSON_SCHEMA_TYPES; } } else if (Utils.isObject(schema) && typeof schema.type === 'string' && ProcessUtils.JSON_SCHEMA_TYPES.includes(schema.type)) { return [schema.type]; } else { return anyIsEmpty ? [] : ProcessUtils.JSON_SCHEMA_TYPES; } } /** * Returns the schema for a property of an object or an element of an array. * * If you want to retrieve the schema for a specific key, use the parameter `key`. * * @param {object} schema - The JSON schema to parse. * @param {string|integer|null} key - If you want to retrieve the schema for a specific key, otherwise null. * @returns {object} - JSON Schema */ static getElementJsonSchema(schema, key = null) { let types = ProcessUtils.getNativeTypesForJsonSchema(schema); if (Utils.isObject(schema) && types.includes('array') && typeof key !== 'string') { if (Utils.isObject(schema.items)) { // Array with one schema for all items: https://json-schema.org/understanding-json-schema/reference/array.html#id5 return schema.items; } else if (Array.isArray(schema.items)) { // Tuple validation: https://json-schema.org/understanding-json-schema/reference/array.html#id6 if (key !== null && Utils.isObject(schema.items[key])) { return schema.items[key]; } else if (Utils.isObject(schema.additionalItems)) { return schema.additionalItems; } } } if (Utils.isObject(schema) && types.includes('object')) { if (key !== null && Utils.isObject(schema.properties) && Utils.isObject(schema.properties[key])) { return schema.properties[key]; } else if (Utils.isObject(schema.additionalProperties)) { return schema.additionalProperties; } // ToDo: No support for patternProperties yet } return {}; } }
JavaScript
class ASTNode { /* constructor() { // this.type = void(0); // this.value = 0; // this.left = null; // this.right = null; } */ static createNode(type, left, right) { const node = new ASTNode(); node.type = type; node.left = left; node.right = right; return node; } static createUnaryNode(left) { const node = new ASTNode(); node.type = 'unaryMinus'; node.left = left; node.right = null; return node; } static createLeaf(value) { const node = new ASTNode(); node.type = 'number'; node.value = value; return node; } }
JavaScript
class Car extends React.Component { constructor(props){ super(props); this.state = { name: "Centuary one", brand: "Meina ", yearLaunched: 2039, model: 9, color: "Inspiron Blue" }; } componentDidMount() { setTimeout(() =>{ this.setState({color: "Naya Color"}) }, 2000); } // static getDerivedStateFromProps(props, state) { // return {color: props.carColor}; // } render(){ return ( <div align="center"> <h1>My {this.state.brand+" "+this.state.name}</h1> <p> it is a model {this.state.model} , shinning in {this.state.color} </p> </div> ); } }