language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class EntityInterface { /** * Create a new EntityInterface instance * * @param {Client} client - a `Client` instance * @param {object} payloadObject - the `EntityObject` that the `CID` represents */ constructor (client, payloadObject) { // setup client for this entity instance if (check.instance(client, ClientInterface)) { this.client = client; } else { throw new Error('invalid client. expected client to be instance of ClientInterface'); } // setup payload const payload = new Payload(payloadObject, () => true); this.remoteCid = payload.removeCid(); try { this.payload = new Payload(payload.toJson(), this.client.getEntityCid.bind(this.client)); } catch (e) { throw new VError(e, 'failed to create new entity'); } this.cid = this.client.getEntityCid(this.payload); // throw error if there is weird cid mismatch if (check.not.undefined(this.remoteCid) && this.remoteCid !== this.cid) { const remoteCid = `remoteCid(${this.remoteCid})`; const payloadCid = `payloadCid(${this.cid})`; const cidMismatchError = new Error(`mismatch ${remoteCid} <> ${payloadCid}`); const invalidCidsError = new VError(cidMismatchError, 'invalid cids'); throw new VError(invalidCidsError, 'failed to instantiate new entity'); } // debug and log if (check.not.undefined(this.remoteCid)) { debug.extend(`newRemote${this.type}`)(this.remoteCid); } else { debug.extend(`newLocal${this.type}`)(this.cid); } } set payload (payload) { this._payload = payload; } get payload () { return this._payload; } set remoteCid (cid) { this._remoteCid = cid; } get remoteCid () { return this._remoteCid; } get type () { return this.payload.type; } /** * Create the entity on the server by sending its payload * * @async * @returns {Promise<String>|Error} - Resolves to the CID of the entities payload */ async create () { const cid = await this.client.createEntity(this.payload); this.remoteCid = cid; debug.extend(`create${this.type}`)(`...${this.remoteCid.slice(-8)}`); return this.remoteCid; } /** * Given the payload of the entity it fetches the related entities and instantiates * proper `Entities` from them. * * @async */ async resolve () { /* eslint-disable-next-line no-unused-vars */ const decoder = this.client.rlay.decodeValue.bind(this.client.rlay); const resolver = this.client.Entity.find.bind(this.client.Entity); const resolvedPayload = await this.payload.clone(). decode(decoder). resolveCids(resolver); resolvedPayload.removeType(); Object.assign(this, resolvedPayload); debug.extend(`resolve${this.type}`)(`...${this.remoteCid.slice(-8)}`); return this; } async fetch () { console.warn('DEPRECATED: use `.resolve`. `.fetch` will be retired in the next minor release'); return this.resolve(); } }
JavaScript
class Sprite { constructor(x, y, w, h, color) { this.x = x; this.y = y; this.w = w; this.h = h; this.color = color; this.speed = 3; allSprites.push(this); } create(x,y,w,h) { return new Sprite(x, y, w, h) } // snses if objects collide collideWith(obj){ if (this.x + this.w >= obj.x && this.x <= obj.x + obj.w && this.y + this.h >= obj.y && this.y <= obj.y + obj.h ) { return true; } } // update method draw() { ctx.fillStyle = this.color; ctx.fillRect(this.x, this.y, this.w, this.h); } }
JavaScript
class Wall extends Sprite { constructor (x, y, w, h, color) { super(x, y, w, h, color); this.x = x; this.y = y; this.w = w; this.h = h; this.color = 'rgb(0, 200, 200)'; allWalls.push(this); } create(x,y,w,h) { return new Wall(x, y, w, h) } }
JavaScript
class Cactus extends Sprite { constructor (x, y, w, h, color) { super(x, y, w, h, color); this.x = x; this.y = y; this.w = w; this.h = h; this.color = 'rgb(0, 255, 0)'; allCacti.push(this); } create(x,y,w,h) { return new Cactus(x, y, w, h) } }
JavaScript
class CalendarTraceToString extends Temporal.Calendar { constructor(id) { super("iso8601"); this.id_ = id; this.calls = 0; } toString() { ++this.calls; return this.id_; } }
JavaScript
class Api { constructor(config) { this.cohortId = config.cohortId; this.serverUrl = config.serverUrl; this.authToken = config.authToken; } //gets user info from server getUserInfo() { return fetch((this.serverUrl + this.cohortId + '/users/me'), { method: 'GET', headers: { 'authorization': this.authToken, }, }) .then( (res) => { if (res.ok) { return res.json(); } else { return Promise.reject; } }) .catch((err) => console.log('Could not get user info: ' + err)); } //fetches cards from server getCards() { return fetch((this.serverUrl + this.cohortId + '/cards'), { method: 'GET', headers: { 'authorization': this.authToken, } }) .then( (res) => { if (res.ok) { return res.json(); } return Promise.reject('Could not get cards: ' + res.status); }); } //sets a temporary text value to a button while data is being loaded loadingButtonText(loadingData, submitButton, originalButtonText) { // accepts boolean, DOM element, string if (loadingData) { submitButton.textContent = 'Загрузка...'; submitButton.style.color = 'greenyellow'; } else { submitButton.textContent = originalButtonText; submitButton.style.color = 'white'; } } //sends new name and info values to server updateForm(name, info) { return fetch((this.serverUrl + this.cohortId + '/users/me'), { method: 'PATCH', headers: { 'authorization': this.authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ name: name, about: info, }), }) .then((res) => { if (res.ok) { return res.json() ; } else { return Promise.reject; } }) .catch( (err) => console.log('Cannot get user info, error: ' + err) ); } //sends a new card to server postCardToServer(name, link) { return fetch((this.serverUrl + this.cohortId + '/cards'), { method: 'POST', headers: { 'authorization': this.authToken, 'Content-Type': 'application/json', }, body: JSON.stringify({ name: name, link: link, }), }) .then((res) => { if (res.ok) { return res.json(); } else { return Promise.reject; } }) .catch((err) => console.log('Could not post card. Reason: ' + err)); } //removes card from server deleteCard(id) { return fetch((this.serverUrl + this.cohortId + '/cards/' + id), { method: 'DELETE', headers: { 'authorization': this.authToken, 'Content-Type': 'application/json', } }) .then((resp) => { if (resp.ok) { return resp.json(); } else { return Promise.reject; } }) .catch((err) => console.log('Could not delete card. Reason: ' + err)); } //adds user's like to card renderLikes(id, likes) { return fetch((this.serverUrl + this.cohortId + '/cards/like/' + id), { method: 'PUT', headers: { 'authorization': this.authToken, 'Content-Type': 'application/json', }, body: JSON.stringify({ likes: likes, }), }) .then((resp) => { if (resp.ok) { return resp.json(); } else { return Promise.reject; } }) .catch((err) => console.log('Could not render likes. Reason: ' + err)); } //develes user's like from card unlikeCard(id) { return fetch((this.serverUrl + this.cohortId + '/cards/like/' + id), { method: 'DELETE', headers: { authorization: this.authToken, 'Content-Type': 'application/json' } }) } //updates avatar url on server changeAvatar(avatarUrl) { return fetch((this.serverUrl + this.cohortId + '/users/me/avatar'), { method: 'PATCH', headers: { 'authorization': this.authToken, 'Content-Type': 'application/json', }, body: JSON.stringify({ avatar: avatarUrl, }), }) .then((resp) => { if (resp.ok) { return resp.json(); } else { return Promise.reject; } }) .catch((err) => console.log('Could not change avatar. Reason: ' + err)); } }
JavaScript
class Controller extends EventEmitter { #color = true; #elapsed = 0; #mute = false; #timer = null; #timerLabel = null; /** * @summary Matches reserver chars for filepath parts * @example * on "win32" drive split by ":" -> /test:file/ matches * @type {Map.<string, RegExp>} * @private */ #reserved = new Map() .set('win32', /[/\?%*|"<>]|([^:]):(?!:)/g); /** * @param {EventEmitterOptions} emitterOpts * @param {ExposeRequireOptions} [opts] */ constructor(emitterOpts = {}, opts = {}) { super(emitterOpts); opts.mute && this.mute(); this.#color = opts.color || true; this.output = validateLog(opts.log); this.logs = new Map(); } /** * Getter for reserved RegExp * @returns {RegExp} */ get reserved() { const { os } = this; return this.#reserved.get(os); } /** * Getter for platform * @returns {string} */ get os() { return OS.platform(); } /** * Logs a message at debug level * @param {string} msg * @returns {Controller} */ debug(msg) { return this.log(blue(msg), 'debug'); } /** * Logs an error level message * @param {string} msg * @returns {Controller} */ err(msg) { return this.log(red(msg), 'error'); } /** * Mutes log output * @returns {Controller} */ mute() { this.emit('mute'); this.#mute = true; return this; } /** * Replaces OS-specific reserved chars in file path * @param {string} [filePath] * @returns {string} */ replaceReserved(filePath = '') { const { reserved } = this; const { sep } = pt; const parts = pt.normalize(filePath).split(sep); const mapped = parts .slice(1) .map(part => { const fixedPath = part.replace(reserved, '$1'); return fixedPath; }); return pt.join(parts[0], ...mapped); } /** * Logs a message at success level * @param {string} msg * @returns {Controller} */ success(msg) { return this.log(green(msg), 'success'); } /** * Logs a message * @param {string} message * @param {string} level * @returns {Controller} */ log(message, level = 'log') { const { logs, output } = this; this.emit('log', message, level); logs .set(Date.now(), { message, level }); this.#color || (message = stripColor(message)); this.#mute || output.write(`${message}\n`); return this; } /** * Starts timer * @param {string} [label] * @returns {Controller} */ time(label) { this.timeReset(); const alreadyRunning = this.#timer; alreadyRunning && clearInterval(this.#timerLabel); const timer = setInterval(() => this.#elapsed += .001, 1); this.#timer = timer; typeof label === 'string' && (this.#timerLabel = label); return this; } /** * Resets timer * @returns {Controller} */ timeReset() { this.#elapsed = 0; return this; } /** * Ends timer * @returns {number} */ timeEnd() { const elapsed = this.#elapsed.toFixed(3); const timer = this.#timer; if (timer) { const label = this.#timerLabel; clearInterval(timer); this.log(`${label || 'Timer'} done in ${elapsed}s`); } this.timeReset(); return elapsed; } /** * Unmutes log output * @returns {Controller} */ unmute() { this.emit('unmute'); this.#mute = false; return this; } /** * Logs a warning level message * @param {string} msg * @returns {Controller} */ warn(msg) { return this.log(yellow(msg), 'warn'); } }
JavaScript
class PostponedVideo extends Component { constructor(props) { super(props); this.videoRef = React.createRef(); this.state = { isPlaying: false, }; const { update, index } = props.deck; const { setSteps } = updaters; update(setSteps(index, 1)); } get _video() { return this.videoRef.current; } componentDidMount() { this._resetVideo(); if (this.props.deck.active) { this._updateVideoBasedOnStep(); } } componentDidUpdate(prevProps) { if (prevProps.deck.active && !this.props.deck.active) { setTimeout(this._resetVideo, transitionDuration); } if (prevProps.deck.step !== this.props.deck.step) { this._updateVideoBasedOnStep(); } } render() { const { isPlaying } = this.state; return ( <VideoWrapper> <Centered> <video ref={this.videoRef} {...this.props} /> </Centered> {isPlaying || <CenteredPlayIcon onClick={this._startPlaying} />} </VideoWrapper> ); } _updateVideoBasedOnStep() { const { step, active } = this.props.deck; if (step === 0) { this._video.pause(); this.setState({ isPlaying: false }); } else if (step === 1 && active) { this._startPlaying(); } } _startPlaying = () => { this._video.play(); this.setState({ isPlaying: true }); }; _resetVideo = () => { this._video.load(); }; }
JavaScript
class BaseRTCStatsReport { /** * Create a BaseRTCStatsReport. * * @constructs * @param {RTCStatsReport} originalReport - original stats report from `(pc|sender|receiver).getStats()`. */ constructor(originalReport) { const report = new Map(); for (const originalStats of originalReport.values()) { const ref = this._getRTCStatsReference(originalStats); const stats = {}; // get the preferred value from original stats. for (const attr of RTCStatsReferenceMap.get(ref)) { if (originalStats[attr] !== undefined) { stats[attr] = originalStats[attr]; } } // update the stats object if (report.has(ref)) { const statsArray = report.get(ref); statsArray.push(stats); report.set(ref, statsArray); } else { report.set(ref, [stats]); } } this._report = report; } /** * Get the array of type of stats referred by `key`. * * @param {string} key - A stats object reference defined in {@link RTCStatsReferences} enum. * @return {Array<RTCStats>} An array of stats referred by `key`. * @example * const report = new BaseRTCStatsReport(await pc.getStats()); * * if (report.get(RTCStatsReferences.RTCInboundRtpVideoStreams.key)) { * const stats = report.get( * RTCStatsReferences.RTCInboundRtpVideoStreams.key * )[0]; * logger.info(`ts:${stats.timestamp} id:${stats.trackId} recv:${stats.bytesReceived}`); */ get(key) { return this._report.get(key); } /** * Check if the instance has the type of stats referred by `key`. * * @param {string} key - A stats object reference defined in {@link RTCStatsReferences} enum. * @return {bool} True if the referred stats exists. * @example * const report = new BaseRTCStatsReport(await pc.getStats()); * * if (report.has(RTCStatsReferences.RTCInboundRtpVideoStreams.key)) { * logger.info("receiving video."); * } else { * logger.info("no video streams receiving."); * } */ has(key) { return this._report.has(key); } _getRTCStatsReference(stats) { switch (stats.type) { case "codec": return RTCStatsReferences.RTCCodecs.key; case "inbound-rtp": if (stats.kind === "video") { return RTCStatsReferences.RTCInboundRtpVideoStreams.key; } else if (stats.kind === "audio") { return RTCStatsReferences.RTCInboundRtpAudioStreams.key; } break; case "outbound-rtp": if (stats.kind === "video") { return RTCStatsReferences.RTCOutboundRtpVideoStreams.key; } else if (stats.kind === "audio") { return RTCStatsReferences.RTCOutboundRtpAudioStreams.key; } break; case "remote-inbound-rtp": if (stats.kind === "video") { return RTCStatsReferences.RTCRemoteInboundRtpVideoStreams.key; } else if (stats.kind === "audio") { return RTCStatsReferences.RTCRemoteInboundRtpAudioStreams.key; } break; case "remote-outbound-rtp": if (stats.kind === "video") { return RTCStatsReferences.RTCRemoteOutboundRtpVideoStreams.key; } else if (stats.kind === "audio") { return RTCStatsReferences.RTCRemoteOutboundRtpAudioStreams.key; } break; case "media-source": if (stats.kind === "video") { return RTCStatsReferences.RTCVideoSources.key; } else if (stats.kind === "audio") { return RTCStatsReferences.RTCAudioSources.key; } break; case "csrc": return RTCStatsReferences.RTCRtpContributingSources.key; case "peer-connection": return RTCStatsReferences.RTCPeerConnection.key; case "data-channel": return RTCStatsReferences.RTCDataChannels.key; case "stream": return RTCStatsReferences.RTCMediaStreams.key; case "sender": if (stats.kind === "video") { return RTCStatsReferences.RTCVideoSenders.key; } else if (stats.kind === "audio") { return RTCStatsReferences.RTCAudioSenders.key; } break; case "receiver": if (stats.kind === "video") { return RTCStatsReferences.RTCVideoReceivers.key; } else if (stats.kind === "audio") { return RTCStatsReferences.RTCAudioReceivers.key; } break; case "transport": return RTCStatsReferences.RTCTransports.key; case "candidate-pair": return RTCStatsReferences.RTCIceCandidatePairs.key; case "local-candidate": return RTCStatsReferences.RTCLocalIceCandidates.key; case "remote-candidate": return RTCStatsReferences.RTCRemoteIceCandidates.key; case "certificate": return RTCStatsReferences.RTCCertificates.key; case "stunserverconnection": return RTCStatsReferences.RTCStunServerConnections.key; default: throw new Error( `Received an unknown stats-type string: ${stats.type}.` ); } throw new Error( `Received an unknown kind of ${stats.type}: ${stats.kind}.` ); } }
JavaScript
class ChromeRTCStatsReport extends BaseRTCStatsReport { _getRTCStatsReference(stats) { switch (stats.type) { case "track": if (stats.remoteSource && stats.kind === "video") { return RTCStatsReferences.RTCVideoReceivers.key; } else if (stats.remoteSource && stats.kind === "audio") { return RTCStatsReferences.RTCAudioReceivers.key; } else if (stats.kind === "video") { return RTCStatsReferences.RTCVideoSenders.key; } else if (stats.kind === "audio") { return RTCStatsReferences.RTCAudioSenders.key; } } return super._getRTCStatsReference(stats); } }
JavaScript
class FirefoxRTCStatsReport extends BaseRTCStatsReport { constructor(originalReport) { super(originalReport); // retrieve receiver/sender stats const statsRefs = [...originalReport.keys()]; const rtpRefs = statsRefs.filter(ref => /(in|out)bound_rtp_.*/.test(ref)); for (const originalRef of rtpRefs) { const originalStats = originalReport.get(originalRef); const ref = getTrackStatsOfFirefox(originalStats); const stats = {}; // get the preferred value from original stats. for (const attr of RTCStatsReferenceMap.get(ref)) { if (originalStats[attr] !== undefined) { stats[attr] = originalStats[attr]; } } // update the stats object if (this._report.has(ref)) { const statsArray = this._report.get(ref); statsArray.push(stats); this._report.set(ref, statsArray); } else { this._report.set(ref, [stats]); } } } }
JavaScript
class SafariRTCStatsReport extends BaseRTCStatsReport { _getRTCStatsReference(stats) { switch (stats.type) { case "track": if (stats.remoteSource && stats.hasOwnProperty("frameHeight")) { return RTCStatsReferences.RTCVideoReceivers.key; } else if (stats.remoteSource && stats.hasOwnProperty("audioLevel")) { return RTCStatsReferences.RTCAudioReceivers.key; } else if (stats.hasOwnProperty("frameHeight")) { return RTCStatsReferences.RTCVideoSenders.key; } else if (stats.hasOwnProperty("audioLevel")) { return RTCStatsReferences.RTCAudioSenders.key; } break; case "inbound-rtp": if (stats.mediaType === "video") { return RTCStatsReferences.RTCInboundRtpVideoStreams.key; } else if (stats.mediaType === "audio") { return RTCStatsReferences.RTCInboundRtpAudioStreams.key; } break; case "outbound-rtp": if (stats.mediaType === "video") { return RTCStatsReferences.RTCOutboundRtpVideoStreams.key; } else if (stats.mediaType === "audio") { return RTCStatsReferences.RTCOutboundRtpAudioStreams.key; } break; } return super._getRTCStatsReference(stats); } }
JavaScript
class RTCStatsMoment { /** * Create a RTCStatsMoment. * * @constructs */ constructor() { this.standardizer = getStandardizer(); this._report = { prev: new Map(), last: new Map() }; } /** * Update the report. * * @param {RTCStatsReport} report - original stats report from `(pc|sender|receiver).getStats()`. * @example * import { RTCStatsMoment } from 'rtcstats-wrapper'; * * const moment = new RTCStatsMoment(); * * const id = setInterval(() => { * const report = await pc.getStats(); * moment.update(report); * }, INTERVAL); */ update(report) { this._report.prev = this._report.last; this._report.last = new this.standardizer(report); } /** * Calculate the momentary value based on the updated value. * MomentaryReport does not have attribute that can not be obtained. * * @return {MomentaryReport} * @example * import { RTCStatsMoment } from 'rtcstats-wrapper'; * * const moment = new RTCStatsMoment(); * * const receiver = pc.getReceivers().find(sender => sender.kind === "video"); * const report = receiver.getStats(); * moment.update(report); * moment.report(); * //=> { * // "send": { * // "video": { ... }, * // } * //} */ report() { const { last, prev } = this._report; return { send: { video: getVideoSenderStats(last, prev), audio: getAudioSenderStats(last, prev) }, receive: { video: getVideoReceiverStats(last, prev), audio: getAudioReceiverStats(last, prev) }, candidatePair: getCandidatePairStats(last, prev) }; } }
JavaScript
class RTCStatsInsight extends EventEmitter { /** * Create a RTCStatsInsight. * * @constructs * @param {RTCPeerConnection|RTCRtpReceiver|RTCRtpSender} statsSrc - getStats() method of this object is called in RTCStatsInsight. * @param {Object} options * @param {Number} options.interval - The polling interval in milliseconds. default 1000ms. * @param {Thresholds} options.thresholds - A set of thresholds for emitting each events. * @param {Object} options.triggerCondition - The trigger condition which defines how much failures makes this to fire an event. `${triggerCondition.failCount}` failures within `${triggerCondition.within}` attemption causes trigger of events. */ constructor(statsSrc, options) { super(); options = options || {}; this._statsSrc = statsSrc; this._interval = options.interval || 1000; this._thresholds = { ...DEFAULT_THRESHOLDS, ...options.thresholds }; this._moment = new RTCStatsMoment(); this._status = RTCStatsInsightEvents.enums.reduce( (acc, cur) => Object.assign(acc, { [cur]: new ConnectionStatus(options.triggerCondition) }), {} ); } /** * Start polling getStats(). * * @fires RTCStatsInsight#audio-rtt * @fires RTCStatsInsight#video-rtt * @fires RTCStatsInsight#audio-jitter * @fires RTCStatsInsight#video-jitter * @fires RTCStatsInsight#audio-fractionLost * @fires RTCStatsInsight#video-fractionLost * @fires RTCStatsInsight#audio-jitterBufferDelay * @fires RTCStatsInsight#video-jitterBufferDelay * @fires RTCStatsInsight#rtt * @see {RTCStatsInsightEvents} */ watch() { /** * Fires when an RTT of sending audio stream has been changed. * By default, `unstable` fires on RTT > 400ms and `critical` fires on RTT > 800ms. * * @event RTCStatsInsight#audio-rtt * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ /** * Fires when an RTT of sending video stream has been changed. * By default, `unstable` fires on RTT > 400ms and `critical` fires on RTT > 800ms. * * @event RTCStatsInsight#video-rtt * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ /** * Fires when a jitter of sending audio stream has been changed. * By default, `unstable` fires on jitter > 50ms and `critical` fires on jitter > 100ms. * * @event RTCStatsInsight#audio-jitter * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ /** * Fires when a jitter of sending video stream has been changed. * By default, `unstable` fires on jitter > 30ms and `critical` fires on jitter > 100ms. * * @event RTCStatsInsight#video-jitter * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ /** * Fires when the packet loss rate of receiving audio stream has been changed. * By default, `unstable` fires on packet loss rate > 8% and `critical` fires on packet loss rate > 15%. * * @event RTCStatsInsight#audio-fractionLost * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ /** * Fires when the packet loss rate of receiving video stream has been changed. * By default, `unstable` fires on packet loss rate > 8% and `critical` fires on packet loss rate > 15%. * * @event RTCStatsInsight#video-fractionLost * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ /** * Fires when the jitter buffer delay of receiving audio stream has been changed. * By default, `unstable` fires on jitter buffer delay > 500ms and `critical` fires on jitter buffer delay > 1000ms. * * @event RTCStatsInsight#audio-jitterBufferDelay * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ /** * Fires when the jitter buffer delay of receiving video stream has been changed. * By default, `unstable` fires on jitter buffer delay > 50ms and `critical` fires on jitter buffer delay > 100ms. * * @event RTCStatsInsight#video-jitterBufferDelay * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ /** * Fires when the rtt of ICE connection has been changed. * The difference with media RTT is that media RTT uses the value of RTCP packet, and this RTT uses ICE connectivity checks timestamp. * By default, `unstable` fires on rtt > 500ms and `critical` fires on rtt > 1000ms. * * @event RTCStatsInsight#rtt * @property {string} level - Warning level. This will be "stable" or "unstable" or "critical". * @property {string} threshold - Threshold for this event to fire. * @property {string} value - Last measured value when this event fires. */ this._intervalID = setInterval(async () => { const report = await this._statsSrc.getStats(); this._moment.update(report); const momentum = this._moment.report(); this._checkStatus(momentum); }, this._interval); } /** * Stop polling getStats(). */ stop() { clearInterval(this._intervalID); } get status() { return this._status; } _checkStatus(moment) { const metrics = [ { direction: "send", kind: "audio", key: "rtt" }, { direction: "send", kind: "video", key: "rtt" }, { direction: "send", kind: "audio", key: "jitter" }, { direction: "send", kind: "video", key: "jitter" }, { direction: "receive", kind: "audio", key: "fractionLost" }, { direction: "receive", kind: "video", key: "fractionLost" }, { direction: "receive", kind: "audio", key: "jitterBufferDelay" }, { direction: "receive", kind: "video", key: "jitterBufferDelay" }, { direction: "candidatePair", key: "rtt" } ]; for (const { direction, kind, key } of metrics) { const stats = direction === "candidatePair" ? moment[direction] : moment[direction][kind]; const eventKey = direction === "candidatePair" ? key : `${kind}-${key}`; if (stats.hasOwnProperty(key)) { // Update the value and emit when the the level has been changed. const currentLevel = this._status[eventKey].level; this._status[eventKey].check(stats[key], this._thresholds[eventKey]); const updatedLevel = this._status[eventKey].level; if (updatedLevel !== currentLevel) { if (currentLevel === "unknown" && updatedLevel === "stable") continue; this.emit(eventKey, { level: updatedLevel, event: eventKey, threshold: this._thresholds[eventKey][updatedLevel], value: stats[key] }); } } } } }
JavaScript
class PulldownHeaderMenu extends React.Component { static propTypes = { topMenuData: PropTypes.array.isRequired, onMenuItemPress: PropTypes.func, } handleMenuItemPress = (index, data) => { this.props.onMenuItemPress && this.props.onMenuItemPress(index, data) } render() { return ( <AnimatedNode_ animationKey='headerBGColor' > <Animated.View style={styles.container} > { this.props.topMenuData.map((data, index) => ( <AnimatedNode_ key={`listItem${index}`} animationKey={`expandedHeaderItem${(index + 1)}`} > <AnimatedHeaderListItem text={data.title} onPress={() => this.handleMenuItemPress(index, data)} /> </AnimatedNode_> )) } </Animated.View> </AnimatedNode_> ) } }
JavaScript
class App extends Component { componentDidMount() { // react Component method this.refreshPizzas(); } // refreshPizzas gets the pizzas from the database and adds them to the Redux state refreshPizzas = () => { // grab the dispatch function from props const { dispatch } = this.props; // axios server request axios.get("/api/pizza") .then((response) => { dispatch({ type: "GET_PIZZAS", payload: response.data }); }) .catch((error) => { console.log(error); }); }; // end refreshPizzas // React render function render() { return ( <Router> <div className="App"> <Header /> <Switch> <Route exact path="/"> <PizzaList /> </Route> <Route exact path="/customer-info"> <CustomerInfoForm refreshPizzas={this.refreshPizzas} /> </Route> <Route exact path="/checkout"> <Checkout /> </Route> <Route exact path="/admin"> <Admin /> </Route> </Switch> <Footer /> </div> </Router> ); // end return } // end render } // end App
JavaScript
class App extends Component { render() { return ( <div> <MemoryGame /> </div> ) } }
JavaScript
class Ad extends okanjo.Placement { constructor(element, options) { // Initialize placement w/o loading (we need to jack the config) options = options || {}; const no_init = options.no_init; // hold original no_init flag, if set options.no_init = true; super(element, options); okanjo.warn('Ad widget has been deprecated. Use Placement instead (may require configuration changes)', { widget: this }); // Start loading content if (!no_init) { delete this.config.no_init; this.init(); } } //noinspection JSUnusedGlobalSymbols /** * Converts the old product widget configuration into a usable placement configuration */ _setCompatibilityOptions() { // Convert the product config to a placement configuration this.config.backwards = 'Ad'; this.config.type = okanjo.Placement.ContentTypes.products; // Id / single mode is now ids this.config.url = null; if (this.config.id) { this.config.ids = [this.config.id]; } else { okanjo.warn('Ad widget should have parameter `id` set.'); } this.config.take = 1; delete this.config.id; // Content is automatically determined whether the placement element contains children delete this.config.content; } }
JavaScript
class AppCredentials { constructor(appId, channelAuthTenant, oAuthScope = authenticationConstants_1.AuthenticationConstants.ToBotFromChannelTokenIssuer) { this.refreshingToken = null; this.appId = appId; this.tenant = channelAuthTenant; this.oAuthEndpoint = authenticationConstants_1.AuthenticationConstants.ToChannelFromBotLoginUrlPrefix + this.tenant; this.oAuthScope = oAuthScope; } get tenant() { return this._tenant; } set tenant(value) { this._tenant = value && value.length > 0 ? value : authenticationConstants_1.AuthenticationConstants.DefaultChannelAuthTenant; } get oAuthScope() { return this._oAuthScope; } set oAuthScope(value) { this._oAuthScope = value; this.tokenCacheKey = `${this.appId}${this.oAuthScope}-cache`; } get oAuthEndpoint() { return this._oAuthEndpoint; } set oAuthEndpoint(value) { // aadApiVersion is set to '1.5' to avoid the "spn:" concatenation on the audience claim // For more info, see https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/issues/128 this._oAuthEndpoint = value; this.authenticationContext = new adal.AuthenticationContext(value, true, undefined, '1.5'); } /** * Adds the host of service url to trusted hosts. * If expiration time is not provided, the expiration date will be current (utc) date + 1 day. * @param {string} serviceUrl The service url * @param {Date} expiration? The expiration date after which this service url is not trusted anymore */ static trustServiceUrl(serviceUrl, expiration) { if (!expiration) { expiration = new Date(Date.now() + 86400000); // 1 day } const uri = url.parse(serviceUrl); if (uri.host) { AppCredentials.trustedHostNames.set(uri.host, expiration); } } /** * Checks if the service url is for a trusted host or not. * @param {string} serviceUrl The service url * @returns {boolean} True if the host of the service url is trusted; False otherwise. */ static isTrustedServiceUrl(serviceUrl) { try { const uri = url.parse(serviceUrl); if (uri.host) { return AppCredentials.isTrustedUrl(uri.host); } } catch (e) { // tslint:disable-next-line:no-console console.error('Error in isTrustedServiceUrl', e); } return false; } static isTrustedUrl(uri) { const expiration = AppCredentials.trustedHostNames.get(uri); if (expiration) { // check if the trusted service url is still valid return expiration.getTime() > (Date.now() - 300000); // 5 Minutes } return false; } signRequest(webResource) { return __awaiter(this, void 0, void 0, function* () { if (this.shouldSetToken(webResource)) { const token = yield this.getToken(); return new msrest.TokenCredentials(token).signRequest(webResource); } return webResource; }); } getToken(forceRefresh = false) { return __awaiter(this, void 0, void 0, function* () { if (!forceRefresh) { // check the global cache for the token. If we have it, and it's valid, we're done. const oAuthToken = AppCredentials.cache.get(this.tokenCacheKey); if (oAuthToken) { // we have the token. Is it valid? if (oAuthToken.expirationTime > Date.now()) { return oAuthToken.accessToken; } } } // We need to refresh the token, because: // 1. The user requested it via the forceRefresh parameter // 2. We have it, but it's expired // 3. We don't have it in the cache. const res = yield this.refreshToken(); this.refreshingToken = null; if (res && res.accessToken) { // `res` is equalivent to the results from the cached promise `this.refreshingToken`. // Because the promise has been cached, we need to see if the body has been read. // If the body has not been read yet, we can call res.json() to get the access_token. // If the body has been read, the OAuthResponse for that call should have been cached already, // in which case we can return the cache from there. If a cached OAuthResponse does not exist, // call getToken() again to retry the authentication process. // Subtract 5 minutes from expires_in so they'll we'll get a // new token before it expires. res.expirationTime = Date.now() + (res.expiresIn * 1000) - 300000; AppCredentials.cache.set(this.tokenCacheKey, res); return res.accessToken; } else { throw new Error('Authentication: No response or error received from ADAL.'); } }); } shouldSetToken(webResource) { return AppCredentials.isTrustedServiceUrl(webResource.url); } }
JavaScript
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } }
JavaScript
class Employee { constructor(name, id, email, office){ this.name = name; this.id = id; this.email = email; this.office = office; } printInput(){ console.log(`Name: ${this.name}`); console.log(`ID: ${this.id}`); console.log(`Email: ${this.email}`); console.log(`Office: ${this.office}`); } }
JavaScript
class Workflow extends Base { /** * Creates a `Workflow`. * @param {object} workflow - The initial workflow object. This User object will be extended with workflow properties. * @param {object} opts - The configuration options. * @param {string} opts.nuxeo - The {@link Nuxeo} object linked to this workflow. * @param {string} [opts.documentId] - The attached document id of this workflow, if any. */ constructor(workflow, opts) { super(opts); this._nuxeo = opts.nuxeo; this._documentId = opts.documentId; extend(true, this, workflow); } /** * Fetches the tasks of this workflow. * @param {object} [opts] - Options overriding the ones from this object. * @returns {Promise} A promise object resolved with the tasks. */ fetchTasks(opts = {}) { const options = this._computeOptions(opts); options.documentId = this.uid; return this._buildTasksRequest() .get(options); } /** * Fetches this workflow graph. * @param {object} [opts] - Options overriding the ones from this object. * @returns {Promise} A promise object resolved with the workflow graph. */ fetchGraph(opts = {}) { const options = this._computeOptions(opts); const path = join(WORKFLOW_PATH, this.id, 'graph'); return this._nuxeo.request(path) .get(options); } /** * Builds the correct `Request` object depending of whether this workflow is attached to a document or not. * @returns {Request} A request object. */ _buildTasksRequest() { if (this._documentId) { const path = join('id', this._documentId, '@workflow', this.id, 'task'); return this._nuxeo.request(path); } return this._nuxeo.request('task') .queryParams({ workflowInstanceId: this.id, }); } }
JavaScript
class Unit extends GameObject { /** * Initializes a Unit with basic logic as provided by the Creer code generator. * * Never use this directly. It is for internal Joueur use. */ constructor(...args) { super(...args); // The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. // default values for private member values this.acted = false; this.crew = 0; this.crewHealth = 0; this.gold = 0; this.moves = 0; this.owner = null; this.path = []; this.shipHealth = 0; this.stunTurns = 0; this.targetPort = null; this.tile = null; //<<-- Creer-Merge: init -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // any additional init logic you want can go here //<<-- /Creer-Merge: init -->> } // Member variables /** * Whether this Unit has performed its action this turn. * * @type {boolean} */ get acted() { return client.gameManager.getMemberValue(this, 'acted'); } set acted(value) { client.gameManager.setMemberValue(this, 'acted', value); } /** * How many crew are on this Tile. This number will always be <= crewHealth. * * @type {number} */ get crew() { return client.gameManager.getMemberValue(this, 'crew'); } set crew(value) { client.gameManager.setMemberValue(this, 'crew', value); } /** * How much total health the crew on this Tile have. * * @type {number} */ get crewHealth() { return client.gameManager.getMemberValue(this, 'crewHealth'); } set crewHealth(value) { client.gameManager.setMemberValue(this, 'crewHealth', value); } /** * How much gold this Unit is carrying. * * @type {number} */ get gold() { return client.gameManager.getMemberValue(this, 'gold'); } set gold(value) { client.gameManager.setMemberValue(this, 'gold', value); } /** * How many more times this Unit may move this turn. * * @type {number} */ get moves() { return client.gameManager.getMemberValue(this, 'moves'); } set moves(value) { client.gameManager.setMemberValue(this, 'moves', value); } /** * The Player that owns and can control this Unit, or null if the Unit is neutral. * * @type {Pirates.Player} */ get owner() { return client.gameManager.getMemberValue(this, 'owner'); } set owner(value) { client.gameManager.setMemberValue(this, 'owner', value); } /** * (Merchants only) The path this Unit will follow. The first element is the Tile this Unit will move to next. * * @type {Array.<Pirates.Tile>} */ get path() { return client.gameManager.getMemberValue(this, 'path'); } set path(value) { client.gameManager.setMemberValue(this, 'path', value); } /** * If a ship is on this Tile, how much health it has remaining. 0 for no ship. * * @type {number} */ get shipHealth() { return client.gameManager.getMemberValue(this, 'shipHealth'); } set shipHealth(value) { client.gameManager.setMemberValue(this, 'shipHealth', value); } /** * (Merchants only) The number of turns this merchant ship won't be able to move. They will still attack. Merchant ships are stunned when they're attacked. * * @type {number} */ get stunTurns() { return client.gameManager.getMemberValue(this, 'stunTurns'); } set stunTurns(value) { client.gameManager.setMemberValue(this, 'stunTurns', value); } /** * (Merchants only) The Port this Unit is moving to. * * @type {Pirates.Port} */ get targetPort() { return client.gameManager.getMemberValue(this, 'targetPort'); } set targetPort(value) { client.gameManager.setMemberValue(this, 'targetPort', value); } /** * The Tile this Unit is on. * * @type {Pirates.Tile} */ get tile() { return client.gameManager.getMemberValue(this, 'tile'); } set tile(value) { client.gameManager.setMemberValue(this, 'tile', value); } /** * Attacks either the 'crew' or 'ship' on a Tile in range. * * @param {Pirates.Tile} tile - The Tile to attack. * @param {string} target - Whether to attack 'crew' or 'ship'. Crew deal damage to crew and ships deal damage to ships. Consumes any remaining moves. * @returns {boolean} - True if successfully attacked, false otherwise. */ attack(tile, target) { return client.runOnServer(this, 'attack', { tile: tile, target: target, }); } /** * Buries gold on this Unit's Tile. Gold must be a certain distance away for it to get interest (Game.minInterestDistance). * * @param {number} amount - How much gold this Unit should bury. Amounts <= 0 will bury as much as possible. * @returns {boolean} - True if successfully buried, false otherwise. */ bury(amount) { return client.runOnServer(this, 'bury', { amount: amount, }); } /** * Puts gold into an adjacent Port. If that Port is the Player's port, the gold is added to that Player. If that Port is owned by merchants, it adds to that Port's investment. * * @param {number} [amount] - The amount of gold to deposit. Amounts <= 0 will deposit all the gold on this Unit. * @returns {boolean} - True if successfully deposited, false otherwise. */ deposit(amount) { if(arguments.length <= 0) { amount = 0; } return client.runOnServer(this, 'deposit', { amount: amount, }); } /** * Digs up gold on this Unit's Tile. * * @param {number} [amount] - How much gold this Unit should take. Amounts <= 0 will dig up as much as possible. * @returns {boolean} - True if successfully dug up, false otherwise. */ dig(amount) { if(arguments.length <= 0) { amount = 0; } return client.runOnServer(this, 'dig', { amount: amount, }); } /** * Moves this Unit from its current Tile to an adjacent Tile. If this Unit merges with another one, the other Unit will be destroyed and its tile will be set to null. Make sure to check that your Unit's tile is not null before doing things with it. * * @param {Pirates.Tile} tile - The Tile this Unit should move to. * @returns {boolean} - True if it moved, false otherwise. */ move(tile) { return client.runOnServer(this, 'move', { tile: tile, }); } /** * Regenerates this Unit's health. Must be used in range of a port. * * @returns {boolean} - True if successfully rested, false otherwise. */ rest() { return client.runOnServer(this, 'rest', { }); } /** * Moves a number of crew from this Unit to the given Tile. This will consume a move from those crew. * * @param {Pirates.Tile} tile - The Tile to move the crew to. * @param {number} [amount] - The number of crew to move onto that Tile. Amount <= 0 will move all the crew to that Tile. * @param {number} [gold] - The amount of gold the crew should take with them. Gold < 0 will move all the gold to that Tile. * @returns {boolean} - True if successfully split, false otherwise. */ split(tile, amount, gold) { if(arguments.length <= 1) { amount = 1; } if(arguments.length <= 2) { gold = 0; } return client.runOnServer(this, 'split', { tile: tile, amount: amount, gold: gold, }); } /** * Takes gold from the Player. You can only withdraw from your own Port. * * @param {number} [amount] - The amount of gold to withdraw. Amounts <= 0 will withdraw everything. * @returns {boolean} - True if successfully withdrawn, false otherwise. */ withdraw(amount) { if(arguments.length <= 0) { amount = 0; } return client.runOnServer(this, 'withdraw', { amount: amount, }); } //<<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // any additional functions you want to add to this class can be preserved here //<<-- /Creer-Merge: functions -->> }
JavaScript
class SlideOne extends React.Component { constructor(props){ super(props) this.props.setHeader() } getSlideImage = id => { switch(id){ case 1: return FalaUmSVG case 2: return FalaDoisSVG default: throw Error('Erro ao buscar slide desconhecido.') } } render() { return ( <ContentBox> <ImageSlide getSlide={this.getSlideImage} slideCount={SlideCount.CONSIDERACOES_FINAIS_DIALOG} /> <PrimaryText> <p>Neste curso vimos, através dos Micromundos, que o Pensamento Computacional está naturalmente presente em nossa prática diária, permeando o cotidiano, em variadas situações que podem ser exploradas em sala de aula, no contexto da BNCC.</p> <p>Reconhece-se hoje, internacionalmente, a importância das estratégias de raciocínio do Pensamento Computacional para a realidade do mundo atual. E as pesquisas apontam que essas estratégias deveriam ser desenvolvidas não só nos primeiros anos de escolaridade, capitalizando a naturalidade das crianças para essa forma de pensamento, mas ao longo de toda a vida escolar das crianças e jovens.</p> <p>Assim, este curso, voltado para os Anos Finais do Ensino Fundamental, insere-se no esforço de sensibilização e motivação dos professores para realizarem o trabalho com o Pensamento Computacional em sala de aula, embasado no uso dos quatro pilares, não necessariamente usando soluções prontas e acabadas, mas principalmente apontando caminhos para que o professor desenvolva os seus próprios recursos, ampliando o acervo pedagógico para o tema.</p> </PrimaryText> </ContentBox> ) } }
JavaScript
class ProjectNameForm extends Component { static propTypes = { onSubmit: PropTypes.func.isRequired, onBlur: PropTypes.func, ui: PropTypes.object, updateUI: PropTypes.func } componentDidMount() { this.refs.nameField.focus(); }; handleSubmit(e) { e.preventDefault(); this.props.onSubmit(this.props.ui.name); this.props.updateUI("name", ""); return false; }; render() { return ( <form onSubmit={this.handleSubmit.bind(this)} className="project-form"> <TextField ref="nameField" fullWidth={true} hintText="Project name" value={this.props.ui.name} onBlur={this.props.onBlur} onChange={(e) => {this.props.updateUI("name", e.target.value)}} /> </form> ); } }
JavaScript
class Exception { /** * @param {string} message * @param {string} code */ constructor(message = ErrorMessage.UNKNOWN, code = ErrorCodes.UNKNOWN) { // super(message) this.message = message; this.code = code; } }
JavaScript
class OptionType { /** Makes a new option type * * @param {string} name The name of the type, as displayed to the user if needed. * @param {function(*, *):boolean} validate The validation function, takes a potential new option value and an * argument set at register, and should return true iff it is a valid value for this option. * @param {function(*, *):*} cast The casting function, takes the same arguments as `validate` and should return * a value cast to the appropriate type for the option. * @since 0.0.21-alpha */ constructor(name, validate, cast) { this._validator = validate; this.name = name; this._cast = cast; } /** Returns true iff the given value is a valid value. * @param {*} value The value to check. * @param {*} arg A value stored when the option is registered. * @return {boolean} Whether this value is valid. */ validate(value, arg) { return this._validator(value, arg); } /** Converts the value to the correct type for this option. * @param {*} value The value to convert. * @param {*} arg A value stored when the option is registered. * @return {*} The appropriate value in its correct type. */ cast(value, arg) { return this._cast(value, arg); } toString() { return "[OptionType "+this.name+"]"; } }
JavaScript
class InstancePicker extends Component { constructor(props) { super(props); this.error = ''; this.instances = []; this.filter = ''; this.loadedMinTime = true; this.timeoutId = undefined; this.postLoadState = STATE_LOADING; this.state = { instances: {}, state: STATE_LOADING }; this.onInstancesReceived = this.onInstancesReceived.bind(this); this.onPlayerAdded = this.onPlayerAdded.bind(this); this.onPlayerRemoved = this.onPlayerRemoved.bind(this); this.onInstanceCreated = this.onInstanceCreated.bind(this); this.onInstanceRemoved = this.onInstanceRemoved.bind(this); this.filterList = this.filterList.bind(this); this.isFiltered = this.isFiltered.bind(this); this.pingAllInstances = this.pingAllInstances.bind(this); this.initList = this.initList.bind(this); this.onRetry = this.onRetry.bind(this); this.connectionTimedOut = this.connectionTimedOut.bind(this); } componentWillMount() { this.setState({ state: STATE_LOADING }); this.initList(); } componentWillUnmount() { clearInterval(this.pingLoop); } onRetry() { this.setState({ state: STATE_LOADING }); this.props.communication.getInstances(this); this.loadedMinTime = false; this.postLoadState = STATE_LOADING; // Timeout for minimum amount of loading time. setTimeout(() => { this.loadedMinTime = true; if (this.postLoadState !== STATE_LOADING) { this.setState({ state: this.postLoadState }); } }, TIME_MINLOADING); // Timeout for maximum amount of loading time. this.timeoutId = setTimeout(this.connectionTimedOut, TIME_TIMEOUT); } /* * Callback for when the RPC call returns the instances. */ onInstancesReceived(err, result) { if (this.timeoutId !== undefined) { clearTimeout(this.timeoutId); this.timeoutId = undefined; } if (!err) { this.instances = result; this.setState({ instances: result }); this.pingLoop = setInterval(this.pingAllInstances, 1000); this.postLoadState = STATE_OK; if (this.loadedMinTime) { this.setState({ state: STATE_OK }); } } else { if (err === deepstream.CONSTANTS.EVENT.NO_RPC_PROVIDER) { this.error = 'Service is not responding'; } else { this.error = err; } this.postLoadState = STATE_ERROR; if (this.loadedMinTime) { this.setState({ state: STATE_ERROR }); } } } /* * Increases the counter of the number of players active when a new * player connects. */ onPlayerAdded(playerName, instanceName) { if (this.instances[instanceName] === undefined) { return; } this.instances[instanceName].currentlyPlaying += 1; } /* * Decreases the counter of the number of players active when a * player disconnects. */ onPlayerRemoved(playerName, instanceName) { if (this.instances[instanceName] === undefined) { return; } this.instances[instanceName].currentlyPlaying -= 1; } /* * Adds the instance to the list when it is started. */ onInstanceCreated(instanceName, maxPlayers, gamemode, buttons) { const instance = { name: instanceName, currentlyPlaying: 0, maxPlayers, gamemode, buttons, }; if (!this.isFiltered(instanceName)) { const { instances } = this.state; instances[instanceName] = instance; this.setState({ instances }); } this.instances[instanceName] = instance; } /* * Remove the instance from the list when it is started. */ onInstanceRemoved(instanceName) { if (!this.isFiltered(instanceName)) { const { instances } = this.state; delete instances[instanceName]; this.setState({ instances }); } delete this.instances[instanceName]; } connectionTimedOut() { this.error = 'Connection timed out'; this.setState({ state: STATE_ERROR }); } pingAllInstances() { const { instances } = this.state; const keys = Object.keys(instances); const self = this; for (let i = 0; i < keys.length; i += 1) { const current = Date.now(); this.props.communication.pingInstance(keys[i], err => { const ping = Date.now() - current; if (err === deepstream.CONSTANTS.EVENT.NO_RPC_PROVIDER) { // No RPC provide -> instance is no longer up. self.onInstanceRemoved(keys[i]); return; } // If the instance went down in between sending the ping and receiving it // this would crash. This is a fail safe for that. if (instances[keys[i]] === undefined) { return; } instances[keys[i]].pingTime = ping; this.setState({ instances }); this.forceUpdate(); }); } } /** * Update the list of active instances */ initList() { this.loadedMinTime = true; this.postLoadState = STATE_OK; this.timeoutId = setTimeout(this.connectionTimedOut, TIME_TIMEOUT); this.props.communication.requestInstances(this); } isFiltered(instanceName) { return !instanceName.toLowerCase().includes(this.filter); } /* * This will filter the list with the given string. */ filterList(filter) { this.filter = filter.toLowerCase(); const stateInstances = {}; const keys = Object.keys(this.instances); for (let i = 0; i < keys.length; i += 1) { if (!this.isFiltered(keys[i])) { stateInstances[keys[i]] = this.instances[keys[i]]; } } this.setState({ instances: stateInstances }); } // Seems wrong to put this outside the class // eslint-disable-next-line renderLoading() { // #2196F3 -> md-blue-500 return ( <div className="instancesSpinner"> <MDSpinner singleColor="#2196F3" /> </div> ); } renderError() { return ( <div className="instancesError" onClick={this.onRetry} role="button" tabIndex={0}> {this.error} <br /> Press here to refresh &#x21bb; </div> ); } renderInstances() { if (Object.keys(this.state.instances).length === 0) { return <div className="instancesError">There are no instances running</div>; } return Object.keys(this.state.instances).map(instanceKey => ( <div key={instanceKey}> <InstanceItem instanceObj={this.state.instances[instanceKey]} instanceName={instanceKey} enterCharacterSelection={this.props.enterCharacterSelection} communication={this.props.communication} /> <Divider /> </div> )); } render() { return ( <div> <FilterInstances onInputChange={this.filterList} /> <Paper> <Grid className="md-grid instanceHeader"> <Cell className="md-cell--6"> <div className="cellCol--2-6">Instance Name</div> <div className="cellCol--2-6">Gamemode</div> <div className="cellCol--1-6">Players</div> <div className="cellCol--1-6">Latency</div> </Cell> </Grid> </Paper> <Paper> {(() => { switch (this.state.state) { case STATE_LOADING: return this.renderLoading(); case STATE_ERROR: return this.renderError(); case STATE_OK: return this.renderInstances(); default: return <div>Invalid state: {this.state.state}</div>; } })()} </Paper> </div> ); } }
JavaScript
class EventsApiService { constructor() { this.foundedEvent = ''; this.page = 1; this.country = ''; } fetchEvents() { const url = `${BASE_URL}/events.json?keyword=${this.foundedEvent}&countryCode=${this.country}&size=24&page=${this.page}&apikey=${KEY}`; return fetch(url) .then(r => r.json()) .then(data => { this.incrementPage(data.page.totalPages); console.log(data); if (data.hasOwnProperty("_embedded")) return data._embedded.events; }); } incrementPage(maxPages) { this.page < maxPages ? this.page += 1 : this.page = maxPages; } resetPage() { this.page = 1; } get event() { return this.foundedEvent; } set event(newEvent) { this.foundedEvent = newEvent; } set selectedCountry(newCountry) { this.country = newCountry; } }
JavaScript
class ItemFactory extends AbstractEntityFactory { static get $dependencies() { return []; } constructor() { super(ItemEntity); } }
JavaScript
class FirebaseContextContainer extends PureComponent { state = { firebase: null }; componentDidMount() { /** * Need to add a new Firebase feature or library? * Import and add it to the initialization promise here. */ const loadApp = import('firebase/app'); const loadAnalytics = import('firebase/analytics'); const loadAuth = import('firebase/auth'); const loadFirestore = import('firebase/firestore'); const loadRemoteConfig = import('firebase/remote-config'); Promise.all([ loadApp, loadAnalytics, loadAuth, loadFirestore, loadRemoteConfig ]).then((firebaseImports) => { const firebase = getFirebaseInstance(firebaseImports[0]); this.setState({ firebase }, () => { const remoteConfig = firebase.remoteConfig(); remoteConfig.defaultConfig = FirebaseConfig.remoteConfigDefaults; d(`Firebase Initialized (%s)`, !!firebase.apps.length); }); }); } render = () => { const { children } = this.props; const { firebase } = this.state; if (!firebase) { return null; } return ( <FirebaseContext.Provider value={firebase}> {children} </FirebaseContext.Provider> ); }; }
JavaScript
class Viewport { constructor(dira) { this.dira = dira this.dira.viewport = this this.applyOptions(dira.options) this.initRenderer() this.initTileManager() this._tick() } applyOptions(options) { this.options = options if (!options.pixelRatio) options.pixelRatio = window.devicePixelRatio } initRenderer() { this.el = this.options.rootElement this.el.style.fontSize = 0 this.el.style.margin = 0 this.el.style.padding = 0 this.stage = new Container() this.renderer = autoDetectRenderer({ width: this.width, height: this.height, resolution: this.options.pixelRatio, autoResize: true, antialias: true, }) if (this.options.pixelRatio > 1) { this.renderer.view.style.imageRendering = 'pixelated' this.resize() } this.el.appendChild(this.renderer.view) window.addEventListener('resize', this.resize.bind(this)) } initTileManager() { this.manager = new TileManager(this.dira) } get width() { return this.el.clientWidth } get height() { return this.el.clientHeight } resize(width, height) { if (!width || !height) { width = this.width height = this.height } this.renderer.view.style.width = `${width}px` this.renderer.view.style.height = `${height}px` this.renderer.resize(width, height) } _tick() { this.renderer.render(this.stage) requestAnimationFrame(this._tick.bind(this)) } }
JavaScript
class LoginComponent extends React.Component { constructor(props) { super(props); this.state = { isAuthenticated: props.isAuthenticated } this.authorize = props.authorize; this.unauthorize = props.unauthorize; } componentDidMount() { //original button would be mounted here // window.gapi.signin2.render( // GOOGLE_BUTTON_ID, { width: 200, height: 50 } // ); } /* * @description gather google profile data @param object googlUser */ onSuccess = (googlUser) => { let profile = googlUser.getBasicProfile(); console.log("Id", profile.getId()); console.log("Name", profile.getName()); console.log("Image url:", profile.getImageUrl()); console.log("Email", profile.getEmail()); } /* * @description makes the authentication process happen using the api keys @param */ signIn = () => { let auth = false; async function initGoogleAuthen(authorize, unauthorize, setState, props) { let additionalPermissions = function () { let auth2 = window.gapi.auth2.init( { apiKey: keys.apiKey, client_id: keys.client_id, cookiepolicy: 'single_host_origin', /** Default value **/ scope: 'profile' } ); let options = new gapi.auth2.SigninOptionsBuilder( { 'scope': 'https://www.googleapis.com/auth/contacts' }); let googleUser = auth2.currentUser.get(); googleUser.grant(options).then( function (success) { console.log(JSON.stringify({ message: "success", value: success })); auth = true; authorize(); props.history.push("/profile"); }, function (fail) { alert(JSON.stringify({ LoginFail: "fail to login, please login", reason: fail })); unauthorize(); } ) } await gapi.load('auth2', additionalPermissions) return auth; } initGoogleAuthen(this.authorize, this.unauthorize, this.setState, this.props).then((auth) => { }); } /* * @description signs out the google user @param */ signOut = () => { let auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { }); } render() { let { isAuthenticated } = this.state; let { signIn } = this; let props = this.props; return (<div className={"row"}> <div className={"column"} > <GoogleIconButton signIn={signIn}></GoogleIconButton> </div> <div id={GOOGLE_BUTTON_ID}></div> <Route render={ (props) => (isAuthenticated === true ? <Redirect push to="/contacts" /> : <Redirect to='/' /> )} /> </div> ) } }
JavaScript
class ErrorResponseHandler extends ResponseHandler { constructor(options) { super(Object.assign({ type: 'cli-error-response-handler' }, options)); } /** * Handler entry point. * Prints the message with a leading cross mark (❌) to console. */ call(onResult) { console.log(`❌ ${this.response.message}`); // eslint-disable-line no-console onResult(); } }
JavaScript
class CozyFolder extends CozyFile { /** * Create a folder with a reference to the given document * @param {String} path Folder path * @param {Object} document Document to make reference to. Any doctype. * @return {Object} Folder document */ static async createFolderWithReference(path, document) { const collection = this.cozyClient.collection(CozyFile.doctype) const dirId = await collection.ensureDirectoryExists(path) await collection.addReferencesTo(document, [ { _id: dirId } ]) const { data: dirInfos } = await collection.get(dirId) return dirInfos } /** * Returns a "Magic Folder", given its id * @param {String} id Magic Folder id. `CozyFolder.magicFolders` contains the * ids of folders that can be magic folders. * @param {String} path Default path to use if magic folder does not exist * @return {Object} Folder document */ static async ensureMagicFolder(id, path) { const magicFolderDocument = { _type: Application.doctype, _id: id } const folders = await this.getReferencedFolders(magicFolderDocument) const existingMagicFolder = folders.length ? folders[0] : null if (existingMagicFolder) return existingMagicFolder const magicFoldersValues = Object.values(this.magicFolders) if (!magicFoldersValues.includes(id)) { throw new Error( `Cannot create Magic folder with id ${id}. Allowed values are ${magicFoldersValues.join( ', ' )}.` ) } if (!path) { throw new Error('Magic folder default path must be defined') } return this.createFolderWithReference(path, magicFolderDocument) } /** * Returns an array of folder referenced by the given document * @param {Object} document Document to get references from * @return {Array} Array of folders referenced with the given * document */ static async getReferencedFolders(document) { const { included } = await this.cozyClient .collection(CozyFile.doctype) .findReferencedBy(document) return included.filter(folder => !this.isTrashed(folder)) } /** * Returns an unique folder referenced with the given reference. Creates it * if it does not exist. * @param {String} path Path used to create folder if the referenced * folder does not exist. * @param {Object} document Document to create references from * @return {Objet} Folder referenced with the give reference */ static async ensureFolderWithReference(path, document) { const existingFolders = await this.getReferencedFolders(document) if (existingFolders.length) return existingFolders[0] const collection = this.cozyClient.collection(CozyFile.doctype) const dirId = await collection.ensureDirectoryExists(path) await collection.addReferencesTo(document, [ { _id: dirId } ]) const { data: dirInfos } = await collection.get(dirId) return dirInfos } /** * Indicates if a folder is in trash * @param {Object} folder `io.cozy.files` document * @return {Boolean} `true` if the folder is in trash, `false` * otherwise. */ static isTrashed(folder) { return /^\/\.cozy_trash/.test(folder.attributes.path) } }
JavaScript
class DialogueNotifiers extends Component { static propTypes = { policiesAction: PropTypes.string.isRequired, policies: PropTypes.arrayOf(PropTypes.object).isRequired, selectedPolicyIds: PropTypes.arrayOf(PropTypes.string).isRequired, notifiers: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string.isRequired, id: PropTypes.string.isRequired, }) ).isRequired, selectedNotifiers: PropTypes.arrayOf(PropTypes.string), setPolicyNotifiers: PropTypes.func.isRequired, }; static defaultProps = { selectedNotifiers: [], }; toggleRow = (id) => { const { selectedNotifiers } = this.props; if (selectedNotifiers.indexOf(id) > -1) { this.props.setPolicyNotifiers( selectedNotifiers.filter((notifierId) => notifierId !== id) ); } else if (selectedNotifiers.length === 0) { this.props.setPolicyNotifiers([id]); } else { this.props.setPolicyNotifiers(selectedNotifiers.concat([id])); } }; toggleSelectAll = () => { const { notifiers, selectedNotifiers } = this.props; if (notifiers.length > selectedNotifiers.length) { this.props.setPolicyNotifiers(notifiers.map((notifier) => notifier.id)); } else { this.props.setPolicyNotifiers([]); } }; selectedPolicyNotifiers = () => { const { notifiers } = this.props; if (this.props.policiesAction === policyBulkActions.enableNotification) { return notifiers; } const policyNotifiers = uniq( this.props.policies .filter( (policy) => this.props.selectedPolicyIds.find((id) => id === policy.id) && policy.notifiers.length > 0 ) .flatMap((policy) => policy.notifiers) ); return notifiers.filter((notifier) => policyNotifiers.find((o) => o === notifier.id)); }; render() { const notifiers = this.selectedPolicyNotifiers(); if (notifiers.length < 1) { return null; } if (notifiers.length === 1) { return ( <div className="p-4 border-b border-base-300 bg-base-100 text-base-900"> Selected Notifier: {notifiers[0].name} </div> ); } const columns = [ { accessor: 'name', Header: 'Select Notifiers', }, ]; const { selectedNotifiers } = this.props; return ( <div> <CheckboxTable rows={notifiers} columns={columns} selection={selectedNotifiers} toggleRow={this.toggleRow} toggleSelectAll={this.toggleSelectAll} /> </div> ); } }
JavaScript
class Note extends XmlObject { /** * Create a note from an XML node * @param {NodeObject} node - the XML Node representing the note * @param {Number} divisions - The divisions entry from the measure node */ constructor(node, attributes) { super(node); if (node.tagName !== 'note') { throw new MusicXmlError('ne_001', 'Wrong XML type inserted into Note class!'); } /** * Private property to store attributes before this note * @prop {Number} Note.mAttributes */ this.mAttributes = attributes; this.lastNote = { Clef: {}, mAttributes: {}, }; /** * Private property to store measures divions units * @prop {Number} Note.mDivisions */ this.mDivisions = attributes.Divisions; /** * Shows if this note is a rest * @prop {Boolean} Note.isRest */ this.isRest = this.childExists('rest'); /** * Shows if this note is part of a chord * @prop {Boolean} Note.isInChord */ this.isInChord = this.childExists('chord'); /** * Shows if this Note is before a backup element or the last in the measure * @prop {Boolean} Note.isLast */ this.isLast = this.Node.nextElementSibling === null || this.Node.nextElementSibling === undefined || this.Node.nextElementSibling.tagName === 'backup'; /** * The note's staff number * @prop {Number} Note.Staff */ const tStaff = this.getNum('staff'); this.Staff = Number.isNaN(tStaff) ? 1 : tStaff; /** * The duration of the note * @prop {Number} Note.Duration */ this.Duration = this.getNum('duration'); /** * The notes type of representation (8th, whole, ...) * @prop {String} Note.Type */ this.Type = this.getText('type'); /** * The notes stem direction (up, down) * @prop {String} Note.Stem */ this.Stem = this.getText('stem'); /** * The notes beam state. It indicates if a beam starts or ends here * @prop {Array} Note.Beam is an array of beams. They can be 'begin', 'end', * 'continue' or 'none' */ // FIXME: Description doesn't match implementation this.BeamState = this.getTextArray('beam').indexOf('begin') > -1 || this.getTextArray('beam').indexOf('continue') > -1 || this.getTextArray('beam').indexOf('end') > -1; /** * Indicates if this is the last not in a beam. * @prop {Boolean} Note.isLastBeamNote is an boolean that indicates the last * not in a beam */ this.isLastBeamNote = this.getTextArray('beam').every(b => b.indexOf('end') > -1); /** * Percussion notes don't have absolute values and are called "unpitched" * @param {Boolean} Note.isUnpitched defines if note is a percussion note */ this.isUnpitched = this.childExists('unpitched'); /** * The note's length. It is defined by the duration divided by the divisions * in this measure. * @param {Number} Note.NoteLength defines the note's length */ this.NoteLength = this.Duration / this.mDivisions; this.Dots = this.NoteLength >= 1 && this.NoteLength % 1 === 0.5; } /** * The note's voice number * @returns {Number} voice Number of the voice */ get Voice() { const voice = this.getNum('voice'); return Number.isNaN(voice) ? 1 : voice; } /** * The notes pitch. It is defined by a step and the octave. * @prop {Object} .Step: Step inside octave * .Octave: Octave of the note */ get Pitch() { const stepName = this.isUnpitched ? 'display-step' : 'step'; const octaveName = this.isUnpitched ? 'display-octave' : 'octave'; return { Step: this.childExists(stepName) ? this.getText(stepName) : undefined, Octave: this.getNum(octaveName), }; } get Notation() { return this.childExists('notations') ? new Notation(this.getChild('notations')) : null; } get IsLastSlur() { let res = false; if (this.Notation && this.Notation.Slur) { res = this.Notation.Slur.type === 'stop'; } return res; } get Accidental() { return this.getText('accidental'); } get Clef() { return this.mAttributes.Clef.filter(c => c.Number === this.Staff)[0]; } get hasClefChange() { return JSON.stringify(this.Clef) !== JSON.stringify(this.lastNote.Clef); } }
JavaScript
class DrgAttachment extends OkitArtifact { /* ** Create */ constructor (data={}, okitjson={}) { super(okitjson); // Configure default values this.display_name = this.generateDefaultName(okitjson.drg_attachments.length + 1); this.compartment_id = data.compartment_id; this.drg_id = ''; this.drg_route_table_id = ''; this.network_details = { id: '', type: 'VCN', route_table_id: '' } // Update with any passed data this.merge(data); this.convert(); // Expose vcn_id at the top level delete this.vcn_id; Object.defineProperty(this, 'vcn_id', {get: function() {return this.network_details.id;}, set: function(id) {this.network_details.id = id;}, enumerable: true }); // Expose route_table_id at the top level delete this.route_table_id; Object.defineProperty(this, 'route_table_id', {get: function() {return this.network_details.route_table_id;}, set: function(id) {this.network_details.route_table_id = id;}, enumerable: true }); } /* ** Clone Functionality */ clone() { return new DrgAttachment(JSON.clone(this), this.getOkitJson()); } /* ** Name Generation */ getNamePrefix() { return super.getNamePrefix() + 'da'; } /* ** Static Functionality */ static getArtifactReference() { return 'Drg Attachment'; } }
JavaScript
class MDCIconToggleAdapter { /** @param {string} className */ addClass(className) {} /** @param {string} className */ removeClass(className) {} /** * @param {string} type * @param {!EventListener} handler */ registerInteractionHandler(type, handler) {} /** * @param {string} type * @param {!EventListener} handler */ deregisterInteractionHandler(type, handler) {} /** @param {string} text */ setText(text) {} /** @return {number} */ getTabIndex() {} /** @param {number} tabIndex */ setTabIndex(tabIndex) {} /** * @param {string} name * @return {string} */ getAttr(name) {} /** * @param {string} name * @param {string} value */ setAttr(name, value) {} /** @param {string} name */ rmAttr(name) {} /** @param {!IconToggleEvent} evtData */ notifyChange(evtData) {} }
JavaScript
class VisibleTodoList extends Component { componentDidMount() { this.fetchData(); } componentDidUpdate(prevProps) { const { filter } = this.props; if (prevProps.filter !== filter) { this.fetchData(); } } fetchData = () => { const { filter, fetchTodos } = this.props; fetchTodos(filter); }; render() { const { isFetching, errorMessage, todos, onTodoClick } = this.props; // show loading only when there is no cached todos to show if (isFetching && !todos.length) { return ( <Box display="flex" justifyContent="center"> <CircularProgress /> </Box> ); } if (errorMessage && !todos.length) { return <FetchError message={errorMessage} onRetry={() => this.fetchData()} />; } return <TodoList todos={todos} onTodoClick={onTodoClick} />; } }
JavaScript
class QuickOpenHandlerDescriptor { constructor(ctor, id, prefix, contextKey, param, instantProgress = false) { this.ctor = ctor; this.id = id; this.prefix = prefix; this.contextKey = contextKey; this.instantProgress = instantProgress; if (types_1.isString(param)) { this.description = param; } else { this.helpEntries = param; } } getId() { return this.id; } instantiate(instantiationService) { return instantiationService.createInstance(this.ctor); } }
JavaScript
class EditorQuickOpenEntry extends quickOpenModel_1.QuickOpenEntry { constructor(_editorService) { super(); this._editorService = _editorService; } get editorService() { return this._editorService; } getInput() { return undefined; } getOptions() { return undefined; } run(mode, context) { const hideWidget = (mode === 1 /* OPEN */); if (mode === 1 /* OPEN */ || mode === 2 /* OPEN_IN_BACKGROUND */) { const sideBySide = context.keymods.ctrlCmd; let openOptions; if (mode === 2 /* OPEN_IN_BACKGROUND */) { openOptions = { pinned: true, preserveFocus: true }; } else if (context.keymods.alt) { openOptions = { pinned: true }; } const input = this.getInput(); if (input instanceof editor_1.EditorInput) { let opts = this.getOptions(); if (opts) { opts = objects_1.mixin(opts, openOptions, true); } else if (openOptions) { opts = editor_1.EditorOptions.create(openOptions); } this.editorService.openEditor(input, types_1.withNullAsUndefined(opts), sideBySide ? editorService_1.SIDE_GROUP : editorService_1.ACTIVE_GROUP); } else { const resourceInput = input; if (openOptions) { resourceInput.options = objects_1.assign(resourceInput.options || Object.create(null), openOptions); } this.editorService.openEditor(resourceInput, sideBySide ? editorService_1.SIDE_GROUP : editorService_1.ACTIVE_GROUP); } } return hideWidget; } }
JavaScript
class EditorQuickOpenEntryGroup extends quickOpenModel_1.QuickOpenEntryGroup { getInput() { return undefined; } getOptions() { return undefined; } }
JavaScript
class Popover extends Component { /** * Upgrades all Popover AUI components. * @returns {Array} Returns an array of all newly upgraded components. */ static upgradeElements() { let components = []; Array.from(document.querySelectorAll(SELECTOR_COMPONENT)).forEach(element => { if (!Component.isElementUpgraded(element)) { components.push(new Popover(element)); } }); return components; }; /** * Initialize component */ init() { super.init(); this._body = document.querySelector('body'); this._id = this._element.getAttribute('id'); this._trigger = document.getElementById(this._element.getAttribute('for')); this._tether = null; const placement = this._element.hasAttribute('data-placement') ? this._element.getAttribute('data-placement') : 'top'; this._attachement = AttachmentMap[placement.toLowerCase()]; const content = this._element.querySelector('.aui-popover__content'); const arrowColor = this._element.hasAttribute('data-arrow-color') ? this._element.getAttribute('data-arrow-color') : window.getComputedStyle(content).backgroundColor; this._arrow = this._addArrow(content, arrowColor); if (this._trigger) { this._trigger.addEventListener('click', this._boundClickHandler = (event) => this.toggle(event)); } } /** * Dispose component */ dispose() { super.dispose(); this.hide(); this.removeChild(this._arrow); if (this._trigger) { this._trigger.removeEventListener('click', this._boundClickHandler); } } /** * Toggle show/hide Popover * @param {Event} event Click event of trigger element (optional) */ toggle(event) { const performToggle = () => { if (!this._element.classList.contains(CLASS_ACTIVE) && this._tether) { this.show(); } else { this.hide(); } }; if (event) { event.preventDefault(); if (this._tether === null) { this._tether = new Tether({ element: this._element, target: event.currentTarget, attachment: this._attachement, classPrefix: 'aui-tether', // NOTE We set an offset in CSS, because this offset wouln't be // flipped as it should: // https://github.com/HubSpot/tether/issues/106 offset: '0 0', constraints: [{ to: 'window', pin: ['left', 'right'], attachment: 'together' }], optimizations: { gpu: false } }); reflow(this._element); // REVIEW Do we need this anymore? this._tether.position(); } performToggle(); } else { performToggle(); } } /** * Show Popover */ show() { this._body.classList.add(CLASS_POPOVER_IS_OPEN); this._element.classList.add(CLASS_ACTIVE); this._element.classList.add(CLASS_SHOWN); setTimeout(() => { window.addEventListener('click', this._boundWindowClickHandler = (event) => this._onClickOutside(event)); }) } /** * Hide Popover */ hide() { this._element.classList.remove(CLASS_SHOWN); this._element.addEventListener(transitionend, this._boundAnimationendHandler = (event) => this._onHideComplete(event)); window.removeEventListener('click', this._boundWindowClickHandler); } /** * Clean up Tether instance * @private */ _cleanupTether() { if (this._tether) { this._tether.destroy(); this._tether = null; } this._element.removeAttribute('style'); } /** * Handle click of window. * @param {Event} event The event that fired. * @private */ _onClickOutside(event) { // Hide if target dismisses Popover if (closest(event.target, SELECTOR_DISMISS, this._element)) { this.hide(); // Hide if target is not inside Popover and is not a trigger element } else if (!this._element.contains(event.target) && event.target !== this._trigger) { this.hide(); } } /** * Handle hide transition complete. * @param {Event} event The event that fired. * @private */ _onHideComplete(event) { this._body.classList.remove(CLASS_POPOVER_IS_OPEN); this._element.classList.remove(CLASS_ACTIVE); this._element.removeEventListener(transitionend, this._boundAnimationendHandler); this._cleanupTether(); } /** * Adds an arrow SVG element * <span class="…"><svg … ><path … /></svg></span> * * @param {HTMLElement} parent element to append arrow to. * @param {string} color used as value of fill property. * @returns {HTMLElement} the added arrow element. */ _addArrow(parent, color) { const element = document.createElement('span'); element.classList.add(CLASS_ARROW); const svg = this.createSvgNode('svg', { class: CLASS_ARROW_SHAPE, width: ARROW_SIZE, height: ARROW_SIZE, viewBox: `0 0 ${ARROW_SIZE} ${ARROW_SIZE}` }); // Draw a diamond square ◆ const path = this.createSvgNode('path', { d: `M${ARROW_SIZE / 2} 0 L ${ARROW_SIZE} ${ARROW_SIZE / 2} L ${ARROW_SIZE / 2} ${ARROW_SIZE} L 0 ${ARROW_SIZE / 2} Z`, fill: color }); svg.appendChild(path); element.appendChild(svg); parent.appendChild(element); return element; } }
JavaScript
class UIState { constructor() { /** * @type {boolean} */ this.allOk = false; /** * The RegExp used to select the currently rendered entries. * @type {?RegExp} */ this.exploreSearchRegex = null; /** * The selected (not starred) test entry element. * @type {?TestEntry} */ this.selectedTestEntry = null; /** * @type {HTMLDivElement} */ this.explorerView = /** @type {HTMLDivElement} */ ( utils.querySelector('#entries_explorer_view')); if (this.explorerView.children.length !== 0) { throw new Error('#entries_explorer_view should hold 0 child on startup.') } this.explorerView.addEventListener('scroll', () => { utils.clearSingletonTooltip(); }); /** * @type {HTMLDivElement} */ this.iconsView = /** @type {HTMLDivElement} */ ( utils.querySelector('#entries_peek_icons_view')); if (this.iconsView.children.length !== 0) { throw new Error( '#entries_peek_icons_view should hold 0 child on startup.') } this.iconsView.addEventListener('scroll', () => { utils.clearSingletonTooltip(); }); /** * @type {HTMLInputElement} */ this.searchBar = /** @type {HTMLInputElement} */ ( utils.querySelector('input#entries_search_bar')); if (!this.searchBar) { throw new Error('unable to find the search bar.') } /** * @type {HTMLInputElement} */ this.showSuccessCheckbox = /** @type {HTMLInputElement} */ (utils.querySelector( 'input#view_control_visibility_checkbox_successes')); if (!this.showSuccessCheckbox) { throw new Error('unable to find the checkbox that show successes.'); } /** * @type {HTMLInputElement} */ this.showErrorCheckbox = /** @type {HTMLInputElement} */ ( utils.querySelector('input#view_control_visibility_checkbox_errors')); if (!this.showErrorCheckbox) { throw new Error('unable to find the checkbox that show errors.'); } /** * @type {IntersectionObserver} */ this.explorerViewportObserver = new IntersectionObserver( this.handleExplorerViewIntersection_.bind(this), { root: this.explorerView, // The viewport element of the observed rootMargin: '1%', // Grow the root bounding box by 1% threshold: 0 // Visible amount of item shown in relation to root }); } /** * @param {!PeekIcon} icon * @return {!TestEntry} */ findTestEntry(icon) { const testIndex = icon.getAttribute(PeekIconAttribute.INDEX); // string const entry = utils.querySelector( `test-entry[${TestEntryAttribute.INDEX}='${testIndex}']`, this.explorerView); if (!entry) { throw new Error(`unable to find a test entry with index ${testIndex}`); } return /** @type {!TestEntry} */ (entry); } /** * @param {!TestEntry} entry * @return {!PeekIcon} */ findPeekIcon(entry) { const testIndex = entry.getAttribute(TestEntryAttribute.INDEX); // string const peekIcon = utils.querySelector( `peek-icon[${PeekIconAttribute.INDEX}='${testIndex}']`, this.iconsView); if (!peekIcon) { throw new Error(`unable to find a peek icon with index ${testIndex}`); } return /** @type {!PeekIcon} */ (peekIcon); } unsetSelectedEntry() { if (!this.selectedTestEntry) { return; } this.findPeekIcon(this.selectedTestEntry) .removeAttribute(PeekIconAttribute.SELECTED); this.selectedTestEntry.removeAttribute(TestEntryAttribute.SELECTED); this.selectedTestEntry = null; } /** * @param {!TestEntry} entry */ setSelectedEntry(entry) { if (this.selectedTestEntry) { throw new Error( 'you should explicitly unset a selected entry before setting a new one.') } this.findPeekIcon(entry).setAttribute(PeekIconAttribute.SELECTED, ''); entry.setAttribute(TestEntryAttribute.SELECTED, ''); this.selectedTestEntry = entry; } /** * @param {!Array<!IntersectionObserverEntry>} intersectedEntries */ handleExplorerViewIntersection_(intersectedEntries) { intersectedEntries.forEach((intersectedEntry) => { const entry = /** @type {!TestEntry} */ (intersectedEntry.target); const peekIcon = this.findPeekIcon(entry); if (intersectedEntry.isIntersecting) { entry.setAttribute(TestEntryAttribute.IN_VIEW, ''); peekIcon.setAttribute(PeekIconAttribute.ENTRY_IN_VIEW, ''); } else { entry.removeAttribute(TestEntryAttribute.IN_VIEW); peekIcon.removeAttribute(PeekIconAttribute.ENTRY_IN_VIEW); } }); } }
JavaScript
class DataState { constructor() { /** * Sorted test ID strings from dataStorage data. * @type {!Array<string>} */ this.testIds = []; } }
JavaScript
class Footer extends BaElement { constructor() { super(); const { EnvironmentService } = $injector.inject('EnvironmentService'); this._environmentService = EnvironmentService; } onWindowLoad() { if (!this.isRenderingSkipped()) { this._root.querySelector('.preload').classList.remove('preload'); } } isRenderingSkipped() { return this._environmentService.isEmbedded(); } createView(state) { const { open, portrait, minWidth } = state; const getOverlayClass = () => { return (open && !portrait) ? 'is-open' : ''; }; const getOrientationClass = () => { return portrait ? 'is-portrait' : 'is-landscape'; }; const getMinWidthClass = () => { return minWidth ? 'is-desktop' : 'is-tablet'; }; return html` <style>${css}</style> <div class="preload"> <div class="${getOrientationClass()} ${getMinWidthClass()}"> <div class="footer ${getOverlayClass()}"> <div class="scale"></div> <ba-attribution-info></ba-attribution-info> <div class="content"> ${this.createChildrenView()} </div> </div> </div> </div> `; } createChildrenView() { return html` <ba-map-info></ba-map-info> `; } /** * @override * @param {Object} globalState */ extractState(globalState) { const { mainMenu: { open }, media: { portrait, minWidth } } = globalState; return { open, portrait, minWidth }; } static get tag() { return 'ba-footer'; } }
JavaScript
class NotificationUser extends Model { /** * get ViewModel class bind with Model * @return {ViewModel} - ViewModel class */ getViewModel() { return require('../vm/NotificationUser'); } }
JavaScript
class CoverImageUI { constructor() { } static getImageTableElement() { return document.getElementById("imagesTable"); } /** return URL of image to use for cover, or NULL if no cover */ static getCoverImageUrl() { let url = CoverImageUI.getCoverImageUrlInput().value; return util.isNullOrEmpty(url) ? null : url; } /** toggle visibility of the Cover Image URL input control * @param {bool} visible - show/hide control */ static showCoverImageUrlInput(visible) { document.getElementById("coverUrlSection").hidden = !visible; document.getElementById("imagesTableDiv").hidden = visible; } /** clear all UI elements associated with selecting the Cover Image */ static clearUI() { CoverImageUI.clearImageTable(); CoverImageUI.setCoverImageUrl(null); } /** remove all images from the table of images to pick from */ static clearImageTable() { let imagesTable = CoverImageUI.getImageTableElement(); while (imagesTable.children.length > 0) { imagesTable.removeChild(imagesTable.children[imagesTable.children.length - 1]) } } /** create table of images for user to pick from * @param {array of ImageInfo} images to populate table with */ static populateImageTable(images) { CoverImageUI.clearImageTable(); let imagesTable = CoverImageUI.getImageTableElement(); let checkBoxIndex = 0; if (0 === images.length) { imagesTable.parentElement.appendChild(document.createTextNode(chrome.i18n.getMessage("noImagesFoundLabel"))); } else { images.forEach(function (imageInfo) { let row = document.createElement("tr"); // add checkbox let checkbox = CoverImageUI.createCheckBoxAndLabel(imageInfo.sourceUrl, checkBoxIndex); CoverImageUI.appendColumnToRow(row, checkbox); // add image let img = document.createElement("img"); img.setAttribute("style", "max-height: 120px; width: auto; "); img.src = imageInfo.sourceUrl; CoverImageUI.appendColumnToRow(row, img); imagesTable.appendChild(row); ++checkBoxIndex; }); } } /** adds row to the images table * @private */ static createCheckBoxAndLabel(sourceUrl, checkBoxIndex) { let label = document.createElement("label"); let checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.id = "setCoverCheckBox" + checkBoxIndex; checkbox.onclick = function() { CoverImageUI.onImageClicked(checkbox.id, sourceUrl); }; label.appendChild(checkbox); label.appendChild(document.createTextNode(chrome.i18n.getMessage("setCover"))); // default to first image as cover image if (checkBoxIndex === 0) { CoverImageUI.setCoverImageUrl(sourceUrl); checkbox.checked = true; } return label; } /** user has selected/unselected an image for cover * @private */ static onImageClicked(checkboxId, sourceUrl) { let checkbox = document.getElementById(checkboxId); if (checkbox.checked === true) { CoverImageUI.setCoverImageUrl(sourceUrl); // uncheck any other checked boxes let imagesTable = CoverImageUI.getImageTableElement(); for(let box of imagesTable.querySelectorAll("input")) { if (box.id !== checkboxId) { box.checked = false; } } } else { CoverImageUI.setCoverImageUrl(null); } } /** * @private */ static appendColumnToRow(row, element) { let col = document.createElement("td"); col.appendChild(element); col.style.whiteSpace = "nowrap"; row.appendChild(col); return col; } /** * @private * @todo this should be moved to Baka-Tsuki, this logic is specific to B-T */ static onCoverFromUrlClick(enable, images) { if (enable) { CoverImageUI.setCoverImageUrl(null); CoverImageUI.clearImageTable(); CoverImageUI.showCoverImageUrlInput(true); } else { CoverImageUI.showCoverImageUrlInput(false); CoverImageUI.populateImageTable(images); } } /** user has selected/unselected an image for cover * @private */ static getCoverImageUrlInput() { return document.getElementById("coverImageUrlInput"); } /** set URL of image to use for cover, or NULL if no cover * @public */ static setCoverImageUrl(url) { CoverImageUI.getCoverImageUrlInput().value = url; } }
JavaScript
class BasicAuthenticator { /** * Create new service instance. Used only by the provider. * * @param {Runtime} runtime Application runtime. * @param {string} realm The authentication realm. */ constructor(runtime, realm) { this._challenge = 'Basic realm="' + realm + '", charset="UTF-8"'; this._actorRegistry = runtime.service('actorRegistry'); if (typeof this._actorRegistry.validCredentials !== 'function') throw new Error( 'Actor registry service does not provide validCredentials()' + ' method required by the Basic authenticator.'); this._actorRegistryCache = runtime.service('actorRegistryCache'); } /* * Perform authentication. */ authenticate(httpRequest, requestUrl) { // get and parse the authorization header const authHeader = httpRequest.headers['authorization']; const data = ( authHeader && /^\s*basic\s+([0-9a-z+/]+={0,2})\s*$/i.exec(authHeader)); if (!data) return Promise.resolve({ actor: null, challenge: this._challenge }); // decode the authorization header const dataPlain = (new Buffer(data[1], 'base64')).toString('utf8'); const colInd = dataPlain.indexOf(':'); if ((colInd <= 0) || (colInd >= dataPlain.length - 1)) return Promise.resolve({ actor: null, challenge: this._challenge }); // create incomplete authentication result object const authResult = { actorId: dataPlain.substring(0, colInd), credentials: dataPlain.substring(colInd + 1) }; // perform lookup and return result promise return new Promise((resolve, reject) => { this._actorRegistryCache.lookup(authResult).then( actor => { authResult.actor = actor; if (actor === null) { authResult.challenge = this._challenge; } else if (!this._actorRegistry.validCredentials( actor, authResult)) { authResult.actor = null; authResult.challenge = this._challenge; } resolve(authResult); }, err => { if (err.code === 'server_error') return reject(err); authResult.actor = null; authResult.challenge = this._challenge; resolve(authResult); } ); }); } /** * Does nothing. */ addResponseAuthInfo(response, actor, requestUrl, httpRequestHeaders) { // nothing } }
JavaScript
class Logger extends EventEmitter { log(msg) { //Call event this.emit('message', { id: uuid.v4(), msg:msg }); } }
JavaScript
class ScopedActionFactory { constructor(actionCreators) { this._creators = actionCreators; } scope(id) { return scopeActionCreators(this._creators, id); } }
JavaScript
class Chapter{ /** * Creates a Chapter instance. * @constructor * @param {HTMLElement} post - the root element of a WordPress post; usually <article> */ constructor(post) { /** @private @readonly */ this._post = post; /** @private */ this._title = post.getElementsByTagName("h1")[0].innerText; /** @private */ this._fileName = Chapter.madokamiFileName(this, GROUPNAME, SOURCE.UNKNOWN); /** @private */ this._images = this.getImages(this._post); } get post() { return this._post; } set post(value) { // read only } get title() { return this._title; } set title(value) { this._title = value; } get fileName() { return this._fileName; } set fileName(fName) { this._fileName = fName; } get images() { return this._images; } set images(post) { this._images = this.getImages(post); } /** * Estimates a filename compatible with the Madokami Naming Scheme based on the * chapter title. * @see {@link https://github.com/Daiz/manga-naming-scheme} for more info. * * @method Chapter.madokamiFileName * @static * @param {Chapter} chapter - a Chapter object to base the filename on * @param {String} chapter.title - the title of the chapter * * @param {String} groupName - the name of the scanlation group to use in the filename * @param {SOURCE.Enum} source - the source of the scanlation can be either (mag|mix|v|web) * * @returns {String} the estimated madokami filename; Still needs to be adjusted slightly */ static madokamiFileName(chapter, groupName=GROUPNAME, source=SOURCE.UNKNOWN){ let chapterInfo = chapter.title.split(/(^.*?)\s?((volume|v)\s?\d{1,2})?\s?((chapter|ch|c)?\s?\d{1,}-?\d{1,})/gi); chapterInfo = chapterInfo.splice(1, chapterInfo.length - 2); let seriesTitle = chapterInfo[0]; let chapterNo = (chapterInfo[3]) ? chapterInfo[3].replace(/(chapter|ch|c)\s?/i, "").padStart(3, "0") : ""; let sourceStr = null; // Deterimine source. switch(source) { case SOURCE.MAGAZINE: sourceStr = "(mag) "; break; case SOURCE.MIX: sourceStr = "(mix) "; break; case SOURCE.VOLUME: // Check if volumeNo was found in ChapterInfo sourceStr = chapterInfo[1] ? chapterInfo[1].replace(/(volume|vol|v)\s?/i, "").padStart(2,"0") : ""; sourceStr = (sourceStr !== "") ? `(v${sourceStr}) ` : ""; // output: "(v??) " break; case SOURCE.WEB: sourceStr = "(web) "; break; case SOURCE.UNKNOWN: sourceStr = "(unk) "; break; default: sourceStr = "(unk) "; } // Example output: "Giant Killing - c001 (v01) [GROUPNAME]" let madokamiStr = `${seriesTitle} - c${chapterNo} ${sourceStr}[${groupName}]`; return madokamiStr; } /** * Extracts all images from a WordPress gallery. * * @method Chapter#getImages * @param {HTMLElement} post - root element of a WordPress post containing a gallery * * @returns {?Array.<Object>} - returns an array of Objects or null. */ getImages(post) { if ( post.classList.contains("post_format-post-format-gallery") || post.getElementsByClassName("tiled-gallery").length > 0) { let images = []; let imgElements = Array.from(post.getElementsByTagName("img")); for (let img of imgElements) { let chapImg = {}; chapImg.url = img.dataset.origFile.split('?')[0]; // remove any width parameters chapImg.fileName = `${img.dataset.imageTitle}.${chapImg.url.match(/\.(\w{3,4})(?:($|\?))/)[1]}`; images.push(chapImg); } return images; } else { return null; } } /** * Fetch an image by url and turn it into a Blob object. * Uses http://cors-anywhere.herokuapp.com as a porxy because of Same-Origin * issues * * @method Chapter.getImageBlob * @static * @param {String} url - the url the image resides at. * @return {Blob} a Blob object of the fetched image data. * */ static getImageBlob(url){ const proxy = "https://cors-anywhere.herokuapp.com"; return fetch(`${proxy}/${url}`).then((response) => { return response.blob(); }); } }
JavaScript
class BackgroundScene extends Scene { /** * Create a new BackgroundScene with the specified options. * @param {object} options The options for the BackgroundScene, composed of the properties. * @property {integer} offsetX The offset x-coordinate in the asset in pixels (optional, default 0) * @property {integer} offsetY The offset y-coordinate in the asset in pixels (optional, default 0) * @property {integer} width The width in pixels (optional, default asset width) * @property {integer} height The height in pixels (optional, default asset height) */ constructor (options = {}) { super(options) this.offsetX = options.offsetX || 0 this.offsetY = options.offsetY || 0 this.width = options.width this.height = options.height if (typeof (this.width) === 'undefined' && this.asset) this.width = this.asset.element.width if (typeof (this.height) === 'undefined' && this.asset) this.height = this.asset.element.height } /** * Draw the BackgroundScene into the given context. * @param {CanvasRenderingContext2D} context The context in which to draw */ draw (context) { // If we're not marked for a redraw or we're invisible, return if (!this._doredraw || !this.visible) return // Save the context params context.save() // Reset the origin to our coordinates (so child entities are relative to us) context.translate(this.x, this.y) context.scale(this.scale, this.scale) context.rotate(this.rotate) // Ensure Scene sort order if (!this._sceneOrderMap) this.sortScenesZ() // Draw Background Image context.drawImage( this.asset.element, this.offsetX, this.offsetY, this.width, this.height, 0, 0, this.width, this.height ) // Now the Entities for this layer this.drawEntities(context) // Next draw any subscenes for this layer this.drawScenes(context) // Restore the context params for the next thing being drawn context.restore() // Reset the redraw flag this._doredraw = false } }
JavaScript
class Table extends Component { constructor(props) { super(props); this.state = { table_number: '1', loading: true, show_message: false, message: 'Error', header: 'Error!', table_name: 'Table 1', seat_states: [ {}, { taken: false, name: '' }, { taken: false, name: '' }, { taken: false, name: '' }, { taken: false, name: '' }, { taken: false, name: '' }, { taken: false, name: '' }, { taken: false, name: '' }, { taken: false, name: '' }, { taken: false, name: '' }, { taken: false, name: '' } ] }; } /** * Render the apps UI */ render() { return ( <div style={styles.root}> <Grid columns="equal"> <Grid.Column computer={8} mobile={16}> <Image src={require('../plan.jpeg')} style={styles.image} fluid /> </Grid.Column> <Grid.Column computer={8} mobile={16}> <Grid> <Grid.Row> <div style={styles.svg_wrapper}> {this.getSVG()} </div> </Grid.Row> <Grid.Row> <Loader size="large" active={this.state.loading} inline="centered" /> </Grid.Row> <Grid.Row> <Form style={styles.form}> <br /> <div style={styles.instructions}> Pick a table, check its occupancy, then pick a seat </div> <br /> {this.getMessage()} <Form.Input type="number" required name="table_number" onChange={this.handleInput} label="Table number" > <input placeholder="Enter table number" /> </Form.Input> <Button onClick={this.handleClickCheck}> Check </Button> <br /> <br /> <Form.Input type="number" name="seat_number" required onChange={this.handleInput} label="Seat number" > <input placeholder="Enter seat number" /> </Form.Input> <Form.Input type="email" name="email_address" required onChange={this.handleInput} label="Email address" > <input placeholder="Enter email address" /> </Form.Input> <Form.Input type="number" name="ticket_number" required onChange={this.handleInput} label="Ticket number" > <input placeholder="Enter ticket number" /> </Form.Input> <Button onClick={this.handleClickSelect} type="submit" > Select </Button> </Form> </Grid.Row> </Grid> </Grid.Column> </Grid> </div> ); } /** * Handle table number selection, highlight special table */ handleInput = event => { const name = event.target.name; const value = event.target.value; let x = `${name}`; if (x === 'table_number') { let y = `${value}`; if (y === '3') { this.setState({ [name]: value, table_name: 'Arch' }); } else { this.setState({ [name]: value, table_name: `Table ${value}` }); } } else { this.setState({ [name]: value }); } }; /** * Check table occupancy */ handleClickCheck = event => { event.preventDefault(); utils.log('Checking table'); this.setState({ loading: true, show_message: false }); if (this.validateTableInput()) { utils.log('Table input validated'); this.updateSeatStates(); } else { utils.log('Table input validation failed'); this.setState({ loading: false, header: 'Error!', show_message: true, message: 'Wrong table number' }); } }; /** * Select a seat */ handleClickSelect = event => { utils.log('Selecting seat'); this.setState({ loading: true, show_message: false }); event.preventDefault(); if (this.validateSeatInput() && this.validateTableInput()) { this.pickASeat(); } else { utils.log('Input validation failed'); this.setState({ loading: false, header: 'Error!', show_message: true, message: 'Input validation failed' }); } utils.log(this.state); }; /** * Validate selected table number */ validateTableInput = () => { utils.log('Validating table number input'); let table_number = parseInt(this.state.table_number); utils.log(table_number); if (table_number < 21 && table_number > 0) { return true; } return false; }; /** * Validate selected seat number */ validateSeatInput = () => { utils.log('Validating input'); if ( this.state.email_address !== undefined && this.state.seat_number < 11 && this.state.ticket_number > 0 ) { return true; } return false; }; componentDidMount() { this.updateSeatStates(); } /** * Update seat states */ updateSeatStates = async () => { utils.log('Updating table seat states'); try { let seat_states = await backend.getTableOccupancy( this.state.table_number ); utils.log('Table seat_states data is', seat_states); this.setState({ seat_states: seat_states, loading: false }); } catch (error) { this.setState({ loading: false, header: 'Error!', show_message: true, message: 'Failed to update table' }); } }; /** * Pick a seat by interacting with the backend */ pickASeat = async () => { utils.log('Updating table seat states'); try { let data = { seat_number: this.state.seat_number, email_address: this.state.email_address, ticket_number: this.state.ticket_number }; let result = await backend.selectSeat( this.state.table_number, data ); utils.log('Seat selection result is', result); this.setState({ loading: false, show_message: true, header: 'Message', message: result }); setTimeout(() => { this.updateSeatStates(); }, 2000); } catch (error) { this.setState({ loading: false, show_message: true, header: 'Error!', message: 'Failed to select seat' }); setTimeout(() => { this.updateSeatStates(); }, 2000); } }; /** * Display nofication */ getMessage = () => { if (this.state.show_message) { return ( <Message onDismiss={this.handleDismiss} header={this.state.header} content={this.state.message} /> ); } }; /** * Get table fill color */ getFill = seat => { if (seat.taken === true) { return 'red'; } return 'black'; }; /** * Get table name */ getTableName = () => { return `${this.state.table_name}`; }; /** * Returns the JSX compatible SVG */ getSVG = () => { return ( <svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="573px" height="445px" version="1.1" > <defs /> <g transform="translate(0.5,0.5)"> <g id="cell-4"> <ellipse cx={287} cy={222} rx={156} ry={156} fill="#ffffff" stroke="#000000" pointerEvents="none" /> <g transform="translate(172.5,186.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={378} height={118} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 379, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 100 }}> {this.getTableName()} </font> </div> </div> </foreignObject> <text x={189} y={65} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > &lt;font style="font-size: 100px"&gt;Table 12&lt;/font&gt; </text> </switch> </g> </g> <g id="cell-5"> <rect x="268.5" y={18} width={36} height={36} fill={this.getFill(this.state.seat_states[1])} stroke="#000000" pointerEvents="none" /> <g transform="translate(283.5,30.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#ffffff" > 1 </font> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-6"> <rect x="380.4" y={54} width={36} height={36} fill={this.getFill(this.state.seat_states[2])} stroke="#000000" transform="rotate(35,398.4,72)" pointerEvents="none" /> <g transform="translate(394.5,66.5)scale(0.6)rotate(35,5,9)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#ffffff" > 2 </font> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-7"> <rect x="386.4" y={354} width={36} height={36} fill={this.getFill(this.state.seat_states[5])} stroke="#000000" transform="rotate(140,404.4,372)" pointerEvents="none" /> <g transform="translate(400.5,366.5)scale(0.6)rotate(140,5,9)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font color="#ffffff" style={{ fontSize: 17 }} > 5 </font> <br /> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-8"> <rect x="80.4" y="254.7" width={36} height={36} fill={this.getFill(this.state.seat_states[8])} stroke="#000000" transform="rotate(-105,98.4,272.7)" pointerEvents="none" /> <g transform="translate(94.5,266.5)scale(0.6)rotate(-105,5,9)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font color="#ffffff" style={{ fontSize: 17 }} > 8 </font> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-9"> <rect x="146.4" y={348} width={36} height={36} fill={this.getFill(this.state.seat_states[7])} stroke="#000000" transform="rotate(-140,164.4,366)" pointerEvents="none" /> <g transform="translate(160.5,360.5)scale(0.6)rotate(-140,5,9)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font color="#ffffff" style={{ fontSize: 17 }} > 7 </font> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-10"> <rect x="442.5" y={138} width={36} height={36} fill={this.getFill(this.state.seat_states[3])} stroke="#000000" transform="rotate(70,460.5,156)" pointerEvents="none" /> <g transform="translate(457.5,150.5)scale(0.6)rotate(70,5,9)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#ffffff" > 3 </font> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-11"> <rect x="164.4" y={48} width={36} height={36} fill={this.getFill(this.state.seat_states[10])} stroke="#000000" transform="rotate(-40,182.4,66)" pointerEvents="none" /> <g transform="translate(176.5,60.5)scale(0.6)rotate(-40,9.5,9)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={19} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 19, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#ffffff" > 10 </font> </div> </div> </foreignObject> <text x={10} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-12"> <rect x="94.5" y={126} width={36} height={36} fill={this.getFill(this.state.seat_states[9])} stroke="#000000" transform="rotate(-60,112.5,144)" pointerEvents="none" /> <g transform="translate(109.5,138.5)scale(0.6)rotate(-60,5,9)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font color="#ffffff" style={{ fontSize: 17 }} > 9 </font> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-13"> <rect x="452.4" y="254.7" width={36} height={36} fill={this.getFill(this.state.seat_states[4])} stroke="#000000" transform="rotate(110,470.4,272.7)" pointerEvents="none" /> <g transform="translate(466.5,266.5)scale(0.6)rotate(110,5,9)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#ffffff" > 4 </font> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-14"> <rect x="268.5" y={390} width={36} height={36} fill={this.getFill(this.state.seat_states[6])} stroke="#000000" pointerEvents="none" /> <g transform="translate(283.5,402.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={10} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 11, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font color="#ffffff" style={{ fontSize: 17 }} > 6 </font> </div> </div> </foreignObject> <text x={5} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-3f48a8a04b434277-14"> <path d="M 171 52.2 L 171 52.2" fill="none" stroke="#000000" strokeMiterlimit={10} pointerEvents="none" /> <path d="M 171 52.2 L 171 52.2 L 171 52.2 L 171 52.2 Z" fill="#000000" stroke="#000000" strokeMiterlimit={10} pointerEvents="none" /> </g> <g id="cell-43d37fc22e3b8da7-14"> <g transform="translate(262.5,0.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <span style={{ fontSize: 17 }}> <font color="#000"> { this.state .seat_states[1].name } </font> </span> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-15"> <g transform="translate(262.5,432.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > {this.state.seat_states[6].name} </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-16"> <g transform="translate(445.5,390.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > {this.state.seat_states[5].name} </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-17"> <g transform="translate(93.5,378.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > {this.state.seat_states[7].name} </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-18"> <g transform="translate(23.5,278.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > {this.state.seat_states[8].name} </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-19"> <g transform="translate(501.5,272.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > {this.state.seat_states[4].name} </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-20"> <g transform="translate(493.5,144.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > {this.state.seat_states[3].name} </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-21"> <g transform="translate(31.5,126.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > {this.state.seat_states[9].name} </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-22"> <g transform="translate(427.5,48.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > {this.state.seat_states[2].name} </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> <g id="cell-43d37fc22e3b8da7-23"> <g transform="translate(103.5,48.5)scale(0.6)"> <switch> <foreignObject style={{ overflow: 'visible' }} pointerEvents="all" width={78} height={18} requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', fontSize: 12, fontFamily: 'Helvetica', color: 'rgb(0, 0, 0)', lineHeight: '1.2', verticalAlign: 'top', width: 79, whiteSpace: 'nowrap', wordWrap: 'normal', textAlign: 'center' }} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ display: 'inline-block', textAlign: 'inherit', textDecoration: 'inherit' }} > <font style={{ fontSize: 17 }} color="#000" > { this.state.seat_states[10] .name } </font> </div> </div> </foreignObject> <text x={39} y={15} fill="#000000" textAnchor="middle" fontSize="12px" fontFamily="Helvetica" > [Not supported by viewer] </text> </switch> </g> </g> </g> </svg> ); }; }
JavaScript
class Deployer { /** * Instantiate a Deployer object. * * <b>NOTE: This is not inteded to be called by the user; if you are looking to create a Deployer from web3, please use "static async build" instead!</b> * * @param {web3_instance} _web3 - Initizalized web3 instance, with provider set * @param {object} [_compiled=null] - solc compilation output * @param {string[]} [_accounts=null] - Array of accounts * @param {Logger.state.ENUM} [_logSetting=Logger.state.NORMAL] - Logger state for deployer to use when running methods. * @param {object} options - User options */ //_compiled as an optional param, a way to sort of... hmmm, should be property? //NOTE: THIS IS NOT INTENDED TO BE CALLED; ONLY FOR PRIVATE USE. PLEASE USE BUILD INSTEAD!!! constructor(_web3, _compiled = null, _accounts = null, _logSetting = Logger.state.NORMAL, _options=null) { this.web3 = _web3; this.accounts = _accounts; this.compiled = _compiled; this.log = new Logger(_logSetting); this.options = _options; } /** * Construct a Deployer object. <b>The intended point of entry.</b> * * @param {web3_instance} _web3 - Initizalized web3 instance, with provider set * @param {JSON} [_compiled=null] - solc compilation output. Required for using `async deploy()` function! * @param {Logger.state.ENUM} [_logSetting=Logger.state.NORMAL] - Logger state f or deployer to use when running methods. * @param {object} options - User options * * @return {Deployer} deployer - a new Deployer object instantiated using the provided parameters. */ static async build(_web3, _compiled = null, _logSetting = Logger.state.NORMAL, _options=null) { let accounts = await _web3.eth.getAccounts(); return new Deployer(_web3, _compiled, accounts, _logSetting, _options); } /** * Deploy a contract by name, by parsing the object's (if not provided) compiled material. Returns the contract deployed as a web3.eth.Contract object (as provided by web3). * * @param {string} name - Name of the contract (e.g. Calculator.sol, ERC20.sol) * @param {array} [args=[]] - Constructor arguments for the contract * @param {object} [sender={ from: this.accounts[0] }] - The send object to be passed along in deployment. By default, it is passed an object declaring the 1st account as the sender. * @param {JSON} [compiled=this.compiled] - solc compilation output. * * @return {web3.eth.Contract} - Contract web3 object of the deployed contract. */ async deploy(name, args = [], sender = { from: this.accounts[0] }, compiled=this.compiled){ if(!compiled) { throw "No compilation material provided to deployer!"; } this.log.print(Logger.state.SUPER, "Accounts: " + this.accounts + "\n"); const contractInput = DeployUtil.extractContract(compiled, name); this.log.print(Logger.state.MASTER, contractInput); let Contract = await this.deployContract(contractInput, args, sender); return Contract; } /** * Deploy a contract object [defined internally; see return val of DeployUtil.extractContract]. * * @param {object} contract - Contract object [constructed internally, NOT web3] * @param {array} args - Constructor arguments for the contract * @param {object} sendOptions - The send object to be passed along in deployment. * * @return {web3.eth.Contract} - Contract web3 object of the deployed contract. */ async deployContract(contract, args, sendOptions){ console.log(pp.miniheadline("Deploying " + contract.name + '...')); const spinner = ora().start(); spinner.clear(); let spinnerConf; let contractWeb3 = await (new this.web3.eth.Contract(contract.abi) .deploy({ "data": contract.bytecode.indexOf('0x') === 0 ? contract.bytecode : '0x' + contract.bytecode, "arguments": args }) .send(sendOptions) .on('receipt', (receipt) => { spinner.succeed(); console.log(pp.arrow("status: " + receipt.status ? "Success!" : "Failed :(")); console.log(pp.arrow("transaction hash: " + receipt.transactionHash)); console.log(pp.arrow("contract address: " + receipt.contractAddress)); console.log(pp.arrow("from: " + receipt.from)); console.log(pp.arrow("block number: " + receipt.blockNumber)); console.log(pp.arrow("gas used: " + receipt.gasUsed)); console.log(pp.miniheadline("\nPausing for " + this.options.deployment.confirmations + " confirmations...")); spinnerConf = ora().start(); spinnerConf.clear(); }) .on('confirmation', (num, receipt) => { console.log("confirmation number: " + num + " (block: " + receipt.blockNumber + ")"); if(num === this.options.deployment.confirmations) { //if(spinnerConf) spinnerConf.succeed(); spinnerConf.succeed(); console.log("..."); console.log("Confirmed!"); process.exit(0); console.log("\n\nExtra confirmations:\n") //resolve(); } }) .on('error', (err) => { console.log(err); spinner.fail(); })); return contractWeb3; } }
JavaScript
class OctKey extends Key { constructor (...args) { super(...args) Object.defineProperties(this, { kty: { value: 'oct', enumerable: true }, length: { value: this[KEYOBJECT] ? this[KEYOBJECT].symmetricKeySize * 8 : undefined }, k: { enumerable: false, get () { if (this[KEYOBJECT]) { Object.defineProperty(this, 'k', { value: base64url.encodeBuffer(this[KEYOBJECT].export()), configurable: false }) } else { Object.defineProperty(this, 'k', { value: undefined, configurable: false }) } return this.k }, configurable: true } }) } static get [PUBLIC_MEMBERS] () { return OCT_PUBLIC } static get [PRIVATE_MEMBERS] () { return OCT_PRIVATE } // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special // JSON.stringify handling in V8 [THUMBPRINT_MATERIAL] () { if (!this[KEYOBJECT]) { throw new TypeError('reference "oct" keys without "k" cannot have their thumbprint calculated') } return { k: this.k, kty: 'oct' } } [KEY_MANAGEMENT_ENCRYPT] () { return new Set([ ...this.algorithms('wrapKey'), ...this.algorithms('deriveKey') ]) } [KEY_MANAGEMENT_DECRYPT] () { return this[KEY_MANAGEMENT_ENCRYPT]() } algorithms (...args) { if (!this[KEYOBJECT]) { return new Set() } return Key.prototype.algorithms.call(this, ...args) } static async generate (...args) { return this.generateSync(...args) } static generateSync (len = 256, privat = true) { if (!privat) { throw new TypeError('"oct" keys cannot be generated as public') } if (!Number.isSafeInteger(len) || !len || len % 8 !== 0) { throw new TypeError('invalid bit length') } return createSecretKey(randomBytes(len / 8)) } }
JavaScript
class PasswordResetError extends Error { constructor(msg) { super(); this.message = msg || 'Currently unable to reset password.'; this.name = 'Password Error'; this.code = 1005; this.data = {}; } }
JavaScript
class Comments extends HTMLElement { constructor () { super() /** * Listens to the event name/typeArg: 'comment' * * @param {CustomEvent & {detail: import("../controllers/Comments.js").CommentsEventDetail}} event */ this.commentListener = event => event.detail.fetch.then(({ comment }) => { this.insertBefore(this.createComment(comment, false), this.firstCard) this.formControl.value = '' }) /** * Listens to the event name/typeArg: 'comments' * which is returned when adding a comment * * @param {CustomEvent & {detail: import("../controllers/Comments.js").CommentEventDetail}} event */ this.commentsListener = event => this.render(event.detail.fetch) /** * target href to dispatch a CustomEvent requestListArticles, which will trigger ListArticlePreviews to render with new query * * @param {event & {target: HTMLElement}} event * @return {void | false} */ this.clickListener = event => { let isDeleteIcon = false if (!event.target || (event.target.tagName !== 'BUTTON' && !(isDeleteIcon = event.target.classList.contains('ion-trash-a')))) return false event.preventDefault() if (isDeleteIcon) { const card = event.target.parentNode.parentNode.parentNode if (card && card.classList.contains('card')) { this.dispatchEvent(new CustomEvent('deleteComment', { /** @type {import("../controllers/Comments.js").DeleteCommentEventDetail} */ detail: { id: card.getAttribute('id') }, bubbles: true, cancelable: true, composed: true })) card.remove() } } else { if (this.formControl.value) { this.dispatchEvent(new CustomEvent('addComment', { /** @type {import("../controllers/Comments.js").AddCommentsEventDetail} */ detail: { body: this.formControl.value }, bubbles: true, cancelable: true, composed: true })) } } } } connectedCallback () { // listen for comments document.body.addEventListener('comments', this.commentsListener) document.body.addEventListener('comment', this.commentListener) this.addEventListener('click', this.clickListener) // on every connect it will attempt to get newest comments this.dispatchEvent(new CustomEvent('getComments', { bubbles: true, cancelable: true, composed: true })) if (this.shouldComponentRender()) this.render(null) } disconnectedCallback () { document.body.removeEventListener('comments', this.commentsListener) document.body.removeEventListener('comment', this.commentListener) this.removeEventListener('click', this.clickListener) } /** * evaluates if a render is necessary * * @return {boolean} */ shouldComponentRender () { return !this.innerHTML } /** * renders each received comment * * @param {Promise<import("../../helpers/Interfaces.js").MultipleComments> | null} fetchComments * @return {void} */ render (fetchComments) { this.innerHTML = /* html */ ` <form class="card comment-form"> <div class="card-block"> <textarea class="form-control" placeholder="Write a comment..." rows="3"></textarea> </div> <div class="card-footer"> <img src="${secureImageSrc(this.getAttribute('user-image')) || ''}" class="comment-author-img" /> <button class="btn btn-sm btn-primary"> Post Comment </button> </div> </form> ` fetchComments && fetchComments.then(({ comments }) => { this.innerHTML += comments.reduce((commentsStr, comment) => (commentsStr += this.createComment(comment)), '') }) } /** * html snipper for comment to be filled * * @param {import("../../helpers/Interfaces.js").SingleComment} comment * @param {boolean} [returnString = true] * @return {string | Node} */ createComment (comment, returnString = true) { const card = /* html */` <div class="card" id="${comment.id}"> <div class="card-block"> <p class="card-text">${comment.body}</p> </div> <div class="card-footer"> <a href="" class="comment-author"> <img src="${secureImageSrc(comment.author.image)}" class="comment-author-img" /> </a> &nbsp; <a href="#/profile/${comment.author.username}" class="comment-author">${comment.author.username}</a> <span class="date-posted">${new Date(comment.createdAt).toDateString()}</span> ${comment.author.username === this.getAttribute('user-name') ? '<span class="mod-options"><i class="ion-trash-a"></i></span>' : ''} </div> </div> ` if (returnString) return card const div = document.createElement('div') div.innerHTML = card return div.children[0] } get formControl () { return this.querySelector('.form-control') } /** * returns the first card element * * @readonly * @return {HTMLElement} */ get firstCard () { return this.querySelector('.card:not(.comment-form)') } }
JavaScript
class SampleTransactionEventHandler { /** * Constructor. * @param {String} transactionId Transaction ID for which events will be received. * @param {ChannelEventHub[]} eventHubs Event hubs from which events will be received. * @param {Object} [options] Additional configuration options. * @param {Number} [options.commitTimeout] Time in seconds to wait for commit events to be reveived. */ constructor(transactionId, eventHubs, options) { this.transactionId = transactionId; this.eventHubs = eventHubs; const defaultOptions = { commitTimeout: 120 // 2 minutes }; this.options = Object.assign(defaultOptions, options); this.notificationPromise = new Promise((resolve, reject) => { this._resolveNotificationPromise = resolve; this._rejectNotificationPromise = reject; }); this.eventCounts = { expected: this.eventHubs.length, received: 0 }; } /** * Called to initiate listening for transaction events. * @async * @throws {Error} if not in a state where the handling strategy can be satified and the transaction should * be aborted. For example, if insufficient event hubs could be connected. */ async startListening() { if (this.eventHubs.length > 0) { this._setListenTimeout(); await this._registerTxEventListeners(); } else { // Assume success if no event hubs this._resolveNotificationPromise(); } } /** * Wait until enough events have been received from the event hubs to satisfy the event handling strategy. * @async * @throws {Error} if the transaction commit is not successful within the timeout period. */ async waitForEvents() { await this.notificationPromise; } /** * Cancel listening for events. */ cancelListening() { clearTimeout(this.timeoutHandler); this.eventHubs.forEach((eventHub) => { eventHub.unregisterTxEvent(this.transactionId); eventHub.disconnect(); }); } _setListenTimeout() { if (this.options.commitTimeout <= 0) { return; } this.timeoutHandler = setTimeout(() => { this._fail(new Error(`Timeout waiting for commit events for transaction ID ${this.transactionId}`)); }, this.options.commitTimeout * 1000); } async _registerTxEventListeners() { const registrationOptions = {unregister: true, disconnect: true}; const promises = this.eventHubs.map((eventHub) => { return new Promise((resolve) => { eventHub.registerTxEvent( this.transactionId, (txId, code) => this._onEvent(eventHub, txId, code), (err) => this._onError(eventHub, err), registrationOptions ); eventHub.connect(); resolve(); }); }); await Promise.all(promises); } _onEvent(eventHub, txId, code) { if (code !== 'VALID') { // Peer has rejected the transaction so stop listening with a failure const message = `Peer ${eventHub.getPeerAddr()} has rejected transaction ${txId} with code ${code}`; this._fail(new Error(message)); } else { // -------------------------------------------------------------- // Handle processing of successful transaction commit events here // -------------------------------------------------------------- this._responseReceived(); } } _onError(eventHub, err) { // eslint-disable-line no-unused-vars // ---------------------------------------------------------- // Handle processing of event hub communication failures here // ---------------------------------------------------------- this._responseReceived(); } /** * Simple event handling logic that is satisfied once all of the event hubs have either responded with valid * events or disconnected. */ _responseReceived() { this.eventCounts.received++; if (this.eventCounts.received === this.eventCounts.expected) { this._success(); } } _fail(error) { this.cancelListening(); this._rejectNotificationPromise(error); } _success() { this.cancelListening(); this._resolveNotificationPromise(); } }
JavaScript
class UserStorage { loginUser(username, password) { return new Promise((resolve, reject) => { console.log('로그인을 시도하고 있습니다....'); setTimeout(() => { if ( (username === 'ellie' && password === 'dream') || (username === 'coder' && password === 'academy') ) { resolve(username); } else { reject(new Error('not found')); } },1000); }) } getRoles(user) { return new Promise((resolve, reject) => { console.log('권한을 가져오는 중입니다.....'); setTimeout(() => { if (user === 'ellie'){ resolve({ name: 'ellie', role: 'admin' }); } else { reject(new Error('no access')); } }, 2000); }) } }
JavaScript
class Magpie extends EventEmitter { /** * Gives easy access to validators. Validation is based on [vuelidate](https://vuelidate.js.org). * * * | Name | Meta parameters | Description | * |---|---|---| * | required | none | Requires non-empty data. Checks for empty arrays and strings containing only whitespaces. | * | requiredIf | locator * | Requires non-empty data only if provided property or predicate is true. | * | requiredUnless | locator * | Requires non-empty data only if provided property or predicate is false. | * | minLength | min length | Requires the input to have a minimum specified length, inclusive. Works with arrays. | * | maxLength | max length | Requires the input to have a maximum specified length, inclusive. Works with arrays. | * | minValue | min | Requires entry to have a specified minimum numeric value or Date. | * | maxValue | max | Requires entry to have a specified maximum numeric value or Date. | * | between | min, max | Checks if a number or Date is in specified bounds. Min and max are both inclusive. | * | alpha | none | Accepts only alphabet characters. | * | alphaNum | none | Accepts only alphanumerics. | * | numeric | none | Accepts only numerics. | * | integer | none | Accepts positive and negative integers. | * | decimal | none | Accepts positive and negative decimal numbers. | * | email | none | Accepts valid email addresses. Keep in mind you still have to carefully verify it on your server, as it is impossible to tell if the address is real without sending verification email. | * | ipAddress | none | Accepts valid IPv4 addresses in dotted decimal notation like 127.0.0.1. | * | macAddress | separator=':' | Accepts valid MAC addresses like 00:ff:11:22:33:44:55. Don't forget to call it macAddress(), as it has optional parameter. You can specify your own separator instead of ':'. Provide empty separator macAddress('') to validate MAC addresses like 00ff1122334455. | * | sameAs | locator * | Checks for equality with a given property. | * | url | none | Accepts only URLs. | * | or | validators... | Passes when at least one of provided validators passes. | * | and | validators... | Passes when all of provided validators passes. | * | not | validator | Passes when provided validator would not pass, fails otherwise. Can be chained with other validators like not(sameAs('field')). | * * * \* Locator is a sibling property name. * * * @instance * @member validators * @memberOf Magpie * @type {object} */ get validators() { return validators; } /** * Shorthand for $magpie.validators * @instance * @member v * @memberOf Magpie * @type {object} */ get v() { return validators; } constructor(options) { super(); this.experiment = {}; // options /** * The ID of the experiment * * @instance * @member id * @memberOf Magpie * @type {string} */ this.id = options.experimentId; /** * @instance * @member serverUrl * @memberOf Magpie * @type {string} */ this.serverUrl = options.serverUrl; /** * @instance * @member submissionUrl * @memberOf Magpie * @type {string} */ this.submissionUrl = this.serverUrl + (this.serverUrl[this.serverUrl.length - 1] === '/' ? '' : '/') + 'api/submit_experiment/' + this.id; /** * @instance * @member submissionUrl * @memberOf Magpie * @type {string} */ this.completionUrl = options.completionUrl; /** * @instance * @member contactEmail * @memberOf Magpie * @type {string} */ this.contactEmail = options.contactEmail; /** * @instance * @member mode * @memberOf Magpie * @type {string} */ this.mode = options.mode; /** * @instance * @member contactEmail * @memberOf Magpie * @type {boolean} */ this.debug = options.mode === 'debug'; /** * @instance * @member socket * @memberOf Magpie * @type {Socket} */ this.socket = options.socketUrl ? new Socket(options.experimentId, options.socketUrl, this.onSocketError) : false; this.trialData = window.magpie_trial_data = {}; this.expData = window.magpie_exp_data = {}; this.progress = -1; /** * @instance * @member mousetracking * @memberOf Magpie * @type {Mousetracking} */ this.mousetracking = new Mousetracking(); /** * @instance * @member eyetracking * @memberOf Magpie * @type {Eyetracking} */ this.eyetracking = new Eyetracking(); /** * The id of the current screen * @instance * @member currentScreenIndex * @memberOf Magpie * @type {number} */ this.currentScreenIndex = 0; /** * The id of the current slide * @instance * @member currentSlideIndex * @memberOf Magpie * @type {number} */ this.currentSlideIndex = 0; /** * The start time of the response_time measurement * @instance * @member responseTimeStart * @memberOf Magpie * @type {number} */ this.responseTimeStart = Date.now(); /** * The measurements of the current screen. All data in this object * can be saved using $magpie.saveMeasurements * @instance * @member measurements * @memberOf Magpie * @type {object} */ this.measurements = {}; /** * Validation results on the current measurements * @instance * @member validateMeasurements * @memberOf Magpie * @type {object} */ this.validateMeasurements = {}; /** * A hash of timer start points by id * @instance * @member timers * @memberOf Magpie * @type {object} */ this.timers = {}; // Provide debug info console.log('_magpie ' + packageJSON.version); console.log('Experiment id: ' + this.id); console.log('Server: ' + this.serverUrl); console.log('Submission URL: ' + this.submissionUrl); console.log('Mode: ' + this.mode); console.log('Completion URL: ' + this.completionUrl); console.log('magpie_trial_data = ', this.trialData); console.log('magpie_exp_data = ', this.expData); Vue.observable(this); if (this.mode === 'prolific') { this.extractProlificData(); } this.addExpData({ experiment_start_time: Date.now() }); } /** * Go to the next slide. * @instance * @memberOf Magpie * @public * @param index{int} the index of the slide to go to (optional; default is next slide) */ nextSlide(index) { if (typeof index === 'number') { this.currentSlideIndex = index; return; } this.currentSlideIndex++; } /** * Go to the next screen. (Will also reset scroll position.) * @instance * @memberOf Magpie * @public * @param index{int} the index of the screen to go to (optional; default is next screen) */ nextScreen(index) { if (typeof index === 'number') { this.currentScreenIndex = index; } else { this.currentScreenIndex += 1; } this.currentSlideIndex = 0; this.measurements = {}; this.currentVarsData = {}; if (this.socket) { this.socket.setCurrentScreen(this.currentScreenIndex); } // Start new trial data and restart response timer this.responseTimeStart = Date.now(); this.experiment.scrollToTop(); this.mousetracking.start(); this.eyetracking.pause(); } /** * SaveMeasurements and go to the next screen. (Will also reset scroll position.) * @instance * @memberOf Magpie * @public * @param index{int} the index of the screen to go to (optional; default is next screen) */ saveAndNextScreen(index) { this.saveMeasurements(); this.nextScreen(index); } /** * Add a result set * This method will automatically add a response_time key to your data with time measured from the start of the current screen * @instance * @memberOf Magpie * @public * @param data{Object} a flat object whose data you want to add to the results */ addTrialData(data) { if (!this.trialData[this.currentScreenIndex]) { this.trialData[this.currentScreenIndex] = []; } this.trialData[this.currentScreenIndex].push({ response_time: Date.now() - this.responseTimeStart, ...data }); } /** * Add global facts that will be added to each result set * @instance * @memberOf Magpie * @public * @param data{Object} a flat object whose data you want to add to the facts */ addExpData(data) { Object.assign(this.expData, data); } saveMeasurements() { this.addTrialData({ response_time: Date.now() - this.responseTimeStart, ...this.measurements }); } onSocketError(er) { console.error(er); } /** * Returns an array of objects with all trial data that has been submitted so far, including experiment-wide data * @instance * @memberOf Magpie * @public * @returns {Object[]} */ getAllData() { return flattenData({ ...this.expData, experiment_end_time: Date.now(), experiment_duration: Date.now() - this.expData.experiment_start_time, trials: addEmptyColumns( flatten(Object.values(this.trialData)).map((o) => Object.assign( {}, Object.fromEntries( Object.entries(o).filter( ([, value]) => typeof value !== 'function' ) ) ) ) ) // clone the data }); } /** * Submit all data collected so far * @instance * @memberOf Magpie * @returns {Promise<void>} */ submit() { if (!this.submissionUrl) { throw new Error('No submission URL set'); } return this.submitResults(this.submissionUrl, this.getAllData()); } /** * Submit all data collected so far as intermediate results * @instance * @memberOf Magpie * @returns {Promise<void>} */ submitIntermediateResults() { if (!this.submissionUrl) { throw new Error('No submission URL set'); } return this.submitResults(this.submissionUrl, this.getAllData(), true); } async submitResults(submissionURL, data, intermediate) { if (this.socket) { const submissionType = intermediate ? 'save_intermediate_results' : 'submit_results'; return new Promise((resolve, reject) => this.socket.participantChannel .push(submissionType, { results: data }) .receive('ok', resolve) .receive('error', reject) ); } const resp = await fetch(submissionURL, { method: 'POST', mode: 'cors', headers: { 'Content-type': 'application/json' }, body: JSON.stringify(data) }); if (!resp.ok) { throw new Error('The server says: ' + (await resp.text())); } } /** * Set progress bar percentage * Will display a progress bar if it's not visible, yet. * @public * @instance * @memberOf Magpie * @param percentage{float} the percentage to display as a number between 0 and 1 */ setProgress(percentage) { this.progress = percentage; } extractProlificData() { const url = new URL(window.location); this.addExpData({ prolific_pid: url.searchParams.get('PROLIFIC_PID'), prolific_study_id: url.searchParams.get('STUDY_ID'), prolific_session_id: url.searchParams.get('SESSION_ID') }); } }
JavaScript
class PatternTokenizer extends models['Tokenizer'] { /** * Create a PatternTokenizer. * @member {string} [pattern] A regular expression pattern to match token * separators. Default is an expression that matches one or more whitespace * characters. Default value: '\W+' . * @member {object} [flags] Regular expression flags. * @member {string} [flags.name] * @member {number} [group] The zero-based ordinal of the matching group in * the regular expression pattern to extract into tokens. Use -1 if you want * to use the entire pattern to split the input into tokens, irrespective of * matching groups. Default is -1. Default value: -1 . */ constructor() { super(); } /** * Defines the metadata of PatternTokenizer * * @returns {object} metadata of PatternTokenizer * */ mapper() { return { required: false, serializedName: '#Microsoft.Azure.Search.PatternTokenizer', type: { name: 'Composite', className: 'PatternTokenizer', modelProperties: { name: { required: true, serializedName: 'name', type: { name: 'String' } }, odatatype: { required: true, serializedName: '@odata\\.type', type: { name: 'String' } }, pattern: { required: false, serializedName: 'pattern', defaultValue: '\W+', type: { name: 'String' } }, flags: { required: false, serializedName: 'flags', type: { name: 'Composite', className: 'RegexFlags' } }, group: { required: false, serializedName: 'group', defaultValue: -1, type: { name: 'Number' } } } } }; } }
JavaScript
class RDFTransformNamespacesManager { /** @type RDFTransformDialog */ #dialog; #theNamespaces; #theVocabManager; constructor(dialog) { this.#dialog = dialog; this.#theVocabManager = new RDFTransformVocabManager(this); // Namespaces have not been initialized... // Initialize after construction due to await'ing on defaults when needed! } async init() { this.#dialog.waitOnNamespaces(); // Get existing namespaces (clone namespaces)... var theNamespaces = this.#dialog.getNamespaces(); if ( ! theNamespaces ) { var data = null; this.#theNamespaces = {} // ...empty object, no namespaces try { data = await this.#getDefaults(); } catch (evt) { // ...ignore error, no namespaces... } var bError = false; if (data !== null && "namespaces" in data) { this.#theNamespaces = data.namespaces; // ...new defaults namespaces } else { // (data === null || data.code === "error") bError = true; } // We might have namespace errors... if (bError) { alert( $.i18n('rdft-vocab/error-retrieve-default') ); } } else { this.#theNamespaces = JSON.parse( JSON.stringify( theNamespaces ) ); this.#saveNamespaces(); } this.#renderNamespaces(); } reset() { this.#dialog.waitOnNamespaces(); // Get existing namespaces (clone namespaces)... this.#theNamespaces = JSON.parse( JSON.stringify( this.#dialog.getNamespaces() ) ); this.#saveNamespaces(); this.#renderNamespaces(); } /* * Method: getDefaults() * * Get the Default Namespaces from the server. As this method returns a Promise, it expects * the caller is an "async" function "await"ing the results of the Promise. * */ #getDefaults() { return new Promise( (resolve, reject) => { // GET default namespaces in ajax $.ajax( { url : "command/rdf-transform/get-default-namespaces", type : "GET", async: false, // ...wait on results data : { "project" : theProject.id }, dataType : "json", success : (result, strStatus, xhr) => { resolve(result); }, error : (xhr, strStatus, error) => { resolve(null); } } ); } ); } #saveNamespaces(onDoneSave) { Refine.postCSRF( "command/rdf-transform/save-namespaces", { "project" : theProject.id, "namespaces" : this.#theNamespaces }, (data) => { if (onDoneSave) { onDoneSave(data); } }, "json" ); } showManageWidget() { this.#theVocabManager.show( () => this.#renderNamespaces() ); } #renderNamespaces() { this.#dialog.updateNamespaces(this.#theNamespaces); } isNull() { if (this.#theNamespaces === null) { return true; } return false; } isEmpty() { if (this.#theNamespaces === null || Object.keys(this.#theNamespaces).length === 0) { return true; } return false; } getNamespaces(){ return this.#theNamespaces } removeNamespace(strPrefixFind) { if (strPrefixFind in this.#theNamespaces) { delete this.#theNamespaces[strPrefixFind]; this.#dialog.updatePreview(); } } addNamespace(strMessage, strPrefixGiven, onDoneAdd) { var widget = new RDFTransformNamespaceAdder(this); widget.show( strMessage, strPrefixGiven, (strPrefix, strNamespace) => { // NOTE: The RDFTransformNamespaceAdder should have validated the // prefix information, so no checks are required here. // Add the Prefix and its Namespace... this.#theNamespaces[strPrefix] = strNamespace; this.#saveNamespaces(); this.#renderNamespaces(); if (onDoneAdd) { onDoneAdd(strPrefix); } this.#dialog.updatePreview(); } ); } hasPrefix(strPrefixFind) { if (strPrefixFind in this.#theNamespaces) { return true; } return false; } getNamespaceOfPrefix(strPrefixFind) { if (strPrefixFind in this.#theNamespaces) { return this.#theNamespaces[strPrefixFind]; } return null; } }
JavaScript
class ImageLoader { constructor() { } static read(url) { return new Promise((resolve, reject) => { this.request(url).then((data) => { // console.log(data); resolve(data) }).catch((err) => { reject(err); }); }); } static request(url) { return new Promise((resolve, reject) => { var protocol = url.indexOf('https') > -1 ? https : http; protocol.get(url, (res) => { var imageData = []; res.setEncoding('binary'); res.on('data', (chunk) => { imageData.push(chunk); }); res.on('end', () => { var imageBase64 = new Buffer(imageData.join(''), 'binary').toString('base64'); resolve(imageBase64); }); res.on('error', (err) => { reject(err); }); }); }); } }
JavaScript
class DiscordTransport extends winston_transport_1.default { constructor(opts) { super(opts); /** Helper function to retrieve url */ this.getUrl = () => { return `https://discordapp.com/api/v6/webhooks/${this.id}/${this.token}`; }; /** * Initialize the transport to fetch Discord id and token */ this.initialize = () => { this.initialized = new Promise((resolve, reject) => { const opts = { url: this.webhook, method: 'GET', json: true }; superagent_1.default .get(opts.url) .set('accept', 'json') .then(response => { this.id = response.body.id; this.token = response.body.token; resolve(); }).catch(err => { console.error(`Could not connect to Discord Webhook at ${this.webhook}`); reject(err); }); }); }; /** * Sends log message to discord */ this.sendToDiscord = (info) => __awaiter(this, void 0, void 0, function* () { const postBody = { content: undefined, embeds: [{ description: info.message, color: DiscordTransport.COLORS[info.level], fields: [], timestamp: new Date().toISOString(), }] }; if (info.level === 'error' && info.error && info.error.stack) { postBody.content = `\`\`\`${info.error.stack}\`\`\``; } if (this.defaultMeta) { Object.keys(this.defaultMeta).forEach(key => { postBody.embeds[0].fields.push({ name: key, value: this.defaultMeta[key] }); }); } if (info.meta) { Object.keys(info.meta).forEach(key => { postBody.embeds[0].fields.push({ name: key, value: info.meta[key] }); }); } postBody.embeds[0].fields.push({ name: 'Host', value: os_1.default.hostname() }); const options = { url: this.getUrl(), method: 'POST', json: true, body: postBody }; try { // await request(options); yield superagent_1.default .post(options.url) .send(options.body) .set('accept', 'json'); } catch (err) { console.error('Error sending to discord'); } }); this.webhook = opts.webhook; this.defaultMeta = opts.defaultMeta; this.initialize(); } /** * Function exposed to winston to be called when logging messages * @param info Log message from winston * @param callback Callback to winston to complete the log */ log(info, callback) { if (info.discord !== false) { setImmediate(() => { this.initialized.then(() => { this.sendToDiscord(info); }).catch(err => { console.log('Error sending message to discord', err); }); }); } callback(); } }
JavaScript
class QuadPatternFragmentsController extends Controller { constructor(options) { options = options || {}; super(options); this._routers = options.routers || []; this._extensions = options.extensions || []; this.viewName = 'QuadPatternFragments'; } // The required features the given datasource must have supportsDatasource(datasource) { return datasource.supportedFeatures.triplePattern || datasource.supportedFeatures.quadPattern; } // Try to serve the requested fragment _handleRequest(request, response, next) { // Create the query from the request by calling the fragment routers let requestParams = { url: request.parsedUrl, headers: request.headers }, query = this._routers.reduce((query, router) => { try { router.extractQueryParams(requestParams, query); } catch (e) { /* ignore routing errors */ } return query; }, { features: [] }); // Execute the query on the data source let datasource = query.features.datasource && this._datasources[query.datasource]; delete query.features.datasource; if (!datasource || !datasource.supportsQuery(query) || !this.supportsDatasource(datasource)) return next(); // Generate the query result let view = this._negotiateView(this.viewName, request, response), settings = this._createFragmentMetadata(request, query, datasource); settings.results = datasource.select(query, (error) => { error && next(error); }); // Execute the extensions and render the query result let extensions = this._extensions, extensionId = 0; (function nextExtension(error) { // Log a possible error with the previous extension if (error) process.stderr.write(error.stack + '\n'); // Execute the next extension if (extensionId < extensions.length) extensions[extensionId++].handleRequest(request, response, nextExtension, settings); // Render the query result else view.render(settings, request, response); })(); } // Create the template URL for requesting quad patterns _createTemplateUrl(datasourceUrl, supportsQuads) { return datasourceUrl + (!supportsQuads ? '{?subject,predicate,object}' : '{?subject,predicate,object,graph}'); } // Create parameterized pattern string for quad patterns _createPatternString(query, supportsQuads) { let subject = query.subject, predicate = query.predicate, object = query.object, graph = ''; // Serialize subject and predicate IRIs or variables subject = subject ? '<' + query.subject.value + '> ' : '?s '; predicate = predicate ? '<' + query.predicate.value + '> ' : '?p '; // Serialize object IRI, literal, or variable if (query.object && query.object.termType === 'NamedNode') object = '<' + query.object.value + '> '; else object = query.object ? query.object.value : '?o'; // Serialize graph IRI default graph, or variable if (supportsQuads) { graph = query.graph; if (graph && graph.termType === 'DefaultGraph') graph = ' @default'; else if (graph) graph = ' <' + graph.value + '>'; else graph = ' ?g'; } // Join them in a pattern return '{ ' + subject + predicate + object + graph + '. }'; } // Creates metadata about the requested fragment _createFragmentMetadata(request, query, datasourceSettings) { // TODO: these URLs should be generated by the routers let requestUrl = request.parsedUrl, // maintain the originally requested query string to avoid encoding differences origQuery = request.url.replace(/[^?]+/, ''), pageUrl = url.format(requestUrl).replace(/\?.*/, origQuery), paramsNoPage = _.omit(requestUrl.query, 'page'), currentPage = parseInt(requestUrl.query.page, 10) || 1, datasourceUrl = url.format(_.omit(requestUrl, 'query')), fragmentUrl = url.format({ ...requestUrl, query: paramsNoPage }), fragmentPageUrlBase = fragmentUrl + (/\?/.test(fragmentUrl) ? '&' : '?') + 'page=', indexUrl = url.format(_.omit(requestUrl, 'search', 'query', 'pathname')) + '/'; // Generate a textual representation of the pattern let supportsQuads = datasourceSettings.supportedFeatures.quadPattern || false; query.patternString = this._createPatternString(query, supportsQuads); return { datasource: _.assign(datasourceSettings, { index: indexUrl + '#dataset', url: datasourceUrl + '#dataset', templateUrl: this._createTemplateUrl(datasourceUrl, supportsQuads), supportsQuads: supportsQuads, }), fragment: { url: fragmentUrl, pageUrl: pageUrl, firstPageUrl: fragmentPageUrlBase + '1', nextPageUrl: fragmentPageUrlBase + (currentPage + 1), previousPageUrl: currentPage > 1 ? fragmentPageUrlBase + (currentPage - 1) : null, }, query: query, prefixes: this._prefixes, datasources: this._datasources, }; } // Close all data sources close() { for (let datasourceName in this._datasources) { try { this._datasources[datasourceName].close(); } catch (error) { /* ignore closing errors */ } } } }
JavaScript
class AuthApi extends BaseAPI { /** * * @summary Get the account information on blockchain * @param {string} address Account address * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AuthApi */ authAccountsAddressGet(address, options) { return AuthApiFp(this.configuration).authAccountsAddressGet(address, options)(this.axios, this.basePath); } }
JavaScript
class BankApi extends BaseAPI { /** * * @summary Send coins from one account to another * @param {string} address Account address in bech32 format * @param {SendReq} account * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof BankApi */ bankAccountsAddressTransfersPost(address, account, options) { return BankApiFp(this.configuration).bankAccountsAddressTransfersPost(address, account, options)(this.axios, this.basePath); } /** * * @summary Get the account balances * @param {string} address Account address in bech32 format * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof BankApi */ bankBalancesAddressGet(address, options) { return BankApiFp(this.configuration).bankBalancesAddressGet(address, options)(this.axios, this.basePath); } }
JavaScript
class DistributionApi extends BaseAPI { /** * * @summary Community pool parameters * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionCommunityPoolGet(options) { return DistributionApiFp(this.configuration).distributionCommunityPoolGet(options)(this.axios, this.basePath); } /** * Get the sum of all the rewards earned by delegations by a single delegator * @summary Get the total rewards balance from all delegations * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionDelegatorsDelegatorAddrRewardsGet(delegatorAddr, options) { return DistributionApiFp(this.configuration).distributionDelegatorsDelegatorAddrRewardsGet(delegatorAddr, options)(this.axios, this.basePath); } /** * Withdraw all the delegator\'s delegation rewards * @summary Withdraw all the delegator\'s delegation rewards * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {WithdrawRewardsReq} [withdrawRequestBody] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionDelegatorsDelegatorAddrRewardsPost(delegatorAddr, withdrawRequestBody, options) { return DistributionApiFp(this.configuration).distributionDelegatorsDelegatorAddrRewardsPost(delegatorAddr, withdrawRequestBody, options)(this.axios, this.basePath); } /** * Query a single delegation reward by a delegator * @summary Query a delegation reward * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionDelegatorsDelegatorAddrRewardsValidatorAddrGet(delegatorAddr, validatorAddr, options) { return DistributionApiFp(this.configuration).distributionDelegatorsDelegatorAddrRewardsValidatorAddrGet(delegatorAddr, validatorAddr, options)(this.axios, this.basePath); } /** * Withdraw a delegator\'s delegation reward from a single validator * @summary Withdraw a delegation reward * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {WithdrawRewardsReq} [withdrawRequestBody] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionDelegatorsDelegatorAddrRewardsValidatorAddrPost(delegatorAddr, validatorAddr, withdrawRequestBody, options) { return DistributionApiFp(this.configuration).distributionDelegatorsDelegatorAddrRewardsValidatorAddrPost(delegatorAddr, validatorAddr, withdrawRequestBody, options)(this.axios, this.basePath); } /** * Get the delegations\' rewards withdrawal address. This is the address in which the user will receive the reward funds * @summary Get the rewards withdrawal address * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionDelegatorsDelegatorAddrWithdrawAddressGet(delegatorAddr, options) { return DistributionApiFp(this.configuration).distributionDelegatorsDelegatorAddrWithdrawAddressGet(delegatorAddr, options)(this.axios, this.basePath); } /** * Replace the delegations\' rewards withdrawal address for a new one. * @summary Replace the rewards withdrawal address * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {SetWithdrawAddressReq} [withdrawRequestBody] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionDelegatorsDelegatorAddrWithdrawAddressPost(delegatorAddr, withdrawRequestBody, options) { return DistributionApiFp(this.configuration).distributionDelegatorsDelegatorAddrWithdrawAddressPost(delegatorAddr, withdrawRequestBody, options)(this.axios, this.basePath); } /** * * @summary Fee distribution parameters * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionParametersGet(options) { return DistributionApiFp(this.configuration).distributionParametersGet(options)(this.axios, this.basePath); } /** * Query the distribution information of a single validator * @summary Validator distribution information * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionValidatorsValidatorAddrGet(validatorAddr, options) { return DistributionApiFp(this.configuration).distributionValidatorsValidatorAddrGet(validatorAddr, options)(this.axios, this.basePath); } /** * * @summary Fee distribution outstanding rewards of a single validator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionValidatorsValidatorAddrOutstandingRewardsGet(validatorAddr, options) { return DistributionApiFp(this.configuration).distributionValidatorsValidatorAddrOutstandingRewardsGet(validatorAddr, options)(this.axios, this.basePath); } /** * Query the commission and self-delegation rewards of validator. * @summary Commission and self-delegation rewards of a single validator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionValidatorsValidatorAddrRewardsGet(validatorAddr, options) { return DistributionApiFp(this.configuration).distributionValidatorsValidatorAddrRewardsGet(validatorAddr, options)(this.axios, this.basePath); } /** * Withdraw the validator\'s self-delegation and commissions rewards * @summary Withdraw the validator\'s rewards * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {WithdrawRewardsReq} [withdrawRequestBody] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DistributionApi */ distributionValidatorsValidatorAddrRewardsPost(validatorAddr, withdrawRequestBody, options) { return DistributionApiFp(this.configuration).distributionValidatorsValidatorAddrRewardsPost(validatorAddr, withdrawRequestBody, options)(this.axios, this.basePath); } }
JavaScript
class GaiaRESTApi extends BaseAPI { /** * Information about the connected node * @summary The properties of the connected node * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GaiaRESTApi */ nodeInfoGet(options) { return GaiaRESTApiFp(this.configuration).nodeInfoGet(options)(this.axios, this.basePath); } }
JavaScript
class GovernanceApi extends BaseAPI { /** * Query governance deposit parameters. The max_deposit_period units are in nanoseconds. * @summary Query governance deposit parameters * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govParametersDepositGet(options) { return GovernanceApiFp(this.configuration).govParametersDepositGet(options)(this.axios, this.basePath); } /** * Query governance tally parameters * @summary Query governance tally parameters * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govParametersTallyingGet(options) { return GovernanceApiFp(this.configuration).govParametersTallyingGet(options)(this.axios, this.basePath); } /** * Query governance voting parameters. The voting_period units are in nanoseconds. * @summary Query governance voting parameters * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govParametersVotingGet(options) { return GovernanceApiFp(this.configuration).govParametersVotingGet(options)(this.axios, this.basePath); } /** * Query proposals information with parameters * @summary Query proposals * @param {string} [voter] voter address * @param {string} [depositor] depositor address * @param {string} [status] proposal status, valid values can be &#x60;\&quot;deposit_period\&quot;&#x60;, &#x60;\&quot;voting_period\&quot;&#x60;, &#x60;\&quot;passed\&quot;&#x60;, &#x60;\&quot;rejected\&quot;&#x60; * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsGet(voter, depositor, status, options) { return GovernanceApiFp(this.configuration).govProposalsGet(voter, depositor, status, options)(this.axios, this.basePath); } /** * Generate a parameter change proposal transaction * @summary Generate a parameter change proposal transaction * @param {ParamChangeProposalReq} postProposalBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsParamChangePost(postProposalBody, options) { return GovernanceApiFp(this.configuration).govProposalsParamChangePost(postProposalBody, options)(this.axios, this.basePath); } /** * Send transaction to submit a proposal * @summary Submit a proposal * @param {PostProposalReq} postProposalBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsPost(postProposalBody, options) { return GovernanceApiFp(this.configuration).govProposalsPost(postProposalBody, options)(this.axios, this.basePath); } /** * Query deposit by proposalId and depositor address * @summary Query deposit * @param {string} proposalId proposal id * @param {string} depositor Bech32 depositor address * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdDepositsDepositorGet(proposalId, depositor, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdDepositsDepositorGet(proposalId, depositor, options)(this.axios, this.basePath); } /** * Query deposits by proposalId * @summary Query deposits * @param {string} proposalId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdDepositsGet(proposalId, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdDepositsGet(proposalId, options)(this.axios, this.basePath); } /** * Send transaction to deposit tokens to a proposal * @summary Deposit tokens to a proposal * @param {string} proposalId proposal id * @param {DepositReq} postDepositBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdDepositsPost(proposalId, postDepositBody, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdDepositsPost(proposalId, postDepositBody, options)(this.axios, this.basePath); } /** * Query a proposal by id * @summary Query a proposal * @param {string} proposalId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdGet(proposalId, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdGet(proposalId, options)(this.axios, this.basePath); } /** * Query for the proposer for a proposal * @summary Query proposer * @param {string} proposalId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdProposerGet(proposalId, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdProposerGet(proposalId, options)(this.axios, this.basePath); } /** * Gets a proposal\'s tally result at the current time. If the proposal is pending deposits (i.e status \'DepositPeriod\') it returns an empty tally result. * @summary Get a proposal\'s tally result at the current time * @param {string} proposalId proposal id * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdTallyGet(proposalId, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdTallyGet(proposalId, options)(this.axios, this.basePath); } /** * Query voters information by proposalId * @summary Query voters * @param {string} proposalId proposal id * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdVotesGet(proposalId, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdVotesGet(proposalId, options)(this.axios, this.basePath); } /** * Send transaction to vote a proposal * @summary Vote a proposal * @param {string} proposalId proposal id * @param {VoteReq} postVoteBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdVotesPost(proposalId, postVoteBody, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdVotesPost(proposalId, postVoteBody, options)(this.axios, this.basePath); } /** * Query vote information by proposal Id and voter address * @summary Query vote * @param {string} proposalId proposal id * @param {string} voter Bech32 voter address * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof GovernanceApi */ govProposalsProposalIdVotesVoterGet(proposalId, voter, options) { return GovernanceApiFp(this.configuration).govProposalsProposalIdVotesVoterGet(proposalId, voter, options)(this.axios, this.basePath); } }
JavaScript
class IBCApi extends BaseAPI { /** * * @summary Channel open-init * @param {ChannelOpenInitReq} channelOpenInitRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcChannelsOpenInitPost(channelOpenInitRequestBody, options) { return IBCApiFp(this.configuration).ibcChannelsOpenInitPost(channelOpenInitRequestBody, options)(this.axios, this.basePath); } /** * * @summary Channel open-try * @param {ChannelOpenTryReq} channelOpenTryRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcChannelsOpenTryPost(channelOpenTryRequestBody, options) { return IBCApiFp(this.configuration).ibcChannelsOpenTryPost(channelOpenTryRequestBody, options)(this.axios, this.basePath); } /** * * @summary Query client state * @param {string} clientId Client ID * @param {boolean} [prove] Proof of result * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcClientsClientIdClientStateGet(clientId, prove, options) { return IBCApiFp(this.configuration).ibcClientsClientIdClientStateGet(clientId, prove, options)(this.axios, this.basePath); } /** * * @summary Query connections of a client * @param {string} clientId Client ID * @param {boolean} [prove] Proof of result * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcClientsClientIdConnectionsGet(clientId, prove, options) { return IBCApiFp(this.configuration).ibcClientsClientIdConnectionsGet(clientId, prove, options)(this.axios, this.basePath); } /** * * @summary Query cliet consensus-state * @param {string} clientId Client ID * @param {boolean} [prove] Proof of result * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcClientsClientIdConsensusStateGet(clientId, prove, options) { return IBCApiFp(this.configuration).ibcClientsClientIdConsensusStateGet(clientId, prove, options)(this.axios, this.basePath); } /** * * @summary Submit misbehaviour * @param {string} clientId Client ID * @param {SubmitMisbehaviourReq} submitMisbehaviourRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcClientsClientIdMisbehaviourPost(clientId, submitMisbehaviourRequestBody, options) { return IBCApiFp(this.configuration).ibcClientsClientIdMisbehaviourPost(clientId, submitMisbehaviourRequestBody, options)(this.axios, this.basePath); } /** * * @summary Query client root * @param {string} clientId Client ID * @param {number} height Root height * @param {boolean} [prove] Proof of result * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcClientsClientIdRootsHeightGet(clientId, height, prove, options) { return IBCApiFp(this.configuration).ibcClientsClientIdRootsHeightGet(clientId, height, prove, options)(this.axios, this.basePath); } /** * * @summary Update client * @param {string} clientId Client ID * @param {UpdateClientReq} updateClientRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcClientsClientIdUpdatePost(clientId, updateClientRequestBody, options) { return IBCApiFp(this.configuration).ibcClientsClientIdUpdatePost(clientId, updateClientRequestBody, options)(this.axios, this.basePath); } /** * * @summary Create client * @param {CreateClientReq} createClientRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcClientsPost(createClientRequestBody, options) { return IBCApiFp(this.configuration).ibcClientsPost(createClientRequestBody, options)(this.axios, this.basePath); } /** * * @summary Query connection * @param {string} connectionId Connection ID * @param {boolean} [prove] Proof of result * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcConnectionsConnectionIdGet(connectionId, prove, options) { return IBCApiFp(this.configuration).ibcConnectionsConnectionIdGet(connectionId, prove, options)(this.axios, this.basePath); } /** * * @summary Connection open-ack * @param {string} connectionId Connection ID * @param {ConnectionOpenAckReq} connectionOpenAckRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcConnectionsConnectionIdOpenAckPost(connectionId, connectionOpenAckRequestBody, options) { return IBCApiFp(this.configuration).ibcConnectionsConnectionIdOpenAckPost(connectionId, connectionOpenAckRequestBody, options)(this.axios, this.basePath); } /** * * @summary Connection open-confirm * @param {string} connectionId Connection ID * @param {ConnectionOpenConfirmReq} connectionOpenConfirmRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcConnectionsConnectionIdOpenConfirmPost(connectionId, connectionOpenConfirmRequestBody, options) { return IBCApiFp(this.configuration).ibcConnectionsConnectionIdOpenConfirmPost(connectionId, connectionOpenConfirmRequestBody, options)(this.axios, this.basePath); } /** * * @summary Connection open-init * @param {ConnectionOpenInitReq} connectionOpenInitRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcConnectionsOpenInitPost(connectionOpenInitRequestBody, options) { return IBCApiFp(this.configuration).ibcConnectionsOpenInitPost(connectionOpenInitRequestBody, options)(this.axios, this.basePath); } /** * * @summary Connection open-try * @param {ConnectionOpenTryReq} connectionOpenTryRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcConnectionsOpenTryPost(connectionOpenTryRequestBody, options) { return IBCApiFp(this.configuration).ibcConnectionsOpenTryPost(connectionOpenTryRequestBody, options)(this.axios, this.basePath); } /** * * @summary Query header * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcHeaderGet(options) { return IBCApiFp(this.configuration).ibcHeaderGet(options)(this.axios, this.basePath); } /** * * @summary Query node consensus-state * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcNodeStateGet(options) { return IBCApiFp(this.configuration).ibcNodeStateGet(options)(this.axios, this.basePath); } /** * * @summary Receive packet * @param {ReceivedPacketReq} receivePacketRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPacketsReceivePost(receivePacketRequestBody, options) { return IBCApiFp(this.configuration).ibcPacketsReceivePost(receivePacketRequestBody, options)(this.axios, this.basePath); } /** * * @summary Query IBC path * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPathGet(options) { return IBCApiFp(this.configuration).ibcPathGet(options)(this.axios, this.basePath); } /** * * @summary Channel close-confirm * @param {string} portId Port ID * @param {string} channelId Channel ID * @param {ChannelCloseConfirmReq} channelCloseConfirmRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPortsPortIdChannelsChannelIdCloseConfirmPost(portId, channelId, channelCloseConfirmRequestBody, options) { return IBCApiFp(this.configuration).ibcPortsPortIdChannelsChannelIdCloseConfirmPost(portId, channelId, channelCloseConfirmRequestBody, options)(this.axios, this.basePath); } /** * * @summary Channel close-init * @param {string} portId Port ID * @param {string} channelId Channel ID * @param {ChannelCloseInitReq} channelCloseInitRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPortsPortIdChannelsChannelIdCloseInitPost(portId, channelId, channelCloseInitRequestBody, options) { return IBCApiFp(this.configuration).ibcPortsPortIdChannelsChannelIdCloseInitPost(portId, channelId, channelCloseInitRequestBody, options)(this.axios, this.basePath); } /** * * @summary Query channel * @param {string} portId Port ID * @param {string} channelId Channel ID * @param {boolean} [prove] Proof of result * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPortsPortIdChannelsChannelIdGet(portId, channelId, prove, options) { return IBCApiFp(this.configuration).ibcPortsPortIdChannelsChannelIdGet(portId, channelId, prove, options)(this.axios, this.basePath); } /** * * @summary Query next sequence receive * @param {string} portId Port ID * @param {string} channelId Channel ID * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPortsPortIdChannelsChannelIdNextSequenceRecvGet(portId, channelId, options) { return IBCApiFp(this.configuration).ibcPortsPortIdChannelsChannelIdNextSequenceRecvGet(portId, channelId, options)(this.axios, this.basePath); } /** * * @summary Channel open-ack * @param {string} portId Port ID * @param {string} channelId Channel ID * @param {ChannelOpenAckReq} channelOpenAckRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPortsPortIdChannelsChannelIdOpenAckPost(portId, channelId, channelOpenAckRequestBody, options) { return IBCApiFp(this.configuration).ibcPortsPortIdChannelsChannelIdOpenAckPost(portId, channelId, channelOpenAckRequestBody, options)(this.axios, this.basePath); } /** * * @summary Channel open-confirm * @param {string} portId Port ID * @param {string} channelId Channel ID * @param {ChannelOpenConfirmReq} channelOpenConfirmRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPortsPortIdChannelsChannelIdOpenConfirmPost(portId, channelId, channelOpenConfirmRequestBody, options) { return IBCApiFp(this.configuration).ibcPortsPortIdChannelsChannelIdOpenConfirmPost(portId, channelId, channelOpenConfirmRequestBody, options)(this.axios, this.basePath); } /** * * @summary Transfer token * @param {string} portId Port ID * @param {string} channelId Channel ID * @param {TransferTokenReq} transferTokenRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof IBCApi */ ibcPortsPortIdChannelsChannelIdTransferPost(portId, channelId, transferTokenRequestBody, options) { return IBCApiFp(this.configuration).ibcPortsPortIdChannelsChannelIdTransferPost(portId, channelId, transferTokenRequestBody, options)(this.axios, this.basePath); } }
JavaScript
class MintApi extends BaseAPI { /** * * @summary Current minting annual provisions value * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MintApi */ mintingAnnualProvisionsGet(options) { return MintApiFp(this.configuration).mintingAnnualProvisionsGet(options)(this.axios, this.basePath); } /** * * @summary Current minting inflation value * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MintApi */ mintingInflationGet(options) { return MintApiFp(this.configuration).mintingInflationGet(options)(this.axios, this.basePath); } /** * * @summary Minting module parameters * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MintApi */ mintingParametersGet(options) { return MintApiFp(this.configuration).mintingParametersGet(options)(this.axios, this.basePath); } }
JavaScript
class SlashingApi extends BaseAPI { /** * * @summary Get the current slashing parameters * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SlashingApi */ slashingParametersGet(options) { return SlashingApiFp(this.configuration).slashingParametersGet(options)(this.axios, this.basePath); } /** * Get sign info of all validators * @summary Get sign info of given all validators * @param {number} page Page number * @param {number} limit Maximum number of items per page * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SlashingApi */ slashingSigningInfosGet(page, limit, options) { return SlashingApiFp(this.configuration).slashingSigningInfosGet(page, limit, options)(this.axios, this.basePath); } /** * Send transaction to unjail a jailed validator * @summary Unjail a jailed validator * @param {string} validatorAddr Bech32 validator address * @param {UnjailReq} unjailBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SlashingApi */ slashingValidatorsValidatorAddrUnjailPost(validatorAddr, unjailBody, options) { return SlashingApiFp(this.configuration).slashingValidatorsValidatorAddrUnjailPost(validatorAddr, unjailBody, options)(this.axios, this.basePath); } }
JavaScript
class StakingApi extends BaseAPI { /** * * @summary Get all delegations from a delegator * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrDelegationsGet(delegatorAddr, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrDelegationsGet(delegatorAddr, options)(this.axios, this.basePath); } /** * * @summary Submit delegation * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {DelegateReq} [delegation] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrDelegationsPost(delegatorAddr, delegation, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrDelegationsPost(delegatorAddr, delegation, options)(this.axios, this.basePath); } /** * * @summary Query the current delegation between a delegator and a validator * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrDelegationsValidatorAddrGet(delegatorAddr, validatorAddr, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrDelegationsValidatorAddrGet(delegatorAddr, validatorAddr, options)(this.axios, this.basePath); } /** * * @summary Submit a redelegation * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {RedelegationReq} [delegation] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrRedelegationsPost(delegatorAddr, delegation, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrRedelegationsPost(delegatorAddr, delegation, options)(this.axios, this.basePath); } /** * * @summary Get all unbonding delegations from a delegator * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrUnbondingDelegationsGet(delegatorAddr, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrUnbondingDelegationsGet(delegatorAddr, options)(this.axios, this.basePath); } /** * * @summary Submit an unbonding delegation * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {UndelegateReq} [delegation] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrUnbondingDelegationsPost(delegatorAddr, delegation, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrUnbondingDelegationsPost(delegatorAddr, delegation, options)(this.axios, this.basePath); } /** * * @summary Query all unbonding delegations between a delegator and a validator * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrUnbondingDelegationsValidatorAddrGet(delegatorAddr, validatorAddr, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrUnbondingDelegationsValidatorAddrGet(delegatorAddr, validatorAddr, options)(this.axios, this.basePath); } /** * * @summary Query all validators that a delegator is bonded to * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrValidatorsGet(delegatorAddr, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrValidatorsGet(delegatorAddr, options)(this.axios, this.basePath); } /** * * @summary Query a validator that a delegator is bonded to * @param {string} delegatorAddr Bech32 AccAddress of Delegator * @param {string} validatorAddr Bech32 ValAddress of Delegator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingDelegatorsDelegatorAddrValidatorsValidatorAddrGet(delegatorAddr, validatorAddr, options) { return StakingApiFp(this.configuration).stakingDelegatorsDelegatorAddrValidatorsValidatorAddrGet(delegatorAddr, validatorAddr, options)(this.axios, this.basePath); } /** * * @summary Get the current staking parameter values * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingParametersGet(options) { return StakingApiFp(this.configuration).stakingParametersGet(options)(this.axios, this.basePath); } /** * * @summary Get the current state of the staking pool * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingPoolGet(options) { return StakingApiFp(this.configuration).stakingPoolGet(options)(this.axios, this.basePath); } /** * * @summary Get all redelegations (filter by query params) * @param {string} [delegator] Bech32 AccAddress of Delegator * @param {string} [validatorFrom] Bech32 ValAddress of SrcValidator * @param {string} [validatorTo] Bech32 ValAddress of DstValidator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingRedelegationsGet(delegator, validatorFrom, validatorTo, options) { return StakingApiFp(this.configuration).stakingRedelegationsGet(delegator, validatorFrom, validatorTo, options)(this.axios, this.basePath); } /** * * @summary Get all validator candidates. By default it returns only the bonded validators. * @param {string} [status] The validator bond status. Must be either \&#39;bonded\&#39;, \&#39;unbonded\&#39;, or \&#39;unbonding\&#39;. * @param {number} [page] The page number. * @param {number} [limit] The maximum number of items per page. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingValidatorsGet(status, page, limit, options) { return StakingApiFp(this.configuration).stakingValidatorsGet(status, page, limit, options)(this.axios, this.basePath); } /** * * @summary Get all delegations from a validator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingValidatorsValidatorAddrDelegationsGet(validatorAddr, options) { return StakingApiFp(this.configuration).stakingValidatorsValidatorAddrDelegationsGet(validatorAddr, options)(this.axios, this.basePath); } /** * * @summary Query the information from a single validator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingValidatorsValidatorAddrGet(validatorAddr, options) { return StakingApiFp(this.configuration).stakingValidatorsValidatorAddrGet(validatorAddr, options)(this.axios, this.basePath); } /** * * @summary Get all unbonding delegations from a validator * @param {string} validatorAddr Bech32 OperatorAddress of validator * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StakingApi */ stakingValidatorsValidatorAddrUnbondingDelegationsGet(validatorAddr, options) { return StakingApiFp(this.configuration).stakingValidatorsValidatorAddrUnbondingDelegationsGet(validatorAddr, options)(this.axios, this.basePath); } }
JavaScript
class SupplyApi extends BaseAPI { /** * * @summary Total supply of a single coin denomination * @param {string} denomination Coin denomination * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SupplyApi */ supplyTotalDenominationGet(denomination, options) { return SupplyApiFp(this.configuration).supplyTotalDenominationGet(denomination, options)(this.axios, this.basePath); } /** * * @summary Total supply of coins in the chain * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SupplyApi */ supplyTotalGet(options) { return SupplyApiFp(this.configuration).supplyTotalGet(options)(this.axios, this.basePath); } }
JavaScript
class TendermintRPCApi extends BaseAPI { /** * * @summary Get a block at a certain height * @param {number} height Block height * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TendermintRPCApi */ blocksHeightGet(height, options) { return TendermintRPCApiFp(this.configuration).blocksHeightGet(height, options)(this.axios, this.basePath); } /** * * @summary Get the latest block * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TendermintRPCApi */ blocksLatestGet(options) { return TendermintRPCApiFp(this.configuration).blocksLatestGet(options)(this.axios, this.basePath); } /** * Get if the node is currently syning with other nodes * @summary Syncing state of node * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TendermintRPCApi */ syncingGet(options) { return TendermintRPCApiFp(this.configuration).syncingGet(options)(this.axios, this.basePath); } /** * * @summary Get a validator set a certain height * @param {number} height Block height * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TendermintRPCApi */ validatorsetsHeightGet(height, options) { return TendermintRPCApiFp(this.configuration).validatorsetsHeightGet(height, options)(this.axios, this.basePath); } /** * * @summary Get the latest validator set * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TendermintRPCApi */ validatorsetsLatestGet(options) { return TendermintRPCApiFp(this.configuration).validatorsetsLatestGet(options)(this.axios, this.basePath); } }
JavaScript
class TransactionsApi extends BaseAPI { /** * Decode a transaction (signed or not) from base64-encoded Amino serialized bytes to JSON * @summary Decode a transaction from the Amino wire format * @param {DecodeReq} tx * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TransactionsApi */ txsDecodePost(tx, options) { return TransactionsApiFp(this.configuration).txsDecodePost(tx, options)(this.axios, this.basePath); } /** * Encode a transaction (signed or not) from JSON to base64-encoded Amino serialized bytes * @summary Encode a transaction to the Amino wire format * @param {EncodeReq} tx * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TransactionsApi */ txsEncodePost(tx, options) { return TransactionsApiFp(this.configuration).txsEncodePost(tx, options)(this.axios, this.basePath); } /** * Search transactions by events. * @summary Search transactions * @param {string} [messageAction] transaction events such as \&#39;message.action&#x3D;send\&#39; which results in the following endpoint: \&#39;GET /txs?message.action&#x3D;send\&#39;. note that each module documents its own events. look for xx_events.md in the corresponding cosmos-sdk/docs/spec directory * @param {string} [messageSender] transaction tags with sender: \&#39;GET /txs?message.action&#x3D;send&amp;message.sender&#x3D;cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv\&#39; * @param {number} [page] Page number * @param {number} [limit] Maximum number of items per page * @param {number} [txMinheight] transactions on blocks with height greater or equal this value * @param {number} [txMaxheight] transactions on blocks with height less than or equal this value * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TransactionsApi */ txsGet(messageAction, messageSender, page, limit, txMinheight, txMaxheight, options) { return TransactionsApiFp(this.configuration).txsGet(messageAction, messageSender, page, limit, txMinheight, txMaxheight, options)(this.axios, this.basePath); } /** * Retrieve a transaction using its hash. * @summary Get a Tx by hash * @param {string} hash Tx hash * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TransactionsApi */ txsHashGet(hash, options) { return TransactionsApiFp(this.configuration).txsHashGet(hash, options)(this.axios, this.basePath); } /** * Broadcast a signed tx to a full node * @summary Broadcast a signed tx * @param {BroadcastReq} txBroadcast * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TransactionsApi */ txsPost(txBroadcast, options) { return TransactionsApiFp(this.configuration).txsPost(txBroadcast, options)(this.axios, this.basePath); } }
JavaScript
class SingleMetricsController extends BaseController { /** * Single Metrics Controller * @param {object} params - SingleMetricsController parameters * @param {express} params.app - Express app * @param {object} params.metric - A metric with name and value for which the endpoint is made * @constructor */ constructor(params) { super(params); this.id = 'SingleMetricsController'; this._app = params.app; this._metric = params.metric; this._addEndpoint(); } /** * Exposes tne endpoint to collect the metric */ _addEndpoint() { this._app.get('/v1/metric/' + this._metric.metricName, (req, res) => { let response = { metricName: this._metric.metricName, value: this._metric.getValue() }; this.render(res, response, HTTPStatus.OK); }); } }
JavaScript
class ApacheHandler extends WebServerHandler { constructor(options) { super(options); _.assign(this, { user: apacheCore.systemUser, group: apacheCore.systemGroup, httpPort: apacheCore.httpPort, httpsPort: apacheCore.httpsPort, configureModules: apacheCore.configureModules, config: new Config(), moduleObject: new Module(), }, _.pick( apacheCore, ['installdir', 'confDir', 'binDir', 'dataDir', 'logsDir', 'libDir', 'persistDir'] )); } module(mod) { const _module = _.isPlainObject(mod) ? {name: mod.name, id: mod.id} : {name: mod, id: mod}; return _.assign(this.moduleObject, _module); } /** * Restart the Apache server * @function handler.webservers.apache~restart * @example * restart(); */ restart() { this.logger.debug('Restarting apache...'); return apacheCore.restart(); } /** * Reload configuration * @function handler.webservers.apache~reload * @example * reload(); */ reload() { this.logger.debug('Reloading apache configuration...'); return apacheCore.reload(); } /** * Start the Apache server * @function handler.webservers.apache~start * @example * start(); */ start() { this.logger.debug('Starting apache...'); return apacheCore.start(); } /** * Stop the Apache server * @function handler.webservers.apache~stop * @example * stop(); */ stop() { this.logger.debug('Stopping apache...'); return apacheCore.stop(); } /** * Get the status of the Apache server * @function handler.webservers.apache~status * @example * status(); */ status() { return apacheCore.status(); } _getHostText(hosts, port) { if (!_.isArray(hosts)) hosts = [hosts]; return _.map(hosts, (h) => ` ${h}:${port}`).join(' '); } /** * Add a virtual host for an application * @function handler.webservers.apache~addAppVhost * @param {string} name - Application name for which configure the virtual host * @param {Object} [options] - Options object * @param {string} [options.type] - Application runtime type (php, java, node, python, ruby) * @param {string[]} [options.hosts=127.0.0.1, _default_] - Server hosts * @param {number} [options.port] - HTTP port * @param {string} [options.documentRoot] - Application document root * @param {string} [options.requireOption] - Application Require option * @param {boolean} [options.moveHtaccess=true] - Move application htaccess to a configuration file * @param {boolean} [options.enableHttps=true] - Create another virtual Host using HTTPS certificates * @param {number} [options.httpsPort] - HTTPS port * @param {string} [options.certificatePath='conf/qingcloud/certs/'] - Path to server.crt and server.key files * @param {string} [options.extraDirectoryConfiguration] - Additional configuration in the document root directory * @example * // Configure default vhost file * addAppVhost('drupal'); */ addAppVhost(name, options) { options = _.defaults(options || {}, { type: 'php', hosts: ['127.0.0.1', '_default_'], port: apacheCore.httpPort, documentRoot: $file.join($file.dirname(this.cwd), name), requireOption: 'all granted', moveHtaccess: true, enableHttps: true, httpsPort: apacheCore.httpsPort, certificatePath: $file.join(apacheCore.confDir, 'qingcloud/certs/'), extraDirectoryConfiguration: '', additionalConfiguration: '', }); if (options.moveHtaccess) apacheCore.replaceHtaccessFiles(name); if ($file.exists($file.join(apacheCore.htaccessDir, `${name}-htaccess.conf`))) { options.allowOverride = 'None'; options.htaccess = `Include ${$file.join(apacheCore.htaccessDir, `${name}-htaccess.conf`)}`; } else { options.allowOverride = 'All'; options.htaccess = ''; } apacheCore.addVhost(name, { vhostText: $hb.render( $file.join(__dirname, 'vhosts', `httpd-vhost-${options.type}.conf.tpl`), _.defaults({hostText: this._getHostText(options.hosts, options.port)}, options) ), }); if (options.enableHttps) { options.sslInfo = `SSLEngine on SSLCertificateFile "${options.certificatePath}/server.crt" SSLCertificateKeyFile "${options.certificatePath}/server.key"`; options.port = options.httpsPort; apacheCore.addVhost(`${name}-https`, { vhostText: $hb.render( $file.join(__dirname, 'vhosts', `httpd-vhost-${options.type}.conf.tpl`), _.defaults({hostText: this._getHostText(options.hosts, options.port)}, options) ), }); } apacheCore.reload(); } /** * Set the application installing page * @function handler.webservers.apache~setInstallingPage * @example * // Add installing page * setInstallingPage(); */ setInstallingPage() { const tmpDir = $os.createTempDir(); $file.copy($file.join(__dirname, '../../loading_page/*'), tmpDir); apacheCore.addVhost('__loading', { vhostText: $hb.render( $file.join(__dirname, 'vhosts/loading-page-vhost.conf.tpl'), {hostText: `_default_:${apacheCore.httpPort}`, documentRoot: tmpDir} ), }); apacheCore.reload(); } /** * Remove the application installing page * @function handler.webservers.apache~removeInstallingPage * @example * // Remove installing page * removeInstallingPage(); */ removeInstallingPage() { apacheCore.removeVhost('__loading'); apacheCore.reload(); } }
JavaScript
class ClientSink extends BaseSink { /** * Registers an instance of this class as a logging sink with the main * `@bayou/see-all` module. */ static init() { SeeAll.theOne.add(new ClientSink()); } /** * Writes a log record to the console. * * @param {LogRecord} logRecord The record to write. */ _impl_sinkLog(logRecord) { if (logRecord.isTime()) { // Special colorful markup for timestamps. this._logTime(logRecord); return; } const payload = logRecord.payload; const [prefixFormat, ...args] = this._makePrefix(logRecord); const formatStr = [prefixFormat]; // We append to this array and `args`. let logMethod; switch (payload.name) { case 'error': { logMethod = 'error'; break; } case 'warn': { logMethod = 'warn'; break; } default: { logMethod = 'log'; break; } } function formatValue(value) { if (value instanceof Functor) { // Handle functors specially, so that they look "functorish" rather // than being undifferentiated "decomposed objects." formatStr.push('%s('); args.push(value.name); let first = true; for (const a of value.args) { if (first) { first = false; } else { formatStr.push(', '); } formatValue(a); } formatStr.push(')'); } else { formatStr.push('%o'); args.push(value); } } if (logRecord.isEvent()) { const metricName = logRecord.metricName; if (metricName === null) { formatStr.push('%c '); args.push('color: #840; font-weight: bold'); formatValue(payload); } else { const metricArgs = logRecord.payload.args; const label = `${metricName}${(metricArgs.length === 0) ? '' : ': '}`; formatStr.push('%c %s'); args.push('color: #503; font-weight: bold'); args.push(label); switch (metricArgs.length) { case 0: { break; } case 1: { formatValue(metricArgs[0]); break; } default: { formatValue(metricArgs); break; } } } } else { for (const a of payload.args) { switch (typeof a) { case 'function': case 'object': { formatStr.push(' '); formatValue(a); break; } default: { formatStr.push(' %s'); args.push(a); break; } } } } console[logMethod](formatStr.join(''), ...args); if (payload.name === 'debug') { // The browser's `console` methods _mostly_ do the right thing with regard // to providing distinguishing markings and stack traces when appropriate. // We just disagree about `debug`, so in that case we include an explicit // trace in a "group." console.groupCollapsed('stack trace'); console.trace('stack trace'); console.groupEnd(); } } /** * Logs the indicated time record. * * @param {LogRecord} logRecord Log record, which must be for a time. */ _logTime(logRecord) { const [utc, local] = logRecord.timeStrings; console.log(`%c[time] %c${utc} %c/ %c${local}`, 'color: #999; font-weight: bold', 'color: #66a; font-weight: bold', 'color: #999; font-weight: bold', 'color: #99e; font-weight: bold'); } /** * Constructs a prefix header for the given record. The return value is an * array suitable for passing to a `log()` method, including an initial format * string and additional arguments as appropriate. * * @param {LogRecord} logRecord The log record in question. * @returns {array<string>} The prefix. */ _makePrefix(logRecord) { // Color the prefix depending on the event name / severity level. let prefixColor; switch (logRecord.payload.name) { case 'error': { prefixColor = '#a44'; break; } case 'warn': { prefixColor = '#a70'; break; } default: { prefixColor = '#999'; break; } } let formatStr = '%c%s'; const args = [`color: ${prefixColor}; font-weight: bold`, logRecord.prefixString]; if (logRecord.contextString !== null) { formatStr += '%c%s'; args.push('color: #44e; font-weight: bold'); args.push(` ${logRecord.contextString}`); } // Reset the style at the end. formatStr += '%c'; args.push(''); return [formatStr, ...args]; } }
JavaScript
class User { constructor() { this.id = ""; this.first_name = ""; this.last_name = ""; this.email = ""; this.type = 0; this.avatar = "empty.png"; this.access_token = ""; } set(field, value) { this[field] = value; } get(field) { if (this[field]) { return this[field]; } } parse(auth_user) { this.id = auth_user.id; this.first_name = auth_user.first_name; this.last_name = auth_user.last_name; this.email = auth_user.email; this.type = auth_user.type; this.avatar = auth_user.avatar; } logged() { return this.access_token != "" ? true : false; } }
JavaScript
class Home { // # // # // ### ## ### // # # # ## # // ## ## # // # ## ## // ### /** * Processes the request. * @param {Express.Request} req The request. * @param {Express.Response} res The response. * @returns {Promise} A promise that resolves when the request is complete. */ static async get(req, res) { const standings = await Team.getSeasonStandings(), stats = await Player.getTopKda(), matches = await Match.getCurrent(), teams = new Teams(); let news; try { const discordNews = await Discord.announcementsChannel.messages.fetch({limit: 5}); news = discordNews.map((m) => { m.content = DiscordMarkdown.toHTML(m.content, {discordCallback: {user: (user) => `@${Discord.findGuildMemberById(user.id).displayName}`, channel: (channel) => `#${Discord.findChannelById(channel.id).name}`, role: (role) => `@${Discord.findRoleById(role.id).name}`, emoji: () => ""}}); return m; }); } catch (err) { news = []; } standings.forEach((standing) => { teams.getTeam(standing.teamId, standing.name, standing.tag, standing.disbanded, standing.locked); }); stats.forEach((stat) => { teams.getTeam(stat.teamId, stat.name, stat.tag, stat.disbanded, stat.locked); }); res.status(200).send(await Common.page( "", {css: ["/css/home.css"]}, HomeView.get({ standings, stats, matches, news, teams }), req )); } }
JavaScript
class NotImplementedError extends Error { constructor(className, methodName) { super("Method '"+methodName+"' not implemented in class '"+className+"'.") this.name = this.constructor.name } }
JavaScript
class Column extends Component { constructor(props) { super(props); this.state = { width: COLUMN_WIDTH, }; } /** * Placeholder to handle column's right side being dragged to new width */ handleDrag() { const width = COLUMN_WIDTH; if (this.props.setWidth !== null) { this.props.setWidth(width); } this.setState({width: width}); } render() { const navStyle = {width: `${this.state.width}em`}; const gripStyle = {left: `${this.state.width}em`}; return ( <Fragment> <div className={css(styles.column)} style={navStyle}> {this.props.children} </div> <div className={css(styles.grip)} style={gripStyle}/> </Fragment> ); } }
JavaScript
class Hello { constructor(params) { this._params = params || {}; this._say = (this._params['http://example.org/hello/say'] || ['World'])[0]; this._hello = (this._params['http://example.org/hello/hello'] || ['Hello'])[0]; } run() { console.log(this._hello + ' ' + this._say); } }
JavaScript
class CreateProblem extends Component { constructor(props) { super(props); this.state = { title :'', category :'', description: '', solutions :[], tags: [], file :'', submitted : false , errors: new Map(), editorState: EditorState.createEmpty(), value : RichTextEditor.createEmptyValue(), statement : RichTextEditor.createEmptyValue(), inputFormat :RichTextEditor.createEmptyValue(), outputFormat :RichTextEditor.createEmptyValue(), contsraints :RichTextEditor.createEmptyValue(), challengeName : '', text :'', challengeDescription :'', challengeLevel :'', challengeType :'', challengeScore :Number, challengelanguage :'', }; } componentWillMount() { let errors = new Map(); errors.set('name', ''); errors.set('description', ''); errors.set('level', ''); errors.set('type', ''); errors.set('score', ''); this.setState({errors: errors}); } //***********************************// componentWillReceiveProps(nextProps) { this.props.paneActions.textEditor.updateTextValue(this.state.value.toString('html')); const newValue = nextProps.paneData.getIn(['text_editor', 'value']); this.setState({statement: RichTextEditor.createValueFromString(newValue, 'html')}); } //********************************// handleChange(text, medium) { this.setState({text: text}); } //**********************// //onChange = (editorState) => this.setState({editorState}); //******************************// onChange = (value) => { console.log("value" + value); this.setState({statement :value}); if (this.props.onChange) { // Send the changes up to the parent component as an HTML string. // This is here to demonstrate using `.toString()` but in a real app it // would be better to avoid generating a string on each change. this.props.onChange( value.toString('html') ); } }; handleChange(tags) { this.setState({tags}) } handleChallengeType(e) { console.log(e.target.value); this.setState({challengeType :value}); } //*******************************// renderErrorMsg(data) { console.log('data' + data); return (data ? <ErrorMsg> {data } </ErrorMsg> : null); } //***********************************// //****************************************// checkName =(e)=>{ let value = e.target.value; let errors = this.state.errors; let submitted = this.state.submitted ; if(submitted==true) { if(value =='') { console.log("empty password"); errors.set('name','Challenge Name is empty! Please provide a name') this.setState({errors:errors}) }else if(value.length<3) { console.log("name length min"); errors.set('name','Challenge Name should be at least 3 characters long.') this.setState({errors:errors}) } } this.setState({challengeName :value}); } //*******function to check the type of problem //******* checkType = (e) =>{ let value = e.target.value; console.log("value" + JSON.stringify(value)); this.setState({ challengeType:value}); } //****************************// checkDescription = (e) =>{ let value = e.target.value; console.log("value" + JSON.stringify(value)); this.setState({ challengeDescription:value}); } //****************************// checkLevel = (e) =>{ let value = e.target.value; console.log("value" + JSON.stringify(value)); this.setState({ challengeLevel:value}); } //**************************************// checkScore = (e) =>{ let value = e.target.value; console.log("value" + JSON.stringify(value)); this.setState({ challengeScore:value}); } //**************************************// checkLanguage = (e) =>{ let value = e.target.value; console.log("value" + JSON.stringify(value)); this.setState({ challengelanguage:value}); } //***************function to submit the problem***************// CreateChallenge =( event)=>{ event.preventDefault(); this.setState({submitted :true}) let challengeName = this.state.challengeName ; let challengeDescription = this.state.challengeDescription; let challengeLevel = this.state.challengeLevel ; console.log("clicked "); } render() { let errors = this.state.errors return ( <div className="container"> <div className="row"> <div className="alert alert-light" role="alert"> Create Challenge </div> </div> <hr/> <br/> <br/> <form className="form-inline" onSubmit={this.CreateChallenge} noValidate> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="description">Select Type of Challenge </label> </div> </div> <div className="col-md-8"> <div className="form-group"> <select onChange={(event) => this.checkType(event)} value={this.state.challengeType} className="form-control" id="sel1"> <option value="Problem Solving">Problem Solving</option> <option value="Web-Client">Web-Client</option> <option value="Web-Server">Web-Server</option> </select> </div> </div> </div> <br /> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="description">Select The Programming language </label> </div> </div> <div className="col-md-8"> <div className="form-group"> <select onChange={(event) => this.checkLanguage(event)} value={this.state.challengelanguage} className="form-control" id="sel1"> <option value="Python">Python</option> <option value="Java">Java</option> <option value="C++">C++</option> <option value="C">C</option> <option value="PHP">PHP</option> </select> </div> </div> </div> <br /> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="name">Challenge Name:</label> </div> </div> <div className="col-md-8"> <div className="form-group"> <input type="text" value={this.state.challengeName} className="form-control" id="name" onChange={(event) => this.checkName(event)} /> </div> </div> </div> { this.renderErrorMsg(errors.get('name'))} <br /> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="description">Description</label> </div> </div> <div className="col-md-8"> <div className="form-group"> <textarea className="form-control" value={this.state.challengeDescription} onChange={(event) => this.checkDescription(event)} rows="5" id="description"></textarea> </div> </div> </div> { this.renderErrorMsg(errors.get('description'))} <br /> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="description">Challenge Difficulty </label> </div> </div> <div className="col-md-8"> <div className="form-group"> <select value={this.state.challengeLevel} onChange={(event) => this.checkLevel(event)} className="form-control" id="sel1"> <option value="Easy">Easy</option> <option value="Medium">Medium</option> <option value="Hard">Hard</option> </select> </div> </div> </div> <br /> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="score">Challenge Score:</label> </div> </div> <div className="col-md-8"> <div className="form-group"> <input type="number" value={this.state.challengeScore} className="form-control" id="score" onChange={(event) => this.checkScore(event)} /> </div> </div> </div> { this.renderErrorMsg(errors.get('name'))} <br /> <br /> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="description">Problem Statement</label> </div> </div> <div className="col-md-8"> <div className="form-group"> </div> </div> </div> <br/> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="description">Problem Statement</label> </div> </div> <div className="col-md-8"> <div className="form-group"> <textarea className="form-control" value={this.state.challengeDescription} onChange={(event) => this.checkDescription(event)} rows="5" id="description"></textarea> </div> </div> </div> <br/> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="description">INput Format</label> </div> </div> <div className="col-md-8"> <div className="form-group"> <textarea className="form-control" value={this.state.challengeDescription} onChange={(event) => this.checkDescription(event)} rows="5" id="description"></textarea> </div> </div> </div> <br/> <div className="row"> <div className="col-md-4"> <div className="form-group"> <label for="description">OutPut Format</label> </div> </div> <div className="col-md-8"> <div className="form-group"> <textarea className="form-control" value={this.state.challengeDescription} onChange={(event) => this.checkDescription(event)} rows="5" id="description"></textarea> </div> </div> </div> <br/> <br /> <br /> <div className="row"> <button type="submit" className="btn btn-success">Add</button> </div> </form> </div> ); } }
JavaScript
class Geolocation { constructor(dialogService) { this.dialogService = dialogService; this.coordinates = null; this.errors = { 'PERMISSION_DENIED':'You have rejected access to your location', 'POSITION_UNAVAILABLE':'Unable to determine your location', 'TIMEOUT':'Service timeout has been reached' } } getLocation() { if (this.coordinates !== null) { return this.coordinates; } let deferred = new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition(success => resolve(success), error => { console.log(error); switch (error.code) { case 1: error = this.errors['PERMISSION_DENIED']; break; case 2: error = this.errors['POSITION_UNAVAILABLE']; break; case 3: error = this.errors['TIMEOUT']; break; default: error = 'Location error'; break; } this.dialogService.open({ viewModel: Prompt, model: error }); reject(error); }) }); // Cache the location this.coordinates = deferred; return deferred; } }
JavaScript
class FakeAudioChart { get options() { return { duration: 10e3, frequencyLow: 42, frequencyHigh: 84 } } updateOptions(newOptions) { // This is the real code... if (newOptions === undefined || Object.keys(newOptions).length === 0) { throw Error('No new options given') } } }
JavaScript
class Manage extends Component{ constructor(props) { super(props); this.state = { pageLoc: "myDatasets", filterDatasetName: "", filterCategory: "", filterSize: "", filterOwner: "", filterPublicPrivate: "" } this.askPermissionHandler = this.askPermissionHandler.bind(this); this.acceptPermissionHandler = this.acceptPermissionHandler.bind(this); this.rejectPermissionHandler = this.rejectPermissionHandler.bind(this); this.loadMail(); } filter = () => { this.setState({ filterCategory: document.getElementById("category").value, filterDatasetName: document.getElementById("datasetName").value, filterSize: document.getElementById("size").value, filterOwner: document.getElementById("owner").value, filterPublicPrivate: document.getElementById("publicPrivate").value, }); this.forceUpdate(); }; //<editor-fold desc="Mail Module Logic"> //<editor-fold desc="Ask Permission"> askPermissionHandler(e){ //get td id and extract inner html let id = e.target.id.split('-')[1]; let datasetName = document.getElementById("managePermissionDatasetName-"+id).innerHTML; console.log(datasetName) this.askPermissionsRequest(datasetName) .then((response)=>{ if(response.status < 400){ console.log('success!'); console.log(response.data['message']); this.loadMail(); } else{ window.alert('uh oh, there\'s a problem!') } }); } askPermissionsRequest(datasetName){ const url = '/api/askPermission?dataset='+datasetName; const config = { headers: { 'content-type': 'multipart/form-data', 'x-access-token': cookies.get('auth-token') } }; return Axios.get(url,config); } //</editor-fold> //<editor-fold desc="Accept Permission"> acceptPermissionHandler(e){ //get td id and extract inner html let id = e.target.id.split('-')[1]; let datasetName = document.getElementById("managePermissionDatasetName-"+id).innerHTML; let email = document.getElementById("managePermissionGrantee-"+id).innerHTML; console.log(datasetName); console.log(email); this.acceptPermissionsRequest(datasetName,email) .then((response)=>{ if(response.status < 400){ console.log('success!'); console.log(response.data['message']); this.loadMail(); } else{ window.alert('uh oh, there\'s a problem!') } }); } acceptPermissionsRequest(datasetName,email){ const url = '/api/acceptPermission?dataset='+datasetName+"&userEmail="+email; const config = { headers: { 'content-type': 'multipart/form-data', 'x-access-token': cookies.get('auth-token') } }; return Axios.get(url,config); } getEmail(){ const url = '/api/getEmail'; const config = { headers: { 'content-type': 'multipart/form-data', 'x-access-token': cookies.get('auth-token') } }; return Axios.get(url,config); } //</editor-fold> //<editor-fold desc="Reject Permission"> rejectPermissionHandler(e){ //get td id and extract inner html let id = e.target.id.split('-')[1]; let datasetName = document.getElementById("managePermissionDatasetName-"+id).innerHTML; let email = document.getElementById("managePermissionGrantee-"+id).innerHTML; console.log(datasetName); console.log(email); this.rejectPermissionsRequest(datasetName,email) .then((response)=>{ if(response.status < 400){ console.log('success!'); console.log(response.data['message']); } else{ window.alert('uh oh, there\'s a problem!') } }); this.loadMail(); } rejectPermissionsRequest(datasetName,email){ const url = '/api/rejectPermission?dataset='+datasetName+"&userEmail="+email; const config = { headers: { 'content-type': 'multipart/form-data', 'x-access-token': cookies.get('auth-token') } }; return Axios.get(url,config); } //</editor-fold> //<editor-fold desc="Load Mail"> loadMail(){ this.loadMailRequest() .then((response)=>{ if(response.status < 400){ let i; let restablesToExplore= response.data["tablesToExplore"]; console.log('gerghrtewghtewr') console.log(response.data["tablesToExplore"]) console.log('gerghrtewghtewr') let tablesToExplore = {"rows": []} for (i = 0; i < response.data["tablesToExploreLen"]; i++) { let y=restablesToExplore[parseInt(i)]; tablesToExplore.rows.push(y) } sessionStorage.setItem('tablesToExplore',JSON.stringify(tablesToExplore)); let resMyDatasets= response.data["myDatasets"]; let myDatasets = {"rows": []} for (i = 0; i < response.data["myDatasetsLen"]; i++) { let y=resMyDatasets[parseInt(i)]; myDatasets.rows.push(y) } sessionStorage.setItem('myDatasets',JSON.stringify(myDatasets)); let resMyPermissions= response.data["myPermissions"]; let myPermissions = {"rows": []} for (i = 0; i < response.data["myPermissionsLen"]; i++) { let y=resMyPermissions[parseInt(i)]; myPermissions.rows.push(y) } sessionStorage.setItem('myPermissions',JSON.stringify(myPermissions)); // let fullName = response.data['User_full_name'] let resAskPermissions= response.data["askPermissions"]; let askPermissions = {"rows": []} for (i = 0; i < response.data["askPermissionsLen"]; i++) { let y=resAskPermissions[parseInt(i)]; //if he is the owner, then it's a request that he needs to approve. //else, it's a request that he asked for and no further action is available // if(y['Owner'].localeCompare(fullName) === 0) // approve.rows.push(y); // else askPermissions.rows.push(y) } sessionStorage.setItem('askPermissions',JSON.stringify(askPermissions)); console.log(response.data["approve"]) let resApprove= response.data["approve"]; let approve = {"rows": []} for (i = 0; i < response.data["approveLen"]; i++) { console.log(resApprove[parseInt(i)]) let y=resApprove[parseInt(i)]; approve.rows.push(y) } sessionStorage.setItem('approve',JSON.stringify(approve)); window.dispatchEvent(new Event("ReloadMail")); } else{ window.alert('uh oh, there\'s a problem!') } }); }; loadMailRequest = () => { const url = '/api/loadMail'; const config = { headers: { 'content-type': 'multipart/form-data', 'x-access-token': cookies.get('auth-token') } }; return Axios.get(url,config); }; //</editor-fold> //</editor-fold> //<editor-fold desc="Tab Switch Logic"> clicked = (id) => { this.setState({pageLoc: id}) this.forceUpdate() }; isInTab = (tab,datasetName) => { let flag = false; JSON.parse(sessionStorage.getItem(tab)).rows.find((iter) => flag |= datasetName.localeCompare(iter['DatasetName']) === 0); return flag; } isInExploreTab = (datasetName) => { return !(this.isInTab('myDatasets',datasetName) || this.isInTab('myPermissions',datasetName) || this.isInTab('askPermissions',datasetName) || this.isInTab('approve',datasetName)); }; //</editor-fold> componentDidMount() { if (sessionStorage.getItem("user").localeCompare("true")!==0) { window.open('/Login', "_self");; } sessionStorage.setItem("dataSet","false"); window.dispatchEvent(new Event("ReloadTable1")); window.dispatchEvent(new Event("ReloadDataSet")); } renderTableHeader = () => { return( <thead> <tr> <td> <Form.Control id={"datasetName"} onChange={this.filter} placeholder={"Dataset Name"} type={"text"}/> </td> <td> <Form.Control id={"category"} onChange={this.filter} placeholder={"Category"} type={"text"}/> </td> <td> <Form.Control id={"size"} onChange={this.filter} placeholder={"Size"} type={"text"}/> </td> <td> <Form.Control id={"owner"} onChange={this.filter} placeholder={"Owner"} type={"text"}/> </td> <td> <Form.Control id={"publicPrivate"} onChange={this.filter} placeholder={"Public/Private"} type={"text"}/> </td> <td hidden={this.state.pageLoc.localeCompare("tablesToExplore") !== 0}> Request Access </td> <td hidden={this.state.pageLoc.localeCompare("approve") !== 0}> Grantee </td> <td hidden={this.state.pageLoc.localeCompare("approve") !== 0}> Grant Access </td> <td hidden={this.state.pageLoc.localeCompare("approve") !== 0}> Deny Access </td> </tr> </thead> ); }; renderTableRow = (row, index) => { return( <tr key={index.toString()}> <td id={'managePermissionDatasetName-'+index}> {row["DatasetName"]} </td> <td>{row["Category"]}</td> <td>{row["Size"]}</td> <td>{row["Owner"]}</td> <td>{row["PublicPrivate"]}</td> <td hidden={this.state.pageLoc.localeCompare("tablesToExplore") !== 0}> <Button className={"btn-hugobot"} id={"askPermission-"+index} onClick={this.askPermissionHandler}> Access </Button> </td> <td hidden={this.state.pageLoc.localeCompare("approve") !== 0} id={'managePermissionGrantee-'+index}> {row["Grantee"]} </td> <td hidden={this.state.pageLoc.localeCompare("approve") !== 0}> <Button className={"btn-hugobot"} id={"acceptPermission-"+index} onClick={this.acceptPermissionHandler}> Grant Access </Button> </td> <td hidden={this.state.pageLoc.localeCompare("approve") !== 0}> <Button className={"btn-hugobot"} id={"rejectPermission-"+index} onClick={this.rejectPermissionHandler}> Deny Access </Button> </td> </tr> ); }; renderTableData = () => { let canLaunch = "approve" in sessionStorage && "askPermissions" in sessionStorage && "askPermissions" in sessionStorage && "askPermissions" in sessionStorage if(canLaunch){ return JSON.parse(sessionStorage.getItem(this.state.pageLoc)).rows.map((iter, index) => { if(this.state.pageLoc.localeCompare("tablesToExplore") !== 0 || this.isInExploreTab(iter['DatasetName'])){ if((this.state.filterSize.localeCompare("") === 0 || parseFloat(this.state.filterSize)>parseFloat(iter["Size"])) &&(this.state.filterDatasetName.localeCompare("") === 0 || iter["DatasetName"].includes(this.state.filterDatasetName)) &&(this.state.filterCategory.localeCompare("") === 0 || iter["Category"].includes(this.state.filterCategory)) &&(this.state.filterOwner.localeCompare("") === 0 || iter["Owner"].includes(this.state.filterOwner)) &&(this.state.filterPublicPrivate.localeCompare("") === 0 || iter["PublicPrivate"].includes(this.state.filterPublicPrivate))) { return this.renderTableRow(iter, index); } else{ return null; } } else{ return null; } }); } }; render() { let that = this; window.addEventListener("ReloadMail", function(){that.forceUpdate()}); return ( <Container fluid={true}> <br/> <br/> <Nav variant={"tabs"}> {/*<HashRouter history={History}>*/} <Button active={this.state.pageLoc.localeCompare("myDatasets") === 0} id={"myDatasets"} className={"nav-link btn-hugobot"} onClick={this.clicked.bind(null,"myDatasets")}> My Datasets </Button> <Button active={this.state.pageLoc.localeCompare("approve") === 0} id={"approve"} className={"nav-link btn-hugobot"} onClick={this.clicked.bind(null,"approve")}> Approve </Button> <Button active={this.state.pageLoc.localeCompare("myPermissions") === 0} id={"myPermissions"} className={"nav-link btn-hugobot"} onClick={this.clicked.bind(null,"myPermissions")}> Shared with me </Button> <Button active={this.state.pageLoc.localeCompare("askPermissions") === 0} id={"askPermissions"} className={"nav-link btn-hugobot"} onClick={this.clicked.bind(null,"askPermissions")}> Pending Approval </Button> <Button active={this.state.pageLoc.localeCompare("tablesToExplore") === 0} id={"tablesToExplore"} className={"nav-link btn-hugobot"} onClick={this.clicked.bind(null,"tablesToExplore")}> Explore... </Button> {/*</HashRouter>*/} </Nav> <br/> <Table striped={true} bordered={true} hover={true}> {this.renderTableHeader()} <tbody> {this.renderTableData()} </tbody> </Table> </Container> ); } }
JavaScript
class MyCompany extends Component { state = { CompanyName: '', CompanyId: '', CompanyType: 0, CompanyTypeDescription: '', CompanyTypeData: [], isSaved : false, } componentWillUnmount(){ this.setState({ CompanyName: '', CompanyId: '', CompanyType: 0, CompanyTypeDescription: '', CompanyTypeData: [], isSaved : false, }) } componentDidMount() { if (!isLoggedIn() && isBrowser ) { window.location.href="/" } const { saveState, state } = this; /** get Account Company Details **/ axios.get(process.env.REACT_APP_API_DATABASE_URL, { params: { tblName: 'tblCompany', queryType: 'getSingleCompanyInfo', companyId: getUser().companyid } }) .then(function (response) { saveState({ CompanyName: response.data.companyName, CompanyId: response.data.companyId, CompanyType: response.data.CompanyType, CompanyTypeDescription: response.data.CompanyTypeDesc }); }) .catch(function (error) { console.log(error); }) .then(function (response) { // always executed console.log(response,`successfull`); }); /** Get All Company Type Details **/ axios.get(process.env.REACT_APP_API_DATABASE_URL, { params: { tblName: 'tblCompanyType', queryType: 'getAllCompanyType' } }) .then(function (response) { // console.log('Company Type Data: '+ JSON.stringify(response.data)); saveState({ CompanyTypeData: response.data }); }) .catch(function (error) { console.log(error); }) .then(function (response) { // always executed console.log(response,`successfull`); }); } saveState = (data) => { this.setState(data); } onSaveCompany = () => { const { saveState, state } = this; if(window.localStorage.getItem("gatsbyUser") && typeof window !== "undefined"){ // console.log('Company data: '+window.localStorage.getItem("gatsbyUser")); // console.log('Company Id: '+getUser().companyid); } axios({ method: 'get', url: process.env.REACT_APP_API_DATABASE_URL, params: { tblName: 'tblCompany', queryType: 'editSingleCompanyInfo', CompanyID: this.state.CompanyId, EditCompanyName: this.state.CompanyName, CompanyType: this.state.CompanyType } }) .then(function (response) { saveState({ isSaved: true }); console.log(response,`Updating Company Info successfull`); }) .catch(function (error) { console.log(error,`error`); }); } onChangeStatus = (e) => { this.setState({ CompanyName: e.target.value }); // console.log('Change Status: '+e.target.value); } onChangeOption = (e) => { this.setState({ CompanyTypeDescription: e.label, CompanyType: e.value, }); //console.log('Select Optin value: '+ e.label); } render() { const { state, onChangeOption, onChangeStatus, onSaveCompany } = this; return ( <> <SEO title="My Company" /> <div className="content-wrapper px-4 py-4"> <Card> <CardBody> <Container> <Row> <Col breakPoint={{ xs: 12 }}> <h1 className="mb-5">{state.CompanyName}</h1> { state.isSaved ? <Col breakPoint={{ xs: 12 }} className="success text-center"><Alert className="success-message bg-success">Successfully Added New Lead Company</Alert></Col> : false } </Col> </Row> <Row className="justify-content-center align-items-center mb-5"> <Col className="col-lg-8"> <form> <Row> <Col breakPoint={{ xs: 12 }} > <label htmlFor="EditCompanyName">Company Name</label> <Input fullWidth size="Small"> <input type="text" placeholder={state.CompanyName} id="EditCompanyName" value={state.CompanyName} className="EditCompanyName" name="EditCompanyName" onChange ={onChangeStatus.bind(this)}/> </Input> </Col> <Col breakPoint={{ xs: 12 }}> <label htmlFor="EditCompanyType">Company Type</label> <SelectStyled options={state.CompanyTypeData.map(({ CompanyTypeID, CompanyTypeDesc }) => { return { value: CompanyTypeID, label: CompanyTypeDesc }; })} placeholder={state.CompanyTypeDescription} id="EditCompanyType" name="EditCompanyType" value={state.CompanyId} onChange ={onChangeOption.bind(this)} /> </Col> <Col breakPoint={{ xs: 12 }} > <Button status="Success" type="button" shape="SemiRound" onClick={onSaveCompany} fullWidth>Save</Button> </Col> </Row> </form> </Col> </Row> </Container> </CardBody> </Card> </div> </> ); } }
JavaScript
class Employee extends Person { /** * @constructor * @param {Object} obj The object passed to constructor */ constructor(obj) { if (!obj) { super(null); this.department = null; this.dependents = null; this.hiredAt = null; this.joiningDay = 'Monday'; this.salary = null; this.workingDays = null; this.boss = null; } else { super(obj); this.department = (obj.department !== undefined && obj.department !== null) ? obj.department : null; this.dependents = (obj.dependents !== undefined && obj.dependents !== null) ? obj.dependents.map(model => new Person(model)) : null; this.hiredAt = (obj.hiredAt !== undefined && obj.hiredAt !== null) ? new Date(obj.hiredAt).toUTCString() : null; this.joiningDay = (obj.joiningDay !== undefined && obj.joiningDay !== null) ? obj.joiningDay : null; this.salary = (obj.salary !== undefined && obj.salary !== null) ? obj.salary : null; this.workingDays = (obj.workingDays !== undefined && obj.workingDays !== null) ? obj.workingDays : null; this.boss = (obj.boss !== undefined && obj.boss !== null) ? obj.boss : null; } } }
JavaScript
class PmfApp { /** * * @param component the vue component */ constructor(component) { Vue.use(VueI18n); // Create VueI18n instance with options const i18n = new VueI18n({ locale: 'th', // set locale messages: { th: lang }, // set locale messages }); Vue.use(ElementUI,{ i18n: (key, value) => i18n.t(key, value) }); Vue.component(FormSection.name, FormSection); Vue.component(PmfAlert.name, PmfAlert); Vue.component(AppPanel.name, AppPanel); Vue.component(component.name, component); // Create a Vue instance with `i18n` option this.instance = new Vue({ el: '#app', i18n: i18n }); } }
JavaScript
class Dialog extends Component { /** * @param {Object} [props] * @param {(boolean|string)} [props.backdrop='static'] The kind of modal backdrop * to use (see Bootstrap documentation). * @param {string} [props.contentClass] Class to add to the dialog * @param {boolean} [props.fullscreen=false] Whether the dialog should be * open in fullscreen mode (the main usecase is mobile). * @param {boolean} [props.renderFooter=true] Whether the dialog footer * should be rendered. * @param {boolean} [props.renderHeader=true] Whether the dialog header * should be rendered. * @param {string} [props.size='large'] 'extra-large', 'large', 'medium' * or 'small'. * @param {string} [props.stopClicks=true] whether the dialog should stop * the clicks propagation outside of itself. * @param {string} [props.subtitle=''] * @param {string} [props.title='Odoo'] * @param {boolean} [props.technical=true] If set to false, the modal will have * the standard frontend style (use this for non-editor frontend features). */ constructor() { super(...arguments); this.modalRef = useRef('modal'); this.footerRef = useRef('modal-footer'); useExternalListener(window, 'keydown', this._onKeydown); } mounted() { this.constructor.display(this); // TODO: this.env.bus.on('close_dialogs', this, this._close); if (this.props.renderFooter) { // Set up main button : will first look for an element with the // 'btn-primary' class, then a 'btn' class, then the first button // element. let mainButton = this.footerRef.el.querySelector('.btn.btn-primary'); if (!mainButton) { mainButton = this.footerRef.el.querySelector('.btn'); } if (!mainButton) { mainButton = this.footerRef.el.querySelector('button'); } if (mainButton) { this.mainButton = mainButton; this.mainButton.addEventListener('keydown', this._onMainButtonKeydown.bind(this)); this.mainButton.focus(); } } this._removeTooltips(); } willUnmount() { // TODO: this.env.bus.off('close_dialogs', this, this._close); this._removeTooltips(); this.constructor.hide(this); } //-------------------------------------------------------------------------- // Getters //-------------------------------------------------------------------------- /** * @returns {string} */ get size() { return SIZE_CLASSES[this.props.size]; } //-------------------------------------------------------------------------- // Private //-------------------------------------------------------------------------- /** * Send an event signaling that the dialog must be closed. * @private */ _close() { this.trigger('dialog-closed'); } /** * Remove any existing tooltip present in the DOM. * @private */ _removeTooltips() { for (const tooltip of document.querySelectorAll('.tooltip')) { tooltip.remove(); // remove open tooltip if any to prevent them staying when modal is opened } } //-------------------------------------------------------------------------- // Handlers //-------------------------------------------------------------------------- /** * @private * @param {MouseEvent} ev */ _onBackdropClick(ev) { if (!this.props.backdrop || ev.target !== ev.currentTarget) { return; } if (this.props.backdrop === 'static') { if (this.mainButton) { this.mainButton.focus(); } } else { this._close(); } } /** * @private * @param {MouseEvent} ev */ _onClick(ev) { if (this.props.stopClicks) { ev.stopPropagation(); } } /** * @private */ _onFocus() { if (this.mainButton) { this.mainButton.focus(); } } /** * Manage the TAB key on the main button. If the focus is on a primary * button and the user tries to tab to go to the next button : a tooltip * will be displayed. * @private * @param {KeyboardEvent} ev */ _onMainButtonKeydown(ev) { if (ev.key === 'Tab' && !ev.shiftKey) { ev.preventDefault(); $(this.mainButton) .tooltip({ delay: { show: 200, hide: 0 }, title: () => this.env.qweb.renderToString('web.DialogButton.tooltip', { title: this.mainButton.innerText.toUpperCase(), }), trigger: 'manual', }) .tooltip('show'); } } /** * @private * @param {KeyboardEvent} ev */ _onKeydown(ev) { if ( ev.key === 'Escape' && !['INPUT', 'TEXTAREA'].includes(ev.target.tagName) && this.constructor.displayed[this.constructor.displayed.length - 1] === this ) { ev.preventDefault(); ev.stopImmediatePropagation(); ev.stopPropagation(); this._close(); } } //-------------------------------------------------------------------------- // Static //-------------------------------------------------------------------------- /** * Push the given dialog at the end of the displayed list then set it as * active and all the others as passive. * @param {(LegacyDialog|OwlDialog)} dialog */ static display(dialog) { const activeDialog = this.displayed[this.displayed.length - 1]; if (activeDialog) { // Deactivate previous dialog const activeDialogEl = activeDialog instanceof this ? // Owl dialog activeDialog.modalRef.el : // Legacy dialog activeDialog.$modal[0]; activeDialogEl.classList.add('o_inactive_modal'); } // Push dialog this.displayed.push(dialog); // Update body class document.body.classList.add('modal-open'); } /** * Set the given displayed dialog as passive and the last added displayed dialog * as active, then remove it from the displayed list. * @param {(LegacyDialog|OwlDialog)} dialog */ static hide(dialog) { // Remove given dialog from the list this.displayed.splice(this.displayed.indexOf(dialog), 1); // Activate last dialog and update body class const lastDialog = this.displayed[this.displayed.length - 1]; if (lastDialog) { lastDialog.el.focus(); const modalEl = lastDialog instanceof this ? // Owl dialog lastDialog.modalRef.el : // Legacy dialog lastDialog.$modal[0]; modalEl.classList.remove('o_inactive_modal'); } else { document.body.classList.remove('modal-open'); } } }
JavaScript
class StorageApi { constructor(browser) { this.browser = browser } /** * It set the password of the private store. * @param password the password to encrypt/decrypt the data of local storage * @return {Promise<unknown>} a promise that resolves to void */ setPassword(password) { return this.browser.runtime.sendMessage({ hotmoka: { type: 'store-set-pwd', password: password } }) } /** * It initializes the private store. * @return {Promise<unknown>} a promise that resolves to void */ initPrivateStore() { return this.browser.runtime.sendMessage({ hotmoka: { type: 'store-init-private', keys: privateStoreObjectKeys } }) } /** * It persists an object to the private store. * @param key the key of the object * @param data the data object * @return {Promise<boolean>} a promise that resolves to void */ persistToPrivateStore(key, data) { return this.browser.runtime.sendMessage({ hotmoka: { type: 'store-persist-private', data: data, key: key } }) } /** * It persists an object to the public store. * @param key the key of the object * @param data the data object * @return {Promise<void>} a promise that resolves to void */ persistToPublicStore(key, data) { return this.browser.runtime.sendMessage({ hotmoka: { type: 'store-persist-public', data: data, key: key } }) } /** * It returns the data from the store. * @param key an optional key that if specified returns the data associated with that key * @return {Promise<unknown>} a promise that resolves to the result data or undefined if data was not found */ getStore(key) { return this.browser.runtime.sendMessage({ hotmoka: { type: 'store-get', key: key } }) } // helpers /** * Returns the array of accounts. * @return {Promise<unknown>} a promise that resolves to the array of accounts */ async getAccounts() { const accounts = await this.getStore('accounts') if (accounts && Array.isArray(accounts)) { return accounts } return [] } /** * Returns the array of accounts of a network. * @param network the network * @return {Promise<unknown>} a promise that resolves to the array of accounts */ async getAccountsForNetwork(network) { const accounts = await this.getAccounts() return accounts.filter(acc => acc.network.value === network.value) } /** * It adds an account to the list of accounts. * @param account the account object * @return {Promise<void>} a promise that resolves to void */ async addAccount(account) { const accounts = await this.getAccounts() for (const acc of accounts) { if (acc.name === account.name) { throw new Error('Account name already registered') } acc.selected = false acc.logged = false } accounts.push(account) await this.persistToPrivateStore('accounts', accounts) await this.persistToPublicStore('account', { name: account.name, publicKey: account.publicKey }) } /** * It removes an account from the list of accounts. * @param account the account * @return {Promise<void>} a promise that resolves to void */ async removeAccount(account) { const accounts = await this.getAccounts() const accountsToPersist = accounts.filter(acc => acc.publicKey !== account.publicKey) await this.persistToPrivateStore('accounts', accountsToPersist) } /** * It updates an account. * @param account the account * @return {Promise<void>} a promise that resolves to void */ async updateAccount(account) { const accounts = await this.getAccounts() const tempAccounts = accounts.filter(acc => acc.publicKey !== account.publicKey) for (const acc of tempAccounts) { if (acc.name === account.name) { throw new Error('Account name already registered') } } tempAccounts.push(account) await this.persistToPrivateStore('accounts', tempAccounts) await this.persistToPublicStore('account', { name: account.name, publicKey: account.publicKey }) } /** * Returns the current selected account object of a network. * @param network the current network * @return {Promise<unknown>} a promise that resolves to the current account object or throws an err if data was not found */ async getCurrentAccount(network) { const accounts = await this.getAccounts() for (const account of accounts) { if (account.network.value === network.value && account.selected) { return account } } // no account found throw new Error('No account found for this network') } /** * It sets the authentication state of an account to logged or not logged. * @param account the account object * @param logged the authentication state of the account, true if logged, false if not logged * @return {Promise<void>} a promise that resolves to void */ async setAccountAuth(account, logged) { const accounts = await this.getAccounts() accounts.forEach(acc => { if (acc.publicKey === account.publicKey) { acc.logged = logged acc.selected = true } else { acc.logged = false acc.selected = false } }) await this.persistToPrivateStore('accounts', accounts) if (logged) { await this.persistToPublicStore('account', { name: account.name, publicKey: account.publicKey }) } } /** * It performs a logout for all the accounts. * @return {Promise<void>} a promise that resolves to void */ async logoutAllAccounts() { const accounts = await this.getAccounts() accounts.forEach(acc => { acc.logged = false acc.selected = false }) await this.persistToPrivateStore('accounts', accounts) await this.persistToPublicStore('account', null) } /** * Sets the current network as the selected network. * @param network the network object * @return {Promise<void>} a promise that resolves to void */ async selectNetwork(network) { const networks = await this.getNetworks() networks.forEach(network_ => network_.selected = network_.value === network.value) await this.persistToPublicStore('networks', networks) } /** * It adds a network the list of networks. * @param network the network object * @return {Promise<void>} a promise that resolves to void */ async addNetwork(network) { const networks = await this.getNetworks() for (const _network of networks) { if (_network.value === network.value) { throw new Error('Network already registered') } _network.selected = false } networks.push(network) await this.persistToPublicStore('networks', networks) } /** * Returns the array of networks. * @return {Promise<[unknown]>} a promise that resolves to array of networks */ async getNetworks() { const storedNetworks = await this.getStore('networks') if (storedNetworks && Array.isArray(storedNetworks) && storedNetworks.length > 0) { return storedNetworks } else { throw new Error('No network available') } } /** * Returns the current selected network. * @return {Promise<unknown>} a promise that resolves to selected network or to null */ async getCurrentNetwork() { const networks = await this.getNetworks() const selectedNetworks = networks.filter(network => network.selected) const network = selectedNetworks.length > 0 ? selectedNetworks[0] : null if (network) { return network } else { throw new Error('No network selected') } } /** * Returns the authentication object. * @return {Promise<{authenticated: boolean, hasAccount: boolean}>} a promise that resolves to an authentication object */ getAuthentication() { return new Promise(resolve => { this.getStore().then(store => { const result = { authenticated: false, hasAccount: false } if (store && store.account) { result.hasAccount = true if (store.accounts) { store.accounts.forEach(account => { if (account.logged) { result.authenticated = true } }) } } resolve(result) }).catch(() => resolve({ authenticated: false, hasAccount: false })) }).catch(() => {}) } }
JavaScript
class SocketIOEventEmitter extends EventEmitter { /** * Construct the emitter with an socket.io instance. * @param {mixed} io Socket IO instance. */ constructor(io) { super(); this.io = io; } /** * * @param {(string[]|string)} to Target to emit to. * @param {String} event Event name. * @param {String} data Data to send. */ emit(to, event, data) { } }
JavaScript
class BaseDao { static datastore = null; static initDatastoreWith(dbFileName) { // See if pasted db file exists or not let dbPath = this.buildDbPathWith(dbFileName); if (fs.existsSync(dbPath)) { // Nedb won't throw error when creating Datastore instance, // it just set db file path into instance for further use. this.datastore = Datastore.create( this.buildDbCreationOptionWith(dbPath) ); } else { let initError = new DatabaseInitializingError(dbPath, new Error('db file not exists')); logger.error(initError.toString()); throw initError; } } static buildDbCreationOptionWith(filePath) { return { filename: filePath, autoload: true }; } static buildDbPathWith(dbFileName) { return `${DB_FILE_DIR}/${dbFileName}${FILE_SUFFIX}`; } static async getOneById(id, projection = {}) { if (id) { return this.findOne(id, projection); } else { return this.rejectAndLogWarnQueryFormatError(id); } } /* Execute query and handle promise type result. */ static async findOne(id, projection) { return this.datastore.findOne({id: id}, projection).then( result => { let resultIsTrusthyFlag = !!result; return this.checkResultThenReturn(result, resultIsTrusthyFlag, id); }, reason => this.rejectAndLogErrorExecuteFailError(reason)); } static checkResultThenReturn(value, condition, query) { if (condition) { return value; } else { return this.rejectAndLogWarnNoResultError( new Error(`query matched nothing:${JSON.stringify(query)}`)); } } /* Something bad happened inside nedb. Reject with DatabaseQueryExecuteNoResultError, then log it at warn level */ static rejectAndLogWarnNoResultError(query) { let error = new DatabaseQueryExecuteNoResultError( this.getDbNameFrom(this.datastore), query); logger.warn(error.toString()); return Promise.reject(error); } /* Reject with DatabaseQueryExecuteFailError, then log it at error level */ static rejectAndLogErrorExecuteFailError(inner = undefined) { let error = new DatabaseQueryExecuteFailError(inner); logger.error(error.toString()); return Promise.reject(error); } /* Query|id passed to base dao is falsy, can't build a valid query option before execute query. */ static async rejectAndLogWarnQueryFormatError(query) { let error = new DatabaseQueryFormatError(query); logger.warn(error.toString()); return Promise.reject(error); } static getDbNameFrom(datastore) { if (datastore) { let dbFilePath = datastore.__original.filename; let regex = /[a-z]+.nedb/; return dbFilePath.match(regex)[0]; } else { return 'falsy_db_name'; } } static async getManyByQuery(query, projection = {}) { let queryIsTrusthyAndNotEmptyFlag = query && Object.entries(query).length > 0; if (queryIsTrusthyAndNotEmptyFlag) { return this.findMany(query, projection); } else { return this.rejectAndLogWarnQueryFormatError(query); } } static async findMany(query, projection) { return this.datastore.find(query, projection).then( result => this.checkResultThenReturn(result, result.length > 0, query), reason => this.rejectAndLogErrorExecuteFailError(reason) ); } }
JavaScript
class LinearSearch extends Algorithm { /** * sets the collection to to search the value * @param input */ set input(input) { this._input = input; } /** * gets the input collection provided for searching * @returns {*} */ get input() { return this._input; } /** * Finds if a given value as one of the input does exist in the input of * array collection given to search and returns a boolean value * @param {Array} input * @param {number|string|boolean} value * @returns {boolean} */ execute(input, value) { let exists = false; this.input = input; for (let i = 0; i < this.input.length; i += 1) { if (this.input[i] === value) { exists = true; } } return exists; } }
JavaScript
class TemplateWam extends WebAudioModule { /** The Base URL of this file */ _baseURL = new URL('.', import.meta.url).href; /** The URL of the descriptor JSON */ _descriptorUrl = `${this._baseURL}descriptor.json`; /** Merge the descriptor JSON to this */ async _loadDescriptor() { const url = this._descriptorUrl; if (!url) throw new TypeError('Descriptor not found'); const response = await fetch(url); const descriptor = await response.json(); Object.assign(this.descriptor, descriptor); } /** This will be called by the host */ async initialize(state) { await this._loadDescriptor(); return super.initialize(state); } /** This will be called by `super.initialize()` */ async createAudioNode(initialState) { // Prepare all the AudioNodes: const node = new TemplateWamNode(this.audioContext); // Setup our node to get its WAM APIs ready await node.setup(this); // If there is an initial state at construction for this plugin, if (initialState) node.setState(initialState); // Now the WAM is ready return node; } createGui() { return createElement(this); } /** * @param {import('./Gui').TemplateWamElement} el */ destroyGui(el) { el.disconnectedCallback(); } }