language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class numbers { math = create(all, { number: 'BigNumber', precision: 64, }); constructor() {} fromDayMonthYear(date) { let mom = moment().dayOfYear(date.day) mom.set('hour', date.hour) mom.set('year', date.year) return mom.format('ddd, hA') } fromSmartContractTimeToMinutes(time) { return dayjs.unix(time).toDate(); } fromMinutesToSmartContracTime(time) { return time } fromHex(hex){ return hex.toString(); } toFloat(number) { return parseFloat(parseFloat(number).toFixed(2)) } timeToSmartContractTime(time) { return parseInt(new Date(time).getTime() / 1000) } toDate(date) { let mom = moment().dayOfYear(date.day) mom.set('hour', date.hour) mom.set('year', date.year) return mom.unix() } toMoney(number) { var _0xbea8=["\x45\x55\x52","\x25\x76","\x66\x6F\x72\x6D\x61\x74\x4D\x6F\x6E\x65\x79"];return accounting[_0xbea8[2]](number,{symbol:_0xbea8[0],format:_0xbea8[1]}) } formatNumber(number) { return accounting.formatNumber(number) } /** * @function toSmartContractDecimals * @description Converts a "human" number to the minimum unit. * @param {Float} value The number that you want to convert * @param {Integer} decimals Number of decimals * @returns {string} */ toSmartContractDecimals(value, decimals) { return this.math.chain(this.math.bignumber(value)).multiply(this.math.bignumber(10 ** decimals)).done().toFixed(0); } /** * @function fromDecimals * @description Converts a number from his minimum unit to a human readable one. * @param {Float} value The number that you want to convert * @param {Integer} decimals Number of decimals * @returns {string} */ fromDecimals(value, decimals) { if (value == null) { return 0; } return this.math.chain( this.math.bignumber(value.toString())).divide(this.math.bignumber(10 ** decimals) ).toString(); } fromExponential(x) { var _0xe3ed=["\x61\x62\x73","\x65\x2D","\x73\x70\x6C\x69\x74","\x70\x6F\x77","\x30\x2E","\x30","\x6A\x6F\x69\x6E","\x73\x75\x62\x73\x74\x72\x69\x6E\x67","\x2B"];if(Math[_0xe3ed[0]](x)< 1.0){var e=parseInt(x.toString()[_0xe3ed[2]](_0xe3ed[1])[1]);if(e){x*= Math[_0xe3ed[3]](10,e- 1);x= _0xe3ed[4]+ new Array(e)[_0xe3ed[6]](_0xe3ed[5])+ x.toString()[_0xe3ed[7]](2)}}else {var e=parseInt(x.toString()[_0xe3ed[2]](_0xe3ed[8])[1]);if(e> 20){e-= 20;x/= Math[_0xe3ed[3]](10,e);x+= new Array(e+ 1)[_0xe3ed[6]](_0xe3ed[5])}};return x } }
JavaScript
class FooterNav extends Component { handleClick() { hashHistory.push('/counter') } render() { return ( <Paper zDepth={1}> <BottomNavigation selectedIndex={ 0 }> <BottomNavigationItem label="Logout" icon={ logoutIcon } onClick={ this.handleClick.bind() } /> </BottomNavigation> </Paper> ); } }
JavaScript
class uiProxy extends assignableProxyHandler{ constructor(assignable){ super(assignable); } /** * Factory method. * @param {Proxy} parentProxy * @param {String} parentProperty */ static new(parentProxy, parentProperty,assignable){ return new Proxy(new uiProxy(), new uiProxyHandler(parentProxy,parentProperty,assignable)); } }
JavaScript
class Tree extends Text { static get properties () { return { selectionColor: { type: 'ColorGradient', defaultValue: Color.rgb(21, 101, 192) }, fontFamily: { defaultValue: config.codeEditor.defaultStyle.fontFamily }, nativeCursor: { defaultValue: 'auto' }, selectable: { defaultValue: false }, acceptsDrops: { defaultValue: false }, fixedWidth: { defaultValue: true }, fixedHeight: { defaultValue: true }, disableIndent: { defaultValue: false }, activateOnHover: { defaultValue: true }, readOnly: { defaultValue: true }, lineHeight: { defaultValue: 1.5 }, clipMode: { defaultValue: 'auto' }, padding: { defaultValue: Rectangle.inset(3) }, master: { initialize () { this.master = { auto: 'styleguide://SystemWidgets/tree/light' }; } }, resizeNodes: { defaultValue: false, set (val) { this.setProperty('resizeNodes', val); this.resetCache(); this.update(); } }, treeData: { after: ['selection'], set (val) { this.setProperty('treeData', val); this.resetCache(); this.update(); } }, selectedIndex: { derived: true, after: ['selectedNode', 'nodes'], get () { return this.selectedNode ? this.nodes.indexOf(this.selectedNode) : -1; }, set (i) { this.selectedNode = this.nodes[i]; } }, nodes: { derived: true, after: ['treeData'], get () { return this.treeData.asList(); } }, defaultViewState: { get () { return { ...super.prototype.defaultViewState, fastScroll: false }; } }, selectedNode: { set (sel) { this.setProperty('selectedNode', sel); this.update(); } }, selectedNodeAndSiblings: { readOnly: true, derived: true, after: ['selectedNode', 'treeData'], get () { return this.selectedNode ? this.treeData.nodeWithSiblings(this.selectedNode) : []; } }, selectionFontColor: { isStyleProp: true, defaultValue: Color.white, set (c) { this.setProperty('selectionFontColor', c); } }, nonSelectionFontColor: { isStyleProp: true, defaultValue: Color.rgbHex('333'), set (c) { this.setProperty('nonSelectionFontColor', c); } }, nodeItemContainer: { derived: true, readOnly: true, after: ['submorphs'], get () { return this; } }, nodeMorphs: { derived: true, readOnly: true, after: ['submorphs'], get () { return this.nodeItemContainer.submorphs.slice(); } } }; } constructor (props = {}) { if (!props.treeData) { throw new Error('Cannot create tree without TreeData!'); } super(props); this.resetCache(); this.update(); } onChange (change) { super.onChange(change); if (['fontSize', 'fontColor', 'selectionColor', 'disableIndent', 'nonSelectionFontColor', 'selectionFontColor'].includes(change.prop)) { this.update(true); } } resetCache () { this._lineHeightCache = null; } get isTree () { return true; } get nodeStyle () { return { fontFamily: this.fontFamily, fontSize: this.fontSize, fontWeight: this.fontWeight, autofit: !this.resizeNodes }; } lineBounds (idx) { let charBounds = this.textLayout.charBoundsOfRow(this, idx); let tl = Rectangle.fromLiteral(arr.first(charBounds)).topLeft(); let br = Rectangle.fromLiteral(arr.last(charBounds)).bottomRight(); return Rectangle.fromAny(tl, br); } recoverOriginalLine (row) { let attrs = this.document.getTextAndAttributesOfLine(row); for (let i = 0; i < attrs.length; i++) { let fontColor = this._originalColor[i]; if (!fontColor || obj.isString(attrs[i])) continue; if (attrs[i]) { attrs[i].fontColor = fontColor; } else { attrs[i] = { fontColor }; } } this.document.setTextAndAttributesOfLine(row, attrs); } renderSelectedLine (row) { let attrs = this.document.getTextAndAttributesOfLine(row); this._originalColor = new Array(attrs.length); for (let i = 0; i < attrs.length; i++) { if ((i % 2) === 0) { if (attrs[i] && attrs[i].isMorph) { this._originalColor[i] = attrs[i] ? attrs[i].fontColor || this.nonSelectionFontColor : null; attrs[i].fontColor = this.selectionFontColor; attrs[i].isSelected = true; continue; } else { continue; } } this._originalColor[i] = (attrs[i] ? attrs[i].fontColor : null) || this.nonSelectionFontColor; if (attrs[i]) { attrs[i].fontColor = this.selectionFontColor; } else { attrs[i] = { fontColor: this.selectionFontColor }; } } this.document.setTextAndAttributesOfLine(row, attrs); this.selectLine(row, true); this._lastSelectedIndex = row + 1; } computeTreeAttributes (nodes) { if (!nodes.length) return []; let containerTextAndAttributes = arr.genN(8 * (nodes.length - 1), () => undefined); let i = 1; let j; let isSelected; let toggleWidth = this.disableIndent ? 0 : this.fontSize * 1.3; let offset = 0; const { selectedIndex } = this; for (; i < nodes.length; i++) { j = 8 * (i - 1) + offset; isSelected = selectedIndex == i; nodes[i].node.isSelected = isSelected; // indent containerTextAndAttributes[j] = ' '; containerTextAndAttributes[j + 1] = { fontSize: toggleWidth, fontColor: Color.transparent, textStyleClasses: ['fas'], paddingRight: (toggleWidth * (nodes[i].depth - 1)) + 'px' }; // toggle containerTextAndAttributes[j + 3] = { fontColor: Color.transparent, textStyleClasses: ['fas'], paddingTop: (this.fontSize / 10) + 'px', paddingRight: (this.fontSize / 8) + 'px' }; if (!this.treeData.isLeaf(nodes[i].node)) { containerTextAndAttributes[j + 2] = this.treeData.isCollapsed(nodes[i].node) ? ' \uf0da ' : ' \uf0d7 '; Object.assign( containerTextAndAttributes[j + 3], { paddingRight: this.treeData.isCollapsed(nodes[i].node) ? `${this.fontSize / 4}px` : '0px', paddingTop: '0px', nativeCursor: 'pointer', fontColor: this.fontColor }); } else { containerTextAndAttributes[j + 2] = this.disableIndent ? '' : ' '; } // node let displayedNode = this.treeData.safeDisplay(nodes[i].node); if (displayedNode.isMorph) { if (displayedNode._capturedProps) { Object.assign(displayedNode, displayedNode._capturedProps); } if (isSelected) { displayedNode._capturedProps = obj.select(displayedNode, ['fontColor']); } displayedNode.fontColor = this.nonSelectionFontColor; } if (arr.isArray(displayedNode)) { displayedNode = arr.flatten(displayedNode); arr.pushAllAt(containerTextAndAttributes, displayedNode, j + 4); const increment = Math.max(0, displayedNode.length - 2); j += increment; offset += increment; } else { containerTextAndAttributes[j + 4] = displayedNode; containerTextAndAttributes[j + 5] = { fontColor: this.fontColor }; } containerTextAndAttributes[j + 6] = '\n'; containerTextAndAttributes[j + 7] = {}; } containerTextAndAttributes.push(' ', { fontSize: this.fontSize * 1.3, textStyleClasses: ['far'] }); containerTextAndAttributes = containerTextAndAttributes.filter(v => typeof v !== 'undefined'); return nodes.length > 1 ? containerTextAndAttributes : []; } update (force) { // fixme: this method should only be used in cases, where the tree data is replaced. // When collapsing/uncollapsing nodes, we should insert, remove ranges of the text // which makes for a faster rendering of the tree. if (this._updating || !this.treeData || !this.nodeItemContainer) return; this._updating = true; try { this.withMetaDo({ isLayoutAction: true }, () => { let { treeData, padding, extent, resizeNodes, nodeMorphs, selectedNode } = this; let nodes = treeData.asListWithIndexAndDepth(); let treeDataRestructured = this.treeData !== this.lastTreeData || this.lastNumberOfNodes !== nodes.length; let row, attrs; if (treeDataRestructured || force) { this.replace( { start: { row: 0, column: 0 }, end: this.documentEndPosition }, this.computeTreeAttributes(nodes), false, false); this.invalidateTextLayout(true, false); this.whenRendered().then(async () => { this.makeDirty(); }); } else if (this._lastSelectedIndex) { this.recoverOriginalLine(this._lastSelectedIndex - 1); } this.lastTreeData = this.treeData; this.lastNumberOfNodes = nodes.length; this.cursorPosition = { row: 0, column: 0 }; if (this.selectedIndex > 0) { this.renderSelectedLine(this.selectedIndex - 1); } else { const selection = this.getProperty('selection'); if (selection && !selection.isEmpty()) { selection.collapse(selection.lead); } } }); } finally { this._updating = false; } } buildViewState (nodeIdFn) { if (typeof nodeIdFn !== 'function') { nodeIdFn = node => node; } let selId = this.selectedNode ? nodeIdFn(this.selectedNode) : null; let collapsedMap = new Map(); tree.prewalk(this.treeData.root, node => collapsedMap.set(nodeIdFn(node), this.treeData.isCollapsed(node)), node => this.treeData.getChildrenIfUncollapsed(node)); return { selectionId: selId, collapsedMap, scroll: this.scroll }; } async applyViewState (viewState, nodeIdFn) { if (typeof nodeIdFn !== 'function') { nodeIdFn = node => node; } let { selectionId, collapsedMap, scroll } = viewState; let i = 0; let newSelIndex = -1; while (true) { let nodes = this.nodes; if (i >= nodes.length) break; let id = nodeIdFn(nodes[i]); if (selectionId === id) newSelIndex = i; if (collapsedMap.has(id) && !collapsedMap.get(id)) { await this.treeData.collapse(nodes[i], false); } i++; } this.selectedIndex = newSelIndex; this.update(); this.scroll = scroll; this.scrollSelectionIntoView(); await promise.delay(0); } async maintainViewStateWhile (whileFn, nodeIdFn) { // keeps the scroll, selection, and node collapse state, useful when updating the list // specify a nodeIdFn to compare old and new nodes, useful when you // generate a new tree but still want to have the same elements uncollapsed in // the new. let viewState = this.buildViewState(nodeIdFn); await whileFn(); await this.applyViewState(viewState, nodeIdFn); } async onNodeCollapseChanged ({ node, isCollapsed }) { this.resetCache(); try { await this.treeData.collapse(node, isCollapsed); signal(this, 'nodeCollapseChanged', { node, isCollapsed }); this.update(); // this perform cut/paste of the node contents instead of a brute force update } catch (e) { this.showError(e); } } async uncollapse (node = this.selectedNode) { if (!node || !this.treeData.isCollapsed(node)) return; await this.onNodeCollapseChanged({ node, isCollapsed: false }); return node; } async collapse (node = this.selectedNode) { if (!node || this.treeData.isCollapsed(node)) return; await this.onNodeCollapseChanged({ node, isCollapsed: true }); return node; } selectedPath () { return this.treeData.pathOf(this.selectedNode); } async selectPath (path) { return this.selectedNode = await this.treeData.followPath(path); } gotoIndex (i) { this.selectedNode = this.nodes[i]; this.scrollIndexIntoView(i); } scrollSelectionIntoView () { this.selectedNode && this.scrollIndexIntoView(this.selectedIndex); } scrollIndexIntoView (idx) { this.scrollToIndex(idx, 'into view'); } centerSelection () { this.selectedNode && this.scrollToIndex(this.selectedIndex, 'center'); } scrollToIndex (idx) { this.scrollPositionIntoView({ row: idx - 1, column: 0 }); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // event handling // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- contextMenuForNode (node, evt) { signal(this, 'contextMenuRequested', { node, evt }); } onKeyDown (evt) { let w = this.world(); let f = w.focusedMorph; // to not steal keys from inner morphs if (f.isText && !f.readOnly) return; return super.onKeyDown(evt); } onDragStart (evt) { super.onDragStart(evt); let { onDragStart, onDrag, onDragEnd } = this.textAttributeAtPoint(evt.positionIn(this)) || {}; if (onDrag) this._onDragHandler = onDrag; if (onDragEnd) this._onDragEndHandler = onDragEnd; if (onDragStart) onDragStart(evt); } onDrag (evt) { // allow text attributes to be dragged instead if (this._onDragHandler) this._onDragHandler(evt); else super.onDrag(evt); } onDragEnd (evt) { super.onDragEnd(evt); delete this._onDragHandler; if (this._onDragEndHandler) this._onDragEndHandler(evt); delete this._onDragEndHandler; } async onMouseDown (evt) { // super.onMouseDown(evt); let { row, column } = this.textPositionFromPoint(evt.positionIn(this)); let clickedNode = this.nodes[row + 1]; if (!clickedNode) return; if (!this.treeData.isLeaf(clickedNode) && column < 4) { await clickedNode.isCollapsed ? this.uncollapse(clickedNode) : this.collapse(clickedNode); } else { if (this.selectedIndex != row + 1) { this.selectedIndex = row + 1; } } // check for defined onMouseDown in attributes let { onMouseDown } = this.textAttributeAt({ row, column }) || {}; if (onMouseDown) onMouseDown(evt); } onMouseUp (evt) { super.onMouseUp(evt); let { onMouseUp } = this.textAttributeAtPoint(evt.positionIn(this)) || {}; if (onMouseUp) onMouseUp(evt); } onHoverIn (evt) { super.onHoverIn(evt); if (this.activateOnHover) { this.clipMode = 'auto'; } } onHoverOut (evt) { super.onHoverOut(evt); if (touchInputDevice) return; if (this.activateOnHover) { this.clipMode = 'hidden'; } } onContextMenu (evt) { if (evt.targetMorph !== this) return; evt.stop(); let { row, column } = this.textPositionFromPoint(evt.positionIn(this)); let clickedNode = this.nodes[row + 1]; if (!clickedNode) return; this.contextMenuForNode(clickedNode, evt); } get keybindings () { return [ { keys: 'Up|Ctrl-P', command: 'select node above' }, { keys: 'Down|Ctrl-N', command: 'select node below' }, { keys: 'Left', command: 'collapse selected node' }, { keys: 'Right', command: 'uncollapse selected node' }, { keys: 'Alt-V|PageUp', command: 'page up' }, { keys: 'Ctrl-V|PageDown', command: 'page down' }, { keys: 'Alt-Shift-,', command: 'goto first item' }, { keys: 'Alt-Shift-.', command: 'goto last item' }, { keys: 'Alt-Space', command: 'select via filter' }, { keys: 'Ctrl-L', command: 'realign top-bottom-center' }, { keys: { mac: 'Meta-[', win: 'Ctrl-[' }, command: { command: 'collapse or uncollapse all siblings', args: { what: 'collapse' } } }, { keys: { mac: 'Meta-]', win: 'Ctrl-]' }, command: { command: 'collapse or uncollapse all siblings', args: { what: 'uncollapse' } } }, { keys: 'Alt-N', command: 'goto next sibling' }, { keys: 'Alt-P', command: 'goto prev sibling' }, { keys: 'Alt-U', command: 'goto parent' } ]; // .concat(super.keybindings); } get commands () { return treeCommands; } highlightChangedNodes (treeData) { /* highlights all visible nodes that contain different information to their (location-wise) counterparts in 'treeData'. */ let changedNodes = this.treeData.diff(treeData); changedNodes.forEach(([n, _]) => n.renderedNode && n.renderedNode.highlight()); } }
JavaScript
class BaseNotificationService extends BaseService { constructor() { super() } getIdentifier() { return this.constructor.identifier } /** * Used to retrieve documents related to a shipment. */ sendNotification(event, data) { throw new Error("Must be overridden by child") } resendNotification(notification, config = {}) { throw new Error("Must be overridden by child") } }
JavaScript
class CreateCheckoutPaymentRequest extends BaseModel { /** * @constructor * @param {Object} obj The object passed to constructor */ constructor(obj) { super(obj); if (obj === undefined || obj === null) return; this.acceptedPaymentMethods = this.constructor.getValue(obj.acceptedPaymentMethods || obj.accepted_payment_methods); this.acceptedMultiPaymentMethods = this.constructor.getValue(obj.acceptedMultiPaymentMethods || obj.accepted_multi_payment_methods); this.successUrl = this.constructor.getValue(obj.successUrl || obj.success_url); this.defaultPaymentMethod = this.constructor.getValue(obj.defaultPaymentMethod || obj.default_payment_method); this.gatewayAffiliationId = this.constructor.getValue(obj.gatewayAffiliationId || obj.gateway_affiliation_id); this.creditCard = this.constructor.getValue(obj.creditCard || obj.credit_card); this.debitCard = this.constructor.getValue(obj.debitCard || obj.debit_card); this.boleto = this.constructor.getValue(obj.boleto); this.customerEditable = this.constructor.getValue(obj.customerEditable || obj.customer_editable); this.expiresIn = this.constructor.getValue(obj.expiresIn || obj.expires_in); this.skipCheckoutSuccessPage = this.constructor.getValue(obj.skipCheckoutSuccessPage || obj.skip_checkout_success_page); this.billingAddressEditable = this.constructor.getValue(obj.billingAddressEditable || obj.billing_address_editable); this.billingAddress = this.constructor.getValue(obj.billingAddress || obj.billing_address); this.bankTransfer = this.constructor.getValue(obj.bankTransfer || obj.bank_transfer); } /** * Function containing information about the fields of this model * @return {array} Array of objects containing information about the fields */ static mappingInfo() { return super.mappingInfo().concat([ { name: 'acceptedPaymentMethods', realName: 'accepted_payment_methods', array: true }, { name: 'acceptedMultiPaymentMethods', realName: 'accepted_multi_payment_methods', array: true, }, { name: 'successUrl', realName: 'success_url' }, { name: 'defaultPaymentMethod', realName: 'default_payment_method' }, { name: 'gatewayAffiliationId', realName: 'gateway_affiliation_id' }, { name: 'creditCard', realName: 'credit_card', type: 'CreateCheckoutCreditCardPaymentRequest', }, { name: 'debitCard', realName: 'debit_card', type: 'CreateCheckoutDebitCardPaymentRequest', }, { name: 'boleto', realName: 'boleto', type: 'CreateCheckoutBoletoPaymentRequest' }, { name: 'customerEditable', realName: 'customer_editable' }, { name: 'expiresIn', realName: 'expires_in' }, { name: 'skipCheckoutSuccessPage', realName: 'skip_checkout_success_page' }, { name: 'billingAddressEditable', realName: 'billing_address_editable' }, { name: 'billingAddress', realName: 'billing_address', type: 'CreateAddressRequest' }, { name: 'bankTransfer', realName: 'bank_transfer', type: 'CreateCheckoutBankTransferRequest', }, ]); } /** * Function containing information about discriminator values * mapped with their corresponding model class names * * @return {object} Object containing Key-Value pairs mapping discriminator * values with their corresponding model classes */ static discriminatorMap() { return {}; } }
JavaScript
class SnapshotEngine { constructor(config) { this.changeStore = config.changeStore this.snapshotStore = config.snapshotStore } /* Compute snapshot for given documentId and version Example: Let's assume we want to request a snapshot for a new version 20. Now getClosestSnapshot will give us version 15. This requires us to fetch the changes since version 16 and apply those, plus the very new change. */ getSnapshot(documentId, version, cb) { let jsonDoc = EMPTY_DOC this._getClosestSnapshot(documentId, version, (err, snapshot, closestVersion) => { if (err) { return cb(err) } if (snapshot && version === closestVersion) { // we alread have a snapshot for this version return cb(null, snapshot, version) } let knownVersion if (snapshot) { knownVersion = closestVersion } else { knownVersion = 0 // we need to fetch all changes } if (snapshot) { jsonDoc = snapshot } // Now we get the remaining changes after the known version this.changeStore.getChanges(documentId, knownVersion, version, (err, changes) => { if (err) return cb(err) if (changes.length < (version - knownVersion)) { return cb('Changes missing for reconstructing version '+ version) } jsonDoc = computeSnapshot(jsonDoc, changes) cb(null, jsonDoc, version) }) }) } /* Creates a snapshot */ createSnapshot(documentId, version, cb) { this.getSnapshot(documentId, version, (err, snapshot) => { if (err) return cb(err) this.snapshotStore.saveSnapshot(documentId, version, snapshot, cb) }) } _getClosestSnapshot(documentId, version, cb) { let closestVersion this.snapshotStore.getVersions(documentId, (err, versions) => { if (err) return cb(err) if(versions.length === 0) { return cb(null, undefined) } if (versions.indexOf(version) >= 0) { closestVersion = version } else { // We don't have a snaphot for that requested version let smallerVersions = versions.filter(function(v) { return parseInt(v, 10) < version }) // Take the closest version if there is any closestVersion = Math.max.apply(null, smallerVersions) } if (!closestVersion) { return cb(null, undefined) } this.snapshotStore.getSnapshot(documentId, closestVersion, cb) }) } }
JavaScript
class PullRequestTemplate extends textfile_1.TextFile { /** * @experimental */ constructor(github, options = {}) { var _b; super(github.project, '.github/pull_request_template.md', { lines: (options.lines && ((_b = options.lines) === null || _b === void 0 ? void 0 : _b.length) > 0) ? options.lines : ['Fixes #'], }); } }
JavaScript
class Map { /** * New instance * * @since 1.2.0 * * @param Document document Document to create a map for */ constructor(document) { Object.defineProperties(this, { document: { enumerable: true, value: document }, paragraphs: { enumerable: true, get: () => { return document.lines .filter( (l) => l instanceof TypeLine && l.lineType === Constants.T_PARAGRAPH ) .map((l) => new MapPoint(this, l, "paragraph")); }, }, }); } /** * Get map info for a specific offset * * @since 1.2.0 * * @param int offset * @return object */ at(offset = 0) { let pos = 0, lineOffset = null, destination = null, out = { line: null, section: null, paragraph: null, note: null, cell: null, heading: null, }; // find the text line at this offset for (let i = 0; i < this.document.lines.length; i++) { let line = this.document.lines[i]; if (line instanceof TextLine) { if (pos <= offset && pos + line.length > offset) { lineOffset = i; out.line = new MapPoint(this, line, "line"); break; } pos += line.length; } } // find the parent containers of this line reverse: for (let i = lineOffset; i >= 0; i--) { let line = this.document.lines[i]; if (!(line instanceof TypeLine)) continue; switch (line.lineType) { case Constants.T_SECTION: out.section = new MapPoint(this, line, "section"); break reverse; case Constants.T_PARAGRAPH: if (!out.paragraph && (destination == null || destination === Constants.D_BODY)) out.paragraph = new MapPoint(this, line, "paragraph"); break; case Constants.T_DESTINATION: { if (destination === null) { destination = line.destination; switch (destination) { case Constants.D_NOTE: out.note = new MapPoint(this, line, "note"); break; case Constants.D_CELL: out.cell = new MapPoint(this, line, "cell"); break; case Constants.D_HEAD: out.heading = new MapPoint(this, line, "heading"); break; } } break; } } } return out; } }
JavaScript
class RemoteSocket { constructor(adapter, details) { this.id = details.id; this.handshake = details.handshake; this.rooms = new Set(details.rooms); this.data = details.data; this.operator = new BroadcastOperator(adapter, new Set([this.id])); } emit(ev, ...args) { return this.operator.emit(ev, ...args); } /** * Joins a room. * * @param {String|Array} room - room or array of rooms * @public */ join(room) { return this.operator.socketsJoin(room); } /** * Leaves a room. * * @param {String} room * @public */ leave(room) { return this.operator.socketsLeave(room); } /** * Disconnects this client. * * @param {Boolean} close - if `true`, closes the underlying connection * @return {Socket} self * * @public */ disconnect(close = false) { this.operator.disconnectSockets(close); return this; } }
JavaScript
class Coordinate { constructor(lat, lon) { this.lat = lat; this.lon = lon; } }
JavaScript
class AccessibilityCommon { constructor() { /** @private {Autoclick} */ this.autoclick_ = null; /** @private {Magnifier} */ this.magnifier_ = null; /** @private {Dictation} */ this.dictation_ = null; this.init_(); } /** * @return {Autoclick} */ getAutoclickForTest() { return this.autoclick_; } /** * @return {Magnifier} */ getMagnifierForTest() { return this.magnifier_; } /** * Initializes the AccessibilityCommon extension. * @private */ init_() { chrome.accessibilityFeatures.autoclick.get( {}, details => this.onAutoclickUpdated_(details)); chrome.accessibilityFeatures.autoclick.onChange.addListener( details => this.onAutoclickUpdated_(details)); chrome.accessibilityFeatures.screenMagnifier.get( {}, details => this.onMagnifierUpdated_(Magnifier.Type.FULL_SCREEN, details)); chrome.accessibilityFeatures.screenMagnifier.onChange.addListener( details => this.onMagnifierUpdated_(Magnifier.Type.FULL_SCREEN, details)); chrome.accessibilityFeatures.dockedMagnifier.get( {}, details => this.onMagnifierUpdated_(Magnifier.Type.DOCKED, details)); chrome.accessibilityFeatures.dockedMagnifier.onChange.addListener( details => this.onMagnifierUpdated_(Magnifier.Type.DOCKED, details)); chrome.accessibilityFeatures.dictation.get( {}, details => this.onDictationUpdated_(details)); chrome.accessibilityFeatures.dictation.onChange.addListener( details => this.onDictationUpdated_(details)); // AccessibilityCommon is an IME so it shows in the input methods list // when it starts up. Remove from this list, Dictation will add it back // whenever needed. Dictation.removeAsInputMethod(); } /** * Called when the autoclick feature is enabled or disabled. * @param {*} details * @private */ onAutoclickUpdated_(details) { if (details.value && !this.autoclick_) { // Initialize the Autoclick extension. this.autoclick_ = new Autoclick(); } else if (!details.value && this.autoclick_) { // TODO(crbug.com/1096759): Consider using XHR to load/unload autoclick // rather than relying on a destructor to clean up state. this.autoclick_.onAutoclickDisabled(); this.autoclick_ = null; } } /** * @param {!Magnifier.Type} type * @param {*} details * @private */ onMagnifierUpdated_(type, details) { if (details.value && !this.magnifier_) { this.magnifier_ = new Magnifier(type); } else if ( !details.value && this.magnifier_ && this.magnifier_.type === type) { this.magnifier_.onMagnifierDisabled(); this.magnifier_ = null; } } /** * Called when the dictation feature is enabled or disabled. * @param {*} details * @private */ onDictationUpdated_(details) { if (details.value && !this.dictation_) { this.dictation_ = new Dictation(); } else if (!details.value && this.dictation_) { this.dictation_ = null; } } }
JavaScript
class Record extends Observable { constructor(title, time) { super(); this.id = uuid().substring(substring) + "_audio.ogg"; this.title = title; this.time = time; this.audioFile = null; this.currentAudio = null; } // Returns the audioFile as a .ogg file async getOggFile() { return await fetch(this.audioFile) .then(result => result.blob()) .then(blob => { return new File([blob], this.id, { type: "audio/ogg; codecs=opus" }); }); } // Plays the audio file linked to this record playAudio() { let audio = new Audio(), event = new Event("audio-play", this); audio.src = this.audioFile; audio.load(); audio.onloadeddata = () => audio.play(); audio.onended = () => onAudioEnd(this); this.notifyAll(event); this.currentAudio = audio; } // Stop the audio stopAudio() { if (this.isPlaying()) { this.currentAudio.pause(); } } setAudio(audioFile) { this.audioFile = audioFile; } isPlaying() { if (this.currentAudio === null || this.currentAudio === undefined) { return false; } return !this.currentAudio.paused && !this.currentAudio.ended; } getID() { return this.id; } setTitle(title) { this.title = title; } getTitle() { return this.title; } getTime() { return this.time; } }
JavaScript
class Fellowship_Item extends React.Component { render() { return ( <Router> <div className="container-fluid bg-white"> <div className="row"> <div id="column-info" className="col-md-3"> <div className="py-2"> <h5 className="darkblue-tag">Meeting Times</h5> <p>{this.props.date}<br/>{this.props.time}</p> </div> <div className="py-2"> <h5 className="darkblue-tag">Location</h5> <p>{this.props.loc}</p> </div> <div className="py-2"> <h5 className="darkblue-tag">Contact</h5> {/* Dynamically outputs formatted List of Contact information for all persons */} { this.props.contact.map((leader)=>{ return(<div className="py-1"> <p>{leader.name}<br/>{leader.email}</p> </div> ); }) } </div> </div> <div id="column-info" className="col-md"> <div className="py-2"> <h5 className="darkblue-tag">Description</h5> <p>{this.props.desc}</p> </div> <div className="py-2"> <Link id="backtrack-events" to="/fellowships"> <h6 id="attach-icon">Back to Fellowship Groups </h6> <h6 className="fa-solid" id="attach-icon"></h6> </Link> </div> </div> </div> </div> </Router> ); } }
JavaScript
class CollectionsLoader { /** * Creates new instance * * @param {ServiceLocator} locator The Service Locator for resolving dependencies. */ constructor(locator) { this._locator = locator; /** * Current event bus. * * @type {EventEmitter} * @private */ this._events = locator.resolve('events'); /** * Current collections finder. * * @type {CollectionsFinder} * @private */ this._collectionsFinder = locator.resolve('collectionsFinder'); /** * Current map of the loaded collections by their names. * * @type {Object} * @private */ this._loadedCollections = null; } /** * Loads all collections into the memory. * * @returns {Promise<Object>} The promise for map of loaded collections. */ async load() { if (this._loadedCollections) { return this._loadedCollections; } const result = Object.create(null); const collections = await this._collectionsFinder.find(); Object .keys(collections) .map(collection_name => this._getCollection(collections[collection_name])) .filter(collection => collection && typeof (collection) === 'object') .forEach(collection => { this._events.emit('collectionLoaded', collection); result[collection.name] = collection; }); this._loadedCollections = result; this._events.emit('allCollectionsLoaded', result); return this._loadedCollections; } /** * Load/Reload collection * * @param {Object} descriptor Collection's descriptor * @return {void} * @private */ loadCollection(descriptor) { const collection = this._getCollection(descriptor); if (collection) { this._loadedCollections[descriptor.name] = collection; this._events.emit('collectionLoaded', collection); } } /** * Remove collection by name * * @param {String} name Collection's name * @return {void} */ removeCollection(name) { if (this._loadedCollections && this._loadedCollections[name]) { delete this._loadedCollections[name]; } } /** * Gets a collection object by the found collection details. * * collection = { * constructor: Class, * name: '' * properties: { * logic: '', * endpoints: {} * } * path: '' * } * * @param {Object} descriptor The found details. * @returns {Object} The collection object. * @private */ _getCollection(descriptor) { const logic_path = this._getLogicPath(descriptor); let constructor; try { constructor = require(logic_path); } catch (e) { // remove, if it was previously loaded this.removeCollection(descriptor.name); if (e.code === 'ENOENT' || e.message.indexOf(logic_path) !== -1) { this._events.emit('error', `In collection "${descriptor.name}" the logic file has been moved or deleted. Skipping...`); } else { this._events.emit('error', `In collection "${descriptor.name}" error. Skipping... \n ${e.stack}`); } return null; } if (typeof (constructor) !== 'function') { this._events.emit('warn', `File at ${logic_path} of collection "${descriptor.name}" not found or does not export the constructor. Skipping...` ); return null; } const collection = Object.create(descriptor); collection.constructor = constructor; return collection; } /** * Return descriptor of collection by name * * @param {String} name Collection's name * @return {Object} Loaded collection */ getCollectionByName(name) { return this._loadedCollections[name]; } /** * Return collections by name * @return {Object} Loaded collections */ getCollectionsByNames() { return this._loadedCollections; } /** * Gets an absolute path to the collection's logic file. * @param {Object} collectionDetails The collection details object. * @returns {string} The absolute path to the logic file. * @private */ _getLogicPath(collectionDetails) { return path.resolve(path.dirname(collectionDetails.path), collectionDetails.properties.logic); } }
JavaScript
class WKTWriter { /** * @param {GeometryFactory} geometryFactory */ constructor(geometryFactory) { this.parser = new WKTParser(geometryFactory); } /** * Converts a <code>Geometry</code> to its Well-known Text representation. * * @param {Geometry} geometry a <code>Geometry</code> to process. * @return {string} a <Geometry Tagged Text> string (see the OpenGIS Simple * Features Specification). * @memberof module:org/locationtech/jts/io/WKTWriter# */ write(geometry) { return this.parser.write(geometry); } /** * Generates the WKT for a <tt>LINESTRING</tt> specified by two * {@link Coordinate}s. * * @param p0 the first coordinate. * @param p1 the second coordinate. * * @return the WKT. * @private */ static toLineString(p0, p1) { if (arguments.length !== 2) { throw new Error('Not implemented'); } return 'LINESTRING ( ' + p0.x + ' ' + p0.y + ', ' + p1.x + ' ' + p1.y + ' )'; } }
JavaScript
class GeoJSONParser { constructor(geometryFactory) { this.geometryFactory = geometryFactory || new GeometryFactory(); } /** * Deserialize a GeoJSON object and return the Geometry or Feature(Collection) with JSTS Geometries * * @param {} * A GeoJSON object. * @return {} A Geometry instance or object representing a Feature(Collection) with Geometry instances. * @private */ read(json) { let obj; if (typeof json === 'string') obj = JSON.parse(json);else obj = json; const type = obj.type; if (!parse$1[type]) throw new Error('Unknown GeoJSON type: ' + obj.type); if (geometryTypes.indexOf(type) !== -1) return parse$1[type].call(this, obj.coordinates);else if (type === 'GeometryCollection') return parse$1[type].call(this, obj.geometries); // feature or feature collection return parse$1[type].call(this, obj); } /** * Serialize a Geometry object into GeoJSON * * @param {Geometry} * geometry A Geometry or array of Geometries. * @return {Object} A GeoJSON object represting the input Geometry/Geometries. * @private */ write(geometry) { const type = geometry.getGeometryType(); if (!extract$1[type]) throw new Error('Geometry is not supported'); return extract$1[type].call(this, geometry); } }
JavaScript
class GeoJSONReader { /** * A <code>GeoJSONReader</code> is parameterized by a <code>GeometryFactory</code>, * to allow it to create <code>Geometry</code> objects of the appropriate * implementation. In particular, the <code>GeometryFactory</code> determines * the <code>PrecisionModel</code> and <code>SRID</code> that is used. * * @param {GeometryFactory} geometryFactory */ constructor(geometryFactory) { this.parser = new GeoJSONParser(geometryFactory || new GeometryFactory()); } /** * Reads a GeoJSON representation of a {@link Geometry} * * Will also parse GeoJSON Features/FeatureCollections as custom objects. * * @param {Object|String} geoJson a GeoJSON Object or String. * @return {Geometry|Object} a <code>Geometry or Feature/FeatureCollection representation.</code> * @memberof module:org/locationtech/jts/io/GeoJSONReader# */ read(geoJson) { var geometry = this.parser.read(geoJson); return geometry; } }
JavaScript
class GeoJSONWriter { /** * The <code>GeoJSONWriter</code> outputs coordinates rounded to the precision * model. Only the maximum number of decimal places necessary to represent the * ordinates to the required precision will be output. * * @param {GeometryFactory} geometryFactory * @constructor */ constructor() { this.parser = new GeoJSONParser(this.geometryFactory); } /** * Converts a <code>Geometry</code> to its GeoJSON representation. * * @param {Geometry} * geometry a <code>Geometry</code> to process. * @return {Object} The GeoJSON representation of the Geometry. * @memberof module:org/locationtech/jts/io/GeoJSONWriter# */ write(geometry) { return this.parser.write(geometry); } }
JavaScript
class WKTReader { /** * A <code>WKTReader</code> is parameterized by a <code>GeometryFactory</code>, * to allow it to create <code>Geometry</code> objects of the appropriate * implementation. In particular, the <code>GeometryFactory</code> determines * the <code>PrecisionModel</code> and <code>SRID</code> that is used. * @param {GeometryFactory} geometryFactory */ constructor(geometryFactory) { this.parser = new WKTParser(geometryFactory || new GeometryFactory()); } /** * Reads a Well-Known Text representation of a {@link Geometry} * * @param {string} * wkt a <Geometry Tagged Text> string (see the OpenGIS Simple Features * Specification). * @return {Geometry} a <code>Geometry</code> read from * <code>string.</code> * @memberof module:org/locationtech/jts/io/WKTReader# */ read(wkt) { var geometry = this.parser.read(wkt); return geometry; } }
JavaScript
class InlineResponse20062DataGeneral { /** * Constructs a new <code>InlineResponse20062DataGeneral</code>. * General information. * @alias module:model/InlineResponse20062DataGeneral */ constructor() { InlineResponse20062DataGeneral.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>InlineResponse20062DataGeneral</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/InlineResponse20062DataGeneral} obj Optional instance to populate. * @return {module:model/InlineResponse20062DataGeneral} The populated <code>InlineResponse20062DataGeneral</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new InlineResponse20062DataGeneral(); if (data.hasOwnProperty('isin')) { obj['isin'] = ApiClient.convertToType(data['isin'], 'String'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('currency')) { obj['currency'] = InlineResponse20062DataGeneralCurrency.constructFromObject(data['currency']); } if (data.hasOwnProperty('reportingDate')) { obj['reportingDate'] = ApiClient.convertToType(data['reportingDate'], 'Date'); } if (data.hasOwnProperty('legalStructure')) { obj['legalStructure'] = InlineResponse20062DataGeneralLegalStructure.constructFromObject(data['legalStructure']); } if (data.hasOwnProperty('fund')) { obj['fund'] = InlineResponse20062DataGeneralFund.constructFromObject(data['fund']); } if (data.hasOwnProperty('issuer')) { obj['issuer'] = InlineResponse20062DataGeneralIssuer.constructFromObject(data['issuer']); } if (data.hasOwnProperty('guarantor')) { obj['guarantor'] = InlineResponse20062DataGeneralGuarantor.constructFromObject(data['guarantor']); } if (data.hasOwnProperty('type')) { obj['type'] = InlineResponse20062DataGeneralType.constructFromObject(data['type']); } if (data.hasOwnProperty('leveragedOrContingent')) { obj['leveragedOrContingent'] = ApiClient.convertToType(data['leveragedOrContingent'], 'Boolean'); } if (data.hasOwnProperty('manufacturer')) { obj['manufacturer'] = InlineResponse20062DataGeneralManufacturer.constructFromObject(data['manufacturer']); } if (data.hasOwnProperty('approvalProcedure')) { obj['approvalProcedure'] = ApiClient.convertToType(data['approvalProcedure'], 'String'); } if (data.hasOwnProperty('complexProduct')) { obj['complexProduct'] = ApiClient.convertToType(data['complexProduct'], 'String'); } } return obj; } }
JavaScript
class MountVolumes { /** * Create a MountVolumes. * @member {array} [azureFileShares] Azure File Share setup configuration. * References to Azure File Shares that are to be mounted to the cluster * nodes. * @member {array} [azureBlobFileSystems] Azure Blob FileSystem setup * configuration. References to Azure Blob FUSE that are to be mounted to the * cluster nodes. * @member {array} [fileServers] References to a list of file servers that * are mounted to the cluster node. * @member {array} [unmanagedFileSystems] References to a list of file * servers that are mounted to the cluster node. */ constructor() { } /** * Defines the metadata of MountVolumes * * @returns {object} metadata of MountVolumes * */ mapper() { return { required: false, serializedName: 'MountVolumes', type: { name: 'Composite', className: 'MountVolumes', modelProperties: { azureFileShares: { required: false, serializedName: 'azureFileShares', type: { name: 'Sequence', element: { required: false, serializedName: 'AzureFileShareReferenceElementType', type: { name: 'Composite', className: 'AzureFileShareReference' } } } }, azureBlobFileSystems: { required: false, serializedName: 'azureBlobFileSystems', type: { name: 'Sequence', element: { required: false, serializedName: 'AzureBlobFileSystemReferenceElementType', type: { name: 'Composite', className: 'AzureBlobFileSystemReference' } } } }, fileServers: { required: false, serializedName: 'fileServers', type: { name: 'Sequence', element: { required: false, serializedName: 'FileServerReferenceElementType', type: { name: 'Composite', className: 'FileServerReference' } } } }, unmanagedFileSystems: { required: false, serializedName: 'unmanagedFileSystems', type: { name: 'Sequence', element: { required: false, serializedName: 'UnmanagedFileSystemReferenceElementType', type: { name: 'Composite', className: 'UnmanagedFileSystemReference' } } } } } } }; } }
JavaScript
class PostSelfLoansRequest { /** * Constructs a new <code>PostSelfLoansRequest</code>. * PostSelfLoansRequest * @alias module:model/PostSelfLoansRequest */ constructor() { PostSelfLoansRequest.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>PostSelfLoansRequest</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PostSelfLoansRequest} obj Optional instance to populate. * @return {module:model/PostSelfLoansRequest} The populated <code>PostSelfLoansRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new PostSelfLoansRequest(); if (data.hasOwnProperty('dateFormat')) { obj['dateFormat'] = ApiClient.convertToType(data['dateFormat'], 'String'); } if (data.hasOwnProperty('locale')) { obj['locale'] = ApiClient.convertToType(data['locale'], 'String'); } if (data.hasOwnProperty('clientId')) { obj['clientId'] = ApiClient.convertToType(data['clientId'], 'Number'); } if (data.hasOwnProperty('productId')) { obj['productId'] = ApiClient.convertToType(data['productId'], 'Number'); } if (data.hasOwnProperty('principal')) { obj['principal'] = ApiClient.convertToType(data['principal'], 'Number'); } if (data.hasOwnProperty('loanTermFrequency')) { obj['loanTermFrequency'] = ApiClient.convertToType(data['loanTermFrequency'], 'Number'); } if (data.hasOwnProperty('loanTermFrequencyType')) { obj['loanTermFrequencyType'] = ApiClient.convertToType(data['loanTermFrequencyType'], 'Number'); } if (data.hasOwnProperty('loanType')) { obj['loanType'] = ApiClient.convertToType(data['loanType'], 'String'); } if (data.hasOwnProperty('numberOfRepayments')) { obj['numberOfRepayments'] = ApiClient.convertToType(data['numberOfRepayments'], 'Number'); } if (data.hasOwnProperty('repaymentEvery')) { obj['repaymentEvery'] = ApiClient.convertToType(data['repaymentEvery'], 'Number'); } if (data.hasOwnProperty('repaymentFrequencyType')) { obj['repaymentFrequencyType'] = ApiClient.convertToType(data['repaymentFrequencyType'], 'Number'); } if (data.hasOwnProperty('interestRatePerPeriod')) { obj['interestRatePerPeriod'] = ApiClient.convertToType(data['interestRatePerPeriod'], 'Number'); } if (data.hasOwnProperty('amortizationType')) { obj['amortizationType'] = ApiClient.convertToType(data['amortizationType'], 'Number'); } if (data.hasOwnProperty('interestType')) { obj['interestType'] = ApiClient.convertToType(data['interestType'], 'Number'); } if (data.hasOwnProperty('interestCalculationPeriodType')) { obj['interestCalculationPeriodType'] = ApiClient.convertToType(data['interestCalculationPeriodType'], 'Number'); } if (data.hasOwnProperty('transactionProcessingStrategyId')) { obj['transactionProcessingStrategyId'] = ApiClient.convertToType(data['transactionProcessingStrategyId'], 'Number'); } if (data.hasOwnProperty('expectedDisbursementDate')) { obj['expectedDisbursementDate'] = ApiClient.convertToType(data['expectedDisbursementDate'], 'String'); } if (data.hasOwnProperty('submittedOnDate')) { obj['submittedOnDate'] = ApiClient.convertToType(data['submittedOnDate'], 'String'); } if (data.hasOwnProperty('linkAccountId')) { obj['linkAccountId'] = ApiClient.convertToType(data['linkAccountId'], 'Number'); } if (data.hasOwnProperty('fixedEmiAmount')) { obj['fixedEmiAmount'] = ApiClient.convertToType(data['fixedEmiAmount'], 'Number'); } if (data.hasOwnProperty('maxOutstandingLoanBalance')) { obj['maxOutstandingLoanBalance'] = ApiClient.convertToType(data['maxOutstandingLoanBalance'], 'Number'); } if (data.hasOwnProperty('disbursementData')) { obj['disbursementData'] = ApiClient.convertToType(data['disbursementData'], [PostSelfLoansDisbursementData]); } if (data.hasOwnProperty('datatables')) { obj['datatables'] = ApiClient.convertToType(data['datatables'], [PostSelfLoansDatatables]); } } return obj; } }
JavaScript
class FileController { /** * @description upload csv file * @param {Request} req * @param {Response} res * @return {File} returns a message responnse */ static async upload(req, res) { try { // console.log('req======>>>>', req.body); const form = formidable({ multiples: true }); form.parse(req, (err, fields, files) => { if (err) { errorResponse(res, 400, 'Bad Request'); console.log(err); } const data = csvToJson({ sourceFile: files.file.path, columnToKey: { '*': '{{columnHeader}}', }, }); const users = data[Object.keys(data)[0]]; users.shift(); users.forEach((user) => { const { error } = fileSchemaValidation.validate(user, { abortEarly: false, }); if (error.details && Array.isArray(error.details)) { error.details.forEach((err) => { if (err.context.key) { user.errors = { ...user.errors, [err.context.key]: err.message, }; } // console.log('user.errors =================>>>>>>>>', user.erro`rs); }); } }); return Users.bulkCreate(users) .then((data) => res.status(201).json({ status: 201, filename: req.file.originalname, message: 'data saved', })) .catch((err) => res.status(400).json({ status: 400, errors: err, })); }); } catch (error) { console.error(error); } } /** * @description * @param {Request} req * @param {Response} res * @return {array} returns a list of users */ static async getAllUsers(req, res) { const limit = req.query.limit ? req.query.limit : 10; const offset = req.query.offset ? req.query.offset : 0; const users = await Users.findAll({ offset, limit }); if (users.length < 1) { return errorResponse(res, 404, 'Users Not Found'); } return successResponse(res, 200, 'All users', undefined, users); } /** * @description * @param {Request} req * @param {Response} res * @return {array} returns a list of users */ static async getOneUser(req, res) { const id = req.params.id ? parseInt(req.params.id, 10) : 0; if (!id) { return errorResponse(res, 400, 'Please provide the user id'); } const user = await Users.findOne({ where: { id } }); if (!user) { return errorResponse(res, 404, 'User not Found'); } return successResponse(res, 200, 'User found', undefined, user); } }
JavaScript
class MockServer { constructor( /** Routes to handle requests */ routes, /** time to wait before receiving a response */ latency = 300) { this.routes = routes; this.latency = latency; } /** * Handle given request. */ request(request) { return __awaiter(this, void 0, void 0, function* () { const resource = this.findRoute(request.getFinalUrl()); if (!resource) { return new ResponseBuilder().status(404).body(JSON.stringify({ message: 'Not Found' })).build(); } // sleep yield new Promise(resolve => setTimeout(resolve, this.latency)); return resource.controller(request); }); } /** * Find route from given url by pattern matching. */ findRoute(url) { return this.routes.find(({ pattern }) => new RegExp(pattern).test(url)); } }
JavaScript
class PostDetails extends Component { static propTypes = { showModal: PropTypes.func.isRequired, user: PropTypes.string.isRequired, isAuth: PropTypes.bool, post: PropTypes.shape(PropTypes.object.isRequired), isFetching: PropTypes.bool.isRequired, handleUpvote: PropTypes.func.isRequired, upvotePayload: PropTypes.shape(PropTypes.object.isRequired), replies: PropTypes.arrayOf(PropTypes.object.isRequired), sendComment: PropTypes.func.isRequired, isCommenting: PropTypes.bool.isRequired, commentedId: PropTypes.number, commentPayload: PropTypes.shape(PropTypes.object.isRequired), }; static defaultProps = { post: {}, upvotePayload: {}, commentPayload: {}, commentedId: 0, isAuth: false, replies: [], } constructor(props) { super(props); this.images = []; this.imagesAlts = []; this.sortOptions = [ {key: 0, value: 'new', text: 'New'}, {key: 1, value: 'old', text: 'Old'}, //{key: 2, value: 'votes', text: 'Votes'}, {key: 3, value: 'rep', text: 'Reputation'}, {key: 4, value: 'payout', text: 'Payout'} ]; this.state = { sortBy: 'new', } } //Needed to `dangerouslySetInnerHTML` createMarkup = (html) => { return {__html: html}; } /** * Set state values for when tag input text changes. * * @param {event} e Event triggered by element to handle * @param {string} value Value of the element triggering the event */ handleSortChange = (e, {value}) => { this.setState({ sortBy: value, }); } /** * Lifted from busy.org source code to play d.tube videos on-site. */ renderDtubeEmbedPlayer(post) { const parsedJsonMetaData = _.attempt(JSON.parse, post.json_metadata); if (_.isError(parsedJsonMetaData)) { return null; } const video = getFromMetadata(post.json_metadata, 'video'); const isDtubeVideo = _.has(video, 'content.videohash') && _.has(video, 'info.snaphash'); if (isDtubeVideo) { const videoTitle = _.get(video, 'info.title', ''); const author = _.get(video, 'info.author', ''); const permlink = _.get(video, 'info.permlink', ''); const dTubeEmbedUrl = `https://emb.d.tube/#!/${author}/${permlink}/true`; const dTubeIFrame = `<iframe width="100%" height="340" src="${dTubeEmbedUrl}" title="${videoTitle}" allowFullScreen></iframe>`; const embed = { type: 'video', provider_name: 'DTube', embed: dTubeIFrame, thumbnail: getProxyImageURL(`https://ipfs.io/ipfs/${video.info.snaphash}`, 'preview'), }; return <PostFeedEmbed embed={embed} />; } return null; } render() { const { showModal, user, isAuth, isFetching, handleUpvote, upvotePayload, replies, sendComment, isCommenting, commentedId, commentPayload, } = this.props; const { sortBy, } = this.state; let {post} = this.props; if (upvotePayload.post.id > 0 && post.id === upvotePayload.post.id) { post = upvotePayload.post } const title = post.title; const author = post.author; const authorReputation = post.author_reputation; const permlink = post.permlink; const category = post.category; const created = post.created; const activeVotes = post.active_votes; const totalPayout = sumPayout(post); const totalRShares = post.active_votes.reduce((a, b) => a + parseFloat(b.rshares), 0); const ratio = totalRShares === 0 ? 0 : totalPayout / totalRShares; const commentCount = post.children; const canonicalUrl = `https://thekure.net${post.url}`; const url = `https://thekure.net${post.url}`; const ampUrl = `${url}/amp`; const metaTitle = `${title} - KURE`; const desc = post.desc; const postMetaData = jsonParse(post.json_metadata); const postMetaImage = postMetaData && postMetaData.image && postMetaData.image[0]; const image = postMetaImage || `https://steemitimages.com/u/${author}/avatar` || '/images/logo.png'; const body = post.body || ''; const parsedBody = getHtml(body, {}, 'text'); this.images = extractImageTags(parsedBody); let tags = getFromMetadata(post.json_metadata, 'tags'); if (tags === null) tags = [post.category]; const comments = replies; const pid = post.id; return ( <HelmetProvider> <React.Fragment> <Helmet> <title>{title}</title> <link rel="canonical" href={canonicalUrl} /> <link rel="amphtml" href={ampUrl} /> <meta property="description" content={desc} /> <meta property="og:title" content={metaTitle} /> <meta property="og:type" content="article" /> <meta property="og:url" content={url} /> <meta property="og:image" content={image} /> <meta property="og:description" content={desc} /> <meta property="og:site_name" content="Kure" /> <meta property="article:tag" content={category} /> <meta property="article:published_time" content={new Date(created).toDateString()} /> </Helmet> <Grid verticalAlign='middle' columns={1} centered> <Grid.Row> <Grid.Column width={11}> <React.Fragment> { isFetching ? <Loading /> : ( <React.Fragment> <div className='PostContent'> <h1> {title} </h1> <AuthorCatgoryTime author={author} authorReputation={authorReputation} category={category} created={created} permlink={permlink} /> <hr /> {this.renderDtubeEmbedPlayer(post)} <PostBody full rewriteLinks={false} body={body} json_metadata={post.json_metadata} /> <br /> <div className='footer'> <div className='left'> <Tags tags={tags} /> </div> <div className='alt-site right'> {`View on `} <a target='_blank' rel='noopener noreferrer' href={`https://steemit.com${post.url}`} > {'Steemit'} </a> {' | '} <a target='_blank' rel='noopener noreferrer' href={`https://busy.org/@${author}/${permlink}`} > {'Busy'} </a> </div> <div className='clear' /> <div className='post-actions'> <PostActions activeVotes={activeVotes} commentCount={commentCount} author={author} category={category} payoutValue={totalPayout} permlink={permlink} title={title} showModal={showModal} user={user} handleUpvote={handleUpvote} upvotePayload={upvotePayload} ratio={ratio} pid={pid} image={image} /> </div> <hr /> { isAuth && ( <ReplyForm sendComment={sendComment} isCommenting={isCommenting} parentPost={post} commentedId={commentedId} /> ) } </div> </div> </React.Fragment> ) } <div className='comments' id='comments'> { !!comments.length && ( <React.Fragment> <div className='left'> <h2>Comments</h2> </div> <div className='right'> <Form> <Form.Group> <Form.Field control={Select} defaultValue={this.sortOptions[0].value} options={this.sortOptions} onChange={this.handleSortChange} /> </Form.Group> </Form> </div> <Comments comments={comments} sendComment={sendComment} isCommenting={isCommenting} commentedId={commentedId} isAuth={isAuth} commentPayload={commentPayload} pid={pid} handleUpvote={handleUpvote} user={user} upvotePayload={upvotePayload} sortBy={sortBy} /> </React.Fragment> ) } </div> </React.Fragment> </Grid.Column> </Grid.Row> </Grid> </React.Fragment> </HelmetProvider> ) } }
JavaScript
class TopologyDefineField extends TopologyDefineItem { /** * Create a TopologyDefineField instance. * @class TopologyDefineField * @extends TopologyDefineItem * * SETTINGS FORMAT: * "fields": * "fieldA": * // DATA * "type": "integer", * "auto_increment": false, * "allow_null": false, * "is_unique":true, * "is_primary_key":true, * "expression":null, * "column":"id", * "alias":"id_user", * * // VALUE * "default":"", * "hash": "md5", * "validate_rule": "alphaALPHAnum_-space", * "validate_error_label": "upper or lower alphanumeric and - and _ and space" * * // VIEW * "label": "Id", * "placeholder": "Enter lastname", * "is_editable": "0", * "is_visible": "0" * "fieldB":... * * @param {string} arg_name - instance name. * @param {object} arg_settings - instance settings map. * @param {string} arg_log_context - trace context string. * * @returns {nothing} */ constructor(arg_name, arg_settings, arg_log_context) { const log_context = arg_log_context ? arg_log_context : context super(arg_name, arg_settings, 'TopologyDefineField', log_context) this.is_topology_define_field = true this.topology_type = 'fields' // DATA this.field_type = this.get_setting('type', 'string') this.field_is_primary_key = this.get_setting('is_primary_key', false) this.field_auto_increment = this.get_setting('auto_increment', false) this.field_allow_null = this.get_setting('allow_null', true) this.field_is_unique = this.get_setting('is_unique', false) this.field_expression = this.get_setting('expression', undefined) this.field_column = this.get_setting('column', undefined) this.field_alias = this.get_setting('alias', arg_name) // VALUE this.field_default = this.get_setting('default', undefined) this.field_hash = this.get_setting('hash', 'md5') this.field_validate_rule = this.get_setting('validate_rule', undefined) this.field_validate_error_label = this.get_setting('validate_error_label', undefined) // VIEW this.field_label = this.get_setting('label', arg_name) this.field_placeholder = this.get_setting('placeholder', undefined) this.field_is_editable = this.get_setting('is_editable', true) this.field_is_visible = this.get_setting('is_visible', true) this.info('Field is created') } /** * ... * * @returns {nothing} */ is_valid() // TODO check and load collection schema { try { // CHECK FIELD TYPE assert( T.isString(this.field_type) ) switch(this.field_type) { case 'integer': case 'boolean': case 'string': // case 'object': break default: return false } // CHECK PRIMARY KEY assert( T.isBoolean(this.field_is_primary_key) ) assert( T.isBoolean(this.field_allow_null) ) assert( T.isBoolean(this.field_is_unique) ) assert( this.field_is_primary_key ? ! this.field_allow_null : true) } catch(e) { return false } return true } }
JavaScript
class BodyDelta extends BaseDelta { /** * Given a Quill `Delta` instance, returns an instance of this class with the * same operations. * * @param {Delta|array} quillDelta Quill `Delta` instance or array of Quill * delta ops. * @returns {BodyDelta} Equivalent instance of this class. */ static fromQuillForm(quillDelta) { let ops; if (Array.isArray(quillDelta)) { ops = quillDelta; } else { ops = BodyDelta._opsOfQuillDelta(quillDelta); } ops = Object.freeze(ops.map(BodyOp.fromQuillForm)); return new BodyDelta(ops); } /** * Computes the difference between this instance and another, where both must * be document (from-empty) deltas. The return value is a delta which can be * `compose()`d with this instance to produce the delta passed in here as an * argument. That is, `newerDelta == this.compose(this.diff(newerDelta), * true)`. * * **Note:** The parameter name `newer` is meant to be suggestive of the * typical use case for this method, but strictly speaking there does not have * to be a particular time order between this instance and the argument. * * @param {BodyDelta} newerDelta Instance to take the difference from. * @returns {BodyDelta} Delta which represents the difference between * `newerDelta` and this instance. */ diff(newerDelta) { if (!this.isDocument()) { throw Errors.badUse('Called on non-document instance.'); } else if (!newerDelta.isDocument()) { throw Errors.badValue(newerDelta, BodyDelta, 'isDocument()'); } // Use Quill's implementation. const quillThis = this.toQuillForm(); const quillNewer = newerDelta.toQuillForm(); const quillResult = quillThis.diff(quillNewer); return BodyDelta.fromQuillForm(quillResult); } /** * Produces a Quill `Delta` (per se) with the same contents as this instance. * * @returns {Delta} A Quill `Delta` with the same contents as `this`. */ toQuillForm() { const ops = this.ops.map(op => op.toQuillForm()); return new Text.Delta(ops); } /** * Computes the transformation of a delta with respect to this one, such that * the result can be composed on top of this instance to produce a sensible * combined result. For example, given a document delta and two different * change deltas to that specific document, it is reasonable to write code * such as: * * ```javascript * document * .compose(change1, false) * .compose(change1.transform(change2, true), false) * ``` * * **Note:** This operation only makes sense when both `this` and `other` are * being treated as non-document deltas. * * @param {BodyDelta} other Instance to transform. * @param {boolean} thisIsFirst "Priority" of the two instances. If `true` * then the operations of `this` are taken to have come first / won the * race. Contrawise, if `false` then the operations of `other` are taken to * have come first. * @returns {BodyDelta} Delta which represents the transformation ofbetween * `newerDelta` and this instance. */ transform(other, thisIsFirst) { BodyDelta.check(other); TBoolean.check(thisIsFirst); // Use Quill's implementation. const quillThis = this.toQuillForm(); const quillOther = other.toQuillForm(); const quillResult = quillThis.transform(quillOther, thisIsFirst); return BodyDelta.fromQuillForm(quillResult); } /** * Main implementation of {@link #compose}. * * @param {BodyDelta} other Delta to compose with this instance. * @param {boolean} wantDocument Whether the result of the operation should be * a document delta. * @returns {BodyDelta} Composed result. */ _impl_compose(other, wantDocument) { // Use Quill's implementation. const quillThis = this.toQuillForm(); const quillOther = other.toQuillForm(); const quillResult = quillThis.compose(quillOther); const result = BodyDelta.fromQuillForm(quillResult); // **Note:** `quill-delta` doesn't alter its behavior based on whether the // result should be a document or not, and it is possible to have a valid // (from `quill-delta`'s perspective) case of a valid document `this` to be // composed with a valid change `other`, returning a _non-document_ delta // result. Trivial example (in pseudocode): // // this = [insert('xyz')] // other = [retain(4)] // this.compose(other) = [insert('xyz'), retain(1)] // // That last line is a valid `quill-delta` composition result, but in the // context of `wantDocument === true` it is invalid, because document deltas // are not allowed to have any `retain` operations (because there is by // definition nothing to retain). // // The following check _just_ catches these sorts of problems, providing a // reasonably apt error message, so as to avoid confusing any of the higher // layers. if (wantDocument && !result.isDocument()) { // **TODO:** Remove this logging once we track down why we're seeing this // error. log.event.badComposeOrig(this, other, result); log.event.badComposeQuill(quillThis.ops, quillOther.ops, quillResult.ops); throw Errors.badUse('Inappropriate `other` for composition given `wantDocument === true`.'); } return result; } /** * Main implementation of {@link #isDocument}. See the class header comment * for details about the constraints that define document deltas for this * class. * * @returns {boolean} `true` if this instance can be used as a document or * `false` if not. */ _impl_isDocument() { const ops = this.ops; if (ops.length === 0) { return true; } const lastOp = ops[ops.length - 1]; const props = lastOp.props; if ((props.opName !== BodyOp.CODE_text) || !props.text.endsWith('\n')) { return false; } for (const op of ops) { if (!op.isInsert()) { return false; } } return true; } /** * {class} Class (constructor function) of operation objects to be used with * instances of this class. */ static get _impl_opClass() { return BodyOp; } /** * Checks that the argument is a Quill delta, and if so returns the `ops` * array inside it. Throws an error if not. * * @param {Delta} quillDelta Quill delta instance. * @returns {array} Array of Quill operations that `delta` contains. */ static _opsOfQuillDelta(quillDelta) { try { TObject.check(quillDelta, Text.Delta); } catch (e) { if ((typeof quillDelta === 'object') && (quillDelta.constructor.name === 'Delta')) { // The version of `Delta` used by Quill is different than the one which // is specified in the configuration hook // {@link @bayou/config-common/Text}. Even though it will often happen // to work if we just let it slide (e.g. by snarfing `ops` out of the // object and running with it), we don't want to end up shipping two // versions of `Delta` to the client; so, instead of just blithely // accepting this possibility, we reject it here and report an error // which makes it easy to figure out what happened. Should you find // yourself looking at this error, the likely right thing to do is // look at the lines logged just before the error was thrown, and change // either how `Text` is configured to match the incoming `Delta` version // _or_ change where the incoming `Delta` version is used to match what // got configured for `Text`. Of particular note, if you are using a // version of `Quill` in distribution form, it bundles within itself a // version of `Delta`, and you will want to make sure that `Text` uses // `Quill.import('delta')` to get it hooked up. // This is an attempt to get a stack trace each from both "our" `Delta` // and the incoming `Delta`, as a possible breadcrumb for folks running // into this problem. log.error('Divergent versions of `quill-delta` package.'); BodyDelta._logWhichDelta('ours', Text.Delta); BodyDelta._logWhichDelta('incoming', quillDelta.constructor); throw Errors.badUse('Divergent versions of `quill-delta` package.'); } throw e; } return quillDelta.ops; } /** * Helper used when making the "divergent" complaint, which aims to log an * error pointing at the source of one of the versions of `Delta`. * * @param {string} label Short label indicating which version this is. * @param {class} Delta A version of the `Delta` class. */ static _logWhichDelta(label, Delta) { const delta = new Delta([{ insert: 'x' }]); let trace; try { delta.forEach(() => { throw new Error('x'); }); } catch (e) { trace = e.stack; } for (const line of trace.split('\n')) { const match = line.match(/at Delta[^(]+\(([^:)]+)[:)]/); if (match) { log.info(`${label}: ${match[1]}`); return; } } log.error(`Could not determine \`Delta\` version "${label}" from stack trace!`, trace); } }
JavaScript
@Module({ deps: ['Client', { dep: 'ExtensionFeaturesOptions', optional: true }], }) class ExtensionFeatures extends DataFetcher { /** * @constructor * @param {Object} params - params object * @param {Client} params.client - client module instance */ constructor({ client, ...options }) { super({ client, subscriptionFilters: [subscriptionFilters.extensionInfo], subscriptionHandler: async (message) => { await this._subscriptionHandleFn(message); }, async fetchFunction() { const res = await client.service .platform() .get('/account/~/extension/~/features'); return extractData(res.json()); }, cleanOnReset: true, ...options, }); } get _name() { return 'extensionFeatures'; } async _subscriptionHandleFn(message) { if ( message && message.body && message.body.hints && (message.body.hints.includes(subscriptionHints.limits) || message.body.hints.includes(subscriptionHints.features) || message.body.hints.includes(subscriptionHints.permissions)) ) { await this.fetchData(); } } @selector features = [() => this.data, (data) => data || {}]; }
JavaScript
class MyTransition extends React.Component { constructor(props) { super(props) } render() { return ( <CSSTransition {...this.props} classNames="example" timeout={{ enter: 1000, exit: 1000 }} /> ) } }
JavaScript
class Demo extends React.Component { render() { // console.log("lng:", this.props.coords.longitude) return !this.props.isGeolocationAvailable ? ( <div>Your browser does not support Geolocation</div> ) : !this.props.isGeolocationEnabled ? ( <div style={{ background: "white", borderRadius: "20px", padding: "30px" }} > Geolocation is not enabled </div> ) : this.props.coords ? ( <div> <Maps lat={this.props.coords.latitude} lng={this.props.coords.longitude} mapMode={this.props.mapMode} handleMapMode={this.props.handleMapMode} /> </div> ) : ( <div style={{ background: "white", borderRadius: "20px", padding: "30px" }} > Getting the location data&hellip;{" "} </div> ); } }
JavaScript
class Layer extends EventEmitter { /** * Instantiates a new Layer object. * * @param {Object} options - The options. * @param {number} options.opacity - The layer opacity. * @param {number} options.zIndex - The layer z-index. * @param {boolean} options.hidden - Whether or not the layer is visible. */ constructor(options = {}) { super(); this.opacity = defaultTo(options.opacity, 1.0); this.hidden = defaultTo(options.hidden, false); this.zIndex = defaultTo(options.zIndex, 0); this.renderer = defaultTo(options.renderer, null); this.highlighted = null; this.selected = []; this.plot = null; } /** * Executed when the layer is attached to a plot. * * @param {Plot} plot - The plot to attach the layer to. * * @returns {Layer} The layer object, for chaining. */ onAdd(plot) { if (!plot) { throw 'No plot argument provided'; } // set plot this.plot = plot; // flag as dirty this.plot.setDirty(); // execute renderer hook if (this.renderer) { this.renderer.onAdd(this); } return this; } /** * Executed when the layer is removed from a plot. * * @param {Plot} plot - The plot to remove the layer from. * * @returns {Layer} The layer object, for chaining. */ onRemove(plot) { if (!plot) { throw 'No plot argument provided'; } // execute renderer hook if (this.renderer) { this.renderer.onRemove(this); } // clear state this.clear(); // flag as dirty this.plot.setDirty(); // remove plot this.plot = null; return this; } /** * Add a renderer to the layer. * * @param {Renderer} renderer - The renderer to add to the layer. * * @returns {Layer} The layer object, for chaining. */ setRenderer(renderer) { if (!renderer) { throw 'No renderer argument provided'; } if (this.renderer && this.plot) { this.renderer.onRemove(this); } this.renderer = renderer; if (this.plot) { this.renderer.onAdd(this); } return this; } /** * Remove the renderer from the layer. * * @returns {Layer} The layer object, for chaining. */ removeRenderer() { if (!this.renderer) { throw 'No renderer is currently attached to the layer'; } if (this.plot) { this.renderer.onRemove(this); } this.renderer = null; return this; } /** * Returns the renderer of the layer. * * @returns {Renderer} The renderer object. */ getRenderer() { return this.renderer; } /** * Set the opacity of the layer. * * @param {number} opacity - The opacity to set. * * @returns {Layer} The layer object, for chaining. */ setOpacity(opacity) { opacity = clamp(opacity, 0, 1); if (this.opacity !== opacity) { this.opacity = opacity; if (this.plot) { this.plot.setDirty(); } } return this; } /** * Get the opacity of the layer. * * @returns {number} The opacity of the layer object,. */ getOpacity() { return this.opacity; } /** * Set the z-index of the layer. * * @param {number} zIndex - The z-index to set. * * @returns {Layer} The layer object, for chaining. */ setZIndex(zIndex) { if (this.zIndex !== zIndex) { this.zIndex = zIndex; if (this.plot) { this.plot.setDirty(); } } return this; } /** * Get the z-index of the layer. * * @returns {number} The zIndex of the layer object,. */ getZIndex() { return this.zIndex; } /** * Make the layer visible. * * @returns {Layer} The layer object, for chaining. */ show() { if (this.hidden) { this.hidden = false; if (this.plot) { this.plot.setDirty(); } } return this; } /** * Make the layer invisible. * * @returns {Layer} The layer object, for chaining. */ hide() { if (!this.hidden) { this.hidden = true; if (this.renderer) { this.renderer.clear(); } if (this.plot) { this.plot.setDirty(); } } return this; } /** * Returns true if the layer is hidden. * * @returns {boolean} Whether or not the layer is hidden. */ isHidden() { return this.hidden; } /** * Pick a position of the layer for a collision with any rendered objects. * * @param {Object} pos - The plot position to pick at. * * @returns {Object} The collision, or null. */ pick(pos) { if (this.renderer) { return this.renderer.pick(pos); } return null; } /** * Highlights the provided data. * * @param {Object} data - The data to highlight. * * @returns {Layer} The layer object, for chaining. */ highlight(data) { if (this.highlighted !== data) { this.highlighted = data; if (this.plot) { this.plot.setDirty(); } } return this; } /** * Clears any current highlight. * * @returns {Layer} The layer object, for chaining. */ unhighlight() { if (this.highlighted !== null) { this.highlighted = null; if (this.plot) { this.plot.setDirty(); } } return this; } /** * Returns any highlighted data. * * @returns {Object} The highlighted data. */ getHighlighted() { return this.highlighted; } /** * Returns true if the provided argument is highlighted. * * @param {Object} data - The data to test. * * @returns {boolean} Whether or not there is highlighted data. */ isHighlighted(data) { return this.highlighted === data; } /** * Selects the provided data. * * @param {Object} data - The data to select. * @param {Object} multiSelect - Whether mutli-select is enabled. * * @returns {Layer} The layer object, for chaining. */ select(data, multiSelect) { let changed = false; if (multiSelect) { // add to collection if multi-selection is enabled const index = this.selected.indexOf(data); if (index === -1) { // select point this.selected.push(data); changed = true; } } else { // clear selection, adding only the latest entry if (this.selected.length !== 1 || this.selected[0] !== data) { this.selected = [ data ]; changed = true; } } if (this.plot && changed) { this.plot.setDirty(); } return this; } /** * Remove the provided data from the current selection. * * @param {Object} data - The data to unselect. * * @returns {Layer} The layer object, for chaining. */ unselect(data) { const index = this.selected.indexOf(data); if (index !== -1) { // unselect point this.selected.splice(index, 1); if (this.plot) { this.plot.setDirty(); } } return this; } /** * Clears the current selection. * * @returns {Layer} The layer object, for chaining. */ unselectAll() { if (this.selected.length > 0) { // unselect all this.selected = []; if (this.plot) { this.plot.setDirty(); } } return this; } /** * Returns any selected data. * * @returns {Array} The selected data. */ getSelected() { return this.selected; } /** * Returns true if the provided argument is selected. * * @param {Object} data - The data to test. * * @returns {boolean} Whether or not the data is selected. */ isSelected(data) { return this.selected.indexOf(data) !== -1; } /** * Draw the layer for the frame. * * @param {number} timestamp - The frame timestamp. * * @returns {Layer} The layer object, for chaining. */ draw(timestamp) { if (this.renderer) { this.renderer.draw(timestamp); } return this; } /** * Clears any persisted state in the layer. * * @returns {Layer} The layer object, for chaining. */ clear() { // clear selected / highlighted if (this.highlighted || this.selected.length > 0) { this.highlighted = null; this.selected = []; } // clear renderer state if (this.renderer) { this.renderer.clear(); } // flag as dirty if (this.plot) { this.plot.setDirty(); } return this; } /** * Clears any persisted state in the layer and refreshes the underlying * data. * * @returns {Layer} The layer object, for chaining. */ refresh() { // clear the layer state this.clear(); // emit refresh event this.emit(EventType.REFRESH, new Event(this)); return this; } }
JavaScript
class Table { constructor(headers) { this.MIN_COL_WIDTH = 6; this.SEP = " "; this.headers = headers; this.hl = []; for (let i = 0; i < headers.length; i++) { // pad headers to min width let h = headers[i]; h = h.padEnd(this.MIN_COL_WIDTH); this.headers[i] = h; this.hl[i] = h.length; } } header_row_str() { let s = ""; for (let i = 0; i < this.headers.length; i++) { s += this.headers[i] + this.SEP; } return s; } // Assume row values are in the same order as the headrs. row_to_str(r) { let s = ""; for (let i = 0; i < this.headers.length; i++) { let v = r[i]; if (typeof v == 'number') { v = v.toFixed(2); } s += v.padStart(this.hl[i]) + this.SEP; } return s; } }
JavaScript
class SobjectCentricView extends MyTriggerViewBase { @track metadata = []; isAnyChanged = false; @api set customMetadata(value) { console.log("SobjectCentricView set customMetadata"); console.log(value.data); if (value.data) { this.metadata = value.data; this.options = this.calculateOptions(); if (!this.initialized) { this.currentFilter = this.calculateDefaultFilter(); this.initialized = true; } } } get customMetadata(){ console.log("SobjectCentricView get customMetadata"); return this.metadata; } get rows(){ console.log("SobjectCentricView get rows"); let mapped = this.mapTheData(this.metadata, this.currentFilter); let tableCells = []; for (var index = 0; index < mapped.length; index++) { tableCells.push(mapped[index]); } return tableCells; } get headers() { console.log("SobjectCentricView get headers"); let headers = [{"label":"Trigger Order","key":"-1","size" : 1}]; let filter = this.currentFilter; if (filter.classValue) { console.log(JSON.stringify(filter.classValue)); for (let index = 0; index < filter.classValue.length; index++) { headers.push({ "label" : filter.classValue[index], "key" : filter.classValue[index], "size" : 2 }); } } console.log(headers); return headers; } calculateDefaultFilter() { console.log("SobjectCentricView calculateDefaultFilter"); let opt = this.options; let valueClasses = []; for (var i = 0; i < opt.optionClass.length; i++) { valueClasses.push(opt.optionClass[i].value); } let valueDml = []; for (var i = 0; i < opt.optionDml.length; i++) { valueDml.push(opt.optionDml[i].value); } let valueTiming = []; for (var i = 0; i < opt.optionTiming.length; i++) { valueTiming.push(opt.optionTiming[i].value); } return { "classValue" : valueClasses, "sobjectsValues" : opt.optionSobject[0].value, "crudValue" : valueDml, "timingValue" : valueTiming }; } handleFilterChange(event){ console.log("SobjectCentricView handleFilterChange"); var filter = event.detail; this.currentFilter = filter; console.log(filter.classValue); console.log(filter.sobjectsValues); console.log(filter.crudValue); console.log(filter.timingValue); var headers = [{"label":"Trigger Order","key":"-1","size" : 1}]; for (var index = 0; index < filter.classValue.length; index++) { headers.push({ "label" : filter.classValue[index], "key" : filter.classValue[index], "size" : 2 }); } var mapped = this.mapTheData(this.metadata, filter); var tableCells = []; for (var index = 0; index < mapped.length; index++) { tableCells.push(mapped[index]); } console.log(tableCells); var table = this.template.querySelector('c-table-component'); table.update(headers, tableCells); } handleSaveChanges(event) { console.log("SobjectCentricView@handleSaveChanges"); this.dispatchEvent( new CustomEvent( 'savechangedclick' ) ); } mapTheData(mdtDataAsList, filter) { console.log('SobjectCentricView mapTheData'); //console.log(mdtDataAsList); var mdtData = mdtDataAsList; var mapped = []; var possibleDMLs = ['INSERT', 'UPDATE', 'DELETE', 'UNDELETE']; var possibleTimings = ['BEFORE', 'AFTER']; //console.log('SobjectCentricView before possible'); var possibleOrderNumbers = this.collectAndSortPossibleOrderNumbers(mdtData); console.log("possibleOrderNumber calculated"); console.log(possibleOrderNumbers); if (this.initialized) this.isAnyChanged = false; for (var mdtIndexer = 0; mdtIndexer < mdtData.length; mdtIndexer++) { let mdtRow = mdtData[mdtIndexer]; this.isAnyChanged = this.isAnyChanged || mdtRow.isChanged; let mdtId = mdtRow.Id; let clasName = (mdtRow.ClassNamespacePrefix__c ? mdtRow.ClassNamespacePrefix__c + "." : "") + mdtRow.Class__c; let triggerEventDML = mdtRow.Event__c.split('_')[1]; let triggerEventTime = mdtRow.Event__c.split('_')[0]; let sobject = ( mdtRow.sObject__c === null || mdtRow.sObject__c === "" || mdtRow.sObject__c === undefined ? mdtRow.sObjectAPIName__c : mdtRow.sObject__c ); let orderNumber = mdtRow.Order__c; //console.log(clasName + ' ' + triggerEventDML + ' ' + triggerEventTime + ' ' + sobject); if (sobject === filter.sobjectsValues) { if (filter.crudValue.includes(triggerEventDML)) { var grandParent = mapped[possibleDMLs.indexOf(triggerEventDML)]; if (grandParent == undefined) { mapped[possibleDMLs.indexOf(triggerEventDML)] = this.createGrandParentElement(triggerEventDML); grandParent = mapped[possibleDMLs.indexOf(triggerEventDML)]; } if (filter.timingValue.includes(triggerEventTime)) { if (filter.classValue.includes(clasName)) { var parent = grandParent.rows[possibleTimings.indexOf(triggerEventTime)]; if (parent == undefined) { grandParent.rows[possibleTimings.indexOf(triggerEventTime)] = this.createParentRowElement(triggerEventTime); parent = grandParent.rows[possibleTimings.indexOf(triggerEventTime)]; } var rowIndex = possibleOrderNumbers.indexOf(orderNumber); //console.log(rowIndex); if (parent.elements[rowIndex] == undefined) { parent.elements[rowIndex] = this.createChildRowElement(rowIndex, orderNumber); } var rowElement = parent.elements[rowIndex]; rowElement.elements[filter.classValue.indexOf(clasName)+1] = this.createCellElement(mdtRow); } } } } } //console.log('mapped before'); //console.log(mapped); console.log('mapped after'); for (var dmlIndex = 0; dmlIndex < mapped.length; dmlIndex++) { var dmlElement = mapped[dmlIndex]; console.log(dmlElement); if (dmlElement != undefined) { for (var timingIndex = 0; timingIndex < dmlElement.rows.length; timingIndex++){ var timingElement = dmlElement.rows[timingIndex]; if (timingElement != undefined) { //console.log(timingElement); for (var rowy = 0; rowy < possibleOrderNumbers.length; rowy++) { var rowElement = timingElement.elements[rowy]; if (rowElement != undefined) { //console.log(rowElement); for (var coly = 0; coly < filter.classValue.length+1; coly++) { if (rowElement.elements[coly] == undefined) { rowElement.elements[coly] = { "label" : "", "key" : coly, "size" : 2 }; } } } } } } } } //console.log(mapped); return mapped; } createGrandParentElement(triggerEventDML) { return { "title" : triggerEventDML, "key" : triggerEventDML, "rows" : [] }; } createParentRowElement(triggerEventTime) { return { "title" : triggerEventTime, "key" : triggerEventTime, "isLastRow" : "false", "isMultipleRows" : "true", "elements" : [] }; } createChildRowElement(rowIndex, orderNumber) { return { "key" : rowIndex, "elements" : [{"key":"0","label":orderNumber,"size" : 1}] }; } createCellElement(mdtRow) { return { "label" : mdtRow.Description__c == undefined ? mdtRow.Label : mdtRow.Description__c, "key" : mdtRow.Id, "id" : mdtRow.Id, "isChanged" : mdtRow.isChanged, "size" : 2 }; } }
JavaScript
class AtomTransition extends Transition { /** * @param {org.antlr.v4.runtime.atn.ATNState} target * @param {number} label */ constructor(target, label) { super(target); /** * The token type or character value; or, signifies special label. * * @type {number} */ this.tlabel = label; } getSerializationType() { return Transition.ATOM; } label() { return IntervalSet.of(this.tlabel); } matches(symbol, minVocabSymbol, maxVocabSymbol) { return this.tlabel === symbol; } /** * @return {string} */ toString() { return "" + this.tlabel; } }
JavaScript
class Title extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <H1> its afterhours </H1> <H2>Teusday core hours start in 2 hours</H2> </div> ); } }
JavaScript
class Format12 { constructor(p) { this.format = 12; p.uint16; this.length = p.uint32; this.language = p.uint32; this.numGroups = p.uint32; const getter = () => [...new Array(this.numGroups)].map(_ => new SequentialMapGroup(p)); lazy(this, `groups`, getter); } supports(charCode) { if (charCode.charCodeAt) charCode = charCode.charCodeAt(0); const groups = this.groups; let i = groups.findIndex(s => s.startcharCode > charCode); if (i===0) return false; if (i===-1) i = groups.length; let g = groups[i-1]; if (g.endcharCode < charCode) return false; return charCode - g.startcharCode + g.startGlyphID; } getSupportedCharCodes(preservePropNames=false) { if (preservePropNames) return this.groups; return this.groups.map(v => ({ start: v.startCode, end: v.endCode})); } }
JavaScript
class ArtificialFailureInfo extends CommonBase { /** * {string} Type indicating that "failure" should just be in the form of logs * that look "faily" without any other change in behavior. */ static get TYPE_justLogging() { return 'justLogging'; } /** {string} Type indicating no actual failure at all. */ static get TYPE_none() { return 'none'; } /** * Constructs an instance. * * @param {BuildInfo} buildInfo The boot info, which includes artificial * failure configuration. */ constructor(buildInfo) { BuildInfo.check(buildInfo); super(); const [failPercent, failType] = ArtificialFailureInfo._parseInfo(buildInfo); /** * {boolean} Whether failure is actually allowed. If `false`, then this * instance reports that failure shouldn't actually happen. */ this._allowFailure = false; /** {Int} Percentage of servers which should experience a failure. */ this._failPercent = failPercent; /** {string} Type of failure to induce. */ this._failType = failType; Object.seal(this); if (this._failPercent !== 0) { log.event.artificialFailureParameters(this._failPercent, this._failType); log.info('#####'); log.info('#####'); log.info('##### NOTE: This build is configured with artificial failure!'); log.info('#####'); log.info('#####'); } } /** {Int} Percentage of servers which should experience a failure. */ get failPercent() { return this._allowFailure ? this._failPercent : 0; } /** {string} Type of failure to induce. */ get failType() { return this._allowFailure ? this._failType : ArtificialFailureInfo.TYPE_none; } /** * {Int} _Nascent_ failure percentage. This is what {@link #failPercent} would * report if {@link #allowFailure} were called. This can be used to help * clients of this class decide whether or not to "pull the trigger" on * failure. */ get nascentFailPercent() { return this._failPercent; } /** * Indicate that failure is actually allowed. If this call is never made, then * it is as if the build was not configured with any failures. */ allowFailure() { if (this._allowFailure || (this._failPercent === 0)) { return; } log.event.artificialFailureEnabled(); log.info('#####'); log.info('#####'); log.info('##### NOTE: Artificial failure is now enabled!'); log.info('#####'); log.info('#####'); this._allowFailure = true; } /** * Indicates whether this server should actually be failing at all, or failing * specifically with the indicated type of failure. This will be `true` _if * and only if_ all of: * * * {@link #allowFailure} was called. * * {@link #failType} is the one passed here or is `null`. * * This server's hash causes it to be in the failing cohort per the * {@link #failPercent}. * * @param {string|null} [failType = null] Type of failure in question, or * `null` to just ask if this server should be faily in general. If * non-`null`, must be one of the `TYPE_*` constants defined by this class. * @returns {boolean} `true` if this server should be failing in the indicated * manner, or `false` if not. */ shouldFail(failType = null) { TString.orNull(failType); const percent = this.failPercent; // This will be `0` if `allowFailure()` wasn't called. const typeMatches = (failType === null) || (failType === this.failType); if ((percent === 0) || !typeMatches) { return false; } // Hash the server ID and convert it into a value in the range 0..99. const serverNum = ArtificialFailureInfo._percentFromString(Deployment.serverId()); return serverNum < percent; } /** * Parses the failure info out of a boot info object. * * @param {BootInfo} buildInfo The boot info. * @returns {array} Failure info consisting of `[failPercent, failType]`. */ static _parseInfo(buildInfo) { BuildInfo.check(buildInfo); const { artificialFailurePercent, artificialFailureType } = buildInfo.info; const percentNum = parseInt(artificialFailurePercent); const camelType = camelCase(artificialFailureType || '<bogus>'); const typeConst = ArtificialFailureInfo[`TYPE_${camelType}`]; if ( isNaN(percentNum) || (percentNum < 0) || (percentNum > 100) || (typeConst !== camelType)) { // Fail-safe: If the build info properties aren't set up right, treat it // as a no-failure situation. return [0, ArtificialFailureInfo.TYPE_none]; } return [percentNum, typeConst]; } /** * Gets an integer value in the range `[0..99]` as the hash of a given string. * * @param {string} s The string to hash. * @returns {Int} The hashed value. */ static _percentFromString(s) { TString.check(s); const hash = crypto.createHash('sha256'); hash.update(s); const digest = hash.digest(); const value = digest.readUInt32LE(); // Grab first 32 bits as the base hash. const frac = value / 0x100000000; return Math.floor(frac * 100); } }
JavaScript
class Weather { constructor() { messaging.peerSocket.addEventListener("message", (evt) => { if (evt.data !== undefined && evt.data.command == "weather") { getWeather(); } }); } }
JavaScript
class SpriteBrush{ constructor(onCreate, mode = 'random') { this.sprites = []; this.overlaySprites = []; this.mode = mode; this.index = -1; this.total = 0; this.selected_sprite = {}; this.id = Gamelab.create_id(); onCreate = onCreate || function(){}; onCreate.bind(this); } addSprite(src, scale, callback) { this.sprites.push(new Gamelab.Sprite(src, scale)); if(callback) callback.bind(this).call(); } addOverlaySprite(src, scale, callback) { console.info(`SpriteFill().addOverlay(): --adds an overlay. Every overlay must fit with every sourceSprite, matching non-transparent pixels only`); this.overlaySprites.push(new Gamelab.Sprite(src, scale)); if(callback) callback.bind(this).call(); } removeAll(){ this.sprites = []; this.overlaySprites = []; } next(){ this.index += 1; switch(this.mode.toLowerCase()) { case 'random': var index = Math.floor(Math.random() * this.sprites.length); this.selected_sprite = this.sprites[index]; return this.selected_sprite; break; case 'consecutive': this.selected_sprite = this.sprites[this.index % this.sprites.length]; return this.selected_sprite; break; } } Clone(spritebrush) { var outputSprite = new Gamelab.SpriteBrush(); outputSprite.id = spritebrush.id; var oix = 0; spritebrush.sprites.forEach(function(sprite){ outputSprite.addSprite(sprite.src, sprite.size); oix += 1; }); spritebrush.overlaySprites.forEach(function(sprite){ outputSprite.addOverlaySprite(sprite.src, sprite.size); oix += 1; }); return outputSprite; } FromData(spritebrush) { var outputSprite = new Gamelab.SpriteBrush(); outputSprite.id = spritebrush.id; var oix = 0; spritebrush.sprites.forEach(function(sprite){ outputSprite.addSprite(sprite.src, sprite.size); oix += 1; }); spritebrush.overlaySprites.forEach(function(sprite){ outputSprite.addOverlaySprite(sprite.src, sprite.size); oix += 1; }); return outputSprite; } }
JavaScript
class Authentication { /** * @description Generates access token * @param {object} payload User credential(s) * @param {string} secret encryption key * @param {string} duration token expiry time * @returns {string} Access token */ static generateToken(payload, secret = seCrypt, duration = '7d') { return jwt.sign({ payload }, secret, { expiresIn: duration }); } /** * @description Verifies and decodes the access token * @param {string} token Access token * @param {string} secret decryption key * @returns {object} Decoded Access token */ static verifyToken(token, secret = seCrypt) { return jwt.verify(token, secret); } /** * @description Decodes the reset token * @param {string} token reset token * @returns {object} Decoded Access token */ static decodeToken(token) { return (jwt.decode(token)).payload; } }
JavaScript
class PipelineBuffer { /** * Constructor. */ constructor() { this.buffer = new Map(); } /** * * @param {string} pipelineName The name of the pipeline request. * @param {Array|string} dependant The pipeline request name of the dependant(s). */ set(pipelineName, dependant) { if (typeof pipelineName !== 'string') throw new Error(`Expected string for 'pipelineName'. Received: '${typeof pipelineName}'`); if (!dependant) throw new Error('No dependant was set!'); if (!Array.isArray(dependant) && typeof dependant !== 'string') { throw new Error(`Expected string or array for 'dependant'. Received: '${typeof dependant}'`); } const dependants = [].concat(dependant); const entry = this.buffer.get(pipelineName); if (!entry) { this.buffer.set(pipelineName, dependants); return; } this.buffer.set(pipelineName, [ ...entry, ...dependants, ]); } /** * Returns the dependants of a pipeline request. * @param {string} pipelineName The name of the pipeline request to get the dependants for. * @return {Array} */ get(pipelineName) { if (typeof pipelineName !== 'string') throw new Error(`Expected string for 'pipelineName'. Received: '${typeof pipelineName}'`); const entry = this.buffer.get(pipelineName); if (!entry) return DEFAULT_ENTRY; return entry; } }
JavaScript
class Polyfill { /** * 兼容不支持es6方法的浏览器 */ static install() { // ES6 Object.setPrototypeOf Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) { obj.__proto__ = proto; return obj; }; // ES6 Object.assign Object.assign = Object.assign || function (target) { if (target === undefined || target === null) { throw new TypeError('Cannot convert undefined or null to object'); } let output = Object(target); for (let i = 1; i < arguments.length; i++) { let source = arguments[i]; if (source !== undefined && source !== null) { for (let key in source) { if (source.hasOwnProperty(key)) { output[key] = source[key]; } } } } return output; }; // ES6 Promise (missing support in IE11) if (typeof self.Promise !== 'function') { require('es6-promise').polyfill(); } } }
JavaScript
class BookDetailContainer extends Component { constructor(props) { super(props); } componentWillMount() { this.props.fetchBook(this.props.params.bookId) } render() { if (!this.props.fetching) { return ( <div> <BookDetails book={this.props.book} /> </div> ) } return ( <div>Loading</div> ) } }
JavaScript
class ModbusSerialServer extends ModbusSlave { /** * Create a Modbus Tcp Server. * @param {number} p Port to listen. * @param {string} tp. Transport layer. Can be tcp, udp4 or udp6 * @param {number} modbusAddress. address based on modbus protocol * @param {string} mode mode of work. 'rtu' frame rtu only, 'ascii' frame ascii only, 'auto' (default) both mode */ constructor(p = 502, tp='tcp', modbusAddress = 1, mode = 'rtu'){ super(modbusAddress); var self = this; var transportProtocol if(typeof tp == 'string'){ transportProtocol = tp } else{ throw new TypeError('transport protocol should be a string') } /** * network layer * @type {object} */ switch(transportProtocol){ case 'udp4': this.netServer = new udpServer(p, 'udp4'); break; case 'udp6': this.netServer = new udpServer(p, 'udp6'); break; default: this.netServer = new tcpServer(p); } //Adding listeners to netServer events this.netServer.onData = this.ProcessModbusIndication.bind(this); /** * @fires ModbusnetServer#connection */ this.netServer.onConnection = function EmitConnection (socket) { /** * connection event. * Emited when new connecton is sablished * @event ModbusnetServer#connection * @type {object} * @see https://nodejs.org/api/net.html */ this.emit('connection',socket); }.bind(this); /** * Event connection closed * Emited when socket closed * @see https://nodejs.org/api/net.html * @fires ModbusnetServer#connection-closed */ this.netServer.onConnectionClose = function EmitConnectionClosed(socket){ /** * connection-closed event. * @event ModbusnetServer#connection-closed * @type {object} */ this.emit('connection-closed', socket) }.bind(this); /** * Event listening * Emited when server is listening * @see https://nodejs.org/api/net.html * @fires ModbusnetServer#listening */ this.netServer.onListening = function EmitListening(port){ /** * listening event. * @event ModbusnetServer#listening * @type {number} */ this.emit('listening',self.port); }.bind(this); /** * Event closed * Emited when server is closed * @see https://nodejs.org/api/net.html * @fires ModbusnetServer#closed */ this.netServer.onServerClose = function EmitClosed(){ /** * closed event. * @event ModbusnetServer#closed */ this.emit('closed'); }.bind(this); /** * Event error * Emited when error hapen * @fires ModbusnetServer#error */ this.netServer.onError = function EmitError(err){ /** * error event. * @event ModbusnetServer#error */ this.emit('error', err); }.bind(this); /** * Event response * Emited when response is send to master * @fires ModbusnetServer#response */ this.netServer.onWrite = function EmitResponse(resp){ /** * response event. * @event ModbusnetServer#response */ this.emit('response', resp); this.resCounter++; }.bind(this); /** * Event client disconnect * Emited when client send fin packet * @fires ModbusnetServer#client-disconnect */ this.netServer.onClientEnd = function EmitClientDisconnect(socket){ /** * client-disconnect event. * @event ModbusnetServer#client-disconnect */ this.emit('client-disconnect',socket); } /** * mode * @type {string} */ this.mode = mode; /** * current req * If another req arrive while the current req is not null, exepction 5 should be sended * @type {Array} */ this.currentRequest = null; //Sellando el netServer Object.defineProperty(self, 'netServer', { enumerable:false, writable:false, configurable:false }) } get maxConnections(){ return this.netServer.maxConnections; } set maxConnections(max){ this.netServer.maxConnections = 1; } /** * Getter listening status */ get isListening(){ return this.netServer.isListening; } get port(){ return this.netServer.port } set port(newport){ this.netServer.port = newport } /** * Function to start the server */ Start(){ this.netServer.Start(); } /** * Function to stop the server */ Stop(){ this.netServer.Stop(); } /** * Function to execute when data are recive * @param {Buffer} aduBuffer frame received by server * @return {Buffer} response; * @fires ModbusnetServer#indication {Buffer} */ ProcessModbusIndication(connectionID, dataFrame){ var self = this; let socket = this.netServer.activeConnections[connectionID]; /** * indication event. * @event ModbusnetServer#indication */ this.emit('indication', socket, dataFrame); let req = new Request(self.mode); req.adu.aduBuffer = dataFrame; req.slaveID = self.address; let reqADUParsedOk = req.adu.ParseBuffer(); if(reqADUParsedOk){ //add req to request stack self.reqCounter++; req.id = self.reqCounter; self.emit('request', socket, req); //creating Response var resp = new Response(self.mode); if(this.currentRequest == null){ let respADU = self.CreateRespSerialADU(req.adu); if(respADU != null){ resp.connectionID = connectionID; self.currentRequest = req; resp.adu = self.CreateRespSerialADU(req.adu); resp.id = self.resCounter; resp.adu.MakeBuffer(); resp.timeStamp = Date.now(); resp.data = self.ParseResponsePDU(resp.adu.pdu, req.adu.pdu); self.resCounter++; //removing req from req stak self.currentRequest = null; self.netServer.Write(connectionID, resp); } } else{ //response modbus exeption 6 slave Busy resp.adu.pdu = self.MakeModbusException(req.adu.pdu, 6); resp.adu.MakeBuffer(); resp.timeStamp = Date.now(); resp.data = self.ParseResponsePDU(resp.adu.pdu, req.adu.pdu); self.resCounter++ self.netServer.Write(connectionID, resp); } return true; } else { return false; } } }
JavaScript
class AudioListenerComponentSystem extends ComponentSystem { constructor(app, manager) { super(app); this.id = "audiolistener"; this.ComponentType = AudioListenerComponent; this.DataType = AudioListenerComponentData; this.schema = _schema; this.manager = manager; this.current = null; this.app.systems.on('update', this.onUpdate, this); } initializeComponentData(component, data, properties) { properties = ['enabled']; super.initializeComponentData(component, data, properties); } onUpdate(dt) { if (this.current) { const position = this.current.getPosition(); this.manager.listener.setPosition(position); const wtm = this.current.getWorldTransform(); this.manager.listener.setOrientation(wtm); } } destroy() { super.destroy(); this.app.systems.off('update', this.onUpdate, this); } }
JavaScript
class Analytics { constructor(client) { this.client = client; this.itineraryPriceMetrics = new ItineraryPriceMetrics(client); } }
JavaScript
class Tooltip extends Component { render() { return <LeafletTooltip {...this.props} /> } }
JavaScript
class ResponseDto { /** * Create new auto response data. * @param {String[]} trigger - The regex to trigger. * @param {String} response - What to respond with or the image location. * @param {String} title - What to put as the title of the response. */ constructor(trigger = [''], response = '', title = '') { this.trigger = trigger; this.response = response; this.title = title; } /** * Serializes the auto response object. * @returns {object} A JSON representation of the auto response. */ toJSON() { return { trigger: this.trigger, response: this.response, title: this.title, }; } /** * Deserialize JSON data. * @param {object} object - The object to deserialize. * @returns {ResponseDto} The auto response object from the JSON. */ static fromJSON(object) { return new ResponseDto(object.trigger, object.response, object.title); } }
JavaScript
@Route("/") class GetRoute { // the HTTP method, e.g GET, POST, PUT, etc. @Method("GET") // method name can be anything get(ctx) { ctx.body = "Hello world!"; // you can send json in the form of an object or a string: // ctx.body = {test: 123}; // ctx.body = `{"test": 123}`; } }
JavaScript
class KeyboardShortcuts { constructor(diagnosticUpdater) { this._index = null; this._diagnostics = []; this._subscriptions = new (_UniversalDisposable || _load_UniversalDisposable()).default(); const first = () => this.setIndex(0); const last = () => this.setIndex(this._diagnostics.length - 1); this._subscriptions.add(diagnosticUpdater.allMessageUpdates.subscribe(diagnostics => { this._diagnostics = diagnostics.filter(diagnostic => diagnostic.scope === 'file'); this._index = null; this._traceIndex = null; }), atom.commands.add('atom-workspace', 'diagnostics:go-to-first-diagnostic', first), atom.commands.add('atom-workspace', 'diagnostics:go-to-last-diagnostic', last), atom.commands.add('atom-workspace', 'diagnostics:go-to-next-diagnostic', () => { this._index == null ? first() : this.setIndex(this._index + 1); }), atom.commands.add('atom-workspace', 'diagnostics:go-to-previous-diagnostic', () => { this._index == null ? last() : this.setIndex(this._index - 1); }), atom.commands.add('atom-workspace', 'diagnostics:go-to-next-diagnostic-trace', () => { this.nextTrace(); }), atom.commands.add('atom-workspace', 'diagnostics:go-to-previous-diagnostic-trace', () => { this.previousTrace(); })); } setIndex(index) { this._traceIndex = null; if (this._diagnostics.length === 0) { this._index = null; return; } this._index = Math.max(0, Math.min(index, this._diagnostics.length - 1)); this.gotoCurrentIndex(); } gotoCurrentIndex() { if (!(this._index != null)) { throw new Error('Invariant violation: "this._index != null"'); } if (!(this._traceIndex == null)) { throw new Error('Invariant violation: "this._traceIndex == null"'); } const diagnostic = this._diagnostics[this._index]; const range = diagnostic.range; if (range == null) { (0, (_goToLocation || _load_goToLocation()).goToLocation)(diagnostic.filePath); } else { (0, (_goToLocation || _load_goToLocation()).goToLocation)(diagnostic.filePath, range.start.row, range.start.column); } } nextTrace() { const traces = this.currentTraces(); if (traces == null) { return; } let candidateTrace = this._traceIndex == null ? 0 : this._traceIndex + 1; while (candidateTrace < traces.length) { if (this.trySetCurrentTrace(traces, candidateTrace)) { return; } candidateTrace++; } this._traceIndex = null; this.gotoCurrentIndex(); } previousTrace() { const traces = this.currentTraces(); if (traces == null) { return; } let candidateTrace = this._traceIndex == null ? traces.length - 1 : this._traceIndex - 1; while (candidateTrace >= 0) { if (this.trySetCurrentTrace(traces, candidateTrace)) { return; } candidateTrace--; } this._traceIndex = null; this.gotoCurrentIndex(); } currentTraces() { if (this._index == null) { return null; } const diagnostic = this._diagnostics[this._index]; return diagnostic.trace; } // TODO: Should filter out traces whose location matches the main diagnostic's location? trySetCurrentTrace(traces, traceIndex) { const trace = traces[traceIndex]; if (trace.filePath != null && trace.range != null) { this._traceIndex = traceIndex; (0, (_goToLocation || _load_goToLocation()).goToLocation)(trace.filePath, trace.range.start.row, trace.range.start.column); return true; } return false; } dispose() { this._subscriptions.dispose(); } }
JavaScript
class NamedExpression{ constructor(name, value) { this.onChange = []; this.name = name; this._value = value; } get value(){ return this._value; } set value(v){ if (v !== this._value){ this._value = v; for (var i = 0; i < this.onChange.length; i++){ this.onChange[i].update(); } } } register(obs){ this.onChange.push(obs); } update(){ } }
JavaScript
class Token { /** * Constructor. * * @param {TokenName} name token name. * @param {any} value token value. */ constructor(name, value) { this.name = name; this.value = value; } /** * Is name. * * @param {TokenName} name token name. * @return {boolean} is name. */ is(name) { return this.name === name; } /** * Gets the token value as byte. * * @return {number} token value as byte. */ asByte() { return this.value & 0xFF; } /** * Gets the token value as address. * * @return {number} token value as address. */ asAddress() { return this.value & 0xFFF; } /** * Gets the token value as register. * * @return {number} token value as register. */ asRegister() { return this.value & 0xF; } /** * Gets as register X. * * @return {number} register X. */ asRegisterX() { return this.asRegister() << 8; } /** * Gets as register Y. * * @return {number} register Y. */ asRegisterY() { return this.asRegister() << 4; } }
JavaScript
class Node { /** * Basic contructor for the Node. * @param {*} data is the object to store inside the node */ constructor(data) { this.data = data this.next = null } }
JavaScript
class OnboardingChooseDestinationPageElement extends PolymerElement { static get is() { return 'onboarding-choose-destination-page'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** @private */ destinationOwner_: { type: String, value: '', }, }; } constructor() { super(); /** @private {ShimlessRmaServiceInterface} */ this.shimlessRmaService_ = getShimlessRmaService(); } /** * @param {!CustomEvent<{value: string}>} event * @protected */ onDestinationSelectionChanged_(event) { this.destinationOwner_ = event.detail.value; const disabled = !this.destinationOwner_; this.dispatchEvent(new CustomEvent( 'disable-next-button', {bubbles: true, composed: true, detail: disabled}, )); } /** @return {!Promise<!StateResult>} */ onNextButtonClick() { if (this.destinationOwner_ === 'originalOwner') { return this.shimlessRmaService_.setSameOwner(); } else if (this.destinationOwner_ === 'newOwner') { return this.shimlessRmaService_.setDifferentOwner(); } else { return Promise.reject(new Error('No destination selected')); } } }
JavaScript
class TemplateInstance { constructor(template, processor, options) { this.__parts = []; this.template = template; this.processor = processor; this.options = options; } update(values) { let i = 0; for (const part of this.__parts) { if (part !== undefined) { part.setValue(values[i]); } i++; } for (const part of this.__parts) { if (part !== undefined) { part.commit(); } } } _clone() { // There are a number of steps in the lifecycle of a template instance's // DOM fragment: // 1. Clone - create the instance fragment // 2. Adopt - adopt into the main document // 3. Process - find part markers and create parts // 4. Upgrade - upgrade custom elements // 5. Update - set node, attribute, property, etc., values // 6. Connect - connect to the document. Optional and outside of this // method. // // We have a few constraints on the ordering of these steps: // * We need to upgrade before updating, so that property values will pass // through any property setters. // * We would like to process before upgrading so that we're sure that the // cloned fragment is inert and not disturbed by self-modifying DOM. // * We want custom elements to upgrade even in disconnected fragments. // // Given these constraints, with full custom elements support we would // prefer the order: Clone, Process, Adopt, Upgrade, Update, Connect // // But Safari does not implement CustomElementRegistry#upgrade, so we // can not implement that order and still have upgrade-before-update and // upgrade disconnected fragments. So we instead sacrifice the // process-before-upgrade constraint, since in Custom Elements v1 elements // must not modify their light DOM in the constructor. We still have issues // when co-existing with CEv0 elements like Polymer 1, and with polyfills // that don't strictly adhere to the no-modification rule because shadow // DOM, which may be created in the constructor, is emulated by being placed // in the light DOM. // // The resulting order is on native is: Clone, Adopt, Upgrade, Process, // Update, Connect. document.importNode() performs Clone, Adopt, and Upgrade // in one step. // // The Custom Elements v1 polyfill supports upgrade(), so the order when // polyfilled is the more ideal: Clone, Process, Adopt, Upgrade, Update, // Connect. const fragment = _dom.isCEPolyfill ? this.template.element.content.cloneNode(true) : document.importNode(this.template.element.content, true); const stack = []; const parts = this.template.parts; // Edge needs all 4 parameters present; IE11 needs 3rd parameter to be null const walker = document.createTreeWalker(fragment, 133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */ , null, false); let partIndex = 0; let nodeIndex = 0; let part; let node = walker.nextNode(); // Loop through all the nodes and parts of a template while (partIndex < parts.length) { part = parts[partIndex]; if (!(0, _template.isTemplatePartActive)(part)) { this.__parts.push(undefined); partIndex++; continue; } // Progress the tree walker until we find our next part's node. // Note that multiple parts may share the same node (attribute parts // on a single element), so this loop may not run at all. while (nodeIndex < part.index) { nodeIndex++; if (node.nodeName === 'TEMPLATE') { stack.push(node); walker.currentNode = node.content; } if ((node = walker.nextNode()) === null) { // We've exhausted the content inside a nested template element. // Because we still have parts (the outer for-loop), we know: // - There is a template in the stack // - The walker will find a nextNode outside the template walker.currentNode = stack.pop(); node = walker.nextNode(); } } // We've arrived at our part's node. if (part.type === 'node') { const part = this.processor.handleTextExpression(this.options); part.insertAfterNode(node.previousSibling); this.__parts.push(part); } else { this.__parts.push(...this.processor.handleAttributeExpressions(node, part.name, part.strings, this.options)); } partIndex++; } if (_dom.isCEPolyfill) { document.adoptNode(fragment); customElements.upgrade(fragment); } return fragment; } }
JavaScript
class TemplateResult { constructor(strings, values, type, processor) { this.strings = strings; this.values = values; this.type = type; this.processor = processor; } /** * Returns a string of HTML used to create a `<template>` element. */ getHTML() { const l = this.strings.length - 1; let html = ''; let isCommentBinding = false; for (let i = 0; i < l; i++) { const s = this.strings[i]; // For each binding we want to determine the kind of marker to insert // into the template source before it's parsed by the browser's HTML // parser. The marker type is based on whether the expression is in an // attribute, text, or comment position. // * For node-position bindings we insert a comment with the marker // sentinel as its text content, like <!--{{lit-guid}}-->. // * For attribute bindings we insert just the marker sentinel for the // first binding, so that we support unquoted attribute bindings. // Subsequent bindings can use a comment marker because multi-binding // attributes must be quoted. // * For comment bindings we insert just the marker sentinel so we don't // close the comment. // // The following code scans the template source, but is *not* an HTML // parser. We don't need to track the tree structure of the HTML, only // whether a binding is inside a comment, and if not, if it appears to be // the first binding in an attribute. const commentOpen = s.lastIndexOf('<!--'); // We're in comment position if we have a comment open with no following // comment close. Because <-- can appear in an attribute value there can // be false positives. isCommentBinding = (commentOpen > -1 || isCommentBinding) && s.indexOf('-->', commentOpen + 1) === -1; // Check to see if we have an attribute-like sequence preceding the // expression. This can match "name=value" like structures in text, // comments, and attribute values, so there can be false-positives. const attributeMatch = _template.lastAttributeNameRegex.exec(s); if (attributeMatch === null) { // We're only in this branch if we don't have a attribute-like // preceding sequence. For comments, this guards against unusual // attribute values like <div foo="<!--${'bar'}">. Cases like // <!-- foo=${'bar'}--> are handled correctly in the attribute branch // below. html += s + (isCommentBinding ? commentMarker : _template.nodeMarker); } else { // For attributes we use just a marker sentinel, and also append a // $lit$ suffix to the name to opt-out of attribute-specific parsing // that IE and Edge do for style and certain SVG attributes. html += s.substr(0, attributeMatch.index) + attributeMatch[1] + attributeMatch[2] + _template.boundAttributeSuffix + attributeMatch[3] + _template.marker; } } html += this.strings[l]; return html; } getTemplateElement() { const template = document.createElement('template'); template.innerHTML = this.getHTML(); return template; } }
JavaScript
class DefaultTemplateProcessor { /** * Create parts for an attribute-position binding, given the event, attribute * name, and string literals. * * @param element The element containing the binding * @param name The attribute name * @param strings The string literals. There are always at least two strings, * event for fully-controlled bindings with a single expression. */ handleAttributeExpressions(element, name, strings, options) { const prefix = name[0]; if (prefix === '.') { const committer = new _parts.PropertyCommitter(element, name.slice(1), strings); return committer.parts; } if (prefix === '@') { return [new _parts.EventPart(element, name.slice(1), options.eventContext)]; } if (prefix === '?') { return [new _parts.BooleanAttributePart(element, name.slice(1), strings)]; } const committer = new _parts.AttributeCommitter(element, name, strings); return committer.parts; } /** * Create parts for a text-position binding. * @param templateFactory */ handleTextExpression(options) { return new _parts.NodePart(options); } }
JavaScript
class UpdatingElement extends HTMLElement { constructor() { super(); this._updateState = 0; this._instanceProperties = undefined; // Initialize to an unresolved Promise so we can make sure the element has // connected before first update. this._updatePromise = new Promise(res => this._enableUpdatingResolver = res); /** * Map with keys for any properties that have changed since the last * update cycle with previous values. */ this._changedProperties = new Map(); /** * Map with keys of properties that should be reflected when updated. */ this._reflectingProperties = undefined; this.initialize(); } /** * Returns a list of attributes corresponding to the registered properties. * @nocollapse */ static get observedAttributes() { // note: piggy backing on this to ensure we're finalized. this.finalize(); const attributes = []; // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays this._classProperties.forEach((v, p) => { const attr = this._attributeNameForProperty(p, v); if (attr !== undefined) { this._attributeToPropertyMap.set(attr, p); attributes.push(attr); } }); return attributes; } /** * Ensures the private `_classProperties` property metadata is created. * In addition to `finalize` this is also called in `createProperty` to * ensure the `@property` decorator can add property metadata. */ /** @nocollapse */ static _ensureClassProperties() { // ensure private storage for property declarations. if (!this.hasOwnProperty(JSCompiler_renameProperty('_classProperties', this))) { this._classProperties = new Map(); // NOTE: Workaround IE11 not supporting Map constructor argument. const superProperties = Object.getPrototypeOf(this)._classProperties; if (superProperties !== undefined) { superProperties.forEach((v, k) => this._classProperties.set(k, v)); } } } /** * Creates a property accessor on the element prototype if one does not exist * and stores a PropertyDeclaration for the property with the given options. * The property setter calls the property's `hasChanged` property option * or uses a strict identity check to determine whether or not to request * an update. * * This method may be overridden to customize properties; however, * when doing so, it's important to call `super.createProperty` to ensure * the property is setup correctly. This method calls * `getPropertyDescriptor` internally to get a descriptor to install. * To customize what properties do when they are get or set, override * `getPropertyDescriptor`. To customize the options for a property, * implement `createProperty` like this: * * static createProperty(name, options) { * options = Object.assign(options, {myOption: true}); * super.createProperty(name, options); * } * * @nocollapse */ static createProperty(name, options = defaultPropertyDeclaration) { // Note, since this can be called by the `@property` decorator which // is called before `finalize`, we ensure storage exists for property // metadata. this._ensureClassProperties(); this._classProperties.set(name, options); // Do not generate an accessor if the prototype already has one, since // it would be lost otherwise and that would never be the user's intention; // Instead, we expect users to call `requestUpdate` themselves from // user-defined accessors. Note that if the super has an accessor we will // still overwrite it if (options.noAccessor || this.prototype.hasOwnProperty(name)) { return; } const key = typeof name === 'symbol' ? Symbol() : `__${name}`; const descriptor = this.getPropertyDescriptor(name, key, options); if (descriptor !== undefined) { Object.defineProperty(this.prototype, name, descriptor); } } /** * Returns a property descriptor to be defined on the given named property. * If no descriptor is returned, the property will not become an accessor. * For example, * * class MyElement extends LitElement { * static getPropertyDescriptor(name, key, options) { * const defaultDescriptor = * super.getPropertyDescriptor(name, key, options); * const setter = defaultDescriptor.set; * return { * get: defaultDescriptor.get, * set(value) { * setter.call(this, value); * // custom action. * }, * configurable: true, * enumerable: true * } * } * } * * @nocollapse */ static getPropertyDescriptor(name, key, _options) { return { // tslint:disable-next-line:no-any no symbol in index get() { return this[key]; }, set(value) { const oldValue = this[name]; this[key] = value; this._requestUpdate(name, oldValue); }, configurable: true, enumerable: true }; } /** * Returns the property options associated with the given property. * These options are defined with a PropertyDeclaration via the `properties` * object or the `@property` decorator and are registered in * `createProperty(...)`. * * Note, this method should be considered "final" and not overridden. To * customize the options for a given property, override `createProperty`. * * @nocollapse * @final */ static getPropertyOptions(name) { return this._classProperties && this._classProperties.get(name) || defaultPropertyDeclaration; } /** * Creates property accessors for registered properties and ensures * any superclasses are also finalized. * @nocollapse */ static finalize() { // finalize any superclasses const superCtor = Object.getPrototypeOf(this); if (!superCtor.hasOwnProperty(finalized)) { superCtor.finalize(); } this[finalized] = true; this._ensureClassProperties(); // initialize Map populated in observedAttributes this._attributeToPropertyMap = new Map(); // make any properties // Note, only process "own" properties since this element will inherit // any properties defined on the superClass, and finalization ensures // the entire prototype chain is finalized. if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) { const props = this.properties; // support symbols in properties (IE11 does not support this) const propKeys = [...Object.getOwnPropertyNames(props), ...(typeof Object.getOwnPropertySymbols === 'function' ? Object.getOwnPropertySymbols(props) : [])]; // This for/of is ok because propKeys is an array for (const p of propKeys) { // note, use of `any` is due to TypeSript lack of support for symbol in // index types // tslint:disable-next-line:no-any no symbol in index this.createProperty(p, props[p]); } } } /** * Returns the property name for the given attribute `name`. * @nocollapse */ static _attributeNameForProperty(name, options) { const attribute = options.attribute; return attribute === false ? undefined : typeof attribute === 'string' ? attribute : typeof name === 'string' ? name.toLowerCase() : undefined; } /** * Returns true if a property should request an update. * Called when a property value is set and uses the `hasChanged` * option for the property if present or a strict identity check. * @nocollapse */ static _valueHasChanged(value, old, hasChanged = notEqual) { return hasChanged(value, old); } /** * Returns the property value for the given attribute value. * Called via the `attributeChangedCallback` and uses the property's * `converter` or `converter.fromAttribute` property option. * @nocollapse */ static _propertyValueFromAttribute(value, options) { const type = options.type; const converter = options.converter || defaultConverter; const fromAttribute = typeof converter === 'function' ? converter : converter.fromAttribute; return fromAttribute ? fromAttribute(value, type) : value; } /** * Returns the attribute value for the given property value. If this * returns undefined, the property will *not* be reflected to an attribute. * If this returns null, the attribute will be removed, otherwise the * attribute will be set to the value. * This uses the property's `reflect` and `type.toAttribute` property options. * @nocollapse */ static _propertyValueToAttribute(value, options) { if (options.reflect === undefined) { return; } const type = options.type; const converter = options.converter; const toAttribute = converter && converter.toAttribute || defaultConverter.toAttribute; return toAttribute(value, type); } /** * Performs element initialization. By default captures any pre-set values for * registered properties. */ initialize() { this._saveInstanceProperties(); // ensures first update will be caught by an early access of // `updateComplete` this._requestUpdate(); } /** * Fixes any properties set on the instance before upgrade time. * Otherwise these would shadow the accessor and break these properties. * The properties are stored in a Map which is played back after the * constructor runs. Note, on very old versions of Safari (<=9) or Chrome * (<=41), properties created for native platform properties like (`id` or * `name`) may not have default values set in the element constructor. On * these browsers native properties appear on instances and therefore their * default value will overwrite any element default (e.g. if the element sets * this.id = 'id' in the constructor, the 'id' will become '' since this is * the native platform default). */ _saveInstanceProperties() { // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays this.constructor._classProperties.forEach((_v, p) => { if (this.hasOwnProperty(p)) { const value = this[p]; delete this[p]; if (!this._instanceProperties) { this._instanceProperties = new Map(); } this._instanceProperties.set(p, value); } }); } /** * Applies previously saved instance properties. */ _applyInstanceProperties() { // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays // tslint:disable-next-line:no-any this._instanceProperties.forEach((v, p) => this[p] = v); this._instanceProperties = undefined; } connectedCallback() { // Ensure first connection completes an update. Updates cannot complete // before connection. this.enableUpdating(); } enableUpdating() { if (this._enableUpdatingResolver !== undefined) { this._enableUpdatingResolver(); this._enableUpdatingResolver = undefined; } } /** * Allows for `super.disconnectedCallback()` in extensions while * reserving the possibility of making non-breaking feature additions * when disconnecting at some point in the future. */ disconnectedCallback() {} /** * Synchronizes property values when attributes change. */ attributeChangedCallback(name, old, value) { if (old !== value) { this._attributeToProperty(name, value); } } _propertyToAttribute(name, value, options = defaultPropertyDeclaration) { const ctor = this.constructor; const attr = ctor._attributeNameForProperty(name, options); if (attr !== undefined) { const attrValue = ctor._propertyValueToAttribute(value, options); // an undefined value does not change the attribute. if (attrValue === undefined) { return; } // Track if the property is being reflected to avoid // setting the property again via `attributeChangedCallback`. Note: // 1. this takes advantage of the fact that the callback is synchronous. // 2. will behave incorrectly if multiple attributes are in the reaction // stack at time of calling. However, since we process attributes // in `update` this should not be possible (or an extreme corner case // that we'd like to discover). // mark state reflecting this._updateState = this._updateState | STATE_IS_REFLECTING_TO_ATTRIBUTE; if (attrValue == null) { this.removeAttribute(attr); } else { this.setAttribute(attr, attrValue); } // mark state not reflecting this._updateState = this._updateState & ~STATE_IS_REFLECTING_TO_ATTRIBUTE; } } _attributeToProperty(name, value) { // Use tracking info to avoid deserializing attribute value if it was // just set from a property setter. if (this._updateState & STATE_IS_REFLECTING_TO_ATTRIBUTE) { return; } const ctor = this.constructor; // Note, hint this as an `AttributeMap` so closure clearly understands // the type; it has issues with tracking types through statics // tslint:disable-next-line:no-unnecessary-type-assertion const propName = ctor._attributeToPropertyMap.get(name); if (propName !== undefined) { const options = ctor.getPropertyOptions(propName); // mark state reflecting this._updateState = this._updateState | STATE_IS_REFLECTING_TO_PROPERTY; this[propName] = // tslint:disable-next-line:no-any ctor._propertyValueFromAttribute(value, options); // mark state not reflecting this._updateState = this._updateState & ~STATE_IS_REFLECTING_TO_PROPERTY; } } /** * This private version of `requestUpdate` does not access or return the * `updateComplete` promise. This promise can be overridden and is therefore * not free to access. */ _requestUpdate(name, oldValue) { let shouldRequestUpdate = true; // If we have a property key, perform property update steps. if (name !== undefined) { const ctor = this.constructor; const options = ctor.getPropertyOptions(name); if (ctor._valueHasChanged(this[name], oldValue, options.hasChanged)) { if (!this._changedProperties.has(name)) { this._changedProperties.set(name, oldValue); } // Add to reflecting properties set. // Note, it's important that every change has a chance to add the // property to `_reflectingProperties`. This ensures setting // attribute + property reflects correctly. if (options.reflect === true && !(this._updateState & STATE_IS_REFLECTING_TO_PROPERTY)) { if (this._reflectingProperties === undefined) { this._reflectingProperties = new Map(); } this._reflectingProperties.set(name, options); } } else { // Abort the request if the property should not be considered changed. shouldRequestUpdate = false; } } if (!this._hasRequestedUpdate && shouldRequestUpdate) { this._updatePromise = this._enqueueUpdate(); } } /** * Requests an update which is processed asynchronously. This should * be called when an element should update based on some state not triggered * by setting a property. In this case, pass no arguments. It should also be * called when manually implementing a property setter. In this case, pass the * property `name` and `oldValue` to ensure that any configured property * options are honored. Returns the `updateComplete` Promise which is resolved * when the update completes. * * @param name {PropertyKey} (optional) name of requesting property * @param oldValue {any} (optional) old value of requesting property * @returns {Promise} A Promise that is resolved when the update completes. */ requestUpdate(name, oldValue) { this._requestUpdate(name, oldValue); return this.updateComplete; } /** * Sets up the element to asynchronously update. */ async _enqueueUpdate() { this._updateState = this._updateState | STATE_UPDATE_REQUESTED; try { // Ensure any previous update has resolved before updating. // This `await` also ensures that property changes are batched. await this._updatePromise; } catch (e) {// Ignore any previous errors. We only care that the previous cycle is // done. Any error should have been handled in the previous update. } const result = this.performUpdate(); // If `performUpdate` returns a Promise, we await it. This is done to // enable coordinating updates with a scheduler. Note, the result is // checked to avoid delaying an additional microtask unless we need to. if (result != null) { await result; } return !this._hasRequestedUpdate; } get _hasRequestedUpdate() { return this._updateState & STATE_UPDATE_REQUESTED; } get hasUpdated() { return this._updateState & STATE_HAS_UPDATED; } /** * Performs an element update. Note, if an exception is thrown during the * update, `firstUpdated` and `updated` will not be called. * * You can override this method to change the timing of updates. If this * method is overridden, `super.performUpdate()` must be called. * * For instance, to schedule updates to occur just before the next frame: * * ``` * protected async performUpdate(): Promise<unknown> { * await new Promise((resolve) => requestAnimationFrame(() => resolve())); * super.performUpdate(); * } * ``` */ performUpdate() { // Mixin instance properties once, if they exist. if (this._instanceProperties) { this._applyInstanceProperties(); } let shouldUpdate = false; const changedProperties = this._changedProperties; try { shouldUpdate = this.shouldUpdate(changedProperties); if (shouldUpdate) { this.update(changedProperties); } else { this._markUpdated(); } } catch (e) { // Prevent `firstUpdated` and `updated` from running when there's an // update exception. shouldUpdate = false; // Ensure element can accept additional updates after an exception. this._markUpdated(); throw e; } if (shouldUpdate) { if (!(this._updateState & STATE_HAS_UPDATED)) { this._updateState = this._updateState | STATE_HAS_UPDATED; this.firstUpdated(changedProperties); } this.updated(changedProperties); } } _markUpdated() { this._changedProperties = new Map(); this._updateState = this._updateState & ~STATE_UPDATE_REQUESTED; } /** * Returns a Promise that resolves when the element has completed updating. * The Promise value is a boolean that is `true` if the element completed the * update without triggering another update. The Promise result is `false` if * a property was set inside `updated()`. If the Promise is rejected, an * exception was thrown during the update. * * To await additional asynchronous work, override the `_getUpdateComplete` * method. For example, it is sometimes useful to await a rendered element * before fulfilling this Promise. To do this, first await * `super._getUpdateComplete()`, then any subsequent state. * * @returns {Promise} The Promise returns a boolean that indicates if the * update resolved without triggering another update. */ get updateComplete() { return this._getUpdateComplete(); } /** * Override point for the `updateComplete` promise. * * It is not safe to override the `updateComplete` getter directly due to a * limitation in TypeScript which means it is not possible to call a * superclass getter (e.g. `super.updateComplete.then(...)`) when the target * language is ES5 (https://github.com/microsoft/TypeScript/issues/338). * This method should be overridden instead. For example: * * class MyElement extends LitElement { * async _getUpdateComplete() { * await super._getUpdateComplete(); * await this._myChild.updateComplete; * } * } */ _getUpdateComplete() { return this._updatePromise; } /** * Controls whether or not `update` should be called when the element requests * an update. By default, this method always returns `true`, but this can be * customized to control when to update. * * @param _changedProperties Map of changed properties with old values */ shouldUpdate(_changedProperties) { return true; } /** * Updates the element. This method reflects property values to attributes. * It can be overridden to render and keep updated element DOM. * Setting properties inside this method will *not* trigger * another update. * * @param _changedProperties Map of changed properties with old values */ update(_changedProperties) { if (this._reflectingProperties !== undefined && this._reflectingProperties.size > 0) { // Use forEach so this works even if for/of loops are compiled to for // loops expecting arrays this._reflectingProperties.forEach((v, k) => this._propertyToAttribute(k, this[k], v)); this._reflectingProperties = undefined; } this._markUpdated(); } /** * Invoked whenever the element is updated. Implement to perform * post-updating tasks via DOM APIs, for example, focusing an element. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values */ updated(_changedProperties) {} /** * Invoked when the element is first updated. Implement to perform one time * work on the element after update. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values */ firstUpdated(_changedProperties) {} }
JavaScript
class ClassList { constructor(element) { this.classes = new Set(); this.changed = false; this.element = element; const classList = (element.getAttribute('class') || '').split(/\s+/); for (const cls of classList) { this.classes.add(cls); } } add(cls) { this.classes.add(cls); this.changed = true; } remove(cls) { this.classes.delete(cls); this.changed = true; } commit() { if (this.changed) { let classString = ''; this.classes.forEach(cls => classString += cls + ' '); this.element.setAttribute('class', classString); } } }
JavaScript
class Product extends BOBasePage { /** * @constructs * Creating products page (selectors and static messages) */ constructor() { super(); this.pageTitle = 'Products •'; this.productDeletedSuccessfulMessage = 'Product successfully deleted.'; this.productMultiDeletedSuccessfulMessage = 'Product(s) successfully deleted.'; this.productDeactivatedSuccessfulMessage = 'Product successfully deactivated.'; this.productActivatedSuccessfulMessage = 'Product successfully activated.'; this.productMultiActivatedSuccessfulMessage = 'Product(s) successfully activated.'; this.productMultiDeactivatedSuccessfulMessage = 'Product(s) successfully deactivated.'; // Selectors // List of products this.productListForm = '#product_catalog_list'; this.productTable = `${this.productListForm} table`; this.productRow = `${this.productTable} tbody tr`; this.productListfooterRow = `${this.productListForm} div.row:nth-of-type(3)`; this.productNumberBloc = `${this.productListfooterRow} ul.pagination + div`; this.dropdownToggleButton = row => `${this.productRow}:nth-of-type(${row}) button.dropdown-toggle`; this.dropdownMenu = row => `${this.productRow}:nth-of-type(${row}) div.dropdown-menu`; this.dropdownMenuDeleteLink = row => `${this.dropdownMenu(row)} a.product-edit[onclick*='delete']`; this.dropdownMenuPreviewLink = row => `${this.dropdownMenu(row)} a.product-edit:not([onclick])`; this.dropdownMenuDuplicateLink = row => `${this.dropdownMenu(row)} a.product-edit[onclick*='duplicate']`; this.productRowEditLink = row => `${this.productRow}:nth-of-type(${row}) a.tooltip-link.product-edit`; this.selectAllBulkCheckboxLabel = '#catalog-actions div.md-checkbox label'; this.productBulkMenuButton = '#product_bulk_menu:not([disabled])'; this.productBulkMenuButtonState = state => `${this.productBulkMenuButton}[aria-expanded='${state}']`; this.productBulkDropdownMenu = 'div.bulk-catalog div.dropdown-menu.show'; this.productBulkDeleteLink = `${this.productBulkDropdownMenu} a[onclick*='delete_all']`; this.productBulkEnableLink = `${this.productBulkDropdownMenu} a[onclick*='activate_all']`; this.productBulkDisableLink = `${this.productBulkDropdownMenu} a[onclick*='deactivate_all']`; // Filters input this.productFilterIDMinInput = `${this.productListForm} #filter_column_id_product_min`; this.productFilterIDMaxInput = `${this.productListForm} #filter_column_id_product_max`; this.productFilterInput = filterBy => `${this.productListForm} input[name='filter_column_${filterBy}']`; this.productFilterSelect = filterBy => `${this.productListForm} select[name='filter_column_${filterBy}']`; this.productFilterPriceMinInput = `${this.productListForm} #filter_column_price_min`; this.productFilterPriceMaxInput = `${this.productListForm} #filter_column_price_max`; this.productFilterQuantityMinInput = `${this.productListForm} #filter_column_sav_quantity_min`; this.productFilterQuantityMaxInput = `${this.productListForm} #filter_column_sav_quantity_max`; this.filterSearchButton = `${this.productListForm} button[name='products_filter_submit']`; this.filterResetButton = `${this.productListForm} button[name='products_filter_reset']`; // Products list this.productsListTableRow = row => `${this.productRow}:nth-child(${row})`; this.productsListTableColumnID = row => `${this.productsListTableRow(row)}[data-product-id]`; this.productsListTableColumnName = row => `${this.productsListTableRow(row)} td:nth-child(4) a`; this.productsListTableColumnReference = row => `${this.productsListTableRow(row)} td:nth-child(5)`; this.productsListTableColumnCategory = row => `${this.productsListTableRow(row)} td:nth-child(6)`; this.productsListTableColumnPrice = row => `${this.productsListTableRow(row)} td:nth-child(7)`; this.productsListTableColumnQuantity = row => `${this.productsListTableRow(row)} td.product-sav-quantity`; this.productsListTableColumnStatus = row => `${this.productsListTableRow(row)} td:nth-child(9)`; this.productsListTableColumnStatusEnabled = row => `${this.productsListTableColumnStatus(row)} .action-enabled`; // Filter Category this.treeCategoriesBloc = '#tree-categories'; this.filterByCategoriesButton = '#product_catalog_category_tree_filter button'; this.filterByCategoriesUnselectButton = `${this.treeCategoriesBloc} a#product_catalog_category_tree_filter_reset`; // HEADER buttons this.addProductButton = '#page-header-desc-configuration-add'; // pagination this.paginationNextLink = '.page-item.next:not(.disabled) #pagination_next_url'; // Modal Dialog this.catalogDeletionModalDialog = '#catalog_deletion_modal div.modal-dialog'; this.modalDialogDeleteNowButton = `${this.catalogDeletionModalDialog} button[value='confirm']`; } /* Methods */ /** * Filter products Min - Max * @param page {Page} Browser tab * @param min {number} Minimum id to search * @param max {number} Maximum id to search * @return {Promise<void>} */ async filterIDProducts(page, min, max) { await page.type(this.productFilterIDMinInput, min.toString()); await page.type(this.productFilterIDMaxInput, max.toString()); await this.clickAndWaitForNavigation(page, this.filterSearchButton); } /** * Get Product ID * @param page {Page} Browser tab * @param row {number} Product row number in table * @returns {Promise<string>} */ async getProductIDFromList(page, row) { return this.getNumberFromText(page, this.productsListTableColumnID(row)); } /** * Get Product Name * @param page {Page} Browser tab * @param row {number} Product row number in table * @returns {Promise<string>} */ async getProductNameFromList(page, row) { return this.getTextContent(page, this.productsListTableColumnName(row)); } /** * Get Product Reference * @param page {Page} Browser tab * @param row {number} Product row number in table * @returns {Promise<string>} */ async getProductReferenceFromList(page, row) { return this.getTextContent(page, this.productsListTableColumnReference(row)); } /** * Get Product Category * @param page {Page} Browser tab * @param row {number} Product row number in table * @returns {Promise<string>} */ async getProductCategoryFromList(page, row) { return this.getTextContent(page, this.productsListTableColumnCategory(row)); } /** * Filter price Min - Max * @param page {Page} Browser tab * @param min {number} Minimum price to search * @param max {number} Maximum price to search * @return {Promise<void>} */ async filterPriceProducts(page, min, max) { await page.type(this.productFilterPriceMinInput, min.toString()); await page.type(this.productFilterPriceMaxInput, max.toString()); await this.clickAndWaitForNavigation(page, this.filterSearchButton); } /** * Get Product Price * @param page {Page} Browser tab * @param row {number} Product row number in table * @returns {Promise<number>} */ async getProductPriceFromList(page, row) { const text = await this.getTextContent(page, this.productsListTableColumnPrice(row)); const price = /\d+(\.\d+)?/g.exec(text).toString(); return parseFloat(price); } /** * Filter Quantity Min - Max * @param page {Page} Browser tab * @param min {number} Minimum quantity to search * @param max {number} Maximum quantity to search * @return {Promise<void>} */ async filterQuantityProducts(page, min, max) { await page.type(this.productFilterQuantityMinInput, min.toString()); await page.type(this.productFilterQuantityMaxInput, max.toString()); await this.clickAndWaitForNavigation(page, this.filterSearchButton); } /** * Get Product Quantity * @param page {Page} Browser tab * @param row {number} Product row number in table * @returns {Promise<string>} */ async getProductQuantityFromList(page, row) { return this.getNumberFromText(page, this.productsListTableColumnQuantity(row)); } /** * Filter products * @param page {Page} Browser tab * @param filterBy {string} Column name to filter with * @param value {string} String value to search * @param filterType {string} type of the filter (input / select) * @return {Promise<void>} */ async filterProducts(page, filterBy, value = '', filterType = 'input') { switch (filterType) { case 'input': switch (filterBy) { case 'id_product': await this.filterIDProducts(page, value.min, value.max); break; case 'price': await this.filterPriceProducts(page, value.min, value.max); break; case 'sav_quantity': await this.filterQuantityProducts(page, value.min, value.max); break; default: await page.type(this.productFilterInput(filterBy), value); } break; case 'select': await this.selectByVisibleText( page, this.productFilterSelect(filterBy), value ? 'Active' : 'Inactive', ); break; default: // Do nothing } // click on search await this.clickAndWaitForNavigation(page, this.filterSearchButton); } /** * Get Text Column * @param page {Page} Browser tab * @param column{string} Column name to get text from * @param row {number} Product row number in table * @returns {Promise<string|number>} */ async getTextColumn(page, column, row) { switch (column) { case 'id_product': return this.getProductIDFromList(page, row); case 'name': return this.getProductNameFromList(page, row); case 'reference': return this.getProductReferenceFromList(page, row); case 'name_category': return this.getProductCategoryFromList(page, row); case 'price': return this.getProductPriceFromList(page, row); case 'sav_quantity': return this.getProductQuantityFromList(page, row); case 'active': return this.getProductStatusFromList(page, row); default: // Do nothing } throw new Error(`${column} was not found as column`); } /** * Get content from all rows * @param page {Page} Browser tab * @param column {string} Column name to get text from * @return {Promise<Array>} */ async getAllRowsColumnContent(page, column) { const rowsNumber = await this.getNumberOfProductsFromList(page); const allRowsContentTable = []; for (let i = 1; i <= rowsNumber; i++) { const rowContent = await this.getTextColumn(page, column, i); await allRowsContentTable.push(rowContent); } return allRowsContentTable; } /** * Get number of products displayed in list * @param page {Page} Browser tab * @returns {Promise<number>} */ async getNumberOfProductsFromList(page) { const found = await this.elementVisible(page, this.paginationNextLink, 1000); // In case we filter products and there is only one page, link next from pagination does not appear if (!found) { return (await page.$$(this.productRow)).length; } const footerText = await this.getTextContent(page, this.productNumberBloc); const numberOfProduct = /\d+/g.exec(footerText.match(/out of ([0-9]+)/)).toString(); return parseInt(numberOfProduct, 10); } /** * Reset input filters * @param page {Page} Browser tab * @return {Promise<void>} */ async resetFilter(page) { if (!(await this.elementNotVisible(page, this.filterResetButton, 2000))) { await this.clickAndWaitForNavigation(page, this.filterResetButton); } await this.waitForVisibleSelector(page, this.filterSearchButton, 2000); } /** * Reset Filter And get number of elements in list * @param page {Page} Browser tab * @returns {Promise<number>} */ async resetAndGetNumberOfLines(page) { await this.resetFilter(page); return this.getNumberOfProductsFromList(page); } /** * Reset DropDown Filter Category * @param page {Page} Browser tab * @return {Promise<void>} */ async resetFilterCategory(page) { // Click and wait to be open await page.click(this.filterByCategoriesButton); await this.waitForVisibleSelector(page, `${this.filterByCategoriesButton}[aria-expanded='true']`); await Promise.all([ this.waitForVisibleSelector(page, `${this.filterByCategoriesButton}[aria-expanded='false']`), this.clickAndWaitForNavigation(page, this.filterByCategoriesUnselectButton), ]); } /** * GOTO form Add Product * @param page {Page} Browser tab * @return {Promise<void>} */ async goToAddProductPage(page) { await this.clickAndWaitForNavigation(page, this.addProductButton); } /** * GOTO edit products page from row * @param page {Page} Browser tab * @param row {number} Product row number in table * @returns {Promise<void>} */ async goToEditProductPage(page, row) { await this.clickAndWaitForNavigation(page, this.productRowEditLink(row)); } /** * Open row dropdown for a products * @param page {Page} Browser tab * @param row {number} Product row number in table * @return {Promise<void>} */ async openProductDropdown(page, row) { await Promise.all([ this.waitForVisibleSelector(page, `${this.dropdownToggleButton(row)}[aria-expanded='true']`), page.click(this.dropdownToggleButton(row)), ]); } /** * Duplicate products * @param page {Page} Browser tab * @param row {number} Product row number in table * @return {Promise<string>} */ async duplicateProduct(page, row) { // Open dropdown await this.openProductDropdown(page, row); // Duplicate products and go to add products page await this.clickAndWaitForNavigation(page, this.dropdownMenuDuplicateLink(row)); return this.getAlertSuccessBlockParagraphContent(page); } /** * Delete products with dropdown Menu * @param page {Page} Browser tab * @param productData * @returns {Promise<string>} */ async deleteProduct(page, productData) { // Filter By reference first await this.filterProducts(page, 'reference', productData.reference); // Then delete first products and only products shown await Promise.all([ this.waitForVisibleSelector(page, `${this.dropdownToggleButton(1)}[aria-expanded='true']`), page.click(this.dropdownToggleButton(1)), ]); await Promise.all([ this.waitForVisibleSelector(page, this.catalogDeletionModalDialog), page.click(this.dropdownMenuDeleteLink(1)), ]); await this.clickAndWaitForNavigation(page, this.modalDialogDeleteNowButton); return this.getAlertSuccessBlockParagraphContent(page); } /** * Delete All products with Bulk Actions * @param page {Page} Browser tab * @returns {Promise<string>} */ async deleteAllProductsWithBulkActions(page) { // Then delete first products and only products shown await Promise.all([ this.waitForVisibleSelector(page, this.productBulkMenuButton), page.click(this.selectAllBulkCheckboxLabel), ]); await Promise.all([ this.waitForVisibleSelector(page, this.productBulkMenuButtonState('true')), page.click(this.productBulkMenuButton), ]); await Promise.all([ this.waitForVisibleSelector(page, this.catalogDeletionModalDialog), page.click(this.productBulkDeleteLink), ]); await this.clickAndWaitForNavigation(page, this.modalDialogDeleteNowButton); return this.getAlertSuccessBlockParagraphContent(page); } /** * Bulk set status * @param page {Page} Browser tab * @param status {boolean} Wanted status of products * @return {Promise<string>} */ async bulkSetStatus(page, status) { await Promise.all([ this.waitForVisibleSelector(page, this.productBulkMenuButton), page.click(this.selectAllBulkCheckboxLabel), ]); await Promise.all([ this.waitForVisibleSelector(page, this.productBulkMenuButtonState('true')), page.click(this.productBulkMenuButton), ]); await this.clickAndWaitForNavigation(page, status ? this.productBulkEnableLink : this.productBulkDisableLink); return this.getAlertSuccessBlockParagraphContent(page); } /** * Get Value of column Displayed * @param page {Page} Browser tab * @param row {number} Product row number in table, row in table * @return {Promise<boolean>} */ async getProductStatusFromList(page, row) { return this.elementVisible(page, this.productsListTableColumnStatusEnabled(row), 100); } /** * Quick edit toggle column value * @param page {Page} Browser tab * @param row {number} Product row number in table, row in table * @param status {boolean} Value wanted in column * @return {Promise<boolean>} return true if action is done, false otherwise */ async setProductStatus(page, row, status = true) { await this.waitForVisibleSelector(page, this.productsListTableColumnStatus(row), 2000); const actualStatus = await this.getProductStatusFromList(page, row); if (actualStatus !== status) { await this.clickAndWaitForNavigation(page, this.productsListTableColumnStatus(row)); return true; } return false; } }
JavaScript
class Header extends React.Component { static propTypes = { name: PropTypes.string.isRequired, routes: PropTypes.arrayOf(PropTypes.object).isRequired, }; render() { return ( <div> {this.props.routes ? ( <ButtonAppBar title={this.props.name} routes={this.props.routes} /> ) : null} </div> ); } }
JavaScript
class RateLimiter { /** * @param initialCapacity Initial maximum number of operations per second. * @param multiplier Rate by which to increase the capacity. * @param multiplierMillis How often the capacity should increase in * milliseconds. * @param maximumCapacity Maximum number of allowed operations per second. * The number of tokens added per second will never exceed this number. * @param startTimeMillis The starting time in epoch milliseconds that the * rate limit is based on. Used for testing the limiter. */ constructor(initialCapacity, multiplier, multiplierMillis, maximumCapacity, startTimeMillis = Date.now()) { this.initialCapacity = initialCapacity; this.multiplier = multiplier; this.multiplierMillis = multiplierMillis; this.maximumCapacity = maximumCapacity; this.startTimeMillis = startTimeMillis; this.availableTokens = initialCapacity; this.lastRefillTimeMillis = startTimeMillis; this.previousCapacity = initialCapacity; } /** * Tries to make the number of operations. Returns true if the request * succeeded and false otherwise. * * @param requestTimeMillis The time used to calculate the number of available * tokens. Used for testing the limiter. * @private */ tryMakeRequest(numOperations, requestTimeMillis = Date.now()) { this.refillTokens(requestTimeMillis); if (numOperations <= this.availableTokens) { this.availableTokens -= numOperations; return true; } return false; } /** * Returns the number of ms needed to make a request with the provided number * of operations. Returns 0 if the request can be made with the existing * capacity. Returns -1 if the request is not possible with the current * capacity. * * @param requestTimeMillis The time used to calculate the number of available * tokens. Used for testing the limiter. * @private */ getNextRequestDelayMs(numOperations, requestTimeMillis = Date.now()) { this.refillTokens(requestTimeMillis); if (numOperations < this.availableTokens) { return 0; } const capacity = this.calculateCapacity(requestTimeMillis); if (capacity < numOperations) { return -1; } const requiredTokens = numOperations - this.availableTokens; return Math.ceil((requiredTokens * 1000) / capacity); } /** * Refills the number of available tokens based on how much time has elapsed * since the last time the tokens were refilled. * * @param requestTimeMillis The time used to calculate the number of available * tokens. Used for testing the limiter. * @private */ refillTokens(requestTimeMillis) { if (requestTimeMillis >= this.lastRefillTimeMillis) { const elapsedTime = requestTimeMillis - this.lastRefillTimeMillis; const capacity = this.calculateCapacity(requestTimeMillis); const tokensToAdd = Math.floor((elapsedTime * capacity) / 1000); if (tokensToAdd > 0) { this.availableTokens = Math.min(capacity, this.availableTokens + tokensToAdd); this.lastRefillTimeMillis = requestTimeMillis; } } else { throw new Error('Request time should not be before the last token refill time.'); } } /** * Calculates the maximum capacity based on the provided date. * * @private */ // Visible for testing. calculateCapacity(requestTimeMillis) { assert(requestTimeMillis >= this.startTimeMillis, 'startTime cannot be after currentTime'); const millisElapsed = requestTimeMillis - this.startTimeMillis; const operationsPerSecond = Math.min(Math.floor(Math.pow(this.multiplier, Math.floor(millisElapsed / this.multiplierMillis)) * this.initialCapacity), this.maximumCapacity); if (operationsPerSecond !== this.previousCapacity) { logger_1.logger('RateLimiter.calculateCapacity', null, `New request capacity: ${operationsPerSecond} operations per second.`); } this.previousCapacity = operationsPerSecond; return operationsPerSecond; } }
JavaScript
class Interface { /// Holds which of the toolboxes is active in the toolbar /// Valid values: ["text", "draw"] static active_toolbox = "text"; /// Holds the active tool in use by the user. Null if no tool is selected. /// Valid values: [null, "pen", "erase"] static active_tool = null; /// Return an object holding the style attributes fetched from the interface static GetDrawStyle() { return { "color": "#333", "size": Number(document.getElementById("tb-draw-size").value), "fill": "none", }; } }
JavaScript
class History { constructor(element) { this.element = element; this.currentIndex = 0; this.historyArray = [element.innerHTML] } goBack() { let i = this.currentIndex - 1; if (i < 0) { return; } else { this.currentIndex = i; this.element.innerHTML = this.historyArray[this.currentIndex]; } } goForward() { let i = this.currentIndex + 1; if (i >= this.historyArray.length) { return; } else { this.currentIndex = i; this.element.innerHTML = this.historyArray[this.currentIndex]; } } saveState() { for (let i = this.currentIndex + 1; i < this.historyArray.length; i++) { this.historyArray.pop(); } this.historyArray.push(this.element.innerHTML); this.currentIndex++; } }
JavaScript
class ContractProvider extends BaseContractProvider { constructor (options) { super(options, defaultOptions) } get dependencies () { return ['web3', 'wallet'] } async _onStart () { this._initContract() this._initContractInfo() } /** * @return {string} Address of the connected contract. */ get address () { return this.contract.options.address } /** * @return {boolean} `true` if the contract has an address, `false` otherwise. */ get hasAddress () { return this.contract && this.address !== null } /** * @return {boolean} `true` if the contract is ready to be used, `false` otherwise. */ get ready () { return this.hasAddress && this.operatorEndpoint } /** * Returns the current web3 instance. * Mainly used for convenience. * @return {*} The current web3 instance. */ get web3 () { return this.services.web3 } /** * @return {string} Plasma Chain contract name. */ get plasmaChainName () { return this.options.plasmaChainName } /** * Checks whether an account is unlocked * and attempts to unlock it if not. * @param {string} address Address of the account to check. */ async checkAccountUnlocked (address) { if (this.services.wallet.addAccountToWallet) { await this.services.wallet.addAccountToWallet(address) } } /** * Queries a given block. * @param {number} block Number of the block to query. * @return {string} Root hash of the block with that number. */ async getBlock (block) { return this.contract.methods.blockHashes(block).call() } /** * @return {number} Number of the block that will be submitted next. */ async getNextBlock () { return this.contract.methods.nextPlasmaBlockNumber().call() } /** * @return {number} Number of the last submitted block. */ async getCurrentBlock () { const nextBlockNumber = await this.getNextBlock() return nextBlockNumber - 1 } /** * @return {string} Address of the current operator. */ async getOperator () { return this.contract.methods.operator().call() } /** * Returns the address for a given token ID. * @param {string} token The token ID. * @return {string} Address of the contract for that token. */ async getTokenAddress (token) { if (this.web3.utils.isAddress(token)) { return token } return this.contract.methods['listings__contractAddress']( token.toString() ).call() } /** * Lists a token with the given address * so that it can be deposited. * @param {string} tokenAddress Address of the token. * @param {string} senderAddress Address of the account sending the listToken transaction. * @return {EthereumTransaction} The Ethereum transaction result. */ async listToken (tokenAddress, senderAddress) { let sender if (senderAddress === undefined) { const accounts = await this.services.wallet.getAccounts() sender = accounts[0] } else { sender = senderAddress } await this.checkAccountUnlocked(sender) const tx = this.contract.methods.listToken(tokenAddress, 0) const gas = await tx.estimateGas({ from: sender }) return tx.send({ from: sender, gas }) } /** * Gets the current challenge period. * Challenge period is returned in number of blocks. * @return {number} Current challenge period. */ async getChallengePeriod () { return this.contract.methods['CHALLENGE_PERIOD']().call() } /** * Gets the token ID for a specific token. * Token IDs are unique to each plasma chain. * TODO: Add link that explains how token IDs work. * @param {string} tokenAddress Token contract address. * @return {string} ID of that token. */ async getTokenId (tokenAddress) { return this.contract.methods.listed(tokenAddress).call() } /** * Checks whether a specific deposit actually exists. * @param {Deposit} deposit Deposit to check. * @return {boolean} `true` if the deposit exists, `false` otherwise. */ async depositValid (deposit) { // Find past deposit events. const depositEvents = await this.contract.getPastEvents('DepositEvent', { filter: { depositer: deposit.owner // block: deposit.block }, fromBlock: 0 }) // Check that one of the events matches this deposit. return depositEvents.some((event) => { const casted = new DepositEvent(event) return ( casted.owner === deposit.owner && casted.start.eq(deposit.start) && casted.end.eq(deposit.end) && casted.token.eq(deposit.token) ) }) } /** * Submits a deposit for a user. * This method will pipe the `deposit` call to the correct * ERC20 or ETH call. * @param {BigNum} token Token to deposit, specified by ID. * @param {BigNum} amount Amount to deposit. * @param {string} owner Address of the user to deposit for. * @return {EthereumTransaction} Deposit transaction receipt. */ async deposit (token, amount, owner) { if (!this.hasAddress) { throw new Error('Plasma chain contract address has not yet been set.') } await this.checkAccountUnlocked(owner) amount = new BigNum(amount, 'hex') if (token.toString() === '0') { return this.depositETH(amount, owner) } else { return this.depositERC20(token, amount, owner) } } /** * Deposits an amount of ETH for a user. * @param {BigNum} amount Amount to deposit. * @param {string} owner Address of the user to deposit for. * @return {EthereumTransaction} Deposit transaction receipt. */ async depositETH (amount, owner) { return this.contract.methods.depositETH().send({ from: owner, value: amount, gas: 150000 }) } /** * Deposits an amount of an ERC20 for a user. * @param {BigNum} amount Amount to deposit. * @param {string} owner Address of the user to deposit for. * @return {EthereumTransaction} Deposit transaction receipt. */ async depositERC20 (token, amount, owner) { const tokenAddress = await this.getTokenAddress(token) const tokenContract = new this.web3.eth.Contract( erc20Compiled.abi, tokenAddress ) await tokenContract.methods.approve(this.address, amount).send({ from: owner, gas: 6000000 // TODO: Figure out how much this should be. }) return this.contract.methods.depositERC20(tokenAddress, amount).send({ from: owner, gas: 6000000 // TODO: Figure out how much this should be. }) } /** * Starts an exit for a user. * Exits can only be started on *transfers*, meaning you * need to specify the block in which the transfer was received. * TODO: Add link that explains this in more detail. * @param {BigNum} block Block in which the transfer was received. * @param {BigNum} token Token to be exited. * @param {BigNum} start Start of the range received in the transfer. * @param {BigNum} end End of the range received in the transfer. * @param {string} owner Adress to exit from. * @return {EthereumTransaction} Exit transaction receipt. */ async startExit (block, token, start, end, owner) { await this.checkAccountUnlocked(owner) return this.contract.methods.beginExit(token, block, start, end).send({ from: owner, gas: 200000 }) } /** * Finalizes an exit for a user. * @param {string} exitId ID of the exit to finalize. * @param {BigNum} exitableEnd Weird quirk in how we handle exits. For more information, see: https://github.com/plasma-group/plasma-contracts/issues/44. * @param {string} owner Address that owns this exit. * @return {EthereumTransaction} Finalization transaction receipt. */ async finalizeExit (exitId, exitableEnd, owner) { await this.checkAccountUnlocked(owner) return this.contract.methods.finalizeExit(exitId, exitableEnd).send({ from: owner, gas: 100000 }) } /** * Submits a block with the given hash. * Will only work if the operator's account is unlocked and * available to the node. * @param {string} hash Hash of the block to submit. * @return {EthereumTransaction} Block submission transaction receipt. */ async submitBlock (hash) { const operator = await this.getOperator() await this.checkAccountUnlocked(operator) return this.contract.methods.submitBlock(hash).send({ from: operator }) } /** * Initializes the contract instance. */ _initContract () { if (this.contract) return this.contract = new this.web3.eth.Contract(plasmaChainCompiled.abi) this.registryContract = new this.web3.eth.Contract( registryCompiled.abi, this.options.registryAddress ) } /** * Initializes the contract address and operator endpoint. * Queries information from the registry. */ async _initContractInfo () { if (!this.plasmaChainName) { throw new Error('ERROR: Plasma chain name not provided.') } const plasmaChainName = utils.utils.web3Utils .asciiToHex(this.plasmaChainName) .padEnd(66, '0') const operator = await this.registryContract.methods .plasmaChainNames(plasmaChainName) .call() const events = await this.registryContract.getPastEvents('NewPlasmaChain', { filter: { OperatorAddress: operator }, fromBlock: 0 }) const event = events.find((event) => { return event.returnValues.PlasmaChainName === plasmaChainName }) if (!event) { throw new Error('ERROR: Plasma chain name not found in registry.') } const parsed = new ChainCreatedEvent(event) this.contract.options.address = parsed.plasmaChainAddress this.operatorEndpoint = parsed.operatorEndpoint this.emit('initialized') this.logger(`Connected to plasma chain: ${this.plasmaChainName}`) this.logger(`Contract address set: ${this.address}`) this.logger(`Operator endpoint set: ${this.operatorEndpoint}`) } }
JavaScript
class Controller extends EventTarget { /** * Constructor. * @param {!angular.Scope} $scope * @param {!angular.JQLite} $element * @ngInject */ constructor($scope, $element) { super(); /** * @type {?angular.Scope} * @private */ this.scope_ = $scope; /** * @type {?angular.JQLite} * @private */ this.element_ = $element; /** * @type {boolean} */ this.scope_['showResetButton'] = false; this.scope_['tabs'] = IconSelectorManager.getInstance().getAll(); this.scope_['showtabs'] = this.scope_['tabs'].length === 1 ? false : true; this.scope_['activeTab'] = this.scope_['tabs'].length > 0 ? this.scope_['tabs'][0]['name'] : ''; this.scope_['tabMap'] = {}; for (var i = 0; i < this.scope_['tabs'].length; i++) { // wrap each icon selector in tab structure var markup = '<div class="d-flex flex-fill" ng-if="activeTab == \'' + this.scope_['tabs'][i]['name'] + '\'">' + this.scope_['tabs'][i]['html'] + '</div>'; this.scope_['tabMap'][this.scope_['tabs'][i]['name']] = this.scope_['tabs'][i]; if (!exists(iconSelectors, markup)) { add(iconSelectors, markup, 201); } } this.scope_.$watch('activeTab', function() { this['showResetButton'] = false; }.bind(this)); this.scope_.$on('iconselector.showreseticon', function(event) { this['showResetButton'] = true; }.bind(this)); this.scope_.$on('iconselector.closewindow', function(event) { this.okay(); }.bind(this)); this.scope_.$emit(WindowEventType.READY); $scope.$on('$destroy', this.destroy_.bind(this)); } /** * Clean up. * * @private */ destroy_() { this.scope_ = null; this.element_ = null; } /** * Is valid if the user has picked something * * @return {boolean} * @export */ isValid() { return this.scope_['selected'] && !!this.scope_['selected']['path']; } /** * Notify parent scope that no icon was selected * * @export */ cancel() { this.close_(); } /** * Close the window. * * @private */ close_() { close(this.element_); } /** * Notify parent scope which icon the user picked * * @export */ okay() { if (this.scope_['acceptCallback']) { this.scope_['acceptCallback'](this.scope_['selected']); } this.close_(); } /** * Notify parent scope which icon the user picked * * @param {string} name * @export */ setTab(name) { this.scope_['activeTab'] = name; } /** * Emits signal that certain button is clicked * @export */ reset() { this.scope_.$broadcast('iconselector.reseticon'); } /** * Translates from google uri if needed * * @param {string} path * @return {string} * @export */ getPath(path) { return GMAPS_SEARCH.test(path) ? replaceGoogleUri(path) : path; } }
JavaScript
class TaskLatLon extends Component { rounded = value => Number(value.toFixed(7)) // 7 digits max precision render() { const centerpoint = AsMappableTask(this.props.task).calculateCenterPoint() if (!centerpoint || (centerpoint.lat === 0 && centerpoint.lng === 0)) { return null } return ( <div className={classNames('task-lat-lon', this.props.className)}> <span className='task-lat-lon__label'>Lon/Lat:</span> <span className='task-lat-lon__longitude'> {this.rounded(centerpoint.lng)} </span>, <span className='task-lat-lon__latitude'> {this.rounded(centerpoint.lat)} </span> <CopyToClipboard text={`${this.rounded(centerpoint.lat)}, ${this.rounded(centerpoint.lng)}`}> <button className="button is-clear has-svg-icon task-lat-lon__copy-button"> <SvgSymbol viewBox='0 0 20 20' sym="clipboard-icon" /> </button> </CopyToClipboard> </div> ) } }
JavaScript
class SlideEight extends React.Component { constructor(props) { super(props) this.props.setHeader() } render() { return ( <ContentBox> <PrimaryText> <SubtitleBar type={1} title='EVENTO 2' subtitle='Conhecer e Apropriar-se das Modalidades Esportivas'/> <EmptySpace/> <Image center width='750px' src={QuadroUmSVG} alt='As práticas esportivas devem integrar-se às demais ações da escola, com vistas à formação integral de seus alunos e como espaços privilegiados para criação de conhecimento. Assim é possível que na escola os estudantes possam ser críticos quanto às modalidades esportivas conhecidas e serem capazes de inovar também nesse campo. Etc...'/> <EmptySpace /> </PrimaryText> </ContentBox> ) } }
JavaScript
class Resident { constructor(species, name, gender, voice, friends) { this.species = species; this.name = name; this.gender = gender; this.voice = voice; this.friends = friends; this.residentData; } setResidentData() { this.residentData = Object.values(this); } getResidentInfo() { this.setResidentData(); print(this.residentData.join('; ')); } }
JavaScript
class Button { constructor(tagIDClasses, ...p) { var componentParams = new ComponentParams({ tagIDClasses: '$button.btn', paramNames : 'focusOnMouseClick,icon', nameForCB :'onActivatedCB' }, tagIDClasses, ...p); if (componentParams.optParams.icon) componentParams.className += " icon "+componentParams.optParams.icon; // b/c we pass in 'this' to makeHtmlNode it will initialize this with all the properties expected of a bgComponent. We do // this before setting any other this.props so that the memory layout of all bgComponent will share a common layout up to // that point. This is not functional in the code but may aid in some transparent runtime optimizations. // properties set: name, mounted, mountedUnamed, el, bgComponent componentParams.makeHtmlNode(this); this.disposables = new Disposables(); this.componentParams = componentParams; this.optParams = componentParams.optParams; this.iconName = componentParams.optParams.icon; this.onActivatedCB = componentParams.getCompositeCB(false, 'onActivatedCB'); this.setLabel(componentParams.optParams.label); this.el.onclick = (e)=>{this.rawOnClick(e)}; if (! componentParams.optParams["focusOnMouseClick"]) this.el.onmousedown = ()=>{this.lastFocused=document.activeElement} // TODO: should this ComponentMount any specified child content? or should buttons not support child content? } destroy() { this.disposables.dispose(); deps.objectDestroyed(this); this.componentParams.destroyHtmlNode(this); } rawOnClick(e) { this.lastFocused && this.lastFocused.focus(); this.lastFocused=null; this.onClick(e); } onClick(e) { this.onClickCB && this.onClickCB(this, e); this.onActivated(e); } onActivated(e) { this.onActivatedCB && this.onActivatedCB(this, e); } getLabel() {return this.label || ''} setLabel(label) { this.label = label || ''; if (reHTMLContent.test(this.label)) this.el.innerHTML = this.label; else this.el.innerText = this.label; } }
JavaScript
class ToggleButton extends Button { constructor(bgNodeID, ...options) { super({paramNames: 'pressed', nameForCB:'onStateChangeCB'}, bgNodeID, ...options); this.setPressedState(Boolean(this.optParams["pressed"])); this.onStateChangeCB = this.componentParams.getCompositeCB(false, 'onStateChangeCB'); } onActivated(e) { this.el.classList.toggle("selected"); super.onActivated(e); this.onStateChange(this.isPressed()); } onStateChange(newState) { this.onStateChangeCB && this.onStateChangeCB(newState, this); } setState(newState) { if (newState != this.isPressed()) { this.setPressedState(newState); super.onActivated(); this.onStateChange(this.isPressed()); } } isPressed() { return this.el.classList.contains("selected"); } setPressedState(state) { this.el.classList.toggle("selected", state); } }
JavaScript
class CommandButton extends Button { constructor(tagIDClasses, cmdName, ...options) { super(tagIDClasses, {paramNames:'target'}, ()=>this.onClick(), ...options); this.cmdName = cmdName; this.cmdTarget = this.optParams["target"] || atom.workspace.getElement(); const allCommands = atom.commands.findCommands({target: this.cmdTarget}); const command = allCommands.filter((command) => command.name === cmdName)[0] || {displayName:'unknown', description:'unknown'}; if (!this.getLabel() && !this.iconName) { this.setLabel(command.displayName); this.toolTipTitle = command.description; } else this.toolTipTitle = command.displayName; setTimeout(()=>{ this.toolTipDispose = atom.tooltips.add(this.el, {title: this.toolTipTitle, keyBindingCommand: this.cmdName}); //, keyBindingTarget: this.cmdTarget }, 1000); } onClick() { atom.commands.dispatch(this.cmdTarget, this.cmdName); } destroy() { this.toolTipDispose.dispose(); super.destroy(); } }
JavaScript
class OneShotButton extends ToggleButton { constructor(bgNodeID, ...options) { super({nameForCB:'onActivatedCB'}, bgNodeID, ...options); } reset() { this.setPressedState(false); } onActivated(e) { if (!this.isPressed()) { super.onActivated(e); } } }
JavaScript
class DeviceData { constructor(deviceId) { this.deviceId = deviceId; this.maxLen = 50; this.timeData = new Array(this.maxLen); this.temperatureData = new Array(this.maxLen); this.humidityData = new Array(this.maxLen); } addData(time, temperature, humidity) { this.timeData.push(time); this.temperatureData.push(temperature); this.humidityData.push(humidity || null); if (this.timeData.length > this.maxLen) { this.timeData.shift(); this.temperatureData.shift(); this.humidityData.shift(); } } }
JavaScript
class TrackedDevices { constructor() { this.devices = []; } // Find a device based on its Id findDevice(deviceId) { for (let i = 0; i < this.devices.length; ++i) { if (this.devices[i].deviceId === deviceId) { return this.devices[i]; } } return undefined; } }
JavaScript
class ProductCard extends NavigationMixin(LightningElement) { // Exposing fields to make them available in the template categoryField = CATEGORY_FIELD; levelField = LEVEL_FIELD; msrpField = MSRP_FIELD; batteryField = BATTERY_FIELD; chargerField = CHARGER_FIELD; motorField = MOTOR_FIELD; materialField = MATERIAL_FIELD; forkField = FOPK_FIELD; frontBrakesField = FRONT_BRAKES_FIELD; rearBrakesField = REAR_BRAKES_FIELD; // Id of Product__c to display recordId; // Product fields displayed with specific format productName; productPictureUrl; // Product field for Quantity in Stock inStockQuantity; /** Load context for Ligthning Messaging Service */ @wire(MessageContext) messageContext; /** Subscription for ProductSelected Ligthning message */ productSelectionSubscription; connectedCallback() { // Subscribe to ProductSelected message this.productSelectionSubscription = subscribe( this.messageContext, PRODUCT_SELECTED_MESSAGE, (message) => this.handleProductSelected(message.productId) ); } handleRecordLoaded(event) { const { records } = event.detail; const recordData = records[this.recordId]; this.productName = getFieldValue(recordData, NAME_FIELD); this.productPictureUrl = getFieldValue(recordData, PICTURE_URL_FIELD); //callout to apex to get the real-time quantity in stock, pass the product name getProductInStockQuantity({productName : this.productName}) .then(result => { this.inStockQuantity = result; }) .catch(error => { this.inStockQuantity = error; }) } /** * Handler for when a product is selected. When `this.recordId` changes, the * lightning-record-view-form component will detect the change and provision new data. */ handleProductSelected(productId) { this.recordId = productId; } handleNavigateToRecord() { this[NavigationMixin.Navigate]({ type: 'standard__recordPage', attributes: { recordId: this.recordId, objectApiName: PRODUCT_OBJECT.objectApiName, actionName: 'view' } }); } }
JavaScript
class FilesPreview extends React.PureComponent { state = { files: [], }; static propTypes = { files: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number.isRequired, file: PropTypes.any.isRequired, }), ).isRequired, onRemoveFile: PropTypes.func, onRetryFileUpload: PropTypes.func, filesUploadProps: PropTypes.objectOf( PropTypes.shape({ isUploading: PropTypes.bool.isRequired, done: PropTypes.bool.isRequired, error: PropTypes.bool.isRequired, errorHelperText: PropTypes.string, progress: PropTypes.number, }), ), }; componentDidUpdate(prevProps) { if (prevProps.files.length !== this.props.files.length) { if (this.props.files.length > prevProps.files.length) { /** * @description * When this occurs it means that a new file has been added * For performance purposes, we only try to obtain the base64 * encoding of the last file added and add it to file in our state * * Also we want to do the necessary encoding only if * the file format is supported by our system */ let { file, id } = this.props.files[this.props.files.length - 1], fileReader = new FileReader(); if (Object.values(FILE_UPLOAD_TYPE).indexOf(file.type) !== -1) { fileReader.onload = event => { this.setState(prevState => ({ files: [ ...prevState.files, { id, name: file.name, size: file.size, type: file.type, base64: event.target.result, }, ], })); }; fileReader.readAsDataURL(file); } } else if (this.props.files.length < prevProps.files.length) { /** * @description * When this occurs it means that a file has been removed * To adequately remove the missing file, we need to check * for the file that is missing and remove it from our state * * However this is done appropriately since we use a timestamp ID and not an index ID * therefore ReactJs will not destroy and create any list of file preview :-) */ let ArrayOfIds = this.props.files.map(file => file.id); this.setState(prevState => ({ files: prevState.files.filter( file => ArrayOfIds.indexOf(file.id) !== -1, ), })); } } } renderFilePreview = id => { let { filesUploadProps } = this.props, _filesUploadProps = filesUploadProps || {}, uploadProps = _filesUploadProps[id] || {}, previewText = ''; if (uploadProps.error === true && uploadProps.isUploading === false) { previewText = uploadProps.errorHelperText || 'The upload failed. Please try again.'; } else if (uploadProps.done === true && uploadProps.isUploading === false) { previewText = 'Attached'; } else if (uploadProps.done === false && uploadProps.isUploading === true) { previewText = 'Uploading...'; } return ( <span className={classNames( classes.previewAttachedText, uploadProps.error === true && uploadProps.isUploading === false && classes.previewErrorText, uploadProps.isUploading === true && classes.previewUploadingText, )}> {previewText} </span> ); }; renderProgressBar = id => { let { filesUploadProps } = this.props, _filesUploadProps = filesUploadProps || {}, uploadProps = _filesUploadProps[id] || {}; if (uploadProps.progress === undefined) { return; } else if ( uploadProps.progress !== undefined && typeof uploadProps.progress !== 'number' ) { throw new Error( 'Progress value for image upload must be a number between 0 and 1', ); } return uploadProps.progress === undefined || uploadProps.done === true || uploadProps.error === true ? null : ( <div className={classes.progressBar}> <div className={classes.progressValue} style={{ width: `${uploadProps.progress * 100}%` }} /> </div> ); }; render() { let { filesUploadProps } = this.props, _filesUploadProps = filesUploadProps || {}; return ( <React.Fragment> {this.state.files.map(file => ( <figure key={file.id} className={classes.fileContainer}> <div className={classes.previewImageContainer}> <img className={classes.previewImage} src={file.base64} /> </div> <figcaption className={classes.previewCaptionContainer}> <div style={{ display: 'flex', alignItems: 'center' }}> <span className={classes.previewName}>{file.name}</span> <div className={classes.dotSeperator} /> <span className={classes.previewSize}> {Math.round(file.size / 1000)} KB </span> </div> {this.renderFilePreview(file.id)} {this.renderProgressBar(file.id)} </figcaption> <div style={{ display: 'flex' }}> {_filesUploadProps[file.id] && _filesUploadProps[file.id].error === true && _filesUploadProps[file.id].isUploading === false && ( <MdRetry onClick={() => this.props.onRetryFileUpload(file.id)} className={classes.previewActionBtn} style={{ marginRight: 2 }} /> )} <MdClose className={classes.previewActionBtn} onClick={() => this.props.onRemoveFile(file.id)} /> </div> </figure> ))} </React.Fragment> ); } }
JavaScript
@tagName('div') @templateLayout(layout) @classNames('nucleus-tabs__list__item') @classNameBindings('isActive:is-active', 'isDisabled:is-disabled', 'isPressed:is-pressed') @attributeBindings('isDisabled:disabled', 'tabindex', 'title', 'role', 'aria-controls', 'aria-selected', 'testId:data-test-tab-id') class TabListItem extends Component { /** * disabled * * @field disabled * @type string * @default null * @readonly * @public */ @defaultProp disabled = null; /** * controls * * @field controls * @description idref to what panel this tab item controls * @type string|null * @readonly * @public */ @defaultProp controls; /** * selected * * @field selected * @description currently selected tab * @readonly * @public */ @defaultProp selected; /** * tabOrder * * @field tabOrder * @description order in which tabs are displayed. Only first tabs will not have tabIndex value * @type number * @readonly * @public */ @defaultProp tabOrder; /** * testId * * @field testId * @type string|null * @default null * @readonly * @public */ @defaultProp testId = null; /** * role * * @field role * @type string * @default 'tab' * @public */ role = 'tab'; /** * isPressed * * @field isPressed * @description to solve focus on click styling * @type boolean * @default false * @public */ isPressed = false; /** * tabindex * * @field tabindex * @type string|null * @public */ @computed('tabOrder', function() { let tabIndex = null; if(!get(this, 'isDisabled')) { tabIndex = (get(this, 'tabOrder') === 0)? '0' : '-1'; } return tabIndex; }) tabindex; /** * isActive * * @field isActive * @type boolean * @public */ @computed('selected', function() { return (get(this, 'selected') === get(this, 'name')); }) isActive; /** * isDisabled * * @field isDisabled * @type boolean * @public */ @computed('disabled', function() { return (get(this, 'disabled').toString() === 'true')? true : false; }) isDisabled; /** * title * * @field title * @type string * @public */ @computed('name', function() { return get(this, 'name'); }) title; /** * data-test-tab-id * * @field data-test-tab-id * @type string * @public */ @computed('testId', function() { return get(this, 'testId'); }) 'data-test-tab-id'; /** * aria-controls * * @field aria-controls * @type string * @public */ @computed('controls', function() { return get(this, 'controls'); }) 'aria-controls'; /** * aria-selected * * @field aria-selected * @type boolean * @public */ @computed('selected', function() { return (get(this, 'selected') === get(this, 'name')).toString(); }) 'aria-selected'; /** * didInsertElement * * @method didInsertElement * @description lifecycle event * @public * */ didInsertElement() { get(this, 'registerTabListItem').call(this, { id: get(this, 'elementId'), name: get(this, 'name') }); } /** * mouseDown * * @method mouseDown * @description event handler : We are negating the style applied on click-focus * @public * */ mouseDown() { if(get(this, 'isDisabled') === false) { set(this, 'isPressed', true); } } /** * focusOut * * @method focusOut * @description event handler : Removing style that was applied during press to negate focus * @public * */ focusOut() { if(get(this, 'isPressed') === true) { set(this, 'isPressed', false); } } /** * click * * @method click * @description event handler * @public * */ click(event) { if(get(this, 'isDisabled') === false) { get(this, 'handleActivateTab').call(this, get(this, 'name'), event); } } /** * keyDown * * @method keyDown * @description event handler * @public * */ keyDown(event) { event.stopPropagation(); const targetElement = event.target; const firstElement = targetElement.parentElement.firstElementChild; const lastElement = targetElement.parentElement.lastElementChild; const keyCode = TABS_KEY_CODE; switch (event.keyCode) { case keyCode.ENTER: case keyCode.SPACE: event.preventDefault(); targetElement.click(); break; case keyCode.END: lastElement.focus(); break; case keyCode.HOME: firstElement.focus(); break; case keyCode.LEFT: get(this, '_changeTabFocus').call(this, 'previous', targetElement); break; case keyCode.RIGHT: get(this, '_changeTabFocus').call(this, 'next', targetElement); break; default: break; } } /** * _changeTabFocus * * @method _changeTabFocus * @description Change focus based on direction * @param {string} direction takes either 'next' or 'previous' * @param {Object} element * @param {Object} [elementInFocus] * @private * */ _changeTabFocus(direction, element, elementInFocus) { let adjacentElement; if(direction === 'previous') { adjacentElement = (element.previousElementSibling)? element.previousElementSibling : element.parentElement.lastElementChild; } else { adjacentElement = (element.nextElementSibling)? element.nextElementSibling : element.parentElement.firstElementChild; } if(elementInFocus && (elementInFocus.id === adjacentElement.id)) { return; } else if(adjacentElement.getAttribute('tabindex') === null) { get(this, '_changeTabFocus').call(this, direction, adjacentElement, element); } else { adjacentElement.focus(); } } }
JavaScript
class Player { /** * Creates player * @param name * @param color */ constructor(name, color, canvas, img) { this.score = 0; this.resources = 0; this.canvas = canvas; this.allRegions = null; this.img = img; this.regions = []; this.status = PLAYER_STATES.DISABLED; this.color = color; this.name = name; } setAllRegtions(regions) { this.allRegions = regions; } /** * should be overriden */ init() { } /** * Принадлежит ли данный регион игроку * @param region * @return {boolean} */ isTheRegionOfPlayer(region) { for (let i = 0; i < this.regions.length; ++i) { if (this.regions[i].name === region.name) { return true; } } return false; } /** * Gives the player new region * @param newRegion */ addRegion(newRegion, player) { newRegion.area.setColor(this.color); renderScene(this.canvas, this.allRegions, this.img); newRegion.area.reColor(this.color); newRegion.owner = player; this.regions.push(newRegion); } addRegionForWeb(newRegion, player, allRegions) { newRegion.area.setColor(this.color); renderScene(this.canvas, allRegions, this.img); newRegion.area.reColor(this.color); newRegion.owner = player; this.regions.push(newRegion); } /** * deletes region * @param reg */ delRegion(reg) { for (let i = 0; i < this.regions.length; ++i) { if (this.regions[i] === reg) { this.regions.splice(i,1); } } if (this.regions.length === 0) { this.status = PLAYER_STATES.LOSE; } } /** * sets player's status * @param status */ setStatus(status) { this.status = status; } }
JavaScript
class PixelException { constructor (message) { this.message = message; } }
JavaScript
class CQueue { constructor () { this.front = null this.rear = null } insert(ele) { var node = new newNode(ele) if(this.front==null) this.front=node else this.rear.next=node this.rear=node this.rear.next=this.front } del() { if(this.front==null) console.log("Queue Empty") else { var temp=this.front console.log(temp.data) this.front=this.front.next this.rear.next=this.front temp=null } if(this.front==null) console.log("Now Queue Empty") } display() { var temp=this.front do { console.log(temp.data) temp=temp.next }while(temp!=this.front) } }
JavaScript
class Cancel { constructor() { this.cancelRequestMap = {} this.cancelRequestGroupMap = {} this.interceptorsRef = {} } /** * @description * Extract the url pathname method and cancelGroupKey if exist * @param config * @returns [requestKey, groupKey] * @private */ _generateKeys(config) { const urlObject = url.parse(config.url) const urlPathName = urlObject.pathname const requestKey = `${urlPathName} -> ${config.method}` const groupKey = config.headers[uniqueGroupKey] return [requestKey, groupKey] } /** * @description * Return array of cancel objects that sign to the specific group key * @param groupKey - string * @returns [cancelObject] * @private */ _getGroupByKey(groupKey) { return Array.isArray(this.cancelRequestGroupMap[groupKey]) ? [...this.cancelRequestGroupMap[groupKey]] : [] } _signToGroup(key, groupKey) { if (!groupKey) { return } if (Array.isArray(this.cancelRequestGroupMap[groupKey])) { this.cancelRequestGroupMap[groupKey].push(key) return } this.cancelRequestGroupMap[groupKey] = [key] } /** * @description * Sign the request to the cancelMainObject and, * cancelMainGroupObject if a groupKey exists. * Return an axios cancel token instance * @param axios config * @returns axios cancel token instance * @private */ _sign(config) { const [key, groupKey] = this._generateKeys(config) const source = CancelToken.source() this.cancelRequestMap[key] = { cancel: source.cancel, config: { ...config }, } this._signToGroup(key, groupKey) return source.token } /** * @description * Will delete the request only after the cancellation process execute * Or Request resolved/rejected * @param config * @private */ _delete(config) { const [key, groupKey] = this._generateKeys(config) if (this.cancelRequestMap[key]) { delete this.cancelRequestMap[key] } this._deleteFromGroup(key, groupKey) } _deleteFromGroup(key, groupKey) { let cancelGroup = [...this._getGroupByKey(groupKey)] if (groupKey && cancelGroup) { cancelGroup = cancelGroup.filter(requestKey => requestKey !== key) if (!cancelGroup.length) { delete this.cancelRequestGroupMap[groupKey] } else { this.cancelRequestGroupMap[groupKey] = cancelGroup } } } _onRequestSuccess(config) { const [key] = this._generateKeys(config) const cancelItem = this.cancelRequestMap[key] if (cancelItem) { cancelItem.cancel({ ...cancelItem.config, isCanceled: true }) } const cancelToken = this._sign(config) return { ...config, cancelToken } } _onResponseFailed(error) { const config = ensureGetConfig(error) const customError = { ...error, config } const isCanceledByAxios = isAxiosCancel(error) this._delete(config) if (isCanceledByAxios) { logger.group('cancel request execute') logger.log(config) logger.groupEnd('cancel request execute') customError.isCanceled = true } return Promise.reject(customError) } _onResponseSuccess(response) { this._delete(response.config) return response } /* EXPOSE */ /** * @description * This function is a must function in each plugin. * The function should sign the plugin into the * axios interceptors request and response * @param axios */ applyPlugin(axios) { this.interceptorsRef.request = axios.interceptors.request.use(this._onRequestSuccess.bind(this)) this.interceptorsRef.response = axios.interceptors.response.use( this._onResponseSuccess.bind(this), this._onResponseFailed.bind(this), ) } /** * @description * eject the current axios interceptor from the axios instance * @param axios */ eject(axios) { axios.interceptors.request.eject(this.interceptorsRef.request) axios.interceptors.response.eject(this.interceptorsRef.response) } /** * @description * Cancel all requests that belong to the groupKey * @param groupKey */ cancelGroupRequests(groupKey) { const cancelGroup = this.cancelRequestGroupMap[groupKey] if (!Array.isArray(cancelGroup)) { return } cancelGroup.forEach(key => { const cancelItem = this.cancelRequestMap[key] cancelItem.cancel({ ...cancelItem.config }) this._delete(cancelItem.config) }) delete this.cancelRequestGroupMap[groupKey] } /** * @description * Return object with { ccgk: customCancelGroupKey } to use in the axios config headers * @param customCancelGroupKey * @returns {{}} */ getCancelGroupHeader(customCancelGroupKey) { if (!customCancelGroupKey) { throw new Error(`"getCancelGroupHeader" should invoke with cancel group key, please verify that you didn't invoke the function with undefined or null`) } return { [uniqueGroupKey]: customCancelGroupKey, } } }
JavaScript
class ImageCaption extends Plugin { /** * @inheritDoc */ static get requires() { return [ ImageCaptionEngine ]; } /** * @inheritDoc */ static get pluginName() { return 'ImageCaption'; } }
JavaScript
class SiteExtensionInfo extends models['ProxyOnlyResource'] { /** * Create a SiteExtensionInfo. * @member {string} [siteExtensionInfoId] Site extension ID. * @member {string} [title] Site extension title. * @member {string} [siteExtensionInfoType] Site extension type. Possible * values include: 'Gallery', 'WebRoot' * @member {string} [summary] Summary description. * @member {string} [description] Detailed description. * @member {string} [version] Version information. * @member {string} [extensionUrl] Extension URL. * @member {string} [projectUrl] Project URL. * @member {string} [iconUrl] Icon URL. * @member {string} [licenseUrl] License URL. * @member {string} [feedUrl] Feed URL. * @member {array} [authors] List of authors. * @member {string} [installationArgs] Installer command line parameters. * @member {date} [publishedDateTime] Published timestamp. * @member {number} [downloadCount] Count of downloads. * @member {boolean} [localIsLatestVersion] <code>true</code> if the local * version is the latest version; <code>false</code> otherwise. * @member {string} [localPath] Local path. * @member {date} [installedDateTime] Installed timestamp. * @member {string} [provisioningState] Provisioning state. * @member {string} [comment] Site Extension comment. */ constructor() { super(); } /** * Defines the metadata of SiteExtensionInfo * * @returns {object} metadata of SiteExtensionInfo * */ mapper() { return { required: false, serializedName: 'SiteExtensionInfo', type: { name: 'Composite', className: 'SiteExtensionInfo', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, kind: { required: false, serializedName: 'kind', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, siteExtensionInfoId: { required: false, serializedName: 'properties.id', type: { name: 'String' } }, title: { required: false, serializedName: 'properties.title', type: { name: 'String' } }, siteExtensionInfoType: { required: false, serializedName: 'properties.type', type: { name: 'Enum', allowedValues: [ 'Gallery', 'WebRoot' ] } }, summary: { required: false, serializedName: 'properties.summary', type: { name: 'String' } }, description: { required: false, serializedName: 'properties.description', type: { name: 'String' } }, version: { required: false, serializedName: 'properties.version', type: { name: 'String' } }, extensionUrl: { required: false, serializedName: 'properties.extensionUrl', type: { name: 'String' } }, projectUrl: { required: false, serializedName: 'properties.projectUrl', type: { name: 'String' } }, iconUrl: { required: false, serializedName: 'properties.iconUrl', type: { name: 'String' } }, licenseUrl: { required: false, serializedName: 'properties.licenseUrl', type: { name: 'String' } }, feedUrl: { required: false, serializedName: 'properties.feedUrl', type: { name: 'String' } }, authors: { required: false, serializedName: 'properties.authors', type: { name: 'Sequence', element: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, installationArgs: { required: false, serializedName: 'properties.installationArgs', type: { name: 'String' } }, publishedDateTime: { required: false, serializedName: 'properties.publishedDateTime', type: { name: 'DateTime' } }, downloadCount: { required: false, serializedName: 'properties.downloadCount', type: { name: 'Number' } }, localIsLatestVersion: { required: false, serializedName: 'properties.localIsLatestVersion', type: { name: 'Boolean' } }, localPath: { required: false, serializedName: 'properties.localPath', type: { name: 'String' } }, installedDateTime: { required: false, serializedName: 'properties.installedDateTime', type: { name: 'DateTime' } }, provisioningState: { required: false, serializedName: 'properties.provisioningState', type: { name: 'String' } }, comment: { required: false, serializedName: 'properties.comment', type: { name: 'String' } } } } }; } }
JavaScript
class DetectTokensController { /** * Creates a DetectTokensController * * @param {Object} [config] - Options to configure controller */ constructor({ interval = DEFAULT_INTERVAL, network, provider } = {}) { this.interval = interval this.network = network this.initState = { tokens: [] } this.detectedTokensStore = new ObservableStore({ tokens: [] }) this._provider = provider this.web3 = new Web3(this._provider) this.selectedAddress = '' } /** * For each token in eth-contract-metadata, find check selectedAddress balance. * */ async detectNewTokens() { if (this.network.getNetworkNameFromNetworkCode() !== MAINNET || this.selectedAddress === '') { this.detectedTokensStore.putState({ tokens: [] }) return } const tokensToDetect = [] // eslint-disable-next-line no-restricted-syntax for (const contractAddress in contracts) { if (contracts[contractAddress].erc20) { tokensToDetect.push(contractAddress) } } if (tokensToDetect.length > 0) { const web3Instance = this.web3 const ethContract = new web3Instance.eth.Contract(SINGLE_CALL_BALANCES_ABI, SINGLE_CALL_BALANCES_ADDRESS) ethContract.methods.balances([this.selectedAddress], tokensToDetect).call({ from: this.selectedAddress }, (error, result) => { if (error) { warn('MetaMask - DetectTokensController single call balance fetch failed', error) return } const nonZeroTokens = [] tokensToDetect.forEach((tokenAddress, index) => { const balance = toHex(result[index]) if (balance && balance !== '0x0') { // do sth else here nonZeroTokens.push({ ...contracts[tokenAddress], tokenAddress, balance }) // this._preferences.addToken(tokenAddress, contracts[tokenAddress].symbol, contracts[tokenAddress].decimals) } }) this.detectedTokensStore.putState({ tokens: nonZeroTokens }) }) } } /** * Find if selectedAddress has tokens with contract in contractAddress. * * @param {string} contractAddress Hex address of the token contract to explore. * @returns {boolean} If balance is detected, token is added. * */ async detectEtherscanTokenBalance(contractAddress, data = {}) { const nonZeroTokens = this.detectedTokensStore.getState().tokens const index = nonZeroTokens.findIndex((element) => element.tokenAddress.toLowerCase() === contractAddress.toLowerCase()) if (index === -1) { nonZeroTokens.push({ ...data, tokenAddress: contractAddress, balance: `0x${new BigNumber(data.balance).times(new BigNumber(10).pow(new BigNumber(data.decimals))).toString(16)}`, }) this.detectedTokensStore.putState({ tokens: nonZeroTokens }) } } async refreshTokenBalances() { if (this.network.store.getState().provider.type !== MAINNET || this.selectedAddress === '') { this.detectedTokensStore.putState({ tokens: [] }) return } const oldTokens = this.detectedTokensStore.getState().tokens const tokenAddresses = oldTokens.map((x) => x.tokenAddress) if (tokenAddresses.length > 0) { const web3Instance = this.web3 const ethContract = new web3Instance.eth.Contract(SINGLE_CALL_BALANCES_ABI, SINGLE_CALL_BALANCES_ADDRESS) ethContract.methods.balances([this.selectedAddress], tokenAddresses).call({ from: this.selectedAddress }, (error, result) => { if (error) { warn('MetaMask - DetectTokensController single call balance fetch failed', error) return } const nonZeroTokens = [] tokenAddresses.forEach((tokenAddress, index) => { const balance = toHex(result[index]) if (balance && balance !== '0x0') { nonZeroTokens.push({ ...oldTokens[index], balance }) } }) this.detectedTokensStore.putState({ tokens: nonZeroTokens }) }) } } /** * Restart token detection polling period and call detectNewTokens * in case of address change or user session initialization. * */ restartTokenDetection() { if (!this.selectedAddress) { return } // this.detectedTokensStore.putState({ tokens: [] }) this.detectNewTokens() this.interval = DEFAULT_INTERVAL } /** * @type {Number} */ set interval(interval) { if (this._handle) clearInterval(this._handle) if (!interval) { return } this._handle = setInterval(() => { this.detectNewTokens() this.refreshTokenBalances() }, interval) } /** * In setter when isUnlocked is updated to true, detectNewTokens and restart polling * @type {Object} */ startTokenDetection(selectedAddress) { this.selectedAddress = selectedAddress this.restartTokenDetection() } }
JavaScript
class Group extends OkitArtifact { /* ** Create */ constructor (data={}, okitjson={}) { super(okitjson); // Configure default values this.display_name = this.generateDefaultName(okitjson.groups.length + 1); this.compartment_id = null; this.description = '' this.user_ids = [] // Update with any passed data this.merge(data); this.convert(); } /* ** Clone Functionality */ clone() { return new Group(JSON.clone(this), this.getOkitJson()); } /* ** Name Generation */ getNamePrefix() { return super.getNamePrefix() + 'grp'; } /* ** Static Functionality */ static getArtifactReference() { return 'Group'; } }
JavaScript
class App extends Component { constructor(props) { super(props); this.state = { videos: [], selectedVideo: null }; //videos is the property name. Its default value is an empty array. //(data) => is the same as function(data) //'surfboards' is the search keyword. YTSearch({key : API_KEY, term: 'cat'}, (videos) => { //this.setState({ videos: data}); //change (videos) => to (data) => //this.setState({ videos: videos}); //change (data) => to (videos) => this.setState({ videos: videos, selectedVideo: videos[0] }); //Assign returned 'videos' to state. //This works only when key and value is the same. }); } //Wrap YTSearch into a function, so it can be passed to SearchBar. videoSearch(term) { YTSearch({key : API_KEY, term: term}, (videos) => { //this.setState({ videos: data}); //change (videos) => to (data) => //this.setState({ videos: videos}); //change (data) => to (videos) => this.setState({ videos: videos, selectedVideo: videos[0] }); //Assign returned 'videos' to state. //This works only when key and value is the same. }); } render() { //lodash debounce: videoSearch is called only once every 300 ms. const videoSearch = _.debounce((term) => {this.videoSearch(term)}, 300); return ( //Pass the props 'videos' to VideoList. <div> <SearchBar onSearchTermChange={videoSearch} /> <VideoDetail video={this.state.selectedVideo}/> <VideoList //Pass the function property onVideoSelect to ViedoList. //In onVideoSelect function, pass selectedVideo to state. onVideoSelect={selectedVideo => this.setState({selectedVideo})} videos={this.state.videos} /> </div> ); } }
JavaScript
class IndexMinPQ { constructor(maxN) { if (maxN < 0) { throw new Error('IllegalArgumentException'); } // maximum number of elements on PQ this._maxN = maxN; // number of elements on PQ this._n = 0; // binary heap using 1-based indexing this._pq = new Array(this._maxN + 1); // inverse of pq - qp[pq[i]] = pq[qp[i]] = i this._qp = new Array(this._maxN + 1); // make this of length maxN?? // keys[i] = priority of i this._keys = new Array(this._maxN + 1); // make this of length maxN?? for (let i = 0; i <= this._maxN; i++) { this._qp[i] = -1; } } /** * Returns true if this priority queue is empty. */ isEmpty() { return this._n === 0; } /** * Is {@code i} an index on this priority queue? * @param {number} i */ contains(i) { if (i < 0 || i >= this._maxN) { throw new Error('IllegalArgumentException'); } return this._qp[i] !== -1; } /** * Returns the number of keys on this priority queue. */ size() { return this._n; } /** * Associates key with index {@code i}. (aka. add_with_priority()) * @param {number} i * @param {Key} key */ insert(i, key) { if (i < 0 || i >= this._maxN) { throw new Error('IllegalArgumentException'); } if (this.contains(i)) { throw new Error('index is already in the priority queue'); } this._n++; this._qp[i] = this._n; this._pq[this._n] = i; this._keys[i] = key; this._swim(this._n); } /** * Returns an index associated with a minimum key. */ minIndex() { if (this._n == 0) { throw new Error('Priority queue underflow'); } return this._pq[1]; } /** * Returns a minimum key. */ minKey() { if (this._n == 0) { throw new Error('Priority queue underflow'); } return this._keys[this._pq[1]]; } /** * Removes a minimum key and returns its associated index. (aka. extract_min()) */ delMin() { if (this._n == 0) { throw new Error('Priority queue underflow'); } const min = this._pq[1]; this._exch(1, this._n--); this._sink(1); this._qp[min] = -1; // delete this._keys[min] = null; // to help with garbage collection this._pq[this._n + 1] = -1; // not needed return min; } /** * Returns the key associated with index {@code i}. * * @param {number} i */ keyOf(i) { if (i < 0 || i >= this._maxN) { throw new Error('IllegalArgumentException'); } if (!this.contains(i)) { throw new Error('index is not in the priority queue'); } else { return this._keys[i]; } } /** * Change the key associated with index {@code i} to the specified value. * * @param {number} i * @param {Key} key */ changeKey(i, key) { if (i < 0 || i >= this._maxN) { throw new Error('IllegalArgumentException'); } if (!this.contains(i)) { throw new Error('index is not in the priority queue'); } this._keys[i] = key; this._swim(this._qp[i]); this._sink(this._qp[i]); } /** * Change the key associated with index {@code i} to the specified value. * * @Deprecated * * @param {*} i * @param {*} key */ change(i, key) { this.changeKey(i, key); } /** * Decrease the key associated with index {@code i} to the specified value. (aka. decrease_priority()) * * @param {number} i * @param {Key} key */ decreaseKey(i, key) { if (i < 0 || i >= this._maxN) { throw new Error('IllegalArgumentException'); } if (!this.contains(i)) { throw new Error('index is not in the priority queue'); } if (this._keys[i].localeCompare(key) <= 0) { throw new Error('Calling decreaseKey() with given argument would not strictly decrease the key'); } this._keys[i] = key; this._swim(this._qp[i]); } /** * Increase the key associated with index {@code i} to the specified value. * * @param {number} i * @param {Key} key */ increaseKey(i, key) { if (i < 0 || i >= this._maxN) { throw new Error('IllegalArgumentException'); } if (!this.contains(i)) { throw new Error('index is not in the priority queue'); } if (this._keys[i].localeCompare(key) >= 0) { throw new Error('Calling increaseKey() with given argument would not strictly increase the key'); } this._keys[i] = key; this._sink(this._qp[i]); } /** * Remove the key associated with index {@code i}. * * @param {number} i the index of the key to remove */ delete(i) { if (i < 0 || i >= this._maxN) { throw new Error('IllegalArgumentException'); } if (!this.contains(i)) { throw new Error('index is not in the priority queue'); } const index = this._qp[i]; this._exch(index, this._n--); this._swim(index); this._sink(index); this._keys[i] = null; this.qp[i] = -1; } // General helper functions. /** * @param {number} i * @param {number} j */ _greater(i, j) { return this._keys[this._pq[i]].localeCompare(this._keys[this._pq[j]]) > 0; } /** * @param {number} i * @param {number} j */ _exch(i, j) { let swap = this._pq[i]; this._pq[i] = this._pq[j]; this._pq[j] = swap; sthis._qp[this._pq[i]] = i; this._qp[this._pq[j]] = j; } // Heap helper functions. /** * (aka. heapifyUp) * * @param {number} k customStartIndex */ _swim(k) { // take last element (last in array or the bottom left in a tree) in // a heap container and lift him up until we find the parent element // that is less then the current new one // k = currentIndex // hasParent(currentIndex) && lessThan(heapContainer[currentIndex], parent(currentIndex)) while (k > 1 && this._greater(k / 2, k)) { // swap(currentIndex, getParentIndex(currentIndex)) this._exch(k, k / 2); // currentIndex = getParentIndex(currentIndex) k = k / 2; } } /** * (aka. heapifyDown) * * @param {number} k root of heap */ _sink(k) { // compare the root element to its children and swap root with the smallest // of children. do the same for next children after swap while (2 * k <= this._n) { // hasLeftChild(k), k - currentIndex // children of node at k are 2 * k and 2 * k + 1 let j = 2 * k; // hasRightChild(currentIndex) && lessThan(rightChild(currentIndex), leftChild(currentIndex) if (j < this._n && this._greater(j, j + 1)) { // nextIndex j++; } // lessThan(heapContainer[currentIndex], heapContainer[nextIndex]) if (!this._greater(k, j)) { break; } // swap(currentIndex, nextIndex); this._exch(k, j); // currentIndex = nextIndex; k = j; } } }
JavaScript
class Listing { constructor(srcElem, postcodeResolver, speedResolver) { this.elem = srcElem; this.address_elem = this.elem.querySelector('*[itemprop="address"] > *:first-of-type'); this.address = this.address_elem.innerText; this.postcode_resolver = postcodeResolver; this.speed_resolver = speedResolver; } /** * The estimated internet speed for this Zoopla listing. * @return Promise A promise that will be fulfilled with a string representation of the available internet speed. */ getSpeed() { return new Promise((resolve, reject) => { // Resolve partial address into postcode. this.postcode_resolver.getFromPartialAddress(this.address) .then( this.speed_resolver.getFromPostcode.bind(this.speed_resolver), (reason) => { reject('Can\'t retrieve a speed estimate: No postcode resolved.') } ) .then(resolve, reject); }); } render() { this.getSpeed() .then(this.createDomForSpeed) .then(speedDom => this.address_elem.appendChild(speedDom) ); } createDomForSpeed(speed) { return new Promise((resolve, reject) => { // Construct speed DOM to show on page var domForSpeed = document.createElement('ul') domForSpeed.style.margin = '0'; domForSpeed.style.padding = '0'; domForSpeed.className = 'ZooplaInternetEstimate'; var averageSpeedElement = document.createElement('li'); averageSpeedElement.style.margin = '0'; averageSpeedElement.style.padding = '0'; averageSpeedElement.appendChild( document.createTextNode( 'Avg speed: ' + speed.broadbandAverageSpeed + 'Mb/s' ) ) var superfastSpeedElement = document.createElement('li'); superfastSpeedElement.style.margin = '0'; superfastSpeedElement.style.padding = '0'; superfastSpeedElement.appendChild( document.createTextNode( 'Superfast max: ' + speed.superFastMaxSpeedRange + 'Mb/s' ) ); domForSpeed.appendChild(averageSpeedElement); domForSpeed.appendChild(superfastSpeedElement); // Add to actual page DOM resolve(domForSpeed); }); } }
JavaScript
class Tweet extends Component { //> This is called from the parent class's constructor. // Why is it called `init()` and not `constructor()`, you might ask? // There are a few reasons why I made this call. Primarily, this ensured that // components always had a valid and correct `#node` property by allowing // Torus to render all components in the constructor. This allows for the component // system to have a generally more ergonomic API. We can read and override // `Component#super()` if we want to extend Torus's functionality. init(author, content) { this.author = author; this.content = content; //> For some reason, if we want this component to update every time // the window is resized, we can do add kinds of listeners here. this.render = this.render.bind(this); window.addEventListener('resize', this.render); } //> Since we bound a listener in `init()`, we need to make sure we clean up // after ourselves. remove() { window.removeEventListener('resize', this.render); } //> We can access the instance and class variables within our JDOM template, // because it's just a JavaScript method. compose() { return jdom`<div class="tweet"> <div>${this.content}</div> <cite>${this.author}</cite> <p>The window size is now ${window.innerWidth}</p> </div>`; } }
JavaScript
class FancyInput extends Component { init() { this.onFocus = this.onFocus.bind(this); this.onBlur = this.onBlur.bind(this); } onFocus() { console.log('Focused input'); } onBlur() { console.log('Blurred input'); } compose() { return jdom`<input type=text onfocus=${this.onFocus} onblur=${this.onBlur} />`; } }
JavaScript
class RankingsList extends Component { //> Let's say we want this component to display top 10 places by default init(limit = 10) { this.limit = limit; this.rankings = []; //> We don't always want to fetch when we create a view, but just for today, // let's say we'll fetch for new data when this view first appears. this.fetch(); } async fetch() { const data = fetch('/api/v2/rankings?limit=10').then(r = r.json()); //> Only take the first `this.limit` results this.rankings = data.slice(0, this.limit); //> Since data's changed, we'll re-render the view this.render(); } compose() { return jdom`<ol> ${this.rankings.map(winner => { //> We can nest a template within a template to render // a very simple list like this. For more complex lists, // we'll want to use a `List` component, like the one below, // where each item gets its own component. return jdom`<li> ${winner.name}, from ${winner.city} </li>`; })} </ol>`; } }
JavaScript
class AppWithSidebar extends Component { init() { //> As a downside of that tradeoff, we need to keep track // of children components ourselves... this.sidebar = new Sidebar(); this.main = new MainPanel(); } remove() { //> ... but most of that just means instantiating and removing children views // inside parent views, like this. this.sidebar.remove(); this.main.remove(); } compose() { //> Because we can embed HTML nodes inside `jdom` templates, we can // include our children components in the parent component's DOM tree easily, like this. return jdom`<div class="root"> ${this.sidebar.node} ${this.main.node} </div>`; } }
JavaScript
class FancyForm extends Component { compose() { return `<form> <h1>Super fancy form!</h1> <input name="full_name"/> ${fancyButton('Submit!')} </form>`; } }
JavaScript
class FancyForm extends Component { init() { this.button = new ClassyButton('Submit!'); } compose() { return `<form> <h1>Super fancy form!</h1> <input name="full_name"/> ${this.button.node} </form>`; } }
JavaScript
class MyVideoPlayer extends Component { //> **Option A** init() { //> Create a new element when the component is created, // and keep track of it. this.videoEl = document.createElement('video'); this.videoEl.src = '/videos/abc'; } play() { this.videoEl.play(); } compose() { //> We can compose a literal element within the root element return jdom`<div id="player"> ${this.videoEl} </div>`; } }
JavaScript
class FancyList extends StyledComponent { //> We define all of our styles in a `styles()` method, which returns a JSON // that resembles normal CSS, but with nesting and automagical media query resolution, // as well as downward scoping of CSS rules to this component. That means that when we // style `button` in this component, it won't ever conflict with other `button` elements // anywhere else on the page. styles() { return { //> Normal CSS properties are applied to the root node 'font-size': '18px', 'background': 'rgba(0, 0, 0, .4)', //> Keyframes and media queries will be scoped globally, // just like in CSS '@keyframes some-name': { 'from': {'opacity': 0}, 'to': {'opacity': 1}, }, //> Note that we don't select the element again // inside @media -- that's done for us by styled components. '@media (min-width: 600px)': { 'border-color': 'rgb(0, 1, 2)', 'p': { 'font-style': 'italic', }, }, //> We can use SCSS-like syntax for hierarchy. // '&' are replaced by the parent selector. '&.invalid': { // FancyList.invalid 'color': 'red', }, '&::after': { // FancyList::after 'content': '""', 'display': 'block', }, 'p': { // FancyList p 'font-weight': 'bold', 'em': { // FancyList p em 'color': 'blue', } } } } compose() { /* ... */ } }
JavaScript
class FancyList extends StyledComponent { styles() { //> Write the styles returned as a template literal with `css`. return css` font-size: 18px; background: rgba(0, 0, 0, .4); @keyframes some-name { from { opacity: 0; } to { opacity: 1; } } @media (min-width: 600px) { border-color: rgb(0, 1, 2); p { font-style: italic; } } &.invalid { color: red; } &::after { content: ""; display: block; } p { font-weight: bold; em { color: blue; } } `; } compose() { /* ... */ } }
JavaScript
class CakeProductListing extends Component { init(cakeProduct) { //> Bind this component to `cakeProduct`, so that when `cakeProduct` // updates, this callback function is called with the summary of the record. // Usually, we'll want to re-render. Note that when we bind, it immediately // calls the callback (in this case, `this.render(props)`) once. That means // everything we need to run render should be defined before this bind call. this.bind(cakeProduct, props => { //> `compose()` will be called with `props`, the summary of the cake record. // We don't always have to just re-render when the record updates. // we can also do other things in this callback. But rendering is most common. this.render(props); }); } //> We can have the component stop listening to a record, by calling `#unbind()`. stopUpdating() { // probably wouldn't write something like this normally this.unbind(); } //> When we bind a component to a new record, it stops listening to the old one automatically. switchCake(newCake) { // implicit `this.unbind()` this.bind(newCake, props => this.render(props)); } }