language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Calculations { constructor (pricing, done) { this.pricing = pricing; this.items = pricing.items; this.price = { now: {}, next: {}, base: { plan: {}, addons: {} }, addons: {}, // DEPRECATED currency: { code: this.pricing.currencyCode, symbol: this.pricing.currencySymbol }, taxes: [] }; this.subtotal(); this.tax(function () { this.total(); this.giftCard(); each(this.price.base.plan, decimalizeMember, this.price.base.plan); each(this.price.base.addons, decimalizeMember, this.price.base.addons); each(this.price.addons, decimalizeMember, this.price.addons); // DEPRECATED each(this.price.now, decimalizeMember, this.price.now); each(this.price.next, decimalizeMember, this.price.next); done(this.price); }); } /** * Calculates subtotal * * @private */ subtotal () { this.price.now.subtotal = 0; this.price.next.subtotal = 0; this.plan(); this.price.now.subtotal += this.price.now.plan; this.price.next.subtotal += this.price.next.plan; this.addons(); this.price.now.subtotal += this.price.now.addons; this.price.next.subtotal += this.price.next.addons; this.setupFee(); this.discount(); this.price.now.subtotal -= this.price.now.discount; this.price.next.subtotal -= this.price.next.discount; this.price.now.subtotal += this.price.now.setup_fee; } /** * Calculates total * * @private */ total () { this.price.now.total = this.price.now.subtotal + this.price.now.tax; this.price.next.total = this.price.next.subtotal + this.price.next.tax; } /** * Calculates tax * * tax info precedence: `tax` > `shipping_address` > `address` * * @param {Function} done * @private */ tax (done) { this.price.now.tax = 0; this.price.next.tax = 0; // If tax amount has been specified, simply apply it if (this.items.tax && this.items.tax.amount) { this.price.now.tax = taxCeil(this.items.tax.amount.now); this.price.next.tax = taxCeil(this.items.tax.amount.next); return done.call(this); } // Tax the shipping address if present, or const taxAddress = this.items.shipping_address || this.items.address; const taxInfo = Object.assign({}, taxAddress, this.items.tax); if (!isEmpty(taxInfo)) { this.pricing.recurly.tax(taxInfo, (err, taxes) => { if (err) { this.pricing.emit('error', err); } else { this.price.taxes = []; each(taxes, tax => { if (this.pricing.taxExempt) return; this.price.now.tax += parseFloat((this.price.now.subtotal * tax.rate).toFixed(6)); this.price.next.tax += parseFloat((this.price.next.subtotal * tax.rate).toFixed(6)); // If we have taxes, we may want to display the rate... // push the taxes so we know what they are... this.price.taxes.push(tax); }); // tax estimation prefers partial cents to always round up this.price.now.tax = taxCeil(this.price.now.tax); this.price.next.tax = taxCeil(this.price.next.tax); } done.call(this); }); } else { done.call(this); } } /** * Computes plan prices * * @private */ plan () { this.price.now.plan = 0; this.price.next.plan = 0; if (!this.items.plan) return; const base = this.items.plan.price[this.items.currency]; this.price.base.plan.unit = base.unit_amount; this.price.base.plan.setup_fee = base.setup_fee; const amount = this.planPrice().amount; this.price.now.plan = amount; this.price.next.plan = amount; if (this.isTrial()) this.price.now.plan = 0; } /** * Computes addon prices and applies addons to the subtotal * * @private */ addons () { this.price.now.addons = 0; this.price.next.addons = 0; if (!this.items.plan) return; if (!Array.isArray(this.items.plan.addons)) return; this.items.plan.addons.forEach(addon => { // exclude usage addons if (addon.add_on_type !== 'fixed') return; let price = addon.price[this.items.currency].unit_amount; this.price.base.addons[addon.code] = price; this.price.addons[addon.code] = price; // DEPRECATED const selected = find(this.items.addons, { code: addon.code }); if (selected) { price = price * selected.quantity; if (!this.isTrial()) this.price.now.addons += price; this.price.next.addons += price; } }); } /** * Applies coupon discount to the subtotal * * @private */ discount () { var coupon = this.items.coupon; this.price.now.discount = 0; this.price.next.discount = 0; if (!coupon) return; if (coupon.discount.rate) { var discountNow = parseFloat((this.price.now.subtotal * coupon.discount.rate).toFixed(6)); var discountNext = parseFloat((this.price.next.subtotal * coupon.discount.rate).toFixed(6)); this.price.now.discount = Math.round(discountNow * 100) / 100; this.price.next.discount = Math.round(discountNext * 100) / 100; } else if (coupon.discount.type === 'free_trial') { // Handled in separate trial logic } else { const discountableNow = this.price.now.subtotal + this.price.now.setup_fee; const discountableNext = this.price.next.subtotal; this.price.now.discount = Math.min(discountableNow, coupon.discount.amount[this.items.currency]); this.price.next.discount = Math.min(discountableNext, coupon.discount.amount[this.items.currency]); } if (coupon.single_use && this.price.now.discount > 0) this.price.next.discount = 0; } /** * Applies plan setup fee to the subtotal * * @private */ setupFee () { this.price.now.setup_fee = this.planPrice().setup_fee; this.price.next.setup_fee = 0; } /** * Subtracts any giftcard value from the total * * @private */ giftCard () { if (this.pricing.items.gift_card) { let nowTotal = this.price.now.total; let nextTotal = this.price.next.total; let giftcardNow = useGiftcard(nowTotal,this.pricing.items.gift_card.unit_amount); let giftcardNext = useGiftcard(nextTotal,giftcardNow.remains); this.price.now.gift_card = giftcardNow.used; this.price.next.gift_card = giftcardNext.used; this.price.now.total = nowTotal - giftcardNow.used; this.price.next.total = nextTotal - giftcardNext.used; } function useGiftcard (price,giftcardValue){ let used = 0; let remains = 0; if(giftcardValue > price){ used = price; remains = giftcardValue - price; } else { used = giftcardValue; } return { used, remains }; } } /** * Get the price structure of the current plan on the current currency * * @return {Object} { amount, setup_fee } * @private */ planPrice () { const plan = this.items.plan; if (!plan) return { amount: 0, setup_fee: 0 }; let price = plan.price[this.items.currency]; price.amount = price.unit_amount * (plan.quantity || 1); return price; } isTrial () { const coupon = this.items.coupon; if (coupon && coupon.discount.type === 'free_trial') return true; return this.items.plan.trial; } }
JavaScript
class AssertionError extends bs.CustomError { constructor(message=null, ...params) { super("AssertionError", message, ...params); } }
JavaScript
class KeyError extends CustomError { constructor(message=null, ...params) { super("KeyError", message, ...params); } }
JavaScript
class ValueError extends bs.CustomError { constructor(message=null, ...params) { super("ValueError", message, ...params); } }
JavaScript
class Dictionary { constructor(init_seq) { if (bs.is_null_or_undefined(init_seq) === false){ if (bs.type(init_seq) === bs.TYPE_ARRAY) { // If a proper list is provided, use it to initialise the dictionary for (let i = 0; i < init_seq.length; i++) { let key_i, value_i; [key_i, value_i] = init_seq[i]; if (bs.not_in(bs.type(key_i), [bs.TYPE_STRING, bs.TYPE_STRING_OBJECT])) { TypeError(`Element key [${i}] = ${key_i} should be a string but is of type ${type(key_i)}`); } this[key_i] = value_i; } } else if (!bs.is_null_or_undefined(Object.keys(init_seq))) { let keys = Object.keys(init_seq); for (let i = 0; i < keys.length; i++) { this[keys[i]] = init_seq[keys[i]]; } } else { throw new bs.ValueError(`the given argument of type '${init_seq}' cannot be converted to dictionary.`); } } } clear() { let all_keys = this.keys(); for (let i = 0; i < all_keys.length; i++) { delete this[all_keys[i]]; } } del(key) { if (bs.in(key, this.keys())) { delete this[key]; } } keys() { return Object.keys(this); } get(key, _default=null) { let val = this[key]; if (val === undefined) { return _default; } else { return val; } } }
JavaScript
class Value { /** * Convert a native javascript primative value to a Value * @param {any} value - The value to convert */ static fromPrimativeNative(value) { if ( !value ) { if ( value === undefined ) return undef; if ( value === null ) return nil; if ( value === false ) return fals; if ( value === '' ) return emptyString; } if ( value === true ) return tru; if ( typeof value === 'number' ) { if ( value === 0 ) { return 1 / value > 0 ? zero : negzero; } if ( value | 0 === value ) { let snv = smallIntValues[value + 1]; if ( snv ) return snv; } return new NumberValue(value); } if ( typeof value === 'string' ) return new StringValue(value); if ( typeof value === 'boolean' ) return tru; } static hasBookmark(native) { return bookmarks.has(native); } static getBookmark(native) { return bookmarks.get(native); } /** * Convert a native javascript value to a Value * * @param {any} value - The value to convert * @param {Realm} realm - The realm of the new value. */ static fromNative(value, realm) { if ( value instanceof Value ) return value; let prim = Value.fromPrimativeNative(value); if ( prim ) return prim; if ( value instanceof Error ) { if ( !realm ) throw new Error('We needed a realm, but we didnt have one. We were sad :('); if ( value instanceof TypeError ) return realm.TypeError.makeFrom(value); if ( value instanceof ReferenceError ) return realm.ReferenceError.makeFrom(value); if ( value instanceof SyntaxError ) return realm.SyntaxError.makeFrom(value); else return realm.Error.makeFrom(value); } if ( Value.hasBookmark(value) ) { return Value.getBookmark(value); } throw new TypeError('Tried to load an unsafe native value into the interperter:' + typeof value + ' / ' + value); //TODO: Is this cache dangerous? if ( !cache.has(value) ) { let nue = new BridgeValue(realm, value); cache.set(value, nue); return nue; } return cache.get(value); } /** * Holds a value representing `undefined` * * @returns {UndefinedValue} */ static get undef() { return undef; } /** * Holds a value representing `null` * * @returns {NullValue} */ static get null() { return nil; } /** * Holds a value representing `true` * * @returns {BooleanValue} true */ static get true() { return tru; } /** * Holds a value representing `fasle` * * @returns {BooleanValue} false */ static get false() { return fals; } /** * Holds a value representing `NaN` * * @returns {NumberValue} NaN */ static get nan() { return nan; } /** * Holds a value representing `''` * * @returns {StringValue} '' */ static get emptyString() { return emptyString; } /** * Holds a value representing `0` * * @returns {NumberValue} 0 */ static get zero() { return zero; } /** * Holds a value representing `1` * * @returns {NumberValue} 1 */ static get one() { return one; } static createNativeBookmark(v, realm) { var out; let thiz = this; if ( typeof v.call === 'function' ) { switch ( realm ? realm.options.bookmarkInvocationMode : '' ) { case 'loop': out = function Bookmark() { let Evaluator = require('./Evaluator'); let cthis = realm.makeForForeignObject(this); let c = v.call(cthis, Array.from(arguments).map((v) => realm.makeForForeignObject(v)), realm.globalScope); let evalu = new Evaluator(realm, null, realm.globalScope); evalu.pushFrame({type: 'program', generator: c, scope: realm.globalScope}); let gen = evalu.generator(); let result; do { result = gen.next(); } while ( !result.done ); return result.value.toNative(); }; break; default: out = function Bookmark() { throw new Error('Atempted to invoke bookmark for ' + v.debugString); }; } } else { out = {}; } Object.defineProperties(out, { toString: {value: function() { return v.debugString; }, writable: true}, inspect: {value: function() { return v.debugString; }, writable: true}, esperValue: {get: function() { return v; } }, }); bookmarks.set(out, v); return out; } constructor() { this.serial = serial++; } /** * Converts this value to a native javascript value. * * @abstract * @returns {*} */ toNative() { throw new Error('Unimplemented: Value#toNative'); } /** * Deep copy this value to a native javascript value. * * @returns {*} */ toJS() { return this.toNative(); } /** * A string representation of this Value suitable for display when * debugging. * @abstract * @returns {string} */ get debugString() { let native = this.toNative(); return native ? native.toString() : '???'; } inspect() { return this.debugString; } /** * Indexes the value to get the value of a property. * i.e. `value[name]` * @param {String} name * @param {Realm} realm * @abstract * @returns {Value} */ *get(name, realm) { let err = "Can't access get " + name + ' of that type.'; return yield CompletionRecord.typeError(err); } getImmediate(name) { return GenDash.syncGenHelper(this.get(name)); } /** * Computes the javascript expression `!value` * @returns {Value} */ *not() { return !this.truthy ? Value.true : Value.false; } /** * Computes the javascript expression `+value` * @returns {Value} */ *unaryPlus() { return Value.fromNative(+(yield * this.toNumberValue()).toNative()); } /** * Computes the javascript expression `-value` * @returns {Value} */ *unaryMinus() { return Value.fromNative(-(yield * this.toNumberValue()).toNative()); } /** * Computes the javascript expression `typeof value` * @returns {Value} */ *typeOf() { return Value.fromNative(this.jsTypeName); } /** * Computes the javascript expression `!(value == other)` * @param {Value} other - The other value * @param {Realm} realm - The realm to use when creating resuls. * @returns {Value} */ *notEquals(other, realm) { var result = yield * this.doubleEquals(other, realm); return yield * result.not(); } /** * Computes the javascript expression `!(value === other)` * @param {Value} other - The other value * @param {Realm} realm - The realm to use when creating resuls. * @returns {Value} */ *doubleNotEquals(other, realm) { var result = yield * this.tripleEquals(other, realm); return yield * result.not(); } /** * Computes the javascript expression `value === other` * @param {Value} other - The other value * @param {Realm} realm - The realm to use when creating resuls. * @returns {Value} */ *tripleEquals(other, realm) { return other === this ? Value.true : Value.false; } getPrototypeProperty() { let p = this.properties['prototype']; if ( !p ) return; return p.value; } *makeThisForNew(realm) { var nue = new ObjectValue(realm); var p = this.getPrototypeProperty(); if ( p ) nue.setPrototype(p); return nue; } /** * Computes the javascript expression `value > other` * @param {Value} other - The other value * @returns {Value} */ *gt(other) { return Value.fromNative((yield * this.toNumberNative()) > (yield * other.toNumberNative())); } /** * Computes the javascript expression `value < other` * @param {Value} other - The other value * @returns {Value} */ *lt(other) { return Value.fromNative((yield * this.toNumberNative()) < (yield * other.toNumberNative())); } /** * Computes the javascript expression `value >= other` * @param {Value} other - The other value * @returns {Value} */ *gte(other) { return Value.fromNative((yield * this.toNumberNative()) >= (yield * other.toNumberNative())); } /** * Computes the javascript expression `value <= other` * @param {Value} other - The other value * @returns {Value} */ *lte(other) { return Value.fromNative((yield * this.toNumberNative()) <= (yield * other.toNumberNative())); } /** * Computes the javascript expression `value - other` * @param {Value} other - The other value * @returns {Value} */ *subtract(other) { return Value.fromNative((yield * this.toNumberNative()) - (yield * other.toNumberNative())); } /** * Computes the javascript expression `value / other` * @param {Value} other - The other value * @returns {Value} */ *divide(other) { return Value.fromNative((yield * this.toNumberNative()) / (yield * other.toNumberNative())); } /** * Computes the javascript expression `value * other` * @param {Value} other - The other value * @returns {Value} */ *multiply(other) { return Value.fromNative((yield * this.toNumberNative()) * (yield * other.toNumberNative())); } /** * Computes the javascript expression `value % other` * @param {Value} other - The other value * @returns {Value} */ *mod(other) { return Value.fromNative((yield * this.toNumberNative()) % (yield * other.toNumberNative())); } *bitNot() { return Value.fromNative(~(yield * this.toNumberNative())); } *shiftLeft(other) { return Value.fromNative((yield * this.toNumberNative()) << (yield * other.toNumberNative())); } *shiftRight(other) { return Value.fromNative((yield * this.toNumberNative()) >> (yield * other.toNumberNative())); } *shiftRightZF(other) { return Value.fromNative((yield * this.toNumberNative()) >>> (yield * other.toNumberNative())); } *bitAnd(other) { return Value.fromNative((yield * this.toNumberNative()) & (yield * other.toNumberNative())); } *bitOr(other) { return Value.fromNative((yield * this.toNumberNative()) | (yield * other.toNumberNative())); } *bitXor(other) { return Value.fromNative((yield * this.toNumberNative()) ^ (yield * other.toNumberNative())); } /** * Computes the `value` raised to the `other` power (`value ** other`) * @param {Value} other - The other value * @returns {Value} */ *pow(other) { return Value.fromNative(Math.pow(yield * this.toNumberNative(),yield * other.toNumberNative())); } *inOperator(other) { let err = "Cannot use 'in' operator to search for 'thing' in 'thing'"; return new CompletionRecord(CompletionRecord.THROW, { type: "TypeError", message: err }); } /** * Is the value is truthy, i.e. `!!value` * * @abstract * @type {boolean} */ get truthy() { throw new Error('Unimplemented: Value#truthy'); } get jsTypeName() { throw new Error('Unimplemented: Value#jsTypeName'); } get specTypeName() { return this.jsTypeName; } get isCallable() { return ( typeof this.call === 'function' ); } *toNumberValue() { throw new Error('Unimplemented: Value#toNumberValue'); } *toStringValue() { throw new Error('Unimplemented: Value#StringValue'); } *toStringNative() { return (yield * this.toStringValue()).native; } *toBooleanValue() { return this.truthy ? tru : fals; } *toUIntNative() { let nv = yield * this.toNumberValue(); return Math.floor(nv.native); } *toIntNative() { let nv = yield * this.toNumberValue(); return Math.floor(nv.native); } *toNumberNative() { let nv = yield * this.toNumberValue(); return nv.native; } *toPrimitiveValue(preferedType) { throw new Error('Unimplemented: Value#toPrimitiveValue'); } *toPrimitiveNative(preferedType) { return (yield * this.toPrimitiveValue(preferedType)).native; } /** * Quickly make a generator for this value */ *fastGen() { return this; } /** * Garentee this value can never change * * @abstract * @returns bool */ makeImmutable() { throw new Error('Unimplemented: Value#makeImmutable'); } }
JavaScript
class OutputWindow extends Component { OUTPUT_COLUMNS = [ { Header: 'Output Name', accessor: 'name' }, { Header: 'Value', accessor: 'value' }, { Header: 'Units', accessor: 'units' }, ]; /** @override */ render() { return ( <div> <Tabs> <TabList> <Tab>Output</Tab> { this.props.outputGraphs.map((og) => { return <Tab>{og.name}</Tab> }) } </TabList> <TabPanel> <ReactTable data={this.props.outputs} columns={this.OUTPUT_COLUMNS} defaultPageSize={10}/> </TabPanel> { this.props.outputGraphs.map((og) => { return ( <TabPanel> <Plot data={[og]} layout={{title:og.name}}/> </TabPanel> ); }) } </Tabs> </div> ); } }
JavaScript
class StaticSymbol { constructor(filePath, name, members) { this.filePath = filePath; this.name = name; this.members = members; } assertNoMembers() { if (this.members.length) { throw new Error(`Illegal state: symbol without members expected, but got ${JSON.stringify(this)}.`); } } }
JavaScript
class StaticSymbolCache { constructor() { this.cache = new Map(); } get(declarationFile, name, members) { members = members || []; const memberSuffix = members.length ? `.${members.join('.')}` : ''; const key = `"${declarationFile}".${name}${memberSuffix}`; let result = this.cache.get(key); if (!result) { result = new StaticSymbol(declarationFile, name, members); this.cache.set(key, result); } return result; } }
JavaScript
class Button extends Component { constructor(props) { super(props); let config = { ...props }; this.state = { options: { type: config.type || "raised", size: config.size || " ", label: config.label || " ", disabled: config.disabled || false, color: config.color || " ", textColor: config.textColor || "white-text", wavesEffect: config.wavesEffect || true, wavesType: config.wavesType || " ", wavesColor: config.wavesColor || " ", pulse: config.pulse || false, href: config.href, dataTarget: config.dataTarget || " ", trigger: config.trigger || " ", onClick: config.onClick || (() => {})() } }; this.availableWavesColors = [ "waves-light", "waves-red", "waves-yellow", "waves-orange", "waves-purple", "waves-green", "waves-teal" ]; this.availableSizes = ["normal", "small", "large"]; this.availableTypes = ["raised", "floating", "flat"]; } _wavesColorIsValid = color => { if (this.availableWavesColors.includes(color)) { return true; } else if (!color || color == null || color == undefined || color === " ") { return false; } else { console.warn("ReactMaterial Warning: Button attr - wavesColor is invalid"); return false; } }; _sizeIsValid = size => { if (this.availableSizes.includes(size)) { return true; } else if (!size || size == null || size == undefined || size === " ") { return false; } else { console.warn( "ReactMaterial Error: Button attr - size is empty or invalid \n Component will re" + "nder abnormal ui." ); return false; } }; _typeIsInvalid = type => { if (this.availableTypes.includes(type)) { return true; } else if (!type || type == null || type == undefined || type === " ") { return false; } else { console.warn( "ReactMaterial Error: Button attr - type is empty or invalid \n Component will re" + "nder abnormal ui." ); return false; } }; render() { let btnType; if (this._typeIsInvalid(this.state.options.type)) { if (this.state.options.type === "raised") { btnType = "btn"; } else if (this.state.options.type === "floating") { btnType = "btn-floating"; } else if (this.state.options.type === "flat") { btnType = "btn-flat"; } } let btnSize; if (this._sizeIsValid(this.state.options.size)) { if (this.state.options.size === "normal") { btnSize = ""; } else if (this.state.options.size === "large") { btnSize = "btn-large"; } else if (this.state.options.size === "small") { btnSize = "btn-small"; } } return ( <a className={` ${this.state.options.wavesEffect ? "waves-effect" : ""} ${ this._wavesColorIsValid(this.state.options.wavesColor) ? this.state.options.wavesColor : "" } ${btnType} ${btnSize ? btnSize : ""} ${this.state.options.color} ${this.state.options.textColor} ${this.state.options.disabled ? "disabled" : ""} ${this.state.options.type === "floating" && this.state.options.pulse ? "pulse" : "" } ${this.state.options.trigger ? this.state.options.trigger : ""}` } href={`${ this.state.options.href ? this.state.options.href : "javascript:void(0)" }`} onClick={this.state.options.onClick} data-target={ this.state.options.dataTarget ? this.state.options.dataTarget : "" }> {this.state.options.type === "floating" ? "" : this.state.options.label} {this.props.children} </a> ); } }
JavaScript
class FavoritesSection extends Component { _renderTiles() { console.log('lol'); return ( <List> <ListItem leftColumn={<img src="/public/img/icon/codepen-paper-icon.svg" />} heading="Material Design Login Form" subHeading={<span>Created by <a>Andy Tran</a></span>} /> <ListItem leftColumn={<img src="/public/img/icon/codepen-paper-icon.svg" />} rightColumn={<div>R</div>} > Item 1 </ListItem> <ListItem>Item 2</ListItem> <ListItem>Item 3</ListItem> </List> ) } render() { const { className, label } = this.props; const classes = classNames('favorites-section', className); return ( <section className={classes}> <SectionHeader label="Favorites" /> {this._renderTiles()} </section> ); } }
JavaScript
class FridaHelper { /** * @field * @static */ static SPAWN = 0x1; /** * @field * @static */ static ATTACH_BY_NAME = 0x2; /** * @field * @static */ static ATTACH_BY_PID = 0x3; /* static async exec( pDevice, pScript, pType, pApp){ let FRIDA = require('frida'); var hookRoutine = co.wrap(function *() { let session = null, pid=null, applications=null; const device = yield FRIDA.getDevice(pDevice.getUID()); switch(pType){ case FridaHelper.SPAWN: pid = yield device.spawn([pExtra]); session = yield device.attach(pid); Logger.info('spawned:', pid); break; case FridaHelper.ATTACH_BY_PID: applications = yield device.enumerateApplications(); for(let i=0; i<applications.length; i++){ if(applications[i].identifier == pExtra) pid = applications[i].pid; } if(pid > -1) { session = yield device.attach(pid); Logger.info('attached to '+pExtra+" (pid="+pid+")"); }else{ throw new Error('Failed to attach to application ('+pExtra+' not running).'); } break; case FridaHelper.ATTACH_BY_NAME: applications = yield device.enumerateApplications(); if(applications.length == 1 && applications[0].name == "Gadget") { session = yield device.attach(applications[0].pid); Logger.info('attached to Gadget:', pid); }else Logger.error('Failed to attach to Gadget.'); break; case FridaHelper.ATTACH_BY_PID: session = yield device.attach(pid); Logger.info('spawned:', pid); break; default: Logger.error('Failed to attach/spawn'); return; break; } const script = yield session.createScript(pScript); // For frida-node > 11.0.2 script.message.connect(message => { PROBE_SESSION.push(message);//{ msg:message, d:data }); //console.log('[*] Message:', message); }); yield script.load(); PROBE_SESSION.fridaScript = script; console.log('script loaded', script); yield device.resume(pid); }); hookRoutine() .catch(error => { console.log(error); console.log('error:', error.message); }); }*/ /** * * Return an object formatted like that : * { * version: "v12.2.21", * major: 12, * minor: 2, * patch: 21 * } * @param {*} pFridaPath */ static getLocalFridaVersion(pFridaPath){ let v = _ps_.execSync(pFridaPath + ' --version'); let ver = v.slice(0 , v.lastIndexOf( require('os').EOL )).toString(); v = ver.split('.'); return { version: ver, major: v[0], minor: v[1], patch: v[2] }; } /** * To download a remote file into temporary folder * * TODO : move to utils * * @param {*} pRemotepPath * @param {*} pLocalName */ static async download( pRemotepPath, pLocalName){ let tmp = _path_.join( DexcaliburWorkspace.getInstance().getTempFolderLocation(), pLocalName ); Logger.info(`[FRIDA HELPER] Downloading ${pRemotepPath} ...`); if(_fs_.existsSync(tmp) == true){ _fs_.unlinkSync(tmp); } // download file await pipeline( _got_.stream(pRemotepPath), _fs_.createWriteStream( tmp, { flags: 'w+', mode: 0o777, encoding: 'binary' } ) ); Logger.info(`[FRIDA HELPER] ${pRemotepPath} downloaded. `); if(_fs_.existsSync(tmp) == true){ return tmp; }else{ return null; } } static async startServer( pDevice, pOptions = { path:null, privileged:true }){ if(pDevice == null) throw new Error("[FRIDA HELPER] Unknow device. Device not connected not enrolled ?"); if( (pDevice.getFridaServerPath() == null) && (pOptions.path == null)) throw new Error("[FRIDA HELPER] Path of Frida server is unknow"); let frida = pDevice.getFridaServerPath(); let res = null; //console.log(pOptions); if(pOptions.path != null && pOptions.path != '') frida = pOptions.path; if(pDevice.getDefaultBridge().isNetworkTransport()){ frida += " -l 0.0.0.0" } //if(pOptions.listen != null) if(pOptions.privileged) res = await pDevice.privilegedExecSync(frida, {detached:true}); else res = pDevice.execSync(frida); return res; } /** * * @param {*} pDevice * @method */ static async getDevice(pDevice){ if(_frida_ == null){ _frida_ = require('frida'); } let dev=null, bridge = pDevice.getDefaultBridge(); if(bridge==null) return null; dev = await _frida_.getDevice(bridge.deviceID).catch(async function(err){ if(bridge.isNetworkTransport()){ return await _frida_.getDeviceManager().addRemoteDevice(bridge.deviceID); }else{ return null; } }); if(dev==null && bridge.isNetworkTransport()){ dev = await _frida_.getDeviceManager().addRemoteDevice(bridge.deviceID); } return dev; } static async getServerStatus( pDevice, pOptions = { nofrida:false }){ if(_frida_ == null){ _frida_ = require('frida'); } let flag = false, dev=null; try{ dev = await FridaHelper.getDevice(pDevice); if(dev==null) return false; dev = await dev.enumerateProcesses(); flag = true; }catch(err){ Logger.debug(err.message); flag = false; } return flag; } /** * To download and push Frida server binary into the device * * Options supported: * - frida * - version * - url * - remote_path * - local_path * * @param {Device} pDevice target device * @param {Object} pOptions install options * @method * @static */ static async installServer( pDevice, pOptions = {}){ let ver, xzpath, path, arch, tmp; // retrieve frida version ver = FridaHelper.getLocalFridaVersion( pOptions.path != null? pOptions.path : HOST_FRIDA_BIN_NAME); // get device a architecture arch = pDevice.getProfile().getSystemProfile().getArchitecture(); if(pOptions.remoteURL != null){ tmp = pOptions.remoteURL; }else{ tmp = `https://github.com/frida/frida/releases/download/${ver.version}/frida-server-${ver.version}-android-${arch}.xz` } // download sever xzpath = await FridaHelper.download( tmp, 'frida_server', pOptions); Logger.info('[FRIDA HELPER] Server download. Path: ',xzpath); path = xzpath.substr(0,xzpath.length-3); Logger.info('[FRIDA HELPER] Extracting server from archive ...'); // un-xz await pipeline( _fs_.createReadStream( xzpath), new _xz_.Decompressor(), _fs_.createWriteStream( path, { flags: 'w+', mode: 0o777, encoding: 'binary' } ) ); if(pOptions.randomName == true){ tmp = Util.randomString(8); }else{ tmp = REMOT_FRIDA_DEFAULT_NAME; } // push binary if(pOptions.devicePath != null ){ pDevice.pushBinary( path, pOptions.devicePath+tmp); pDevice.setFridaServer( pOptions.devicePath+tmp); }else{ pDevice.pushBinary( path, REMOTE_FRIDA_PATH+tmp); pDevice.setFridaServer( REMOTE_FRIDA_PATH+tmp); } // remove downloaded files _fs_.unlinkSync(xzpath); _fs_.unlinkSync(path); return true; } }
JavaScript
class ManageParticipantList extends React.Component { constructor(props){ super(props); //this.history = useHistory(); this.state = { publishingModal: false, deleteModal: false, rows: {}, alerts: {}, currentDataObject: {}, lastFetch: Date.now(), loading: true, advancedFilter: null, selectedId: 0, content: '' }; this.fetchData = this.fetchData.bind(this); this.rowActionsFormatter = this.rowActionsFormatter.bind(this); this.DeleteParticipant = this.DeleteParticipant.bind(this); this.showHandler = this.showHandler.bind(this); this.contentInfo = this.contentInfo.bind(this); this.approve = this.approve.bind(this); this.disapprove = this.disapprove.bind(this); } async componentDidMount() { if (await isAdmin() === false) { return this.props.history.push("/login"); } this.fetchData(); } /** * Fetches Table Data * Sets the state with the fetched data for use in WeferralTableBase's props.row */ fetchData() { let self = this; let url = `${port}/api/v1/participants`; Fetcher(url).then(function (response) { if (!response.error) { self.setState({rows: response}); } self.setState({loading: false}); }); } DeleteParticipant(id, value){ let self = this; if(value === 'suspend'){ Fetcher(`${port}/api/v1/participant/suspend/${id}`).then(function (response) { if(!response.error){ self.setState({success: true, response: response, alerts: {color:'info', message: 'Successfully suspended'}}); }else{ let msg = 'Cannot suspend participant.' self.setState({ alerts: { color: 'danger', message: `${response.error} : ${msg}` } }); } }) }else{ Fetcher(`${port}/api/v1/participant/${id}`, 'DELETE').then(function (response) { if(!response.error){ self.setState({success: true, response: response, alerts: {color:'info', message: response.message}}); }else{ let msg = 'Cannot delete a participant that has records attached to it.' self.setState({ alerts: { color: 'danger', message: `${response.error} : ${response.message}` } }); } }) } } contentInfo(closeToast) { let self = this; let id = self.state.selectedId; let value = self.state.content; return( <Media> <Media middle left className="mr-3"> <i className="fa fa-fw fa-2x fa-info"></i> </Media> <Media body> <Media heading tag="h6"> Alert! </Media> <p> Are you sure you want to do this. </p> <div className="d-flex mt-2"> {value === 'suspend' && <Button color="primary" onClick={() => { self.DeleteParticipant(id, value) }} > Suspend </Button>} {value === 'delete' && <Button color="danger" onClick={() => { self.DeleteParticipant(id, value) }} > Delete </Button> } <Button color="link" onClick={() => { closeToast }} className="ml-2 text-primary"> No </Button> </div> </Media> </Media> ) } async showHandler(id, value){ let self = this; await self.setState({selectedId: id, content: value}); toast.error(self.contentInfo()); } approve(id){ let self = this; Fetcher(`${port}/api/v1/participant/approve/${id}`).then(function (response) { if(!response.error){ self.setState({success: true, response: response, alerts: {color:'info', message: 'Successfully approved'}}); }else{ let msg = 'Cannot approve participant.' self.setState({ alerts: { color: 'danger', message: `${response.error} : ${msg}` } }); } }) } disapprove(id){ let self = this; Fetcher(`${port}/api/v1/participant/disapprove/${id}`).then(function (response) { if(!response.error){ self.setState({success: true, response: response, alerts: {color:'info', message: 'Successfully disapproved'}}); }else{ let msg = 'Cannot disapprove participant.' self.setState({ alerts: { color: 'danger', message: `${response.error} : ${msg}` } }); } }) } /** * Cell formatters * Formats each cell data by passing the function as the dataFormat prop in TableHeaderColumn */ nameFormatter(cell, row){ return ( <Link to={`/manage-participant/${row.id}`}>{cell}</Link> ); } emailFormatter(cell){ return ( cell ); } idFormatter(cell){ return ( cell ); } statusFormatter(cell){ let pqProps; switch (cell) { case 'active': pqProps = { color: 'success', text: 'Active' } break; case 'suspended': pqProps = { color: 'warning', text: 'Suspended' } break; default: pqProps = { color: 'secondary', text: 'Invited' } } return (<Badge color={pqProps.color}>{ pqProps.text}</Badge> ); // return ( cell ? 'Published' : 'Unpublished' ); } createdFormatter(cell){ return (DateFormat(cell, {time: true})); } rowActionsFormatter(cell, row){ let self = this; return( <UncontrolledButtonDropdown> <DropdownToggle color="link" className={` text-decoration-none `}> <i className="fa fa-gear"></i><i className="fa fa-angle-down ml-2"></i> </DropdownToggle> <DropdownMenu right> <DropdownItem tag={Link} to={`/edit-participant/${row.id}`}> <i className="fa fa-fw fa-edit mr-2"></i> Edit </DropdownItem> <DropdownItem onClick={() => { this.showHandler(row.id, 'suspend') }}> <i className="fa fa-fw fa-archive mr-2"></i> Suspend </DropdownItem> {row.status === 'active' ? <DropdownItem onClick={() => { this.disapprove(row.id) }}> <i className="fa fa-fw fa-minus-square mr-2"></i> Disapprove </DropdownItem> : <DropdownItem onClick={() => { this.approve(row.id) }}> <i className="fa fa-fw fa-check mr-2"></i> Approve </DropdownItem>} <DropdownItem onClick={() => { this.showHandler(row.id, 'delete') }}> <i className="fa fa-fw fa-trash mr-2"></i> Delete </DropdownItem> </DropdownMenu> </UncontrolledButtonDropdown> ) } render() { if(this.state.loading){ return( <EmptyLayout> <EmptyLayout.Section center> <Load/> </EmptyLayout.Section> </EmptyLayout> ) }else { let alert = this.state.alerts; return( <Container> {alert.message && <UncontrolledAlert color={alert.color}> {alert.message} </UncontrolledAlert>} <Row> <Col xl={ 12 }> <ImportButton /> <WeferralTableBase rows={this.state.rows} createItemAction={() => { this.props.history.push('/participant/create') }} createItemLabel={'Create a Participant'} fetchRows={this.fetchData} sortColumn="created_at" sortOrder="desc" > <TableHeaderColumn isKey dataField='name' dataSort={ true } dataFormat={ this.nameFormatter } width={200}> Name </TableHeaderColumn> <TableHeaderColumn dataField='email' dataSort={ true } dataFormat={ this.emailFormatter } searchable={true} width={150}> Email </TableHeaderColumn> <TableHeaderColumn dataField='referral_code' dataSort={ true } dataFormat={ this.idFormatter } searchable={true} width={200}> Referral Code </TableHeaderColumn> <TableHeaderColumn dataField='status' dataSort={ true } dataFormat={ this.statusFormatter } searchable={false} filterFormatted width={100}> Status </TableHeaderColumn> <TableHeaderColumn dataField='created_at' dataSort={ true } dataFormat={ this.createdFormatter } searchable={true} filterFormatted width={150}> Created At </TableHeaderColumn> <TableHeaderColumn dataField='Actions' className={'action-column-header'} columnClassName={'action-column'} dataFormat={ this.rowActionsFormatter } searchable={false} width={100}> </TableHeaderColumn> </WeferralTableBase> </Col> </Row> <ToastContainer position="top-center" autoClose={50000} draggable={true} hideProgressBar={true} /> </Container> ) } } }
JavaScript
class RushConfiguration { /** * Use RushConfiguration.loadFromConfigurationFile() or Use RushConfiguration.loadFromDefaultLocation() * instead. */ constructor(rushConfigurationJson, rushJsonFilename) { if (rushConfigurationJson.nodeSupportedVersionRange) { if (!semver.validRange(rushConfigurationJson.nodeSupportedVersionRange)) { throw new Error('Error parsing the node-semver expression in the "nodeSupportedVersionRange"' + ` field from rush.json: "${rushConfigurationJson.nodeSupportedVersionRange}"`); } if (!semver.satisfies(process.version, rushConfigurationJson.nodeSupportedVersionRange)) { throw new Error(`Your dev environment is running Node.js version ${process.version} which does` + ` not meet the requirements for building this repository. (The rush.json configuration` + ` requires nodeSupportedVersionRange="${rushConfigurationJson.nodeSupportedVersionRange}")`); } } this._rushJsonFile = rushJsonFilename; this._rushJsonFolder = path.dirname(rushJsonFilename); this._commonFolder = path.resolve(path.join(this._rushJsonFolder, RushConstants_1.RushConstants.commonFolderName)); this._commonRushConfigFolder = path.join(this._commonFolder, 'config', 'rush'); RushConfiguration._validateCommonRushConfigFolder(this._commonRushConfigFolder); this._commonTempFolder = path.join(this._commonFolder, RushConstants_1.RushConstants.rushTempFolderName); this._npmCacheFolder = path.resolve(path.join(this._commonTempFolder, 'npm-cache')); this._npmTmpFolder = path.resolve(path.join(this._commonTempFolder, 'npm-tmp')); this._changesFolder = path.join(this._commonFolder, RushConstants_1.RushConstants.changeFilesFolderName); this._committedShrinkwrapFilename = path.join(this._commonRushConfigFolder, RushConstants_1.RushConstants.npmShrinkwrapFilename); this._tempShrinkwrapFilename = path.join(this._commonTempFolder, RushConstants_1.RushConstants.npmShrinkwrapFilename); this._homeFolder = RushConfiguration.getHomeDirectory(); this._rushLinkJsonFilename = path.join(this._commonTempFolder, 'rush-link.json'); this._npmToolVersion = rushConfigurationJson.npmVersion; this._npmToolFilename = path.resolve(path.join(this._commonTempFolder, 'npm-local', 'node_modules', '.bin', 'npm')); this._projectFolderMinDepth = rushConfigurationJson.projectFolderMinDepth !== undefined ? rushConfigurationJson.projectFolderMinDepth : 1; if (this._projectFolderMinDepth < 1) { throw new Error('Invalid projectFolderMinDepth; the minimum possible value is 1'); } this._projectFolderMaxDepth = rushConfigurationJson.projectFolderMaxDepth !== undefined ? rushConfigurationJson.projectFolderMaxDepth : 2; if (this._projectFolderMaxDepth < this._projectFolderMinDepth) { throw new Error('The projectFolderMaxDepth cannot be smaller than the projectFolderMinDepth'); } this._approvedPackagesPolicy = new ApprovedPackagesPolicy_1.ApprovedPackagesPolicy(this, rushConfigurationJson); this._gitAllowedEmailRegExps = []; this._gitSampleEmail = ''; if (rushConfigurationJson.gitPolicy) { if (rushConfigurationJson.gitPolicy.sampleEmail) { this._gitSampleEmail = rushConfigurationJson.gitPolicy.sampleEmail; } if (rushConfigurationJson.gitPolicy.allowedEmailRegExps) { this._gitAllowedEmailRegExps = rushConfigurationJson.gitPolicy.allowedEmailRegExps; if (this._gitSampleEmail.trim().length < 1) { throw new Error('The rush.json file is missing the "sampleEmail" option, ' + 'which is required when using "allowedEmailRegExps"'); } } } if (rushConfigurationJson.repository) { this._repositoryUrl = rushConfigurationJson.repository.url; } this._telemetryEnabled = !!rushConfigurationJson.telemetryEnabled; if (rushConfigurationJson.eventHooks) { this._eventHooks = new EventHooks_1.default(rushConfigurationJson.eventHooks); } const versionPolicyConfigFile = path.join(this._commonRushConfigFolder, RushConstants_1.RushConstants.versionPoliciesFileName); this._versionPolicyConfiguration = new VersionPolicyConfiguration_1.VersionPolicyConfiguration(versionPolicyConfigFile); this._projects = []; this._projectsByName = new Map(); // We sort the projects array in alphabetical order. This ensures that the packages // are processed in a deterministic order by the various Rush algorithms. const sortedProjectJsons = rushConfigurationJson.projects.slice(0); sortedProjectJsons.sort((a, b) => a.packageName.localeCompare(b.packageName)); const tempNamesByProject = RushConfiguration._generateTempNamesForProjects(sortedProjectJsons); for (const projectJson of sortedProjectJsons) { const tempProjectName = tempNamesByProject.get(projectJson); if (tempProjectName) { const project = new RushConfigurationProject_1.default(projectJson, this, tempProjectName); this._projects.push(project); if (this._projectsByName.get(project.packageName)) { throw new Error(`The project name "${project.packageName}" was specified more than once` + ` in the rush.json configuration file.`); } this._projectsByName.set(project.packageName, project); } } for (const project of this._projects) { project.cyclicDependencyProjects.forEach((cyclicDependencyProject) => { if (!this.getProjectByName(cyclicDependencyProject)) { throw new Error(`In rush.json, the "${cyclicDependencyProject}" project does not exist,` + ` but was referenced by the cyclicDependencyProjects for ${project.packageName}`); } }); // Compute the downstream dependencies within the list of Rush projects. this._populateDownstreamDependencies(project.packageJson.dependencies, project.packageName); this._populateDownstreamDependencies(project.packageJson.devDependencies, project.packageName); } // Example: "./common/config/rush/pinnedVersions.json" const pinnedVersionsFile = path.join(this.commonRushConfigFolder, RushConstants_1.RushConstants.pinnedVersionsFilename); this._pinnedVersions = PinnedVersionsConfiguration_1.PinnedVersionsConfiguration.tryLoadFromFile(pinnedVersionsFile); } /** * Loads the configuration data from an Rush.json configuration file and returns * an RushConfiguration object. */ static loadFromConfigurationFile(rushJsonFilename) { const rushConfigurationJson = node_core_library_1.JsonFile.load(rushJsonFilename); // Check the Rush version *before* we validate the schema, since if the version is outdated // then the schema may have changed. This should no longer be a problem after Rush 4.0 and the C2R wrapper, // but we'll validate anyway. const expectedRushVersion = rushConfigurationJson.rushVersion; // If the version is missing or malformed, fall through and let the schema handle it. if (expectedRushVersion && semver.valid(expectedRushVersion)) { if (semver.lt(Rush_1.default.version, expectedRushVersion)) { throw new Error(`Your rush tool is version ${Rush_1.default.version}, but rush.json ` + `requires version ${rushConfigurationJson.rushVersion}. To upgrade, ` + `run "npm install @microsoft/rush -g".`); } else if (semver.lt(expectedRushVersion, MINIMUM_SUPPORTED_RUSH_JSON_VERSION)) { throw new Error(`rush.json is version ${expectedRushVersion}, which is too old for this tool. ` + `The minimum supported version is ${MINIMUM_SUPPORTED_RUSH_JSON_VERSION}.`); } } RushConfiguration._jsonSchema.validateObject(rushConfigurationJson, rushJsonFilename); return new RushConfiguration(rushConfigurationJson, rushJsonFilename); } static loadFromDefaultLocation() { const rushJsonLocation = RushConfiguration.tryFindRushJsonLocation(); if (rushJsonLocation) { return RushConfiguration.loadFromConfigurationFile(rushJsonLocation); } else { throw new Error('Unable to find rush.json configuration file'); } } /** * Find the rush.json location and return the path, or undefined if a rush.json can't be found. */ static tryFindRushJsonLocation(verbose = true) { let currentFolder = process.cwd(); // Look upwards at parent folders until we find a folder containing rush.json for (let i = 0; i < 10; ++i) { const rushJsonFilename = path.join(currentFolder, 'rush.json'); if (fsx.existsSync(rushJsonFilename)) { if (i > 0 && verbose) { console.log('Found configuration in ' + rushJsonFilename); } if (verbose) { console.log(''); } return rushJsonFilename; } const parentFolder = path.dirname(currentFolder); if (parentFolder === currentFolder) { break; } currentFolder = parentFolder; } return undefined; } /** * Get the user's home directory. On windows this looks something like "C:\users\username\" and on UNIX * this looks something like "/usr/username/" */ static getHomeDirectory() { const unresolvedUserFolder = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; const homeFolder = path.resolve(unresolvedUserFolder); if (!fsx.existsSync(homeFolder)) { throw new Error('Unable to determine the current user\'s home directory'); } return homeFolder; } /** * This generates the unique names that are used to create temporary projects * in the Rush common folder. * NOTE: sortedProjectJsons is sorted by the caller. */ static _generateTempNamesForProjects(sortedProjectJsons) { const tempNamesByProject = new Map(); const usedTempNames = new Set(); // NOTE: projectJsons was already sorted in alphabetical order by the caller. for (const projectJson of sortedProjectJsons) { // If the name is "@ms/MyProject", extract the "MyProject" part const unscopedName = Utilities_1.default.parseScopedPackageName(projectJson.packageName).name; // Generate a unique like name "@rush-temp/MyProject", or "@rush-temp/MyProject-2" if // there is a naming conflict let counter = 0; let tempProjectName = `${RushConstants_1.RushConstants.rushTempNpmScope}/${unscopedName}`; while (usedTempNames.has(tempProjectName)) { ++counter; tempProjectName = `${RushConstants_1.RushConstants.rushTempNpmScope}/${unscopedName}-${counter}`; } usedTempNames.add(tempProjectName); tempNamesByProject.set(projectJson, tempProjectName); } return tempNamesByProject; } /** * If someone adds a config file in the "common/rush/config" folder, it would be a bad * experience for Rush to silently ignore their file simply because they misspelled the * filename, or maybe it's an old format that's no longer supported. The * _validateCommonRushConfigFolder() function makes sure that this folder only contains * recognized config files. */ static _validateCommonRushConfigFolder(commonRushConfigFolder) { if (!fsx.existsSync(commonRushConfigFolder)) { console.log(`Creating folder: ${commonRushConfigFolder}`); fsx.mkdirsSync(commonRushConfigFolder); return; } const filenames = fsx.readdirSync(commonRushConfigFolder); for (const filename of filenames) { const resolvedFilename = path.resolve(commonRushConfigFolder, filename); // Ignore things that aren't actual files const stat = fsx.lstatSync(resolvedFilename); if (!stat.isFile() && !stat.isSymbolicLink()) { continue; } // Ignore harmless file extensions const fileExtension = path.extname(filename); if (['.bak', '.disabled', '.md', '.old', '.orig'].indexOf(fileExtension) >= 0) { continue; } const knownSet = new Set(knownRushConfigFilenames.map(x => x.toUpperCase())); // Is the filename something we know? If not, report an error. if (!knownSet.has(filename.toUpperCase())) { throw new Error(`An unrecognized file "${filename}" was found in the Rush config folder:` + ` ${commonRushConfigFolder}`); } } } /** * The Rush configuration file */ get rushJsonFile() { return this._rushJsonFile; } /** * The folder that contains rush.json for this project. */ get rushJsonFolder() { return this._rushJsonFolder; } /** * The folder that contains all change files. */ get changesFolder() { return this._changesFolder; } /** * The fully resolved path for the "common" folder where Rush will store settings that * affect all Rush projects. This is always a subfolder of the folder containing "rush.json". * Example: "C:\MyRepo\common" */ get commonFolder() { return this._commonFolder; } /** * The folder where Rush's additional config files are stored. This folder is always a * subfolder called "config\rush" inside the common folder. (The "common\config" folder * is reserved for configuration files used by other tools.) To avoid confusion or mistakes, * Rush will report an error if this this folder contains any unrecognized files. * * Example: "C:\MyRepo\common\config\rush" */ get commonRushConfigFolder() { return this._commonRushConfigFolder; } /** * The folder where temporary files will be stored. This is always a subfolder called "temp" * inside the common folder. * Example: "C:\MyRepo\common\temp" */ get commonTempFolder() { return this._commonTempFolder; } /** * The local folder that will store the NPM package cache. Rush does not rely on the * NPM's default global cache folder, because NPM's caching implementation does not * reliably handle multiple processes. (For example, if a build box is running * "rush install" simultaneously for two different working folders, it may fail randomly.) * * Example: "C:\MyRepo\common\temp\npm-cache" */ get npmCacheFolder() { return this._npmCacheFolder; } /** * The local folder where NPM's temporary files will be written during installation. * Rush does not rely on the global default folder, because it may be on a different * hard disk. * * Example: "C:\MyRepo\common\temp\npm-tmp" */ get npmTmpFolder() { return this._npmTmpFolder; } /** * The filename of the NPM shrinkwrap file that is tracked e.g. by Git. (The "rush install" * command uses a temporary copy, whose path is tempShrinkwrapFilename.) * This property merely reports the filename; the file itself may not actually exist. * Example: "C:\MyRepo\common\npm-shrinkwrap.json" */ get committedShrinkwrapFilename() { return this._committedShrinkwrapFilename; } /** * The filename of the temporary NPM shrinkwrap file that is used by "rush install". * (The master copy is tempShrinkwrapFilename.) * This property merely reports the filename; the file itself may not actually exist. * Example: "C:\MyRepo\common\temp\npm-shrinkwrap.json" */ get tempShrinkwrapFilename() { return this._tempShrinkwrapFilename; } /** * The absolute path to the home directory for the current user. On Windows, * it would be something like "C:\Users\YourName". */ get homeFolder() { return this._homeFolder; } /** * The filename of the build dependency data file. By default this is * called 'rush-link.json' resides in the Rush common folder. * Its data structure is defined by IRushLinkJson. * * Example: "C:\MyRepo\common\temp\rush-link.json" */ get rushLinkJsonFilename() { return this._rushLinkJsonFilename; } /** * The version of the locally installed NPM tool. (Example: "1.2.3") */ get npmToolVersion() { return this._npmToolVersion; } /** * The absolute path to the locally installed NPM tool. If "rush install" has not * been run, then this file may not exist yet. * Example: "C:\MyRepo\common\temp\npm-local\node_modules\.bin\npm" */ get npmToolFilename() { return this._npmToolFilename; } /** * The minimum allowable folder depth for the projectFolder field in the rush.json file. * This setting provides a way for repository maintainers to discourage nesting of project folders * that makes the directory tree more difficult to navigate. The default value is 2, * which implements a standard 2-level hierarchy of <categoryFolder>/<projectFolder>/package.json. */ get projectFolderMinDepth() { return this._projectFolderMinDepth; } /** * The maximum allowable folder depth for the projectFolder field in the rush.json file. * This setting provides a way for repository maintainers to discourage nesting of project folders * that makes the directory tree more difficult to navigate. The default value is 2, * which implements on a standard convention of <categoryFolder>/<projectFolder>/package.json. */ get projectFolderMaxDepth() { return this._projectFolderMaxDepth; } /** * The "approvedPackagesPolicy" settings. */ get approvedPackagesPolicy() { return this._approvedPackagesPolicy; } /** * [Part of the "gitPolicy" feature.] * A list of regular expressions describing allowable e-mail patterns for Git commits. * They are case-insensitive anchored JavaScript RegExps. * Example: ".*@example\.com" * This array will never be undefined. */ get gitAllowedEmailRegExps() { return this._gitAllowedEmailRegExps; } /** * [Part of the "gitPolicy" feature.] * An example valid e-mail address that conforms to one of the allowedEmailRegExps. * Example: "foxtrot@example\.com" * This will never be undefined, and will always be nonempty if gitAllowedEmailRegExps is used. */ get gitSampleEmail() { return this._gitSampleEmail; } /** * The remote url of the repository. It helps 'Rush change' finds the right remote to compare against. */ get repositoryUrl() { return this._repositoryUrl; } /** * Indicates whether telemetry collection is enabled for Rush runs. * @beta */ get telemetryEnabled() { return this._telemetryEnabled; } get projects() { return this._projects; } get projectsByName() { return this._projectsByName; } /** * The PinnedVersionsConfiguration object. If the pinnedVersions.json file is missing, * this property will NOT be undefined. Instead it will be initialized in an empty state, * and calling PinnedVersionsConfiguration.save() will create the file. */ get pinnedVersions() { return this._pinnedVersions; } /** * The rush hooks. It allows customized scripts to run at the specified point. * @beta */ get eventHooks() { return this._eventHooks; } /** * Looks up a project in the projectsByName map. If the project is not found, * then undefined is returned. */ getProjectByName(projectName) { return this._projectsByName.get(projectName); } /** * This is used e.g. by command-line interfaces such as "rush build --to example". * If "example" is not a project name, then it also looks for a scoped name * like "@something/example". If exactly one project matches this heuristic, it * is returned. Otherwise, undefined is returned. */ findProjectByShorthandName(shorthandProjectName) { // Is there an exact match? let result = this._projectsByName.get(shorthandProjectName); if (result) { return result; } // Is there an approximate match? for (const project of this._projects) { if (Utilities_1.default.parseScopedPackageName(project.packageName).name === shorthandProjectName) { if (result) { // Ambiguous -- there is more than one match return undefined; } else { result = project; } } } return result; } /** * Looks up a project by its RushConfigurationProject.tempProjectName field. * @returns The found project, or undefined if no match was found. */ findProjectByTempName(tempProjectName) { // Is there an approximate match? for (const project of this._projects) { if (project.tempProjectName === tempProjectName) { return project; } } return undefined; } /** * @beta */ get versionPolicyConfiguration() { return this._versionPolicyConfiguration; } _populateDownstreamDependencies(dependencies, packageName) { if (!dependencies) { return; } Object.keys(dependencies).forEach(dependencyName => { const depProject = this._projectsByName.get(dependencyName); if (depProject) { depProject.downstreamDependencyProjects.push(packageName); } }); } }
JavaScript
class DeployedApplicationHealthEvaluation extends models['HealthEvaluation'] { /** * Create a DeployedApplicationHealthEvaluation. * @member {string} [nodeName] * @member {string} [applicationName] * @member {array} [unhealthyEvaluations] */ constructor() { super(); } /** * Defines the metadata of DeployedApplicationHealthEvaluation * * @returns {object} metadata of DeployedApplicationHealthEvaluation * */ mapper() { return { required: false, serializedName: 'DeployedApplication', type: { name: 'Composite', className: 'DeployedApplicationHealthEvaluation', modelProperties: { aggregatedHealthState: { required: false, serializedName: 'AggregatedHealthState', type: { name: 'String' } }, description: { required: false, serializedName: 'Description', type: { name: 'String' } }, kind: { required: true, serializedName: 'Kind', type: { name: 'String' } }, nodeName: { required: false, serializedName: 'NodeName', type: { name: 'String' } }, applicationName: { required: false, serializedName: 'ApplicationName', type: { name: 'String' } }, unhealthyEvaluations: { required: false, serializedName: 'UnhealthyEvaluations', type: { name: 'Sequence', element: { required: false, serializedName: 'HealthEvaluationWrapperElementType', type: { name: 'Composite', className: 'HealthEvaluationWrapper' } } } } } } }; } }
JavaScript
class BlurFilterPass extends Filter { /** * @param {boolean} horizontal - Do pass along the x-axis (`true`) or y-axis (`false`). * @param {number} strength - The strength of the blur filter. * @param {number} quality - The quality of the blur filter. * @param {number} resolution - The resolution of the blur filter. * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. */ constructor(horizontal, strength, quality, resolution, kernelSize) { kernelSize = kernelSize || 5; const vertSrc = generateBlurVertSource(kernelSize, horizontal); const fragSrc = generateBlurFragSource(kernelSize); super( // vertex shader vertSrc, // fragment shader fragSrc ); this.horizontal = horizontal; this.resolution = resolution || settings.RESOLUTION; this._quality = 0; this.quality = quality || 4; this.blur = strength || 8; } apply(filterManager, input, output, clear) { if (output) { if (this.horizontal) { this.uniforms.strength = (1 / output.width) * (output.width / input.width); } else { this.uniforms.strength = (1 / output.height) * (output.height / input.height); } } else { if (this.horizontal) // eslint-disable-line { this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); } else { this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line } } // screen space! this.uniforms.strength *= this.strength; this.uniforms.strength /= this.passes; if (this.passes === 1) { filterManager.applyFilter(this, input, output, clear); } else { const renderTarget = filterManager.getFilterTexture(); const renderer = filterManager.renderer; let flip = input; let flop = renderTarget; this.state.blend = false; filterManager.applyFilter(this, flip, flop, false); for (let i = 1; i < this.passes - 1; i++) { renderer.renderTexture.bind(flip, flip.filterFrame); this.uniforms.uSampler = flop; const temp = flop; flop = flip; flip = temp; renderer.shader.bind(this); renderer.geometry.draw(5); } this.state.blend = true; filterManager.applyFilter(this, flop, output, clear); filterManager.returnFilterTexture(renderTarget); } } /** * Sets the strength of both the blur. * * @member {number} * @default 16 */ get blur() { return this.strength; } set blur(value) // eslint-disable-line require-jsdoc { this.padding = 1 + (Math.abs(value) * 2); this.strength = value; } /** * Sets the quality of the blur by modifying the number of passes. More passes means higher * quaility bluring but the lower the performance. * * @member {number} * @default 4 */ get quality() { return this._quality; } set quality(value) // eslint-disable-line require-jsdoc { this._quality = value; this.passes = value; } }
JavaScript
class ImageC extends React.Component { constructor(props) { super(props) this.state = { x: props.x, y: props.y, width: 200, height: 160, image: null, scaleY: props.scaleY, scaleX: props.scaleX, rotation: props.rotation }; } componentDidMount() { const image = new window.Image(); image.crossOrigin = "Anonymous"; image.src = this.props.url; image.onload = () => { const scale = 160 / image.naturalHeight // setState will redraw layer // because "image" property is changed this.setState({ // scaleX: scaleY, // scaleY: scaleY, //initiale scale value image: image, width: scale * image.naturalWidth, height: scale * image.naturalHeight, }, () => { this.node.cache(); }); }; } handleDragEnd = e => { // correctly save node position this.setState({ // text3: Konva.Util.getRandomColor(), x: e.target.x(), y: e.target.y() }); this.props.updateCardPos( this.props.id, { x: e.target.x(), y: e.target.y() } ) this.props.handleDragEnd() }; handleDragStart = e => { this.props.handleDragStart(e.target.x(), e.target.y(), 'Image') }; handleDragMove = e => { this.props.handleDragMove(e.target.x(), e.target.y(), 'Image') }; handleTransformEnd = e => { // correctly save node position const changes = { size : { width: e.target.width(), height: e.target.height() }, rotation: e.target.rotation(), scaleX: e.target.scaleX(), scaleY: e.target.scaleY() } this.setState({ // text3: Konva.Util.getRandomColor(), ...changes }); this.props.updateCardSize( this.props.id, changes ) } componentDidUpdate(oldProps, oldState) { if(this.props !== this.props) { this.node.cache() //see https://konvajs.github.io/docs/react/Filters.html } } render() { return <Image draggable x={this.state.x} y={this.state.y} red={this.props.red} green={this.props.green} blue={this.props.blue} alpha={this.props.alpha} contrast={this.props.contrast} stroke={this.props.stroke} strokeWidth={this.props.strokeWidth} ref={node => this.node = node} filters={[Konva.Filters.RGBA, Konva.Filters.Contrast]} onDragEnd={this.handleDragEnd} onDragMove={this.handleDragMove} onDragStart={this.handleDragStart} onTransformEnd={this.handleTransformEnd} width={this.state.width} height={this.state.height} image={this.state.image} imageSrc={this.props.url} //usefull for serialization name={this.props.name} scaleX={this.state.scaleX} scaleY={this.state.scaleY} rotation={this.state.rotation} /> } }
JavaScript
class AlarmController { /** * Retrieve a Alarm [GET /sites/{siteId}/alarms/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Alarm ID * @return {Promise<AlarmModel>} */ static getOne(siteId, id) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/sites/${siteId}/alarms/${id}`) .then((result) => { let resolveValue = (function(){ return AlarmModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Update a Alarm [PATCH /sites/{siteId}/alarms/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Alarm ID * @param {AlarmController.UpdateData} updateData The Alarm Update Data * @return {Promise<AlarmModel>} */ static update(siteId, id, updateData) { return new Promise((resolve, reject) => { RequestHelper.patchRequest(`/sites/${siteId}/alarms/${id}`, updateData) .then((result) => { let resolveValue = (function(){ return AlarmModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Delete a Alarm [DELETE /sites/{siteId}/alarms/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Alarm ID * @return {Promise<boolean>} */ static delete(siteId, id) { return new Promise((resolve, reject) => { RequestHelper.deleteRequest(`/sites/${siteId}/alarms/${id}`) .then((result) => { resolve(result ?? true); }) .catch(error => reject(error)); }); } /** * Retrieve the History of an Alarm [GET /sites/{siteId}/alarms/{id}/history] * * Retrieves History (Logged Events) for a Single Alarm * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Alarm ID * @param {AlarmController.GetOneHistoryQueryParameters} [queryParameters] The Optional Query Parameters * @return {Promise<Array<AlarmController.AlarmHistoryItem>>} */ static getOneHistory(siteId, id, queryParameters = {}) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/sites/${siteId}/alarms/${id}/history`, queryParameters) .then((result) => { let resolveValue = (function(){ if(Array.isArray(result) !== true) { return []; } return result.map((resultItem) => { return (function(){ let resultItemObject = {}; if(typeof resultItem === 'object' && 'id' in resultItem) { resultItemObject.id = (function(){ if(typeof resultItem.id !== 'string') { return String(resultItem.id); } return resultItem.id; }()); } else { resultItemObject.id = ""; } if(typeof resultItem === 'object' && 'tripTimestamp' in resultItem) { resultItemObject.tripTimestamp = (function(){ if(typeof resultItem.tripTimestamp !== 'string') { return new Date(String(resultItem.tripTimestamp)); } return new Date(resultItem.tripTimestamp); }()); } else { resultItemObject.tripTimestamp = new Date(); } if(typeof resultItem === 'object' && 'resetTimestamp' in resultItem) { resultItemObject.resetTimestamp = (function(){ if(resultItem.resetTimestamp === null) { return null; } if(typeof resultItem.resetTimestamp !== 'string') { return new Date(String(resultItem.resetTimestamp)); } return new Date(resultItem.resetTimestamp); }()); } else { resultItemObject.resetTimestamp = null; } if(typeof resultItem === 'object' && 'trippedDuration' in resultItem) { resultItemObject.trippedDuration = (function(){ if(typeof resultItem.trippedDuration !== 'number') { return Number.isInteger(Number(resultItem.trippedDuration)) ? Number(resultItem.trippedDuration) : Math.floor(Number(resultItem.trippedDuration)); } return Number.isInteger(resultItem.trippedDuration) ? resultItem.trippedDuration : Math.floor(resultItem.trippedDuration); }()); } else { resultItemObject.trippedDuration = 0; } return resultItemObject; }()); }); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * List all Alarms [GET /sites/{siteId}/alarms] * * @static * @public * @param {number} siteId The Site ID * @param {AlarmController.GetAllQueryParameters} [queryParameters] The Optional Query Parameters * @return {Promise<AlarmModel[]>} */ static getAll(siteId, queryParameters = {}) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/sites/${siteId}/alarms`, queryParameters) .then((result) => { let resolveValue = (function(){ if(Array.isArray(result) !== true) { return []; } return result.map((resultItem) => { return (function(){ return AlarmModel.fromJSON(resultItem); }()); }); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Create a Alarm [POST /sites/{siteId}/alarms] * * @static * @public * @param {number} siteId The Site ID * @param {AlarmController.CreateData} createData The Alarm Create Data * @return {Promise<AlarmModel>} */ static create(siteId, createData) { return new Promise((resolve, reject) => { RequestHelper.postRequest(`/sites/${siteId}/alarms`, createData) .then((result) => { let resolveValue = (function(){ return AlarmModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Retrieve the History of all Alarms [GET /sites/{siteId}/alarms/history] * * Retrieves History (Logged Events) for all Alarms * * @static * @public * @param {number} siteId The Site ID * @param {AlarmController.GetAllHistoryQueryParameters} [queryParameters] The Optional Query Parameters * @return {Promise<Array<AlarmController.AlarmHistoryItem>>} */ static getAllHistory(siteId, queryParameters = {}) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/sites/${siteId}/alarms/history`, queryParameters) .then((result) => { let resolveValue = (function(){ if(Array.isArray(result) !== true) { return []; } return result.map((resultItem) => { return (function(){ let resultItemObject = {}; if(typeof resultItem === 'object' && 'id' in resultItem) { resultItemObject.id = (function(){ if(typeof resultItem.id !== 'string') { return String(resultItem.id); } return resultItem.id; }()); } else { resultItemObject.id = ""; } if(typeof resultItem === 'object' && 'tripTimestamp' in resultItem) { resultItemObject.tripTimestamp = (function(){ if(typeof resultItem.tripTimestamp !== 'string') { return new Date(String(resultItem.tripTimestamp)); } return new Date(resultItem.tripTimestamp); }()); } else { resultItemObject.tripTimestamp = new Date(); } if(typeof resultItem === 'object' && 'resetTimestamp' in resultItem) { resultItemObject.resetTimestamp = (function(){ if(resultItem.resetTimestamp === null) { return null; } if(typeof resultItem.resetTimestamp !== 'string') { return new Date(String(resultItem.resetTimestamp)); } return new Date(resultItem.resetTimestamp); }()); } else { resultItemObject.resetTimestamp = null; } if(typeof resultItem === 'object' && 'trippedDuration' in resultItem) { resultItemObject.trippedDuration = (function(){ if(typeof resultItem.trippedDuration !== 'number') { return Number.isInteger(Number(resultItem.trippedDuration)) ? Number(resultItem.trippedDuration) : Math.floor(Number(resultItem.trippedDuration)); } return Number.isInteger(resultItem.trippedDuration) ? resultItem.trippedDuration : Math.floor(resultItem.trippedDuration); }()); } else { resultItemObject.trippedDuration = 0; } return resultItemObject; }()); }); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } }
JavaScript
class PropertyData { /** * @signature `new PropertyData(location)` * @sigparam {PropertyData} location - The PropertyData instance to clone from. * * @signature `new PropertyData(object)` * @sigparam {{name: string, value: string}} object - The property object to clone from. * * @signature `new PropertyData(name, value)` * @sigparam {string} name - The property name. * @sigparam {string} value - The property value. * * @param {string|PropertyDataObject|PropertyData} varArg1 * @param {string} [varArg2] */ constructor(varArg1, varArg2) { if (arguments.length === 2) { return new PropertyData({name: varArg1, value: varArg2}) } if (varArg1 instanceof PropertyData) { return new PropertyData({name: varArg1.getName(), value: varArg1.getValue()}) } const {name, value} = varArg1 ArgumentGuard.isString(name, 'name') ArgumentGuard.notNull(value, 'value') /** @type {string} */ this._name = name /** @type {string} */ this._value = value } /** * @return {string} */ getName() { return this._name } /** * @param {string} value */ setName(value) { this._name = value } /** * @return {string} */ getValue() { return this._value } /** * @param {string} value */ setValue(value) { this._value = value } /** * @override */ toJSON() { return { name: this._name, value: this._value, } } /** * @override */ toString() { return `PropertyData { ${JSON.stringify(this)} }` } }
JavaScript
class Media { /** * Constructs a new <code>Media</code>. * @alias module:model/Media * @class */ constructor() { } /** * Constructs a <code>Media</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/Media} obj Optional instance to populate. * @return {module:model/Media} The populated <code>Media</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Media(); if (data.hasOwnProperty('_syncFields')) obj.syncFields = ApiClient.convertToType(data['_syncFields'], 'String'); if (data.hasOwnProperty('name')) obj.name = ApiClient.convertToType(data['name'], 'String'); if (data.hasOwnProperty('url')) obj.url = ApiClient.convertToType(data['url'], 'String'); if (data.hasOwnProperty('filepath')) obj.filepath = ApiClient.convertToType(data['filepath'], 'String'); if (data.hasOwnProperty('filetype')) obj.filetype = ApiClient.convertToType(data['filetype'], 'String'); if (data.hasOwnProperty('isDownload')) obj.isDownload = ApiClient.convertToType(data['isDownload'], 'Number'); if (data.hasOwnProperty('isGlobal')) obj.isGlobal = ApiClient.convertToType(data['isGlobal'], 'Number'); if (data.hasOwnProperty('description')) obj.description = ApiClient.convertToType(data['description'], 'String'); if (data.hasOwnProperty('limitedVisibility')) obj.limitedVisibility = ApiClient.convertToType(data['limitedVisibility'], 'Number'); if (data.hasOwnProperty('startDate')) obj.startDate = ApiClient.convertToType(data['startDate'], 'Number'); if (data.hasOwnProperty('endDate')) obj.endDate = ApiClient.convertToType(data['endDate'], 'Number'); if (data.hasOwnProperty('uploaderId')) obj.uploaderId = ApiClient.convertToType(data['uploaderId'], 'String'); if (data.hasOwnProperty('id')) obj.id = ApiClient.convertToType(data['id'], 'Number'); if (data.hasOwnProperty('foreignId')) obj.foreignId = ApiClient.convertToType(data['foreignId'], 'String'); if (data.hasOwnProperty('language')) obj.language = ApiClient.convertToType(data['language'], 'Number'); if (data.hasOwnProperty('createDate')) obj.createDate = ApiClient.convertToType(data['createDate'], 'Number'); if (data.hasOwnProperty('changeDate')) obj.changeDate = ApiClient.convertToType(data['changeDate'], 'Number'); if (data.hasOwnProperty('deleted')) obj.deleted = ApiClient.convertToType(data['deleted'], 'Number'); if (data.hasOwnProperty('hidden')) obj.hidden = ApiClient.convertToType(data['hidden'], 'Number'); if (data.hasOwnProperty('sorting')) obj.sorting = ApiClient.convertToType(data['sorting'], 'Number'); if (data.hasOwnProperty('tags')) obj.tags = ApiClient.convertToType(data['tags'], 'String'); if (data.hasOwnProperty('glyphicon')) obj.glyphicon = ApiClient.convertToType(data['glyphicon'], 'String'); } return obj; } }
JavaScript
class BelongsTo extends Association { /** * @method getForeignKeyArray * @return {Array} Array of camelized name of the model owning the association * and foreign key for the association * @public */ getForeignKeyArray() { return [camelize(this.ownerModelName), this.getForeignKey()]; } /** * @method getForeignKey * @return {String} Foreign key for the association * @public */ getForeignKey() { return `${camelize(this.key)}Id`; } /** * Registers belongs-to association defined by given key on given model, * defines getters / setters for associated parent and associated parent's id, * adds methods for creating unsaved parent record and creating a saved one * * @method addMethodsToModelClass * @param {Function} ModelClass * @param {String} key the named key for the association * @public */ addMethodsToModelClass(ModelClass, key) { let modelPrototype = ModelClass.prototype; let association = this; let foreignKey = this.getForeignKey(); let associationHash = { [key]: this }; modelPrototype.belongsToAssociations = _assign(modelPrototype.belongsToAssociations, associationHash); // Add to target's dependent associations array this.schema.addDependentAssociation(this, this.modelName); // TODO: look how this is used. Are these necessary, seems like they could be gotten from the above? // Or we could use a single data structure to store this information? modelPrototype.associationKeys.push(key); modelPrototype.associationIdKeys.push(foreignKey); Object.defineProperty(modelPrototype, foreignKey, { /* object.parentId - returns the associated parent's id */ get() { this._tempAssociations = this._tempAssociations || {}; let tempParent = this._tempAssociations[key]; let id; if (tempParent === null) { id = null; } else { if (association.isPolymorphic) { if (tempParent) { id = { id: tempParent.id, type: tempParent.modelName }; } else { id = this.attrs[foreignKey]; } } else { if (tempParent) { id = tempParent.id; } else { id = this.attrs[foreignKey]; } } } return id; }, /* object.parentId = (parentId) - sets the associated parent via id */ set(id) { let tempParent; if (id === null) { tempParent = null; } else if (id !== undefined) { if (association.isPolymorphic) { assert(typeof id === 'object', `You're setting an ID on the polymorphic association '${association.key}' but you didn't pass in an object. Polymorphic IDs need to be in the form { type, id }.`); tempParent = association.schema[toCollectionName(id.type)].find(id.id); } else { tempParent = association.schema[toCollectionName(association.modelName)].find(id); assert(tempParent, `Couldn't find ${association.modelName} with id = ${id}`); } } this[key] = tempParent; } }); Object.defineProperty(modelPrototype, key, { /* object.parent - returns the associated parent */ get() { this._tempAssociations = this._tempAssociations || {}; let tempParent = this._tempAssociations[key]; let foreignKeyId = this[foreignKey]; let model = null; if (tempParent) { model = tempParent; } else if (foreignKeyId !== null) { if (association.isPolymorphic) { model = association.schema[toCollectionName(foreignKeyId.type)].find(foreignKeyId.id); } else { model = association.schema[toCollectionName(association.modelName)].find(foreignKeyId); } } return model; }, /* object.parent = (parentModel) - sets the associated parent via model I want to jot some notes about hasInverseFor. There used to be an association.inverse() check, but adding polymorphic associations complicated this. `comment.commentable`, you can't easily check for an inverse since `comments: hasMany()` could be on any model. Instead of making it very complex and looking for an inverse on the association in isoaltion, it was much simpler to ask the model being passed in if it had an inverse for the setting model and with its association. */ set(model) { this._tempAssociations = this._tempAssociations || {}; this._tempAssociations[key] = model; if (model && model.hasInverseFor(association)) { let inverse = model.inverseFor(association); model.associate(this, inverse); } } }); /* object.newParent - creates a new unsaved associated parent TODO: document polymorphic */ modelPrototype[`new${capitalize(key)}`] = function(...args) { let modelName, attrs; if (association.isPolymorphic) { modelName = args[0]; attrs = args[1]; } else { modelName = association.modelName; attrs = args[0]; } let parent = association.schema[toCollectionName(modelName)].new(attrs); this[key] = parent; return parent; }; /* object.createParent - creates a new saved associated parent, and immediately persists both models TODO: document polymorphic */ modelPrototype[`create${capitalize(key)}`] = function(...args) { let modelName, attrs; if (association.isPolymorphic) { modelName = args[0]; attrs = args[1]; } else { modelName = association.modelName; attrs = args[0]; } let parent = association.schema[toCollectionName(modelName)].create(attrs); this[key] = parent; this.save(); return parent; }; } /** * * * @public */ disassociateAllDependentsFromTarget(model) { let owner = this.ownerModelName; let fk; if (this.isPolymorphic) { fk = { type: model.modelName, id: model.id }; } else { fk = model.id; } let dependents = this.schema[toCollectionName(owner)] .where((potentialOwner) => { let id = potentialOwner[this.getForeignKey()]; if (!id) { return false; } if (typeof id === 'object') { return id.type === fk.type && id.id === fk.id; } else { return id === fk; } }); dependents.models.forEach(dependent => { dependent.disassociate(model, this); dependent.save(); }); } }
JavaScript
class Content { setOwner (owner) { this.owner = owner } sectionName (name) { this.owner.currentSection.name = name } section (name) { this.owner.section(name) } icon (asset) { this.owner.icon(asset) } text (text, size) { this.owner.text(text, size) } animatedBar (width, height, horizontal, percent) { this.owner.animatedBar(width, height, horizontal, percent) } button (name, functionToCall, context, asset) { this.owner.button(name, functionToCall, context, asset) } labeledImage (text, asset) { this.owner.labeledImage(text, asset) } add (component) { this.owner.add(component) } addSection (section) { this.owner.addSection(section) } addSections (sections) { this.owner.addSections(sections) } /** * Helper function to format a number to not have decimals. * * @param {*} number */ format (number, decimals) { if (number == null) return number if (decimals == null) decimals = 0 return number.toFixed(decimals) } }
JavaScript
class AccountScreen extends React.Component { static navigationOptions = { header: null, }; // signOut = async () => { // try { // await GoogleSignin.revokeAccess(); // await GoogleSignin.signOut(); // this.setState({ user: null }); // Remember to remove the user from your app's state as well // } catch (error) { // console.error(error); // } // }; logout = () => { API.logout() .then(() => { this.clearAsyncStorage().then(() => { const navigateHome = NavigationActions.navigate({ routeName: "Auth", }); this.props.navigation.dispatch(navigateHome); }) } ) .catch(err => console.log(err)); } clearAsyncStorage = () => { return AsyncStorage.removeItem("user"); } showConfirm = () => { Alert.alert( 'Are you sure you want to exit the game?', 'Your pets will miss you', [ { text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel', }, { text: 'Exit', onPress: () => this.logout() }, ], { cancelable: false }, ) return true; } render() { const {navigate} = this.props.navigation; return ( <Container> <Header> <Body> <Title style={{alignSelf: 'center'}}>Settings</Title> </Body> </Header> <Content> <List> <ListItem icon onPress={() => navigate('AboutGame')}> <Left> <Icon name="md-information-circle"/> </Left> <Body> <Text>About the game</Text> </Body> </ListItem> <ListItem icon onPress={() => navigate('AboutUs')}> <Left> <Icon name="md-browsers"/> </Left> <Body> <Text>About the developers</Text> </Body> </ListItem> <ListItem icon onPress={() => this.showConfirm()}> <Left> <Icon name="md-nuclear"/> </Left> <Body> <Text>Log Out & Exit</Text> </Body> </ListItem> </List> </Content> </Container> ); } }
JavaScript
class ActorSheetElvenRogue extends DCCActorSheet { /** @override */ getData () { const data = super.getData() this.options.template = 'modules/dcc-crawl-classes/templates/actor-sheet-elven-rogue.html' data.data.class.className = 'Elven Rogue' return data } }
JavaScript
class Automaton { //initialize automaton with rule constructor(rule, size) { this.rule = rule; this.size = size; /* contains all the loaded chunks. the implementation of this compels my soul to escape my body to achieve some degree of inner peace that I lost while typing this simple initialization. */ this.loadedChunks = {}; //store newly born chunks here instead of above. (logic for step()) this.bufferedChunks = {}; /* simple checks - here really only to help me pretend I care about other people's screw-ups. */ if(!rule instanceof Function){ console.error("Rule is not a function!"); } if((!Number.isInteger(size)) || size < 1){ console.error("Invalid chunk size: "+size); } } //increments the automaton by the number of steps step(steps = 1) { if(!Number.isInteger(steps)){ return; } while(steps > 0){ steps--; /* each property of loadedChunks is keyed with a 2 element int array for location */ for(var key in this.loadedChunks){ var coord = key.split(","); var chunk = this.loadedChunks[coord]; if(chunk.isEmpty){ updateChunkEmpty(coord, chunk, this); }else{ updateChunkFilled(coord, chunk, this); } } /* handle newly created chunks: update and then add to loadedChunks. */ for(var key in this.bufferedChunks){ var coord = key.split(","); var chunk = this.bufferedChunks[coord]; updateChunkEmpty(coord, chunk, this); this.loadedChunks[coord] = chunk; } this.bufferedChunks = {}; /* set each chunk's current buffer to the next one */ for(var key in this.loadedChunks){ var coord = key.split(","); this.loadedChunks[coord].swap(); } } } /* gets the chunk at the specified location. if the chunk is unloaded, returns undefined. x and y are expected to be integers, but no type checking is done. */ getChunk(x, y){ var coords = [x,y]; return this.loadedChunks[coords]; } /* gets the cell state of the cell at the given position. x and y are expected to be integers, but no type checking is done. If the chunk is unloaded, then null is returned. */ getCell(x, y){ var coords = [Math.floor(x/this.size),Math.floor(y/this.size)]; var chunk = this.loadedChunks[coords]; if(chunk == null){ return null; } x -= coords[0] * this.size; y -= coords[1] * this.size; return chunk.getState(x,y); } /* sets the cell state of the cell at the given position. x and y are expected to be integers, but no type checking is done. If the chunk is unloaded, then the chunk is loaded. */ setCell(x, y, state){ var coords = [Math.floor(x/this.size),Math.floor(y/this.size)]; x -= coords[0] * this.size; y -= coords[1] * this.size; if(this.loadedChunks[coords] == null){ this.loadedChunks[coords] = new Chunk(this.size); } this.loadedChunks[coords].setCurrentState(x,y,state); this.loadedChunks[coords].emptyCheck(); return; } }
JavaScript
class Chunk { constructor(size) { this.size = size; //board state, array of cells this.currentState = new Array(size * size).fill(null); this.nextState = new Array(size * size).fill(null); //boolean states for emptiness this.currEmpty = true; this.nextEmpty = true; } get isEmpty(){ return this.currEmpty; } //preps for the next iteration of the automaton //for this chunk swap(){ //swap arrays var tmp = this.currentState; this.currentState = this.nextState; this.nextState = tmp; //shift empty state this.currEmpty = this.nextEmpty; this.nextEmpty = true; } getState(x, y){ var index = y * this.size + x; return this.currentState[y * this.size + x]; } setCurrentState(x, y, state){ this.currentState[y * this.size + x] = state; } setState(x, y, state){ this.nextState[y * this.size + x] = state; if(state != null){ this.nextEmpty = false; } } //checks to see if current state is empty, sets emptiness accordingly emptyCheck(){ var i; var max = this.size * this.size; this.currEmpty = true; for(i = 0; i < max; i++){ if(this.currentState[i] != null) this.currEmpty = false; } } }
JavaScript
class ToolBar extends Control { /** * * @param {Control} parent * @param {String} id * @param {Object} toolbar */ constructor(parent, id, toolbar) { super(parent, id) this.buttonStyle = this.parent.buttonStyle if (toolbar) this.setToolbar(toolbar) } setToolbar(toolbar) { for (let k of this.controls) { delete this.controls[k] } for (let item of toolbar.items) { let button = new Button(this, item.id) button = Object.assign(button, item) button.buttonStyle = this.buttonStyle this.addButton(button) } } /** * Add a button to the toolbar * @param {Object} button The x coordinate of the pointer */ addButton(btnData) { let button = new Button(this, btnData.id) this.controls[button.id] = button button.on('click', (x, y, button) => { if (button.left) { this.parent.emit('command', button.id) } }) this.pack() } /** * Orders the children * @param {Int} x The x coordinate of the pointer * @param {Int} y The y coordinate of the pointer * @param {String} button The button **/ pack() { let i = 0 let left = 0 let buttonSize = 18 for (let buttonId of Object.keys(this.controls)) { let button = this.controls[buttonId] button.left = left button.top = 0 button.width = this.graphics.measureText(button.text) + 18 button.height = buttonSize left += button.width } this.width = left this.yoghurt.render() } render(gc) { super.render(gc) this.style.renderToolbar(gc, this) } }
JavaScript
class MetricsOutput extends TableOutput { constructor (city, title, metrics) { super(city, title) this._metrics = metrics } render () { const models = this._models const headers = ['Models'] for (const metric of this._metrics) { const units = metric.unit.displayName || metric.unit.name const columnHeader = `${metric.displayName} (${units}) &nbsp;`.replace(/ /g, '<br>') headers.push(columnHeader) } this.renderHeaderRow(headers) for (const model of models) { const stringValues = [model.name] for (const metric of this._metrics) { const value = model.getValueForMetric(metric) if (value > 10 || value === 0) { // TODO: this is a hack, figure out a better way to determine number format based on metric stringValues.push(TableOutput.toStringWithCommas(value)) } else { stringValues.push(value.toFixed(2)) } } this.renderBodyRow(stringValues) } } }
JavaScript
class IdGenerator { constructor(options) { this._generator = new FlakeId(options); if (options && options.worker) { shortid.worker(options.worker); } } /** * Generates a new big int ID. */ nextBigInt() { return bufferToBigInt(this._generator.next()); } /** * Generates a 7-character UID. */ nextShortId() { return shortid.generate(); } /** * Generates a version-4 UUID. */ nextUuidv4() { return uuidv4(); } // public wrapBigInt(value: string): Int64 // public wrapBigInt(buf: Buffer): Int64 // public wrapBigInt(value?: number): Int64 /** * Parses input value into bigint type. * @param value The value to be wrapped. If not given, the behavior is same with `next()`. */ wrapBigInt(value) { if (value == null) { return this.nextBigInt(); } switch (typeof value) { case 'bigint': return value; case 'string': case 'number': return BigInt(value); default: if (value instanceof Buffer) { return bufferToBigInt(value); } return BigInt(value); } } }
JavaScript
class CidrIpAddress { /** * Create a CidrIpAddress. * @member {string} [baseIpAddress] Ip adress itself. * @member {number} [prefixLength] The length of the prefix of the ip * address. */ constructor() { } /** * Defines the metadata of CidrIpAddress * * @returns {object} metadata of CidrIpAddress * */ mapper() { return { required: false, serializedName: 'cidrIpAddress', type: { name: 'Composite', className: 'CidrIpAddress', modelProperties: { baseIpAddress: { required: false, serializedName: 'baseIpAddress', type: { name: 'String' } }, prefixLength: { required: false, serializedName: 'prefixLength', type: { name: 'Number' } } } } }; } }
JavaScript
class StateList { /** * Store Fabric context for subsequent API access, and name of list */ constructor(ctx, listName) { this.ctx = ctx; this.name = listName; this.supportedClasses = {}; } /** * Add a state to the list. Creates a new state in worldstate with * appropriate composite key. Note that state defines its own key. * State object is serialized before writing. */ async addState(state, uuid) { // await this.ctx.stub.putState('<UUID HERE>', Buffer.from(JSON.stringify(state))); // let key = this.ctx.stub.createCompositeKey(this.name, state.getSplitKey()); let data = State.serialize(state); await this.ctx.stub.putState(uuid, data); } /** * Get a state from the list using supplied keys. Form composite * keys to retrieve state from world state. State data is deserialized * into JSON object before being returned. */ async getState(uuid) { const emissionasBytes = await this.ctx.stub.getState(uuid); // get the car from chaincode state if (!emissionasBytes || emissionasBytes.length === 0) { throw new Error(`${uuid} does not exist`); } console.log(emissionasBytes.toString()); return emissionasBytes.toString(); } async getAllStateByUtilityIdAndPartyId(queryData) { const allResults = []; let stringQuery = `{"selector": {"utilityId": "${queryData.utilityId}", "partyId": "${queryData.partyId}"}}`; const iterator = await this.ctx.stub.getQueryResult(stringQuery); let result = await iterator.next(); while (!result.done) { const strValue = Buffer.from(result.value.value.toString()).toString("utf8"); let record; try { record = JSON.parse(strValue); } catch (err) { console.log(err); record = strValue; } allResults.push({ Key: result.value.key, Record: record }); result = await iterator.next(); } return JSON.stringify(allResults); } async getAllState() { const allResults = []; let stringQuery = `{"selector": {}}`; const iterator = await this.ctx.stub.getQueryResult(stringQuery); let result = await iterator.next(); while (!result.done) { const strValue = Buffer.from(result.value.value.toString()).toString("utf8"); let record; try { record = JSON.parse(strValue); } catch (err) { console.log(err); record = strValue; } allResults.push({ Key: result.value.key, Record: record }); result = await iterator.next(); } return JSON.stringify(allResults); } /** * Update a state in the list. Puts the new state in world state with * appropriate composite key. Note that state defines its own key. * A state is serialized before writing. Logic is very similar to * addState() but kept separate becuase it is semantically distinct. */ async updateState(state, uuid) { // await this.ctx.stub.putState('<UUID HERE>', Buffer.from(JSON.stringify(state))); // let key = this.ctx.stub.createCompositeKey(this.name, state.getSplitKey()); let data = State.serialize(state); await this.ctx.stub.putState(uuid, data); } /** Stores the class for future deserialization */ use(stateClass) { this.supportedClasses[stateClass.getClass()] = stateClass; } }
JavaScript
class ProxyComponent extends Component { get config() { return Object.assign({ template: ({$component}) => { return h($component.getTargetElementTag(), { attrs: $component.getAttributes(), on: $component._getProxiedEventHandlers(), }); }, }, this.localConfig); } /** * Override this to extend the default configuration. * * @see Component#config */ get localConfig() { return {}; } /** * Override to determine which tag to instantiate as the child. * * This is where all switching logic should go. * * @returns {string} - tag name of the component to instantiate * * @example <caption>a URL based feature flag</caption> * class MyWidget extends ProxyComponent { * getTargetElementTag() { * if (window.location.search.includes('enable_beta') { * return 'my-widget-v2'; * } * * return 'my-widget-v1' * } * } */ getTargetElementTag() { throw new Error(`You must override getTargetElementTag().`); } _getProxiedEventHandlers() { const handler = this.proxyEventHandler.bind(this); return this.observedEvents.reduce((acc, ev) => { acc[ev] = handler; return acc; }, {}); } /** * Override this method to stop events from being bubbled through this element. * @param {Event} ev - event to check * @returns {boolean} whether event should bubble through * * @example <caption>filter specific events out</caption> * class MyWidget extends ProxyComponent { * allowEvent(ev) { * // don't propagate click events for the v2 component * return this.getTargetElementTag() !== `my-widget-v2` && ev.type !== `click`; * } * } */ allowEvent(ev) { // eslint-disable-line no-unused-vars return true; } // Proxied events will be stripped of their native attributes and re-wrapped as CustomEvents. Callers // should assume that only `detail` remains intact. proxyEventHandler(ev) { if (!this.allowEvent(ev)) { return false; } if (!ev.bubbles) { this.dispatchEvent(new CustomEvent(ev.type, ev)); } return true; } // Return a map of attributes to pass to the child. getAttributes() { const attributes = {}; for (let i = 0; i < this.attributes.length; i++) { const attr = this.attributes[i]; attributes[attr.name] = attr.value; } return attributes; } /** * Defines the names of events which will be emitted by the wrapped component. * Bubbling events will bubble through, but non-composed events from ShadowDOM * elements will not and will be re-dispatched from the proxy. * @type {string[]} */ get observedEvents() { return []; } }
JavaScript
class ClairvoyanceResult extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className={'row'}> <div className={'col-sm-6'}> <h4>Beste resultaat</h4> <ClairvoyanceResultMapper onSubmitValuesAsHint={this.props.onSubmitValuesAsHint} result={this.props.result.best} hints={this.props.hints}/> </div> <div className={'col-sm-6'}> <h4>Overige resultaten <span className="label label-default">{this.props.result.other.length}</span></h4> {this.props.result.other.map((result, i) => <ClairvoyanceResultMapper key={i} onSubmitValuesAsHint={this.props.onSubmitValuesAsHint} result={result} hints={this.props.hints} />)} </div> </div> ); } }
JavaScript
class Stopwatch extends Component { static propTypes = { classes: PropTypes.object.isRequired, } /** * state: * time: displayed time value (string) * active: whether it is running (boolean) * startTime: when the time was last started/resumed (int) * accTime: how much time has accumulated (int) */ state = { time: '00:00:00.000', active: false, startTime: 0, accTime: 0 } componentDidMount() { window.requestAnimationFrame(this.tick); } /** Update the display time value */ tick = () => { window.requestAnimationFrame(this.tick); // Get current ms running let ms = (new Date()).getTime(); if (!this.state.active) { ms = 0; } // Find total elapsed time and update time string const elapsed = ms - this.state.startTime + this.state.accTime; this.setState({ time: formatTime(elapsed), }); } /** Activate/deactivate the timer when the start/stop button is pressed */ handleStartAndStop = () => { this.setState((prevState) => { // Timer is stopped let newStartTime = (new Date()).getTime(); let newAccTime = prevState.accTime; if (prevState.active) { // Find out the elapsed time on the timer and stop the interval newAccTime = (new Date()).getTime() - prevState.startTime + prevState.accTime; newStartTime = 0; } // Toggle active state return { active: !prevState.active, startTime: newStartTime, accTime: newAccTime }; }); }; /** Clears all states */ handleClear = () => { this.setState({ active: false, startTime: 0, accTime: 0, }); } render() { const { classes } = this.props; const { active } = this.state; return ( <Grid container spacing={16} alignItems="center"> <Grid item xs={2}> <Typography variant="title" color="inherit">Mission Stopwatch</Typography> </Grid> <Grid item xs={2}> <Paper className={classes.paper}> <Typography>{this.state.time}</Typography> </Paper> </Grid> <Grid item xs={1}> <Button variant="raised" color="primary" className={classNames(classes.stopwatchTriggerButton, (active ? classes.stopButton : classes.startButton))} onClick={this.handleStartAndStop}> {this.state.active ? 'Stop' : 'Start'} </Button> </Grid> <Grid item xs={1}> <Button variant="raised" color="default" onClick={this.handleClear}> Clear </Button> </Grid> </Grid> ); } }
JavaScript
class ColorPicker extends Component { static propTypes = { readOnly: PropTypes.bool, current: PropTypes.number, onSelect: PropTypes.func, palette: PropTypes.string, }; static defaultProps = { current: 0, }; constructor(props) { super(props); this.palette = getPalette(props.palette); const paletteIndex = Number.isInteger(props.current) ? props.current : 0; this.state = { showContent: false, //hoverText: this.nameColor(this.props.current), hoverText: this.palette[paletteIndex].name, }; } componentWillReceiveProps(nextProps) { if (this.props.palette !== nextProps.palette) { this.palette = getPalette(nextProps.palette); } } onClickCurrent = () => { const handleDocumentClick = (evt) => { this.setState({ showContent: false }); document.removeEventListener('click', handleDocumentClick); }; if (this.state.showContent || this.props.readOnly) return; //dont register more than once document.addEventListener('click', handleDocumentClick); this.setState({ showContent: true }); }; onMouseEnter = (str) => { //this.setState({ hoverText: this.nameColor(hoverText) }); this.setState({ hoverText: str }); }; onMouseOut = () => { //this.setState({ hoverText: this.nameColor(this.props.current) }); this.setState({ hoverText: this.getColor(this.props.current).name }); }; getColor(index = 0) { if (!Number.isInteger(index) || index < 0) { console.warn('current index is not an index'); //eslint-disable-line no-console return this.palette[0]; } return this.palette[index]; } render() { const { current, readOnly, onSelect } = this.props; return ( <div className={`Picker ColorPicker${readOnly ? ' readOnly' : ''}`}> <div ref={(ref) => { this.pickerToggler = ref; }} className="Picker-current" onClick={this.onClickCurrent} > <PickerItem isCurrent={false} styles={{ backgroundColor: this.getColor(current).hex }} /> </div> {this.state.showContent && ( <div className="Picker-content" onMouseOut={this.onMouseOut} > <div className="Picker-currentHovered">{this.state.hoverText}</div> <div className="Picker-options"> {this.palette.map((obj, index) => (<PickerItem key={obj.hex} isCurrent={current === index} onMouseEnter={() => this.onMouseEnter(obj.name)} onClick={() => !readOnly && onSelect(index)} styles={{ backgroundColor: obj.hex }} />))} </div> </div> )} </div> ); } }
JavaScript
class IterableUtil extends UtilityClass { /** * Coerces an iterable-which-might-be-an-iterator into an iterable that is * presumed safe to use more than once. Specifically: * * * Normal iterables are returned as-is. * * If given an iterable which also appears to support the `Iterator` * protocol, returns a new iterable which is guaranteed to only iterate * using the originally-passed value once. The new iterable will only call * through to the original on an as-needed basis; that is, it doesn't just * collect the full iteration results up-front. * * **Context:** The values returned from built-in iteration methods such as * `Map.values()` and `Object.entries()` are both `Iterator`s and `Iterable`s, * but when used as an iterable, they are _not_ safe to use more than once. * So, code that generically accepts an iterable-in-general and expects to * iterate using it more than once needs to do _something_ to ensure that it * doesn't get undermined by this oddball behavior. This method is one way to * get the necessary protection. * * @param {Iterable} iterable The iterable to ensure safe multiple-use of. * @returns {Iterable} `iterable` itself, if safe, or a new instance if not. */ static multiUseSafe(iterable) { TIterable.check(iterable); if ((typeof iterable.next) !== 'function') { // It does not appear to be an `Iterator`. return iterable; } // It looks like an `Iterator`. Provide a safe replacement. const iterator = iterable; // Rename to indicate what it really is. const elements = []; let done = false; function* makeIterator() { // Yield any elements already collected from the original iterator. yield* elements; // Continue to iterate over the original iterator, until it's exhausted. let at = elements.length; for (;;) { // Yield elements that got appended by other simultaneously-active // iterators or by our own handling of `next()` below. while (at < elements.length) { yield elements[at]; at++; } if (done) { break; } // Append one more element to `elements`, or note that the iterator is // done if that turns out to be the case. const next = iterator.next(); if (next.done) { done = true; break; } else { elements.push(next.value); } } } return { [Symbol.iterator]: makeIterator }; } }
JavaScript
class TimeScaleIntervalChange extends PureComponent { constructor(props) { super(props); this.state = { toolTipHovered: false, customIntervalText: 'Custom', }; } componentDidMount() { const { customDelta, customInterval } = this.props; if (customDelta !== 1 && customInterval) { this.setCustomIntervalText(); } } componentDidUpdate(prevProps) { const { customDelta, timeScaleChangeUnit, customSelected, } = this.props; const { customIntervalText, } = this.state; const isCustomIntervalTextSet = customIntervalText !== 'Custom'; const defaultDelta = !customDelta || customDelta === 1; if (!customSelected && isCustomIntervalTextSet && (defaultDelta || !timeScaleChangeUnit)) { // reset from tour step change where previous step has custom interval and next step doesn't this.resetCustomIntervalText(); } else if (customSelected && customDelta && timeScaleChangeUnit) { const didCustomDeltaChange = customDelta !== prevProps.customDelta; const didTimeScaleChangeUnitChange = timeScaleChangeUnit !== prevProps.timeScaleChangeUnit; if (didCustomDeltaChange || didTimeScaleChangeUnitChange) { this.setCustomIntervalText(); } } } toolTipHoverOn = () => { this.setState({ toolTipHovered: true, }); } toolTipHoverOff = () => { this.setState({ toolTipHovered: false, }); } onClick = () => { const { toolTipHovered } = this.state; this.setState({ toolTipHovered: !toolTipHovered, }); } handleClickInterval = (timescale, openModal = false) => { // send props function to change timescale interval throughout app this.setState({ toolTipHovered: false, }, this.setTimeScaleIntervalChangeUnit(timescale, openModal)); } /** * @desc handle SELECT of LEFT/RIGHT interval selection * @param {String} timeScale * @param {Boolean} modalOpen - is custom interval modal open */ setTimeScaleIntervalChangeUnit = (timeScale, openModal) => { const { customInterval, customDelta, selectInterval, toggleCustomModal, modalType, } = this.props; const customSelected = timeScale === 'custom'; let delta; let newTimeScale = timeScale; if (openModal) { toggleCustomModal(openModal, modalType); return; } if (customSelected && customInterval && customDelta) { newTimeScale = customInterval; delta = customDelta; } else { newTimeScale = Number(timeScaleToNumberKey[newTimeScale]); delta = 1; } selectInterval(delta, newTimeScale, customSelected); }; // set custom text for custom interval setCustomIntervalText = () => { const { customDelta, customInterval } = this.props; this.setState({ customIntervalText: `${customDelta} ${timeScaleFromNumberKey[customInterval]}`, }); } // reset custom text for custom interval resetCustomIntervalText = () => { this.setState({ customIntervalText: 'Custom', }); } render() { const { customIntervalText, toolTipHovered, } = this.state; const { customSelected, hasSubdailyLayers, interval, } = this.props; return ( <> <div id="timeline-interval-btn-container" className="interval-btn-container noselect no-drag" onMouseEnter={this.toolTipHoverOn} onMouseLeave={this.toolTipHoverOff} onClick={this.onClick} > {/* timeScale display */} <span id="current-interval" className={`no-drag interval-btn interval-btn-active${customSelected ? ' custom-interval-text' : ''}`} > {customSelected ? customIntervalText : `${1} ${timeScaleFromNumberKey[interval]}`} </span> {/* hover timeScale unit dialog / entry point to Custom selector */} <div className="wv-tooltip" style={{ display: toolTipHovered ? 'block' : 'none' }} > <div id="timeline-interval" className="timeline-interval"> <span id="interval-years" className="interval-btn interval-years" onClick={() => this.handleClickInterval('year')} > Year </span> <span id="interval-months" className="interval-btn interval-months" onClick={() => this.handleClickInterval('month')} > Month </span> <span id="interval-days" className="interval-btn interval-days" onClick={() => this.handleClickInterval('day')} > Day </span> {hasSubdailyLayers ? ( <> <span id="interval-hours" className="interval-btn interval-hours" onClick={() => this.handleClickInterval('hour')} > Hour </span> <span id="interval-minutes" className="interval-btn interval-minutes" onClick={() => this.handleClickInterval('minute')} > Minute </span> </> ) : null} <span id="interval-custom" className="interval-btn interval-custom custom-interval-text" style={{ display: customIntervalText === 'Custom' ? 'none' : 'block' }} onClick={() => this.handleClickInterval('custom')} > {customIntervalText} </span> <span id="interval-custom-static" className="interval-btn interval-custom custom-interval-text" onClick={() => this.handleClickInterval('custom', true)} > Custom </span> </div> </div> </div> </> ); } }
JavaScript
class PrinterNode extends Node{ constructor(_env){ super(_env, PrinterNodeMetadata); //create the links this.lastPacket = undefined; this.reset(); } // this handler is called when the node receive a packet update(gateIdx, pkt){ this.lastPacket = pkt; //this.sendPacket(getOut, Packet, delay); this.sendPacket(1, pkt, 0); } // this handler is called at the start of the simulation init(){ this.lastPacket = undefined; } // should return the number of input/output link getNumberLinks(){ return 2; } // this handler is called when a collection is created or desctructed onLinkUpdate(idx){ } }
JavaScript
class GPrinterNode extends GNode{ constructor(_node){ super(_node); this.timer = 50; this.prePacket = undefined; } //draw function draw(cnv, ctx){ ctx.lineWidth = 1; ctx.strokeStyle = "black"; ctx.fillStyle = "rgb(220, 220, 220)"; ctx.beginPath(); ctx.rect(0, 0, this.size.x, this.size.y); ctx.stroke(); ctx.fill(); ctx.strokeStyle = "rgba(0, 0, 0, 0)"; ctx.fillStyle = "red"; if(this.prePacket != this.node.lastPacket){ ctx.beginPath(); ctx.arc(5, 5, 3, 0, 2 * Math.PI); ctx.stroke(); ctx.fill(); this.timer--; } if(this.timer == 0){ this.timer = 5; this.prePacket = this.node.lastPacket; } ctx.save(); ctx.beginPath(); ctx.rect(0, 0, this.size.x, this.size.y); ctx.clip(); if(this.node.lastPacket){ let i = 0; ctx.fillStyle = "black"; for(let o in this.node.lastPacket){ ctx.font = "10px Courier New"; ctx.fillText(o + ":" + this.node.lastPacket[o], 10, i * 20 + 20); i++; } } ctx.restore(); } //function to set the position of the pins of the node setPins(){ this.pins[0].position = new vec3(0, this.size.y * 0.5); this.pins[0].name = "in"; this.pins[0].nameLocation = [-1, 1]; this.pins[1].position = new vec3(this.size.x, this.size.y * 0.5); this.pins[1].name = "out"; this.pins[1].nameLocation = [1, 1]; } onParamChange(){ this.size = new vec3(this.node.params.width, this.node.params.height); } }
JavaScript
class ChunkedLinesGeometry extends LinesGeometry { constructor(chunksCount, segmentsCount, enableCollision) { super(chunksCount * segmentsCount); this._init(segmentsCount); this._collisionGeo = enableCollision ? new CylinderCollisionGeo(chunksCount * segmentsCount, 3) : null; } startUpdate() { return true; } computeBoundingSphere() { const collisionGeo = this._collisionGeo; if (collisionGeo) { collisionGeo.computeBoundingSphere(); this.boundingSphere = collisionGeo.boundingSphere; return; } super.computeBoundingSphere(); } computeBoundingBox() { const collisionGeo = this._collisionGeo; if (collisionGeo) { collisionGeo.computeBoundingBox(); this.boundingBox = collisionGeo.boundingBox; return; } super.computeBoundingBox(); } raycast(raycaster, intersects) { const collisionGeo = this._collisionGeo; if (!collisionGeo) { return; } const segCount = this._chunkSize; this._collisionGeo.raycast(raycaster, intersects); for (let i = 0, n = intersects.length; i < n; ++i) { let { chunkIdx } = intersects[i]; if (chunkIdx === undefined) { continue; } chunkIdx = (chunkIdx / segCount) | 0; intersects[i].chunkIdx = chunkIdx; } } setColor(chunkIdx, colorVal) { const chunkSize = this._chunkSize; for (let i = chunkIdx * chunkSize, end = i + chunkSize; i < end; ++i) { super.setColor(i, colorVal); } } setSegment(chunkIdx, segIdx, pos1, pos2) { const chunkSize = this._chunkSize; const idx = chunkIdx * chunkSize + segIdx; super.setSegment(idx, pos1, pos2); if (this._collisionGeo) { this._collisionGeo.setItem(chunkIdx * chunkSize + segIdx, pos1, pos2, COLLISION_RAD); } } finalize() { this.finishUpdate(); this.computeBoundingSphere(); } setOpacity(chunkIndices, value) { const chunkSize = this._chunkSize; for (let i = 0, n = chunkIndices.length; i < n; ++i) { const left = chunkIndices[i] * chunkSize; super.setOpacity(left, left + chunkSize - 1, value); } } getSubset(chunkIndices) { const instanceCount = chunkIndices.length; const chunkSize = this._chunkSize; const subset = new ChunkedLinesGeometry(instanceCount, chunkSize, false); for (let i = 0, n = chunkIndices.length; i < n; ++i) { const dstPtOffset = i * chunkSize; const startSegIdx = chunkIndices[i] * chunkSize; subset.setSegments(dstPtOffset, this.getSubsetSegments(startSegIdx, chunkSize)); subset.setColors(dstPtOffset, this.getSubsetColors(startSegIdx, chunkSize)); } subset.boundingSphere = this.boundingSphere; subset.boundingBox = this.boundingBox; return [subset]; } _init(chunkSize) { this._chunkSize = chunkSize; } }
JavaScript
class SettingsClaimActions { /** * This is started after pressing the button "Lookup Balances" * * @param {String} ownerKeyString * @returns {function(*=)} */ static lookupBalances(ownerKeyString) { return (dispatch) => { dispatch(resetBalancesDataAction()); //TODO::services try { let privateKey = PrivateKey.fromWif(ownerKeyString), publicKey = privateKey.toPublicKey().toPublicKeyString(), addresses = key.addresses(publicKey); BalanceRepository.getBalanceObjects(addresses).then( results => { if (!results.length) { dispatch(setKeyErrorAction({ claim_error: counterpart.translate("errors.no_balance_objects") })); return Promise.reject("No balance objects"); } let balance_ids = []; for(let balance of results) { balance_ids.push(balance.id); } dispatch(setPrivateKeyAction({ claim_privateKey: ownerKeyString })); return BalanceRepository.getVestedBalances(balance_ids).then( vested_balances => { let assetsPromises = []; let assetsIdsHash = Object.create(null); let balances = Immutable.List().withMutations( balance_list => { for(let i = 0; i < results.length; i++) { let balance = results[i]; if(balance.vesting_policy) { balance.vested_balance = vested_balances[i]; } balance.available_balance = vested_balances[i]; balance.public_key_string = publicKey; balance_list.push(Immutable.fromJS(balance)); if (!assetsIdsHash[balance.balance.asset_id]) { assetsIdsHash[balance.balance.asset_id] = true; assetsPromises.push(Repository.getAsset(balance.balance.asset_id)); } } }); return Promise.all([Promise.all(assetsPromises),balances]) }); }).then(([assets, balances]) => { let assetsHash = Object.create(null); assets.forEach((asset) => { assetsHash[asset.get('id')] = asset; }); balances = balances.map((balance) => { return balance.setIn(['balance', 'asset'], assetsHash[balance.getIn(['balance', 'asset_id'])]); }); Repository.getAccountRefsOfKey(publicKey).then((resultKeys) => { let ids = []; resultKeys.forEach((rKey) => { ids.push(rKey) }); if (ids.length) { let accountPromises = ids.map((id) => { return Repository.getAccount(id); }); Promise.all(accountPromises).then((accounts) => { let accountsNames = []; accounts.forEach((account) => { accountsNames.push(account.get('name')); }); balances = balances.map((balance) => { return balance.setIn(['accounts'], accountsNames); }); dispatch(setBalancesDataAction({ claim_balances: balances })); }); } else { dispatch(setBalancesDataAction({ claim_balances: balances })); } }); }); } catch (e) { console.error(e); dispatch(setKeyErrorAction({ claim_error: counterpart.translate("errors.paste_your_redemption_key_here")//e.message })); } } } /** * This is started after pressing the button "Import Balances" * * @returns {function(*=, *)} */ static importBalance() { return (dispatch, getState) => { return new Promise((resolve) => { let state = getState(); let balances = state.pageSettings.claim_balances; let account_name_or_id = state.app.accountId; let account_lookup = FetchChain("getAccount", account_name_or_id); let p = Promise.all([ account_lookup ]).then( (results)=> { let account = results[0]; if(!account) { return Promise.reject("Unknown account " + account_name_or_id); } let balance_claims = []; for(let balance of balances) { balance = balance.toJS(); let {vested_balance, public_key_string} = balance; let total_claimed; if( vested_balance ) { if(vested_balance.amount == 0) // recently claimed continue; total_claimed = vested_balance.amount; } else total_claimed = balance.balance.amount; //assert if(vested_balance && vested_balance.asset_id != balance.balance.asset_id) { throw new Error("Vested balance record and balance record asset_id missmatch", vested_balance.asset_id, balance.balance.asset_id ) } balance_claims.push({ fee: { amount: "0", asset_id: "1.3.0"}, deposit_to_account: account.get("id"), balance_to_claim: balance.id, balance_owner_key: public_key_string, total_claimed: { amount: total_claimed, asset_id: balance.balance.asset_id } }) } if( ! balance_claims.length) { throw new Error("No balances to claim") } return new Promise((resolve) => { KeysService.getActiveKeyFromState(state, dispatch).then(() => { TransactionService.importBalances(balance_claims, account.get("id"), state.pageSettings.claim_privateKey, () => { dispatch(resetBalancesDataAction()); resolve(); }).then((trFnc) => { dispatch(trFnc); }); }); }); }); resolve(p) }) } } static resetKey() { return resetBalancesDataAction(); } static resetBalances() { return resetBalancesAction(); } }
JavaScript
class DiscordRuntime { #configuration_ = null; #connection_ = null; #guilds_ = null; #manager_ = null; #userId_ = null; #userName_ = null; constructor(configuration, manager) { this.#configuration_ = configuration; this.#connection_ = new DiscordConnection(configuration, this); this.#guilds_ = new Map(); this.#manager_ = manager; } // --------------------------------------------------------------------------------------------- // Section: connection management // --------------------------------------------------------------------------------------------- // Returns whether the Discord connection is available for use at this time. isAvailable() { return this.#connection_.isConnected() && this.#connection_.isAuthenticated(); } // Initializes the connection to Discord when the necessary configuration has been given. This // call will be silently ignored when it's not, as it's entirely optional. connect() { if (this.#configuration_ === null || typeof this.#configuration_.token !== 'string') return; // the necessary configuration is missing, cannot continue this.#connection_.connect(); } // --------------------------------------------------------------------------------------------- // Called when a message of the given |intent| has been received from Discord. Not all messages // have to be handled. Messages will only be received when the connection is authenticated. onMessage(intent, data) { let guild = null; let member = null; let message = null; switch (intent) { case 'READY': this.#userId_ = data.user.id; this.#userName_ = data.user.username; break; // ------------------------------------------------------------------------------------- // Category: GUILD_* messages // ------------------------------------------------------------------------------------- case 'GUILD_CREATE': guild = new Guild(data, this.#userId_); console.log(`${guild.name} (Id: ${guild.id}):`); console.log(guild.members.size + ' members'); console.log(guild.roles.size + ' roles'); console.log(guild.channels.size + ' channels'); console.log(guild.bot + ' is our bot'); this.#guilds_.set(data.id, guild); break; case 'GUILD_MEMBER_UPDATE': guild = this.#guilds_.get(data.guild_id); member = guild.members.get(data.user.id); if (guild && member) { member.nickname = data.nick || data.user.username; member.roles.clear(); for (const roleId of data.roles) { const role = guild.roles.get(roleId); if (role) member.roles.add(role); } } break; // ------------------------------------------------------------------------------------- // Category: MESSAGE_* messages // ------------------------------------------------------------------------------------- case 'MESSAGE_CREATE': guild = this.#guilds_.get(data.guild_id); message = new Message(data, guild); this.#manager_.onMessage(message); break; // ------------------------------------------------------------------------------------- // Category: Presence messages // ------------------------------------------------------------------------------------- case 'PRESENCE_UPDATE': for (const guild of this.#guilds_.values()) { const member = guild.members.get(data.user.id); if (member) member.status = data.status; } break; // ------------------------------------------------------------------------------------- // Category: Ignored messages // ------------------------------------------------------------------------------------- case 'MESSAGE_DELETE': case 'TYPING_START': break; // ------------------------------------------------------------------------------------- default: console.log('Unhandled Discord message (' + intent + '):', data); break; } } // --------------------------------------------------------------------------------------------- dispose() { this.#connection_.dispose(); } }
JavaScript
class ArticleAdapter extends DocumentAdapter { _initialize() { const doc = this.doc const engine = this.engine // hack: monkey patching the instance to register a setter that updates this adapter _addAutorunFeature(doc, this) let model = engine.addDocument({ id: doc.id, name: this.name, lang: 'mini', cells: this._getCellNodes().map(_getCellData), autorun: doc.autorun, onCellRegister: mapCellState.bind(null, doc) }) this.model = model // TODO: do this somewhere else doc.autorun = false this.editorSession.on('update', this._onDocumentChange, this, { resource: 'document' }) this.engine.on('update', this._onEngineUpdate, this) } _getCellNodes() { return this.doc.findAll('cell') } /* Call on every document change detecting updates to cells that are used to keep the Engine's model in sync. */ _onDocumentChange(change) { const doc = this.doc const model = this.model // inspecting ops to detect structural changes and updates // Cell removals are applied directly to the engine model // while insertions are applied at the end // 1. removes, 2. creates, 3. updates, 3. creates let created, updated const ops = change.ops for (let i = 0; i < ops.length; i++) { const op = ops[i] switch (op.type) { case 'create': { let node = doc.get(op.path[0]) if (this._isCell(node)) { if (!created) created = new Set() created.add(node.id) } break } case 'delete': { // TODO: would be good to still have the node instance let nodeData = op.val if (this._isCell(nodeData)) { model.removeCell(nodeData.id) } break } case 'set': case 'update': { let node = doc.get(op.path[0]) // null if node is deleted within the same change if (!node) continue if (node.type === 'source-code') { node = node.parentNode } if (this._isCell(node)) { if (!updated) updated = new Set() updated.add(node.id) } break } default: throw new Error('Invalid state') } } if (created) { let cellNodes = this._getCellNodes() for (let i = 0; i < cellNodes.length; i++) { const cellNode = cellNodes[i] if (created.has(cellNode.id)) { model.insertCellAt(i, _getCellData(cellNode)) } } } if (updated) { updated.forEach(id => { const cell = this.doc.get(id) const cellData = { source: _getSource(cell), lang: _getLang(cell) } model.updateCell(id, cellData) }) } } /* Used internally to filter cells. */ _isCell(node) { return node.type === 'cell' } static connect(engine, editorSession, name) { return new ArticleAdapter(engine, editorSession, name) } }
JavaScript
class ServiceLocator { static fromServices(services) { const loc = new ServiceLocator(); Object.keys(services).forEach(serviceKey => { loc.register(serviceKey, services[serviceKey]); }); return loc; } constructor() { this._deps = new Map(); this._boundLookups = new Map(); } clearDependencyCache() { this._boundLookups = new Map(); } register(key, service, options = {}) { if (this._deps.has(key) && !options.allowOverwrite) { throw new Error(`Service key already used: ${toString(key)}`); } if (options.withParams && typeof service !== 'function') { throw new Error( `Cannot use "withParams" option with ${key} of type ${typeof service}; must be function or class.` ); } this._deps.set(key, { service, options }); } resolve(dependencies) { if (Array.isArray(dependencies)) { return dependencies.map(this._lookup); } else if (!!dependencies && typeof dependencies === 'object') { return Object.entries(dependencies).reduce((result, [key, name]) => { result[name] = this._lookup(key); return result; }, {}); } else { throw new Error( `Unsupported dependency list. Only Arrays and Objects are supported. Got: ${JSON.stringify( dependencies )}` ); } } _lookup = key => { assertInDev( this._deps.has(key), `Expected a service matching key: ${toString(key)}` ); const { service, options } = this._deps.get(key); if (options.withParams) { if (!this._boundLookups.has(key)) { const args = this._makeDepArgs(options); const boundFn = bindArgsAndMaintainStatics(service, args); this._boundLookups.set(key, boundFn); } const boundService = this._boundLookups.get(key); if (options.asInstance) { return new boundService(); } return boundService; } if (options.asInstance) { return new service(); } return service; }; _makeDepArgs = options => { if (Array.isArray(options.withParams)) { return options.withParams.map(param => { if (typeof param === 'object' && param[lookupSymbol] != null) { return this._lookup(param[lookupSymbol]); } else { return param; } }); } return []; }; }
JavaScript
class jobInputs extends events.EventEmitter { /* Constructor can receive a map w/ two types of value Should be SYNC-like */ constructor(data /*, skip?:boolean*/) { super(); this.streams = {}; this.paths = {}; this.hashes = {}; this.hashable = false; let safeNameInput = true; if (!data) return; let buffer = {}; // Coherce array in litteral, autogenerate keys if (data.constructor === Array) { safeNameInput = false; let a = data; for (let e of a.entries()) buffer[`file${e[0]}`] = e[1]; } else { buffer = data; } if (!cType.isStreamOrStringMap(buffer)) throw (`Wrong format for ${util.format(buffer)}`); let nTotal = Object.keys(buffer).length; logger_js_1.logger.debug(`jobInput constructed w/ ${nTotal} items:\n${util.format(buffer)}`); let self = this; for (let key in data) { if (isStream(buffer[key])) this.streams[key] = buffer[key]; else { try { //if (!safeNameInput) throw('file naming is unsafe'); let datum = buffer[key]; fs.lstatSync(datum).isFile(); let k = path.basename(datum).replace(/\.[^/.]+$/, ""); k = key; // GL Aug2018, HOTFIX from taskobject, maybe will break JM -- MS side let'see this.streams[k] = fs.createReadStream(datum); logger_js_1.logger.debug(`${buffer[key]} is a file, stream assigned to ${k}`); } catch (e) { logger_js_1.logger.warn(`Provided input named ${key} is not a file, assuming a string`); // Handle error if (e.code == 'ENOENT') { //no such file or directory //do something } else { //do something else } this.streams[key] = new streamLib.Readable(); this.streams[key].push(buffer[key]); this.streams[key].push(null); // this.streams[key].on('data',(e)=>{ logger.error(`${e.toString()}`); }); // Following block works as intended /* let toto:any = new streamLib.Readable(); toto.push(<string>buffer[key]); toto.push(null); toto.on('data',(e)=>{ logger.error(`${e.toString()}`); });*/ // } } this.streams[key].on('error', (e) => { self.emit('streamReadError', e); }); } } // Access from client side to wrap in socketIO getStreamsMap() { if (this.hashable) { logger_js_1.logger.warn('All streams were consumed'); return undefined; } return this.streams; } hash() { if (!this.hashable) { logger_js_1.logger.warn('Trying to get hash of inputs before write it to files'); return undefined; } return this.hashes; } write(location) { /*let iteratee = function(string:symbol,stream:streamLib.Readable){ let target = fs.createWriteStream(`${location}/${symbol}.inp`); stream.pipe(target);//.on('finish', function () { ... }); }*/ let self = this; let inputs = []; Object.keys(this.streams).forEach((k) => { let tuple = [k, self.streams[k]]; inputs.push(tuple); }); let promises = inputs.map(function (tuple) { return new Promise(function (resolve, reject) { fs.stat(location, (err, stats) => { if (err) { logger_js_1.logger.error("Wrong filr path :: " + err); reject('path error'); return; } let path = `${location}/${tuple[0]}.inp`; let target = fs.createWriteStream(path); target.on('error', (msg) => { logger_js_1.logger.error('Failed to open write stream'); reject('createWriteStreamError'); }); //logger.info(`opening ${path} success`); tuple[1].pipe(target); target .on('data', (d) => { console.log(d); }) .on('close', () => { // the file you want to get the hash let fd = fs.createReadStream(path); fd.on('error', () => { logger_js_1.logger.error(`Can't open for reading ${path}`); }); let hash = crypto.createHash('sha1'); hash.setEncoding('hex'); // fd.on('error',()=>{logger.error('KIN')}); fd.on('end', function () { hash.end(); let sum = hash.read().toString(); self.hashes[tuple[0]] = sum; // the desired sha1sum self.paths[tuple[0]] = path; // the path to file resolve([tuple[0], path, sum]); //. }); // read all file and pipe it (write it) to the hash object fd.pipe(hash); }); }); }); }); // WE SHOULD HANDLE STREAM WRITE ERROR REJECTION AND PROPAGATE IT FOR // owner JOB to be set in error status // BUT FIFO mess seems fixed so we'll see later, sorry Promise.all(promises).then(values => { self.hashable = true; //logger.error(`${values}`); self.emit('OK', values); }, reason => { console.log(reason); }); return this; } }
JavaScript
class jobProxy extends events.EventEmitter { constructor(jobOpt, uuid) { super(); this.exportVar = {}; this.modules = []; this.hasShimmerings = []; this.id = uuid ? uuid : uuidv4(); if ('modules' in jobOpt) this.modules = jobOpt.modules; if ('jobProfile' in jobOpt) this.jobProfile = jobOpt.jobProfile; if ('script' in jobOpt) this.script = jobOpt.script; if ('tagTask' in jobOpt) this.tagTask = jobOpt.tagTask; if ('namespace' in jobOpt) this.namespace = jobOpt.namespace; if ('socket' in jobOpt) this.socket = jobOpt.socket; if ('exportVar' in jobOpt) this.exportVar = jobOpt.exportVar; this.inputs = new jobInputs(jobOpt.inputs); } // 2ways Forwarding event to consumer or publicMS // WARNING wont work with streams jEmit(eName, ...args) { logger_js_1.logger.silly(`jEmit(this) ${String(eName)}`); this.hasShimmerings.forEach((shimJob) => { shimJob.jEmit(eName, ...args); }); // We call the original emitter anyhow //logger.debug(`${eName} --> ${util.format(args)}`); //this.emit.apply(this, eName, args); //this.emit.apply(this, [eName, ...args]) if (eName !== 'completed') { this.emit(eName, ...args); // Boiler-plate to emit conform completed event // if the consumer is in the same MS as the JM. } else if (this instanceof jobObject) { let stdout, stderr; if (this.isShimmeringOf) { stderr = this.isShimmeringOf.stderr(); stdout = this.isShimmeringOf.stdout(); } else { stderr = this.stderr(); stdout = this.stdout(); } Promise.all([stdout, stderr]).then((results) => { logger_js_1.logger.silly("Emitting completed event"); this.emit('completed', ...results); }); } //return true; // if a socket is registred we serialize objects if needed, then // pass it to socket //If it exists, // arguments are tricky (ie: streams), we socketPull // otherwise, we JSON.stringify arguments and emit them on socket if (this.socket) { // logger.warn(`jEmitToSocket ${eName}`); if (eName === 'completed') { //logger.debug(`SSP::\n${util.format(args)}`); //socketPull(...args);//eventName, jobObject let sArgs = [this, undefined, undefined]; if (this.isShimmeringOf) sArgs = [this, this.isShimmeringOf.stdout(), this.isShimmeringOf.stderr()]; job_manager_server_1.socketPull(...sArgs); return true; } // Easy to serialize content let _args = args.map((e) => { return JSON.stringify(e); // Primitive OR }); logger_js_1.logger.silly(`socket emiting event ${String(eName)}`); this.socket.emit(eName, ..._args); } return true; } }
JavaScript
class DirectorySuggestion extends mixinBehaviors([I18nBehavior, FormatBehavior, IronFormElementBehavior, IronValidatableBehavior], Nuxeo.Element) { static get template() { return html` <style> :host { display: block; } :host([hidden]) { display: none; } </style> <nuxeo-selectivity id="s2" operation="[[operation]]" label="[[label]]" min-chars="[[minChars]]" frequency="[[frequency]]" multiple="[[multiple]]" params="[[_computeParams(params.*, directoryName, dbl10n)]]" placeholder="[[placeholder]]" error-message="[[errorMessage]]" readonly="[[readonly]]" value="{{value}}" selected-items="{{selectedItems}}" selected-item="{{selectedItem}}" selection-formatter="[[selectionFormatter]]" required="[[required]]" invalid="[[invalid]]" resolve-entry="[[resolveEntry]]" stay-open-on-select="[[stayOpenOnSelect]]" id-function="[[idFunction]]" query-results-filter="[[queryResultsFilter]]"> </nuxeo-selectivity> `; } static get is() { return 'nuxeo-directory-suggestion'; } static get properties() { return { /** * Name of the directory. */ directoryName: { type: String, }, /** * Checking this option means that the labels are localized with translations provided * in the directory itself (i.e. in fields). Otherwise labels are translated as usual * picking values in messages*.properties files. */ dbl10n: { type: Boolean, value: false }, /** * Label. */ label: String, /** * In case of hierarchical vocabulary, if true, parent item can be selected. */ canSelectParent: Boolean, /** * Operation to call for suggestions. */ operation: { type: String, value: 'Directory.SuggestEntries', }, /** * Parameters for the operation. */ params: Object, /** * Selected value(s). */ value: { type: String, notify: true, }, /** * Set to `true` to allow multiple selection. */ multiple: { type: Boolean, value: false, }, /** * If true, the dropdown stays open after a selection is made. */ stayOpenOnSelect: { type: Boolean, value: false, }, /** * Set to `true` for read only mode. */ readonly: { type: Boolean, value: false, }, /** * Function used to get the id from the choice object. */ idFunction: { type: Function, value() { return this._idFunction.bind(this); }, }, /** * Minimum number of chars to trigger the suggestions. */ minChars: { type: Number, value: 3, }, /** * Time in ms used to debounce requests. */ frequency: Number, /** * Placeholder. */ placeholder: String, /** * Error message to show when `invalid` is true. */ errorMessage: String, /** * Selected items. */ selectedItems: { type: Array, notify: true, }, /** * Selected item. */ selectedItem: { type: Object, notify: true, }, /** * Formatter for a selected entry. */ selectionFormatter: { type: Function, value() { return this._selectionFormatter.bind(this); }, }, /** * Separator used for hierachical vocabulary entry's label. */ separator: { type: String, value: '/', }, /** * Function that transforms the entries added using the value property into object */ resolveEntry: { type: Function, value() { return this._resolveEntry.bind(this); }, }, /** * Results filtering function (optional). */ queryResultsFilter: Function, }; } /* Override method from Polymer.IronValidatableBehavior. */ _getValidity() { return this.$.s2._getValidity(); } _computeParams() { return Object.assign({}, { directoryName: this.directoryName, dbl10n: this.dbl10n, canSelectParent: this.canSelectParent, localize: true, lang: (window.nuxeo.I18n.language) ? window.nuxeo.I18n.language.split('-')[0] : 'en', }, this.params); } _selectionFormatter(entry) { return entry.absoluteLabel || entry.displayLabel; } _resolveEntry(entry) { if (entry && entry['entity-type'] && entry['entity-type'] === 'directoryEntry') { if (entry.properties) { return { id: entry.properties.id, displayLabel: this.formatDirectory(entry, this.separator), }; } } return { id: entry, displayLabel: entry, }; } _idFunction(item) { return item.computedId || item.id || item.uid; } }
JavaScript
class Scanner { constructor(text, patternMatches) { this.text = text; this.patternMatches = patternMatches; } /** * Does 4 things. * Creates a string literal for all the characters between the tokens * Takes all tokens queued for BEFORE this index and adds them to tokens. * Inserts the last token assigned AT this index and replaces the character in the string. * Takes all tokens queued for AFTER this index and adds them to tokens. */ scan() { let tokens = []; let tokenAt; let offsets = this.patternMatches.getOffsets(); let count; let start; let end; let literal; let before; let after; let at; let lineParser = newLineParser(this.text); // add the beginning and end of string to the offsets the text literal substrings are based on if (offsets[0] !== 0) offsets.unshift(0); if (offsets[offsets.length - 1] !== this.text.length) offsets.push(this.text.length); // process index one greater because there may be tokens that need to be processed // before the end of the string count = offsets.length + 1; while (count--) { tokenAt = null; start = start || offsets.shift(); let literalStart = start; let lineNumber; end = offsets.shift(); // todo: replace before/at/after with insert/replace before = this.patternMatches.on('before', start); after = this.patternMatches.on('after', start); at = this.patternMatches.on('at', start); // todo: remove line number if no longer needed lineNumber = lineParser(getCharIndexFromTokens(before, at, after)); if (at && at.length) { tokenAt = at[at.length - 1]; literalStart += getTokenLength(tokenAt); } if (before && before.length) tokens.push(...appendLineData(before, lineNumber)); if (tokenAt) tokens.push(...appendLineData([tokenAt], lineNumber)); if (literalStart < this.text.length && literalStart < end) { // there are no literals after the end of the string. literal = newLiteral(this.text.substring(literalStart, end), literalStart); tokens.push(...appendLineData([literal], lineParser(literal.index))); } // if (after && after.length) tokens.push(...appendLineData(after, lineNumber)); start = end; } return tokens; } }
JavaScript
class ProofLine { /** * @param {Array.number} dependencies - assumption dependencies * @param {Number} lineNum - line number * @param {string} proposition - proposition result from assumption or inference rule * @param {string} rule - rule used (or assumption) * @param {Array.number} ruleDependencies - line numbers that given inference rule depends on */ constructor(dependencies, lineNum, proposition, rule, ruleDependencies) { this.dependencies = dependencies; this.lineNum = lineNum; this.proposition = proposition; this.rule = rule; this.ruleDependencies = ruleDependencies; } //getters getDependencies() { return this.dependencies; } getLineNum() { return this.lineNum; } getProposition() { return this.proposition; } getRule() { return this.rule; } getRuleDependencies() { return this.ruleDependencies; } /** * @return {string} - proof line as a string */ getLineAsString() { if(this.rule === "assume"){ return this.dependencies + " " + "(" + this.lineNum.toString() + ")" + " " + this.proposition + " " + this.rule; } return this.dependencies + " " + "(" + this.lineNum.toString() + ")" + " " + this.proposition + " " + this.rule + " " + this.ruleDependencies; } }
JavaScript
class HashTable { constructor(size) { //create a map of buckets with the size this.size = size; this.map = new Array(size) } // hash() method that will take a key value and transform it into an index. hash(key) { let hash = key.split('').reduce((acc, char) => { return acc + char.charCodeAt(0); }, 0) * 677 % this.size; // console.log(hash); // return the index for the key return hash } // add method with Arguments: key, value add(key, value) { // index for the key let hash = this.hash(key); // check if there is a linked list at the hashed index, if not add a new linkedlist if (!this.map[hash]) { this.map[hash] = new LinkedList(); } // add the key and the value to the buckets and use linkedList insert let addBucket = { [key]: value }; this.map[hash].insert(addBucket); } // get method with Arguments: key to get the value for that key get(key) { // index for the key let hash = this.hash(key); // check if the key is in the map buckets if (!this.map[hash]) { return null }; // the first value in the linkedlist for the key and return the value let current = this.map[hash].head; if (current.value[key]) { return current.value[key] }; // while loop for the next value in the linkedlist if 2 values have the same hashed key[index] while (current.next) { current = current.next; if (current.value[key]) { return current.value[key] }; } } // contains method with Arguments: key to check if that key in the hash table contains(key) { let hash = this.hash(key); if (!this.map[hash]) { return false; } let current = this.map[hash].head; while (current) { if (current.value[key]) { return true; } current = current.next; } return false; } }
JavaScript
class PostDocLoadResourceObserver extends InstrumentationBase { constructor(config = {}) { super(MODULE_NAME, version, Object.assign({}, {allowedInitiatorTypes: defaultAllowedInitiatorTypes}, config)); this.observer = undefined; } init() {} _startObserver() { this.observer = new PerformanceObserver( (list) => { if (window.document.readyState === 'complete') { list.getEntries().forEach( entry => { if (this._config.allowedInitiatorTypes.includes(entry.initiatorType)) { this._createSpan(entry); } }); } }); //apparently safari 13.1 only supports entryTypes this.observer.observe({entryTypes: ['resource']}); } _createSpan(entry) { if (isUrlIgnored(entry.name, this._config.ignoreUrls)) { return; } const span = this._tracer.startSpan( //TODO use @opentelemetry/instrumentation-document-load AttributeNames.RESOURCE_FETCH ?, // AttributeNames not exported currently 'resourceFetch', { startTime: hrTime(entry.fetchStart), } ); span.setAttribute('component', MODULE_NAME); span.setAttribute(HttpAttribute.HTTP_URL, entry.name); addSpanNetworkEvents(span, entry); //TODO look for server-timings? captureTraceParentFromPerformanceEntries(entry) const resEnd = entry['responseEnd']; if (resEnd && resEnd > 0) { span.end(resEnd); } else { span.end(); } } enable() { if (window.PerformanceObserver) { window.addEventListener('load', () => { this._startObserver(); }); } } disable() { if (this.observer) { this.observer.disconnect(); } } }
JavaScript
class DownloadResult { /** * The url of the audio resource * @type {string|null} */ url = null; /** * AudioBuffer or Html5Audio element * @type {AudioBuffer|Audio} */ value = null; /** * Download error * @type {any} */ error = null; /** * Success or failure status of download. * @type {DownloadStatus} */ status = null; /** * @param {string|null} url The url of the audio resource * @param {AudioBuffer|Audio} [value] AudioBuffer or Html5Audio element * @param {*} [error] Download error */ constructor(url, value, error) { this.url = url; this.value = value; this.error = error || null; this.status = error ? DownloadStatus.Failure : DownloadStatus.Success; } }
JavaScript
class M5AtomLite extends Esp32Pico_1.Esp32Pico { constructor() { super(...arguments); this._name = "m5atom-lite"; // add device events onmethod this.onbutton = () => { }; } addDeviceMessageHandlers(messageHandlers) { messageHandlers.push({ name: "button", listener: () => this.onbutton() }); } async drawpix(number, color) { // const regexp = /^#([0-9a-fA-F]{3}|[0-9a-fA-number: numberF]{6})$/ // TODO: おいおい実装したら↓と切り替え const regexp = /^#([0-9a-fA-F]{6})$/; if (!regexp.test(color)) return false; return Boolean(await super.exec("drawpix", number, color)); } }
JavaScript
class ServiceClient { constructor(tokenHeaderIdentifier, tokenHeaderOrStrOrBaseClient, baseServer, port, defaultHeaders = {}) { if (isBaseHTTPClient(tokenHeaderOrStrOrBaseClient)) { // we are using a base client this.c = new HTTPClient(tokenHeaderOrStrOrBaseClient); } else { // Accept token header as string or object // - workaround to allow backwards compatibility for multiple headers let tokenHeader; if (typeof tokenHeaderOrStrOrBaseClient === 'string') { tokenHeader = convertTokenStringToTokenHeader(tokenHeaderOrStrOrBaseClient, tokenHeaderIdentifier); } else { tokenHeader = tokenHeaderOrStrOrBaseClient; } this.c = new HTTPClient(tokenHeader, baseServer, port, defaultHeaders); } this.intDecoding = IntDecoding.DEFAULT; } /** * Set the default int decoding method for all JSON requests this client creates. * @param method - \{"default" | "safe" | "mixed" | "bigint"\} method The method to use when parsing the * response for request. Must be one of "default", "safe", "mixed", or "bigint". See * JSONRequest.setIntDecoding for more details about what each method does. */ setIntEncoding(method) { this.intDecoding = method; } /** * Get the default int decoding method for all JSON requests this client creates. */ getIntEncoding() { return this.intDecoding; } }
JavaScript
class Ray{ constructor(pos, angle){ // pos = (x, y) this.pos = pos; // Make a new vector(x,y) from an angle 0-360 this.dir = p5.Vector.fromAngle(angle); } //TODO setAngle(angle){ this.dir = p5.Vector.fromAngle(angle); } // Testing function to make sure the ray was rendering lookAt(x, y){ this.dir.x = x - this.pos.x; this.dir.y = y - this.pos.y; this.dir.normalize(); } //Show the ray will be called by the particle show(){ stroke(255); push(); translate(this.pos.x, this.pos.y); line(0, 0, this.dir.x * 10, this.dir.y * 10); pop(); } //Wall has 2 points. cast(wall){ //find the wall lines const x1 = wall.a.x; const y1 = wall.a.y; const x2 = wall.b.x; const y2 = wall.b.y; // Get this ray's line positions const x3 = this.pos.x; const y3 = this.pos.y; const x4 = this.pos.x + this.dir.x; const y4 = this.pos.y + this.dir.y; //both x,y have the same denominator const den = (x1-x2) * (y3-y4) - (y1-y2) * (x3-x4); if(den == 0){ return; } //Need to find t and u to see if the line will be cast const t = ((x1-x3) * (y3-y4) - (y1-y3) * (x3-x4)) / den; const u = -((x1-x2) * (y1-y3) - (y1-y2) * (x1-x4)) / den; //check to see if 0 < t < 1 and u > 0 // if true cast the line if( t > 0 && t < 1 && u > 0){ const pt = createVector(); pt.x = x1 + t * (x2 - x1); pt.y = y1 + t * (y2 - y1); return pt; } else{ return; } } }
JavaScript
class LoginScreen extends Component { constructor(props){ super(props); this.state = { email:"", password:"" }; } static navigationOptions = { headerShown: false } // To accept the login with the credentials present in the database. // If user not signed up, throw an exception LogIn = (email,password) => { //Firebase's signInWithEmailAndPassword function for signing in existing user try { firebase.auth() .signInWithEmailAndPassword(email,password) .then(res => {console.log(res.user.email); this.props.navigation.navigate('WelcomeScreen');}); } catch (error) { console.log(error.toString(error)); } } // Render the UI render(){ return ( <View style={styles.container}> <Image style={styles.logo} source={require("../assets/Splitup.jpg")}/> <View style={styles.inputView}> <TextInput style={styles.inputText} placeholder="Email..." placeholderTextColor="#003f5c" onChangeText={email => this.setState({email})} /> </View> <View style={styles.inputView}> <TextInput secureTextEntry={true} style={styles.inputText} placeholder="Password..." placeholderTextColor="#003f5c" onChangeText={password => this.setState({password})}/> </View> <TouchableOpacity> <Text style={styles.forgot}>Forgot Password?</Text> </TouchableOpacity> <TouchableOpacity style={styles.loginBtn} onPress={() => this.LogIn(this.state.email,this.state.password)} > <Text style={{color:"white"}}>LOGIN</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.props.navigation.navigate('SignupScreen')} > <Text style={{color:"darkslateblue"}}>SIGNUP</Text> </TouchableOpacity> </View> ); } }
JavaScript
class Transactions { constructor ({ httpClient }) { this.url = '/transactions'; this.__httpClient = httpClient; /** * @type {AsyncTransaction} */ this.async = new AsyncTransaction({ httpClient }); /** * @type {SyncTransaction} */ this.sync = new SyncTransaction({ httpClient }); } /** * Get all the transactions. * @param {Object} options - The parameters to provider the API. * @param {Object} [options.params] - The query params for the API. * @link https://dvs-api-doc.dtone.com/#tag/Transactions/paths/~1transactions/get * @returns {AsyncIterator.<DVSAPIResponse>} */ get ({ params }) { return this.__httpClient.getWithPages({ params, url: this.url }); } /** * Get a transaction by ID. * @param {Object} options - The parameters to provider the API. * @param {number} [options.transactionId] - The transaction ID. * @link https://dvs-api-doc.dtone.com/#tag/Transactions/paths/~1transactions~1{transaction_id}/get * @returns {Promise.<DVSAPIResponse>} */ async getByTransactionId ({ transactionId }) { const url = `${this.url}/${transactionId}`; return this.__httpClient.get({ url }); } /** * Cancel a transaction * @param {Object} options - The parameters to provider the API. * @param {number} [options.transactionId] - The transaction ID. * @link https://dvs-api-doc.dtone.com/#tag/Transactions/paths/~1transactions~1{transaction_id}~1cancel/post * @returns {Promise.<DVSAPIResponse>} */ async cancel ({ transactionId }) { const url = `${this.url}/${transactionId}/cancel`; return this.__httpClient.post({ url }); } }
JavaScript
class CombatSidebarDw { // This must be called in the `init` hook in order for the other hooks to // fire correctly. startup() { // CONFIG.debug.hooks = true; // Add support for damage rolls via event delegation. Hooks.on('ready', () => { // Damage rolls from the combat tracker. $('body').on('click', '.dw-rollable', (event) => { let $self = $(event.currentTarget); let $actorElem = $self.parents('.actor-elem'); let combatant_id = $actorElem.length > 0 ? $actorElem.attr('data-combatant-id') : null; if (combatant_id) { let combatant = game.combat.combatants.find(c => c._id == combatant_id); let actor = combatant.actor ? combatant.actor : null; if (actor) { actor._onRoll(event, actor); } } }); }); // Re-render combat when actors are modified. Hooks.on('updateActor', (actor, data, options, id) => { ui.combat.render(); }); Hooks.on('updateToken', (scene, token, data, options, id) => { ui.combat.render(); }); // Update the move counter if a player made a move. Requires a GM account // to be logged in currently for the socket to work. If GM account is the // one that made the move, that happens directly in the actor update. game.socket.on('system.dungeonworld', (data) => { if (!game.user.isGM) { return; } if (data.combatantUpdate) { game.combat.updateCombatant(data.combatantUpdate); ui.combat.render(); } }); // Pre-roll initiative for new combatants. Because DW doesn't use // initiative, set them in increments of 10. However, the system still has // initiative formula using a d20, in case the reroll initiative button // is used. Hooks.on('preCreateCombatant', (combat, combatant, options, id) => { if (!combatant.initiative) { let highestInit = 0; let token = canvas.tokens.get(combatant.tokenId); let actorType = token.actor ? token.actor.data.type : 'character'; // Iterate over actors of this type and update the initiative of this // actor based on that. combat.combatants.filter(c => c.actor.data.type == actorType).forEach(c => { let init = Number(c.initiative); if (init >= highestInit) { highestInit = init + 10; } }); // Update this combatant. combatant.initiative = highestInit; } }); // TODO: Replace this hack that triggers an extra render. Hooks.on('renderSidebar', (app, html, options) => { ui.combat.render(); }); // When the combat tracker is rendered, we need to completely replace // its HTML with a custom version. Hooks.on('renderCombatTracker', async (app, html, options) => { // Find the combat element, which is where combatants are stored. let newHtml = html.find('#combat'); if (newHtml.length < 1) { newHtml = html; } // If there's as combat, we can proceed. if (game.combat) { // Retrieve a list of the combatants grouped by actor type and sorted // by their initiative count. let combatants = this.getCombatantsData(); // Add a counter for the total number of moves all characters have made. let moveTotal = 0; if (combatants.character) { combatants.character.forEach(c => { moveTotal = c.flags.dungeonworld ? moveTotal + Number(c.flags.dungeonworld.moveCount) : moveTotal; }); } // Get the custom template. let template = 'systems/dungeonworld/templates/combat/combat.html'; let templateData = { combatants: combatants, moveTotal: moveTotal }; // Render the template and update the markup with our new version. let content = await renderTemplate(template, templateData) newHtml.find('#combat-tracker').remove(); newHtml.find('#combat-round').after(content); // Add an event listener for input fields. This is currently only // used for updating HP on actors. newHtml.find('.ct-item input').change(event => { event.preventDefault(); // Get the incput and actor element. const dataset = event.currentTarget.dataset; let $input = $(event.currentTarget); let $actorRow = $input.parents('.directory-item.actor-elem'); // If there isn't an actor element, don't proceed. if (!$actorRow.length > 0) { return; } // Retrieve the combatant for this actor, or exit if not valid. const combatant = game.combat.combatants.find(c => c._id == $actorRow.data('combatant-id')); if (!combatant) { return; } const actor = combatant.actor; // Check for bad numbers, otherwise convert into a Number type. let value = $input.val(); if (dataset.dtype == 'Number') { value = Number(value); if (Number.isNaN(value)) { $input.val(actor.data.data.attributes.hp.value); return false; } } // Prepare update data for the actor. let updateData = {}; // If this started with a "+" or "-", handle it as a relative change. let operation = $input.val().match(/^\+|\-/g); if (operation) { updateData[$input.attr('name')] = Number(actor.data.data.attributes.hp.value) + value; } // Otherwise, set it absolutely. else { updateData[$input.attr('name')] = value; } // Update the actor. actor.update(updateData); return; }); // Drag handler for the combat tracker. if (game.user.isGM) { newHtml.find('.directory-item.actor-elem') .attr('draggable', true).addClass('draggable') // Initiate the drag event. .on('dragstart', (event) => { // Set the drag data for later usage. let dragData = event.currentTarget.dataset; event.originalEvent.dataTransfer.setData('text/plain', JSON.stringify(dragData)); // Store the combatant type for reference. We have to do this // because dragover doesn't have access to the drag data, so we // store it as a new type entry that can be split later. let newCombatant = game.combat.combatants.find(c => c._id == dragData.combatantId); event.originalEvent.dataTransfer.setData(`newtype--${dragData.actorType}`, ''); }) // Add a class on hover, if the actor types match. .on('dragover', (event) => { // Get the drop target. let $self = $(event.originalEvent.target); let $dropTarget = $self.parents('.directory-item'); // Exit early if we don't need to make any changes. if ($dropTarget.hasClass('drop-hover')) { return; } if (!$dropTarget.data('combatant-id')) { return; } // Retrieve the actor type for the drop target, exit early if // it doesn't exist. let oldType = $dropTarget.data('actor-type'); let newType = null; if (!oldType) { return; } // Retrieve the actor type for the actor being dragged. newType = event.originalEvent.dataTransfer.types.find(t => t.includes('newtype')); newType = newType ? newType.split('--')[1] : null; // If the type matches, add a css class to let the user know this // is a valid drop target. if (newType == oldType) { $dropTarget.addClass('drop-hover'); } // Otherwise, we should exit. else { return false; } return false; }) // Remove the class on drag leave. .on('dragleave', (event) => { // Get the drop target and remove any hover classes on it when // the mouse leaves it. let $self = $(event.originalEvent.target); let $dropTarget = $self.parents('.directory-item'); $dropTarget.removeClass('drop-hover'); return false; }) // Update initiative on drop. .on('drop', async (event) => { // Retrieve the default encounter. let combat = game.combat; // TODO: This is how foundry.js retrieves the combat in certain // scenarios, so I'm leaving it here as a comment in case this // needs to be refactored. // --------------------------------------------------------------- // const view = game.scenes.viewed; // const combats = view ? game.combats.entities.filter(c => c.data.scene === view._id) : []; // let combat = combats.length ? combats.find(c => c.data.active) || combats[0] : null; // Retreive the drop target, remove any hover classes. let $self = $(event.originalEvent.target); let $dropTarget = $self.parents('.directory-item'); $dropTarget.removeClass('drop-hover'); // Attempt to retrieve and parse the data transfer from the drag. let data; try { data = JSON.parse(event.originalEvent.dataTransfer.getData('text/plain')); // if (data.type !== "Item") return; } catch (err) { return false; } // Retrieve the combatant being dropped. let newCombatant = combat.combatants.find(c => c._id == data.combatantId); // Retrieve the combatants grouped by type. let combatants = this.getCombatantsData(false); // Retrieve the combatant being dropped onto. let originalCombatant = combatants[newCombatant.actor.data.type].find(c => { return c._id == $dropTarget.data('combatant-id'); }); // Set the initiative equal to the drop target's initiative. let oldInit = originalCombatant ? originalCombatant.initiative : null; // If the initiative was valid, we need to update the initiative // for every combatant to reset their numbers. if (oldInit !== null) { // Set the initiative of the actor being draged to the drop // target's +1. This will later be adjusted increments of 10. let updatedCombatant = combatants[newCombatant.actor.data.type].find(c => c._id == newCombatant._id); updatedCombatant.initiative = Number(oldInit) + 1; // Loop through all combatants in initiative order, and assign // a new initiative in increments of 10. The "updates" variable // will be an array of objects iwth _id and initiative keys. let updatedInit = 0; let updates = combatants[newCombatant.actor.data.type].sort((a, b) => a.initiative - b.initiative).map(c => { let result = { _id: c._id, initiative: updatedInit }; updatedInit = updatedInit + 10; return result; }); // If there are updates, update the combatants at once. if (updates) { await combat.updateCombatant(updates); } } }); // end of newHtml.find('.directory-item.actor-elem') } } }); } /** * Retrieve a list of combatants for the current combat. * * Combatants will be sorted into groups by actor type. Set the * updateInitiative argument to true to reassign init numbers. * @param {Boolean} updateInitiative */ getCombatantsData(updateInitiative = false) { // If there isn't a combat, exit and return an empty array. if (!game.combat || !game.combat.data) { return []; } let currentInitiative = 0; // Reduce the combatants array into a new object with keys based on // the actor types. let combatants = game.combat.data.combatants.reduce((groups, combatant) => { // If this is for a combatant that has had its token/actor deleted, // remove it from the combat. if (!combatant.actor) { game.combat.deleteCombatant(combatant._id); } // Append valid actors to the appropriate group. else { // Initialize the group if it doesn't exist. let group = combatant.actor.data.type; if (!groups[group]) { groups[group] = []; } // Retrieve the health bars mode from the token's resource settings. let displayBarsMode = Object.entries(CONST.TOKEN_DISPLAY_MODES).find(i => i[1] == combatant.token.displayBars)[0]; // Assume player characters should always show their health bar. let displayHealth = group == 'character' ? true : false; // If this is a group other than character (such as NPC), we need to // evaluate whether or not this player can see its health bar. if (group != 'character') { // If the mode is one of the owner options, only the token owner or // the GM should be able to see it. if (displayBarsMode.includes("OWNER")) { if (combatant.owner || game.user.isGM) { displayHealth = true; } } // For other modes, always show it. else if (displayBarsMode != "NONE") { displayHealth = true; } // If it's set to the none mode, hide it from players, but allow // the GM to see it. else { displayHealth = game.user.isGM ? true : false; } // If the updateInitiative flag was set to true, recalculate the // initiative for each actor while we're looping through them. if (updateInitiative) { combatant.initiative = currentInitiative; currentInitiative = currentInitiative + 10; } } // Set a property based on the health mode earlier. combatant.displayHealth = displayHealth; // Set a property for whether or not this is editable. This controls // whether editabel fields like HP will be shown as an input or a div // in the combat tracker HTML template. combatant.editable = combatant.owner || game.user.isGM; // Build the radial progress circle settings for the template. combatant.healthSvg = DwUtility.getProgressCircle({ current: combatant.actor.data.data.attributes.hp.value, max: combatant.actor.data.data.attributes.hp.max, radius: 16 }); // If this is the GM or the owner, push to the combatants list. // Otherwise, only push if the token isn't hidden in the scene. if (game.user.isGM || combatant.owner || !combatant.token.hidden) { groups[group].push(combatant); } } // Return the updated group. return groups; }, {}); // Sort the combatants in each group by initiative. for (let [groupKey, group] of Object.entries(combatants)) { combatants[groupKey].sort((a, b) => { return Number(a.initiative) - Number(b.initiative) }); } // Return the list of combatants. return combatants; } }
JavaScript
class Events { constructor({errorCode} = {}) { this.callbacks = []; this.errorCode = errorCode; } on(event, cb) { this.callbacks.push({event, cb}); } off(removeEvent, removeCb) { this.callbacks = this.callbacks .filter(({event, cb}) => ! (event === removeEvent && cb === removeCb)); } fire(fireEvent, ...args) { this.callbacks .filter(({event}) => event === fireEvent) .forEach(({cb}) => { try { cb(...args) } catch (e) { if (this.errorCode && fireEvent !== this.errorCode) { this.fire(this.errorCode, fireEvent, args, cb, e); } } }); } }
JavaScript
class Pet { static value () { return 'happiness'; } static purpose () { // "this" points to the class return `The purpose of pets is ${this.value()}`; } // you MUST create a constructor here, gets invoked immediatelyupon "new" constructor(nickname, type) { // setting up public properties of the object: this.nickname = nickname; this.type = type; this.likesToBath = false; }; // rewriting methods in a shorter, class based way, // can drop function declaration and "this" petDescription () { return `My pet, ${this.nickname}, is a ${this.type}.`; }; setNickname (newNickname) { this.nickname = newNickname; }; setType (newType) { this.type = newType; } }
JavaScript
class CancellationTokenSource { constructor(timeout) { /**@type {string} */ this._cancel = false; this.controller = new AbortController(); this.abort = this.abort.bind(this); if (timeout) { setTimeout(this.abort, timeout.msecs != null ? timeout.msecs : timeout); } } Cancel() { this.abort(); } get aborted() { return this._cancel; } get signal() { return this.controller.signal; } IsCancellationRequested() { return this._cancel; } get Token() { return this; } abort() { this._cancel = true; this.controller.abort(); } }
JavaScript
class MinehutServer { constructor(data) { let server = data.server; let serverprop = server.server_properties; /** * Server Properties Data * @type {{maxPlayers: number, gamemode: number, allowFight: boolean, spawnAnimals: booleam, spawnMobs: boolean, forceGamemode: boolean, isHardcore: boolean, pvpAllowed: boolean, netherEnabled: boolean, generateStructures: boolean, commandBlocksEnabled: boolean, announceAchievements: boolean, level: {name: string, type: string }, spawnProtection: number, renderDistance: number}} */ this.properties = { maxPlayers: serverprop.max_players, gamemode: serverprop.gamemode, allowFlight: serverprop.allow_flight, spawnAnimals: serverprop.spawn_animals, spawnMobs: serverprop.spawn_mobs, forceGamemode: serverprop.force_gamemode, isHardcore: serverprop.hardcore, pvpAllowed: serverprop.pvp, netherEnabled: serverprop.allow_nether, generateStructures: serverprop.generate_structures, commandBlocksEnabled: serverprop.enable_command_block, announceAchievements: serverprop.announce_player_achievements, level: { name: serverprop.level_name, type: serverprop.level_type }, spawnProtection: serverprop.spawn_protection, renderDistance: serverprop.view_distance }; /** * Whether or not the server is suspended * @type {boolean} */ this.isSuspended = server.suspended; /** * The amount of backup slots the server has * @type {number} */ this.backupSlots = server.backup_slots; /** * Server's Database ID * @type {string} */ this.id = server._id; /** * The platform the server is currently on * @type {string} */ this.platform = server.platform; /** * The amount of credits the server earns. daily * @type {number} */ this.creditsPerDay = server.credits_per_day; /** * The current minehut plan the server has * @type {string} */ this.plan = server.server_plan.toLowerCase(); /** * The server's MOTD (message of the day) * @type {string} */ this.motd = server.motd; /** * The server owner's database ID * @type {string} */ this.id = server.owner; /** * The server name * @type {string} */ this.name = server.name; /** * Timestamp of when the server was last online * @type {number} */ this.onlineTimestamp = server.last_online; /** * Whether or not the server is currently online * @type {boolean} */ this.isOnline = server.online; /** * The maximum players allowed on the server * @type {number} */ this.maxPlayers = server.maxPlayers; /** * The current amount of players online * @type {number} */ this.onlinePlayers = server.playerCount; } }
JavaScript
class ThemeBase extends Plugin { /** * @function * @async * @param {Defiant.Plugin} plugin * The Plugin to which the `action` pertains. * @param {String} action * The action being performed. Example actions include "pre-enable", * "enable", "disable", "update". * @param {Mixed} [data=NULL] * Any supplementary information. */ async notify(plugin, action, data=null) { super.notify(plugin, action, data); switch (action) { case 'pre:enable': /** * @member {Defiant.util.InitRegistry} Defiant.Plugin.ThemeBase#renderables * A registry of all the Renderables provided by this theme set. */ this.renderables = new InitRegistry({}, [this.engine]); /** * @member {String} Defiant.Plugin.ThemeBase#parentName * The name of the parent theme set. */ this.parentName = Object.getPrototypeOf(Object.getPrototypeOf(this)).constructor.name; /** * @member {Defiant.Plugin.ThemeBase} Defiant.Plugin.ThemeBase#parent * The Class of the parent theme set. */ this.parent = this.parentName != 'Plugin' ? this.engine.pluginRegistry.get(this.parentName) : undefined; // Add the default Renderables. for (let renderable of [ require('./renderable/page'), ]) { this.setRenderable(renderable); } for (let existingPlugin of ['Router'].map(name => this.engine.pluginRegistry.get(name))) { if (existingPlugin instanceof Plugin) { await this.notify(existingPlugin, 'enable'); } } break; // pre:enable case 'enable': switch ((plugin || {}).id) { case 'Router': plugin // Serve default CSS & JavaScript files. .addHandler(new ServeDirectoryHandler({ id: 'ThemeBase.DirectoryHandler', path: 'file/theme/themeBase', target: path.join(__dirname, 'file'), menu: undefined, fileOptions: {}, directoryOptions: undefined, })); break; // Router default: // Populate this.parent, in the event that the parent theme plugin // is loaded after the child theme. if (!this.parent && this.parentName != 'Plugin') { this.parent = this.engine.pluginRegistry.get(this.parentName); } break; // default } break; // enable case 'pre:disable': // @todo Cleanup entries in Router. break; // pre:disable } } /** * Add a Renderable to the ThemeBase. * @function * @param {Defiant.Plugin.Theme.Renderable} renderable * Add a renderable to the ThemeBase. * @returns {Defiant.Plugin.ThemeBase} * The ThemeBase. */ setRenderable(renderable) { this.renderables.set(renderable); if (renderable.templateFile) { renderable.templateContents = fs.readFileSync(renderable.templateFile); renderable.templateFunction = Renderable.compileTemplate(renderable.variables, renderable.templateContents, renderable.boilerplate); } return this; } /** * Get the Renderable that matches the argument `name`. * * If this theme set does not have an entry for the requested Renderable, * then check the parent theme recursively. * @function * @param {String} name * The name of the Renderable. * @returns {Defiant.Plugin.Theme.Renderable} * The renderable matching the requested `name`. */ getRenderable(name) { return this.renderables.get(name) || (this.parent ? this.parent.getRenderable(name) : undefined); } }
JavaScript
class Message { constructor(a, m) { this.author = a; this.message = m; } static HTMLToMessage(element) { if (!element.children[0]) { console.error(element); badElements.push(element); return; } if (!element.children[0].children[1]) { console.error(element); badElements.push(element); return; } if (!element.children[0].children[1].children[0]) { console.error(element); badElements.push(element); return; } if (!element.innerText) { console.error(element); badElements.push(element); return; } return new Message(element.children[0].children[1].children[0].innerText, element.innerText); } }
JavaScript
class RuleBraceStyle extends CoreRule { /** * @var string */ get default() { return 'stroustrup'; } /** * @var string */ get property() { return 'brace-style'; } /** * Mandatory entry function to create a decision * * @return boolean */ identify() { let output = this.default; // Check for stroustrup if (this.input.match(/}\s*\n\s*(else|catch)[^\{\n]+{/gms)) { output = 'stroustrup'; } else if (this.input.match(/} *(else|catch) ?(if|\()?/gms)) { output = '1tbs'; } else if (this.input.match(/}\s*\n\s*(else|catch)[^\{]+\n\s*{/gms)) { output = 'allman'; } return output; } }
JavaScript
class SimpleGenerator extends AbstractGenerator { constructor() { super(); } init(expert, project) { this.expert = expert; this.project = project; } static getRandomPrimitiveType() { return ['string', 'number', 'boolean'].randomItem(); } static getRandomType() { return ['string', 'number', 'boolean', 'object'].randomItem(); } static generateRandomObject() { let depth = 0; return Utils.randomListOfStrings(Math.randomInt(5) + 1, Math.randomInt(5) + 1) .reduce((obj, item) => { obj[item] = depth > config.mutation.object.maxDepth ? '' : SimpleGenerator.generateRandomInputFromType(SimpleGenerator.getRandomType()); ++depth; return obj; }, {}); } static generateRandomInputFromType(type) { if (!type) { return SimpleGenerator.generateRandomInputFromType(SimpleGenerator.getRandomType()); } if ('object' === typeof(type)) { // the "type" here is the structure of the JSON if (Object.keys(type).length === 0) { let randObj = this.generateRandomObject(); return randObj; } else { let newObject = Array.isArray(type) ? [] : {}; for (let key in type) { newObject[key] = SimpleGenerator.generateRandomInputFromType(type[key]); } return newObject; } } switch (type) { case 'string': return (Math.randomString(Math.randomInt(20) + 1)); case 'number': return (Math.random() * 500); case 'boolean': return (Math.random() > 0.5 ? true : false); case 'object': return this.generateRandomObject(); case 'hexNumber': return Math.randomString(Math.randomInt(20) + 1, 16); default: throw Error('Unsupported type:' + type); } } static generateRandomPrimitive() { return SimpleGenerator.generateRandomInputFromType(SimpleGenerator.getRandomPrimitiveType()); } static generateRandomInput() { return SimpleGenerator.generateRandomInputFromType(SimpleGenerator.getRandomType()); } // static generateInput(entryPoint) { // let newParamVals = null; // let newBody = null; // if (config.mutation.mutateOnGenInputParams) { // newParamVals = SimpleGenerator.generateNewParamValsForEntryPoint(entryPoint); // } else if (config.mutation.mutateOnGenInputBody) { // newBody = SimpleGenerator.generateNewBodyValsForEntryPoint(entryPoint); // } else { // throw Error('Either `mutateOnGenInputBody` or `mutateOnGenInputParams` should be set in the config file!'); // } // if (!newBody) { // new BodyVal({}, {}) // } else if (!newParamVals) { // newParamsVals = entryPoint.enteryParams.map(param => new ParamVal(param)); // } // return new GeneralizedInput(entryPoint, newParamVals, newBody); // } // static generateNewParamValsForEntryPoint(entryPoint) { // return entryPoint.enteryParams.map(param => new ParamVal(param, SimpleGenerator.generateRandomInputFromType(param.type))); // } // static generateNewBodyValsForEntryPoint(generalizedInput) { // if (!generalizedInput || !generalizedInput.bodyVal || !generalizedInput.bodyVal.type || 0 === Object.keys(generalizedInput.bodyVal.type).length) { // return new BodyVal({}, {}); // // return this.generateRandomObject(); // } // // TODO: think if generalizedInput.bodyVal.type (JSON) should be cloned somehow // return new BodyVal(SimpleGenerator.generateRandomInputFromType(generalizedInput.bodyVal.type), generalizedInput.bodyVal.type /*, generalizedInput.bodyVal.flatType*/ ); // } }
JavaScript
class WMInterface extends events.EventEmitter { constructor() { super(); } move(num) { throw new Error('not implemented in base class'); } kill_window() { throw new Error('not implemented in base class'); } focus_window(id) {} }
JavaScript
class UserContextProvider extends Component { state = initUserState; /* User Actions */ addUser = async (user) => { this.setState({ users: this.state.users.concat(user) }); }; render() { return ( <UserContext.Provider value={{ loading: this.state.loading, users: this.state.users, addUser: this.addUser, }} > {this.props.children} </UserContext.Provider> ); } }
JavaScript
class UMLClassModel { get modCount() { return this.$modCount } get selectedIndex() { return this.$selectedIndex } set selectedIndex(v) { this.$selectedIndex = v this.modify() } constructor(data) { this.stereotype = (data && data.stereotype) || '' this.constraint = (data && data.constraint) || '' this.className = (data && data.className) || 'ClassName' this.attributes = (data && data.attributes) || [] this.operations = (data && data.operations) || [] this.attributesOpen = this.attributes.length > 0 this.operationsOpen = this.operations.length > 0 this.$selectedIndex = -1 this.selectedCategory = 1 this.$modCount = 0 } modify() { this.$modCount++ } clone() { const clone = new UMLClassModel() clone.stereotype = this.stereotype clone.constraint = this.constraint clone.className = this.className clone.attributes = Array.from(this.attributes) clone.operations = Array.from(this.operations) clone.attributesOpen = this.attributesOpen clone.operationsOpen = this.operationsOpen clone.selectedIndex = this.selectedIndex return clone } }
JavaScript
class DatabaseTarget { // constructor constructor(backendUrl, target, child, childTarget) { // url of backend application this.backendUrl = backendUrl; // target string used to associate with a database table this.target = target; // whether the database target is the child of another, // i.e. its records are owned by a record from another target this.child = child; // child database target object this.childTarget = childTarget; // whether the database target is the parent of another this.parent = (this.childTarget) ? true : false; } // get the number of pages of records from the server // and use this to create pagination links getPagination(byMatch, selector, startPage = 1) { // compose data to be sent var data = { target: this.target }; // if records are selected by match with parent ID if (byMatch) { // set action and ID accordingly data.action = "get-count-by-match"; data.match = selector; // if records are selected by search } else { // set action and searchTerm accordingly data.action = "get-count"; data.searchTerm = selector; } // make asynchronous POST request $.post(this.backendUrl, data, response => { checkResponse(response, responseData => { this.displayPagination(responseData, byMatch, selector, startPage); }); }); } // display pagination links on the page displayPagination(pages, byMatch, selector, startPage) { // get number of pages pages = parseInt(pages); // process start page if (startPage == -1) { startPage = pages; } // get target var target = this.target; // get pagination elements var pagination = $(`#${target}-pagination`); var paginationLinks = $(`#${target}-pagination-links`); // destroy previous pagination destroyPagination(paginationLinks); pagination.html(""); // display new pagination if number of pages is positive if (pages > 0) { // create pagination links element within pagination element pagination.html(`<ul id='${target}-pagination-links' class='pagination-sm justify-content-center mt-3'></ul>`); // get new pagination links element paginationLinks = $(`#${target}-pagination-links`); // set up pagination links (using twbsPagination jQuery plugin) paginationLinks.twbsPagination({ totalPages: pages, visiblePages: 3, startPage: startPage, // page click event for pagination onPageClick: (event, page) => { // display page that was clicked this.getPage(byMatch, selector, page); } }); // otherwise display page without pagination links } else { this.getPage(byMatch, selector, 1); } } // get a page of records from the server and display it on the page getPage(byMatch, selector, page) { throw new Error("Not implemented!"); } }
JavaScript
class LocationController extends Controller { /** * Location controller web component constructor. * @constructor */ constructor() { // Call the super with the page to load super({ htmlPath: 'location.html', cssPath: 'location.css', importMetaUrl: import.meta.url }); // Set location members this.href = ''; this.protocol = ''; this.host = ''; this.hostname = ''; this.port = ''; this.pathname = ''; this.search = ''; this.hash = ''; } /** * Override loadedCallback function to handle when HTML/CSS has been loaded. * @override */ loadedCallback() { // Reset location members this.href = Location.href; this.protocol = Location.protocol; this.host = Location.host; this.hostname = Location.hostname; this.port = Location.port; this.pathname = Location.pathname; this.search = Location.search; this.hash = Location.hash; // Log search params console.log(Location.searchParams()); // Create template area object this._templateArea = new Template('templateArea', this); // Update the template area for the first time this._templateArea.update(); } /** * Update button event. */ update() { // Reset location members this.href = Location.href; this.protocol = Location.protocol; this.host = Location.host; this.hostname = Location.hostname; this.port = Location.port; this.pathname = Location.pathname; this.search = Location.search; this.hash = Location.hash; // Log search params console.log(Location.searchParams()); // Update the template area with the new values this._templateArea.update(); } }
JavaScript
class Proof extends vcx_base_with_state_1.VCXBaseWithState { constructor(sourceId, { attrs, name }) { super(sourceId); this._releaseFn = rustlib_1.rustAPI().vcx_proof_release; this._updateStFn = rustlib_1.rustAPI().vcx_proof_update_state; this._updateStWithMessageFn = rustlib_1.rustAPI().vcx_proof_update_state_with_message; this._getStFn = rustlib_1.rustAPI().vcx_proof_get_state; this._serializeFn = rustlib_1.rustAPI().vcx_proof_serialize; this._deserializeFn = rustlib_1.rustAPI().vcx_proof_deserialize; this._proofState = null; this._requestedAttributes = attrs; this._name = name; } /** * Builds a generic proof object * * Example: * ``` * data = { * attrs: [ * { name: 'attr1' }, * { name: 'attr2' }], * name: 'Proof', * sourceId: 'testProofSourceId', * revocationInterval: {from: 1, to: 2} * } * proof1 = await Proof.create(data) * ``` */ static create(_a) { var { sourceId } = _a, createDataRest = __rest(_a, ["sourceId"]); return __awaiter(this, void 0, void 0, function* () { try { const proof = new Proof(sourceId, createDataRest); const commandHandle = 0; yield proof._create((cb) => rustlib_1.rustAPI().vcx_proof_create(commandHandle, proof.sourceId, JSON.stringify(createDataRest.attrs), JSON.stringify([]), JSON.stringify(createDataRest.revocationInterval), createDataRest.name, cb)); return proof; } catch (err) { throw new errors_1.VCXInternalError(err); } }); } /** * Builds a Proof object with defined attributes. * * Attributes are provided by a previous call to the serialize function. * ``` * data = { * attrs: [ * { name: 'attr1' }, * { name: 'attr2' }], * name: 'Proof', * sourceId: 'testProofSourceId' * } * proof1 = await Proof.create(data) * data1 = await Proof.serialize() * await Proof.deserialize(data1) * ``` */ static deserialize(proofData) { const _super = Object.create(null, { _deserialize: { get: () => super._deserialize } }); return __awaiter(this, void 0, void 0, function* () { try { const { data: { requested_attrs, name } } = proofData; const attrs = JSON.parse(requested_attrs); const constructorParams = { attrs, name }; const proof = yield _super._deserialize.call(this, Proof, proofData, constructorParams); return proof; } catch (err) { throw new errors_1.VCXInternalError(err); } }); } /** * * Updates the state of the proof from the given message. * * Example: * ``` * await object.updateStateWithMessage(message) * ``` * @returns {Promise<void>} */ updateStateWithMessage(message) { return __awaiter(this, void 0, void 0, function* () { try { const commandHandle = 0; yield ffi_helpers_1.createFFICallbackPromise((resolve, reject, cb) => { const rc = rustlib_1.rustAPI().vcx_proof_update_state_with_message(commandHandle, this.handle, message, cb); if (rc) { resolve(common_1.StateType.None); } }, (resolve, reject) => ffi.Callback('void', ['uint32', 'uint32', 'uint32'], (handle, err, state) => { if (err) { reject(err); } resolve(state); })); } catch (err) { throw new errors_1.VCXInternalError(err); } }); } /** * Sends a proof request to pairwise connection. * * Example * ``` * data = { * attrs: [ * { name: 'attr1' }, * { name: 'attr2' }], * name: 'Proof', * sourceId: 'testProofSourceId' * } * proof = await Proof.create(data) * await proof.requestProof(connection) * ``` */ requestProof(connection) { return __awaiter(this, void 0, void 0, function* () { try { yield ffi_helpers_1.createFFICallbackPromise((resolve, reject, cb) => { const rc = rustlib_1.rustAPI().vcx_proof_send_request(0, this.handle, connection.handle, cb); if (rc) { reject(rc); } }, (resolve, reject) => ffi.Callback('void', ['uint32', 'uint32'], (xcommandHandle, err) => { if (err) { reject(err); return; } resolve(); })); } catch (err) { throw new errors_1.VCXInternalError(err); } }); } /** * Generates the proof request message for sending. * * Example: * ``` * data = { * attrs: [ * { name: 'attr1' }, * { name: 'attr2' }], * name: 'Proof', * sourceId: 'testProofSourceId' * } * proof = await Proof.create(data) * await proof.getProofRequestMessage() * ``` */ getProofRequestMessage() { return __awaiter(this, void 0, void 0, function* () { try { return yield ffi_helpers_1.createFFICallbackPromise((resolve, reject, cb) => { const rc = rustlib_1.rustAPI().vcx_proof_get_request_msg(0, this.handle, cb); if (rc) { reject(rc); } }, (resolve, reject) => ffi.Callback('void', ['uint32', 'uint32', 'string'], (xHandle, err, message) => { if (err) { reject(err); return; } if (!message) { reject(`proof ${this.sourceId} returned empty string`); return; } resolve(message); })); } catch (err) { throw new errors_1.VCXInternalError(err); } }); } /** * Returns the requested proof if available * * Example * ``` * data = { * attrs: [ * { name: 'attr1' }, * { name: 'attr2' }], * name: 'Proof', * sourceId: 'testProofSourceId' * } * proof = await Proof.create(data) * await proof.requestProof(connection) * proofData = await proof.getProof(connection) * assert.equal(proofData.proofState, ProofState.Verified) * ``` */ getProof(connection) { return __awaiter(this, void 0, void 0, function* () { try { const proofRes = yield ffi_helpers_1.createFFICallbackPromise((resolve, reject, cb) => { const rc = rustlib_1.rustAPI().vcx_get_proof(0, this.handle, connection.handle, cb); if (rc) { reject(rc); } }, (resolve, reject) => ffi.Callback('void', ['uint32', 'uint32', 'uint32', 'string'], (xcommandHandle, err, proofState, proofData) => { if (err) { reject(err); return; } resolve({ proofState, proofData }); })); this._proofState = proofRes.proofState; return { proof: proofRes.proofData, proofState: proofRes.proofState }; } catch (err) { throw new errors_1.VCXInternalError(err); } }); } /** * Get the state of the proof * * Example * ``` * data = { * attrs: [ * { name: 'attr1' }, * { name: 'attr2' }], * name: 'Proof', * sourceId: 'testProofSourceId' * } * proof = await Proof.create(data) * await proof.requestProof(connection) * assert.equal(await proof.getState(), StateType.OfferSent) * ``` */ get proofState() { return this._proofState; } /** * Get the attributes of the proof * * Example * ``` * data = { * attrs: [ * { name: 'attr1' }, * { name: 'attr2' }], * name: 'Proof', * sourceId: 'testProofSourceId' * } * proof = await Proof.create(data) * await proof.requestProof(connection) * assert.equal(await proof.getState(), StateType.OfferSent) * proofData = await proof.getProof(connection) * await proof.updateState() * assert.equal(await proof.requestedAttributes(), data.attrs) * ``` */ get requestedAttributes() { return this._requestedAttributes; } /** * Get the name of the proof * * Example * ``` * data = { * attrs: [ * { name: 'attr1' }, * { name: 'attr2' }], * name: 'Proof', * sourceId: 'testProofSourceId' * } * proof = await Proof.create(data) * await proof.requestProof(connection) * assert.equal(await proof.getState(), StateType.OfferSent) * proofData = await proof.getProof(connection) * await proof.updateState() * assert.equal(await proof.name(), data.name) * ``` */ get name() { return this._name; } }
JavaScript
class DisplayModeTracker extends EventHandler { constructor() { super() if (SINGLETON !== null) { throw new Error('Use DisplayModeTracker.Singleton, not new DisplayModeTracker()') } this._flatCapable = null this._portalCapable = null this._immersiveCapable = null this._mode = 'flat' } get flatCapable() { return this._flatCapable } get portalCapable() { return this._portalCapable } get immersiveCapable() { return this._immersiveCapable } setModes(flatCapable, portalCapable, immersiveCapable) { if ( flatCapable == this._flatCapable && portalCapable == this._portalCapable && immersiveCapable == this._immersiveCapable ) return this._flatCapable = !!flatCapable this._portalCapable = !!portalCapable this._immersiveCapable = !!immersiveCapable this._triggerUpdate() } get currentDisplayMode() { return this._mode } /** @param {string} mode like 'flat', 'portal', or 'immersive' */ set currentDisplayMode(mode) { if (mode === this._mode) return this._mode = mode this.trigger(DisplayModeTracker.DisplayModeChangedEvent, mode, this) } _triggerUpdate() { this.trigger(DisplayModeTracker.DisplayUpdatedEvent, this.flatCapable, this.portalCapable, this.immersiveCapable) } static get Singleton() { if (!SINGLETON) { SINGLETON = new DisplayModeTracker() } return SINGLETON } }
JavaScript
class CacheableExecutorFactory { constructor(arweave, baseImplementation, cache) { this.baseImplementation = baseImplementation; this.cache = cache; this.logger = logging_1.LoggerFactory.INST.create('CacheableExecutorFactory'); } async create(contractDefinition) { // warn: do not cache on the contractDefinition.srcTxId. This might look like a good optimisation // (as many contracts share the same source code), but unfortunately this is causing issues // with the same SwGlobal object being cached for all contracts with the same source code // (eg. SwGlobal.contract.id field - which of course should have different value for different contracts // that share the same source). // warn#2: cache key MUST be a combination of both txId and srcTxId - // as "evolve" feature changes the srcTxId for the given txId... const cacheKey = `${contractDefinition.txId}_${contractDefinition.srcTxId}`; if (!this.cache.contains(cacheKey)) { this.logger.debug('Updating executor factory cache'); const handler = await this.baseImplementation.create(contractDefinition); this.cache.put(cacheKey, handler); } return this.cache.get(cacheKey); } }
JavaScript
class RenameFormComponent extends Component { static propTypes = { form: PropTypes.object.isRequired, type: PropTypes.string.isRequired, name: PropTypes.string.isRequired, visible: PropTypes.bool.isRequired, validator: PropTypes.func, }; componentDidUpdate(prevProps) { this.autoFocus(prevProps); this.resetFields(prevProps); } autoFocusInputRef = (inputToAutoFocus) => { this.inputToAutoFocus = inputToAutoFocus; inputToAutoFocus.focus(); inputToAutoFocus.select(); }; autoFocus = (prevProps) => { if (prevProps.visible === false && this.props.visible === true) { // focus on input field this.inputToAutoFocus && this.inputToAutoFocus.focus(); // select text this.inputToAutoFocus && this.inputToAutoFocus.select(); } }; resetFields = (prevProps) => { if (prevProps.name !== this.props.name) { // reset input field to reset displayed initialValue this.props.form.resetFields([NEW_NAME_FIELD]); } }; render() { const { getFieldDecorator } = this.props.form; return ( <Form layout='vertical'> <Form.Item label={`New ${this.props.type} name`}> {getFieldDecorator(NEW_NAME_FIELD, { rules: [ { required: true, message: `Please input a new name for the ${this.props.type}.` }, { validator: this.props.validator }, ], initialValue: this.props.name, })( <Input placeholder={`Input a ${this.props.type} name`} ref={this.autoFocusInputRef} />, )} </Form.Item> </Form> ); } }
JavaScript
class Router { construct() { this.uri = new Uri(); } parseRequest(uriRequest) { if (uriRequest instanceof Uri) { this.uri = uriRequest; } } }
JavaScript
class Route { /** * @param {String} name * @param {String} pattern * @param {Object} payload */ constructor(name, pattern, payload = {}) { this._name = name; this._pattern = pattern; this._payload = payload; } /** * @returns {String} */ get name() { return this._name; } /** * @returns {String} */ get pattern() { return this._pattern; } /** * @returns {Object} */ get payload() { return this._payload; } }
JavaScript
class RhCta extends RHElement { get html() { return ` <style> :host { --rh-cta--main: var(--rh-theme--color--ui-link, #06c); --rh-cta--main--hover: var(--rh-theme--color--ui-link--hover, #003366); --rh-cta--main--focus: var(--rh-theme--color--ui-link--focus, #003366); --rh-cta--main--visited: var(--rh-theme--color--ui-link--visited, rebeccapurple); --rh-cta--aux: transparent; --rh-cta--aux--hover: transparent; display: inline-block; font-weight: bold; } :host ::slotted(a) { line-height: inherit; color: var(--rh-cta--main) !important; } :host ::slotted(a)::after { display: block; margin-left: 0.25rem; vertical-align: middle; border-style: solid; border-width: 0.313em 0.313em 0; border-color: transparent; border-top-color: var(--rh-cta--main); transform: rotate(-90deg); display: inline-block; content: ""; } :host ::slotted(a:hover) { color: var(--rh-cta--main--hover) !important; } :host ::slotted(a:hover)::after { border-top-color: var(--rh-cta--main--hover); } :host ::slotted(a:focus) { color: var(--rh-cta--main--focus) !important; } :host ::slotted(a:focus)::after { border-top-color: var(--rh-cta--main--focus); } :host([priority="primary"]) { --rh-cta--main: var(--rh-theme--color--ui-accent, #fe460d); --rh-cta--main--hover: var(--rh-theme--color--ui-accent--hover, #a42701); --rh-cta--aux: var(--rh-theme--color--ui-accent--text, #fff); --rh-cta--aux--hover: var(--rh-theme--color--ui-accent--text--hover, #fff); } :host([priority="primary"]) ::slotted(a) { display: inline-block; padding: 8px 32px; border-radius: 5em; border: 1px solid transparent; text-decoration: none; line-height: 1.2; border-color: var(--rh-cta--main) !important; background: var(--rh-cta--main) !important; color: var(--rh-cta--aux) !important; } :host([priority="primary"]) ::slotted(a)::after { display: none; } :host([priority="primary"]) ::slotted(a:hover), :host([priority="primary"]) ::slotted(a:focus) { border-color: var(--rh-cta--main--hover) !important; background: var(--rh-cta--main--hover) !important; color: var(--rh-cta--aux--hover) !important; } :host([priority="secondary"]) { --rh-cta--main: var(--rh-theme--color--ui-base, #0477a4); --rh-cta--main--hover: var(--rh-theme--color--ui-base--hover, #022f40); --rh-cta--aux: var(--rh-theme--color--ui-base--text, #fff); --rh-cta--aux--hover: var(--rh-theme--color--ui-base--text--hover, #fff); } :host([priority="secondary"]) ::slotted(a) { display: inline-block; padding: 8px 32px; border-radius: 5em; border: 1px solid var(--rh-cta--main); text-decoration: none; line-height: 1.2; border-color: var(--rh-cta--main) !important; background: var(--rh-cta--aux) !important; color: var(--rh-cta--main) !important; } :host([priority="secondary"]) ::slotted(a)::after { display: none; } :host([priority="secondary"]) ::slotted(a:hover), :host([priority="secondary"]) ::slotted(a:focus) { border-color: var(--rh-cta--main--hover) !important; background: var(--rh-cta--main--hover) !important; color: var(--rh-cta--aux--hover) !important; } :host([on="dark"]) { --rh-cta--main: var(--rh-theme--color--text--on-dark, #fff); --rh-cta--main--hover: var(--rh-theme--color--ui-link--on-dark--hover, #cce6ff); --rh-cta--aux: transparent; --rh-cta--aux--hover: transparent; } :host([on="dark"][priority="primary"]) { --rh-cta--main: var(--rh-theme--color--ui-accent--text, #fff); --rh-cta--main--hover: var(--rh-theme--color--ui-accent--text--hover, #fff); --rh-cta--aux: var(--rh-theme--color--ui-accent, #fe460d); --rh-cta--aux--hover: var(--rh-theme--color--ui-accent--hover, #a42701); } :host([on="dark"][priority="secondary"]) { --rh-cta--main: var(--rh-theme--color--ui-base--text, #fff); --rh-cta--main--hover: var(--rh-theme--color--ui-base--text--hover, #fff); --rh-cta--aux: transparent; --rh-cta--aux--hover: var(--rh-theme--color--ui-base--hover, #022f40); } :host([color="base"]) { --rh-cta--main: var(--rh-theme--color--ui-base, #0477a4) !important; --rh-cta--main--hover: var(--rh-theme--color--ui-base--hover, #022f40) !important; --rh-cta--aux: var(--rh-theme--color--ui-base--text, #fff) !important; --rh-cta--aux--hover: var(--rh-theme--color--ui-base--text--hover, #fff) !important; } :host([color="complement"]) { --rh-cta--main: var(--rh-theme--color--ui-complement, #464646) !important; --rh-cta--main--hover: var(--rh-theme--color--ui-complement--hover, #131313) !important; --rh-cta--aux: var(--rh-theme--color--ui-complement--text, #fff) !important; --rh-cta--aux--hover: var(--rh-theme--color--ui-complement--text--hover, #fff) !important; } :host([color="accent"]) { --rh-cta--main: var(--rh-theme--color--ui-accent, #fe460d) !important; --rh-cta--main--hover: var(--rh-theme--color--ui-accent--hover, #a42701) !important; --rh-cta--aux: var(--rh-theme--color--ui-accent--text, #fff) !important; --rh-cta--aux--hover: var(--rh-theme--color--ui-accent--text--hover, #fff) !important; } </style> <slot></slot>`; } static get tag() { return "rh-cta"; } get styleUrl() { return "rh-cta.scss"; } get templateUrl() { return "rh-cta.html"; } constructor() { super(RhCta); } connectedCallback() { super.connectedCallback(); const firstChild = this.children[0]; if (!firstChild) { console.warn( "The first child in the light DOM must be an anchor tag (<a>)" ); } else if (firstChild && firstChild.tagName.toLowerCase() !== "a") { console.warn( "The first child in the light DOM must be an anchor tag (<a>)" ); } else { this.link = this.querySelector("a"); } } disconnectedCallback() {} }
JavaScript
class LocalEvaluator { constructor(settings) { /** * The logger */ this.logger_ = logger.getLogger('Evaluator'); this.pubsub = settings.pubsub; /** * Evaluation engines * @type {{}} * @private */ this.engines_ = {}; /** * evalRule * @type {{}} * @private */ this.rules_ = {}; // Subscribe to the submission action event this.pubsub.subscribe(Events.ANSWER_EVALUATE, this.handleEvaluateEvent_.bind(this) ); } /** * Register an evaluator engine * @param name * @param engine */ registerEngine(engine) { this.engines_[engine.name] = engine; } /** * Register rules per item * Applicable for in-memory evaluation (e.g. non remote) * * @param {string} itemId * @param {Object} rule */ registerItem(itemContext) { var itemId = itemContext.getAssociationId(); var rule = itemContext.getContent().evalRule; this.rules_[itemId] = rule; } /** * Retrieves a rule * @param itemId * @returns {Promise} */ retrieveRule(itemId) { var promise = promiseutils.createPromise( function(resolve, reject) { if (itemId in this.rules_) { resolve(this.rules_[itemId]); } else { reject({error:'Eval rule for item ' + itemId + ' not found.'}); } }.bind(this)); return promise; } /** * Submits the staged for evaluation * * @param {string} itemId * @param {core.AnswerSubmission} payload * * @return {Promise} * On Success: (core.AnswerSubmission) */ evaluate(itemId, payload) { var promise = promiseutils.createPromise( function(resolve, reject) { // @todo - make rest call to the evaluatorUrl_ // For remote call var evalArgs = { submissionContext: { itemId: itemId }, fields: payload.fields }; // Local evaluation: this.retrieveRule(itemId) .then( function(rule) { this.evaluateFields_(rule, payload.fields) .then( function(result) { // Retuning var returnMessage = { timeSpent: payload.timeSpent, fields: result, score: .5, // @todo overallFeedback: '' // @todo } resolve(returnMessage); }.bind(this)) .catch( function(error) { reject(error); }); }.bind(this)) .catch( function(error) { reject(error); }) .finally(function () { this.logger_.info( 'LocalEvaluator.evaluate():completed' ); }.bind(this)); }.bind(this)); return promise; } /** * Evaluate all fields in the submitted answer * * @param {Object} rule * @param {Object} answer * * @returns {Promise} * On Succss: (Array<core.AnswerField>) */ evaluateFields_(rule, answer) { var promises = {}; answer.forEach( function(answeredField) { var fieldRule = rule.fieldRules[answeredField.fieldId]; promises[answeredField.fieldId] = this.engines_[fieldRule.engine].evaluate(fieldRule, answeredField.answered); }.bind(this)); var promise = promiseutils.createPromise( function(resolve, reject) { promiseutils.props(promises) .then(function (result) { var response = []; answer.forEach( function(answeredField) { // To the same answer structure, add the correctness and feedback properties var responseEntry = _.clone(answeredField, true); responseEntry.correctness = result[answeredField.fieldId]; if (responseEntry.correctness) { responseEntry.feedback = 'correct'; } else { responseEntry.feedback = 'incorrect'; } response.push(responseEntry); }, this); resolve(response); }.bind(this)) .catch(function (error) { reject(error); }); }.bind(this)); return promise; } /** * PubSub Event subscription handler * * @param message * @private */ handleEvaluateEvent_(message) { var itemId = message.source.itemId; this.evaluate(itemId, message.payload) .then( function(result){ this.pubsub.publish( Events.ANSWER_EVALUATED, itemId, 'evaluator', 'evaluation', /** @type core.AnswerSubmission */ (result) ); this.logger_.info({itemId: itemId}, 'Evaluation:published'); }.bind(this)) .catch( function (error) { this.logger_.info({itemId: itemId, error: error}, 'Evaluation:error'); }.bind(this)); } }
JavaScript
class TemplatePlugin { initialize(config, context) { // before all features, // config: current config values loaded from /config folder // context: cucumber context ("this" in support files) // this is a synchronous-only method // use this.log for all output from this plugin this.log('initialize', context, config); } /* cli(program, config) { // optional, allows plugins to define CLI commands ("./run <command>") // program is a commander instance: https://github.com/tj/commander.js this.config = config; program.command(this.name) .description('the command description') .option('-f, --force', 'force run') .action((options) => { if (!options.force && !this.config.dontForce) { this.log('ignoring this run'); return; } return this.doIt(); }); } */ extendWorld(world) { // extend world, eg. adding members used step definitions // this is a synchronous-only method this.log('extending', world); } beforeFeatures(features) { // before all features // return a promise for async operations this.log('before features', features); } beforeScenario(world) { // initialize the world before scenario begins // return a promise for async operations this.log('initializing', world); } beforeStep(world, step) { // before each step in scenarios // this is a synchronous-only method this.log('before step', world, step); } afterStep(world, stepResult) { // after each step in scenarios // this is a synchronous-only method this.log('after step', world, stepResult); } afterScenario(world, scenarioResult) { // after each scenario is complete // return a promise for async operations this.log('after scenario', world, scenarioResult); } afterScenarioCleanup(world) { // cleanup after each scenario, runs after all plugins "afterScenario"s // return a promise for async operations this.log('after scenario cleanup', world); } afterFeatures(features) { // after all features/scenarios are complete // return a promise for async operations this.log('after features', features); } }
JavaScript
class Trip { /** * Trip Constructor * @constructor * @param {string} id Trip ID * @param {Route} route Trip Route * @param {Service} service Trip Service * @param {StopTime[]} stopTimes Trip StopTimes list * @param {Object} [optional] Optional Arguments * @param {string} [optional.headsign] Trip Headsign * @param {string} [optional.shortName] Trip Short Name * @param {int} [optional.directionId=-1] Trip Direction ID * @param {string} [optional.directionDescription] Trip Direction Description * @param {int} [optional.blockId] Trip Block ID * @param {int} [optional.shapeId] Trip Shape ID * @param {int} [optional.wheelchairAccessible=0] Trip Wheelchair Accessibility code * @param {int} [optional.bikesAllowed=0] Trip Bikes Allowed code * @param {boolean} [optional.peak] Trip Peak Status */ constructor(id, route, service, stopTimes, optional={}) { /** * A unique ID representing the Trip * @type {string} */ this.id = id; /** * The Trip's parent Route * @type {Route} */ this.route = route; /** * The Service the Trip operates on * @type {Service} */ this.service = service; /** * List of scheduled StopTimes for the Trip * @type {StopTime[]} */ this.stopTimes = stopTimes; /** * Trip Headsign - text displayed to passengers indicating the Trip's destination * @type {string} */ this.headsign = provided(optional.headsign); /** * Publicly-viewable Trip ID or name * @type {string} */ this.shortName = provided(optional.shortName, this.id); /** * Direction of travel for the Trip * @type {int} * @default -1 */ this.directionId = provided(optional.directionId, -1); /** * A description of the Trip's direction * @type {string} */ this.directionDescription = provided(optional.directionDescription, "Unspecified Direction"); /** * The ID of the block the Trip belongs to * @type {string} */ this.blockId = provided(optional.blockId); /** * The ID of the shape the Trip belongs to * @type {string} */ this.shapeId = provided(optional.shapeId); /** * Value indicating the wheelchair accessibility of the vehicle * making the Trip * @type {int} * @default 0 */ this.wheelchairAccessible = provided(optional.wheelchairAccessible, Trip.WHEELCHAIR_ACCESSIBLE_UNKNOWN); /** * Value indicating whether bikes are allowed on the vehicle making the Trip * @type {int} * @default 0 */ this.bikesAllowed = provided(optional.bikesAllowed, Trip.BIKES_ALLOWED_UNKNOWN); /** * Value indicating the peak status of the Trip. * @type {boolean} * @default false */ this.peak = provided(optional.peak, false); // Sort stoptimes by stop sequence if ( this.stopTimes ) { this.stopTimes.sort(StopTime.sortByStopSequence); } } /** * Get the StopTime associated with the specified Stop * @param {Stop|String} stop Stop (or Stop ID) to find in Trip's list of StopTimes * @returns {StopTime} matching StopTime */ getStopTime(stop) { if ( typeof stop === 'object' ) { stop = stop.id; } for ( let i = 0; i < this.stopTimes.length; i++ ) { let stopTime = this.stopTimes[i]; if ( this.stopTimes[i].stop.id === stop ) { return this.stopTimes[i]; } } } /** * Check if the Trip's list of StopTimes includes the specified Stop * @param {Stop|String} stop Stop (or Stop ID) to check for * @returns {boolean} true if the Stop is found in list of StopTimes */ hasStopTime(stop) { if ( typeof stop === 'object' ) { stop = stop.id; } for ( let i = 0; i < this.stopTimes.length; i++ ) { if ( this.stopTimes[i].stop.id === stop ) { return true; } } return false; } }
JavaScript
class ValidateCustomer { /** * @method registrationDetails * @description Validates registration details provided by customer * @param {object} req - The request object * @param {object} res - The response object * @param {callback} next - Callback method * @returns {object} - JSON response object */ static async registrationDetails(req, res, next) { const { email, name, password } = req.body; const fields = validationResult(req).mapped(); const errorObj = ValidateCustomer.validateUserFields(fields); if (Object.keys(errorObj).length) { return ResponseHandler.badRequest(errorObj, res); } // Check if user email is unique try { if (await ValidateCustomer.emailIsUnique(email, res)) { req.name = name.trim(); req.email = email.trim(); req.password = password; return next(); } return ResponseHandler.badRequest({ code: 'USR_04', message: 'The email already exists', field: 'email' }, res); } catch (error) { return ResponseHandler.serverError(res); } } /** * @method loginDetails * @description Validates login details provided by user * @param {object} req - The request object * @param {object} res - The response object * @param {callback} next - Callback method * @returns {object} - JSON response object */ static async loginDetails(req, res, next) { const { email, password } = req.body; const fields = validationResult(req).mapped(); const errorObj = ValidateCustomer.validateUserFields(fields); if (Object.keys(errorObj).length) { return ResponseHandler.badRequest(errorObj, res); } if (req.body.access_token) { return next(); } try { const customerDetails = await dbQuery('CALL customer_get_login_info(?)', email); if (customerDetails[0].length > 0) { const hashedPassword = customerDetails[0][0].password; const passwordIsCorrect = HelperUtils.verifyPassword(password, hashedPassword); if (passwordIsCorrect) { req.email = email; return next(); } return ResponseHandler.badRequest({ code: 'USR_01', message: 'Email or Password is invalid', field: 'email, password' }, res); } return ResponseHandler.badRequest({ code: 'USR_05', message: "The email doesn't exist.", field: 'email' }, res); } catch (error) { return ResponseHandler.serverError(res); } } /** * @method updateProfileDetails * @description Validates profile details provided by user during update * @param {object} req - The request object * @param {object} res - The response object * @param {callback} next - Callback method * @returns {object} - JSON response object */ static async updateProfileDetails(req, res, next) { const fields = validationResult(req).mapped(); const errorObj = ValidateCustomer.validateUserFields(fields); if (Object.keys(errorObj).length) { return ResponseHandler.badRequest(errorObj, res); } const { body, customerData } = req; const { customer_id: customerId, name, email, password, day_phone: dayPhone, eve_phone: evePhone, mob_phone: mobPhone } = customerData; const customerProfileData = { customer_id: customerId, name, email, password, day_phone: dayPhone, eve_phone: evePhone, mob_phone: mobPhone }; if (body.password) { const hashedPassword = HelperUtils.hashPassword(body.password); Object.assign(body, { password: hashedPassword }); } const updatedCustomerDetails = Object.assign(customerProfileData, body); req.customerDetails = updatedCustomerDetails; return next(); } /** * @method updateAddressDetails * @description Validates address details provided by user during update * @param {object} req - The request object * @param {object} res - The response object * @param {callback} next - Callback method * @returns {object} - JSON response object */ static async updateAddressDetails(req, res, next) { const fields = validationResult(req).mapped(); const errorObj = ValidateCustomer.validateUserFields(fields, 'USR_09'); if (Object.keys(errorObj).length) { return ResponseHandler.badRequest(errorObj, res); } const { body, customerData } = req; const { email, customer_id: customerId, address_1: address1, address_2: address2, city, region, country, postal_code: postalCode, shipping_region_id: shippingRegionId } = customerData; const customerAddressData = { customer_id: customerId, address_1: address1, address_2: address2, city, region, postal_code: postalCode, country, shipping_region_id: shippingRegionId }; const updatedCustomerDetails = Object.assign(customerAddressData, body); req.customerDetails = updatedCustomerDetails; req.email = email; return next(); } /** * @method updateCreditCardDetails * @description Validates credit card details provided by user during update * @param {object} req - The request object * @param {object} res - The response object * @param {callback} next - Callback method * @returns {object} - JSON response object */ static async updateCreditCardDetails(req, res, next) { const fields = validationResult(req).mapped(); const errorObj = ValidateCustomer.validateUserFields(fields, 'USR_08'); if (Object.keys(errorObj).length) { return ResponseHandler.badRequest(errorObj, res); } const { body, customerData } = req; const { customer_id: customerId, email } = customerData; req.customerDetails = { customerId, creditCard: body.credit_card }; req.email = email; return next(); } /** * @method emailIsUnique * @description Validates if user email is unique * @param {string} email - User's email * @returns {boolean} - If user email is unique or not */ static async emailIsUnique(email) { try { const getUniqueUser = await dbQuery('CALL customer_get_login_info(?)', email); return getUniqueUser[0].length === 0; } catch (error) { throw new Error(error); } } /** * @method validateUserFields * @description Validates fields specified by customer * @param {string} fields - Fields specified in either request parama * @returns {boolean} - If user email is unique or not */ static validateUserFields(fields) { const requiredFieldsErrors = FieldValidation.validateRequiredFields(fields, 'USR_02'); // Cater for other generic responses e.g invalid email, max length of characters etc const genericErrors = FieldValidation.validateField(fields, 'USR_03'); if (requiredFieldsErrors || genericErrors) { const errorObj = requiredFieldsErrors || genericErrors; if (errorObj.message.includes('long') || errorObj.message.includes('short')) { errorObj.code = 'USR_07'; } if (errorObj.field === 'credit_card') errorObj.code = 'USR_08'; return errorObj; } return []; } }
JavaScript
class LRUCache { /** * @description Initializer * @param {Object} options * - options.capacity - the doubly linked list's limitation * @return {void} */ constructor(options = {}) { if (options.capacity === 0) { assert('options.capacity can not be 0'); } this.options = Object.assign({}, defaultOpts, options); this.capacity = this.options.capacity; this.hash = new Hash(); this.map = this.hash.map; } /** * @description find an value from lru cache by key * @param {String} key - cache key * @return {String | Boolean} value */ get(key) { if (!this.authKey(key)) return false; const list = this.map.get(key); return list.get(); } /** * @description Set a cache to lru cache * @param {String} key - cache key * @param {String} value - cache value * @return {boolean} */ set(key, value) { if (!this.isValid(key) || !this.isValid(value)) { debug('the key/value must be an valid string or number'); return false; } if (this.map.has(key)) { const list = this.map.get(key); return list.set(key, value); } const list = new DoublyLinkedList(this.options); this.map.set(key, list); return list.set(key, value); } /** * @description get front node times of hit * @param {String} key * @return {Number} */ hit(key) { if (!this.authKey(key)) return 0; const list = this.map.get(key); return list.hit(); } /** * @description Authentication the is valid string * @param {String} key * @return {boolean} */ authKey(key) { if (!this.isValid(key)) { debug(`An invalid key:${key}`); return false; } if (!this.map.has(key) || this.isMapEmpty()) { debug(`Not found doubly linked list by key:${key}`); return false; } return true; } /** * @description detect the map's length * @return {boolean} */ isMapEmpty() { return this.map.size === 0; } /** * @description detect v is an valid string or number * @param {String | Number} v - a string for detection * @return {boolean} */ isValid(v) { return v !== null && v !== undefined; } /** * @description convert all list values to array * @param {String} key * @return {Array} */ toArray(key) { if (!this.authKey(key)) return []; const list = this.map.get(key); return list.toArray(); } }
JavaScript
class PID { /** * Make a new PID controller * * @param {Blackbox} blackbox - The blackbox for recording data */ constructor(blackbox) { this.blackbox = blackbox; this.p = 0; this.i = 0; this.d = 0; this.pTune = 0.01; this.iTune = 0.01; this.dTune = 0.01; this.error = 0; this.previousError = 0; this.dt = 1; this.blackbox.log(`PID - Controller ready`); } /** * Reset the PID controller, we do this when we have corrected the error, or we have * overshot past it and we are dealing the new overshoot error */ reset() { this.p = 0; this.i = 0; this.d = 0; this.dt = 1; this.error = 0; this.previousError = 0; this.blackbox.log(`PID - Controller reset`); } /** * Calculate the PID values based on the supplied error * Returns the output value that is used to apply the correction. It is a measure of * how much correction to apply. A big error usually produces a big correction, as the * error reduces the correction decreases as well. * * @param {number} error - The error value (current angle - desired angle) * @returns {number} - The correction value */ calculateErrorCorrection(error) { this.blackbox.log(`PID - Fixing error ${parseFloat(error).toFixed(3)}`); let correction = 0; /* Error from the FC (current angle - desired angle) */ this.error = error; if(this.error == 0) { this.blackbox.log(`PID - Error is zero`); /* No error, we are done, woohoo */ this.reset(); return 0; } else { /* P = the error reported (proportion here is 2 to 1) */ this.p = this.error/2; /* I = I + the error * the number of times we've tried to fix it */ this.i = this.i + this.error * this.dt; /* D = This error - previous error (difference in error) / times we've tried to fix it */ this.d = (this.error - this.previousError) / this.dt; this.blackbox.log(`PID - Calculated P ${parseFloat(this.p).toFixed(2)}, I ${parseFloat(this.i).toFixed(2)}, D ${parseFloat(this.d).toFixed(2)}, dt ${this.dt}`); /* Output I + P + D with their relevant tunes / weights applied */ correction = ( this.pTune * this.p ) + ( this.iTune * this.i ) + ( this.dTune * this.d ); this.blackbox.log(`PID - Correction value ${parseFloat(correction).toFixed(3)}`); /* Remember this error for the next loop */ this.previousError = this.error; /* Increase the counter until we know we have fixed the error */ this.dt += 1; /* Returnt the correction value */ return correction; } } }
JavaScript
class AssetsManager extends StaticClass { static textures = {} static sounds = {} static addFromFile(assetInfo, callback) { let assetSrc = "./assets/" + assetInfo[0], assetName = extractFilename(assetSrc) switch (determineAssetType(assetSrc)) { case ASSET_TYPE.IMAGE: let img = new Image() img.src = assetSrc if (assetInfo.length === 3) { img.onload = function () { AssetsManager.textures[assetName] = new SpriteSheet(assetName, img, assetInfo[1], assetInfo[2]) callback() } } else { img.onload = function () { AssetsManager.textures[assetName] = new SingleImage(assetName, img) callback() } } break case ASSET_TYPE.SOUND: AssetsManager.sounds[assetName] = new Audio(assetSrc) AssetsManager.sounds[assetName].src = assetSrc AssetsManager.sounds[assetName].volume = 0.3 callback() break } } static loadAssets(assetsLoadedCallback) { let assetsUnhandledCount = ASSETS_LIST.length, onSingleAssetLoaded = function () { if (--assetsUnhandledCount === 0) { console.log(ASSETS_LIST.length + " assets loaded!") assetsLoadedCallback(); } }; console.log("Loading assets...") for (let i = 0; i < ASSETS_LIST.length; i++) { AssetsManager.addFromFile(ASSETS_LIST[i], onSingleAssetLoaded) } } }
JavaScript
class Rule extends rule_1.AbstractRule { constructor() { super(...arguments); this.ruleName = Rule.RULE_NAME; this.code = error_code_1.ErrorCode.MUST_USE_PROMISES; } register(checker) { checker.on(ts.SyntaxKind.CallExpression, checkCallExpression, this.code); } }
JavaScript
class FollowButton extends Component { constructor(props) { super(props) this.followUser = this.followUser.bind(this) } followUser () { // check if user is signed in. if (Object.keys(this.props._user).length > 0) { // check if user is not the same person to follow if (this.props._user._id !== this.props.to_follow) { // check if you are not already following him if (this.props.user.indexOf(this.props.to_follow) === -1) { this.props.follow(this.props._user._id,this.props.to_follow) } } }else{ this.props.toggleOpen() } } render() { let following = this.props.user const f = following.indexOf(this.props.to_follow) return ( <div> <div> <div onClick={this.followUser} data-reactroot=""><a className={f === -1 ? "button green-border-button follow-button" : "button green-inner-button follow-button"} href="javascript:void(0);">{f === -1 ? 'Follow':'Following'}</a></div> </div> </div> ); } }
JavaScript
class Subscription { /** * Constructs a new <code>Subscription</code>. * @alias module:model/Subscription */ constructor() { Subscription.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>Subscription</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/Subscription} obj Optional instance to populate. * @return {module:model/Subscription} The populated <code>Subscription</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Subscription(); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('customerId')) { obj['customerId'] = ApiClient.convertToType(data['customerId'], 'String'); } if (data.hasOwnProperty('region')) { obj['region'] = ApiClient.convertToType(data['region'], 'String'); } if (data.hasOwnProperty('resource')) { obj['resource'] = Resource.constructFromObject(data['resource']); } if (data.hasOwnProperty('endpoint')) { obj['endpoint'] = Endpoint.constructFromObject(data['endpoint']); } if (data.hasOwnProperty('status')) { obj['status'] = ApiClient.convertToType(data['status'], 'String'); } if (data.hasOwnProperty('created')) { obj['created'] = ApiClient.convertToType(data['created'], 'Date'); } if (data.hasOwnProperty('modified')) { obj['modified'] = ApiClient.convertToType(data['modified'], 'Date'); } } return obj; } }
JavaScript
class DemoFuroIconList extends FBP(LitElement) { /** * Themable Styles * @private * @return {CSSResult} */ static get styles() { // language=CSS return ( Theme.getThemeForComponent('DemoFuroIconList') || css` :host { display: block; padding-right: var(--spacing); } :host([hidden]) { display: none; } h2 { margin-top: 0; } ` ); } /** * @private * @returns {TemplateResult} */ render() { // language=HTML return html` <h2>Iconset baseIcons</h2> <p> <pre> import {FuroBaseIcons} from "@furo/icon/assets/iconsets/baseIcons"; Iconset.registerIconset("default", FuroBaseIcons); </pre></p> <div> <furo-icon-with-label icon="3d-rotation"></furo-icon-with-label> <furo-icon-with-label icon="accessibility"></furo-icon-with-label> <furo-icon-with-label icon="accessible"></furo-icon-with-label> <furo-icon-with-label icon="account-balance"></furo-icon-with-label> <furo-icon-with-label icon="account-balance-wallet"></furo-icon-with-label> <furo-icon-with-label icon="account-box"></furo-icon-with-label> <furo-icon-with-label icon="account-circle"></furo-icon-with-label> <furo-icon-with-label icon="add"></furo-icon-with-label> <furo-icon-with-label icon="add-alert"></furo-icon-with-label> <furo-icon-with-label icon="add-box"></furo-icon-with-label> <furo-icon-with-label icon="add-circle"></furo-icon-with-label> <furo-icon-with-label icon="add-circle-outline"></furo-icon-with-label> <furo-icon-with-label icon="add-shopping-cart"></furo-icon-with-label> <furo-icon-with-label icon="alarm"></furo-icon-with-label> <furo-icon-with-label icon="alarm-add"></furo-icon-with-label> <furo-icon-with-label icon="alarm-off"></furo-icon-with-label> <furo-icon-with-label icon="alarm-on"></furo-icon-with-label> <furo-icon-with-label icon="all-out"></furo-icon-with-label> <furo-icon-with-label icon="android"></furo-icon-with-label> <furo-icon-with-label icon="announcement"></furo-icon-with-label> <furo-icon-with-label icon="apps"></furo-icon-with-label> <furo-icon-with-label icon="archive"></furo-icon-with-label> <furo-icon-with-label icon="arrow-back"></furo-icon-with-label> <furo-icon-with-label icon="arrow-downward"></furo-icon-with-label> <furo-icon-with-label icon="arrow-drop-down"></furo-icon-with-label> <furo-icon-with-label icon="arrow-drop-down-circle"></furo-icon-with-label> <furo-icon-with-label icon="arrow-drop-up"></furo-icon-with-label> <furo-icon-with-label icon="arrow-forward"></furo-icon-with-label> <furo-icon-with-label icon="arrow-upward"></furo-icon-with-label> <furo-icon-with-label icon="aspect-ratio"></furo-icon-with-label> <furo-icon-with-label icon="assessment"></furo-icon-with-label> <furo-icon-with-label icon="assignment"></furo-icon-with-label> <furo-icon-with-label icon="assignment-ind"></furo-icon-with-label> <furo-icon-with-label icon="assignment-late"></furo-icon-with-label> <furo-icon-with-label icon="assignment-return"></furo-icon-with-label> <furo-icon-with-label icon="assignment-returned"></furo-icon-with-label> <furo-icon-with-label icon="assignment-turned-in"></furo-icon-with-label> <furo-icon-with-label icon="attachment"></furo-icon-with-label> <furo-icon-with-label icon="autorenew"></furo-icon-with-label> <furo-icon-with-label icon="backspace"></furo-icon-with-label> <furo-icon-with-label icon="backup"></furo-icon-with-label> <furo-icon-with-label icon="block"></furo-icon-with-label> <furo-icon-with-label icon="book"></furo-icon-with-label> <furo-icon-with-label icon="bookmark"></furo-icon-with-label> <furo-icon-with-label icon="bookmark-border"></furo-icon-with-label> <furo-icon-with-label icon="bug-report"></furo-icon-with-label> <furo-icon-with-label icon="build"></furo-icon-with-label> <furo-icon-with-label icon="cached"></furo-icon-with-label> <furo-icon-with-label icon="camera-enhance"></furo-icon-with-label> <furo-icon-with-label icon="cancel"></furo-icon-with-label> <furo-icon-with-label icon="card-giftcard"></furo-icon-with-label> <furo-icon-with-label icon="card-membership"></furo-icon-with-label> <furo-icon-with-label icon="card-travel"></furo-icon-with-label> <furo-icon-with-label icon="change-history"></furo-icon-with-label> <furo-icon-with-label icon="check"></furo-icon-with-label> <furo-icon-with-label icon="check-box"></furo-icon-with-label> <furo-icon-with-label icon="check-box-outline-blank"></furo-icon-with-label> <furo-icon-with-label icon="check-circle"></furo-icon-with-label> <furo-icon-with-label icon="chevron-left"></furo-icon-with-label> <furo-icon-with-label icon="chevron-right"></furo-icon-with-label> <furo-icon-with-label icon="chrome-reader-mode"></furo-icon-with-label> <furo-icon-with-label icon="class"></furo-icon-with-label> <furo-icon-with-label icon="clear"></furo-icon-with-label> <furo-icon-with-label icon="close"></furo-icon-with-label> <furo-icon-with-label icon="cloud"></furo-icon-with-label> <furo-icon-with-label icon="cloud-circle"></furo-icon-with-label> <furo-icon-with-label icon="cloud-done"></furo-icon-with-label> <furo-icon-with-label icon="cloud-download"></furo-icon-with-label> <furo-icon-with-label icon="cloud-off"></furo-icon-with-label> <furo-icon-with-label icon="cloud-queue"></furo-icon-with-label> <furo-icon-with-label icon="cloud-upload"></furo-icon-with-label> <furo-icon-with-label icon="code"></furo-icon-with-label> <furo-icon-with-label icon="compare-arrows"></furo-icon-with-label> <furo-icon-with-label icon="content-copy"></furo-icon-with-label> <furo-icon-with-label icon="content-cut"></furo-icon-with-label> <furo-icon-with-label icon="content-paste"></furo-icon-with-label> <furo-icon-with-label icon="copyright"></furo-icon-with-label> <furo-icon-with-label icon="create"></furo-icon-with-label> <furo-icon-with-label icon="create-new-folder"></furo-icon-with-label> <furo-icon-with-label icon="credit-card"></furo-icon-with-label> <furo-icon-with-label icon="dashboard"></furo-icon-with-label> <furo-icon-with-label icon="date-range"></furo-icon-with-label> <furo-icon-with-label icon="delete"></furo-icon-with-label> <furo-icon-with-label icon="delete-forever"></furo-icon-with-label> <furo-icon-with-label icon="delete-sweep"></furo-icon-with-label> <furo-icon-with-label icon="description"></furo-icon-with-label> <furo-icon-with-label icon="dns"></furo-icon-with-label> <furo-icon-with-label icon="done"></furo-icon-with-label> <furo-icon-with-label icon="done-all"></furo-icon-with-label> <furo-icon-with-label icon="donut-large"></furo-icon-with-label> <furo-icon-with-label icon="donut-small"></furo-icon-with-label> <furo-icon-with-label icon="drafts"></furo-icon-with-label> <furo-icon-with-label icon="eject"></furo-icon-with-label> <furo-icon-with-label icon="error"></furo-icon-with-label> <furo-icon-with-label icon="error-outline"></furo-icon-with-label> <furo-icon-with-label icon="euro-symbol"></furo-icon-with-label> <furo-icon-with-label icon="event"></furo-icon-with-label> <furo-icon-with-label icon="event-seat"></furo-icon-with-label> <furo-icon-with-label icon="exit-to-app"></furo-icon-with-label> <furo-icon-with-label icon="expand-less"></furo-icon-with-label> <furo-icon-with-label icon="expand-more"></furo-icon-with-label> <furo-icon-with-label icon="explore"></furo-icon-with-label> <furo-icon-with-label icon="extension"></furo-icon-with-label> <furo-icon-with-label icon="face"></furo-icon-with-label> <furo-icon-with-label icon="favorite"></furo-icon-with-label> <furo-icon-with-label icon="favorite-border"></furo-icon-with-label> <furo-icon-with-label icon="feedback"></furo-icon-with-label> <furo-icon-with-label icon="file-download"></furo-icon-with-label> <furo-icon-with-label icon="file-upload"></furo-icon-with-label> <furo-icon-with-label icon="filter-list"></furo-icon-with-label> <furo-icon-with-label icon="find-in-page"></furo-icon-with-label> <furo-icon-with-label icon="find-replace"></furo-icon-with-label> <furo-icon-with-label icon="fingerprint"></furo-icon-with-label> <furo-icon-with-label icon="first-page"></furo-icon-with-label> <furo-icon-with-label icon="flag"></furo-icon-with-label> <furo-icon-with-label icon="flight-land"></furo-icon-with-label> <furo-icon-with-label icon="flight-takeoff"></furo-icon-with-label> <furo-icon-with-label icon="flip-to-back"></furo-icon-with-label> <furo-icon-with-label icon="flip-to-front"></furo-icon-with-label> <furo-icon-with-label icon="folder"></furo-icon-with-label> <furo-icon-with-label icon="folder-open"></furo-icon-with-label> <furo-icon-with-label icon="folder-shared"></furo-icon-with-label> <furo-icon-with-label icon="font-download"></furo-icon-with-label> <furo-icon-with-label icon="forward"></furo-icon-with-label> <furo-icon-with-label icon="fullscreen"></furo-icon-with-label> <furo-icon-with-label icon="fullscreen-exit"></furo-icon-with-label> <furo-icon-with-label icon="g-translate"></furo-icon-with-label> <furo-icon-with-label icon="gavel"></furo-icon-with-label> <furo-icon-with-label icon="gesture"></furo-icon-with-label> <furo-icon-with-label icon="get-app"></furo-icon-with-label> <furo-icon-with-label icon="gif"></furo-icon-with-label> <furo-icon-with-label icon="grade"></furo-icon-with-label> <furo-icon-with-label icon="group-work"></furo-icon-with-label> <furo-icon-with-label icon="help"></furo-icon-with-label> <furo-icon-with-label icon="help-outline"></furo-icon-with-label> <furo-icon-with-label icon="highlight-off"></furo-icon-with-label> <furo-icon-with-label icon="history"></furo-icon-with-label> <furo-icon-with-label icon="home"></furo-icon-with-label> <furo-icon-with-label icon="hourglass-empty"></furo-icon-with-label> <furo-icon-with-label icon="hourglass-full"></furo-icon-with-label> <furo-icon-with-label icon="http"></furo-icon-with-label> <furo-icon-with-label icon="https"></furo-icon-with-label> <furo-icon-with-label icon="important-devices"></furo-icon-with-label> <furo-icon-with-label icon="inbox"></furo-icon-with-label> <furo-icon-with-label icon="indeterminate-check-box"></furo-icon-with-label> <furo-icon-with-label icon="info"></furo-icon-with-label> <furo-icon-with-label icon="info-outline"></furo-icon-with-label> <furo-icon-with-label icon="input"></furo-icon-with-label> <furo-icon-with-label icon="invert-colors"></furo-icon-with-label> <furo-icon-with-label icon="label"></furo-icon-with-label> <furo-icon-with-label icon="label-outline"></furo-icon-with-label> <furo-icon-with-label icon="language"></furo-icon-with-label> <furo-icon-with-label icon="last-page"></furo-icon-with-label> <furo-icon-with-label icon="launch"></furo-icon-with-label> <furo-icon-with-label icon="lightbulb-outline"></furo-icon-with-label> <furo-icon-with-label icon="line-style"></furo-icon-with-label> <furo-icon-with-label icon="line-weight"></furo-icon-with-label> <furo-icon-with-label icon="link"></furo-icon-with-label> <furo-icon-with-label icon="list"></furo-icon-with-label> <furo-icon-with-label icon="lock"></furo-icon-with-label> <furo-icon-with-label icon="lock-open"></furo-icon-with-label> <furo-icon-with-label icon="lock-outline"></furo-icon-with-label> <furo-icon-with-label icon="low-priority"></furo-icon-with-label> <furo-icon-with-label icon="loyalty"></furo-icon-with-label> <furo-icon-with-label icon="mail"></furo-icon-with-label> <furo-icon-with-label icon="markunread"></furo-icon-with-label> <furo-icon-with-label icon="markunread-mailbox"></furo-icon-with-label> <furo-icon-with-label icon="menu"></furo-icon-with-label> <furo-icon-with-label icon="more-horiz"></furo-icon-with-label> <furo-icon-with-label icon="more-vert"></furo-icon-with-label> <furo-icon-with-label icon="motorcycle"></furo-icon-with-label> <furo-icon-with-label icon="move-to-inbox"></furo-icon-with-label> <furo-icon-with-label icon="next-week"></furo-icon-with-label> <furo-icon-with-label icon="note-add"></furo-icon-with-label> <furo-icon-with-label icon="offline-pin"></furo-icon-with-label> <furo-icon-with-label icon="opacity"></furo-icon-with-label> <furo-icon-with-label icon="open-in-browser"></furo-icon-with-label> <furo-icon-with-label icon="open-in-new"></furo-icon-with-label> <furo-icon-with-label icon="open-with"></furo-icon-with-label> <furo-icon-with-label icon="pageview"></furo-icon-with-label> <furo-icon-with-label icon="pan-tool"></furo-icon-with-label> <furo-icon-with-label icon="payment"></furo-icon-with-label> <furo-icon-with-label icon="perm-camera-mic"></furo-icon-with-label> <furo-icon-with-label icon="perm-contact-calendar"></furo-icon-with-label> <furo-icon-with-label icon="perm-data-setting"></furo-icon-with-label> <furo-icon-with-label icon="perm-device-information"></furo-icon-with-label> <furo-icon-with-label icon="perm-identity"></furo-icon-with-label> <furo-icon-with-label icon="perm-media"></furo-icon-with-label> <furo-icon-with-label icon="perm-phone-msg"></furo-icon-with-label> <furo-icon-with-label icon="perm-scan-wifi"></furo-icon-with-label> <furo-icon-with-label icon="pets"></furo-icon-with-label> <furo-icon-with-label icon="picture-in-picture"></furo-icon-with-label> <furo-icon-with-label icon="picture-in-picture-alt"></furo-icon-with-label> <furo-icon-with-label icon="play-for-work"></furo-icon-with-label> <furo-icon-with-label icon="polymer"></furo-icon-with-label> <furo-icon-with-label icon="power-settings-new"></furo-icon-with-label> <furo-icon-with-label icon="pregnant-woman"></furo-icon-with-label> <furo-icon-with-label icon="print"></furo-icon-with-label> <furo-icon-with-label icon="query-builder"></furo-icon-with-label> <furo-icon-with-label icon="question-answer"></furo-icon-with-label> <furo-icon-with-label icon="radio-button-checked"></furo-icon-with-label> <furo-icon-with-label icon="radio-button-unchecked"></furo-icon-with-label> <furo-icon-with-label icon="receipt"></furo-icon-with-label> <furo-icon-with-label icon="record-voice-over"></furo-icon-with-label> <furo-icon-with-label icon="redeem"></furo-icon-with-label> <furo-icon-with-label icon="redo"></furo-icon-with-label> <furo-icon-with-label icon="refresh"></furo-icon-with-label> <furo-icon-with-label icon="remove"></furo-icon-with-label> <furo-icon-with-label icon="remove-circle"></furo-icon-with-label> <furo-icon-with-label icon="remove-circle-outline"></furo-icon-with-label> <furo-icon-with-label icon="remove-shopping-cart"></furo-icon-with-label> <furo-icon-with-label icon="reorder"></furo-icon-with-label> <furo-icon-with-label icon="reply"></furo-icon-with-label> <furo-icon-with-label icon="reply-all"></furo-icon-with-label> <furo-icon-with-label icon="report"></furo-icon-with-label> <furo-icon-with-label icon="report-problem"></furo-icon-with-label> <furo-icon-with-label icon="restore"></furo-icon-with-label> <furo-icon-with-label icon="restore-page"></furo-icon-with-label> <furo-icon-with-label icon="room"></furo-icon-with-label> <furo-icon-with-label icon="rounded-corner"></furo-icon-with-label> <furo-icon-with-label icon="rowing"></furo-icon-with-label> <furo-icon-with-label icon="save"></furo-icon-with-label> <furo-icon-with-label icon="schedule"></furo-icon-with-label> <furo-icon-with-label icon="search"></furo-icon-with-label> <furo-icon-with-label icon="select-all"></furo-icon-with-label> <furo-icon-with-label icon="send"></furo-icon-with-label> <furo-icon-with-label icon="settings"></furo-icon-with-label> <furo-icon-with-label icon="settings-applications"></furo-icon-with-label> <furo-icon-with-label icon="settings-backup-restore"></furo-icon-with-label> <furo-icon-with-label icon="settings-bluetooth"></furo-icon-with-label> <furo-icon-with-label icon="settings-brightness"></furo-icon-with-label> <furo-icon-with-label icon="settings-cell"></furo-icon-with-label> <furo-icon-with-label icon="settings-ethernet"></furo-icon-with-label> <furo-icon-with-label icon="settings-input-antenna"></furo-icon-with-label> <furo-icon-with-label icon="settings-input-component"></furo-icon-with-label> <furo-icon-with-label icon="settings-input-composite"></furo-icon-with-label> <furo-icon-with-label icon="settings-input-hdmi"></furo-icon-with-label> <furo-icon-with-label icon="settings-input-svideo"></furo-icon-with-label> <furo-icon-with-label icon="settings-overscan"></furo-icon-with-label> <furo-icon-with-label icon="settings-phone"></furo-icon-with-label> <furo-icon-with-label icon="settings-power"></furo-icon-with-label> <furo-icon-with-label icon="settings-remote"></furo-icon-with-label> <furo-icon-with-label icon="settings-voice"></furo-icon-with-label> <furo-icon-with-label icon="shop"></furo-icon-with-label> <furo-icon-with-label icon="shop-two"></furo-icon-with-label> <furo-icon-with-label icon="shopping-basket"></furo-icon-with-label> <furo-icon-with-label icon="shopping-cart"></furo-icon-with-label> <furo-icon-with-label icon="sort"></furo-icon-with-label> <furo-icon-with-label icon="speaker-notes"></furo-icon-with-label> <furo-icon-with-label icon="speaker-notes-off"></furo-icon-with-label> <furo-icon-with-label icon="spellcheck"></furo-icon-with-label> <furo-icon-with-label icon="star"></furo-icon-with-label> <furo-icon-with-label icon="star-border"></furo-icon-with-label> <furo-icon-with-label icon="star-half"></furo-icon-with-label> <furo-icon-with-label icon="stars"></furo-icon-with-label> <furo-icon-with-label icon="store"></furo-icon-with-label> <furo-icon-with-label icon="subdirectory-arrow-left"></furo-icon-with-label> <furo-icon-with-label icon="subdirectory-arrow-right"></furo-icon-with-label> <furo-icon-with-label icon="subject"></furo-icon-with-label> <furo-icon-with-label icon="supervisor-account"></furo-icon-with-label> <furo-icon-with-label icon="swap-horiz"></furo-icon-with-label> <furo-icon-with-label icon="swap-vert"></furo-icon-with-label> <furo-icon-with-label icon="swap-vertical-circle"></furo-icon-with-label> <furo-icon-with-label icon="system-update-alt"></furo-icon-with-label> <furo-icon-with-label icon="tab"></furo-icon-with-label> <furo-icon-with-label icon="tab-unselected"></furo-icon-with-label> <furo-icon-with-label icon="text-format"></furo-icon-with-label> <furo-icon-with-label icon="theaters"></furo-icon-with-label> <furo-icon-with-label icon="thumb-down"></furo-icon-with-label> <furo-icon-with-label icon="thumb-up"></furo-icon-with-label> <furo-icon-with-label icon="thumbs-up-down"></furo-icon-with-label> <furo-icon-with-label icon="timeline"></furo-icon-with-label> <furo-icon-with-label icon="toc"></furo-icon-with-label> <furo-icon-with-label icon="today"></furo-icon-with-label> <furo-icon-with-label icon="toll"></furo-icon-with-label> <furo-icon-with-label icon="touch-app"></furo-icon-with-label> <furo-icon-with-label icon="track-changes"></furo-icon-with-label> <furo-icon-with-label icon="translate"></furo-icon-with-label> <furo-icon-with-label icon="trending-down"></furo-icon-with-label> <furo-icon-with-label icon="trending-flat"></furo-icon-with-label> <furo-icon-with-label icon="trending-up"></furo-icon-with-label> <furo-icon-with-label icon="turned-in"></furo-icon-with-label> <furo-icon-with-label icon="turned-in-not"></furo-icon-with-label> <furo-icon-with-label icon="unarchive"></furo-icon-with-label> <furo-icon-with-label icon="undo"></furo-icon-with-label> <furo-icon-with-label icon="unfold-less"></furo-icon-with-label> <furo-icon-with-label icon="unfold-more"></furo-icon-with-label> <furo-icon-with-label icon="update"></furo-icon-with-label> <furo-icon-with-label icon="verified-user"></furo-icon-with-label> <furo-icon-with-label icon="view-agenda"></furo-icon-with-label> <furo-icon-with-label icon="view-array"></furo-icon-with-label> <furo-icon-with-label icon="view-carousel"></furo-icon-with-label> <furo-icon-with-label icon="view-column"></furo-icon-with-label> <furo-icon-with-label icon="view-day"></furo-icon-with-label> <furo-icon-with-label icon="view-headline"></furo-icon-with-label> <furo-icon-with-label icon="view-list"></furo-icon-with-label> <furo-icon-with-label icon="view-module"></furo-icon-with-label> <furo-icon-with-label icon="view-quilt"></furo-icon-with-label> <furo-icon-with-label icon="view-stream"></furo-icon-with-label> <furo-icon-with-label icon="view-week"></furo-icon-with-label> <furo-icon-with-label icon="visibility"></furo-icon-with-label> <furo-icon-with-label icon="visibility-off"></furo-icon-with-label> <furo-icon-with-label icon="warning"></furo-icon-with-label> <furo-icon-with-label icon="watch-later"></furo-icon-with-label> <furo-icon-with-label icon="weekend"></furo-icon-with-label> <furo-icon-with-label icon="work"></furo-icon-with-label> <furo-icon-with-label icon="youtube-searched-for"></furo-icon-with-label> <furo-icon-with-label icon="zoom-in"></furo-icon-with-label> <furo-icon-with-label icon="zoom-out"></furo-icon-with-label> </div> <h2>Iconset avIcons</h2> <p> <pre> import {AvIcons} from "@furo/icon/assets/iconsets/avIcons"; Iconset.registerIconset("av", AvIcons); </pre></p> <div> <furo-icon-with-label icon="av:add-to-queue"></furo-icon-with-label> <furo-icon-with-label icon="av:airplay"></furo-icon-with-label> <furo-icon-with-label icon="av:album"></furo-icon-with-label> <furo-icon-with-label icon="av:art-track"></furo-icon-with-label> <furo-icon-with-label icon="av:av-timer"></furo-icon-with-label> <furo-icon-with-label icon="av:branding-watermark"></furo-icon-with-label> <furo-icon-with-label icon="av:call-to-action"></furo-icon-with-label> <furo-icon-with-label icon="av:closed-caption"></furo-icon-with-label> <furo-icon-with-label icon="av:equalizer"></furo-icon-with-label> <furo-icon-with-label icon="av:explicit"></furo-icon-with-label> <furo-icon-with-label icon="av:fast-forward"></furo-icon-with-label> <furo-icon-with-label icon="av:fast-rewind"></furo-icon-with-label> <furo-icon-with-label icon="av:featured-play-list"></furo-icon-with-label> <furo-icon-with-label icon="av:featured-video"></furo-icon-with-label> <furo-icon-with-label icon="av:fiber-dvr"></furo-icon-with-label> <furo-icon-with-label icon="av:fiber-manual-record"></furo-icon-with-label> <furo-icon-with-label icon="av:fiber-new"></furo-icon-with-label> <furo-icon-with-label icon="av:fiber-pin"></furo-icon-with-label> <furo-icon-with-label icon="av:fiber-smart-record"></furo-icon-with-label> <furo-icon-with-label icon="av:forward-10"></furo-icon-with-label> <furo-icon-with-label icon="av:forward-30"></furo-icon-with-label> <furo-icon-with-label icon="av:forward-5"></furo-icon-with-label> <furo-icon-with-label icon="av:games"></furo-icon-with-label> <furo-icon-with-label icon="av:hd"></furo-icon-with-label> <furo-icon-with-label icon="av:hearing"></furo-icon-with-label> <furo-icon-with-label icon="av:high-quality"></furo-icon-with-label> <furo-icon-with-label icon="av:library-add"></furo-icon-with-label> <furo-icon-with-label icon="av:library-books"></furo-icon-with-label> <furo-icon-with-label icon="av:library-music"></furo-icon-with-label> <furo-icon-with-label icon="av:loop"></furo-icon-with-label> <furo-icon-with-label icon="av:mic"></furo-icon-with-label> <furo-icon-with-label icon="av:mic-none"></furo-icon-with-label> <furo-icon-with-label icon="av:mic-off"></furo-icon-with-label> <furo-icon-with-label icon="av:movie"></furo-icon-with-label> <furo-icon-with-label icon="av:music-video"></furo-icon-with-label> <furo-icon-with-label icon="av:new-releases"></furo-icon-with-label> <furo-icon-with-label icon="av:not-interested"></furo-icon-with-label> <furo-icon-with-label icon="av:note"></furo-icon-with-label> <furo-icon-with-label icon="av:pause"></furo-icon-with-label> <furo-icon-with-label icon="av:pause-circle-filled"></furo-icon-with-label> <furo-icon-with-label icon="av:pause-circle-outline"></furo-icon-with-label> <furo-icon-with-label icon="av:play-arrow"></furo-icon-with-label> <furo-icon-with-label icon="av:play-circle-filled"></furo-icon-with-label> <furo-icon-with-label icon="av:play-circle-outline"></furo-icon-with-label> <furo-icon-with-label icon="av:playlist-add"></furo-icon-with-label> <furo-icon-with-label icon="av:playlist-add-check"></furo-icon-with-label> <furo-icon-with-label icon="av:playlist-play"></furo-icon-with-label> <furo-icon-with-label icon="av:queue"></furo-icon-with-label> <furo-icon-with-label icon="av:queue-music"></furo-icon-with-label> <furo-icon-with-label icon="av:queue-play-next"></furo-icon-with-label> <furo-icon-with-label icon="av:radio"></furo-icon-with-label> <furo-icon-with-label icon="av:recent-actors"></furo-icon-with-label> <furo-icon-with-label icon="av:remove-from-queue"></furo-icon-with-label> <furo-icon-with-label icon="av:repeat"></furo-icon-with-label> <furo-icon-with-label icon="av:repeat-one"></furo-icon-with-label> <furo-icon-with-label icon="av:replay"></furo-icon-with-label> <furo-icon-with-label icon="av:replay-10"></furo-icon-with-label> <furo-icon-with-label icon="av:replay-30"></furo-icon-with-label> <furo-icon-with-label icon="av:replay-5"></furo-icon-with-label> <furo-icon-with-label icon="av:shuffle"></furo-icon-with-label> <furo-icon-with-label icon="av:skip-next"></furo-icon-with-label> <furo-icon-with-label icon="av:skip-previous"></furo-icon-with-label> <furo-icon-with-label icon="av:slow-motion-video"></furo-icon-with-label> <furo-icon-with-label icon="av:snooze"></furo-icon-with-label> <furo-icon-with-label icon="av:sort-by-alpha"></furo-icon-with-label> <furo-icon-with-label icon="av:stop"></furo-icon-with-label> <furo-icon-with-label icon="av:subscriptions"></furo-icon-with-label> <furo-icon-with-label icon="av:subtitles"></furo-icon-with-label> <furo-icon-with-label icon="av:surround-sound"></furo-icon-with-label> <furo-icon-with-label icon="av:video-call"></furo-icon-with-label> <furo-icon-with-label icon="av:video-label"></furo-icon-with-label> <furo-icon-with-label icon="av:video-library"></furo-icon-with-label> <furo-icon-with-label icon="av:videocam"></furo-icon-with-label> <furo-icon-with-label icon="av:videocam-off"></furo-icon-with-label> <furo-icon-with-label icon="av:volume-down"></furo-icon-with-label> <furo-icon-with-label icon="av:volume-mute"></furo-icon-with-label> <furo-icon-with-label icon="av:volume-off"></furo-icon-with-label> <furo-icon-with-label icon="av:volume-up"></furo-icon-with-label> <furo-icon-with-label icon="av:web"></furo-icon-with-label> <furo-icon-with-label icon="av:web-asset"></furo-icon-with-label> </div> <h2>Iconset communicationIcons</h2> <p> <pre> import {CommunicationIcons} from "@furo/icon/assets/iconsets/communicationIcons"; Iconset.registerIconset("communication", CommunicationIcons); </pre></p> <div> <furo-icon-with-label icon="communication:business"></furo-icon-with-label> <furo-icon-with-label icon="communication:call"></furo-icon-with-label> <furo-icon-with-label icon="communication:call-end"></furo-icon-with-label> <furo-icon-with-label icon="communication:call-made"></furo-icon-with-label> <furo-icon-with-label icon="communication:call-merge"></furo-icon-with-label> <furo-icon-with-label icon="communication:call-missed"></furo-icon-with-label> <furo-icon-with-label icon="communication:call-missed-outgoing"></furo-icon-with-label> <furo-icon-with-label icon="communication:call-received"></furo-icon-with-label> <furo-icon-with-label icon="communication:call-split"></furo-icon-with-label> <furo-icon-with-label icon="communication:chat"></furo-icon-with-label> <furo-icon-with-label icon="communication:chat-bubble"></furo-icon-with-label> <furo-icon-with-label icon="communication:chat-bubble-outline"></furo-icon-with-label> <furo-icon-with-label icon="communication:clear-all"></furo-icon-with-label> <furo-icon-with-label icon="communication:comment"></furo-icon-with-label> <furo-icon-with-label icon="communication:contact-mail"></furo-icon-with-label> <furo-icon-with-label icon="communication:contact-phone"></furo-icon-with-label> <furo-icon-with-label icon="communication:contacts"></furo-icon-with-label> <furo-icon-with-label icon="communication:dialer-sip"></furo-icon-with-label> <furo-icon-with-label icon="communication:dialpad"></furo-icon-with-label> <furo-icon-with-label icon="communication:email"></furo-icon-with-label> <furo-icon-with-label icon="communication:forum"></furo-icon-with-label> <furo-icon-with-label icon="communication:import-contacts"></furo-icon-with-label> <furo-icon-with-label icon="communication:import-export"></furo-icon-with-label> <furo-icon-with-label icon="communication:invert-colors-off"></furo-icon-with-label> <furo-icon-with-label icon="communication:live-help"></furo-icon-with-label> <furo-icon-with-label icon="communication:location-off"></furo-icon-with-label> <furo-icon-with-label icon="communication:location-on"></furo-icon-with-label> <furo-icon-with-label icon="communication:mail-outline"></furo-icon-with-label> <furo-icon-with-label icon="communication:message"></furo-icon-with-label> <furo-icon-with-label icon="communication:no-sim"></furo-icon-with-label> <furo-icon-with-label icon="communication:phone"></furo-icon-with-label> <furo-icon-with-label icon="communication:phonelink-erase"></furo-icon-with-label> <furo-icon-with-label icon="communication:phonelink-lock"></furo-icon-with-label> <furo-icon-with-label icon="communication:phonelink-ring"></furo-icon-with-label> <furo-icon-with-label icon="communication:phonelink-setup"></furo-icon-with-label> <furo-icon-with-label icon="communication:portable-wifi-off"></furo-icon-with-label> <furo-icon-with-label icon="communication:present-to-all"></furo-icon-with-label> <furo-icon-with-label icon="communication:ring-volume"></furo-icon-with-label> <furo-icon-with-label icon="communication:rss-feed"></furo-icon-with-label> <furo-icon-with-label icon="communication:screen-share"></furo-icon-with-label> <furo-icon-with-label icon="communication:speaker-phone"></furo-icon-with-label> <furo-icon-with-label icon="communication:stay-current-landscape"></furo-icon-with-label> <furo-icon-with-label icon="communication:stay-current-portrait"></furo-icon-with-label> <furo-icon-with-label icon="communication:stay-primary-landscape"></furo-icon-with-label> <furo-icon-with-label icon="communication:stay-primary-portrait"></furo-icon-with-label> <furo-icon-with-label icon="communication:stop-screen-share"></furo-icon-with-label> <furo-icon-with-label icon="communication:swap-calls"></furo-icon-with-label> <furo-icon-with-label icon="communication:textsms"></furo-icon-with-label> <furo-icon-with-label icon="communication:voicemail"></furo-icon-with-label> <furo-icon-with-label icon="communication:vpn-key"></furo-icon-with-label> </div> <h2>Iconset deviceIcons</h2> <p> <pre> import {DeviceIcons} from "@furo/icon/assets/iconsets/deviceIcons"; Iconset.registerIconset("device", DeviceIcons); </pre></p> <div> <furo-icon-with-label icon="device:access-alarm"></furo-icon-with-label> <furo-icon-with-label icon="device:access-alarms"></furo-icon-with-label> <furo-icon-with-label icon="device:access-time"></furo-icon-with-label> <furo-icon-with-label icon="device:add-alarm"></furo-icon-with-label> <furo-icon-with-label icon="device:airplanemode-active"></furo-icon-with-label> <furo-icon-with-label icon="device:airplanemode-inactive"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-20"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-30"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-50"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-60"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-80"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-90"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-alert"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-charging-20"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-charging-30"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-charging-50"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-charging-60"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-charging-80"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-charging-90"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-charging-full"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-full"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-std"></furo-icon-with-label> <furo-icon-with-label icon="device:battery-unknown"></furo-icon-with-label> <furo-icon-with-label icon="device:bluetooth"></furo-icon-with-label> <furo-icon-with-label icon="device:bluetooth-connected"></furo-icon-with-label> <furo-icon-with-label icon="device:bluetooth-disabled"></furo-icon-with-label> <furo-icon-with-label icon="device:bluetooth-searching"></furo-icon-with-label> <furo-icon-with-label icon="device:brightness-auto"></furo-icon-with-label> <furo-icon-with-label icon="device:brightness-high"></furo-icon-with-label> <furo-icon-with-label icon="device:brightness-low"></furo-icon-with-label> <furo-icon-with-label icon="device:brightness-medium"></furo-icon-with-label> <furo-icon-with-label icon="device:data-usage"></furo-icon-with-label> <furo-icon-with-label icon="device:developer-mode"></furo-icon-with-label> <furo-icon-with-label icon="device:devices"></furo-icon-with-label> <furo-icon-with-label icon="device:dvr"></furo-icon-with-label> <furo-icon-with-label icon="device:gps-fixed"></furo-icon-with-label> <furo-icon-with-label icon="device:gps-not-fixed"></furo-icon-with-label> <furo-icon-with-label icon="device:gps-off"></furo-icon-with-label> <furo-icon-with-label icon="device:graphic-eq"></furo-icon-with-label> <furo-icon-with-label icon="device:location-disabled"></furo-icon-with-label> <furo-icon-with-label icon="device:location-searching"></furo-icon-with-label> <furo-icon-with-label icon="device:network-cell"></furo-icon-with-label> <furo-icon-with-label icon="device:network-wifi"></furo-icon-with-label> <furo-icon-with-label icon="device:nfc"></furo-icon-with-label> <furo-icon-with-label icon="device:screen-lock-landscape"></furo-icon-with-label> <furo-icon-with-label icon="device:screen-lock-portrait"></furo-icon-with-label> <furo-icon-with-label icon="device:screen-lock-rotation"></furo-icon-with-label> <furo-icon-with-label icon="device:screen-rotation"></furo-icon-with-label> <furo-icon-with-label icon="device:sd-storage"></furo-icon-with-label> <furo-icon-with-label icon="device:settings-system-daydream"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-0-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-1-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-2-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-3-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-4-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-connected-no-internet-0-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-connected-no-internet-1-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-connected-no-internet-2-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-connected-no-internet-3-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-connected-no-internet-4-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-no-sim"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-null"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-cellular-off"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-0-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-1-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-1-bar-lock"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-2-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-2-bar-lock"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-3-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-3-bar-lock"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-4-bar"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-4-bar-lock"></furo-icon-with-label> <furo-icon-with-label icon="device:signal-wifi-off"></furo-icon-with-label> <furo-icon-with-label icon="device:storage"></furo-icon-with-label> <furo-icon-with-label icon="device:usb"></furo-icon-with-label> <furo-icon-with-label icon="device:wallpaper"></furo-icon-with-label> <furo-icon-with-label icon="device:widgets"></furo-icon-with-label> <furo-icon-with-label icon="device:wifi-lock"></furo-icon-with-label> <furo-icon-with-label icon="device:wifi-tethering"></furo-icon-with-label> </div> <h2>Iconset editorIcons</h2> <p> <pre> import {EditorIcons} from "@furo/icon/assets/iconsets/editorIcons"; Iconset.registerIconset("editor", EditorIcons); </pre></p> <div> <furo-icon-with-label icon="editor:attach-file"></furo-icon-with-label> <furo-icon-with-label icon="editor:attach-money"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-all"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-bottom"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-clear"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-color"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-horizontal"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-inner"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-left"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-outer"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-right"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-style"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-top"></furo-icon-with-label> <furo-icon-with-label icon="editor:border-vertical"></furo-icon-with-label> <furo-icon-with-label icon="editor:bubble-chart"></furo-icon-with-label> <furo-icon-with-label icon="editor:drag-handle"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-align-center"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-align-justify"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-align-left"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-align-right"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-bold"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-clear"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-color-fill"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-color-reset"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-color-text"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-indent-decrease"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-indent-increase"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-italic"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-line-spacing"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-list-bulleted"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-list-numbered"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-paint"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-quote"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-shapes"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-size"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-strikethrough"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-textdirection-l-to-r"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-textdirection-r-to-l"></furo-icon-with-label> <furo-icon-with-label icon="editor:format-underlined"></furo-icon-with-label> <furo-icon-with-label icon="editor:functions"></furo-icon-with-label> <furo-icon-with-label icon="editor:highlight"></furo-icon-with-label> <furo-icon-with-label icon="editor:insert-chart"></furo-icon-with-label> <furo-icon-with-label icon="editor:insert-comment"></furo-icon-with-label> <furo-icon-with-label icon="editor:insert-drive-file"></furo-icon-with-label> <furo-icon-with-label icon="editor:insert-emoticon"></furo-icon-with-label> <furo-icon-with-label icon="editor:insert-invitation"></furo-icon-with-label> <furo-icon-with-label icon="editor:insert-link"></furo-icon-with-label> <furo-icon-with-label icon="editor:insert-photo"></furo-icon-with-label> <furo-icon-with-label icon="editor:linear-scale"></furo-icon-with-label> <furo-icon-with-label icon="editor:merge-type"></furo-icon-with-label> <furo-icon-with-label icon="editor:mode-comment"></furo-icon-with-label> <furo-icon-with-label icon="editor:mode-edit"></furo-icon-with-label> <furo-icon-with-label icon="editor:monetization-on"></furo-icon-with-label> <furo-icon-with-label icon="editor:money-off"></furo-icon-with-label> <furo-icon-with-label icon="editor:multiline-chart"></furo-icon-with-label> <furo-icon-with-label icon="editor:pie-chart"></furo-icon-with-label> <furo-icon-with-label icon="editor:pie-chart-outlined"></furo-icon-with-label> <furo-icon-with-label icon="editor:publish"></furo-icon-with-label> <furo-icon-with-label icon="editor:short-text"></furo-icon-with-label> <furo-icon-with-label icon="editor:show-chart"></furo-icon-with-label> <furo-icon-with-label icon="editor:space-bar"></furo-icon-with-label> <furo-icon-with-label icon="editor:strikethrough-s"></furo-icon-with-label> <furo-icon-with-label icon="editor:text-fields"></furo-icon-with-label> <furo-icon-with-label icon="editor:title"></furo-icon-with-label> <furo-icon-with-label icon="editor:vertical-align-bottom"></furo-icon-with-label> <furo-icon-with-label icon="editor:vertical-align-center"></furo-icon-with-label> <furo-icon-with-label icon="editor:vertical-align-top"></furo-icon-with-label> <furo-icon-with-label icon="editor:wrap-text"></furo-icon-with-label> </div> <h2>Iconset hardwareIcons</h2> <p> <pre> import {HardwareIcons} from "@furo/icon/assets/iconsets/hardwareIcons"; Iconset.registerIconset("hardware", HardwareIcons); </pre></p> <div> <furo-icon-with-label icon="hardware:cast"></furo-icon-with-label> <furo-icon-with-label icon="hardware:cast-connected"></furo-icon-with-label> <furo-icon-with-label icon="hardware:computer"></furo-icon-with-label> <furo-icon-with-label icon="hardware:desktop-mac"></furo-icon-with-label> <furo-icon-with-label icon="hardware:desktop-windows"></furo-icon-with-label> <furo-icon-with-label icon="hardware:developer-board"></furo-icon-with-label> <furo-icon-with-label icon="hardware:device-hub"></furo-icon-with-label> <furo-icon-with-label icon="hardware:devices-other"></furo-icon-with-label> <furo-icon-with-label icon="hardware:dock"></furo-icon-with-label> <furo-icon-with-label icon="hardware:gamepad"></furo-icon-with-label> <furo-icon-with-label icon="hardware:headset"></furo-icon-with-label> <furo-icon-with-label icon="hardware:headset-mic"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-arrow-down"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-arrow-left"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-arrow-right"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-arrow-up"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-backspace"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-capslock"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-hide"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-return"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-tab"></furo-icon-with-label> <furo-icon-with-label icon="hardware:keyboard-voice"></furo-icon-with-label> <furo-icon-with-label icon="hardware:laptop"></furo-icon-with-label> <furo-icon-with-label icon="hardware:laptop-chromebook"></furo-icon-with-label> <furo-icon-with-label icon="hardware:laptop-mac"></furo-icon-with-label> <furo-icon-with-label icon="hardware:laptop-windows"></furo-icon-with-label> <furo-icon-with-label icon="hardware:memory"></furo-icon-with-label> <furo-icon-with-label icon="hardware:mouse"></furo-icon-with-label> <furo-icon-with-label icon="hardware:phone-android"></furo-icon-with-label> <furo-icon-with-label icon="hardware:phone-iphone"></furo-icon-with-label> <furo-icon-with-label icon="hardware:phonelink"></furo-icon-with-label> <furo-icon-with-label icon="hardware:phonelink-off"></furo-icon-with-label> <furo-icon-with-label icon="hardware:power-input"></furo-icon-with-label> <furo-icon-with-label icon="hardware:router"></furo-icon-with-label> <furo-icon-with-label icon="hardware:scanner"></furo-icon-with-label> <furo-icon-with-label icon="hardware:security"></furo-icon-with-label> <furo-icon-with-label icon="hardware:sim-card"></furo-icon-with-label> <furo-icon-with-label icon="hardware:smartphone"></furo-icon-with-label> <furo-icon-with-label icon="hardware:speaker"></furo-icon-with-label> <furo-icon-with-label icon="hardware:speaker-group"></furo-icon-with-label> <furo-icon-with-label icon="hardware:tablet"></furo-icon-with-label> <furo-icon-with-label icon="hardware:tablet-android"></furo-icon-with-label> <furo-icon-with-label icon="hardware:tablet-mac"></furo-icon-with-label> <furo-icon-with-label icon="hardware:toys"></furo-icon-with-label> <furo-icon-with-label icon="hardware:tv"></furo-icon-with-label> <furo-icon-with-label icon="hardware:videogame-asset"></furo-icon-with-label> <furo-icon-with-label icon="hardware:watch"></furo-icon-with-label> </div> <h2>Iconset imageIcons</h2> <p> <pre> import {ImageIcons} from "@furo/icon/assets/iconsets/imageIcons"; Iconset.registerIconset("image", ImageIcons); </pre></p> <div> <furo-icon-with-label icon="image:add-a-photo"></furo-icon-with-label> <furo-icon-with-label icon="image:add-to-photos"></furo-icon-with-label> <furo-icon-with-label icon="image:adjust"></furo-icon-with-label> <furo-icon-with-label icon="image:assistant"></furo-icon-with-label> <furo-icon-with-label icon="image:assistant-photo"></furo-icon-with-label> <furo-icon-with-label icon="image:audiotrack"></furo-icon-with-label> <furo-icon-with-label icon="image:blur-circular"></furo-icon-with-label> <furo-icon-with-label icon="image:blur-linear"></furo-icon-with-label> <furo-icon-with-label icon="image:blur-off"></furo-icon-with-label> <furo-icon-with-label icon="image:blur-on"></furo-icon-with-label> <furo-icon-with-label icon="image:brightness-1"></furo-icon-with-label> <furo-icon-with-label icon="image:brightness-2"></furo-icon-with-label> <furo-icon-with-label icon="image:brightness-3"></furo-icon-with-label> <furo-icon-with-label icon="image:brightness-4"></furo-icon-with-label> <furo-icon-with-label icon="image:brightness-5"></furo-icon-with-label> <furo-icon-with-label icon="image:brightness-6"></furo-icon-with-label> <furo-icon-with-label icon="image:brightness-7"></furo-icon-with-label> <furo-icon-with-label icon="image:broken-image"></furo-icon-with-label> <furo-icon-with-label icon="image:brush"></furo-icon-with-label> <furo-icon-with-label icon="image:burst-mode"></furo-icon-with-label> <furo-icon-with-label icon="image:camera"></furo-icon-with-label> <furo-icon-with-label icon="image:camera-alt"></furo-icon-with-label> <furo-icon-with-label icon="image:camera-front"></furo-icon-with-label> <furo-icon-with-label icon="image:camera-rear"></furo-icon-with-label> <furo-icon-with-label icon="image:camera-roll"></furo-icon-with-label> <furo-icon-with-label icon="image:center-focus-strong"></furo-icon-with-label> <furo-icon-with-label icon="image:center-focus-weak"></furo-icon-with-label> <furo-icon-with-label icon="image:collections"></furo-icon-with-label> <furo-icon-with-label icon="image:collections-bookmark"></furo-icon-with-label> <furo-icon-with-label icon="image:color-lens"></furo-icon-with-label> <furo-icon-with-label icon="image:colorize"></furo-icon-with-label> <furo-icon-with-label icon="image:compare"></furo-icon-with-label> <furo-icon-with-label icon="image:control-point"></furo-icon-with-label> <furo-icon-with-label icon="image:control-point-duplicate"></furo-icon-with-label> <furo-icon-with-label icon="image:crop"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-16-9"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-3-2"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-5-4"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-7-5"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-din"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-free"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-landscape"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-original"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-portrait"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-rotate"></furo-icon-with-label> <furo-icon-with-label icon="image:crop-square"></furo-icon-with-label> <furo-icon-with-label icon="image:dehaze"></furo-icon-with-label> <furo-icon-with-label icon="image:details"></furo-icon-with-label> <furo-icon-with-label icon="image:edit"></furo-icon-with-label> <furo-icon-with-label icon="image:exposure"></furo-icon-with-label> <furo-icon-with-label icon="image:exposure-neg-1"></furo-icon-with-label> <furo-icon-with-label icon="image:exposure-neg-2"></furo-icon-with-label> <furo-icon-with-label icon="image:exposure-plus-1"></furo-icon-with-label> <furo-icon-with-label icon="image:exposure-plus-2"></furo-icon-with-label> <furo-icon-with-label icon="image:exposure-zero"></furo-icon-with-label> <furo-icon-with-label icon="image:filter"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-1"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-2"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-3"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-4"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-5"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-6"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-7"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-8"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-9"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-9-plus"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-b-and-w"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-center-focus"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-drama"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-frames"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-hdr"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-none"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-tilt-shift"></furo-icon-with-label> <furo-icon-with-label icon="image:filter-vintage"></furo-icon-with-label> <furo-icon-with-label icon="image:flare"></furo-icon-with-label> <furo-icon-with-label icon="image:flash-auto"></furo-icon-with-label> <furo-icon-with-label icon="image:flash-off"></furo-icon-with-label> <furo-icon-with-label icon="image:flash-on"></furo-icon-with-label> <furo-icon-with-label icon="image:flip"></furo-icon-with-label> <furo-icon-with-label icon="image:gradient"></furo-icon-with-label> <furo-icon-with-label icon="image:grain"></furo-icon-with-label> <furo-icon-with-label icon="image:grid-off"></furo-icon-with-label> <furo-icon-with-label icon="image:grid-on"></furo-icon-with-label> <furo-icon-with-label icon="image:hdr-off"></furo-icon-with-label> <furo-icon-with-label icon="image:hdr-on"></furo-icon-with-label> <furo-icon-with-label icon="image:hdr-strong"></furo-icon-with-label> <furo-icon-with-label icon="image:hdr-weak"></furo-icon-with-label> <furo-icon-with-label icon="image:healing"></furo-icon-with-label> <furo-icon-with-label icon="image:image"></furo-icon-with-label> <furo-icon-with-label icon="image:image-aspect-ratio"></furo-icon-with-label> <furo-icon-with-label icon="image:iso"></furo-icon-with-label> <furo-icon-with-label icon="image:landscape"></furo-icon-with-label> <furo-icon-with-label icon="image:leak-add"></furo-icon-with-label> <furo-icon-with-label icon="image:leak-remove"></furo-icon-with-label> <furo-icon-with-label icon="image:lens"></furo-icon-with-label> <furo-icon-with-label icon="image:linked-camera"></furo-icon-with-label> <furo-icon-with-label icon="image:looks"></furo-icon-with-label> <furo-icon-with-label icon="image:looks-3"></furo-icon-with-label> <furo-icon-with-label icon="image:looks-4"></furo-icon-with-label> <furo-icon-with-label icon="image:looks-5"></furo-icon-with-label> <furo-icon-with-label icon="image:looks-6"></furo-icon-with-label> <furo-icon-with-label icon="image:looks-one"></furo-icon-with-label> <furo-icon-with-label icon="image:looks-two"></furo-icon-with-label> <furo-icon-with-label icon="image:loupe"></furo-icon-with-label> <furo-icon-with-label icon="image:monochrome-photos"></furo-icon-with-label> <furo-icon-with-label icon="image:movie-creation"></furo-icon-with-label> <furo-icon-with-label icon="image:movie-filter"></furo-icon-with-label> <furo-icon-with-label icon="image:music-note"></furo-icon-with-label> <furo-icon-with-label icon="image:nature"></furo-icon-with-label> <furo-icon-with-label icon="image:nature-people"></furo-icon-with-label> <furo-icon-with-label icon="image:navigate-before"></furo-icon-with-label> <furo-icon-with-label icon="image:navigate-next"></furo-icon-with-label> <furo-icon-with-label icon="image:palette"></furo-icon-with-label> <furo-icon-with-label icon="image:panorama"></furo-icon-with-label> <furo-icon-with-label icon="image:panorama-fish-eye"></furo-icon-with-label> <furo-icon-with-label icon="image:panorama-horizontal"></furo-icon-with-label> <furo-icon-with-label icon="image:panorama-vertical"></furo-icon-with-label> <furo-icon-with-label icon="image:panorama-wide-angle"></furo-icon-with-label> <furo-icon-with-label icon="image:photo"></furo-icon-with-label> <furo-icon-with-label icon="image:photo-album"></furo-icon-with-label> <furo-icon-with-label icon="image:photo-camera"></furo-icon-with-label> <furo-icon-with-label icon="image:photo-filter"></furo-icon-with-label> <furo-icon-with-label icon="image:photo-library"></furo-icon-with-label> <furo-icon-with-label icon="image:photo-size-select-actual"></furo-icon-with-label> <furo-icon-with-label icon="image:photo-size-select-large"></furo-icon-with-label> <furo-icon-with-label icon="image:photo-size-select-small"></furo-icon-with-label> <furo-icon-with-label icon="image:picture-as-pdf"></furo-icon-with-label> <furo-icon-with-label icon="image:portrait"></furo-icon-with-label> <furo-icon-with-label icon="image:remove-red-eye"></furo-icon-with-label> <furo-icon-with-label icon="image:rotate-90-degrees-ccw"></furo-icon-with-label> <furo-icon-with-label icon="image:rotate-left"></furo-icon-with-label> <furo-icon-with-label icon="image:rotate-right"></furo-icon-with-label> <furo-icon-with-label icon="image:slideshow"></furo-icon-with-label> <furo-icon-with-label icon="image:straighten"></furo-icon-with-label> <furo-icon-with-label icon="image:style"></furo-icon-with-label> <furo-icon-with-label icon="image:switch-camera"></furo-icon-with-label> <furo-icon-with-label icon="image:switch-video"></furo-icon-with-label> <furo-icon-with-label icon="image:tag-faces"></furo-icon-with-label> <furo-icon-with-label icon="image:texture"></furo-icon-with-label> <furo-icon-with-label icon="image:timelapse"></furo-icon-with-label> <furo-icon-with-label icon="image:timer"></furo-icon-with-label> <furo-icon-with-label icon="image:timer-10"></furo-icon-with-label> <furo-icon-with-label icon="image:timer-3"></furo-icon-with-label> <furo-icon-with-label icon="image:timer-off"></furo-icon-with-label> <furo-icon-with-label icon="image:tonality"></furo-icon-with-label> <furo-icon-with-label icon="image:transform"></furo-icon-with-label> <furo-icon-with-label icon="image:tune"></furo-icon-with-label> <furo-icon-with-label icon="image:view-comfy"></furo-icon-with-label> <furo-icon-with-label icon="image:view-compact"></furo-icon-with-label> <furo-icon-with-label icon="image:vignette"></furo-icon-with-label> <furo-icon-with-label icon="image:wb-auto"></furo-icon-with-label> <furo-icon-with-label icon="image:wb-cloudy"></furo-icon-with-label> <furo-icon-with-label icon="image:wb-incandescent"></furo-icon-with-label> <furo-icon-with-label icon="image:wb-iridescent"></furo-icon-with-label> <furo-icon-with-label icon="image:wb-sunny"></furo-icon-with-label> </div> <h2>Iconset mapsIcons</h2> <p> <pre> import {MapsIcons} from "@furo/icon/assets/iconsets/mapsIcons"; Iconset.registerIconset("maps", MapsIcons); </pre></p> <div> <furo-icon-with-label icon="map:add-location"></furo-icon-with-label> <furo-icon-with-label icon="map:beenhere"></furo-icon-with-label> <furo-icon-with-label icon="map:directions"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-bike"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-boat"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-bus"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-car"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-railway"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-run"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-subway"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-transit"></furo-icon-with-label> <furo-icon-with-label icon="map:directions-walk"></furo-icon-with-label> <furo-icon-with-label icon="map:edit-location"></furo-icon-with-label> <furo-icon-with-label icon="map:ev-station"></furo-icon-with-label> <furo-icon-with-label icon="map:flight"></furo-icon-with-label> <furo-icon-with-label icon="map:hotel"></furo-icon-with-label> <furo-icon-with-label icon="map:layers"></furo-icon-with-label> <furo-icon-with-label icon="map:layers-clear"></furo-icon-with-label> <furo-icon-with-label icon="map:local-activity"></furo-icon-with-label> <furo-icon-with-label icon="map:local-airport"></furo-icon-with-label> <furo-icon-with-label icon="map:local-atm"></furo-icon-with-label> <furo-icon-with-label icon="map:local-bar"></furo-icon-with-label> <furo-icon-with-label icon="map:local-cafe"></furo-icon-with-label> <furo-icon-with-label icon="map:local-car-wash"></furo-icon-with-label> <furo-icon-with-label icon="map:local-convenience-store"></furo-icon-with-label> <furo-icon-with-label icon="map:local-dining"></furo-icon-with-label> <furo-icon-with-label icon="map:local-drink"></furo-icon-with-label> <furo-icon-with-label icon="map:local-florist"></furo-icon-with-label> <furo-icon-with-label icon="map:local-gas-station"></furo-icon-with-label> <furo-icon-with-label icon="map:local-grocery-store"></furo-icon-with-label> <furo-icon-with-label icon="map:local-hospital"></furo-icon-with-label> <furo-icon-with-label icon="map:local-hotel"></furo-icon-with-label> <furo-icon-with-label icon="map:local-laundry-service"></furo-icon-with-label> <furo-icon-with-label icon="map:local-library"></furo-icon-with-label> <furo-icon-with-label icon="map:local-mall"></furo-icon-with-label> <furo-icon-with-label icon="map:local-movies"></furo-icon-with-label> <furo-icon-with-label icon="map:local-offer"></furo-icon-with-label> <furo-icon-with-label icon="map:local-parking"></furo-icon-with-label> <furo-icon-with-label icon="map:local-pharmacy"></furo-icon-with-label> <furo-icon-with-label icon="map:local-phone"></furo-icon-with-label> <furo-icon-with-label icon="map:local-pizza"></furo-icon-with-label> <furo-icon-with-label icon="map:local-play"></furo-icon-with-label> <furo-icon-with-label icon="map:local-post-office"></furo-icon-with-label> <furo-icon-with-label icon="map:local-printshop"></furo-icon-with-label> <furo-icon-with-label icon="map:local-see"></furo-icon-with-label> <furo-icon-with-label icon="map:local-shipping"></furo-icon-with-label> <furo-icon-with-label icon="map:local-taxi"></furo-icon-with-label> <furo-icon-with-label icon="map:map"></furo-icon-with-label> <furo-icon-with-label icon="map:my-location"></furo-icon-with-label> <furo-icon-with-label icon="map:navigation"></furo-icon-with-label> <furo-icon-with-label icon="map:near-me"></furo-icon-with-label> <furo-icon-with-label icon="map:person-pin"></furo-icon-with-label> <furo-icon-with-label icon="map:person-pin-circle"></furo-icon-with-label> <furo-icon-with-label icon="map:pin-drop"></furo-icon-with-label> <furo-icon-with-label icon="map:place"></furo-icon-with-label> <furo-icon-with-label icon="map:rate-review"></furo-icon-with-label> <furo-icon-with-label icon="map:restaurant"></furo-icon-with-label> <furo-icon-with-label icon="map:restaurant-menu"></furo-icon-with-label> <furo-icon-with-label icon="map:satellite"></furo-icon-with-label> <furo-icon-with-label icon="map:store-mall-directory"></furo-icon-with-label> <furo-icon-with-label icon="map:streetview"></furo-icon-with-label> <furo-icon-with-label icon="map:subway"></furo-icon-with-label> <furo-icon-with-label icon="map:terrain"></furo-icon-with-label> <furo-icon-with-label icon="map:traffic"></furo-icon-with-label> <furo-icon-with-label icon="map:train"></furo-icon-with-label> <furo-icon-with-label icon="map:tram"></furo-icon-with-label> <furo-icon-with-label icon="map:transfer-within-a-station"></furo-icon-with-label> <furo-icon-with-label icon="map:zoom-out-map"></furo-icon-with-label> </div> <h2>Iconset notificationIcons</h2> <p> <pre> import {NotificationIcons} from "@furo/icon/assets/iconsets/notificationIcons"; Iconset.registerIconset("notification", NotificationIcons); </pre></p> <div> <furo-icon-with-label icon="notification:adb"></furo-icon-with-label> <furo-icon-with-label icon="notification:airline-seat-flat"></furo-icon-with-label> <furo-icon-with-label icon="notification:airline-seat-flat-angled"></furo-icon-with-label> <furo-icon-with-label icon="notification:airline-seat-individual-suite"></furo-icon-with-label> <furo-icon-with-label icon="notification:airline-seat-legroom-extra"></furo-icon-with-label> <furo-icon-with-label icon="notification:airline-seat-legroom-normal"></furo-icon-with-label> <furo-icon-with-label icon="notification:airline-seat-legroom-reduced"></furo-icon-with-label> <furo-icon-with-label icon="notification:airline-seat-recline-extra"></furo-icon-with-label> <furo-icon-with-label icon="notification:airline-seat-recline-normal"></furo-icon-with-label> <furo-icon-with-label icon="notification:bluetooth-audio"></furo-icon-with-label> <furo-icon-with-label icon="notification:confirmation-number"></furo-icon-with-label> <furo-icon-with-label icon="notification:disc-full"></furo-icon-with-label> <furo-icon-with-label icon="notification:do-not-disturb"></furo-icon-with-label> <furo-icon-with-label icon="notification:do-not-disturb-alt"></furo-icon-with-label> <furo-icon-with-label icon="notification:do-not-disturb-off"></furo-icon-with-label> <furo-icon-with-label icon="notification:do-not-disturb-on"></furo-icon-with-label> <furo-icon-with-label icon="notification:drive-eta"></furo-icon-with-label> <furo-icon-with-label icon="notification:enhanced-encryption"></furo-icon-with-label> <furo-icon-with-label icon="notification:event-available"></furo-icon-with-label> <furo-icon-with-label icon="notification:event-busy"></furo-icon-with-label> <furo-icon-with-label icon="notification:event-note"></furo-icon-with-label> <furo-icon-with-label icon="notification:folder-special"></furo-icon-with-label> <furo-icon-with-label icon="notification:live-tv"></furo-icon-with-label> <furo-icon-with-label icon="notification:mms"></furo-icon-with-label> <furo-icon-with-label icon="notification:more"></furo-icon-with-label> <furo-icon-with-label icon="notification:network-check"></furo-icon-with-label> <furo-icon-with-label icon="notification:network-locked"></furo-icon-with-label> <furo-icon-with-label icon="notification:no-encryption"></furo-icon-with-label> <furo-icon-with-label icon="notification:ondemand-video"></furo-icon-with-label> <furo-icon-with-label icon="notification:personal-video"></furo-icon-with-label> <furo-icon-with-label icon="notification:phone-bluetooth-speaker"></furo-icon-with-label> <furo-icon-with-label icon="notification:phone-forwarded"></furo-icon-with-label> <furo-icon-with-label icon="notification:phone-in-talk"></furo-icon-with-label> <furo-icon-with-label icon="notification:phone-locked"></furo-icon-with-label> <furo-icon-with-label icon="notification:phone-missed"></furo-icon-with-label> <furo-icon-with-label icon="notification:phone-paused"></furo-icon-with-label> <furo-icon-with-label icon="notification:power"></furo-icon-with-label> <furo-icon-with-label icon="notification:priority-high"></furo-icon-with-label> <furo-icon-with-label icon="notification:rv-hookup"></furo-icon-with-label> <furo-icon-with-label icon="notification:sd-card"></furo-icon-with-label> <furo-icon-with-label icon="notification:sim-card-alert"></furo-icon-with-label> <furo-icon-with-label icon="notification:sms"></furo-icon-with-label> <furo-icon-with-label icon="notification:sms-failed"></furo-icon-with-label> <furo-icon-with-label icon="notification:sync"></furo-icon-with-label> <furo-icon-with-label icon="notification:sync-disabled"></furo-icon-with-label> <furo-icon-with-label icon="notification:sync-problem"></furo-icon-with-label> <furo-icon-with-label icon="notification:system-update"></furo-icon-with-label> <furo-icon-with-label icon="notification:tap-and-play"></furo-icon-with-label> <furo-icon-with-label icon="notification:time-to-leave"></furo-icon-with-label> <furo-icon-with-label icon="notification:vibration"></furo-icon-with-label> <furo-icon-with-label icon="notification:voice-chat"></furo-icon-with-label> <furo-icon-with-label icon="notification:vpn-lock"></furo-icon-with-label> <furo-icon-with-label icon="notification:wc"></furo-icon-with-label> <furo-icon-with-label icon="notification:wifi"></furo-icon-with-label> </div> <h2>Iconset placesIcons</h2> <p> <pre> import {PlacesIcons} from "@furo/icon/assets/iconsets/placesIcons"; Iconset.registerIconset("places", PlacesIcons); </pre></p> <div> <furo-icon-with-label icon="places:ac-unit"></furo-icon-with-label> <furo-icon-with-label icon="places:airport-shuttle"></furo-icon-with-label> <furo-icon-with-label icon="places:all-inclusive"></furo-icon-with-label> <furo-icon-with-label icon="places:beach-access"></furo-icon-with-label> <furo-icon-with-label icon="places:business-center"></furo-icon-with-label> <furo-icon-with-label icon="places:casino"></furo-icon-with-label> <furo-icon-with-label icon="places:child-care"></furo-icon-with-label> <furo-icon-with-label icon="places:child-friendly"></furo-icon-with-label> <furo-icon-with-label icon="places:fitness-center"></furo-icon-with-label> <furo-icon-with-label icon="places:free-breakfast"></furo-icon-with-label> <furo-icon-with-label icon="places:golf-course"></furo-icon-with-label> <furo-icon-with-label icon="places:hot-tub"></furo-icon-with-label> <furo-icon-with-label icon="places:kitchen"></furo-icon-with-label> <furo-icon-with-label icon="places:pool"></furo-icon-with-label> <furo-icon-with-label icon="places:room-service"></furo-icon-with-label> <furo-icon-with-label icon="places:rv-hookup"></furo-icon-with-label> <furo-icon-with-label icon="places:smoke-free"></furo-icon-with-label> <furo-icon-with-label icon="places:smoking-rooms"></furo-icon-with-label> <furo-icon-with-label icon="places:spa"></furo-icon-with-label> </div> <h2>Iconset socialIcons</h2> <p> <pre> import {SocialIcons} from "@furo/icon/assets/iconsets/socialIcons"; Iconset.registerIconset("social", SocialIcons); </pre></p> <div> <furo-icon-with-label icon="social:cake"></furo-icon-with-label> <furo-icon-with-label icon="social:domain"></furo-icon-with-label> <furo-icon-with-label icon="social:group"></furo-icon-with-label> <furo-icon-with-label icon="social:group-add"></furo-icon-with-label> <furo-icon-with-label icon="social:location-city"></furo-icon-with-label> <furo-icon-with-label icon="social:mood"></furo-icon-with-label> <furo-icon-with-label icon="social:mood-bad"></furo-icon-with-label> <furo-icon-with-label icon="social:notifications"></furo-icon-with-label> <furo-icon-with-label icon="social:notifications-active"></furo-icon-with-label> <furo-icon-with-label icon="social:notifications-none"></furo-icon-with-label> <furo-icon-with-label icon="social:notifications-off"></furo-icon-with-label> <furo-icon-with-label icon="social:notifications-paused"></furo-icon-with-label> <furo-icon-with-label icon="social:pages"></furo-icon-with-label> <furo-icon-with-label icon="social:party-mode"></furo-icon-with-label> <furo-icon-with-label icon="social:people"></furo-icon-with-label> <furo-icon-with-label icon="social:people-outline"></furo-icon-with-label> <furo-icon-with-label icon="social:person"></furo-icon-with-label> <furo-icon-with-label icon="social:person-add"></furo-icon-with-label> <furo-icon-with-label icon="social:person-outline"></furo-icon-with-label> <furo-icon-with-label icon="social:plus-one"></furo-icon-with-label> <furo-icon-with-label icon="social:poll"></furo-icon-with-label> <furo-icon-with-label icon="social:public"></furo-icon-with-label> <furo-icon-with-label icon="social:school"></furo-icon-with-label> <furo-icon-with-label icon="social:sentiment-dissatisfied"></furo-icon-with-label> <furo-icon-with-label icon="social:sentiment-neutral"></furo-icon-with-label> <furo-icon-with-label icon="social:sentiment-satisfied"></furo-icon-with-label> <furo-icon-with-label icon="social:sentiment-very-dissatisfied"></furo-icon-with-label> <furo-icon-with-label icon="social:sentiment-very-satisfied"></furo-icon-with-label> <furo-icon-with-label icon="social:share"></furo-icon-with-label> <furo-icon-with-label icon="social:whatshot"></furo-icon-with-label> </div> `; } }
JavaScript
class Response { constructor() { this.headers = {}; } /** * @param headers */ addHeaders(headers = {}) { this.headers = { ...this.headers, ...headers, }; } /** * @param statusCode * @param body * @param headers * @returns {Response} */ respond(statusCode, body, headers) { this.statusCode = statusCode; this.body = body; this.addHeaders(headers); return this; } }
JavaScript
class PluginService { /** * @returns {boolean} */ isNativeMessagingSupported() { return Boolean(cadesplugin.CreateObjectAsync); } /** * @returns {boolean} */ isReady() { return Boolean(cadesplugin.CreateObjectAsync) || Boolean(cadesplugin.CreateObject); } }
JavaScript
class NotFound extends Component { static propTypes = { classes: PropTypes.object.isRequired } constructor(props) { super(props) this.state = { tiltX: 0, tiltY: 0, deg: 0 } } onMouseMove = ({pageX: x, pageY: y}) => { const cx = Math.ceil(window.innerWidth / 2) const cy = Math.ceil(window.innerHeight / 2) const dx = x - cx const dy = y - cy const tiltX = dy / cy const tiltY = -(dx / cx) const radius = Math.sqrt((tiltX ** 2) + (tiltY ** 2)) const deg = radius * 25 this.setState({tiltX, tiltY, deg}) } render() { const {classes} = this.props const {tiltX, tiltY, deg} = this.state return ( <div className={classes.notFound} onMouseMove={this.onMouseMove} > <div className={classes.inner} /> <div className={classes.ringFirst} /> <div className={classes.ringSecond} /> <div className={classes.ringThird} /> <div className={classes.target}> <Motion style={{ x: spring(tiltX), y: spring(tiltY), deg: spring(deg) }} > {({x, y, deg: nextDeg}) => ( <div className={classes.targetInner} style={{ WebkitTransform: `rotate3d(${x}, ${y}, 0, ${nextDeg}deg)`, transform: `rotate3d(${x}, ${y}, 0, ${nextDeg}deg)`, }} > <div className={classes.logo}> <NotFoundIcon className={classes.logoBase} /> </div> </div> )} </Motion> </div> </div> ) } }
JavaScript
class LineColTransformer { constructor(_session) { this._session = _session; } setBreakpoints(args) { args.breakpoints.forEach(bp => this.convertClientLocationToDebugger(bp)); if (!this.columnBreakpointsEnabled) { args.breakpoints.forEach(bp => bp.column = undefined); } return args; } setBreakpointsResponse(response) { response.breakpoints.forEach(bp => this.convertDebuggerLocationToClient(bp)); if (!this.columnBreakpointsEnabled) { response.breakpoints.forEach(bp => bp.column = 1); } } stackTraceResponse(response) { response.stackFrames.forEach(frame => this.convertDebuggerLocationToClient(frame)); } breakpointResolved(bp) { this.convertDebuggerLocationToClient(bp); if (!this.columnBreakpointsEnabled) { bp.column = undefined; } } scopeResponse(scopeResponse) { scopeResponse.scopes.forEach(scope => this.mapScopeLocations(scope)); } mappedExceptionStack(location) { this.convertDebuggerLocationToClient(location); } mapScopeLocations(scope) { this.convertDebuggerLocationToClient(scope); if (typeof scope.endLine === 'number') { const endScope = { line: scope.endLine, column: scope.endColumn }; this.convertDebuggerLocationToClient(endScope); scope.endLine = endScope.line; scope.endColumn = endScope.column; } } convertClientLocationToDebugger(location) { if (typeof location.line === 'number') { location.line = this.convertClientLineToDebugger(location.line); } if (typeof location.column === 'number') { location.column = this.convertClientColumnToDebugger(location.column); } } convertDebuggerLocationToClient(location) { if (typeof location.line === 'number') { location.line = this.convertDebuggerLineToClient(location.line); } if (typeof location.column === 'number') { location.column = this.convertDebuggerColumnToClient(location.column); } } convertClientLineToDebugger(line) { return this._session.convertClientLineToDebugger(line); } convertDebuggerLineToClient(line) { return this._session.convertDebuggerLineToClient(line); } convertClientColumnToDebugger(column) { return this._session.convertClientColumnToDebugger(column); } convertDebuggerColumnToClient(column) { return this._session.convertDebuggerColumnToClient(column); } }
JavaScript
class WireCollection extends BaseLineCollection { constructor(capacity) { super(capacity, 4); // items per wire this.type = 'WireCollection'; } _makeProgram(gl) { return makeLinesProgram(gl, this.buffer, /* drawTriangles = */ false); } _addInternal(line, offset) { let lineUI = new WireAccessor(this.buffer, offset); lineUI.update(line.from, line.to) return lineUI; } }
JavaScript
class HelpScene extends Scene { /** * Opens the help scene. * * @memberof HelpScene */ start() { super.start({ layout: 'rect', width: 91, height: 30, fontSize: 24, fontFamily: 'monospace', forceSquareRatio: false, music: this.game.menumusic, }); this.game.display.drawText(43, 1, 'Help'); this.game.display.drawText( 2, 3, ' You are Emmanuel de Rouge, the professor of archeology.' + ' Through research you learned about a forgotten Aztec temple' + ' that holds the golden feather of divine powers, the Amulet of' + ' Quetzalcoatl.', ); this.game.display.drawText( 2, 7, ' You decided to get it and finally found the island, but your' + ' rivals followed you. They will try to get the feather at all costs.', ); this.game.display.drawText( 2, 12, ' Move with left click on the ground or with arrow or Num or' + ' WASD keys', ); this.game.display.drawText( 2, 14, ' Move upstairs or downstairs with left click on the stairs or' + ' with the Enter key', ); this.game.display.drawText( 2, 16, ' Attack with left click on the enemy or by moving into the ' + 'position of the enemy', ); this.game.display.drawText( 2, 18, ' Heal yourself with left click on your character or on the' + ' heart or medkit symbols or with the Enter key', ); this.game.display.drawText( 2, 21, ' Set console or tile-based display with left click on the ' + 'symbol of your character on the HUD or with the T key', ); this.game.display.drawText( 2, 24, ' Mute or unmute the music or sound with left click on the' + ' music or sound symbol or with the M or N key', ); this.game.display.drawText(2, 28, '➧Back'); } /** * Handles the keydown and mousedown events of this scene. * * @param {Event} event * @memberof Scene */ handleEvent(event) { super.handleEvent(event); if (event.type === 'keydown') { if (event.keyCode === 13) { this.switchTo(this.game.menuScene); } } else if (event.type === 'mousedown') { if (this.eventX > 1 && this.eventX < 6 && this.eventY === 28) { this.switchTo(this.game.menuScene); } } } }
JavaScript
class Devices { /** * Create a Devices. * @param {MobileEngagementClient} client Reference to the service client. */ constructor(client) { this.client = client; this._list = _list; this._getByDeviceId = _getByDeviceId; this._getByUserId = _getByUserId; this._tagByDeviceId = _tagByDeviceId; this._tagByUserId = _tagByUserId; this._listNext = _listNext; } /** * Query the information associated to the devices running an application. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {object} [options] Optional Parameters. * * @param {number} [options.top] Number of devices to return with each call. * Defaults to 100 and cannot return more. Passing a greater value is ignored. * The response contains a `nextLink` property describing the URI path to get * the next page of results if not all results could be returned at once. * * @param {string} [options.select] By default all `meta` and `appInfo` * properties are returned, this property is used to restrict the output to the * desired properties. It also excludes all devices from the output that have * none of the selected properties. In other terms, only devices having at * least one of the selected property being set is part of the results. * Examples: - `$select=appInfo` : select all devices having at least 1 * appInfo, return them all and don’t return any meta property. - * `$select=meta` : return only meta properties in the output. - * `$select=appInfo,meta/firstSeen,meta/lastSeen` : return all `appInfo`, plus * meta object containing only firstSeen and lastSeen properties. The format is * thus a comma separated list of properties to select. Use `appInfo` to select * all appInfo properties, `meta` to select all meta properties. Use * `appInfo/{key}` and `meta/{key}` to select specific appInfo and meta * properties. * * @param {string} [options.filter] Filter can be used to reduce the number of * results. Filter is a boolean expression that can look like the following * examples: * `$filter=deviceId gt 'abcdef0123456789abcdef0123456789'` * * `$filter=lastModified le 1447284263690L` * `$filter=(deviceId ge * 'abcdef0123456789abcdef0123456789') and (deviceId lt * 'bacdef0123456789abcdef0123456789') and (lastModified gt 1447284263690L)` * The first example is used automatically for paging when returning the * `nextLink` property. The filter expression is a combination of checks on * some properties that can be compared to their value. The available operators * are: * `gt` : greater than * `ge` : greater than or equals * `lt` : less * than * `le` : less than or equals * `and` : to add multiple checks (all * checks must pass), optional parentheses can be used. The properties that can * be used in the expression are the following: * `deviceId {operator} * '{deviceIdValue}'` : a lexicographical comparison is made on the deviceId * value, use single quotes for the value. * `lastModified {operator} * {number}L` : returns only meta properties or appInfo properties whose last * value modification timestamp compared to the specified value is matching * (value is milliseconds since January 1st, 1970 UTC). Please note the `L` * character after the number of milliseconds, its required when the number of * milliseconds exceeds `2^31 - 1` (which is always the case for recent * timestamps). Using `lastModified` excludes all devices from the output that * have no property matching the timestamp criteria, like `$select`. Please * note that the internal value of `lastModified` timestamp for a given * property is never part of the results. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DevicesQueryResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listWithHttpOperationResponse(resourceGroupName, appCollection, appName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._list(resourceGroupName, appCollection, appName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Query the information associated to the devices running an application. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {object} [options] Optional Parameters. * * @param {number} [options.top] Number of devices to return with each call. * Defaults to 100 and cannot return more. Passing a greater value is ignored. * The response contains a `nextLink` property describing the URI path to get * the next page of results if not all results could be returned at once. * * @param {string} [options.select] By default all `meta` and `appInfo` * properties are returned, this property is used to restrict the output to the * desired properties. It also excludes all devices from the output that have * none of the selected properties. In other terms, only devices having at * least one of the selected property being set is part of the results. * Examples: - `$select=appInfo` : select all devices having at least 1 * appInfo, return them all and don’t return any meta property. - * `$select=meta` : return only meta properties in the output. - * `$select=appInfo,meta/firstSeen,meta/lastSeen` : return all `appInfo`, plus * meta object containing only firstSeen and lastSeen properties. The format is * thus a comma separated list of properties to select. Use `appInfo` to select * all appInfo properties, `meta` to select all meta properties. Use * `appInfo/{key}` and `meta/{key}` to select specific appInfo and meta * properties. * * @param {string} [options.filter] Filter can be used to reduce the number of * results. Filter is a boolean expression that can look like the following * examples: * `$filter=deviceId gt 'abcdef0123456789abcdef0123456789'` * * `$filter=lastModified le 1447284263690L` * `$filter=(deviceId ge * 'abcdef0123456789abcdef0123456789') and (deviceId lt * 'bacdef0123456789abcdef0123456789') and (lastModified gt 1447284263690L)` * The first example is used automatically for paging when returning the * `nextLink` property. The filter expression is a combination of checks on * some properties that can be compared to their value. The available operators * are: * `gt` : greater than * `ge` : greater than or equals * `lt` : less * than * `le` : less than or equals * `and` : to add multiple checks (all * checks must pass), optional parentheses can be used. The properties that can * be used in the expression are the following: * `deviceId {operator} * '{deviceIdValue}'` : a lexicographical comparison is made on the deviceId * value, use single quotes for the value. * `lastModified {operator} * {number}L` : returns only meta properties or appInfo properties whose last * value modification timestamp compared to the specified value is matching * (value is milliseconds since January 1st, 1970 UTC). Please note the `L` * character after the number of milliseconds, its required when the number of * milliseconds exceeds `2^31 - 1` (which is always the case for recent * timestamps). Using `lastModified` excludes all devices from the output that * have no property matching the timestamp criteria, like `$select`. Please * note that the internal value of `lastModified` timestamp for a given * property is never part of the results. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {DevicesQueryResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link DevicesQueryResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName, appCollection, appName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._list(resourceGroupName, appCollection, appName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._list(resourceGroupName, appCollection, appName, options, optionalCallback); } } /** * Get the information associated to a device running an application. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {string} deviceId Device identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Device>} - The deserialized result object. * * @reject {Error} - The error object. */ getByDeviceIdWithHttpOperationResponse(resourceGroupName, appCollection, appName, deviceId, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._getByDeviceId(resourceGroupName, appCollection, appName, deviceId, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Get the information associated to a device running an application. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {string} deviceId Device identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Device} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Device} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ getByDeviceId(resourceGroupName, appCollection, appName, deviceId, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._getByDeviceId(resourceGroupName, appCollection, appName, deviceId, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._getByDeviceId(resourceGroupName, appCollection, appName, deviceId, options, optionalCallback); } } /** * Get the information associated to a device running an application using the * user identifier. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {string} userId User identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Device>} - The deserialized result object. * * @reject {Error} - The error object. */ getByUserIdWithHttpOperationResponse(resourceGroupName, appCollection, appName, userId, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._getByUserId(resourceGroupName, appCollection, appName, userId, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Get the information associated to a device running an application using the * user identifier. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {string} userId User identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Device} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Device} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ getByUserId(resourceGroupName, appCollection, appName, userId, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._getByUserId(resourceGroupName, appCollection, appName, userId, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._getByUserId(resourceGroupName, appCollection, appName, userId, options, optionalCallback); } } /** * Update the tags registered for a set of devices running an application. * Updates are performed asynchronously, meaning that a few seconds are needed * before the modifications appear in the results of the Get device command. * * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {object} parameters * * @param {object} parameters.tags A JSON object describing the set of tags to * record for a set of users. Each key is a device/user identifier, each value * is itself a key/value set: the tags to set for the specified device/user * identifier. * * * @param {boolean} [parameters.deleteOnNull] If this parameter is `true`, tags * with a null value will be deleted. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DeviceTagsResult>} - The deserialized result object. * * @reject {Error} - The error object. */ tagByDeviceIdWithHttpOperationResponse(resourceGroupName, appCollection, appName, parameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._tagByDeviceId(resourceGroupName, appCollection, appName, parameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Update the tags registered for a set of devices running an application. * Updates are performed asynchronously, meaning that a few seconds are needed * before the modifications appear in the results of the Get device command. * * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {object} parameters * * @param {object} parameters.tags A JSON object describing the set of tags to * record for a set of users. Each key is a device/user identifier, each value * is itself a key/value set: the tags to set for the specified device/user * identifier. * * * @param {boolean} [parameters.deleteOnNull] If this parameter is `true`, tags * with a null value will be deleted. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {DeviceTagsResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link DeviceTagsResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ tagByDeviceId(resourceGroupName, appCollection, appName, parameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._tagByDeviceId(resourceGroupName, appCollection, appName, parameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._tagByDeviceId(resourceGroupName, appCollection, appName, parameters, options, optionalCallback); } } /** * Update the tags registered for a set of users running an application. * Updates are performed asynchronously, meaning that a few seconds are needed * before the modifications appear in the results of the Get device command. * * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {object} parameters * * @param {object} parameters.tags A JSON object describing the set of tags to * record for a set of users. Each key is a device/user identifier, each value * is itself a key/value set: the tags to set for the specified device/user * identifier. * * * @param {boolean} [parameters.deleteOnNull] If this parameter is `true`, tags * with a null value will be deleted. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DeviceTagsResult>} - The deserialized result object. * * @reject {Error} - The error object. */ tagByUserIdWithHttpOperationResponse(resourceGroupName, appCollection, appName, parameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._tagByUserId(resourceGroupName, appCollection, appName, parameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Update the tags registered for a set of users running an application. * Updates are performed asynchronously, meaning that a few seconds are needed * before the modifications appear in the results of the Get device command. * * * @param {string} resourceGroupName The name of the resource group. * * @param {string} appCollection Application collection. * * @param {string} appName Application resource name. * * @param {object} parameters * * @param {object} parameters.tags A JSON object describing the set of tags to * record for a set of users. Each key is a device/user identifier, each value * is itself a key/value set: the tags to set for the specified device/user * identifier. * * * @param {boolean} [parameters.deleteOnNull] If this parameter is `true`, tags * with a null value will be deleted. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {DeviceTagsResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link DeviceTagsResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ tagByUserId(resourceGroupName, appCollection, appName, parameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._tagByUserId(resourceGroupName, appCollection, appName, parameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._tagByUserId(resourceGroupName, appCollection, appName, parameters, options, optionalCallback); } } /** * Query the information associated to the devices running an application. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DevicesQueryResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Query the information associated to the devices running an application. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {DevicesQueryResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link DevicesQueryResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listNext(nextPageLink, options, optionalCallback); } } }
JavaScript
class PathEndPoint extends AbstractSimObject { /** @param {string} name the name of this SimObject @param {!NumericalPath} path the path to connect @param {!RigidBody} body the RigidBody to connect @param {!Vector} attach_body the attachment point on the RigidBody in body coordinates @param {number} limit the limiting value of the path position, `p`, when the body moves beyond this then a collision is created. @param {boolean} upperLimit `true` means this is an is an upper limit; `false` indicates this is a lower limit */ constructor(name, path, body, attach_body, limit, upperLimit) { super(name); /** * @type {!RigidBody} * @private */ this.body_ = body; /** path that joint is attached to * @type {!NumericalPath} * @private */ this.path_ = path; /** attachment point in body coords of this.body_ * @type {!Vector} * @private */ this.attach_body_ = attach_body; /** the limiting value of the path position, `p`, when the body moves * beyond this then a collision is created. * @type {number} * @private */ this.limit_ = limit; /** `true` means this is an is an upper limit; `false` indicates * this is a lower limit. * @type {boolean} * @private */ this.upperLimit_ = upperLimit; /** * @type {!Vector} * @private */ this.location_ = path.map_p_to_vector(limit); // NOTE: important to search over entire curve for closest point here // later we will use findNearestLocal which is a local not global minimum. var point = this.body_.bodyToWorld(this.attach_body_); /** current position along the path * @type {!PathPoint} * @private */ this.ppt_ =this.path_.findNearestGlobal(point); /** last position along the path * @type {!PathPoint} * @private */ this.ppt_old_ = new PathPoint(this.ppt_.p); }; /** @override */ toString() { return Util.ADVANCED ? '' : super.toString().slice(0, -1) +', body_:='+this.body_.toStringShort() +', path_: '+this.path_.toStringShort() +', attach_body_: '+this.attach_body_ +', limit_: '+Util.NF(this.limit_) +', upperLimit_: '+this.upperLimit_ +'}'; }; /** @override */ getClassName() { return 'PathEndPoint'; }; /** @override */ addCollision(collisions, time, accuracy) { var c = new ConnectorCollision(this.body_, Scrim.getScrim(), this, /*joint=*/false); this.updateCollision(c); c.setDetectedTime(time); if (c.distance < 0) { // We only report a collision when distance went from positive to negative. // Find the old body distance, was it positive? var body_old = this.body_.getOldCoords(); if (body_old == null) { return; } var point_old = body_old.bodyToWorld(this.attach_body_); this.path_.findNearestLocal(point_old, this.ppt_old_); this.path_.map_p_to_slope(this.ppt_old_); var distance_old = this.upperLimit_ ? this.limit_ - this.ppt_old_.p : this.ppt_old_.p - this.limit_; if (distance_old < 0) { return; // it did not cross from positive to negative, so no collision } /*if (false && this.path_.isClosedLoop()) { // Deal with case where the body crosses the 'stitch' point, where p // suddenly goes from 0 to total path length. // If the change in distance is same as path length, ignore this. if (Math.abs(c.distance - distance_old) > 0.9*this.path_.getLength()) { return; } }*/ } if (c.distance < this.body_.getDistanceTol()) { collisions.unshift(c); } }; /** @override */ align() { }; /** Returns the attachment point on the RigidBody in body coordinates. @return {!Vector} the attachment point on the RigidBody in body coordinates */ getAttach1() { return this.attach_body_; }; /** @override */ getBody1() { return this.body_; }; /** @override */ getBody2() { return Scrim.getScrim(); }; /** @override */ getBoundsWorld() { return DoubleRect.make(this.location_, this.location_); }; /** @override */ getNormalDistance() { var collisions = /** @type {!Array<!RigidBodyCollision>} */([]); this.addCollision(collisions, /*time=*/NaN, /*accuracy=*/NaN); return collisions[0].getDistance(); }; /** Returns the NumericalPath to which this PathEndPoint attaches the RigidBody. @return {!NumericalPath} the NumericalPath to which this PathEndPoint attaches the RigidBody. */ getPath() { return this.path_; }; /** @override */ getPosition1() { return this.location_; }; /** @override */ getPosition2() { return this.location_; }; /** @override */ updateCollision(c) { if (c.primaryBody != this.body_ || c.normalBody != Scrim.getScrim()) { throw new Error(); } if (c.getConnector() != this) { throw new Error(); } var point = this.body_.bodyToWorld(this.attach_body_); c.impact1 = point; this.path_.findNearestLocal(point, this.ppt_); this.path_.map_p_to_slope(this.ppt_); c.distance = this.upperLimit_ ? this.limit_ - this.ppt_.p : this.ppt_.p - this.limit_; c.normal = this.ppt_.getSlope().multiply(this.upperLimit_ ? -1 : 1); c.ballNormal = false; c.impact2 = this.ppt_.getPosition(); c.creator = Util.DEBUG ? 'PathEndPoint' : ''; }; } // end class
JavaScript
class Login extends Component { constructor(props) { super(props); var localloginComponent=[]; this.state = { username: '', password: '', loginComponent:localloginComponent, draweropen: false } } handleDrawerOpen = () => { this.setState({ draweropen: true }); }; handleDrawerClose = () => { this.setState({ draweropen: false }); }; componentDidMount(){ document.title = "issuer app" } componentWillMount(){ } handleLoginClick(event) { var self = this; var payload = { "username": this.state.username, "password": this.state.password } axios.post(apiBaseUrl + 'login', payload) .then(function (response) { console.log(response); console.log(response.status); if (response.status === 200) { console.log("Login successfull"); console.log(response.data.token); //var issuerScreen = []; //issuerScreen.push(<IssuerScreen appContext={self.props.appContext} />) //self.props.appContext.setState({ loginPage: [], issuerScreen: issuerScreen }) localStorage.setItem('token', response.data.token) self.props.handler() self.props.history.push("/onboarding"); } else if (response.status === 204) { console.log("Username password do not match"); alert("username password do not match") } else { console.log("Username does not exists"); alert("Username does not exist"); } }) .catch(function (error) { alert(error); console.log(error); }); } render() { return ( <MuiThemeProvider> <div> <IssuerBar /> <TextField hintText="Enter your Username" floatingLabelText="Username" onChange={(event, newValue) => this.setState({ username: newValue })} /> <br /> <TextField type="password" hintText="Enter your Password" floatingLabelText="Password" onChange={(event, newValue) => this.setState({ password: newValue })} /> <br /> <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleLoginClick(event)} /> </div> </MuiThemeProvider> ); } }
JavaScript
class InlineResponse2005DataUnderlyingNotation { /** * Constructs a new <code>InlineResponse2005DataUnderlyingNotation</code>. * @alias module:model/InlineResponse2005DataUnderlyingNotation */ constructor() { InlineResponse2005DataUnderlyingNotation.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>InlineResponse2005DataUnderlyingNotation</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/InlineResponse2005DataUnderlyingNotation} obj Optional instance to populate. * @return {module:model/InlineResponse2005DataUnderlyingNotation} The populated <code>InlineResponse2005DataUnderlyingNotation</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new InlineResponse2005DataUnderlyingNotation(); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('count')) { obj['count'] = ApiClient.convertToType(data['count'], 'Number'); } } return obj; } }
JavaScript
class client extends Class(SimpleEmitter) { /** * Create an `EventSource` like transport with the ability to send data too. * @param {string} url the end point enabled as bidi-sse server * @param {ClientOptions=} options extra options to use */ constructor(url, options = {}) { super(); const once = {once: true}; const fetch = options.fetch || {}; const withCredentials = fetch.credentials !== 'omit'; const es = new EventSource(url, {withCredentials}); const {parse, stringify} = options.JSON || JSON; const $ = {es, stringify, href: '', options: fetch, state: CONNECTING}; // regular flow es.addEventListener('bidi-sse', ({data}) => { const id = parse(data); const location = new URL(es.url); location.searchParams.append('bidi-sse', id); $.href = location.href; $.state = OPEN; this.emit('open'); }, once); es.addEventListener( 'message', ({data}) => this.emit('message', parse(data)) ); es.addEventListener('close', () => { $.state = CLOSED; es.close(); this.emit('close'); }, once); // error handling es.addEventListener( 'unexpected', ({data}) => this.emit('error', new Error('Unexpected ➡ ' + parse(data))) ); es.addEventListener('error', () => { $.state = CLOSING; this.emit('error', new Error('Connection lost ➡ ' + es.url)); this.close(); }, once); _.set(this, $); } /** * @type {CONNECTING | OPEN | CLOSING | CLOSED} */ get readyState() { return _.get(this).state; } /** * Send data to the server side bidi-sse enabled end point. * @param {any} data serializable data to send */ send(data) { const {stringify, href, options, state} = _.get(this); if (state !== OPEN) throw new Error('invalid state'); const body = stringify(data); fetch(href, {...options, method: 'post', body}).then(fetchText); } /** * Disconnect the `EventSource` and emit `close` event. */ close() { _.get(this).es.dispatchEvent(new Event('close')); } }