language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class View extends Value { constructor(info) { super(); this.info = info || new Null(); } /** clone returns a copy with the stream set to null */ clone() { return new View(this.info); } run(store) { return invoke( store, field(store, this.info, new Text("viewFn")), this.info ); } apply(c) { if (!(c instanceof PathChange)) return super.apply(c); if (!c.path || c.path.length == 0) { return this.apply(c.change); } if (c.path[0] != "info") { throw new Error("unexpected field: " + c.path[0]); } const pc = new PathChange(c.path.slice(1), c.change); return new View(this.info.apply(pc)); } get(key) { if (key != "info") { throw new Error("unexpected key: " + key); } return this.info.clone().setStream(new Substream(this.stream, "info")); } toJSON() { return Encoder.encode(this.info); } static typeName() { return "dotdb.View"; } static fromJSON(decoder, json) { return new View(decoder.decode(json)); } }
JavaScript
class MapStream extends DerivedStream { constructor(base, fn, value) { super(base.stream); this.base = base; this.fn = fn || ((k, v) => v); if (!value) { if (typeof this.base[MapIterator] !== "function") { value = null; } else { value = {}; for (let [key, val] of this.base[MapIterator]()) { value[key] = this.fn(key, val); } } } this._value = value; } append(c) { return this._append(c, false); } reverseAppend(c) { return this._append(c, true); } _append(c, reverse) { // proxy any changes to a field over to this._value const updated = {}; if (!this._appendChanges(c, updated, reverse)) { // TODO: this is not atomic!! updated could have // partially changed at this point. REDO this return null; } const value = Object.assign({}, this._value, updated); const version = new MapStream(this.base, this.fn, value); return {change: c, version}; } get value() { if (!this._value) { return new Null().setStream(this); } const m = {}; for (let key in this._value) { m[key] = this._value[key].clone(); } return new Dict(m).setStream(this); } _getNext() { const basen = this.base.next; if (!this._value) { if (!basen) { return null; } const version = new MapStream(basen.version, this.fn, null); const change = new Replace(this.value.clone(), version.value.clone()); return { change, version }; } if (basen && typeof basen.version[MapIterator] !== "function") { const version = new MapStream(basen.version, this.fn, null); const change = new Replace(this.value.clone(), version.value.clone()); return { change, version }; } const updated = Object.assign({}, this._value); const changes = []; if (basen) { this._updateKeys(basen.version, basen.change, updated, changes); } for (let key in this._value) { if (!updated.hasOwnProperty(key)) continue; const val = this._value[key]; const n = val.next; if (n) { changes.push(new PathChange([key], n.change)); updated[key] = n.version; } } if (changes.length === 0) { return null; } const change = changes.length == 1 ? changes[0] : new Changes(changes); const version = new MapStream( basen ? basen.version : this.base, this.fn, updated ); return { change, version }; } _updateKeys(base, c, updated, changes) { if (!c) { return; } if (c instanceof Changes) { for (let cx of c) { this._updateKeys(base, cx, updated, changes); } return; } if (!(c instanceof PathChange)) { return; } if ((c.path || []).length == 0) { return this._updateKeys(base, c.change, updated, changes); } const key = c.path[0]; const existed = updated.hasOwnProperty(key); const nowExists = !(base.get(key) instanceof Null); if (!existed && nowExists) { updated[key] = this.fn(key, base.get(key)); const replace = new Replace(new Null(), updated[key].clone()); changes.push(new PathChange([key], replace)); } else if (existed && !nowExists) { const replace = new Replace(new Null(), updated[key].clone()); delete updated[key]; changes.push(new PathChange([key], replace.revert())); } } _appendChanges(c, updated, reverse) { if (c instanceof Changes) { let result = false; for (let cx of c) { result = result || this._appendChanges(cx, updated, reverse); } return result; } if (!(c instanceof PathChange)) { return false; } if (!c.path || c.path.length === 0) { return this._appendChanges(c.change, reverse); } const key = c.path[0]; if (this._value.hasOwnProperty(key)) { const cx = PathChange.create(c.path.slice(1), c.change); const val = this._value[key]; // TODO: ignores reverse flag!!! Fix updated[key] = val.appendChange(cx); console.log("updated", val, "to", updated[key]) return true; } return false; } }
JavaScript
class GroupStream extends DerivedStream { constructor(base, groups, groupsMap) { super(base.stream); this.base = base; this.groups = groups; if (!groupsMap && isMapLike(base)) { groupsMap = {}; for (let [key] of base[MapIterator]()) { groupsMap[key] = GroupStream._groupOf(key, groups); } } this.groupsMap = groupsMap; } append(c) { return this._append(c, false); } reverseAppend(c) { return this._append(c, true); } _append(c, reverse) { if (!c || !this.base.stream) { return this; } const groupsMap = Object.assign({}, this.groupsMap); c = this._proxyChange(c, groupsMap); const s = this.base.stream; return this._nextf(reverse ? s.reverseAppend(c) : s.append(c), groupsMap); } _nextf(n, groupsMap) { if(!n) { return null; } const base = this.base .apply(n.change) .clone() .setStream(n.version); const version = new GroupStream(base, this.groups, groupsMap); return {change: n.change, version}; } get value() { if (!isMapLike(this.base)) { return new Null().setStream(this); } const value = {}; for (let [key] of this.base[MapIterator]()) { const group = GroupStream._groupOf(key, this.groups); value[group] = value[group] || {}; value[group][key] = this.base.get(key).clone(); } for (let group in value) { value[group] = new Dict(value[group]); } return GroupStream._collection(value).setStream(this); } _getNext() { let groupsn = this.groups.next; let basen = this.base.next; const groups = groupsn ? groupsn.version : this.groups; const base = basen ? basen.version : this.base; if (!isMapLike(this.base) || !isMapLike(base)) { if (!groupsn && !basen) { return null; } const version = new GroupStream(base, groups, null); const change = new Replace(new Null(), version.value.clone()); return { change, version }; } const changes = []; const oldGroups = {}; for (let [key, val] of this.base[MapIterator]()) { const before = this.groupsMap[key]; oldGroups[before] = 0; const after = GroupStream._groupOf(key, groups); if (before !== after) { const r1 = new Replace(val.clone(), new Null()); changes.push(new PathChange([before, key], r1)); if (base.keyExists(key)) { const r2 = new Replace(new Null(), val.clone()); changes.push(new PathChange([after, key], r2)); } } } // delete empty groups for (let [key] of base[MapIterator]()) { oldGroups[GroupStream._groupOf(key, groups)] = 1; } for (let group in oldGroups) { if (!oldGroups[group]) { const r = new Replace(GroupStream._collection(null), new Null()); changes.push(new PathChange([group], r)); } } if (!this._groupChanges(base, basen && basen.change, groups, changes)) { // an unsupport change type. replace whole object const version = new GroupStream(base, groups, null); const change = new Replace(this.value.clone(), version.value.clone()); return { change, version }; } if (!changes.length) { return null; } const change = new Changes(changes); const version = new GroupStream(base, groups, null); return { change, version }; } _groupChanges(base, c, groups, changes) { if (!c) { return true; } if (c instanceof Changes) { for (let cx of c) { if (!this._groupChanges(base, cx, groups, changes)) { return false; } } return true; } if (!(c instanceof PathChange)) { return false; } if (!c.path || !c.path.length) { return this._groupChanges(base, c.change, groups, changes); } if (base.keyExists(c.path[0])) { const group = GroupStream._groupOf(c.path[0], groups); changes.push(PathChange.create([group].concat(c.path), c.change)); } return true; } _proxyChange(c, groupsMap) { if (!c) { return null; } if (c instanceof Changes) { const changes = []; for (let cx of c) { cx = this._proxyChange(cx, groupsMap); if (cx) { changes.push(cx); } } return Changes.create(changes); } if (!(c instanceof PathChange)) { throw new Error("cannot proxy change"); } if (!c.path || c.path.length === 0) { return this._proxyChange(c.change, groupsMap); } const group = c.path[0]; const change = PathChange.create(c.path.slice(1), c.change); return this._proxyGroupChange(group, change, groupsMap); } _proxyGroupChange(group, c, groupsMap) { if (!c) { return null; } if (c instanceof Changes) { const changes = []; for (let cx of c) { cx = this._proxyGroupChange(group, cx, groupsMap); if (cx) { changes.push(cx); } } return Changes.create(changes); } if (c instanceof PathChange) { if (!c.path || !c.path.length) { return this._proxyGroupChange(group, c.change, groupsMap); } groupsMap[c.path[0]] = group; return c; } if (!(c instanceof Replace)) { throw new Error("unexpected change"); } const changes = []; if (isMapLike(c.before)) { // delete old items for (let [key, before] of c.before[MapIterator]()) { const r = new Replace(before, new Null()); changes.push(new PathChange([key], r)); } } if (isMapLike(c.after)) { // insert new items for (let [key, after] of c.after[MapIterator]()) { const r = new Replace(new Null(), after); changes.push(new PathChange([key], r)); } } return this._proxyGroupChange(group, new Changes(changes), groupsMap); } static _groupOf(key, groups) { if (!isMapLike(groups)) { return ""; } return GroupStream.KeyString(groups.get(key)); } static KeyString(val) { return JSON.stringify(Encoder.encode(val)); } static _collection(m) { return new Dict(m, () => new Dict()); } }
JavaScript
class Store extends Dict { constructor(map, defaultFn) { super(map, defaultFn || (() => new Dict())); } static typeName() { return "dotdb.Store"; } }
JavaScript
class Seq extends Value { constructor(entries) { super(); this.entries = entries || []; } /** * splice splices a replacement sequence * * @param {Number} offset - where the replacement starts * @param {Number} count - number of items to remove * @param {Text|String} replacement - what to replace with * * @return {Text} */ splice(offset, count, replacement) { const before = this.slice(offset, offset + count); return this.appendChange(new Splice(offset, before, replacement)).version; } /** * move shifts the sub-sequence by the specified distance. * If distance is positive, the sub-sequence shifts over to the * right by as many characters as specified in distance. Negative * distance shifts left. * * @param {Number} offset - start of sub-sequence to shift * @param {Number} count - size of sub-sequence to shift * @param {Number} distance - distance to shift * * @return {Text} */ move(offset, count, distance) { return this.appendChange(new Move(offset, count, distance)).version; } /** clone makes a copy but with stream set to null */ clone() { return new Seq(this.entries); } slice(start, end) { return new Seq(this.entries.slice(start, end)); } _concat(...args) { const entries = []; for (let arg of args) { entries.push(arg.entries); } return new Seq(this.entries.concat(...entries)); } get length() { return this.entries.length; } get(idx) { return this.entries[idx].clone().setStream(new Substream(this.stream, idx)); } _set(idx, val) { const slice = this.entries.slice(0); slice[idx] = val; return new Seq(slice); } apply(c) { return applySeq(this, c); } *[SeqIterator]() { for (let kk = 0; kk < this.entries.length; kk++) { yield this.get(kk); } } toJSON() { return Encoder.encodeArrayValue(this.entries); } static typeName() { return "dotdb.Seq"; } static fromJSON(decoder, json) { return new Seq((json || []).map(x => decoder.decodeValue(x))); } }
JavaScript
class Num extends Value { constructor(num) { super(); this.n = parseFloat(+num); if (isNaN(this.n) || !isFinite(this.n)) { throw new Error("not a number: " + num); } } valueOf() { return this.n; } /** clone makes a copy but with stream set to null */ clone() { return new Num(this.n); } toJSON() { return this.n; } static typeName() { return "dotdb.Num"; } static fromJSON(decoder, json) { return new Num(json); } }
JavaScript
class Ref extends Value { constructor(path) { super(); this._path = path; } /** clone makes a copy but with stream set to null */ clone() { return new Ref(this._path); } /** run returns the underlying value at the path */ run(store) { let result = store; for (let elt of this._path) { result = field(store, result, new Text(elt)); } return result; } toJSON() { return JSON.stringify(this._path); } static typeName() { return "dotdb.Ref"; } static fromJSON(decoder, json) { return new Ref(JSON.parse(json)); } }
JavaScript
class Transformer { /** * @param {Conn} conn -- the connection to wrap. * @param {Object} [cache] -- an optional ops cache. * @param {Object} cache.untransformed -- a map of version => raw operation. * @param {Object} cache.transformed - a map of version => transformed op. * @param {Object} cache.merge - a map of version to array of merge ops. */ constructor(conn, cache) { this._c = conn; this._cache = cache || { untransformed: {}, transformed: {}, merge: {} }; } /** write passes through to the underlying {@link Conn} */ write(ops) { return this._c.write(ops); } /** read is the work horse, fetching ops from {@link Conn} and transforming it as needed */ async read(version, limit, duration) { const transformed = this._cache.transformed[version]; let ops = []; if (transformed) { for (let count = 0; count < limit; count++) { const op = this._cache.transformed[version + count]; if (!op) break; ops.push(op); } return ops; } const raw = this._cache.untransformed[version]; if (!raw) { ops = await this._c.read(version, limit, duration); } else { for (let count = 0; count < limit; count++) { const op = this._cache.untransformed[version + count]; if (!op) break; ops.push(op); } } const result = []; for (let op of ops || []) { this._cache.untransformed[op.version] = op; const { xform } = await this._transformAndCache(op); result.push(xform); } return result; } async _transformAndCache(op) { if (!this._cache.transformed[op.version]) { const { xform, merge } = await this._transform(op); this._cache.transformed[op.version] = xform; this._cache.merge[op.version] = merge; } const xform = this._cache.transformed[op.version]; const merge = this._cache.merge[op.version].slice(0); return { xform, merge }; } async _transform(op) { const gap = op.version - op.basis - 1; if (gap === 0) { // no interleaved op, so no special transformation needed. return { xform: op, merge: [] }; } // fetch all ops since basis const ops = await this.read(op.basis + 1, gap); let xform = op; let merge = []; if (op.parentId) { // skip all those before the parent if current op has parent while (!Transformer._equal(ops[0].id, op.parentId)) { ops.shift(); } const parent = ops[0]; ops.shift(); // The current op is meant to be applied on top of the parent op. // The parent op has a merge chain which corresponds to the set of // operation were accepted by the server before the parent operation // but which were not known to the parent op. // // The current op may have factored in a few but those in the // merge chain that were not factored would contribute to its own // merge chain. ({ xform, merge } = await this._getMergeChain(op, parent)); } // The transformed op needs to be merged against all ops that were // accepted by the server between the parent and the current op. for (let opx of ops) { let { xform: x } = await this._transformAndCache(opx); [xform, x] = Transformer._merge(x, xform); merge.push(x); } return { xform, merge }; } // getMergeChain gets all operations in the merge chain of the parent // that hove not been factored into the current op. The provided op // is transformed against this merge chain to form its own initial merge // chain. async _getMergeChain(op, parent) { const { merge } = await this._transformAndCache(parent); while (merge.length > 0 && merge[0].version <= op.basis) { merge.shift(); } let xform = op; for (let kk = 0; kk < merge.length; kk++) { [xform, merge[kk]] = Transformer._merge(merge[kk], xform); } return { xform, merge }; } static _merge(op1, op2) { let [c1, c2] = [op2.changes, op1.changes]; if (op1.changes) { [c1, c2] = op1.changes.merge(op2.changes); } const op1x = new Operation( op2.id, op2.parentId, op2.version, op2.basis, c1 ); const op2x = new Operation( op1.id, op1.parentId, op1.version, op1.basis, c2 ); return [op1x, op2x]; } static _equal(id1, id2) { // IDs can be any type, so to be safe JSON stringify it. return JSON.stringify(id1) == JSON.stringify(id2); } }
JavaScript
class Session { /** undoable wraps the object with a undo stack **/ static undoable(obj) { return obj.clone().setStream(undoable(obj.stream)); } /** Serialize serializes a connected value for later * use with connect */ static serialize(obj) { const root = Encoder.encode(obj.latest()); const stream = obj.stream; if (!stream || !(stream instanceof SessionStream)) { return { root, version: -1, merge: [], pending: [] }; } stream._push(); stream._pull(); const result = { root: root, version: stream._info.version, merge: stream._info.merge, pending: stream._info.pending }; return JSON.parse(JSON.stringify(result)); } /** connect creates a root object that can sync against * the provided URL. If serialized is not provided, a Null * initial object is created. */ static connect(url, serialized) { const conn = this._conn(url); const { root, version, merge, pending } = this._root(serialized); const parent = new Stream(); const info = { conn: conn, stream: parent, version: version, pending: (pending || []).slice(0), merge: (merge || []).slice(0), pulling: null, pushing: null, unsent: (pending || []).slice(0), unmerged: [] }; return root.setStream(new SessionStream(parent, info)); } static _root(serialized) { if (!serialized) { return { root: new Null(), version: -1 }; } const d = new Decoder(); const root = d.decodeValue(serialized.root); const { version } = serialized; const merge = serialized.merge.map(x => Operation.fromJSON(d, x)); const pending = serialized.pending.map(x => Operation.fromJSON(d, x)); return { root, version, merge, pending }; } static _conn(url) { if (typeof url !== "string") { return url; } // eslint-disable-next-line const f = typeof fetch == "function" ? fetch : null; return new Transformer(new Conn(url, f)); } }
JavaScript
class Reflect { /** Definition returns the definition of the value * Calling run(store, def(val)) will produce the value itself. * Definitions can be stored. */ static definition(val) { const s = val.stream; if (s instanceof RunStream) { return Reflect.definition(s.obj); } if (s instanceof FieldStream) { return new View( new Dict({ viewFn: new FieldFn(), obj: Reflect.definition(s.obj), key: Reflect.definition(s.key) }) ); } if (s instanceof InvokeStream) { // field(store, this.info, new Text("viewFn")) if (s.fn.stream instanceof FieldStream) { if ( s.fn.stream.key instanceof Text && s.fn.stream.key.text == "viewFn" ) { // this is actually an invoke stream of a View return new View(s.fn.stream.obj.clone()); } } const fn = Reflect.definition(s.fn); const args = Reflect.definition(s.args); return new View(extend(args, new Dict({ viewFn: fn() })).clone()); } return val.clone(); } static get FieldFn() { return FieldFn; } }
JavaScript
class GROReader extends PDBStream { constructor(data) { super(data); /** @type Number */ this._next = -1; // End position of line this.next(); } /** * Getting end of string. * @returns {Number} Pointer to end of string */ getNext() { return this._next; } }
JavaScript
class BaseController { static getName() { return 'BaseCtrl'; } static getDependencies() { return ['$rootScope', '$scope', '$location', 'velocity', '_', '$sce', BaseController]; } constructor($rootScope, $scope, $location, velocity, _, $sce) { this.$rootScope = $rootScope; this.$location = $location; this.velocity = velocity; this._ = _; this.$rootScope.appData = { smallScreenHeader: 'Cinescape', activeNavigationLink: 'home' }; this.navLinks = [ {label: 'Ceremony', smallLabel: $sce.trustAsHtml('<span>Ceremony</span>'), href: '#/', isActive: false}, {label: 'Reception', smallLabel: $sce.trustAsHtml('<span>Reception</span>'), href: '#/portfolio', isActive: false}, {label: 'Afterparty', smallLabel: $sce.trustAsHtml('<span>Afterparty</span>'), href: '#/pricing', isActive: false} // {label: 'About Us', smallLabel: $sce.trustAsHtml('<i class="fa fa-user"></i><span>About Us</span>'), href: '#/about', isActive: false}, // {label: 'Contact Us', smallLabel: $sce.trustAsHtml('<i class="fa fa-phone"></i><span>Contact Us</span>'), href: '#/contact', isActive: false} ]; this.init($scope); } init($scope) { //when the user navigates to a new page, clear the page messages/errors $scope.$on('$locationChangeStart', event => { let currentPath = this.$location.path(); switch (currentPath) { case '/': this.setLinksInactive(); this._.find(this.navLinks, {href: '#/'}).isActive = true; break; case '/about': this.setLinksInactive(); this._.find(this.navLinks, {href: '#/about'}).isActive = true; break; case '/contact': this.setLinksInactive(); this._.find(this.navLinks, {href: '#/contact'}).isActive = true; break; case '/portfolio': this.setLinksInactive(); this._.find(this.navLinks, {href: '#/portfolio'}).isActive = true; break; case '/pricing': this.setLinksInactive(); this._.find(this.navLinks, {href: '#/pricing'}).isActive = true; break; } this.scrollToTop(0); }); } setLinksInactive() { this._.forEach(this.navLinks, link => {link.isActive = false}); } afterViewEnter() { $('#view').attr('style', ''); } onScrollToTopClick() { this.scrollToTop(350); } scrollToTop(duration) { this.velocity($('html'), 'scroll', {duration: duration}); } }
JavaScript
class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; const headers = new Headers(opts.headers); if (body != null && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS$1] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } }
JavaScript
class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parse_url(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parse_url(`${input}`); } input = {}; } else { parsedURL = parse_url(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } }
JavaScript
class RequestError extends Error { constructor(message, statusCode, options) { super(message); // Maintains proper stack trace (only available on V8) /* istanbul ignore next */ if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = "HttpError"; this.status = statusCode; Object.defineProperty(this, "code", { get() { logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); return statusCode; } }); this.headers = options.headers || {}; // redact request credentials without mutating original request options const requestCopy = Object.assign({}, options.request); if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") }); } requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); this.request = requestCopy; } }
JavaScript
class EventListeners { static init (slideShow) { slideShow.slider.addEventListener('wheel', function (ev) { // si la fenetre scroll ev.preventDefault() // on empêche de retester l'événement slideShow.scrolling = ev.deltaY // on récupère la valeur de scrolling if (slideShow.scrolling > 0) { // si le scrolling est vers le bas, on appelle nextslide() slideShow.next() } else { // si le scrolling est vers le haut, on appelle prevslide() slideShow.prev() } slideShow.allPoints[slideShow.currentSlide].classList.add('select') }) document.addEventListener('mousemove', function () { window.clearTimeout(slideShow.timeOut1) slideShow.showInterface() slideShow.timeOut1 = window.setTimeout(slideShow.hideInterface, 4000) }) slideShow.slider.addEventListener('click', function () { window.clearTimeout(slideShow.timeOut1) slideShow.showInterface() slideShow.timeOut1 = window.setTimeout(slideShow.hideInterface, 4000) }) // Keyboard Events document.addEventListener('keyup', function (ev) { slideShow.allPoints[slideShow.currentSlide].classList.remove('select') if (ev.keyCode === 37 || ev.keyCode === 38) { slideShow.prev() } else if (ev.keyCode === 39 || ev.keyCode === 40 || ev.keyCode === 32 || ev.keyCode === 13) { slideShow.next() } else if (ev.keyCode === 36) { slideShow.goto(0) } else if (ev.keyCode === 27 || ev.keyCode === 72) { slideShow.hideInterface() } else if (ev.keyCode === 115) { slideShow.globalView() } else if (ev.keyCode === 35) { slideShow.goto(slideShow.allSlides.length - 1) } else if (ev.key === 'r') { ev.preventDefault() window.location.href = '../../../public/force-ratio.html' } slideShow.allPoints[slideShow.currentSlide].classList.add('select') }) document.addEventListener('keydown', function (ev) { if (ev.ctrlKey && ev.keyCode === 80) { ev.preventDefault() slideShow.print() } }) const sliderHammer = new Hammer(slideShow.slider) sliderHammer .on('swiperight', function () { slideShow.prev() }) .on('swipeleft', function () { slideShow.next() }) // Eventlisteners dans le code // qS('[cjs-action]', true).forEach(element => { // let action = element.getAttribute('cjs-action') // let setAction(content) { // element.addEventListener('click', ev => { // ev.preventDefault() // content() // }) // } // switch (action) { // case 'prev': // setEventListener(() => {slideShow.prev()}) // case 'next': // setEventListener(() => {slideShow.next()}) // case '': // setEventListener(() => {slideShow.next()}) // } // }) } }
JavaScript
class ContourRepresentation extends GeometryRepresentation { constructor() { super(); this.readerType = 'contourJsonReader'; } }
JavaScript
class UpdateQuery extends Abstract.mixin(Abstract.Setable, Abstract.Wherable) { constructor() { super(); this.type = 'update'; this.query = { table: '', set: [], where: [], having: [], group: [] }; } /** * This method will specify in which table the values need to be updated. * * @param {String} table The table in which the values need to be updated. * @return {InsertQuery} The current object for chaining. */ table(table) { this.query.table = table; return this; } }
JavaScript
class Polygon extends Drawable { /** * Create a shape instance. * * @param {Space} arg_space - drawing space. * @param {Drawable} arg_owner - parent shape (or undefined for top Space). * @param {array|Vector} arg_position - shape position. * @param {string} arg_color - shape color. * @param {number} arg_edges - shape edges count. * @param {number} arg_radius - shape radius. * * @returns {nothing} */ constructor(arg_space, arg_owner, arg_position, arg_color=undefined, arg_edges, arg_radius) { super(arg_space, arg_owner, arg_position, 'polygon') this.is_svg_polygon = true this._edges = typeof arg_edges == 'number' ? arg_edges : DEFAULT_EDGES this._radius = typeof arg_radius == 'number' ? arg_radius : DEFAULT_RADIUS this.color = arg_color } _draw_self() { // DO NOT RENDER if (this.color == 'none') { return } const pos_h = this.h() const pos_v = this.v() const radius_h = this.svg_space().range_to_screen_h(this._radius) const radius_v = this.svg_space().range_to_screen_v(this._radius) const radius = Math.min(radius_h, radius_v) const edges = typeof this._edges == 'number' ? this._edges : DEFAULT_EDGES let i, a, x, y const points = [] const degrees = 360 / edges for (i = 0; i < edges; i++) { a = i * degrees - 90 x = radius + radius * Math.cos(a * Math.PI / 180) y = radius + radius * Math.sin(a * Math.PI / 180) points.push([x, y]) } this._shape = this.svg_space().svg() .polygon(new SVG.PointArray(points)) .center(pos_h, pos_v) this.draw_color() return this } }
JavaScript
class AppAuth { /** * Your frontend app pages, authentication logic for access: JWT, AWS Cognito, Google sign in, * facebook sign in, Twitter sign in ... your fancy * @returns {Promise<*>} */ isAuthenticated = async () => { // TODO: write you authentication logic here that will need to pass for a user to // access a secured page. For example if you were using aws, and a user should only // access a page if still logged in, you would do something like the below commented out code: // return await Auth.currentAuthenticatedUser() // .then(async (data) => { // console.log('user data ::', data); // return true; // }) // .catch(() => { // return false; // }); //START my authentication logic for this framework template. // Of course, remove it and use your own return !(isNullUndefined(appStores.stores.appStore.user) || isEmptyObject(appStores.stores.appStore.user)); //END my logic }; handleLogin = () => { // TODO: handle any of your pre-login stuff here // or in any other function anywhere. appNavigation.navigateToSecuredAppHomepageExample(); }; handleLogout = action(() => { try { // TODO: your logout logic, e.g: // -> AWS sign out if you are using AWS: await Auth.signOut(); // -> or another type of sign out process that you are using // START my example sign out logic for this framework template share. // Of course, remove it and use your own when using this template appStores.stores.appStore.user = null; this.stopStoresPersistenceToLocalStorageAndClearOnLogout(); appNavigation.navigateToLoginAndRegistration(); // END my logic } catch (e) { console.log('handleLogout', e); } }); stopStoresPersistenceToLocalStorageAndClearOnLogout = () => { unregisterPersistenceEventListeners(); clearAllPersistedStoresToLocalStorage(); }; }
JavaScript
class ThreeAxisAccelerometer extends Webbit { static get dashboardConfig() { return { displayName: '3-Axis Accelerometer', category: 'Robot & Field Info', description: 'Component for displaying data from a 3-axis accelerometer.', documentationLink: 'https://frc-web-components.github.io/components/3-axis-accelerometer/', slots: [], editorTabs: ['properties', 'sources'], resizable: { left: true, right: true }, minSize: { width: 100, height: 10 } }; } static get properties() { return { x: { type: Number, defaultValue: 0 }, y: { type: Number, defaultValue: 0 }, z: { type: Number, defaultValue: 0 }, min: { type: Number, defaultValue: -16, get() { return Math.min(this._min, this._max); } }, max: { type: Number, defaultValue: 16, get() { return Math.max(this._min, this._max); } }, center: { type: Number, defaultValue: 0 }, precision: { type: Number, defaultValue: 2, get() { return clamp(this._precision, 0, 100); } }, hideText: { type: Boolean }, numTickMarks: { type: Number, defaultValue: 3, get() { return Math.max(0, this._numTickMarks); } }, unit: { type: String, defaultValue: 'g' } }; } static get styles() { return css` :host { display: inline-flex; flex-direction: column; height: auto; font-family: sans-serif; width: 300px; } [part=accelerometer] { width: 100%; display: flex; margin-bottom: 10px; } [part=accelerometer]:last-child { margin-bottom: 0; } [part=accelerometer] label { width: 10px; padding-top: 2px; font-weight: bold; text-transform: uppercase; } frc-accelerometer { width: 100%; flex: 1; } :host(:not([num-tick-marks="0"])) frc-accelerometer::part(bar) { width: calc(100% - 40px); margin: 0 20px; } :host([num-tick-marks="0"]) frc-accelerometer::part(bar) { width: 100%; margin: 0; } `; } renderAccelerometer(part, numTickMarks) { return html` <div part="accelerometer"> <label part="label">${part}</label> <frc-accelerometer part="${part}" value="${this[part]}" min="${this.min}" max="${this.max}" center="${this.center}" precision="${this.precision}" ?hide-text="${this.hideText}" num-tick-marks="${numTickMarks}" unit="${this.unit}" ></frc-accelerometer> </div> `; } render() { return html` ${this.renderAccelerometer('x', 0)} ${this.renderAccelerometer('y', 0)} ${this.renderAccelerometer('z', this.numTickMarks)} `; } }
JavaScript
class TelemetryLoggerMiddleware { /** * Initializes a new instance of the TelemetryLoggerMiddleware class. * @param telemetryClient The BotTelemetryClient used for logging. * @param logPersonalInformation (Optional) Enable/Disable logging original message name within Application Insights. */ constructor(telemetryClient, logPersonalInformation = false) { this._telemetryClient = telemetryClient || new botTelemetryClient_1.NullTelemetryClient(); this._logPersonalInformation = logPersonalInformation; } /** * Gets a value indicating whether determines whether to log personal information that came from the user. */ get logPersonalInformation() { return this._logPersonalInformation; } /** * Gets the currently configured botTelemetryClient that logs the events. */ get telemetryClient() { return this._telemetryClient; } /** * Logs events based on incoming and outgoing activities using the botTelemetryClient class. * @param context The context object for this turn. * @param next The delegate to call to continue the bot middleware pipeline */ onTurn(context, next) { return __awaiter(this, void 0, void 0, function* () { if (context === null) { throw new Error('context is null'); } // log incoming activity at beginning of turn if (context.activity !== null) { const activity = context.activity; // Log Bot Message Received yield this.onReceiveActivity(activity); } // hook up onSend pipeline context.onSendActivities((ctx, activities, nextSend) => __awaiter(this, void 0, void 0, function* () { // run full pipeline const responses = yield nextSend(); activities.forEach((act) => __awaiter(this, void 0, void 0, function* () { yield this.onSendActivity(act); })); return responses; })); // hook up update activity pipeline context.onUpdateActivity((ctx, activity, nextUpdate) => __awaiter(this, void 0, void 0, function* () { // run full pipeline const response = yield nextUpdate(); yield this.onUpdateActivity(activity); return response; })); // hook up delete activity pipeline context.onDeleteActivity((ctx, reference, nextDelete) => __awaiter(this, void 0, void 0, function* () { // run full pipeline yield nextDelete(); const deletedActivity = turnContext_1.TurnContext.applyConversationReference({ type: botframework_schema_1.ActivityTypes.MessageDelete, id: reference.activityId, }, reference, false); yield this.onDeleteActivity(deletedActivity); })); if (next !== null) { yield next(); } }); } /** * Invoked when a message is received from the user. * Performs logging of telemetry data using the IBotTelemetryClient.TrackEvent() method. * The event name logged is "BotMessageReceived". * @param activity Current activity sent from user. */ onReceiveActivity(activity) { return __awaiter(this, void 0, void 0, function* () { this.telemetryClient.trackEvent({ name: TelemetryLoggerMiddleware.botMsgReceiveEvent, properties: yield this.fillReceiveEventProperties(activity), }); }); } /** * Invoked when the bot sends a message to the user. * Performs logging of telemetry data using the botTelemetryClient.trackEvent() method. * The event name logged is "BotMessageSend". * @param activity Last activity sent from user. */ onSendActivity(activity) { return __awaiter(this, void 0, void 0, function* () { this.telemetryClient.trackEvent({ name: TelemetryLoggerMiddleware.botMsgSendEvent, properties: yield this.fillSendEventProperties(activity), }); }); } /** * Invoked when the bot updates a message. * Performs logging of telemetry data using the botTelemetryClient.trackEvent() method. * The event name used is "BotMessageUpdate". * @param activity */ onUpdateActivity(activity) { return __awaiter(this, void 0, void 0, function* () { this.telemetryClient.trackEvent({ name: TelemetryLoggerMiddleware.botMsgUpdateEvent, properties: yield this.fillUpdateEventProperties(activity), }); }); } /** * Invoked when the bot deletes a message. * Performs logging of telemetry data using the botTelemetryClient.trackEvent() method. * The event name used is "BotMessageDelete". * @param activity */ onDeleteActivity(activity) { return __awaiter(this, void 0, void 0, function* () { this.telemetryClient.trackEvent({ name: TelemetryLoggerMiddleware.botMsgDeleteEvent, properties: yield this.fillDeleteEventProperties(activity), }); }); } /** * Fills the Application Insights Custom Event properties for BotMessageReceived. * These properties are logged in the custom event when a new message is received from the user. * @param activity Last activity sent from user. * @param telemetryProperties Additional properties to add to the event. * @returns A dictionary that is sent as "Properties" to botTelemetryClient.trackEvent method. */ fillReceiveEventProperties(activity, telemetryProperties) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; return __awaiter(this, void 0, void 0, function* () { const properties = {}; if (activity) { properties[telemetryConstants_1.TelemetryConstants.fromIdProperty] = (_b = (_a = activity.from) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : ''; properties[telemetryConstants_1.TelemetryConstants.conversationIdProperty] = (_d = (_c = activity.conversation) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : ''; properties[telemetryConstants_1.TelemetryConstants.conversationNameProperty] = (_f = (_e = activity.conversation) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : ''; properties[telemetryConstants_1.TelemetryConstants.localeProperty] = (_g = activity.locale) !== null && _g !== void 0 ? _g : ''; properties[telemetryConstants_1.TelemetryConstants.recipientIdProperty] = (_j = (_h = activity.recipient) === null || _h === void 0 ? void 0 : _h.id) !== null && _j !== void 0 ? _j : ''; properties[telemetryConstants_1.TelemetryConstants.recipientNameProperty] = (_l = (_k = activity.recipient) === null || _k === void 0 ? void 0 : _k.name) !== null && _l !== void 0 ? _l : ''; // Use the LogPersonalInformation flag to toggle logging PII data, text and user name are common examples if (this.logPersonalInformation) { const fromName = (_o = (_m = activity.from) === null || _m === void 0 ? void 0 : _m.name) === null || _o === void 0 ? void 0 : _o.trim(); if (fromName) { properties[telemetryConstants_1.TelemetryConstants.fromNameProperty] = fromName; } const activityText = (_p = activity.text) === null || _p === void 0 ? void 0 : _p.trim(); if (activityText) { properties[telemetryConstants_1.TelemetryConstants.textProperty] = activityText; } const activitySpeak = (_q = activity.speak) === null || _q === void 0 ? void 0 : _q.trim(); if (activitySpeak) { properties[telemetryConstants_1.TelemetryConstants.speakProperty] = activitySpeak; } } // Additional Properties can override "stock" properties. if (telemetryProperties) { return Object.assign({}, properties, telemetryProperties); } } this.populateAdditionalChannelProperties(activity, properties); // Additional Properties can override "stock" properties. if (telemetryProperties) { return Object.assign({}, properties, telemetryProperties); } return properties; }); } /** * Fills the Application Insights Custom Event properties for BotMessageSend. * These properties are logged in the custom event when a response message is sent by the Bot to the user. * @param activity - Last activity sent from user. * @param telemetryProperties Additional properties to add to the event. * @returns A dictionary that is sent as "Properties" to botTelemetryClient.trackEvent method. */ fillSendEventProperties(activity, telemetryProperties) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; return __awaiter(this, void 0, void 0, function* () { const properties = {}; if (activity) { properties[telemetryConstants_1.TelemetryConstants.replyActivityIdProperty] = (_a = activity.replyToId) !== null && _a !== void 0 ? _a : ''; properties[telemetryConstants_1.TelemetryConstants.recipientIdProperty] = (_c = (_b = activity.recipient) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : ''; properties[telemetryConstants_1.TelemetryConstants.conversationIdProperty] = (_e = (_d = activity.conversation) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : ''; properties[telemetryConstants_1.TelemetryConstants.conversationNameProperty] = (_g = (_f = activity.conversation) === null || _f === void 0 ? void 0 : _f.name) !== null && _g !== void 0 ? _g : ''; properties[telemetryConstants_1.TelemetryConstants.localeProperty] = (_h = activity.locale) !== null && _h !== void 0 ? _h : ''; // Use the LogPersonalInformation flag to toggle logging PII data, text and user name are common examples if (this.logPersonalInformation) { const recipientName = (_k = (_j = activity.recipient) === null || _j === void 0 ? void 0 : _j.name) === null || _k === void 0 ? void 0 : _k.trim(); if (recipientName) { properties[telemetryConstants_1.TelemetryConstants.recipientNameProperty] = recipientName; } const activityText = (_l = activity.text) === null || _l === void 0 ? void 0 : _l.trim(); if (activityText) { properties[telemetryConstants_1.TelemetryConstants.textProperty] = activityText; } const activitySpeak = (_m = activity.speak) === null || _m === void 0 ? void 0 : _m.trim(); if (activitySpeak) { properties[telemetryConstants_1.TelemetryConstants.speakProperty] = activitySpeak; } if ((_o = activity.attachments) === null || _o === void 0 ? void 0 : _o.length) { properties[telemetryConstants_1.TelemetryConstants.attachmentsProperty] = JSON.stringify(activity.attachments); } } // Additional Properties can override "stock" properties. if (telemetryProperties) { return Object.assign({}, properties, telemetryProperties); } } return properties; }); } /** * Fills the event properties for BotMessageUpdate. * These properties are logged when an activity message is updated by the Bot. * For example, if a card is interacted with by the use, and the card needs to be updated to reflect * some interaction. * @param activity - Last activity sent from user. * @param telemetryProperties Additional properties to add to the event. * @returns A dictionary that is sent as "Properties" to botTelemetryClient.trackEvent method. */ fillUpdateEventProperties(activity, telemetryProperties) { var _a, _b, _c, _d, _e, _f, _g, _h; return __awaiter(this, void 0, void 0, function* () { const properties = {}; if (activity) { properties[telemetryConstants_1.TelemetryConstants.recipientIdProperty] = (_b = (_a = activity.recipient) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : ''; properties[telemetryConstants_1.TelemetryConstants.conversationIdProperty] = (_d = (_c = activity.conversation) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : ''; properties[telemetryConstants_1.TelemetryConstants.conversationNameProperty] = (_f = (_e = activity.conversation) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : ''; properties[telemetryConstants_1.TelemetryConstants.localeProperty] = (_g = activity.locale) !== null && _g !== void 0 ? _g : ''; // Use the LogPersonalInformation flag to toggle logging PII data, text is a common example if (this.logPersonalInformation) { const activityText = (_h = activity.text) === null || _h === void 0 ? void 0 : _h.trim(); if (activityText) { properties[telemetryConstants_1.TelemetryConstants.textProperty] = activityText; } } // Additional Properties can override "stock" properties. if (telemetryProperties) { return Object.assign({}, properties, telemetryProperties); } } return properties; }); } /** * Fills the Application Insights Custom Event properties for BotMessageDelete. * These properties are logged in the custom event when an activity message is deleted by the Bot. This is a relatively rare case. * @param activity - Last activity sent from user. * @param telemetryProperties Additional properties to add to the event. * @returns A dictionary that is sent as "Properties" to botTelemetryClient.trackEvent method. */ fillDeleteEventProperties(activity, telemetryProperties) { var _a, _b, _c, _d, _e, _f, _g; return __awaiter(this, void 0, void 0, function* () { const properties = {}; if (activity) { properties[telemetryConstants_1.TelemetryConstants.channelIdProperty] = (_a = activity.channelId) !== null && _a !== void 0 ? _a : ''; properties[telemetryConstants_1.TelemetryConstants.recipientIdProperty] = (_c = (_b = activity.recipient) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : ''; properties[telemetryConstants_1.TelemetryConstants.conversationIdProperty] = (_e = (_d = activity.conversation) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : ''; properties[telemetryConstants_1.TelemetryConstants.conversationNameProperty] = (_g = (_f = activity.conversation) === null || _f === void 0 ? void 0 : _f.name) !== null && _g !== void 0 ? _g : ''; // Additional Properties can override "stock" properties. if (telemetryProperties) { return Object.assign({}, properties, telemetryProperties); } } return properties; }); } populateAdditionalChannelProperties(activity, properties) { var _a, _b, _c, _d; if (activity) { const channelData = activity.channelData; switch (activity.channelId) { case 'msteams': properties.TeamsUserAadObjectId = (_b = (_a = activity.from) === null || _a === void 0 ? void 0 : _a.aadObjectId) !== null && _b !== void 0 ? _b : ''; if (isTeamsChannelData(channelData)) { properties.TeamsTenantId = (_d = (_c = channelData.tenant) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : ''; if (channelData.team) { properties.TeamsTeamInfo = JSON.stringify(channelData.team); } } break; default: break; } } } }
JavaScript
class EitherValue extends Value { constructor(type, eithertype, varianttype) { super(type); this.eithertype = eithertype; this.varianttype = varianttype; if (this.varianttype.recordtype === null) { this.fields = undefined; } else { this.fields = this.varianttype.recordtype.makeDefaultValue(); } } // call this from JS as follows: // let x = thing.match({ // Variant1: (t) => 1, // Variant2: (t) => { return t.two + 2; }, // }); match(variants) { let fn = variants[this.varianttype.name]; if (fn === undefined) { return undefined; } if (typeof fn === 'function') { return fn(this.fields); } else { // maybe it's an expression return fn; } } assign(newValue) { let ok = false; if (this.type == this.eithertype) { ok = (newValue instanceof EitherValue && this.eithertype == newValue.eithertype); } else { // this.type == this.varianttype ok = (newValue instanceof EitherValue && this.varianttype == newValue.varianttype); } if (ok) { this.varianttype = newValue.varianttype; if (this.varianttype.recordtype === null) { this.fields = undefined; } else { this.fields = this.varianttype.recordtype.makeDefaultValue(); this.fields.assign(newValue.fields); } } else { throw new errors.Internal(`Cannot assign value of ${newValue} to ` + `either-type ${this.type.getName()}`); } } lookup(name) { return this.fields.lookup(name); } set(name, value) { return this.fields.set(name, value); } equals(other) { if (this.varianttype != other.varianttype) { return false; } if (this.fields !== undefined) { return this.fields.equals(other.fields); } return true; } innerToString() { if (this.fields !== undefined) { return this.fields.toString(); } else { return this.varianttype.name; } } toString() { if (this.fields !== undefined) { return `${this.varianttype.name} { ${this.fields.innerToString()} }`; } else { return `${this.varianttype.name}`; } } assignJSON(spec) { if (typeof spec === 'string') { this.assign( this.eithertype.getVariant(spec) .makeDefaultValue()); } else { this.assign( this.eithertype.getVariant(spec.tag) .makeDefaultValue()); this.fields.assignJSON(spec.fields); } } toJSON() { if (this.fields !== undefined) { let o = {}; o.tag = this.varianttype.name; o.fields = this.fields.toJSON(); return o; } else { return this.varianttype.name; } } }
JavaScript
class EitherVariant extends Type { constructor(decl, env, name, parenttype) { super(decl, env, name); this.parenttype = parenttype; if (this.decl.kind == 'enumvariant') { this.recordtype = null; let constant = new EitherValue(this, this.parenttype, this); constant.isConstant = true; this.env.vars.set(this.name, constant, this.decl.id.source); } else { this.recordtype = makeType.make(decl.type, this.env, this.name); this.env.assignType(this.name, this); } } equals(other) { return this === other; } makeDefaultValue() { return new EitherValue(this, this.parenttype, this); } fieldType(name) { return this.recordtype.fieldType(name); } toString() { return `${this.name} (EitherVariant)`; } }
JavaScript
class DirCrawler { constructor(opts) { // Callbacks are: (itemPath, stats, context, tracker) => Promise<boolean> || boolean // Return boolean for matching and ignoring // Return a Promise<Boolean> for async operations let { fileMatch, // a callback that returns true to include a file in flat index dirMatch, // a callback that returns true to include a directory (sans contents) in flat index dirIgnore, // a callback that returns true to skip a directory's contents maxDepth, // the maximum number of subdirectories to explore fileMatched, // a callback that is called after a file is identified as a match dirMatched, // a callback that is called after a directory is identified as a match postFile, // a callback that is called after a file has been inspected (so it is safe to rename, delete, etc.) postDir, // a callback that is called after a directory has been inspected (so it is safe to rename, delete, etc.) } = opts; this.fileMatch = fileMatch || (async () => false); // If not provided, no files will be matched this.dirMatch = dirMatch || (async () => false); // If not provided, no directories will be matched this.dirIgnore = dirIgnore || (async () => false); // If not provided, no directories will be skipped this.maxDepth = maxDepth || 5; this.fileMatched = fileMatched || (async a => a); // By default, nothing happens this.dirMatched = dirMatched || (async a => a); // By default, nothing happens this.postFile = postFile || (async a => a); // By default, nothing happens this.postDir = postDir || (async a => a); // By default, nothing happens } // From a root directory, read through all files and subdirectories, looking for items // Returns a Promise, as crawl recursively calls itself async crawl(directory, workingContext, workingTracker) { // Provided as a safe place for callbacks to store state const context = workingContext || {}; // Used internally to track progress - available for reporting const tracker = workingTracker || { startTime: Date.now().valueOf(), dirCount: 0, dirSkips: 0, dirFinds: 0, fileCount: 0, fileFinds: 0, currentDepth: 0, crawler: this, }; // Fully qualify directory path and read contents const dir = path.resolve(directory); let items = fs.readdirSync(dir); // Iterate each item in the directory for (let i = 0, l = items.length; i < l; i++) { let item = items[i]; // Fully qualify the item's path and get its stats let itemPath = path.resolve(dir, item); let stats = fs.statSync(itemPath); // Work with directories if (stats.isDirectory()) { tracker.dirCount++; let dirMatch = await this.dirMatch(itemPath, stats, context, tracker); if (dirMatch) { tracker.dirFinds++; await this.dirMatched(itemPath, stats, context, tracker); } let dirIgnore = await this.dirIgnore(itemPath, stats, context, tracker); if (!dirIgnore) { // Ignore if filtered out if (tracker.currentDepth < this.maxDepth) { // Skip if max depth reached tracker.currentDepth++; // crawl() MUST be async to account for multiple awaits within (otherwise nested crawl will jump ahead) await this.crawl(itemPath, context, tracker); // Recurse only if not ignored tracker.currentDepth--; } else tracker.dirSkips++; // Count skipped if depth was provided (and thus exceeded here) } else tracker.dirSkips++; // Count skipped if filter was provided (and thus matched here) await this.postDir(itemPath, stats, context, tracker); } // Work with files else { tracker.fileCount++; let fileMatch = await this.fileMatch(itemPath, stats, context, tracker); if (fileMatch) { tracker.fileFinds++; await this.fileMatched(itemPath, stats, context, tracker); } await this.postFile(itemPath, stats, context, tracker); } } if (tracker.currentDepth === 0) await this.postDir(dir, fs.statSync(dir), context, tracker); // Return context and tracker for follow-up processing return Promise.resolve({ context, tracker }); } }
JavaScript
class RoleSectionHead extends RoleStructure { /** * @param {boolean|undefined} expanded */ set expanded(expanded) { this.setAttr(ARIAExpanded, expanded) } /** * @returns {boolean|undefined} */ get expanded() { return this.getAttr(ARIAExpanded) } }
JavaScript
class StaticGrid extends layer_1.DrawLayer { constructor(localTransform, zoomLevel, visible, gridWidth = 256, gridHeight = 256) { super(localTransform, 1, visible); this.gridWidth = gridWidth; this.gridHeight = gridHeight; let zoom = Math.pow(2, zoomLevel); this.zoomWidth = gridWidth / zoom; this.zoomHeight = gridHeight / zoom; } draw(ctx, transform, view) { let offsetX = view.x * view.zoomX; let offsetY = view.y * view.zoomY; let viewWidth = view.width / view.zoomX; let viewHeight = view.height / view.zoomY; let gridAcross = viewWidth / this.zoomWidth; let gridHigh = viewHeight / this.zoomHeight; let xMin = Math.floor(view.x / this.zoomWidth); let xLeft = xMin * this.zoomWidth * view.zoomX; let xMax = Math.ceil((view.x + viewWidth) / this.zoomWidth); let xRight = xMax * this.zoomWidth * view.zoomX; let yMin = Math.floor(view.y / this.zoomHeight); let yTop = yMin * this.zoomHeight * view.zoomX; let yMax = Math.ceil((view.y + viewHeight) / this.zoomHeight); let yBottom = yMax * this.zoomHeight * view.zoomX; ctx.beginPath(); ctx.strokeStyle = "black"; for (var x = xMin; x <= xMax; x++) { //console.log("at " + minX); let xMove = x * this.zoomWidth * view.zoomX; ctx.moveTo(xMove - offsetX, yTop - offsetY); ctx.lineTo(xMove - offsetX, yBottom - offsetY); } for (var y = yMin; y <= yMax; y++) { let yMove = y * this.zoomHeight * view.zoomY; ctx.moveTo(xLeft - offsetX, yMove - offsetY); ctx.lineTo(xRight - offsetX, yMove - offsetY); for (var x = xMin; x <= xMax; x++) { let xMove = (x - .5) * this.zoomWidth * view.zoomX; yMove = (y - .5) * this.zoomHeight * view.zoomY; let text = "" + (x - 1) + ", " + (y - 1); ctx.strokeText(text, xMove - offsetX, yMove - offsetY); } } ctx.closePath(); ctx.stroke(); return true; } getDimension() { return new point2d_1.Dimension(0, 0, 0, 0); } }
JavaScript
class VideoMergeJobModel extends ModelBase { /** * Constructor for video merge job model. * * @augments ModelBase * * @constructor */ constructor() { super({ dbName: dbName }); const oThis = this; oThis.tableName = 'video_merge_jobs'; } /** * Format db data. * * @param {object} dbRow * @param {number} dbRow.id * @param {number} dbRow.user_id * @param {string} dbRow.merged_url * @param {number} dbRow.status * @param {string} dbRow.created_at * @param {string} dbRow.updated_at * * @return {object} */ formatDbData(dbRow) { const oThis = this; const formattedData = { id: dbRow.id, userId: dbRow.user_id, mergedUrl: shortToLongUrl.getFullUrlInternal(dbRow.merged_url, videoConstants.originalResolution), status: videoMergeJobConstants.statuses[dbRow.status], createdAt: dbRow.created_at, updatedAt: dbRow.updated_at }; return oThis.sanitizeFormattedData(formattedData); } /** * Update job status * @param status * @param jobId * @returns {Promise<void>} */ async updateStatus(status, jobId) { const oThis = this; await oThis .update(['status = ?', videoMergeJobConstants.invertedStatuses[status]]) .where(['id = ?', jobId]) .fire(); await VideoMergeJobModel.flushCache({ ids: [jobId] }); } /** * Fetch video merge jobs by ids. * * @param {number} jobIds * * @returns {Promise<{}>} */ async fetchVideoMergeJobByIds(jobIds) { const oThis = this; const dbRows = await oThis .select('*') .where({ id: jobIds }) .fire(); const response = {}; for (let index = 0; index < dbRows.length; index++) { const formatDbRow = oThis.formatDbData(dbRows[index]); response[formatDbRow.id] = formatDbRow; } return response; } /** * Insert video merge job. * * @param {object} params * @param {number} params.userId * @param {string} params.mergedUrl * * @returns {Promise<void>} */ async insertJob(params) { const oThis = this; const resp = await oThis .insert({ user_id: params.userId, merged_url: params.mergedUrl, status: videoMergeJobConstants.invertedStatuses[videoMergeJobConstants.notStartedStatus] }) .fire(); await VideoMergeJobModel.flushCache({ ids: [resp.insertId] }); return resp; } /** * Flush cache. * * @param {object} params * @param {array<number>} [params.ids] * * @returns {Promise<void>} */ static async flushCache(params) { const promisesArray = []; if (params.ids) { const VideoMergeJobByIdsCache = require(rootPrefix + '/lib/cacheManagement/multi/VideoMergeJobByIds'); promisesArray.push(new VideoMergeJobByIdsCache({ ids: params.ids }).clear()); } await Promise.all(promisesArray); } }
JavaScript
class WorkbookDefinedNameCollection { constructor(wb) { this._wb = wb; } ; /** * Get read-only array of global defined names */ get items() { if (!this._wb.Workbook) return []; if (!this._wb.Workbook.Names) return []; return this._wb.Workbook.Names.filter((name) => { name.Sheet == null; }).map((name) => new DefinedName(name)); } ; /** * Get defined name object */ getName(name) { if (this._wb.Workbook && this._wb.Workbook.Names) { const names = this._wb.Workbook.Names; for (let i = 0; i < names.length; ++i) { if (names[i].Name.toLowerCase() != name.toLowerCase()) continue; if (names[i].Sheet != null) continue; return new DefinedName(names[i]); } } throw new Error(`Cannot find defined name |${name}|`); } /** * Number of global defined names */ get count() { if (!this._wb.Workbook) return 0; if (!this._wb.Workbook.Names) return 0; return this._wb.Workbook.Names.filter((name) => { typeof name.Sheet == "undefined"; }).length; } /** * Add or update defined name * @param name String name * @param ref Range object or string range/formula * @param comment Optional comment */ add(name, ref /*TODO: | Range */, comment) { try { return this.getName(name); } catch (e) { const nm = { Name: name, Ref: ref.toString(), Comment: comment || "" }; if (!this._wb.Workbook) this._wb.Workbook = {}; if (!this._wb.Workbook.Names) this._wb.Workbook.Names = []; this._wb.Workbook.Names.push(nm); return new DefinedName(nm); } } }
JavaScript
class XYZPlugin extends AbstractPlugin { /** * Constructor. */ constructor() { super(); this.id = 'xyz'; } /** * @inheritDoc */ init() { var lcm = LayerConfigManager.getInstance(); lcm.registerLayerConfig('XYZ', XYZLayerConfig); var im = ImportManager.getInstance(); im.registerImportUI(this.id, new ProviderImportUI('<xyzprovider></xyzprovider>')); im.registerServerType(this.id, { type: 'xyz', helpUi: XYZProviderHelpUI.directiveTag, formUi: XYZImportForm.directiveTag, label: 'XYZ Map Layer' }); } }
JavaScript
class EventManager { /** * Constructor */ constructor() { /** * Registered events * @type {Bag} * @private */ this._events = new Bag() } /** * Get registered events * @returns {Bag} */ getEvents() { return this._events } /** * Set registered events * @param {Object|Bag} events * @throws {InvalidArgumentException} throws an exception if events is not an instance of Bag or an object */ setEvents(events) { if (events instanceof Bag) { this._events = events } else if (typeof events === 'object') { this._events = new Bag(events) } else { throw new InvalidArgumentException('[Event/EventManager#setEvents] events must be an instance of Bag or an object') } } /** * Subscribe a listener to Event Manager * * @param {!string} name Name of event to subscribe * @param {!EventListener} listener A listener object to handle incoming event * @throws {Exception} throws an exception if listener is not an instance of Event/EventListener */ subscribe(name, listener) { if (!(listener instanceof EventListener)) { throw new Exception('[Event/EventManager#subscribe] listener must be an instance of Event/EventListener') } this.on(name, listener.getRunner(), listener.getPriority(), listener.getLimit()) } /** * Unsubscribe a listener * * @param {!string} name Name of event to unsubscribe * @param {!EventListener} listener EventListener to unsubscribe */ unsubscribe(name, listener) { if (!(listener instanceof EventListener)) { throw new Error('[Event/EventManager#unsubscribe] listener must be an instance of Event/EventListener') } this.off(name, listener.getPriority()) } /** * Register an event handler * * @param {!string} name Name of event to listen * @param {!function} runner Callback to handle incoming event * @param {?number} [priority=null] Higher priority handler will be call later than the others * @param {?number} [limit=null] Number of times to be run. Default is null to ignore limit * @returns {EventListener} EventListener instance of registration */ on(name, runner, priority = null, limit = null) { if (!this.getEvents().has(name)) { this.getEvents().set(name, getEventItem()) } let listener = new CallableEventListener(runner, priority, limit) this.getEvents().get(name).listeners.push(listener) return listener } /** * Register an one time handler of a specific event * * @param {!string} name Name of event to listen * @param {!function} runner Callback to handle incoming event * @param {?number} [priority=null] Higher priority handler will be call later than the others * @returns {EventListener} EventListener instance of registration */ once(name, runner, priority = null) { return this.on(name, runner, priority, EventListener.LIMIT_ONCE) } /** * Register an twice times handler of a specific event * * @param {!string} name Name of event to listen * @param {!function} runner Callback to handle incoming event * @param {?number} [priority=null] Higher priority handler will be call later than the others * @returns {EventListener} EventListener instance of registration */ twice(name, runner, priority = null) { return this.on(name, runner, priority, EventListener.LIMIT_TWICE) } /** * Remove event's listeners * * @param {string} name Name of event to remove its listeners * @param {?number} [priority=null] Priority of handler to remove. In case this parameter is undefined, * it will remove all handlers * @throws {Error} If name of event is not specified */ off(name, priority = null) { if (priority === null) { // remove all listeners of event's name this.getEvents().set(name, getEventItem()) } else if (this.getEvents().has(name)) { let listeners = this.getEvents().get(name).listeners for (let i = 0; i < listeners.length; i++) { let listener = listeners[i] if (listener.getPriority() === priority) { listeners.splice(i, 1) } } } else { throw new Exception('[Event/EventManager#off] name must be specified.') } } /** * Sort event listeners by priority * @see {EventManager.SORT_ASCENDING} * @param {!string} name Name of event to sort * @param {string} [type='asc'] Sorting type, asc (EventManager.SORT_ASCENDING) or desc (EventManager.SORT_DESCENDING) */ sort(name, type = EventManager.SORT_ASCENDING) { let events = this.getEvents().get(name) if (events.sorted) { return false } const total = events.listeners.length let pos, guard, listener, temporary for (let i = 0; i < total - 1; i++) { pos = i for (let j = i + 1; j < total; j++) { guard = events.listeners[pos] listener = events.listeners[j] if (type === EventManager.SORT_ASCENDING && guard.priority > listener.priority || type === EventManager.SORT_DESCENDING && guard.priority < listener.priority) { pos = j } } if (i !== pos) { temporary = events.listeners[i] events.listeners[i] = events.listeners[pos] events.listeners[pos] = temporary } } } /** * Emit (Fire) an event * * @param {string} name Event's name to be fired * @param {Bag|Object} parameters Parameters for event * @param {boolean} [series=false] Run listeners in series or parallel * @returns {Promise} */ emit(name, parameters = null, series = false) { if (!this.getEvents().has(name)) { this.getEvents().set(name, getEventItem()) } else { this.sort(name) } if (parameters === undefined || parameters === null) { parameters = new Bag() } else if (typeof parameters === 'object') { if (!(parameters instanceof Bag)) { parameters = new Bag(parameters) } } else { throw new InvalidArgumentException('[Event/EventManager#emit] args must be an instance of Bag or an object') } let listeners = this.getEvents().get(name).listeners const total = listeners.length let parallels = [] for (let i = 0; i < total; i++) { // Set a callback function to allow listener to add its result to final results // which is an array and processed as a third parameter after all tasks are run parallels.push((next) => listeners[i].getRunner()(parameters, next)) } // run tasks return new Promise((resolve, reject) => { if (parallels.length) { try { const args = [parallels, (err, results) => { this._onAsyncCompleted(name, err, results) if (err) { reject(err) } else { resolve(results) } }] if (series === true) { async.series.apply(this, args) } else { async.parallel.apply(this, args) } } catch (e) { reject(e) } } else { resolve() } }) } /** * Handle event when asynchronous calls have been completed * @param {string} name Event's name * @param {Exception} err A string represent for error * @param {Array} results An array of results of tasks * @private */ _onAsyncCompleted(name, err, results) { let event = this.getEvents().get(name), listeners = event.listeners, listener = null, limit = null for (let i = 0; i < listeners.length; i++) { listener = listeners[i], limit = listener.getLimit() if (limit !== EventListener.LIMIT_NONE) { // reduce listener's limit event.listeners[i].setLimit(--limit) } if (err) { // there is an expected error when running tasks in parallel/series listener.onError(err) } else { // it seems to be fine, set results if any to event listener.onComplete(results) } if (limit === 0) { // remove this listener event.listeners.splice(i, 1) } } } }
JavaScript
class SetsUpMixin extends SuperClass { /** * Setup before the first class test. * * @memberof test.mixins.core.SetsUp * @instance */ beforeAll() {} // /** * Setup before any class test. * * @memberof test.mixins.core.SetsUp * @instance */ beforeEach() {} // /** * Tear down after any class test. * * @memberof test.mixins.core.SetsUp * @instance */ afterEach() {} // /** * Tear down after the last class test. * * @memberof test.mixins.core.SetsUp * @instance */ afterAll() {// } }
JavaScript
class ElementHandler { constructor(content){ this.content = content } element(element) { element.setInnerContent(this.content) } }
JavaScript
class RedirectHandler{ constructor(tag, link){ this.tag = tag this.link = link } element(element){ element.setAttribute(this.tag, this.link) } }
JavaScript
class SequenceValidationCard extends React.Component { constructor(props){ super(props); } generateListItems(issues, warnings) { let listItems = []; // add all issues and warnings to listItems list issues && issues.forEach((issue) => { let itemType = "issue"; if(issue.type === "prerequisite" || issue.type === "corequisite"){ issue.data.unmetRequirements.forEach((requirement) => { let shouldSkip = false; // skip issues that include an exempted courseCode requirement requirement.forEach((courseCode) => { COURSE_EXEMPTIONS.indexOf(courseCode) >= 0 && (shouldSkip = true); }); if(!shouldSkip){ listItems.push({ type: itemType, positionsToHighlight: [issue.data.position], message: sprintf(UI_STRINGS.VALIDATION_MISSING_REQUISITE_T, issue.data.courseCode, issue.type, requirement.join(" or ")) }); } }); } if(issue.type === "creditCount") { listItems.push({ type: itemType, positionsToHighlight: [], message: sprintf(UI_STRINGS.VALIDATION_MISSING_CREDITS_T, issue.data.actual, issue.data.required) }); } }); warnings && warnings.forEach((warning) => { let itemType = "warning"; if(warning.type === "repeated") { listItems.push({ type: itemType, positionsToHighlight: warning.data.positions, message: sprintf(UI_STRINGS.VALIDATION_REPEATED_COURSE_T, warning.data.courseCode, warning.data.positions.length) }); } if(warning.type === "unselectedOption") { listItems.push({ type: itemType, positionsToHighlight: [warning.data.position], message: sprintf(UI_STRINGS.VALIDATION_NO_OPTION_SELECT_T, warning.data.position.season, (parseInt(warning.data.position.yearIndex) + 1), (parseInt(warning.data.position.courseIndex) + 1)) }); } }); return listItems; } renderCardHeader(isValid, isLoading) { let title, loadingIcon, showExpandableButton; if(isLoading){ title = UI_STRINGS.VALIDATION_LOADING; loadingIcon = LOADING_ICON_TYPES.small; showExpandableButton = true; } else if(isValid) { title = UI_STRINGS.VALIDATION_SUCCESS_MSG; showExpandableButton = false } else { title = UI_STRINGS.VALIDATION_FAILURE_MSG; showExpandableButton = true; } return ( <CardHeader title={title} actAsExpander={!isValid} showExpandableButton={showExpandableButton} closeIcon={loadingIcon} openIcon={loadingIcon}/> ); } renderCardText(listItems) { return ( <CardText expandable={true}> {listItems.map((item, index) => ( <div className={"validationListItem " + item.type} key={index} onMouseEnter={() => this.props.onMouseEnterItem(item.positionsToHighlight)} onMouseLeave={() => this.props.onMouseLeaveItem(item.positionsToHighlight)}> <div className="validationListIcon">{ERROR_ICONS[item.type]}</div> <div className="validationMessage">{item.message}</div> </div> ))} </CardText> ); } render() { let issues = this.props.validationResults.issues; let warnings = this.props.validationResults.warnings; let listItems = this.generateListItems(issues, warnings); let isValid = this.props.validationResults.isValid === "true" || listItems.length === 0; let isLoading = this.props.validationResults.isLoading; return ( <Card> {this.renderCardHeader(isValid, isLoading)} {!isValid && this.renderCardText(listItems)} </Card> ); } }
JavaScript
class Main { /** * Provides opportunity to commit actions depend on different orientations of screen. * Helps to build responsivity. * * @example <caption>You can call it like this:</caption> * Main.responsiveOrientation(new Map([ * [{width: 1000, height: 1400}, () => { * doSmth(); * }], * [{width: 1000, height: 750}, () => { * doSmthAnother(); * }], * [0, () => { * okDoSmthELSE(); * }] * ])); * * * @param {Map} data Map which consists of {width: Num, height: Num} => actionCallback. OR 0 => actionCallback. * {width: Num, height: Num} - describes orientation, actionCallback - action that should be performed in case of * reaching the orientation. 0 - if no particular orientations were reached, in that case it's * possible to commit some action. * @param {Callback|Boolean} $endActionCallback Action at the end of adjusting element. * @return {Void} */ static responsiveOrientation(data, $endActionCallback = false) { let windowWidth = window.innerWidth; let windowHeight = window.innerHeight; let currentWindowRatio = windowWidth / windowHeight; // Represents if any given screen ratio were reached let hasConditionBeenFulfilled = false; // orientationData = {width: Num, height: Num} (refering to particular screen ratio) // OR // orientationData = 0 (else, not matching with particular screen ratio) // actionCallback - action that should be performed in case of reaching appropriate screen ratio for (let [orientationData, actionCallback] of data) { // You can interpret this as long chain of if () .... let breakpointWindowRatio = orientationData.width / orientationData.height; if (currentWindowRatio <= breakpointWindowRatio) { actionCallback(); hasConditionBeenFulfilled = true; break; } } // And this one as ELSE (after long chain of ifs ()...) if (!hasConditionBeenFulfilled) { let actionCallback = data.get(0); // means else actionCallback(); } if ($endActionCallback !== false) $endActionCallback(); } }
JavaScript
class Checkout extends React.Component { constructor() { super(); this.cartRef = React.createRef(); this.state = { products: [], addresses: [], selectedAddressIndex: 0, newAddress: "", balance: 0, loading: false, }; } /** * Check the response of the getProducts() API call to be valid and handle any failures along the way * * @param {boolean} errored * Represents whether an error occurred in the process of making the API call itself * @param {Product[]|{ success: boolean, message: string }} response * The response JSON object which may contain further success or error messages * @returns {boolean} * Whether validation has passed or not * * If the API call itself encounters an error, errored flag will be true. * If the backend returns an error, then success field will be false and message field will have a string with error details to be displayed. * When there is an error in the API call itself, display a generic error message and return false. * When there is an error returned by backend, display the given message field and return false. * When there is no error and API call is successful, return true. */ validateGetProductsResponse = (errored, response) => { if (errored || (!response.length && !response.message)) { message.error( "Could not fetch products. Check that the backend is running, reachable and returns valid JSON." ); return false; } if (!response.length) { message.error(response.message || "No products found in database"); return false; } return true; }; /** * Perform the API call to fetch all products from backend * - Set the loading state variable to true * - Perform the API call via a fetch call: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API * - The call must be made asynchronously using Promises or async/await * - The call must handle any errors thrown from the fetch call * - Parse the result as JSON * - Set the loading state variable to false once the call has completed * - Call the validateGetProductsResponse(errored, response) function defined previously * - If response passes validation, and the response exists, * - Update products state variable with the response * * Example for successful response from backend: * HTTP 200 * [ * { * "name": "iPhone XR", * "category": "Phones", * "cost": 100, * "rating": 4, * "image": "https://i.imgur.com/lulqWzW.jpg", * "_id": "v4sLtEcMpzabRyfx" * }, * { * "name": "Basketball", * "category": "Sports", * "cost": 100, * "rating": 5, * "image": "https://i.imgur.com/lulqWzW.jpg", * "_id": "upLK9JbQ4rMhTwt4" * } * ] * * Example for failed response from backend: * HTTP 500 * { * "success": false, * "message": "Something went wrong. Check the backend console for more details" * } */ getProducts = async () => { let response = {}; let errored = false; this.setState({ loading: true, }); try { response = await (await fetch(`${config.endpoint}/products`)).json(); } catch (e) { errored = true; } this.setState({ loading: false, }); if (this.validateGetProductsResponse(errored, response)) { if (response) { this.setState({ products: response, }); } } }; /** * Check the response of other API calls to be valid and handle any failures along the way * * @param {boolean} errored * Represents whether an error occurred in the process of making the API call itself * @param {Address[]|{ success: boolean, message?: string }} response * The response JSON object which may contain further success or error messages * @param {string} couldNot * String indicating what could not be loaded * @returns {boolean} * Whether validation has passed or not * * If the API call itself encounters an error, errored flag will be true. * If the backend returns an error, then success field will be false and message field will have a string with error details to be displayed. * When there is an error in the API call itself, display a generic error message and return false. * When there is an error returned by backend, display the given message field and return false. * When there is no error and API call is successful, return true. */ validateResponse = (errored, response, couldNot) => { if (errored) { message.error( `Could not ${couldNot}. Check that the backend is running, reachable and returns valid JSON.` ); return false; } if (response.message) { message.error(response.message); return false; } return true; }; /** * Perform the API call to fetch the user's addresses from backend * - Set the loading state variable to true * - Perform the API call via a fetch call: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API * - The call must be made asynchronously using Promises or async/await * - The call must be authenticated with an authorization header containing Oauth token * - The call must handle any errors thrown from the fetch call * - Parse the result as JSON * - Set the loading state variable to false once the call has completed * - Call the validateResponse(errored, response, couldNot) function defined previously * - If response passes validation, update the addresses state variable * * Example for successful response from backend: * HTTP 200 * [ * { * "_id": "m_rg_eW5kLALNcn70kpyR", * "address": "No. 341, Banashankari, Bangalore, India" * }, * { * "_id": "9sW_60WkwrT7gDPmgUdoP", * "address": "123 Main Street, New York, NY 10030" * }, * ] * * Example for failed response from backend: * HTTP 401 * { * "success": false, * "message": "Protected route, Oauth2 Bearer token not found" * } */ getAddresses = async () => { let response = {}; let errored = false; this.setState({ loading: true, }); try { response = await ( await fetch(`${config.endpoint}/user/addresses`, { method: "GET", headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, }, }) ).json(); } catch (e) { errored = true; } this.setState({ loading: false, }); if (this.validateResponse(errored, response, "fetch addresses")) { if (response) { this.setState({ addresses: response, }); } } }; /** * Perform the API call to add an address for the user * - Set the loading state variable to true * - Perform the API call via a fetch call: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API * - The call must be made asynchronously using Promises or async/await * - The call must be authenticated with an authorization header containing Oauth token * - The call must handle any errors thrown from the fetch call * - Parse the result as JSON * - Set the loading state variable to false once the call has completed * - Call the validateResponse(errored, response, couldNot) function defined previously * - If response passes validation, and response exists, * - Show an appropriate success message * - Clear the new address input field * - Call getAddresses() to refresh list of addresses * * Example for successful response from backend: * HTTP 200 * { * "success": true * } * * Example for failed response from backend: * HTTP 400 * { * "success": false, * "message": "Address should be greater than 20 characters" * } */ addAddress = async () => { let response = {}; let errored = false; this.setState({ loading: true, }); try { response = await ( await fetch(`${config.endpoint}/user/addresses`, { method: "POST", headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, "Content-Type": "application/json", }, body: JSON.stringify({ address: this.state.newAddress, }), }) ).json(); } catch (e) { errored = true; } this.setState({ loading: false, }); if (this.validateResponse(errored, response, "add a new address")) { if (response) { message.success("Address added"); this.setState({ newAddress: "", }); await this.getAddresses(); } } }; // TODO: CRIO_TASK_MODULE_CHECKOUT - Implement deleteAddresses() to make DELETE API request to the backend API path "/user/addresses/:userid" /** * Perform the API call to delete an address for the user * * @param {string} addressId * ID of the address record to delete * * - Set the loading state variable to true * - Perform the API call via a fetch call: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API * - The call must be made asynchronously using Promises or async/await * - The call must be authenticated with an authorization header containing Oauth token * - The call must handle any errors thrown from the fetch call * - Parse the result as JSON * - Set the loading state variable to false once the call has completed * - Call the validateResponse(errored, response, couldNot) function defined previously * - If response passes validation, and response exists, * - Show an appropriate success message * - Call getAddresses() to refresh list of addresses * * Example request * DELETE /user/addresses/ARqizV9kPhXU57pf1OEMm * * Example for successful response from backend: * HTTP 200 * { * "success": true * } * * Example for failed response from backend: * HTTP 404 * { * "success": false, * "message": "Address to delete was not found" * } */ deleteAddress = async (addressId) => { let response = {}; let errored = false; this.setState({ loading: true, }); try { response = await ( await fetch(`${config.endpoint}/user/addresses/${addressId}`, { method: "DELETE", headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, }, }) ).json(); } catch (e) { errored = true; } this.setState({ loading: false, }); if (this.validateResponse(errored, response, "delete address")) { if (response) { message.success("Address deleted"); await this.getAddresses(); } } }; /** * Perform the API call to place an order * * - Set the loading state variable to true * - Perform the API call via a fetch call: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API * - The call must be made asynchronously using Promises or async/await * - The call must be authenticated with an authorization header containing Oauth token * - The call must handle any errors thrown from the fetch call * - Parse the result as JSON * - Set the loading state variable to false once the call has completed * - Call the validateResponse(errored, response, couldNot) function defined previously * - If response passes validation, and response exists, * - Show an appropriate success message * - Update the localStorage field for `balance` to reflect the new balance * - Redirect the user to the thanks page * * Example for successful response from backend: * HTTP 200 * { * "success": true * } * * Example for failed response from backend: * HTTP 400 * { * "success": false, * "message": "Wallet balance not sufficient to place order" * } */ checkout = async () => { let response = {}; let errored = false; this.setState({ loading: true, }); try { response = await ( await fetch(`${config.endpoint}/cart/checkout`, { method: "POST", headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, "Content-Type": "application/json", }, body: JSON.stringify({ addressId: this.state.addresses[this.state.selectedAddressIndex] ._id, }), }) ).json(); } catch (e) { errored = true; } this.setState({ loading: false, }); if (this.validateResponse(errored, response, "checkout")) { // TODO: CRIO_TASK_MODULE_CHECKOUT - // 1. Display a order successful message // 2. Update user's balance in localStorage // 3. Redirect to "/thanks" page if (response) { message.success("Order placed"); localStorage.setItem( "balance", parseInt(localStorage.getItem("balance")) - this.cartRef.current.calculateTotal() ); this.props.history.push("/thanks"); } } }; // TODO: CRIO_TASK_MODULE_CHECKOUT - Implement the order() method /** * Function that is called when the user clicks on the place order button * - If the user's wallet balance is less than the total cost of the user's cart, then display an appropriate error message * - Else if the user does not have any addresses, or has not selected an available address, then display an appropriate error message * - Else call the checkout() method to proceed with placing and order */ order = async () => { if (this.state.balance < this.cartRef.current.calculateTotal()) { message.error( "You do not have enough balance in your wallet for this purchase" ); } else if ( !this.state.addresses.length || !this.state.addresses[this.state.selectedAddressIndex] ) { message.error("Please select an address or add a new address to proceed"); } else { this.checkout(); } }; // TODO: CRIO_TASK_MODULE_CHECKOUT - Implement the componentDidMount() lifecycle method /** * Function that runs when component has loaded * This is the function that is called when the user lands on the Checkout page * If the user is logged in (i.e. the localStorage fields for `username` and `token` exist), fetch products and addresses from backend (asynchronously) to component state * Update the balance state variable with the value stored in localStorage * Else, show an error message indicating that the user must be logged in first and redirect the user to the home page */ async componentDidMount() { if (localStorage.getItem("username") && localStorage.getItem("token")) { await this.getProducts(); await this.getAddresses(); } else { message.error("You must be logged in to do that."); this.props.history.push("/"); } this.setState({ balance: localStorage.getItem("balance"), }); } /** * JSX and HTML goes here * We display the cart component as the main review for the user on this page (Cart component must know that it should be non-editable) * We display the payment method and wallet balance * We display the list of addresses for the user to select from * If the user has no addresses, appropriate text is displayed instead * A text field (and button) is required so the user may add a new address * We display a link to the products page if the user wants to shop more or update cart * A button to place the order is displayed */ render() { const radioStyle = { display: "block", height: "30px", lineHeight: "30px", }; return ( <> {/* Display Header */} <Header history={this.props.history} /> {/* Display Checkout page content */} <div className="checkout-container"> <Row> {/* TODO: CRIO_TASK_MODULE_CHECKOUT - Cart should be shown on top of Shipping and Pricing blocks in "xs" devices */} {/* Display checkout instructions */} <Col xs={{ span: 24, order: 2 }} md={{ span: 18, order: 1 }}> <div className="checkout-shipping"> <h1 style={{ marginBottom: "-10px" }}>Shipping</h1> <hr></hr> <br></br> <p> Manage all the shipping addresses you want (work place, home address)<br></br>This way you won't have to enter the shipping address manually with each order. </p> {/* Display the "Shipping" sectino */} <div className="address-section"> {this.state.addresses.length ? ( // Display the list of addresses as radio buttons <Radio.Group className="addresses" defaultValue={this.state.selectedAddressIndex} onChange={(e) => { this.setState({ selectedAddressIndex: e.target.value, }); }} > <Row> {/* Create a view for each of the user's addresses */} {this.state.addresses.map((address, index) => ( <Col xs={24} lg={12} key={address._id}> <div className="address"> <Radio.Button value={index}> <div className="address-box"> {/* Display address title */} <div className="address-text"> {address.address} </div> {/* TODO: CRIO_TASK_MODULE_CHECKOUT - Clicking on Delete button should call "deleteAddress" function with the correct argument*/} {/* Display button to delete address from user's list */} <Button type="primary" onClick={async () => { await this.deleteAddress(address._id); }} > Delete </Button> </div> </Radio.Button> </div> </Col> ))} </Row> </Radio.Group> ) : ( // Display static text banner if no addresses are added <div className="red-text checkout-row"> No addresses found. Please add one to proceed. </div> )} <div className="checkout-row"> {/* Text input field to type a new address */} <div> <TextArea className="new-address" placeholder="Add new address" rows={4} value={this.state.newAddress} onChange={(e) => { this.setState({ newAddress: e.target.value, }); }} /> </div> {/* Button to submit address added */} <div> <Button type="primary" onClick={this.addAddress}> Add New Address </Button> </div> </div> </div> <br></br> {/* Display the "Pricing" section */} <div> <h1 style={{ marginBottom: "-10px" }}>Pricing</h1> <hr></hr> <h2>Payment Method</h2> <Radio.Group value={1}> <Radio style={radioStyle} value={1}> Wallet <strong> (₹{this.state.balance} available)</strong> </Radio> </Radio.Group> </div> <br></br> {/* Button to confirm order */} <Button className="ant-btn-success" loading={this.state.loading} type="primary" onClick={this.order} > <strong>Place Order</strong> </Button> </div> </Col> {/* TODO: CRIO_TASK_MODULE_CHECKOUT - Cart should be shown on top of Shipping and Pricing blocks in "xs" and "sm" devices */} {/* Display the cart */} <Col xs={{ span: 24, order: 1 }} md={6} className="checkout-cart"> <div> {this.state.products.length && ( <Cart ref={this.cartRef} products={this.state.products} history={this.props.history} token={localStorage.getItem("token")} checkout={true} /> )} </div> </Col> </Row> </div> {/* Display the footer */} <Footer></Footer> </> ); } }
JavaScript
class CreateCompetencyButton extends React.Component { componentDidMount() { let competencyLevels = CompetencyServices.getCompetencyLevels(); let competencyFrequencies = CompetencyServices.getEvaluationFrequencies(); let competencyDomains = CompetencyServices.getCompetencyDomains(); if (this.props.id) { let competency = ComptencyServices.getCompetencyById(this.props.id) let competencySubcategories = CompetencyServices.getCompetencySubCategories(competency.domain) this.setState({ level: competency.difficulty, description: competency.description, frequency: competency.frequency, title: competency.title, domain: competency.domain, subcategory: competency.subcategory, details: competency.details, zeroScale: competency.zeroScale, oneScale: competency.oneScale, twoScale: competency.twoScale, threeScale: competency.threeScale, fourScale: competency.fourScale, NScale: competency.NScale, levels: competencyLevels, frequencies: competencyFrequencies, domains: competencyDomains, subcategories: competencySubcategories }) } else { let competencySubcategories = CompetencyServices.getCompetencySubCategories(this.state.domain) this.setState({ levels: competencyLevels, frequencies: competencyFrequencies, domains: competencyDomains, subcategories: competencySubcategories }) } } constructor(props) { super(props); this.state = { level: '', description: '', frequency: '', title: '', domain: 'Transportation', subcategory: '', details: '', zeroScale: '', oneScale: '', twoScale: '', threeScale: '', fourScale: '', NScale: '', subcategories: [], levels: [], frequencies: [], domains: [], open: false, } } setLevel(newLevel) { this.setState({ level: newLevel }) } setTitle(newTitle) { this.setState({ title: newTitle }) } setFrequency(newFrequency) { this.setState({ frequency: newFrequency }) } setDetails(details) { this.setState({ details: details }) } setDescription(newDescription) { this.setState({ description: newDescription }) } setDomain(newDomain) { this.setState({ domain: newDomain }) } setSubCategories(subcategories) { this.setState({ subcategories: subcategories }) } setSubCategory(subcategory) { this.setState({ subcategory: subcategory }) } setZeroScale(zeroScale) { this.setState({ zeroScale: zeroScale }) } setOneScale(oneScale) { this.setState({ oneScale: oneScale }) } setTwoScale(twoScale) { this.setState({ twoScale: twoScale }) } setThreeScale(threeScale) { this.setState({ threeScale: threeScale }) } setFourScale(fourScale) { this.setState({ fourScale: fourScale }) } setNScale(nScale) { this.setState({ nScale: nScale }) } handleChangeZeroScale = event => { this.setZeroScale(event.target.value) } handleChangeOneScale = event => { this.setOneScale(event.target.value) } handleChangeTwoScale = event => { this.setTwoScale(event.target.value) } handleChangeThreeScale = event => { this.setThreeScale(event.target.value) } handleChangeFourScale = event => { this.setFourScale(event.target.value) } handleChangeNScale = event => { this.setNScale(event.target.value) } handleChangeLevel = event => { this.setLevel(event.target.value); }; handleChangeDescription = event => { this.setDescription(event.target.value); }; handleChangeFrequency = event => { this.setFrequency(event.target.value); } handleChangeDomain = event => { let subcategories = CompetencyServices.getCompetencySubCategories(event.target.value); this.setDomain(event.target.value); this.setSubCategories(subcategories); } handleChangeSubcategory = event => { this.setSubCategory(event.target.value) } handleChangeTitle = event => { this.setTitle(event.target.value); } handleChangeDetails = event => { this.setDetails(event.target.value); } openWindow = () => { this.setState({ open: true }); }; closeWindow = () => { this.setState({ open: false }); }; handleSubmit = () => { let competency = { level: this.state.level, description: this.state.description, frequency: this.state.frequency, title: this.state.title, domain: this.state.domain, subcategory: this.state.subcategory, details: this.state.details, zeroScale: this.state.zeroScale, oneScale: this.state.oneScale, twoScale: this.state.twoScale, threeScale: this.state.threeScale, fourScale: this.state.fourScale, NScale: this.state.NScale } if (!(competency.level && competency.description && competency.frequency && competency.title && competency.domain && competency.subcategory)) { alert("Please fill in all required fields (*)") } else { CompetencyServices.createCompetency(competency) this.closeWindow() } } rendorLevelList() { const listItems = this.state.levels.map((item) => <option value={item}>{item}</option>) return listItems } rendorFrequencyList() { const frequencies = this.state.frequencies.map((item) => <option value={item}>{item}</option>) return frequencies } rendorDomainList() { const domains = this.state.domains.map((item) => <option value={item}>{item}</option>) return domains } rendorSubcategoryList() { const subcategories = this.state.subcategories.map((item) => <option value={item}>{item}</option>) if (subcategories === []) { return ['Select Domain'] } return subcategories } renderButton() { if (this.props.id || this.props.id === 0) { return (<div classname="cardStyle" style={{ height: '50%', maxWidth: '5%', margin: '1.9vh 1vw 1vh 0.1vw' }}> <Button onClick={this.openWindow} size='small'> <img src={EditBtn} width="22vw" height="50%" alt="Edit" /> </Button> </div>) } else { return (<Button variant='contained' onClick={this.openWindow} color='secondary'>{this.props.buttonTitle}</Button>) } } render() { return ( <div> {this.renderButton()} <Dialog maxWidth='lg' fullWidth={true} open={this.state.open} onClose={this.closeWindow}> <div style={{ display: 'flex', flexDirection: 'row' }}> <div style={{ flex: 1 }}> <DialogTitle>{this.props.title}</DialogTitle> </div> <Button onClick={this.closeWindow} size='small'> <img src={DeleteImage} width="22vw" height="50%" alt="Delete" /> </Button> </div> <DialogContent> <div style={{ flex: 1 }}> <Grid container spacing={4}> <Grid xs={12} item> <TextField label="Title" size='medium' fullWidth={true} variant='outlined' required={true} value={this.state.title} onChange={this.handleChangeTitle} /> </Grid> <Grid xs={7} item> <Grid container spacing={2}> <Grid item> <FormLabel>Domain: </FormLabel> </Grid> <Grid item> <Select label="Domain" native value={this.state.domain} onChange={this.handleChangeDomain} > {this.rendorDomainList()} </Select> </Grid> <Grid item> <FormLabel>Subcategory: </FormLabel> </Grid> <Grid item> <Select label="Subcategory" native defaultValue={this.state.subcategory} value={this.state.subcategory} onChange={this.handleChangeSubcategory} > {this.rendorSubcategoryList()} </Select> </Grid> </Grid> </Grid> <Grid xs={5} item> <Grid container spacing={3}> <Grid item> <FormLabel>Level: </FormLabel> </Grid> <Grid item> <Select label="Level" native value={this.state.level} onChange={this.handleChangeLevel} > {this.rendorLevelList()} </Select> </Grid> <Grid item> <FormLabel>Frequency: </FormLabel> </Grid> <Grid item> <Select label="Evaluation Frequency" native value={this.state.frequency} onChange={this.handleChangeFrequency} > {this.rendorFrequencyList()} </Select> </Grid> </Grid> </Grid> <Grid xs={12} item> <TextField label="Description" rows="4" variant='outlined' multiline size='medium' margin='normal' fullWidth={true} required={true} value={this.state.description} onChange={this.handleChangeDescription} /> </Grid> <Grid xs={12} item> <Grid container spacing={2}> <Grid item xs={4}> <TextField label="Zero Scale" variant="outlined" size='medium' margin='normal' fullWidth={true} multiline={true} rows='1' rowsMax='3' value={this.state.zeroScale} onChange={this.handleChangeZeroScale} /> </Grid> <Grid item xs={4}> <TextField label="One Scale" variant="outlined" size='medium' margin='normal' fullWidth={true} multiline={true} rows='1' rowsMax='3' value={this.state.oneScale} onChange={this.handleChangeOneScale} /> </Grid> <Grid item xs={4}> <TextField label="Two Scale" variant="outlined" size='medium' margin='normal' fullWidth={true} multiline={true} rows='1' rowsMax='3' value={this.state.twoScale} onChange={this.handleChangeTwoScale} /> </Grid> </Grid> </Grid> <Grid xs={12} item> <Grid container spacing={2}> <Grid item xs={4}> <TextField label="Three Scale" variant="outlined" size='medium' margin='normal' fullWidth={true} multiline={true} rows='1' rowsMax='3' value={this.state.threeScale} onChange={this.handleChangeThreeScale} /> </Grid> <Grid item xs={4}> <TextField label="Four Scale" variant="outlined" size='medium' margin='normal' fullWidth={true} multiline={true} rows='1' rowsMax='3' value={this.state.fourScale} onChange={this.handleChangeFourScale} /> </Grid> <Grid item xs={4}> <TextField label="N Scale" variant="outlined" size='medium' margin='normal' fullWidth={true} multiline={true} rows='1' rowsMax='3' value={this.state.nScale} onChange={this.handleChangeNScale} /> </Grid> </Grid> </Grid> <Grid xs={12} item> <TextField label="Details Required" rows="4" variant="outlined" multiline={true} size='medium' margin='normal' fullWidth={true} value={this.state.details} onChange={this.handleChangeDetails} /> </Grid> </Grid> </div> </DialogContent> <DialogActions> <Button variant='contained' onClick={this.handleSubmit} color="secondary"> {this.props.buttonTitle} </Button> </DialogActions> </Dialog> </div > ); } }
JavaScript
class DownloadService { /** * Constructor of DownloadService * @constructor */ constructor() { this.mimeType = ''; this.toString = a => String(a); this.fileName = ''; this.reader = new FileReader(); } /** * Download file * @param data {string|Object} - Downloaded data * @param strFileName {string} - Name of downloaded file * @param strMimeType {string} - Mime type of downloaded file * @return {Promise<void>} - Promise resolved after downloading file * @async */ download(data, strFileName, strMimeType) { this.fileName = strFileName || CONSTANTS.DEFAULT_FILE_NAME; this.mimeType = strMimeType; this.payload = data; let MyBlob = (window.Blob || window['MozBlob'] || window['WebKitBlob'] || this.toString); MyBlob = MyBlob.call ? MyBlob.bind(window) : Blob ; if (this._isPayloadBase64()) { if (this._isBigBase64(MyBlob)) { this._convertBase64ToBlob(MyBlob); } else { return this._saveBase64(MyBlob); } } return this._saveBlob(MyBlob); } /** * Converting big base64 string to blob * @param MyBlob - Copy of Blob class for current browser * @private */ _convertBase64ToBlob(MyBlob) { this.payload = this._dataUrlToBlob(this.payload, MyBlob); this.mimeType = this.payload.type || CONSTANTS.DEFAULT_TYPE; } /** * Download data in base64 format * @param MyBlob - Copy of Blob class for current browser * @private */ _saveBase64(MyBlob) { return new Promise((resolve) => { if (navigator.msSaveBlob) { navigator.msSaveBlob(this._dataUrlToBlob(this.payload, MyBlob), this.fileName); } else { this._save(this.payload); } resolve(); }); } /** * Download data in Blob format * @param MyBlob - Copy of Blob class for current browser * @private */ _saveBlob(MyBlob) { const blob = this.payload instanceof MyBlob ? this.payload : new MyBlob([ this.payload ], { type: this.mimeType }); if (navigator.msSaveBlob) { return navigator.msSaveBlob(blob, this.fileName); } if (window.URL) { return this._save(window.URL.createObjectURL(blob), true); } else { if (typeof blob === 'string' || blob.constructor === this.toString ) { return this._saveBigBase64(blob); } return this._convertByFileReader(blob) .then(base64 => this._save(base64)); } } /** * Download file in Blob (String) format * @param blob - Instance of Blob for current browser * @private */ _saveBigBase64(blob) { try { return this._save('data:' + this.mimeType + ';base64,' + window.btoa(blob)); } catch(y) { return this._save('data:' + this.mimeType + ',' + encodeURIComponent(blob)); } } /** * Download converted data * @param url - URL of converted downloaded data * @param winMode - Indicator showing data has been converted by window.URL * @private */ _save(url, winMode) { const anchor = document.createElement('a'); if ('download' in anchor) { return this._saveByAnchor(anchor, url, winMode); } if (this._isSafari()) { return this._saveByLocationForSafari(url); } this._saveByIframe(url, winMode); } /** * Finish downloading by anchor * @param anchor - Created link for downloading * @param url URL - of converted downloaded data * @param winMode - Indicator showing data has been converted by window.URL * @private */ _saveByAnchor(anchor, url, winMode) { return new Promise((resolve) => { anchor.href = url; anchor.setAttribute('download', this.fileName); anchor.style.display = 'none'; document.body.appendChild(anchor); setTimeout(() => { anchor.click(); document.body.removeChild(anchor); if (winMode) setTimeout(() => window.URL.revokeObjectURL(anchor.href), 250); resolve(); }, 66); }); } /** * Finish downloading by window location (for Safari) * @param url - URL of converted downloaded data * @private */ _saveByLocationForSafari(url) { const urlWithoutBase64 = url.replace(CONSTANTS.BASE_64_REGEX, CONSTANTS.DEFAULT_TYPE); if (!window.open(urlWithoutBase64)) { if (window.confirm(CONSTANTS.CONFIRM_TEXT)) { window.location.href = urlWithoutBase64; } } return true; } /** * Finish downloading by iframe * @param url - URL of converted downloaded data * @param winMode - Indicator showing data has been converted by window.URL * @private */ _saveByIframe(url, winMode) { let iframe = document.createElement('iframe'); document.body.appendChild(iframe); iframe.src = winMode ? url : 'data:' + url.replace(CONSTANTS.BASE_64_REGEX, CONSTANTS.DEFAULT_TYPE); setTimeout(() => document.body.removeChild(iframe), 333); } /** * Convert blob to base64 using FileReader * @param blob - Instance of Blob for current browser * @private */ _convertByFileReader(blob) { return new Promise((resolve) => { this.reader.onload = () => this.reader.result && resolve(this.reader.result); this.reader.readAsDataURL(blob); }); } /** * Convert URL string to blob * @param strUrl - URL of downloaded data * @param MyBlob - Copy of Blob class for current browser * @private */ _dataUrlToBlob(strUrl, MyBlob) { const parts = strUrl.split(/[:;,]/); const type = parts[1]; const decoder = parts[2] === 'base64' ? atob : decodeURIComponent; const binData = decoder(parts.pop() || ''); const mx = binData.length; const uiArr = new Uint8Array(mx); let index = 0; for (index; index < mx; ++index) uiArr[index] = binData.charCodeAt(index); return new MyBlob([uiArr], {type}); } /** * Check that downloaded data has base64 format * @return {boolean} * @private */ _isPayloadBase64() { return CONSTANTS.FULL_BASE_64_REGEX.test(this.payload); } /** * Check that downloaded base64 is to big * @return {boolean} * @private */ _isBigBase64(MyBlob) { return this.payload.length > CONSTANTS.MAX_PAYLOAD_LENGTH && MyBlob !== this.toString; } /** * Check that current browser is Safari * @return {boolean} * @private */ _isSafari() { return CONSTANTS.SAFARI_REGEX.test(navigator.userAgent); } }
JavaScript
class Plane { /** * Constructor */ constructor() { /** * Distance from origin * * @type {number} */ this.distance = 0; /** * Normal * * @type {vec3} */ this.normal = vec3.create(); } /** * Get distance from a given point * * @param {number} x Point position on X * @param {number} y Point position on Y * @param {number} z Point position on Z */ distanceTo(x, y, z) { return vec3.dot(this.normal, vec3.fromValues(x, y, z)) + this.distance; } /** * Normalize * * @return {Plane} A reference to the instance */ normalize() { const length = vec3.length(this.normal); this.normal[0] /= length; this.normal[1] /= length; this.normal[2] /= length; this.distance /= length; return this; } /** * Set plane using a position and an origin * * @param {number} x Normal on X * @param {number} y Normal on Y * @param {number} z Normal on Z * @param {number} distance Distance from origin * @return {Plane} A reference to the instance */ set(x, y, z, distance) { vec3.set(this.normal, x, y, z); this.distance = distance; return this; } /** * Set plane using a position and an origin * * @param {Array.<number>} a Point A * @param {Array.<number>} b Point B * @param {Array.<number>} c Point C * @return {Plane} A reference to the instance */ setFromPoints(a, b, c) { // Diff const edge1 = vec3.create(); const edge2 = vec3.create(); const vecA = vec3.fromValues(a[0], a[1], a[2]); vec3.subtract(edge1, vec3.fromValues(b[0], b[1], b[2]), vecA); vec3.subtract(edge2, vec3.fromValues(c[0], c[1], c[2]), vecA); // Compute vec3.cross(this.normal, edge1, edge2); this.distance = -vec3.dot(this.normal, a); this.normalize(); return this; } /** * Get normal * * @return {vec3} */ getNormal() { return this.normal; } /** * Get distance * * @return {number} */ getDistance() { return this.distance; } }
JavaScript
class Feed extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); const t = (entry, tagname) => entry.getElementsByTagName(tagname)[0]; fetch(this.getAttribute('url')) .then((response) => response.text()) .then((xml) => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xml, 'text/xml'); const list = document.createElement('ul'); list.part = 'entries'; for (const entry of xmlDoc.getElementsByTagName('entry')) { const listItem = document.createElement('li'); listItem.part = 'entry'; const link = document.createElement('a'); link.part = 'title'; link.setAttribute( 'href', t(entry, 'link').getAttribute('href') ); const title = document.createTextNode( t(entry, 'title').innerHTML ); link.appendChild(title); listItem.appendChild(link); const date = document.createElement('div'); date.part = 'date'; const dateText = document.createTextNode( new Date( t(entry, 'published').textContent ).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric', }) ); date.appendChild(dateText); listItem.appendChild(date); list.appendChild(listItem); } shadowRoot.append(list); }); } }
JavaScript
class ForwardError extends Error { constructor(message, statusCode, systemError) { super(message); this.message = message; this.statusCode = statusCode; // when err.type is `system`, err.code contains system error code if (systemError) { this.code = this.errno = systemError.code; } // hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); } }
JavaScript
class DialogSignupAlert extends React.Component { /** * @method handleClose * @memberof Component.DialogSignupAlert * @desc Trigger local modal closure. */ handleClose = () => { signupError(); }; /** * @method render * @memberof Component.DialogSignupAlert * @desc Render the DialogLoginAlert form if the server return an error. */ render() { const actions = [ <FlatButton label={l10n.global.ok} primary={true} onClick={this.handleClose} /> ]; return ( <div> <Dialog actions={actions} modal={false} open={this.props.open} > <p>{this.props.message}</p> </Dialog> </div> ); } }
JavaScript
class KeyBoard extends Component { render() { const number = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]; return ( <table> <tbody> {number.map(row => { return ( <tr> {row.map(val => { return ( <button class="KeyBoard" onClick={() => this.props.handleKeyClick(val)}> {val} </button> ) })} </tr> ) })} <tr> <button class="KeyBoard" onClick={() => this.props.handleKeyClick(0)}> <Icon name='eraser' size='small' /> </button> </tr> </tbody> </table> ); } }
JavaScript
class Worker extends Service { constructor (method) { super(method); // self.worker = new Worker('validator.js'); this.method = method; this.machine = new Machine(); this.router = new Router(); this.behaviors = {}; } use (definition) { return this.router.use(definition); } /** * Handle a task. * @param {Vector} input Input vector. * @return {String} Outcome of the requested job. */ async compute (input) { let output = await this.machine.compute(input); console.log('[FABRIC:WORKER]', this.machine.clock, 'Computed output:', output); switch (input) { case 'PING': this.emit('pong'); break; } return output; } async route (path) { switch (path) { default: await this.compute(path); break; } } }
JavaScript
class OlLayerHandler { /** * * @param {string} id Id for this handler, which will be also the id of the layer created by this handler * @param {LayerHandlerOptions} [options] Optional configuration for this handler */ constructor(id, options = {}) { if (this.constructor === OlLayerHandler) { // Abstract class can not be constructed. throw new TypeError('Can not construct abstract class.'); } if (!id) { throw new TypeError('Id of this handler must be defined.'); } this._id = id; this._active = false; this._options = { ...getDefaultLayerOptions(), ...options }; } get id() { return this._id; } get active() { return this._active; } get options() { return this._options; } /** * Activates this handler and creates an ol layer. * @param {Map} olMap * @returns {BaseLayer} olLayer the layer which shoud be added to the map */ activate(map) { const layer = this.onActivate(map); this._active = true; return layer; } /** * Deactivates this handler. * @param {Map} olmap */ deactivate(map) { this.onDeactivate(map); this._active = false; } /** * Callback called when this handler is activated. Creates an ol layer. The layer must not be added to the map. * @abstract * @protected * @param {Map} olMap * @returns {BaseLayer} olLayer the layer which shoud be added to the map */ onActivate(/*eslint-disable no-unused-vars */ map) { // The child has not implemented this method. throw new TypeError('Please implement abstract method #onActivate or do not call super.onActivate from child.'); } /** * Callback called when this handler is deactivated. The corresponding layer is already removed from the map. * @abstract * @protected * @param {Map} olmap */ onDeactivate(/*eslint-disable no-unused-vars */ map) { // The child has not implemented this method. throw new TypeError('Please implement abstract method #onDeactivate or do not call super.onDeactivate from child.'); } }
JavaScript
class AdvancedFilter { /** * Create a AdvancedFilter. * @member {string} [key] The filter key. Represents an event property with * up to two levels of nesting. * @member {string} operatorType Polymorphic Discriminator */ constructor() { } /** * Defines the metadata of AdvancedFilter * * @returns {object} metadata of AdvancedFilter * */ mapper() { return { required: false, serializedName: 'AdvancedFilter', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'operatorType', clientName: 'operatorType' }, uberParent: 'AdvancedFilter', className: 'AdvancedFilter', modelProperties: { key: { required: false, serializedName: 'key', type: { name: 'String' } }, operatorType: { required: true, serializedName: 'operatorType', isPolymorphicDiscriminator: true, type: { name: 'String' } } } } }; } }
JavaScript
class LintDocBuilder extends _DocBuilder2.default { /** * execute building output. */ exec() { const results = []; const docs = this._find({ kind: ['method', 'function'] }); for (const doc of docs) { if (doc.undocument) continue; const node = _ASTNodeContainer2.default.getNode(doc.__docId__); const codeParams = this._getParamsFromNode(node); const docParams = this._getParamsFromDoc(doc); if (this._match(codeParams, docParams)) continue; results.push({ node, doc, codeParams, docParams }); } _results.push(...results); this._showResult(results); } /** * get variable names of method argument. * @param {ASTNode} node - target node. * @returns {string[]} variable names. * @private */ _getParamsFromNode(node) { let params; switch (node.type) { case 'FunctionExpression': case 'FunctionDeclaration': params = node.params || []; break; case 'ClassMethod': params = node.params || []; break; case 'ArrowFunctionExpression': params = node.params || []; break; default: throw new Error(`unknown node type. type = ${ node.type }`); } const result = []; for (const param of params) { switch (param.type) { case 'Identifier': result.push(param.name); break; case 'AssignmentPattern': if (param.left.type === 'Identifier') { result.push(param.left.name); } else if (param.left.type === 'ObjectPattern') { result.push('*'); } break; case 'RestElement': result.push(param.argument.name); break; case 'ObjectPattern': result.push('*'); break; case 'ArrayPattern': result.push('*'); break; default: throw new Error(`unknown param type: ${ param.type }`); } } return result; } /** * get variable names of method argument. * @param {DocObject} doc - target doc object. * @returns {string[]} variable names. * @private */ _getParamsFromDoc(doc) { const params = doc.params || []; return params.map(v => v.name).filter(v => !v.includes('.')).filter(v => !v.includes('[')); } _match(codeParams, docParams) { if (codeParams.length !== docParams.length) return false; for (let i = 0; i < codeParams.length; i++) { if (codeParams[i] === '*') { // nothing } else if (codeParams[i] !== docParams[i]) { return false; } } return true; } /** * show invalid lint code. * @param {Object[]} results - target results. * @param {DocObject} results[].doc * @param {ASTNode} results[].node * @param {string[]} results[].codeParams * @param {string[]} results[].docParams * @private */ _showResult(results) { const sourceDir = _path2.default.dirname(_path2.default.resolve(this._config.source)); for (const result of results) { const doc = result.doc; const node = result.node; const filePath = doc.longname.split('~')[0]; const name = doc.longname.split('~')[1]; const absFilePath = _path2.default.resolve(sourceDir, filePath); const comment = node.leadingComments[node.leadingComments.length - 1]; const startLineNumber = comment.loc.start.line; const endLineNumber = node.loc.start.line; const lines = _fsExtra2.default.readFileSync(absFilePath).toString().split('\n'); const targetLines = []; for (let i = startLineNumber - 1; i < endLineNumber; i++) { targetLines.push(`${ i }| ${ lines[i] }`); } console.log(`warning: signature mismatch: ${ name } ${ filePath }#${ startLineNumber }`); console.log(targetLines.join('\n')); console.log(''); } } }
JavaScript
class Store { // get cart items ID from local storage static getCartItemsID() { const keysArray = Object.keys(localStorage); return keysArray; } static getCartItemDetails(id) { let details; if (localStorage.getItem(id) === null) { details = []; } else { details = JSON.parse(localStorage.getItem(id)); } return details; } static addItemToCart(id, objDetails) { const details = Store.getCartItemDetails(id); details.push(objDetails); localStorage.setItem(id, JSON.stringify(details)); } static updateQtyForSize(id, size, newQty) { const details = Store.getCartItemDetails(id); details.forEach(detail => { if (detail.size === size) { detail.quantity = newQty; } }) localStorage.setItem(id, JSON.stringify(details)); } }
JavaScript
class Game { /** * @param {object} options * @param {(array: any[]) => any[]} [options.shuffle] */ constructor({shuffle = null} = {}) { this.store = new Store(); /** * @type {Object.<string, Player>} */ this.players = {}; this.trash = /** @type {Card[]} */ ([]); this.started = false; this.shuffle = shuffle || this.fisherYatesShuffle; } /** * @param {any[]} array */ fisherYatesShuffle(array) { let currentIndex = array.length; while (0 !== currentIndex) { const rIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; const temporaryValue = array[currentIndex]; array[currentIndex] = array[rIndex]; array[rIndex] = temporaryValue; } return array; } /** * @param {Player[]} ps */ initClients(ps) { const included = this.store.included .sort((a, b) => a.compareTo(b, {compareKind: false})) .map(c => c.name); ps.forEach(p => p.send({included})); const colors = this.store.getAllCards().reduce((o, c) => { o[c.name] = c.color; o["Buy: " + c.name] = c.color; return o; }, {}); ps.forEach(p => p.send({colors})); } /** * @param {boolean} debugMode */ async start(debugMode) { this.started = true; const ps = this.allPlayers(); this.initClients(ps.filter(p => p.connection.connected)); // disconnected clients will be initialized later ps.forEach(p => p.redrawHand()); if (debugMode) { ps[0].hand.push(...this.store.getAvailable(99, null)); ps[0].sendHand(); this.allLog("!!!!!! " + ps[0].name + " IS CHEATING!!!!!!"); } let turn = this.shuffle([...Array(ps.length).keys()])[0]; for (;;) { await ps[turn % ps.length].takeTurn(); ++turn; if (this.store.gameOver()) { this.allLog(""); this.allLog("GAME OVER!!!"); ps.sort((a, b) => b.getPoints() - a.getPoints()) // descending .map( p => `${p.name}: ${p.getPoints()} +VP: ${p.victory} Cards: ${this.getEndGame( p.allCards() )}` ) .forEach(line => this.allLog(line)); return; } } } /** * @param {Card[]} cards */ getEndGame(cards) { cards = cards.slice().sort((a, b) => a.compareTo(b)); const isPoint = /** @param {Card} c */ c => c.ofKind("victory") || c.ofKind("curse"); const byVictory = [...cards.filter(isPoint), ...cards.filter(c => !isPoint(c))]; const map = new Map(); byVictory.forEach(c => map.set(c.name, 1 + (map.get(c.name) || 0))); return Array.from(map, ([name, count]) => `${name} (${count})`).join(", "); } /** * @param {Connection} connection */ addPlayer(connection) { if (this.started) { throw new Error("Can't change players after game started"); } const name = connection.name; const player = new Player(connection, this); if (!Object.keys(this.players).length) { const setCards = setOrder.reduce((o, set) => { o[set] = this.store .optional() .filter(card => card.set === set) .map(c => c.name); return o; }, {}); player.send({isLeader: setCards}); player.send({ included: this.store .optional() .sort((a, b) => a.compareTo(b, {compareSet: true})) .map(c => c.name), }); } else { player.sendMessage("Waiting for the leader to start the game"); this.allLog(player.name + " joined"); } this.players[name] = player; connection.messageHandlers.chat = data => { this.allLog(player.name + ": " + data); }; connection.messageHandlers["gameStart"] = /** @param {{included: string[], debugMode: boolean}} data */ data => { this.store.init( data.included.map(n => cards[n]), this.allPlayers().length ); this.start(data.debugMode); }; connection.ws.addEventListener("close", () => { this.allLog(player.name + " disconnected"); }); } /** * @param {Connection} connection */ removePlayer(connection) { if (this.started) { throw new Error("Can't change players after game started"); } delete this.players[connection.name]; } allPlayers() { return Object.keys(this.players).map(n => this.players[n]); } /** * @param {Player} player */ otherPlayers(player) { return this.allPlayers().filter(p => p.name !== player.name); } /** * @param {Player} player * @param {(other: Player) => Promise<void>} attack */ parallelAttack(player, attack) { return Promise.all(this.otherPlayers(player).map(p => p.attacked(attack))); } /** * @param {Player} player * @param {(other: Player) => Promise<void>} attack */ async sequentialAttack(player, attack) { const ps = this.allPlayers(); ps.push(...ps.splice(0, ps.indexOf(player))); // Rotate around so player is ps[0] for (let i = 1; i < ps.length; ++i) { await ps[i].attacked(attack); } } /** * @param {string} text */ allLog(text) { for (const id in this.players) { this.players[id].sendMessage(text); } } /** * @param {Player} player * @param {string} cardName * @param {object} options * @param {boolean} [options.toHand] */ gainCard(player, cardName, {toHand = false} = {}) { if (!this.store.counts[cardName]) { throw new Error(`Out of ${cardName}`); } const card = cards[cardName]; if (toHand) { player.hand.push(card); } else { player.discardPile.push(card); } this.store.gain(card); this.allLog(`${player.name} gained ${cardName}`); } /** * @param {Player} player * @param {string} cardName */ tryGainCard(player, cardName) { if (this.store.counts[cardName]) { this.gainCard(player, cardName); } } /** * @param {Player} player * @param {Card} card */ trashPush(player, card) { this.allLog(`${player.name} trashed ${card.name}`); this.trash.push(card); } }
JavaScript
class ReadPerMinute { static rates = Object.freeze({ default: 200, ar: 181, zh: 260, nl: 228, en: 236, fi: 195, fr: 214, de: 260, he: 224, it: 285, ko: 226, es: 278, sv: 218, }) /** * Returns whether the specified lang is indexed in the rate list. * @param lang {string} Lang to test * @returns {boolean} True if the lang is indexed, false if not */ static isLangExist(lang) { return !!lang && !!ReadPerMinute.rates[lang] } /** * Parses a string, counts the number the words and divides it by the lang rate to get an estimated reading time. * The function returns an object containing the estimated time, the number of words and the rate used in the calculation. * @param text {string} String to parse. * @param lang {string} Lang used to retrieve the reading rate. * @returns {{rate: number, words: number, time: number}} Object containing the estimated time, the number of words and the rate used in the calculation. */ parse(text = '', lang = 'en') { if (!text) { text = '' } if (!ReadPerMinute.isLangExist(lang)) { lang = 'default' } const rate = ReadPerMinute.rates[lang] const words = text.trim().split(/\s+/).length return { time: Math.ceil(words / rate), words, rate, } } }
JavaScript
class List { #list = new Pair(); // cache #last = null; #size = -1; /** * * @param {*} head: Element * @param {*} tail: List<Element> */ constructor(head, tail = List.EMPTY_LIST) { if (head === null || head === undefined) return this; this.#list = new Pair(head, emptyTail(tail) ? new List() : tail); this.#last = this.getLast(); } head() { return this.#list.left(); } tail() { return this.#list.right(); } concat(list) { if (this.isEmpty()) return list; return new List(this.head(), this.tail().concat(list)); } concatTail(list, result = this) { if (this.isEmpty()) return list; if (list.isEmpty()) return result; return this.concatTail(list.tail(), result.push(list.head())); } push(element) { if (this.isEmpty()) return new List(element); return new List(this.head(), this.tail().push(element)); } sum = this.concat; map(f) {} isEmpty() { return this.#list.isEmpty(); } length() { if (this.#size >= 0) return this.#size; if (this.isEmpty()) return 0; this.#size = 1 + this.tail().length(); return this.#size; } getLast() { if (this.#last !== null) return this.#last; if (this.tail().isEmpty()) return this; this.#last = this.tail().getLast(); return this.#last; } toArray() { if (this.isEmpty()) return []; return [this.head()].concat(this.tail().toArray()); } toString() { if (this.isEmpty()) return "[]"; return `[${this.toStringRecursive()}]`; } toStringRecursive() { if (this.isEmpty()) return ""; return `${this.head()}, ${this.tail().toStringRecursive()}`; } static fromArray([head, ...tail]) { if (!head) return new List(); return new List(head, List.fromArray(tail)); } static of(...array) { return List.fromArray(array); } static EMPTY_LIST = new List(); static range = (init = 0) => (end, step = 1) => init < end ? new List(init, List.range(init + step)(end, step)) : List.EMPTY_LIST; static range0 = List.range(0); static rangeR = (init = 0) => (end, step = 1) => List.rangeTail(init, end, step, new List()); static rangeTail(init, end, step, result) { if (init >= end) return result; return List.rangeTail( init + step, end, step, result.concat(new List(init)) ); } }
JavaScript
class Debug { log(msg) { console.log(msg); } highlight(msg) { console.log('\x1b[36m%s\x1b[0m', msg); } warning(msg) { console.log('\x1b[33m%s\x1b[0m', msg); } error(msg) { console.log('\x1b[31m%s\x1b[0m', msg); } success(msg) { console.log('\x1b[32m%s\x1b[0m', msg); } }
JavaScript
class MediaFileNode extends FileNode { [Symbol.toStringTag] = "MediaFileNode"; constructor(node, masterKey) { super(node, masterKey); this.type = "mediaFile"; this.fileAttributesStr = node.fileAttributesStr; } fileAttributesStr; // [requires key] //todo mixin for it /** @returns {Promise<Uint8Array>} */ getThumbnail() { return FileAttributes.getThumbnail(this); }; /** @returns {Promise<Uint8Array>} */ getPreview() { return FileAttributes.getPreview(this); }; get thumbnail() { // todo others return FileAttributes.of(this).byType(FileAttributes.Thumbnail.type); } get preview() { return FileAttributes.of(this).byType(FileAttributes.Preview.type); } }
JavaScript
class Nodes { /** * @param {string|URL} url * @returns {Promise<SharedFileNode|SharedMediaFileNode|RootFolderNode|FolderNode|FileNode|MediaFileNode> * |Promise<(SharedFileNode|SharedMediaFileNode)[]|(RootFolderNode,FolderNode,FileNode,MediaFileNode)[]>} */ static async of(url) { const share = Share.fromUrl(url); return share.isFolder ? Nodes.getFolderNodes(share) : Nodes.getSharedNode(share); } /** * @param {string|URL} url * @returns {Promise<SharedFileNode|SharedMediaFileNode|RootFolderNode|FolderNode|FileNode|MediaFileNode>} */ static async node(url) { const share = Share.fromUrl(url); if (share.isFolder) { const nodes = await Nodes.getFolderNodes(share); if (nodes.selected) { return nodes.selected; } else { return nodes.root; } } else { return Nodes.getSharedNode(share); } } /** * @param {string|URL} url * @returns {Promise<(SharedFileNode|SharedMediaFileNode)[]|(RootFolderNode,FolderNode,FileNode,MediaFileNode)[]>} */ static async nodes(url) { const share = Share.fromUrl(url); if (share.isFolder) { return Nodes.getFolderNodes(share); } else { return [await Nodes.getSharedNode(share)]; } } /** * @param {Share} share * @returns {Promise<SharedFileNode|SharedMediaFileNode>} */ static async getSharedNode(share) { const nodeInfo = await MegaApi.requestNodeInfo(share.id); if (nodeInfo.fileAttributesStr) { return new SharedMediaFileNode(share, nodeInfo); } else { return new SharedFileNode(share, nodeInfo); } } /** * @param {Share} share * @returns {Promise<(RootFolderNode,FolderNode,FileNode,MediaFileNode)[]>} [note] The array have mixed type content */ static async getFolderNodes(share) { const masterKey = share.decryptionKeyStr ? MegaUtil.megaBase64ToArrayBuffer(share.decryptionKeyStr) : null; //logger.debug("[masterKey]", masterKey); const { nodes, rootId } = await MegaApi.requestFolderInfo(share.id); //logger.debug(`[requestFolderInfo("${share.id}").nodes]`, nodes); const folders = new Map(); // [note] JS's HashMap holds the insert order const files = []; // `masterKey` is null when the share has no specified key, // `node.decryptionKeyStr` is null when `k` of node info (from API) is an empty string (Mega's bug) //todo either handle it here (new classes for nodes without a key) // or in the node constructor modify its type to indicate this thing for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; let resultNode; node.parent = folders.get(node.parentId); // `undefine` for root if (node.type === "file") { if (node.fileAttributesStr) { resultNode = new MediaFileNode(node, masterKey); } else { resultNode = new FileNode(node, masterKey); } files.push(resultNode); // the parent node is always located before the child node, no need to check its existence [1][note] folders.get(resultNode.parentId).files.push(resultNode); } else if (node.type === "folder") { if (node.id === rootId) { // or `if (i === 0)` resultNode = new RootFolderNode(node, masterKey); } else { resultNode = new FolderNode(node, masterKey); folders.get(resultNode.parentId).folders.push(resultNode); // see [1] note } folders.set(node.id, resultNode); } nodes[i] = null; } // todo: rework – make an iterable class with these getters const resultArray = [...folders.values(), ...files]; const root = folders.get(rootId); const selected = resultArray.find(node => node.id === share.selectedId); Object.defineProperty(resultArray, "root", { get: () => root }); Object.defineProperty(resultArray, "selected", { get: () => selected }); Object.defineProperty(resultArray, "folders", { get: () => [...folders.values()] }); Object.defineProperty(resultArray, "files", { get: () => files }); //todo .mediaNodes return resultArray; } static isMediaNode(node) { return node.type === "sharedMediaFile" || node.type === "mediaFile"; } }
JavaScript
class Animation { constructor(id = "default", frames = [], frameDuration = 0, dontInterrupt = false) { this.id = id; this.frames = frames; this.frameDuration = frameDuration; this.dontInterrupt = dontInterrupt; } }
JavaScript
class Animator extends Component { constructor(entity, animations = [], currentAnimation = 0) { super(entity); this.animations = animations; this.currentAnimation = currentAnimation; this.timer = 0; this.currentFrameIndex = 0; this.dontInterrupt = false; } update(level) { this.timer -= deltaTime; if(this.timer <= 0) { // Reset the timer this.timer = this.animations[this.currentAnimation].frameDuration; this.currentFrameIndex += 1; // Make sure the frame index isn't out of bounds if(this.currentFrameIndex >= this.animations[this.currentAnimation].frames.length) { // This means the animation is finished, so reset if(this.dontInterrupt) { this.dontInterrupt = false; this.currentFrameIndex -= 1; } else this.currentFrameIndex = 0; } } } changeAnimation(id) { // If it's playing an Animation that isn't allowed to be interrupted, don't change animations if(this.dontInterrupt) return; for(var i = 0; i < this.animations.length; i++) { if(this.animations[i].id == id) { this.currentAnimation = i; this.timer = 0; this.currentFrameIndex = 0; this.dontInterrupt = this.animations[i]; } } } getFrame() { // Return the current character that should be rendered return this.animations[this.currentAnimation].frames[this.currentFrameIndex]; } }
JavaScript
class Tag { static get(tagId){ return this.table.get(tagId) } static get SAVED_PROPERTIES(){ if (undefined === this._savedproperties){ this._savedproperties = [ {id:'id' , type:'number', required:true} , {id:'type' , type:'string', required:true} , {id:'content' , type:'string', required:true} , {id:'intensity' , type:'number', required:true} , {id:'top' , type:'number', required:true} , {id:'height' , type:'number', required:true} , {id:'fixed' , type:'boolean', required:true} , {id:'date' , type:'number', required:true} ] } return this._savedproperties ; } /** Pour faire tourner la fonction +method+ sur tous les tags +method+ :: Si [Function] On passe en premier argument le tag [Tag] Si [String] C'est une méthode d'instance qu'on invoque. **/ static forEachTag(method) { if ( method instanceof Function ) { this.items.forEach(tag => method(tag)) } else if ('string' == typeof method ) /* => méthode de tag */ { this.items.forEach(tag => tag[method].call(tag)) } else { console.error("La méthode devrait être un string (méthode de tag) ou une fonction", method) } } /** Faire tourner la méthode +method+ [Function] avec toutes les données des types en arguments respectifs. **/ static forEachType(method) { Object.values(DATA_TAG_TYPES).forEach(dtype => method.call(null, dtype)) } /** Pour afficher/masquer les tags du type +tagType+ [String] +tagType+:: [String] L'identifiant du type (clé dans DATA_TAG_TYPES) **/ static toggleType(tagType, showIt){ this.forEachTag(tag => { let ok ; if ( tagType.match('fixed') ) { ok = tag.fixed.value == (tagType == 'fixed') } else { ok = tag.type.value == tagType } ok && tag[showIt?'show':'hide'].call(tag) }) } /** Chargement des tags du document **/ static load(){ console.log('-> Tag::load') Ajax.send({ data:{ script:'get-tags' , args:{} } , success: this.onLoaded.bind(this) }) } static onLoaded(ret){ if (ret.error){ console.error("Impossible de charger les tags…") } else { // console.log("ret", ret) Object.values(ret.tags).forEach(dtag => new Tag(dtag)) this.build() } } /** Construction de tous les tags **/ static build(){ // log("Construction des tags ", this.items) this.items.forEach(tag => tag.build()) } /** Sauvegarde tous les tags Note : ça ne se fait que lorsqu'ils ne sont pas nombreux Sinon, ensuite, on fait du cas par cas. **/ static save(){ return console.warn("Je ne dois plus enregistrer tous les tags") } static get items(){ return this._items || (this._items = []) } static get table(){ return this._table || ( this._table = new Map() ) } static set table(v){this._table = v} /** Ajoute un nouveau tag **/ static addNewItem(data) { console.log('-> Tag::addNewItem') // showBacktrace() Object.assign(data, { id: this.nextId() , date: Number(new Date()) }) // Le type, en fonction de la lettre pressée (if any) et des // settings des raccourcis-souris data.type = this.newTagTypeFor(data) delete data.letter console.log("data.type = '%s'", data.type, data) data.content || (data.content = "Nouveau commentaire") delete data.left // pas besoin const tag = new Tag(data) tag.isNew = true tag.build({}) // On met le tag en édition pour pouvoir le sauver ensuite tag.edit({top:data.top, left:data.left}) return tag } static newTagTypeFor(data){ if ( data.type ) return data.type if (data.letter) { return PDFTagger.config.letter2type(data.letter) } else { log("- aucune lettre pressée -") return 'com' } } static reset(){ delete this.tag2index } /** Fonction complète de destruction du tag C'est celle-ci qui doit être utilisée en priorité **/ static removeItem(tag){ console.log('-> Tag::remove') tag.remove() const indexItem = this.indexOf(tag) this.items.splice(indexItem,1) this.table.delete(tag.id) this.reset() } /** +return+:: [Integer] Index du tag +tag+ dans les items **/ static indexOf(tag){ if ( undefined === this.tag2index) { this.tag2index = {} var index ; this.items.forEach(tag => { Object.assign(this.tag2index, {[tag.id]: index++}) }) } return this.tag2index[tag.id] } /** Pour ajouter une tag à la liste Attention, cette méthode est employée à l'instanciation du tag. Elle n'est pas à confondre avec la méthode addNewItem qui crée un nouvel item (et donc enregistre la nouvelle liste) **/ static addItem(tag){ if ( undefined === tag.id.value ) { tag.id.value = this.nextId() } console.log("tag id = %i", tag.id.value) this.items.push(tag) this.table.set(tag.id.value, tag) } static nextId(){ this.lastId = this.lastId || 0 return ++ this.lastId } /** --------------------------------------------------------------------- * * INSTANCE * *** --------------------------------------------------------------------- */ constructor(data){ // log(data) for(var k in data) this[k].value = data[k] ; this.set(data, /* prop trait plat */ true, /* save = */ false) this.constructor.addItem(this) this.onMouseDown = this.onMouseDown.bind(this) this.onMouseMove = this.onMouseMove.bind(this) this.onMouseUp = this.onMouseUp.bind(this) } // Pour écrire un message en console avec une référence à l'élément log(msg,args){ log(`[${this.ref}] ${msg}`, args) } get ref(){return this._ref||(this._ref = `Tag#${this.id.value}`)} /** Pour sauver le tag **/ save(){ this.log('-> save') Ajax.send({ data:{ script:'save-tag' , args:{tag:this.toJson} } , success: this.onSaved.bind(this) }) } onSaved(ret){ if ( ret.error ) { console.error("Une erreur est survenue : ", ret.error) console.log(ret) } else { this.isNew = false log("Enregistrement effectué avec succès", ret) } } /** Destruction du tag **/ destroy(){ this.log('-> destroy') Ajax.send({ data:{ script: 'destroy-tag' , args:{tagId:this.id.value} } , success: this.onSaved.bind(this) }) } onDestroyed(ret){ if ( ret.error ) { console.error("Une erreur est survenue : ", ret.error) } else { log("Destruction effectuée avec succès", ret) } } edit(options){ log('-> Tag#edit') TagEditor.edit(this, options) log('<- Tag#edit') } show(){ this.obj.classList.remove('noDisplay')} hide(){ this.obj.classList.add('noDisplay')} /** @private Méthode de destruction du tag (utiliser la méthode de classe) **/ remove(){ this.log('-> remove') this.unobserve() this.obj.remove() this.isNew || this.destroy() } /** Pour définir ou redéfinir les données **/ set(data, propTraitPlat = false, saveIfChanged = false){ this.log('-> set') let tagHasChanged = false ; for(var k in data){ let tprop = this[k] var oldValue = tprop._value var newValue = data[k] let propHasChanged = oldValue != newValue tprop[propTraitPlat?'_value':'value'] = data[k] if ( propHasChanged ) tagHasChanged = true ; } tagHasChanged && this.domUpdate() if ( tagHasChanged && saveIfChanged ){ log("des valeurs ont changées, je dois enregistrer la nouvelle donnée.") this.save() } } domUpdate(){ log('-> Tag#domUpdate') this.peuple() this.setClass() this.updateHeight() } /** Retourne le code pour enregistrement **/ get toJson(){ var h = {} this.constructor.SAVED_PROPERTIES.forEach( dprop => { let value = this[dprop.id] ; if ( value instanceof TagProperty ) { value = value.value } else { console.log("La propriété '%s' n'est pas une TagProperty", dprop.id) } Object.assign(h, {[dprop.id]: value}) }) return h } /* Events method */ /** **/ onMouseDown(ev){ this.log('-> onMouseDown') this.mousedownTime = Number(ev.timeStamp) this.clientYStart = Number(ev.clientY) this.topStart = Number(this.obj.offsetTop) this.setMovable() stopEvent(ev) } onMouseUp(ev){ this.log('-> onMouseUp') let mTimeDown ; if ( ! this.mousedownTime ) { // Cela arrive par exemple quand on clique sur une poignée du tag // Il faut alors ne rien faire ici et ne surtout pas interrompre // l'évènement return true } else { mTimeDown = Number(this.mousedownTime) delete this.mousedownTime } // console.log({ // 'temps mousedown': mTimeDown // , 'temps mouseup':ev.timeStamp // , 'is click': (ev.timeStamp < mTimeDown + 1) // }) if ( ev.timeStamp < mTimeDown + 500) { // C'est un vrai click, pas un déplacement this.unsetMovable() this.edit() } else { this.unsetMovable() this.onEndMoving(ev) } } onMouseMove(ev){ stopEvent(ev) this.obj.style.top = `${this.topStart + (ev.clientY - this.clientYStart) + 10}px` } onEndMoving(ev){ this.log('-> onEndMoving') this.top.value = this.topStart + (ev.clientY - this.clientYStart) + 10 this.save() return stopEvent(ev) } // Pour rendre le tag déplaçable setMovable(){ this.obj.classList.add('moving') this.obj.onmouseup = this.onMouseUp window.onmousemove = this.onMouseMove } // Pour fixer le tag (non déplaçable) unsetMovable(){ this.obj.classList.remove('moving') this.obj.onmouseup = null window.onmousemove = null } /* DOM methods */ build(){ const div = DCreate('DIV', { id: `tag-${this.id.value}` , class: this.cssClass , style:`top:${this.top.value - 10}px;height:${this.height.value||20}px;` , inner: [ DCreate('SPAN', {class:'mark-stylo'}) , DCreate('SPAN', {class:'intensity'}) , DCreate('SPAN', {class:`fixed`}) , DCreate('SPAN', {class:'content'}) , DCreate('SPAN', {class:'height-handler'}) ]}) this._obj = div UI.bandeSensible.append(div) this.domUpdate() this.observe() } peuple(){ this.content.domUpdate() this.fixed.domUpdate() this.intensity.domUpdate() } /** Définir la classe du tag Cette classe définit son aspect et dépend de son type **/ setClass(){ this.log(`-> setClass ('${this.cssClass}')`) this.obj.className = this.cssClass } get cssClass(){ try { return `tag ${this.type.value} ${this.positivityClass}` } catch (err) { var errors = [] if ( !this.obj ) { errors.push('this.obj est non défini')} if ( !this.type) { errors.push('this.type est non défini')} else if ( !(this.type instanceof TagProperty) ) {errors.push('this.type devrait être une TagProperty')} console.error("Une erreur est survenue dans Tag#setClass :", err) console.error(errors.join("\n")) } } observe(){ this.obj.onmousedown = this.onMouseDown this.heightHandler.onmousedown = this.onHeightHandlerMouseDown.bind(this) } unobserve(){ this.obj.onmousedown = null this.heightHandler.onmousedown = null } onHeightHandlerMouseDown(ev){ this.log("-> onHeightHandlerMouseDown") window.onmouseup = this.onHeightHandlerMouseUp.bind(this) window.onmousemove = this.onHeightHandlerMouseMove.bind(this) stopEvent(ev) this.offsetYonStart = ev.clientY this.heightOnStart = this.height.value || this.obj.offsetHeight log("<- onHeightHandlerMouseDown") return false } onHeightHandlerMouseUp(ev){ this.log("-> onHeightHandlerMouseUp") const diff = ev.clientY - this.offsetYonStart this.height.value = this.heightOnStart + diff this.updateHeight() window.onmouseup = null ; window.onmousemove = null ; this.save() log("<- onHeightHandlerMouseUp") return stopEvent(ev) } onHeightHandlerMouseMove(ev){ log("-> onHeightHandlerMouseMove") stopEvent(ev) // console.log("ev:", ev) const diff = ev.clientY - this.offsetYonStart // console.log("Je déplace de ", diff) // console.log("Nouvelle hauteur : ", this.heightOnStart + diff) this.updateHeight(this.heightOnStart + diff) } // Régler la hauteur du tag updateHeight(newHeight){ newHeight = `${newHeight||this.height.value}px` this.obj.style.height = newHeight this.markStylo.style.height = newHeight } /* Properties */ // NB: TagProperty est défini ci-dessous, pour le moment get id(){return this._id || (this._id = new TagProperty(this, 'id'))} get type(){return this._type || (this._type = new TagProperty(this, 'type'))} get content(){return this._content || (this._content = new TagProperty(this, 'content'))} get fixed(){return this._fixed || (this._fixed = new TagProperty(this, 'fixed'))} get intensity(){return this._intensity || (this._intensity = new TagProperty(this, 'intensity'))} get top(){return this._top || (this._top = new TagProperty(this, 'top'))} get height(){return this._height || (this._height = new TagProperty(this, 'height'))} get date(){return this._date || (this._date = new TagProperty(this, 'date'))} /* State methods */ /** +return+ true si c'est un commentaire positif, false dans le cas contraire C'est en fonction du type qu'on le détermine **/ get isPositive(){ return (DATA_TAG_TYPES[this.type.value].positivity === 1) } get positivity(){return DATA_TAG_TYPES[this.type.value].positivity} get positivityClass(){ switch(this.positivity){ case 1 : return 'pos' ; case -1 : return 'neg' ; case 0 : return 'neu' ; } } /* DOM properties */ // Mark "de stylo" près du document get markStylo(){ return this._markstylo || (this._markstylo = DGet('.mark-stylo', this.obj)) } // Poignée pour régler la hauteur get heightHandler(){ return this._heighthandler || (this._heighthandler = DGet('.height-handler', this.obj)) } // DOM élément get obj(){ return this._obj } // jQuery objet get jqObj(){return $(this.obj)} }
JavaScript
class FileSystem { constructor() { this.root = new FsDir(FS_ROOT_NAME); this.pointer = this.root; } /** * Change pointer to passed directory * TODO: Fix exception throwing * * @param {String[]} pathTo */ cd(pathTo) { const unit = this.get(pathTo); if (!unit) { throw new Error('Invalid path'); } if (unit.type != FS_UNIT_TYPE.DIR) { throw new Error(`${pathTo} is not a directory`); } this.pointer = unit; } /** * Get formatted path according to pointer * * @returns {String} */ pwd() { let current = this.pointer; if (current === this.root) { return '/'; } else { const path = []; do { path.push(current.name) current = current.parentDir; } while (current !== this.root); return `/${path.reverse().join('/')}`; } } /** * Get root dir content * * @returns {FsUnit[]} */ get content() { return this.root.content; } /** * Get byte size of root dir * * @returns {Number} */ get size() { return this.root.size; } /** * Create new dir or file in passed location. * Check if location exists * TODO: Fix exceptions * * @param {FsUnit} fsUnit * @param {String[]} fsUnitPath Full path to fsUnit. Should not contain new unit name * @returns {FsUnit} */ add(fsUnit, fsUnitPath) { if (fsUnitPath.length > 1) { if (fsUnit.name !== fsUnitPath[fsUnitPath - 1]) { throw new Error('Last element of path should contain fs unit name'); } const parentUnit = this.get(fsUnitPath.slice(0, -1)); if (!parentUnit) { throw new Error('Unit not exists'); } if (parentUnit.type !== FS_UNIT_TYPE.DIR) { throw new Error('Should be directory'); } fsUnit.parentDir = parentUnit; parentUnit.update(fsUnit); } else { fsUnit.parentDir = this.root; this.root.update(fsUnit); } return fsUnit; } // TODO: implement removal method remove(fsUnit) { if (fsUnitPath.length > 1) { } else { fsUnit.parentDir = this.root; this.root.remove(fsUnit); } } /** * Get file or dir by full path * * @param {String[]} fsUnitPath * @returns {FsUnit|undefined} */ get(fsUnitPath) { if (fsUnitPath.length >= 1) { let unit = undefined; let unitPosition = 0; do { if (unitPosition == 0) { unit = this.root.get(fsUnitPath[unitPosition]); } else if (unit.type == FS_UNIT_TYPE.DIR) { unit = unit.get(fsUnitPath[unitPosition]); } unitPosition++; } while(unitPosition < fsUnitPath.length && unit); return unit; } else { return this.root; } } }
JavaScript
class Navigation extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { open: false, }; _.bindAll([ 'handleOpen', ]); } handleOpen = () => this.setState({ open: !this.state.open }); render() { const fullNav = ( <NavBar background={this.props.background}> <span style={styles.logoFont}>hashtgd</span> <ul> <li style={styles.logo}> <Button color='contrast' style={styles.logoFont} href='/'> hashtgd </Button> </li> <div> <li> <Button color='contrast' href='/orthodontists' style={styles.button}> FOR ORTHODONTISTS </Button> </li> <li> <Button color='contrast' style={styles.button} href='/thesite'> WHAT WE OFFER </Button> </li> <li> <Button color='contrast' style={styles.button} href='/pricing'> WHAT'S IT COST? </Button> </li> <li> <Button color='contrast' style={styles.button} href='/book'> BOOK ONLINE </Button> </li> <li> <Button color='contrast' href='/contact' style={styles.button}> CONTACT US </Button> </li> <li> <Button color='contrast' style={styles.button} href="/about"> ABOUT US </Button> </li> </div> </ul> </NavBar> ); const sideNav = ( <div> <ListItem > <Hamburger > <Button style={styles.darkBurger} onClick={this.handleOpen}> &#8801; </Button> </Hamburger> </ListItem> <br /> <List className='list' disablePadding> <ListItem> <Button color='contrast' href='/' style={styles.button} > <ListItemText primary='Home' /> </Button> </ListItem> <Divider /> <ListItem> <Button color='contrast' style={styles.button} href='/orthodontists'> <ListItemText primary='FOR ORTHODONTISTS' /> </Button> </ListItem> <Divider /> <ListItem> <Button color='contrast' style={styles.button} href='/pricing'> <ListItemText primary="WHAT'S IT COST" /> </Button> </ListItem> <Divider /> <ListItem> <Button color='contrast' style={styles.button} href='/thesite'> <ListItemText primary='What we can do' /> </Button> </ListItem> <Divider /> <ListItem > <Button color='contrast' style={styles.button} href='/book'> <ListItemText primary='Book Online' /> </Button> </ListItem> <Divider /> <ListItem > <Button color='contrast' style={styles.button} href="/about"> <ListItemText primary='About' /> </Button> </ListItem> <Divider /> <ListItem button href="/contact"> <Button color='contrast' href='/contact' style={styles.button}> <ListItemText primary='Contact' /> </Button> </ListItem> <Divider /> </List> </div> ); return ( <section> <Drawer open={this.state.open} onRequestClose={this.handleOpen} onClick={this.handleOpen} anchor='left' style={styles.drawer} className='drawer' > {sideNav} </Drawer> <Hamburger > <Button onClick={this.handleOpen} color='contrast' style={styles.lightBurger}> &#8801; </Button> </Hamburger> {fullNav} </section> ); } }
JavaScript
class AbstractCamera{ constructor(graphics){ this.graphics = graphics; this.loc = new XYZ(0, 0, 0); this.rot = new Vec(0, 0, 0); this.velo = new Vec(0, 0, 0); this.rotVelo = new Vec(0, 0, 0); this.scale = 1; this.scaleVelo = 0; this.target = {}; //some constants to alter the targetting system this.speed = { scale: 600, rot: 600, loc: 600 } this.targetForce = { scale: 2, rot: 3, loc: 3 } this.targetFriction = { scale: 0.8, rot: 0.8, loc: 0.8 } this.targetFullRotations = false; //location and rotation change var This = this; this.loc.onChange(function(){ This.graphics.__updateHtmlShapesLoc(); }); this.rot.onChange(function(){ This.graphics.__updateHtmlShapesLoc(); }); var This = this; graphics.onUpdate(function(time){ //move to target pos if defined if(This.target.loc){ var delta = This.loc.getVecTo(This.target.loc); This.velo.add(delta.mul(time * This.targetForce.loc)); } //move to target pos if defined if(This.target.rot){ var delta = This.rot.getVecTo(This.target.rot); if(!this.targetFullRotations) //modulo centered around 0 delta.mod(Math.PI*2).add(Math.PI*3).mod(Math.PI*2).sub(Math.PI); This.rotVelo.add(delta.mul(time * This.targetForce.rot)); } //move to target pos if defined if(This.target.scale){ var delta = This.target.scale-This.scale; This.scaleVelo += delta * time * This.targetForce.scale; } //apply velocity This.velo.mul(1-This.targetFriction.loc); //drag/friction This.rotVelo.mul(1-This.targetFriction.rot); This.scaleVelo *= 1-This.targetFriction.scale; if(This.velo.getLength()>1e-6/This.getScale()) This.loc.add(new Vec(This.velo).mul(time * This.speed.loc)); if(This.rotVelo.getLength()>1e-6) This.rot.add(new Vec(This.rotVelo).mul(time * This.speed.rot)); if(Math.abs(This.scaleVelo)>1e-5) This.setScale(This.scale + This.scaleVelo*time * This.speed.scale); }); this.windowSizeScaleFactor = 1; //some scaling factor that depands on the visualisation area size } __updateLoc(){} //some methods to take care of scaling on window resize setWindowSize(width, height){ var ratio = width/height; if(ratio>16/9){ this.windowSizeScaleFactor = height/1080; }else{ this.windowSizeScaleFactor = width/1920; } this.setScale(this.getScale()); return this; } getTotalScale(){ return this.scale*this.windowSizeScaleFactor; } //position setX(x){ this.loc.setX(x); return this; } getX(){ return this.loc.getX(); } setY(y){ this.loc.setY(y); return this; } getY(){ return this.loc.getY(); } setZ(z){ this.loc.setZ(z); return this; } getZ(){ return this.loc.getZ(); } setLoc(x, y, z){ this.loc.set(x, y, z); return this; } getLoc(){ return this.loc; } //rotation setXRot(x){ this.rot.setX(x); return this; } getXRot(){ return this.rot.getX(); } setYRot(y){ this.rot.setY(y); return this; } getYRot(){ return this.rot.getY(); } setZRot(z){ this.rot.setZ(z); return this; } getZRot(){ return this.rot.getZ(); } setRot(x, y, z){ this.rot.set(x, y, z); return this; } getRot(){ return this.rot; } //scaling setScale(scale){ this.scale = scale; this.graphics.__updateHtmlShapesLoc(); return this; } getScale(){ return this.scale; } //velocity getVelo(){ return this.velo; } getRotVelo(){ return this.rotVelo(); } setScaleVelo(scaleVelo){ this.scaleVelo = scaleVelo; return this; } getScaleVelo(){ return this.scaleVelo; } //targetting methods setTargetLoc(x, y, z){ if(x instanceof AbstractShape) x = x.getLoc(); if(x.x==null) x = new XYZ(x, y, z); this.target.loc = x; return this; } setTargetRot(x, y, z){ if(x instanceof AbstractShape) x = x.getRot(); if(x.x==null) x = new XYZ(x, y, z); this.target.rot = x; return this; } setTargetScale(scale){ if(scale instanceof AbstractShape) scale = 1/scale.getScale(); this.target.scale = scale; return this; } setTarget(loc, rot, scale){ this.setTargetLoc(loc); this.setTargetRot(rot); this.setTargetScale(scale); return this; } setTargetFullRotations(rotations){ this.targetFullRotations = rotations; return this; } getTargetFullRotations(){ return this.targetFullRotations; } //mouse interaction translateScreenToWorldLoc(x, y, z){} translateWorldToScreenLoc(x, y, z){} }
JavaScript
class Forgot { /* * Initializes the model */ constructor() { this.form = document.querySelector('form') // handle submit this.form.addEventListener('submit', function(e) { shared.toast.show('loading', 'Sending reset email...', false) let data = { email: document.querySelector('#forgot-email').value }, context = this // post form var xhr = new XMLHttpRequest() xhr.open('POST', '/api/user/forgot', true) xhr.setRequestHeader('Content-Type', 'application/json') xhr.send(JSON.stringify(data)) xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 400) { shared.toast.show('success', 'Email sent!', true) location.href = '/reset' } else { shared.toast.show('failure', 'There was an error reseting your password.', true) } } // end xhr e.preventDefault() return false }) } }
JavaScript
class Home extends React.Component { constructor(props) { super(props); this.state = { //randomly generated graph data rData: { more: this.rNum(), less: this.rNum(), action: this.rNum(), inaction: this.rNum(), known: this.rNum(), unknown: this.rNum(), pedestrians: this.rNum(), passengers: this.rNum() }, //global average graph data aData: { more: this.rNum(), less: this.rNum(), action: this.rNum(), inaction: this.rNum(), known: this.rNum(), unknown: this.rNum(), pedestrians: this.rNum(), passengers: this.rNum() } } } componentDidMount() { //Fetch summary data for radar graph axios.get('https://ethicsenginebackend.herokuapp.com/summary') .then(res => { const aPrefs = res.data[0]; this.setState({ aData: { more: aPrefs.more, less: aPrefs.less, action: aPrefs.action, inaction: aPrefs.inaction, known: aPrefs.known, unknown: aPrefs.unknown, pedestrians: aPrefs.pedestrians, passengers: aPrefs.passengers } }) }) //Set values between .15 and .85 for user data every 2 seconds this.interval = setInterval(() => this.setState({ rData: { more: this.rNum(), less: this.rNum(), action: this.rNum(), inaction: this.rNum(), known: this.rNum(), unknown: this.rNum(), pedestrians: this.rNum(), passengers: this.rNum() } }), 2500); } //Clears interval with random number generation componentWillUnmount() { clearInterval(this.interval); } //returns random number between .15 and .85 rNum() { return Math.floor(Math.random() * (61) + 15) / 100; } render() { return <div className="home-container"> <Container fluid id="home-fluid"> <Row> <Col lg={6} > <h1>{Text[this.props.language].Home.Headings.main}</h1> <h6>{Text[this.props.language].Home.Headings.sub}</h6> <p>{Text[this.props.language].Home.Paragraphs.main}</p> <Link to="/quiz"><button>{Text[this.props.language].Home.Buttons.start}</button></Link> </Col> <Col lg={6} > <Radar data={{ labels: [Text[this.props.language].Radar.Labels.more, Text[this.props.language].Radar.Labels.less, Text[this.props.language].Radar.Labels.action, Text[this.props.language].Radar.Labels.inaction, Text[this.props.language].Radar.Labels.known, Text[this.props.language].Radar.Labels.unknown, Text[this.props.language].Radar.Labels.pedestrians, Text[this.props.language].Radar.Labels.passengers], datasets: [ { label: Text[this.props.language].Radar.Headings.you, data: [this.state.rData.more, this.state.rData.less, this.state.rData.action, this.state.rData.inaction, this.state.rData.known, this.state.rData.unknown, this.state.rData.pedestrians, this.state.rData.passengers], backgroundColor: 'rgb(255, 103, 135, .3)', borderColor: 'rgb(255, 103, 135)', pointBackgroundColor: 'rgb(255,103,135)', pointBorderColor: '#FFFFFF' }, { label: Text[this.props.language].Radar.Headings.average, data: [(this.state.aData.more / Totals.more).toFixed(2), (this.state.aData.less / Totals.less).toFixed(2), (this.state.aData.action / Totals.action).toFixed(2), (this.state.aData.inaction / Totals.inaction).toFixed(2), (this.state.aData.known / Totals.known).toFixed(2), (this.state.aData.unknown / Totals.unknown).toFixed(2), (this.state.aData.pedestrians / Totals.pedestrians).toFixed(2), (this.state.aData.passengers / Totals.passengers).toFixed(2)], backgroundColor: 'rgb(54, 162, 235, .3)', borderColor: 'rgb(54, 162, 235)', pointBackgroundColor: 'rgb(54, 162, 235)', pointBorderColor: '#FFFFFF' } ] }} options={{ scale: { ticks: { suggestedMin: 0, suggestedMax: 1. } } }} /> </Col> </Row> </Container> </div> } }
JavaScript
class EndpointsTree { constructor() { /** * @type ApiEndpointsTreeItem[] */ this.result = []; /** @type Record<string, number> */ this.indents = {}; } /** * @param {ApiEndPointListItem[]} list Sorted list of endpoints. * @returns {ApiEndpointsTreeItem[]} */ create(list) { if (!Array.isArray(list) || !list.length) { return []; } const { result, indents } = this; let prev = /** @type ApiEndpointsTreeItem */ (null); for (let i = 0, len = list.length; i < len; i++) { const item = /** @type ApiEndpointsTreeItem */ ({ ...list[i], indent: 0, label: '' }); const { path } = item; const parts = path.split('/'); const hasParts = parts.length > 1 && !(parts.length === 2 && !parts[0]); if (i === 0) { if (hasParts) { const parent = { indent: 0, path: parts.slice(0, parts.length - 1).join('/'), label: undefined, operations: [], hasChildren: true, }; parent.label = parent.path; prev = parent; indents[parent.path] = item.indent; result.push(parent); } else { prev = item; indents[item.path] = item.indent; result.push(this.prepareLabel(item)); continue; } } // this is similar to the next block but is faster when the previous item is parent. if (path.startsWith(prev.path)) { item.indent = prev.indent + 1; prev.hasChildren = true; indents[item.path] = item.indent; result.push(this.prepareLabel(item, prev.path)); prev = item; continue; } const upPath = this.findParentEndpoint(parts); if (upPath) { item.indent = indents[upPath] + 1; const parent = result.find((p) => p.path === upPath); parent.hasChildren = true; indents[item.path] = item.indent; result.push(this.prepareLabel(item, upPath)); } else { if (hasParts) { const info = this.findCommonRootInfo(parts); if (info) { const parent = { indent: info.item.indent, path: info.common, label: info.common, operations: [], hasChildren: true, }; this.postInsertParent(parent); indents[parent.path] = parent.indent; result.splice(info.index, 0, parent); item.indent = parent.indent + 1; indents[item.path] = item.indent; result.push(this.prepareLabel(item, parent.path)); continue; } } item.indent = 0; indents[item.path] = item.indent; result.push(this.prepareLabel(item)); } prev = item; } return result; } /** * @param {string[]} parts Path parts of the currently evaluated endpoint */ findParentEndpoint(parts) { const { indents } = this; const list = Array.from(parts); const compare = Object.keys(indents).reverse(); // eslint-disable-next-line no-constant-condition while (true) { const path = list.join('/'); if (!path) { break; } const upPath = compare.find((candidate) => path.startsWith(candidate)); if (upPath) { return upPath; } list.pop(); if (!list.length) { break; } } return undefined; } /** * @param {string[]} parts Path parts of the currently evaluated endpoint * @returns {CommonRootInfo|undefined} */ findCommonRootInfo(parts) { const { result } = this; const list = Array.from(parts); // eslint-disable-next-line no-constant-condition while (true) { list.pop(); if (!list.length) { break; } const path = list.join('/'); if (!path) { break; } const index = result.findIndex((candidate) => candidate.path.startsWith(path)); if (index !== -1) { return { index, item: result[index], common: path, }; } } return undefined; } /** * @param {ApiEndpointsTreeItem} item * @param {string=} prevPath * @returns {ApiEndpointsTreeItem} */ prepareLabel(item, prevPath) { const { name, path, indent } = item; item.label = path; if (name) { item.label = name; } else if (indent > 0 && prevPath) { item.label = item.label.replace(prevPath, ''); item.hasShortPath = true; if (!item.label.startsWith('/')) { item.label = `/${item.label}`; } } return item; } /** * Updates paths and indentation of children after inserting a new (abstract) parent. * @param {ApiEndpointsTreeItem} parent */ postInsertParent(parent) { const { result } = this; result.forEach((item) => { const { path } = item; if (path.startsWith(parent.path)) { item.indent += 1; item.label = item.label.replace(parent.path, ''); } }); } }
JavaScript
class ViewMixin extends superclass { /** * @constructs * @param {String} [cssClass] additional CSS classes to set to the view element * @param {...*} args parent class parameters */ constructor({cssClass = null, ...args} = {}) { super(args) /* ViewMixin is prepared to be initialized multiple times along the inheritance path; * this may happen when inheriting ViewMixin more than once through mixins */ if (this._html === undefined) { this._html = null } if (this._state === undefined) { this._state = STATE_NORMAL this._warningMessage = null this._errorMessage = null this._progressPercent = null } if (!this._cssClass) { this._cssClass = cssClass } else { this._cssClass += ` ${cssClass}` } } /* HTML */ /** * Create the HTML element of this view. * @abstract * @returns {jQuery} */ makeHTML() { return $('<div></div>') } /** * Override this to further initialize the HTML element of this view. * @param {jQuery} html the HTML element to be initialized */ initHTML(html) { } /** * Return the HTML element of this view. * @returns {jQuery} */ getHTML() { if (this._html == null) { this._html = this.makeHTML() this.initHTML(this._html) if (this._cssClass) { this._html.addClass(this._cssClass) } this.init() } return this._html } /** * Tells if the HTML element of this view has been created. * @return {Boolean} */ hasHTML() { return this._html != null } /** * Initialize the view. Called after the HTML has been created and initialized. */ init() { } /* State */ /** * Update the current state. * @param {String} state the desired state */ setState(state) { /* Make sure we have the HTML created before switching states */ this.getHTML() if (this._state !== state) { this.leaveState(this._state, state) } let oldState = this._state this._state = state this.enterState(oldState, state) } /** * Return the current view state. * @returns {String} */ getState() { return this._state } /** * Define the behavior of the view when entering states. Entering a state usually means showing a visual element * corresponding to that state. * @param {String} oldState * @param {String} newState */ enterState(oldState, newState) { switch (newState) { case STATE_NORMAL: break case STATE_WARNING: this.showWarning(this._warningMessage) break case STATE_ERROR: this.showError(this._errorMessage) break case STATE_PROGRESS: this.showProgress(this._progressPercent) break } } /** * Define the behavior of the view when leaving states. Leaving a state usually means hiding a visual element * corresponding to that state. * @param {String} oldState * @param {String} newState */ leaveState(oldState, newState) { switch (oldState) { case STATE_NORMAL: break case STATE_WARNING: this._warningMessage = null this.hideWarning() break case STATE_ERROR: this._errorMessage = null this.hideError() break case STATE_PROGRESS: this._progressPercent = null this.hideProgress() break } } /* Progress */ /** * Put the view in the progress state or updates the progress. The view state is set to * {@link qui.views.STATE_PROGRESS}. * * It is safe to call this method multiple times, updating the progress percent. * * @param {?Number} [percent] optional progress percent (from `0` to `100`); `null` indicates indefinite * progress */ setProgress(percent = null) { /* No duplicate setProgress() protection, since we want to be able to update the progress */ this._progressPercent = percent this.setState(STATE_PROGRESS) } /** * Put the view in the normal state, but only if the current state is {@link qui.views.STATE_PROGRESS}. */ clearProgress() { if (this._state === STATE_PROGRESS) { this.setState(STATE_NORMAL) } } /** * Return the current progress percent. * * An exception will be thrown if the current view state is not {@link qui.views.STATE_PROGRESS}. * * @returns {?Number} */ getProgressPercent() { if (this._state !== STATE_PROGRESS) { throw new AssertionError(`getProgressPercent() called in ${this._state} state`) } return this._progressPercent } /** * Define how the view is displayed in progress state, disallowing any user interaction. * * {@link qui.views.ViewMixin#inProgress} returns `true` when called from this method. * * Does nothing by default. Override this method to implement your own progress display. * * @param {?Number} [percent] optional progress percent (from `0` to `100`); `null` indicates indefinite * progress */ showProgress(percent) { } /** * Hide a previously displayed progress, re-enabling user interaction. * * {@link qui.views.ViewMixin#inProgress} returns `false` when called from this method. * * Does nothing by default. Override this method to implement your own progress hiding. */ hideProgress() { } /** * Tell if the view is currently in progress (its state is {@link qui.views.STATE_PROGRESS}). * @returns {Boolean} */ inProgress() { return this._state === STATE_PROGRESS } /* Warning */ /** * Put the view in the warning state or updates the warning message. The view state is set to * {@link qui.views.STATE_WARNING}. * * It is safe to call this method multiple times, updating the warning message. * * @param {?String} [message] an optional warning message */ setWarning(message = null) { /* No duplicate setWarning() protection, since we want to be able to update the error */ this._warningMessage = message this.setState(STATE_WARNING) } /** * Put the view in the normal state, but only if the current state is {@link qui.views.STATE_WARNING}. */ clearWarning() { if (this._state === STATE_WARNING) { this.setState(STATE_NORMAL) } } /** * Return the warning message set with {@link qui.views.ViewMixin#setWarning} or `null` if no warning message * was set. * * An exception will be thrown if the current view state is not {@link qui.views.STATE_WARNING}. * * @returns {?String} */ getWarningMessage() { if (this._state !== STATE_WARNING) { throw new AssertionError(`getWarningMessage() called in ${this._state} state`) } return this._warningMessage } /** * Define how the view is displayed in warning state, showing the warning message. * * {@link qui.views.ViewMixin#hasWarning} returns `true` when called from this method. * * By default displays a warning toast message. Override this method to implement your own warning display. * * @param {?String} message the warning message, or `null` if no warning message available */ showWarning(message) { Toast.show({message: message, type: 'error', timeout: 0}) } /** * Hide a previously displayed warning. * * {@link qui.views.ViewMixin#hasWarning} returns `false` when called from this method. * * By default calls {@link qui.messages.toast.hide}. Override this method to implement your own warning * hiding. */ hideWarning() { Toast.hide() } /** * Tell if the view is currently in the warning state (its state is {@link qui.views.STATE_WARNING}). * @returns {Boolean} */ hasWarning() { return this._state === STATE_WARNING } /* Error */ /** * Put the view in the error state or updates the error message. * * The view state is set to {@link qui.views.STATE_ERROR}. * * It is safe to call this method multiple times, updating the error message. * * @param {?String|Error} [message] an error message */ setError(message = null) { /* No duplicate setError() protection, since we want to be able to update the error */ if (message instanceof Error) { message = message.message } this._errorMessage = message this.setState(STATE_ERROR) } /** * Put the view in the normal state, but only if the current state is {@link qui.views.STATE_ERROR}. */ clearError() { if (this._state === STATE_ERROR) { this.setState(STATE_NORMAL) } } /** * Return the error message set with {@link qui.views.ViewMixin#setError} or `null` if no error message was set. * * An exception will be thrown if the current view state is not {@link qui.views.STATE_ERROR}. * * @returns {?String} */ getErrorMessage() { if (this._state !== STATE_ERROR) { throw new AssertionError(`getErrorMessage() called in ${this._state} state`) } return this._errorMessage } /** * Define how the view is displayed in error state, showing the error message. * * {@link qui.views.ViewMixin#hasError} returns `true` when called from this method. * * By default displays a error toast message. Override this method to implement your own error display. * * @param {?String} message the error message, or `null` if no error message available */ showError(message) { Toast.show({message: message, type: 'error', timeout: 0}) } /** * Hide a previously displayed error. * * {@link qui.views.ViewMixin#hasError} returns `false` when called from this method. * * By default calls {@link qui.messages.toast.hide}. Override this method to implement your own error * hiding. */ hideError() { Toast.hide() } /** * Tell if the view is currently in the error state (its state is {@link qui.views.STATE_ERROR}). * @returns {Boolean} */ hasError() { return this._state === STATE_ERROR } /* Closing */ /** * Tell if the view has been closed. * * By default returns `false`. * * Override this method to implement your own closed status. * * @returns {Boolean} */ isClosed() { return false } /** * Close the view. * * By default does nothing. * * Override this method to implement your own close behavior. */ close() { } }
JavaScript
class RemoteObject { /** * Constructs a new <code>RemoteObject</code>. * The linked item. * @alias module:model/RemoteObject * @param title {String} The title of the item. * @param url {String} The URL of the item. */ constructor(title, url) { RemoteObject.initialize(this, title, url); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, title, url) { obj['title'] = title; obj['url'] = url; } /** * Constructs a <code>RemoteObject</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/RemoteObject} obj Optional instance to populate. * @return {module:model/RemoteObject} The populated <code>RemoteObject</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new RemoteObject(); if (data.hasOwnProperty('icon')) { obj['icon'] = ApiClient.convertToType(data['icon'], Icon); } if (data.hasOwnProperty('status')) { obj['status'] = ApiClient.convertToType(data['status'], Status); } if (data.hasOwnProperty('summary')) { obj['summary'] = ApiClient.convertToType(data['summary'], 'String'); } if (data.hasOwnProperty('title')) { obj['title'] = ApiClient.convertToType(data['title'], 'String'); } if (data.hasOwnProperty('url')) { obj['url'] = ApiClient.convertToType(data['url'], 'String'); } } return obj; } }
JavaScript
class Game { /** * Constructor for a Game object. */ constructor() { var gameName; var gameRating; } getName() { return this.gameName; } setName(name) { this.gameName = name; } getRating() { return this.gameRating; } setRating(rating) { this.gameRating = rating; } }
JavaScript
class Router extends Backbone.Router { constructor() { super({ routes }); } index() { if(this.view){ this.view.cleanup(); } this.view = new HomePage({ el: 'main' }).render(); } videoCall() { if(this.view){ this.view.cleanup(); } this.view = new VideoCall({ el: 'main' }).render(); } }
JavaScript
class HTMLAttributes { /** * Constructor * @constructor * @param {string|Array|Object} data - Attribute data */ constructor( data = null ) { /** * Attributes that get converted to arrays internally * @protected * @property * @type {string[]} */ this._convert2array = [ 'class' ]; /** * Attribute data * @public * @property * @type {Object} */ this.data = {}; // Parse input data if ( isPojo( data ) ) { const values = Object.entries( data ); for ( let i = 0; i < values.length; i++ ) { const [ name, value ] = values[ i ]; this.set( name, value ); } } else if ( data instanceof Array ) { this._requireAttribute( 'class', data ); } else if ( typeof data === 'string' && data.length ) { this._requireAttribute( 'id', data ); } } /** * Require attribute name with default value * @protected * @param {string} name - Attribute name * @param {*} value - Default value * @return {void} */ _requireAttribute( name, value ) { if ( !this.data[ name ] ) { this.data[ name ] = value; } } /** * Set attribute * @param {string} name - Attribute name * @param {*} value - Attribute value * @return {HTMLAttributes} - Self for chaining */ set( name, value ) { if ( typeof name !== 'string' || !name.length ) { throw new HTMLAttributesException( 'Invalid attribute name' ); } if ( this._convert2array.includes( name ) && !( value instanceof Array ) ) { if ( typeof value === 'string' ) { value = value.split( ' ' ); } else { value = [ value ]; } } this.data[ name ] = value; return this; } /** * Has given attribute * @param {string} name - Attribute name * @return {boolean} - True if attribute is set */ has( name ) { return !!this.data[ name ] || typeof this.data[ name ] === 'string'; } /** * Add class * @param {string|Array} classname - Classname * @return {HTMLAttributes} - Self for chaining */ addClass( classname ) { if ( !classname ) return this; if ( classname instanceof Array ) { return this.addClasses( classname ); } if ( typeof classname !== 'string' ) { throw new HTMLAttributesException( 'Invalid class value ' + typeof classname ); } if ( classname.length ) { this._requireAttribute( 'class', [] ); if ( !this.data[ 'class' ].includes( classname ) ) { this.data[ 'class' ].push( classname ); } } return this; } /** * Add classes * @param {string|Array} classnames - Classnames array * @return {HTMLAttributes} - Self for chaining */ addClasses( classnames ) { if ( classnames instanceof Array ) { for ( let i = 0; i < classnames.length; i++ ) { this.addClass( classnames[ i ] ); } } else { this.addClass( classnames ); } return this; } /** * Converts attribute data * @return {string} - Compiled html tag attributes */ toString() { const result = []; const data = Object.entries( this.data ); for ( let i = 0; i < data.length; i++ ) { const [ name, value ] = data[ i ]; // Skip special properties if ( name.substr( 0, 2 ) === '__' ) { continue; } // Only add none empties if ( value !== null && typeof value !== 'undefined' ) { let quotes = '"', output = value; const to = typeof output; if ( to === 'boolean' ) { output = output ? 'true' : 'false'; } else if ( output instanceof Array && output.every( ( v ) => { return typeof v === 'string'; } ) ) { output = output.join( ' ' ); } else if ( to !== 'string' && to !== 'number' ) { output = JSON.stringify( output ); quotes = '\''; } result.push( name + ( output.length ? '=' + quotes + output + quotes : '' ) ); } } return result.join( ' ' ); } }
JavaScript
class Primer extends Mesh { /** * post some config to primer * @param {*} geo have not be used * @param {*} mat config primer status * @param {*} options config primer status */ constructor(geo, mat, options) { super(geo, mat); const { frameAspect = 1, targetAspect = 1, backgroundSize = 'COVER', } = options; /** * frame aspect, same with texture aspect (width / height) */ this.frameAspect = frameAspect; /** * viewport aspect, same with viewport aspect (width / height) */ this.targetAspect = targetAspect; /** * background aspect, fill with 'COVER' or 'CONTAIN' */ this.backgroundSize = backgroundSize; } /** * set the target viewport aspect * @param {Number} targetAspect target viewport aspect */ setAspect(targetAspect) { console.trace('aaa'); this.targetAspect = targetAspect; if (this.loaded) this._updateAttributes(); } /** * update attribute * @private */ _updateAttributes() { const { width, height } = this._cs(); this._setPositions(this.geometry.attributes.position, width, height); } /** * calculation the size for geometry in this frameAspect * @return {Object} size * @private */ _cs() { const scale = this.frameAspect / this.targetAspect; const size = { width: 1, height: 1, }; if (this.backgroundSize === 'COVER') { this._cover(size, scale); } else if (this.backgroundSize === 'CONTAIN') { this._contain(size, scale); } else { this._cover(size, scale); } return size; } /** * calculate background size with 'COVER' mode * @param {*} size size * @param {*} scale scale * @return {Object} size * @private */ _cover(size, scale) { if (this.targetAspect > this.frameAspect) { size.height = 1 / scale; } else { size.width = scale; } return size; } /** * calculate background size with 'CONTAIN' mode * @param {*} size size * @param {*} scale scale * @return {Object} size * @private */ _contain(size, scale) { if (this.frameAspect > this.targetAspect) { size.height = 1 / scale; } else { size.width = scale; } return size; } /** * resize geometry size * @param {BufferAttribute} positions positions buffer * @param {Number} width target width * @param {Number} height target height * @return {BufferAttribute} updated BufferAttribute */ _setPositions(positions, width, height) { const coefficient = [ -1, 1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ]; for (let i = 0; i < positions.count; i++) { const item = positions.itemSize * i; positions.array[item] = coefficient[item] * width; positions.array[item + 1] = coefficient[item + 1] * height; } positions.needsUpdate = true; return positions; } /** * resize layer size when viewport has change * @param {number} width layer buffer width * @param {number} height layer buffer height */ setSize(width, height) { this.setAspect(width / height); } }
JavaScript
class PathfinderCommunity extends Pathfinder { /** * @inheritdoc */ get name() { return 'Pathfinder Community'; } constructor() { super(); } /** * @inheritdoc */ getSkillMod(character, skillName) { if (skillName === 'Appraise') return CharSheetUtils.getSheetAttr(character, 'Appraise'); if (skillName === 'Heal') return CharSheetUtils.getSheetAttr(character, 'Heal'); if (skillName === 'Knowledge(Arcana)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Arcana'); if (skillName === 'Knowledge(Dungeoneering)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Dungeoneering'); if (skillName === 'Knowledge(Engineering)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Engineering'); if (skillName === 'Knowledge(Geography)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Geography'); if (skillName === 'Knowledge(History)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-History'); if (skillName === 'Knowledge(Local)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Local'); if (skillName === 'Knowledge(Nature)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Nature'); if (skillName === 'Knowledge(Nobility)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Nobility'); if (skillName === 'Knowledge(Planes)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Planes'); if (skillName === 'Knowledge(Religion)') return CharSheetUtils.getSheetAttr(character, 'Knowledge-Religion'); if (skillName === 'Linguistics') return CharSheetUtils.getSheetAttr(character, 'Linguistics'); if (skillName === 'Perception') return CharSheetUtils.getSheetAttr(character, 'Perception'); if (skillName === 'Sense Motive') return CharSheetUtils.getSheetAttr(character, 'Sense-Motive'); if (skillName === 'Spellcraft') return CharSheetUtils.getSheetAttr(character, 'Spellcraft'); if (skillName === 'Survival') return CharSheetUtils.getSheetAttr(character, 'Survival'); } }
JavaScript
class SunPosition { constructor() { this.init(); } init() { this.m = Math; (this.PI = m.PI), (this.sin = m.sin); this.cos = m.cos; this.tan = m.tan; this.asin = m.asin; this.atan = m.atan2; this.rad = PI / 180; this.dayMs = 1000 * 60 * 60 * 24; this.J1970 = 2440588; this.J2000 = 2451545; this.e = this.rad * 23.4397; // obliquity of the Earth } toJulian(date) { return date.valueOf() / this.dayMs - 0.5 + this.J1970; } toDays(date) { return this.toJulian(date) - this.J2000; } getRightAscension(l, b) { return this.atan( this.sin(l) * this.cos(this.e) - this.tan(b) * this.sin(this.e), this.cos(l) ); } getDeclination(l, b) { return this.asin( this.sin(b) * this.cos(this.e) + this.cos(b) * this.sin(this.e) * this.sin(l) ); } getAzimuth(H, phi, dec) { return this.atan( this.sin(H), this.cos(H) * this.sin(phi) - this.tan(dec) * this.cos(phi) ); } getAltitude(H, phi, dec) { return this.asin( this.sin(phi) * this.sin(dec) + this.cos(phi) * this.cos(dec) * this.cos(H) ); } getSiderealTime(d, lw) { return this.rad * (280.16 + 360.9856235 * d) - lw; } getSolarMeanAnomaly(d) { return this.rad * (357.5291 + 0.98560028 * d); } getEquationOfCenter(M) { return ( this.rad * (1.9148 * this.sin(M) + 0.02 * this.sin(2 * M) + 0.0003 * this.sin(3 * M)) ); } getEclipticLongitude(M, C) { var P = this.rad * 102.9372; // perihelion of the Earth return M + C + P + this.PI; } getSunPosition(date, lat, lon) { var lw = this.rad * -lon, phi = this.rad * lat, d = this.toDays(date), M = this.getSolarMeanAnomaly(d), C = this.getEquationOfCenter(M), L = this.getEclipticLongitude(M, C), D = this.getDeclination(L, 0), A = this.getRightAscension(L, 0), t = this.getSiderealTime(d, lw), H = t - A; return { altitude: this.getAltitude(H, phi, D), azimuth: this.getAzimuth(H, phi, D) - this.PI / 2 // origin: north }; } }
JavaScript
class DecideStackScreen extends React.Component { async componentDidMount() { this.props.dispatch(resetData()); await hathorLib.storage.store.preStart(); if (hathorLib.wallet.loaded()) { this.props.navigation.navigate('App'); } else { this.props.navigation.navigate('Init'); } } render() { return null; } }
JavaScript
class ToneAudioNode extends ToneWithContext { constructor() { super(...arguments); /** * The name of the class */ this.name = "ToneAudioNode"; /** * List all of the node that must be set to match the ChannelProperties */ this._internalChannels = []; } /** * The number of inputs feeding into the AudioNode. * For source nodes, this will be 0. * @example * const node = new Tone.Gain(); * console.log(node.numberOfInputs); */ get numberOfInputs() { if (isDefined(this.input)) { if (isAudioParam(this.input) || this.input instanceof Param) { return 1; } else { return this.input.numberOfInputs; } } else { return 0; } } /** * The number of outputs of the AudioNode. * @example * const node = new Tone.Gain(); * console.log(node.numberOfOutputs); */ get numberOfOutputs() { if (isDefined(this.output)) { return this.output.numberOfOutputs; } else { return 0; } } //------------------------------------- // AUDIO PROPERTIES //------------------------------------- /** * Used to decide which nodes to get/set properties on */ _isAudioNode(node) { return isDefined(node) && (node instanceof ToneAudioNode || isAudioNode(node)); } /** * Get all of the audio nodes (either internal or input/output) which together * make up how the class node responds to channel input/output */ _getInternalNodes() { const nodeList = this._internalChannels.slice(0); if (this._isAudioNode(this.input)) { nodeList.push(this.input); } if (this._isAudioNode(this.output)) { if (this.input !== this.output) { nodeList.push(this.output); } } return nodeList; } /** * Set the audio options for this node such as channelInterpretation * channelCount, etc. * @param options */ _setChannelProperties(options) { const nodeList = this._getInternalNodes(); nodeList.forEach(node => { node.channelCount = options.channelCount; node.channelCountMode = options.channelCountMode; node.channelInterpretation = options.channelInterpretation; }); } /** * Get the current audio options for this node such as channelInterpretation * channelCount, etc. */ _getChannelProperties() { const nodeList = this._getInternalNodes(); assert(nodeList.length > 0, "ToneAudioNode does not have any internal nodes"); // use the first node to get properties // they should all be the same const node = nodeList[0]; return { channelCount: node.channelCount, channelCountMode: node.channelCountMode, channelInterpretation: node.channelInterpretation, }; } /** * channelCount is the number of channels used when up-mixing and down-mixing * connections to any inputs to the node. The default value is 2 except for * specific nodes where its value is specially determined. */ get channelCount() { return this._getChannelProperties().channelCount; } set channelCount(channelCount) { const props = this._getChannelProperties(); // merge it with the other properties this._setChannelProperties(Object.assign(props, { channelCount })); } /** * channelCountMode determines how channels will be counted when up-mixing and * down-mixing connections to any inputs to the node. * The default value is "max". This attribute has no effect for nodes with no inputs. * * "max" - computedNumberOfChannels is the maximum of the number of channels of all connections to an input. In this mode channelCount is ignored. * * "clamped-max" - computedNumberOfChannels is determined as for "max" and then clamped to a maximum value of the given channelCount. * * "explicit" - computedNumberOfChannels is the exact value as specified by the channelCount. */ get channelCountMode() { return this._getChannelProperties().channelCountMode; } set channelCountMode(channelCountMode) { const props = this._getChannelProperties(); // merge it with the other properties this._setChannelProperties(Object.assign(props, { channelCountMode })); } /** * channelInterpretation determines how individual channels will be treated * when up-mixing and down-mixing connections to any inputs to the node. * The default value is "speakers". */ get channelInterpretation() { return this._getChannelProperties().channelInterpretation; } set channelInterpretation(channelInterpretation) { const props = this._getChannelProperties(); // merge it with the other properties this._setChannelProperties(Object.assign(props, { channelInterpretation })); } //------------------------------------- // CONNECTIONS //------------------------------------- /** * connect the output of a ToneAudioNode to an AudioParam, AudioNode, or ToneAudioNode * @param destination The output to connect to * @param outputNum The output to connect from * @param inputNum The input to connect to */ connect(destination, outputNum = 0, inputNum = 0) { connect(this, destination, outputNum, inputNum); return this; } /** * Connect the output to the context's destination node. * @example * const osc = new Tone.Oscillator("C2").start(); * osc.toDestination(); */ toDestination() { this.connect(this.context.destination); return this; } /** * Connect the output to the context's destination node. * See [[toDestination]] * @deprecated */ toMaster() { warn("toMaster() has been renamed toDestination()"); return this.toDestination(); } /** * disconnect the output */ disconnect(destination, outputNum = 0, inputNum = 0) { disconnect(this, destination, outputNum, inputNum); return this; } /** * Connect the output of this node to the rest of the nodes in series. * @example * const player = new Tone.Player("https://tonejs.github.io/audio/drum-samples/handdrum-loop.mp3"); * player.autostart = true; * const filter = new Tone.AutoFilter(4).start(); * const distortion = new Tone.Distortion(0.5); * // connect the player to the filter, distortion and then to the master output * player.chain(filter, distortion, Tone.Destination); */ chain(...nodes) { connectSeries(this, ...nodes); return this; } /** * connect the output of this node to the rest of the nodes in parallel. * @example * const player = new Tone.Player("https://tonejs.github.io/audio/drum-samples/conga-rhythm.mp3"); * player.autostart = true; * const pitchShift = new Tone.PitchShift(4).toDestination(); * const filter = new Tone.Filter("G5").toDestination(); * // connect a node to the pitch shift and filter in parallel * player.fan(pitchShift, filter); */ fan(...nodes) { nodes.forEach(node => this.connect(node)); return this; } /** * Dispose and disconnect */ dispose() { super.dispose(); if (isDefined(this.input)) { if (this.input instanceof ToneAudioNode) { this.input.dispose(); } else if (isAudioNode(this.input)) { this.input.disconnect(); } } if (isDefined(this.output)) { if (this.output instanceof ToneAudioNode) { this.output.dispose(); } else if (isAudioNode(this.output)) { this.output.disconnect(); } } this._internalChannels = []; return this; } }
JavaScript
class ReqM2Oreqm extends ReqM2Specobjects { /** * Construct new object * @param {string} filename of the oreqm file * @param {string} content XML data * @param {string[]} excluded_doctypes List of doctypes to exclude from diagram * @param {string[]} excluded_ids List of IDs to exclude from diagram */ constructor (filename, content, excluded_doctypes, excluded_ids) { super(filename, content, excluded_doctypes, excluded_ids) // diagram related members this.doctype_clusters = null // A map of {doctype : [doctype:safetyclass]} this.dt_map = null // new Map(); // A map of { doctype_name : DoctypeRelations } this.safety_regex_array = [] // Array of regex to match relations } /** @description Initial part of dot file */ static get DOT_PREAMBLE () { const preamble = `digraph "" { rankdir="RL" node [shape=plaintext fontname="Arial" fontsize=16] edge [color="blue",dir="forward",arrowhead="normal",arrowtail="normal"]; ` return preamble } /** @description Final part of dot file */ static get DOT_EPILOGUE () { const epilogue = '\n}\n' return epilogue } /** * Format a node to dot format. Use a cache to speed up subsequent renderings. * @param {string} req_id * @param {boolean} ghost Is this a deleted speocobject (in a comparison) * @param {boolean} show_coverage * @param {boolean} color_status * @return {string} dot html table string */ get_format_node (req_id, ghost, show_coverage, color_status) { let node if (this.format_cache.has(req_id)) { node = this.format_cache.get(req_id) // console.log('cache hit: ', req_id) } else { node = format_node( req_id, this.requirements.get(req_id), ghost, this, show_coverage, color_status ) this.format_cache.set(req_id, node) } return node } /** * Return a 'dot' compatible graph with the subset of nodes nodes * accepted by the selection_function. * Also updates the doctype table in lower left of window. * The 'TOP' node forces a sensible layout for highest level requirements * (some level of visual proximity and aligned to the left of the graph) * @param {function} selection_function A function which tells if a particular node is included * @param {array} top_doctypes List of doctypes to link to 'TOP' node * @param {string} title diagram legend as dot html table * @param {object} highlights List of object IDs to be outlined as selected * @param {number} max_nodes Upper limit of nodes to render * @param {boolean} show_coverage * @param {boolean} color_status * @return {string} dot graph */ create_graph ( selection_function, top_doctypes, title, highlights, max_nodes, show_coverage, color_status ) { //rq: ->(rq_dot) D(* Function shall output a dot graph*) let graph = ReqM2Oreqm.DOT_PREAMBLE const subset = [] const ids = this.requirements.keys() let node_count = 0 let edge_count = 0 const doctype_dict = new Map() // { doctype : [id] } list of id's per doctype const selected_dict = new Map() // { doctype : [id] } list of selected id's per doctype const selected_nodes = [] let limited = false for (const req_id of ids) { this.doctype_grouping( req_id, doctype_dict, selected_dict, selection_function, subset, highlights, selected_nodes ) if (subset.length > max_nodes) { limited = true limit_reporter(max_nodes) //rq: ->(rq_config_node_limit) break // hard limit on node count } this.subset = selected_nodes // keep this subset to enable "save selection" } let show_top; ({ show_top, graph } = this.handle_top_node(top_doctypes, graph)) // babel artifact? below names must match what is used in return from visible_duplicates() let arrays_of_duplicates let not_duplicates; ({ arrays_of_duplicates, not_duplicates } = this.visible_duplicates( subset )) // console.log(arrays_of_duplicates) // console.log(not_duplicates) for (const dup_list of arrays_of_duplicates) { //rq: ->(rq_dup_req_display) const dup_cluster_id = this.requirements.get(dup_list[0]).id const versions = dup_list.map((a) => this.requirements.get(a).version) const versions_set = new Set(versions) const version_set_size = versions_set.size //console.log(dup_list, versions, versions_set, versions.length, version_set_size) const dup_versions = versions.length !== version_set_size const label = 'duplicate' + (dup_versions ? ' id + version' : ' id') //rq: ->(rq_dup_id_ver_disp) const fontcolor = dup_versions ? 'fontcolor="red" ' : '' graph += `subgraph "cluster_${dup_cluster_id}_dups" { color=grey penwidth=2 label="${label}" ${fontcolor}fontname="Arial" labelloc="t" style="rounded"\n` for (const req_id of dup_list) { // duplicate nodes ({ graph, node_count } = this.add_node_to_graph( req_id, show_coverage, color_status, highlights, graph, node_count )) } graph += '}\n\n' } for (const req_id of not_duplicates) { // nodes ({ graph, node_count } = this.add_node_to_graph( req_id, show_coverage, color_status, highlights, graph, node_count )) } graph += '\n # Edges\n' graph = this.handle_top_node_edges(show_top, subset, top_doctypes, graph) for (const req_id of subset) { // edges ({ graph, edge_count } = this.add_dot_edge( req_id, subset, graph, edge_count )) } graph += `\n label=${title}\n labelloc=b\n fontsize=18\n fontcolor=black\n fontname="Arial"\n` //rq: ->(rq_diagram_legend) graph += ReqM2Oreqm.DOT_EPILOGUE this.dot = graph selected_nodes.sort() const result = { node_count: node_count, edge_count: edge_count, doctype_dict: doctype_dict, selected_dict: selected_dict, limited: limited, selected_nodes: selected_nodes } return result } add_node_to_graph ( req_id, show_coverage, color_status, highlights, graph, node_count ) { const ghost = this.removed_reqs.includes(req_id) || this.requirements.get(req_id).ffb_placeholder === true let node = this.get_format_node(req_id, ghost, show_coverage, color_status) node = this.add_node_emphasis(req_id, node, req_id, highlights) graph += node + '\n' node_count += 1 return { graph, node_count } } /** * Calculate the subset of visible nodes that are duplicates * @param {string[]} subset keys of visible nodes * @return { string[][], string[] } An array of visible duplicate sets, array of rest */ visible_duplicates (subset) { let set_copy = subset.slice() const not_duplicates = [] const arrays_of_duplicates = [] while (set_copy.length > 0) { const key = set_copy[0] const id = this.requirements.get(set_copy[0]).id if (this.duplicates.has(id)) { // Add the duplicates on the list to dup_set which are also in the subset const dup_set = [] const dup_arr = this.duplicates.get(id) for (const dup_pair of dup_arr) { if (set_copy.includes(dup_pair.id)) { dup_set.push(dup_pair.id) } } // Remove these ids/keys from set_copy const temp_copy = set_copy.filter(function (value, _index, _arr) { return !dup_set.includes(value) }) set_copy = temp_copy arrays_of_duplicates.push(dup_set) } else { not_duplicates.push(key) set_copy = set_copy.slice(1) } } // console.log("visible_duplicates", subset, arrays_of_duplicates, not_duplicates); return { arrays_of_duplicates, not_duplicates } } handle_top_node_edges (show_top, subset, top_doctypes, graph) { if (show_top) { for (const req_id of subset) { if (top_doctypes.includes(this.requirements.get(req_id).doctype)) { graph += format_edge(req_id, 'TOP', '', '', '', '') } } } return graph } /** * Add 'TOP' node if there will be edges to it. * @param {string[]} top_doctypes * @param {string} graph */ handle_top_node (top_doctypes, graph) { let show_top = false for (const top_dt of top_doctypes) { if ( this.doctypes.has(top_dt) && !this.excluded_doctypes.includes(top_dt) ) { show_top = true } } if (show_top) { graph += ' "TOP" [fontcolor=lightgray];\n\n' } return { show_top, graph } } add_dot_edge (req_id, subset, graph, edge_count) { let kind = '' let linkerror = { error: '' } if (this.linksto.has(req_id)) { for (const link of this.linksto.get(req_id)) { // Do not reference non-selected specobjets if (subset.includes(link)) { if ( this.fulfilledby.has(req_id) && this.fulfilledby.get(req_id).has(link) ) { kind = 'fulfilledby' linkerror = this.get_ffb_link_error(link, req_id) } else { kind = null if (this.untraced.has(req_id) && this.untraced.get(req_id).has(link)) { kind = 'untraced' console.log(kind) } linkerror = this.get_link_error(req_id, link) } graph += format_edge( req_id, link, kind, linkerror.error, linkerror.color, linkerror.label ) edge_count += 1 } } } return { graph, edge_count } } /** * Calculate categories of nodes in diagram * @param {string} req_id of current node * @param {Map<string, string[]>} doctype_dict * @param {Map<string, string[]>} selected_dict * @param {function(string, Object, Set<number>)} selection_function * @param {string[]} subset [output] List of selected and reachable ids * @param {string[]} highlights [input] list of selected ids * @param {string[]} selected_nodes [output] */ doctype_grouping ( req_id, doctype_dict, selected_dict, selection_function, subset, highlights, selected_nodes ) { const rec = this.requirements.get(req_id) if (!doctype_dict.has(rec.doctype)) { doctype_dict.set(rec.doctype, []) selected_dict.set(rec.doctype, []) } if ( selection_function(req_id, rec, this.color.get(req_id)) && !this.excluded_doctypes.includes(rec.doctype) && !this.excluded_ids.includes(req_id) ) { subset.push(req_id) doctype_dict.get(rec.doctype).push(req_id) if (highlights.includes(req_id)) { selected_dict.get(rec.doctype).push(req_id) selected_nodes.push(req_id) } } } /** * Decorate the node with a colored 'cluster¨' if one of special categories. * @param {string} req_id specobject id * @param {string} node 'dot' language node * @param {string} dot_id svg level id * @param {string[]} highlights id's of selected nodes */ add_node_emphasis (req_id, node, dot_id, highlights) { //rq: ->(rq_req_diff_show) if (this.new_reqs.includes(req_id)) { node = `subgraph "cluster_${dot_id}_new" { color=limegreen penwidth=2 label="new" fontname="Arial" labelloc="t" style="rounded"\n${node}}\n` } else if (this.updated_reqs.includes(req_id)) { node = `subgraph "cluster_${dot_id}_changed" { color=orange3 penwidth=2 label="changed" fontname="Arial" labelloc="t" style="rounded"\n${node}}\n` } else if (this.removed_reqs.includes(req_id)) { node = `subgraph "cluster_${dot_id}_removed" { color=red penwidth=2 label="removed" fontname="Arial" labelloc="t" style="rounded"\n${node}}\n` } if (highlights.includes(req_id)) { //rq: ->(rq_highlight_sel) node = `subgraph "cluster_${dot_id}" { id="sel_${dot_id}" color=maroon3 penwidth=3 label="" style="rounded"\n${node}}\n` } return node } /** * Get error possibly associated with linksto * @param {string} req_id specobject id * @param {string} link specobject in linksto reference * @return {string} error string or '' */ get_link_error (req_id, link) { //rq: ->(rq_show_diff_links) const rec = this.requirements.get(req_id) let error = '' let color = '' let label = '' for (const lt of rec.linksto) { if (lt.linksto === link) { error = lt.linkerror label = lt.diff switch (label) { case 'removed': color = '"#C00000" style=dashed' break case 'new': color = 'green3' break case 'chg': color = 'orange3' break } } } return { error: error, color: color, label: label } } /** * Get error possibly associated with fulfilledby link * @param {string} req_id specobject id * @param {string} link specobject in ffb reference * @return {string} error string or '' */ get_ffb_link_error (req_id, link) { const rec = this.requirements.get(req_id) let error = '' let color = '' let label = '' for (const ffb of rec.fulfilledby) { if (ffb.id === link) { error = ffb.ffblinkerror label = ffb.diff switch (label) { case 'removed': color = '"#C00000" style=dashed' break case 'new': color = 'green3' break case 'chg': color = 'orange3' break } } } return { error: error, label: label, color: color } } /** * Check two expanded doctype:safetyclass pairs for compliance with at least one of the supplied rules, * i.e. permitted safetyclass for providescoverage <from_safetyclass>:<to_safetyclass> * @param {string} from origin doctype:safetyclass * @param {string} to descination doctype:safetyclass * @return {boolean} */ check_linksto_safe (from, to) { const combo = `${from}>${to}` for (const re of this.safety_regex_array) { if (combo.match(re)) { return true } } return false } /** * Generate doctype:safetyclass classifier * @param {string} id * @param {string} safety safetyclass * @return {string} */ build_doctype_with_safetyclass (id, safety) { // construct a doctype name, qualified with safetyclass const rec = this.requirements.get(id) if (safety) { return `${rec.doctype}:${rec.safetyclass}` } else { return rec.doctype } } /** * Calculate edge color according to compliance with safety rules * @param {string} from origin doctype * @param {string} to destination doctype * @return {string} RGB color of graph edge */ linksto_safe_color (from, to) { return this.check_linksto_safe(from, to) ? '#00AA00' : '#FF0000' } /** * Build a mapping of doctype relations. * Update this.dt_map * @param {boolean} doctype_safety consider safetyclass in diagram */ build_doctype_mapping (doctype_safety) { const id_list = this.requirements.keys() let doctype = null let dest_doctype = null let basic_doctype = null this.doctype_clusters = new Map() // {doctype : [doctype:safetyclass]} for (const id of id_list) { if (this.requirements.get(id).ffb_placeholder === true) { // skip placeholders continue } // make a cluster of doctypes with the different safetyclasses basic_doctype = this.requirements.get(id).doctype if (!this.doctype_clusters.has(basic_doctype)) { this.doctype_clusters.set(basic_doctype, []) } doctype = this.build_doctype_with_safetyclass(id, doctype_safety) if (!this.dt_map.has(doctype)) { this.dt_map.set(doctype, new DoctypeRelations(doctype)) // Create clusters of refined doctypes, based on fundamental one if (!this.doctype_clusters.get(basic_doctype).includes(doctype)) { this.doctype_clusters.get(basic_doctype).push(doctype) } } this.dt_map.get(doctype).add_instance(id) // linksto if (this.linksto.has(id)) { const linksto = Array.from(this.linksto.get(id)) for (const linked_id of linksto) { if (this.requirements.has(linked_id)) { dest_doctype = this.build_doctype_with_safetyclass( linked_id, doctype_safety ) // console.log("add_linksto ", doctype, linked_id, dest_doctype) this.dt_map.get(doctype).add_linksto(dest_doctype, [linked_id, id]) } } } // needsobj const need_list = Array.from(this.requirements.get(id).needsobj) for (const need of need_list) { if (!need.endsWith('*')) { if (doctype_safety) { // will need at least its own safetyclass dest_doctype = `${need}:${this.requirements.get(id).safetyclass}` } else { dest_doctype = need } // console.log("add_needsobj ", dest_doctype) this.dt_map.get(doctype).add_needsobj(dest_doctype) } } // fulfilledby const ffb_list = Array.from(this.requirements.get(id).fulfilledby) for (const ffb of ffb_list) { if (doctype_safety) { // will need at least its own safetyclass dest_doctype = `${ffb.doctype}:${ this.requirements.get(id).safetyclass }` } else { dest_doctype = ffb.doctype } // console.log("add_fulfilledby ", dest_doctype) this.dt_map.get(doctype).add_fulfilledby(dest_doctype, [id, ffb.id]) } } } /** * Build safety regexes from strings * @return {boolean} true: regex list updated, false: regex broken */ build_safety_regexes () { const result = process_rule_set(program_settings.safety_link_rules) if (result.pass) { this.safety_regex_array = result.regex_list } else { // alert(result.error); } return result.pass } /** * Scan all requirements and summarize the relationships between doctypes * with counts of instances and relations (needsobj, linksto, fulfilledby) * When doctype_safety is true, the doctypes are qualified with the safetyclass * of the requirement as in <doctype>:<safetyclass> and these are the nodes rendered * @param {boolean} doctype_safety false: plain doctype relations; true: safetyclass checks for doctype relations * @return {string} dot language diagram */ scan_doctypes (doctype_safety) { //rq: ->(rq_doctype_hierarchy) //rq: ->(rq_doctype_aggr_safety) if (doctype_safety) { this.build_safety_regexes() } this.dt_map = new Map() // A map of { doctype_name : DoctypeRelations } this.build_doctype_mapping(doctype_safety) // DOT language start of diagram let graph = `digraph "" { rankdir="${doctype_safety ? 'BT' : 'TD'}" node [shape=plaintext fontname="Arial" fontsize=16] edge [color="black" dir="forward" arrowhead="normal" arrowtail="normal" fontname="Arial" fontsize=11];\n\n` // Define the doctype nodes - the order affects the layout const doctype_array = Array.from(this.doctype_clusters.keys()) for (const doctype of doctype_array) { const doctypes_in_cluster = this.doctype_clusters.get(doctype) let sc_stats = '' let count_total = 0 const sc_list = Array.from(doctypes_in_cluster.keys()) sc_list.sort() let sc_string = '' for (const sub_doctype of doctypes_in_cluster) { const dt = this.dt_map.get(sub_doctype) const sc = sub_doctype.split(':')[1] sc_string += `</TD><TD port="${sc_str(sc)}">${sc_str(sc)}: ${ dt.count } ` count_total += dt.count } if (doctype_safety) { sc_stats = `\n <TR><TD>safetyclass:${sc_string}</TD></TR>` } const dt_node = `\ "${doctype}" [label=< <TABLE BGCOLOR="${get_color( doctype )}" BORDER="0" CELLSPACING="0" CELLBORDER="1" COLOR="black" > <TR><TD COLSPAN="5" CELLSPACING="0" >doctype: ${doctype}</TD></TR> <TR><TD COLSPAN="5" ALIGN="LEFT">specobject count: ${count_total}</TD></TR>${sc_stats} </TABLE>>];\n\n` graph += dt_node } let dt let count const doctype_edges = Array.from(this.dt_map.keys()) // Loop over doctypes for (const doctype of doctype_edges) { dt = this.dt_map.get(doctype) // Needsobj links graph += `# linkage from ${doctype}\n` const need_keys = Array.from(dt.needsobj.keys()) if (!doctype_safety) { for (const nk of need_keys) { count = dt.needsobj.get(nk) graph += ` "${doctype.split(':')[0]}" -> "${ nk.split(':')[0] }" [label="need(${count})${ doctype_safety ? `\n${dt_sc_str(doctype)}` : '' } " style="dotted"]\n` } } // linksto links const lt_keys = Array.from(dt.linksto.keys()) for (let lk of lt_keys) { count = dt.linksto.get(lk).length graph += ` "${doctype.split(':')[0]}" -> "${ lk.split(':')[0] }" [label="linksto(${count})${ doctype_safety ? `\\l${dt_sc_str(doctype)}>${dt_sc_str(lk)}` : '' } " color="${ doctype_safety ? this.linksto_safe_color(doctype, lk) : 'black' }"]\n` if (doctype_safety && !this.check_linksto_safe(doctype, lk)) { const prov_list = dt.linksto .get(lk) .map((x) => `${quote_id(x[1])} -> ${quote_id(x[0])}`) let dt2 = doctype if (dt2.endsWith(':')) { dt2 += '<none>' } if (lk.endsWith(':')) { lk += '<none>' } const problem = `${dt2} provcov to ${lk}\n ${prov_list.join('\n ')}` this.problem_report(problem) } } // fulfilledby links const ffb_keys = Array.from(dt.fulfilledby.keys()) for (const ffb of ffb_keys) { count = dt.fulfilledby.get(ffb).length graph += ` "${doctype.split(':')[0]}" -> "${ ffb.split(':')[0] }" [label="fulfilledby(${count})${ doctype_safety ? `\n${dt_sc_str(ffb)}>${dt_sc_str(doctype)}` : '' } " color="${ doctype_safety ? this.linksto_safe_color(ffb, doctype) : 'purple' }" style="dashed"]\n` if (doctype_safety && !this.check_linksto_safe(ffb, doctype)) { const problem = `${ffb} fulfilledby ${doctype}` this.problem_report(problem) } } } let rules if (doctype_safety) { const safety_rules_string = JSON.stringify( program_settings.safety_link_rules, null, 2 ) rules = { text: xml_escape(safety_rules_string.replace(/\\/g, '\\\\')).replace(/\n/gm, '<BR ALIGN="LEFT"/> '), title: 'Safety rules for coverage<BR/>list of regex<BR/>doctype:safetyclass&gt;doctype:safetyclass' } } //rq: ->(rq_diagram_legend) graph += `\n label=${this.construct_graph_title( false, rules, null, false, null )}\n labelloc=b\n fontsize=14\n fontcolor=black\n fontname="Arial"\n` graph += '\n}\n' // console.log(graph) this.dot = graph return graph } /** * Construct diagram legend as 'dot' table. * @param {boolean} show_filters display selection criteria * @param {object} extra object with .title and .text for additional row * @param {object} oreqm_ref optional reference (2nd) oreqm object * @param {boolean} id_checkbox search <id>s only * @param {string} search_pattern 'selection criteria' string * @return {string} 'dot' table */ construct_graph_title ( show_filters, extra, oreqm_ref, id_checkbox, search_pattern ) { //rq: ->(rq_diagram_legend) let title = '""' title = '<\n <table border="0" cellspacing="0" cellborder="1">\n' title += ` <tr><td cellspacing="0" >File</td><td>${this.filename.replace( /([^\n]{30,500}?(\\|\/))/g, '$1<BR ALIGN="LEFT"/>' )}</td><td>${this.timestamp}</td></tr>\n` if (show_filters) { if (oreqm_ref) { title += ` <tr><td>Ref. file</td><td>${oreqm_ref.filename.replace( /([^\n]{30,500}?(\\|\/))/g, '$1<BR ALIGN="LEFT"/>' )}</td><td>${oreqm_ref.timestamp}</td></tr>\n` } if (search_pattern.length) { const search_formatted = xml_escape( search_pattern.replace(/&/g, '&amp;') ) const pattern_string = search_formatted .trim() .replace(/([^\n]{40,500}?\|)/g, '$1<BR ALIGN="LEFT"/>') .replace(/\n/g, '<BR ALIGN="LEFT"/>') if (id_checkbox) { title += ` <tr><td>Search &lt;id&gt;</td><td colspan="2">${pattern_string.replace( /\\/g, '\\\\' )}<BR ALIGN="LEFT"/></td></tr>\n` } else { title += ` <tr><td>Search text</td><td colspan="2">${pattern_string.replace( /\\/g, '\\\\' )}<BR ALIGN="LEFT"/></td></tr>\n` } } const ex_dt_list = this.excluded_doctypes if (ex_dt_list.length) { title += ` <tr><td>excluded doctypes</td><td colspan="2">${ex_dt_list .join(', ') .replace(/([^\n]{60,500}? )/g, '$1<BR ALIGN="LEFT"/>')}</td></tr>\n` } const excluded_ids = this.excluded_ids if (excluded_ids.length) { title += ` <tr><td>excluded &lt;id&gt;s</td><td colspan="2">${excluded_ids.join( '<BR ALIGN="LEFT"/>' )}<BR ALIGN="LEFT"/></td></tr>\n` } } if ( extra && extra.title && extra.text && extra.title.length && extra.text.length ) { title += ` <tr><td>${extra.title}</td><td colspan="2">${extra.text}<BR ALIGN="LEFT"/></td></tr>\n` } title += ' </table>>' // console.log(title) return title } }
JavaScript
@connect(state => ({ screen: state.screen })) class Manifests extends React.Component { static propTypes = { items: PropTypes.array.isRequired, total: PropTypes.number.isRequired, screen: PropTypes.object } static defaultProps = { items: [], total: 0, screen: {} } columns = [ { title: 'Name', dataIndex: 'name', key: 'name', render: text => <b>{text}</b> }, { title: <span> <Tooltip placement='left' title='Tax Included. Hover for item subtotals.'> Price/ea&nbsp; <Icon type='question-circle-o' /> </Tooltip> </span>, // title: <Tooltip placement='left' title='Tax Included. Mouse over for item subtotals.'>Price/ea</Tooltip>, dataIndex: 'price', key: 'price', render: (text, record) => <Tooltip placement='left' title={`Subtotal: ${currency(record.tax ? record.price * record.quantity * (1 + record.tax / 100) : record.price * record.quantity)}`}> {currency(record.price * (1 + record.tax / 100))} </Tooltip>, sorter: (a, b) => a.price - b.price, width: 120, padding: 0 }, { title: 'Q', dataIndex: 'quantity', key: 'quantity', width: 50 } ] expandedRowRender = ({ price, tax, description } = {}) => { return <span> <em>{Number.parseFloat(tax) > 0 ? `${tax}% tax applied to base cost (${currency(price)})` : 'Untaxed or taxed separately'}</em> <p>{description || <em>No description provided</em>}</p> </span> } footer = () => <span><h2>{`Grand Total: ${currency(this.props.total || 0)}`}</h2><h6>Tax Included in Calculation</h6></span> render ( { items, total, screen } = this.props ) { return ( <div> <h1>Budget</h1> {items && <Table dataSource={items} sort size='middle' columns={this.columns} rowKey={record => record._id} // The above will throw an error if using faker data, since duplicates are involved. expandedRowRender={screen.greaterThan.small ? this.expandedRowRender : false} defaultExpandAllRows={screen.greaterThan.small} pagination={false} footer={this.footer} /> } </div> ) } }
JavaScript
class Controller { /** *Creates an instance of Controller. * @param {!object} ui - An instance of AppView * @param {!object} dataRepository - An Instance of DataRepository */ constructor(ui, dataRepository) { this.ui = ui; this.dataRepository = dataRepository; this.ui.displayRestaurantReviews( this.handleDisplayReviews, this.handleDisplayImage ); this.ui.applyReviewRatingEffect(this.handleReviewRatingEffect()); this.ui.executeFilterOptions(this.handleFilter); this.ui.manageReviewsModal(this.handleReviewModalActions); this.ui.manageAddRestaurantDialog(this.handleAddNewRestaurantFormActions); this.ui.manageSearchActions( this.handleSearchActionsService(), this.handleSearchActionsRepository() ); MAP_SERVICE.displayAddRestaurantDialog( this.handleLaunchAddNewRestaurantForm ); } /** * Handles Retrieval of restaurant data that matches id * @param {String} id - Restaurant's restaurantId * @returns A callback that on execution returns a restaurant object * @memberof Controller */ handleDisplayReviews = (id) => { return this.dataRepository.getRestaurantDataFromId(id); }; /** * Handles Retrieval of available restaurant image * @param {object} - A restaurant object * @returns A callback that retrieves a restaurant image * @memberof Controller */ handleDisplayImage = (restaurant) => { return DataService.getAvailableImage(restaurant); }; /** * Handles visual effects * on mouseover and on mouseout * over the review rating stars * @memberof Controller */ handleReviewRatingEffect = () => { return this.ui.reviewRatingStars; }; /** * Handles filtering restaurants based on rating * @param {object} options - Filter from and to rating values * @memberof Controller */ handleFilter = (options) => { const filtered = this.dataRepository.filterRestaurant(options); this.ui.renderRestaurants(filtered); MAP_SERVICE.setRestaurantMarkers(filtered); }; /** * Handles actions on displayed review modal * Mainly, add/submit new reviews and close the modal * @param {string} id - restaurant id * @param {object} data - new review data * @memberof Controller */ handleReviewModalActions = (id, data) => { const restaurant = this.dataRepository.addRestaurantReview(id, data); this.ui.updateModalReviewDetails(restaurant); this.handleFilter(this.ui.filterValues()); }; /** * Handles submission of new restaurant data * or cancel/close submission * @param {object} restaurant - new restaurant data * @memberof Controller */ handleAddNewRestaurantFormActions = (restaurant) => { this.dataRepository.addRestaurant(restaurant); this.handleFilter(this.ui.filterValues()); }; /** * Returns the service used to perform a search * on the map * @memberof Controller */ handleSearchActionsService = () => { return MAP_SERVICE; }; /** * Returns the repository where * the users location is saved * @memberof Controller */ handleSearchActionsRepository = () => { return this.dataRepository; }; /** * Handles the display of form required * to enter restaurant details * when adding a new restaurant * @param {object} event - event object * @memberof Controller */ handleLaunchAddNewRestaurantForm = (event) => { this.ui.displayAddNewRestaurantForm(event); }; /** * Handles Geolocation options * initilises app on success * handles error on failure * @memberof Controller */ initApp = () => { // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( LOCATION_PARAMETERS.locationSuccess, LOCATION_PARAMETERS.locationError, LOCATION_PARAMETERS.locationOptions ); } else { LOCATION_PARAMETERS.locationError(error); } }; }
JavaScript
class Type { constructor(typeString, schema, ...aliases) { if (this.constructor === Type) { throw new Error('Cannot instantiate Type class directly'); } this.type = typeString; this.schema = schema; this.aliases = aliases; this.listeners = []; } addAlias(name) { const self = this; this.aliases.push(name); this.notify({ eventName: 'aliasAdded', target: self, newAlias: name }); return this; } removeAlias(name) { const self = this, idx = this.aliases.indexOf(name); if (idx === -1) { throw new Error(`No such alias ${name}`); } this.aliases.splice(idx, 1); this.notify({ eventName: 'aliasRemoved', target: self, oldAlias: name }); } getAliases() { return this.aliases.slice(); } getKeys() { if (!this.keyFunction) { const tag = Object.prototype.toString.call(this); throw new Error(`${tag} does not implement a key function`); } return this .getNameAndAliases() .map(this.keyFunction); } getNameAndAliases() { return this .getAliases() .concat(this.type); } getSchema() { return this.schema; } getDesign() { return this.schema.getDesign(); } getDataDictionary() { if(!this.schema) { throw new Error('no schema'); } return this.schema.getDataDictionary(); } getFieldData() { return this.schema.getFieldData(); } addListener(listener) { this.listeners.push(listener); return this; } notify(event) { this.listeners.forEach((listener) => { listener.notify(event); }); } }
JavaScript
class Queue { constructor() { this._q = [] } /** * Todo consider how a sequence of async actions should be handled * * @param {...QueueAction} actions on or more QueueActions to apply to the queue */ push(...actions) { for (let i = 0, n = actions.length; i < n; i++) { actions[i].do() this._q.push(actions[i]) } } /** * @returns {mixed} The result of the QueueAction undo, or undefined if the queue is empty */ pop() { return this._q.length ? this._q.pop().undo() : undefined } }
JavaScript
class MyUser { constructor(first, last) { this.id = cuid(); this.first = first; this.last = last; } get name() { return `${this.first} ${this.last}`; } }
JavaScript
class EventRequestBody { /** * Constructs a new <code>EventRequestBody</code>. * @alias module:model/EventRequestBody */ constructor() { EventRequestBody.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>EventRequestBody</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/EventRequestBody} obj Optional instance to populate. * @return {module:model/EventRequestBody} The populated <code>EventRequestBody</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new EventRequestBody(); if (data.hasOwnProperty('created')) { obj['created'] = ApiClient.convertToType(data['created'], DateTimeInterval); } if (data.hasOwnProperty('updated')) { obj['updated'] = ApiClient.convertToType(data['updated'], DateTimeInterval); } if (data.hasOwnProperty('signalIds')) { obj['signalIds'] = ApiClient.convertToType(data['signalIds'], 'String'); } if (data.hasOwnProperty('ids')) { obj['ids'] = ApiClient.convertToType(data['ids'], 'String'); } if (data.hasOwnProperty('portfolios')) { obj['portfolios'] = ApiClient.convertToType(data['portfolios'], 'String'); } if (data.hasOwnProperty('themes')) { obj['themes'] = ApiClient.convertToType(data['themes'], 'String'); } if (data.hasOwnProperty('categories')) { obj['categories'] = ApiClient.convertToType(data['categories'], 'String'); } if (data.hasOwnProperty('userRelevanceScore')) { obj['userRelevanceScore'] = ApiClient.convertToType(data['userRelevanceScore'], RelevanceScoreRange); } if (data.hasOwnProperty('sort')) { obj['sort'] = ApiClient.convertToType(data['sort'], 'String'); } } return obj; } }
JavaScript
class ForceGraphPersistence { /** * Save the graph in a object elem and in the field fieldName * @param elem * @param fieldName */ constructor(elem, fieldName) { this._self = this; this._elem = elem; this._fieldName = fieldName; } /** * Load the graph positions. * @returns {*} */ load() { let prevLoc = []; if (this._elem && this._elem[this._fieldName]) { prevLoc = JSON.parse(this._elem[this._fieldName]); return prevLoc.data; } } /** * Save D3 data nodes. * Ex: d3.selectAll(".node") * * @param data D3 nodes. */ save(data) { // Save node positions to an object: let prevLoc = []; data.each(function(d) { if (d && d.id) { prevLoc.push({'id':d.id, 'x':d.x, 'y':d.y}); } }); if (this._elem && prevLoc.length > 0) { this._elem[this._fieldName] = JSON.stringify({"data":prevLoc}); } } }
JavaScript
class Healthcheck { /** * @constructor * @param {object} repConfig - extensions.replication configs * @param {node-zookeeper-client.Client} zkClient - zookeeper client * @param {BackbeatProducer} crrProducer - producer for CRR topic * @param {BackbeatProducer} crrStatusProducer - CRR status producer * @param {BackbeatProducer} metricProducer - producer for metric */ constructor(repConfig, zkClient, crrProducer, crrStatusProducer, metricProducer) { this._repConfig = repConfig; this._zkClient = zkClient; this._crrProducer = crrProducer; this._crrStatusProducer = crrStatusProducer; this._metricProducer = metricProducer; } _checkProducersReady() { return this._crrProducer.isReady() && this._metricProducer.isReady() && this._crrStatusProducer.isReady(); } _getConnectionDetails() { return { zookeeper: { status: this._zkClient.getState().name === 'SYNC_CONNECTED' ? 'ok' : 'error', details: this._zkClient.getState(), }, kafkaProducer: { status: this._checkProducersReady() ? 'ok' : 'error', }, }; } /** * Checks health of in-sync replicas * @param {object} topicMd - topic metadata object * @return {string} 'ok' if ISR is healthy, else 'error' */ _checkISRHealth(topicMd) { let status = 'ok'; topicMd.partitions.forEach(partition => { if (partition.isrs && partition.isrs.length !== IN_SYNC_REPLICAS) { status = 'error'; } }); return status; } /** * Ensure that there is an in-sync replica for each partition. * @param {object} topicMd - topic metadata object * @return {boolean} true if each partition has a replica, false otherwise */ _isMissingISR(topicMd) { return topicMd.partitions.some(partition => (partition.isrs && partition.isrs.length === 0)); } /** * Builds the healthcheck response * @param {Werelogs} log - The werelogs logger * @param {function} cb - callback(error, data) * @return {undefined} */ getHealthcheck(log, cb) { const params = { topic: this._repConfig.topic, timeout: 10000 }; this._crrProducer.getMetadata(params, (err, res) => { if (err) { log.error('error getting healthcheck metadata for topics', { method: 'Healthcheck.getHealthcheck', error: err, }); return cb(errors.InternalError); } const response = {}; const topics = {}; const connections = {}; const topicMd = res.topics.find( topic => topic.name === this._repConfig.topic); if (topicMd) { topics[this._repConfig.topic] = topicMd; connections.isrHealth = this._checkISRHealth(topicMd); } if (topicMd && this._isMissingISR(topicMd)) { log.error('no in-sync replica for partition', { method: 'Healthcheck.getHealthcheck', topicMd, }); return cb(errors.InternalError); } Object.assign(connections, this._getConnectionDetails()); response.topics = topics; response.internalConnections = connections; return cb(null, response); }); } }
JavaScript
class Square { constructor(north, south, east, west) { this.north = north; this.south = south; this.east = east; this.west = west; this.start = false; this.end = false; } makeStart() { this.start = true; } makeEnd() { this.end = true; } }
JavaScript
class Grid { /** * @param {Array[]} data The data to populate this grid with. */ constructor(data) { this.data = data; } /** * Builds a grid given dimensions and a value. * @param {number} rows The amount of rows (vertical, Y) to have. * @param {number} columns The amount of columns (horizontal, X) to have. * @param {*} defaultValue The value of each cell. * @returns {Array[]} The built grid. */ static build(rows, columns, defaultValue) { return new Array(rows).fill().map(() => { return new Array(columns).fill().map(() => { return defaultValue; }); }); } }
JavaScript
class RequestedFaceMatchCheck extends RequestedCheck { /** * @param {RequestedFaceMatchCheckConfig} config */ constructor(config) { Validation.instanceOf(config, RequestedFaceMatchCheckConfig, 'config'); super(DocScanConstants.ID_DOCUMENT_FACE_MATCH, config); } }
JavaScript
class AuthLocalController { /** * @description user signup function * @param {object} req request from user * @param {object} res response from server * @return {object} user information & token */ static async signup(req, res) { const { email, firstName, lastName } = req.body; req.body.password = helper.password.hash(req.body.password); const newUser = await User.create(req.body); const errors = newUser.errors ? helper.checkCreateUpdateUserErrors(newUser.errors) : null; return errors ? res.status(errors.code).json({ errors: errors.errors }) : (await helper.sendMail(email, 'signup', { email, firstName, lastName })) && res.status(status.CREATED).json({ message: 'check your email to activate your account', user: newUser }); } /** * @description - login user function * @param {object} req user request * @param {object} res response form server * @returns {object} user token */ static async login(req, res) { const { email, password } = req.body; const checkUser = await User.findOne({ email }); if (Object.keys(checkUser).length > 0) { const comparePassword = helper.password.compare(password, checkUser.password || ''); if (!comparePassword) { return res.status(status.UNAUTHORIZED).json({ errors: { credentials: 'The credentials you provided are incorrect' } }); } const payload = { id: checkUser.id, role: checkUser.role, permissions: checkUser.permissions }; const token = helper.token.generate(payload); delete checkUser.password; return res.status(status.OK).json({ message: 'signIn successfully', user: checkUser, token }); } } /** * @description function to delete user * @param {object} req user request object * @param {object} res response object from server * @returns {object} return true if user deleted or false when user not deleted */ static async deactivateAccount(req, res) { const { id } = req.params; const deactivateAccount = await User.update({ isActive: false }, { id }); return deactivateAccount ? res.status(status.OK).json({ message: 'User account deleted successfully', userId: id }) : res.status(status.UNAUTHORIZED).json({ errors: 'Unauthorized access' }); } /** * @description method to find one user * @param {object} req user request object * @param {object} res response object from server * @returns {object} return all users */ static async getOne(req, res) { const id = Number.parseInt(req.params.id, 10); const fetchUser = await User.findOne({ id: Number.isNaN(id) ? 0 : id }); delete fetchUser.password; return Object.keys(fetchUser).length ? res.status(status.OK).json({ user: fetchUser }) : res .status(status.NOT_FOUND) .json({ errors: { user: `sorry, user with id "${req.params.id}" not found!!` } }); } /** * @description function for admin to create user * @param {object} req user request object * @param {object} res response object from server * @returns {object} return true if user created or flase when was not */ static async create(req, res) { const { email, firstName, lastName } = req.body; req.body.password = helper.password.hash(req.body.password); const newUser = await User.create(req.body); if (newUser.errors) { const errors = helper.checkCreateUpdateUserErrors(newUser.errors); const { code } = errors; delete errors.code; return res.status(code).json(errors); } if (newUser) { await helper.sendMail(email, 'signup', { email, firstName, lastName }); return res.status(status.CREATED).json({ message: `activation message sent to ${req.body.email}` }); } } /** * @description function to activate user account * @param {object} req * @param {object} res * @returns {object} it return true if account activeted otherwise it return false */ static async activate(req, res) { const { user } = req; await User.update({ isActive: true }, { email: user.email }); return res.redirect(`${(CI && travis) || appUrl}/login`); } /** * @param {object} req * @param {object} res * @return {object} return an object containing the confirmation message */ static async sendEmail(req, res) { const { email } = req.body; const result = await User.findOne({ email }); // check if the email exist if (Object.keys(result).length <= 0) { return res.status(status.NOT_FOUND).json({ errors: 'email not found..' }); } await helper.sendMail(email, 'resetPassword', { email, names: `${result.firstName} ${result.lastName}` }); // send mail return res.status(status.OK).json({ message: 'Email sent, please check your email' }); } /** * @param {object} req * @param {object} res * @return {object} return an object containing the confirmation message */ static async updatePassword(req, res) { const token = req.body.token || req.params.token; const { passwordOne, passwordTwo } = req.body; if (passwordOne !== passwordTwo) { return res.status(status.BAD_REQUEST).json({ errors: 'Passwords are not matching' }); } if (!req.body.passwordOne || !req.body.passwordTwo) { return res.status(status.BAD_REQUEST).json({ errors: 'the password can not be empty' }); } const isPasswordValid = validate.password(passwordOne, 'required'); const isPasswordValidTwo = validate.password(passwordTwo, 'required'); if (isPasswordValid.length || isPasswordValidTwo.length) { return res.status(status.BAD_REQUEST).json({ message: isPasswordValid[0] }); } const { email } = helper.token.decode(token); const isUpdated = await User.update({ password: helper.password.hash(passwordOne) }, { email }); delete isUpdated.password; return isUpdated ? res .status(status.OK) .json({ isUpdated, message: 'Success! your password has been changed.' }) : res.status(status.NOT_MODIFIED).json({ errors: 'Password not updated' }); } }
JavaScript
class PrivilegeOperation { static OPERATIONS = { GRANT: 'GRANT', REVOKE: 'REVOKE', DENY: 'DENY', }; static DATABASE_OPERATIONS = dbOps; static PRIVILEGES = { TRAVERSE: 'TRAVERSE', READ_ALL: 'READ {*}', MATCH_ALL: 'MATCH {*}', WRITE: 'WRITE', }; static ENTITIES = { ALL_NODES: 'NODES *', ALL_RELS: 'RELATIONSHIPS *', ALL_ELEMENTS: 'ELEMENTS *', }; static VALID_OPERATIONS = ['GRANT', 'REVOKE', 'DENY']; static VALID_PRIVILEGES = ['TRAVERSE', 'READ {*}', 'MATCH {*}', 'WRITE'] .concat(Object.values(PrivilegeOperation.DATABASE_OPERATIONS)); static VALID_ENTITIES = ['NODES *', 'RELATIONSHIPS *', 'ELEMENTS *']; constructor(props) { this.operation = props.operation; this.privilege = props.privilege; this.database = props.database; this.entity = props.entity; this.role = props.role; } static isDatabaseOperation(priv) { return Object.values(PrivilegeOperation.DATABASE_OPERATIONS).indexOf(priv) > -1; } /** * In the construction of certain queries, the entity portion isn't * used. This lets you determine whether the entity portion applies * based on the privilege in question. * @param {String} priv */ static allowsEntity(priv) { if (priv === 'WRITE' || PrivilegeOperation.isDatabaseOperation(priv)) { return false; } return true; } properties() { return { operation: this.operation, privilege: this.privilege, // TODO: in 4.0 graphs and databases are the same, but this will not persist long // term. database: this.database || this.graph, graph: this.graph, entity: this.entity, role: this.role, }; } validate() { let error = null; ['operation', 'privilege', 'database', 'entity', 'role'].forEach(key => { if (!this[key]) { error = `Missing key ${key}`; } }); return error; } /** * Neo4j reports the privileges back in an awkward schema. This function turns a row * of { action, grant, resource, role, segment, graph } into a PrivilegeOperation. * * This function lets you take an existing privilege, and easily "undo" it, by applying * a different operation to it. * * Sorry, but this is difficult code because of the syntax peculiarities of how permissions * commands work in 4.0 * * @param {String} operation: one of GRANT, REVOKE, DENY * @param {Object} row */ static fromSystemPrivilege(operation, row) { const actionToVerb = a => { // #operability the output of show privileges doesn't match actual // permissions names when granting, which is confusing. const mapping = { read: 'READ', write: 'WRITE', find: 'TRAVERSE', create_propertykey: dbOps.CREATE_PROPERTY, create_reltype: dbOps.CREATE_RELATIONSHIP, create_label: dbOps.CREATE_LABEL, drop_constraint: dbOps.DROP_CONSTRAINT, constraint_management: dbOps.CONSTRAINT_MANAGEMENT, create_constraint: dbOps.CREATE_CONSTRAINT, create_index: dbOps.CREATE_INDEX, drop_index: dbOps.DROP_INDEX, name_management: dbOps.NAME_MANAGEMENT, start_database: dbOps.START, stop_database: dbOps.STOP, access: dbOps.ACCCESS, }; return mapping[a.toLowerCase()] || a.toUpperCase(); }; const resourceToWhat = r => { // When you say READ (*) the "resource" will appear as "all_properties" // When you say TRAVERSE the "resource" will appear as "graph". const mapping = { graph: '', all_properties: '{*}', }; const v = mapping[r]; if (!_.isNil(v)) { return v; } // Resource can be "property(foo, bar)" const re = new RegExp('property\\((?<list>.*?)\\)'); const match = r.match(re); if (match && match.groups && match.groups.list) { return `(${match.groups.list})`; } return v ? v : ''; }; const verb = actionToVerb(row.action); const what = resourceToWhat(row.resource); // #operability because WRITE {proplist} isn't supported in 4.0, WRITE has a special // form. You GRANT WRITE and DENY WRITE, but never DENY WRITE {*} which is a syntax error // despite it meaning the same thing. This means there are certain privileges and actions // that don't permit an "entity" ({*}) and you have to watch out for this special case when // generating queries. const privilege = (what && this.allowsEntity(verb)) ? `${verb} ${what}` : verb; // If you did GRANT MATCH (*) ON foo NODES * TO role // That "NODES *" would turn into segment=NODE(*) so we're reversing that mapping // to turn what Neo4j gives us with SHOW PRIVILEGES into something that // can be used to build a related privilege command. const entityFromSegment = s => { // Case: turn "NODE(Foo) => NODES Foo" // #operability: grant syntax is NODES{*} but return in the table is NODES(*) // which is super annoying to have to translate back and forth, and users // may not know the difference. const re = new RegExp('(?<element>(NODE|RELATIONSHIP))\\((?<list>.*?)\\)'); const match = s.match(re); if (match && match.groups && match.groups.list) { return `${match.groups.element}S ${match.groups.list}`; } // Sometimes entity doesn't apply. return 'DATABASE'; }; const props = { operation, database: row.graph, entity: entityFromSegment(row.segment), role: row.role, privilege, }; const op = new PrivilegeOperation(props); return op; } buildQuery() { // sentry.fine('buildQuery', this); const op = this.operation; const priv = this.privilege; // Escape with back-ticks ONLY if the database isn't *. // #operability otherwise we defeat the * expansion and are talking about // a database named * which cannot exist due to naming rules. const db = this.database === '*' ? this.database : `\`${this.database}\``; // When the entity is 'DATABASE' effectively the entity doesn't apply. // For example when GRANT START ON DATABASE FOO TO ROLE const entity = this.entity === 'DATABASE' ? '' : this.entity; const role = this.role; let graphToken = (db === '*') ? 'GRAPHS' : 'GRAPH'; // #operability when referring to database privileges the syntax is different. if (PrivilegeOperation.isDatabaseOperation(priv)) { graphToken = 'DATABASE'; } const preposition = (op === 'REVOKE') ? 'FROM' : 'TO'; /** * WRITE does not support ELEMENTS * https://neo4j.com/docs/cypher-manual/4.0-preview/administration/security/subgraph/#administration-security-subgraph-write */ if (priv.indexOf('WRITE') > -1) { return `${op} ${priv} ON ${graphToken} ${db} ${preposition} ${role}`; } else if(Object.values(PrivilegeOperation.DATABASE_OPERATIONS).indexOf(priv) > -1) { return `${op} ${priv} ON DATABASE ${db} ${preposition} ${role}`; } return `${op} ${priv} ON ${graphToken} ${db} ${entity} ${preposition} ${role}`; } }
JavaScript
class LayoutBuilder extends Component { /** * Handles a `click` event on a button for removing rows. * @param {!Event} event * @protected */ handleClickRemove_(event) { var element = event.delegateTarget; var index = parseInt(element.getAttribute('data-index'), 10); this.rows.splice(index, 1); this.rows = this.rows; } }
JavaScript
class PreloaderModule extends Module { /** * @memberof Vevet.PreloaderModule * @typedef {object} Properties * @augments Vevet.Module.Properties * * @property {string|HTMLElement} [selector=.v-preloader] - *** The selector of the preloader element. * @property {number} [animation=750] - Duration of animation when hiding. * @property {number} [animationInner=25] - Inner animation before the preloader hides. * @property {Vevet.PreloaderModule.Progress} [progress] * @property {boolean} [hide] - Defines if the preloader will be hidden automatically * when all resources are loaded. */ /** * @memberof Vevet.PreloaderModule * @typedef {object} Progress * @property {boolean} [on=false] - If enabled, the progress of loading resources will be enabled. * @property {number} [k=0.1] - The higher number, the faster animation. * @property {boolean} [forceEnd=false] - When resources are loaded and the progress is still not 100%, * this allows to end animation in a certain period of time. * @property {number} [forceEndDuration=3000] - Duration of the force-ednd-animation. * @property {boolean} [images=true] - Load images. * @property {string|false} [bgSelector=*:not(script)] - If you are loading images, you may also need to load * background images. To do this, set a background selector or make it false to skip this step. * @property {boolean} [videos=true] - Load videos. * @property {number} [resources=0] - Amount of resources to be loaded. * It's a rare case when you need to set it. * F.e., whe you want to imitate loading resources when there's actually none of them. * @property {string|Array<number>|Function} [easing] - Easing function. * The default value is equal to {@linkcode Vevet.Application#easing}. */ /** * @alias Vevet.PreloaderModule * * @param {Vevet.PreloaderModule.Properties} [data] */ constructor(data) { super(data); } get prefix() { return `${this._v.prefix}preloader`; } /** * @readonly * @type {Vevet.PreloaderModule.Properties} */ get defaultProp() { return merge(super.defaultProp, { selector: '.' + this._prefix, animation: 750, animationInner: 25, progress: { on: false, k: .01, forceEnd: false, forceEndDuration: 3000, easing: this._vp.easing, images: true, bgSelector: '*:not(script)', videos: true, resources: 0 }, hide: true }); } /** * @member Vevet.PreloaderModule#prop * @memberof Vevet.PreloaderModule * @readonly * @type {Vevet.PreloaderModule.Properties} */ /** * @member Vevet.PreloaderModule#_prop * @memberof Vevet.PreloaderModule * @protected * @type {Vevet.PreloaderModule.Properties} */ /** * @function Vevet.PreloaderModule#changeProp * @memberof Vevet.PreloaderModule * @param {Vevet.PreloaderModule.Properties} [prop] */ /** * @description If the page is loaded. * @default false * @readonly * @type {boolean} */ get loaded() { return this._v.load.loaded; } /** * @description Get total amount of resources that are being loaded. * @default false * @readonly * @type {number} */ get resourcesTotal() { return this._resourcesTotal; } /** * @description Get total amount of resources that are loaded. * @default false * @readonly * @type {number} */ get resourcesLoaded() { return this._resourcesLoaded; } /** * @description If the preloader is hidden. * @default false * @readonly * @type {boolean} */ get hidden() { return this._hidden; } /** * @description Outer element. * @readonly * @type {HTMLElement} */ get outer() { return this._outer; } // Extra Constructor _extra() { super._extra(); let prop = this._prop; /** * @description Outer element. * @protected * @member {HTMLElement} */ this._outer = selectEl.one(prop.selector); this._outer.classList.add(this._prefix); /** * @description Current loading time. * @protected * @member {number} */ this._time = +new Date(); /** * @description If the preloader is hidden. * @protected * @member {boolean} */ this._hidden = false; /** * @description Images list. * @protected * @member {Array<string>} */ this._images = []; /** * @description Videos list. * @protected * @member {Array<HTMLVideoElement>} */ this._videos = []; /** * @description Total amount of resources. * @protected * @member {number} */ this._resourcesTotal = prop.progress.resources; /** * @description Total amount of loaded resources. * @protected * @member {number} */ this._resourcesLoaded = 0; /** * @description Loading progress. * @protected * @member {number} */ this._progressLoad = 0; /** * @description Loading animation progress. * @protected * @member {number} */ this._progressAnim = 0; /** * @description Progress animationFrame. * @protected * @member {null|number} */ this._progressFrameId = null; /** * @description If progress enabled. * @protected * @member {boolean} */ this._progressBool = true; // set styles to the preloader this._setStyles(); } /** * @description Set transition styles of the preloader. * @protected */ _setStyles() { let outer = this._outer; outer.style.opacity = '1'; outer.style.transition = `${this._prop.animation / 1000}s`; outer.classList.add(`${this._prefix}_animate`); return true; } // Set Events _setEvents() { // when the page is loaded this.addEvent('load', { name: this._name, do: () => { this._onloaded(); } }); // copy properties let progressProp = this._prop.progress; // load resources if enables if (progressProp.on) { // count resources if (progressProp.images) { this._resourcesTotal += this._getImages(); } if (progressProp.videos) { this._resourcesTotal += this._getVideos(); } // check how many resources there are // if more than zero, an animation frame will be launched // and the resources will be loaded if (this._resourcesTotal > 0) { this._resourcesLoad(); this._frameLaunch(); } else { this._onloaded(); } } } /** * @description Add images to stack. * @protected * @returns {number} Total number of images to be loaded. */ _getImages() { let images = this._images; // get real DOM images let imgs = document.querySelectorAll("img"); imgs.forEach(img => { images.push(img.src); }); // get backgrounds let bgSelector = this._prop.progress.bgSelector; if (bgSelector) { let el = document.querySelectorAll(bgSelector); for (let i = 0; i < el.length; i++) { let url = getComputedStyle(el[i]).backgroundImage; if (url.indexOf('none') == -1 & url.indexOf('-gradient') == -1) { if (url.indexOf('url') != -1) { let temp = url.match(/url\((.*?)\)/); url = temp[1].replace(/"/g, ''); images.push(url); } } else { if (el[i].tagName == "IMG") { images.push(el[i].src); } } } } return images.length; } /** * @description Add videos to stack. * @protected * @returns {number} Total number of images to be loaded. */ _getVideos() { let videos = this._videos; let el = document.querySelectorAll('video'); for (let i = 0; i < el.length; i++) { videos.push(el[i]); } return videos.length; } /** * @description Load real resources. * @protected */ _resourcesLoad() { let images = this._images, videos = this._videos; // load images for (let i = 0; i < images.length; i++) { let image = new Image(); image.onload = () => { this._resourcesOnLoaded(); }; image.onerror = () => { this._resourcesOnLoaded(); }; image.src = images[i]; } // load videos for (let i = 0; i < videos.length; i++) { videos[i].load(); videos[i].onloadeddata = () => { this._resourcesOnLoaded(); } } } /** * @memberof Vevet.PreloaderModule * @typedef {object} Callback * @property {number} progress Current loading progress. * @property {number} easing Current easing progress. * @property {number} loaded Number of resources loaded. * @property {number} total Total number of resources. */ /** * @description Event on any resource loaded. * @protected */ _resourcesOnLoaded() { let total = this._resourcesTotal; // iterate the quantity of loaded resources this._resourcesLoaded++; let loaded = this._resourcesLoaded; // and update the progress value - NOT THE FRAME PROGRESS this._progressLoad = loaded / total; // when all resources are loaded if (loaded == total) { this._onloaded(); } } /** * @description Iterate total amount of resources. * @param {number} num - Amount of resources to add. */ resourcesAddTotal(num = 1) { this._resourcesTotal += num; } /** * @description Iterate total amount of resources that are loaded. * @param {number} num - Amount of resources to add. */ resourcesAddLoaded(num = 1) { for (let i = 0; i < num; i++) { this._resourcesOnLoaded(); } } /** * @description Set progress animation frame. * @protected */ _frameLaunch() { this._progressFrameId = window.requestAnimationFrame(this._frame.bind(this)); } /** * @description Frame animation * @protected */ _frame() { // check if animation progress is enabled if (!this._progressBool) { return; } let prop = this._prop; // progress interpolation this._progressAnim = lerp(this._progressAnim, this._progressLoad, prop.progress.k); let progress = this._progressAnim; // if close to 1 if (progress >= .999) { progress = 1; } // launch callbacks this.lbt('progress', { progress: progress, easing: easing(progress, prop.progress.easing), loaded: this._resourcesLoaded, total: this._resourcesTotal }); // stop animaton frame if progress is close to 1 or equal to 1 if (progress == 1) { cancelAnimationFrame(this._progressFrameId); // hide this._onloaded(); return; } // continue animation this._progressFrameId = window.requestAnimationFrame(this._frame.bind(this)); } /** * @description Timeline animation. * @protected * @param {Vevet.TimelineModule.Data} p */ _progressFrameForce(p) { this._progressAnim = p.s; // callbacks if animation is still in process this.lbt('progress', { progress: this._progressAnim, easing: easing(p.s, this._prop.progress.easing), loaded: this.resourcesLoaded, total: this.resourcesTotal }); // callbacks if animation ended if (p.p === 1) { this._onloaded(); return; } } /** * @description Call it when either all resources are loaded or the page is loaded. * @protected */ _onloaded() { // return if page not loaded if (!this.loaded) { return; } let progressProp = this._prop.progress; // if progress is enabled // we will launch a timeline animation for the preloader if (progressProp.on) { // return if not all resources are loaded if (this._resourcesTotal > this._resourcesLoaded) { return; } // run animation if (this._progressAnim < 1) { if (progressProp.forceEnd) { // stop frame animation cancelAnimationFrame(this._progressFrameId); this._progressBool = false; // create a timeline animation let timeline = new TimelineModule({ destroyOnEnd: true }); timeline.add({ target: 'progress', do: this._progressFrameForce.bind(this) }); timeline.play({ duration: progressProp.forceEndDuration, easing: 'linear', // progressProp.easing, scope: [this._progressAnim, 1] }); return; } else{ return; } } } // hide preloader this._hide(); } /** * @description Hide preloader. */ hide() { let interval = this._interval(); timeoutCallback(this._hideAnimate.bind(this), interval); } /** * @description Hide callback. Hide preloader when everything is loaded. * @protected */ _hide() { this.lbt('hide'); if (this._prop.hide) { this.hide(); } } /** * @description Difference between the start time and the end time. * Inner animation duration is applied. */ _interval() { let time = +new Date(), diff = time - this._time, inner = this._prop.animationInner; let interval = 0; if (diff < inner) { interval = inner - diff; } return interval; } /** * @description Now we really hide the preloader. * @protected */ _hideAnimate() { let outer = this._outer, prefix = this._prefix; outer.style.opacity = '0'; outer.classList.add(`${prefix}_hide`); setTimeout(() => { outer.classList.add(`${prefix}_hidden`); this._onhidden(); }, this._prop.animation); } /** * @description This action is called when the preloader is finally hidden. * @protected */ _onhidden() { this._hidden = true; this.lbt('hidden'); } }
JavaScript
class Porter { /** * Object with events. */ events = {}; /** * Raw websocket events. */ rawEvents = {}; /** * Options. */ options = { pingInterval: 30000, maxBodySize: 1e+6, }; /** * Queue while WebSocket not connected. */ shouldSend = []; /** * @param {function} */ connected = null; /** * @param {function} */ disconnected = null; /** * @param {function} */ error = null; /** * @param {function} */ pong; pingInterval; /** * Constructor. * * @param {WebSocket} ws */ constructor(ws, options) { this.ws = ws; if (options) { this.options = { ...this.options, ...options }; } this.initPingPongEvent(); } initPingPongEvent() { this.pingInterval ? clearInterval(this.pingInterval) : this.pingInterval = setInterval(() => { this.sendRaw('ping'); }, this.options.pingInterval); this.onRaw('pong', payload => { // code... // exec user function for pong event if (typeof this.pong == 'function') { this.pong(payload); } }); } /** * Handle event from server. * * @param {string} type * @param {function} handler * @returns {self} */ on(type, handler) { this.events[type] = handler; return this; } /** * Send event to server. * * @param {string} type * @param {object} data * @param {?function} handler opt_argument Alternative for `on` method. * @returns */ event(type, data, callback) { if (callback) { this.on(type, callback); } if (this.ws.readyState !== WebSocket.OPEN) { this.shouldSend.push({ type: type, data: data }); return this; } let eventData = JSON.stringify({ type: type, data: data || {}, }); var bodySize = new Blob([eventData]).size; if (bodySize / this.options.maxBodySize > 1) { console.warn( `The event was not dispatched because the body size (${bodySize}) exceeded the allowable value (${this.options.maxBodySize}).` ); return this; }; this.ws.send(eventData); return this; } onRaw(data, handler) { if (data == 'pong' && 'pong' in this.rawEvents) { throw new Error( 'You cannot override the "pong" service event. Use `porterInstance.pong = () => {...}` instead.' ); } this.rawEvents[data] = handler; return this; } sendRaw(data) { this.ws.send(data); } /** * Start listen events from server. */ listen() { this.ws.onopen = () => { this.shouldSend.forEach(event => { this.event(event.type, event.data); }); this.connected && this.connected.call(); }; this.ws.onclose = this.disconnected; this.ws.onerror = this.error; this.ws.onmessage = event => { try { var payload = JSON.parse(event.data); var handler = this.events[payload.type] || null; } catch (error) { var payload = event.data; var handler = this.rawEvents[event.data] || null; } if (typeof handler == 'function') { handler(payload); } } } /** * Close connection. */ close() { this.ws.close(); } }
JavaScript
class ProcessEnvConfigService { constructor() { this._properties = new Map(); // We cannot use the EnvironmentService for accessing the window object. It is not yet initialized at this moment. // eslint-disable-next-line no-undef this._properties.set('RUNTIME_MODE', window?.ba_externalConfigProperties?.NODE_ENV ?? process.env.NODE_ENV); // eslint-disable-next-line no-undef this._properties.set('SOFTWARE_INFO', window?.ba_externalConfigProperties?.SOFTWARE_INFO ?? process.env.SOFTWARE_INFO); // eslint-disable-next-line no-undef this._properties.set('DEFAULT_LANG', window?.ba_externalConfigProperties?.DEFAULT_LANG ?? process.env.DEFAULT_LANG); // eslint-disable-next-line no-undef this._properties.set('PROXY_URL', window?.ba_externalConfigProperties?.PROXY_URL ?? process.env.PROXY_URL); // eslint-disable-next-line no-undef this._properties.set('BACKEND_URL', window?.ba_externalConfigProperties?.BACKEND_URL ?? process.env.BACKEND_URL); // eslint-disable-next-line no-undef this._properties.set('SHORTENING_SERVICE_URL', window?.ba_externalConfigProperties?.SHORTENING_SERVICE_URL ?? process.env.SHORTENING_SERVICE_URL); // eslint-disable-next-line no-undef this._properties.set('FIRST_STEPS_CONTENT_URL', window?.ba_externalConfigProperties?.FIRST_STEPS_CONTENT_URL ?? process.env.FIRST_STEPS_CONTENT_URL); this._properties.forEach((value, key) => { if (value === undefined) { console.warn('No config property found for ' + key + '. This is likely because the .env file is missing or you have to append this key to the .env file.'); } }); } /** * * @param {string} value * @private */ _trailingSlash(value, append) { if (!value) { return; } value = value.trim(); if (append) { return value.endsWith('/') ? value : value + '/'; } return value.replace(/\/$/, ''); } /** * * @param {string} key * @param {string} defaultValue * @public */ getValue(key, defaultValue) { // eslint-disable-next-line no-undef if (this.hasKey(key)) { // eslint-disable-next-line no-undef return this._properties.get(key); } if (defaultValue !== undefined) { return defaultValue; } throw new Error(`No value found for '${key}'`); } /** * Ensures that the value ends with a <code>/</code> * @param {string} key * @param {string} defaultValue * @public */ getValueAsPath(key, defaultValue) { return this._trailingSlash(this.getValue(key, defaultValue), true); } /** * * @param {string} key * @public */ hasKey(key) { return !!this._properties.get(key); } }
JavaScript
class DependencyManager { constructor({ rootNode, onNodeRemoved, onNodeAdded, onError, onTreeUpdate = () => {}, }) { this.nodeContext = {} this.dependencies = {} this.dependingOn = {} this.onNodeAdded = onNodeAdded this.onTreeUpdate = onTreeUpdate this.onError = onError this.dependencies[rootNode] = [] this.onNodeAdded(rootNode) } getTree() { return this.tree } updateDependencies(name, list) { const oldDepenencies = this.dependencies[name] const addedDependencies = setDifference(oldDepenencies, list) const removedDependencies = setDifference(list, oldDepenencies) // No changes? if (!addedDependencies.length && !removedDependencies.length) { return } const oldListOfModules = Object.keys(this.dependingOn) // Sync this.dependingOn and this.dependencies addedDependencies.forEach(addedDependency => { const set = this.dependingOn[addedDependency] || new Set() this.dependingOn[addedDependency] = set this.dependingOn[addedDependency].add(name) }) removedDependencies.forEach(removedDependency => { const set = this.dependingOn[removedDependency] set.delete(name) if (!set.size) { delete this.dependingOn[removedDependency] } }) // Set the new value for this node this.dependencies[name] = [...list] this.checkTree(oldListOfModules) /* const circularDependencies = this.checkCircularDependencies(name) if (!circularDependencies.length) { this.onError('Circular dependencies:', circularDependencies.join('->')) } */ // this.onTreeUpdate(this.dependencies, this.dependingOn) } checkTree(oldListOfModules) { // Check if modules has changed const listOfModules = Object.keys(this.dependingOn) const addedNodes = setDifference(oldListOfModules, listOfModules) const removedNodes = setDifference(listOfModules, oldListOfModules) // Notify listeners removedNodes.forEach(nodeName => { delete this.dependencies[nodeName] this.onNodeRemoved(nodeName, this.nodeContext[nodeName]) }) addedNodes.forEach(nodeName => { this.dependencies[nodeName] = [] this.nodeContext[nodeName] = this.onNodeAdded(nodeName) }) this.onTreeUpdate( addedNodes, removedNodes, this.dependencies, this.dependingOn ) } checkCircularDependencies(name, originalName) { // Error! if (originalName === name) { return [name] } return [ ...this.dependencies[name] .every(this.checkCircularDependencies), ] } }
JavaScript
class TransactionId { /** * @param {AccountId} accountId * @param {Timestamp} validStart */ constructor(accountId, validStart) { /** * The Account ID that paid for this transaction. * * @readonly */ this.accountId = accountId; /** * The time from when this transaction is valid. * * When a transaction is submitted there is additionally a validDuration (defaults to 120s) * and together they define a time window that a transaction may be processed in. * * @readonly */ this.validStart = validStart; Object.freeze(this); } /** * Generates a new transaction ID for the given account ID. * * Note that transaction IDs are made of the valid start of the transaction and the account * that will be charged the transaction fees for the transaction. * * @param {AccountId | string} id * @returns {TransactionId} */ static generate(id) { return new TransactionId( typeof id === "string" ? AccountId.fromString(id) : id, Timestamp.generate() ); } /** * @param {string} id * @returns {TransactionId} */ static fromString(id) { const [account, time] = id.split("@"); const [seconds, nanos] = time.split(".").map(Number); return new TransactionId( AccountId.fromString(account), new Timestamp(seconds, nanos) ); } /** * @returns {string} */ toString() { return `${this.accountId.toString()}@${this.validStart.seconds.toInt()}.${this.validStart.nanos.toInt()}`; } /** * @internal * @param {proto.ITransactionID} id * @returns {TransactionId} */ static _fromProtobuf(id) { return new TransactionId( AccountId._fromProtobuf( /** @type {proto.IAccountID} */ (id.accountID) ), Timestamp._fromProtobuf( /** @type {proto.ITimestamp} */ (id.transactionValidStart) ) ); } /** * @internal * @returns {proto.ITransactionID} */ _toProtobuf() { return { accountID: this.accountId._toProtobuf(), transactionValidStart: this.validStart._toProtobuf(), }; } /** * @param {Uint8Array} bytes * @returns {TransactionId} */ static fromBytes(bytes) { return TransactionId._fromProtobuf(proto.TransactionID.decode(bytes)); } /** * @returns {Uint8Array} */ toBytes() { return proto.TransactionID.encode(this._toProtobuf()).finish(); } }
JavaScript
class MessageLogger extends Module { constructor() { super(); this.module = 'MessageLogger'; this.friendlyName = 'Message Logger'; this.description = 'Logs incoming messages to the database.'; this.core = true; this.enabled = true; this.list = false; } static get name() { return 'MessageLogger'; } /** * Log messages to the db * @param {Message} message Message object */ messageCreate({ message, guildConfig }) { const globalConfig = this.dyno.globalConfig; if (globalConfig && globalConfig.modules.hasOwnProperty(this.module) && globalConfig.modules[this.module] === false) return; if (!this.isEnabled(message.channel.guild, this.dyno.modules.get('ActionLog'), guildConfig)) return; if (!message.author) return; Message.collection.insert({ id: message.id, type: message.type, channelID: message.channel.id, content: message.content, cleanContent: message.cleanContent, timestamp: message.timestamp, author: Object.assign(message.author.toJSON(), { avatarURL: message.author.avatarURL }), createdAt: new Date(), }); } }
JavaScript
class Auth extends Component { render() { return ( <div className="background-white"> { this.props.user ? this.props.children : ( <div className="is-padding"> <h2 className="subtitle"> 您好,您需要登录才能浏览本页面, 若您没有尚贝里学联ID, 请点击“注册”选项卡注册 </h2> <Account register={this.props.register} /> </div> ) } </div> ) } }
JavaScript
class MultisigFollowUp extends PureComponent { static get propTypes() { return { joinKey: PropTypes.string, token: PropTypes.string, walletId: PropTypes.string, cosignerId: PropTypes.string, path: PropTypes.string, m: PropTypes.number, n: PropTypes.number, initialized: PropTypes.bool, cosigners: PropTypes.array, history: PropTypes.object, // react-router history action: PropTypes.string, setTemporarySecrets: PropTypes.func, }; } static get defaultProps() { return { joinKey: null, token: null, cosigners: [], }; } headerCopy() { const { action, walletId, m, n, cosigners, initialized } = this.props; // action can be join or new if (action === 'join') { // wallet can be initialized or not initialized if (initialized) return `Wallet ${walletId} initialized`; return `Wallet ${walletId} has ${cosigners.length}, needs ${n} total`; } if (action === 'new') return `Your wallet ${m} of ${n} ${walletId} will be initialized after all participants have joined`; } componentWillUnmount() { const { setTemporarySecrets, walletId } = this.props; // clear the temporary secrets setTemporarySecrets(walletId, { type: 'clear' }); } // depends on react router complete() { const { history } = this.props; history.replace(`/${BASE_PATH}`); } render() { const { joinKey, token, cosignerId } = this.props; return ( <BoxGrid rowClass="text-center" colClass="flex-column justify-content-center m-auto" colcount={2} > <div> <Header type="h2">Multi Party Wallet</Header> {cosignerId && ( <Label className="d-flex align-items-start" text="Cosigner ID"> <Text style={style.secretText} type="p"> {cosignerId} </Text> </Label> )} {joinKey && ( <Label className="d-flex align-items-start" text="Join Key"> <Text style={style.secretText} type="p"> {joinKey} </Text> </Label> )} {token && ( <Label className="d-flex align-items-start" text="Cosigner Token"> <Text style={style.secretText} type="p"> {token} </Text> </Label> )} </div> <BoxGrid colcount={1} rowClass="d-inline"> <div className="pt-5" /> <Text type="p">{this.headerCopy()}</Text> {/* only render relevent copy */} {joinKey && ( <Text type="p"> Privately share your Join Key with participants. </Text> )} {token && ( <Text type="p"> Your cosigner token will be used to approve multi party proposals. Please be sure to record this information. </Text> )} <Text type="p">Are you sure you recorded this information?</Text> <Button onClick={() => this.complete()}>Complete</Button> </BoxGrid> </BoxGrid> ); } }
JavaScript
class DownloadContainer { constructor(widget) { const { file: { url: provenFileUrl, filename: filename } } = widget.configuration; this.element = null; this.request = null; this.widget = widget; this.url = provenFileUrl || null; /** * A mapper for the request object to make the last more flexible and reusable * @type {{downloadingFinished: string, downloadingStarted: string, downloadingProgress: string}} */ this.observerMapper = { 'downloadingProgress': 'downloadingProgressObserver', 'downloadingStarted': 'downloadingStartedObserver', 'downloadingFinished': 'downloadingFinishedObserver', 'downloadingFailed': 'downloadingFailedObserver' }; if (this.url !== null) { let { proxy: { url: proxyUrl, enabled: proxyEnabled } } = widget.configuration; /** * If the proxy is listed then change the download URL * @type {string} */ const downloadUrl = utils.getUrlToDownload(this.url, proxyUrl, proxyEnabled); this.request = utils.getHttpRequest(downloadUrl, this.widget, this.observerMapper, filename, this.url); } this.init(); } /** * Create and initialize all container elements */ init() { this.element = VirtualDOMService.createElement('div', { classes: utils.extractClasses(styles, styleCodes.download.code) }); this.initializeObservers(); } /** * Initialize the observers */ initializeObservers() { this.widget.observers.downloadModeInitiatedObserver.subscribe(() => { this.downloadModeInitiated(); }); this.widget.observers.downloadingCanceledObserver.subscribe(() => { this.downloadingCanceled(); }); this.widget.observers.downloadingStartedObserver.subscribe(() => { this.element.hide(); }); this.widget.observers.errorCaughtObserver.subscribe(() => { this.downloadingCanceled(); }); this.widget.observers.uploadModeInitiatedObserver.subscribe(() => { this.element.hide(); }); this.widget.observers.widgetResetObserver.subscribe(() => { this.downloadingCanceled(); }); } download() { if (this.request !== null) { this.request.start(); } } downloadFile() { this.download(this.url); } downloadModeInitiated() { this.downloadFile(); } /** * It the user close the download process, abort the request */ downloadingCanceled() { if (this.request !== null) { this.request.abort(); } } get() { return this.element; } }
JavaScript
class BaseGameObject { /** * toString override for easier debugging * @returns {string} human readable string in the format `GameObjectName #id` */ toString() { return `${this.gameObjectName} #${this.id}`; } }
JavaScript
class RandomUnitTable { /** * */ constructor() { /** @member {number} */ this.id = 0; /** @member {string} */ this.name = ''; /** @member {number} */ this.positions = 0; /** @member {Int32Array} */ this.columnTypes = new Int32Array(1); /** @member {Array<RandomUnit>} */ this.units = []; } /** * @param {BinaryStream} stream */ load(stream) { this.id = stream.readInt32(); this.name = stream.readUntilNull(); this.positions = stream.readInt32(); this.columnTypes = stream.readInt32Array(this.positions); for (let i = 0, l = stream.readUint32(); i < l; i++) { let unit = new RandomUnit(); unit.load(stream, this.positions); this.units[i] = unit; } } /** * @param {BinaryStream} stream */ save(stream) { stream.writeInt32(this.id); stream.write(`${this.name}\0`); stream.writeInt32(this.positions); stream.writeInt32Array(this.columnTypes); stream.writeUint32(this.units.length); for (let unit of this.units) { unit.save(stream); } } /** * @return {number} */ getByteLength() { return 13 + this.name.length + this.columnTypes.byteLength + (this.units.length * (4 + 4 * this.positions)); } }